@code-yeongyu/senpi-ai 2026.8.12-4 → 2026.8.13
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/README.md +24 -8
- package/dist/api/anthropic-messages.js.map +1 -1
- package/dist/api/azure-openai-responses.js +5 -1
- package/dist/api/azure-openai-responses.js.map +1 -1
- package/dist/api/bedrock-converse-stream.js.map +1 -1
- package/dist/api/bedrock-converse-stream.lazy.js.map +1 -1
- package/dist/api/google-generative-ai.d.ts.map +1 -1
- package/dist/api/google-generative-ai.js +2 -2
- package/dist/api/google-generative-ai.js.map +1 -1
- package/dist/api/google-shared.d.ts +15 -1
- package/dist/api/google-shared.d.ts.map +1 -1
- package/dist/api/google-shared.js +103 -4
- package/dist/api/google-shared.js.map +1 -1
- package/dist/api/google-vertex.d.ts.map +1 -1
- package/dist/api/google-vertex.js +2 -2
- package/dist/api/google-vertex.js.map +1 -1
- package/dist/api/lazy.d.ts +5 -1
- package/dist/api/lazy.d.ts.map +1 -1
- package/dist/api/lazy.js +19 -7
- package/dist/api/lazy.js.map +1 -1
- package/dist/api/openai-codex-responses.js.map +1 -1
- package/dist/api/openai-completions.d.ts +3 -1
- package/dist/api/openai-completions.d.ts.map +1 -1
- package/dist/api/openai-completions.js +47 -7
- package/dist/api/openai-completions.js.map +1 -1
- package/dist/api/openai-responses-shared.d.ts.map +1 -1
- package/dist/api/openai-responses-shared.js +22 -9
- package/dist/api/openai-responses-shared.js.map +1 -1
- package/dist/api/openai-responses.js +5 -1
- package/dist/api/openai-responses.js.map +1 -1
- package/dist/api/pi-messages.d.ts.map +1 -1
- package/dist/api/pi-messages.js.map +1 -1
- package/dist/api/simple-options.d.ts +2 -0
- package/dist/api/simple-options.d.ts.map +1 -1
- package/dist/api/simple-options.js +8 -2
- package/dist/api/simple-options.js.map +1 -1
- package/dist/api/transform-messages.js.map +1 -1
- package/dist/api/warm-prompt-cache.js.map +1 -1
- package/dist/auth/credential-store.d.ts +6 -6
- package/dist/auth/credential-store.d.ts.map +1 -1
- package/dist/auth/credential-store.js +22 -11
- package/dist/auth/credential-store.js.map +1 -1
- package/dist/auth/helpers.d.ts +1 -0
- package/dist/auth/helpers.d.ts.map +1 -1
- package/dist/auth/helpers.js +7 -2
- package/dist/auth/helpers.js.map +1 -1
- package/dist/auth/oauth/anthropic.d.ts.map +1 -1
- package/dist/auth/oauth/anthropic.js +14 -8
- package/dist/auth/oauth/anthropic.js.map +1 -1
- package/dist/auth/oauth/device-code.d.ts +1 -1
- package/dist/auth/oauth/device-code.d.ts.map +1 -1
- package/dist/auth/oauth/device-code.js +4 -4
- package/dist/auth/oauth/device-code.js.map +1 -1
- package/dist/auth/oauth/github-copilot.d.ts.map +1 -1
- package/dist/auth/oauth/github-copilot.js +43 -30
- package/dist/auth/oauth/github-copilot.js.map +1 -1
- package/dist/auth/oauth/kimi-coding.d.ts.map +1 -1
- package/dist/auth/oauth/kimi-coding.js +17 -5
- package/dist/auth/oauth/kimi-coding.js.map +1 -1
- package/dist/auth/oauth/load.d.ts.map +1 -1
- package/dist/auth/oauth/load.js.map +1 -1
- package/dist/auth/oauth/openai-codex.d.ts.map +1 -1
- package/dist/auth/oauth/openai-codex.js +12 -5
- package/dist/auth/oauth/openai-codex.js.map +1 -1
- package/dist/auth/oauth/openrouter.d.ts.map +1 -1
- package/dist/auth/oauth/openrouter.js +10 -10
- package/dist/auth/oauth/openrouter.js.map +1 -1
- package/dist/auth/oauth/radius.d.ts.map +1 -1
- package/dist/auth/oauth/radius.js +8 -7
- package/dist/auth/oauth/radius.js.map +1 -1
- package/dist/auth/oauth/xai.d.ts.map +1 -1
- package/dist/auth/oauth/xai.js +3 -2
- package/dist/auth/oauth/xai.js.map +1 -1
- package/dist/auth/resolve.d.ts +1 -0
- package/dist/auth/resolve.d.ts.map +1 -1
- package/dist/auth/resolve.js +24 -13
- package/dist/auth/resolve.js.map +1 -1
- package/dist/auth/types.d.ts +21 -8
- package/dist/auth/types.d.ts.map +1 -1
- package/dist/auth/types.js.map +1 -1
- package/dist/cli.js +1 -0
- package/dist/cli.js.map +1 -1
- package/dist/compat.js.map +1 -1
- package/dist/env-api-keys.d.ts.map +1 -1
- package/dist/env-api-keys.js +2 -0
- package/dist/env-api-keys.js.map +1 -1
- package/dist/image-models.generated.d.ts +69 -54
- package/dist/image-models.generated.d.ts.map +1 -1
- package/dist/image-models.generated.js +15 -0
- package/dist/image-models.generated.js.map +1 -1
- package/dist/images-models.d.ts.map +1 -1
- package/dist/images-models.js +1 -0
- package/dist/images-models.js.map +1 -1
- package/dist/model.d.ts +2 -0
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js.map +1 -1
- package/dist/models-store.d.ts +9 -12
- package/dist/models-store.d.ts.map +1 -1
- package/dist/models-store.js +6 -3
- package/dist/models-store.js.map +1 -1
- package/dist/models.d.ts +40 -18
- package/dist/models.d.ts.map +1 -1
- package/dist/models.generated.d.ts +4 -0
- package/dist/models.generated.d.ts.map +1 -1
- package/dist/models.generated.js +4 -0
- package/dist/models.generated.js.map +1 -1
- package/dist/models.js +247 -91
- package/dist/models.js.map +1 -1
- package/dist/node/provider-scope.d.ts.map +1 -1
- package/dist/providers/all.d.ts.map +1 -1
- package/dist/providers/all.js +4 -0
- package/dist/providers/all.js.map +1 -1
- package/dist/providers/amazon-bedrock.d.ts.map +1 -1
- package/dist/providers/amazon-bedrock.js +15 -7
- package/dist/providers/amazon-bedrock.js.map +1 -1
- package/dist/providers/anthropic.d.ts.map +1 -1
- package/dist/providers/anthropic.js +15 -6
- package/dist/providers/anthropic.js.map +1 -1
- package/dist/providers/baseten.d.ts +3 -0
- package/dist/providers/baseten.d.ts.map +1 -0
- package/dist/providers/baseten.js +15 -0
- package/dist/providers/baseten.js.map +1 -0
- package/dist/providers/baseten.models.d.ts +4 -0
- package/dist/providers/baseten.models.d.ts.map +1 -0
- package/dist/providers/baseten.models.js +6 -0
- package/dist/providers/baseten.models.js.map +1 -0
- package/dist/providers/cloudflare-auth.d.ts.map +1 -1
- package/dist/providers/cloudflare-auth.js +15 -10
- package/dist/providers/cloudflare-auth.js.map +1 -1
- package/dist/providers/data/.manifest.json +1 -1
- package/dist/providers/data/baseten.json +1 -0
- package/dist/providers/data/fireworks.json +1 -1
- package/dist/providers/data/github-copilot.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-individual.json +1 -0
- package/dist/providers/data/qwen-token-plan.json +1 -1
- package/dist/providers/data/vercel-ai-gateway.json +1 -1
- package/dist/providers/data/xai.json +1 -1
- package/dist/providers/faux.d.ts +18 -13
- package/dist/providers/faux.d.ts.map +1 -1
- package/dist/providers/faux.js +95 -5
- package/dist/providers/faux.js.map +1 -1
- package/dist/providers/github-copilot.js +1 -1
- package/dist/providers/github-copilot.js.map +1 -1
- package/dist/providers/google-vertex.d.ts.map +1 -1
- package/dist/providers/google-vertex.js +15 -7
- package/dist/providers/google-vertex.js.map +1 -1
- package/dist/providers/kimi-coding.d.ts.map +1 -1
- package/dist/providers/kimi-coding.js +1 -0
- package/dist/providers/kimi-coding.js.map +1 -1
- package/dist/providers/ollama.d.ts.map +1 -1
- package/dist/providers/ollama.js +1 -2
- package/dist/providers/ollama.js.map +1 -1
- package/dist/providers/openai-codex.d.ts.map +1 -1
- package/dist/providers/openai-codex.js +5 -1
- package/dist/providers/openai-codex.js.map +1 -1
- package/dist/providers/qwen-token-plan-individual.d.ts +3 -0
- package/dist/providers/qwen-token-plan-individual.d.ts.map +1 -0
- package/dist/providers/qwen-token-plan-individual.js +15 -0
- package/dist/providers/qwen-token-plan-individual.js.map +1 -0
- package/dist/providers/qwen-token-plan-individual.models.d.ts +4 -0
- package/dist/providers/qwen-token-plan-individual.models.d.ts.map +1 -0
- package/dist/providers/qwen-token-plan-individual.models.js +6 -0
- package/dist/providers/qwen-token-plan-individual.models.js.map +1 -0
- package/dist/providers/radius.d.ts.map +1 -1
- package/dist/providers/radius.js +36 -26
- package/dist/providers/radius.js.map +1 -1
- package/dist/providers/xai.d.ts.map +1 -1
- package/dist/providers/xai.js +1 -0
- package/dist/providers/xai.js.map +1 -1
- package/dist/tool-call-middleware/context-transformer.js.map +1 -1
- package/dist/tool-call-middleware/protocols/anthropic-xml/recovery-wrapper-state.d.ts.map +1 -1
- package/dist/tool-call-middleware/protocols/kimi-xtml/parse.js.map +1 -1
- package/dist/tool-call-middleware/recovery-content-lifecycle.d.ts.map +1 -1
- package/dist/tool-call-middleware/recovery-event-stream.d.ts.map +1 -1
- package/dist/tool-call-middleware/recovery-native-projection.d.ts.map +1 -1
- package/dist/tool-call-middleware/recovery-native-projection.js.map +1 -1
- package/dist/tool-call-middleware/recovery-stream-terminal.d.ts.map +1 -1
- package/dist/tool-call-middleware/recovery-stream-wrapper.d.ts.map +1 -1
- package/dist/tool-call-middleware/recovery-stream-wrapper.js +5 -0
- package/dist/tool-call-middleware/recovery-stream-wrapper.js.map +1 -1
- package/dist/tool-call-middleware/recovery-text-projection.d.ts.map +1 -1
- package/dist/tool-call-middleware/recovery-text-projection.js.map +1 -1
- package/dist/tool-call-middleware/stream-thinking-projection.d.ts.map +1 -1
- package/dist/tool-call-middleware/stream-wrapper-shared.d.ts.map +1 -1
- package/dist/tool-call-middleware/stream-wrapper-shared.js.map +1 -1
- package/dist/tool-call-middleware/stream-wrapper.js.map +1 -1
- package/dist/types.d.ts +94 -87
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/utils/abort.d.ts +8 -0
- package/dist/utils/abort.d.ts.map +1 -0
- package/dist/utils/abort.js +49 -0
- package/dist/utils/abort.js.map +1 -0
- package/dist/utils/deferred-tools.js.map +1 -1
- package/dist/utils/event-stream.d.ts.map +1 -1
- package/dist/utils/overflow.d.ts +14 -1
- package/dist/utils/overflow.d.ts.map +1 -1
- package/dist/utils/overflow.js +18 -1
- package/dist/utils/overflow.js.map +1 -1
- package/dist/utils/prompt-cache-ttl.d.ts +3 -1
- package/dist/utils/prompt-cache-ttl.d.ts.map +1 -1
- package/dist/utils/prompt-cache-ttl.js +2 -0
- package/dist/utils/prompt-cache-ttl.js.map +1 -1
- package/dist/utils/provider-retry.js.map +1 -1
- package/dist/utils/tool-schema-compat.d.ts.map +1 -1
- package/dist/utils/tool-schema-compat.js +1 -0
- package/dist/utils/tool-schema-compat.js.map +1 -1
- package/dist/utils/validation.d.ts.map +1 -1
- package/dist/utils/validation.js +6 -0
- package/dist/utils/validation.js.map +1 -1
- package/package.json +2 -1
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
function abortReason(signal) {
|
|
2
|
+
if (signal.reason !== undefined)
|
|
3
|
+
return signal.reason;
|
|
4
|
+
const error = new Error("The operation was aborted");
|
|
5
|
+
error.name = "AbortError";
|
|
6
|
+
return error;
|
|
7
|
+
}
|
|
8
|
+
/** Create an operation-local signal for public APIs whose signal is optional. */
|
|
9
|
+
export function operationSignal(signal) {
|
|
10
|
+
return signal ?? new AbortController().signal;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Stop waiting for an operation when its signal aborts while continuing to
|
|
14
|
+
* observe the abandoned promise so a later rejection is always handled.
|
|
15
|
+
*/
|
|
16
|
+
export function raceWithAbortSignal(operation, signal) {
|
|
17
|
+
if (signal.aborted) {
|
|
18
|
+
void operation.catch(() => { });
|
|
19
|
+
return Promise.reject(abortReason(signal));
|
|
20
|
+
}
|
|
21
|
+
return new Promise((resolve, reject) => {
|
|
22
|
+
let settled = false;
|
|
23
|
+
const cleanup = () => signal.removeEventListener("abort", onAbort);
|
|
24
|
+
const onAbort = () => {
|
|
25
|
+
if (settled)
|
|
26
|
+
return;
|
|
27
|
+
settled = true;
|
|
28
|
+
cleanup();
|
|
29
|
+
reject(abortReason(signal));
|
|
30
|
+
};
|
|
31
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
32
|
+
void operation.then((value) => {
|
|
33
|
+
if (settled)
|
|
34
|
+
return;
|
|
35
|
+
settled = true;
|
|
36
|
+
cleanup();
|
|
37
|
+
resolve(value);
|
|
38
|
+
}, (error) => {
|
|
39
|
+
if (settled)
|
|
40
|
+
return;
|
|
41
|
+
settled = true;
|
|
42
|
+
cleanup();
|
|
43
|
+
reject(error);
|
|
44
|
+
});
|
|
45
|
+
if (signal.aborted)
|
|
46
|
+
onAbort();
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
//# sourceMappingURL=abort.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"abort.js","sourceRoot":"","sources":["../../src/utils/abort.ts"],"names":[],"mappings":"AAAA,SAAS,WAAW,CAAC,MAAmB;IACvC,IAAI,MAAM,CAAC,MAAM,KAAK,SAAS;QAAE,OAAO,MAAM,CAAC,MAAM,CAAC;IACtD,MAAM,KAAK,GAAG,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAC;IACrD,KAAK,CAAC,IAAI,GAAG,YAAY,CAAC;IAC1B,OAAO,KAAK,CAAC;AACd,CAAC;AAED,iFAAiF;AACjF,MAAM,UAAU,eAAe,CAAC,MAAoB;IACnD,OAAO,MAAM,IAAI,IAAI,eAAe,EAAE,CAAC,MAAM,CAAC;AAC/C,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,mBAAmB,CAAI,SAAqB,EAAE,MAAmB;IAChF,IAAI,MAAM,CAAC,OAAO,EAAE,CAAC;QACpB,KAAK,SAAS,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;QAC/B,OAAO,OAAO,CAAC,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC;IAC5C,CAAC;IAED,OAAO,IAAI,OAAO,CAAI,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACzC,IAAI,OAAO,GAAG,KAAK,CAAC;QACpB,MAAM,OAAO,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACnE,MAAM,OAAO,GAAG,GAAG,EAAE;YACpB,IAAI,OAAO;gBAAE,OAAO;YACpB,OAAO,GAAG,IAAI,CAAC;YACf,OAAO,EAAE,CAAC;YACV,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC;QAC7B,CAAC,CAAC;QAEF,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;QAC1D,KAAK,SAAS,CAAC,IAAI,CAClB,CAAC,KAAK,EAAE,EAAE;YACT,IAAI,OAAO;gBAAE,OAAO;YACpB,OAAO,GAAG,IAAI,CAAC;YACf,OAAO,EAAE,CAAC;YACV,OAAO,CAAC,KAAK,CAAC,CAAC;QAChB,CAAC,EACD,CAAC,KAAc,EAAE,EAAE;YAClB,IAAI,OAAO;gBAAE,OAAO;YACpB,OAAO,GAAG,IAAI,CAAC;YACf,OAAO,EAAE,CAAC;YACV,MAAM,CAAC,KAAK,CAAC,CAAC;QACf,CAAC,CACD,CAAC;QACF,IAAI,MAAM,CAAC,OAAO;YAAE,OAAO,EAAE,CAAC;IAC/B,CAAC,CAAC,CAAC;AACJ,CAAC","sourcesContent":["function abortReason(signal: AbortSignal): unknown {\n\tif (signal.reason !== undefined) return signal.reason;\n\tconst error = new Error(\"The operation was aborted\");\n\terror.name = \"AbortError\";\n\treturn error;\n}\n\n/** Create an operation-local signal for public APIs whose signal is optional. */\nexport function operationSignal(signal?: AbortSignal): AbortSignal {\n\treturn signal ?? new AbortController().signal;\n}\n\n/**\n * Stop waiting for an operation when its signal aborts while continuing to\n * observe the abandoned promise so a later rejection is always handled.\n */\nexport function raceWithAbortSignal<T>(operation: Promise<T>, signal: AbortSignal): Promise<T> {\n\tif (signal.aborted) {\n\t\tvoid operation.catch(() => {});\n\t\treturn Promise.reject(abortReason(signal));\n\t}\n\n\treturn new Promise<T>((resolve, reject) => {\n\t\tlet settled = false;\n\t\tconst cleanup = () => signal.removeEventListener(\"abort\", onAbort);\n\t\tconst onAbort = () => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\treject(abortReason(signal));\n\t\t};\n\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\tvoid operation.then(\n\t\t\t(value) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tcleanup();\n\t\t\t\tresolve(value);\n\t\t\t},\n\t\t\t(error: unknown) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tcleanup();\n\t\t\t\treject(error);\n\t\t\t},\n\t\t);\n\t\tif (signal.aborted) onAbort();\n\t});\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"deferred-tools.js","sourceRoot":"","sources":["../../src/utils/deferred-tools.ts"],"names":[],"mappings":"AAIA,MAAM,gBAAgB,GAAuB,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC;AAE5D,yEAAyE;AACzE,MAAM,UAAU,kBAAkB,CACjC,OAAgB,EAChB,OAAgB,EAChB,
|
|
1
|
+
{"version":3,"file":"deferred-tools.js","sourceRoot":"","sources":["../../src/utils/deferred-tools.ts"],"names":[],"mappings":"AAIA,MAAM,gBAAgB,GAAuB,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC;AAE5D,yEAAyE;AACzE,MAAM,UAAU,kBAAkB,CACjC,OAAgB,EAChB,OAAgB,EAChB,gBAAoC,gBAAgB;IAEpD,MAAM,WAAW,GAAG,IAAI,GAAG,EAAgB,CAAC;IAC5C,KAAK,MAAM,IAAI,IAAI,OAAO,CAAC,KAAK,IAAI,EAAE;QAAE,WAAW,CAAC,GAAG,CAAC,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAC;IACxF,IAAI,CAAC,OAAO;QAAE,OAAO,EAAE,SAAS,EAAE,CAAC,GA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Tool } from \"../types.ts\";\n\ntype ToolNameNormalizer = (name: string) => string;\n\nconst identityToolName: ToolNameNormalizer = (name) => name;\n\n/** Split current tools into prefix and transcript-loaded definitions. */\nexport function splitDeferredTools(\n\tcontext: Context,\n\tenabled: boolean,\n\tnormalizeName: ToolNameNormalizer = identityToolName,\n): { immediate: Tool[]; deferred: Map<string, Tool> } {\n\tconst uniqueTools = new Map<string, Tool>();\n\tfor (const tool of context.tools ?? []) uniqueTools.set(normalizeName(tool.name), tool);\n\tif (!enabled) return { immediate: [...uniqueTools.values()], deferred: new Map() };\n\n\tconst deferredNames = new Set<string>();\n\tconst usedNames = new Set<string>();\n\tfor (const message of context.messages) {\n\t\tif (message.role === \"assistant\") {\n\t\t\tfor (const block of message.content) {\n\t\t\t\tif (block.type === \"toolCall\") usedNames.add(normalizeName(block.name));\n\t\t\t}\n\t\t} else if (message.role === \"toolResult\") {\n\t\t\tfor (const name of message.addedToolNames ?? []) {\n\t\t\t\tconst normalizedName = normalizeName(name);\n\t\t\t\tif (!usedNames.has(normalizedName)) deferredNames.add(normalizedName);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst immediate: Tool[] = [];\n\tconst deferred = new Map<string, Tool>();\n\tfor (const [name, tool] of uniqueTools) {\n\t\tif (deferredNames.has(name)) deferred.set(name, tool);\n\t\telse immediate.push(tool);\n\t}\n\treturn { immediate, deferred };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"event-stream.d.ts","sourceRoot":"","sources":["../../src/utils/event-stream.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAG3E,qBAAa,WAAW,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,CAAE,YAAW,aAAa,CAAC,CAAC,CAAC;;IAG7D,OAAO,CAAC,OAAO,CAAgG;IAC/G,OAAO,CAAC,IAAI,CAAS;IAGrB,OAAO,CAAC,kBAAkB,CAAa;IACvC,OAAO,CAAC,kBAAkB,CAAuB;IACjD,OAAO,CAAC,iBAAiB,CAA4B;IACrD,OAAO,CAAC,UAAU,CAAwB;IAC1C,OAAO,CAAC,aAAa,CAAkB;
|
|
1
|
+
{"version":3,"file":"event-stream.d.ts","sourceRoot":"","sources":["../../src/utils/event-stream.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAG3E,qBAAa,WAAW,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,CAAE,YAAW,aAAa,CAAC,CAAC,CAAC;;IAG7D,OAAO,CAAC,OAAO,CAAgG;IAC/G,OAAO,CAAC,IAAI,CAAS;IAGrB,OAAO,CAAC,kBAAkB,CAAa;IACvC,OAAO,CAAC,kBAAkB,CAAuB;IACjD,OAAO,CAAC,iBAAiB,CAA4B;IACrD,OAAO,CAAC,UAAU,CAAwB;IAC1C,OAAO,CAAC,aAAa,CAAkB;gBAE3B,UAAU,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,OAAO,EAAE,aAAa,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC;IAU7E,IAAI,KAAK,IAAI,CAAC,EAAE,CAEf;IAmBD,IAAI,CAAC,KAAK,EAAE,CAAC,GAAG,IAAI;IAiBpB,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,GAAG,IAAI;IAYrB,IAAI,CAAC,KAAK,EAAE,OAAO,GAAG,IAAI;IAY1B,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,aAAa,CAAC,CAAC,CAAC;IAiB1C,MAAM,IAAI,OAAO,CAAC,CAAC,CAAC;CAGpB;AAED,qBAAa,2BAA4B,SAAQ,WAAW,CAAC,qBAAqB,EAAE,gBAAgB,CAAC;;CAcpG;AAED,+EAA+E;AAC/E,wBAAgB,iCAAiC,IAAI,2BAA2B,CAE/E"}
|
package/dist/utils/overflow.d.ts
CHANGED
|
@@ -2,11 +2,13 @@ import type { AssistantMessage } from "../types.ts";
|
|
|
2
2
|
/**
|
|
3
3
|
* Check if an assistant message represents a context overflow error.
|
|
4
4
|
*
|
|
5
|
-
* This handles
|
|
5
|
+
* This handles three cases:
|
|
6
6
|
* 1. Error-based overflow: Most providers return stopReason "error" with a
|
|
7
7
|
* specific error message pattern.
|
|
8
8
|
* 2. Silent overflow: Some providers accept overflow requests and return
|
|
9
9
|
* successfully. For these, we check if usage.input exceeds the context window.
|
|
10
|
+
* 3. Length-stop overflow: Xiaomi MiMo can return "length" with zero output when
|
|
11
|
+
* the input fills the context window.
|
|
10
12
|
*
|
|
11
13
|
* ## Reliability by Provider
|
|
12
14
|
*
|
|
@@ -52,4 +54,15 @@ import type { AssistantMessage } from "../types.ts";
|
|
|
52
54
|
* @returns true if the message indicates a context overflow
|
|
53
55
|
*/
|
|
54
56
|
export declare function isContextOverflow(message: AssistantMessage, contextWindow?: number): boolean;
|
|
57
|
+
/**
|
|
58
|
+
* Check whether a length stop ended below the caller or model's intended output limit.
|
|
59
|
+
* Such responses may be caused by context pressure or provider-side truncation, so callers
|
|
60
|
+
* can make one bounded compact-and-retry attempt. `desiredMaxOutput` must be the original
|
|
61
|
+
* limit before any context-based clamping.
|
|
62
|
+
*/
|
|
63
|
+
export declare function isRecoverableLength(message: AssistantMessage, desiredMaxOutput: number): boolean;
|
|
64
|
+
/**
|
|
65
|
+
* Get the overflow patterns for testing purposes.
|
|
66
|
+
*/
|
|
67
|
+
export declare function getOverflowPatterns(): RegExp[];
|
|
55
68
|
//# sourceMappingURL=overflow.d.ts.map
|
|
@@ -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;AA+EpD
|
|
1
|
+
{"version":3,"file":"overflow.d.ts","sourceRoot":"","sources":["../../src/utils/overflow.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AA+EpD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqDG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,gBAAgB,EAAE,aAAa,CAAC,EAAE,MAAM,GAAG,OAAO,CA6B5F;AACD;;;;;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
|
@@ -76,11 +76,13 @@ const NON_OVERFLOW_PATTERNS = [
|
|
|
76
76
|
/**
|
|
77
77
|
* Check if an assistant message represents a context overflow error.
|
|
78
78
|
*
|
|
79
|
-
* This handles
|
|
79
|
+
* This handles three cases:
|
|
80
80
|
* 1. Error-based overflow: Most providers return stopReason "error" with a
|
|
81
81
|
* specific error message pattern.
|
|
82
82
|
* 2. Silent overflow: Some providers accept overflow requests and return
|
|
83
83
|
* successfully. For these, we check if usage.input exceeds the context window.
|
|
84
|
+
* 3. Length-stop overflow: Xiaomi MiMo can return "length" with zero output when
|
|
85
|
+
* the input fills the context window.
|
|
84
86
|
*
|
|
85
87
|
* ## Reliability by Provider
|
|
86
88
|
*
|
|
@@ -152,4 +154,19 @@ export function isContextOverflow(message, contextWindow) {
|
|
|
152
154
|
}
|
|
153
155
|
return false;
|
|
154
156
|
}
|
|
157
|
+
/**
|
|
158
|
+
* Check whether a length stop ended below the caller or model's intended output limit.
|
|
159
|
+
* Such responses may be caused by context pressure or provider-side truncation, so callers
|
|
160
|
+
* can make one bounded compact-and-retry attempt. `desiredMaxOutput` must be the original
|
|
161
|
+
* limit before any context-based clamping.
|
|
162
|
+
*/
|
|
163
|
+
export function isRecoverableLength(message, desiredMaxOutput) {
|
|
164
|
+
return message.stopReason === "length" && desiredMaxOutput > 0 && message.usage.output < desiredMaxOutput;
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Get the overflow patterns for testing purposes.
|
|
168
|
+
*/
|
|
169
|
+
export function getOverflowPatterns() {
|
|
170
|
+
return [...OVERFLOW_PATTERNS];
|
|
171
|
+
}
|
|
155
172
|
//# sourceMappingURL=overflow.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"overflow.js","sourceRoot":"","sources":["../../src/utils/overflow.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,MAAM,iBAAiB,GAAG;IACzB,qBAAqB,EAAE,2BAA2B;IAClD,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,iCAAiC;IACvF,kCAAkC,EAAE,8BAA8B;IAClE,gCAAgC,EAAE,mBAAmB;IACrD,kBAAkB,EAAE,mBAAmB;IACvC,uBAAuB,EAAE,mBAAmB;IAC5C,+CAA+C,EAAE,iCAAiC;CAClF,CAAC;AAEF;;;;;;;;GAQG;AACH,MAAM,qBAAqB,GAAG;IAC7B,2CAA2C,EAAE,oFAAoF;IACjI,aAAa,EAAE,wBAAwB;IACvC,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OAAO,KAAK,CAAC;AACd,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: Does NOT error, accepts overflow silently - handled 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 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/^4(?:00|13)\\s*(?:status code)?\\s*\\(no body\\)/i, // Cerebras: 400/413 with no body\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 two 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 *\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 *\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 && OVERFLOW_PATTERNS.some((p) => p.test(message.errorMessage!))) {\n\t\t\treturn true;\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"]}
|
|
1
|
+
{"version":3,"file":"overflow.js","sourceRoot":"","sources":["../../src/utils/overflow.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;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Content":["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: Does NOT error, accepts overflow silently - handled 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 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/^4(?:00|13)\\s*(?:status code)?\\s*\\(no body\\)/i, // Cerebras: 400/413 with no body\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 *\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 && OVERFLOW_PATTERNS.some((p) => p.test(message.errorMessage!))) {\n\t\t\treturn true;\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 * 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"]}
|
|
@@ -3,12 +3,14 @@ export declare const PROMPT_CACHE_TTL_SHORT_SECONDS = 300;
|
|
|
3
3
|
export declare const PROMPT_CACHE_TTL_LONG_SECONDS = 3600;
|
|
4
4
|
export declare function isAnthropicApiBaseUrl(baseUrl: string): boolean;
|
|
5
5
|
export declare function getAnthropicCompat(model: Model<"anthropic-messages">): Required<Omit<AnthropicMessagesCompat, "forceAdaptiveThinking">>;
|
|
6
|
-
export type ResolvedOpenAICompletionsCompat = Omit<Required<OpenAICompletionsCompat>, "cacheControlFormat" | "toolCallFormat" | "deferredToolsMode" | "toolSchemaFlavor" | "supportsPromptCacheKey"> & {
|
|
6
|
+
export type ResolvedOpenAICompletionsCompat = Omit<Required<OpenAICompletionsCompat>, "cacheControlFormat" | "toolCallFormat" | "deferredToolsMode" | "toolSchemaFlavor" | "supportsPromptCacheKey" | "chatTemplateArgs" | "supportsThinkingTokenBudget"> & {
|
|
7
7
|
cacheControlFormat?: OpenAICompletionsCompat["cacheControlFormat"];
|
|
8
8
|
supportsPromptCacheKey?: OpenAICompletionsCompat["supportsPromptCacheKey"];
|
|
9
9
|
toolCallFormat?: OpenAICompletionsCompat["toolCallFormat"];
|
|
10
10
|
deferredToolsMode?: OpenAICompletionsCompat["deferredToolsMode"];
|
|
11
11
|
toolSchemaFlavor?: OpenAICompletionsCompat["toolSchemaFlavor"];
|
|
12
|
+
chatTemplateArgs?: OpenAICompletionsCompat["chatTemplateArgs"];
|
|
13
|
+
supportsThinkingTokenBudget?: OpenAICompletionsCompat["supportsThinkingTokenBudget"];
|
|
12
14
|
};
|
|
13
15
|
/**
|
|
14
16
|
* Get resolved compatibility settings for a model.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prompt-cache-ttl.d.ts","sourceRoot":"","sources":["../../src/utils/prompt-cache-ttl.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,uBAAuB,EACvB,GAAG,EAEH,KAAK,EACL,uBAAuB,EACvB,WAAW,EACX,MAAM,aAAa,CAAC;AAGrB,eAAO,MAAM,8BAA8B,MAAM,CAAC;AAClD,eAAO,MAAM,6BAA6B,OAAO,CAAC;AAElD,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAM9D;AAkBD,wBAAgB,kBAAkB,CACjC,KAAK,EAAE,KAAK,CAAC,oBAAoB,CAAC,GAChC,QAAQ,CAAC,IAAI,CAAC,uBAAuB,EAAE,uBAAuB,CAAC,CAAC,CA6BlE;AAED,MAAM,MAAM,+BAA+B,GAAG,IAAI,CACjD,QAAQ,CAAC,uBAAuB,CAAC,
|
|
1
|
+
{"version":3,"file":"prompt-cache-ttl.d.ts","sourceRoot":"","sources":["../../src/utils/prompt-cache-ttl.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,uBAAuB,EACvB,GAAG,EAEH,KAAK,EACL,uBAAuB,EACvB,WAAW,EACX,MAAM,aAAa,CAAC;AAGrB,eAAO,MAAM,8BAA8B,MAAM,CAAC;AAClD,eAAO,MAAM,6BAA6B,OAAO,CAAC;AAElD,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAM9D;AAkBD,wBAAgB,kBAAkB,CACjC,KAAK,EAAE,KAAK,CAAC,oBAAoB,CAAC,GAChC,QAAQ,CAAC,IAAI,CAAC,uBAAuB,EAAE,uBAAuB,CAAC,CAAC,CA6BlE;AAED,MAAM,MAAM,+BAA+B,GAAG,IAAI,CACjD,QAAQ,CAAC,uBAAuB,CAAC,EAC/B,oBAAoB,GACpB,gBAAgB,GAChB,mBAAmB,GACnB,kBAAkB,GAClB,wBAAwB,GACxB,kBAAkB,GAClB,6BAA6B,CAC/B,GAAG;IACH,kBAAkB,CAAC,EAAE,uBAAuB,CAAC,oBAAoB,CAAC,CAAC;IACnE,sBAAsB,CAAC,EAAE,uBAAuB,CAAC,wBAAwB,CAAC,CAAC;IAC3E,cAAc,CAAC,EAAE,uBAAuB,CAAC,gBAAgB,CAAC,CAAC;IAC3D,iBAAiB,CAAC,EAAE,uBAAuB,CAAC,mBAAmB,CAAC,CAAC;IACjE,gBAAgB,CAAC,EAAE,uBAAuB,CAAC,kBAAkB,CAAC,CAAC;IAC/D,gBAAgB,CAAC,EAAE,uBAAuB,CAAC,kBAAkB,CAAC,CAAC;IAC/D,2BAA2B,CAAC,EAAE,uBAAuB,CAAC,6BAA6B,CAAC,CAAC;CACrF,CAAC;AA6GF;;;GAGG;AACH,wBAAgB,0BAA0B,CAAC,KAAK,EAAE,KAAK,CAAC,oBAAoB,CAAC,GAAG,+BAA+B,CAqC9G;AAED,wBAAgB,8BAA8B,CAAC,OAAO,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAM5F;AAED,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,KAAK,CAAC,yBAAyB,CAAC,GAAG,OAAO,CAKxF;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,KAAK,CAAC,yBAAyB,CAAC,EAAE,GAAG,CAAC,EAAE,WAAW,GAAG,OAAO,CAmBzG;AAiDD,wBAAgB,4BAA4B,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,GAAG,CAAC,EAAE,WAAW,GAAG,MAAM,GAAG,SAAS,CA4CrG"}
|
|
@@ -167,7 +167,9 @@ export function getOpenAICompletionsCompat(model) {
|
|
|
167
167
|
openRouterRouting: model.compat.openRouterRouting ?? detected.openRouterRouting,
|
|
168
168
|
vercelGatewayRouting: model.compat.vercelGatewayRouting ?? detected.vercelGatewayRouting,
|
|
169
169
|
chatTemplateKwargs: model.compat.chatTemplateKwargs ?? detected.chatTemplateKwargs,
|
|
170
|
+
chatTemplateArgs: model.compat.chatTemplateArgs ?? detected.chatTemplateArgs,
|
|
170
171
|
zaiToolStream: model.compat.zaiToolStream ?? detected.zaiToolStream,
|
|
172
|
+
supportsThinkingTokenBudget: model.compat.supportsThinkingTokenBudget ?? detected.supportsThinkingTokenBudget,
|
|
171
173
|
supportsStrictMode: model.compat.supportsStrictMode ?? detected.supportsStrictMode,
|
|
172
174
|
toolSchemaFlavor: model.compat.toolSchemaFlavor ?? detected.toolSchemaFlavor,
|
|
173
175
|
toolCallFormat: model.compat.toolCallFormat ?? detected.toolCallFormat,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prompt-cache-ttl.js","sourceRoot":"","sources":["../../src/utils/prompt-cache-ttl.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAExD,MAAM,CAAC,MAAM,8BAA8B,GAAG,GAAG,CAAC;AAClD,MAAM,CAAC,MAAM,6BAA6B,GAAG,IAAI,CAAC;AAElD,MAAM,UAAU,qBAAqB,CAAC,OAAe;IACpD,IAAI,CAAC;QACJ,OAAO,IAAI,GAAG,CAAC,OAAO,CAAC,CAAC,QAAQ,KAAK,mBAAmB,CAAC;IAC1D,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,KAAK,CAAC;IACd,CAAC;AACF,CAAC;AAED,MAAM,+BAA+B,GAAG,kCAAkC,CAAC;AAE3E;;;;GAIG;AACH,SAAS,6BAA6B,CAAC,KAAkC;IACxE,IAAI,KAAK,CAAC,QAAQ,KAAK,WAAW,IAAI,KAAK,CAAC,EAAE,CAAC,QAAQ,CAAC,OAAO,CAAC;QAAE,OAAO,KAAK,CAAC;IAC/E,MAAM,OAAO,GAAG,KAAK,CAAC,EAAE,CAAC,KAAK,CAAC,uDAAuD,CAAC,CAAC;IACxF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AC;QACnC,CAAC;QACD,KAAK,oBAAoB,EAAE,CAAC;YAC3B,MAAM,gBAAgB,GAAG,KAAoC,CAAC;YAC9D,MAAM,SAAS,GAAG,sCAAsC,CAAC,gBAAgB,CAAC,cAAc,EAAE,GAAG,CAAC,CAAC;YAC/F,IAAI,SAAS,KAAK,MAAM;gBAAE,OAAO,SAAS,CAAC;YAC3C,MAAM,MAAM,GAAG,0BAA0B,CAAC,gBAAgB,CAAC,CAAC;YAC5D,IAAI,MAAM,CAAC,kBAAkB,KAAK,WAAW,EAAE,CAAC;gBAC/C,OAAO,SAAS,KAAK,MAAM,IAAI,MAAM,CAAC,0BAA0B;oBAC/D,CAAC,CAAC,6BAA6B;oBAC/B,CAAC,CAAC,8BAA8B,CAAC;YACnC,CAAC;YACD,OAAO,8BAA8B,CAAC;QACvC,CAAC;QACD,KAAK,kBAAkB,CAAC;QACxB,KAAK,wBAAwB,CAAC;QAC9B,KAAK,wBAAwB,EAAE,CAAC;YAC/B,MAAM,SAAS,GAAG,oCAAoC,CAAC,KAAK,CAAC,cAAc,EAAE,GAAG,CAAC,CAAC;YAClF,OAAO,SAAS,KAAK,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,8BAA8B,CAAC;QAC1E,CAAC;QACD;YACC,OAAO,SAAS,CAAC;IACnB,CAAC;AACF,CAAC","sourcesContent":["import type {\n\tAnthropicMessagesCompat,\n\tApi,\n\tCacheRetention,\n\tModel,\n\tOpenAICompletionsCompat,\n\tProviderEnv,\n} from \"../types.ts\";\nimport { getProviderEnvValue } from \"./provider-env.ts\";\n\nexport const PROMPT_CACHE_TTL_SHORT_SECONDS = 300;\nexport const PROMPT_CACHE_TTL_LONG_SECONDS = 3600;\n\nexport function isAnthropicApiBaseUrl(baseUrl: string): boolean {\n\ttry {\n\t\treturn new URL(baseUrl).hostname === \"api.anthropic.com\";\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nconst CLAUDE_FABLE_OR_MYTHOS_MODEL_ID = /^claude-(?:fable|mythos)(?:-|$)/i;\n\n/**\n * Default for `supportsToolReferences`: first-party Anthropic models except\n * Haiku (rejects client-side tool_reference blocks) and models that predate\n * tool search (Claude 3.x, Opus/Sonnet 4.0, Opus 4.1).\n */\nfunction defaultSupportsToolReferences(model: Model<\"anthropic-messages\">): boolean {\n\tif (model.provider !== \"anthropic\" || model.id.includes(\"haiku\")) return false;\n\tconst version = model.id.match(/^claude-(?:opus|sonnet|fable)-(\\d+)(?:-(\\d+))?(?:-|$)/);\n\tif (!version) return false;\n\tconst major = Number(version[1]);\n\tconst minor = version[2] && version[2].length < 8 ? Number(version[2]) : 0;\n\treturn major > 4 || (major === 4 && minor >= 5);\n}\n\nexport function getAnthropicCompat(\n\tmodel: Model<\"anthropic-messages\">,\n): Required<Omit<AnthropicMessagesCompat, \"forceAdaptiveThinking\">> {\n\t// Auto-detect session affinity and cache control support from provider\n\tconst isFireworks = model.provider === \"fireworks\";\n\tconst isCloudflareAiGatewayAnthropic =\n\t\tmodel.provider === \"cloudflare-ai-gateway\" && model.baseUrl.includes(\"anthropic\");\n\tconst isXiaomi = model.provider === \"xiaomi\" || model.provider.startsWith(\"xiaomi-token-plan-\");\n\treturn {\n\t\tsupportsEagerToolInputStreaming: model.compat?.supportsEagerToolInputStreaming ?? !isFireworks,\n\t\tsupportsLongCacheRetention: model.compat?.supportsLongCacheRetention ?? !isFireworks,\n\t\tsendSessionAffinityHeaders:\n\t\t\tmodel.compat?.sendSessionAffinityHeaders ?? !!(isFireworks || isCloudflareAiGatewayAnthropic),\n\t\tsupportsCacheControlOnTools: model.compat?.supportsCacheControlOnTools ?? !isFireworks,\n\t\tsupportsDisabledThinking: model.compat?.supportsDisabledThinking ?? !isXiaomi,\n\t\tsupportsTemperature: model.compat?.supportsTemperature ?? true,\n\t\tsupportsToolChoice: model.compat?.supportsToolChoice ?? true,\n\t\tsupportsForcedToolChoice:\n\t\t\tmodel.compat?.supportsForcedToolChoice ?? !CLAUDE_FABLE_OR_MYTHOS_MODEL_ID.test(model.id),\n\t\tallowEmptySignature: model.compat?.allowEmptySignature ?? false,\n\t\tunsignedThinkingReplay:\n\t\t\tmodel.compat?.unsignedThinkingReplay ?? (model.compat?.allowEmptySignature ? \"empty-signature\" : \"text\"),\n\t\tsupportsStrictTools: model.compat?.supportsStrictTools ?? false,\n\t\tsupportsToolReferences: model.compat?.supportsToolReferences ?? defaultSupportsToolReferences(model),\n\t\t// Default: first-party Anthropic only. Anthropic-compatible providers\n\t\t// (kimi-coding, fireworks, copilot, gateways) may execute the server-side\n\t\t// search but reject the replayed server_tool_use / web_search_tool_result\n\t\t// blocks on the next request (kimi-coding 400s with `tool_call_id is not\n\t\t// found`).\n\t\tsupportsWebSearch: model.compat?.supportsWebSearch ?? isAnthropicApiBaseUrl(model.baseUrl),\n\t};\n}\n\nexport type ResolvedOpenAICompletionsCompat = Omit<\n\tRequired<OpenAICompletionsCompat>,\n\t\"cacheControlFormat\" | \"toolCallFormat\" | \"deferredToolsMode\" | \"toolSchemaFlavor\" | \"supportsPromptCacheKey\"\n> & {\n\tcacheControlFormat?: OpenAICompletionsCompat[\"cacheControlFormat\"];\n\tsupportsPromptCacheKey?: OpenAICompletionsCompat[\"supportsPromptCacheKey\"];\n\ttoolCallFormat?: OpenAICompletionsCompat[\"toolCallFormat\"];\n\tdeferredToolsMode?: OpenAICompletionsCompat[\"deferredToolsMode\"];\n\ttoolSchemaFlavor?: OpenAICompletionsCompat[\"toolSchemaFlavor\"];\n};\n\n/**\n * Detect compatibility settings from provider and baseUrl for known providers.\n * Provider takes precedence over URL-based detection since it's explicitly configured.\n * Returns a fully resolved OpenAICompletionsCompat object with all fields set.\n */\nfunction detectOpenAICompletionsCompat(model: Model<\"openai-completions\">): ResolvedOpenAICompletionsCompat {\n\tconst provider = model.provider;\n\tconst baseUrl = model.baseUrl;\n\n\tconst isZai =\n\t\tprovider === \"zai\" ||\n\t\tprovider === \"zai-coding-cn\" ||\n\t\tbaseUrl.includes(\"api.z.ai\") ||\n\t\tbaseUrl.includes(\"open.bigmodel.cn\");\n\tconst isTogether =\n\t\tprovider === \"together\" || baseUrl.includes(\"api.together.ai\") || baseUrl.includes(\"api.together.xyz\");\n\tconst isMoonshot = provider === \"moonshotai\" || provider === \"moonshotai-cn\" || baseUrl.includes(\"api.moonshot.\");\n\tconst isOpenRouter = provider === \"openrouter\" || baseUrl.includes(\"openrouter.ai\");\n\tconst isCloudflareWorkersAI = provider === \"cloudflare-workers-ai\" || baseUrl.includes(\"api.cloudflare.com\");\n\tconst isCloudflareAiGateway = provider === \"cloudflare-ai-gateway\" || baseUrl.includes(\"gateway.ai.cloudflare.com\");\n\tconst isNvidia = provider === \"nvidia\" || baseUrl.includes(\"integrate.api.nvidia.com\");\n\tconst isAntLing = provider === \"ant-ling\" || baseUrl.includes(\"api.ant-ling.com\");\n\n\tconst isNonStandard =\n\t\tisNvidia ||\n\t\tprovider === \"cerebras\" ||\n\t\tbaseUrl.includes(\"cerebras.ai\") ||\n\t\tprovider === \"xai\" ||\n\t\tbaseUrl.includes(\"api.x.ai\") ||\n\t\tisTogether ||\n\t\tbaseUrl.includes(\"chutes.ai\") ||\n\t\tbaseUrl.includes(\"deepseek.com\") ||\n\t\tisZai ||\n\t\tisMoonshot ||\n\t\tprovider === \"opencode\" ||\n\t\tbaseUrl.includes(\"opencode.ai\") ||\n\t\tisCloudflareWorkersAI ||\n\t\tisCloudflareAiGateway ||\n\t\tisAntLing;\n\n\tconst useMaxTokens =\n\t\tbaseUrl.includes(\"chutes.ai\") ||\n\t\tisMoonshot ||\n\t\tisCloudflareAiGateway ||\n\t\tisTogether ||\n\t\tisNvidia ||\n\t\tisAntLing ||\n\t\tisZai;\n\n\tconst isGrok = provider === \"xai\" || baseUrl.includes(\"api.x.ai\");\n\tconst isDeepSeek = provider === \"deepseek\" || baseUrl.includes(\"deepseek.com\");\n\tconst isOpenRouterDeveloperRoleModel =\n\t\tisOpenRouter && (model.id.startsWith(\"anthropic/\") || model.id.startsWith(\"openai/\"));\n\tconst openRouterCacheControlPrefixes = [\"anthropic/\", \"qwen/\", \"google/\"];\n\tconst cacheControlModelId = model.id.startsWith(\"~\") ? model.id.slice(1) : model.id;\n\tconst supportsOpenRouterCacheControl = openRouterCacheControlPrefixes.some((prefix) =>\n\t\tcacheControlModelId.startsWith(prefix),\n\t);\n\tconst cacheControlFormat = provider === \"openrouter\" && supportsOpenRouterCacheControl ? \"anthropic\" : undefined;\n\n\treturn {\n\t\tsupportsStore: !isNonStandard,\n\t\tsupportsDeveloperRole: isOpenRouterDeveloperRoleModel || (!isNonStandard && !isOpenRouter),\n\t\tsupportsReasoningEffort:\n\t\t\t!isGrok && !isZai && !isMoonshot && !isTogether && !isCloudflareAiGateway && !isNvidia && !isAntLing,\n\t\tsupportsUsageInStreaming: true,\n\t\tsupportsFinishReason: true,\n\t\tmaxTokensField: useMaxTokens ? \"max_tokens\" : \"max_completion_tokens\",\n\t\trequiresToolResultName: false,\n\t\trequiresAssistantAfterToolResult: false,\n\t\trequiresThinkingAsText: false,\n\t\trequiresReasoningContentOnAssistantMessages: isDeepSeek,\n\t\tthinkingFormat: isDeepSeek\n\t\t\t? \"deepseek\"\n\t\t\t: isZai\n\t\t\t\t? \"zai\"\n\t\t\t\t: isTogether\n\t\t\t\t\t? \"together\"\n\t\t\t\t\t: isAntLing\n\t\t\t\t\t\t? \"ant-ling\"\n\t\t\t\t\t\t: isOpenRouter\n\t\t\t\t\t\t\t? \"openrouter\"\n\t\t\t\t\t\t\t: \"openai\",\n\t\topenRouterRouting: {},\n\t\tvercelGatewayRouting: {},\n\t\tchatTemplateKwargs: {},\n\t\tzaiToolStream: false,\n\t\tsupportsStrictMode: !isMoonshot && !isTogether && !isCloudflareAiGateway && !isNvidia,\n\t\ttoolSchemaFlavor: isMoonshot ? \"moonshot-mfjs\" : undefined,\n\t\tsupportsDisabledThinking: true,\n\t\ttoolCallFormat: undefined,\n\t\tsupportsOpenAIGrammarTools: false,\n\t\tcacheControlFormat,\n\t\tsendSessionAffinityHeaders: isOpenRouter,\n\t\tdeferredToolsMode: undefined,\n\t\tsessionAffinityFormat: isOpenRouter ? \"openrouter\" : \"openai\",\n\t\tsupportsPromptCacheKey: isMoonshot || baseUrl.includes(\"api.openai.com\"),\n\t\tsupportsLongCacheRetention: !(\n\t\t\tisTogether ||\n\t\t\tisCloudflareWorkersAI ||\n\t\t\tisCloudflareAiGateway ||\n\t\t\tisNvidia ||\n\t\t\tisAntLing\n\t\t),\n\t};\n}\n\n/**\n * Get resolved compatibility settings for a model.\n * Auto-detects from provider/URL then overrides with explicit model.compat.\n */\nexport function getOpenAICompletionsCompat(model: Model<\"openai-completions\">): ResolvedOpenAICompletionsCompat {\n\tconst detected = detectOpenAICompletionsCompat(model);\n\tif (!model.compat) return detected;\n\n\treturn {\n\t\tsupportsStore: model.compat.supportsStore ?? detected.supportsStore,\n\t\tsupportsDeveloperRole: model.compat.supportsDeveloperRole ?? detected.supportsDeveloperRole,\n\t\tsupportsReasoningEffort: model.compat.supportsReasoningEffort ?? detected.supportsReasoningEffort,\n\t\tsupportsUsageInStreaming: model.compat.supportsUsageInStreaming ?? detected.supportsUsageInStreaming,\n\t\tsupportsFinishReason: model.compat.supportsFinishReason ?? detected.supportsFinishReason,\n\t\tmaxTokensField: model.compat.maxTokensField ?? detected.maxTokensField,\n\t\trequiresToolResultName: model.compat.requiresToolResultName ?? detected.requiresToolResultName,\n\t\trequiresAssistantAfterToolResult:\n\t\t\tmodel.compat.requiresAssistantAfterToolResult ?? detected.requiresAssistantAfterToolResult,\n\t\trequiresThinkingAsText: model.compat.requiresThinkingAsText ?? detected.requiresThinkingAsText,\n\t\trequiresReasoningContentOnAssistantMessages:\n\t\t\tmodel.compat.requiresReasoningContentOnAssistantMessages ??\n\t\t\tdetected.requiresReasoningContentOnAssistantMessages,\n\t\tthinkingFormat: model.compat.thinkingFormat ?? detected.thinkingFormat,\n\t\tsupportsDisabledThinking: model.compat.supportsDisabledThinking ?? detected.supportsDisabledThinking,\n\t\topenRouterRouting: model.compat.openRouterRouting ?? detected.openRouterRouting,\n\t\tvercelGatewayRouting: model.compat.vercelGatewayRouting ?? detected.vercelGatewayRouting,\n\t\tchatTemplateKwargs: model.compat.chatTemplateKwargs ?? detected.chatTemplateKwargs,\n\t\tzaiToolStream: model.compat.zaiToolStream ?? detected.zaiToolStream,\n\t\tsupportsStrictMode: model.compat.supportsStrictMode ?? detected.supportsStrictMode,\n\t\ttoolSchemaFlavor: model.compat.toolSchemaFlavor ?? detected.toolSchemaFlavor,\n\t\ttoolCallFormat: model.compat.toolCallFormat ?? detected.toolCallFormat,\n\t\tsupportsOpenAIGrammarTools: model.compat.supportsOpenAIGrammarTools ?? detected.supportsOpenAIGrammarTools,\n\t\tcacheControlFormat: model.compat.cacheControlFormat ?? detected.cacheControlFormat,\n\t\tsendSessionAffinityHeaders: model.compat.sendSessionAffinityHeaders ?? detected.sendSessionAffinityHeaders,\n\t\tdeferredToolsMode: model.compat.deferredToolsMode ?? detected.deferredToolsMode,\n\t\tsessionAffinityFormat: model.compat.sessionAffinityFormat ?? detected.sessionAffinityFormat,\n\t\tsupportsPromptCacheKey: model.compat.supportsPromptCacheKey ?? detected.supportsPromptCacheKey,\n\t\tsupportsLongCacheRetention: model.compat.supportsLongCacheRetention ?? detected.supportsLongCacheRetention,\n\t};\n}\n\nexport function getBedrockModelMatchCandidates(modelId: string, modelName?: string): string[] {\n\tconst values = modelName ? [modelId, modelName] : [modelId];\n\treturn values.flatMap((value) => {\n\t\tconst lower = value.toLowerCase();\n\t\treturn [lower, lower.replace(/[\\s_.:]+/g, \"-\")];\n\t});\n}\n\nexport function supportsOneHourCacheTtl(model: Model<\"bedrock-converse-stream\">): boolean {\n\tconst candidates = getBedrockModelMatchCandidates(model.id, model.name);\n\treturn candidates.some((candidate) =>\n\t\t[\"opus-4-5\", \"sonnet-4-5\", \"haiku-4-5\"].some((modelVersion) => candidate.includes(modelVersion)),\n\t);\n}\n\n/**\n * Check if the model supports prompt caching.\n * Supported: Claude 3.5 Haiku, Claude 3.7 Sonnet, Claude 4.x models, Claude 5 models\n *\n * For base models and system-defined inference profiles the model ID / ARN\n * contains the model name, so we can decide locally.\n *\n * For application inference profiles (whose ARNs don't contain the model name),\n * also checks model.name which is user-controlled via models.json or registerProvider.\n * As a last resort, set AWS_BEDROCK_FORCE_CACHE=1 to enable cache points.\n * Amazon Nova models have automatic caching and don't need explicit cache points.\n */\nexport function supportsPromptCaching(model: Model<\"bedrock-converse-stream\">, env?: ProviderEnv): boolean {\n\tconst candidates = getBedrockModelMatchCandidates(model.id, model.name);\n\n\tconst hasClaudeRef = candidates.some((s) => s.includes(\"claude\"));\n\tif (!hasClaudeRef) {\n\t\t// Application inference profiles don't contain the model name in the ARN.\n\t\t// Allow users to force cache points via environment variable.\n\t\tif (getProviderEnvValue(\"AWS_BEDROCK_FORCE_CACHE\", env) === \"1\") return true;\n\t\treturn false;\n\t}\n\t// Claude 5 models (fable-5, opus-5, sonnet-5)\n\tif (candidates.some((s) => s.includes(\"fable-5\") || s.includes(\"opus-5\") || s.includes(\"sonnet-5\"))) return true;\n\t// Claude 4.x models (opus-4, sonnet-4, haiku-4)\n\tif (candidates.some((s) => s.includes(\"-4-\"))) return true;\n\t// Claude 3.7 Sonnet\n\tif (candidates.some((s) => s.includes(\"claude-3-7-sonnet\"))) return true;\n\t// Claude 3.5 Haiku\n\tif (candidates.some((s) => s.includes(\"claude-3-5-haiku\"))) return true;\n\treturn false;\n}\n\nfunction resolveAnthropicCacheRetention(\n\tcacheRetention?: CacheRetention,\n\tenv?: ProviderEnv,\n\tfallback: CacheRetention = \"short\",\n): CacheRetention {\n\tif (cacheRetention) {\n\t\treturn cacheRetention;\n\t}\n\tif (getProviderEnvValue(\"PI_CACHE_RETENTION\", env) === \"long\") {\n\t\treturn \"long\";\n\t}\n\tif (typeof process !== \"undefined\" && process.env.PI_CACHE_RETENTION !== undefined) {\n\t\treturn \"short\";\n\t}\n\treturn fallback;\n}\n\nfunction resolveOpenAICompletionsCacheRetention(cacheRetention?: CacheRetention, env?: ProviderEnv): CacheRetention {\n\tif (cacheRetention) {\n\t\treturn cacheRetention;\n\t}\n\tif (getProviderEnvValue(\"PI_CACHE_RETENTION\", env) === \"long\") {\n\t\treturn \"long\";\n\t}\n\treturn \"short\";\n}\n\nfunction resolveBedrockCacheRetention(cacheRetention?: CacheRetention, env?: ProviderEnv): CacheRetention {\n\tif (cacheRetention) {\n\t\treturn cacheRetention;\n\t}\n\tif (getProviderEnvValue(\"PI_CACHE_RETENTION\", env) === \"long\") {\n\t\treturn \"long\";\n\t}\n\treturn \"short\";\n}\n\nfunction resolveOpenAIResponsesCacheRetention(cacheRetention?: CacheRetention, env?: ProviderEnv): CacheRetention {\n\tif (cacheRetention) {\n\t\treturn cacheRetention;\n\t}\n\tif (getProviderEnvValue(\"PI_CACHE_RETENTION\", env) === \"long\") {\n\t\treturn \"long\";\n\t}\n\treturn \"short\";\n}\n\nexport function resolvePromptCacheTtlSeconds(model: Model<Api>, env?: ProviderEnv): number | undefined {\n\tswitch (model.api) {\n\t\tcase \"claude-sdk-oauth\":\n\t\t\t// The Claude SDK owns prompt caching for this lane and uses Anthropic's default 5m TTL.\n\t\t\treturn PROMPT_CACHE_TTL_SHORT_SECONDS;\n\t\tcase \"anthropic-messages\": {\n\t\t\tconst anthropicModel = model as Model<\"anthropic-messages\">;\n\t\t\tconst retention = resolveAnthropicCacheRetention(anthropicModel.cacheRetention, env, \"short\");\n\t\t\tif (retention === \"none\") return undefined;\n\t\t\treturn retention === \"long\" &&\n\t\t\t\tisAnthropicApiBaseUrl(anthropicModel.baseUrl) &&\n\t\t\t\tgetAnthropicCompat(anthropicModel).supportsLongCacheRetention\n\t\t\t\t? PROMPT_CACHE_TTL_LONG_SECONDS\n\t\t\t\t: PROMPT_CACHE_TTL_SHORT_SECONDS;\n\t\t}\n\t\tcase \"bedrock-converse-stream\": {\n\t\t\tconst bedrockModel = model as Model<\"bedrock-converse-stream\">;\n\t\t\tconst retention = resolveBedrockCacheRetention(bedrockModel.cacheRetention, env);\n\t\t\tif (retention === \"none\" || !supportsPromptCaching(bedrockModel, env)) return undefined;\n\t\t\treturn retention === \"long\" && supportsOneHourCacheTtl(bedrockModel)\n\t\t\t\t? PROMPT_CACHE_TTL_LONG_SECONDS\n\t\t\t\t: PROMPT_CACHE_TTL_SHORT_SECONDS;\n\t\t}\n\t\tcase \"openai-completions\": {\n\t\t\tconst completionsModel = model as Model<\"openai-completions\">;\n\t\t\tconst retention = resolveOpenAICompletionsCacheRetention(completionsModel.cacheRetention, env);\n\t\t\tif (retention === \"none\") return undefined;\n\t\t\tconst compat = getOpenAICompletionsCompat(completionsModel);\n\t\t\tif (compat.cacheControlFormat === \"anthropic\") {\n\t\t\t\treturn retention === \"long\" && compat.supportsLongCacheRetention\n\t\t\t\t\t? PROMPT_CACHE_TTL_LONG_SECONDS\n\t\t\t\t\t: PROMPT_CACHE_TTL_SHORT_SECONDS;\n\t\t\t}\n\t\t\treturn PROMPT_CACHE_TTL_SHORT_SECONDS;\n\t\t}\n\t\tcase \"openai-responses\":\n\t\tcase \"openai-codex-responses\":\n\t\tcase \"azure-openai-responses\": {\n\t\t\tconst retention = resolveOpenAIResponsesCacheRetention(model.cacheRetention, env);\n\t\t\treturn retention === \"none\" ? undefined : PROMPT_CACHE_TTL_SHORT_SECONDS;\n\t\t}\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"prompt-cache-ttl.js","sourceRoot":"","sources":["../../src/utils/prompt-cache-ttl.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAExD,MAAM,CAAC,MAAM,8BAA8B,GAAG,GAAG,CAAC;AAClD,MAAM,CAAC,MAAM,6BAA6B,GAAG,IAAI,CAAC;AAElD,MAAM,UAAU,qBAAqB,CAAC,OAAe;IACpD,IAAI,CAAC;QACJ,OAAO,IAAI,GAAG,CAAC,OAAO,CAAC,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,KAAK,CAAC,cAAc,EAAE,GAAG,CAAC,CAAC;YAClF,OAAO,SAAS,KAAK,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,8BAA8B,CAAC;QAC1E,CAAC;QACD;YACC,OAAO,SAAS,CAAC;IACnB,CAAC;AACF,CAAC","sourcesContent":["import type {\n\tAnthropicMessagesCompat,\n\tApi,\n\tCacheRetention,\n\tModel,\n\tOpenAICompletionsCompat,\n\tProviderEnv,\n} from \"../types.ts\";\nimport { getProviderEnvValue } from \"./provider-env.ts\";\n\nexport const PROMPT_CACHE_TTL_SHORT_SECONDS = 300;\nexport const PROMPT_CACHE_TTL_LONG_SECONDS = 3600;\n\nexport function isAnthropicApiBaseUrl(baseUrl: string): boolean {\n\ttry {\n\t\treturn new URL(baseUrl).hostname === \"api.anthropic.com\";\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nconst CLAUDE_FABLE_OR_MYTHOS_MODEL_ID = /^claude-(?:fable|mythos)(?:-|$)/i;\n\n/**\n * Default for `supportsToolReferences`: first-party Anthropic models except\n * Haiku (rejects client-side tool_reference blocks) and models that predate\n * tool search (Claude 3.x, Opus/Sonnet 4.0, Opus 4.1).\n */\nfunction defaultSupportsToolReferences(model: Model<\"anthropic-messages\">): boolean {\n\tif (model.provider !== \"anthropic\" || model.id.includes(\"haiku\")) return false;\n\tconst version = model.id.match(/^claude-(?:opus|sonnet|fable)-(\\d+)(?:-(\\d+))?(?:-|$)/);\n\tif (!version) return false;\n\tconst major = Number(version[1]);\n\tconst minor = version[2] && version[2].length < 8 ? Number(version[2]) : 0;\n\treturn major > 4 || (major === 4 && minor >= 5);\n}\n\nexport function getAnthropicCompat(\n\tmodel: Model<\"anthropic-messages\">,\n): Required<Omit<AnthropicMessagesCompat, \"forceAdaptiveThinking\">> {\n\t// Auto-detect session affinity and cache control support from provider\n\tconst isFireworks = model.provider === \"fireworks\";\n\tconst isCloudflareAiGatewayAnthropic =\n\t\tmodel.provider === \"cloudflare-ai-gateway\" && model.baseUrl.includes(\"anthropic\");\n\tconst isXiaomi = model.provider === \"xiaomi\" || model.provider.startsWith(\"xiaomi-token-plan-\");\n\treturn {\n\t\tsupportsEagerToolInputStreaming: model.compat?.supportsEagerToolInputStreaming ?? !isFireworks,\n\t\tsupportsLongCacheRetention: model.compat?.supportsLongCacheRetention ?? !isFireworks,\n\t\tsendSessionAffinityHeaders:\n\t\t\tmodel.compat?.sendSessionAffinityHeaders ?? !!(isFireworks || isCloudflareAiGatewayAnthropic),\n\t\tsupportsCacheControlOnTools: model.compat?.supportsCacheControlOnTools ?? !isFireworks,\n\t\tsupportsDisabledThinking: model.compat?.supportsDisabledThinking ?? !isXiaomi,\n\t\tsupportsTemperature: model.compat?.supportsTemperature ?? true,\n\t\tsupportsToolChoice: model.compat?.supportsToolChoice ?? true,\n\t\tsupportsForcedToolChoice:\n\t\t\tmodel.compat?.supportsForcedToolChoice ?? !CLAUDE_FABLE_OR_MYTHOS_MODEL_ID.test(model.id),\n\t\tallowEmptySignature: model.compat?.allowEmptySignature ?? false,\n\t\tunsignedThinkingReplay:\n\t\t\tmodel.compat?.unsignedThinkingReplay ?? (model.compat?.allowEmptySignature ? \"empty-signature\" : \"text\"),\n\t\tsupportsStrictTools: model.compat?.supportsStrictTools ?? false,\n\t\tsupportsToolReferences: model.compat?.supportsToolReferences ?? defaultSupportsToolReferences(model),\n\t\t// Default: first-party Anthropic only. Anthropic-compatible providers\n\t\t// (kimi-coding, fireworks, copilot, gateways) may execute the server-side\n\t\t// search but reject the replayed server_tool_use / web_search_tool_result\n\t\t// blocks on the next request (kimi-coding 400s with `tool_call_id is not\n\t\t// found`).\n\t\tsupportsWebSearch: model.compat?.supportsWebSearch ?? isAnthropicApiBaseUrl(model.baseUrl),\n\t};\n}\n\nexport type ResolvedOpenAICompletionsCompat = Omit<\n\tRequired<OpenAICompletionsCompat>,\n\t| \"cacheControlFormat\"\n\t| \"toolCallFormat\"\n\t| \"deferredToolsMode\"\n\t| \"toolSchemaFlavor\"\n\t| \"supportsPromptCacheKey\"\n\t| \"chatTemplateArgs\"\n\t| \"supportsThinkingTokenBudget\"\n> & {\n\tcacheControlFormat?: OpenAICompletionsCompat[\"cacheControlFormat\"];\n\tsupportsPromptCacheKey?: OpenAICompletionsCompat[\"supportsPromptCacheKey\"];\n\ttoolCallFormat?: OpenAICompletionsCompat[\"toolCallFormat\"];\n\tdeferredToolsMode?: OpenAICompletionsCompat[\"deferredToolsMode\"];\n\ttoolSchemaFlavor?: OpenAICompletionsCompat[\"toolSchemaFlavor\"];\n\tchatTemplateArgs?: OpenAICompletionsCompat[\"chatTemplateArgs\"];\n\tsupportsThinkingTokenBudget?: OpenAICompletionsCompat[\"supportsThinkingTokenBudget\"];\n};\n\n/**\n * Detect compatibility settings from provider and baseUrl for known providers.\n * Provider takes precedence over URL-based detection since it's explicitly configured.\n * Returns a fully resolved OpenAICompletionsCompat object with all fields set.\n */\nfunction detectOpenAICompletionsCompat(model: Model<\"openai-completions\">): ResolvedOpenAICompletionsCompat {\n\tconst provider = model.provider;\n\tconst baseUrl = model.baseUrl;\n\n\tconst isZai =\n\t\tprovider === \"zai\" ||\n\t\tprovider === \"zai-coding-cn\" ||\n\t\tbaseUrl.includes(\"api.z.ai\") ||\n\t\tbaseUrl.includes(\"open.bigmodel.cn\");\n\tconst isTogether =\n\t\tprovider === \"together\" || baseUrl.includes(\"api.together.ai\") || baseUrl.includes(\"api.together.xyz\");\n\tconst isMoonshot = provider === \"moonshotai\" || provider === \"moonshotai-cn\" || baseUrl.includes(\"api.moonshot.\");\n\tconst isOpenRouter = provider === \"openrouter\" || baseUrl.includes(\"openrouter.ai\");\n\tconst isCloudflareWorkersAI = provider === \"cloudflare-workers-ai\" || baseUrl.includes(\"api.cloudflare.com\");\n\tconst isCloudflareAiGateway = provider === \"cloudflare-ai-gateway\" || baseUrl.includes(\"gateway.ai.cloudflare.com\");\n\tconst isNvidia = provider === \"nvidia\" || baseUrl.includes(\"integrate.api.nvidia.com\");\n\tconst isAntLing = provider === \"ant-ling\" || baseUrl.includes(\"api.ant-ling.com\");\n\n\tconst isNonStandard =\n\t\tisNvidia ||\n\t\tprovider === \"cerebras\" ||\n\t\tbaseUrl.includes(\"cerebras.ai\") ||\n\t\tprovider === \"xai\" ||\n\t\tbaseUrl.includes(\"api.x.ai\") ||\n\t\tisTogether ||\n\t\tbaseUrl.includes(\"chutes.ai\") ||\n\t\tbaseUrl.includes(\"deepseek.com\") ||\n\t\tisZai ||\n\t\tisMoonshot ||\n\t\tprovider === \"opencode\" ||\n\t\tbaseUrl.includes(\"opencode.ai\") ||\n\t\tisCloudflareWorkersAI ||\n\t\tisCloudflareAiGateway ||\n\t\tisAntLing;\n\n\tconst useMaxTokens =\n\t\tbaseUrl.includes(\"chutes.ai\") ||\n\t\tisMoonshot ||\n\t\tisCloudflareAiGateway ||\n\t\tisTogether ||\n\t\tisNvidia ||\n\t\tisAntLing ||\n\t\tisZai;\n\n\tconst isGrok = provider === \"xai\" || baseUrl.includes(\"api.x.ai\");\n\tconst isDeepSeek = provider === \"deepseek\" || baseUrl.includes(\"deepseek.com\");\n\tconst isOpenRouterDeveloperRoleModel =\n\t\tisOpenRouter && (model.id.startsWith(\"anthropic/\") || model.id.startsWith(\"openai/\"));\n\tconst openRouterCacheControlPrefixes = [\"anthropic/\", \"qwen/\", \"google/\"];\n\tconst cacheControlModelId = model.id.startsWith(\"~\") ? model.id.slice(1) : model.id;\n\tconst supportsOpenRouterCacheControl = openRouterCacheControlPrefixes.some((prefix) =>\n\t\tcacheControlModelId.startsWith(prefix),\n\t);\n\tconst cacheControlFormat = provider === \"openrouter\" && supportsOpenRouterCacheControl ? \"anthropic\" : undefined;\n\n\treturn {\n\t\tsupportsStore: !isNonStandard,\n\t\tsupportsDeveloperRole: isOpenRouterDeveloperRoleModel || (!isNonStandard && !isOpenRouter),\n\t\tsupportsReasoningEffort:\n\t\t\t!isGrok && !isZai && !isMoonshot && !isTogether && !isCloudflareAiGateway && !isNvidia && !isAntLing,\n\t\tsupportsUsageInStreaming: true,\n\t\tsupportsFinishReason: true,\n\t\tmaxTokensField: useMaxTokens ? \"max_tokens\" : \"max_completion_tokens\",\n\t\trequiresToolResultName: false,\n\t\trequiresAssistantAfterToolResult: false,\n\t\trequiresThinkingAsText: false,\n\t\trequiresReasoningContentOnAssistantMessages: isDeepSeek,\n\t\tthinkingFormat: isDeepSeek\n\t\t\t? \"deepseek\"\n\t\t\t: isZai\n\t\t\t\t? \"zai\"\n\t\t\t\t: isTogether\n\t\t\t\t\t? \"together\"\n\t\t\t\t\t: isAntLing\n\t\t\t\t\t\t? \"ant-ling\"\n\t\t\t\t\t\t: isOpenRouter\n\t\t\t\t\t\t\t? \"openrouter\"\n\t\t\t\t\t\t\t: \"openai\",\n\t\topenRouterRouting: {},\n\t\tvercelGatewayRouting: {},\n\t\tchatTemplateKwargs: {},\n\t\tzaiToolStream: false,\n\t\tsupportsStrictMode: !isMoonshot && !isTogether && !isCloudflareAiGateway && !isNvidia,\n\t\ttoolSchemaFlavor: isMoonshot ? \"moonshot-mfjs\" : undefined,\n\t\tsupportsDisabledThinking: true,\n\t\ttoolCallFormat: undefined,\n\t\tsupportsOpenAIGrammarTools: false,\n\t\tcacheControlFormat,\n\t\tsendSessionAffinityHeaders: isOpenRouter,\n\t\tdeferredToolsMode: undefined,\n\t\tsessionAffinityFormat: isOpenRouter ? \"openrouter\" : \"openai\",\n\t\tsupportsPromptCacheKey: isMoonshot || baseUrl.includes(\"api.openai.com\"),\n\t\tsupportsLongCacheRetention: !(\n\t\t\tisTogether ||\n\t\t\tisCloudflareWorkersAI ||\n\t\t\tisCloudflareAiGateway ||\n\t\t\tisNvidia ||\n\t\t\tisAntLing\n\t\t),\n\t};\n}\n\n/**\n * Get resolved compatibility settings for a model.\n * Auto-detects from provider/URL then overrides with explicit model.compat.\n */\nexport function getOpenAICompletionsCompat(model: Model<\"openai-completions\">): ResolvedOpenAICompletionsCompat {\n\tconst detected = detectOpenAICompletionsCompat(model);\n\tif (!model.compat) return detected;\n\n\treturn {\n\t\tsupportsStore: model.compat.supportsStore ?? detected.supportsStore,\n\t\tsupportsDeveloperRole: model.compat.supportsDeveloperRole ?? detected.supportsDeveloperRole,\n\t\tsupportsReasoningEffort: model.compat.supportsReasoningEffort ?? detected.supportsReasoningEffort,\n\t\tsupportsUsageInStreaming: model.compat.supportsUsageInStreaming ?? detected.supportsUsageInStreaming,\n\t\tsupportsFinishReason: model.compat.supportsFinishReason ?? detected.supportsFinishReason,\n\t\tmaxTokensField: model.compat.maxTokensField ?? detected.maxTokensField,\n\t\trequiresToolResultName: model.compat.requiresToolResultName ?? detected.requiresToolResultName,\n\t\trequiresAssistantAfterToolResult:\n\t\t\tmodel.compat.requiresAssistantAfterToolResult ?? detected.requiresAssistantAfterToolResult,\n\t\trequiresThinkingAsText: model.compat.requiresThinkingAsText ?? detected.requiresThinkingAsText,\n\t\trequiresReasoningContentOnAssistantMessages:\n\t\t\tmodel.compat.requiresReasoningContentOnAssistantMessages ??\n\t\t\tdetected.requiresReasoningContentOnAssistantMessages,\n\t\tthinkingFormat: model.compat.thinkingFormat ?? detected.thinkingFormat,\n\t\tsupportsDisabledThinking: model.compat.supportsDisabledThinking ?? detected.supportsDisabledThinking,\n\t\topenRouterRouting: model.compat.openRouterRouting ?? detected.openRouterRouting,\n\t\tvercelGatewayRouting: model.compat.vercelGatewayRouting ?? detected.vercelGatewayRouting,\n\t\tchatTemplateKwargs: model.compat.chatTemplateKwargs ?? detected.chatTemplateKwargs,\n\t\tchatTemplateArgs: model.compat.chatTemplateArgs ?? detected.chatTemplateArgs,\n\t\tzaiToolStream: model.compat.zaiToolStream ?? detected.zaiToolStream,\n\t\tsupportsThinkingTokenBudget: model.compat.supportsThinkingTokenBudget ?? detected.supportsThinkingTokenBudget,\n\t\tsupportsStrictMode: model.compat.supportsStrictMode ?? detected.supportsStrictMode,\n\t\ttoolSchemaFlavor: model.compat.toolSchemaFlavor ?? detected.toolSchemaFlavor,\n\t\ttoolCallFormat: model.compat.toolCallFormat ?? detected.toolCallFormat,\n\t\tsupportsOpenAIGrammarTools: model.compat.supportsOpenAIGrammarTools ?? detected.supportsOpenAIGrammarTools,\n\t\tcacheControlFormat: model.compat.cacheControlFormat ?? detected.cacheControlFormat,\n\t\tsendSessionAffinityHeaders: model.compat.sendSessionAffinityHeaders ?? detected.sendSessionAffinityHeaders,\n\t\tdeferredToolsMode: model.compat.deferredToolsMode ?? detected.deferredToolsMode,\n\t\tsessionAffinityFormat: model.compat.sessionAffinityFormat ?? detected.sessionAffinityFormat,\n\t\tsupportsPromptCacheKey: model.compat.supportsPromptCacheKey ?? detected.supportsPromptCacheKey,\n\t\tsupportsLongCacheRetention: model.compat.supportsLongCacheRetention ?? detected.supportsLongCacheRetention,\n\t};\n}\n\nexport function getBedrockModelMatchCandidates(modelId: string, modelName?: string): string[] {\n\tconst values = modelName ? [modelId, modelName] : [modelId];\n\treturn values.flatMap((value) => {\n\t\tconst lower = value.toLowerCase();\n\t\treturn [lower, lower.replace(/[\\s_.:]+/g, \"-\")];\n\t});\n}\n\nexport function supportsOneHourCacheTtl(model: Model<\"bedrock-converse-stream\">): boolean {\n\tconst candidates = getBedrockModelMatchCandidates(model.id, model.name);\n\treturn candidates.some((candidate) =>\n\t\t[\"opus-4-5\", \"sonnet-4-5\", \"haiku-4-5\"].some((modelVersion) => candidate.includes(modelVersion)),\n\t);\n}\n\n/**\n * Check if the model supports prompt caching.\n * Supported: Claude 3.5 Haiku, Claude 3.7 Sonnet, Claude 4.x models, Claude 5 models\n *\n * For base models and system-defined inference profiles the model ID / ARN\n * contains the model name, so we can decide locally.\n *\n * For application inference profiles (whose ARNs don't contain the model name),\n * also checks model.name which is user-controlled via models.json or registerProvider.\n * As a last resort, set AWS_BEDROCK_FORCE_CACHE=1 to enable cache points.\n * Amazon Nova models have automatic caching and don't need explicit cache points.\n */\nexport function supportsPromptCaching(model: Model<\"bedrock-converse-stream\">, env?: ProviderEnv): boolean {\n\tconst candidates = getBedrockModelMatchCandidates(model.id, model.name);\n\n\tconst hasClaudeRef = candidates.some((s) => s.includes(\"claude\"));\n\tif (!hasClaudeRef) {\n\t\t// Application inference profiles don't contain the model name in the ARN.\n\t\t// Allow users to force cache points via environment variable.\n\t\tif (getProviderEnvValue(\"AWS_BEDROCK_FORCE_CACHE\", env) === \"1\") return true;\n\t\treturn false;\n\t}\n\t// Claude 5 models (fable-5, opus-5, sonnet-5)\n\tif (candidates.some((s) => s.includes(\"fable-5\") || s.includes(\"opus-5\") || s.includes(\"sonnet-5\"))) return true;\n\t// Claude 4.x models (opus-4, sonnet-4, haiku-4)\n\tif (candidates.some((s) => s.includes(\"-4-\"))) return true;\n\t// Claude 3.7 Sonnet\n\tif (candidates.some((s) => s.includes(\"claude-3-7-sonnet\"))) return true;\n\t// Claude 3.5 Haiku\n\tif (candidates.some((s) => s.includes(\"claude-3-5-haiku\"))) return true;\n\treturn false;\n}\n\nfunction resolveAnthropicCacheRetention(\n\tcacheRetention?: CacheRetention,\n\tenv?: ProviderEnv,\n\tfallback: CacheRetention = \"short\",\n): CacheRetention {\n\tif (cacheRetention) {\n\t\treturn cacheRetention;\n\t}\n\tif (getProviderEnvValue(\"PI_CACHE_RETENTION\", env) === \"long\") {\n\t\treturn \"long\";\n\t}\n\tif (typeof process !== \"undefined\" && process.env.PI_CACHE_RETENTION !== undefined) {\n\t\treturn \"short\";\n\t}\n\treturn fallback;\n}\n\nfunction resolveOpenAICompletionsCacheRetention(cacheRetention?: CacheRetention, env?: ProviderEnv): CacheRetention {\n\tif (cacheRetention) {\n\t\treturn cacheRetention;\n\t}\n\tif (getProviderEnvValue(\"PI_CACHE_RETENTION\", env) === \"long\") {\n\t\treturn \"long\";\n\t}\n\treturn \"short\";\n}\n\nfunction resolveBedrockCacheRetention(cacheRetention?: CacheRetention, env?: ProviderEnv): CacheRetention {\n\tif (cacheRetention) {\n\t\treturn cacheRetention;\n\t}\n\tif (getProviderEnvValue(\"PI_CACHE_RETENTION\", env) === \"long\") {\n\t\treturn \"long\";\n\t}\n\treturn \"short\";\n}\n\nfunction resolveOpenAIResponsesCacheRetention(cacheRetention?: CacheRetention, env?: ProviderEnv): CacheRetention {\n\tif (cacheRetention) {\n\t\treturn cacheRetention;\n\t}\n\tif (getProviderEnvValue(\"PI_CACHE_RETENTION\", env) === \"long\") {\n\t\treturn \"long\";\n\t}\n\treturn \"short\";\n}\n\nexport function resolvePromptCacheTtlSeconds(model: Model<Api>, env?: ProviderEnv): number | undefined {\n\tswitch (model.api) {\n\t\tcase \"claude-sdk-oauth\":\n\t\t\t// The Claude SDK owns prompt caching for this lane and uses Anthropic's default 5m TTL.\n\t\t\treturn PROMPT_CACHE_TTL_SHORT_SECONDS;\n\t\tcase \"anthropic-messages\": {\n\t\t\tconst anthropicModel = model as Model<\"anthropic-messages\">;\n\t\t\tconst retention = resolveAnthropicCacheRetention(anthropicModel.cacheRetention, env, \"short\");\n\t\t\tif (retention === \"none\") return undefined;\n\t\t\treturn retention === \"long\" &&\n\t\t\t\tisAnthropicApiBaseUrl(anthropicModel.baseUrl) &&\n\t\t\t\tgetAnthropicCompat(anthropicModel).supportsLongCacheRetention\n\t\t\t\t? PROMPT_CACHE_TTL_LONG_SECONDS\n\t\t\t\t: PROMPT_CACHE_TTL_SHORT_SECONDS;\n\t\t}\n\t\tcase \"bedrock-converse-stream\": {\n\t\t\tconst bedrockModel = model as Model<\"bedrock-converse-stream\">;\n\t\t\tconst retention = resolveBedrockCacheRetention(bedrockModel.cacheRetention, env);\n\t\t\tif (retention === \"none\" || !supportsPromptCaching(bedrockModel, env)) return undefined;\n\t\t\treturn retention === \"long\" && supportsOneHourCacheTtl(bedrockModel)\n\t\t\t\t? PROMPT_CACHE_TTL_LONG_SECONDS\n\t\t\t\t: PROMPT_CACHE_TTL_SHORT_SECONDS;\n\t\t}\n\t\tcase \"openai-completions\": {\n\t\t\tconst completionsModel = model as Model<\"openai-completions\">;\n\t\t\tconst retention = resolveOpenAICompletionsCacheRetention(completionsModel.cacheRetention, env);\n\t\t\tif (retention === \"none\") return undefined;\n\t\t\tconst compat = getOpenAICompletionsCompat(completionsModel);\n\t\t\tif (compat.cacheControlFormat === \"anthropic\") {\n\t\t\t\treturn retention === \"long\" && compat.supportsLongCacheRetention\n\t\t\t\t\t? PROMPT_CACHE_TTL_LONG_SECONDS\n\t\t\t\t\t: PROMPT_CACHE_TTL_SHORT_SECONDS;\n\t\t\t}\n\t\t\treturn PROMPT_CACHE_TTL_SHORT_SECONDS;\n\t\t}\n\t\tcase \"openai-responses\":\n\t\tcase \"openai-codex-responses\":\n\t\tcase \"azure-openai-responses\": {\n\t\t\tconst retention = resolveOpenAIResponsesCacheRetention(model.cacheRetention, env);\n\t\t\treturn retention === \"none\" ? undefined : PROMPT_CACHE_TTL_SHORT_SECONDS;\n\t\t}\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provider-retry.js","sourceRoot":"","sources":["../../src/utils/provider-retry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AAEnF,MAAM,0BAA0B,GAAG,MAAM,CAAC;AAC1C,MAAM,mCAAmC,GAAG,iDAAiD,CAAC;AAiB9F,SAAS,eAAe,CAAC,KAAc;IACtC,IAAI,CAAC,CAAC,KAAK,YAAY,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IAC5C,IAAI,KAAK,CAAC,OAAO,KAAK,mCAAmC;QAAE,OAAO,IAAI,CAAC;IACvE,IAAI,CAAC,CAAC,QAAQ,IAAI,KAAK,CAAC,IAAI,CAAC,CAAC,SAAS,IAAI,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IAChE,OAAO,CACN,CAAC,KAAK,CAAC,MAAM,KAAK,SAAS,IAAI,OAAO,KAAK,CAAC,MAAM,KAAK,QAAQ,CAAC;QAChE,CAAC,KAAK,CAAC,OAAO,KAAK,S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EAAE,CAAC;YAC9B,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBAChB,cAAc,GAAG,IAAI,CAAC;gBACtB,MAAM,KAAK,CAAC;YACb,CAAC;YACD,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;gBACf,SAAS,GAAG,IAAI,CAAC;gBACjB,OAAO;YACR,CAAC;YACD,MAAM,IAAI,CAAC,KAAK,CAAC;QAClB,CAAC;IACF,CAAC;YAAS,CAAC;QACV,IAAI,CAAC,SAAS,IAAI,CAAC,cAAc,EAAE,CAAC;YACnC,MAAM,QAAQ,CAAC,MAAM,EAAE,EAAE,CAAC;QAC3B,CAAC;IACF,CAAC;AACF,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,0BAA0B,CAC/C,OAAgE,EAChE,OAAO,GAAyB,EAAE;IAElC,OAAO,oBAAoB,CAAC,KAAK,IAAI,EAAE;QACtC,MAAM,OAAO,GAAG,MAAM,OAAO,EAAE,CAAC;QAChC,MAAM,QAAQ,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,aAAa,CAAC,EAAE,CAAC;QACxD,MAAM,KAAK,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;QACpC,OAAO;YACN,MAAM,EAAE,sBAAsB,CAAC,KAAK,EAAE,QAAQ,CAAC;YAC/C,QAAQ,EAAE,OAAO,CAAC,QAAQ;SAC1B,CAAC;IACH,CAAC,EAAE,OAAO,CAAC,CAAC;AACb,CAAC","sourcesContent":["import { appendRetryAfterMsMarker, extract429RetryAfterMs } from \"./retry-hint.ts\";\n\nconst DEFAULT_MAX_RETRY_DELAY_MS = 60_000;\nconst DIGITALOCEAN_STREAM_FAILURE_MESSAGE = \"Upstream error from DigitalOcean: stream failed\";\n\nexport interface ProviderRetryDelayError extends Error {\n\treadonly retryAfterMs: number;\n}\n\ninterface ProviderRetryOptions {\n\tmaxRetries?: number;\n\tmaxRetryDelayMs?: number;\n\tsignal?: AbortSignal;\n}\n\ninterface ProviderError extends Error {\n\tstatus: number | undefined;\n\theaders: Headers | undefined;\n}\n\nfunction isProviderError(error: unknown): error is ProviderError {\n\tif (!(error instanceof Error)) return false;\n\tif (error.message === DIGITALOCEAN_STREAM_FAILURE_MESSAGE) return true;\n\tif (!(\"status\" in error) || !(\"headers\" in error)) return false;\n\treturn (\n\t\t(error.status === undefined || typeof error.status === \"number\") &&\n\t\t(error.headers === undefined || error.headers instanceof Headers)\n\t);\n}\n\n/** Mirrors the pinned OpenAI/Anthropic SDK retry policy; review when either SDK is upgraded. */\nfunction isRetryableProviderError(error: ProviderError): boolean {\n\tconst shouldRetry = error.headers?.get(\"x-should-retry\");\n\tif (shouldRetry === \"true\") return true;\n\tif (shouldRetry === \"false\") return false;\n\n\tif (error.status === undefined) return true;\n\treturn (\n\t\terror.status === 408 ||\n\t\terror.status === 409 ||\n\t\terror.status === 429 ||\n\t\t(typeof error.status === \"number\" && error.status >= 500)\n\t);\n}\n\nfunction validateServerRetryDelayMs(\n\tdelayMs: number,\n\tmaxRetryDelayMs: number | undefined,\n\tproviderErrorMessage: string,\n): number {\n\tconst maxDelayMs = maxRetryDelayMs ?? DEFAULT_MAX_RETRY_DELAY_MS;\n\tif (maxDelayMs > 0 && delayMs > maxDelayMs) {\n\t\tconst message = `Server requested ${Math.ceil(delayMs / 1000)}s retry delay (max: ${Math.ceil(maxDelayMs / 1000)}s). ${providerErrorMessage}`;\n\t\tconst error: ProviderRetryDelayError = Object.assign(new Error(appendRetryAfterMsMarker(message, delayMs)), {\n\t\t\tretryAfterMs: delayMs,\n\t\t});\n\t\tthrow error;\n\t}\n\treturn delayMs;\n}\n\nfunction getRetryDelayMs(error: ProviderError, retryIndex: number, maxRetryDelayMs: number | undefined): number {\n\tconst hintMs = extract429RetryAfterMs({\n\t\tstatus: 429,\n\t\theaders: error.headers,\n\t\tbodyText: \"\",\n\t});\n\tif (hintMs !== undefined) {\n\t\treturn validateServerRetryDelayMs(hintMs, maxRetryDelayMs, error.message);\n\t}\n\n\tconst exponentialDelay = Math.min(0.5 * 2 ** retryIndex, 8) * 1000;\n\treturn exponentialDelay * (1 - Math.random() * 0.25);\n}\n\nfunction createAbortError(): Error {\n\tconst error = new Error(\"Request aborted\");\n\terror.name = \"AbortError\";\n\treturn error;\n}\n\nfunction abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(createAbortError());\n\t\t\treturn;\n\t\t}\n\n\t\tconst onAbort = () => {\n\t\t\tclearTimeout(timeout);\n\t\t\treject(createAbortError());\n\t\t};\n\t\tconst timeout = setTimeout(\n\t\t\t() => {\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\tresolve();\n\t\t\t},\n\t\t\tMath.max(0, ms),\n\t\t);\n\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t});\n}\n\n/**\n * Reproduce the retry behavior used by the OpenAI and Anthropic SDKs while making\n * their backoff sleep interruptible. Their built-in retry timers ignore the\n * request AbortSignal, so callers must invoke the SDK with `maxRetries: 0` and\n * wrap the request with this helper. Provider-requested delays above\n * `maxRetryDelayMs` fail immediately (60 seconds by default); set it to zero to\n * disable the limit.\n */\nexport async function retryProviderRequest<T>(\n\trequest: () => Promise<T>,\n\toptions: ProviderRetryOptions = {},\n): Promise<T> {\n\tconst maxRetries = options.maxRetries ?? 0;\n\tlet retriesRemaining = maxRetries;\n\n\tfor (;;) {\n\t\ttry {\n\t\t\t// Each retry is a fresh SDK request, so X-Stainless-Retry-Count remains zero.\n\t\t\treturn await request();\n\t\t} catch (error) {\n\t\t\tif (options.signal?.aborted) throw createAbortError();\n\t\t\tif (retriesRemaining <= 0 || !isProviderError(error) || !isRetryableProviderError(error)) throw error;\n\n\t\t\tconst retryIndex = maxRetries - retriesRemaining;\n\t\t\tretriesRemaining--;\n\t\t\tawait abortableSleep(getRetryDelayMs(error, retryIndex, options.maxRetryDelayMs), options.signal);\n\t\t}\n\t}\n}\n\ninterface ProviderStreamAttempt<TChunk, TMetadata> {\n\tstream: AsyncIterable<TChunk>;\n\tmetadata: TMetadata;\n}\n\nasync function* replayPrefetchedStream<TChunk>(\n\tfirst: IteratorResult<TChunk>,\n\titerator: AsyncIterator<TChunk>,\n): AsyncGenerator<TChunk> {\n\tif (first.done) return;\n\tlet completed = false;\n\tlet providerFailed = false;\n\ttry {\n\t\tyield first.value;\n\t\tfor (;;) {\n\t\t\tlet next: IteratorResult<TChunk>;\n\t\t\ttry {\n\t\t\t\tnext = await iterator.next();\n\t\t\t} catch (error) {\n\t\t\t\tproviderFailed = true;\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tif (next.done) {\n\t\t\t\tcompleted = true;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tyield next.value;\n\t\t}\n\t} finally {\n\t\tif (!completed && !providerFailed) {\n\t\t\tawait iterator.return?.();\n\t\t}\n\t}\n}\n\nexport async function retryProviderStreamRequest<TChunk, TMetadata>(\n\trequest: () => Promise<ProviderStreamAttempt<TChunk, TMetadata>>,\n\toptions: ProviderRetryOptions = {},\n): Promise<ProviderStreamAttempt<TChunk, TMetadata>> {\n\treturn retryProviderRequest(async () => {\n\t\tconst attempt = await request();\n\t\tconst iterator = attempt.stream[Symbol.asyncIterator]();\n\t\tconst first = await iterator.next();\n\t\treturn {\n\t\t\tstream: replayPrefetchedStream(first, iterator),\n\t\t\tmetadata: attempt.metadata,\n\t\t};\n\t}, options);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"provider-retry.js","sourceRoot":"","sources":["../../src/utils/provider-retry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AAEnF,MAAM,0BAA0B,GAAG,MAAM,CAAC;AAC1C,MAAM,mCAAmC,GAAG,iDAAiD,CAAC;AAiB9F,SAAS,eAAe,CAAC,KAAc;IACtC,IAAI,CAAC,CAAC,KAAK,YAAY,KAAK,CAAC;QAAE,OAA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AC","sourcesContent":["import { appendRetryAfterMsMarker, extract429RetryAfterMs } from \"./retry-hint.ts\";\n\nconst DEFAULT_MAX_RETRY_DELAY_MS = 60_000;\nconst DIGITALOCEAN_STREAM_FAILURE_MESSAGE = \"Upstream error from DigitalOcean: stream failed\";\n\nexport interface ProviderRetryDelayError extends Error {\n\treadonly retryAfterMs: number;\n}\n\ninterface ProviderRetryOptions {\n\tmaxRetries?: number;\n\tmaxRetryDelayMs?: number;\n\tsignal?: AbortSignal;\n}\n\ninterface ProviderError extends Error {\n\tstatus: number | undefined;\n\theaders: Headers | undefined;\n}\n\nfunction isProviderError(error: unknown): error is ProviderError {\n\tif (!(error instanceof Error)) return false;\n\tif (error.message === DIGITALOCEAN_STREAM_FAILURE_MESSAGE) return true;\n\tif (!(\"status\" in error) || !(\"headers\" in error)) return false;\n\treturn (\n\t\t(error.status === undefined || typeof error.status === \"number\") &&\n\t\t(error.headers === undefined || error.headers instanceof Headers)\n\t);\n}\n\n/** Mirrors the pinned OpenAI/Anthropic SDK retry policy; review when either SDK is upgraded. */\nfunction isRetryableProviderError(error: ProviderError): boolean {\n\tconst shouldRetry = error.headers?.get(\"x-should-retry\");\n\tif (shouldRetry === \"true\") return true;\n\tif (shouldRetry === \"false\") return false;\n\n\tif (error.status === undefined) return true;\n\treturn (\n\t\terror.status === 408 ||\n\t\terror.status === 409 ||\n\t\terror.status === 429 ||\n\t\t(typeof error.status === \"number\" && error.status >= 500)\n\t);\n}\n\nfunction validateServerRetryDelayMs(\n\tdelayMs: number,\n\tmaxRetryDelayMs: number | undefined,\n\tproviderErrorMessage: string,\n): number {\n\tconst maxDelayMs = maxRetryDelayMs ?? DEFAULT_MAX_RETRY_DELAY_MS;\n\tif (maxDelayMs > 0 && delayMs > maxDelayMs) {\n\t\tconst message = `Server requested ${Math.ceil(delayMs / 1000)}s retry delay (max: ${Math.ceil(maxDelayMs / 1000)}s). ${providerErrorMessage}`;\n\t\tconst error: ProviderRetryDelayError = Object.assign(new Error(appendRetryAfterMsMarker(message, delayMs)), {\n\t\t\tretryAfterMs: delayMs,\n\t\t});\n\t\tthrow error;\n\t}\n\treturn delayMs;\n}\n\nfunction getRetryDelayMs(error: ProviderError, retryIndex: number, maxRetryDelayMs: number | undefined): number {\n\tconst hintMs = extract429RetryAfterMs({\n\t\tstatus: 429,\n\t\theaders: error.headers,\n\t\tbodyText: \"\",\n\t});\n\tif (hintMs !== undefined) {\n\t\treturn validateServerRetryDelayMs(hintMs, maxRetryDelayMs, error.message);\n\t}\n\n\tconst exponentialDelay = Math.min(0.5 * 2 ** retryIndex, 8) * 1000;\n\treturn exponentialDelay * (1 - Math.random() * 0.25);\n}\n\nfunction createAbortError(): Error {\n\tconst error = new Error(\"Request aborted\");\n\terror.name = \"AbortError\";\n\treturn error;\n}\n\nfunction abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(createAbortError());\n\t\t\treturn;\n\t\t}\n\n\t\tconst onAbort = () => {\n\t\t\tclearTimeout(timeout);\n\t\t\treject(createAbortError());\n\t\t};\n\t\tconst timeout = setTimeout(\n\t\t\t() => {\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\tresolve();\n\t\t\t},\n\t\t\tMath.max(0, ms),\n\t\t);\n\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t});\n}\n\n/**\n * Reproduce the retry behavior used by the OpenAI and Anthropic SDKs while making\n * their backoff sleep interruptible. Their built-in retry timers ignore the\n * request AbortSignal, so callers must invoke the SDK with `maxRetries: 0` and\n * wrap the request with this helper. Provider-requested delays above\n * `maxRetryDelayMs` fail immediately (60 seconds by default); set it to zero to\n * disable the limit.\n */\nexport async function retryProviderRequest<T>(\n\trequest: () => Promise<T>,\n\toptions: ProviderRetryOptions = {},\n): Promise<T> {\n\tconst maxRetries = options.maxRetries ?? 0;\n\tlet retriesRemaining = maxRetries;\n\n\tfor (;;) {\n\t\ttry {\n\t\t\t// Each retry is a fresh SDK request, so X-Stainless-Retry-Count remains zero.\n\t\t\treturn await request();\n\t\t} catch (error) {\n\t\t\tif (options.signal?.aborted) throw createAbortError();\n\t\t\tif (retriesRemaining <= 0 || !isProviderError(error) || !isRetryableProviderError(error)) throw error;\n\n\t\t\tconst retryIndex = maxRetries - retriesRemaining;\n\t\t\tretriesRemaining--;\n\t\t\tawait abortableSleep(getRetryDelayMs(error, retryIndex, options.maxRetryDelayMs), options.signal);\n\t\t}\n\t}\n}\n\ninterface ProviderStreamAttempt<TChunk, TMetadata> {\n\tstream: AsyncIterable<TChunk>;\n\tmetadata: TMetadata;\n}\n\nasync function* replayPrefetchedStream<TChunk>(\n\tfirst: IteratorResult<TChunk>,\n\titerator: AsyncIterator<TChunk>,\n): AsyncGenerator<TChunk> {\n\tif (first.done) return;\n\tlet completed = false;\n\tlet providerFailed = false;\n\ttry {\n\t\tyield first.value;\n\t\tfor (;;) {\n\t\t\tlet next: IteratorResult<TChunk>;\n\t\t\ttry {\n\t\t\t\tnext = await iterator.next();\n\t\t\t} catch (error) {\n\t\t\t\tproviderFailed = true;\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tif (next.done) {\n\t\t\t\tcompleted = true;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tyield next.value;\n\t\t}\n\t} finally {\n\t\tif (!completed && !providerFailed) {\n\t\t\tawait iterator.return?.();\n\t\t}\n\t}\n}\n\nexport async function retryProviderStreamRequest<TChunk, TMetadata>(\n\trequest: () => Promise<ProviderStreamAttempt<TChunk, TMetadata>>,\n\toptions: ProviderRetryOptions = {},\n): Promise<ProviderStreamAttempt<TChunk, TMetadata>> {\n\treturn retryProviderRequest(async () => {\n\t\tconst attempt = await request();\n\t\tconst iterator = attempt.stream[Symbol.asyncIterator]();\n\t\tconst first = await iterator.next();\n\t\treturn {\n\t\t\tstream: replayPrefetchedStream(first, iterator),\n\t\t\tmetadata: attempt.metadata,\n\t\t};\n\t}, options);\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-schema-compat.d.ts","sourceRoot":"","sources":["../../src/utils/tool-schema-compat.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,MAAM,MAAM,gBAAgB,GAAG,eAAe,CAAC;
|
|
1
|
+
{"version":3,"file":"tool-schema-compat.d.ts","sourceRoot":"","sources":["../../src/utils/tool-schema-compat.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,MAAM,MAAM,gBAAgB,GAAG,eAAe,CAAC;AAsM/C;;;GAGG;AACH,wBAAgB,sCAAsC,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAG/G;AAqBD;;;GAGG;AACH,wBAAgB,kCAAkC,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAE3G;AAED;;;;;;GAMG;AACH,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAEhG"}
|
|
@@ -153,6 +153,7 @@ function normalizeNode(node, isRoot = false) {
|
|
|
153
153
|
if (!isJsonObject(node)) {
|
|
154
154
|
return node;
|
|
155
155
|
}
|
|
156
|
+
delete node.optional;
|
|
156
157
|
const hasCombiner = COMBINER_KEYS.some((key) => Array.isArray(node[key]));
|
|
157
158
|
// The root of a tool's parameters must keep `type: "object"`; hoisting it into
|
|
158
159
|
// the branches leaves a typeless root that gateways reject outright.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-schema-compat.js","sourceRoot":"","sources":["../../src/utils/tool-schema-compat.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAIH,MAAM,aAAa,GAAG,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,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AC,SAAS,CAAC;IACtB,OAAO,IAAI,CAAC,UAAU,CAAC;IACvB,OAAO,IAAI,CAAC,OAAO,CAAC;IACpB,OAAO,IAAI,CAAC,GAAG,CAAC;IAEhB,KAAK,MAAM,QAAQ,IAAI,aAAa,EAAE,CAAC;QACtC,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC;QAChC,IAAI,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE,CAAC;YAC7B,IAAI,CAAC,QAAQ,CAAC,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,wBAAwB,CAAC,MAAM,CAAC,CAAC,CAAC;QAC7E,CAAC;IACF,CAAC;IAED,KAAK,MAAM,GAAG,IAAI,kBAAkB,EAAE,CAAC;QACtC,IAAI,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE,CAAC;YAC9B,IAAI,CAAC,GAAG,CAAC,GAAG,wBAAwB,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;QACjD,CAAC;IACF,CAAC;IAED,KAAK,MAAM,GAAG,IAAI,eAAe,EAAE,CAAC;QACnC,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC;QACtB,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC;YAAE,SAAS;QACjC,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;YACrC,GAAG,CAAC,IAAI,CAAC,GAAG,wBAAwB,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC;QACjD,CAAC;IACF,CAAC;IAED,OAAO,IAAI,CAAC;AACb,CAAC","sourcesContent":["/**\n * JSON Schema normalization for tool parameters sent to OpenAI-compatible\n * backends. Some gateways (e.g. Apitopia → Kimi / Moonshot) enforce a stricter\n * subset that rejects a sibling `type` keyword on schemas that also declare\n * `anyOf` / `oneOf` / `allOf`. This helper removes that redundancy while\n * preserving the schema's semantics.\n */\n\nexport type ToolSchemaFlavor = \"moonshot-mfjs\";\n\nconst COMBINER_KEYS = [\"anyOf\", \"oneOf\", \"allOf\"] as const;\nconst SCHEMA_MAP_KEYS = [\"properties\", \"patternProperties\", \"$defs\", \"definitions\"] as const;\nconst SCHEMA_SINGLE_KEYS = [\n\t\"items\",\n\t\"additionalProperties\",\n\t\"contains\",\n\t\"propertyNames\",\n\t\"if\",\n\t\"then\",\n\t\"else\",\n\t\"not\",\n] as const;\n\nfunction isJsonObject(value: unknown): value is Record<string, unknown> {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction isScalarType(type: unknown): type is \"string\" | \"number\" | \"integer\" | \"boolean\" {\n\treturn type === \"string\" || type === \"number\" || type === \"integer\" || type === \"boolean\";\n}\n\n/**\n * Move a parent-level `type` keyword into combiner branches that do not already\n * declare one, then drop the parent `type`. This keeps the schema equivalent\n * while satisfying validators that require `type` to live inside each branch.\n */\nfunction moveTypeIntoCombinerBranches(node: Record<string, unknown>): void {\n\tif (!(\"type\" in node)) return;\n\n\tconst parentType = node.type;\n\tfor (const combiner of COMBINER_KEYS) {\n\t\tconst branches = node[combiner];\n\t\tif (!Array.isArray(branches)) continue;\n\n\t\tfor (const branch of branches) {\n\t\t\tif (isJsonObject(branch) && !(\"type\" in branch)) {\n\t\t\t\tbranch.type = parentType;\n\t\t\t}\n\t\t}\n\t}\n\n\tdelete node.type;\n}\n\n/**\n * Collapse a homogeneous all-`const` union into a typed `enum`. This is the\n * wire shape many OpenAI-compatible gateways expect for literal unions.\n */\nfunction collapseConstUnion(node: Record<string, unknown>): void {\n\tconst branches = node.anyOf;\n\tif (!Array.isArray(branches) || branches.length < 2) return;\n\tif (\"type\" in node) return;\n\n\tconst values: unknown[] = [];\n\tlet sharedType: string | undefined;\n\n\tfor (const branch of branches) {\n\t\tif (!isJsonObject(branch)) return;\n\t\tif (!Object.hasOwn(branch, \"const\")) return;\n\n\t\tconst keys = Object.keys(branch);\n\t\tif (keys.length !== 2 || !keys.includes(\"type\")) return;\n\n\t\tconst branchType = branch.type;\n\t\tif (!isScalarType(branchType)) return;\n\n\t\tif (sharedType === undefined) {\n\t\t\tsharedType = branchType;\n\t\t} else if (sharedType !== branchType) {\n\t\t\treturn;\n\t\t}\n\n\t\tvalues.push(branch.const);\n\t}\n\n\tif (sharedType === undefined || values.length === 0) return;\n\n\tdelete node.anyOf;\n\tnode.type = sharedType;\n\tnode.enum = values;\n}\n\n/**\n * Collapse a root-level object union into one object schema.\n *\n * A tool's root parameters schema must be a plain `{\"type\":\"object\"}` schema:\n * OpenAI-compatible gateways reject a root that only carries `anyOf`/`oneOf`\n * with `tools.function.parameters.type is required and must be \"object\"`. The\n * merge is intentionally lossy in the direction of permissiveness — branch\n * exclusivity becomes advisory — but it must never lose a declared parameter,\n * so the root's own `properties` and `required` are merged with the branches'\n * rather than replaced by them.\n */\nfunction mergeRootObjectUnion(schema: Record<string, unknown>): Record<string, unknown> | undefined {\n\tconst branches = Array.isArray(schema.anyOf) ? schema.anyOf : Array.isArray(schema.oneOf) ? schema.oneOf : undefined;\n\tif (branches === undefined || branches.length === 0) return undefined;\n\tif (schema.properties !== undefined && !isJsonObject(schema.properties)) return undefined;\n\tif (schema.required !== undefined && !Array.isArray(schema.required)) return undefined;\n\n\tconst objectBranches: Record<string, unknown>[] = [];\n\tfor (const branch of branches) {\n\t\t// An untyped branch is a constraint-only variant (e.g. `{ required: [...] }`)\n\t\t// over the root's own properties, so it merges like an object branch.\n\t\tif (!isJsonObject(branch) || (branch.type !== \"object\" && branch.type !== undefined)) return undefined;\n\t\tif (branch.properties !== undefined && !isJsonObject(branch.properties)) return undefined;\n\t\tif (branch.required !== undefined && !Array.isArray(branch.required)) return undefined;\n\t\tobjectBranches.push(branch);\n\t}\n\n\tconst properties: Record<string, unknown> = isJsonObject(schema.properties) ? { ...schema.properties } : {};\n\tfor (const branch of objectBranches) {\n\t\tif (!isJsonObject(branch.properties)) continue;\n\t\tfor (const [name, propertySchema] of Object.entries(branch.properties)) {\n\t\t\tconst existing = properties[name];\n\t\t\tproperties[name] =\n\t\t\t\texisting === undefined || JSON.stringify(existing) === JSON.stringify(propertySchema)\n\t\t\t\t\t? propertySchema\n\t\t\t\t\t: { anyOf: [existing, propertySchema] };\n\t\t}\n\t}\n\n\t// Only names required by EVERY branch stay required; a name required by one\n\t// branch alone would reject payloads the union accepts. Root-level `required`\n\t// applies to all branches, so it is unioned back in.\n\tconst rootRequired = Array.isArray(schema.required)\n\t\t? schema.required.filter((name): name is string => typeof name === \"string\")\n\t\t: [];\n\tconst branchRequiredSets = objectBranches.map(\n\t\t(branch) =>\n\t\t\tnew Set(\n\t\t\t\tArray.isArray(branch.required)\n\t\t\t\t\t? branch.required.filter((name): name is string => typeof name === \"string\")\n\t\t\t\t\t: [],\n\t\t\t),\n\t);\n\tconst firstBranchRequired = branchRequiredSets[0];\n\tconst commonBranchRequired = firstBranchRequired\n\t\t? [...firstBranchRequired].filter((name) => branchRequiredSets.every((names) => names.has(name)))\n\t\t: [];\n\tconst required = [...new Set([...rootRequired, ...commonBranchRequired])];\n\n\tconst { anyOf: _anyOf, oneOf: _oneOf, ...rest } = schema;\n\treturn {\n\t\t...rest,\n\t\ttype: \"object\",\n\t\tproperties,\n\t\t...(required.length > 0 ? { required } : {}),\n\t};\n}\n\nfunction normalizeNode(node: unknown, isRoot = false): unknown {\n\tif (Array.isArray(node)) {\n\t\treturn node.map((child) => normalizeNode(child));\n\t}\n\n\tif (!isJsonObject(node)) {\n\t\treturn node;\n\t}\n\n\tconst hasCombiner = COMBINER_KEYS.some((key) => Array.isArray(node[key]));\n\t// The root of a tool's parameters must keep `type: \"object\"`; hoisting it into\n\t// the branches leaves a typeless root that gateways reject outright.\n\tif (hasCombiner && !isRoot) {\n\t\tmoveTypeIntoCombinerBranches(node);\n\t}\n\n\tfor (const combiner of COMBINER_KEYS) {\n\t\tconst branches = node[combiner];\n\t\tif (Array.isArray(branches)) {\n\t\t\tnode[combiner] = branches.map((branch) => normalizeNode(branch));\n\t\t}\n\t}\n\n\tif (Array.isArray(node.anyOf)) {\n\t\tcollapseConstUnion(node);\n\t}\n\n\tfor (const key of SCHEMA_SINGLE_KEYS) {\n\t\tif (Object.hasOwn(node, key)) {\n\t\t\tnode[key] = normalizeNode(node[key]);\n\t\t}\n\t}\n\n\tfor (const key of SCHEMA_MAP_KEYS) {\n\t\tconst map = node[key];\n\t\tif (!isJsonObject(map)) continue;\n\t\tfor (const name of Object.keys(map)) {\n\t\t\tmap[name] = normalizeNode(map[name]);\n\t\t}\n\t}\n\n\treturn node;\n}\n\n/**\n * Return a deep-normalized copy of a tool's JSON Schema parameters, suitable\n * for OpenAI-compatible Chat Completions backends.\n */\nexport function normalizeToolParametersForOpenAICompat(schema: Record<string, unknown>): Record<string, unknown> {\n\tconst normalized = normalizeNode(structuredClone(schema), true) as Record<string, unknown>;\n\treturn ensureRootObjectSchema(normalized);\n}\n\n/**\n * Guarantee the wire shape every OpenAI-compatible backend requires for tool\n * parameters: a root object schema. A root union of object shapes is merged into\n * one object schema; a root that merely lost its `type` gets it restored.\n *\n * A root whose branches are not object shapes is left alone: forcing\n * `type: \"object\"` onto a scalar union would assert something the schema\n * contradicts, which is worse than the missing keyword. Tool parameters are\n * objects in practice, so this only guards against corrupting an exotic schema.\n */\nfunction ensureRootObjectSchema(schema: Record<string, unknown>): Record<string, unknown> {\n\tconst merged = mergeRootObjectUnion(schema);\n\tif (merged) return merged;\n\tif (schema.type !== undefined) return schema;\n\tconst hasCombiner = COMBINER_KEYS.some((key) => Array.isArray(schema[key]));\n\tif (hasCombiner) return schema;\n\treturn { ...schema, type: \"object\" };\n}\n\n/**\n * Moonshot-flavored JSON Schema subset: in addition to the OpenAI-compatible\n * normalization, drop non-structural annotation keywords that Moonshot rejects.\n */\nexport function normalizeToolParametersForMoonshot(schema: Record<string, unknown>): Record<string, unknown> {\n\treturn stripMoonshotAnnotations(normalizeToolParametersForOpenAICompat(schema));\n}\n\n/**\n * Resolve a tool's root parameters into a single object schema, without the\n * OpenAI-specific rewrites. Wire formats that read a tool's parameters from\n * top-level `properties`/`required` need this: a root union carries neither, so\n * they would otherwise describe the tool to the model as taking no arguments.\n * Schemas that are already plain objects are returned untouched.\n */\nexport function resolveRootObjectSchema(schema: Record<string, unknown>): Record<string, unknown> {\n\treturn mergeRootObjectUnion(structuredClone(schema)) ?? schema;\n}\n\nfunction stripMoonshotAnnotations(node: unknown): Record<string, unknown> {\n\tif (Array.isArray(node)) {\n\t\treturn node.map((child) => stripMoonshotAnnotations(child)) as unknown as Record<string, unknown>;\n\t}\n\n\tif (!isJsonObject(node)) {\n\t\treturn node as Record<string, unknown>;\n\t}\n\n\t// Moonshot does not support JSON Schema validators like `format` or\n\t// annotation-only keywords like `examples` inside function parameters.\n\tdelete node.format;\n\tdelete node.examples;\n\tdelete node.readOnly;\n\tdelete node.writeOnly;\n\tdelete node.deprecated;\n\tdelete node.$schema;\n\tdelete node.$id;\n\n\tfor (const combiner of COMBINER_KEYS) {\n\t\tconst branches = node[combiner];\n\t\tif (Array.isArray(branches)) {\n\t\t\tnode[combiner] = branches.map((branch) => stripMoonshotAnnotations(branch));\n\t\t}\n\t}\n\n\tfor (const key of SCHEMA_SINGLE_KEYS) {\n\t\tif (Object.hasOwn(node, key)) {\n\t\t\tnode[key] = stripMoonshotAnnotations(node[key]);\n\t\t}\n\t}\n\n\tfor (const key of SCHEMA_MAP_KEYS) {\n\t\tconst map = node[key];\n\t\tif (!isJsonObject(map)) continue;\n\t\tfor (const name of Object.keys(map)) {\n\t\t\tmap[name] = stripMoonshotAnnotations(map[name]);\n\t\t}\n\t}\n\n\treturn node;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"tool-schema-compat.js","sourceRoot":"","sources":["../../src/utils/tool-schema-compat.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAIH,MAAM,aAAa,GAAG,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,CAAU,CAAC;AAC3D,MA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,OAAO,IAAI,CAAC,SAAS,CAAC;IACtB,OAAO,IAAI,CAAC,UAAU,CAAC;IACvB,OAAO,IAAI,CAAC,OAAO,CAAC;IACpB,OAAO,IAAI,CAAC,GAAG,CAAC;IAEhB,KAAK,MAAM,QAAQ,IAAI,aAAa,EAAE,CAAC;QACtC,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC;QAChC,IAAI,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE,CAAC;YAC7B,IAAI,CAAC,QAAQ,CAAC,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,wBAAwB,CAAC,MAAM,CAAC,CAAC,CAAC;QAC7E,CAAC;IACF,CAAC;IAED,KAAK,MAAM,GAAG,IAAI,kBAAkB,EAAE,CAAC;QACtC,IAAI,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE,CAAC;YAC9B,IAAI,CAAC,GAAG,CAAC,GAAG,wBAAwB,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;QACjD,CAAC;IACF,CAAC;IAED,KAAK,MAAM,GAAG,IAAI,eAAe,EAAE,CAAC;QACnC,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC;QACtB,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC;YAAE,SAAS;QACjC,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;YACrC,GAAG,CAAC,IAAI,CAAC,GAAG,wBAAwB,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC;QACjD,CAAC;IACF,CAAC;IAED,OAAO,IAAI,CAAC;AACb,CAAC","sourcesContent":["/**\n * JSON Schema normalization for tool parameters sent to OpenAI-compatible\n * backends. Some gateways (e.g. Apitopia → Kimi / Moonshot) enforce a stricter\n * subset that rejects a sibling `type` keyword on schemas that also declare\n * `anyOf` / `oneOf` / `allOf`. This helper removes that redundancy while\n * preserving the schema's semantics.\n */\n\nexport type ToolSchemaFlavor = \"moonshot-mfjs\";\n\nconst COMBINER_KEYS = [\"anyOf\", \"oneOf\", \"allOf\"] as const;\nconst SCHEMA_MAP_KEYS = [\"properties\", \"patternProperties\", \"$defs\", \"definitions\"] as const;\nconst SCHEMA_SINGLE_KEYS = [\n\t\"items\",\n\t\"additionalProperties\",\n\t\"contains\",\n\t\"propertyNames\",\n\t\"if\",\n\t\"then\",\n\t\"else\",\n\t\"not\",\n] as const;\n\nfunction isJsonObject(value: unknown): value is Record<string, unknown> {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction isScalarType(type: unknown): type is \"string\" | \"number\" | \"integer\" | \"boolean\" {\n\treturn type === \"string\" || type === \"number\" || type === \"integer\" || type === \"boolean\";\n}\n\n/**\n * Move a parent-level `type` keyword into combiner branches that do not already\n * declare one, then drop the parent `type`. This keeps the schema equivalent\n * while satisfying validators that require `type` to live inside each branch.\n */\nfunction moveTypeIntoCombinerBranches(node: Record<string, unknown>): void {\n\tif (!(\"type\" in node)) return;\n\n\tconst parentType = node.type;\n\tfor (const combiner of COMBINER_KEYS) {\n\t\tconst branches = node[combiner];\n\t\tif (!Array.isArray(branches)) continue;\n\n\t\tfor (const branch of branches) {\n\t\t\tif (isJsonObject(branch) && !(\"type\" in branch)) {\n\t\t\t\tbranch.type = parentType;\n\t\t\t}\n\t\t}\n\t}\n\n\tdelete node.type;\n}\n\n/**\n * Collapse a homogeneous all-`const` union into a typed `enum`. This is the\n * wire shape many OpenAI-compatible gateways expect for literal unions.\n */\nfunction collapseConstUnion(node: Record<string, unknown>): void {\n\tconst branches = node.anyOf;\n\tif (!Array.isArray(branches) || branches.length < 2) return;\n\tif (\"type\" in node) return;\n\n\tconst values: unknown[] = [];\n\tlet sharedType: string | undefined;\n\n\tfor (const branch of branches) {\n\t\tif (!isJsonObject(branch)) return;\n\t\tif (!Object.hasOwn(branch, \"const\")) return;\n\n\t\tconst keys = Object.keys(branch);\n\t\tif (keys.length !== 2 || !keys.includes(\"type\")) return;\n\n\t\tconst branchType = branch.type;\n\t\tif (!isScalarType(branchType)) return;\n\n\t\tif (sharedType === undefined) {\n\t\t\tsharedType = branchType;\n\t\t} else if (sharedType !== branchType) {\n\t\t\treturn;\n\t\t}\n\n\t\tvalues.push(branch.const);\n\t}\n\n\tif (sharedType === undefined || values.length === 0) return;\n\n\tdelete node.anyOf;\n\tnode.type = sharedType;\n\tnode.enum = values;\n}\n\n/**\n * Collapse a root-level object union into one object schema.\n *\n * A tool's root parameters schema must be a plain `{\"type\":\"object\"}` schema:\n * OpenAI-compatible gateways reject a root that only carries `anyOf`/`oneOf`\n * with `tools.function.parameters.type is required and must be \"object\"`. The\n * merge is intentionally lossy in the direction of permissiveness — branch\n * exclusivity becomes advisory — but it must never lose a declared parameter,\n * so the root's own `properties` and `required` are merged with the branches'\n * rather than replaced by them.\n */\nfunction mergeRootObjectUnion(schema: Record<string, unknown>): Record<string, unknown> | undefined {\n\tconst branches = Array.isArray(schema.anyOf) ? schema.anyOf : Array.isArray(schema.oneOf) ? schema.oneOf : undefined;\n\tif (branches === undefined || branches.length === 0) return undefined;\n\tif (schema.properties !== undefined && !isJsonObject(schema.properties)) return undefined;\n\tif (schema.required !== undefined && !Array.isArray(schema.required)) return undefined;\n\n\tconst objectBranches: Record<string, unknown>[] = [];\n\tfor (const branch of branches) {\n\t\t// An untyped branch is a constraint-only variant (e.g. `{ required: [...] }`)\n\t\t// over the root's own properties, so it merges like an object branch.\n\t\tif (!isJsonObject(branch) || (branch.type !== \"object\" && branch.type !== undefined)) return undefined;\n\t\tif (branch.properties !== undefined && !isJsonObject(branch.properties)) return undefined;\n\t\tif (branch.required !== undefined && !Array.isArray(branch.required)) return undefined;\n\t\tobjectBranches.push(branch);\n\t}\n\n\tconst properties: Record<string, unknown> = isJsonObject(schema.properties) ? { ...schema.properties } : {};\n\tfor (const branch of objectBranches) {\n\t\tif (!isJsonObject(branch.properties)) continue;\n\t\tfor (const [name, propertySchema] of Object.entries(branch.properties)) {\n\t\t\tconst existing = properties[name];\n\t\t\tproperties[name] =\n\t\t\t\texisting === undefined || JSON.stringify(existing) === JSON.stringify(propertySchema)\n\t\t\t\t\t? propertySchema\n\t\t\t\t\t: { anyOf: [existing, propertySchema] };\n\t\t}\n\t}\n\n\t// Only names required by EVERY branch stay required; a name required by one\n\t// branch alone would reject payloads the union accepts. Root-level `required`\n\t// applies to all branches, so it is unioned back in.\n\tconst rootRequired = Array.isArray(schema.required)\n\t\t? schema.required.filter((name): name is string => typeof name === \"string\")\n\t\t: [];\n\tconst branchRequiredSets = objectBranches.map(\n\t\t(branch) =>\n\t\t\tnew Set(\n\t\t\t\tArray.isArray(branch.required)\n\t\t\t\t\t? branch.required.filter((name): name is string => typeof name === \"string\")\n\t\t\t\t\t: [],\n\t\t\t),\n\t);\n\tconst firstBranchRequired = branchRequiredSets[0];\n\tconst commonBranchRequired = firstBranchRequired\n\t\t? [...firstBranchRequired].filter((name) => branchRequiredSets.every((names) => names.has(name)))\n\t\t: [];\n\tconst required = [...new Set([...rootRequired, ...commonBranchRequired])];\n\n\tconst { anyOf: _anyOf, oneOf: _oneOf, ...rest } = schema;\n\treturn {\n\t\t...rest,\n\t\ttype: \"object\",\n\t\tproperties,\n\t\t...(required.length > 0 ? { required } : {}),\n\t};\n}\n\nfunction normalizeNode(node: unknown, isRoot = false): unknown {\n\tif (Array.isArray(node)) {\n\t\treturn node.map((child) => normalizeNode(child));\n\t}\n\n\tif (!isJsonObject(node)) {\n\t\treturn node;\n\t}\n\n\tdelete node.optional;\n\n\tconst hasCombiner = COMBINER_KEYS.some((key) => Array.isArray(node[key]));\n\t// The root of a tool's parameters must keep `type: \"object\"`; hoisting it into\n\t// the branches leaves a typeless root that gateways reject outright.\n\tif (hasCombiner && !isRoot) {\n\t\tmoveTypeIntoCombinerBranches(node);\n\t}\n\n\tfor (const combiner of COMBINER_KEYS) {\n\t\tconst branches = node[combiner];\n\t\tif (Array.isArray(branches)) {\n\t\t\tnode[combiner] = branches.map((branch) => normalizeNode(branch));\n\t\t}\n\t}\n\n\tif (Array.isArray(node.anyOf)) {\n\t\tcollapseConstUnion(node);\n\t}\n\n\tfor (const key of SCHEMA_SINGLE_KEYS) {\n\t\tif (Object.hasOwn(node, key)) {\n\t\t\tnode[key] = normalizeNode(node[key]);\n\t\t}\n\t}\n\n\tfor (const key of SCHEMA_MAP_KEYS) {\n\t\tconst map = node[key];\n\t\tif (!isJsonObject(map)) continue;\n\t\tfor (const name of Object.keys(map)) {\n\t\t\tmap[name] = normalizeNode(map[name]);\n\t\t}\n\t}\n\n\treturn node;\n}\n\n/**\n * Return a deep-normalized copy of a tool's JSON Schema parameters, suitable\n * for OpenAI-compatible Chat Completions backends.\n */\nexport function normalizeToolParametersForOpenAICompat(schema: Record<string, unknown>): Record<string, unknown> {\n\tconst normalized = normalizeNode(structuredClone(schema), true) as Record<string, unknown>;\n\treturn ensureRootObjectSchema(normalized);\n}\n\n/**\n * Guarantee the wire shape every OpenAI-compatible backend requires for tool\n * parameters: a root object schema. A root union of object shapes is merged into\n * one object schema; a root that merely lost its `type` gets it restored.\n *\n * A root whose branches are not object shapes is left alone: forcing\n * `type: \"object\"` onto a scalar union would assert something the schema\n * contradicts, which is worse than the missing keyword. Tool parameters are\n * objects in practice, so this only guards against corrupting an exotic schema.\n */\nfunction ensureRootObjectSchema(schema: Record<string, unknown>): Record<string, unknown> {\n\tconst merged = mergeRootObjectUnion(schema);\n\tif (merged) return merged;\n\tif (schema.type !== undefined) return schema;\n\tconst hasCombiner = COMBINER_KEYS.some((key) => Array.isArray(schema[key]));\n\tif (hasCombiner) return schema;\n\treturn { ...schema, type: \"object\" };\n}\n\n/**\n * Moonshot-flavored JSON Schema subset: in addition to the OpenAI-compatible\n * normalization, drop non-structural annotation keywords that Moonshot rejects.\n */\nexport function normalizeToolParametersForMoonshot(schema: Record<string, unknown>): Record<string, unknown> {\n\treturn stripMoonshotAnnotations(normalizeToolParametersForOpenAICompat(schema));\n}\n\n/**\n * Resolve a tool's root parameters into a single object schema, without the\n * OpenAI-specific rewrites. Wire formats that read a tool's parameters from\n * top-level `properties`/`required` need this: a root union carries neither, so\n * they would otherwise describe the tool to the model as taking no arguments.\n * Schemas that are already plain objects are returned untouched.\n */\nexport function resolveRootObjectSchema(schema: Record<string, unknown>): Record<string, unknown> {\n\treturn mergeRootObjectUnion(structuredClone(schema)) ?? schema;\n}\n\nfunction stripMoonshotAnnotations(node: unknown): Record<string, unknown> {\n\tif (Array.isArray(node)) {\n\t\treturn node.map((child) => stripMoonshotAnnotations(child)) as unknown as Record<string, unknown>;\n\t}\n\n\tif (!isJsonObject(node)) {\n\t\treturn node as Record<string, unknown>;\n\t}\n\n\t// Moonshot does not support JSON Schema validators like `format` or\n\t// annotation-only keywords like `examples` inside function parameters.\n\tdelete node.format;\n\tdelete node.examples;\n\tdelete node.readOnly;\n\tdelete node.writeOnly;\n\tdelete node.deprecated;\n\tdelete node.$schema;\n\tdelete node.$id;\n\n\tfor (const combiner of COMBINER_KEYS) {\n\t\tconst branches = node[combiner];\n\t\tif (Array.isArray(branches)) {\n\t\t\tnode[combiner] = branches.map((branch) => stripMoonshotAnnotations(branch));\n\t\t}\n\t}\n\n\tfor (const key of SCHEMA_SINGLE_KEYS) {\n\t\tif (Object.hasOwn(node, key)) {\n\t\t\tnode[key] = stripMoonshotAnnotations(node[key]);\n\t\t}\n\t}\n\n\tfor (const key of SCHEMA_MAP_KEYS) {\n\t\tconst map = node[key];\n\t\tif (!isJsonObject(map)) continue;\n\t\tfor (const name of Object.keys(map)) {\n\t\t\tmap[name] = stripMoonshotAnnotations(map[name]);\n\t\t}\n\t}\n\n\treturn node;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validation.d.ts","sourceRoot":"","sources":["../../src/utils/validation.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"validation.d.ts","sourceRoot":"","sources":["../../src/utils/validation.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAmQlD;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,IAAI,EAAE,EAAE,QAAQ,EAAE,QAAQ,GAAG,GAAG,CAMvE;AAED;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,IAAI,EAAE,QAAQ,EAAE,QAAQ,GAAG,GAAG,CAgCzE"}
|
package/dist/utils/validation.js
CHANGED
|
@@ -150,6 +150,12 @@ function applySchemaArrayCoercion(value, schema) {
|
|
|
150
150
|
}
|
|
151
151
|
}
|
|
152
152
|
function coerceWithUnionSchema(value, schemas) {
|
|
153
|
+
for (const schema of schemas) {
|
|
154
|
+
const validator = getSubSchemaValidator(schema);
|
|
155
|
+
if (validator?.Check(value)) {
|
|
156
|
+
return value;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
153
159
|
for (const schema of schemas) {
|
|
154
160
|
const candidate = structuredClone(value);
|
|
155
161
|
const coerced = coerceWithJsonSchema(candidate, schema);
|