@bastani/pi-ai 0.9.39 → 0.9.40-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +31 -0
- package/README.md +2 -0
- package/dist/api/azure-openai-responses.d.ts.map +1 -1
- package/dist/api/azure-openai-responses.js +6 -2
- package/dist/api/azure-openai-responses.js.map +1 -1
- package/dist/api/openai-codex-responses.d.ts.map +1 -1
- package/dist/api/openai-codex-responses.js +6 -2
- package/dist/api/openai-codex-responses.js.map +1 -1
- package/dist/api/openai-completions.d.ts.map +1 -1
- package/dist/api/openai-completions.js +9 -3
- package/dist/api/openai-completions.js.map +1 -1
- package/dist/api/openai-responses-shared.d.ts +16 -0
- package/dist/api/openai-responses-shared.d.ts.map +1 -1
- package/dist/api/openai-responses-shared.js +60 -8
- package/dist/api/openai-responses-shared.js.map +1 -1
- package/dist/api/openai-responses.d.ts.map +1 -1
- package/dist/api/openai-responses.js +2 -2
- package/dist/api/openai-responses.js.map +1 -1
- package/dist/api/system-one-shared.d.ts +10 -0
- package/dist/api/system-one-shared.d.ts.map +1 -1
- package/dist/api/system-one-shared.js +34 -4
- package/dist/api/system-one-shared.js.map +1 -1
- package/dist/api/typesafe-system-one.d.ts.map +1 -1
- package/dist/api/typesafe-system-one.js +3 -1
- package/dist/api/typesafe-system-one.js.map +1 -1
- package/dist/providers/data/.manifest.json +1 -1
- package/dist/providers/data/amazon-bedrock.json +1 -1
- package/dist/providers/data/azure.json +1 -1
- package/dist/providers/data/cloudflare-ai-gateway.json +1 -1
- package/dist/providers/data/cloudflare-workers-ai.json +1 -1
- package/dist/providers/data/google.json +1 -1
- package/dist/providers/data/huggingface.json +1 -1
- package/dist/providers/data/minimax-cn.json +1 -1
- package/dist/providers/data/minimax.json +1 -1
- package/dist/providers/data/mistral.json +1 -1
- package/dist/providers/data/moonshotai-cn.json +1 -1
- package/dist/providers/data/openai-codex.json +1 -1
- package/dist/providers/data/openai.json +1 -1
- package/dist/providers/data/opencode-go.json +1 -1
- package/dist/providers/data/opencode.json +1 -1
- package/dist/providers/data/openrouter.json +1 -1
- package/dist/providers/data/qwen-token-plan-cn.json +1 -1
- package/dist/providers/data/qwen-token-plan.json +1 -1
- package/dist/providers/data/radius.json +1 -1
- package/dist/providers/data/together.json +1 -1
- package/dist/providers/data/typesafe.json +1 -1
- package/dist/providers/data/vercel-ai-gateway.json +1 -1
- package/dist/providers/data/xai.json +1 -1
- package/dist/utils/overflow.d.ts.map +1 -1
- package/dist/utils/overflow.js +5 -1
- package/dist/utils/overflow.js.map +1 -1
- package/dist/utils/transcript.d.ts +22 -8
- package/dist/utils/transcript.d.ts.map +1 -1
- package/dist/utils/transcript.js +29 -18
- package/dist/utils/transcript.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"openai-responses":{"chat:grok-4.3":{"id":"grok-4.3","name":"Grok 4.3","api":"openai-responses","provider":"xai","baseUrl":"https://api.x.ai/v1","compat":{"supportsLongCacheRetention":false},"reasoning":true,"input":["text","image"],"cost":{"input":1.25,"output":2.5,"cacheRead":0.2,"cacheWrite":0,"tiers":[{"inputTokensAbove":200000,"input":2.5,"output":5,"cacheRead":0.4,"cacheWrite":0}]},"contextWindow":1000000,"maxTokens":30000,"thinkingLevelMap":{"off":"none","minimal":null,"low":"low","medium":"medium","high":"high","xhigh":
|
|
1
|
+
{"openai-responses":{"chat:grok-4.3":{"id":"grok-4.3","name":"Grok 4.3","api":"openai-responses","provider":"xai","baseUrl":"https://api.x.ai/v1","compat":{"supportsLongCacheRetention":false},"reasoning":true,"input":["text","image"],"cost":{"input":1.25,"output":2.5,"cacheRead":0.2,"cacheWrite":0,"tiers":[{"inputTokensAbove":200000,"input":2.5,"output":5,"cacheRead":0.4,"cacheWrite":0}]},"contextWindow":1000000,"maxTokens":30000,"thinkingLevelMap":{"off":"none","minimal":null,"low":"low","medium":"medium","high":"high","xhigh":"xhigh","max":null},"inputLimits":{"images":{"resize":{"maxWidth":2000,"maxHeight":2000,"maxBytes":4718592,"jpegQuality":80}}},"type":"chat"},"chat:grok-4.5":{"id":"grok-4.5","name":"Grok 4.5","api":"openai-responses","provider":"xai","baseUrl":"https://api.x.ai/v1","compat":{"supportsLongCacheRetention":false},"reasoning":true,"input":["text","image"],"cost":{"input":2,"output":6,"cacheRead":0.3,"cacheWrite":0,"tiers":[{"inputTokensAbove":200000,"input":4,"output":12,"cacheRead":0.6,"cacheWrite":0}]},"contextWindow":500000,"maxTokens":500000,"thinkingLevelMap":{"off":null,"minimal":null,"low":"low","medium":"medium","high":"high","xhigh":"xhigh","max":null},"inputLimits":{"images":{"resize":{"maxWidth":2000,"maxHeight":2000,"maxBytes":4718592,"jpegQuality":80}}},"type":"chat"},"chat:grok-4.6":{"id":"grok-4.6","name":"Grok 4.6","api":"openai-responses","provider":"xai","baseUrl":"https://api.x.ai/v1","compat":{"supportsLongCacheRetention":false},"reasoning":true,"input":["text","image"],"cost":{"input":2,"output":6,"cacheRead":0.5,"cacheWrite":0,"tiers":[{"inputTokensAbove":200000,"input":4,"output":12,"cacheRead":1,"cacheWrite":0}]},"contextWindow":500000,"maxTokens":500000,"thinkingLevelMap":{"off":null,"minimal":null,"low":"low","medium":"medium","high":"high","xhigh":"xhigh","max":null},"inputLimits":{"images":{"resize":{"maxWidth":2000,"maxHeight":2000,"maxBytes":4718592,"jpegQuality":80}}},"type":"chat"},"chat:grok-4.7":{"id":"grok-4.7","name":"Grok 4.7","api":"openai-responses","provider":"xai","baseUrl":"https://api.x.ai/v1","compat":{"supportsLongCacheRetention":false},"reasoning":true,"input":["text","image"],"cost":{"input":2,"output":6,"cacheRead":0.5,"cacheWrite":0,"tiers":[{"inputTokensAbove":200000,"input":4,"output":12,"cacheRead":1,"cacheWrite":0}]},"contextWindow":500000,"maxTokens":500000,"thinkingLevelMap":{"off":null,"minimal":null,"low":"low","medium":"medium","high":"high","xhigh":"xhigh","max":null},"inputLimits":{"images":{"resize":{"maxWidth":2000,"maxHeight":2000,"maxBytes":4718592,"jpegQuality":80}}},"type":"chat"}}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"overflow.d.ts","sourceRoot":"","sources":["../../src/utils/overflow.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"overflow.d.ts","sourceRoot":"","sources":["../../src/utils/overflow.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AA6FpD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsDG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,gBAAgB,EAAE,aAAa,CAAC,EAAE,MAAM,GAAG,OAAO,CAkC5F;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,GAAG,OAAO,CAEhG;AAED;;GAEG;AACH,wBAAgB,mBAAmB,IAAI,MAAM,EAAE,CAE9C"}
|
package/dist/utils/overflow.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Regex patterns to detect context overflow errors from different providers.
|
|
3
3
|
*
|
|
4
4
|
* These patterns match error messages returned when the input exceeds
|
|
5
|
-
* the model's context window.
|
|
5
|
+
* the model's context window or the provider's request byte-size limit.
|
|
6
6
|
*
|
|
7
7
|
* Provider-specific patterns (with example error messages):
|
|
8
8
|
*
|
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
* - llama.cpp: "the request exceeds the available context size, try increasing it"
|
|
21
21
|
* - LM Studio: "tokens to keep from the initial prompt is greater than the context length"
|
|
22
22
|
* - GitHub Copilot: "prompt token count of X exceeds the limit of Y"
|
|
23
|
+
* - GitHub Copilot: 'github-copilot API error (413): {"message":"failed to parse request","code":""}'
|
|
23
24
|
* - MiniMax: "invalid params, context window exceeds limit"
|
|
24
25
|
* - Kimi For Coding: "Your request exceeded model token limit: X (requested: Y)"
|
|
25
26
|
* - DS4: "Prompt has X tokens, but the configured context size is Y tokens"
|
|
@@ -58,6 +59,9 @@ const OVERFLOW_PATTERNS = [
|
|
|
58
59
|
/context[_ ]length[_ ]exceeded/i, // Generic fallback
|
|
59
60
|
/too many tokens/i, // Generic fallback
|
|
60
61
|
/token limit exceeded/i, // Generic fallback
|
|
62
|
+
// HTTP 413 means request-size overflow regardless of provider or body text.
|
|
63
|
+
// Match raw SDK errors and formatProviderError's prefix, not a status mentioned in the body.
|
|
64
|
+
/^(?:[\w .-]+ API error \(413\):|413(?:\s|:|$))/i,
|
|
61
65
|
];
|
|
62
66
|
function isCerebrasBodylessOverflow(errorMessage) {
|
|
63
67
|
const normalized = errorMessage.trim().toLowerCase();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"overflow.js","sourceRoot":"","sources":["../../src/utils/overflow.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,MAAM,iBAAiB,GAAG;IACzB,0BAA0B,EAAE,oCAAoC;IAChE,4BAA4B,EAAE,kCAAkC;IAChE,oBAAoB,EAAE,kDAAkD;IACxE,wCAAwC,EAAE,iBAAiB;IAC3D,6BAA6B,EAAE,uCAAuC;IACtE,4FAA4F,EAAE,sCAAsC;IACpI,yCAAyC,EAAE,kBAAkB;IAC7D,+BAA+B,EAAE,aAAa;IAC9C,oCAAoC,EAAE,OAAO;IAC7C,uCAAuC,EAAE,6BAA6B;IACtE,kEAAkE,EAAE,sBAAsB;IAC1F,iFAAiF,EAAE,cAAc;IACjG,2BAA2B,EAAE,iBAAiB;IAC9C,qCAAqC,EAAE,mBAAmB;IAC1D,kCAAkC,EAAE,YAAY;IAChD,+BAA+B,EAAE,UAAU;IAC3C,6BAA6B,EAAE,kBAAkB;IACjD,sDAAsD,EAAE,UAAU;IAClE,+EAA+E,EAAE,aAA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,CAAC,YAAY,CAAC,EAAE,CAAC;gBACzF,OAAO,IAAI,CAAC;YACb,CAAC;QACF,CAAC;IACF,CAAC;IAED,8EAA8E;IAC9E,IAAI,aAAa,IAAI,OAAO,CAAC,UAAU,KAAK,MAAM,EAAE,CAAC;QACpD,MAAM,WAAW,GAAG,OAAO,CAAC,KAAK,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,SAAS,CAAC;QAClE,IAAI,WAAW,GAAG,aAAa,EAAE,CAAC;YACjC,OAAO,IAAI,CAAC;QACb,CAAC;IACF,CAAC;IAED,sFAAsF;IACtF,qFAAqF;IACrF,gEAAgE;IAChE,IAAI,aAAa,IAAI,OAAO,CAAC,UAAU,KAAK,QAAQ,IAAI,OAAO,CAAC,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACpF,MAAM,WAAW,GAAG,OAAO,CAAC,KAAK,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,SAAS,CAAC;QAClE,IAAI,WAAW,IAAI,aAAa,GAAG,IAAI,EAAE,CAAC;YACzC,OAAO,IAAI,CAAC;QACb,CAAC;IACF,CAAC;IAED,OAAO,KAAK,CAAC;AACd,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,mBAAmB,CAAC,OAAyB,EAAE,gBAAwB;IACtF,OAAO,OAAO,CAAC,UAAU,KAAK,QAAQ,IAAI,gBAAgB,GAAG,CAAC,IAAI,OAAO,CAAC,KAAK,CAAC,MAAM,GAAG,gBAAgB,CAAC;AAC3G,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,mBAAmB;IAClC,OAAO,CAAC,GAAG,iBAAiB,CAAC,CAAC;AAC/B,CAAC","sourcesContent":["import type { AssistantMessage } from \"../types.ts\";\n\n/**\n * Regex patterns to detect context overflow errors from different providers.\n *\n * These patterns match error messages returned when the input exceeds\n * the model's context window.\n *\n * Provider-specific patterns (with example error messages):\n *\n * - Anthropic: \"prompt is too long: 213462 tokens > 200000 maximum\"\n * - Anthropic: \"413 {\\\"error\\\":{\\\"type\\\":\\\"request_too_large\\\",\\\"message\\\":\\\"Request exceeds the maximum size\\\"}}\"\n * - OpenAI: \"Your input exceeds the context window of this model\"\n * - OpenAI/LiteLLM: \"Requested token count exceeds the model's maximum context length of 131072 tokens\"\n * - OpenAI-compatible: \"Input length (265330) exceeds model's maximum context length (262144).\"\n * - Google: \"The input token count (1196265) exceeds the maximum number of tokens allowed (1048575)\"\n * - xAI: \"This model's maximum prompt length is 131072 but the request contains 537812 tokens\"\n * - Groq: \"Please reduce the length of the messages or completion\"\n * - OpenRouter: \"This endpoint's maximum context length is X tokens. However, you requested about Y tokens\"\n * - OpenRouter/Poolside: \"Input length X exceeds the maximum allowed input length of Y tokens.\"\n * - Together AI: \"The input (X tokens) is longer than the model's context length (Y tokens).\"\n * - llama.cpp: \"the request exceeds the available context size, try increasing it\"\n * - LM Studio: \"tokens to keep from the initial prompt is greater than the context length\"\n * - GitHub Copilot: \"prompt token count of X exceeds the limit of Y\"\n * - MiniMax: \"invalid params, context window exceeds limit\"\n * - Kimi For Coding: \"Your request exceeded model token limit: X (requested: Y)\"\n * - DS4: \"Prompt has X tokens, but the configured context size is Y tokens\"\n * - Cerebras: \"400/413 status code (no body)\"\n * - Mistral: \"Prompt contains X tokens ... too large for model with Y maximum context length\"\n * - z.ai: `{\"code\":\"1261\",\"message\":\"Prompt too long\"}`, `{\"code\":\"1261\",\"message\":\"Prompt exceeds max length\"}` (CN endpoint), or silent overflow via usage.input > contextWindow\n * - Xiaomi MiMo: Truncates input to fill contextWindow exactly, then returns finish_reason \"length\"\n * with output=0 (no room left to generate). Detected via stopReason \"length\" + zero output +\n * input filling the context window.\n * - DashScope/Qwen: \"Range of input length should be [1, X]\" (HTTP 400 invalid_parameter_error)\n * - Ollama: Some deployments truncate silently, others return errors like \"prompt too long; exceeded max context length by X tokens\"\n */\nconst OVERFLOW_PATTERNS = [\n\t/prompt (?:is )?too long/i, // Anthropic and z.ai token overflow\n\t/prompt exceeds max length/i, // z.ai CN endpoint token overflow\n\t/request_too_large/i, // Anthropic request byte-size overflow (HTTP 413)\n\t/input is too long for requested model/i, // Amazon Bedrock\n\t/exceeds the context window/i, // OpenAI (Completions & Responses API)\n\t/exceeds (?:the )?(?:model'?s )?maximum context length(?: of [\\d,]+ tokens?|\\s*\\([\\d,]+\\))/i, // OpenAI-compatible proxies (LiteLLM)\n\t/input token count.*exceeds the maximum/i, // Google (Gemini)\n\t/maximum prompt length is \\d+/i, // xAI (Grok)\n\t/reduce the length of the messages/i, // Groq\n\t/maximum context length is \\d+ tokens/i, // OpenRouter (most backends)\n\t/exceeds (?:the )?maximum allowed input length of [\\d,]+ tokens?/i, // OpenRouter/Poolside\n\t/input \\(\\d+ tokens\\) is longer than the model'?s context length \\(\\d+ tokens\\)/i, // Together AI\n\t/exceeds the limit of \\d+/i, // GitHub Copilot\n\t/exceeds the available context size/i, // llama.cpp server\n\t/greater than the context length/i, // LM Studio\n\t/context window exceeds limit/i, // MiniMax\n\t/exceeded model token limit/i, // Kimi For Coding\n\t/too large for model with \\d+ maximum context length/i, // Mistral\n\t/prompt has [\\d,]+ tokens?, but the configured context size is [\\d,]+ tokens?/i, // DS4 server\n\t/model_context_window_exceeded/i, // z.ai non-standard finish_reason surfaced as error text\n\t/prompt too long; exceeded (?:max )?context length/i, // Ollama explicit overflow error\n\t/range of input length should be/i, // DashScope / Qwen Token Plan\n\t/context[_ ]length[_ ]exceeded/i, // Generic fallback\n\t/too many tokens/i, // Generic fallback\n\t/token limit exceeded/i, // Generic fallback\n];\n\nfunction isCerebrasBodylessOverflow(errorMessage: string): boolean {\n\tconst normalized = errorMessage.trim().toLowerCase();\n\treturn (\n\t\tnormalized === \"400 status code (no body)\" ||\n\t\tnormalized === \"413 status code (no body)\" ||\n\t\tnormalized === \"400 (no body)\" ||\n\t\tnormalized === \"413 (no body)\"\n\t);\n}\n\n/**\n * Patterns that indicate non-overflow errors (e.g. rate limiting, server errors).\n * Error messages matching any of these are excluded from overflow detection\n * even if they also match an OVERFLOW_PATTERN.\n *\n * Example: Bedrock formats throttling errors as \"ThrottlingException: Too many tokens,\n * please wait before trying again.\" which would match the /too many tokens/i overflow\n * pattern without this exclusion.\n */\nconst NON_OVERFLOW_PATTERNS = [\n\t/^(Throttling error|Service unavailable):/i, // AWS Bedrock non-overflow errors (human-readable prefixes from formatBedrockError)\n\t/rate limit/i, // Generic rate limiting\n\t/too many requests/i, // Generic HTTP 429 style\n];\n\n/**\n * Check if an assistant message represents a context overflow error.\n *\n * This handles three cases:\n * 1. Error-based overflow: Most providers return stopReason \"error\" with a\n * specific error message pattern.\n * 2. Silent overflow: Some providers accept overflow requests and return\n * successfully. For these, we check if usage.input exceeds the context window.\n * 3. Length-stop overflow: Xiaomi MiMo can return \"length\" with zero output when\n * the input fills the context window.\n *\n * ## Reliability by Provider\n *\n * **Reliable detection (returns error with detectable message):**\n * - Anthropic: \"prompt is too long: X tokens > Y maximum\" or \"request_too_large\"\n * - OpenAI (Completions & Responses): \"exceeds the context window\", \"exceeds the model's maximum context length of X tokens\", or \"exceeds model's maximum context length (X)\"\n * - Google Gemini: \"input token count exceeds the maximum\"\n * - xAI (Grok): \"maximum prompt length is X but request contains Y\"\n * - Groq: \"reduce the length of the messages\"\n * - Cerebras: 400/413 status code (no body)\n * - Mistral: \"Prompt contains X tokens ... too large for model with Y maximum context length\"\n * - OpenRouter (most backends): \"maximum context length is X tokens\"\n * - OpenRouter/Poolside: \"Input length X exceeds the maximum allowed input length of Y tokens.\"\n * - Together AI: \"The input (X tokens) is longer than the model's context length (Y tokens).\"\n * - llama.cpp: \"exceeds the available context size\"\n * - LM Studio: \"greater than the context length\"\n * - Kimi For Coding: \"exceeded model token limit: X (requested: Y)\"\n * - DS4: \"Prompt has X tokens, but the configured context size is Y tokens\"\n * - DashScope/Qwen: \"Range of input length should be [1, X]\"\n * - z.ai: \"Prompt too long\"\n *\n * **Unreliable detection:**\n * - z.ai: Sometimes accepts overflow silently (detectable via usage.input > contextWindow),\n * sometimes returns rate limit errors. Pass contextWindow param to detect silent overflow.\n * - Xiaomi MiMo: Truncates input to fit contextWindow then returns stopReason \"length\" with\n * output=0. Pass contextWindow param to detect via the \"filled context + zero output\" signal.\n * - Ollama: May truncate input silently for some setups, but may also return explicit\n * overflow errors that match the patterns above. Silent truncation still cannot be\n * detected here because we do not know the expected token count.\n *\n * ## Custom Providers\n *\n * If you've added custom models via settings.json, this function may not detect\n * overflow errors from those providers. To add support:\n *\n * 1. Send a request that exceeds the model's context window\n * 2. Check the errorMessage in the response\n * 3. Create a regex pattern that matches the error\n * 4. The pattern should be added to OVERFLOW_PATTERNS in this file, or\n * check the errorMessage yourself before calling this function\n *\n * @param message - The assistant message to check\n * @param contextWindow - Optional context window size for detecting silent overflow (z.ai)\n * @returns true if the message indicates a context overflow\n */\nexport function isContextOverflow(message: AssistantMessage, contextWindow?: number): boolean {\n\t// Case 1: Check error message patterns\n\tif (message.stopReason === \"error\" && message.errorMessage) {\n\t\t// Skip messages matching known non-overflow patterns (e.g. throttling / rate-limit)\n\t\tconst isNonOverflow = NON_OVERFLOW_PATTERNS.some((p) => p.test(message.errorMessage!));\n\t\tif (!isNonOverflow) {\n\t\t\tif (OVERFLOW_PATTERNS.some((p) => p.test(message.errorMessage!))) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (message.provider === \"cerebras\" && isCerebrasBodylessOverflow(message.errorMessage)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Case 2: Silent overflow (z.ai style) - successful but usage exceeds context\n\tif (contextWindow && message.stopReason === \"stop\") {\n\t\tconst inputTokens = message.usage.input + message.usage.cacheRead;\n\t\tif (inputTokens > contextWindow) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t// Case 3: Length-stop overflow (Xiaomi MiMo style) - server truncates oversized input\n\t// to fit the context window, leaving no room for output. Returns stopReason \"length\"\n\t// with output=0 and input+cacheRead filling the context window.\n\tif (contextWindow && message.stopReason === \"length\" && message.usage.output === 0) {\n\t\tconst inputTokens = message.usage.input + message.usage.cacheRead;\n\t\tif (inputTokens >= contextWindow * 0.99) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\n/**\n * Check whether a length stop ended below the caller or model's intended output limit.\n * Such responses may be caused by context pressure or provider-side truncation, so callers\n * can make one bounded compact-and-retry attempt. `desiredMaxOutput` must be the original\n * limit before any context-based clamping.\n */\nexport function isRecoverableLength(message: AssistantMessage, desiredMaxOutput: number): boolean {\n\treturn message.stopReason === \"length\" && desiredMaxOutput > 0 && message.usage.output < desiredMaxOutput;\n}\n\n/**\n * Get the overflow patterns for testing purposes.\n */\nexport function getOverflowPatterns(): RegExp[] {\n\treturn [...OVERFLOW_PATTERNS];\n}\n"]}
|
|
1
|
+
{"version":3,"file":"overflow.js","sourceRoot":"","sources":["../../src/utils/overflow.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,MAAM,iBAAiB,GAAG;IACzB,0BAA0B,EAAE,oCAAoC;IAChE,4BAA4B,EAAE,kCAAkC;IAChE,oBAAoB,EAAE,kDAAkD;IACxE,wCAAwC,EAAE,iBAAiB;IAC3D,6BAA6B,EAAE,uCAAuC;IACtE,4FAA4F,EAAE,sCAAsC;IACpI,yCAAyC,EAAE,kBAAkB;IAC7D,+BAA+B,EAAE,aAAa;IAC9C,oCAAoC,EAAE,OAAO;IAC7C,uCAAuC,EAAE,6BAA6B;IACtE,kEAAkE,EAAE,sBAAsB;IAC1F,iFAAiF,EAAE,cAAc;IACjG,2BAA2B,EAAE,iBAAiB;IAC9C,qCAAqC,EAAE,mBAAmB;IAC1D,kCAAkC,EAAE,YAAY;IAChD,+BAA+B,EAAE,UAAU;IAC3C,6BAA6B,EAAE,kBAAkB;IACjD,sDAAsD,EAAE,UAAU;IAClE,+EAA+E,EAAE,aAAa;IAC9F,gCAAgC,EAAE,yDAAyD;IAC3F,oDAAoD,EAAE,iCAAi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AAC,EAAE,CAAC;gBACzF,OAAO,IAAI,CAAC;YACb,CAAC;QACF,CAAC;IACF,CAAC;IAED,8EAA8E;IAC9E,IAAI,aAAa,IAAI,OAAO,CAAC,UAAU,KAAK,MAAM,EAAE,CAAC;QACpD,MAAM,WAAW,GAAG,OAAO,CAAC,KAAK,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,SAAS,CAAC;QAClE,IAAI,WAAW,GAAG,aAAa,EAAE,CAAC;YACjC,OAAO,IAAI,CAAC;QACb,CAAC;IACF,CAAC;IAED,sFAAsF;IACtF,qFAAqF;IACrF,gEAAgE;IAChE,IAAI,aAAa,IAAI,OAAO,CAAC,UAAU,KAAK,QAAQ,IAAI,OAAO,CAAC,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACpF,MAAM,WAAW,GAAG,OAAO,CAAC,KAAK,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,SAAS,CAAC;QAClE,IAAI,WAAW,IAAI,aAAa,GAAG,IAAI,EAAE,CAAC;YACzC,OAAO,IAAI,CAAC;QACb,CAAC;IACF,CAAC;IAED,OAAO,KAAK,CAAC;AACd,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,mBAAmB,CAAC,OAAyB,EAAE,gBAAwB;IACtF,OAAO,OAAO,CAAC,UAAU,KAAK,QAAQ,IAAI,gBAAgB,GAAG,CAAC,IAAI,OAAO,CAAC,KAAK,CAAC,MAAM,GAAG,gBAAgB,CAAC;AAC3G,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,mBAAmB;IAClC,OAAO,CAAC,GAAG,iBAAiB,CAAC,CAAC;AAC/B,CAAC","sourcesContent":["import type { AssistantMessage } from \"../types.ts\";\n\n/**\n * Regex patterns to detect context overflow errors from different providers.\n *\n * These patterns match error messages returned when the input exceeds\n * the model's context window or the provider's request byte-size limit.\n *\n * Provider-specific patterns (with example error messages):\n *\n * - Anthropic: \"prompt is too long: 213462 tokens > 200000 maximum\"\n * - Anthropic: \"413 {\\\"error\\\":{\\\"type\\\":\\\"request_too_large\\\",\\\"message\\\":\\\"Request exceeds the maximum size\\\"}}\"\n * - OpenAI: \"Your input exceeds the context window of this model\"\n * - OpenAI/LiteLLM: \"Requested token count exceeds the model's maximum context length of 131072 tokens\"\n * - OpenAI-compatible: \"Input length (265330) exceeds model's maximum context length (262144).\"\n * - Google: \"The input token count (1196265) exceeds the maximum number of tokens allowed (1048575)\"\n * - xAI: \"This model's maximum prompt length is 131072 but the request contains 537812 tokens\"\n * - Groq: \"Please reduce the length of the messages or completion\"\n * - OpenRouter: \"This endpoint's maximum context length is X tokens. However, you requested about Y tokens\"\n * - OpenRouter/Poolside: \"Input length X exceeds the maximum allowed input length of Y tokens.\"\n * - Together AI: \"The input (X tokens) is longer than the model's context length (Y tokens).\"\n * - llama.cpp: \"the request exceeds the available context size, try increasing it\"\n * - LM Studio: \"tokens to keep from the initial prompt is greater than the context length\"\n * - GitHub Copilot: \"prompt token count of X exceeds the limit of Y\"\n * - GitHub Copilot: 'github-copilot API error (413): {\"message\":\"failed to parse request\",\"code\":\"\"}'\n * - MiniMax: \"invalid params, context window exceeds limit\"\n * - Kimi For Coding: \"Your request exceeded model token limit: X (requested: Y)\"\n * - DS4: \"Prompt has X tokens, but the configured context size is Y tokens\"\n * - Cerebras: \"400/413 status code (no body)\"\n * - Mistral: \"Prompt contains X tokens ... too large for model with Y maximum context length\"\n * - z.ai: `{\"code\":\"1261\",\"message\":\"Prompt too long\"}`, `{\"code\":\"1261\",\"message\":\"Prompt exceeds max length\"}` (CN endpoint), or silent overflow via usage.input > contextWindow\n * - Xiaomi MiMo: Truncates input to fill contextWindow exactly, then returns finish_reason \"length\"\n * with output=0 (no room left to generate). Detected via stopReason \"length\" + zero output +\n * input filling the context window.\n * - DashScope/Qwen: \"Range of input length should be [1, X]\" (HTTP 400 invalid_parameter_error)\n * - Ollama: Some deployments truncate silently, others return errors like \"prompt too long; exceeded max context length by X tokens\"\n */\nconst OVERFLOW_PATTERNS = [\n\t/prompt (?:is )?too long/i, // Anthropic and z.ai token overflow\n\t/prompt exceeds max length/i, // z.ai CN endpoint token overflow\n\t/request_too_large/i, // Anthropic request byte-size overflow (HTTP 413)\n\t/input is too long for requested model/i, // Amazon Bedrock\n\t/exceeds the context window/i, // OpenAI (Completions & Responses API)\n\t/exceeds (?:the )?(?:model'?s )?maximum context length(?: of [\\d,]+ tokens?|\\s*\\([\\d,]+\\))/i, // OpenAI-compatible proxies (LiteLLM)\n\t/input token count.*exceeds the maximum/i, // Google (Gemini)\n\t/maximum prompt length is \\d+/i, // xAI (Grok)\n\t/reduce the length of the messages/i, // Groq\n\t/maximum context length is \\d+ tokens/i, // OpenRouter (most backends)\n\t/exceeds (?:the )?maximum allowed input length of [\\d,]+ tokens?/i, // OpenRouter/Poolside\n\t/input \\(\\d+ tokens\\) is longer than the model'?s context length \\(\\d+ tokens\\)/i, // Together AI\n\t/exceeds the limit of \\d+/i, // GitHub Copilot\n\t/exceeds the available context size/i, // llama.cpp server\n\t/greater than the context length/i, // LM Studio\n\t/context window exceeds limit/i, // MiniMax\n\t/exceeded model token limit/i, // Kimi For Coding\n\t/too large for model with \\d+ maximum context length/i, // Mistral\n\t/prompt has [\\d,]+ tokens?, but the configured context size is [\\d,]+ tokens?/i, // DS4 server\n\t/model_context_window_exceeded/i, // z.ai non-standard finish_reason surfaced as error text\n\t/prompt too long; exceeded (?:max )?context length/i, // Ollama explicit overflow error\n\t/range of input length should be/i, // DashScope / Qwen Token Plan\n\t/context[_ ]length[_ ]exceeded/i, // Generic fallback\n\t/too many tokens/i, // Generic fallback\n\t/token limit exceeded/i, // Generic fallback\n\t// HTTP 413 means request-size overflow regardless of provider or body text.\n\t// Match raw SDK errors and formatProviderError's prefix, not a status mentioned in the body.\n\t/^(?:[\\w .-]+ API error \\(413\\):|413(?:\\s|:|$))/i,\n];\n\nfunction isCerebrasBodylessOverflow(errorMessage: string): boolean {\n\tconst normalized = errorMessage.trim().toLowerCase();\n\treturn (\n\t\tnormalized === \"400 status code (no body)\" ||\n\t\tnormalized === \"413 status code (no body)\" ||\n\t\tnormalized === \"400 (no body)\" ||\n\t\tnormalized === \"413 (no body)\"\n\t);\n}\n\n/**\n * Patterns that indicate non-overflow errors (e.g. rate limiting, server errors).\n * Error messages matching any of these are excluded from overflow detection\n * even if they also match an OVERFLOW_PATTERN.\n *\n * Example: Bedrock formats throttling errors as \"ThrottlingException: Too many tokens,\n * please wait before trying again.\" which would match the /too many tokens/i overflow\n * pattern without this exclusion.\n */\nconst NON_OVERFLOW_PATTERNS = [\n\t/^(Throttling error|Service unavailable):/i, // AWS Bedrock non-overflow errors (human-readable prefixes from formatBedrockError)\n\t/rate limit/i, // Generic rate limiting\n\t/too many requests/i, // Generic HTTP 429 style\n];\n\n/**\n * Check if an assistant message represents a context overflow error.\n *\n * This handles three cases:\n * 1. Error-based overflow: Most providers return stopReason \"error\" with a\n * specific error message pattern.\n * 2. Silent overflow: Some providers accept overflow requests and return\n * successfully. For these, we check if usage.input exceeds the context window.\n * 3. Length-stop overflow: Xiaomi MiMo can return \"length\" with zero output when\n * the input fills the context window.\n *\n * ## Reliability by Provider\n *\n * **Reliable detection (returns error with detectable message):**\n * - Anthropic: \"prompt is too long: X tokens > Y maximum\" or \"request_too_large\"\n * - OpenAI (Completions & Responses): \"exceeds the context window\", \"exceeds the model's maximum context length of X tokens\", or \"exceeds model's maximum context length (X)\"\n * - Google Gemini: \"input token count exceeds the maximum\"\n * - xAI (Grok): \"maximum prompt length is X but request contains Y\"\n * - Groq: \"reduce the length of the messages\"\n * - Cerebras: 400/413 status code (no body)\n * - Mistral: \"Prompt contains X tokens ... too large for model with Y maximum context length\"\n * - OpenRouter (most backends): \"maximum context length is X tokens\"\n * - OpenRouter/Poolside: \"Input length X exceeds the maximum allowed input length of Y tokens.\"\n * - Together AI: \"The input (X tokens) is longer than the model's context length (Y tokens).\"\n * - llama.cpp: \"exceeds the available context size\"\n * - LM Studio: \"greater than the context length\"\n * - Kimi For Coding: \"exceeded model token limit: X (requested: Y)\"\n * - DS4: \"Prompt has X tokens, but the configured context size is Y tokens\"\n * - DashScope/Qwen: \"Range of input length should be [1, X]\"\n * - z.ai: \"Prompt too long\"\n *\n * **Unreliable detection:**\n * - z.ai: Sometimes accepts overflow silently (detectable via usage.input > contextWindow),\n * sometimes returns rate limit errors. Pass contextWindow param to detect silent overflow.\n * - Xiaomi MiMo: Truncates input to fit contextWindow then returns stopReason \"length\" with\n * output=0. Pass contextWindow param to detect via the \"filled context + zero output\" signal.\n * - Ollama: May truncate input silently for some setups, but may also return explicit\n * overflow errors that match the patterns above. Silent truncation still cannot be\n * detected here because we do not know the expected token count.\n *\n * ## Custom Providers\n *\n * If you've added custom models via settings.json, this function may not detect\n * overflow errors from those providers. To add support:\n *\n * 1. Send a request that exceeds the model's context window\n * 2. Check the errorMessage in the response\n * 3. Create a regex pattern that matches the error\n * 4. The pattern should be added to OVERFLOW_PATTERNS in this file, or\n * check the errorMessage yourself before calling this function\n *\n * @param message - The assistant message to check\n * @param contextWindow - Optional context window size for detecting silent overflow (z.ai)\n * @returns true if the message indicates a context overflow\n */\nexport function isContextOverflow(message: AssistantMessage, contextWindow?: number): boolean {\n\t// Case 1: Check error message patterns\n\tif (message.stopReason === \"error\" && message.errorMessage) {\n\t\t// Skip messages matching known non-overflow patterns (e.g. throttling / rate-limit)\n\t\tconst isNonOverflow = NON_OVERFLOW_PATTERNS.some((p) => p.test(message.errorMessage!));\n\t\tif (!isNonOverflow) {\n\t\t\tif (OVERFLOW_PATTERNS.some((p) => p.test(message.errorMessage!))) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (message.provider === \"cerebras\" && isCerebrasBodylessOverflow(message.errorMessage)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Case 2: Silent overflow (z.ai style) - successful but usage exceeds context\n\tif (contextWindow && message.stopReason === \"stop\") {\n\t\tconst inputTokens = message.usage.input + message.usage.cacheRead;\n\t\tif (inputTokens > contextWindow) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t// Case 3: Length-stop overflow (Xiaomi MiMo style) - server truncates oversized input\n\t// to fit the context window, leaving no room for output. Returns stopReason \"length\"\n\t// with output=0 and input+cacheRead filling the context window.\n\tif (contextWindow && message.stopReason === \"length\" && message.usage.output === 0) {\n\t\tconst inputTokens = message.usage.input + message.usage.cacheRead;\n\t\tif (inputTokens >= contextWindow * 0.99) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\n/**\n * Check whether a length stop ended below the caller or model's intended output limit.\n * Such responses may be caused by context pressure or provider-side truncation, so callers\n * can make one bounded compact-and-retry attempt. `desiredMaxOutput` must be the original\n * limit before any context-based clamping.\n */\nexport function isRecoverableLength(message: AssistantMessage, desiredMaxOutput: number): boolean {\n\treturn message.stopReason === \"length\" && desiredMaxOutput > 0 && message.usage.output < desiredMaxOutput;\n}\n\n/**\n * Get the overflow patterns for testing purposes.\n */\nexport function getOverflowPatterns(): RegExp[] {\n\treturn [...OVERFLOW_PATTERNS];\n}\n"]}
|
|
@@ -68,20 +68,34 @@ export declare function getDeclaredTools(messages: TranscriptMessages): Tool[];
|
|
|
68
68
|
export declare function hasToolRedefinitions(messages: TranscriptMessages): boolean;
|
|
69
69
|
/** Whether tool history contains a removal or same-name redeclaration that an addition-only transport cannot replay. */
|
|
70
70
|
export declare function hasNonAdditiveToolChanges(messages: TranscriptMessages): boolean;
|
|
71
|
+
/**
|
|
72
|
+
* How a transport can express tool changes after the first request.
|
|
73
|
+
*
|
|
74
|
+
* - `"none"`: only the top-level tool list exists; it always holds the current tools.
|
|
75
|
+
* - `"additions"`: tools can be added at a later message, but not removed or redefined.
|
|
76
|
+
* - `"changes"`: every tool, including the initial ones, is declared in place, and a later
|
|
77
|
+
* declaration under the same name replaces the earlier one. Removals are not expressible on
|
|
78
|
+
* the wire, so the transport announces them as text and the removed tools stay declared.
|
|
79
|
+
*/
|
|
80
|
+
export type TranscriptToolSupport = "none" | "additions" | "changes";
|
|
71
81
|
export interface TranscriptTools {
|
|
72
82
|
/** Tools sent in the top-level request field. */
|
|
73
83
|
requestTools: Tool[];
|
|
74
84
|
/**
|
|
75
|
-
*
|
|
76
|
-
*
|
|
85
|
+
* Number of leading system messages whose tool changes `requestTools` already holds. Every
|
|
86
|
+
* later system message carries its own tool changes in place.
|
|
77
87
|
*/
|
|
78
|
-
|
|
88
|
+
foldedSystemMessages: number;
|
|
79
89
|
}
|
|
80
90
|
/**
|
|
81
|
-
* Split tool declarations between the top-level request field and in-place
|
|
82
|
-
*
|
|
83
|
-
*
|
|
84
|
-
*
|
|
91
|
+
* Split tool declarations between the top-level request field and in-place changes.
|
|
92
|
+
*
|
|
93
|
+
* With `"changes"`, the top-level list stays empty and every system message, including the
|
|
94
|
+
* leading one, declares its tools in place: an in-place declaration can replace an earlier
|
|
95
|
+
* in-place one, but not a top-level one. With `"additions"`, a removal or redefinition cannot be
|
|
96
|
+
* expressed in place, so the top-level list becomes the tool state after the last such change;
|
|
97
|
+
* later additions stay anchored, and the cached prefix is invalidated once per removal instead
|
|
98
|
+
* of on every later addition. With `"none"`, the top-level list is the current tool set.
|
|
85
99
|
*/
|
|
86
|
-
export declare function resolveTranscriptTools(messages: TranscriptMessages,
|
|
100
|
+
export declare function resolveTranscriptTools(messages: TranscriptMessages, support: TranscriptToolSupport): TranscriptTools;
|
|
87
101
|
//# sourceMappingURL=transcript.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transcript.d.ts","sourceRoot":"","sources":["../../src/utils/transcript.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,aAAa,EAAE,IAAI,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAG3G,YAAY,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAErD;;;GAGG;AACH,wBAAgB,0BAA0B,CACzC,YAAY,EAAE,MAAM,GAAG,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GG;IACH,oBAAoB,EAAE,MAAM,CAAC;CAC7B;AAED;;;;;;;;;GASG;AACH,wBAAgB,sBAAsB,CAAC,QAAQ,EAAE,kBAAkB,EAAE,OAAO,EAAE,qBAAqB,GAAG,eAAe,CAWpH"}
|
package/dist/utils/transcript.js
CHANGED
|
@@ -175,33 +175,44 @@ export function hasToolRedefinitions(messages) {
|
|
|
175
175
|
}
|
|
176
176
|
/** Whether tool history contains a removal or same-name redeclaration that an addition-only transport cannot replay. */
|
|
177
177
|
export function hasNonAdditiveToolChanges(messages) {
|
|
178
|
+
return findLastNonAdditiveToolChange(messages.filter(isSystemMessage)) >= 0;
|
|
179
|
+
}
|
|
180
|
+
/** Index of the last system message with a removal or same-name redeclaration, or -1. */
|
|
181
|
+
function findLastNonAdditiveToolChange(systemMessages) {
|
|
182
|
+
// A name declared before counts as a redeclaration even after its removal: Kimi K3 ignores a
|
|
183
|
+
// removed tool that a later tool message declares again (verified October 2026).
|
|
178
184
|
const declared = new Set();
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
185
|
+
let last = -1;
|
|
186
|
+
for (let index = 0; index < systemMessages.length; index++) {
|
|
187
|
+
const message = systemMessages[index];
|
|
182
188
|
if ((message.toolsRemoved?.length ?? 0) > 0)
|
|
183
|
-
|
|
189
|
+
last = index;
|
|
184
190
|
for (const tool of message.toolsAdded ?? []) {
|
|
185
191
|
if (declared.has(tool.name))
|
|
186
|
-
|
|
192
|
+
last = index;
|
|
187
193
|
declared.add(tool.name);
|
|
188
194
|
}
|
|
189
195
|
}
|
|
190
|
-
return
|
|
196
|
+
return last;
|
|
191
197
|
}
|
|
192
198
|
/**
|
|
193
|
-
* Split tool declarations between the top-level request field and in-place
|
|
194
|
-
*
|
|
195
|
-
*
|
|
196
|
-
*
|
|
199
|
+
* Split tool declarations between the top-level request field and in-place changes.
|
|
200
|
+
*
|
|
201
|
+
* With `"changes"`, the top-level list stays empty and every system message, including the
|
|
202
|
+
* leading one, declares its tools in place: an in-place declaration can replace an earlier
|
|
203
|
+
* in-place one, but not a top-level one. With `"additions"`, a removal or redefinition cannot be
|
|
204
|
+
* expressed in place, so the top-level list becomes the tool state after the last such change;
|
|
205
|
+
* later additions stay anchored, and the cached prefix is invalidated once per removal instead
|
|
206
|
+
* of on every later addition. With `"none"`, the top-level list is the current tool set.
|
|
197
207
|
*/
|
|
198
|
-
export function resolveTranscriptTools(messages,
|
|
199
|
-
const
|
|
200
|
-
|
|
201
|
-
requestTools:
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
208
|
+
export function resolveTranscriptTools(messages, support) {
|
|
209
|
+
const systemMessages = messages.filter(isSystemMessage);
|
|
210
|
+
if (support === "none") {
|
|
211
|
+
return { requestTools: getCurrentTools(systemMessages), foldedSystemMessages: systemMessages.length };
|
|
212
|
+
}
|
|
213
|
+
if (support === "changes")
|
|
214
|
+
return { requestTools: [], foldedSystemMessages: 0 };
|
|
215
|
+
const folded = Math.max(getInitialSystemMessage(messages) ? 1 : 0, findLastNonAdditiveToolChange(systemMessages) + 1);
|
|
216
|
+
return { requestTools: getCurrentTools(systemMessages.slice(0, folded)), foldedSystemMessages: folded };
|
|
206
217
|
}
|
|
207
218
|
//# sourceMappingURL=transcript.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transcript.js","sourceRoot":"","sources":["../../src/utils/transcript.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,oBAAoB,EAAE,MAAM,WAAW,CAAC;AAI9D;;;GAGG;AACH,MAAM,UAAU,0BAA0B,CACzC,YAAgC,EAChC,KAAyB;IAEzB,MAAM,eAAe,GAAG,YAAY,KAAK,SAAS,IAAI,YAAY,CAAC,MAAM,GAAG,CAAC,CAAC;IAC9E,MAAM,QAAQ,GAAG,KAAK,KAAK,SAAS,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC;IACzD,IAAI,CAAC,eAAe,IAAI,CAAC,QAAQ;QAAE,OAAO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ChB,CAAC;AACH,CAAC","sourcesContent":["import type { Context, Message, SystemMessage, Tool, ToolReference, TranscriptContext } from \"../types.ts\";\nimport { contentText, getSystemMessageText } from \"./text.ts\";\n\nexport type { TranscriptContext } from \"../types.ts\";\n\n/**\n * Build the leading system message for a prompt and tool set. Returns undefined when\n * both are empty, so an empty transcript stays empty.\n */\nexport function createInitialSystemMessage(\n\tsystemPrompt: string | undefined,\n\ttools: Tool[] | undefined,\n): SystemMessage | undefined {\n\tconst hasSystemPrompt = systemPrompt !== undefined && systemPrompt.length > 0;\n\tconst hasTools = tools !== undefined && tools.length > 0;\n\tif (!hasSystemPrompt && !hasTools) return undefined;\n\treturn {\n\t\trole: \"system\",\n\t\tcontent: systemPrompt ?? \"\",\n\t\t...(hasTools ? { toolsAdded: tools } : {}),\n\t\ttimestamp: 0,\n\t};\n}\n\n/**\n * Fold `Context.systemPrompt` and `Context.tools` into a leading system message.\n * This is the only entry point that produces a {@link TranscriptContext}; every\n * provider-facing function expects the result.\n */\nexport function normalizeContext(context: Context): TranscriptContext {\n\tconst initialMessage = createInitialSystemMessage(context.systemPrompt, context.tools);\n\tconst messages = initialMessage ? [initialMessage, ...context.messages] : context.messages;\n\treturn { messages } as TranscriptContext;\n}\n\n/**\n * Any message list. The replay helpers only read entries whose role is `\"system\"`, so\n * agent transcripts that carry custom message roles can be passed without filtering.\n */\nexport type TranscriptMessages = readonly { role: string }[];\n\nfunction isSystemMessage(message: { role: string }): message is SystemMessage {\n\treturn message.role === \"system\";\n}\n\n/** Return the leading system message, if the transcript starts with one. */\nexport function getInitialSystemMessage(messages: TranscriptMessages): SystemMessage | undefined {\n\tconst first = messages[0];\n\treturn first && isSystemMessage(first) ? first : undefined;\n}\n\n/** Drop the leading system message for APIs that carry the prompt outside the message list. */\nexport function withoutInitialSystemMessage(messages: Message[]): Message[] {\n\treturn getInitialSystemMessage(messages) ? messages.slice(1) : messages;\n}\n\n/** Resolve the tools available after applying every transcript delta in order. */\nexport function getCurrentTools(messages: TranscriptMessages): Tool[] {\n\tconst tools = new Map<string, Tool>();\n\tfor (const message of messages) {\n\t\tif (!isSystemMessage(message)) continue;\n\t\tfor (const tool of message.toolsRemoved ?? []) tools.delete(tool.name);\n\t\tfor (const tool of message.toolsAdded ?? []) tools.set(tool.name, tool);\n\t}\n\treturn [...tools.values()];\n}\n\n/**\n * Replay every system message into one leading system message holding the current\n * prompt and tools. Later `content` is appended to the base prompt, `sections` are\n * patched by name, and tools are resolved with {@link getCurrentTools}.\n */\nexport function getCurrentSystemMessage(messages: TranscriptMessages): SystemMessage | undefined {\n\tconst content: string[] = [];\n\tconst sections = new Map<string, string>();\n\tlet timestamp: number | undefined;\n\tfor (const message of messages) {\n\t\tif (!isSystemMessage(message)) continue;\n\t\ttimestamp ??= message.timestamp;\n\t\tconst text = contentText(message.content);\n\t\tif (text.length > 0) content.push(text);\n\t\tfor (const [name, value] of Object.entries(message.sections ?? {})) {\n\t\t\tif (value === null) sections.delete(name);\n\t\t\telse sections.set(name, value);\n\t\t}\n\t}\n\tconst tools = getCurrentTools(messages);\n\tif (timestamp === undefined && tools.length === 0) return undefined;\n\treturn {\n\t\trole: \"system\",\n\t\tcontent: content.join(\"\\n\\n\"),\n\t\t...(sections.size > 0 ? { sections: Object.fromEntries(sections) } : {}),\n\t\t...(tools.length > 0 ? { toolsAdded: tools } : {}),\n\t\ttimestamp: timestamp ?? 0,\n\t};\n}\n\n/** Render the current system prompt text after replaying every system message. */\nexport function getCurrentSystemPrompt(messages: TranscriptMessages): string {\n\tconst message = getCurrentSystemMessage(messages);\n\treturn message ? getSystemMessageText(message) : \"\";\n}\n\n/**\n * Rebuild the transcript for APIs without mid-conversation system messages: the replayed\n * system message leads, and every later system message is dropped.\n */\nexport function collapseSystemMessages(context: TranscriptContext): TranscriptContext {\n\tconst head = getCurrentSystemMessage(context.messages);\n\tconst messages = context.messages.filter((message) => message.role !== \"system\");\n\treturn { messages: head ? [head, ...messages] : messages } as TranscriptContext;\n}\n\n/** Keep later system messages in place when the model accepts them; otherwise collapse them. */\nexport function resolveTranscript(\n\tcontext: TranscriptContext,\n\tsupportsMidConvoSystemMessages: boolean | undefined,\n): TranscriptContext {\n\treturn supportsMidConvoSystemMessages ? context : collapseSystemMessages(context);\n}\n\n/** Strip executable and display-only fields from a tool before transcript comparison or persistence. */\nexport function toToolDeclaration(tool: Tool): Tool {\n\treturn {\n\t\tname: tool.name,\n\t\tdescription: tool.description,\n\t\tparameters: JSON.parse(JSON.stringify(tool.parameters)) as Tool[\"parameters\"],\n\t\t...(tool.constrainedSampling === undefined ? {} : { constrainedSampling: tool.constrainedSampling }),\n\t};\n}\n\n/**\n * Whether two tools declare the same interface to the model.\n *\n * Both sides go through {@link toToolDeclaration} first: its JSON round-trip drops the\n * typebox symbol keys and `undefined` fields that a structural comparison would see, and\n * builds both objects with the same key order, so comparing the serialized declarations\n * is exact. This avoids a deep-equal dependency in a browser-safe package.\n */\nexport function declarationsEqual(left: Tool, right: Tool): boolean {\n\treturn JSON.stringify(toToolDeclaration(left)) === JSON.stringify(toToolDeclaration(right));\n}\n\nexport interface ToolStateChanges {\n\ttoolsAdded: Tool[];\n\ttoolsRemoved: ToolReference[];\n}\n\n/** Compare two complete tool states. A changed definition is a removal followed by an addition. */\nexport function getToolStateChanges(previous: readonly Tool[], current: readonly Tool[]): ToolStateChanges {\n\tconst previousTools = new Map(previous.map((tool) => [tool.name, tool]));\n\tconst currentTools = new Map(current.map((tool) => [tool.name, tool]));\n\treturn {\n\t\ttoolsAdded: current\n\t\t\t.filter((tool) => {\n\t\t\t\tconst previousTool = previousTools.get(tool.name);\n\t\t\t\treturn previousTool === undefined || !declarationsEqual(previousTool, tool);\n\t\t\t})\n\t\t\t.map(toToolDeclaration),\n\t\ttoolsRemoved: previous\n\t\t\t.filter((tool) => {\n\t\t\t\tconst currentTool = currentTools.get(tool.name);\n\t\t\t\treturn currentTool === undefined || !declarationsEqual(tool, currentTool);\n\t\t\t})\n\t\t\t.map((tool) => ({ name: tool.name })),\n\t};\n}\n\n/** Every definition referenced by transcript tool state, in first-declaration order. */\nexport function getDeclaredTools(messages: TranscriptMessages): Tool[] {\n\tconst definitions = new Map<string, Tool>();\n\tfor (const message of messages) {\n\t\tif (!isSystemMessage(message)) continue;\n\t\tfor (const tool of message.toolsAdded ?? []) definitions.set(tool.name, tool);\n\t}\n\treturn [...definitions.values()];\n}\n\n/**\n * Whether a tool name was declared twice with different definitions. A transport that can\n * only reference previously declared tools by name cannot replay such a history.\n *\n * @deprecated No built-in transport needs this anymore: Anthropic expresses redefinitions with\n * inline `tool_definition` blocks. Kept for API compatibility and will be removed in a future release.\n */\nexport function hasToolRedefinitions(messages: TranscriptMessages): boolean {\n\tconst declared = new Map<string, Tool>();\n\tfor (const message of messages) {\n\t\tif (!isSystemMessage(message)) continue;\n\t\tfor (const tool of message.toolsAdded ?? []) {\n\t\t\tconst previous = declared.get(tool.name);\n\t\t\tif (previous !== undefined && !declarationsEqual(previous, tool)) return true;\n\t\t\tdeclared.set(tool.name, tool);\n\t\t}\n\t}\n\treturn false;\n}\n\n/** Whether tool history contains a removal or same-name redeclaration that an addition-only transport cannot replay. */\nexport function hasNonAdditiveToolChanges(messages: TranscriptMessages): boolean {\n\tconst declared = new Set<string>();\n\tfor (const message of messages) {\n\t\tif (!isSystemMessage(message)) continue;\n\t\tif ((message.toolsRemoved?.length ?? 0) > 0) return true;\n\t\tfor (const tool of message.toolsAdded ?? []) {\n\t\t\tif (declared.has(tool.name)) return true;\n\t\t\tdeclared.add(tool.name);\n\t\t}\n\t}\n\treturn false;\n}\n\nexport interface TranscriptTools {\n\t/** Tools sent in the top-level request field. */\n\trequestTools: Tool[];\n\t/**\n\t * Whether later system messages carry their own `toolsAdded` as in-place additions.\n\t * When false, `requestTools` already holds the complete current tool set.\n\t */\n\tanchorsAdditions: boolean;\n}\n\n/**\n * Split tool declarations between the top-level request field and in-place additions.\n * Transports that can anchor additions at a system message keep the initial tools at the\n * top and load later ones where they appear; that only works when no tool was removed or\n * redeclared, so everything else sends the current tool list.\n */\nexport function resolveTranscriptTools(messages: TranscriptMessages, supportsToolAdditions: boolean): TranscriptTools {\n\tconst anchorsAdditions = supportsToolAdditions && !hasNonAdditiveToolChanges(messages);\n\treturn {\n\t\trequestTools: anchorsAdditions\n\t\t\t? (getInitialSystemMessage(messages)?.toolsAdded ?? [])\n\t\t\t: getCurrentTools(messages),\n\t\tanchorsAdditions,\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"transcript.js","sourceRoot":"","sources":["../../src/utils/transcript.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,oBAAoB,EAAE,MAAM,WAAW,CAAC;AAI9D;;;GAGG;AACH,MAAM,UAAU,0BAA0B,CACzC,YAAgC,EAChC,KAAyB;IAEzB,MAAM,eAAe,GAAG,YAAY,KAAK,SAAS,IAAI,YAAY,CAAC,MAAM,GAAG,CAAC,CAAC;IAC9E,MAAM,QAAQ,GAAG,KAAK,KAAK,SAAS,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC;IACzD,IAAI,CAAC,eAAe,IAAI,CAAC,QAAQ;QAAE,OAAO,SAAS,CAAC;IACpD,OAAO;QACN,IAAI,EAAE,QAAQ;QACd,OAAO,EAAE,YAAY,IAAI,EAAE;QAC3B,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC1C,SAAS,EAAE,CAAC;KACZ,CAAC;AACH,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,gBAAgB,CAAC,OAAgB;IAChD,MAAM,cAAc,GAAG,0BAA0B,CAAC,OAAO,CAAC,YAAY,EAAE,OAAO,CAAC,KAAK,CAAC,CAAC;IACvF,MAAM,QAAQ,GAAG,cAAc,CAAC,CAAC,CAAC,CAAC,cAAc,EAAE,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC;I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C,CACjD,CAAC;IACF,OAAO,EAAE,YAAY,EAAE,eAAe,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC,EAAE,oBAAoB,EAAE,MAAM,EAAE,CAAC;AACzG,CAAC","sourcesContent":["import type { Context, Message, SystemMessage, Tool, ToolReference, TranscriptContext } from \"../types.ts\";\nimport { contentText, getSystemMessageText } from \"./text.ts\";\n\nexport type { TranscriptContext } from \"../types.ts\";\n\n/**\n * Build the leading system message for a prompt and tool set. Returns undefined when\n * both are empty, so an empty transcript stays empty.\n */\nexport function createInitialSystemMessage(\n\tsystemPrompt: string | undefined,\n\ttools: Tool[] | undefined,\n): SystemMessage | undefined {\n\tconst hasSystemPrompt = systemPrompt !== undefined && systemPrompt.length > 0;\n\tconst hasTools = tools !== undefined && tools.length > 0;\n\tif (!hasSystemPrompt && !hasTools) return undefined;\n\treturn {\n\t\trole: \"system\",\n\t\tcontent: systemPrompt ?? \"\",\n\t\t...(hasTools ? { toolsAdded: tools } : {}),\n\t\ttimestamp: 0,\n\t};\n}\n\n/**\n * Fold `Context.systemPrompt` and `Context.tools` into a leading system message.\n * This is the only entry point that produces a {@link TranscriptContext}; every\n * provider-facing function expects the result.\n */\nexport function normalizeContext(context: Context): TranscriptContext {\n\tconst initialMessage = createInitialSystemMessage(context.systemPrompt, context.tools);\n\tconst messages = initialMessage ? [initialMessage, ...context.messages] : context.messages;\n\treturn { messages } as TranscriptContext;\n}\n\n/**\n * Any message list. The replay helpers only read entries whose role is `\"system\"`, so\n * agent transcripts that carry custom message roles can be passed without filtering.\n */\nexport type TranscriptMessages = readonly { role: string }[];\n\nfunction isSystemMessage(message: { role: string }): message is SystemMessage {\n\treturn message.role === \"system\";\n}\n\n/** Return the leading system message, if the transcript starts with one. */\nexport function getInitialSystemMessage(messages: TranscriptMessages): SystemMessage | undefined {\n\tconst first = messages[0];\n\treturn first && isSystemMessage(first) ? first : undefined;\n}\n\n/** Drop the leading system message for APIs that carry the prompt outside the message list. */\nexport function withoutInitialSystemMessage(messages: Message[]): Message[] {\n\treturn getInitialSystemMessage(messages) ? messages.slice(1) : messages;\n}\n\n/** Resolve the tools available after applying every transcript delta in order. */\nexport function getCurrentTools(messages: TranscriptMessages): Tool[] {\n\tconst tools = new Map<string, Tool>();\n\tfor (const message of messages) {\n\t\tif (!isSystemMessage(message)) continue;\n\t\tfor (const tool of message.toolsRemoved ?? []) tools.delete(tool.name);\n\t\tfor (const tool of message.toolsAdded ?? []) tools.set(tool.name, tool);\n\t}\n\treturn [...tools.values()];\n}\n\n/**\n * Replay every system message into one leading system message holding the current\n * prompt and tools. Later `content` is appended to the base prompt, `sections` are\n * patched by name, and tools are resolved with {@link getCurrentTools}.\n */\nexport function getCurrentSystemMessage(messages: TranscriptMessages): SystemMessage | undefined {\n\tconst content: string[] = [];\n\tconst sections = new Map<string, string>();\n\tlet timestamp: number | undefined;\n\tfor (const message of messages) {\n\t\tif (!isSystemMessage(message)) continue;\n\t\ttimestamp ??= message.timestamp;\n\t\tconst text = contentText(message.content);\n\t\tif (text.length > 0) content.push(text);\n\t\tfor (const [name, value] of Object.entries(message.sections ?? {})) {\n\t\t\tif (value === null) sections.delete(name);\n\t\t\telse sections.set(name, value);\n\t\t}\n\t}\n\tconst tools = getCurrentTools(messages);\n\tif (timestamp === undefined && tools.length === 0) return undefined;\n\treturn {\n\t\trole: \"system\",\n\t\tcontent: content.join(\"\\n\\n\"),\n\t\t...(sections.size > 0 ? { sections: Object.fromEntries(sections) } : {}),\n\t\t...(tools.length > 0 ? { toolsAdded: tools } : {}),\n\t\ttimestamp: timestamp ?? 0,\n\t};\n}\n\n/** Render the current system prompt text after replaying every system message. */\nexport function getCurrentSystemPrompt(messages: TranscriptMessages): string {\n\tconst message = getCurrentSystemMessage(messages);\n\treturn message ? getSystemMessageText(message) : \"\";\n}\n\n/**\n * Rebuild the transcript for APIs without mid-conversation system messages: the replayed\n * system message leads, and every later system message is dropped.\n */\nexport function collapseSystemMessages(context: TranscriptContext): TranscriptContext {\n\tconst head = getCurrentSystemMessage(context.messages);\n\tconst messages = context.messages.filter((message) => message.role !== \"system\");\n\treturn { messages: head ? [head, ...messages] : messages } as TranscriptContext;\n}\n\n/** Keep later system messages in place when the model accepts them; otherwise collapse them. */\nexport function resolveTranscript(\n\tcontext: TranscriptContext,\n\tsupportsMidConvoSystemMessages: boolean | undefined,\n): TranscriptContext {\n\treturn supportsMidConvoSystemMessages ? context : collapseSystemMessages(context);\n}\n\n/** Strip executable and display-only fields from a tool before transcript comparison or persistence. */\nexport function toToolDeclaration(tool: Tool): Tool {\n\treturn {\n\t\tname: tool.name,\n\t\tdescription: tool.description,\n\t\tparameters: JSON.parse(JSON.stringify(tool.parameters)) as Tool[\"parameters\"],\n\t\t...(tool.constrainedSampling === undefined ? {} : { constrainedSampling: tool.constrainedSampling }),\n\t};\n}\n\n/**\n * Whether two tools declare the same interface to the model.\n *\n * Both sides go through {@link toToolDeclaration} first: its JSON round-trip drops the\n * typebox symbol keys and `undefined` fields that a structural comparison would see, and\n * builds both objects with the same key order, so comparing the serialized declarations\n * is exact. This avoids a deep-equal dependency in a browser-safe package.\n */\nexport function declarationsEqual(left: Tool, right: Tool): boolean {\n\treturn JSON.stringify(toToolDeclaration(left)) === JSON.stringify(toToolDeclaration(right));\n}\n\nexport interface ToolStateChanges {\n\ttoolsAdded: Tool[];\n\ttoolsRemoved: ToolReference[];\n}\n\n/** Compare two complete tool states. A changed definition is a removal followed by an addition. */\nexport function getToolStateChanges(previous: readonly Tool[], current: readonly Tool[]): ToolStateChanges {\n\tconst previousTools = new Map(previous.map((tool) => [tool.name, tool]));\n\tconst currentTools = new Map(current.map((tool) => [tool.name, tool]));\n\treturn {\n\t\ttoolsAdded: current\n\t\t\t.filter((tool) => {\n\t\t\t\tconst previousTool = previousTools.get(tool.name);\n\t\t\t\treturn previousTool === undefined || !declarationsEqual(previousTool, tool);\n\t\t\t})\n\t\t\t.map(toToolDeclaration),\n\t\ttoolsRemoved: previous\n\t\t\t.filter((tool) => {\n\t\t\t\tconst currentTool = currentTools.get(tool.name);\n\t\t\t\treturn currentTool === undefined || !declarationsEqual(tool, currentTool);\n\t\t\t})\n\t\t\t.map((tool) => ({ name: tool.name })),\n\t};\n}\n\n/** Every definition referenced by transcript tool state, in first-declaration order. */\nexport function getDeclaredTools(messages: TranscriptMessages): Tool[] {\n\tconst definitions = new Map<string, Tool>();\n\tfor (const message of messages) {\n\t\tif (!isSystemMessage(message)) continue;\n\t\tfor (const tool of message.toolsAdded ?? []) definitions.set(tool.name, tool);\n\t}\n\treturn [...definitions.values()];\n}\n\n/**\n * Whether a tool name was declared twice with different definitions. A transport that can\n * only reference previously declared tools by name cannot replay such a history.\n *\n * @deprecated No built-in transport needs this anymore: Anthropic expresses redefinitions with\n * inline `tool_definition` blocks. Kept for API compatibility and will be removed in a future release.\n */\nexport function hasToolRedefinitions(messages: TranscriptMessages): boolean {\n\tconst declared = new Map<string, Tool>();\n\tfor (const message of messages) {\n\t\tif (!isSystemMessage(message)) continue;\n\t\tfor (const tool of message.toolsAdded ?? []) {\n\t\t\tconst previous = declared.get(tool.name);\n\t\t\tif (previous !== undefined && !declarationsEqual(previous, tool)) return true;\n\t\t\tdeclared.set(tool.name, tool);\n\t\t}\n\t}\n\treturn false;\n}\n\n/** Whether tool history contains a removal or same-name redeclaration that an addition-only transport cannot replay. */\nexport function hasNonAdditiveToolChanges(messages: TranscriptMessages): boolean {\n\treturn findLastNonAdditiveToolChange(messages.filter(isSystemMessage)) >= 0;\n}\n\n/** Index of the last system message with a removal or same-name redeclaration, or -1. */\nfunction findLastNonAdditiveToolChange(systemMessages: readonly SystemMessage[]): number {\n\t// A name declared before counts as a redeclaration even after its removal: Kimi K3 ignores a\n\t// removed tool that a later tool message declares again (verified October 2026).\n\tconst declared = new Set<string>();\n\tlet last = -1;\n\tfor (let index = 0; index < systemMessages.length; index++) {\n\t\tconst message = systemMessages[index];\n\t\tif ((message.toolsRemoved?.length ?? 0) > 0) last = index;\n\t\tfor (const tool of message.toolsAdded ?? []) {\n\t\t\tif (declared.has(tool.name)) last = index;\n\t\t\tdeclared.add(tool.name);\n\t\t}\n\t}\n\treturn last;\n}\n\n/**\n * How a transport can express tool changes after the first request.\n *\n * - `\"none\"`: only the top-level tool list exists; it always holds the current tools.\n * - `\"additions\"`: tools can be added at a later message, but not removed or redefined.\n * - `\"changes\"`: every tool, including the initial ones, is declared in place, and a later\n * declaration under the same name replaces the earlier one. Removals are not expressible on\n * the wire, so the transport announces them as text and the removed tools stay declared.\n */\nexport type TranscriptToolSupport = \"none\" | \"additions\" | \"changes\";\n\nexport interface TranscriptTools {\n\t/** Tools sent in the top-level request field. */\n\trequestTools: Tool[];\n\t/**\n\t * Number of leading system messages whose tool changes `requestTools` already holds. Every\n\t * later system message carries its own tool changes in place.\n\t */\n\tfoldedSystemMessages: number;\n}\n\n/**\n * Split tool declarations between the top-level request field and in-place changes.\n *\n * With `\"changes\"`, the top-level list stays empty and every system message, including the\n * leading one, declares its tools in place: an in-place declaration can replace an earlier\n * in-place one, but not a top-level one. With `\"additions\"`, a removal or redefinition cannot be\n * expressed in place, so the top-level list becomes the tool state after the last such change;\n * later additions stay anchored, and the cached prefix is invalidated once per removal instead\n * of on every later addition. With `\"none\"`, the top-level list is the current tool set.\n */\nexport function resolveTranscriptTools(messages: TranscriptMessages, support: TranscriptToolSupport): TranscriptTools {\n\tconst systemMessages = messages.filter(isSystemMessage);\n\tif (support === \"none\") {\n\t\treturn { requestTools: getCurrentTools(systemMessages), foldedSystemMessages: systemMessages.length };\n\t}\n\tif (support === \"changes\") return { requestTools: [], foldedSystemMessages: 0 };\n\tconst folded = Math.max(\n\t\tgetInitialSystemMessage(messages) ? 1 : 0,\n\t\tfindLastNonAdditiveToolChange(systemMessages) + 1,\n\t);\n\treturn { requestTools: getCurrentTools(systemMessages.slice(0, folded)), foldedSystemMessages: folded };\n}\n"]}
|
package/package.json
CHANGED