package observation import ( "context" "math" "go.maximumdirect.net/promptkit/internal/domain" ) type costContextKey struct{} // WithCostAccumulator carries one invocation's cost state. func WithCostAccumulator(ctx context.Context, accumulator *CostAccumulator) context.Context { return context.WithValue(ctx, costContextKey{}, accumulator) } // CostFromContext returns the current invocation's cost state, if installed. func CostFromContext(ctx context.Context) *CostAccumulator { value, _ := ctx.Value(costContextKey{}).(*CostAccumulator) return value } // ResolveCost applies reported-cost precedence over a configured-zero fallback. func ResolveCost(reported *float64, zeroCost bool) domain.ObservedCost { if reported != nil && !math.IsNaN(*reported) && !math.IsInf(*reported, 0) { return domain.ObservedCost{Value: *reported, Known: true, Complete: true, Source: domain.CostSourceProvider} } if zeroCost { return domain.ObservedCost{Known: true, Complete: true, Source: domain.CostSourceConfiguredZero} } return domain.ObservedCost{} } // CostAccumulator merges dispatched attempts or already aggregated costs. type CostAccumulator struct { value domain.ObservedCost started bool } // Add incorporates one contribution. func (c *CostAccumulator) Add(next domain.ObservedCost) { if !c.started { c.started = true c.value = next return } if next.Known { c.value.Value += next.Value if next.Source != domain.CostSourceNone { if c.value.Source == domain.CostSourceNone { c.value.Source = next.Source } else if c.value.Source != next.Source { c.value.Source = domain.CostSourceMixed } } } c.value.Known = c.value.Known || next.Known c.value.Complete = c.value.Complete && next.Complete } // Observed returns known complete zero when no contribution has been added. func (c CostAccumulator) Observed() domain.ObservedCost { if !c.started { return domain.ObservedCost{Known: true, Complete: true} } return c.value }