Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(agent-runtime): apply CJK correction to context.tools schema in the output cap

xpeng5278-webaee08f0de690
diff --git a/packages/agent-runtime/src/output-cap.test.ts b/packages/agent-runtime/src/output-cap.test.ts
index 88b58a39a..c39495be7 100644
--- a/packages/agent-runtime/src/output-cap.test.ts
+++ b/packages/agent-runtime/src/output-cap.test.ts
@@ -160,6 +160,40 @@ describe("estimateOutputCapInputTokens", () => {
expect(estimateOutputCapInputTokens(context)).toBe(2008);
});
+ it("corrects CJK in context.tools the same way as system toolsAdded", () => {
+ const description = "测".repeat(4000);
+ const tools = [{
+ name: "lookup",
+ description,
+ parameters: { type: "object", properties: {} },
+ }];
+ const viaTools = estimateOutputCapInputTokens({ messages: [], tools });
+ const viaToolsAdded = estimateOutputCapInputTokens({
+ messages: [{ role: "system", content: "", toolsAdded: tools }],
+ });
+ // Serialized schema is 4083 chars: baseline ceil(4083 / 4) = 1021.
+ // 4000 Han chars add ceil(4000 * 0.75) = 3000. Subagent budgets pass
+ // schemas on context.tools, so that path must match toolsAdded.
+ expect(viaTools).toBe(viaToolsAdded);
+ expect(viaTools).toBe(4021);
+ });
+
+ it("estimates an ASCII tool schema the same on context.tools and toolsAdded", () => {
+ const description = "a".repeat(4000);
+ const tools = [{
+ name: "lookup",
+ description,
+ parameters: { type: "object", properties: {} },
+ }];
+ const viaTools = estimateOutputCapInputTokens({ messages: [], tools });
+ const viaToolsAdded = estimateOutputCapInputTokens({
+ messages: [{ role: "system", content: "", toolsAdded: tools }],
+ });
+ // Same 4083-char schema and no CJK, so both stay on the chars/4 baseline.
+ expect(viaTools).toBe(viaToolsAdded);
+ expect(viaTools).toBe(1021);
+ });
+
it("treats a raw string content and empty content consistently", () => {
expect(
estimateOutputCapInputTokens({
diff --git a/packages/agent-runtime/src/output-cap.ts b/packages/agent-runtime/src/output-cap.ts
index 916fd8038..991a627bb 100644
--- a/packages/agent-runtime/src/output-cap.ts
+++ b/packages/agent-runtime/src/output-cap.ts
@@ -271,9 +271,11 @@ export function estimateOutputCapInputTokens(
cjkChars += countCjkChars(context.systemPrompt);
}
if (context.tools?.length) {
- baseline += Math.ceil(
- stringifyForEstimate(context.tools).length / CHARS_PER_TOKEN,
- );
+ // Same formula as system toolsAdded. Subagent budgets pass schemas here,
+ // and chars/4 under-counts CJK in the serialized schema.
+ const serialized = stringifyForEstimate(context.tools);
+ baseline += Math.ceil(serialized.length / CHARS_PER_TOKEN);
+ cjkChars += countCjkChars(serialized);
}
// CJK chars are ~1 token each; the chars/4 baseline charged them 0.25.
return baseline + Math.ceil(cjkChars * 0.75);