kimi-code icon indicating copy to clipboard operation
kimi-code copied to clipboard

fix(kosong): clamp uncached OpenAI input usage

Open morluto opened this issue 4 months ago • 1 comments

Related Issue

No linked issue. This is a focused fix for a reproducible OpenAI-compatible usage edge case.

Problem

When a compatible endpoint reports cached-token details but omits the aggregate prompt/input token count, both OpenAI adapters default the aggregate to zero and then subtract the cache count. That produces a negative inputOther, which cancels the reported cache usage when total input is calculated.

Usage projection Before After
Reported aggregate input 0 0
Reported cache read 10 10
Derived uncached input -10 0
Calculated total input 0 10

Official OpenAI usage objects include the aggregate token fields, so this primarily hardens compatibility with partial responses from OpenAI-compatible endpoints.

What changed

  • Clamp derived uncached input tokens at zero for Chat Completions and Responses usage parsing.
  • Apply the same correction to the legacy and v2 provider implementations.
  • Add regressions for cache details reported without aggregate prompt/input totals.
  • Preserve the provider-reported cache and output counts unchanged.

Test plan

  • pnpm vitest run packages/kosong/test/kimi.test.ts packages/kosong/test/openai-responses.test.ts packages/agent-core-v2/test/kosong/provider/composition.test.ts (239 passed)
  • pnpm vitest run --project kosong (1,336 passed)
  • pnpm vitest run packages/agent-core-v2/test/agent/mcp/output.test.ts (39 passed)
  • pnpm --filter @moonshot-ai/kosong typecheck
  • pnpm --filter @moonshot-ai/agent-core-v2 typecheck
  • pnpm --filter @moonshot-ai/agent-core-v2 lint:domain
  • pnpm --filter @moonshot-ai/kosong build
  • pnpm --filter @moonshot-ai/agent-core-v2 build

Checklist

  • [x] I have read the CONTRIBUTING document.
  • [x] I have linked a related issue, or explained the problem above.
  • [x] I have added tests that prove my feature works.
  • [x] Ran gen-changesets skill, or this PR needs no changeset.
  • [x] Ran gen-docs skill, or this PR needs no doc update.

morluto avatar Jul 24 '26 17:07 morluto

🦋 Changeset detected

Latest commit: fe59b40efec8b2e729de35dea41d64c0a3389336

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@moonshot-ai/kimi-code Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

changeset-bot[bot] avatar Jul 24 '26 17:07 changeset-bot[bot]