@bingjiang0611/rotom 0.1.25 → 0.1.26
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/THIRD_PARTY_NOTICES.md +1 -1
- package/extensions/observability/index.ts +20 -2
- package/extensions/qoder/messages.mjs +1 -1
- package/extensions/qoder/provider.mjs +14 -6
- package/extensions/qoder/transport.mjs +53 -11
- package/extensions/third-party/node_modules/.package-lock.json +6 -6
- package/extensions/third-party/node_modules/pi-subagents/README.md +17 -0
- package/extensions/third-party/node_modules/pi-subagents/agents/delegate.md +2 -0
- package/extensions/third-party/node_modules/pi-subagents/agents/oracle.md +18 -14
- package/extensions/third-party/node_modules/pi-subagents/agents/reviewer.md +5 -3
- package/extensions/third-party/node_modules/pi-subagents/docs/models.md +1 -1
- package/extensions/third-party/node_modules/pi-subagents/docs/tool-reference.md +2 -2
- package/extensions/third-party/node_modules/pi-subagents/docs/workflows.md +2 -2
- package/extensions/third-party/node_modules/pi-subagents/package.json +1 -1
- package/extensions/third-party/node_modules/pi-subagents/prompts/gather-context-and-clarify.md +1 -1
- package/extensions/third-party/node_modules/pi-subagents/prompts/parallel-research.md +4 -6
- package/extensions/third-party/node_modules/pi-subagents/skills/pi-subagents/references/constraints-and-recipes.md +8 -8
- package/extensions/third-party/node_modules/pi-subagents/skills/pi-subagents/references/execution-controls.md +5 -5
- package/extensions/third-party/node_modules/pi-subagents/skills/pi-subagents/references/prompting-and-roles.md +7 -8
- package/extensions/third-party/node_modules/pi-subagents/src/agents/agents.ts +0 -1
- package/extensions/third-party/node_modules/pi-subagents/src/extension/index.ts +9 -2
- package/extensions/third-party/node_modules/pi-subagents/src/profiles/profiles.ts +1 -2
- package/extensions/third-party/node_modules/pi-subagents/src/runs/background/async-execution.ts +81 -52
- package/extensions/third-party/node_modules/pi-subagents/src/runs/background/process-terminal.ts +13 -0
- package/extensions/third-party/node_modules/pi-subagents/src/runs/background/stale-run-reconciler.ts +7 -3
- package/extensions/third-party/node_modules/sol-pi/UPSTREAM.md +1 -0
- package/extensions/third-party/node_modules/sol-pi/package.json +1 -1
- package/extensions/third-party/node_modules/sol-pi/src/sol-pi/extensions/evidence-preserving-reducer/index.ts +1 -0
- package/extensions/third-party/node_modules/sol-pi/src/sol-pi/extensions/evidence-preserving-reducer/receipt.ts +79 -16
- package/extensions/third-party/package-lock.json +8 -8
- package/extensions/third-party/package.json +2 -2
- package/extensions/third-party/vendor/README.md +12 -12
- package/extensions/third-party/vendor/pi-subagents-0.52.1-rotom.10.tgz +0 -0
- package/extensions/third-party/vendor/sol-pi-0.1.0-rotom.2.tgz +0 -0
- package/package.json +3 -3
- package/runtime/pi/fork-build.json +9 -9
- package/runtime/pi/node_modules/.package-lock.json +7 -7
- package/runtime/pi/node_modules/@earendil-works/pi-agent-core/package.json +1 -1
- package/runtime/pi/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.d.ts.map +1 -1
- package/runtime/pi/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.js +2 -1
- package/runtime/pi/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.js.map +1 -1
- package/runtime/pi/node_modules/@earendil-works/pi-ai/dist/utils/error-body.d.ts +8 -0
- package/runtime/pi/node_modules/@earendil-works/pi-ai/dist/utils/error-body.d.ts.map +1 -1
- package/runtime/pi/node_modules/@earendil-works/pi-ai/dist/utils/error-body.js +37 -1
- package/runtime/pi/node_modules/@earendil-works/pi-ai/dist/utils/error-body.js.map +1 -1
- package/runtime/pi/node_modules/@earendil-works/pi-ai/dist/utils/retry.d.ts +6 -0
- package/runtime/pi/node_modules/@earendil-works/pi-ai/dist/utils/retry.d.ts.map +1 -1
- package/runtime/pi/node_modules/@earendil-works/pi-ai/dist/utils/retry.js +34 -0
- package/runtime/pi/node_modules/@earendil-works/pi-ai/dist/utils/retry.js.map +1 -1
- package/runtime/pi/node_modules/@earendil-works/pi-ai/package.json +1 -1
- package/runtime/pi/node_modules/@earendil-works/pi-codemode/package.json +1 -1
- package/runtime/pi/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/anthropic-messages-H6BRNJYC.js +6 -0
- package/runtime/pi/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{azure-openai-responses-KZZFKCXW.js → azure-openai-responses-45AJGMB6.js} +1 -1
- package/runtime/pi/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/bedrock-converse-stream.js +1 -1
- package/runtime/pi/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{chunk-2CKNKV2I.js → chunk-5MTGRVNE.js} +2 -2
- package/runtime/pi/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{chunk-ITZNWD4K.js → chunk-7OCND3IM.js} +1 -1
- package/runtime/pi/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-CTEAMRDY.js +2 -0
- package/runtime/pi/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{chunk-6NUCYK64.js → chunk-ESL4WJJF.js} +9 -9
- package/runtime/pi/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{chunk-DSV77X2M.js → chunk-MXCOAUPD.js} +1 -1
- package/runtime/pi/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{cloudflare-workers-ai-system-one-UTBL2KOF.js → cloudflare-workers-ai-system-one-IEPXKTM7.js} +1 -1
- package/runtime/pi/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{execute-4WILIDZF.js → execute-ULZNGRYF.js} +1 -1
- package/runtime/pi/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{google-generative-ai-KJOKBJM3.js → google-generative-ai-KXRSXWRQ.js} +1 -1
- package/runtime/pi/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{google-vertex-VCLZ36OB.js → google-vertex-CVLJXJIO.js} +1 -1
- package/runtime/pi/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{llama-cpp-classify-FYN623RH.js → llama-cpp-classify-42ZH3VVO.js} +1 -1
- package/runtime/pi/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{openai-codex-responses-ZYGHVE5B.js → openai-codex-responses-L4P7LV62.js} +1 -1
- package/runtime/pi/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{openai-completions-BGCEXFAB.js → openai-completions-ZIOWDPDJ.js} +1 -1
- package/runtime/pi/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{openai-decisions-WVPMQ4JD.js → openai-decisions-L7N23NC7.js} +1 -1
- package/runtime/pi/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{openai-responses-KCCCXI3B.js → openai-responses-XT6CQ4R7.js} +1 -1
- package/runtime/pi/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{openrouter-images-DUPG5DZO.js → openrouter-images-FQ7HEE4T.js} +1 -1
- package/runtime/pi/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{typesafe-system-one-ZSK3RN4B.js → typesafe-system-one-IH2QHGKL.js} +1 -1
- package/runtime/pi/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{virtual-modules-INPREDLP.js → virtual-modules-YSF6BJRF.js} +1 -1
- package/runtime/pi/node_modules/@earendil-works/pi-coding-agent/dist/bundle/cli-runtime.js +1 -1
- package/runtime/pi/node_modules/@earendil-works/pi-coding-agent/dist/bundle/index.js +1 -1
- package/runtime/pi/node_modules/@earendil-works/pi-coding-agent/dist/bundle/rpc-entry.js +1 -1
- package/runtime/pi/node_modules/@earendil-works/pi-coding-agent/dist/core/agent-session.d.ts +5 -0
- package/runtime/pi/node_modules/@earendil-works/pi-coding-agent/dist/core/agent-session.d.ts.map +1 -1
- package/runtime/pi/node_modules/@earendil-works/pi-coding-agent/dist/core/agent-session.js +56 -27
- package/runtime/pi/node_modules/@earendil-works/pi-coding-agent/dist/core/agent-session.js.map +1 -1
- package/runtime/pi/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/status-indicator.d.ts +1 -0
- package/runtime/pi/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/status-indicator.d.ts.map +1 -1
- package/runtime/pi/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/status-indicator.js +4 -1
- package/runtime/pi/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/status-indicator.js.map +1 -1
- package/runtime/pi/node_modules/@earendil-works/pi-coding-agent/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/runtime/pi/node_modules/@earendil-works/pi-coding-agent/dist/modes/rpc/rpc-mode.js +37 -4
- package/runtime/pi/node_modules/@earendil-works/pi-coding-agent/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/runtime/pi/node_modules/@earendil-works/pi-coding-agent/docs/json.md +6 -0
- package/runtime/pi/node_modules/@earendil-works/pi-coding-agent/docs/rpc-extension-ui.md +2 -0
- package/runtime/pi/node_modules/@earendil-works/pi-coding-agent/docs/settings.md +3 -1
- package/runtime/pi/node_modules/@earendil-works/pi-coding-agent/package.json +1 -1
- package/runtime/pi/node_modules/@earendil-works/pi-mcp/package.json +1 -1
- package/runtime/pi/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
- package/runtime/pi/node_modules/@earendil-works/pi-tui/package.json +1 -1
- package/runtime/pi/package-lock.json +7 -7
- package/runtime/pi/vendor/earendil-works-pi-agent-core-1.3.0-rotom.2.tgz +0 -0
- package/runtime/pi/vendor/earendil-works-pi-ai-1.3.0-rotom.2.tgz +0 -0
- package/runtime/pi/vendor/earendil-works-pi-codemode-1.3.0-rotom.2.tgz +0 -0
- package/runtime/pi/vendor/earendil-works-pi-coding-agent-1.3.0-rotom.2.tgz +0 -0
- package/runtime/pi/vendor/earendil-works-pi-mcp-1.3.0-rotom.2.tgz +0 -0
- package/runtime/pi/vendor/earendil-works-pi-telemetry-1.3.0-rotom.2.tgz +0 -0
- package/runtime/pi/vendor/earendil-works-pi-tui-1.3.0-rotom.2.tgz +0 -0
- package/runtime/product-config.mjs +4 -4
- package/extensions/third-party/node_modules/pi-subagents/agents/researcher.md +0 -52
- package/extensions/third-party/node_modules/pi-subagents/docs/agents.md +0 -383
- package/extensions/third-party/vendor/pi-subagents-0.52.1-rotom.7.tgz +0 -0
- package/extensions/third-party/vendor/sol-pi-0.1.0-rotom.1.tgz +0 -0
- package/runtime/pi/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/anthropic-messages-UIH6DSZT.js +0 -6
- package/runtime/pi/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-TEPMHNKQ.js +0 -2
|
@@ -24,10 +24,46 @@ export function normalizeProviderError(error) {
|
|
|
24
24
|
return {
|
|
25
25
|
status,
|
|
26
26
|
body,
|
|
27
|
-
message: error.message,
|
|
27
|
+
message: withConnectFailureCause(error.message, error),
|
|
28
28
|
messageCarriesBody,
|
|
29
29
|
};
|
|
30
30
|
}
|
|
31
|
+
// Socket errors that only occur while connecting, so the request never left
|
|
32
|
+
// this machine: DNS, refused/unroutable connects, connect timeouts.
|
|
33
|
+
const UNSENT_CONNECT_ERROR_CODES = new Set([
|
|
34
|
+
"ENOTFOUND",
|
|
35
|
+
"EAI_AGAIN",
|
|
36
|
+
"ECONNREFUSED",
|
|
37
|
+
"ENETUNREACH",
|
|
38
|
+
"ENETDOWN",
|
|
39
|
+
"EHOSTUNREACH",
|
|
40
|
+
"EADDRNOTAVAIL",
|
|
41
|
+
"UND_ERR_CONNECT_TIMEOUT",
|
|
42
|
+
]);
|
|
43
|
+
// Node/undici wording for a proxy tunnel or TLS handshake that failed before
|
|
44
|
+
// any request bytes were sent (local proxy up, upstream unreachable).
|
|
45
|
+
const UNSENT_CONNECT_ERROR_MESSAGE = /before secure TLS connection was established|when HTTP Tunneling/;
|
|
46
|
+
/**
|
|
47
|
+
* Message of the error in `error`'s cause chain that proves the request never
|
|
48
|
+
* reached the provider, or undefined. SDKs and fetch report these as opaque
|
|
49
|
+
* "fetch failed" / "Connection error." with the socket error only in `cause`.
|
|
50
|
+
*/
|
|
51
|
+
export function connectFailureCause(error) {
|
|
52
|
+
let current = error;
|
|
53
|
+
for (let depth = 0; depth < 5 && current instanceof Error; depth++) {
|
|
54
|
+
const code = current.code;
|
|
55
|
+
if ((typeof code === "string" && UNSENT_CONNECT_ERROR_CODES.has(code)) || UNSENT_CONNECT_ERROR_MESSAGE.test(current.message)) {
|
|
56
|
+
return current.message;
|
|
57
|
+
}
|
|
58
|
+
current = current.cause ?? (current instanceof AggregateError ? current.errors[0] : undefined);
|
|
59
|
+
}
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
62
|
+
/** Append the connect-phase cause so retry policy can tell "never sent" apart. */
|
|
63
|
+
export function withConnectFailureCause(message, error) {
|
|
64
|
+
const cause = connectFailureCause(error);
|
|
65
|
+
return cause === undefined || message.includes(cause) ? message : `${message} (caused by: ${cause})`;
|
|
66
|
+
}
|
|
31
67
|
/**
|
|
32
68
|
* Probe the HTTP status, first numeric hit wins, in SDK-field order:
|
|
33
69
|
* `statusCode` (Mistral) → `status` (`openai`, `@google/genai`) →
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error-body.js","sourceRoot":"","sources":["../../src/utils/error-body.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,EAAE;AACF,8EAA8E;AAC9E,gFAAgF;AAChF,gFAAgF;AAChF,6EAA6E;AAC7E,6EAA6E;AAC7E,yCAAyC;AACzC,EAAE;AACF,uEAAuE;AACvE,6EAA6E;AAC7E,+EAA+E;AAC/E,+EAA+E;AAC/E,0EAA0E;AAE1E,MAAM,CAAC,MAAM,6BAA6B,GAAG,IAAI,CAAC;AAsBlD,MAAM,UAAU,sBAAsB,CAAC,KAAc;IACpD,IAAI,CAAC,CAAC,KAAK,YAAY,KAAK,CAAC,EAAE,CAAC;QAC/B,OAAO,EAAE,OAAO,EAAE,iBAAiB,CAAC,KAAK,CAAC,EAAE,kBAAkB,EAAE,KAAK,EAAE,CAAC;IACzE,CAAC;IAED,MAAM,QAAQ,GAAG,KA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MAAM,KAAK,SAAS,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS;YACvD,CAAC,CAAC,GAAG,MAAM,KAAK,IAAI,CAAC,MAAM,MAAM,IAAI,CAAC,OAAO,EAAE;YAC/C,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC;IACjB,CAAC;IACD,OAAO,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,GAAG,MAAM,KAAK,IAAI,CAAC,MAAM,MAAM,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,MAAM,KAAK,IAAI,CAAC,IAAI,EAAE,CAAC;AAC3G,CAAC;AAED,MAAM,UAAU,iBAAiB,CAAC,IAAY,EAAE,QAAgB;IAC/D,IAAI,IAAI,CAAC,MAAM,IAAI,QAAQ;QAAE,OAAO,IAAI,CAAC;IACzC,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,QAAQ,CAAC,kBAAkB,IAAI,CAAC,MAAM,GAAG,QAAQ,SAAS,CAAC;AACpF,CAAC;AAED,MAAM,UAAU,iBAAiB,CAAC,KAAc;IAC/C,IAAI,CAAC;QACJ,MAAM,UAAU,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;QACzC,OAAO,UAAU,KAAK,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC;IAC9D,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC;IACtB,CAAC;AACF,CAAC","sourcesContent":["// Shared normalization for provider HTTP error objects.\n//\n// Endpoints behind a proxy / gateway may return a non-2xx response whose body\n// the provider SDK cannot fold into `error.message`. The SDK error object still\n// carries the HTTP status and the raw/parsed body, but under SDK-specific field\n// names. Provider catch blocks that read only `error.message` therefore drop\n// the body and surface opaque messages like `\"403 status code (no body)\"` or\n// collapse to `\"Unknown: UnknownError\"`.\n//\n// `normalizeProviderError` probes the known SDK field shapes (Mistral,\n// `openai`, `@google/genai`, AWS Bedrock) and returns a struct each provider\n// composes into its display string. The `messageCarriesBody` flag captures the\n// Anthropic / `@google/genai` happy path where the SDK already folded the body\n// into the message, so providers can preserve it without double-printing.\n\nexport const MAX_PROVIDER_ERROR_BODY_CHARS = 4000;\n\nexport interface NormalizedProviderError {\n\t/** HTTP status code, when one could be extracted from the SDK error object. */\n\tstatus?: number;\n\t/** Raw HTTP body reason, already trimmed and truncated to the cap. */\n\tbody?: string;\n\t/** `error.message`, or `safeJsonStringify(error)` for a non-`Error` throw. */\n\tmessage: string;\n\t/** True when `message` already contains the body (no separate body to add). */\n\tmessageCarriesBody: boolean;\n}\n\ntype SdkErrorShape = Error & {\n\tstatusCode?: unknown;\n\tstatus?: unknown;\n\tbody?: unknown;\n\terror?: unknown;\n\t$metadata?: { httpStatusCode?: unknown };\n\t$response?: { statusCode?: unknown; body?: unknown };\n};\n\nexport function normalizeProviderError(error: unknown): NormalizedProviderError {\n\tif (!(error instanceof Error)) {\n\t\treturn { message: safeJsonStringify(error), messageCarriesBody: false };\n\t}\n\n\tconst sdkError = error as SdkErrorShape;\n\tconst status = extractStatus(sdkError);\n\tconst body = extractBody(sdkError);\n\tconst messageCarriesBody = body === undefined || error.message.includes(body);\n\n\treturn {\n\t\tstatus,\n\t\tbody,\n\t\tmessage: error.message,\n\t\tmessageCarriesBody,\n\t} satisfies NormalizedProviderError;\n}\n\n/**\n * Probe the HTTP status, first numeric hit wins, in SDK-field order:\n * `statusCode` (Mistral) → `status` (`openai`, `@google/genai`) →\n * `$metadata.httpStatusCode` (Bedrock) → `$response.statusCode` (Bedrock).\n */\nfunction extractStatus(error: SdkErrorShape): number | undefined {\n\tif (typeof error.statusCode === \"number\") return error.statusCode;\n\tif (typeof error.status === \"number\") return error.status;\n\tif (typeof error.$metadata?.httpStatusCode === \"number\") return error.$metadata.httpStatusCode;\n\tif (typeof error.$response?.statusCode === \"number\") return error.$response.statusCode;\n\treturn undefined;\n}\n\n/**\n * Probe the raw body reason, first usable hit wins, in SDK-field order:\n * `body` string (Mistral) → `error` parsed JSON body object (`openai` SDK's\n * `this.error`) → `$response.body` (Bedrock). Empty objects and unread response\n * streams are treated as no body so they do not surface as `\"{}\"` or serialized\n * stream internals. The chosen body is truncated to the cap.\n */\nfunction extractBody(error: SdkErrorShape): string | undefined {\n\tconst bodyText = pickBodyText(error);\n\tif (bodyText === undefined) return undefined;\n\tconst trimmed = bodyText.trim();\n\tif (trimmed.length === 0) return undefined;\n\treturn truncateErrorText(trimmed, MAX_PROVIDER_ERROR_BODY_CHARS);\n}\n\nfunction pickBodyText(error: SdkErrorShape): string | undefined {\n\tif (typeof error.body === \"string\") return error.body;\n\tif (isPlainNonEmptyObject(error.error)) return safeJsonStringify(error.error);\n\tconst responseBody = error.$response?.body;\n\tif (typeof responseBody === \"string\") return responseBody;\n\tif (isReadableStreamLike(responseBody)) return undefined;\n\tif (isPlainNonEmptyObject(responseBody)) return safeJsonStringify(responseBody);\n\treturn undefined;\n}\n\nfunction isReadableStreamLike(value: unknown): boolean {\n\treturn typeof value === \"object\" && value !== null && \"pipe\" in value && typeof value.pipe === \"function\";\n}\n\n/**\n * Only a PLAIN object counts as an HTTP body. SDK error fields can hold class\n * instances instead of parsed bodies — AWS SDK v3's `$response.body` is an\n * HTTP stream/response wrapper object, and stringifying one produced garbage\n * like `{\"_events\":...}` as the \"body\", which then REPLACED `error.message`\n * in the composed display string. `error.message` is where the SDK puts the\n * real deserialized exception text (\"Input is too long...\", schema validation\n * details, ...), so the one useful string was discarded for noise. A class\n * instance yields no body, `messageCarriesBody` stays true, and the real\n * message survives. Complements the `pipe` sniffing above: web\n * ReadableStreams (pipeTo/pipeThrough, no `pipe`) and non-stream SDK wrapper\n * classes fail the prototype check, while parsed JSON bodies (plain objects\n * by construction) still pass.\n */\nfunction isPlainNonEmptyObject(value: unknown): boolean {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tconst proto = Object.getPrototypeOf(value);\n\tif (proto !== Object.prototype && proto !== null) return false;\n\treturn Object.keys(value).length > 0;\n}\n\n/**\n * Compose a display string from a normalized error. When the message already\n * carries the body (Anthropic / `@google/genai` happy path) or no body/status\n * was extracted, the message is returned unchanged. Otherwise the status and\n * body are surfaced, with an optional provider prefix.\n *\n * - no prefix: `\"<status>: <body>\"`\n * - prefix: `\"<prefix> (<status>): <body>\"`\n */\nexport function formatProviderError(norm: NormalizedProviderError, prefix?: string): string {\n\tif (norm.messageCarriesBody || norm.status === undefined || norm.body === undefined) {\n\t\treturn prefix !== undefined && norm.status !== undefined\n\t\t\t? `${prefix} (${norm.status}): ${norm.message}`\n\t\t\t: norm.message;\n\t}\n\treturn prefix !== undefined ? `${prefix} (${norm.status}): ${norm.body}` : `${norm.status}: ${norm.body}`;\n}\n\nexport function truncateErrorText(text: string, maxChars: number): string {\n\tif (text.length <= maxChars) return text;\n\treturn `${text.slice(0, maxChars)}... [truncated ${text.length - maxChars} chars]`;\n}\n\nexport function safeJsonStringify(value: unknown): string {\n\ttry {\n\t\tconst serialized = JSON.stringify(value);\n\t\treturn serialized === undefined ? String(value) : serialized;\n\t} catch {\n\t\treturn String(value);\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"error-body.js","sourceRoot":"","sources":["../../src/utils/error-body.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,EAAE;AACF,8EAA8E;AAC9E,gFAAgF;AAChF,gFAAgF;AAChF,6EAA6E;AAC7E,6EAA6E;AAC7E,yCAAyC;AACzC,EAAE;AACF,uEAAuE;AACvE,6EAA6E;AAC7E,+EAA+E;AAC/E,+EAA+E;AAC/E,0EAA0E;AAE1E,MAAM,CAAC,MAAM,6BAA6B,GAAG,IAAI,CAAC;AAsBlD,MAAM,UAAU,sBAAsB,CAAC,KAAc;IACpD,IAAI,CAAC,CAAC,KAAK,YAAY,KAAK,CAAC,EAAE,CAAC;QAC/B,OAAO,EAAE,OAAO,EAAE,iBAAiB,CAAC,KAAK,CAAC,EAAE,kBA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,KAAK,SAAS,IAAI,IAAI,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;QACrF,OAAO,MAAM,KAAK,SAAS,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS;YACvD,CAAC,CAAC,GAAG,MAAM,KAAK,IAAI,CAAC,MAAM,MAAM,IAAI,CAAC,OAAO,EAAE;YAC/C,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC;IACjB,CAAC;IACD,OAAO,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,GAAG,MAAM,KAAK,IAAI,CAAC,MAAM,MAAM,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,MAAM,KAAK,IAAI,CAAC,IAAI,EAAE,CAAC;AAC3G,CAAC;AAED,MAAM,UAAU,iBAAiB,CAAC,IAAY,EAAE,QAAgB;IAC/D,IAAI,IAAI,CAAC,MAAM,IAAI,QAAQ;QAAE,OAAO,IAAI,CAAC;IACzC,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,QAAQ,CAAC,kBAAkB,IAAI,CAAC,MAAM,GAAG,QAAQ,SAAS,CAAC;AACpF,CAAC;AAED,MAAM,UAAU,iBAAiB,CAAC,KAAc;IAC/C,IAAI,CAAC;QACJ,MAAM,UAAU,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;QACzC,OAAO,UAAU,KAAK,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC;IAC9D,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC;IACtB,CAAC;AACF,CAAC","sourcesContent":["// Shared normalization for provider HTTP error objects.\n//\n// Endpoints behind a proxy / gateway may return a non-2xx response whose body\n// the provider SDK cannot fold into `error.message`. The SDK error object still\n// carries the HTTP status and the raw/parsed body, but under SDK-specific field\n// names. Provider catch blocks that read only `error.message` therefore drop\n// the body and surface opaque messages like `\"403 status code (no body)\"` or\n// collapse to `\"Unknown: UnknownError\"`.\n//\n// `normalizeProviderError` probes the known SDK field shapes (Mistral,\n// `openai`, `@google/genai`, AWS Bedrock) and returns a struct each provider\n// composes into its display string. The `messageCarriesBody` flag captures the\n// Anthropic / `@google/genai` happy path where the SDK already folded the body\n// into the message, so providers can preserve it without double-printing.\n\nexport const MAX_PROVIDER_ERROR_BODY_CHARS = 4000;\n\nexport interface NormalizedProviderError {\n\t/** HTTP status code, when one could be extracted from the SDK error object. */\n\tstatus?: number;\n\t/** Raw HTTP body reason, already trimmed and truncated to the cap. */\n\tbody?: string;\n\t/** `error.message`, or `safeJsonStringify(error)` for a non-`Error` throw. */\n\tmessage: string;\n\t/** True when `message` already contains the body (no separate body to add). */\n\tmessageCarriesBody: boolean;\n}\n\ntype SdkErrorShape = Error & {\n\tstatusCode?: unknown;\n\tstatus?: unknown;\n\tbody?: unknown;\n\terror?: unknown;\n\t$metadata?: { httpStatusCode?: unknown };\n\t$response?: { statusCode?: unknown; body?: unknown };\n};\n\nexport function normalizeProviderError(error: unknown): NormalizedProviderError {\n\tif (!(error instanceof Error)) {\n\t\treturn { message: safeJsonStringify(error), messageCarriesBody: false };\n\t}\n\n\tconst sdkError = error as SdkErrorShape;\n\tconst status = extractStatus(sdkError);\n\tconst body = extractBody(sdkError);\n\tconst messageCarriesBody = body === undefined || error.message.includes(body);\n\n\treturn {\n\t\tstatus,\n\t\tbody,\n\t\tmessage: withConnectFailureCause(error.message, error),\n\t\tmessageCarriesBody,\n\t} satisfies NormalizedProviderError;\n}\n\n// Socket errors that only occur while connecting, so the request never left\n// this machine: DNS, refused/unroutable connects, connect timeouts.\nconst UNSENT_CONNECT_ERROR_CODES = new Set([\n\t\"ENOTFOUND\",\n\t\"EAI_AGAIN\",\n\t\"ECONNREFUSED\",\n\t\"ENETUNREACH\",\n\t\"ENETDOWN\",\n\t\"EHOSTUNREACH\",\n\t\"EADDRNOTAVAIL\",\n\t\"UND_ERR_CONNECT_TIMEOUT\",\n]);\n// Node/undici wording for a proxy tunnel or TLS handshake that failed before\n// any request bytes were sent (local proxy up, upstream unreachable).\nconst UNSENT_CONNECT_ERROR_MESSAGE = /before secure TLS connection was established|when HTTP Tunneling/;\n\n/**\n * Message of the error in `error`'s cause chain that proves the request never\n * reached the provider, or undefined. SDKs and fetch report these as opaque\n * \"fetch failed\" / \"Connection error.\" with the socket error only in `cause`.\n */\nexport function connectFailureCause(error: unknown): string | undefined {\n\tlet current = error;\n\tfor (let depth = 0; depth < 5 && current instanceof Error; depth++) {\n\t\tconst code = (current as { code?: unknown }).code;\n\t\tif ((typeof code === \"string\" && UNSENT_CONNECT_ERROR_CODES.has(code)) || UNSENT_CONNECT_ERROR_MESSAGE.test(current.message)) {\n\t\t\treturn current.message;\n\t\t}\n\t\tcurrent = current.cause ?? (current instanceof AggregateError ? current.errors[0] : undefined);\n\t}\n\treturn undefined;\n}\n\n/** Append the connect-phase cause so retry policy can tell \"never sent\" apart. */\nexport function withConnectFailureCause(message: string, error: unknown): string {\n\tconst cause = connectFailureCause(error);\n\treturn cause === undefined || message.includes(cause) ? message : `${message} (caused by: ${cause})`;\n}\n\n/**\n * Probe the HTTP status, first numeric hit wins, in SDK-field order:\n * `statusCode` (Mistral) → `status` (`openai`, `@google/genai`) →\n * `$metadata.httpStatusCode` (Bedrock) → `$response.statusCode` (Bedrock).\n */\nfunction extractStatus(error: SdkErrorShape): number | undefined {\n\tif (typeof error.statusCode === \"number\") return error.statusCode;\n\tif (typeof error.status === \"number\") return error.status;\n\tif (typeof error.$metadata?.httpStatusCode === \"number\") return error.$metadata.httpStatusCode;\n\tif (typeof error.$response?.statusCode === \"number\") return error.$response.statusCode;\n\treturn undefined;\n}\n\n/**\n * Probe the raw body reason, first usable hit wins, in SDK-field order:\n * `body` string (Mistral) → `error` parsed JSON body object (`openai` SDK's\n * `this.error`) → `$response.body` (Bedrock). Empty objects and unread response\n * streams are treated as no body so they do not surface as `\"{}\"` or serialized\n * stream internals. The chosen body is truncated to the cap.\n */\nfunction extractBody(error: SdkErrorShape): string | undefined {\n\tconst bodyText = pickBodyText(error);\n\tif (bodyText === undefined) return undefined;\n\tconst trimmed = bodyText.trim();\n\tif (trimmed.length === 0) return undefined;\n\treturn truncateErrorText(trimmed, MAX_PROVIDER_ERROR_BODY_CHARS);\n}\n\nfunction pickBodyText(error: SdkErrorShape): string | undefined {\n\tif (typeof error.body === \"string\") return error.body;\n\tif (isPlainNonEmptyObject(error.error)) return safeJsonStringify(error.error);\n\tconst responseBody = error.$response?.body;\n\tif (typeof responseBody === \"string\") return responseBody;\n\tif (isReadableStreamLike(responseBody)) return undefined;\n\tif (isPlainNonEmptyObject(responseBody)) return safeJsonStringify(responseBody);\n\treturn undefined;\n}\n\nfunction isReadableStreamLike(value: unknown): boolean {\n\treturn typeof value === \"object\" && value !== null && \"pipe\" in value && typeof value.pipe === \"function\";\n}\n\n/**\n * Only a PLAIN object counts as an HTTP body. SDK error fields can hold class\n * instances instead of parsed bodies — AWS SDK v3's `$response.body` is an\n * HTTP stream/response wrapper object, and stringifying one produced garbage\n * like `{\"_events\":...}` as the \"body\", which then REPLACED `error.message`\n * in the composed display string. `error.message` is where the SDK puts the\n * real deserialized exception text (\"Input is too long...\", schema validation\n * details, ...), so the one useful string was discarded for noise. A class\n * instance yields no body, `messageCarriesBody` stays true, and the real\n * message survives. Complements the `pipe` sniffing above: web\n * ReadableStreams (pipeTo/pipeThrough, no `pipe`) and non-stream SDK wrapper\n * classes fail the prototype check, while parsed JSON bodies (plain objects\n * by construction) still pass.\n */\nfunction isPlainNonEmptyObject(value: unknown): boolean {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tconst proto = Object.getPrototypeOf(value);\n\tif (proto !== Object.prototype && proto !== null) return false;\n\treturn Object.keys(value).length > 0;\n}\n\n/**\n * Compose a display string from a normalized error. When the message already\n * carries the body (Anthropic / `@google/genai` happy path) or no body/status\n * was extracted, the message is returned unchanged. Otherwise the status and\n * body are surfaced, with an optional provider prefix.\n *\n * - no prefix: `\"<status>: <body>\"`\n * - prefix: `\"<prefix> (<status>): <body>\"`\n */\nexport function formatProviderError(norm: NormalizedProviderError, prefix?: string): string {\n\tif (norm.messageCarriesBody || norm.status === undefined || norm.body === undefined) {\n\t\treturn prefix !== undefined && norm.status !== undefined\n\t\t\t? `${prefix} (${norm.status}): ${norm.message}`\n\t\t\t: norm.message;\n\t}\n\treturn prefix !== undefined ? `${prefix} (${norm.status}): ${norm.body}` : `${norm.status}: ${norm.body}`;\n}\n\nexport function truncateErrorText(text: string, maxChars: number): string {\n\tif (text.length <= maxChars) return text;\n\treturn `${text.slice(0, maxChars)}... [truncated ${text.length - maxChars} chars]`;\n}\n\nexport function safeJsonStringify(value: unknown): string {\n\ttry {\n\t\tconst serialized = JSON.stringify(value);\n\t\treturn serialized === undefined ? String(value) : serialized;\n\t} catch {\n\t\treturn String(value);\n\t}\n}\n"]}
|
|
@@ -55,4 +55,10 @@ export declare function retryAssistantCall(produce: () => Promise<AssistantMessa
|
|
|
55
55
|
* before restarting the assistant turn.
|
|
56
56
|
*/
|
|
57
57
|
export declare function isRetryableAssistantError(message: AssistantMessage): boolean;
|
|
58
|
+
/**
|
|
59
|
+
* Whether a retryable failure means the provider could not be reached at all.
|
|
60
|
+
* Callers may keep retrying these without consuming the bounded retry budget,
|
|
61
|
+
* waiting for connectivity until the user cancels.
|
|
62
|
+
*/
|
|
63
|
+
export declare function isConnectionFailureAssistantError(message: AssistantMessage): boolean;
|
|
58
64
|
//# sourceMappingURL=retry.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"retry.d.ts","sourceRoot":"","sources":["../../src/utils/retry.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"retry.d.ts","sourceRoot":"","sources":["../../src/utils/retry.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,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;AAwBD;;;;GAIG;AACH,wBAAgB,iCAAiC,CAAC,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAEpF"}
|
|
@@ -55,6 +55,7 @@ const RETRYABLE_PROVIDER_ERROR_PATTERN = buildProviderErrorPattern([
|
|
|
55
55
|
// "reset before headers" (#733), plus OpenRouter connection drops (#3317).
|
|
56
56
|
"network.?error",
|
|
57
57
|
"connection.?error",
|
|
58
|
+
"connection.?failed",
|
|
58
59
|
"connection.?refused",
|
|
59
60
|
"connection.?lost",
|
|
60
61
|
"other side closed",
|
|
@@ -62,6 +63,10 @@ const RETRYABLE_PROVIDER_ERROR_PATTERN = buildProviderErrorPattern([
|
|
|
62
63
|
"getaddrinfo",
|
|
63
64
|
"ENOTFOUND",
|
|
64
65
|
"EAI_AGAIN",
|
|
66
|
+
"ECONNREFUSED",
|
|
67
|
+
"ENETUNREACH",
|
|
68
|
+
"ENETDOWN",
|
|
69
|
+
"EHOSTUNREACH",
|
|
65
70
|
"upstream.?connect",
|
|
66
71
|
"reset before headers",
|
|
67
72
|
"socket hang up",
|
|
@@ -200,4 +205,33 @@ export function isRetryableAssistantError(message) {
|
|
|
200
205
|
return false;
|
|
201
206
|
return RETRYABLE_PROVIDER_ERROR_PATTERN.test(errorMessage);
|
|
202
207
|
}
|
|
208
|
+
// Failures that prove the request never reached the provider: DNS, refused or
|
|
209
|
+
// unroutable connects, connect timeouts, and proxy tunnel/TLS setup failures
|
|
210
|
+
// (providers append these as "(caused by: ...)", see `withConnectFailureCause`).
|
|
211
|
+
// Like Codex's connect-only rule, an opaque "fetch failed" or a reset after the
|
|
212
|
+
// request was sent is excluded: it may already be processed and billed, so it
|
|
213
|
+
// keeps the bounded retry budget, as do mid-stream drops and timeouts.
|
|
214
|
+
const CONNECTION_FAILURE_ERROR_PATTERN = buildProviderErrorPattern([
|
|
215
|
+
"getaddrinfo",
|
|
216
|
+
"ENOTFOUND",
|
|
217
|
+
"EAI_AGAIN",
|
|
218
|
+
"ECONNREFUSED",
|
|
219
|
+
"ENETUNREACH",
|
|
220
|
+
"ENETDOWN",
|
|
221
|
+
"EHOSTUNREACH",
|
|
222
|
+
"EADDRNOTAVAIL",
|
|
223
|
+
"UND_ERR_CONNECT_TIMEOUT",
|
|
224
|
+
"Connect Timeout Error",
|
|
225
|
+
"before secure TLS connection was established",
|
|
226
|
+
"when HTTP Tunneling",
|
|
227
|
+
"^Qoder: connection_failed$",
|
|
228
|
+
]);
|
|
229
|
+
/**
|
|
230
|
+
* Whether a retryable failure means the provider could not be reached at all.
|
|
231
|
+
* Callers may keep retrying these without consuming the bounded retry budget,
|
|
232
|
+
* waiting for connectivity until the user cancels.
|
|
233
|
+
*/
|
|
234
|
+
export function isConnectionFailureAssistantError(message) {
|
|
235
|
+
return isRetryableAssistantError(message) && CONNECTION_FAILURE_ERROR_PATTERN.test(message.errorMessage);
|
|
236
|
+
}
|
|
203
237
|
//# sourceMappingURL=retry.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"retry.js","sourceRoot":"","sources":["../../src/utils/retry.ts"],"names":[],"mappings":"AAEA,SAAS,yBAAyB,CAAC,QAA2B;IAC7D,OAAO,IAAI,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC;AAC5C,CAAC;AAED,MAAM,0CAA0C,GAAG,yBAAyB,CAAC;IAC5E,8EAA8E;IAC9E,2EAA2E;IAC3E,mBAAmB;IACnB,qBAAqB;IAErB,6EAA6E;IAC7E,yDAAyD;IACzD,6BAA6B;IAC7B,mBAAmB;IAEnB,4EAA4E;IAC5E,4EAA4E;IAC5E,oBAAoB;IACpB,eAAe;IACf,gBAAgB;IAChB,SAAS;IAET,4EAA4E;IAC5E,mCAAmC;IACnC,2CAA2C;CAC3C,CAAC,CAAC;AAEH,MAAM,gCAAgC,GAAG,yBAAyB,CAAC;IAClE,0EAA0E;IAC1E,YAAY;IACZ,aAAa;IACb,4BAA4B;IAC5B,oCAAoC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AC;gBAC3C,MAAM,EAAE,YAAY,EAAE,aAAa,EAAE,GAAG,IAAI,EAAE,GAAG,QAAQ,CAAC;gBAC1D,OAAO,EAAE,GAAG,IAAI,EAAE,UAAU,EAAE,SAAS,EAAE,CAAC;YAC3C,CAAC;YACD,MAAM,KAAK,CAAC;QACb,CAAC;QACD,MAAM,SAAS,EAAE,mBAAmB,EAAE,EAAE,CAAC;IAC1C,CAAC;AACF,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,yBAAyB,CAAC,OAAyB;IAClE,IAAI,OAAO,CAAC,UAAU,KAAK,OAAO,IAAI,CAAC,OAAO,CAAC,YAAY;QAAE,OAAO,KAAK,CAAC;IAC1E,MAAM,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC;IAC1C,IAAI,0CAA0C,CAAC,IAAI,CAAC,YAAY,CAAC;QAAE,OAAO,KAAK,CAAC;IAChF,OAAO,gCAAgC,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;AAC5D,CAAC","sourcesContent":["import type { AssistantMessage } from \"../types.ts\";\n\nfunction buildProviderErrorPattern(patterns: readonly string[]): RegExp {\n\treturn new RegExp(patterns.join(\"|\"), \"i\");\n}\n\nconst NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN = buildProviderErrorPattern([\n\t// OpenCode Go/free-tier limits returned as 429 JSON error types by OpenCode's\n\t// Zen API. These are subscription/account limits, not transient throttles.\n\t\"GoUsageLimitError\",\n\t\"FreeUsageLimitError\",\n\n\t// OpenCode Go subscription-limit text asks users to enable available-balance\n\t// usage after rolling/weekly/monthly limits are reached.\n\t\"Monthly usage limit reached\",\n\t\"available balance\",\n\n\t// Generic quota/budget/billing exhaustion. `insufficient_quota` is OpenAI's\n\t// quota/billing error code; the other strings cover common gateway wording.\n\t\"insufficient_quota\",\n\t\"out of budget\",\n\t\"quota exceeded\",\n\t\"billing\",\n\n\t// Sign in with ChatGPT: the subscription's shared usage limit, which resets\n\t// after hours rather than seconds.\n\t\"subscription_sharing_usage_limit_exceeded\",\n]);\n\nconst RETRYABLE_PROVIDER_ERROR_PATTERN = buildProviderErrorPattern([\n\t// Generic provider load, HTTP status, and server-side transient failures.\n\t\"overloaded\",\n\t\"server_busy\",\n\t\"servers are currently busy\",\n\t\"currently experiencing high demand\",\n\t\"model is at capacity\",\n\t\"rate.?limit\",\n\t\"too many requests\",\n\t\"429\",\n\t\"500\",\n\t\"502\",\n\t\"503\",\n\t\"504\",\n\t\"520\",\n\t\"524\",\n\t// Also matches \"The service is temporarily unavailable\" (#10965).\n\t\"service.?(?:is.?)?(?:temporarily.?)?unavailable\",\n\t\"server.?error\",\n\t\"internal.?error\",\n\n\t// Wrapper/provider text for transient upstream failures, including OpenRouter\n\t// \"Provider returned error\" responses (#2264), gateway wording such as\n\t// \"The upstream provider returned an error\" (#10842), and Qoder's sanitized\n\t// SSE error frame. The outer retry loop owns the bounded retry budget.\n\t\"provider.?returned.?(?:an.?)?error\",\n\t\"upstream_error_frame\",\n\t\"exceeded request buffer limit while retrying upstream\",\n\t// Gateway failure relaying the upstream response stream, sent as an OpenAI\n\t// Responses `response.failed` event without an error code (#10920).\n\t\"unable to forward upstream\",\n\n\t// Network, proxy, and fetch transport failures. This includes OpenAI Codex\n\t// raw-fetch failures such as \"upstream connect\", \"connection refused\", and\n\t// \"reset before headers\" (#733), plus OpenRouter connection drops (#3317).\n\t\"network.?error\",\n\t\"connection.?error\",\n\t\"connection.?refused\",\n\t\"connection.?lost\",\n\t\"other side closed\",\n\t\"fetch failed\",\n\t\"getaddrinfo\",\n\t\"ENOTFOUND\",\n\t\"EAI_AGAIN\",\n\t\"upstream.?connect\",\n\t\"reset before headers\",\n\t\"socket hang up\",\n\t\"socket connection was closed\",\n\t\"timed? out\",\n\t\"timeout\",\n\t\"terminated\",\n\n\t// WebSocket transports can report close/error text instead of HTTP/fetch text.\n\t\"websocket.?closed\",\n\t\"websocket.?error\",\n\n\t// Premature stream endings from SDKs and transports. Anthropic can throw\n\t// \"stream ended without ...\" and \"Anthropic stream ended before message_stop\"\n\t// (#4433); Bedrock/Smithy can throw an HTTP/2 no-response error (#3594).\n\t\"ended without\",\n\t\"stream ended before message_stop\",\n\t\"stream ended before a terminal response event\",\n\t\"http2 request did not get a response\",\n\t// Node ERR_HTTP2_STREAM_CANCEL: the HTTP/2 session died before the request was\n\t// sent, e.g. after the Bedrock SDK's 5-minute session timeout (#10379).\n\t\"pending stream has been canceled\",\n\n\t// Provider-requested retry delay cap failures should flow through the outer\n\t// retry policy so callers can surface/abort the backoff (#1123).\n\t\"retry delay\",\n\n\t// Explicit retry guidance emitted mid-stream by OpenAI Responses and Bedrock\n\t// stream exceptions (#6019).\n\t\"you can retry your request\",\n\t\"try your request again\",\n\t\"please retry your request\",\n\n\t// gRPC based providers (e.g. NVIDIA NIM)\n\t\"ResourceExhausted\",\n\n\t// Sign in with ChatGPT: usage or user data temporarily unavailable. Usage\n\t// failures can arrive mid-stream without an HTTP 503 in the message.\n\t\"subscription_sharing_usage_unavailable\",\n\t\"subscription_sharing_user_unavailable\",\n]);\n\n/**\n * Retry policy: bounded attempts with exponential backoff (`baseDelayMs * 2^(attempt-1)`).\n * `maxAgentDelayMs` caps each computed delay and defaults to 60 seconds.\n * Matches `settings.retry` (`enabled`, `maxRetries`, `baseDelayMs`, `maxAgentDelayMs`) in coding-agent; kept\n * here so the classifier and the policy-driven retry loop live together and stay reusable\n * by the SDK and other callers.\n */\nexport interface RetryPolicy {\n\tenabled: boolean;\n\t/** Max retry attempts (0 = no retries). The initial call never counts as a retry. */\n\tmaxRetries: number;\n\t/** Base delay in ms. Per-attempt delay is `baseDelayMs * 2^(attempt-1)` before jitter. */\n\tbaseDelayMs: number;\n\t/** Optional cap for agent-level retry delays in ms. Defaults to 60 seconds. */\n\tmaxAgentDelayMs?: number;\n}\n\nexport const DEFAULT_MAX_AGENT_RETRY_DELAY_MS = 60_000;\n\nexport function retryDelayMs(policy: Pick<RetryPolicy, \"baseDelayMs\" | \"maxAgentDelayMs\">, attempt: number): number {\n\tconst delay = policy.baseDelayMs * 2 ** Math.max(0, attempt - 1);\n\tconst safeDelay = Number.isSafeInteger(delay) ? delay : Number.MAX_SAFE_INTEGER;\n\treturn Math.min(safeDelay, policy.maxAgentDelayMs ?? DEFAULT_MAX_AGENT_RETRY_DELAY_MS);\n}\n\n/** Optional callbacks emitted by {@link retryAssistantCall} around each retry. */\nexport interface RetryCallbacks {\n\t/** Emitted before the backoff sleep of each retry attempt (1-indexed). */\n\tonRetryScheduled?: (\n\t\tattempt: number,\n\t\tmaxAttempts: number,\n\t\tdelayMs: number,\n\t\terrorMessage: string,\n\t) => void | Promise<void>;\n\t/** Emitted after the backoff sleep, immediately before the retried call starts. */\n\tonRetryAttemptStart?: () => void | Promise<void>;\n\t/** Emitted once when the loop ends: success if a later call completed normally. */\n\tonRetryFinished?: (success: boolean, attempt: number, finalError?: string) => void | Promise<void>;\n}\n\nclass RetrySleepAbortError extends Error {\n\tconstructor() {\n\t\tsuper(\"Aborted\");\n\t}\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(new RetrySleepAbortError());\n\t\t\treturn;\n\t\t}\n\t\tconst timeout = setTimeout(resolve, ms);\n\t\tsignal?.addEventListener(\n\t\t\t\"abort\",\n\t\t\t() => {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t\treject(new RetrySleepAbortError());\n\t\t\t},\n\t\t\t{ once: true },\n\t\t);\n\t});\n}\n\n/**\n * Run a single assistant-producing call with bounded retry on transient errors.\n *\n * Behavior:\n * - A successful response is returned immediately. Aborts are terminal and never\n * retried, but reported as unsuccessful if they happen after a retry was scheduled.\n * Aborts during the backoff sleep are normalized to an aborted `AssistantMessage`\n * too, so callers do not need to care when cancellation happened.\n * - A non-retryable error (per {@link isRetryableAssistantError}, including quota/\n * billing exhaustion) is returned immediately so deterministic errors fail fast.\n * - Otherwise retries up to `maxRetries` times with exponential backoff, emitting\n * `onRetryScheduled` before each sleep, `onRetryAttemptStart` after each sleep before\n * the retried call starts, and `onRetryFinished` once at the end (whether the loop\n * ends in success, exhausted retries, or an aborted backoff).\n *\n * When `policy` is undefined or disabled, the first response is returned unchanged\n * (equivalent to calling `produce()` directly).\n */\nexport async function retryAssistantCall(\n\tproduce: () => Promise<AssistantMessage>,\n\tpolicy: RetryPolicy | undefined,\n\tsignal: AbortSignal | undefined,\n\tcallbacks?: RetryCallbacks,\n): Promise<AssistantMessage> {\n\tconst maxAttempts = policy?.enabled ? policy.maxRetries : 0;\n\n\tlet attempt = 0;\n\tlet lastRetry: { attempt: number; errorMessage: string } | undefined;\n\tfor (;;) {\n\t\tconst response = await produce();\n\n\t\t// Abort: terminal but not successful. Never retry an aborted message.\n\t\tif (response.stopReason === \"aborted\") {\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(false, lastRetry.attempt);\n\t\t\treturn response;\n\t\t}\n\n\t\t// Success: non-error, non-abort responses return as-is.\n\t\tif (response.stopReason !== \"error\") {\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(true, lastRetry.attempt);\n\t\t\treturn response;\n\t\t}\n\n\t\t// Non-retryable, or budget exhausted: return the final error message.\n\t\tif (attempt >= maxAttempts || !isRetryableAssistantError(response)) {\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(false, lastRetry.attempt, response.errorMessage);\n\t\t\treturn response;\n\t\t}\n\n\t\tattempt++;\n\t\tlastRetry = { attempt, errorMessage: response.errorMessage || \"Unknown error\" };\n\t\tconst delayMs = retryDelayMs(policy!, attempt);\n\t\tawait callbacks?.onRetryScheduled?.(attempt, maxAttempts, delayMs, lastRetry.errorMessage);\n\n\t\t// Normalize aborts during retry backoff to the same AssistantMessage shape as\n\t\t// provider stream aborts, so callers do not need to care when cancellation happened.\n\t\ttry {\n\t\t\tawait sleep(delayMs, signal);\n\t\t} catch (error) {\n\t\t\tawait callbacks?.onRetryFinished?.(false, attempt, lastRetry.errorMessage);\n\t\t\tif (error instanceof RetrySleepAbortError) {\n\t\t\t\tconst { errorMessage: _errorMessage, ...rest } = response;\n\t\t\t\treturn { ...rest, stopReason: \"aborted\" };\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\tawait callbacks?.onRetryAttemptStart?.();\n\t}\n}\n\n/**\n * Classifies whether a failed assistant message looks like a transient provider\n * or transport error, so callers can decide if the last assistant turn should be\n * restarted.\n *\n * This does not implement retry policy. Callers should first handle context\n * overflow separately, then apply their own retry budget, backoff, and reporting\n * before restarting the assistant turn.\n */\nexport function isRetryableAssistantError(message: AssistantMessage): boolean {\n\tif (message.stopReason !== \"error\" || !message.errorMessage) return false;\n\tconst errorMessage = message.errorMessage;\n\tif (NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN.test(errorMessage)) return false;\n\treturn RETRYABLE_PROVIDER_ERROR_PATTERN.test(errorMessage);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"retry.js","sourceRoot":"","sources":["../../src/utils/retry.ts"],"names":[],"mappings":"AAEA,SAAS,yBAAyB,CAAC,QAA2B;IAC7D,OAAO,IAAI,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC;AAC5C,CAAC;AAED,MAAM,0CAA0C,GAAG,yBAAyB,CAAC;IAC5E,8EAA8E;IAC9E,2EAA2E;IAC3E,mBAAmB;IACnB,qBAAqB;IAErB,6EAA6E;IAC7E,yDAAyD;IACzD,6BAA6B;IAC7B,mBAAmB;IAEnB,4EAA4E;IAC5E,4EAA4E;IAC5E,oBAAoB;IACpB,eAAe;IACf,gBAAgB;IAChB,SAAS;IAET,4EAA4E;IAC5E,mCAAmC;IACnC,2CAA2C;CAC3C,CAAC,CAAC;AAEH,MAAM,gCAAgC,GAAG,yBAAyB,CAAC;IAClE,0EAA0E;IAC1E,YAAY;IACZ,aAAa;IACb,4BAA4B;IAC5B,oCAAoC;IACpC,sBAAsB;IACtB,aAAa;IACb,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K,YAAY,oBAAoB,EAAE,CAAC;gBAC3C,MAAM,EAAE,YAAY,EAAE,aAAa,EAAE,GAAG,IAAI,EAAE,GAAG,QAAQ,CAAC;gBAC1D,OAAO,EAAE,GAAG,IAAI,EAAE,UAAU,EAAE,SAAS,EAAE,CAAC;YAC3C,CAAC;YACD,MAAM,KAAK,CAAC;QACb,CAAC;QACD,MAAM,SAAS,EAAE,mBAAmB,EAAE,EAAE,CAAC;IAC1C,CAAC;AACF,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,yBAAyB,CAAC,OAAyB;IAClE,IAAI,OAAO,CAAC,UAAU,KAAK,OAAO,IAAI,CAAC,OAAO,CAAC,YAAY;QAAE,OAAO,KAAK,CAAC;IAC1E,MAAM,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC;IAC1C,IAAI,0CAA0C,CAAC,IAAI,CAAC,YAAY,CAAC;QAAE,OAAO,KAAK,CAAC;IAChF,OAAO,gCAAgC,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;AAC5D,CAAC;AAED,8EAA8E;AAC9E,6EAA6E;AAC7E,iFAAiF;AACjF,gFAAgF;AAChF,8EAA8E;AAC9E,uEAAuE;AACvE,MAAM,gCAAgC,GAAG,yBAAyB,CAAC;IAClE,aAAa;IACb,WAAW;IACX,WAAW;IACX,cAAc;IACd,aAAa;IACb,UAAU;IACV,cAAc;IACd,eAAe;IACf,yBAAyB;IACzB,uBAAuB;IACvB,8CAA8C;IAC9C,qBAAqB;IACrB,4BAA4B;CAC5B,CAAC,CAAC;AAEH;;;;GAIG;AACH,MAAM,UAAU,iCAAiC,CAAC,OAAyB;IAC1E,OAAO,yBAAyB,CAAC,OAAO,CAAC,IAAI,gCAAgC,CAAC,IAAI,CAAC,OAAO,CAAC,YAAa,CAAC,CAAC;AAC3G,CAAC","sourcesContent":["import type { AssistantMessage } from \"../types.ts\";\n\nfunction buildProviderErrorPattern(patterns: readonly string[]): RegExp {\n\treturn new RegExp(patterns.join(\"|\"), \"i\");\n}\n\nconst NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN = buildProviderErrorPattern([\n\t// OpenCode Go/free-tier limits returned as 429 JSON error types by OpenCode's\n\t// Zen API. These are subscription/account limits, not transient throttles.\n\t\"GoUsageLimitError\",\n\t\"FreeUsageLimitError\",\n\n\t// OpenCode Go subscription-limit text asks users to enable available-balance\n\t// usage after rolling/weekly/monthly limits are reached.\n\t\"Monthly usage limit reached\",\n\t\"available balance\",\n\n\t// Generic quota/budget/billing exhaustion. `insufficient_quota` is OpenAI's\n\t// quota/billing error code; the other strings cover common gateway wording.\n\t\"insufficient_quota\",\n\t\"out of budget\",\n\t\"quota exceeded\",\n\t\"billing\",\n\n\t// Sign in with ChatGPT: the subscription's shared usage limit, which resets\n\t// after hours rather than seconds.\n\t\"subscription_sharing_usage_limit_exceeded\",\n]);\n\nconst RETRYABLE_PROVIDER_ERROR_PATTERN = buildProviderErrorPattern([\n\t// Generic provider load, HTTP status, and server-side transient failures.\n\t\"overloaded\",\n\t\"server_busy\",\n\t\"servers are currently busy\",\n\t\"currently experiencing high demand\",\n\t\"model is at capacity\",\n\t\"rate.?limit\",\n\t\"too many requests\",\n\t\"429\",\n\t\"500\",\n\t\"502\",\n\t\"503\",\n\t\"504\",\n\t\"520\",\n\t\"524\",\n\t// Also matches \"The service is temporarily unavailable\" (#10965).\n\t\"service.?(?:is.?)?(?:temporarily.?)?unavailable\",\n\t\"server.?error\",\n\t\"internal.?error\",\n\n\t// Wrapper/provider text for transient upstream failures, including OpenRouter\n\t// \"Provider returned error\" responses (#2264), gateway wording such as\n\t// \"The upstream provider returned an error\" (#10842), and Qoder's sanitized\n\t// SSE error frame. The outer retry loop owns the bounded retry budget.\n\t\"provider.?returned.?(?:an.?)?error\",\n\t\"upstream_error_frame\",\n\t\"exceeded request buffer limit while retrying upstream\",\n\t// Gateway failure relaying the upstream response stream, sent as an OpenAI\n\t// Responses `response.failed` event without an error code (#10920).\n\t\"unable to forward upstream\",\n\n\t// Network, proxy, and fetch transport failures. This includes OpenAI Codex\n\t// raw-fetch failures such as \"upstream connect\", \"connection refused\", and\n\t// \"reset before headers\" (#733), plus OpenRouter connection drops (#3317).\n\t\"network.?error\",\n\t\"connection.?error\",\n\t\"connection.?failed\",\n\t\"connection.?refused\",\n\t\"connection.?lost\",\n\t\"other side closed\",\n\t\"fetch failed\",\n\t\"getaddrinfo\",\n\t\"ENOTFOUND\",\n\t\"EAI_AGAIN\",\n\t\"ECONNREFUSED\",\n\t\"ENETUNREACH\",\n\t\"ENETDOWN\",\n\t\"EHOSTUNREACH\",\n\t\"upstream.?connect\",\n\t\"reset before headers\",\n\t\"socket hang up\",\n\t\"socket connection was closed\",\n\t\"timed? out\",\n\t\"timeout\",\n\t\"terminated\",\n\n\t// WebSocket transports can report close/error text instead of HTTP/fetch text.\n\t\"websocket.?closed\",\n\t\"websocket.?error\",\n\n\t// Premature stream endings from SDKs and transports. Anthropic can throw\n\t// \"stream ended without ...\" and \"Anthropic stream ended before message_stop\"\n\t// (#4433); Bedrock/Smithy can throw an HTTP/2 no-response error (#3594).\n\t\"ended without\",\n\t\"stream ended before message_stop\",\n\t\"stream ended before a terminal response event\",\n\t\"http2 request did not get a response\",\n\t// Node ERR_HTTP2_STREAM_CANCEL: the HTTP/2 session died before the request was\n\t// sent, e.g. after the Bedrock SDK's 5-minute session timeout (#10379).\n\t\"pending stream has been canceled\",\n\n\t// Provider-requested retry delay cap failures should flow through the outer\n\t// retry policy so callers can surface/abort the backoff (#1123).\n\t\"retry delay\",\n\n\t// Explicit retry guidance emitted mid-stream by OpenAI Responses and Bedrock\n\t// stream exceptions (#6019).\n\t\"you can retry your request\",\n\t\"try your request again\",\n\t\"please retry your request\",\n\n\t// gRPC based providers (e.g. NVIDIA NIM)\n\t\"ResourceExhausted\",\n\n\t// Sign in with ChatGPT: usage or user data temporarily unavailable. Usage\n\t// failures can arrive mid-stream without an HTTP 503 in the message.\n\t\"subscription_sharing_usage_unavailable\",\n\t\"subscription_sharing_user_unavailable\",\n]);\n\n/**\n * Retry policy: bounded attempts with exponential backoff (`baseDelayMs * 2^(attempt-1)`).\n * `maxAgentDelayMs` caps each computed delay and defaults to 60 seconds.\n * Matches `settings.retry` (`enabled`, `maxRetries`, `baseDelayMs`, `maxAgentDelayMs`) in coding-agent; kept\n * here so the classifier and the policy-driven retry loop live together and stay reusable\n * by the SDK and other callers.\n */\nexport interface RetryPolicy {\n\tenabled: boolean;\n\t/** Max retry attempts (0 = no retries). The initial call never counts as a retry. */\n\tmaxRetries: number;\n\t/** Base delay in ms. Per-attempt delay is `baseDelayMs * 2^(attempt-1)` before jitter. */\n\tbaseDelayMs: number;\n\t/** Optional cap for agent-level retry delays in ms. Defaults to 60 seconds. */\n\tmaxAgentDelayMs?: number;\n}\n\nexport const DEFAULT_MAX_AGENT_RETRY_DELAY_MS = 60_000;\n\nexport function retryDelayMs(policy: Pick<RetryPolicy, \"baseDelayMs\" | \"maxAgentDelayMs\">, attempt: number): number {\n\tconst delay = policy.baseDelayMs * 2 ** Math.max(0, attempt - 1);\n\tconst safeDelay = Number.isSafeInteger(delay) ? delay : Number.MAX_SAFE_INTEGER;\n\treturn Math.min(safeDelay, policy.maxAgentDelayMs ?? DEFAULT_MAX_AGENT_RETRY_DELAY_MS);\n}\n\n/** Optional callbacks emitted by {@link retryAssistantCall} around each retry. */\nexport interface RetryCallbacks {\n\t/** Emitted before the backoff sleep of each retry attempt (1-indexed). */\n\tonRetryScheduled?: (\n\t\tattempt: number,\n\t\tmaxAttempts: number,\n\t\tdelayMs: number,\n\t\terrorMessage: string,\n\t) => void | Promise<void>;\n\t/** Emitted after the backoff sleep, immediately before the retried call starts. */\n\tonRetryAttemptStart?: () => void | Promise<void>;\n\t/** Emitted once when the loop ends: success if a later call completed normally. */\n\tonRetryFinished?: (success: boolean, attempt: number, finalError?: string) => void | Promise<void>;\n}\n\nclass RetrySleepAbortError extends Error {\n\tconstructor() {\n\t\tsuper(\"Aborted\");\n\t}\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(new RetrySleepAbortError());\n\t\t\treturn;\n\t\t}\n\t\tconst timeout = setTimeout(resolve, ms);\n\t\tsignal?.addEventListener(\n\t\t\t\"abort\",\n\t\t\t() => {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t\treject(new RetrySleepAbortError());\n\t\t\t},\n\t\t\t{ once: true },\n\t\t);\n\t});\n}\n\n/**\n * Run a single assistant-producing call with bounded retry on transient errors.\n *\n * Behavior:\n * - A successful response is returned immediately. Aborts are terminal and never\n * retried, but reported as unsuccessful if they happen after a retry was scheduled.\n * Aborts during the backoff sleep are normalized to an aborted `AssistantMessage`\n * too, so callers do not need to care when cancellation happened.\n * - A non-retryable error (per {@link isRetryableAssistantError}, including quota/\n * billing exhaustion) is returned immediately so deterministic errors fail fast.\n * - Otherwise retries up to `maxRetries` times with exponential backoff, emitting\n * `onRetryScheduled` before each sleep, `onRetryAttemptStart` after each sleep before\n * the retried call starts, and `onRetryFinished` once at the end (whether the loop\n * ends in success, exhausted retries, or an aborted backoff).\n *\n * When `policy` is undefined or disabled, the first response is returned unchanged\n * (equivalent to calling `produce()` directly).\n */\nexport async function retryAssistantCall(\n\tproduce: () => Promise<AssistantMessage>,\n\tpolicy: RetryPolicy | undefined,\n\tsignal: AbortSignal | undefined,\n\tcallbacks?: RetryCallbacks,\n): Promise<AssistantMessage> {\n\tconst maxAttempts = policy?.enabled ? policy.maxRetries : 0;\n\n\tlet attempt = 0;\n\tlet lastRetry: { attempt: number; errorMessage: string } | undefined;\n\tfor (;;) {\n\t\tconst response = await produce();\n\n\t\t// Abort: terminal but not successful. Never retry an aborted message.\n\t\tif (response.stopReason === \"aborted\") {\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(false, lastRetry.attempt);\n\t\t\treturn response;\n\t\t}\n\n\t\t// Success: non-error, non-abort responses return as-is.\n\t\tif (response.stopReason !== \"error\") {\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(true, lastRetry.attempt);\n\t\t\treturn response;\n\t\t}\n\n\t\t// Non-retryable, or budget exhausted: return the final error message.\n\t\tif (attempt >= maxAttempts || !isRetryableAssistantError(response)) {\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(false, lastRetry.attempt, response.errorMessage);\n\t\t\treturn response;\n\t\t}\n\n\t\tattempt++;\n\t\tlastRetry = { attempt, errorMessage: response.errorMessage || \"Unknown error\" };\n\t\tconst delayMs = retryDelayMs(policy!, attempt);\n\t\tawait callbacks?.onRetryScheduled?.(attempt, maxAttempts, delayMs, lastRetry.errorMessage);\n\n\t\t// Normalize aborts during retry backoff to the same AssistantMessage shape as\n\t\t// provider stream aborts, so callers do not need to care when cancellation happened.\n\t\ttry {\n\t\t\tawait sleep(delayMs, signal);\n\t\t} catch (error) {\n\t\t\tawait callbacks?.onRetryFinished?.(false, attempt, lastRetry.errorMessage);\n\t\t\tif (error instanceof RetrySleepAbortError) {\n\t\t\t\tconst { errorMessage: _errorMessage, ...rest } = response;\n\t\t\t\treturn { ...rest, stopReason: \"aborted\" };\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\tawait callbacks?.onRetryAttemptStart?.();\n\t}\n}\n\n/**\n * Classifies whether a failed assistant message looks like a transient provider\n * or transport error, so callers can decide if the last assistant turn should be\n * restarted.\n *\n * This does not implement retry policy. Callers should first handle context\n * overflow separately, then apply their own retry budget, backoff, and reporting\n * before restarting the assistant turn.\n */\nexport function isRetryableAssistantError(message: AssistantMessage): boolean {\n\tif (message.stopReason !== \"error\" || !message.errorMessage) return false;\n\tconst errorMessage = message.errorMessage;\n\tif (NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN.test(errorMessage)) return false;\n\treturn RETRYABLE_PROVIDER_ERROR_PATTERN.test(errorMessage);\n}\n\n// Failures that prove the request never reached the provider: DNS, refused or\n// unroutable connects, connect timeouts, and proxy tunnel/TLS setup failures\n// (providers append these as \"(caused by: ...)\", see `withConnectFailureCause`).\n// Like Codex's connect-only rule, an opaque \"fetch failed\" or a reset after the\n// request was sent is excluded: it may already be processed and billed, so it\n// keeps the bounded retry budget, as do mid-stream drops and timeouts.\nconst CONNECTION_FAILURE_ERROR_PATTERN = buildProviderErrorPattern([\n\t\"getaddrinfo\",\n\t\"ENOTFOUND\",\n\t\"EAI_AGAIN\",\n\t\"ECONNREFUSED\",\n\t\"ENETUNREACH\",\n\t\"ENETDOWN\",\n\t\"EHOSTUNREACH\",\n\t\"EADDRNOTAVAIL\",\n\t\"UND_ERR_CONNECT_TIMEOUT\",\n\t\"Connect Timeout Error\",\n\t\"before secure TLS connection was established\",\n\t\"when HTTP Tunneling\",\n\t\"^Qoder: connection_failed$\",\n]);\n\n/**\n * Whether a retryable failure means the provider could not be reached at all.\n * Callers may keep retrying these without consuming the bounded retry budget,\n * waiting for connectivity until the user cancels.\n */\nexport function isConnectionFailureAssistantError(message: AssistantMessage): boolean {\n\treturn isRetryableAssistantError(message) && CONNECTION_FAILURE_ERROR_PATTERN.test(message.errorMessage!);\n}\n"]}
|
|
@@ -102,6 +102,6 @@
|
|
|
102
102
|
"rotomFork": {
|
|
103
103
|
"upstream": "https://github.com/earendil-works/pi",
|
|
104
104
|
"revision": "71023aec1546d6d677a65669c5665c0927ce0dd0",
|
|
105
|
-
"sourceSha256": "
|
|
105
|
+
"sourceSha256": "4d29bfc5fb6e95f198de675f2ebcaed9e1f4a6b730c0a480ec0f057fc954ada6"
|
|
106
106
|
}
|
|
107
107
|
}
|
|
@@ -73,6 +73,6 @@
|
|
|
73
73
|
"rotomFork": {
|
|
74
74
|
"upstream": "https://github.com/earendil-works/pi",
|
|
75
75
|
"revision": "71023aec1546d6d677a65669c5665c0927ce0dd0",
|
|
76
|
-
"sourceSha256": "
|
|
76
|
+
"sourceSha256": "4d29bfc5fb6e95f198de675f2ebcaed9e1f4a6b730c0a480ec0f057fc954ada6"
|
|
77
77
|
}
|
|
78
78
|
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
+
import{ANTHROPIC_FEDERATION_RULE_ID_ENV,ANTHROPIC_IDENTITY_TOKEN_FILE_ENV,ANTHROPIC_ORGANIZATION_ID_ENV,ANTHROPIC_SERVICE_ACCOUNT_ID_ENV,ANTHROPIC_WORKSPACE_ID_ENV}from"./chunk-22CYIUS4.js";import{buildCopilotDynamicHeaders,hasCopilotVisionInput}from"./chunk-PGXDEOVV.js";import{Anthropic}from"./chunk-F5ZABL6Z.js";import{retryProviderRequest}from"./chunk-PMRZO46Y.js";import{withConnectFailureCause}from"./chunk-CTEAMRDY.js";import{adjustMaxTokensForThinking,buildBaseOptions,clampMaxTokensToContext,getJsonSchemaToolParameters,getPiUserAgent,resolveJsonSchemaStrictSampling,splitErrorToolResultImages,transformMessages}from"./chunk-2JW42LFQ.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{headersToRecord}from"./chunk-UTB4DTYQ.js";import{getProviderEnvValue}from"./chunk-DRQDKNXA.js";import{parseJsonWithRepair,parseStreamingJson,parseToolCallArguments}from"./chunk-PYGXRV27.js";import{calculateCost,getCurrentTools,getInitialSystemMessage,getSystemMessageText,renderSystemMessageUpdate,resolveTranscript}from"./chunk-HACVPRBJ.js";import{AssistantMessageEventStream,appendAssistantMessageDiagnostic}from"./chunk-LPXNMA2W.js";import"./chunk-4L3WN2XY.js";function resolveCacheRetention(cacheRetention,env){return cacheRetention||(getProviderEnvValue("PI_CACHE_RETENTION",env)==="long"?"long":"short")}function getCacheControl(model,cacheRetention,env){let retention=resolveCacheRetention(cacheRetention,env);if(retention==="none")return{retention};let ttl=retention==="long"&&getAnthropicCompat(model).supportsLongCacheRetention?"1h":void 0;return{retention,cacheControl:{type:"ephemeral",...ttl&&{ttl}}}}var claudeCodeVersion="2.1.280",claudeCodeTools=["Read","Write","Edit","Bash","Grep","Glob","AskUserQuestion","EnterPlanMode","ExitPlanMode","KillShell","NotebookEdit","Skill","Task","TaskOutput","TodoWrite","WebFetch","WebSearch"],ccToolLookup=new Map(claudeCodeTools.map(t=>[t.toLowerCase(),t])),toClaudeCodeName=name=>ccToolLookup.get(name.toLowerCase())??name,fromClaudeCodeName=(name,tools)=>{if(tools&&tools.length>0){let lowerName=name.toLowerCase(),matchedTool=tools.find(tool=>tool.name.toLowerCase()===lowerName);if(matchedTool)return matchedTool.name}return name};function convertImageBlock(image){return{type:"image",source:{type:"base64",media_type:image.mimeType,data:image.data}}}function convertContentBlocks(content){if(!content.some(c=>c.type==="image"))return sanitizeSurrogates(content.map(c=>c.text).join(`
|
|
3
|
+
`));let blocks=content.map(block=>block.type==="text"?{type:"text",text:sanitizeSurrogates(block.text)}:convertImageBlock(block));return blocks.some(b=>b.type==="text")||blocks.unshift({type:"text",text:"(see attached image)"}),blocks}var FINE_GRAINED_TOOL_STREAMING_BETA="fine-grained-tool-streaming-2025-05-14",INTERLEAVED_THINKING_BETA="interleaved-thinking-2025-05-14",SERVER_SIDE_FALLBACK_BETA="server-side-fallback-2026-07-01",MID_CONVERSATION_OUTPUT_CONFIG_BETA="mid-conversation-output-config-2026-07-01",THINKING_BINDING_CONTROLS_BETA="thinking-binding-controls-2026-08-01",INLINE_TOOLS_BETA="inline-tools-2026-09-15",DEFERRED_TOOL_PLACEHOLDER={name:"__pi_deferred_placeholder__",description:"Reserved placeholder. Never available. Never call this.",input_schema:{type:"object",properties:{},required:[]},defer_loading:!0};function shouldUseServerSideFallbackBeta(model){return(model.compat?.allowedFallbackModels?.length??0)>0}function getAnthropicCompat(model){let isOpenRouter=model.provider==="openrouter"||model.baseUrl.includes("openrouter.ai");return{supportsEagerToolInputStreaming:model.compat?.supportsEagerToolInputStreaming??!0,supportsLongCacheRetention:model.compat?.supportsLongCacheRetention??!0,sendSessionAffinityHeaders:model.compat?.sendSessionAffinityHeaders??isOpenRouter,sessionAffinityFormat:model.compat?.sessionAffinityFormat??(isOpenRouter?"openrouter":void 0),supportsCacheControlOnTools:model.compat?.supportsCacheControlOnTools??!0,supportsTemperature:model.compat?.supportsTemperature??!0,allowEmptySignature:model.compat?.allowEmptySignature??!1,supportsStrictTools:model.compat?.supportsStrictTools??!1,supportsMidConvoSystemMessages:model.compat?.supportsMidConvoSystemMessages??!1,supportsMidConvoToolChanges:model.compat?.supportsMidConvoToolChanges??!1}}function mergeHeaders(...headerSources){let merged={};for(let headers of headerSources)headers&&Object.assign(merged,headers);return merged}function mergeClientHeaders(...headerSources){return mergeHeaders({"User-Agent":getPiUserAgent()},...headerSources)}function hasHeader(headers,name){if(!headers)return!1;let expected=name.toLowerCase();for(let[key,value]of Object.entries(headers))if(key.toLowerCase()===expected&&value!==null&&value.trim().length>0)return!0;return!1}function hasRequestAuth(apiKey,headers){return!!apiKey||hasHeader(headers,"authorization")||hasHeader(headers,"x-api-key")||hasHeader(headers,"cf-aig-authorization")}function assertRequestAuth(provider,apiKey,headers){if(!hasRequestAuth(apiKey,headers))throw new Error(`No API key for provider: ${provider}`)}var PiAnthropic=class extends Anthropic{_shouldResolveDefaultCredentials(){return!1}};function getAnthropicFederation(model,apiKey,headers,env){if(model.provider!=="anthropic"||hasRequestAuth(apiKey,headers))return;let federationRuleId=getProviderEnvValue(ANTHROPIC_FEDERATION_RULE_ID_ENV,env),organizationId=getProviderEnvValue(ANTHROPIC_ORGANIZATION_ID_ENV,env),identityTokenFile=getProviderEnvValue(ANTHROPIC_IDENTITY_TOKEN_FILE_ENV,env);if(!(!federationRuleId||!organizationId||!identityTokenFile))return{organization_id:organizationId,workspace_id:getProviderEnvValue(ANTHROPIC_WORKSPACE_ID_ENV,env),authentication:{type:"oidc_federation",federation_rule_id:federationRuleId,service_account_id:getProviderEnvValue(ANTHROPIC_SERVICE_ACCOUNT_ID_ENV,env),identity_token:{source:"file",path:identityTokenFile}}}}var federationClient,ANTHROPIC_MESSAGE_EVENTS=new Set(["message_start","message_delta","message_stop","content_block_start","content_block_delta","content_block_stop"]);function flushSseEvent(state){if(!state.event&&state.data.length===0)return null;let event={event:state.event,data:state.data.join(`
|
|
4
|
+
`),raw:[...state.raw]};return state.event=null,state.data=[],state.raw=[],event}function decodeSseLine(line,state){if(line==="")return flushSseEvent(state);if(state.raw.push(line),line.startsWith(":"))return null;let delimiterIndex=line.indexOf(":"),fieldName=delimiterIndex===-1?line:line.slice(0,delimiterIndex),value=delimiterIndex===-1?"":line.slice(delimiterIndex+1);return value.startsWith(" ")&&(value=value.slice(1)),fieldName==="event"?state.event=value:fieldName==="data"&&state.data.push(value),null}function nextLineBreakIndex(text){let carriageReturnIndex=text.indexOf("\r"),newlineIndex=text.indexOf(`
|
|
5
|
+
`);return carriageReturnIndex===-1?newlineIndex:newlineIndex===-1?carriageReturnIndex:Math.min(carriageReturnIndex,newlineIndex)}function consumeLine(text){let lineBreakIndex=nextLineBreakIndex(text);if(lineBreakIndex===-1)return null;let nextIndex=lineBreakIndex+1;return text[lineBreakIndex]==="\r"&&text[nextIndex]===`
|
|
6
|
+
`&&(nextIndex+=1),{line:text.slice(0,lineBreakIndex),rest:text.slice(nextIndex)}}async function*iterateSseMessages(body,signal){let reader=body.getReader(),decoder=new TextDecoder,state={event:null,data:[],raw:[]},buffer="";try{for(;;){if(signal?.aborted)throw new Error("Request was aborted");let{value,done}=await reader.read();if(done)break;buffer+=decoder.decode(value,{stream:!0});let consumed2=consumeLine(buffer);for(;consumed2;){buffer=consumed2.rest;let event=decodeSseLine(consumed2.line,state);event&&(yield event),consumed2=consumeLine(buffer)}}buffer+=decoder.decode();let consumed=consumeLine(buffer);for(;consumed;){buffer=consumed.rest;let event=decodeSseLine(consumed.line,state);event&&(yield event),consumed=consumeLine(buffer)}if(buffer.length>0){let event=decodeSseLine(buffer,state);event&&(yield event)}let trailingEvent=flushSseEvent(state);trailingEvent&&(yield trailingEvent)}finally{reader.releaseLock()}}async function*iterateAnthropicEvents(response,signal){if(!response.body)throw new Error("Attempted to iterate over an Anthropic response with no body");let sawMessageStart=!1,sawMessageEnd=!1;for await(let sse of iterateSseMessages(response.body,signal)){if(sse.event==="error")throw new Error(sse.data);if(ANTHROPIC_MESSAGE_EVENTS.has(sse.event??""))try{let event=parseJsonWithRepair(sse.data);event.type==="message_start"?sawMessageStart=!0:event.type==="message_stop"&&(sawMessageEnd=!0),yield event}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`Could not parse Anthropic SSE event ${sse.event}: ${message}; data=${sse.data}; raw=${sse.raw.join("\\n")}`)}}if(sawMessageStart&&!sawMessageEnd)throw new Error("Anthropic stream ended before message_stop")}var stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=resolveTranscript(context,getAnthropicCompat(model).supportsMidConvoSystemMessages),currentTools=getCurrentTools(normalizedContext.messages);return(async()=>{let output={role:"assistant",content:[],api:model.api,provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{let client,isOAuth,usageModel=model,inputTransformations;if(options?.client)client=options.client,isOAuth=!1;else{let apiKey=options?.apiKey,federation=getAnthropicFederation(model,apiKey,options?.headers,options?.env);federation||assertRequestAuth(model.provider,apiKey,options?.headers);let copilotDynamicHeaders;if(model.provider==="github-copilot"){let hasImages=hasCopilotVisionInput(normalizedContext.messages);copilotDynamicHeaders=buildCopilotDynamicHeaders({messages:normalizedContext.messages,hasImages})}let cacheSessionId=resolveCacheRetention(options?.cacheRetention,options?.env)==="none"?void 0:options?.sessionId,created=createClient(model,apiKey,options?.headers,options?.fetch,copilotDynamicHeaders,cacheSessionId,federation);client=created.client,isOAuth=created.isOAuthToken}let requestOptions={...options?.signal?{signal:options.signal}:{},...options?.timeoutMs!==void 0?{timeout:options.timeoutMs}:{},maxRetries:0},disablePreferredStrictTools=!1,response;for(;;){options?.signal?.throwIfAborted();let built=buildParams(model,normalizedContext,isOAuth,options,disablePreferredStrictTools);built.providerThinkingLevel&&(output.providerThinkingLevel=built.providerThinkingLevel);let params=built.params,nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params={...nextParams,stream:!0});try{response=await retryProviderRequest(()=>client.beta.messages.create(params,requestOptions).asResponse(),{maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,signal:options?.signal});break}catch(error){if(options?.signal?.aborted||disablePreferredStrictTools||!built.hasPreferredStrictTools||!(error instanceof Anthropic.APIError)||error.status!==400||error.type!=="invalid_request_error"||!["The compiled grammar is too large","Too many strict tools (","Schemas contains too many parameters with union types ("].some(message=>error.message.includes(message)))throw error;disablePreferredStrictTools=!0,appendAssistantMessageDiagnostic(output,{type:"anthropic_strict_tools_fallback",timestamp:Date.now(),error:{message:error.message},details:{reason:"strict_tool_limits_exceeded"}})}}await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),stream2.push({type:"start",partial:output});let blocks=output.content;for await(let event of iterateAnthropicEvents(response,options?.signal))if(await options?.onProviderStreamEvent?.(event,model),event.type==="message_start"){output.responseId=event.message.id;let transformations=event.message.input_transformations;Array.isArray(transformations)&&(inputTransformations=transformations);let responseModel=event.message.model;responseModel!==model.id&&(output.responseModel=responseModel);let fallbackCost=responseModel===model.id?void 0:model.compat?.allowedFallbackModels?.find(fallback=>fallback.provider===model.provider&&fallback.model===responseModel)?.cost;usageModel=fallbackCost?{...model,id:responseModel,cost:fallbackCost}:model,output.usage.input=event.message.usage.input_tokens||0,output.usage.output=event.message.usage.output_tokens||0,output.usage.cacheRead=event.message.usage.cache_read_input_tokens||0,output.usage.cacheWrite=event.message.usage.cache_creation_input_tokens||0,output.usage.cacheWrite1h=event.message.usage.cache_creation?.ephemeral_1h_input_tokens||0,output.usage.totalTokens=output.usage.input+output.usage.output+output.usage.cacheRead+output.usage.cacheWrite,calculateCost(usageModel,output.usage)}else if(event.type==="content_block_start"){if(event.content_block.type==="fallback"){if(output.content.length>0)throw new Error("Anthropic performed an unsupported mid-output model fallback");continue}if(event.content_block.type==="text"){let block={type:"text",text:event.content_block.text??"",index:event.index};output.content.push(block),stream2.push({type:"text_start",contentIndex:output.content.length-1,partial:output})}else if(event.content_block.type==="thinking"){let block={type:"thinking",thinking:event.content_block.thinking??"",thinkingSignature:event.content_block.signature??"",index:event.index};output.content.push(block),stream2.push({type:"thinking_start",contentIndex:output.content.length-1,partial:output})}else if(event.content_block.type==="redacted_thinking"){let block={type:"thinking",thinking:"[Reasoning redacted]",thinkingSignature:event.content_block.data,redacted:!0,index:event.index};output.content.push(block),stream2.push({type:"thinking_start",contentIndex:output.content.length-1,partial:output})}else if(event.content_block.type==="tool_use"){let block={type:"toolCall",id:event.content_block.id,name:isOAuth?fromClaudeCodeName(event.content_block.name,currentTools):event.content_block.name,arguments:event.content_block.input??{},partialJson:"",index:event.index};output.content.push(block),stream2.push({type:"toolcall_start",contentIndex:output.content.length-1,partial:output})}}else if(event.type==="content_block_delta"){if(event.delta.type==="text_delta"){let index=blocks.findIndex(b=>b.index===event.index),block=blocks[index];block&&block.type==="text"&&(block.text+=event.delta.text,stream2.push({type:"text_delta",contentIndex:index,delta:event.delta.text,partial:output}))}else if(event.delta.type==="thinking_delta"){let index=blocks.findIndex(b=>b.index===event.index),block=blocks[index];block&&block.type==="thinking"&&(block.thinking+=event.delta.thinking,stream2.push({type:"thinking_delta",contentIndex:index,delta:event.delta.thinking,partial:output}))}else if(event.delta.type==="input_json_delta"){let index=blocks.findIndex(b=>b.index===event.index),block=blocks[index];block&&block.type==="toolCall"&&(block.partialJson+=event.delta.partial_json,block.arguments=parseStreamingJson(block.partialJson),stream2.push({type:"toolcall_delta",contentIndex:index,delta:event.delta.partial_json,partial:output}))}else if(event.delta.type==="signature_delta"){let index=blocks.findIndex(b=>b.index===event.index),block=blocks[index];block&&block.type==="thinking"&&(block.thinkingSignature=block.thinkingSignature||"",block.thinkingSignature+=event.delta.signature)}}else if(event.type==="content_block_stop"){let index=blocks.findIndex(b=>b.index===event.index),block=blocks[index];block&&(delete block.index,block.type==="text"?stream2.push({type:"text_end",contentIndex:index,content:block.text,partial:output}):block.type==="thinking"?stream2.push({type:"thinking_end",contentIndex:index,content:block.thinking,partial:output}):block.type==="toolCall"&&(Object.assign(block,parseToolCallArguments(block.partialJson)),delete block.partialJson,stream2.push({type:"toolcall_end",contentIndex:index,toolCall:block,partial:output})))}else if(event.type==="message_delta"){let transformations=event.input_transformations;if(Array.isArray(transformations)&&(inputTransformations=transformations),event.delta.stop_reason){output.rawStopReason=event.delta.stop_reason;let stopReasonResult=mapStopReason(event.delta.stop_reason,event.delta.stop_details);output.stopReason=stopReasonResult.stopReason,stopReasonResult.errorMessage&&(output.errorMessage=stopReasonResult.errorMessage)}if(event.usage){event.usage.input_tokens!=null&&(output.usage.input=event.usage.input_tokens),event.usage.output_tokens!=null&&(output.usage.output=event.usage.output_tokens),event.usage.cache_read_input_tokens!=null&&(output.usage.cacheRead=event.usage.cache_read_input_tokens),event.usage.cache_creation_input_tokens!=null&&(output.usage.cacheWrite=event.usage.cache_creation_input_tokens);let cacheCreation=event.usage.cache_creation;cacheCreation?.ephemeral_1h_input_tokens!=null&&(output.usage.cacheWrite1h=cacheCreation.ephemeral_1h_input_tokens);let thinkingTokens=event.usage.output_tokens_details?.thinking_tokens;thinkingTokens!=null&&(output.usage.reasoning=thinkingTokens)}output.usage.totalTokens=output.usage.input+output.usage.output+output.usage.cacheRead+output.usage.cacheWrite,calculateCost(usageModel,output.usage)}if(options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Anthropic stream ended without a stop reason");if(output.stopReason==="aborted"||output.stopReason==="error")throw new Error(output.errorMessage||"An unknown error occurred");inputTransformations&&inputTransformations.length>0&&appendAssistantMessageDiagnostic(output,{type:"anthropic_input_transformations",timestamp:Date.now(),details:{transformations:inputTransformations.map(transformation=>({type:transformation.type??void 0,path:transformation.path??void 0,reason:transformation.reason??void 0}))}}),stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)delete block.index,delete block.partialJson;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=error instanceof Error?withConnectFailureCause(error.message,error):JSON.stringify(error),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2};function mapThinkingLevelToEffort(model,level){let mapped=level?model.thinkingLevelMap?.[level]:void 0;if(typeof mapped=="string")return mapped;switch(level){case"minimal":case"low":return"low";case"medium":return"medium";case"high":return"high";default:return"high"}}var streamSimple=(model,context,options)=>{getAnthropicFederation(model,options?.apiKey,options?.headers,options?.env)||assertRequestAuth(model.provider,options?.apiKey,options?.headers);let base={...buildBaseOptions(model,context,options,options?.apiKey),toolChoice:options?.toolChoice};if(!options?.reasoning)return stream(model,context,{...base,thinkingEnabled:!1});if(model.compat?.forceAdaptiveThinking===!0){let effort=mapThinkingLevelToEffort(model,options.reasoning);return stream(model,context,{...base,thinkingEnabled:!0,effort})}let adjusted=adjustMaxTokensForThinking(base.maxTokens,model.maxTokens,options.reasoning,options.thinkingBudgets),maxTokens=clampMaxTokensToContext(model,context,adjusted.maxTokens);return stream(model,context,{...base,maxTokens,thinkingEnabled:!0,thinkingBudgetTokens:Math.min(adjusted.thinkingBudget,Math.max(0,maxTokens-1024))})};function isOAuthToken(apiKey){return apiKey.includes("sk-ant-oat")}function createClient(model,apiKey,optionsHeaders,fetch,dynamicHeaders,sessionId,federation){if(model.provider==="github-copilot")return{client:new PiAnthropic({apiKey:null,authToken:apiKey??null,baseURL:model.baseUrl,dangerouslyAllowBrowser:!0,fetch,defaultHeaders:mergeClientHeaders({accept:"application/json","anthropic-dangerous-direct-browser-access":"true"},model.headers,dynamicHeaders,optionsHeaders)}),isOAuthToken:!1};if(apiKey&&isOAuthToken(apiKey))return{client:new PiAnthropic({apiKey:null,authToken:apiKey,baseURL:model.baseUrl,dangerouslyAllowBrowser:!0,fetch,defaultHeaders:mergeClientHeaders({accept:"application/json","anthropic-dangerous-direct-browser-access":"true","user-agent":`claude-cli/${claudeCodeVersion}`,"x-app":"cli"},model.headers,optionsHeaders)}),isOAuthToken:!0};let compat=getAnthropicCompat(model),sessionAffinityHeaders={};if(sessionId&&compat.sendSessionAffinityHeaders){let header=compat.sessionAffinityFormat==="openrouter"?"x-session-id":"x-session-affinity";sessionAffinityHeaders[header]=sessionId}let defaultHeaders=mergeClientHeaders({accept:"application/json","anthropic-dangerous-direct-browser-access":"true"},sessionAffinityHeaders,model.headers,optionsHeaders);if(federation){let key=JSON.stringify([model.baseUrl,federation]);if(federationClient?.key!==key||federationClient.fetch!==fetch){let client2=new PiAnthropic({apiKey:null,authToken:null,config:federation,baseURL:model.baseUrl,dangerouslyAllowBrowser:!0,fetch});federationClient={key,fetch,client:client2}}return{client:federationClient.client.withOptions({defaultHeaders}),isOAuthToken:!1}}return{client:new PiAnthropic({apiKey:apiKey??null,authToken:null,baseURL:model.baseUrl,dangerouslyAllowBrowser:!0,fetch,defaultHeaders}),isOAuthToken:!1}}function getBetaFeatures(model,context,isOAuthToken2,nativeToolChanges,options){let configuredFeatures;for(let headers of[model.headers,options?.headers])for(let[name,value]of Object.entries(headers??{}))name.toLowerCase()==="anthropic-beta"&&(configuredFeatures=value);if(configuredFeatures===null)return[];if(configuredFeatures!==void 0)return[...new Set(configuredFeatures.split(",").map(feature=>feature.trim()).filter(feature=>feature.length>0))];let features=[];return isOAuthToken2&&features.push("claude-code-20250219","oauth-2025-04-20"),shouldUseFineGrainedToolStreamingBeta(model,context)&&features.push(FINE_GRAINED_TOOL_STREAMING_BETA),model.reasoning&&options?.thinkingEnabled===!0&&(options.interleavedThinking??!0)&&model.compat?.forceAdaptiveThinking!==!0&&features.push(INTERLEAVED_THINKING_BETA),shouldUseServerSideFallbackBeta(model)&&features.push(SERVER_SIDE_FALLBACK_BETA),model.compat?.supportsMidConvoEffort===!0&&features.push(MID_CONVERSATION_OUTPUT_CONFIG_BETA,THINKING_BINDING_CONTROLS_BETA),nativeToolChanges&&features.push(INLINE_TOOLS_BETA),[...new Set(features)]}function buildParams(model,context,isOAuthToken2,options,disablePreferredStrictTools=!1){let{cacheControl}=getCacheControl(model,options?.cacheRetention,options?.env),compat=getAnthropicCompat(model),initialSystemMessage=getInitialSystemMessage(context.messages),initialSystemText=initialSystemMessage?getSystemMessageText(initialSystemMessage):"",transformedMessages=transformMessages(context.messages,model,normalizeToolCallId),conversationMessages=initialSystemMessage?transformedMessages.slice(1):transformedMessages,hasPreferredStrictTools=!1,convertToolDefinitions=(tools,toolCacheControl2)=>{let definitions=convertTools(tools,isOAuthToken2,compat.supportsEagerToolInputStreaming,compat.supportsStrictTools,toolCacheControl2,disablePreferredStrictTools);return definitions.some((definition,index)=>{let config=tools[index].constrainedSampling;return definition.strict===!0&&config&&config.type==="json_schema"&&config.strict==="prefer"})&&(hasPreferredStrictTools=!0),definitions},initialTools=initialSystemMessage?.toolsAdded??[],nativeToolChanges=compat.supportsMidConvoSystemMessages&&compat.supportsMidConvoToolChanges&&initialTools.length>0,thinkingDisabled=model.reasoning&&options?.thinkingEnabled===!1&&model.thinkingLevelMap?.off!==null,effortMessages=model.compat?.supportsMidConvoEffort===!0&&!thinkingDisabled,converted=convertMessages(conversationMessages,isOAuthToken2,cacheControl,compat.allowEmptySignature,effortMessages?model.provider:void 0,nativeToolChanges?convertToolDefinitions:void 0),activeEffort=options?.effort??"high",betaFeatures=getBetaFeatures(model,context,isOAuthToken2,nativeToolChanges,options),params={model:model.id,messages:effortMessages?insertThinkingLevelMessages(converted,activeEffort):converted.messages,max_tokens:options?.maxTokens??model.maxTokens,stream:!0,...betaFeatures.length>0?{betas:betaFeatures}:{}};isOAuthToken2?(params.system=[{type:"text",text:"You are Claude Code, Anthropic's official CLI for Claude.",...cacheControl?{cache_control:cacheControl}:{}}],initialSystemText&¶ms.system.push({type:"text",text:sanitizeSurrogates(initialSystemText),...cacheControl?{cache_control:cacheControl}:{}})):initialSystemText&&(params.system=[{type:"text",text:sanitizeSurrogates(initialSystemText),...cacheControl?{cache_control:cacheControl}:{}}]),options?.temperature!==void 0&&!options?.thinkingEnabled&&model.compat?.supportsMidConvoEffort!==!0&&compat.supportsTemperature&&(params.temperature=options.temperature);let toolCacheControl=compat.supportsCacheControlOnTools?cacheControl:void 0;if(nativeToolChanges)params.tools=[...convertToolDefinitions(initialTools,toolCacheControl),DEFERRED_TOOL_PLACEHOLDER];else{let tools=getCurrentTools(context.messages);tools.length>0&&(params.tools=convertToolDefinitions(tools,toolCacheControl))}if(thinkingDisabled)params.thinking={type:"disabled"};else if(effortMessages)params.thinking={type:"adaptive",display:options?.thinkingDisplay??"summarized",block_binding:{prefix_mismatch_behavior:"drop_block"}},params.output_config={effort:"high"};else if(model.reasoning&&options?.thinkingEnabled){let display=options.thinkingDisplay??"summarized";model.compat?.forceAdaptiveThinking===!0?(params.thinking={type:"adaptive",display},options.effort&&(params.output_config={effort:options.effort})):params.thinking={type:"enabled",budget_tokens:options.thinkingBudgetTokens||1024,display}}if(options?.metadata){let userId=options.metadata.user_id;typeof userId=="string"&&(params.metadata={user_id:userId})}options?.toolChoice&&(typeof options.toolChoice=="string"?params.tool_choice={type:options.toolChoice}:params.tool_choice=options.toolChoice);let allowedFallbackModels=model.compat?.allowedFallbackModels;return allowedFallbackModels&&allowedFallbackModels.length>0&&(params.fallbacks=allowedFallbackModels.map(fallback=>({model:fallback.model}))),{params,hasPreferredStrictTools,providerThinkingLevel:effortMessages?activeEffort:void 0}}function normalizeToolCallId(id){return id.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)}function convertToolResult(msg,content=msg.content){return{type:"tool_result",tool_use_id:msg.toolCallId,content:convertContentBlocks(content),is_error:msg.isError}}function convertMessages(transformedMessages,isOAuthToken2,cacheControl,allowEmptySignature=!1,managedProvider,convertToolDefinitions){let params=[],assistantLevels=new Map,pendingSystemMessages=[],flushPendingSystemMessages=()=>{params.push(...pendingSystemMessages),pendingSystemMessages.length=0};for(let i=0;i<transformedMessages.length;i++){let msg=transformedMessages[i];if(msg.role==="system"){let text=renderSystemMessageUpdate(msg),blocks=[];if(text.length>0&&blocks.push({type:"text",text:sanitizeSurrogates(text)}),convertToolDefinitions){let added=msg.toolsAdded??[],redefined=new Set(added.map(tool=>tool.name));for(let tool of msg.toolsRemoved??[])redefined.has(tool.name)||blocks.push({type:"tool_removal",tool:{type:"tool_reference",name:isOAuthToken2?toClaudeCodeName(tool.name):tool.name}});for(let definition of convertToolDefinitions(added))blocks.push({type:"tool_addition",tool:{type:"tool_definition",definition}})}blocks.length>0&&pendingSystemMessages.push({role:"system",content:blocks})}else if(msg.role==="user")if(typeof msg.content=="string")msg.content.trim().length>0&¶ms.push({role:"user",content:sanitizeSurrogates(msg.content)});else{let filteredBlocks=msg.content.map(item=>item.type==="text"?{type:"text",text:sanitizeSurrogates(item.text)}:convertImageBlock(item)).filter(b=>b.type==="text"?b.text.trim().length>0:!0);if(filteredBlocks.length===0)continue;params.push({role:"user",content:filteredBlocks})}else if(msg.role==="assistant"){flushPendingSystemMessages();let blocks=[];for(let block of msg.content)if(block.type==="text"){if(block.text.trim().length===0)continue;blocks.push({type:"text",text:sanitizeSurrogates(block.text)})}else if(block.type==="thinking"){if(block.redacted){blocks.push({type:"redacted_thinking",data:block.thinkingSignature});continue}let thinkingSignature=block.thinkingSignature,hasThinkingSignature=!!thinkingSignature&&thinkingSignature.trim().length>0;if(block.thinking.trim().length===0&&!hasThinkingSignature)continue;hasThinkingSignature?blocks.push({type:"thinking",thinking:sanitizeSurrogates(block.thinking),signature:thinkingSignature}):blocks.push(allowEmptySignature?{type:"thinking",thinking:sanitizeSurrogates(block.thinking),signature:""}:{type:"text",text:sanitizeSurrogates(block.thinking)})}else block.type==="toolCall"&&blocks.push({type:"tool_use",id:block.id,name:isOAuthToken2?toClaudeCodeName(block.name):block.name,input:block.arguments??{}});if(blocks.length===0)continue;let messageIndex=params.length;params.push({role:"assistant",content:blocks}),managedProvider!==void 0&&msg.api==="anthropic-messages"&&msg.provider===managedProvider&&isAnthropicEffort(msg.providerThinkingLevel)&&assistantLevels.set(messageIndex,msg.providerThinkingLevel)}else if(msg.role==="toolResult"){let toolResults=[],errorImages=[],j=i;for(;j<transformedMessages.length&&transformedMessages[j].role==="toolResult";){let toolMsg=transformedMessages[j],split=splitErrorToolResultImages(toolMsg);toolResults.push(convertToolResult(toolMsg,split?.content)),split&&errorImages.push({type:"text",text:split.caption},...split.images.map(convertImageBlock)),j++}i=j-1,params.push({role:"user",content:[...toolResults,...errorImages]})}}if(flushPendingSystemMessages(),cacheControl&¶ms.length>0){let lastMessage=params[params.length-1];if(lastMessage.role==="user"||lastMessage.role==="system")if(Array.isArray(lastMessage.content)){let lastBlock=lastMessage.content[lastMessage.content.length-1];lastBlock&&(lastBlock.type==="text"||lastBlock.type==="image"||lastBlock.type==="tool_result"||lastBlock.type==="tool_addition"||lastBlock.type==="tool_removal")&&(lastBlock.cache_control=cacheControl)}else typeof lastMessage.content=="string"&&(lastMessage.content=[{type:"text",text:lastMessage.content,cache_control:cacheControl}])}return{messages:params,assistantLevels}}function isAnthropicEffort(value){return value==="low"||value==="medium"||value==="high"||value==="xhigh"||value==="max"}function insertThinkingLevelMessages(converted,activeEffort){let messages=[];for(let index=0;index<converted.messages.length;index++){let historicalEffort=converted.assistantLevels.get(index);historicalEffort!==void 0&&messages.push({role:"system",content:[],output_config:{effort:historicalEffort}}),messages.push(converted.messages[index])}return messages.push({role:"system",content:[],output_config:{effort:activeEffort}}),messages}function shouldUseFineGrainedToolStreamingBeta(model,context){return getCurrentTools(context.messages).length>0&&!getAnthropicCompat(model).supportsEagerToolInputStreaming}var ANTHROPIC_STRICT_UNSUPPORTED_KEYWORDS=new Set(["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","maxItems","uniqueItems","minContains","maxContains","minProperties","maxProperties"]),ANTHROPIC_STRICT_STRING_FORMATS=new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","uuid"]),isAnthropicStrictUnsupportedKeyword=(key,value)=>ANTHROPIC_STRICT_UNSUPPORTED_KEYWORDS.has(key)?!0:key==="minItems"?value!==0&&value!==1:key==="format"?typeof value!="string"||!ANTHROPIC_STRICT_STRING_FORMATS.has(value):!1;function convertTools(tools,isOAuthToken2,supportsEagerToolInputStreaming,supportsStrictTools,cacheControl,disablePreferredStrictTools=!1){return tools?tools.map((tool,index)=>{let config=tool.constrainedSampling,strict=disablePreferredStrictTools&&config&&config.type==="json_schema"&&config.strict==="prefer"?void 0:resolveJsonSchemaStrictSampling(tool,supportsStrictTools,isAnthropicStrictUnsupportedKeyword),parameters=getJsonSchemaToolParameters(tool,strict),schema=parameters,legacyInputSchema={type:"object",properties:schema.properties??{},required:schema.required??[]},inputSchema=strict===!0?{...parameters,...legacyInputSchema}:legacyInputSchema;return{name:isOAuthToken2?toClaudeCodeName(tool.name):tool.name,description:tool.description,...supportsEagerToolInputStreaming?{eager_input_streaming:!0}:{},...strict===!0?{strict:!0}:{},input_schema:inputSchema,...cacheControl&&index===tools.length-1?{cache_control:cacheControl}:{}}}):[]}function mapStopReason(reason,stopDetails){switch(reason){case"end_turn":return{stopReason:"stop"};case"max_tokens":return{stopReason:"length"};case"tool_use":return{stopReason:"toolUse"};case"refusal":return{stopReason:"error",errorMessage:stopDetails?.explanation||"The model refused to complete the request"};case"pause_turn":return{stopReason:"stop"};case"stop_sequence":return{stopReason:"stop"};case"sensitive":return{stopReason:"error",errorMessage:"Provider stopped with: sensitive"};default:throw new Error(`Unhandled stop reason: ${reason}`)}}export{stream,streamSimple};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{convertResponsesMessages,convertResponsesTools,processResponsesStream}from"./chunk-UCKJ6OH5.js";import{resolveAzureConfig,resolveDeploymentName}from"./chunk-ZBURYEWF.js";import{clampOpenAIPromptCacheKey}from"./chunk-PRRNXB7S.js";import{AzureOpenAI}from"./chunk-H3QXYIF7.js";import
|
|
2
|
+
import{convertResponsesMessages,convertResponsesTools,processResponsesStream}from"./chunk-UCKJ6OH5.js";import{resolveAzureConfig,resolveDeploymentName}from"./chunk-ZBURYEWF.js";import{clampOpenAIPromptCacheKey}from"./chunk-PRRNXB7S.js";import{AzureOpenAI}from"./chunk-H3QXYIF7.js";import"./chunk-PJACZCIR.js";import{retryProviderRequest}from"./chunk-PMRZO46Y.js";import{formatProviderError,normalizeProviderError}from"./chunk-CTEAMRDY.js";import{buildBaseOptions,createGrammarToolInputProperties,getPiUserAgent,resolveSamplingParams}from"./chunk-2JW42LFQ.js";import"./chunk-L2ZPNLYD.js";import{headersToRecord}from"./chunk-UTB4DTYQ.js";import"./chunk-DRQDKNXA.js";import"./chunk-PYGXRV27.js";import{clampThinkingLevel,getDeclaredTools,resolveTranscript,resolveTranscriptTools}from"./chunk-HACVPRBJ.js";import{AssistantMessageEventStream}from"./chunk-LPXNMA2W.js";import"./chunk-4L3WN2XY.js";var AZURE_TOOL_CALL_PROVIDERS=new Set(["openai","openai-codex","opencode","azure"]),OPENAI_RESPONSES_MIN_OUTPUT_TOKENS=16;function formatAzureOpenAIError(error){return formatProviderError(normalizeProviderError(error),"Azure OpenAI API error")}var stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=resolveTranscript(context,model.compat?.supportsMidConvoSystemMessages);return(async()=>{let deploymentName=resolveDeploymentName(model,options),output={role:"assistant",content:[],api:"azure-openai-responses",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let client=createClient(model,apiKey,options),grammarToolInputProperties=createGrammarToolInputProperties(getDeclaredTools(normalizedContext.messages),model.compat?.supportsOpenAIGrammarTools??!1),params=buildParams(model,normalizedContext,options,deploymentName,grammarToolInputProperties),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let requestOptions={...options?.signal?{signal:options.signal}:{},...options?.timeoutMs!==void 0?{timeout:options.timeoutMs}:{},maxRetries:0},{data:openaiStream,response}=await retryProviderRequest(()=>client.responses.create(params,requestOptions).withResponse(),{maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,signal:options?.signal});if(await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),stream2.push({type:"start",partial:output}),await processResponsesStream(openaiStream,output,stream2,model,{onProviderStreamEvent:options?.onProviderStreamEvent,grammarToolInputProperties}),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Azure OpenAI Responses stream ended without a stop reason");if(output.stopReason==="aborted"||output.stopReason==="error")throw new Error(output.errorMessage||"An unknown error occurred");stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)delete block.index,delete block.partialJson,delete block.customInput;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatAzureOpenAIError(error),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let base={...buildBaseOptions(model,context,options,apiKey),toolChoice:options?.toolChoice},clampedReasoning=options?.reasoning?clampThinkingLevel(model,options.reasoning):void 0;return stream(model,context,{...base,reasoningEffort:clampedReasoning==="off"?void 0:clampedReasoning})};function createClient(model,apiKey,options){let headers={"User-Agent":getPiUserAgent(),...model.headers};options?.headers&&Object.assign(headers,options.headers);let{baseUrl,apiVersion}=resolveAzureConfig(model,options);return new AzureOpenAI({apiKey,apiVersion,dangerouslyAllowBrowser:!0,fetch:options?.fetch,defaultHeaders:headers,baseURL:baseUrl})}function buildParams(model,context,options,deploymentName,grammarToolInputProperties=createGrammarToolInputProperties(getDeclaredTools(context.messages),model.compat?.supportsOpenAIGrammarTools??!1)){let supportsAdditionalTools=model.compat?.supportsAdditionalTools??!1,supportsToolSearch=model.compat?.supportsToolSearch??!1,transcriptTools=resolveTranscriptTools(context.messages,supportsAdditionalTools||supportsToolSearch),messages=convertResponsesMessages(model,context,AZURE_TOOL_CALL_PROVIDERS,{grammarToolInputProperties,supportsMidConvoSystemMessages:model.compat?.supportsMidConvoSystemMessages??!1,supportsAdditionalTools,supportsToolSearch,toolOptions:{supportsStrictMode:model.compat?.supportsStrictMode??!0,supportsOpenAIGrammarTools:model.compat?.supportsOpenAIGrammarTools??!1}}),params={model:deploymentName,input:messages,stream:!0,prompt_cache_key:clampOpenAIPromptCacheKey(options?.sessionId),store:!1};options?.maxTokens&&(params.max_output_tokens=Math.max(options.maxTokens,OPENAI_RESPONSES_MIN_OUTPUT_TOKENS)),options?.temperature!==void 0&&(params.temperature=options?.temperature),transcriptTools.requestTools.length>0&&(params.tools=convertResponsesTools(transcriptTools.requestTools,{supportsStrictMode:model.compat?.supportsStrictMode??!0,supportsOpenAIGrammarTools:model.compat?.supportsOpenAIGrammarTools??!1})),options?.toolChoice!==void 0&&(params.tool_choice=options.toolChoice);let reasoningEffort=options?.reasoningEffort??(options?.reasoningSummary?"medium":void 0);if(model.reasoning)if(reasoningEffort){let effort=options?.reasoningEffort?model.thinkingLevelMap?.[options.reasoningEffort]??options.reasoningEffort:reasoningEffort;params.reasoning={effort,summary:options?.reasoningSummary||"auto"},params.include=["reasoning.encrypted_content"]}else model.thinkingLevelMap?.off!==null&&(params.reasoning={effort:model.thinkingLevelMap?.off??"none"});let samplingParams=resolveSamplingParams(model,reasoningEffort??"off",options?.samplingParams);return samplingParams&&Object.assign(params,samplingParams),params}export{stream,streamSimple};
|
|
@@ -79,7 +79,7 @@ Reference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.ht
|
|
|
79
79
|
|
|
80
80
|
`)}function isSystemMessage(message){return message.role==="system"}function getInitialSystemMessage(messages){let first=messages[0];return first&&isSystemMessage(first)?first:void 0}function withoutInitialSystemMessage(messages){return getInitialSystemMessage(messages)?messages.slice(1):messages}function getCurrentTools(messages){let tools=new Map;for(let message of messages)if(isSystemMessage(message)){for(let tool of message.toolsRemoved??[])tools.delete(tool.name);for(let tool of message.toolsAdded??[])tools.set(tool.name,tool)}return[...tools.values()]}function getCurrentSystemMessage(messages){let content=[],sections=new Map,timestamp;for(let message of messages){if(!isSystemMessage(message))continue;timestamp??=message.timestamp;let text=contentText(message.content);text.length>0&&content.push(text);for(let[name,value]of Object.entries(message.sections??{}))value===null?sections.delete(name):sections.set(name,value)}let tools=getCurrentTools(messages);if(!(timestamp===void 0&&tools.length===0))return{role:"system",content:content.join(`
|
|
81
81
|
|
|
82
|
-
`),...sections.size>0?{sections:Object.fromEntries(sections)}:{},...tools.length>0?{toolsAdded:tools}:{},timestamp:timestamp??0}}function collapseSystemMessages(context){let head=getCurrentSystemMessage(context.messages),messages=context.messages.filter(message=>message.role!=="system");return{messages:head?[head,...messages]:messages}}function calculateCost(model,usage){let inputTokens=usage.input+usage.cacheRead+usage.cacheWrite,rates=model.cost,matchedThreshold=-1;for(let tier of model.cost.tiers??[])inputTokens>tier.inputTokensAbove&&tier.inputTokensAbove>matchedThreshold&&(rates=tier,matchedThreshold=tier.inputTokensAbove);let longWrite=usage.cacheWrite1h??0,shortWrite=usage.cacheWrite-longWrite;return usage.cost.input=rates.input/1e6*usage.input,usage.cost.output=rates.output/1e6*usage.output,usage.cost.cacheRead=rates.cacheRead/1e6*usage.cacheRead,usage.cost.cacheWrite=(rates.cacheWrite*shortWrite+rates.input*2*longWrite)/1e6,usage.cost.total=usage.cost.input+usage.cost.output+usage.cost.cacheRead+usage.cost.cacheWrite,usage.cost}var EXTENDED_THINKING_LEVELS=["off","minimal","low","medium","high","xhigh","max"];function getSupportedThinkingLevels(model){return model.reasoning?EXTENDED_THINKING_LEVELS.filter(level=>{let mapped=model.thinkingLevelMap?.[level];return mapped===null?!1:level==="xhigh"||level==="max"?mapped!==void 0:!0}):["off"]}function clampThinkingLevel(model,level){let availableLevels=getSupportedThinkingLevels(model);if(availableLevels.includes(level))return level;let requestedIndex=EXTENDED_THINKING_LEVELS.indexOf(level);if(requestedIndex===-1)return availableLevels[0]??"off";for(let i5=requestedIndex;i5<EXTENDED_THINKING_LEVELS.length;i5++){let candidate=EXTENDED_THINKING_LEVELS[i5];if(availableLevels.includes(candidate))return candidate}for(let i5=requestedIndex-1;i5>=0;i5--){let candidate=EXTENDED_THINKING_LEVELS[i5];if(availableLevels.includes(candidate))return candidate}return availableLevels[0]??"off"}function normalizeProviderError(error2){if(!(error2 instanceof Error))return{message:safeJsonStringify(error2),messageCarriesBody:!1};let sdkError=error2,status=extractStatus(sdkError),body=extractBody(sdkError),messageCarriesBody=body===void 0||error2.message.includes(body);return{status,body,message:error2.message,messageCarriesBody}}function extractStatus(error2){if(typeof error2.statusCode=="number")return error2.statusCode;if(typeof error2.status=="number")return error2.status;if(typeof error2.$metadata?.httpStatusCode=="number")return error2.$metadata.httpStatusCode;if(typeof error2.$response?.statusCode=="number")return error2.$response.statusCode}function extractBody(error2){let bodyText=pickBodyText(error2);if(bodyText===void 0)return;let trimmed=bodyText.trim();if(trimmed.length!==0)return truncateErrorText(trimmed,4e3)}function pickBodyText(error2){if(typeof error2.body=="string")return error2.body;if(isPlainNonEmptyObject(error2.error))return safeJsonStringify(error2.error);let responseBody=error2.$response?.body;if(typeof responseBody=="string")return responseBody;if(!isReadableStreamLike(responseBody)&&isPlainNonEmptyObject(responseBody))return safeJsonStringify(responseBody)}function isReadableStreamLike(value){return typeof value=="object"&&value!==null&&"pipe"in value&&typeof value.pipe=="function"}function isPlainNonEmptyObject(value){if(typeof value!="object"||value===null)return!1;let proto=Object.getPrototypeOf(value);return proto!==Object.prototype&&proto!==null?!1:Object.keys(value).length>0}function truncateErrorText(text,maxChars){return text.length<=maxChars?text:`${text.slice(0,maxChars)}... [truncated ${text.length-maxChars} chars]`}function safeJsonStringify(value){try{let serialized=JSON.stringify(value);return serialized===void 0?String(value):serialized}catch{return String(value)}}function providerHeadersToRecord(...headerSources){let merged=new Map;for(let source of headerSources)for(let[name,value]of Object.entries(source??{})){let normalizedName=name.toLowerCase();merged.delete(normalizedName),value!==null&&merged.set(normalizedName,[name,value])}return merged.size>0?Object.fromEntries(merged.values()):void 0}var import_partial_json=__toESM(require_dist(),1),VALID_JSON_ESCAPES=new Set(['"',"\\","/","b","f","n","r","t"]);function isControlCharacter(char){let codePoint=char.codePointAt(0);return codePoint!==void 0&&codePoint>=0&&codePoint<=31}function escapeControlCharacter(char){switch(char){case"\b":return"\\b";case"\f":return"\\f";case`
|
|
82
|
+
`),...sections.size>0?{sections:Object.fromEntries(sections)}:{},...tools.length>0?{toolsAdded:tools}:{},timestamp:timestamp??0}}function collapseSystemMessages(context){let head=getCurrentSystemMessage(context.messages),messages=context.messages.filter(message=>message.role!=="system");return{messages:head?[head,...messages]:messages}}function calculateCost(model,usage){let inputTokens=usage.input+usage.cacheRead+usage.cacheWrite,rates=model.cost,matchedThreshold=-1;for(let tier of model.cost.tiers??[])inputTokens>tier.inputTokensAbove&&tier.inputTokensAbove>matchedThreshold&&(rates=tier,matchedThreshold=tier.inputTokensAbove);let longWrite=usage.cacheWrite1h??0,shortWrite=usage.cacheWrite-longWrite;return usage.cost.input=rates.input/1e6*usage.input,usage.cost.output=rates.output/1e6*usage.output,usage.cost.cacheRead=rates.cacheRead/1e6*usage.cacheRead,usage.cost.cacheWrite=(rates.cacheWrite*shortWrite+rates.input*2*longWrite)/1e6,usage.cost.total=usage.cost.input+usage.cost.output+usage.cost.cacheRead+usage.cost.cacheWrite,usage.cost}var EXTENDED_THINKING_LEVELS=["off","minimal","low","medium","high","xhigh","max"];function getSupportedThinkingLevels(model){return model.reasoning?EXTENDED_THINKING_LEVELS.filter(level=>{let mapped=model.thinkingLevelMap?.[level];return mapped===null?!1:level==="xhigh"||level==="max"?mapped!==void 0:!0}):["off"]}function clampThinkingLevel(model,level){let availableLevels=getSupportedThinkingLevels(model);if(availableLevels.includes(level))return level;let requestedIndex=EXTENDED_THINKING_LEVELS.indexOf(level);if(requestedIndex===-1)return availableLevels[0]??"off";for(let i5=requestedIndex;i5<EXTENDED_THINKING_LEVELS.length;i5++){let candidate=EXTENDED_THINKING_LEVELS[i5];if(availableLevels.includes(candidate))return candidate}for(let i5=requestedIndex-1;i5>=0;i5--){let candidate=EXTENDED_THINKING_LEVELS[i5];if(availableLevels.includes(candidate))return candidate}return availableLevels[0]??"off"}function normalizeProviderError(error2){if(!(error2 instanceof Error))return{message:safeJsonStringify(error2),messageCarriesBody:!1};let sdkError=error2,status=extractStatus(sdkError),body=extractBody(sdkError),messageCarriesBody=body===void 0||error2.message.includes(body);return{status,body,message:withConnectFailureCause(error2.message,error2),messageCarriesBody}}var UNSENT_CONNECT_ERROR_CODES=new Set(["ENOTFOUND","EAI_AGAIN","ECONNREFUSED","ENETUNREACH","ENETDOWN","EHOSTUNREACH","EADDRNOTAVAIL","UND_ERR_CONNECT_TIMEOUT"]),UNSENT_CONNECT_ERROR_MESSAGE=/before secure TLS connection was established|when HTTP Tunneling/;function connectFailureCause(error2){let current=error2;for(let depth=0;depth<5&¤t instanceof Error;depth++){let code=current.code;if(typeof code=="string"&&UNSENT_CONNECT_ERROR_CODES.has(code)||UNSENT_CONNECT_ERROR_MESSAGE.test(current.message))return current.message;current=current.cause??(current instanceof AggregateError?current.errors[0]:void 0)}}function withConnectFailureCause(message,error2){let cause=connectFailureCause(error2);return cause===void 0||message.includes(cause)?message:`${message} (caused by: ${cause})`}function extractStatus(error2){if(typeof error2.statusCode=="number")return error2.statusCode;if(typeof error2.status=="number")return error2.status;if(typeof error2.$metadata?.httpStatusCode=="number")return error2.$metadata.httpStatusCode;if(typeof error2.$response?.statusCode=="number")return error2.$response.statusCode}function extractBody(error2){let bodyText=pickBodyText(error2);if(bodyText===void 0)return;let trimmed=bodyText.trim();if(trimmed.length!==0)return truncateErrorText(trimmed,4e3)}function pickBodyText(error2){if(typeof error2.body=="string")return error2.body;if(isPlainNonEmptyObject(error2.error))return safeJsonStringify(error2.error);let responseBody=error2.$response?.body;if(typeof responseBody=="string")return responseBody;if(!isReadableStreamLike(responseBody)&&isPlainNonEmptyObject(responseBody))return safeJsonStringify(responseBody)}function isReadableStreamLike(value){return typeof value=="object"&&value!==null&&"pipe"in value&&typeof value.pipe=="function"}function isPlainNonEmptyObject(value){if(typeof value!="object"||value===null)return!1;let proto=Object.getPrototypeOf(value);return proto!==Object.prototype&&proto!==null?!1:Object.keys(value).length>0}function truncateErrorText(text,maxChars){return text.length<=maxChars?text:`${text.slice(0,maxChars)}... [truncated ${text.length-maxChars} chars]`}function safeJsonStringify(value){try{let serialized=JSON.stringify(value);return serialized===void 0?String(value):serialized}catch{return String(value)}}function providerHeadersToRecord(...headerSources){let merged=new Map;for(let source of headerSources)for(let[name,value]of Object.entries(source??{})){let normalizedName=name.toLowerCase();merged.delete(normalizedName),value!==null&&merged.set(normalizedName,[name,value])}return merged.size>0?Object.fromEntries(merged.values()):void 0}var import_partial_json=__toESM(require_dist(),1),VALID_JSON_ESCAPES=new Set(['"',"\\","/","b","f","n","r","t"]);function isControlCharacter(char){let codePoint=char.codePointAt(0);return codePoint!==void 0&&codePoint>=0&&codePoint<=31}function escapeControlCharacter(char){switch(char){case"\b":return"\\b";case"\f":return"\\f";case`
|
|
83
83
|
`:return"\\n";case"\r":return"\\r";case" ":return"\\t";default:return`\\u${char.codePointAt(0)?.toString(16).padStart(4,"0")??"0000"}`}}function repairJson(json){let repaired="",inString=!1;for(let index=0;index<json.length;index++){let char=json[index];if(!inString){repaired+=char,char==='"'&&(inString=!0);continue}if(char==='"'){repaired+=char,inString=!1;continue}if(char==="\\"){let nextChar=json[index+1];if(nextChar===void 0){repaired+="\\\\";continue}if(nextChar==="u"){let unicodeDigits=json.slice(index+2,index+6);if(/^[0-9a-fA-F]{4}$/.test(unicodeDigits)){repaired+=`\\u${unicodeDigits}`,index+=5;continue}}if(VALID_JSON_ESCAPES.has(nextChar)){repaired+=`\\${nextChar}`,index+=1;continue}repaired+="\\\\";continue}repaired+=isControlCharacter(char)?escapeControlCharacter(char):char}return repaired}function parseJsonWithRepair(json){try{return JSON.parse(json)}catch(error2){let repairedJson=repairJson(json);if(repairedJson!==json)return JSON.parse(repairedJson);throw error2}}function parseToolCallArguments(json){if(!json?.trim())return{arguments:{}};try{let parsed=parseJsonWithRepair(json);if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))throw new Error("Tool arguments must be a JSON object");return{arguments:parsed}}catch(error2){return{arguments:{},argumentsError:`${error2 instanceof Error?error2.message:String(error2)}
|
|
84
84
|
|
|
85
85
|
Received arguments:
|
|
@@ -40,7 +40,7 @@ Searches over deferred tool metadata with BM25 and exposes matching tools for th
|
|
|
40
40
|
|
|
41
41
|
Some of the tools, such as tools of MCP servers, may not have been provided to you upfront, and you should use this tool (\`${TOOL_SEARCH_TOOL_NAME}\`) to search for the required tools. For MCP tool discovery, always use \`${TOOL_SEARCH_TOOL_NAME}\`.`;function createToolSearchToolDefinition(options={}){return{name:TOOL_SEARCH_TOOL_NAME,label:TOOL_SEARCH_TOOL_NAME,description:TOOL_SEARCH_DESCRIPTION,promptSnippet:"Search for tools that are not loaded yet and load the matches",parameters:toolSearchSchema,exposure:"model-only",reachesTools:()=>"all",async execute(_toolCallId,{query,limit}){if(query.trim()==="")throw new Error("query must not be empty");let max=limit??DEFAULT_TOOL_SEARCH_LIMIT;if(!Number.isInteger(max)||max<=0)throw new Error("limit must be a positive integer");let tools=options.tools?searchAndLoad(options.tools,query,max):[];return{content:[{type:"text",text:tools.length===0?"No matching tools found.":`Loaded ${tools.length} tool${tools.length===1?"":"s"}. They are available from your next call:
|
|
42
42
|
${tools.map(tool=>`- ${tool.name}: ${tool.description.trim().split(/\r?\n/)[0]}`).join(`
|
|
43
|
-
`)}`}],details:{loaded:tools.map(tool=>tool.name)}}}}}import{join as join2}from"node:path";function buildProviderErrorPattern(patterns){return new RegExp(patterns.join("|"),"i")}var NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN=buildProviderErrorPattern(["GoUsageLimitError","FreeUsageLimitError","Monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing","subscription_sharing_usage_limit_exceeded"]),RETRYABLE_PROVIDER_ERROR_PATTERN=buildProviderErrorPattern(["overloaded","server_busy","servers are currently busy","currently experiencing high demand","model is at capacity","rate.?limit","too many requests","429","500","502","503","504","520","524","service.?(?:is.?)?(?:temporarily.?)?unavailable","server.?error","internal.?error","provider.?returned.?(?:an.?)?error","upstream_error_frame","exceeded request buffer limit while retrying upstream","unable to forward upstream","network.?error","connection.?error","connection.?refused","connection.?lost","other side closed","fetch failed","getaddrinfo","ENOTFOUND","EAI_AGAIN","upstream.?connect","reset before headers","socket hang up","socket connection was closed","timed? out","timeout","terminated","websocket.?closed","websocket.?error","ended without","stream ended before message_stop","stream ended before a terminal response event","http2 request did not get a response","pending stream has been canceled","retry delay","you can retry your request","try your request again","please retry your request","ResourceExhausted","subscription_sharing_usage_unavailable","subscription_sharing_user_unavailable"]),DEFAULT_MAX_AGENT_RETRY_DELAY_MS=6e4;function retryDelayMs(policy,attempt){let delay=policy.baseDelayMs*2**Math.max(0,attempt-1),safeDelay=Number.isSafeInteger(delay)?delay:Number.MAX_SAFE_INTEGER;return Math.min(safeDelay,policy.maxAgentDelayMs??DEFAULT_MAX_AGENT_RETRY_DELAY_MS)}var RetrySleepAbortError=class extends Error{constructor(){super("Aborted")}};function sleep(ms,signal){return new Promise((resolve,reject)=>{if(signal?.aborted){reject(new RetrySleepAbortError);return}let timeout=setTimeout(resolve,ms);signal?.addEventListener("abort",()=>{clearTimeout(timeout),reject(new RetrySleepAbortError)},{once:!0})})}async function retryAssistantCall(produce,policy,signal,callbacks){let maxAttempts=policy?.enabled?policy.maxRetries:0,attempt=0,lastRetry;for(;;){let response=await produce();if(response.stopReason==="aborted")return lastRetry&&await callbacks?.onRetryFinished?.(!1,lastRetry.attempt),response;if(response.stopReason!=="error")return lastRetry&&await callbacks?.onRetryFinished?.(!0,lastRetry.attempt),response;if(attempt>=maxAttempts||!isRetryableAssistantError(response))return lastRetry&&await callbacks?.onRetryFinished?.(!1,lastRetry.attempt,response.errorMessage),response;attempt++,lastRetry={attempt,errorMessage:response.errorMessage||"Unknown error"};let delayMs=retryDelayMs(policy,attempt);await callbacks?.onRetryScheduled?.(attempt,maxAttempts,delayMs,lastRetry.errorMessage);try{await sleep(delayMs,signal)}catch(error){if(await callbacks?.onRetryFinished?.(!1,attempt,lastRetry.errorMessage),error instanceof RetrySleepAbortError){let{errorMessage:_errorMessage,...rest}=response;return{...rest,stopReason:"aborted"}}throw error}await callbacks?.onRetryAttemptStart?.()}}function isRetryableAssistantError(message){if(message.stopReason!=="error"||!message.errorMessage)return!1;let errorMessage=message.errorMessage;return NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN.test(errorMessage)?!1:RETRYABLE_PROVIDER_ERROR_PATTERN.test(errorMessage)}var SETTINGS_DEFAULTS={transport:"auto",sessionShareDestination:"auto",steeringMode:"one-at-a-time",followUpMode:"one-at-a-time",compaction:{enabled:!0,reserveTokens:16384,keepRecentTokens:2e4},branchSummary:{reserveTokens:16384,skipPrompt:!1},retry:{enabled:!0,maxRetries:3,baseDelayMs:2e3,maxAgentDelayMs:DEFAULT_MAX_AGENT_RETRY_DELAY_MS,provider:{maxRetryDelayMs:6e4}},hideThinkingBlock:!1,showCacheMissNotices:!1,quietStartup:!1,defaultProjectTrust:"ask",collapseChangelog:!1,enableInstallTelemetry:!0,enableAnalytics:!1,enableSkillCommands:!0,terminal:{showImages:!0,imageWidthCells:60,clearOnShrink:!1,showTerminalProgress:!1},images:{autoResize:!0,blockImages:!1},doubleEscapeAction:"tree",treeFilterMode:"default",editorPaddingX:0,outputPad:1,autocompleteMaxVisible:5,markdown:{codeBlockIndent:" ",mermaid:"streaming"},warnings:{anthropicExtraUsage:!0},codemode:{mode:"on",inlineBudget:3e3},cacheWarming:"streaming",tuiMode:"fullscreen",fullscreenExitOutput:"transcript",fullscreenScrollbar:"auto",fullscreenCopyOnSelect:!0,fullscreenWheelScrollLines:"auto"};function wrapToolDefinition(definition,ctxFactory){return{name:definition.name,label:definition.label,description:definition.description,parameters:definition.parameters,outputSchema:definition.outputSchema,constrainedSampling:definition.constrainedSampling,prepareArguments:definition.prepareArguments,executionMode:definition.executionMode,execute:(toolCallId,params,signal,onUpdate,ctx)=>definition.execute(toolCallId,params,signal,onUpdate,ctx??ctxFactory?.(toolCallId,signal))}}function createToolDefinitionFromAgentTool(tool){return{name:tool.name,label:tool.label,description:tool.description,parameters:tool.parameters,outputSchema:tool.outputSchema,constrainedSampling:tool.constrainedSampling,prepareArguments:tool.prepareArguments,executionMode:tool.executionMode,execute:async(toolCallId,params,signal,onUpdate)=>tool.execute(toolCallId,params,signal,onUpdate)}}var loadCodemodeExecutor=()=>import("./execute-
|
|
43
|
+
`)}`}],details:{loaded:tools.map(tool=>tool.name)}}}}}import{join as join2}from"node:path";function buildProviderErrorPattern(patterns){return new RegExp(patterns.join("|"),"i")}var NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN=buildProviderErrorPattern(["GoUsageLimitError","FreeUsageLimitError","Monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing","subscription_sharing_usage_limit_exceeded"]),RETRYABLE_PROVIDER_ERROR_PATTERN=buildProviderErrorPattern(["overloaded","server_busy","servers are currently busy","currently experiencing high demand","model is at capacity","rate.?limit","too many requests","429","500","502","503","504","520","524","service.?(?:is.?)?(?:temporarily.?)?unavailable","server.?error","internal.?error","provider.?returned.?(?:an.?)?error","upstream_error_frame","exceeded request buffer limit while retrying upstream","unable to forward upstream","network.?error","connection.?error","connection.?failed","connection.?refused","connection.?lost","other side closed","fetch failed","getaddrinfo","ENOTFOUND","EAI_AGAIN","ECONNREFUSED","ENETUNREACH","ENETDOWN","EHOSTUNREACH","upstream.?connect","reset before headers","socket hang up","socket connection was closed","timed? out","timeout","terminated","websocket.?closed","websocket.?error","ended without","stream ended before message_stop","stream ended before a terminal response event","http2 request did not get a response","pending stream has been canceled","retry delay","you can retry your request","try your request again","please retry your request","ResourceExhausted","subscription_sharing_usage_unavailable","subscription_sharing_user_unavailable"]),DEFAULT_MAX_AGENT_RETRY_DELAY_MS=6e4;function retryDelayMs(policy,attempt){let delay=policy.baseDelayMs*2**Math.max(0,attempt-1),safeDelay=Number.isSafeInteger(delay)?delay:Number.MAX_SAFE_INTEGER;return Math.min(safeDelay,policy.maxAgentDelayMs??DEFAULT_MAX_AGENT_RETRY_DELAY_MS)}var RetrySleepAbortError=class extends Error{constructor(){super("Aborted")}};function sleep(ms,signal){return new Promise((resolve,reject)=>{if(signal?.aborted){reject(new RetrySleepAbortError);return}let timeout=setTimeout(resolve,ms);signal?.addEventListener("abort",()=>{clearTimeout(timeout),reject(new RetrySleepAbortError)},{once:!0})})}async function retryAssistantCall(produce,policy,signal,callbacks){let maxAttempts=policy?.enabled?policy.maxRetries:0,attempt=0,lastRetry;for(;;){let response=await produce();if(response.stopReason==="aborted")return lastRetry&&await callbacks?.onRetryFinished?.(!1,lastRetry.attempt),response;if(response.stopReason!=="error")return lastRetry&&await callbacks?.onRetryFinished?.(!0,lastRetry.attempt),response;if(attempt>=maxAttempts||!isRetryableAssistantError(response))return lastRetry&&await callbacks?.onRetryFinished?.(!1,lastRetry.attempt,response.errorMessage),response;attempt++,lastRetry={attempt,errorMessage:response.errorMessage||"Unknown error"};let delayMs=retryDelayMs(policy,attempt);await callbacks?.onRetryScheduled?.(attempt,maxAttempts,delayMs,lastRetry.errorMessage);try{await sleep(delayMs,signal)}catch(error){if(await callbacks?.onRetryFinished?.(!1,attempt,lastRetry.errorMessage),error instanceof RetrySleepAbortError){let{errorMessage:_errorMessage,...rest}=response;return{...rest,stopReason:"aborted"}}throw error}await callbacks?.onRetryAttemptStart?.()}}function isRetryableAssistantError(message){if(message.stopReason!=="error"||!message.errorMessage)return!1;let errorMessage=message.errorMessage;return NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN.test(errorMessage)?!1:RETRYABLE_PROVIDER_ERROR_PATTERN.test(errorMessage)}var CONNECTION_FAILURE_ERROR_PATTERN=buildProviderErrorPattern(["getaddrinfo","ENOTFOUND","EAI_AGAIN","ECONNREFUSED","ENETUNREACH","ENETDOWN","EHOSTUNREACH","EADDRNOTAVAIL","UND_ERR_CONNECT_TIMEOUT","Connect Timeout Error","before secure TLS connection was established","when HTTP Tunneling","^Qoder: connection_failed$"]);function isConnectionFailureAssistantError(message){return isRetryableAssistantError(message)&&CONNECTION_FAILURE_ERROR_PATTERN.test(message.errorMessage)}var SETTINGS_DEFAULTS={transport:"auto",sessionShareDestination:"auto",steeringMode:"one-at-a-time",followUpMode:"one-at-a-time",compaction:{enabled:!0,reserveTokens:16384,keepRecentTokens:2e4},branchSummary:{reserveTokens:16384,skipPrompt:!1},retry:{enabled:!0,maxRetries:3,baseDelayMs:2e3,maxAgentDelayMs:DEFAULT_MAX_AGENT_RETRY_DELAY_MS,provider:{maxRetryDelayMs:6e4}},hideThinkingBlock:!1,showCacheMissNotices:!1,quietStartup:!1,defaultProjectTrust:"ask",collapseChangelog:!1,enableInstallTelemetry:!0,enableAnalytics:!1,enableSkillCommands:!0,terminal:{showImages:!0,imageWidthCells:60,clearOnShrink:!1,showTerminalProgress:!1},images:{autoResize:!0,blockImages:!1},doubleEscapeAction:"tree",treeFilterMode:"default",editorPaddingX:0,outputPad:1,autocompleteMaxVisible:5,markdown:{codeBlockIndent:" ",mermaid:"streaming"},warnings:{anthropicExtraUsage:!0},codemode:{mode:"on",inlineBudget:3e3},cacheWarming:"streaming",tuiMode:"fullscreen",fullscreenExitOutput:"transcript",fullscreenScrollbar:"auto",fullscreenCopyOnSelect:!0,fullscreenWheelScrollLines:"auto"};function wrapToolDefinition(definition,ctxFactory){return{name:definition.name,label:definition.label,description:definition.description,parameters:definition.parameters,outputSchema:definition.outputSchema,constrainedSampling:definition.constrainedSampling,prepareArguments:definition.prepareArguments,executionMode:definition.executionMode,execute:(toolCallId,params,signal,onUpdate,ctx)=>definition.execute(toolCallId,params,signal,onUpdate,ctx??ctxFactory?.(toolCallId,signal))}}function createToolDefinitionFromAgentTool(tool){return{name:tool.name,label:tool.label,description:tool.description,parameters:tool.parameters,outputSchema:tool.outputSchema,constrainedSampling:tool.constrainedSampling,prepareArguments:tool.prepareArguments,executionMode:tool.executionMode,execute:async(toolCallId,params,signal,onUpdate)=>tool.execute(toolCallId,params,signal,onUpdate)}}var loadCodemodeExecutor=()=>import("./execute-ULZNGRYF.js");var CODE_PREVIEW_LINES=10,CALL_PREVIEW_COUNT=8,OUTPUT_PREVIEW_LINES=5,COLLAPSED_ARGS_CHARS2=80,SCRIPT_HEADER=/^Script (completed|failed)\nWall time [\d.]+ seconds\nOutput:\n$/;function expandHint(theme,hidden,noun){return`${theme.fg("muted",`... (${hidden} more ${noun},`)} ${keyHint("app.tools.expand","to expand")}${theme.fg("muted",")")}`}function formatDuration(ms){return ms===void 0?"":ms<1e3?`${Math.round(ms)}ms`:`${(ms/1e3).toFixed(1)}s`}function formatCost(cost){return`$${cost>=.01?cost.toFixed(2):cost.toPrecision(2)}`}function statusIcon(call,theme){switch(call.status){case"running":return theme.fg("warning","\u2026");case"ok":return theme.fg("success","\u2713");case"error":return theme.fg("error","\u2717");case"cancelled":return theme.fg("muted","\u2298")}}function formatCall(call,theme,expanded){let args=!expanded&&call.args.length>COLLAPSED_ARGS_CHARS2?`${call.args.slice(0,COLLAPSED_ARGS_CHARS2-3)}...`:call.args,duration=formatDuration(call.durationMs),line=`${statusIcon(call,theme)} ${theme.fg("toolTitle",call.name)}`;return args&&(line+=` ${theme.fg("muted",args)}`),duration&&(line+=` ${theme.fg("dim",duration)}`),call.cost&&(line+=` ${theme.fg("dim",formatCost(call.cost))}`),expanded&&call.error&&(line+=`
|
|
44
44
|
${theme.fg("error",call.error.split(`
|
|
45
45
|
`).join(`
|
|
46
46
|
`))}`),line}var codemodeRenderers={renderCall(args,theme,context){startToolTimer(context);let code=str(args?.code),title=theme.fg("toolTitle",theme.bold("codemode")),component=context.lastComponent??new Container;if(component.clear(),code===null)return component.addChild(new Text(`${title} ${theme.fg("error","[invalid arg]")}`,0,0)),component;if(component.addChild(new Text(title,0,0)),code){let highlighted=highlightCode(replaceTabs(code.replace(/\r/g,"").trimEnd()),"javascript").join(`
|
|
@@ -61,4 +61,4 @@ ${description}`:""}`)}for(let entry of visible)toolSections.push(entry.section)}
|
|
|
61
61
|
|
|
62
62
|
`)}function describeFields(schema,depth){if(typeof schema!="object"||schema===null)return;let{type,properties,required}=schema;if(type!=="object"||typeof properties!="object"||properties===null)return;let requiredNames=new Set(Array.isArray(required)?required:[]);return`{ ${Object.entries(properties).map(([name,field])=>{let nested=depth>0?describeFields(field,depth-1):void 0;return`${name}${requiredNames.has(name)?"":"?"}${nested?`: ${nested}`:""}`}).join(", ")} }`}function describeOutput(schema){let type=renderToolOutputType(schema);return type==="string"?"a string":`\`${describeFields(schema,1)??type.replace(/\s+/g," ")}\``}function describeScriptCall(tool){return`${tool.description.trim()}
|
|
63
63
|
|
|
64
|
-
Codemode: \`tools.${toCodemodeIdentifier(tool.name)}(args)\` resolves to ${describeOutput(toCodemodeDeclaration(tool).outputSchema)}.`}function prepareCodemodeLoadout(loadout,options){let mode=options.getMode?.()??SETTINGS_DEFAULTS.codemode.mode,isDirect=tool=>loadout.getExposure(tool.name)==="direct",callable=getCodemodeCallableTools(loadout.callable),callableNames=new Set(callable.map(tool=>tool.name)),descriptions={};if(mode==="on")for(let tool of loadout.declared)callableNames.has(tool.name)&&(descriptions[tool.name]=describeScriptCall(tool));let listed=mode==="only"?callable:callable.filter(tool=>!isDirect(tool)),namespaces=new Map(listed.flatMap(tool=>{let namespace=loadout.getNamespace(tool.name);return namespace?[[tool.name,namespace]]:[]})),guidelines=new Map(listed.map(tool=>[tool.name,loadout.getPromptGuidelines(tool.name)]));descriptions[CODEMODE_TOOL_NAME]=createCodemodeDescription(listed,{models:options.models===!0,namespaces,guidelines,deferred:new Set(listed.filter(tool=>loadout.getExposure(tool.name)==="deferred").map(tool=>tool.name)),inlineBudget:options.getInlineBudget?.()??DEFAULT_CODEMODE_INLINE_BUDGET});let declaredNames=new Set(loadout.declared.map(tool=>tool.name));return{descriptions,hiddenDeclarations:mode==="only"?callable.filter(tool=>isDirect(tool)&&declaredNames.has(tool.name)).map(tool=>tool.name):[]}}var DISCOVERY_GLOBALS=/\b(searchTools|describeNamespace|describeTool|ALL_TOOLS)\b/;function getScriptReach(code){return typeof code!="string"?[]:DISCOVERY_GLOBALS.test(code)?"all":code.match(/\w+/g)??[]}function createCodemodeToolDefinition(options={}){return{name:CODEMODE_TOOL_NAME,label:CODEMODE_TOOL_NAME,description:createCodemodeDescription([],{models:options.models===!0}),promptSnippet:codemodeToolSystemPromptContribution.snippet,promptGuidelines:[...codemodeToolSystemPromptContribution.guidelines],parameters:codemodeSchema,exposure:"model-only",prepareLoadout:loadout=>prepareCodemodeLoadout(loadout,options),reachesTools:input=>getScriptReach(input.code),constrainedSampling:{type:"grammar",variants:{openai_lark:CODEMODE_SOURCE_GRAMMAR}},execute:async(toolCallId,params,signal,onUpdate,ctx)=>(await loadCodemodeExecutor()).executeCodemode(toolCallId,params,signal,onUpdate,ctx,options),...codemodeRenderers}}export{guard_exports,emit_exports,globals_exports,guard_default,settings_exports,Clone,IsSchema,_Array_,IsArray3 as IsArray,ArrayOptions,IsConstructor3 as IsConstructor,IsFunction3 as IsFunction,Ref,IsRef,IsNever,IsOptional,_Object_,IsObject3 as IsObject,Unknown,IsCyclic,arguments_exports,IsEnum,Intersect,IsIntersect,environment_exports,Unreachable,hash_exports,Get2 as Get,IsCodec,IsRefine,IsBigInt3 as IsBigInt,IsBoolean4 as IsBoolean,IsInteger3 as IsInteger,Literal,IsLiteralBigInt,IsLiteralBoolean,IsLiteralNumber,IsLiteralString,IsLiteral,IsNull3 as IsNull,IsNumber4 as IsNumber,IsSymbol3 as IsSymbol,String2 as String,IsString4 as IsString,Union,IsUnion,TemplateLiteralDecode,Tuple,IsTuple,Flatten,Record,RecordPattern,RecordKey,RecordValue,IsRecord,IsUndefined3 as IsUndefined,IsVoid,IsTemplateLiteral,With2 as With,Instantiate,Evaluate2 as Evaluate,Priority,typebox_exports,build_exports,DEFAULT_MAX_AGENT_RETRY_DELAY_MS,retryDelayMs,retryAssistantCall,isRetryableAssistantError,SETTINGS_DEFAULTS,splitIncompleteAnsiSuffix,stripAnsi,writeOutputFile,createOutputFileStream,DEFAULT_MAX_LINES,DEFAULT_MAX_BYTES,formatSize,truncateHead,truncateTail,truncateLine,truncateMiddle,createUsageTotals,addUsageToTotals,combineUsage,getUsageCostBreakdown,wrapToolDefinition,createToolDefinitionFromAgentTool,truncateToVisualLines,VisualLinePreview,shortenPath,str,formatReadLineRange,replaceTabs,normalizeDisplayText,getTextOutput,formatToolCallWithArgs,startToolTimer,toolTimerText,invalidArgText,renderToolPath,toCodemodeIdentifier,renderToolSample,parseCodemodeSource,TOOL_SEARCH_TOOL_NAME,DEFAULT_TOOL_SEARCH_LIMIT,createToolSearchDocument,Bm25Ranker,createToolSearchToolDefinition,CODEMODE_TOOL_NAME,CODEMODE_STORE_ENTRY_TYPE,CODEMODE_DOCS_PATH,toCodemodeDeclaration,getCodemodeCallableTools,createCodemodeToolDefinition};
|
|
64
|
+
Codemode: \`tools.${toCodemodeIdentifier(tool.name)}(args)\` resolves to ${describeOutput(toCodemodeDeclaration(tool).outputSchema)}.`}function prepareCodemodeLoadout(loadout,options){let mode=options.getMode?.()??SETTINGS_DEFAULTS.codemode.mode,isDirect=tool=>loadout.getExposure(tool.name)==="direct",callable=getCodemodeCallableTools(loadout.callable),callableNames=new Set(callable.map(tool=>tool.name)),descriptions={};if(mode==="on")for(let tool of loadout.declared)callableNames.has(tool.name)&&(descriptions[tool.name]=describeScriptCall(tool));let listed=mode==="only"?callable:callable.filter(tool=>!isDirect(tool)),namespaces=new Map(listed.flatMap(tool=>{let namespace=loadout.getNamespace(tool.name);return namespace?[[tool.name,namespace]]:[]})),guidelines=new Map(listed.map(tool=>[tool.name,loadout.getPromptGuidelines(tool.name)]));descriptions[CODEMODE_TOOL_NAME]=createCodemodeDescription(listed,{models:options.models===!0,namespaces,guidelines,deferred:new Set(listed.filter(tool=>loadout.getExposure(tool.name)==="deferred").map(tool=>tool.name)),inlineBudget:options.getInlineBudget?.()??DEFAULT_CODEMODE_INLINE_BUDGET});let declaredNames=new Set(loadout.declared.map(tool=>tool.name));return{descriptions,hiddenDeclarations:mode==="only"?callable.filter(tool=>isDirect(tool)&&declaredNames.has(tool.name)).map(tool=>tool.name):[]}}var DISCOVERY_GLOBALS=/\b(searchTools|describeNamespace|describeTool|ALL_TOOLS)\b/;function getScriptReach(code){return typeof code!="string"?[]:DISCOVERY_GLOBALS.test(code)?"all":code.match(/\w+/g)??[]}function createCodemodeToolDefinition(options={}){return{name:CODEMODE_TOOL_NAME,label:CODEMODE_TOOL_NAME,description:createCodemodeDescription([],{models:options.models===!0}),promptSnippet:codemodeToolSystemPromptContribution.snippet,promptGuidelines:[...codemodeToolSystemPromptContribution.guidelines],parameters:codemodeSchema,exposure:"model-only",prepareLoadout:loadout=>prepareCodemodeLoadout(loadout,options),reachesTools:input=>getScriptReach(input.code),constrainedSampling:{type:"grammar",variants:{openai_lark:CODEMODE_SOURCE_GRAMMAR}},execute:async(toolCallId,params,signal,onUpdate,ctx)=>(await loadCodemodeExecutor()).executeCodemode(toolCallId,params,signal,onUpdate,ctx,options),...codemodeRenderers}}export{guard_exports,emit_exports,globals_exports,guard_default,settings_exports,Clone,IsSchema,_Array_,IsArray3 as IsArray,ArrayOptions,IsConstructor3 as IsConstructor,IsFunction3 as IsFunction,Ref,IsRef,IsNever,IsOptional,_Object_,IsObject3 as IsObject,Unknown,IsCyclic,arguments_exports,IsEnum,Intersect,IsIntersect,environment_exports,Unreachable,hash_exports,Get2 as Get,IsCodec,IsRefine,IsBigInt3 as IsBigInt,IsBoolean4 as IsBoolean,IsInteger3 as IsInteger,Literal,IsLiteralBigInt,IsLiteralBoolean,IsLiteralNumber,IsLiteralString,IsLiteral,IsNull3 as IsNull,IsNumber4 as IsNumber,IsSymbol3 as IsSymbol,String2 as String,IsString4 as IsString,Union,IsUnion,TemplateLiteralDecode,Tuple,IsTuple,Flatten,Record,RecordPattern,RecordKey,RecordValue,IsRecord,IsUndefined3 as IsUndefined,IsVoid,IsTemplateLiteral,With2 as With,Instantiate,Evaluate2 as Evaluate,Priority,typebox_exports,build_exports,DEFAULT_MAX_AGENT_RETRY_DELAY_MS,retryDelayMs,retryAssistantCall,isRetryableAssistantError,isConnectionFailureAssistantError,SETTINGS_DEFAULTS,splitIncompleteAnsiSuffix,stripAnsi,writeOutputFile,createOutputFileStream,DEFAULT_MAX_LINES,DEFAULT_MAX_BYTES,formatSize,truncateHead,truncateTail,truncateLine,truncateMiddle,createUsageTotals,addUsageToTotals,combineUsage,getUsageCostBreakdown,wrapToolDefinition,createToolDefinitionFromAgentTool,truncateToVisualLines,VisualLinePreview,shortenPath,str,formatReadLineRange,replaceTabs,normalizeDisplayText,getTextOutput,formatToolCallWithArgs,startToolTimer,toolTimerText,invalidArgText,renderToolPath,toCodemodeIdentifier,renderToolSample,parseCodemodeSource,TOOL_SEARCH_TOOL_NAME,DEFAULT_TOOL_SEARCH_LIMIT,createToolSearchDocument,Bm25Ranker,createToolSearchToolDefinition,CODEMODE_TOOL_NAME,CODEMODE_STORE_ENTRY_TYPE,CODEMODE_DOCS_PATH,toCodemodeDeclaration,getCodemodeCallableTools,createCodemodeToolDefinition};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{isRecord,parseClassifierUsage,postClassifierRequest,requiredNumber}from"./chunk-XIX7LUWI.js";import{formatProviderError,normalizeProviderError}from"./chunk-
|
|
2
|
+
import{isRecord,parseClassifierUsage,postClassifierRequest,requiredNumber}from"./chunk-XIX7LUWI.js";import{formatProviderError,normalizeProviderError}from"./chunk-CTEAMRDY.js";function probabilities(label,value,id){if(!isRecord(value))throw new Error(`${label} returned invalid probabilities for ${id}`);return Object.fromEntries(Object.entries(value).map(([key,probability])=>[key,requiredNumber(label,probability,`probability for ${id}.${key}`)]))}function parseAnswers(label,value,context){if(!isRecord(value))throw new Error(`${label} returned an unexpected response`);let answers=[];for(let[id,question]of Object.entries(context.questions)){let answer=value[id];if(!isRecord(answer))throw new Error(`${label} did not return an answer for ${id}`);if(question.type==="choice"){if(answer.type!=="choice"||typeof answer.choice!="string")throw new Error(`${label} did not return a choice answer for ${id}`);answers.push([id,{type:"choice",choice:answer.choice,probabilities:probabilities(label,answer.probabilities,id),confidence:requiredNumber(label,answer.confidence,`confidence for ${id}`)}])}else if(question.type==="score"){if(answer.type!=="score")throw new Error(`${label} did not return a score answer for ${id}`);answers.push([id,{type:"score",score:requiredNumber(label,answer.score,`score for ${id}`),confidence:requiredNumber(label,answer.confidence,`confidence for ${id}`)}])}else{if(answer.type!=="noul")throw new Error(`${label} did not return a bool answer for ${id}`);answers.push([id,{type:"bool",probability:requiredNumber(label,answer.noul,`probability for ${id}`)}])}}return Object.fromEntries(answers)}function wireRequest(context){return{state:context.state,questions:Object.fromEntries(Object.entries(context.questions).map(([id,question])=>[id,question.type==="bool"?{...question,type:"noul"}:question]))}}async function classifySystemOne(transport,model,context,options){let output={api:model.api,provider:model.provider,model:model.id,answers:{},stopReason:"stop",timestamp:Date.now()};try{if(model.api!==transport.api)throw new Error(`Unsupported classifier API: ${model.api}`);if(context.images?.length)throw new Error(`${transport.label} does not support image input`);let body=await postClassifierRequest(transport.label,transport.url(model),model,transport.payload(model,wireRequest(context)),options),result=transport.output(body),usage=parseClassifierUsage(result.usage,model);return usage&&(output.usage=usage),output.answers=parseAnswers(transport.label,result.answers,context),output}catch(error){return output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error),`${transport.label} error`),output}}export{classifySystemOne};
|
package/runtime/pi/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-CTEAMRDY.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
+
function normalizeProviderError(error){if(!(error instanceof Error))return{message:safeJsonStringify(error),messageCarriesBody:!1};let sdkError=error,status=extractStatus(sdkError),body=extractBody(sdkError),messageCarriesBody=body===void 0||error.message.includes(body);return{status,body,message:withConnectFailureCause(error.message,error),messageCarriesBody}}var UNSENT_CONNECT_ERROR_CODES=new Set(["ENOTFOUND","EAI_AGAIN","ECONNREFUSED","ENETUNREACH","ENETDOWN","EHOSTUNREACH","EADDRNOTAVAIL","UND_ERR_CONNECT_TIMEOUT"]),UNSENT_CONNECT_ERROR_MESSAGE=/before secure TLS connection was established|when HTTP Tunneling/;function connectFailureCause(error){let current=error;for(let depth=0;depth<5&¤t instanceof Error;depth++){let code=current.code;if(typeof code=="string"&&UNSENT_CONNECT_ERROR_CODES.has(code)||UNSENT_CONNECT_ERROR_MESSAGE.test(current.message))return current.message;current=current.cause??(current instanceof AggregateError?current.errors[0]:void 0)}}function withConnectFailureCause(message,error){let cause=connectFailureCause(error);return cause===void 0||message.includes(cause)?message:`${message} (caused by: ${cause})`}function extractStatus(error){if(typeof error.statusCode=="number")return error.statusCode;if(typeof error.status=="number")return error.status;if(typeof error.$metadata?.httpStatusCode=="number")return error.$metadata.httpStatusCode;if(typeof error.$response?.statusCode=="number")return error.$response.statusCode}function extractBody(error){let bodyText=pickBodyText(error);if(bodyText===void 0)return;let trimmed=bodyText.trim();if(trimmed.length!==0)return truncateErrorText(trimmed,4e3)}function pickBodyText(error){if(typeof error.body=="string")return error.body;if(isPlainNonEmptyObject(error.error))return safeJsonStringify(error.error);let responseBody=error.$response?.body;if(typeof responseBody=="string")return responseBody;if(!isReadableStreamLike(responseBody)&&isPlainNonEmptyObject(responseBody))return safeJsonStringify(responseBody)}function isReadableStreamLike(value){return typeof value=="object"&&value!==null&&"pipe"in value&&typeof value.pipe=="function"}function isPlainNonEmptyObject(value){if(typeof value!="object"||value===null)return!1;let proto=Object.getPrototypeOf(value);return proto!==Object.prototype&&proto!==null?!1:Object.keys(value).length>0}function formatProviderError(norm,prefix){return norm.messageCarriesBody||norm.status===void 0||norm.body===void 0?prefix!==void 0&&norm.status!==void 0?`${prefix} (${norm.status}): ${norm.message}`:norm.message:prefix!==void 0?`${prefix} (${norm.status}): ${norm.body}`:`${norm.status}: ${norm.body}`}function truncateErrorText(text,maxChars){return text.length<=maxChars?text:`${text.slice(0,maxChars)}... [truncated ${text.length-maxChars} chars]`}function safeJsonStringify(value){try{let serialized=JSON.stringify(value);return serialized===void 0?String(value):serialized}catch{return String(value)}}export{normalizeProviderError,withConnectFailureCause,formatProviderError};
|