@code-yeongyu/senpi 2026.9.28-4 → 2026.9.28-5

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 (164) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/bundle/chunks/{anthropic-messages-W2XLZZ35.js → anthropic-messages-GG4ZKS6A.js} +2 -2
  3. package/dist/bundle/chunks/{app-server-command-7LBMB34E.js → app-server-command-3AJWPHKJ.js} +1 -1
  4. package/dist/bundle/chunks/{azure-openai-responses-WNELC744.js → azure-openai-responses-ZAJSIEAV.js} +1 -1
  5. package/dist/bundle/chunks/{chunk-UTGOAXS6.js → chunk-4BDFNRBE.js} +1 -1
  6. package/dist/bundle/chunks/{chunk-OLQI7DUR.js → chunk-7SFG425F.js} +1 -1
  7. package/dist/bundle/chunks/chunk-7X4ZMME4.js +2 -0
  8. package/dist/bundle/chunks/chunk-BQGVC47Y.js +3 -0
  9. package/dist/bundle/chunks/chunk-C5I2LUOI.js +2 -0
  10. package/dist/bundle/chunks/{chunk-3JX3X45G.js → chunk-CXVI2YV7.js} +1 -1
  11. package/dist/bundle/chunks/{chunk-RKIAHDIB.js → chunk-EXUI5D5V.js} +14 -13
  12. package/dist/bundle/chunks/chunk-J5TMX734.js +2 -0
  13. package/dist/bundle/chunks/{chunk-TYN6XEJL.js → chunk-JCMOKXWG.js} +1 -1
  14. package/dist/bundle/chunks/{chunk-WQO75X37.js → chunk-JGRPPPHS.js} +1 -1
  15. package/dist/bundle/chunks/{chunk-YHT3LLIA.js → chunk-K3SEG6TJ.js} +1 -1
  16. package/dist/bundle/chunks/{chunk-ZORNIKXN.js → chunk-KDZAVHA7.js} +1 -1
  17. package/dist/bundle/chunks/{chunk-HVFSRIJI.js → chunk-KR2TJOGO.js} +1 -1
  18. package/dist/bundle/chunks/chunk-KRNXUTZJ.js +2 -0
  19. package/dist/bundle/chunks/{chunk-OH4ONX6R.js → chunk-LEAJXPT2.js} +4 -4
  20. package/dist/bundle/chunks/{chunk-7FIDRH2I.js → chunk-MMHQLGF2.js} +1 -1
  21. package/dist/bundle/chunks/{chunk-O3D7S64D.js → chunk-OHJLQ7BY.js} +1 -1
  22. package/dist/bundle/chunks/chunk-TJV2LFKM.js +2 -0
  23. package/dist/bundle/chunks/{chunk-6WDC7AEV.js → chunk-UDTWLXSQ.js} +1 -1
  24. package/dist/bundle/chunks/chunk-XNIX26QC.js +8 -0
  25. package/dist/bundle/chunks/{chunk-5LYDQMQY.js → chunk-XPJLBOWV.js} +1 -1
  26. package/dist/bundle/chunks/{chunk-C5FRNOUP.js → chunk-XYGXUFMG.js} +1 -1
  27. package/dist/bundle/chunks/{chunk-3JR7GC6P.js → chunk-YEMM3LPR.js} +1 -1
  28. package/dist/bundle/chunks/{chunk-KAFTHZWC.js → chunk-YLIS5N3W.js} +1 -1
  29. package/dist/bundle/chunks/{chunk-4BK43Q6Z.js → chunk-Z5NVK72W.js} +1 -1
  30. package/dist/bundle/chunks/cli-main-NUSBF3HE.js +3 -0
  31. package/dist/bundle/chunks/github-copilot.js +1 -1
  32. package/dist/bundle/chunks/{google-generative-ai-FUULH4UE.js → google-generative-ai-C4YRAMFN.js} +1 -1
  33. package/dist/bundle/chunks/{google-vertex-PLXS45T4.js → google-vertex-4ZM6HGYI.js} +1 -1
  34. package/dist/bundle/chunks/help-fast-path-A4S4KOQ6.js +2 -0
  35. package/dist/bundle/chunks/host-command-D2CHSATG.js +2 -0
  36. package/dist/bundle/chunks/host-lifecycle-S7O5K62Z.js +3 -0
  37. package/dist/bundle/chunks/interactive-host-runtime-AAK47HIV.js +4 -0
  38. package/dist/bundle/chunks/interactive-mode-LSTD6EUQ.js +2 -0
  39. package/dist/bundle/chunks/{mistral-conversations-G5CGRCMV.js → mistral-conversations-7SROSYOE.js} +1 -1
  40. package/dist/bundle/chunks/{multi-session-host-GJCSLVES.js → multi-session-host-5WNZ7XRV.js} +1 -1
  41. package/dist/bundle/chunks/{openai-codex-responses-4JOIWFJF.js → openai-codex-responses-2ZNOPGE4.js} +1 -1
  42. package/dist/bundle/chunks/{openai-completions-XDHNDF3Z.js → openai-completions-DVEOAQK4.js} +1 -1
  43. package/dist/bundle/chunks/{openai-images-I7DR7ERP.js → openai-images-AEFVNUTL.js} +1 -1
  44. package/dist/bundle/chunks/openai-responses-7H2ADNW4.js +2 -0
  45. package/dist/bundle/chunks/{openrouter-images-IPNDRK6C.js → openrouter-images-N4NZJKSF.js} +1 -1
  46. package/dist/bundle/chunks/{package-manager-cli-E2SGFMXL.js → package-manager-cli-3HZYQYVX.js} +1 -1
  47. package/dist/bundle/chunks/rotation-stream-F36RJ6VP.js +2 -0
  48. package/dist/bundle/chunks/rpc-mode-GMPBEVSL.js +2 -0
  49. package/dist/bundle/chunks/{schedule-command-UKBZQK3Y.js → schedule-command-BYWZGYOJ.js} +1 -1
  50. package/dist/bundle/chunks/session-picker-6VU2F5VF.js +2 -0
  51. package/dist/bundle/chunks/session-worker.js +175 -173
  52. package/dist/bundle/cli.js +1 -1
  53. package/dist/bundle/index.js +1 -1
  54. package/dist/bundle/rpc-entry.js +1 -1
  55. package/dist/core/credential-pool/rejected-token-retry.d.ts +24 -0
  56. package/dist/core/credential-pool/rejected-token-retry.d.ts.map +1 -0
  57. package/dist/core/credential-pool/rejected-token-retry.js +76 -0
  58. package/dist/core/credential-pool/rejected-token-retry.js.map +1 -0
  59. package/dist/core/credential-pool/rotation-events.d.ts +1 -0
  60. package/dist/core/credential-pool/rotation-events.d.ts.map +1 -1
  61. package/dist/core/credential-pool/rotation-events.js +4 -2
  62. package/dist/core/credential-pool/rotation-events.js.map +1 -1
  63. package/dist/core/extensions/builtin/goal/agent-end-continuation.d.ts.map +1 -1
  64. package/dist/core/extensions/builtin/goal/agent-end-continuation.js +13 -1
  65. package/dist/core/extensions/builtin/goal/agent-end-continuation.js.map +1 -1
  66. package/dist/core/extensions/builtin/goal/continuation-recovery.d.ts +8 -0
  67. package/dist/core/extensions/builtin/goal/continuation-recovery.d.ts.map +1 -1
  68. package/dist/core/extensions/builtin/goal/continuation-recovery.js +22 -0
  69. package/dist/core/extensions/builtin/goal/continuation-recovery.js.map +1 -1
  70. package/dist/core/extensions/builtin/goal/terminal-provider-error.d.ts +11 -0
  71. package/dist/core/extensions/builtin/goal/terminal-provider-error.d.ts.map +1 -1
  72. package/dist/core/extensions/builtin/goal/terminal-provider-error.js +31 -0
  73. package/dist/core/extensions/builtin/goal/terminal-provider-error.js.map +1 -1
  74. package/dist/core/model-resolver.js +1 -1
  75. package/dist/core/model-resolver.js.map +1 -1
  76. package/dist/core/model-runtime.d.ts +7 -0
  77. package/dist/core/model-runtime.d.ts.map +1 -1
  78. package/dist/core/model-runtime.js +34 -19
  79. package/dist/core/model-runtime.js.map +1 -1
  80. package/dist/core/retry-fallback/cooldown.d.ts.map +1 -1
  81. package/dist/core/retry-fallback/cooldown.js +2 -1
  82. package/dist/core/retry-fallback/cooldown.js.map +1 -1
  83. package/dist/modes/interactive/interactive-mode.d.ts +1 -0
  84. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  85. package/dist/modes/interactive/interactive-mode.js +13 -0
  86. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  87. package/node_modules/@code-yeongyu/senpi-codemode/CHANGELOG.md +12 -0
  88. package/node_modules/@code-yeongyu/senpi-codemode/package.json +4 -4
  89. package/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
  90. package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.d.ts.map +1 -1
  91. package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.js +8 -1
  92. package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.js.map +1 -1
  93. package/node_modules/@earendil-works/pi-ai/dist/api/github-copilot-errors.d.ts +9 -0
  94. package/node_modules/@earendil-works/pi-ai/dist/api/github-copilot-errors.d.ts.map +1 -0
  95. package/node_modules/@earendil-works/pi-ai/dist/api/github-copilot-errors.js +75 -0
  96. package/node_modules/@earendil-works/pi-ai/dist/api/github-copilot-errors.js.map +1 -0
  97. package/node_modules/@earendil-works/pi-ai/dist/api/github-copilot-headers.d.ts +1 -0
  98. package/node_modules/@earendil-works/pi-ai/dist/api/github-copilot-headers.d.ts.map +1 -1
  99. package/node_modules/@earendil-works/pi-ai/dist/api/github-copilot-headers.js +3 -0
  100. package/node_modules/@earendil-works/pi-ai/dist/api/github-copilot-headers.js.map +1 -1
  101. package/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.d.ts.map +1 -1
  102. package/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.js +8 -1
  103. package/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.js.map +1 -1
  104. package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.d.ts.map +1 -1
  105. package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.js +21 -2
  106. package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.js.map +1 -1
  107. package/node_modules/@earendil-works/pi-ai/dist/auth/helpers.d.ts +1 -0
  108. package/node_modules/@earendil-works/pi-ai/dist/auth/helpers.d.ts.map +1 -1
  109. package/node_modules/@earendil-works/pi-ai/dist/auth/helpers.js +1 -0
  110. package/node_modules/@earendil-works/pi-ai/dist/auth/helpers.js.map +1 -1
  111. package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/github-copilot-model-catalog.d.ts +7 -0
  112. package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/github-copilot-model-catalog.d.ts.map +1 -0
  113. package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/github-copilot-model-catalog.js +46 -0
  114. package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/github-copilot-model-catalog.js.map +1 -0
  115. package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/github-copilot.d.ts.map +1 -1
  116. package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/github-copilot.js +6 -41
  117. package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/github-copilot.js.map +1 -1
  118. package/node_modules/@earendil-works/pi-ai/dist/auth/resolve.d.ts +6 -0
  119. package/node_modules/@earendil-works/pi-ai/dist/auth/resolve.d.ts.map +1 -1
  120. package/node_modules/@earendil-works/pi-ai/dist/auth/resolve.js +6 -5
  121. package/node_modules/@earendil-works/pi-ai/dist/auth/resolve.js.map +1 -1
  122. package/node_modules/@earendil-works/pi-ai/dist/auth/types.d.ts +7 -0
  123. package/node_modules/@earendil-works/pi-ai/dist/auth/types.d.ts.map +1 -1
  124. package/node_modules/@earendil-works/pi-ai/dist/auth/types.js.map +1 -1
  125. package/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  126. package/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  127. package/node_modules/@earendil-works/pi-ai/dist/providers/github-copilot-limits.d.ts +11 -0
  128. package/node_modules/@earendil-works/pi-ai/dist/providers/github-copilot-limits.d.ts.map +1 -0
  129. package/node_modules/@earendil-works/pi-ai/dist/providers/github-copilot-limits.js +65 -0
  130. package/node_modules/@earendil-works/pi-ai/dist/providers/github-copilot-limits.js.map +1 -0
  131. package/node_modules/@earendil-works/pi-ai/dist/providers/github-copilot.d.ts.map +1 -1
  132. package/node_modules/@earendil-works/pi-ai/dist/providers/github-copilot.js +9 -2
  133. package/node_modules/@earendil-works/pi-ai/dist/providers/github-copilot.js.map +1 -1
  134. package/node_modules/@earendil-works/pi-ai/dist/utils/github-copilot-tool-limit.d.ts +10 -0
  135. package/node_modules/@earendil-works/pi-ai/dist/utils/github-copilot-tool-limit.d.ts.map +1 -0
  136. package/node_modules/@earendil-works/pi-ai/dist/utils/github-copilot-tool-limit.js +75 -0
  137. package/node_modules/@earendil-works/pi-ai/dist/utils/github-copilot-tool-limit.js.map +1 -0
  138. package/node_modules/@earendil-works/pi-ai/dist/utils/overflow.js +1 -1
  139. package/node_modules/@earendil-works/pi-ai/dist/utils/overflow.js.map +1 -1
  140. package/node_modules/@earendil-works/pi-ai/dist/utils/retry.d.ts +3 -0
  141. package/node_modules/@earendil-works/pi-ai/dist/utils/retry.d.ts.map +1 -1
  142. package/node_modules/@earendil-works/pi-ai/dist/utils/retry.js +15 -3
  143. package/node_modules/@earendil-works/pi-ai/dist/utils/retry.js.map +1 -1
  144. package/node_modules/@earendil-works/pi-ai/package.json +2 -2
  145. package/node_modules/@earendil-works/pi-pty/package.json +1 -1
  146. package/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  147. package/node_modules/@earendil-works/pi-tui/package.json +1 -1
  148. package/package.json +7 -7
  149. package/dist/bundle/chunks/chunk-2E2FN2VJ.js +0 -2
  150. package/dist/bundle/chunks/chunk-DM3AVOKA.js +0 -2
  151. package/dist/bundle/chunks/chunk-EDU27GXU.js +0 -2
  152. package/dist/bundle/chunks/chunk-NAIMNKNG.js +0 -2
  153. package/dist/bundle/chunks/chunk-PUWVIQW6.js +0 -2
  154. package/dist/bundle/chunks/chunk-S5Q3WPVR.js +0 -8
  155. package/dist/bundle/chunks/cli-main-LVTTAX7I.js +0 -3
  156. package/dist/bundle/chunks/help-fast-path-PCN7D4UN.js +0 -2
  157. package/dist/bundle/chunks/host-command-FETBGITW.js +0 -2
  158. package/dist/bundle/chunks/host-lifecycle-FW6LQ6SW.js +0 -3
  159. package/dist/bundle/chunks/interactive-host-runtime-7RUBGCMP.js +0 -4
  160. package/dist/bundle/chunks/interactive-mode-FDQ4N3JQ.js +0 -2
  161. package/dist/bundle/chunks/openai-responses-MQUMRQVY.js +0 -2
  162. package/dist/bundle/chunks/rotation-stream-3KJLEXQQ.js +0 -2
  163. package/dist/bundle/chunks/rpc-mode-435L7DOL.js +0 -2
  164. package/dist/bundle/chunks/session-picker-JHFPLMON.js +0 -2
@@ -0,0 +1,11 @@
1
+ import type { Credential } from "../auth/types.ts";
2
+ import type { Api, Model } from "../types.ts";
3
+ export interface GitHubCopilotModelLimit {
4
+ readonly id: string;
5
+ readonly maxContextWindowTokens?: number;
6
+ readonly maxPromptTokens?: number;
7
+ readonly maxOutputTokens?: number;
8
+ }
9
+ export declare function parseGitHubCopilotModelLimit(id: string, rawLimits: unknown): GitHubCopilotModelLimit | undefined;
10
+ export declare function applyGitHubCopilotModelLimits<TApi extends Api>(models: readonly Model<TApi>[], credential: Credential | undefined): readonly Model<TApi>[];
11
+ //# sourceMappingURL=github-copilot-limits.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"github-copilot-limits.d.ts","sourceRoot":"","sources":["../../src/providers/github-copilot-limits.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AAE9C,MAAM,WAAW,uBAAuB;IACvC,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,sBAAsB,CAAC,EAAE,MAAM,CAAC;IACzC,QAAQ,CAAC,eAAe,CAAC,EAAE,MAAM,CAAC;IAClC,QAAQ,CAAC,eAAe,CAAC,EAAE,MAAM,CAAC;CAClC;AAUD,wBAAgB,4BAA4B,CAAC,EAAE,EAAE,MAAM,EAAE,SAAS,EAAE,OAAO,GAAG,uBAAuB,GAAG,SAAS,CAehH;AAmBD,wBAAgB,6BAA6B,CAAC,IAAI,SAAS,GAAG,EAC7D,MAAM,EAAE,SAAS,KAAK,CAAC,IAAI,CAAC,EAAE,EAC9B,UAAU,EAAE,UAAU,GAAG,SAAS,GAChC,SAAS,KAAK,CAAC,IAAI,CAAC,EAAE,CAuBxB"}
@@ -0,0 +1,65 @@
1
+ function asRecord(value) {
2
+ return value && typeof value === "object" ? value : undefined;
3
+ }
4
+ function positiveInteger(value) {
5
+ return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : undefined;
6
+ }
7
+ export function parseGitHubCopilotModelLimit(id, rawLimits) {
8
+ const limits = asRecord(rawLimits);
9
+ if (!limits)
10
+ return undefined;
11
+ const maxContextWindowTokens = positiveInteger(limits.max_context_window_tokens);
12
+ const maxPromptTokens = positiveInteger(limits.max_prompt_tokens);
13
+ const maxOutputTokens = positiveInteger(limits.max_output_tokens);
14
+ if (maxContextWindowTokens === undefined && maxPromptTokens === undefined && maxOutputTokens === undefined) {
15
+ return undefined;
16
+ }
17
+ return {
18
+ id,
19
+ ...(maxContextWindowTokens !== undefined ? { maxContextWindowTokens } : {}),
20
+ ...(maxPromptTokens !== undefined ? { maxPromptTokens } : {}),
21
+ ...(maxOutputTokens !== undefined ? { maxOutputTokens } : {}),
22
+ };
23
+ }
24
+ function storedModelLimit(value) {
25
+ const entry = asRecord(value);
26
+ if (!entry || typeof entry.id !== "string")
27
+ return undefined;
28
+ const maxContextWindowTokens = positiveInteger(entry.maxContextWindowTokens);
29
+ const maxPromptTokens = positiveInteger(entry.maxPromptTokens);
30
+ const maxOutputTokens = positiveInteger(entry.maxOutputTokens);
31
+ if (maxContextWindowTokens === undefined && maxPromptTokens === undefined && maxOutputTokens === undefined) {
32
+ return undefined;
33
+ }
34
+ return {
35
+ id: entry.id,
36
+ ...(maxContextWindowTokens !== undefined ? { maxContextWindowTokens } : {}),
37
+ ...(maxPromptTokens !== undefined ? { maxPromptTokens } : {}),
38
+ ...(maxOutputTokens !== undefined ? { maxOutputTokens } : {}),
39
+ };
40
+ }
41
+ export function applyGitHubCopilotModelLimits(models, credential) {
42
+ if (credential?.type !== "oauth" || !Array.isArray(credential.copilotModelLimits))
43
+ return models;
44
+ const limitsById = new Map(credential.copilotModelLimits
45
+ .map(storedModelLimit)
46
+ .filter((entry) => entry !== undefined)
47
+ .map((entry) => [entry.id, entry]));
48
+ if (limitsById.size === 0)
49
+ return models;
50
+ return models.map((model) => {
51
+ const limits = limitsById.get(model.id);
52
+ if (!limits)
53
+ return model;
54
+ const reportedPromptLimit = limits.maxPromptTokens ?? limits.maxContextWindowTokens;
55
+ const contextWindow = reportedPromptLimit !== undefined && limits.maxContextWindowTokens !== undefined
56
+ ? Math.min(reportedPromptLimit, limits.maxContextWindowTokens)
57
+ : reportedPromptLimit;
58
+ return {
59
+ ...model,
60
+ contextWindow: contextWindow ?? model.contextWindow,
61
+ maxTokens: limits.maxOutputTokens ?? model.maxTokens,
62
+ };
63
+ });
64
+ }
65
+ //# sourceMappingURL=github-copilot-limits.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"github-copilot-limits.js","sourceRoot":"","sources":["../../src/providers/github-copilot-limits.ts"],"names":[],"mappings":"AAUA,SAAS,QAAQ,CAAC,KAAc;IAC/B,OAAO,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAE,KAAiC,CAAC,CAAC,CAAC,SAAS,CAAC;AAC5F,CAAC;AAED,SAAS,eAAe,CAAC,KAAc;IACtC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;AAC9F,CAAC;AAED,MAAM,UAAU,4BAA4B,CAAC,EAAU,EAAE,SAAkB;IAC1E,MAAM,MAAM,GAAG,QAAQ,CAAC,SAAS,CAAC,CAAC;IACnC,IAAI,CAAC,MAAM;QAAE,OAAO,SAAS,CAAC;IAC9B,MAAM,sBAAsB,GAAG,eAAe,CAAC,MAAM,CAAC,yBAAyB,CAAC,CAAC;IACjF,MAAM,eAAe,GAAG,eAAe,CAAC,MAAM,CAAC,iBAAiB,CAAC,CAAC;IAClE,MAAM,eAAe,GAAG,eAAe,CAAC,MAAM,CAAC,iBAAiB,CAAC,CAAC;IAClE,IAAI,sBAAsB,KAAK,SAAS,IAAI,eAAe,KAAK,SAAS,IAAI,eAAe,KAAK,SAAS,EAAE,CAAC;QAC5G,OAAO,SAAS,CAAC;IAClB,CAAC;IACD,OAAO;QACN,EAAE;QACF,GAAG,CAAC,sBAAsB,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,sBAAsB,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC3E,GAAG,CAAC,e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OAAO,CAAC,UAAU,CAAC,kBAAkB,CAAC;QAAE,OAAO,MAAM,CAAC;IACjG,MAAM,UAAU,GAAG,IAAI,GAAG,CACzB,UAAU,CAAC,kBAAkB;SAC3B,GAAG,CAAC,gBAAgB,CAAC;SACrB,MAAM,CAAC,CAAC,KAAK,EAAoC,EAAE,CAAC,KAAK,KAAK,SAAS,CAAC;SACxE,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,EAAE,EAAE,KAAK,CAAU,CAAC,CAC5C,CAAC;IACF,IAAI,UAAU,CAAC,IAAI,KAAK,CAAC;QAAE,OAAO,MAAM,CAAC;IACzC,OAAO,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE;QAC3B,MAAM,MAAM,GAAG,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QACxC,IAAI,CAAC,MAAM;YAAE,OAAO,KAAK,CAAC;QAC1B,MAAM,mBAAmB,GAAG,MAAM,CAAC,eAAe,IAAI,MAAM,CAAC,sBAAsB,CAAC;QACpF,MAAM,aAAa,GAClB,mBAAmB,KAAK,SAAS,IAAI,MAAM,CAAC,sBAAsB,KAAK,SAAS;YAC/E,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,mBAAmB,EAAE,MAAM,CAAC,sBAAsB,CAAC;YAC9D,CAAC,CAAC,mBAAmB,CAAC;QACxB,OAAO;YACN,GAAG,KAAK;YACR,aAAa,EAAE,aAAa,IAAI,KAAK,CAAC,aAAa;YACnD,SAAS,EAAE,MAAM,CAAC,eAAe,IAAI,KAAK,CAAC,SAAS;SACpD,CAAC;IACH,CAAC,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { Credential } from \"../auth/types.ts\";\nimport type { Api, Model } from \"../types.ts\";\n\nexport interface GitHubCopilotModelLimit {\n\treadonly id: string;\n\treadonly maxContextWindowTokens?: number;\n\treadonly maxPromptTokens?: number;\n\treadonly maxOutputTokens?: number;\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n\treturn value && typeof value === \"object\" ? (value as Record<string, unknown>) : undefined;\n}\n\nfunction positiveInteger(value: unknown): number | undefined {\n\treturn typeof value === \"number\" && Number.isInteger(value) && value > 0 ? value : undefined;\n}\n\nexport function parseGitHubCopilotModelLimit(id: string, rawLimits: unknown): GitHubCopilotModelLimit | undefined {\n\tconst limits = asRecord(rawLimits);\n\tif (!limits) return undefined;\n\tconst maxContextWindowTokens = positiveInteger(limits.max_context_window_tokens);\n\tconst maxPromptTokens = positiveInteger(limits.max_prompt_tokens);\n\tconst maxOutputTokens = positiveInteger(limits.max_output_tokens);\n\tif (maxContextWindowTokens === undefined && maxPromptTokens === undefined && maxOutputTokens === undefined) {\n\t\treturn undefined;\n\t}\n\treturn {\n\t\tid,\n\t\t...(maxContextWindowTokens !== undefined ? { maxContextWindowTokens } : {}),\n\t\t...(maxPromptTokens !== undefined ? { maxPromptTokens } : {}),\n\t\t...(maxOutputTokens !== undefined ? { maxOutputTokens } : {}),\n\t};\n}\n\nfunction storedModelLimit(value: unknown): GitHubCopilotModelLimit | undefined {\n\tconst entry = asRecord(value);\n\tif (!entry || typeof entry.id !== \"string\") return undefined;\n\tconst maxContextWindowTokens = positiveInteger(entry.maxContextWindowTokens);\n\tconst maxPromptTokens = positiveInteger(entry.maxPromptTokens);\n\tconst maxOutputTokens = positiveInteger(entry.maxOutputTokens);\n\tif (maxContextWindowTokens === undefined && maxPromptTokens === undefined && maxOutputTokens === undefined) {\n\t\treturn undefined;\n\t}\n\treturn {\n\t\tid: entry.id,\n\t\t...(maxContextWindowTokens !== undefined ? { maxContextWindowTokens } : {}),\n\t\t...(maxPromptTokens !== undefined ? { maxPromptTokens } : {}),\n\t\t...(maxOutputTokens !== undefined ? { maxOutputTokens } : {}),\n\t};\n}\n\nexport function applyGitHubCopilotModelLimits<TApi extends Api>(\n\tmodels: readonly Model<TApi>[],\n\tcredential: Credential | undefined,\n): readonly Model<TApi>[] {\n\tif (credential?.type !== \"oauth\" || !Array.isArray(credential.copilotModelLimits)) return models;\n\tconst limitsById = new Map(\n\t\tcredential.copilotModelLimits\n\t\t\t.map(storedModelLimit)\n\t\t\t.filter((entry): entry is GitHubCopilotModelLimit => entry !== undefined)\n\t\t\t.map((entry) => [entry.id, entry] as const),\n\t);\n\tif (limitsById.size === 0) return models;\n\treturn models.map((model) => {\n\t\tconst limits = limitsById.get(model.id);\n\t\tif (!limits) return model;\n\t\tconst reportedPromptLimit = limits.maxPromptTokens ?? limits.maxContextWindowTokens;\n\t\tconst contextWindow =\n\t\t\treportedPromptLimit !== undefined && limits.maxContextWindowTokens !== undefined\n\t\t\t\t? Math.min(reportedPromptLimit, limits.maxContextWindowTokens)\n\t\t\t\t: reportedPromptLimit;\n\t\treturn {\n\t\t\t...model,\n\t\t\tcontextWindow: contextWindow ?? model.contextWindow,\n\t\t\tmaxTokens: limits.maxOutputTokens ?? model.maxTokens,\n\t\t};\n\t});\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"github-copilot.d.ts","sourceRoot":"","sources":["../../src/providers/github-copilot.ts"],"names":[],"mappings":"AAKA,OAAO,EAAkB,KAAK,QAAQ,EAAE,MAAM,cAAc,CAAC;AAG7D,wBAAgB,qBAAqB,IAAI,QAAQ,CAAC,oBAAoB,GAAG,oBAAoB,GAAG,kBAAkB,CAAC,CAyBlH"}
1
+ {"version":3,"file":"github-copilot.d.ts","sourceRoot":"","sources":["../../src/providers/github-copilot.ts"],"names":[],"mappings":"AAMA,OAAO,EAAkB,KAAK,QAAQ,EAAE,MAAM,cAAc,CAAC;AAI7D,wBAAgB,qBAAqB,IAAI,QAAQ,CAAC,oBAAoB,GAAG,oBAAoB,GAAG,kBAAkB,CAAC,CAiClH"}
@@ -1,10 +1,12 @@
1
1
  import { anthropicMessagesApi } from "../api/anthropic-messages.lazy.js";
2
+ import { GITHUB_COPILOT_REJECTED_TOKEN_STATUSES } from "../api/github-copilot-headers.js";
2
3
  import { openAICompletionsApi } from "../api/openai-completions.lazy.js";
3
4
  import { openAIResponsesApi } from "../api/openai-responses.lazy.js";
4
5
  import { envApiKeyAuth, lazyOAuth } from "../auth/helpers.js";
5
6
  import { loadGitHubCopilotOAuth } from "../auth/oauth/load.js";
6
7
  import { createProvider } from "../models.js";
7
8
  import { GITHUB_COPILOT_MODELS } from "./github-copilot.models.js";
9
+ import { applyGitHubCopilotModelLimits } from "./github-copilot-limits.js";
8
10
  export function githubCopilotProvider() {
9
11
  return createProvider({
10
12
  id: "github-copilot",
@@ -12,7 +14,12 @@ export function githubCopilotProvider() {
12
14
  baseUrl: "https://api.individual.githubcopilot.com",
13
15
  auth: {
14
16
  apiKey: envApiKeyAuth("GitHub Copilot token", ["COPILOT_GITHUB_TOKEN"]),
15
- oauth: lazyOAuth({ name: "GitHub Copilot", isSubscription: true, load: loadGitHubCopilotOAuth }),
17
+ oauth: lazyOAuth({
18
+ name: "GitHub Copilot",
19
+ isSubscription: true,
20
+ rejectedTokenStatuses: GITHUB_COPILOT_REJECTED_TOKEN_STATUSES,
21
+ load: loadGitHubCopilotOAuth,
22
+ }),
16
23
  },
17
24
  models: Object.values(GITHUB_COPILOT_MODELS),
18
25
  filterModels: (models, credential) => {
@@ -23,7 +30,7 @@ export function githubCopilotProvider() {
23
30
  return models;
24
31
  }
25
32
  const available = new Set(availableModelIds);
26
- return models.filter((model) => available.has(model.id));
33
+ return applyGitHubCopilotModelLimits(models.filter((model) => available.has(model.id)), credential);
27
34
  },
28
35
  api: {
29
36
  "anthropic-messages": anthropicMessagesApi(),
@@ -1 +1 @@
1
- {"version":3,"file":"github-copilot.js","sourceRoot":"","sources":["../../src/providers/github-copilot.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,mCAAmC,CAAC;AACzE,OAAO,EAAE,oBAAoB,EAAE,MAAM,mCAAmC,CAAC;AACzE,OAAO,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAC;AACrE,OAAO,EAAE,a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AE;YAC5C,oBAAoB,EAAE,oBAAoB,EAAE;YAC5C,kBAAkB,EAAE,kBAAkB,EAAE;SACxC;KACD,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { anthropicMessagesApi } from \"../api/anthropic-messages.lazy.ts\";\nimport { openAICompletionsApi } from \"../api/openai-completions.lazy.ts\";\nimport { openAIResponsesApi } from \"../api/openai-responses.lazy.ts\";\nimport { envApiKeyAuth, lazyOAuth } from \"../auth/helpers.ts\";\nimport { loadGitHubCopilotOAuth } from \"../auth/oauth/load.ts\";\nimport { createProvider, type Provider } from \"../models.ts\";\nimport { GITHUB_COPILOT_MODELS } from \"./github-copilot.models.ts\";\n\nexport function githubCopilotProvider(): Provider<\"anthropic-messages\" | \"openai-completions\" | \"openai-responses\"> {\n\treturn createProvider({\n\t\tid: \"github-copilot\",\n\t\tname: \"GitHub Copilot\",\n\t\tbaseUrl: \"https://api.individual.githubcopilot.com\",\n\t\tauth: {\n\t\t\tapiKey: envApiKeyAuth(\"GitHub Copilot token\", [\"COPILOT_GITHUB_TOKEN\"]),\n\t\t\toauth: lazyOAuth({ name: \"GitHub Copilot\", isSubscription: true, load: loadGitHubCopilotOAuth }),\n\t\t},\n\t\tmodels: Object.values(GITHUB_COPILOT_MODELS),\n\t\tfilterModels: (models, credential) => {\n\t\t\tif (credential?.type !== \"oauth\") return models;\n\t\t\tconst availableModelIds = credential.availableModelIds;\n\t\t\tif (!Array.isArray(availableModelIds) || !availableModelIds.every((id) => typeof id === \"string\")) {\n\t\t\t\treturn models;\n\t\t\t}\n\t\t\tconst available = new Set(availableModelIds);\n\t\t\treturn models.filter((model) => available.has(model.id));\n\t\t},\n\t\tapi: {\n\t\t\t\"anthropic-messages\": anthropicMessagesApi(),\n\t\t\t\"openai-completions\": openAICompletionsApi(),\n\t\t\t\"openai-responses\": openAIResponsesApi(),\n\t\t},\n\t});\n}\n"]}
1
+ {"version":3,"file":"github-copilot.js","sourceRoot":"","sources":["../../src/providers/github-copilot.ts"],"names":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OAAO,EAAE,KAAK,QAAQ,CAAC,EAAE,CAAC;gBACnG,OAAO,MAAM,CAAC;YACf,CAAC;YACD,MAAM,SAAS,GAAG,IAAI,GAAG,CAAC,iBAAiB,CAAC,CAAC;YAC7C,OAAO,6BAA6B,CACnC,MAAM,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,SAAS,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,EACjD,UAAU,CACV,CAAC;QACH,CAAC;QACD,GAAG,EAAE;YACJ,oBAAoB,EAAE,oBAAoB,EAAE;YAC5C,oBAAoB,EAAE,oBAAoB,EAAE;YAC5C,kBAAkB,EAAE,kBAAkB,EAAE;SACxC;KACD,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { anthropicMessagesApi } from \"../api/anthropic-messages.lazy.ts\";\nimport { GITHUB_COPILOT_REJECTED_TOKEN_STATUSES } from \"../api/github-copilot-headers.ts\";\nimport { openAICompletionsApi } from \"../api/openai-completions.lazy.ts\";\nimport { openAIResponsesApi } from \"../api/openai-responses.lazy.ts\";\nimport { envApiKeyAuth, lazyOAuth } from \"../auth/helpers.ts\";\nimport { loadGitHubCopilotOAuth } from \"../auth/oauth/load.ts\";\nimport { createProvider, type Provider } from \"../models.ts\";\nimport { GITHUB_COPILOT_MODELS } from \"./github-copilot.models.ts\";\nimport { applyGitHubCopilotModelLimits } from \"./github-copilot-limits.ts\";\n\nexport function githubCopilotProvider(): Provider<\"anthropic-messages\" | \"openai-completions\" | \"openai-responses\"> {\n\treturn createProvider({\n\t\tid: \"github-copilot\",\n\t\tname: \"GitHub Copilot\",\n\t\tbaseUrl: \"https://api.individual.githubcopilot.com\",\n\t\tauth: {\n\t\t\tapiKey: envApiKeyAuth(\"GitHub Copilot token\", [\"COPILOT_GITHUB_TOKEN\"]),\n\t\t\toauth: lazyOAuth({\n\t\t\t\tname: \"GitHub Copilot\",\n\t\t\t\tisSubscription: true,\n\t\t\t\trejectedTokenStatuses: GITHUB_COPILOT_REJECTED_TOKEN_STATUSES,\n\t\t\t\tload: loadGitHubCopilotOAuth,\n\t\t\t}),\n\t\t},\n\t\tmodels: Object.values(GITHUB_COPILOT_MODELS),\n\t\tfilterModels: (models, credential) => {\n\t\t\tif (credential?.type !== \"oauth\") return models;\n\t\t\tconst availableModelIds = credential.availableModelIds;\n\t\t\tif (!Array.isArray(availableModelIds) || !availableModelIds.every((id) => typeof id === \"string\")) {\n\t\t\t\treturn models;\n\t\t\t}\n\t\t\tconst available = new Set(availableModelIds);\n\t\t\treturn applyGitHubCopilotModelLimits(\n\t\t\t\tmodels.filter((model) => available.has(model.id)),\n\t\t\t\tcredential,\n\t\t\t);\n\t\t},\n\t\tapi: {\n\t\t\t\"anthropic-messages\": anthropicMessagesApi(),\n\t\t\t\"openai-completions\": openAICompletionsApi(),\n\t\t\t\"openai-responses\": openAIResponsesApi(),\n\t\t},\n\t});\n}\n"]}
@@ -0,0 +1,10 @@
1
+ import type { AssistantMessage, ProviderId } from "../types.ts";
2
+ export declare const GITHUB_COPILOT_TOOL_LIMIT = 128;
3
+ export declare const GITHUB_COPILOT_TOOL_LIMIT_DIAGNOSTIC = "github_copilot_tool_limit";
4
+ export declare function limitGitHubCopilotTools<T>(provider: ProviderId, tools: T[] | undefined, toolChoice?: unknown): {
5
+ tools: T[] | undefined;
6
+ omittedCount: number;
7
+ };
8
+ export declare function recordGitHubCopilotToolLimit(message: AssistantMessage, omittedCount: number): void;
9
+ export declare function formatGitHubCopilotToolLimitError(message: AssistantMessage, errorMessage: string): string;
10
+ //# sourceMappingURL=github-copilot-tool-limit.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"github-copilot-tool-limit.d.ts","sourceRoot":"","sources":["../../src/utils/github-copilot-tool-limit.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAGhE,eAAO,MAAM,yBAAyB,MAAM,CAAC;AAC7C,eAAO,MAAM,oCAAoC,8BAA8B,CAAC;AA2BhF,wBAAgB,uBAAuB,CAAC,CAAC,EACxC,QAAQ,EAAE,UAAU,EACpB,KAAK,EAAE,CAAC,EAAE,GAAG,SAAS,EACtB,UAAU,CAAC,EAAE,OAAO,GAClB;IAAE,KAAK,EAAE,CAAC,EAAE,GAAG,SAAS,CAAC;IAAC,YAAY,EAAE,MAAM,CAAA;CAAE,CAmBlD;AAED,wBAAgB,4BAA4B,CAAC,OAAO,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,GAAG,IAAI,CAgBlG;AAED,wBAAgB,iCAAiC,CAAC,OAAO,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,GAAG,MAAM,CAazG"}
@@ -0,0 +1,75 @@
1
+ import { appendAssistantMessageDiagnostic } from "./diagnostics.js";
2
+ export const GITHUB_COPILOT_TOOL_LIMIT = 128;
3
+ export const GITHUB_COPILOT_TOOL_LIMIT_DIAGNOSTIC = "github_copilot_tool_limit";
4
+ function isRecord(value) {
5
+ return typeof value === "object" && value !== null;
6
+ }
7
+ function selectedToolName(toolChoice) {
8
+ if (!isRecord(toolChoice))
9
+ return undefined;
10
+ if (toolChoice.type === "function") {
11
+ if (isRecord(toolChoice.function) && typeof toolChoice.function.name === "string") {
12
+ return toolChoice.function.name;
13
+ }
14
+ return typeof toolChoice.name === "string" ? toolChoice.name : undefined;
15
+ }
16
+ if (toolChoice.type !== "custom" && toolChoice.type !== "tool")
17
+ return undefined;
18
+ return typeof toolChoice.name === "string" ? toolChoice.name : undefined;
19
+ }
20
+ function toolName(tool) {
21
+ if (!isRecord(tool))
22
+ return undefined;
23
+ if (tool.type === "function") {
24
+ if (isRecord(tool.function) && typeof tool.function.name === "string")
25
+ return tool.function.name;
26
+ return typeof tool.name === "string" ? tool.name : undefined;
27
+ }
28
+ return typeof tool.name === "string" ? tool.name : undefined;
29
+ }
30
+ export function limitGitHubCopilotTools(provider, tools, toolChoice) {
31
+ if (provider !== "github-copilot" || tools === undefined || tools.length <= GITHUB_COPILOT_TOOL_LIMIT) {
32
+ return { tools, omittedCount: 0 };
33
+ }
34
+ const forcedName = selectedToolName(toolChoice);
35
+ const forcedIndex = forcedName === undefined ? -1 : tools.findIndex((tool) => toolName(tool) === forcedName);
36
+ if (forcedIndex >= GITHUB_COPILOT_TOOL_LIMIT) {
37
+ const forcedTool = tools[forcedIndex];
38
+ if (forcedTool !== undefined) {
39
+ return {
40
+ tools: [...tools.slice(0, GITHUB_COPILOT_TOOL_LIMIT - 1), forcedTool],
41
+ omittedCount: tools.length - GITHUB_COPILOT_TOOL_LIMIT,
42
+ };
43
+ }
44
+ }
45
+ return {
46
+ tools: tools.slice(0, GITHUB_COPILOT_TOOL_LIMIT),
47
+ omittedCount: tools.length - GITHUB_COPILOT_TOOL_LIMIT,
48
+ };
49
+ }
50
+ export function recordGitHubCopilotToolLimit(message, omittedCount) {
51
+ if (omittedCount === 0 ||
52
+ message.diagnostics?.some((diagnostic) => diagnostic.type === GITHUB_COPILOT_TOOL_LIMIT_DIAGNOSTIC)) {
53
+ return;
54
+ }
55
+ appendAssistantMessageDiagnostic(message, {
56
+ type: GITHUB_COPILOT_TOOL_LIMIT_DIAGNOSTIC,
57
+ timestamp: Date.now(),
58
+ details: {
59
+ limit: GITHUB_COPILOT_TOOL_LIMIT,
60
+ omittedCount,
61
+ message: `GitHub Copilot accepts at most ${GITHUB_COPILOT_TOOL_LIMIT} tools on endpoints without tool search; senpi omitted ${omittedCount} excess tool definition${omittedCount === 1 ? "" : "s"}.`,
62
+ },
63
+ });
64
+ }
65
+ export function formatGitHubCopilotToolLimitError(message, errorMessage) {
66
+ const toolLimitApplied = message.diagnostics?.some((diagnostic) => diagnostic.type === GITHUB_COPILOT_TOOL_LIMIT_DIAGNOSTIC);
67
+ if (message.provider !== "github-copilot" ||
68
+ !toolLimitApplied ||
69
+ message.providerDiagnostic?.httpStatus !== 400 ||
70
+ !/400 Bad Request$/i.test(errorMessage)) {
71
+ return errorMessage;
72
+ }
73
+ return `GitHub Copilot rejected the request after senpi limited its tool list to ${GITHUB_COPILOT_TOOL_LIMIT}. The endpoint may enforce a lower limit or count additional hosted tools. (${errorMessage})`;
74
+ }
75
+ //# sourceMappingURL=github-copilot-tool-limit.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"github-copilot-tool-limit.js","sourceRoot":"","sources":["../../src/utils/github-copilot-tool-limit.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,gCAAgC,EAAE,MAAM,kBAAkB,CAAC;AAEpE,MAAM,CAAC,MAAM,yBAAyB,GAAG,GAAG,CAAC;AAC7C,MAAM,CAAC,MAAM,oCAAoC,GAAG,2BAA2B,CAAC;AAEhF,SAAS,QAAQ,CAAC,KAAc;IAC/B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,CAAC;AACpD,CAAC;AAED,SAAS,gBAAgB,CAAC,UAAmB;IAC5C,IAAI,CAAC,QAAQ,CAAC,UAAU,CAAC;QAAE,OAAO,SAAS,CAAC;IAC5C,IAAI,UAAU,CAAC,IAAI,KAAK,UAAU,EAAE,CAAC;QACpC,IAAI,QAAQ,CAAC,UAAU,CAAC,QAAQ,CAAC,IAAI,OAAO,UAAU,CAAC,QAAQ,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;YACnF,OAAO,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC;QACjC,CAAC;QACD,OAAO,OAAO,UAAU,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC;IAC1E,CAAC;IACD,IAAI,UAAU,CAAC,IAAI,KAAK,QAAQ,IAAI,UAAU,CAAC,IAAI,KAAK,MAAM;QAAE,OAAO,SAAS,CAAC;IACjF,OAAO,OAAO,UAAU,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC;AAC1E,CAAC;AA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C,EACtC,CAAC;QACF,OAAO,YAAY,CAAC;IACrB,CAAC;IACD,OAAO,4EAA4E,yBAAyB,+EAA+E,YAAY,GAAG,CAAC;AAC5M,CAAC","sourcesContent":["import type { AssistantMessage, ProviderId } from \"../types.ts\";\nimport { appendAssistantMessageDiagnostic } from \"./diagnostics.ts\";\n\nexport const GITHUB_COPILOT_TOOL_LIMIT = 128;\nexport const GITHUB_COPILOT_TOOL_LIMIT_DIAGNOSTIC = \"github_copilot_tool_limit\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null;\n}\n\nfunction selectedToolName(toolChoice: unknown): string | undefined {\n\tif (!isRecord(toolChoice)) return undefined;\n\tif (toolChoice.type === \"function\") {\n\t\tif (isRecord(toolChoice.function) && typeof toolChoice.function.name === \"string\") {\n\t\t\treturn toolChoice.function.name;\n\t\t}\n\t\treturn typeof toolChoice.name === \"string\" ? toolChoice.name : undefined;\n\t}\n\tif (toolChoice.type !== \"custom\" && toolChoice.type !== \"tool\") return undefined;\n\treturn typeof toolChoice.name === \"string\" ? toolChoice.name : undefined;\n}\n\nfunction toolName(tool: unknown): string | undefined {\n\tif (!isRecord(tool)) return undefined;\n\tif (tool.type === \"function\") {\n\t\tif (isRecord(tool.function) && typeof tool.function.name === \"string\") return tool.function.name;\n\t\treturn typeof tool.name === \"string\" ? tool.name : undefined;\n\t}\n\treturn typeof tool.name === \"string\" ? tool.name : undefined;\n}\n\nexport function limitGitHubCopilotTools<T>(\n\tprovider: ProviderId,\n\ttools: T[] | undefined,\n\ttoolChoice?: unknown,\n): { tools: T[] | undefined; omittedCount: number } {\n\tif (provider !== \"github-copilot\" || tools === undefined || tools.length <= GITHUB_COPILOT_TOOL_LIMIT) {\n\t\treturn { tools, omittedCount: 0 };\n\t}\n\tconst forcedName = selectedToolName(toolChoice);\n\tconst forcedIndex = forcedName === undefined ? -1 : tools.findIndex((tool) => toolName(tool) === forcedName);\n\tif (forcedIndex >= GITHUB_COPILOT_TOOL_LIMIT) {\n\t\tconst forcedTool = tools[forcedIndex];\n\t\tif (forcedTool !== undefined) {\n\t\t\treturn {\n\t\t\t\ttools: [...tools.slice(0, GITHUB_COPILOT_TOOL_LIMIT - 1), forcedTool],\n\t\t\t\tomittedCount: tools.length - GITHUB_COPILOT_TOOL_LIMIT,\n\t\t\t};\n\t\t}\n\t}\n\treturn {\n\t\ttools: tools.slice(0, GITHUB_COPILOT_TOOL_LIMIT),\n\t\tomittedCount: tools.length - GITHUB_COPILOT_TOOL_LIMIT,\n\t};\n}\n\nexport function recordGitHubCopilotToolLimit(message: AssistantMessage, omittedCount: number): void {\n\tif (\n\t\tomittedCount === 0 ||\n\t\tmessage.diagnostics?.some((diagnostic) => diagnostic.type === GITHUB_COPILOT_TOOL_LIMIT_DIAGNOSTIC)\n\t) {\n\t\treturn;\n\t}\n\tappendAssistantMessageDiagnostic(message, {\n\t\ttype: GITHUB_COPILOT_TOOL_LIMIT_DIAGNOSTIC,\n\t\ttimestamp: Date.now(),\n\t\tdetails: {\n\t\t\tlimit: GITHUB_COPILOT_TOOL_LIMIT,\n\t\t\tomittedCount,\n\t\t\tmessage: `GitHub Copilot accepts at most ${GITHUB_COPILOT_TOOL_LIMIT} tools on endpoints without tool search; senpi omitted ${omittedCount} excess tool definition${omittedCount === 1 ? \"\" : \"s\"}.`,\n\t\t},\n\t});\n}\n\nexport function formatGitHubCopilotToolLimitError(message: AssistantMessage, errorMessage: string): string {\n\tconst toolLimitApplied = message.diagnostics?.some(\n\t\t(diagnostic) => diagnostic.type === GITHUB_COPILOT_TOOL_LIMIT_DIAGNOSTIC,\n\t);\n\tif (\n\t\tmessage.provider !== \"github-copilot\" ||\n\t\t!toolLimitApplied ||\n\t\tmessage.providerDiagnostic?.httpStatus !== 400 ||\n\t\t!/400 Bad Request$/i.test(errorMessage)\n\t) {\n\t\treturn errorMessage;\n\t}\n\treturn `GitHub Copilot rejected the request after senpi limited its tool list to ${GITHUB_COPILOT_TOOL_LIMIT}. The endpoint may enforce a lower limit or count additional hosted tools. (${errorMessage})`;\n}\n"]}
@@ -50,7 +50,7 @@ const OVERFLOW_PATTERNS = [
50
50
  /maximum context length is \d+ tokens/i, // OpenRouter (most backends)
51
51
  /exceeds (?:the )?maximum allowed input length of [\d,]+ tokens?/i, // OpenRouter/Poolside
52
52
  /input \(\d+ tokens\) is longer than the model'?s context length \(\d+ tokens\)/i, // Together AI
53
- /exceeds the limit of \d+/i, // GitHub Copilot
53
+ /model_max_prompt_tokens_exceeded|exceeds the limit of \d+/i, // GitHub Copilot
54
54
  /exceeds the available context size/i, // llama.cpp server
55
55
  /greater than the context length/i, // LM Studio
56
56
  /context window exceeds limit/i, // MiniMax
@@ -1 +1 @@
1
- {"version":3,"file":"overflow.js","sourceRoot":"","sources":["../../src/utils/overflow.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AACH,MAAM,iBAAiB,GAAG;IACzB,6BAA6B,EAAE,qEAAqE;IACpG,qBAAqB,EAAE,2BAA2B;IAClD,oBAAoB,EAAE,kDAAkD;IACxE,wCAAwC,EAAE,iBAAiB;IAC3D,yDAAyD,EAAE,uCAAuC;IAClG,4FAA4F,EAAE,sCAAsC;IACpI,yCAAyC,EAAE,kBAAkB;IAC7D,+BAA+B,EAAE,aAAa;IAC9C,oCAAoC,EAAE,OAAO;IAC7C,uCAAuC,EAAE,6BAA6B;IACtE,kEAAkE,EAAE,sBAAsB;IAC1F,iFAAiF,EAAE,cAAc;IACjG,2BAA2B,EAAE,iBAAiB;IAC9C,qCAAqC,EAAE,mBAAmB;IAC1D,kCAAkC,EAAE,YAAY;IAChD,+BAA+B,EAAE,UAAU;IAC3C,6BAA6B,EAAE,kBAAkB;IACjD,sDAAsD,EAAE,UAAU;IAClE,+EAA+E,EAAE,aAAa;IAC9F,gCAAgC,EAAE,yDAAyD;IAC3F,oDAAoD,EAAE,iCAAiC;IACvF,kCAAkC,EAAE,8BAA8B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AAM,UAAU,kCAAkC,CAAC,OAIlD;IACA,IAAI,OAAO,CAAC,UAAU,KAAK,OAAO,IAAI,CAAC,sBAAsB,CAAC,IAAI,CAAC,OAAO,CAAC,YAAY,IAAI,EAAE,CAAC,EAAE,CAAC;QAChG,OAAO,KAAK,CAAC;IACd,CAAC;IACD,OAAO,CAAC,CAAC,oBAAoB,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC;AAC7C,CAAC;AAED,MAAM,UAAU,yCAAyC,CAAC,OAAkD;IAC3G,OAAO,OAAO,EAAE,eAAe,KAAK,IAAI,CAAC;AAC1C,CAAC;AAED,MAAM,UAAU,iCAAiC,CAAC,SAAkB,EAAE,YAAoB;IACzF,IAAI,SAAS;QAAE,OAAO,KAAK,CAAC;IAC5B,OAAO,qBAAqB,CAAC,IAAI,CAAC,YAAY,IAAI,EAAE,CAAC,CAAC;AACvD,CAAC;AAED,MAAM,UAAU,gCAAgC,CAC/C,QAAW,EACX,QAA4B,EAC5B,MAA0B;IAE1B,IAAI,MAAM,KAAK,UAAU;QAAE,OAAO,QAAQ,CAAC;IAC3C,IAAI,QAAQ,KAAK,QAAQ,IAAI,QAAQ,KAAK,kBAAkB;QAAE,OAAO,QAAQ,CAAC;IAC9E,OAAO,EAAE,GAAG,QAAQ,EAAE,gBAAgB,EAAE,CAAC,EAAE,kBAAkB,EAAE,KAAK,EAAE,CAAC;AACxE,CAAC","sourcesContent":["import type { AssistantMessage } from \"../types.ts\";\n\n/**\n * Regex patterns to detect context overflow errors from different providers.\n *\n * These patterns match error messages returned when the input exceeds\n * the model's context window.\n *\n * Provider-specific patterns (with example error messages):\n *\n * - Anthropic: \"prompt is too long: 213462 tokens > 200000 maximum\"\n * - Anthropic: \"413 {\\\"error\\\":{\\\"type\\\":\\\"request_too_large\\\",\\\"message\\\":\\\"Request exceeds the maximum size\\\"}}\"\n * - OpenAI: \"Your input exceeds the context window of this model\"\n * - OpenAI: \"Your input exceeds the model's context window\" / \"exceeds this model's context window\"\n * - OpenAI/LiteLLM: \"Requested token count exceeds the model's maximum context length of 131072 tokens\"\n * - OpenAI-compatible: \"Input length (265330) exceeds model's maximum context length (262144).\"\n * - Google: \"The input token count (1196265) exceeds the maximum number of tokens allowed (1048575)\"\n * - xAI: \"This model's maximum prompt length is 131072 but the request contains 537812 tokens\"\n * - Groq: \"Please reduce the length of the messages or completion\"\n * - OpenRouter: \"This endpoint's maximum context length is X tokens. However, you requested about Y tokens\"\n * - OpenRouter/Poolside: \"Input length X exceeds the maximum allowed input length of Y tokens.\"\n * - Together AI: \"The input (X tokens) is longer than the model's context length (Y tokens).\"\n * - llama.cpp: \"the request exceeds the available context size, try increasing it\"\n * - LM Studio: \"tokens to keep from the initial prompt is greater than the context length\"\n * - GitHub Copilot: \"prompt token count of X exceeds the limit of Y\"\n * - MiniMax: \"invalid params, context window exceeds limit\"\n * - Kimi For Coding: \"Your request exceeded model token limit: X (requested: Y)\"\n * - DS4: \"Prompt has X tokens, but the configured context size is Y tokens\"\n * - Cerebras: \"400/413 status code (no body)\"\n * - Gateways: \"413 Request body too large\" / \"Request Entity Too Large\" / \"Payload Too Large\" (byte-size overflow)\n * - kiro-lb gateways: \"Request payload is 1095225 bytes, over the 1085435 byte limit Kiro accepts.\" / \"Request payload is N tokens, over the M token limit Kiro accepts.\" (HTTP 400 local payload guard)\n * - Kiro upstream via kiro-lb: \"Model context limit reached. Conversation size exceeds model capacity.\" (CONTENT_LENGTH_EXCEEDS_THRESHOLD token overflow)\n * - Mistral: \"Prompt contains X tokens ... too large for model with Y maximum context length\"\n * - z.ai: Does NOT error, accepts overflow silently - handled via usage.input > contextWindow\n * - Xiaomi MiMo: Truncates input to fill contextWindow exactly, then returns finish_reason \"length\"\n * with output=0 (no room left to generate). Detected via stopReason \"length\" + zero output +\n * input filling the context window.\n * - DashScope/Qwen: \"Range of input length should be [1, X]\" (HTTP 400 invalid_parameter_error)\n * - Ollama: Some deployments truncate silently, others return errors like \"prompt too long; exceeded max context length by X tokens\"\n * - pi-ai pre-flight guard (api/context-room.ts): \"Context window exhausted: the conversation is estimated at X of Y tokens, ...\" - raised before any provider call\n */\nconst OVERFLOW_PATTERNS = [\n\t/^Context window exhausted: /, // pi-ai pre-flight guard: no answer room left, provider never called\n\t/prompt is too long/i, // Anthropic token overflow\n\t/request_too_large/i, // Anthropic request byte-size overflow (HTTP 413)\n\t/input is too long for requested model/i, // Amazon Bedrock\n\t/exceeds (?:(?:the|this) )?(?:model'?s )?context window/i, // OpenAI (Completions & Responses API)\n\t/exceeds (?:the )?(?:model'?s )?maximum context length(?: of [\\d,]+ tokens?|\\s*\\([\\d,]+\\))/i, // OpenAI-compatible proxies (LiteLLM)\n\t/input token count.*exceeds the maximum/i, // Google (Gemini)\n\t/maximum prompt length is \\d+/i, // xAI (Grok)\n\t/reduce the length of the messages/i, // Groq\n\t/maximum context length is \\d+ tokens/i, // OpenRouter (most backends)\n\t/exceeds (?:the )?maximum allowed input length of [\\d,]+ tokens?/i, // OpenRouter/Poolside\n\t/input \\(\\d+ tokens\\) is longer than the model'?s context length \\(\\d+ tokens\\)/i, // Together AI\n\t/exceeds the limit of \\d+/i, // GitHub Copilot\n\t/exceeds the available context size/i, // llama.cpp server\n\t/greater than the context length/i, // LM Studio\n\t/context window exceeds limit/i, // MiniMax\n\t/exceeded model token limit/i, // Kimi For Coding\n\t/too large for model with \\d+ maximum context length/i, // Mistral\n\t/prompt has [\\d,]+ tokens?, but the configured context size is [\\d,]+ tokens?/i, // DS4 server\n\t/model_context_window_exceeded/i, // z.ai non-standard finish_reason surfaced as error text\n\t/prompt too long; exceeded (?:max )?context length/i, // Ollama explicit overflow error\n\t/range of input length should be/i, // DashScope / Qwen Token Plan\n\t/context[_ ]length[_ ]exceeded/i, // Generic fallback\n\t/too many tokens/i, // Generic fallback\n\t/token limit exceeded/i, // Generic fallback\n\t/^4(?:00|13)\\s*(?:status code)?\\s*\\(no body\\)/i, // Cerebras: 400/413 with no body\n\t/(?:request[ _])?(?:body|entity|payload)[_ ]too[_ ]large/i, // Gateway HTTP 413 byte-size rejections (\"Request body too large\", \"Request Entity Too Large\", \"body_too_large\", \"Payload Too Large\"). Substring-anchored by design (JSON bodies lack an adjacent status code); a non-context size rejection (e.g. an oversized image) can over-match, which costs one bounded shrink-retry, never a wedge.\n\t/Request payload is \\d+ (?:bytes, over the \\d+ byte|tokens, over the \\d+ token) limit Kiro accepts\\./, // kiro-lb local byte/token payload guard (HTTP 400; Anthropic uses invalid_request_error, OpenAI uses detail).\n\t/Model context limit reached\\. Conversation size exceeds model capacity\\./, // kiro-lb enhancement of Kiro CONTENT_LENGTH_EXCEEDS_THRESHOLD\n];\n\n/**\n * Patterns that indicate non-overflow errors (e.g. rate limiting, server errors).\n * Error messages matching any of these are excluded from overflow detection\n * even if they also match an OVERFLOW_PATTERN.\n *\n * Example: Bedrock formats throttling errors as \"ThrottlingException: Too many tokens,\n * please wait before trying again.\" which would match the /too many tokens/i overflow\n * pattern without this exclusion. Token-quota / TPM messages such as \"Too many tokens\n * per minute\" or \"This request exceeds the limit of 30000 tokens per minute\" similarly\n * match generic overflow fallbacks and must stay on the rate-limit path.\n */\nconst NON_OVERFLOW_PATTERNS = [\n\t/^(Throttling error|Service unavailable):/i, // AWS Bedrock non-overflow errors (human-readable prefixes from formatBedrockError)\n\t/rate limit/i, // Generic rate limiting\n\t/too many requests/i, // Generic HTTP 429 style\n\t/tokens per (?:min|minute|hour|day)/i, // Token-quota windows (TPM/TPH/TPD), not context size\n\t/\\bTPM\\b/i, // Tokens-per-minute abbreviation\n\t/\\bRPM\\b/i, // Requests-per-minute abbreviation\n\t/quota exceeded/i, // Provider quota, not context window\n\t/retry (?:after|in) \\d/i, // Retry-after rate-limit wording\n\t/^429\\b/, // HTTP 429 prefix\n\t/status code 429/i, // HTTP 429 mentioned mid-message\n\t/overloaded/i, // Provider capacity, not context size\n];\n\n/**\n * Cursor's api2.cursor.sh surfaces a context overflow as a bare gRPC\n * `resource_exhausted` end-stream — the same wording its backend uses for\n * quota and poisoned-conversation rejections. Token evidence disambiguates:\n * a request that already streamed or billed tokens overflowed mid-flight,\n * while a zero-token rejection is a quota/conversation failure that must stay\n * on the rate-limit path (the cursor client rotates the conversation id for\n * those and retry handling supplies the backoff).\n */\nconst RESOURCE_EXHAUSTED_PATTERN = /resource.?exhausted/i;\n\n/**\n * Check if an assistant message represents a context overflow error.\n *\n * This handles three cases:\n * 1. Error-based overflow: Most providers return stopReason \"error\" with a\n * specific error message pattern.\n * 2. Silent overflow: Some providers accept overflow requests and return\n * successfully. For these, we check if usage.input exceeds the context window.\n * 3. Length-stop overflow: Xiaomi MiMo can return \"length\" with zero output when\n * the input fills the context window.\n *\n * ## Reliability by Provider\n *\n * **Reliable detection (returns error with detectable message):**\n * - Anthropic: \"prompt is too long: X tokens > Y maximum\" or \"request_too_large\"\n * - OpenAI (Completions & Responses): \"exceeds the context window\", \"exceeds the model's context window\", \"exceeds this model's context window\", \"exceeds the model's maximum context length of X tokens\", or \"exceeds model's maximum context length (X)\"\n * - Google Gemini: \"input token count exceeds the maximum\"\n * - xAI (Grok): \"maximum prompt length is X but request contains Y\"\n * - Groq: \"reduce the length of the messages\"\n * - Cerebras: 400/413 status code (no body)\n * - Mistral: \"Prompt contains X tokens ... too large for model with Y maximum context length\"\n * - OpenRouter (most backends): \"maximum context length is X tokens\"\n * - OpenRouter/Poolside: \"Input length X exceeds the maximum allowed input length of Y tokens.\"\n * - Together AI: \"The input (X tokens) is longer than the model's context length (Y tokens).\"\n * - llama.cpp: \"exceeds the available context size\"\n * - LM Studio: \"greater than the context length\"\n * - Kimi For Coding: \"exceeded model token limit: X (requested: Y)\"\n * - DS4: \"Prompt has X tokens, but the configured context size is Y tokens\"\n * - DashScope/Qwen: \"Range of input length should be [1, X]\"\n *\n * **Unreliable detection:**\n * - z.ai: Sometimes accepts overflow silently (detectable via usage.input > contextWindow),\n * sometimes returns rate limit errors. Pass contextWindow param to detect silent overflow.\n * - Xiaomi MiMo: Truncates input to fit contextWindow then returns stopReason \"length\" with\n * output=0. Pass contextWindow param to detect via the \"filled context + zero output\" signal.\n * - Ollama: May truncate input silently for some setups, but may also return explicit\n * overflow errors that match the patterns above. Silent truncation still cannot be\n * detected here because we do not know the expected token count.\n *\n * ## Custom Providers\n *\n * If you've added custom models via settings.json, this function may not detect\n * overflow errors from those providers. To add support:\n *\n * 1. Send a request that exceeds the model's context window\n * 2. Check the errorMessage in the response\n * 3. Create a regex pattern that matches the error\n * 4. The pattern should be added to OVERFLOW_PATTERNS in this file, or\n * check the errorMessage yourself before calling this function\n *\n * @param message - The assistant message to check\n * @param contextWindow - Optional context window size for detecting silent overflow (z.ai)\n * @returns true if the message indicates a context overflow\n */\nexport function isContextOverflow(message: AssistantMessage, contextWindow?: number): boolean {\n\t// Case 1: Check error message patterns\n\tif (message.stopReason === \"error\" && message.errorMessage) {\n\t\t// Skip messages matching known non-overflow patterns (e.g. throttling / rate-limit)\n\t\tconst isNonOverflow = NON_OVERFLOW_PATTERNS.some((p) => p.test(message.errorMessage!));\n\t\tif (!isNonOverflow && OVERFLOW_PATTERNS.some((p) => p.test(message.errorMessage!))) {\n\t\t\treturn true;\n\t\t}\n\t\tconst usage = message.usage;\n\t\tconst hasTokenEvidence =\n\t\t\t(usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite) > 0;\n\t\tif (\n\t\t\t!isNonOverflow &&\n\t\t\thasTokenEvidence &&\n\t\t\tRESOURCE_EXHAUSTED_PATTERN.test(message.errorMessage) &&\n\t\t\t(contextWindow === undefined || contextWindow <= 0 || cursorZeroTokenCount(message) >= contextWindow * 0.5)\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t// Case 2: Silent overflow (z.ai style) - successful but usage exceeds context\n\tif (contextWindow && message.stopReason === \"stop\") {\n\t\tconst inputTokens = message.usage.input + message.usage.cacheRead;\n\t\tif (inputTokens > contextWindow) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t// Case 3: Length-stop overflow (Xiaomi MiMo style) - server truncates oversized input\n\t// to fit the context window, leaving no room for output. Returns stopReason \"length\"\n\t// with output=0 and input+cacheRead filling the context window.\n\tif (contextWindow && message.stopReason === \"length\" && message.usage.output === 0) {\n\t\tconst inputTokens = message.usage.input + message.usage.cacheRead;\n\t\tif (inputTokens >= contextWindow * 0.99) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n/**\n * Check whether a length stop ended below the caller or model's intended output limit.\n * Such responses may be caused by context pressure or provider-side truncation, so callers\n * can make one bounded compact-and-retry attempt. `desiredMaxOutput` must be the original\n * limit before any context-based clamping.\n */\nexport function isRecoverableLength(message: AssistantMessage, desiredMaxOutput: number): boolean {\n\treturn message.stopReason === \"length\" && desiredMaxOutput > 0 && message.usage.output < desiredMaxOutput;\n}\n\n/**\n * Get the overflow patterns for testing purposes.\n */\nexport function getOverflowPatterns(): RegExp[] {\n\treturn [...OVERFLOW_PATTERNS];\n}\n\nfunction cursorZeroTokenCount(message: {\n\tusage?: { input?: number; output?: number; cacheRead?: number; cacheWrite?: number; totalTokens?: number };\n}): number {\n\tconst usage = message.usage;\n\tif (!usage) return 0;\n\treturn (\n\t\tusage.totalTokens || (usage.input ?? 0) + (usage.output ?? 0) + (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0)\n\t);\n}\n\nexport function isCursorPayloadResourceExhausted(\n\tmessage: {\n\t\tstopReason?: string;\n\t\terrorMessage?: string;\n\t\tusage?: { input?: number; output?: number; cacheRead?: number; cacheWrite?: number; totalTokens?: number };\n\t},\n\t_estimateTokens: number,\n): boolean {\n\tif (message.stopReason !== \"error\" || !/resource.?exhausted/i.test(message.errorMessage || \"\")) {\n\t\treturn false;\n\t}\n\treturn !(cursorZeroTokenCount(message) > 0);\n}\n\n/**\n * Detects Cursor's verified usage-pool exhaustion signature: a token-bearing\n * `resource_exhausted` error while the conversation is well below the model\n * context window.\n */\nexport function isCursorQuotaResourceExhausted(\n\tmessage: {\n\t\tstopReason?: string;\n\t\terrorMessage?: string;\n\t\tusage?: { input?: number; output?: number; cacheRead?: number; cacheWrite?: number; totalTokens?: number };\n\t},\n\tcontextWindow: number,\n): boolean {\n\tconst tokens = cursorZeroTokenCount(message);\n\treturn (\n\t\tmessage.stopReason === \"error\" &&\n\t\tRESOURCE_EXHAUSTED_PATTERN.test(message.errorMessage || \"\") &&\n\t\tcontextWindow > 0 &&\n\t\ttokens > 0 &&\n\t\ttokens < contextWindow * 0.5\n\t);\n}\n\nexport function isCursorZeroTokenResourceExhausted(message: {\n\tstopReason?: string;\n\terrorMessage?: string;\n\tusage?: { input?: number; output?: number; cacheRead?: number; cacheWrite?: number; totalTokens?: number };\n}): boolean {\n\tif (message.stopReason !== \"error\" || !/resource.?exhausted/i.test(message.errorMessage || \"\")) {\n\t\treturn false;\n\t}\n\treturn !(cursorZeroTokenCount(message) > 0);\n}\n\nexport function shouldSkipProviderFallbackForCursorZeroRe(options: { sameModelRemint?: boolean } | undefined): boolean {\n\treturn options?.sameModelRemint === true;\n}\n\nexport function shouldRetryOverflowWithoutCompact(compacted: boolean, errorMessage: string): boolean {\n\tif (compacted) return false;\n\treturn /Nothing to compact/i.test(errorMessage || \"\");\n}\n\nexport function cursorOverflowCompactionSettings<T extends { keepRecentTokens?: number; restorationEnabled?: boolean }>(\n\tsettings: T,\n\tprovider: string | undefined,\n\treason: string | undefined,\n): T {\n\tif (reason !== \"overflow\") return settings;\n\tif (provider !== \"cursor\" && provider !== \"cursor-cli-oauth\") return settings;\n\treturn { ...settings, keepRecentTokens: 0, restorationEnabled: false };\n}\n"]}
1
+ {"version":3,"file":"overflow.js","sourceRoot":"","sources":["../../src/utils/overflow.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AACH,MAAM,iBAAiB,GAAG;IACzB,6BAA6B,EAAE,qEAAqE;IACpG,qBAAqB,EAAE,2BAA2B;IAClD,oBAAoB,EAAE,kDAAkD;IACxE,wCAAwC,EAAE,iBAAi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AI,QAAQ,KAAK,kBAAkB;QAAE,OAAO,QAAQ,CAAC;IAC9E,OAAO,EAAE,GAAG,QAAQ,EAAE,gBAAgB,EAAE,CAAC,EAAE,kBAAkB,EAAE,KAAK,EAAE,CAAC;AACxE,CAAC","sourcesContent":["import type { AssistantMessage } from \"../types.ts\";\n\n/**\n * Regex patterns to detect context overflow errors from different providers.\n *\n * These patterns match error messages returned when the input exceeds\n * the model's context window.\n *\n * Provider-specific patterns (with example error messages):\n *\n * - Anthropic: \"prompt is too long: 213462 tokens > 200000 maximum\"\n * - Anthropic: \"413 {\\\"error\\\":{\\\"type\\\":\\\"request_too_large\\\",\\\"message\\\":\\\"Request exceeds the maximum size\\\"}}\"\n * - OpenAI: \"Your input exceeds the context window of this model\"\n * - OpenAI: \"Your input exceeds the model's context window\" / \"exceeds this model's context window\"\n * - OpenAI/LiteLLM: \"Requested token count exceeds the model's maximum context length of 131072 tokens\"\n * - OpenAI-compatible: \"Input length (265330) exceeds model's maximum context length (262144).\"\n * - Google: \"The input token count (1196265) exceeds the maximum number of tokens allowed (1048575)\"\n * - xAI: \"This model's maximum prompt length is 131072 but the request contains 537812 tokens\"\n * - Groq: \"Please reduce the length of the messages or completion\"\n * - OpenRouter: \"This endpoint's maximum context length is X tokens. However, you requested about Y tokens\"\n * - OpenRouter/Poolside: \"Input length X exceeds the maximum allowed input length of Y tokens.\"\n * - Together AI: \"The input (X tokens) is longer than the model's context length (Y tokens).\"\n * - llama.cpp: \"the request exceeds the available context size, try increasing it\"\n * - LM Studio: \"tokens to keep from the initial prompt is greater than the context length\"\n * - GitHub Copilot: \"prompt token count of X exceeds the limit of Y\"\n * - MiniMax: \"invalid params, context window exceeds limit\"\n * - Kimi For Coding: \"Your request exceeded model token limit: X (requested: Y)\"\n * - DS4: \"Prompt has X tokens, but the configured context size is Y tokens\"\n * - Cerebras: \"400/413 status code (no body)\"\n * - Gateways: \"413 Request body too large\" / \"Request Entity Too Large\" / \"Payload Too Large\" (byte-size overflow)\n * - kiro-lb gateways: \"Request payload is 1095225 bytes, over the 1085435 byte limit Kiro accepts.\" / \"Request payload is N tokens, over the M token limit Kiro accepts.\" (HTTP 400 local payload guard)\n * - Kiro upstream via kiro-lb: \"Model context limit reached. Conversation size exceeds model capacity.\" (CONTENT_LENGTH_EXCEEDS_THRESHOLD token overflow)\n * - Mistral: \"Prompt contains X tokens ... too large for model with Y maximum context length\"\n * - z.ai: Does NOT error, accepts overflow silently - handled via usage.input > contextWindow\n * - Xiaomi MiMo: Truncates input to fill contextWindow exactly, then returns finish_reason \"length\"\n * with output=0 (no room left to generate). Detected via stopReason \"length\" + zero output +\n * input filling the context window.\n * - DashScope/Qwen: \"Range of input length should be [1, X]\" (HTTP 400 invalid_parameter_error)\n * - Ollama: Some deployments truncate silently, others return errors like \"prompt too long; exceeded max context length by X tokens\"\n * - pi-ai pre-flight guard (api/context-room.ts): \"Context window exhausted: the conversation is estimated at X of Y tokens, ...\" - raised before any provider call\n */\nconst OVERFLOW_PATTERNS = [\n\t/^Context window exhausted: /, // pi-ai pre-flight guard: no answer room left, provider never called\n\t/prompt is too long/i, // Anthropic token overflow\n\t/request_too_large/i, // Anthropic request byte-size overflow (HTTP 413)\n\t/input is too long for requested model/i, // Amazon Bedrock\n\t/exceeds (?:(?:the|this) )?(?:model'?s )?context window/i, // OpenAI (Completions & Responses API)\n\t/exceeds (?:the )?(?:model'?s )?maximum context length(?: of [\\d,]+ tokens?|\\s*\\([\\d,]+\\))/i, // OpenAI-compatible proxies (LiteLLM)\n\t/input token count.*exceeds the maximum/i, // Google (Gemini)\n\t/maximum prompt length is \\d+/i, // xAI (Grok)\n\t/reduce the length of the messages/i, // Groq\n\t/maximum context length is \\d+ tokens/i, // OpenRouter (most backends)\n\t/exceeds (?:the )?maximum allowed input length of [\\d,]+ tokens?/i, // OpenRouter/Poolside\n\t/input \\(\\d+ tokens\\) is longer than the model'?s context length \\(\\d+ tokens\\)/i, // Together AI\n\t/model_max_prompt_tokens_exceeded|exceeds the limit of \\d+/i, // GitHub Copilot\n\t/exceeds the available context size/i, // llama.cpp server\n\t/greater than the context length/i, // LM Studio\n\t/context window exceeds limit/i, // MiniMax\n\t/exceeded model token limit/i, // Kimi For Coding\n\t/too large for model with \\d+ maximum context length/i, // Mistral\n\t/prompt has [\\d,]+ tokens?, but the configured context size is [\\d,]+ tokens?/i, // DS4 server\n\t/model_context_window_exceeded/i, // z.ai non-standard finish_reason surfaced as error text\n\t/prompt too long; exceeded (?:max )?context length/i, // Ollama explicit overflow error\n\t/range of input length should be/i, // DashScope / Qwen Token Plan\n\t/context[_ ]length[_ ]exceeded/i, // Generic fallback\n\t/too many tokens/i, // Generic fallback\n\t/token limit exceeded/i, // Generic fallback\n\t/^4(?:00|13)\\s*(?:status code)?\\s*\\(no body\\)/i, // Cerebras: 400/413 with no body\n\t/(?:request[ _])?(?:body|entity|payload)[_ ]too[_ ]large/i, // Gateway HTTP 413 byte-size rejections (\"Request body too large\", \"Request Entity Too Large\", \"body_too_large\", \"Payload Too Large\"). Substring-anchored by design (JSON bodies lack an adjacent status code); a non-context size rejection (e.g. an oversized image) can over-match, which costs one bounded shrink-retry, never a wedge.\n\t/Request payload is \\d+ (?:bytes, over the \\d+ byte|tokens, over the \\d+ token) limit Kiro accepts\\./, // kiro-lb local byte/token payload guard (HTTP 400; Anthropic uses invalid_request_error, OpenAI uses detail).\n\t/Model context limit reached\\. Conversation size exceeds model capacity\\./, // kiro-lb enhancement of Kiro CONTENT_LENGTH_EXCEEDS_THRESHOLD\n];\n\n/**\n * Patterns that indicate non-overflow errors (e.g. rate limiting, server errors).\n * Error messages matching any of these are excluded from overflow detection\n * even if they also match an OVERFLOW_PATTERN.\n *\n * Example: Bedrock formats throttling errors as \"ThrottlingException: Too many tokens,\n * please wait before trying again.\" which would match the /too many tokens/i overflow\n * pattern without this exclusion. Token-quota / TPM messages such as \"Too many tokens\n * per minute\" or \"This request exceeds the limit of 30000 tokens per minute\" similarly\n * match generic overflow fallbacks and must stay on the rate-limit path.\n */\nconst NON_OVERFLOW_PATTERNS = [\n\t/^(Throttling error|Service unavailable):/i, // AWS Bedrock non-overflow errors (human-readable prefixes from formatBedrockError)\n\t/rate limit/i, // Generic rate limiting\n\t/too many requests/i, // Generic HTTP 429 style\n\t/tokens per (?:min|minute|hour|day)/i, // Token-quota windows (TPM/TPH/TPD), not context size\n\t/\\bTPM\\b/i, // Tokens-per-minute abbreviation\n\t/\\bRPM\\b/i, // Requests-per-minute abbreviation\n\t/quota exceeded/i, // Provider quota, not context window\n\t/retry (?:after|in) \\d/i, // Retry-after rate-limit wording\n\t/^429\\b/, // HTTP 429 prefix\n\t/status code 429/i, // HTTP 429 mentioned mid-message\n\t/overloaded/i, // Provider capacity, not context size\n];\n\n/**\n * Cursor's api2.cursor.sh surfaces a context overflow as a bare gRPC\n * `resource_exhausted` end-stream — the same wording its backend uses for\n * quota and poisoned-conversation rejections. Token evidence disambiguates:\n * a request that already streamed or billed tokens overflowed mid-flight,\n * while a zero-token rejection is a quota/conversation failure that must stay\n * on the rate-limit path (the cursor client rotates the conversation id for\n * those and retry handling supplies the backoff).\n */\nconst RESOURCE_EXHAUSTED_PATTERN = /resource.?exhausted/i;\n\n/**\n * Check if an assistant message represents a context overflow error.\n *\n * This handles three cases:\n * 1. Error-based overflow: Most providers return stopReason \"error\" with a\n * specific error message pattern.\n * 2. Silent overflow: Some providers accept overflow requests and return\n * successfully. For these, we check if usage.input exceeds the context window.\n * 3. Length-stop overflow: Xiaomi MiMo can return \"length\" with zero output when\n * the input fills the context window.\n *\n * ## Reliability by Provider\n *\n * **Reliable detection (returns error with detectable message):**\n * - Anthropic: \"prompt is too long: X tokens > Y maximum\" or \"request_too_large\"\n * - OpenAI (Completions & Responses): \"exceeds the context window\", \"exceeds the model's context window\", \"exceeds this model's context window\", \"exceeds the model's maximum context length of X tokens\", or \"exceeds model's maximum context length (X)\"\n * - Google Gemini: \"input token count exceeds the maximum\"\n * - xAI (Grok): \"maximum prompt length is X but request contains Y\"\n * - Groq: \"reduce the length of the messages\"\n * - Cerebras: 400/413 status code (no body)\n * - Mistral: \"Prompt contains X tokens ... too large for model with Y maximum context length\"\n * - OpenRouter (most backends): \"maximum context length is X tokens\"\n * - OpenRouter/Poolside: \"Input length X exceeds the maximum allowed input length of Y tokens.\"\n * - Together AI: \"The input (X tokens) is longer than the model's context length (Y tokens).\"\n * - llama.cpp: \"exceeds the available context size\"\n * - LM Studio: \"greater than the context length\"\n * - Kimi For Coding: \"exceeded model token limit: X (requested: Y)\"\n * - DS4: \"Prompt has X tokens, but the configured context size is Y tokens\"\n * - DashScope/Qwen: \"Range of input length should be [1, X]\"\n *\n * **Unreliable detection:**\n * - z.ai: Sometimes accepts overflow silently (detectable via usage.input > contextWindow),\n * sometimes returns rate limit errors. Pass contextWindow param to detect silent overflow.\n * - Xiaomi MiMo: Truncates input to fit contextWindow then returns stopReason \"length\" with\n * output=0. Pass contextWindow param to detect via the \"filled context + zero output\" signal.\n * - Ollama: May truncate input silently for some setups, but may also return explicit\n * overflow errors that match the patterns above. Silent truncation still cannot be\n * detected here because we do not know the expected token count.\n *\n * ## Custom Providers\n *\n * If you've added custom models via settings.json, this function may not detect\n * overflow errors from those providers. To add support:\n *\n * 1. Send a request that exceeds the model's context window\n * 2. Check the errorMessage in the response\n * 3. Create a regex pattern that matches the error\n * 4. The pattern should be added to OVERFLOW_PATTERNS in this file, or\n * check the errorMessage yourself before calling this function\n *\n * @param message - The assistant message to check\n * @param contextWindow - Optional context window size for detecting silent overflow (z.ai)\n * @returns true if the message indicates a context overflow\n */\nexport function isContextOverflow(message: AssistantMessage, contextWindow?: number): boolean {\n\t// Case 1: Check error message patterns\n\tif (message.stopReason === \"error\" && message.errorMessage) {\n\t\t// Skip messages matching known non-overflow patterns (e.g. throttling / rate-limit)\n\t\tconst isNonOverflow = NON_OVERFLOW_PATTERNS.some((p) => p.test(message.errorMessage!));\n\t\tif (!isNonOverflow && OVERFLOW_PATTERNS.some((p) => p.test(message.errorMessage!))) {\n\t\t\treturn true;\n\t\t}\n\t\tconst usage = message.usage;\n\t\tconst hasTokenEvidence =\n\t\t\t(usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite) > 0;\n\t\tif (\n\t\t\t!isNonOverflow &&\n\t\t\thasTokenEvidence &&\n\t\t\tRESOURCE_EXHAUSTED_PATTERN.test(message.errorMessage) &&\n\t\t\t(contextWindow === undefined || contextWindow <= 0 || cursorZeroTokenCount(message) >= contextWindow * 0.5)\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t// Case 2: Silent overflow (z.ai style) - successful but usage exceeds context\n\tif (contextWindow && message.stopReason === \"stop\") {\n\t\tconst inputTokens = message.usage.input + message.usage.cacheRead;\n\t\tif (inputTokens > contextWindow) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t// Case 3: Length-stop overflow (Xiaomi MiMo style) - server truncates oversized input\n\t// to fit the context window, leaving no room for output. Returns stopReason \"length\"\n\t// with output=0 and input+cacheRead filling the context window.\n\tif (contextWindow && message.stopReason === \"length\" && message.usage.output === 0) {\n\t\tconst inputTokens = message.usage.input + message.usage.cacheRead;\n\t\tif (inputTokens >= contextWindow * 0.99) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n/**\n * Check whether a length stop ended below the caller or model's intended output limit.\n * Such responses may be caused by context pressure or provider-side truncation, so callers\n * can make one bounded compact-and-retry attempt. `desiredMaxOutput` must be the original\n * limit before any context-based clamping.\n */\nexport function isRecoverableLength(message: AssistantMessage, desiredMaxOutput: number): boolean {\n\treturn message.stopReason === \"length\" && desiredMaxOutput > 0 && message.usage.output < desiredMaxOutput;\n}\n\n/**\n * Get the overflow patterns for testing purposes.\n */\nexport function getOverflowPatterns(): RegExp[] {\n\treturn [...OVERFLOW_PATTERNS];\n}\n\nfunction cursorZeroTokenCount(message: {\n\tusage?: { input?: number; output?: number; cacheRead?: number; cacheWrite?: number; totalTokens?: number };\n}): number {\n\tconst usage = message.usage;\n\tif (!usage) return 0;\n\treturn (\n\t\tusage.totalTokens || (usage.input ?? 0) + (usage.output ?? 0) + (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0)\n\t);\n}\n\nexport function isCursorPayloadResourceExhausted(\n\tmessage: {\n\t\tstopReason?: string;\n\t\terrorMessage?: string;\n\t\tusage?: { input?: number; output?: number; cacheRead?: number; cacheWrite?: number; totalTokens?: number };\n\t},\n\t_estimateTokens: number,\n): boolean {\n\tif (message.stopReason !== \"error\" || !/resource.?exhausted/i.test(message.errorMessage || \"\")) {\n\t\treturn false;\n\t}\n\treturn !(cursorZeroTokenCount(message) > 0);\n}\n\n/**\n * Detects Cursor's verified usage-pool exhaustion signature: a token-bearing\n * `resource_exhausted` error while the conversation is well below the model\n * context window.\n */\nexport function isCursorQuotaResourceExhausted(\n\tmessage: {\n\t\tstopReason?: string;\n\t\terrorMessage?: string;\n\t\tusage?: { input?: number; output?: number; cacheRead?: number; cacheWrite?: number; totalTokens?: number };\n\t},\n\tcontextWindow: number,\n): boolean {\n\tconst tokens = cursorZeroTokenCount(message);\n\treturn (\n\t\tmessage.stopReason === \"error\" &&\n\t\tRESOURCE_EXHAUSTED_PATTERN.test(message.errorMessage || \"\") &&\n\t\tcontextWindow > 0 &&\n\t\ttokens > 0 &&\n\t\ttokens < contextWindow * 0.5\n\t);\n}\n\nexport function isCursorZeroTokenResourceExhausted(message: {\n\tstopReason?: string;\n\terrorMessage?: string;\n\tusage?: { input?: number; output?: number; cacheRead?: number; cacheWrite?: number; totalTokens?: number };\n}): boolean {\n\tif (message.stopReason !== \"error\" || !/resource.?exhausted/i.test(message.errorMessage || \"\")) {\n\t\treturn false;\n\t}\n\treturn !(cursorZeroTokenCount(message) > 0);\n}\n\nexport function shouldSkipProviderFallbackForCursorZeroRe(options: { sameModelRemint?: boolean } | undefined): boolean {\n\treturn options?.sameModelRemint === true;\n}\n\nexport function shouldRetryOverflowWithoutCompact(compacted: boolean, errorMessage: string): boolean {\n\tif (compacted) return false;\n\treturn /Nothing to compact/i.test(errorMessage || \"\");\n}\n\nexport function cursorOverflowCompactionSettings<T extends { keepRecentTokens?: number; restorationEnabled?: boolean }>(\n\tsettings: T,\n\tprovider: string | undefined,\n\treason: string | undefined,\n): T {\n\tif (reason !== \"overflow\") return settings;\n\tif (provider !== \"cursor\" && provider !== \"cursor-cli-oauth\") return settings;\n\treturn { ...settings, keepRecentTokens: 0, restorationEnabled: false };\n}\n"]}
@@ -1,4 +1,7 @@
1
1
  import type { AssistantMessage } from "../types.ts";
2
+ export declare const PROVIDER_REQUEST_ID_MARKER = "request id:";
3
+ export declare function formatProviderRequestId(label: string, id: string): string;
4
+ export declare function stripProviderRequestIds(text: string): string;
2
5
  /**
3
6
  * OpenAI hard account-quota exhaustion (senpi#1969). The wire evidence is a 429
4
7
  * whose body is `{"type":"usage_limit_reached","message":"The usage limit has
@@ -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;AAWpD;;;;;;;;;GASG;AACH,eAAO,MAAM,sBAAsB;IAClC,+EAA+E;aAC/E,KAAK,YAAG,qBAAqB,EAAE,oBAAoB;IACnD,+EAA+E;aAC/E,OAAO,YAAG,qBAAqB,EAAE,oBAAoB,EAAE,8BAA8B;CAC5E,CAAC;AA0CX,wBAAgB,wBAAwB,CAAC,YAAY,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,CAElF;AAoID;;;;;;GAMG;AACH,MAAM,WAAW,WAAW;IAC3B,OAAO,EAAE,OAAO,CAAC;IACjB,qFAAqF;IACrF,UAAU,EAAE,MAAM,CAAC;IACnB,0FAA0F;IAC1F,WAAW,EAAE,MAAM,CAAC;IACpB,+EAA+E;IAC/E,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,oEAAoE;IACpE,MAAM,CAAC,EAAE,MAAM,MAAM,CAAC;CACtB;AAED,eAAO,MAAM,gC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;;;GAOG;AACH,wBAAgB,oBAAoB,CAAC,YAAY,EAAE,MAAM,GAAG,eAAe,GAAG,WAAW,GAAG,SAAS,CAMpG"}
@@ -1,4 +1,15 @@
1
1
  import { FORWARDED_EMPTY_RESPONSE_ERROR, FORWARDED_EMPTY_TOOL_USE_ERROR } from "./empty-response-errors.js";
2
+ // A provider's support request id is opaque hex like `C6FD:AB660:AEB5548:6ABA4D81`.
3
+ // It can contain `429` or `500`, which message classifiers read as HTTP statuses,
4
+ // so every id is rendered behind this marker and removed before classification.
5
+ export const PROVIDER_REQUEST_ID_MARKER = "request id:";
6
+ const REQUEST_ID_SEGMENT = /request id: [^\s,;)]+/gi;
7
+ export function formatProviderRequestId(label, id) {
8
+ return `${label} ${PROVIDER_REQUEST_ID_MARKER} ${id}`;
9
+ }
10
+ export function stripProviderRequestIds(text) {
11
+ return text.replace(REQUEST_ID_SEGMENT, PROVIDER_REQUEST_ID_MARKER);
12
+ }
2
13
  function buildProviderErrorPattern(patterns) {
3
14
  return new RegExp(patterns.join("|"), "i");
4
15
  }
@@ -56,7 +67,7 @@ const QUOTA_EXHAUSTION_PATTERNS = [
56
67
  ];
57
68
  const QUOTA_EXHAUSTION_PATTERN = buildProviderErrorPattern(QUOTA_EXHAUSTION_PATTERNS);
58
69
  export function isQuotaExhaustionMessage(errorMessage) {
59
- return errorMessage !== undefined && QUOTA_EXHAUSTION_PATTERN.test(errorMessage);
70
+ return errorMessage !== undefined && QUOTA_EXHAUSTION_PATTERN.test(stripProviderRequestIds(errorMessage));
60
71
  }
61
72
  const NON_RETRYABLE_PROVIDER_ERROR_PATTERN = buildProviderErrorPattern([
62
73
  ...QUOTA_EXHAUSTION_PATTERNS,
@@ -463,9 +474,10 @@ export function isRetryableErrorMessage(errorMessage) {
463
474
  export function classifyErrorMessage(errorMessage) {
464
475
  if (!errorMessage)
465
476
  return "unknown";
466
- if (NON_RETRYABLE_PROVIDER_ERROR_PATTERN.test(errorMessage))
477
+ const text = stripProviderRequestIds(errorMessage);
478
+ if (NON_RETRYABLE_PROVIDER_ERROR_PATTERN.test(text))
467
479
  return "non-retryable";
468
- if (RETRYABLE_PROVIDER_ERROR_PATTERN.test(errorMessage))
480
+ if (RETRYABLE_PROVIDER_ERROR_PATTERN.test(text))
469
481
  return "retryable";
470
482
  return "unknown";
471
483
  }