@f5-sales-demo/pi-ai 19.51.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/CHANGELOG.md +1997 -0
  2. package/README.md +1160 -0
  3. package/package.json +135 -0
  4. package/src/api-registry.ts +95 -0
  5. package/src/auth-storage.ts +2694 -0
  6. package/src/cli.ts +493 -0
  7. package/src/index.ts +42 -0
  8. package/src/model-cache.ts +97 -0
  9. package/src/model-manager.ts +349 -0
  10. package/src/model-thinking.ts +561 -0
  11. package/src/models.json +49439 -0
  12. package/src/models.json.d.ts +9 -0
  13. package/src/models.ts +56 -0
  14. package/src/prompts/turn-aborted-guidance.md +4 -0
  15. package/src/provider-details.ts +81 -0
  16. package/src/provider-models/descriptors.ts +285 -0
  17. package/src/provider-models/google.ts +90 -0
  18. package/src/provider-models/index.ts +4 -0
  19. package/src/provider-models/openai-compat.ts +2074 -0
  20. package/src/provider-models/special.ts +106 -0
  21. package/src/providers/amazon-bedrock.ts +706 -0
  22. package/src/providers/anthropic.ts +1682 -0
  23. package/src/providers/azure-openai-responses.ts +391 -0
  24. package/src/providers/cursor/gen/agent_pb.ts +15274 -0
  25. package/src/providers/cursor/proto/agent.proto +3526 -0
  26. package/src/providers/cursor/proto/buf.gen.yaml +6 -0
  27. package/src/providers/cursor/proto/buf.yaml +17 -0
  28. package/src/providers/cursor.ts +2218 -0
  29. package/src/providers/github-copilot-headers.ts +140 -0
  30. package/src/providers/gitlab-duo.ts +381 -0
  31. package/src/providers/google-gemini-cli.ts +1133 -0
  32. package/src/providers/google-shared.ts +354 -0
  33. package/src/providers/google-vertex.ts +436 -0
  34. package/src/providers/google.ts +381 -0
  35. package/src/providers/kimi.ts +151 -0
  36. package/src/providers/openai-codex/constants.ts +43 -0
  37. package/src/providers/openai-codex/request-transformer.ts +158 -0
  38. package/src/providers/openai-codex/response-handler.ts +81 -0
  39. package/src/providers/openai-codex-responses.ts +2345 -0
  40. package/src/providers/openai-completions-compat.ts +159 -0
  41. package/src/providers/openai-completions.ts +1290 -0
  42. package/src/providers/openai-responses-shared.ts +452 -0
  43. package/src/providers/openai-responses.ts +519 -0
  44. package/src/providers/register-builtins.ts +329 -0
  45. package/src/providers/synthetic.ts +154 -0
  46. package/src/providers/transform-messages.ts +234 -0
  47. package/src/rate-limit-utils.ts +84 -0
  48. package/src/stream.ts +728 -0
  49. package/src/types.ts +546 -0
  50. package/src/usage/claude.ts +337 -0
  51. package/src/usage/gemini.ts +248 -0
  52. package/src/usage/github-copilot.ts +421 -0
  53. package/src/usage/google-antigravity.ts +200 -0
  54. package/src/usage/kimi.ts +286 -0
  55. package/src/usage/minimax-code.ts +31 -0
  56. package/src/usage/openai-codex.ts +387 -0
  57. package/src/usage/zai.ts +247 -0
  58. package/src/usage.ts +130 -0
  59. package/src/utils/abort.ts +36 -0
  60. package/src/utils/anthropic-auth.ts +293 -0
  61. package/src/utils/discovery/antigravity.ts +261 -0
  62. package/src/utils/discovery/codex.ts +371 -0
  63. package/src/utils/discovery/cursor.ts +306 -0
  64. package/src/utils/discovery/gemini.ts +248 -0
  65. package/src/utils/discovery/index.ts +5 -0
  66. package/src/utils/discovery/openai-compatible.ts +224 -0
  67. package/src/utils/event-stream.ts +209 -0
  68. package/src/utils/http-inspector.ts +165 -0
  69. package/src/utils/idle-iterator.ts +176 -0
  70. package/src/utils/json-parse.ts +28 -0
  71. package/src/utils/oauth/alibaba-coding-plan.ts +59 -0
  72. package/src/utils/oauth/anthropic.ts +134 -0
  73. package/src/utils/oauth/api-key-validation.ts +92 -0
  74. package/src/utils/oauth/callback-server.ts +276 -0
  75. package/src/utils/oauth/cerebras.ts +59 -0
  76. package/src/utils/oauth/cloudflare-ai-gateway.ts +48 -0
  77. package/src/utils/oauth/cursor.ts +157 -0
  78. package/src/utils/oauth/github-copilot.ts +358 -0
  79. package/src/utils/oauth/gitlab-duo.ts +123 -0
  80. package/src/utils/oauth/google-antigravity.ts +275 -0
  81. package/src/utils/oauth/google-gemini-cli.ts +334 -0
  82. package/src/utils/oauth/huggingface.ts +62 -0
  83. package/src/utils/oauth/index.ts +512 -0
  84. package/src/utils/oauth/kagi.ts +47 -0
  85. package/src/utils/oauth/kilo.ts +87 -0
  86. package/src/utils/oauth/kimi.ts +251 -0
  87. package/src/utils/oauth/litellm.ts +81 -0
  88. package/src/utils/oauth/lm-studio.ts +40 -0
  89. package/src/utils/oauth/minimax-code.ts +78 -0
  90. package/src/utils/oauth/moonshot.ts +59 -0
  91. package/src/utils/oauth/nanogpt.ts +51 -0
  92. package/src/utils/oauth/nvidia.ts +70 -0
  93. package/src/utils/oauth/oauth.html +199 -0
  94. package/src/utils/oauth/ollama.ts +47 -0
  95. package/src/utils/oauth/openai-codex.ts +190 -0
  96. package/src/utils/oauth/opencode.ts +49 -0
  97. package/src/utils/oauth/parallel.ts +46 -0
  98. package/src/utils/oauth/perplexity.ts +200 -0
  99. package/src/utils/oauth/pkce.ts +18 -0
  100. package/src/utils/oauth/qianfan.ts +58 -0
  101. package/src/utils/oauth/qwen-portal.ts +60 -0
  102. package/src/utils/oauth/synthetic.ts +60 -0
  103. package/src/utils/oauth/tavily.ts +46 -0
  104. package/src/utils/oauth/together.ts +59 -0
  105. package/src/utils/oauth/types.ts +89 -0
  106. package/src/utils/oauth/venice.ts +59 -0
  107. package/src/utils/oauth/vercel-ai-gateway.ts +47 -0
  108. package/src/utils/oauth/vllm.ts +40 -0
  109. package/src/utils/oauth/xiaomi.ts +88 -0
  110. package/src/utils/oauth/zai.ts +60 -0
  111. package/src/utils/oauth/zenmux.ts +51 -0
  112. package/src/utils/overflow.ts +134 -0
  113. package/src/utils/retry-after.ts +110 -0
  114. package/src/utils/retry.ts +93 -0
  115. package/src/utils/schema/CONSTRAINTS.md +160 -0
  116. package/src/utils/schema/adapt.ts +20 -0
  117. package/src/utils/schema/compatibility.ts +397 -0
  118. package/src/utils/schema/dereference.ts +93 -0
  119. package/src/utils/schema/equality.ts +93 -0
  120. package/src/utils/schema/fields.ts +147 -0
  121. package/src/utils/schema/index.ts +9 -0
  122. package/src/utils/schema/normalize-cca.ts +479 -0
  123. package/src/utils/schema/sanitize-google.ts +212 -0
  124. package/src/utils/schema/strict-mode.ts +385 -0
  125. package/src/utils/schema/types.ts +5 -0
  126. package/src/utils/tool-choice.ts +81 -0
  127. package/src/utils/validation.ts +664 -0
  128. package/src/utils.ts +147 -0
@@ -0,0 +1,40 @@
1
+ /**
2
+ * vLLM login flow.
3
+ *
4
+ * vLLM is commonly self-hosted with an OpenAI-compatible API at a local base URL.
5
+ * Some deployments require a bearer token, others allow unauthenticated access.
6
+ *
7
+ * This flow stores an API-key-style credential used by `/login` and auth storage.
8
+ */
9
+
10
+ import type { OAuthController, OAuthProvider } from "./types";
11
+
12
+ const PROVIDER_ID: OAuthProvider = "vllm";
13
+ const AUTH_URL = "https://docs.vllm.ai/en/latest/serving/openai_compatible_server.html";
14
+ const DEFAULT_LOCAL_BASE_URL = "http://127.0.0.1:8000/v1";
15
+ const DEFAULT_LOCAL_TOKEN = "vllm-local";
16
+ /**
17
+ * Login to vLLM.
18
+ *
19
+ * Opens vLLM OpenAI-compatible auth docs, prompts for an optional token,
20
+ * and returns a stored key value.
21
+ */
22
+ export async function loginVllm(options: OAuthController): Promise<string> {
23
+ if (!options.onPrompt) {
24
+ throw new Error(`${PROVIDER_ID} login requires onPrompt callback`);
25
+ }
26
+ options.onAuth?.({
27
+ url: AUTH_URL,
28
+ instructions: `Paste your vLLM API key if your server requires auth. Leave empty for local no-auth mode (default base URL: ${DEFAULT_LOCAL_BASE_URL}).`,
29
+ });
30
+ const apiKey = await options.onPrompt({
31
+ message: "Paste your vLLM API key (optional for local no-auth)",
32
+ placeholder: DEFAULT_LOCAL_TOKEN,
33
+ allowEmpty: true,
34
+ });
35
+ if (options.signal?.aborted) {
36
+ throw new Error("Login cancelled");
37
+ }
38
+ const trimmed = apiKey.trim();
39
+ return trimmed || DEFAULT_LOCAL_TOKEN;
40
+ }
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Xiaomi MiMo login flow.
3
+ *
4
+ * Xiaomi MiMo provides Anthropic-compatible models via
5
+ * https://api.xiaomimimo.com/anthropic.
6
+ *
7
+ * This is not OAuth - it's a simple API key flow:
8
+ * 1. Open browser to Xiaomi MiMo API key console
9
+ * 2. User copies their API key
10
+ * 3. User pastes the API key into the CLI
11
+ */
12
+
13
+ import type { OAuthController } from "./types";
14
+
15
+ const PROVIDER_ID = "xiaomi";
16
+ const PROVIDER_NAME = "Xiaomi MiMo";
17
+ const AUTH_URL = "https://platform.xiaomimimo.com/#/console/api-keys";
18
+ const API_BASE_URL = "https://api.xiaomimimo.com/anthropic";
19
+ const VALIDATION_MODEL = "mimo-v2-flash";
20
+ const ANTHROPIC_VERSION = "2023-06-01";
21
+ const VALIDATION_TIMEOUT_MS = 15_000;
22
+
23
+ async function validateXiaomiApiKey(apiKey: string, signal?: AbortSignal): Promise<void> {
24
+ const timeoutSignal = AbortSignal.timeout(VALIDATION_TIMEOUT_MS);
25
+ const requestSignal = signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal;
26
+
27
+ const response = await fetch(`${API_BASE_URL}/v1/messages`, {
28
+ method: "POST",
29
+ headers: {
30
+ "Content-Type": "application/json",
31
+ "x-api-key": apiKey,
32
+ "anthropic-version": ANTHROPIC_VERSION,
33
+ },
34
+ body: JSON.stringify({
35
+ model: VALIDATION_MODEL,
36
+ max_tokens: 1,
37
+ messages: [{ role: "user", content: "ping" }],
38
+ }),
39
+ signal: requestSignal,
40
+ });
41
+
42
+ if (response.ok) {
43
+ return;
44
+ }
45
+
46
+ let details = "";
47
+ try {
48
+ details = (await response.text()).trim();
49
+ } catch {
50
+ // ignore body parse errors, status is enough
51
+ }
52
+
53
+ const message = details
54
+ ? `${PROVIDER_NAME} API key validation failed (${response.status}): ${details}`
55
+ : `${PROVIDER_NAME} API key validation failed (${response.status})`;
56
+ throw new Error(message);
57
+ }
58
+
59
+ /**
60
+ * Login to Xiaomi MiMo.
61
+ *
62
+ * Opens browser to API keys page, prompts user to paste their API key.
63
+ * Returns the API key directly (not OAuthCredentials - this isn't OAuth).
64
+ */
65
+ export async function loginXiaomi(options: OAuthController): Promise<string> {
66
+ if (!options.onPrompt) {
67
+ throw new Error(`${PROVIDER_NAME} login requires onPrompt callback`);
68
+ }
69
+ options.onAuth?.({
70
+ url: AUTH_URL,
71
+ instructions: "Copy your API key from the Xiaomi MiMo console",
72
+ });
73
+ const apiKey = await options.onPrompt({
74
+ message: "Paste your Xiaomi API key",
75
+ placeholder: "sk-...",
76
+ });
77
+ if (options.signal?.aborted) {
78
+ throw new Error("Login cancelled");
79
+ }
80
+ const trimmed = apiKey.trim();
81
+ if (!trimmed) {
82
+ throw new Error("API key is required");
83
+ }
84
+
85
+ options.onProgress?.(`Validating ${PROVIDER_ID} API key...`);
86
+ await validateXiaomiApiKey(trimmed, options.signal);
87
+ return trimmed;
88
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Z.AI login flow.
3
+ *
4
+ * Z.AI is a platform that provides access to GLM models through an OpenAI-compatible API.
5
+ * API docs: https://docs.z.ai/guides/overview/quick-start
6
+ *
7
+ * This is not OAuth - it's a simple API key flow:
8
+ * 1. User gets their API key from https://z.ai/settings/api-keys
9
+ * 2. User pastes the API key into the CLI
10
+ */
11
+
12
+ import { validateOpenAICompatibleApiKey } from "./api-key-validation";
13
+ import type { OAuthController } from "./types";
14
+
15
+ const AUTH_URL = "https://z.ai/manage-apikey/apikey-list";
16
+ const API_BASE_URL = "https://api.z.ai/api/coding/paas/v4";
17
+ const VALIDATION_MODEL = "glm-4.7";
18
+
19
+ /**
20
+ * Login to Z.AI.
21
+ *
22
+ * Opens browser to API keys page, prompts user to paste their API key.
23
+ * Returns the API key directly (not OAuthCredentials - this isn't OAuth).
24
+ */
25
+ export async function loginZai(options: OAuthController): Promise<string> {
26
+ if (!options.onPrompt) {
27
+ throw new Error("Z.AI login requires onPrompt callback");
28
+ }
29
+
30
+ // Open browser to API keys page
31
+ options.onAuth?.({
32
+ url: AUTH_URL,
33
+ instructions: "Copy your API key from the dashboard",
34
+ });
35
+
36
+ // Prompt user to paste their API key
37
+ const apiKey = await options.onPrompt({
38
+ message: "Paste your Z.AI API key",
39
+ placeholder: "sk-...",
40
+ });
41
+
42
+ if (options.signal?.aborted) {
43
+ throw new Error("Login cancelled");
44
+ }
45
+
46
+ const trimmed = apiKey.trim();
47
+ if (!trimmed) {
48
+ throw new Error("API key is required");
49
+ }
50
+
51
+ options.onProgress?.("Validating API key...");
52
+ await validateOpenAICompatibleApiKey({
53
+ provider: "Z.AI",
54
+ apiKey: trimmed,
55
+ baseUrl: API_BASE_URL,
56
+ model: VALIDATION_MODEL,
57
+ signal: options.signal,
58
+ });
59
+ return trimmed;
60
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * ZenMux login flow.
3
+ *
4
+ * ZenMux provides both OpenAI-compatible and Anthropic-compatible endpoints.
5
+ * This is an API key flow:
6
+ * 1. Open browser to ZenMux API key settings
7
+ * 2. User copies their API key
8
+ * 3. User pastes the API key into CLI
9
+ */
10
+
11
+ import { validateApiKeyAgainstModelsEndpoint } from "./api-key-validation";
12
+ import type { OAuthController } from "./types";
13
+
14
+ const AUTH_URL = "https://zenmux.ai/settings/keys";
15
+ const API_BASE_URL = "https://zenmux.ai/api/v1";
16
+ const MODELS_URL = `${API_BASE_URL}/models`;
17
+
18
+ export async function loginZenMux(options: OAuthController): Promise<string> {
19
+ if (!options.onPrompt) {
20
+ throw new Error("ZenMux login requires onPrompt callback");
21
+ }
22
+
23
+ options.onAuth?.({
24
+ url: AUTH_URL,
25
+ instructions: "Create or copy your ZenMux API key",
26
+ });
27
+
28
+ const apiKey = await options.onPrompt({
29
+ message: "Paste your ZenMux API key",
30
+ placeholder: "sk-...",
31
+ });
32
+
33
+ if (options.signal?.aborted) {
34
+ throw new Error("Login cancelled");
35
+ }
36
+
37
+ const trimmed = apiKey.trim();
38
+ if (!trimmed) {
39
+ throw new Error("API key is required");
40
+ }
41
+
42
+ options.onProgress?.("Validating API key...");
43
+ await validateApiKeyAgainstModelsEndpoint({
44
+ provider: "ZenMux",
45
+ apiKey: trimmed,
46
+ modelsUrl: MODELS_URL,
47
+ signal: options.signal,
48
+ });
49
+
50
+ return trimmed;
51
+ }
@@ -0,0 +1,134 @@
1
+ import type { AssistantMessage } from "../types";
2
+
3
+ /**
4
+ * Regex patterns to detect context overflow errors from different providers.
5
+ *
6
+ * These patterns match error messages returned when the input exceeds
7
+ * the model's context window.
8
+ *
9
+ * Provider-specific patterns (with example error messages):
10
+ *
11
+ * - Anthropic: "prompt is too long: 213462 tokens > 200000 maximum"
12
+ * - OpenAI: "Your input exceeds the context window of this model"
13
+ * - Google: "The input token count (1196265) exceeds the maximum number of tokens allowed (1048575)"
14
+ * - xAI: "This model's maximum prompt length is 131072 but the request contains 537812 tokens"
15
+ * - Groq: "Please reduce the length of the messages or completion"
16
+ * - OpenRouter: "This endpoint's maximum context length is X tokens. However, you requested about Y tokens"
17
+ * - llama.cpp: "the request exceeds the available context size, try increasing it"
18
+ * - LM Studio: "tokens to keep from the initial prompt is greater than the context length"
19
+ * - GitHub Copilot: "prompt token count of X exceeds the limit of Y"
20
+ * - MiniMax: "invalid params, context window exceeds limit"
21
+ * - Kimi For Coding: "Your request exceeded model token limit: X (requested: Y)"
22
+ * - Anthropic 413: "request_too_large" / "Request exceeds the maximum size" (payload too large)
23
+ * - HTTP 413 variants: "Payload Too Large" / "Request Entity Too Large"
24
+ * - z.ai / GLM: Returns finish_reason: "model_context_window_exceeded" mapped to error message
25
+ * - z.ai: Does NOT error, accepts overflow silently - handled via usage.input > contextWindow
26
+ * - Ollama: Silently truncates input - not detectable via error message
27
+ */
28
+ const OVERFLOW_PATTERNS = [
29
+ /prompt is too long/i, // Anthropic
30
+ /input is too long for requested model/i, // Amazon Bedrock
31
+ /exceeds the context window/i, // OpenAI (Completions & Responses API)
32
+ /input token count.*exceeds the maximum/i, // Google (Gemini)
33
+ /maximum prompt length is \d+/i, // xAI (Grok)
34
+ /reduce the length of the messages/i, // Groq
35
+ /maximum context length is \d+ tokens/i, // OpenRouter (all backends)
36
+ /exceeds the limit of \d+/i, // GitHub Copilot
37
+ /exceeds the available context size/i, // llama.cpp server
38
+ /requested tokens?.*exceed.*context (window|length|size)/i, // llama.cpp / OpenAI-compatible local servers
39
+ /context (window|length|size).*(exceeded|overflow|too small)/i, // Generic local server variants
40
+ /(prompt|input).*(too long|too large).*(context|n_ctx)/i, // llama.cpp phrasing variants
41
+ /requested tokens?.*(exceeds?|greater than).*(n_ctx|context)/i, // llama.cpp n_ctx variants
42
+ /greater than the context length/i, // LM Studio
43
+ /context window exceeds limit/i, // MiniMax
44
+ /exceeded model token limit/i, // Kimi For Coding
45
+ /context[_ ]length[_ ]exceeded/i, // Generic fallback
46
+ /too many tokens/i, // Generic fallback
47
+ /token limit exceeded/i, // Generic fallback
48
+ /request_too_large/i, // Anthropic 413 (request body too large)
49
+ /request exceeds the maximum size/i, // Anthropic 413 variant
50
+ /payload too large/i, // Generic HTTP 413 variant
51
+ /entity too large/i, // Generic HTTP 413 variant
52
+ /\b413\b.*\b(request|payload|entity)\b.*\btoo large\b/i, // "413 Request Entity Too Large" variants
53
+ /model_context_window_exceeded/i, // z.ai non-standard finish_reason surfaced as error text
54
+ ];
55
+ /**
56
+ * Check if an assistant message represents a context overflow error.
57
+ *
58
+ * This handles two cases:
59
+ * 1. Error-based overflow: Most providers return stopReason "error" with a
60
+ * specific error message pattern.
61
+ * 2. Silent overflow: Some providers accept overflow requests and return
62
+ * successfully. For these, we check if usage.input exceeds the context window.
63
+ *
64
+ * ## Reliability by Provider
65
+ *
66
+ * **Reliable detection (returns error with detectable message):**
67
+ * - Anthropic: "prompt is too long: X tokens > Y maximum"
68
+ * - OpenAI (Completions & Responses): "exceeds the context window"
69
+ * - Google Gemini: "input token count exceeds the maximum"
70
+ * - xAI (Grok): "maximum prompt length is X but request contains Y"
71
+ * - Groq: "reduce the length of the messages"
72
+ * - Cerebras: 400/413 status code (no body)
73
+ * - Mistral: 400/413 status code (no body)
74
+ * - HTTP 413 payload/entity-too-large variants
75
+ * - OpenRouter (all backends): "maximum context length is X tokens"
76
+ * - llama.cpp: "exceeds the available context size"
77
+ * - LM Studio: "greater than the context length"
78
+ * - Kimi For Coding: "exceeded model token limit: X (requested: Y)"
79
+ * - Anthropic 413: "request_too_large" (request body exceeds size limit)
80
+ * - HTTP 413: "Payload Too Large" / "Request Entity Too Large"
81
+ *
82
+ * **Unreliable detection:**
83
+ * - z.ai: Sometimes accepts overflow silently (detectable via usage.input > contextWindow),
84
+ * sometimes returns rate limit errors. Pass contextWindow param to detect silent overflow.
85
+ * - Ollama: Silently truncates input without error. Cannot be detected via this function.
86
+ * The response will have usage.input < expected, but we don't know the expected value.
87
+ *
88
+ * ## Custom Providers
89
+ *
90
+ * If you've added custom models via settings.json, this function may not detect
91
+ * overflow errors from those providers. To add support:
92
+ *
93
+ * 1. Send a request that exceeds the model's context window
94
+ * 2. Check the errorMessage in the response
95
+ * 3. Create a regex pattern that matches the error
96
+ * 4. The pattern should be added to OVERFLOW_PATTERNS in this file, or
97
+ * check the errorMessage yourself before calling this function
98
+ *
99
+ * @param message - The assistant message to check
100
+ * @param contextWindow - Optional context window size for detecting silent overflow (z.ai)
101
+ * @returns true if the message indicates a context overflow
102
+ */
103
+ export function isContextOverflow(message: AssistantMessage, contextWindow?: number): boolean {
104
+ // Case 1: Check error message patterns
105
+ if (message.stopReason === "error" && message.errorMessage) {
106
+ // Check known patterns
107
+ if (OVERFLOW_PATTERNS.some(p => p.test(message.errorMessage!))) {
108
+ return true;
109
+ }
110
+
111
+ // Cerebras and Mistral return 400/413 with no body for context overflow
112
+ // Note: 429 is rate limiting (requests/tokens per time), NOT context overflow
113
+ if (/^4(00|13)\s*(status code)?\s*\(no body\)/i.test(message.errorMessage)) {
114
+ return true;
115
+ }
116
+ }
117
+
118
+ // Case 2: Usage-based overflow (silent or provider-specific)
119
+ if (contextWindow) {
120
+ const inputTokens = message.usage.input + message.usage.cacheRead + message.usage.cacheWrite;
121
+ if (inputTokens > contextWindow) {
122
+ return true;
123
+ }
124
+ }
125
+
126
+ return false;
127
+ }
128
+
129
+ /**
130
+ * Get the overflow patterns for testing purposes.
131
+ */
132
+ export function getOverflowPatterns(): RegExp[] {
133
+ return [...OVERFLOW_PATTERNS];
134
+ }
@@ -0,0 +1,110 @@
1
+ export type HeadersLike = Headers | Record<string, string | undefined> | undefined | null;
2
+
3
+ const RETRY_AFTER_HINT = "retry-after-ms=";
4
+
5
+ export function formatErrorMessageWithRetryAfter(error: unknown, headers?: HeadersLike): string {
6
+ const message = error instanceof Error ? error.message : JSON.stringify(error);
7
+ if (message.includes(RETRY_AFTER_HINT)) {
8
+ return message;
9
+ }
10
+
11
+ const retryAfterMs = getRetryAfterMsFromHeaders(headers ?? getHeadersFromError(error));
12
+ if (retryAfterMs === undefined) {
13
+ return message;
14
+ }
15
+
16
+ return `${message} ${RETRY_AFTER_HINT}${retryAfterMs}`;
17
+ }
18
+
19
+ export function getRetryAfterMsFromHeaders(headers: HeadersLike): number | undefined {
20
+ if (!headers) return undefined;
21
+
22
+ const retryAfter = parseRetryAfterHeader(getHeaderValue(headers, "retry-after"));
23
+ const resetMs = parseResetHeader(getHeaderValue(headers, "x-ratelimit-reset-ms"), "ms");
24
+ const resetSeconds = parseResetHeader(getHeaderValue(headers, "x-ratelimit-reset"), "s");
25
+
26
+ const candidates = [retryAfter, resetMs, resetSeconds].filter((value): value is number => value !== undefined);
27
+ if (candidates.length === 0) return undefined;
28
+ return Math.max(...candidates);
29
+ }
30
+
31
+ function getHeadersFromError(error: unknown): HeadersLike {
32
+ if (!error || typeof error !== "object") return undefined;
33
+ const record = error as { headers?: unknown; response?: { headers?: unknown }; cause?: unknown };
34
+ const direct = extractHeaders(record.headers) ?? extractHeaders(record.response?.headers);
35
+ if (direct) return direct;
36
+ if (record.cause) return getHeadersFromError(record.cause);
37
+ return undefined;
38
+ }
39
+
40
+ function extractHeaders(value: unknown): HeadersLike {
41
+ if (!value) return undefined;
42
+ if (value instanceof Headers) return value;
43
+ if (typeof value === "object") return value as Record<string, string | undefined>;
44
+ return undefined;
45
+ }
46
+
47
+ function getHeaderValue(headers: Headers | Record<string, string | undefined>, name: string): string | undefined {
48
+ if (headers instanceof Headers) {
49
+ const value = headers.get(name);
50
+ return value ?? undefined;
51
+ }
52
+
53
+ const target = name.toLowerCase();
54
+ for (const [key, value] of Object.entries(headers)) {
55
+ if (key.toLowerCase() === target && typeof value === "string") {
56
+ return value;
57
+ }
58
+ }
59
+ return undefined;
60
+ }
61
+
62
+ function parseRetryAfterHeader(value: string | undefined): number | undefined {
63
+ if (!value) return undefined;
64
+ const trimmed = value.trim();
65
+ if (!trimmed) return undefined;
66
+
67
+ const numeric = Number(trimmed);
68
+ if (Number.isFinite(numeric)) {
69
+ if (numeric <= 0) return undefined;
70
+ return Math.ceil(numeric * 1000);
71
+ }
72
+
73
+ const dateMs = Date.parse(trimmed);
74
+ if (!Number.isNaN(dateMs)) {
75
+ const delay = dateMs - Date.now();
76
+ return delay > 0 ? Math.ceil(delay) : undefined;
77
+ }
78
+
79
+ return undefined;
80
+ }
81
+
82
+ function parseResetHeader(value: string | undefined, unit: "ms" | "s"): number | undefined {
83
+ if (!value) return undefined;
84
+ const numeric = Number(value);
85
+ if (!Number.isFinite(numeric) || numeric <= 0) return undefined;
86
+
87
+ const nowMs = Date.now();
88
+ let targetMs: number | undefined;
89
+
90
+ if (unit === "ms") {
91
+ if (numeric > 1e12) {
92
+ targetMs = numeric;
93
+ } else if (numeric > 1e9) {
94
+ targetMs = numeric * 1000;
95
+ } else {
96
+ return Math.ceil(numeric);
97
+ }
98
+ } else {
99
+ if (numeric > 1e12) {
100
+ targetMs = numeric;
101
+ } else if (numeric > 1e9) {
102
+ targetMs = numeric * 1000;
103
+ } else {
104
+ return Math.ceil(numeric * 1000);
105
+ }
106
+ }
107
+
108
+ if (targetMs <= nowMs) return undefined;
109
+ return Math.ceil(targetMs - nowMs);
110
+ }
@@ -0,0 +1,93 @@
1
+ type ErrorLike = {
2
+ message?: string;
3
+ name?: string;
4
+ status?: number;
5
+ statusCode?: number;
6
+ response?: { status?: number };
7
+ cause?: unknown;
8
+ };
9
+
10
+ const TRANSIENT_MESSAGE_PATTERN =
11
+ /overloaded|rate.?limit|too many requests|service.?unavailable|server error|internal error|connection.?error|unable to connect|fetch failed|stream stall/i;
12
+
13
+ const VALIDATION_MESSAGE_PATTERN =
14
+ /invalid|validation|bad request|unsupported|schema|missing required|not found|unauthorized|forbidden/i;
15
+
16
+ /**
17
+ * Identify errors that should be retried (timeouts, 5xx, 408, 429, transient network failures).
18
+ */
19
+ export function isRetryableError(error: unknown): boolean {
20
+ const info = error as ErrorLike | null;
21
+ const message = info?.message ?? "";
22
+ const name = info?.name ?? "";
23
+ if (name === "AbortError" || /timeout|timed out|aborted/i.test(message)) return true;
24
+
25
+ const status = extractHttpStatusFromError(error);
26
+ if (status !== undefined) {
27
+ if (status >= 500) return true;
28
+ if (status === 408 || status === 429) return true;
29
+ if (status >= 400 && status < 500) return false;
30
+ }
31
+
32
+ if (VALIDATION_MESSAGE_PATTERN.test(message)) return false;
33
+
34
+ return TRANSIENT_MESSAGE_PATTERN.test(message);
35
+ }
36
+
37
+ export function extractHttpStatusFromError(error: unknown): number | undefined {
38
+ return extractHttpStatusFromErrorInternal(error, 0);
39
+ }
40
+
41
+ function extractHttpStatusFromErrorInternal(error: unknown, depth: number): number | undefined {
42
+ if (!error || typeof error !== "object" || depth > 2) return undefined;
43
+ const info = error as ErrorLike;
44
+ const rawStatus =
45
+ info.status ??
46
+ info.statusCode ??
47
+ (info.response && typeof info.response === "object" ? info.response.status : undefined);
48
+
49
+ let status: number | undefined;
50
+ if (typeof rawStatus === "number" && Number.isFinite(rawStatus)) {
51
+ status = rawStatus;
52
+ } else if (typeof rawStatus === "string") {
53
+ const parsed = Number(rawStatus);
54
+ if (Number.isFinite(parsed)) {
55
+ status = parsed;
56
+ }
57
+ }
58
+
59
+ if (status !== undefined && status >= 100 && status <= 599) {
60
+ return status;
61
+ }
62
+
63
+ if (info.message) {
64
+ const extracted = extractStatusFromMessage(info.message);
65
+ if (extracted !== undefined) return extracted;
66
+ }
67
+
68
+ if (info.cause) {
69
+ return extractHttpStatusFromErrorInternal(info.cause, depth + 1);
70
+ }
71
+
72
+ return undefined;
73
+ }
74
+
75
+ function extractStatusFromMessage(message: string): number | undefined {
76
+ const patterns = [
77
+ /error\s*\((\d{3})\)/i,
78
+ /status\s*[:=]?\s*(\d{3})/i,
79
+ /\bhttp\s*(\d{3})\b/i,
80
+ /\b(\d{3})\s*(?:status|error)\b/i,
81
+ ];
82
+
83
+ for (const pattern of patterns) {
84
+ const match = pattern.exec(message);
85
+ if (!match) continue;
86
+ const value = Number(match[1]);
87
+ if (Number.isFinite(value) && value >= 100 && value <= 599) {
88
+ return value;
89
+ }
90
+ }
91
+
92
+ return undefined;
93
+ }