diff --git a/changelog/unreleased/kiro-prompt-cache-estimate.md b/changelog/unreleased/kiro-prompt-cache-estimate.md new file mode 100644 index 000000000..eafe25b6a --- /dev/null +++ b/changelog/unreleased/kiro-prompt-cache-estimate.md @@ -0,0 +1,7 @@ +### English + +- Kiro usage again reports estimated prompt-cache reads and writes. Kiro still does not send cache figures, so the gateway tracks prompt prefixes per account for five minutes and reports the repeated part as a cache read. + +### 中文 + +- Kiro 用量再次附带估算的提示缓存读写。Kiro 本身仍不返回缓存数字,网关按账号把 prompt 前缀记五分钟,把重复部分报成缓存读取。 diff --git a/internal/providers/kiro/client.go b/internal/providers/kiro/client.go index a58a33770..4dc69336b 100644 --- a/internal/providers/kiro/client.go +++ b/internal/providers/kiro/client.go @@ -44,10 +44,14 @@ type Client struct { mu sync.Mutex models map[string][]providers.ModelInfo logins map[string]*loginState + + // cache estimates prompt-cache reads and writes Kiro does not report. + // A nil cache (tests build Client directly) estimates nothing. + cache *promptCache } func NewClient(store Store) *Client { - return &Client{store: store, http: &http.Client{}} + return &Client{store: store, http: &http.Client{}, cache: newPromptCache()} } func (c *Client) Adapter() providers.Adapter { @@ -285,21 +289,22 @@ func (c *Client) ChatStream(ctx context.Context, accountID string, req translate return nil, providers.ResolvedChat{}, err } resolved := providers.ResolvedChat{ReasoningLevel: payload.Level} + cache := c.cache.begin(accountID, payload) if c.useResponses(ctx, accountID, cred) { body, err := c.postResponses(ctx, client, cred, payload) if err != nil { return nil, providers.ResolvedChat{}, err } - return writeOpenAIStream(body, model, payload.clientNames(), armMarkupFilter(payload.Tools)), resolved, nil + return writeOpenAIStream(body, model, payload.clientNames(), armMarkupFilter(payload.Tools), cache), resolved, nil } body, kind, err := c.postLegacy(ctx, client, accountID, cred, payload) if err != nil { return nil, providers.ResolvedChat{}, err } if kind == streamResponses { - return writeOpenAIStream(body, model, payload.clientNames(), armMarkupFilter(payload.Tools)), resolved, nil + return writeOpenAIStream(body, model, payload.clientNames(), armMarkupFilter(payload.Tools), cache), resolved, nil } - return writeEventStream(body, model, payload.clientNames(), armMarkupFilter(payload.Tools)), resolved, nil + return writeEventStream(body, model, payload.clientNames(), armMarkupFilter(payload.Tools), cache), resolved, nil } func (c *Client) postResponses(ctx context.Context, client *http.Client, cred Credential, payload conversation) (io.ReadCloser, error) { @@ -466,12 +471,12 @@ func applyLegacyHeaders(req *http.Request, cred Credential, endpoint legacyEndpo // writeEventStream reads a generateAssistantResponse body and writes the same // OpenAI chunks CreateResponse produces. -func writeEventStream(body io.ReadCloser, model string, names map[string]string, filter *markupFilter) *http.Response { +func writeEventStream(body io.ReadCloser, model string, names map[string]string, filter *markupFilter, cache *cacheTurn) *http.Response { pr, pw := io.Pipe() go func() { defer body.Close() defer pw.Close() - writeConsumed(pw, model, eventStreamSource(body), names, filter) + writeConsumed(pw, model, eventStreamSource(body), names, filter, cache) }() return &http.Response{ StatusCode: http.StatusOK, diff --git a/internal/providers/kiro/openai_stream.go b/internal/providers/kiro/openai_stream.go index c4358911a..7e62e369f 100644 --- a/internal/providers/kiro/openai_stream.go +++ b/internal/providers/kiro/openai_stream.go @@ -14,12 +14,12 @@ import ( // relay opens a tool_use block on the first chunk that carries a name and then // treats every later arguments fragment as input_json_delta. Sending the name // before the JSON is finished would leave the client with a partial object. -func writeOpenAIStream(body io.ReadCloser, model string, names map[string]string, filter *markupFilter) *http.Response { +func writeOpenAIStream(body io.ReadCloser, model string, names map[string]string, filter *markupFilter, cache *cacheTurn) *http.Response { pr, pw := io.Pipe() go func() { defer body.Close() defer pw.Close() - writeConsumed(pw, model, responsesSSESource(body), names, filter) + writeConsumed(pw, model, responsesSSESource(body), names, filter, cache) }() return &http.Response{ StatusCode: http.StatusOK, @@ -30,8 +30,9 @@ func writeOpenAIStream(body io.ReadCloser, model string, names map[string]string // writeConsumed turns one event source into OpenAI chat chunks. Tool calls are // announced only after the upstream emits a complete call. names maps a Kiro -// tool name back to the name the client declared. -func writeConsumed(w io.Writer, model string, source eventSource, names map[string]string, filter *markupFilter) { +// tool name back to the name the client declared. cache, when set, adds the +// local prompt-cache estimate and is stored only after a clean stream. +func writeConsumed(w io.Writer, model string, source eventSource, names map[string]string, filter *markupFilter, cache *cacheTurn) { index := 0 var inputTokens, outputTokens int var credits, contextPct float64 @@ -90,7 +91,10 @@ func writeConsumed(w io.Writer, model string, source eventSource, names map[stri payload, _ := json.Marshal(map[string]any{"error": map[string]any{"message": err.Error(), "type": "upstream_error"}}) fmt.Fprintf(w, "data: %s\n\n", payload) } - usage := streamUsage(model, inputTokens, outputTokens, contextPct, produced.total(), credits, sawCredits) + usage := streamUsage(model, inputTokens, outputTokens, contextPct, produced.total(), credits, sawCredits, cache.estimate()) + if err == nil { + cache.commit() + } done := map[string]any{ "id": "chatcmpl-kiro", "object": "chat.completion.chunk", "created": time.Now().Unix(), "model": model, "choices": []map[string]any{{"index": 0, "delta": map[string]any{}, "finish_reason": finish}}, diff --git a/internal/providers/kiro/prompt_cache.go b/internal/providers/kiro/prompt_cache.go new file mode 100644 index 000000000..773e7c2e0 --- /dev/null +++ b/internal/providers/kiro/prompt_cache.go @@ -0,0 +1,256 @@ +package kiro + +import ( + "crypto/sha256" + "encoding/json" + "math" + "strings" + "sync" + "time" +) + +// Kiro reports neither cache reads nor cache writes, so they are estimated +// locally the way Kiro-Go does (proxy/cache_tracker.go): each request is cut +// into a prelude (model, system, tools) and one block per turn, every block +// end is fingerprinted with a running SHA-256, and a later request on the same +// account that repeats a stored prefix reads it from "cache". Fingerprints +// live in memory for the Anthropic default TTL of five minutes. The figures +// are an estimate for the request log and the client, not a billing number. + +const ( + promptCacheTTL = 5 * time.Minute + // Anthropic does not cache prefixes shorter than this. + minCacheableTokens = 1024 + opusMinCacheableTokens = 4096 + // The newest content in a request is never all served from cache. + maxCacheReadShare = 0.85 + // Media is counted at a flat size instead of by its base64 length. + mediaTokenEstimate = 1600 +) + +// promptCacheUsage is one request's estimate. Total is the local estimate of +// the whole prompt that Read and Write are measured against. +type promptCacheUsage struct { + Read, Write, Total int +} + +// scaled re-expresses the estimate against input, the prompt size the usage +// chunk reports (Kiro's context share), so the shares stay the same while +// read plus write never exceeds input. +func (u *promptCacheUsage) scaled(input int) (int, int) { + if u == nil || input <= 0 || u.Total <= 0 { + return 0, 0 + } + ratio := float64(input) / float64(u.Total) + read := min(int(math.Round(float64(u.Read)*ratio)), input) + write := min(int(math.Round(float64(u.Write)*ratio)), input-read) + return read, write +} + +type cacheBreakpoint struct { + fingerprint [32]byte + tokens int // cumulative estimate up to and including this block +} + +type cacheProfile struct { + model string + breakpoints []cacheBreakpoint + total int +} + +// buildCacheProfile fingerprints a conversation block by block. A user turn +// hashes the same whether it is the current turn or a replayed history turn, +// so this request's full prompt is the prefix the next turn looks up. +func buildCacheProfile(c conversation) *cacheProfile { + hasher := sha256.New() + profile := &cacheProfile{model: c.Model} + add := func(value any, tokens int) { + encoded, err := json.Marshal(value) + if err != nil { + return + } + hasher.Write(encoded) + hasher.Write([]byte{0}) + profile.total += tokens + var fingerprint [32]byte + copy(fingerprint[:], hasher.Sum(nil)) + profile.breakpoints = append(profile.breakpoints, cacheBreakpoint{fingerprint: fingerprint, tokens: profile.total}) + } + prelude := struct { + Model, System string + Tools []toolSpec + }{c.Model, c.System, c.Tools} + add(prelude, preludeTokens(c)) + for _, turn := range c.History { + switch { + case turn.User != nil: + add(turn.User, userTokens(*turn.User)) + case turn.Assistant != nil: + add(turn.Assistant, assistantTokens(*turn.Assistant)) + } + } + add(c.Current, userTokens(c.Current)) + if len(profile.breakpoints) == 0 || profile.total <= 0 { + return nil + } + return profile +} + +func preludeTokens(c conversation) int { + total := estimateTokens(c.System) + for _, tool := range c.Tools { + total += estimateTokens(tool.Name) + estimateTokens(tool.Description) + if schema, err := json.Marshal(tool.Parameters); err == nil { + total += estimateTokens(string(schema)) + } + } + return total +} + +func userTokens(turn userTurn) int { + total := estimateTokens(turn.Text) + mediaTokenEstimate*(len(turn.Images)+len(turn.Documents)) + for _, result := range turn.Results { + total += estimateTokens(result.Output) + } + return total +} + +func assistantTokens(turn assistantTurn) int { + total := estimateTokens(turn.Text) + for _, block := range turn.Reasoning { + total += estimateTokens(block.Text) + } + for _, call := range turn.ToolUses { + total += estimateTokens(call.Name) + if input, err := json.Marshal(call.Input); err == nil { + total += estimateTokens(string(input)) + } + } + return total +} + +func minCacheableFor(model string) int { + if strings.Contains(strings.ToLower(model), "opus") { + return opusMinCacheableTokens + } + return minCacheableTokens +} + +// promptCache holds stored prefix fingerprints per account. The zero of a nil +// *promptCache is valid and estimates nothing. +type promptCache struct { + mu sync.Mutex + entries map[string]map[[32]byte]time.Time // account -> fingerprint -> expiry + now func() time.Time +} + +func newPromptCache() *promptCache { + return &promptCache{entries: map[string]map[[32]byte]time.Time{}, now: time.Now} +} + +// compute estimates cache use for profile without storing it. The first +// cacheable request on an account writes the whole prompt. Later requests read +// the longest stored prefix, capped so part of the prompt stays uncached, and +// write the rest up to that cap. +func (t *promptCache) compute(account string, profile *cacheProfile) promptCacheUsage { + usage := promptCacheUsage{Total: profile.total} + minTokens := minCacheableFor(profile.model) + if profile.total < minTokens { + return usage + } + now := t.now() + t.mu.Lock() + defer t.mu.Unlock() + t.pruneLocked(now) + entries := t.entries[account] + if len(entries) == 0 { + usage.Write = profile.total + return usage + } + cacheable := int(float64(profile.total) * maxCacheReadShare) + matched := 0 + for i := len(profile.breakpoints) - 1; i >= 0; i-- { + point := profile.breakpoints[i] + if point.tokens < minTokens { + break + } + if _, ok := entries[point.fingerprint]; ok { + matched = min(point.tokens, cacheable) + break + } + } + usage.Read = matched + usage.Write = max(cacheable-matched, 0) + return usage +} + +// update stores every cacheable prefix of profile for the TTL. +func (t *promptCache) update(account string, profile *cacheProfile) { + minTokens := minCacheableFor(profile.model) + now := t.now() + t.mu.Lock() + defer t.mu.Unlock() + t.pruneLocked(now) + entries := t.entries[account] + if entries == nil { + entries = map[[32]byte]time.Time{} + t.entries[account] = entries + } + for _, point := range profile.breakpoints { + if point.tokens >= minTokens { + entries[point.fingerprint] = now.Add(promptCacheTTL) + } + } + if len(entries) == 0 { + delete(t.entries, account) + } +} + +func (t *promptCache) pruneLocked(now time.Time) { + for account, entries := range t.entries { + for fingerprint, expires := range entries { + if !expires.After(now) { + delete(entries, fingerprint) + } + } + if len(entries) == 0 { + delete(t.entries, account) + } + } +} + +// cacheTurn is one request's estimate. It is computed before the request is +// sent and stored only after the stream completes, so a failed request never +// seeds a hit for the next one. +type cacheTurn struct { + tracker *promptCache + account string + profile *cacheProfile + usage promptCacheUsage +} + +func (t *promptCache) begin(account string, c conversation) *cacheTurn { + if t == nil || account == "" { + return nil + } + profile := buildCacheProfile(c) + if profile == nil { + return nil + } + return &cacheTurn{tracker: t, account: account, profile: profile, usage: t.compute(account, profile)} +} + +func (c *cacheTurn) estimate() *promptCacheUsage { + if c == nil { + return nil + } + usage := c.usage + return &usage +} + +func (c *cacheTurn) commit() { + if c == nil { + return + } + c.tracker.update(c.account, c.profile) +} diff --git a/internal/providers/kiro/prompt_cache_test.go b/internal/providers/kiro/prompt_cache_test.go new file mode 100644 index 000000000..77a7cd9ca --- /dev/null +++ b/internal/providers/kiro/prompt_cache_test.go @@ -0,0 +1,161 @@ +package kiro + +import ( + "errors" + "strings" + "testing" + "time" +) + +var errUpstreamTest = errors.New("upstream reset") + +func longText(word string, n int) string { + return strings.TrimSpace(strings.Repeat(word+" ", n)) +} + +func cacheConversation(model string, turns ...string) conversation { + c := conversation{Model: model, System: longText("system", 2000)} + for i, text := range turns[:len(turns)-1] { + if i%2 == 0 { + c.History = append(c.History, historyTurn{User: &userTurn{Text: text}}) + } else { + c.History = append(c.History, historyTurn{Assistant: &assistantTurn{Text: text}}) + } + } + c.Current = userTurn{Text: turns[len(turns)-1]} + return c +} + +func TestPromptCacheFirstRequestWritesOnly(t *testing.T) { + cache := newPromptCache() + turn := cache.begin("acct", cacheConversation("claude-sonnet-4.6", "hello")) + usage := turn.estimate() + if usage.Read != 0 || usage.Write != usage.Total || usage.Total < minCacheableTokens { + t.Fatalf("usage = %+v", usage) + } +} + +func TestPromptCacheNextTurnReadsStoredPrefix(t *testing.T) { + cache := newPromptCache() + first := cache.begin("acct", cacheConversation("claude-sonnet-4.6", "hello")) + first.commit() + + // The new turns are long enough that the stored prefix stays under the + // 85% read cap. + next := cache.begin("acct", cacheConversation("claude-sonnet-4.6", "hello", longText("reply", 600), longText("again", 600))) + usage := next.estimate() + if usage.Read != first.usage.Total { + t.Fatalf("read = %d, want previous prompt %d", usage.Read, first.usage.Total) + } + cacheable := int(float64(usage.Total) * maxCacheReadShare) + if usage.Read+usage.Write != cacheable { + t.Fatalf("usage = %+v, cacheable = %d", usage, cacheable) + } +} + +func TestPromptCacheIsPerAccount(t *testing.T) { + cache := newPromptCache() + cache.begin("a", cacheConversation("claude-sonnet-4.6", "hello")).commit() + usage := cache.begin("b", cacheConversation("claude-sonnet-4.6", "hello")).estimate() + if usage.Read != 0 { + t.Fatalf("account b read account a's cache: %+v", usage) + } +} + +func TestPromptCacheExpires(t *testing.T) { + now := time.Now() + cache := newPromptCache() + cache.now = func() time.Time { return now } + cache.begin("acct", cacheConversation("claude-sonnet-4.6", "hello")).commit() + now = now.Add(promptCacheTTL + time.Second) + usage := cache.begin("acct", cacheConversation("claude-sonnet-4.6", "hello", "hi", "again")).estimate() + if usage.Read != 0 || usage.Write != usage.Total { + t.Fatalf("expired cache still read: %+v", usage) + } +} + +func TestPromptCacheSkipsShortPrompts(t *testing.T) { + cache := newPromptCache() + c := conversation{Model: "claude-sonnet-4.6", Current: userTurn{Text: "hi"}} + usage := cache.begin("acct", c).estimate() + if usage.Read != 0 || usage.Write != 0 { + t.Fatalf("short prompt cached: %+v", usage) + } +} + +func TestPromptCacheOpusNeedsLongerPrefix(t *testing.T) { + c := conversation{Model: "claude-opus-4.6", System: longText("system", 1500), Current: userTurn{Text: "hi"}} + usage := newPromptCache().begin("acct", c).estimate() + if usage.Total < minCacheableTokens || usage.Total >= opusMinCacheableTokens || usage.Write != 0 { + t.Fatalf("usage = %+v", usage) + } +} + +func TestPromptCacheFailedStreamIsNotStored(t *testing.T) { + cache := newPromptCache() + turn := cache.begin("acct", cacheConversation("claude-sonnet-4.6", "hello")) + frames := []streamEvent{ + {Type: "assistantResponseEvent", Event: map[string]any{"content": "partial"}}, + } + failing := func() eventSource { + source := sliceSource(frames) + return func() (streamEvent, error) { + next, err := source() + if err != nil { + return streamEvent{}, errUpstreamTest + } + return next, nil + } + }() + var out strings.Builder + writeConsumed(&out, "claude-sonnet-4.6", failing, nil, nil, turn) + if usage := cache.begin("acct", cacheConversation("claude-sonnet-4.6", "hello")).estimate(); usage.Read != 0 { + t.Fatalf("failed stream seeded a hit: %+v", usage) + } +} + +func TestPromptCacheNilIsSafe(t *testing.T) { + var cache *promptCache + turn := cache.begin("acct", cacheConversation("claude-sonnet-4.6", "hello")) + if turn != nil || turn.estimate() != nil { + t.Fatal("nil cache produced an estimate") + } + turn.commit() +} + +func TestPromptCacheScaledStaysWithinInput(t *testing.T) { + usage := &promptCacheUsage{Read: 800, Write: 150, Total: 1000} + read, write := usage.scaled(4000) + if read != 3200 || write != 600 { + t.Fatalf("scaled = %d, %d", read, write) + } + read, write = (&promptCacheUsage{Read: 900, Write: 900, Total: 1000}).scaled(100) + if read+write > 100 { + t.Fatalf("read %d + write %d exceeds input", read, write) + } +} + +// The usage chunk carries the estimate in OpenAI form; prompt_tokens stays the +// whole prompt and collectOutcome passes the cache split on. +func TestStreamUsageCarriesCacheEstimate(t *testing.T) { + cache := newPromptCache() + cache.begin("acct", cacheConversation("claude-sonnet-4.6", "hello")).commit() + turn := cache.begin("acct", cacheConversation("claude-sonnet-4.6", "hello", "hi there", "and now?")) + + var out strings.Builder + writeConsumed(&out, "claude-sonnet-4.6", sliceSource(capturedLegacyStream()), nil, nil, turn) + usage := finalUsage(t, out.String()) + read, _ := usage["cache_read_tokens"].(float64) + write, _ := usage["cache_write_tokens"].(float64) + if usage["prompt_tokens"] != float64(4109) || read <= 0 || read+write > 4109 { + t.Fatalf("usage = %v", usage) + } + + outcome, err := collectOutcome(strings.NewReader(out.String()), "") + if err != nil { + t.Fatal(err) + } + if outcome.CacheReadTokens == nil || *outcome.CacheReadTokens != int(read) || outcome.CacheWriteTokens == nil || *outcome.CacheWriteTokens != int(write) { + t.Fatalf("outcome = %+v", outcome) + } +} diff --git a/internal/providers/kiro/token_estimate.go b/internal/providers/kiro/token_estimate.go index 0a2ab479a..33a351824 100644 --- a/internal/providers/kiro/token_estimate.go +++ b/internal/providers/kiro/token_estimate.go @@ -41,3 +41,10 @@ func (c *tokenCounter) total() int { estimated := int(math.Ceil(float64(c.ascii)/4.5 + float64(c.digits)/2 + float64(c.symbols)/1.5 + float64(c.other)/1.5)) return max(1, estimated) } + +// estimateTokens is the same estimate for one piece of text. +func estimateTokens(text string) int { + var counter tokenCounter + counter.add(text) + return counter.total() +} diff --git a/internal/providers/kiro/tools_test.go b/internal/providers/kiro/tools_test.go index 9459dd4f9..4ad25b18a 100644 --- a/internal/providers/kiro/tools_test.go +++ b/internal/providers/kiro/tools_test.go @@ -57,7 +57,7 @@ func TestCreateResponseToolStreamMatchesAnthropicMessages(t *testing.T) { "response": map[string]any{"usage": map[string]any{"input_tokens": 11, "output_tokens": 7}}, })) - resp := writeOpenAIStream(io.NopCloser(strings.NewReader(raw.String())), "claude-sonnet-4.5", nil, nil) + resp := writeOpenAIStream(io.NopCloser(strings.NewReader(raw.String())), "claude-sonnet-4.5", nil, nil, nil) defer resp.Body.Close() openai, err := io.ReadAll(resp.Body) if err != nil { @@ -129,7 +129,7 @@ func TestIncompleteToolCallIsNotEmitted(t *testing.T) { raw.WriteString(sseLine(t, map[string]any{"type": "response.output_item.done", "item": map[string]any{"type": "function_call", "id": "fc_bad", "status": "incomplete"}})) raw.WriteString(sseLine(t, map[string]any{"type": "response.completed"})) - resp := writeOpenAIStream(io.NopCloser(strings.NewReader(raw.String())), "claude-sonnet-4.5", nil, nil) + resp := writeOpenAIStream(io.NopCloser(strings.NewReader(raw.String())), "claude-sonnet-4.5", nil, nil, nil) defer resp.Body.Close() body, _ := io.ReadAll(resp.Body) if strings.Contains(string(body), "Write") || strings.Contains(string(body), "call_bad") { @@ -459,7 +459,7 @@ func TestMarkupRescueBecomesToolCall(t *testing.T) { raw.WriteString(sseLine(t, map[string]any{"type": "response.output_text.delta", "delta": "calling "})) raw.WriteString(sseLine(t, map[string]any{"type": "response.output_text.delta", "delta": `/tmp/a`})) raw.WriteString(sseLine(t, map[string]any{"type": "response.completed", "response": map[string]any{"usage": map[string]any{"input_tokens": 1, "output_tokens": 1}}})) - resp := writeOpenAIStream(io.NopCloser(strings.NewReader(raw.String())), "claude-sonnet-4.5", nil, filter) + resp := writeOpenAIStream(io.NopCloser(strings.NewReader(raw.String())), "claude-sonnet-4.5", nil, filter, nil) defer resp.Body.Close() body, err := io.ReadAll(resp.Body) if err != nil { diff --git a/internal/providers/kiro/usage.go b/internal/providers/kiro/usage.go index 10077c99a..7dfbf9e64 100644 --- a/internal/providers/kiro/usage.go +++ b/internal/providers/kiro/usage.go @@ -64,18 +64,20 @@ func resolveUsage(model string, input, output int, contextPct float64, produced } // streamUsage is the usage object on the final OpenAI chunk. It is empty only -// when Kiro sent nothing at all to count. The counts are the tokens Kiro -// measured: a stated total when it sent one, otherwise the context-window -// share for input and the produced text for output. Kiro does not report -// cache reads or writes, so those fields are left off. A billing client -// prices a reported cache write above a normal input, and an estimated one -// would overcharge. -func streamUsage(model string, input, output int, contextPct float64, produced int, credits float64, sawCredits bool) map[string]any { +// when Kiro sent nothing at all to count. prompt_tokens keeps OpenAI meaning: +// it includes the cache read and creation shares estimated in cache. +func streamUsage(model string, input, output int, contextPct float64, produced int, credits float64, sawCredits bool, cache *promptCacheUsage) map[string]any { input, output, estimated := resolveUsage(model, input, output, contextPct, produced) if input <= 0 && output <= 0 && !sawCredits { return map[string]any{} } usage := map[string]any{"prompt_tokens": input, "completion_tokens": output, "total_tokens": input + output} + if cache != nil && input > 0 { + read, write := cache.scaled(input) + usage["cache_read_tokens"] = read + usage["cache_write_tokens"] = write + usage["prompt_tokens_details"] = map[string]any{"cached_tokens": read} + } if sawCredits { usage["credits"] = credits } diff --git a/internal/providers/kiro/usage_test.go b/internal/providers/kiro/usage_test.go index d04b1797e..0b3e9b385 100644 --- a/internal/providers/kiro/usage_test.go +++ b/internal/providers/kiro/usage_test.go @@ -33,12 +33,11 @@ func finalUsage(t *testing.T, raw string) map[string]any { func TestLegacyStreamReportsEstimatedTokensAndCredits(t *testing.T) { var out strings.Builder - writeConsumed(&out, "claude-sonnet-4.6", sliceSource(capturedLegacyStream()), nil, nil) + writeConsumed(&out, "claude-sonnet-4.6", sliceSource(capturedLegacyStream()), nil, nil, nil) usage := finalUsage(t, out.String()) - // 0.4109% of the 1M window Claude 4.6 uses. Cache reads and writes are not - // reported: Kiro did not send them, and a billing client would price a - // cache write above this input. + // 0.4109% of the 1M window Claude 4.6 uses. This stream has no cache + // tracker, so cache reads and writes stay off the usage chunk. if got := usage["prompt_tokens"]; got != float64(4109) { t.Fatalf("prompt_tokens = %v", got) } @@ -61,7 +60,7 @@ func TestLegacyStreamReportsEstimatedTokensAndCredits(t *testing.T) { func TestLegacyNonStreamKeepsUsage(t *testing.T) { var out strings.Builder - writeConsumed(&out, "claude-sonnet-4.6", sliceSource(capturedLegacyStream()), nil, nil) + writeConsumed(&out, "claude-sonnet-4.6", sliceSource(capturedLegacyStream()), nil, nil, nil) outcome, err := collectOutcome(strings.NewReader(out.String()), "medium") if err != nil { t.Fatal(err) @@ -114,7 +113,7 @@ func TestStatedTokensWin(t *testing.T) { }}, } var out strings.Builder - writeConsumed(&out, "claude-sonnet-4.5", sliceSource(frames), nil, nil) + writeConsumed(&out, "claude-sonnet-4.5", sliceSource(frames), nil, nil, nil) usage := finalUsage(t, out.String()) if usage["prompt_tokens"] != float64(11) || usage["completion_tokens"] != float64(7) || usage["source"] != "provider" { t.Fatalf("usage = %v", usage) @@ -141,7 +140,7 @@ func TestContextWindow(t *testing.T) { func TestNoUsageWhenNothingToCount(t *testing.T) { var out strings.Builder - writeConsumed(&out, "claude-sonnet-4.6", sliceSource(nil), nil, nil) + writeConsumed(&out, "claude-sonnet-4.6", sliceSource(nil), nil, nil, nil) if strings.Contains(out.String(), `"usage"`) { t.Fatalf("unexpected usage:\n%s", out.String()) } diff --git a/internal/providers/trae/checkin_test.go b/internal/providers/trae/checkin_test.go index 463531fd2..e7bfa1c5e 100644 --- a/internal/providers/trae/checkin_test.go +++ b/internal/providers/trae/checkin_test.go @@ -8,6 +8,9 @@ import ( "net/http" "strings" "testing" + "time" + + "github.com/caigee-cmd/cli2api/internal/providers" ) // seedCheckinCredential stores a long-lived Trae credential so Checkin does @@ -133,8 +136,14 @@ func TestCheckinClaimAlreadyRace(t *testing.T) { if err != nil { t.Fatal(err) } - if result.Status != "already" { - t.Fatalf("result=%+v", result) + // The claim endpoint can still replay yesterday's "already" before 02:00 + // Beijing, so that window reports unknown instead of a false today-hit. + want := "already" + if providers.CheckinClaimProvisional(time.Now()) { + want = "unknown" + } + if result.Status != want { + t.Fatalf("result=%+v want %s", result, want) } } diff --git a/internal/runtime/checkin_status_test.go b/internal/runtime/checkin_status_test.go index f2d434cb9..fd7d24d26 100644 --- a/internal/runtime/checkin_status_test.go +++ b/internal/runtime/checkin_status_test.go @@ -190,8 +190,13 @@ func TestSyncCheckinStatusUnknownKeepsRealLocalSuccess(t *testing.T) { // A provisional rollover answer: the provider cannot yet confirm today. return providers.CheckinResult{Status: "unknown", Message: "上游日界尚未确认,稍后复核", EarliestCheckin: "00:00"}, nil })) - old := time.Now().UTC().Add(-2 * time.Hour) - if err := manager.store.RecordCheckin(context.Background(), account.ID, "success", "claimed earlier", old); err != nil { + loc := time.FixedZone("UTC+8", 8*3600) + nowLocal := time.Now().In(loc) + claimed := nowLocal.Add(-2 * time.Hour) + if claimed.Format("2006-01-02") != nowLocal.Format("2006-01-02") { + claimed = time.Date(nowLocal.Year(), nowLocal.Month(), nowLocal.Day(), 0, 1, 0, 0, loc) + } + if err := manager.store.RecordCheckin(context.Background(), account.ID, "success", "claimed earlier", claimed.UTC()); err != nil { t.Fatal(err) } manager.SyncCheckinStatuses(context.Background())