@handy_wote/pi-ai 0.81.1

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 (346) hide show
  1. package/README.md +1623 -0
  2. package/dist/api/anthropic-messages.d.ts +71 -0
  3. package/dist/api/anthropic-messages.d.ts.map +1 -0
  4. package/dist/api/anthropic-messages.js +1024 -0
  5. package/dist/api/anthropic-messages.js.map +1 -0
  6. package/dist/api/anthropic-messages.lazy.d.ts +3 -0
  7. package/dist/api/anthropic-messages.lazy.d.ts.map +1 -0
  8. package/dist/api/anthropic-messages.lazy.js +3 -0
  9. package/dist/api/anthropic-messages.lazy.js.map +1 -0
  10. package/dist/api/azure-openai-responses.d.ts +15 -0
  11. package/dist/api/azure-openai-responses.d.ts.map +1 -0
  12. package/dist/api/azure-openai-responses.js +221 -0
  13. package/dist/api/azure-openai-responses.js.map +1 -0
  14. package/dist/api/azure-openai-responses.lazy.d.ts +3 -0
  15. package/dist/api/azure-openai-responses.lazy.d.ts.map +1 -0
  16. package/dist/api/azure-openai-responses.lazy.js +3 -0
  17. package/dist/api/azure-openai-responses.lazy.js.map +1 -0
  18. package/dist/api/bedrock-converse-stream.d.ts +38 -0
  19. package/dist/api/bedrock-converse-stream.d.ts.map +1 -0
  20. package/dist/api/bedrock-converse-stream.js +883 -0
  21. package/dist/api/bedrock-converse-stream.js.map +1 -0
  22. package/dist/api/bedrock-converse-stream.lazy.d.ts +9 -0
  23. package/dist/api/bedrock-converse-stream.lazy.d.ts.map +1 -0
  24. package/dist/api/bedrock-converse-stream.lazy.js +30 -0
  25. package/dist/api/bedrock-converse-stream.lazy.js.map +1 -0
  26. package/dist/api/cloudflare.d.ts +9 -0
  27. package/dist/api/cloudflare.d.ts.map +1 -0
  28. package/dist/api/cloudflare.js +9 -0
  29. package/dist/api/cloudflare.js.map +1 -0
  30. package/dist/api/github-copilot-headers.d.ts +8 -0
  31. package/dist/api/github-copilot-headers.d.ts.map +1 -0
  32. package/dist/api/github-copilot-headers.js +29 -0
  33. package/dist/api/github-copilot-headers.js.map +1 -0
  34. package/dist/api/google-generative-ai.d.ts +13 -0
  35. package/dist/api/google-generative-ai.d.ts.map +1 -0
  36. package/dist/api/google-generative-ai.js +407 -0
  37. package/dist/api/google-generative-ai.js.map +1 -0
  38. package/dist/api/google-generative-ai.lazy.d.ts +3 -0
  39. package/dist/api/google-generative-ai.lazy.d.ts.map +1 -0
  40. package/dist/api/google-generative-ai.lazy.js +3 -0
  41. package/dist/api/google-generative-ai.lazy.js.map +1 -0
  42. package/dist/api/google-shared.d.ts +70 -0
  43. package/dist/api/google-shared.d.ts.map +1 -0
  44. package/dist/api/google-shared.js +329 -0
  45. package/dist/api/google-shared.js.map +1 -0
  46. package/dist/api/google-vertex.d.ts +15 -0
  47. package/dist/api/google-vertex.d.ts.map +1 -0
  48. package/dist/api/google-vertex.js +456 -0
  49. package/dist/api/google-vertex.js.map +1 -0
  50. package/dist/api/google-vertex.lazy.d.ts +3 -0
  51. package/dist/api/google-vertex.lazy.d.ts.map +1 -0
  52. package/dist/api/google-vertex.lazy.js +3 -0
  53. package/dist/api/google-vertex.lazy.js.map +1 -0
  54. package/dist/api/lazy.d.ts +15 -0
  55. package/dist/api/lazy.d.ts.map +1 -0
  56. package/dist/api/lazy.js +58 -0
  57. package/dist/api/lazy.js.map +1 -0
  58. package/dist/api/mistral-conversations.d.ts +25 -0
  59. package/dist/api/mistral-conversations.d.ts.map +1 -0
  60. package/dist/api/mistral-conversations.js +555 -0
  61. package/dist/api/mistral-conversations.js.map +1 -0
  62. package/dist/api/mistral-conversations.lazy.d.ts +3 -0
  63. package/dist/api/mistral-conversations.lazy.d.ts.map +1 -0
  64. package/dist/api/mistral-conversations.lazy.js +3 -0
  65. package/dist/api/mistral-conversations.lazy.js.map +1 -0
  66. package/dist/api/openai-codex-responses.d.ts +31 -0
  67. package/dist/api/openai-codex-responses.d.ts.map +1 -0
  68. package/dist/api/openai-codex-responses.js +1222 -0
  69. package/dist/api/openai-codex-responses.js.map +1 -0
  70. package/dist/api/openai-codex-responses.lazy.d.ts +3 -0
  71. package/dist/api/openai-codex-responses.lazy.d.ts.map +1 -0
  72. package/dist/api/openai-codex-responses.lazy.js +3 -0
  73. package/dist/api/openai-codex-responses.lazy.js.map +1 -0
  74. package/dist/api/openai-completions.d.ts +20 -0
  75. package/dist/api/openai-completions.d.ts.map +1 -0
  76. package/dist/api/openai-completions.js +1120 -0
  77. package/dist/api/openai-completions.js.map +1 -0
  78. package/dist/api/openai-completions.lazy.d.ts +3 -0
  79. package/dist/api/openai-completions.lazy.d.ts.map +1 -0
  80. package/dist/api/openai-completions.lazy.js +3 -0
  81. package/dist/api/openai-completions.lazy.js.map +1 -0
  82. package/dist/api/openai-prompt-cache.d.ts +3 -0
  83. package/dist/api/openai-prompt-cache.d.ts.map +1 -0
  84. package/dist/api/openai-prompt-cache.js +10 -0
  85. package/dist/api/openai-prompt-cache.js.map +1 -0
  86. package/dist/api/openai-responses-shared.d.ts +20 -0
  87. package/dist/api/openai-responses-shared.d.ts.map +1 -0
  88. package/dist/api/openai-responses-shared.js +535 -0
  89. package/dist/api/openai-responses-shared.js.map +1 -0
  90. package/dist/api/openai-responses.d.ts +14 -0
  91. package/dist/api/openai-responses.d.ts.map +1 -0
  92. package/dist/api/openai-responses.js +246 -0
  93. package/dist/api/openai-responses.js.map +1 -0
  94. package/dist/api/openai-responses.lazy.d.ts +3 -0
  95. package/dist/api/openai-responses.lazy.d.ts.map +1 -0
  96. package/dist/api/openai-responses.lazy.js +3 -0
  97. package/dist/api/openai-responses.lazy.js.map +1 -0
  98. package/dist/api/openrouter-images.d.ts +3 -0
  99. package/dist/api/openrouter-images.d.ts.map +1 -0
  100. package/dist/api/openrouter-images.js +126 -0
  101. package/dist/api/openrouter-images.js.map +1 -0
  102. package/dist/api/openrouter-images.lazy.d.ts +3 -0
  103. package/dist/api/openrouter-images.lazy.d.ts.map +1 -0
  104. package/dist/api/openrouter-images.lazy.js +4 -0
  105. package/dist/api/openrouter-images.lazy.js.map +1 -0
  106. package/dist/api/pi-messages.d.ts +97 -0
  107. package/dist/api/pi-messages.d.ts.map +1 -0
  108. package/dist/api/pi-messages.js +307 -0
  109. package/dist/api/pi-messages.js.map +1 -0
  110. package/dist/api/pi-messages.lazy.d.ts +3 -0
  111. package/dist/api/pi-messages.lazy.d.ts.map +1 -0
  112. package/dist/api/pi-messages.lazy.js +3 -0
  113. package/dist/api/pi-messages.lazy.js.map +1 -0
  114. package/dist/api/simple-options.d.ts +9 -0
  115. package/dist/api/simple-options.d.ts.map +1 -0
  116. package/dist/api/simple-options.js +52 -0
  117. package/dist/api/simple-options.js.map +1 -0
  118. package/dist/api/transform-messages.d.ts +8 -0
  119. package/dist/api/transform-messages.d.ts.map +1 -0
  120. package/dist/api/transform-messages.js +187 -0
  121. package/dist/api/transform-messages.js.map +1 -0
  122. package/dist/auth/context.d.ts +7 -0
  123. package/dist/auth/context.d.ts.map +1 -0
  124. package/dist/auth/context.js +42 -0
  125. package/dist/auth/context.js.map +1 -0
  126. package/dist/auth/credential-store.d.ts +17 -0
  127. package/dist/auth/credential-store.d.ts.map +1 -0
  128. package/dist/auth/credential-store.js +40 -0
  129. package/dist/auth/credential-store.js.map +1 -0
  130. package/dist/auth/helpers.d.ts +21 -0
  131. package/dist/auth/helpers.d.ts.map +1 -0
  132. package/dist/auth/helpers.js +48 -0
  133. package/dist/auth/helpers.js.map +1 -0
  134. package/dist/auth/oauth/anthropic.d.ts +9 -0
  135. package/dist/auth/oauth/anthropic.d.ts.map +1 -0
  136. package/dist/auth/oauth/anthropic.js +302 -0
  137. package/dist/auth/oauth/anthropic.js.map +1 -0
  138. package/dist/auth/oauth/device-code.d.ts +23 -0
  139. package/dist/auth/oauth/device-code.d.ts.map +1 -0
  140. package/dist/auth/oauth/device-code.js +69 -0
  141. package/dist/auth/oauth/device-code.js.map +1 -0
  142. package/dist/auth/oauth/github-copilot.d.ts +6 -0
  143. package/dist/auth/oauth/github-copilot.d.ts.map +1 -0
  144. package/dist/auth/oauth/github-copilot.js +313 -0
  145. package/dist/auth/oauth/github-copilot.js.map +1 -0
  146. package/dist/auth/oauth/load.d.ts +23 -0
  147. package/dist/auth/oauth/load.d.ts.map +1 -0
  148. package/dist/auth/oauth/load.js +49 -0
  149. package/dist/auth/oauth/load.js.map +1 -0
  150. package/dist/auth/oauth/oauth-page.d.ts +3 -0
  151. package/dist/auth/oauth/oauth-page.d.ts.map +1 -0
  152. package/dist/auth/oauth/oauth-page.js +105 -0
  153. package/dist/auth/oauth/oauth-page.js.map +1 -0
  154. package/dist/auth/oauth/openai-codex.d.ts +9 -0
  155. package/dist/auth/oauth/openai-codex.d.ts.map +1 -0
  156. package/dist/auth/oauth/openai-codex.js +443 -0
  157. package/dist/auth/oauth/openai-codex.js.map +1 -0
  158. package/dist/auth/oauth/pkce.d.ts +13 -0
  159. package/dist/auth/oauth/pkce.d.ts.map +1 -0
  160. package/dist/auth/oauth/pkce.js +31 -0
  161. package/dist/auth/oauth/pkce.js.map +1 -0
  162. package/dist/auth/oauth/radius.d.ts +16 -0
  163. package/dist/auth/oauth/radius.d.ts.map +1 -0
  164. package/dist/auth/oauth/radius.js +321 -0
  165. package/dist/auth/oauth/radius.js.map +1 -0
  166. package/dist/auth/oauth/xai.d.ts +6 -0
  167. package/dist/auth/oauth/xai.d.ts.map +1 -0
  168. package/dist/auth/oauth/xai.js +189 -0
  169. package/dist/auth/oauth/xai.js.map +1 -0
  170. package/dist/auth/resolve.d.ts +24 -0
  171. package/dist/auth/resolve.d.ts.map +1 -0
  172. package/dist/auth/resolve.js +103 -0
  173. package/dist/auth/resolve.js.map +1 -0
  174. package/dist/auth/types.d.ts +219 -0
  175. package/dist/auth/types.d.ts.map +1 -0
  176. package/dist/auth/types.js +2 -0
  177. package/dist/auth/types.js.map +1 -0
  178. package/dist/bedrock-provider.d.ts +5 -0
  179. package/dist/bedrock-provider.d.ts.map +1 -0
  180. package/dist/bedrock-provider.js +6 -0
  181. package/dist/bedrock-provider.js.map +1 -0
  182. package/dist/bun-oauth.d.ts +3 -0
  183. package/dist/bun-oauth.d.ts.map +1 -0
  184. package/dist/bun-oauth.js +17 -0
  185. package/dist/bun-oauth.js.map +1 -0
  186. package/dist/cli.d.ts +3 -0
  187. package/dist/cli.d.ts.map +1 -0
  188. package/dist/cli.js +115 -0
  189. package/dist/cli.js.map +1 -0
  190. package/dist/compat/extension-oauth-types.d.ts +39 -0
  191. package/dist/compat/extension-oauth-types.d.ts.map +1 -0
  192. package/dist/compat/extension-oauth-types.js +2 -0
  193. package/dist/compat/extension-oauth-types.js.map +1 -0
  194. package/dist/compat.d.ts +70 -0
  195. package/dist/compat.d.ts.map +1 -0
  196. package/dist/compat.js +189 -0
  197. package/dist/compat.js.map +1 -0
  198. package/dist/env-api-keys.d.ts +18 -0
  199. package/dist/env-api-keys.d.ts.map +1 -0
  200. package/dist/env-api-keys.js +148 -0
  201. package/dist/env-api-keys.js.map +1 -0
  202. package/dist/image-models.d.ts +10 -0
  203. package/dist/image-models.d.ts.map +1 -0
  204. package/dist/image-models.js +24 -0
  205. package/dist/image-models.js.map +1 -0
  206. package/dist/images-api-registry.d.ts +14 -0
  207. package/dist/images-api-registry.d.ts.map +1 -0
  208. package/dist/images-api-registry.js +22 -0
  209. package/dist/images-api-registry.js.map +1 -0
  210. package/dist/images-models.d.ts +95 -0
  211. package/dist/images-models.d.ts.map +1 -0
  212. package/dist/images-models.js +142 -0
  213. package/dist/images-models.js.map +1 -0
  214. package/dist/images.d.ts +4 -0
  215. package/dist/images.d.ts.map +1 -0
  216. package/dist/images.js +14 -0
  217. package/dist/images.js.map +1 -0
  218. package/dist/index.d.ts +35 -0
  219. package/dist/index.d.ts.map +1 -0
  220. package/dist/index.js +22 -0
  221. package/dist/index.js.map +1 -0
  222. package/dist/legacy-api-aliases.d.ts +42 -0
  223. package/dist/legacy-api-aliases.d.ts.map +1 -0
  224. package/dist/legacy-api-aliases.js +49 -0
  225. package/dist/legacy-api-aliases.js.map +1 -0
  226. package/dist/models-store.d.ts +27 -0
  227. package/dist/models-store.d.ts.map +1 -0
  228. package/dist/models-store.js +14 -0
  229. package/dist/models-store.js.map +1 -0
  230. package/dist/models.d.ts +178 -0
  231. package/dist/models.d.ts.map +1 -0
  232. package/dist/models.js +432 -0
  233. package/dist/models.js.map +1 -0
  234. package/dist/oauth.d.ts +3 -0
  235. package/dist/oauth.d.ts.map +1 -0
  236. package/dist/oauth.js +2 -0
  237. package/dist/oauth.js.map +1 -0
  238. package/dist/providers/all.d.ts +6 -0
  239. package/dist/providers/all.d.ts.map +1 -0
  240. package/dist/providers/all.js +9 -0
  241. package/dist/providers/all.js.map +1 -0
  242. package/dist/providers/anthropic-compat.d.ts +10 -0
  243. package/dist/providers/anthropic-compat.d.ts.map +1 -0
  244. package/dist/providers/anthropic-compat.js +20 -0
  245. package/dist/providers/anthropic-compat.js.map +1 -0
  246. package/dist/providers/faux.d.ts +97 -0
  247. package/dist/providers/faux.d.ts.map +1 -0
  248. package/dist/providers/faux.js +395 -0
  249. package/dist/providers/faux.js.map +1 -0
  250. package/dist/providers/images/register-builtins.d.ts +4 -0
  251. package/dist/providers/images/register-builtins.d.ts.map +1 -0
  252. package/dist/providers/images/register-builtins.js +34 -0
  253. package/dist/providers/images/register-builtins.js.map +1 -0
  254. package/dist/providers/openai-compat.d.ts +10 -0
  255. package/dist/providers/openai-compat.d.ts.map +1 -0
  256. package/dist/providers/openai-compat.js +24 -0
  257. package/dist/providers/openai-compat.js.map +1 -0
  258. package/dist/providers/openrouter-images.d.ts +3 -0
  259. package/dist/providers/openrouter-images.d.ts.map +1 -0
  260. package/dist/providers/openrouter-images.js +15 -0
  261. package/dist/providers/openrouter-images.js.map +1 -0
  262. package/dist/providers/radius.d.ts +9 -0
  263. package/dist/providers/radius.d.ts.map +1 -0
  264. package/dist/providers/radius.js +70 -0
  265. package/dist/providers/radius.js.map +1 -0
  266. package/dist/session-resources.d.ts +4 -0
  267. package/dist/session-resources.d.ts.map +1 -0
  268. package/dist/session-resources.js +22 -0
  269. package/dist/session-resources.js.map +1 -0
  270. package/dist/types.d.ts +629 -0
  271. package/dist/types.d.ts.map +1 -0
  272. package/dist/types.js +2 -0
  273. package/dist/types.js.map +1 -0
  274. package/dist/utils/abort-signals.d.ts +6 -0
  275. package/dist/utils/abort-signals.d.ts.map +1 -0
  276. package/dist/utils/abort-signals.js +34 -0
  277. package/dist/utils/abort-signals.js.map +1 -0
  278. package/dist/utils/deferred-tools.d.ts +9 -0
  279. package/dist/utils/deferred-tools.d.ts.map +1 -0
  280. package/dist/utils/deferred-tools.js +36 -0
  281. package/dist/utils/deferred-tools.js.map +1 -0
  282. package/dist/utils/diagnostics.d.ts +19 -0
  283. package/dist/utils/diagnostics.d.ts.map +1 -0
  284. package/dist/utils/diagnostics.js +25 -0
  285. package/dist/utils/diagnostics.js.map +1 -0
  286. package/dist/utils/error-body.d.ts +25 -0
  287. package/dist/utils/error-body.d.ts.map +1 -0
  288. package/dist/utils/error-body.js +109 -0
  289. package/dist/utils/error-body.js.map +1 -0
  290. package/dist/utils/estimate.d.ts +17 -0
  291. package/dist/utils/estimate.d.ts.map +1 -0
  292. package/dist/utils/estimate.js +116 -0
  293. package/dist/utils/estimate.js.map +1 -0
  294. package/dist/utils/event-stream.d.ts +21 -0
  295. package/dist/utils/event-stream.d.ts.map +1 -0
  296. package/dist/utils/event-stream.js +81 -0
  297. package/dist/utils/event-stream.js.map +1 -0
  298. package/dist/utils/hash.d.ts +3 -0
  299. package/dist/utils/hash.d.ts.map +1 -0
  300. package/dist/utils/hash.js +14 -0
  301. package/dist/utils/hash.js.map +1 -0
  302. package/dist/utils/headers.d.ts +4 -0
  303. package/dist/utils/headers.d.ts.map +1 -0
  304. package/dist/utils/headers.js +18 -0
  305. package/dist/utils/headers.js.map +1 -0
  306. package/dist/utils/json-parse.d.ts +16 -0
  307. package/dist/utils/json-parse.d.ts.map +1 -0
  308. package/dist/utils/json-parse.js +113 -0
  309. package/dist/utils/json-parse.js.map +1 -0
  310. package/dist/utils/node-http-proxy.d.ts +4 -0
  311. package/dist/utils/node-http-proxy.d.ts.map +1 -0
  312. package/dist/utils/node-http-proxy.js +92 -0
  313. package/dist/utils/node-http-proxy.js.map +1 -0
  314. package/dist/utils/overflow.d.ts +59 -0
  315. package/dist/utils/overflow.d.ts.map +1 -0
  316. package/dist/utils/overflow.js +161 -0
  317. package/dist/utils/overflow.js.map +1 -0
  318. package/dist/utils/provider-env.d.ts +7 -0
  319. package/dist/utils/provider-env.d.ts.map +1 -0
  320. package/dist/utils/provider-env.js +44 -0
  321. package/dist/utils/provider-env.js.map +1 -0
  322. package/dist/utils/retry.d.ts +53 -0
  323. package/dist/utils/retry.d.ts.map +1 -0
  324. package/dist/utils/retry.js +170 -0
  325. package/dist/utils/retry.js.map +1 -0
  326. package/dist/utils/sanitize-unicode.d.ts +22 -0
  327. package/dist/utils/sanitize-unicode.d.ts.map +1 -0
  328. package/dist/utils/sanitize-unicode.js +26 -0
  329. package/dist/utils/sanitize-unicode.js.map +1 -0
  330. package/dist/utils/text.d.ts +6 -0
  331. package/dist/utils/text.d.ts.map +1 -0
  332. package/dist/utils/text.js +10 -0
  333. package/dist/utils/text.js.map +1 -0
  334. package/dist/utils/typebox-helpers.d.ts +17 -0
  335. package/dist/utils/typebox-helpers.d.ts.map +1 -0
  336. package/dist/utils/typebox-helpers.js +21 -0
  337. package/dist/utils/typebox-helpers.js.map +1 -0
  338. package/dist/utils/uuid.d.ts +3 -0
  339. package/dist/utils/uuid.d.ts.map +1 -0
  340. package/dist/utils/uuid.js +46 -0
  341. package/dist/utils/uuid.js.map +1 -0
  342. package/dist/utils/validation.d.ts +18 -0
  343. package/dist/utils/validation.d.ts.map +1 -0
  344. package/dist/utils/validation.js +269 -0
  345. package/dist/utils/validation.js.map +1 -0
  346. package/package.json +95 -0
@@ -0,0 +1,59 @@
1
+ import type { AssistantMessage } from "../types.ts";
2
+ /**
3
+ * Check if an assistant message represents a context overflow error.
4
+ *
5
+ * This handles two cases:
6
+ * 1. Error-based overflow: Most providers return stopReason "error" with a
7
+ * specific error message pattern.
8
+ * 2. Silent overflow: Some providers accept overflow requests and return
9
+ * successfully. For these, we check if usage.input exceeds the context window.
10
+ *
11
+ * ## Reliability by Provider
12
+ *
13
+ * **Reliable detection (returns error with detectable message):**
14
+ * - Anthropic: "prompt is too long: X tokens > Y maximum" or "request_too_large"
15
+ * - OpenAI (Completions & Responses): "exceeds the context window", "exceeds the model's maximum context length of X tokens", or "exceeds model's maximum context length (X)"
16
+ * - Google Gemini: "input token count exceeds the maximum"
17
+ * - xAI (Grok): "maximum prompt length is X but request contains Y"
18
+ * - Groq: "reduce the length of the messages"
19
+ * - Cerebras: 400/413 status code (no body)
20
+ * - Mistral: "Prompt contains X tokens ... too large for model with Y maximum context length"
21
+ * - OpenRouter (most backends): "maximum context length is X tokens"
22
+ * - OpenRouter/Poolside: "Input length X exceeds the maximum allowed input length of Y tokens."
23
+ * - Together AI: "The input (X tokens) is longer than the model's context length (Y tokens)."
24
+ * - llama.cpp: "exceeds the available context size"
25
+ * - LM Studio: "greater than the context length"
26
+ * - Kimi For Coding: "exceeded model token limit: X (requested: Y)"
27
+ * - DS4: "Prompt has X tokens, but the configured context size is Y tokens"
28
+ * - DashScope/Qwen: "Range of input length should be [1, X]"
29
+ *
30
+ * **Unreliable detection:**
31
+ * - z.ai: Sometimes accepts overflow silently (detectable via usage.input > contextWindow),
32
+ * sometimes returns rate limit errors. Pass contextWindow param to detect silent overflow.
33
+ * - Xiaomi MiMo: Truncates input to fit contextWindow then returns stopReason "length" with
34
+ * output=0. Pass contextWindow param to detect via the "filled context + zero output" signal.
35
+ * - Ollama: May truncate input silently for some setups, but may also return explicit
36
+ * overflow errors that match the patterns above. Silent truncation still cannot be
37
+ * detected here because we do not know the expected token count.
38
+ *
39
+ * ## Custom Providers
40
+ *
41
+ * If you've added custom models via settings.json, this function may not detect
42
+ * overflow errors from those providers. To add support:
43
+ *
44
+ * 1. Send a request that exceeds the model's context window
45
+ * 2. Check the errorMessage in the response
46
+ * 3. Create a regex pattern that matches the error
47
+ * 4. The pattern should be added to OVERFLOW_PATTERNS in this file, or
48
+ * check the errorMessage yourself before calling this function
49
+ *
50
+ * @param message - The assistant message to check
51
+ * @param contextWindow - Optional context window size for detecting silent overflow (z.ai)
52
+ * @returns true if the message indicates a context overflow
53
+ */
54
+ export declare function isContextOverflow(message: AssistantMessage, contextWindow?: number): boolean;
55
+ /**
56
+ * Get the overflow patterns for testing purposes.
57
+ */
58
+ export declare function getOverflowPatterns(): RegExp[];
59
+ //# sourceMappingURL=overflow.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"overflow.d.ts","sourceRoot":"","sources":["../../src/utils/overflow.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AA+EpD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmDG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,gBAAgB,EAAE,aAAa,CAAC,EAAE,MAAM,GAAG,OAAO,CA6B5F;AAED;;GAEG;AACH,wBAAgB,mBAAmB,IAAI,MAAM,EAAE,CAE9C","sourcesContent":["import type { AssistantMessage } from \"../types.ts\";\n\n/**\n * Regex patterns to detect context overflow errors from different providers.\n *\n * These patterns match error messages returned when the input exceeds\n * the model's context window.\n *\n * Provider-specific patterns (with example error messages):\n *\n * - Anthropic: \"prompt is too long: 213462 tokens > 200000 maximum\"\n * - Anthropic: \"413 {\\\"error\\\":{\\\"type\\\":\\\"request_too_large\\\",\\\"message\\\":\\\"Request exceeds the maximum size\\\"}}\"\n * - OpenAI: \"Your input exceeds the context window of this model\"\n * - OpenAI/LiteLLM: \"Requested token count exceeds the model's maximum context length of 131072 tokens\"\n * - OpenAI-compatible: \"Input length (265330) exceeds model's maximum context length (262144).\"\n * - Google: \"The input token count (1196265) exceeds the maximum number of tokens allowed (1048575)\"\n * - xAI: \"This model's maximum prompt length is 131072 but the request contains 537812 tokens\"\n * - Groq: \"Please reduce the length of the messages or completion\"\n * - OpenRouter: \"This endpoint's maximum context length is X tokens. However, you requested about Y tokens\"\n * - OpenRouter/Poolside: \"Input length X exceeds the maximum allowed input length of Y tokens.\"\n * - Together AI: \"The input (X tokens) is longer than the model's context length (Y tokens).\"\n * - llama.cpp: \"the request exceeds the available context size, try increasing it\"\n * - LM Studio: \"tokens to keep from the initial prompt is greater than the context length\"\n * - GitHub Copilot: \"prompt token count of X exceeds the limit of Y\"\n * - MiniMax: \"invalid params, context window exceeds limit\"\n * - Kimi For Coding: \"Your request exceeded model token limit: X (requested: Y)\"\n * - DS4: \"Prompt has X tokens, but the configured context size is Y tokens\"\n * - Cerebras: \"400/413 status code (no body)\"\n * - Mistral: \"Prompt contains X tokens ... too large for model with Y maximum context length\"\n * - z.ai: Does NOT error, accepts overflow silently - handled via usage.input > contextWindow\n * - Xiaomi MiMo: Truncates input to fill contextWindow exactly, then returns finish_reason \"length\"\n * with output=0 (no room left to generate). Detected via stopReason \"length\" + zero output +\n * input filling the context window.\n * - DashScope/Qwen: \"Range of input length should be [1, X]\" (HTTP 400 invalid_parameter_error)\n * - Ollama: Some deployments truncate silently, others return errors like \"prompt too long; exceeded max context length by X tokens\"\n */\nconst OVERFLOW_PATTERNS = [\n\t/prompt is too long/i, // Anthropic token overflow\n\t/request_too_large/i, // Anthropic request byte-size overflow (HTTP 413)\n\t/input is too long for requested model/i, // Amazon Bedrock\n\t/exceeds the context window/i, // OpenAI (Completions & Responses API)\n\t/exceeds (?:the )?(?:model'?s )?maximum context length(?: of [\\d,]+ tokens?|\\s*\\([\\d,]+\\))/i, // OpenAI-compatible proxies (LiteLLM)\n\t/input token count.*exceeds the maximum/i, // Google (Gemini)\n\t/maximum prompt length is \\d+/i, // xAI (Grok)\n\t/reduce the length of the messages/i, // Groq\n\t/maximum context length is \\d+ tokens/i, // OpenRouter (most backends)\n\t/exceeds (?:the )?maximum allowed input length of [\\d,]+ tokens?/i, // OpenRouter/Poolside\n\t/input \\(\\d+ tokens\\) is longer than the model'?s context length \\(\\d+ tokens\\)/i, // Together AI\n\t/exceeds the limit of \\d+/i, // GitHub Copilot\n\t/exceeds the available context size/i, // llama.cpp server\n\t/greater than the context length/i, // LM Studio\n\t/context window exceeds limit/i, // MiniMax\n\t/exceeded model token limit/i, // Kimi For Coding\n\t/too large for model with \\d+ maximum context length/i, // Mistral\n\t/prompt has [\\d,]+ tokens?, but the configured context size is [\\d,]+ tokens?/i, // DS4 server\n\t/model_context_window_exceeded/i, // z.ai non-standard finish_reason surfaced as error text\n\t/prompt too long; exceeded (?:max )?context length/i, // Ollama explicit overflow error\n\t/range of input length should be/i, // DashScope / Qwen Token Plan\n\t/context[_ ]length[_ ]exceeded/i, // Generic fallback\n\t/too many tokens/i, // Generic fallback\n\t/token limit exceeded/i, // Generic fallback\n\t/^4(?:00|13)\\s*(?:status code)?\\s*\\(no body\\)/i, // Cerebras: 400/413 with no body\n];\n\n/**\n * Patterns that indicate non-overflow errors (e.g. rate limiting, server errors).\n * Error messages matching any of these are excluded from overflow detection\n * even if they also match an OVERFLOW_PATTERN.\n *\n * Example: Bedrock formats throttling errors as \"ThrottlingException: Too many tokens,\n * please wait before trying again.\" which would match the /too many tokens/i overflow\n * pattern without this exclusion.\n */\nconst NON_OVERFLOW_PATTERNS = [\n\t/^(Throttling error|Service unavailable):/i, // AWS Bedrock non-overflow errors (human-readable prefixes from formatBedrockError)\n\t/rate limit/i, // Generic rate limiting\n\t/too many requests/i, // Generic HTTP 429 style\n];\n\n/**\n * Check if an assistant message represents a context overflow error.\n *\n * This handles two cases:\n * 1. Error-based overflow: Most providers return stopReason \"error\" with a\n * specific error message pattern.\n * 2. Silent overflow: Some providers accept overflow requests and return\n * successfully. For these, we check if usage.input exceeds the context window.\n *\n * ## Reliability by Provider\n *\n * **Reliable detection (returns error with detectable message):**\n * - Anthropic: \"prompt is too long: X tokens > Y maximum\" or \"request_too_large\"\n * - OpenAI (Completions & Responses): \"exceeds the context window\", \"exceeds the model's maximum context length of X tokens\", or \"exceeds model's maximum context length (X)\"\n * - Google Gemini: \"input token count exceeds the maximum\"\n * - xAI (Grok): \"maximum prompt length is X but request contains Y\"\n * - Groq: \"reduce the length of the messages\"\n * - Cerebras: 400/413 status code (no body)\n * - Mistral: \"Prompt contains X tokens ... too large for model with Y maximum context length\"\n * - OpenRouter (most backends): \"maximum context length is X tokens\"\n * - OpenRouter/Poolside: \"Input length X exceeds the maximum allowed input length of Y tokens.\"\n * - Together AI: \"The input (X tokens) is longer than the model's context length (Y tokens).\"\n * - llama.cpp: \"exceeds the available context size\"\n * - LM Studio: \"greater than the context length\"\n * - Kimi For Coding: \"exceeded model token limit: X (requested: Y)\"\n * - DS4: \"Prompt has X tokens, but the configured context size is Y tokens\"\n * - DashScope/Qwen: \"Range of input length should be [1, X]\"\n *\n * **Unreliable detection:**\n * - z.ai: Sometimes accepts overflow silently (detectable via usage.input > contextWindow),\n * sometimes returns rate limit errors. Pass contextWindow param to detect silent overflow.\n * - Xiaomi MiMo: Truncates input to fit contextWindow then returns stopReason \"length\" with\n * output=0. Pass contextWindow param to detect via the \"filled context + zero output\" signal.\n * - Ollama: May truncate input silently for some setups, but may also return explicit\n * overflow errors that match the patterns above. Silent truncation still cannot be\n * detected here because we do not know the expected token count.\n *\n * ## Custom Providers\n *\n * If you've added custom models via settings.json, this function may not detect\n * overflow errors from those providers. To add support:\n *\n * 1. Send a request that exceeds the model's context window\n * 2. Check the errorMessage in the response\n * 3. Create a regex pattern that matches the error\n * 4. The pattern should be added to OVERFLOW_PATTERNS in this file, or\n * check the errorMessage yourself before calling this function\n *\n * @param message - The assistant message to check\n * @param contextWindow - Optional context window size for detecting silent overflow (z.ai)\n * @returns true if the message indicates a context overflow\n */\nexport function isContextOverflow(message: AssistantMessage, contextWindow?: number): boolean {\n\t// Case 1: Check error message patterns\n\tif (message.stopReason === \"error\" && message.errorMessage) {\n\t\t// Skip messages matching known non-overflow patterns (e.g. throttling / rate-limit)\n\t\tconst isNonOverflow = NON_OVERFLOW_PATTERNS.some((p) => p.test(message.errorMessage!));\n\t\tif (!isNonOverflow && OVERFLOW_PATTERNS.some((p) => p.test(message.errorMessage!))) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t// Case 2: Silent overflow (z.ai style) - successful but usage exceeds context\n\tif (contextWindow && message.stopReason === \"stop\") {\n\t\tconst inputTokens = message.usage.input + message.usage.cacheRead;\n\t\tif (inputTokens > contextWindow) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t// Case 3: Length-stop overflow (Xiaomi MiMo style) - server truncates oversized input\n\t// to fit the context window, leaving no room for output. Returns stopReason \"length\"\n\t// with output=0 and input+cacheRead filling the context window.\n\tif (contextWindow && message.stopReason === \"length\" && message.usage.output === 0) {\n\t\tconst inputTokens = message.usage.input + message.usage.cacheRead;\n\t\tif (inputTokens >= contextWindow * 0.99) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\n/**\n * Get the overflow patterns for testing purposes.\n */\nexport function getOverflowPatterns(): RegExp[] {\n\treturn [...OVERFLOW_PATTERNS];\n}\n"]}
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Regex patterns to detect context overflow errors from different providers.
3
+ *
4
+ * These patterns match error messages returned when the input exceeds
5
+ * the model's context window.
6
+ *
7
+ * Provider-specific patterns (with example error messages):
8
+ *
9
+ * - Anthropic: "prompt is too long: 213462 tokens > 200000 maximum"
10
+ * - Anthropic: "413 {\"error\":{\"type\":\"request_too_large\",\"message\":\"Request exceeds the maximum size\"}}"
11
+ * - OpenAI: "Your input exceeds the context window of this model"
12
+ * - OpenAI/LiteLLM: "Requested token count exceeds the model's maximum context length of 131072 tokens"
13
+ * - OpenAI-compatible: "Input length (265330) exceeds model's maximum context length (262144)."
14
+ * - Google: "The input token count (1196265) exceeds the maximum number of tokens allowed (1048575)"
15
+ * - xAI: "This model's maximum prompt length is 131072 but the request contains 537812 tokens"
16
+ * - Groq: "Please reduce the length of the messages or completion"
17
+ * - OpenRouter: "This endpoint's maximum context length is X tokens. However, you requested about Y tokens"
18
+ * - OpenRouter/Poolside: "Input length X exceeds the maximum allowed input length of Y tokens."
19
+ * - Together AI: "The input (X tokens) is longer than the model's context length (Y tokens)."
20
+ * - llama.cpp: "the request exceeds the available context size, try increasing it"
21
+ * - LM Studio: "tokens to keep from the initial prompt is greater than the context length"
22
+ * - GitHub Copilot: "prompt token count of X exceeds the limit of Y"
23
+ * - MiniMax: "invalid params, context window exceeds limit"
24
+ * - Kimi For Coding: "Your request exceeded model token limit: X (requested: Y)"
25
+ * - DS4: "Prompt has X tokens, but the configured context size is Y tokens"
26
+ * - Cerebras: "400/413 status code (no body)"
27
+ * - Mistral: "Prompt contains X tokens ... too large for model with Y maximum context length"
28
+ * - z.ai: Does NOT error, accepts overflow silently - handled via usage.input > contextWindow
29
+ * - Xiaomi MiMo: Truncates input to fill contextWindow exactly, then returns finish_reason "length"
30
+ * with output=0 (no room left to generate). Detected via stopReason "length" + zero output +
31
+ * input filling the context window.
32
+ * - DashScope/Qwen: "Range of input length should be [1, X]" (HTTP 400 invalid_parameter_error)
33
+ * - Ollama: Some deployments truncate silently, others return errors like "prompt too long; exceeded max context length by X tokens"
34
+ */
35
+ const OVERFLOW_PATTERNS = [
36
+ /prompt is too long/i, // Anthropic token overflow
37
+ /request_too_large/i, // Anthropic request byte-size overflow (HTTP 413)
38
+ /input is too long for requested model/i, // Amazon Bedrock
39
+ /exceeds the context window/i, // OpenAI (Completions & Responses API)
40
+ /exceeds (?:the )?(?:model'?s )?maximum context length(?: of [\d,]+ tokens?|\s*\([\d,]+\))/i, // OpenAI-compatible proxies (LiteLLM)
41
+ /input token count.*exceeds the maximum/i, // Google (Gemini)
42
+ /maximum prompt length is \d+/i, // xAI (Grok)
43
+ /reduce the length of the messages/i, // Groq
44
+ /maximum context length is \d+ tokens/i, // OpenRouter (most backends)
45
+ /exceeds (?:the )?maximum allowed input length of [\d,]+ tokens?/i, // OpenRouter/Poolside
46
+ /input \(\d+ tokens\) is longer than the model'?s context length \(\d+ tokens\)/i, // Together AI
47
+ /exceeds the limit of \d+/i, // GitHub Copilot
48
+ /exceeds the available context size/i, // llama.cpp server
49
+ /greater than the context length/i, // LM Studio
50
+ /context window exceeds limit/i, // MiniMax
51
+ /exceeded model token limit/i, // Kimi For Coding
52
+ /too large for model with \d+ maximum context length/i, // Mistral
53
+ /prompt has [\d,]+ tokens?, but the configured context size is [\d,]+ tokens?/i, // DS4 server
54
+ /model_context_window_exceeded/i, // z.ai non-standard finish_reason surfaced as error text
55
+ /prompt too long; exceeded (?:max )?context length/i, // Ollama explicit overflow error
56
+ /range of input length should be/i, // DashScope / Qwen Token Plan
57
+ /context[_ ]length[_ ]exceeded/i, // Generic fallback
58
+ /too many tokens/i, // Generic fallback
59
+ /token limit exceeded/i, // Generic fallback
60
+ /^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i, // Cerebras: 400/413 with no body
61
+ ];
62
+ /**
63
+ * Patterns that indicate non-overflow errors (e.g. rate limiting, server errors).
64
+ * Error messages matching any of these are excluded from overflow detection
65
+ * even if they also match an OVERFLOW_PATTERN.
66
+ *
67
+ * Example: Bedrock formats throttling errors as "ThrottlingException: Too many tokens,
68
+ * please wait before trying again." which would match the /too many tokens/i overflow
69
+ * pattern without this exclusion.
70
+ */
71
+ const NON_OVERFLOW_PATTERNS = [
72
+ /^(Throttling error|Service unavailable):/i, // AWS Bedrock non-overflow errors (human-readable prefixes from formatBedrockError)
73
+ /rate limit/i, // Generic rate limiting
74
+ /too many requests/i, // Generic HTTP 429 style
75
+ ];
76
+ /**
77
+ * Check if an assistant message represents a context overflow error.
78
+ *
79
+ * This handles two cases:
80
+ * 1. Error-based overflow: Most providers return stopReason "error" with a
81
+ * specific error message pattern.
82
+ * 2. Silent overflow: Some providers accept overflow requests and return
83
+ * successfully. For these, we check if usage.input exceeds the context window.
84
+ *
85
+ * ## Reliability by Provider
86
+ *
87
+ * **Reliable detection (returns error with detectable message):**
88
+ * - Anthropic: "prompt is too long: X tokens > Y maximum" or "request_too_large"
89
+ * - OpenAI (Completions & Responses): "exceeds the context window", "exceeds the model's maximum context length of X tokens", or "exceeds model's maximum context length (X)"
90
+ * - Google Gemini: "input token count exceeds the maximum"
91
+ * - xAI (Grok): "maximum prompt length is X but request contains Y"
92
+ * - Groq: "reduce the length of the messages"
93
+ * - Cerebras: 400/413 status code (no body)
94
+ * - Mistral: "Prompt contains X tokens ... too large for model with Y maximum context length"
95
+ * - OpenRouter (most backends): "maximum context length is X tokens"
96
+ * - OpenRouter/Poolside: "Input length X exceeds the maximum allowed input length of Y tokens."
97
+ * - Together AI: "The input (X tokens) is longer than the model's context length (Y tokens)."
98
+ * - llama.cpp: "exceeds the available context size"
99
+ * - LM Studio: "greater than the context length"
100
+ * - Kimi For Coding: "exceeded model token limit: X (requested: Y)"
101
+ * - DS4: "Prompt has X tokens, but the configured context size is Y tokens"
102
+ * - DashScope/Qwen: "Range of input length should be [1, X]"
103
+ *
104
+ * **Unreliable detection:**
105
+ * - z.ai: Sometimes accepts overflow silently (detectable via usage.input > contextWindow),
106
+ * sometimes returns rate limit errors. Pass contextWindow param to detect silent overflow.
107
+ * - Xiaomi MiMo: Truncates input to fit contextWindow then returns stopReason "length" with
108
+ * output=0. Pass contextWindow param to detect via the "filled context + zero output" signal.
109
+ * - Ollama: May truncate input silently for some setups, but may also return explicit
110
+ * overflow errors that match the patterns above. Silent truncation still cannot be
111
+ * detected here because we do not know the expected token count.
112
+ *
113
+ * ## Custom Providers
114
+ *
115
+ * If you've added custom models via settings.json, this function may not detect
116
+ * overflow errors from those providers. To add support:
117
+ *
118
+ * 1. Send a request that exceeds the model's context window
119
+ * 2. Check the errorMessage in the response
120
+ * 3. Create a regex pattern that matches the error
121
+ * 4. The pattern should be added to OVERFLOW_PATTERNS in this file, or
122
+ * check the errorMessage yourself before calling this function
123
+ *
124
+ * @param message - The assistant message to check
125
+ * @param contextWindow - Optional context window size for detecting silent overflow (z.ai)
126
+ * @returns true if the message indicates a context overflow
127
+ */
128
+ export function isContextOverflow(message, contextWindow) {
129
+ // Case 1: Check error message patterns
130
+ if (message.stopReason === "error" && message.errorMessage) {
131
+ // Skip messages matching known non-overflow patterns (e.g. throttling / rate-limit)
132
+ const isNonOverflow = NON_OVERFLOW_PATTERNS.some((p) => p.test(message.errorMessage));
133
+ if (!isNonOverflow && OVERFLOW_PATTERNS.some((p) => p.test(message.errorMessage))) {
134
+ return true;
135
+ }
136
+ }
137
+ // Case 2: Silent overflow (z.ai style) - successful but usage exceeds context
138
+ if (contextWindow && message.stopReason === "stop") {
139
+ const inputTokens = message.usage.input + message.usage.cacheRead;
140
+ if (inputTokens > contextWindow) {
141
+ return true;
142
+ }
143
+ }
144
+ // Case 3: Length-stop overflow (Xiaomi MiMo style) - server truncates oversized input
145
+ // to fit the context window, leaving no room for output. Returns stopReason "length"
146
+ // with output=0 and input+cacheRead filling the context window.
147
+ if (contextWindow && message.stopReason === "length" && message.usage.output === 0) {
148
+ const inputTokens = message.usage.input + message.usage.cacheRead;
149
+ if (inputTokens >= contextWindow * 0.99) {
150
+ return true;
151
+ }
152
+ }
153
+ return false;
154
+ }
155
+ /**
156
+ * Get the overflow patterns for testing purposes.
157
+ */
158
+ export function getOverflowPatterns() {
159
+ return [...OVERFLOW_PATTERNS];
160
+ }
161
+ //# sourceMappingURL=overflow.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"overflow.js","sourceRoot":"","sources":["../../src/utils/overflow.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,MAAM,iBAAiB,GAAG;IACzB,qBAAqB,EAAE,2BAA2B;IAClD,oBAAoB,EAAE,kDAAkD;IACxE,wCAAwC,EAAE,iBAAiB;IAC3D,6BAA6B,EAAE,uCAAuC;IACtE,4FAA4F,EAAE,sCAAsC;IACpI,yCAAyC,EAAE,kBAAkB;IAC7D,+BAA+B,EAAE,aAAa;IAC9C,oCAAoC,EAAE,OAAO;IAC7C,uCAAuC,EAAE,6BAA6B;IACtE,kEAAkE,EAAE,sBAAsB;IAC1F,iFAAiF,EAAE,cAAc;IACjG,2BAA2B,EAAE,iBAAiB;IAC9C,qCAAqC,EAAE,mBAAmB;IAC1D,kCAAkC,EAAE,YAAY;IAChD,+BAA+B,EAAE,UAAU;IAC3C,6BAA6B,EAAE,kBAAkB;IACjD,sDAAsD,EAAE,UAAU;IAClE,+EAA+E,EAAE,aAAa;IAC9F,gCAAgC,EAAE,yDAAyD;IAC3F,oDAAoD,EAAE,iCAAiC;IACvF,kCAAkC,EAAE,8BAA8B;IAClE,gCAAgC,EAAE,mBAAmB;IACrD,kBAAkB,EAAE,mBAAmB;IACvC,uBAAuB,EAAE,mBAAmB;IAC5C,+CAA+C,EAAE,iCAAiC;CAClF,CAAC;AAEF;;;;;;;;GAQG;AACH,MAAM,qBAAqB,GAAG;IAC7B,2CAA2C,EAAE,oFAAoF;IACjI,aAAa,EAAE,wBAAwB;IACvC,oBAAoB,EAAE,yBAAyB;CAC/C,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmDG;AACH,MAAM,UAAU,iBAAiB,CAAC,OAAyB,EAAE,aAAsB,EAAW;IAC7F,uCAAuC;IACvC,IAAI,OAAO,CAAC,UAAU,KAAK,OAAO,IAAI,OAAO,CAAC,YAAY,EAAE,CAAC;QAC5D,oFAAoF;QACpF,MAAM,aAAa,GAAG,qBAAqB,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,YAAa,CAAC,CAAC,CAAC;QACvF,IAAI,CAAC,aAAa,IAAI,iBAAiB,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,YAAa,CAAC,CAAC,EAAE,CAAC;YACpF,OAAO,IAAI,CAAC;QACb,CAAC;IACF,CAAC;IAED,8EAA8E;IAC9E,IAAI,aAAa,IAAI,OAAO,CAAC,UAAU,KAAK,MAAM,EAAE,CAAC;QACpD,MAAM,WAAW,GAAG,OAAO,CAAC,KAAK,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,SAAS,CAAC;QAClE,IAAI,WAAW,GAAG,aAAa,EAAE,CAAC;YACjC,OAAO,IAAI,CAAC;QACb,CAAC;IACF,CAAC;IAED,sFAAsF;IACtF,qFAAqF;IACrF,gEAAgE;IAChE,IAAI,aAAa,IAAI,OAAO,CAAC,UAAU,KAAK,QAAQ,IAAI,OAAO,CAAC,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACpF,MAAM,WAAW,GAAG,OAAO,CAAC,KAAK,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,SAAS,CAAC;QAClE,IAAI,WAAW,IAAI,aAAa,GAAG,IAAI,EAAE,CAAC;YACzC,OAAO,IAAI,CAAC;QACb,CAAC;IACF,CAAC;IAED,OAAO,KAAK,CAAC;AAAA,CACb;AAED;;GAEG;AACH,MAAM,UAAU,mBAAmB,GAAa;IAC/C,OAAO,CAAC,GAAG,iBAAiB,CAAC,CAAC;AAAA,CAC9B","sourcesContent":["import type { AssistantMessage } from \"../types.ts\";\n\n/**\n * Regex patterns to detect context overflow errors from different providers.\n *\n * These patterns match error messages returned when the input exceeds\n * the model's context window.\n *\n * Provider-specific patterns (with example error messages):\n *\n * - Anthropic: \"prompt is too long: 213462 tokens > 200000 maximum\"\n * - Anthropic: \"413 {\\\"error\\\":{\\\"type\\\":\\\"request_too_large\\\",\\\"message\\\":\\\"Request exceeds the maximum size\\\"}}\"\n * - OpenAI: \"Your input exceeds the context window of this model\"\n * - OpenAI/LiteLLM: \"Requested token count exceeds the model's maximum context length of 131072 tokens\"\n * - OpenAI-compatible: \"Input length (265330) exceeds model's maximum context length (262144).\"\n * - Google: \"The input token count (1196265) exceeds the maximum number of tokens allowed (1048575)\"\n * - xAI: \"This model's maximum prompt length is 131072 but the request contains 537812 tokens\"\n * - Groq: \"Please reduce the length of the messages or completion\"\n * - OpenRouter: \"This endpoint's maximum context length is X tokens. However, you requested about Y tokens\"\n * - OpenRouter/Poolside: \"Input length X exceeds the maximum allowed input length of Y tokens.\"\n * - Together AI: \"The input (X tokens) is longer than the model's context length (Y tokens).\"\n * - llama.cpp: \"the request exceeds the available context size, try increasing it\"\n * - LM Studio: \"tokens to keep from the initial prompt is greater than the context length\"\n * - GitHub Copilot: \"prompt token count of X exceeds the limit of Y\"\n * - MiniMax: \"invalid params, context window exceeds limit\"\n * - Kimi For Coding: \"Your request exceeded model token limit: X (requested: Y)\"\n * - DS4: \"Prompt has X tokens, but the configured context size is Y tokens\"\n * - Cerebras: \"400/413 status code (no body)\"\n * - Mistral: \"Prompt contains X tokens ... too large for model with Y maximum context length\"\n * - z.ai: Does NOT error, accepts overflow silently - handled via usage.input > contextWindow\n * - Xiaomi MiMo: Truncates input to fill contextWindow exactly, then returns finish_reason \"length\"\n * with output=0 (no room left to generate). Detected via stopReason \"length\" + zero output +\n * input filling the context window.\n * - DashScope/Qwen: \"Range of input length should be [1, X]\" (HTTP 400 invalid_parameter_error)\n * - Ollama: Some deployments truncate silently, others return errors like \"prompt too long; exceeded max context length by X tokens\"\n */\nconst OVERFLOW_PATTERNS = [\n\t/prompt is too long/i, // Anthropic token overflow\n\t/request_too_large/i, // Anthropic request byte-size overflow (HTTP 413)\n\t/input is too long for requested model/i, // Amazon Bedrock\n\t/exceeds the context window/i, // OpenAI (Completions & Responses API)\n\t/exceeds (?:the )?(?:model'?s )?maximum context length(?: of [\\d,]+ tokens?|\\s*\\([\\d,]+\\))/i, // OpenAI-compatible proxies (LiteLLM)\n\t/input token count.*exceeds the maximum/i, // Google (Gemini)\n\t/maximum prompt length is \\d+/i, // xAI (Grok)\n\t/reduce the length of the messages/i, // Groq\n\t/maximum context length is \\d+ tokens/i, // OpenRouter (most backends)\n\t/exceeds (?:the )?maximum allowed input length of [\\d,]+ tokens?/i, // OpenRouter/Poolside\n\t/input \\(\\d+ tokens\\) is longer than the model'?s context length \\(\\d+ tokens\\)/i, // Together AI\n\t/exceeds the limit of \\d+/i, // GitHub Copilot\n\t/exceeds the available context size/i, // llama.cpp server\n\t/greater than the context length/i, // LM Studio\n\t/context window exceeds limit/i, // MiniMax\n\t/exceeded model token limit/i, // Kimi For Coding\n\t/too large for model with \\d+ maximum context length/i, // Mistral\n\t/prompt has [\\d,]+ tokens?, but the configured context size is [\\d,]+ tokens?/i, // DS4 server\n\t/model_context_window_exceeded/i, // z.ai non-standard finish_reason surfaced as error text\n\t/prompt too long; exceeded (?:max )?context length/i, // Ollama explicit overflow error\n\t/range of input length should be/i, // DashScope / Qwen Token Plan\n\t/context[_ ]length[_ ]exceeded/i, // Generic fallback\n\t/too many tokens/i, // Generic fallback\n\t/token limit exceeded/i, // Generic fallback\n\t/^4(?:00|13)\\s*(?:status code)?\\s*\\(no body\\)/i, // Cerebras: 400/413 with no body\n];\n\n/**\n * Patterns that indicate non-overflow errors (e.g. rate limiting, server errors).\n * Error messages matching any of these are excluded from overflow detection\n * even if they also match an OVERFLOW_PATTERN.\n *\n * Example: Bedrock formats throttling errors as \"ThrottlingException: Too many tokens,\n * please wait before trying again.\" which would match the /too many tokens/i overflow\n * pattern without this exclusion.\n */\nconst NON_OVERFLOW_PATTERNS = [\n\t/^(Throttling error|Service unavailable):/i, // AWS Bedrock non-overflow errors (human-readable prefixes from formatBedrockError)\n\t/rate limit/i, // Generic rate limiting\n\t/too many requests/i, // Generic HTTP 429 style\n];\n\n/**\n * Check if an assistant message represents a context overflow error.\n *\n * This handles two cases:\n * 1. Error-based overflow: Most providers return stopReason \"error\" with a\n * specific error message pattern.\n * 2. Silent overflow: Some providers accept overflow requests and return\n * successfully. For these, we check if usage.input exceeds the context window.\n *\n * ## Reliability by Provider\n *\n * **Reliable detection (returns error with detectable message):**\n * - Anthropic: \"prompt is too long: X tokens > Y maximum\" or \"request_too_large\"\n * - OpenAI (Completions & Responses): \"exceeds the context window\", \"exceeds the model's maximum context length of X tokens\", or \"exceeds model's maximum context length (X)\"\n * - Google Gemini: \"input token count exceeds the maximum\"\n * - xAI (Grok): \"maximum prompt length is X but request contains Y\"\n * - Groq: \"reduce the length of the messages\"\n * - Cerebras: 400/413 status code (no body)\n * - Mistral: \"Prompt contains X tokens ... too large for model with Y maximum context length\"\n * - OpenRouter (most backends): \"maximum context length is X tokens\"\n * - OpenRouter/Poolside: \"Input length X exceeds the maximum allowed input length of Y tokens.\"\n * - Together AI: \"The input (X tokens) is longer than the model's context length (Y tokens).\"\n * - llama.cpp: \"exceeds the available context size\"\n * - LM Studio: \"greater than the context length\"\n * - Kimi For Coding: \"exceeded model token limit: X (requested: Y)\"\n * - DS4: \"Prompt has X tokens, but the configured context size is Y tokens\"\n * - DashScope/Qwen: \"Range of input length should be [1, X]\"\n *\n * **Unreliable detection:**\n * - z.ai: Sometimes accepts overflow silently (detectable via usage.input > contextWindow),\n * sometimes returns rate limit errors. Pass contextWindow param to detect silent overflow.\n * - Xiaomi MiMo: Truncates input to fit contextWindow then returns stopReason \"length\" with\n * output=0. Pass contextWindow param to detect via the \"filled context + zero output\" signal.\n * - Ollama: May truncate input silently for some setups, but may also return explicit\n * overflow errors that match the patterns above. Silent truncation still cannot be\n * detected here because we do not know the expected token count.\n *\n * ## Custom Providers\n *\n * If you've added custom models via settings.json, this function may not detect\n * overflow errors from those providers. To add support:\n *\n * 1. Send a request that exceeds the model's context window\n * 2. Check the errorMessage in the response\n * 3. Create a regex pattern that matches the error\n * 4. The pattern should be added to OVERFLOW_PATTERNS in this file, or\n * check the errorMessage yourself before calling this function\n *\n * @param message - The assistant message to check\n * @param contextWindow - Optional context window size for detecting silent overflow (z.ai)\n * @returns true if the message indicates a context overflow\n */\nexport function isContextOverflow(message: AssistantMessage, contextWindow?: number): boolean {\n\t// Case 1: Check error message patterns\n\tif (message.stopReason === \"error\" && message.errorMessage) {\n\t\t// Skip messages matching known non-overflow patterns (e.g. throttling / rate-limit)\n\t\tconst isNonOverflow = NON_OVERFLOW_PATTERNS.some((p) => p.test(message.errorMessage!));\n\t\tif (!isNonOverflow && OVERFLOW_PATTERNS.some((p) => p.test(message.errorMessage!))) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t// Case 2: Silent overflow (z.ai style) - successful but usage exceeds context\n\tif (contextWindow && message.stopReason === \"stop\") {\n\t\tconst inputTokens = message.usage.input + message.usage.cacheRead;\n\t\tif (inputTokens > contextWindow) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t// Case 3: Length-stop overflow (Xiaomi MiMo style) - server truncates oversized input\n\t// to fit the context window, leaving no room for output. Returns stopReason \"length\"\n\t// with output=0 and input+cacheRead filling the context window.\n\tif (contextWindow && message.stopReason === \"length\" && message.usage.output === 0) {\n\t\tconst inputTokens = message.usage.input + message.usage.cacheRead;\n\t\tif (inputTokens >= contextWindow * 0.99) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\n/**\n * Get the overflow patterns for testing purposes.\n */\nexport function getOverflowPatterns(): RegExp[] {\n\treturn [...OVERFLOW_PATTERNS];\n}\n"]}
@@ -0,0 +1,7 @@
1
+ import type { ProviderEnv } from "../types.ts";
2
+ /**
3
+ * Resolve a provider env value from scoped overrides, normal process.env, then
4
+ * the duplicated Bun sandbox fallback for direct pi-ai consumers.
5
+ */
6
+ export declare function getProviderEnvValue(name: string, env?: ProviderEnv): string | undefined;
7
+ //# sourceMappingURL=provider-env.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider-env.d.ts","sourceRoot":"","sources":["../../src/utils/provider-env.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAwC/C;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,WAAW,GAAG,MAAM,GAAG,SAAS,CAOvF","sourcesContent":["import type { ProviderEnv } from \"../types.ts\";\n\nlet procEnvCache: Map<string, string> | null = null;\n\n/**\n * Fallback for https://github.com/oven-sh/bun/issues/27802.\n * Bun compiled binaries can expose an empty process.env inside Linux sandboxes\n * even though /proc/self/environ contains the environment.\n *\n * This intentionally duplicates restoreSandboxEnv() in\n * packages/coding-agent/src/bun/restore-sandbox-env.ts. The ai package can be\n * used directly, without going through that entrypoint, so provider env lookup\n * must not depend on process.env having been patched.\n */\nfunction getBunSandboxEnvValue(name: string): string | undefined {\n\tif (typeof process === \"undefined\" || !process.versions?.bun || Object.keys(process.env).length > 0) {\n\t\treturn undefined;\n\t}\n\n\tif (procEnvCache === null) {\n\t\tprocEnvCache = new Map();\n\t\ttry {\n\t\t\tconst { readFileSync } = require(\"node:fs\") as {\n\t\t\t\treadFileSync(path: string, encoding: BufferEncoding): string;\n\t\t\t};\n\t\t\tconst data = readFileSync(\"/proc/self/environ\", \"utf-8\");\n\t\t\tfor (const entry of data.split(\"\\0\")) {\n\t\t\t\tconst idx = entry.indexOf(\"=\");\n\t\t\t\tif (idx > 0) {\n\t\t\t\t\tprocEnvCache.set(entry.slice(0, idx), entry.slice(idx + 1));\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\t// /proc/self/environ may not exist or may not be readable.\n\t\t}\n\t}\n\n\treturn procEnvCache.get(name);\n}\n\n/**\n * Resolve a provider env value from scoped overrides, normal process.env, then\n * the duplicated Bun sandbox fallback for direct pi-ai consumers.\n */\nexport function getProviderEnvValue(name: string, env?: ProviderEnv): string | undefined {\n\treturn (\n\t\tenv?.[name] ||\n\t\t(typeof process !== \"undefined\" ? process.env[name] : undefined) ||\n\t\tgetBunSandboxEnvValue(name) ||\n\t\tundefined\n\t);\n}\n"]}
@@ -0,0 +1,44 @@
1
+ let procEnvCache = null;
2
+ /**
3
+ * Fallback for https://github.com/oven-sh/bun/issues/27802.
4
+ * Bun compiled binaries can expose an empty process.env inside Linux sandboxes
5
+ * even though /proc/self/environ contains the environment.
6
+ *
7
+ * This intentionally duplicates restoreSandboxEnv() in
8
+ * packages/coding-agent/src/bun/restore-sandbox-env.ts. The ai package can be
9
+ * used directly, without going through that entrypoint, so provider env lookup
10
+ * must not depend on process.env having been patched.
11
+ */
12
+ function getBunSandboxEnvValue(name) {
13
+ if (typeof process === "undefined" || !process.versions?.bun || Object.keys(process.env).length > 0) {
14
+ return undefined;
15
+ }
16
+ if (procEnvCache === null) {
17
+ procEnvCache = new Map();
18
+ try {
19
+ const { readFileSync } = require("node:fs");
20
+ const data = readFileSync("/proc/self/environ", "utf-8");
21
+ for (const entry of data.split("\0")) {
22
+ const idx = entry.indexOf("=");
23
+ if (idx > 0) {
24
+ procEnvCache.set(entry.slice(0, idx), entry.slice(idx + 1));
25
+ }
26
+ }
27
+ }
28
+ catch {
29
+ // /proc/self/environ may not exist or may not be readable.
30
+ }
31
+ }
32
+ return procEnvCache.get(name);
33
+ }
34
+ /**
35
+ * Resolve a provider env value from scoped overrides, normal process.env, then
36
+ * the duplicated Bun sandbox fallback for direct pi-ai consumers.
37
+ */
38
+ export function getProviderEnvValue(name, env) {
39
+ return (env?.[name] ||
40
+ (typeof process !== "undefined" ? process.env[name] : undefined) ||
41
+ getBunSandboxEnvValue(name) ||
42
+ undefined);
43
+ }
44
+ //# sourceMappingURL=provider-env.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider-env.js","sourceRoot":"","sources":["../../src/utils/provider-env.ts"],"names":[],"mappings":"AAEA,IAAI,YAAY,GAA+B,IAAI,CAAC;AAEpD;;;;;;;;;GASG;AACH,SAAS,qBAAqB,CAAC,IAAY,EAAsB;IAChE,IAAI,OAAO,OAAO,KAAK,WAAW,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACrG,OAAO,SAAS,CAAC;IAClB,CAAC;IAED,IAAI,YAAY,KAAK,IAAI,EAAE,CAAC;QAC3B,YAAY,GAAG,IAAI,GAAG,EAAE,CAAC;QACzB,IAAI,CAAC;YACJ,MAAM,EAAE,YAAY,EAAE,GAAG,OAAO,CAAC,SAAS,CAEzC,CAAC;YACF,MAAM,IAAI,GAAG,YAAY,CAAC,oBAAoB,EAAE,OAAO,CAAC,CAAC;YACzD,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;gBACtC,MAAM,GAAG,GAAG,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;gBAC/B,IAAI,GAAG,GAAG,CAAC,EAAE,CAAC;oBACb,YAAY,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,KAAK,CAAC,KAAK,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC;gBAC7D,CAAC;YACF,CAAC;QACF,CAAC;QAAC,MAAM,CAAC;YACR,2DAA2D;QAC5D,CAAC;IACF,CAAC;IAED,OAAO,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;AAAA,CAC9B;AAED;;;GAGG;AACH,MAAM,UAAU,mBAAmB,CAAC,IAAY,EAAE,GAAiB,EAAsB;IACxF,OAAO,CACN,GAAG,EAAE,CAAC,IAAI,CAAC;QACX,CAAC,OAAO,OAAO,KAAK,WAAW,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QAChE,qBAAqB,CAAC,IAAI,CAAC;QAC3B,SAAS,CACT,CAAC;AAAA,CACF","sourcesContent":["import type { ProviderEnv } from \"../types.ts\";\n\nlet procEnvCache: Map<string, string> | null = null;\n\n/**\n * Fallback for https://github.com/oven-sh/bun/issues/27802.\n * Bun compiled binaries can expose an empty process.env inside Linux sandboxes\n * even though /proc/self/environ contains the environment.\n *\n * This intentionally duplicates restoreSandboxEnv() in\n * packages/coding-agent/src/bun/restore-sandbox-env.ts. The ai package can be\n * used directly, without going through that entrypoint, so provider env lookup\n * must not depend on process.env having been patched.\n */\nfunction getBunSandboxEnvValue(name: string): string | undefined {\n\tif (typeof process === \"undefined\" || !process.versions?.bun || Object.keys(process.env).length > 0) {\n\t\treturn undefined;\n\t}\n\n\tif (procEnvCache === null) {\n\t\tprocEnvCache = new Map();\n\t\ttry {\n\t\t\tconst { readFileSync } = require(\"node:fs\") as {\n\t\t\t\treadFileSync(path: string, encoding: BufferEncoding): string;\n\t\t\t};\n\t\t\tconst data = readFileSync(\"/proc/self/environ\", \"utf-8\");\n\t\t\tfor (const entry of data.split(\"\\0\")) {\n\t\t\t\tconst idx = entry.indexOf(\"=\");\n\t\t\t\tif (idx > 0) {\n\t\t\t\t\tprocEnvCache.set(entry.slice(0, idx), entry.slice(idx + 1));\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\t// /proc/self/environ may not exist or may not be readable.\n\t\t}\n\t}\n\n\treturn procEnvCache.get(name);\n}\n\n/**\n * Resolve a provider env value from scoped overrides, normal process.env, then\n * the duplicated Bun sandbox fallback for direct pi-ai consumers.\n */\nexport function getProviderEnvValue(name: string, env?: ProviderEnv): string | undefined {\n\treturn (\n\t\tenv?.[name] ||\n\t\t(typeof process !== \"undefined\" ? process.env[name] : undefined) ||\n\t\tgetBunSandboxEnvValue(name) ||\n\t\tundefined\n\t);\n}\n"]}
@@ -0,0 +1,53 @@
1
+ import type { AssistantMessage } from "../types.ts";
2
+ /**
3
+ * Retry policy: bounded attempts with exponential backoff (`baseDelayMs * 2^(attempt-1)`).
4
+ * Matches `settings.retry` (`enabled`, `maxRetries`, `baseDelayMs`) in coding-agent; kept
5
+ * here so the classifier and the policy-driven retry loop live together and stay reusable
6
+ * by the SDK and other callers.
7
+ */
8
+ export interface RetryPolicy {
9
+ enabled: boolean;
10
+ /** Max retry attempts (0 = no retries). The initial call never counts as a retry. */
11
+ maxRetries: number;
12
+ /** Base delay in ms. Per-attempt delay is `baseDelayMs * 2^(attempt-1)` before jitter. */
13
+ baseDelayMs: number;
14
+ }
15
+ /** Optional callbacks emitted by {@link retryAssistantCall} around each retry. */
16
+ export interface RetryCallbacks {
17
+ /** Emitted before the backoff sleep of each retry attempt (1-indexed). */
18
+ onRetryScheduled?: (attempt: number, maxAttempts: number, delayMs: number, errorMessage: string) => void | Promise<void>;
19
+ /** Emitted after the backoff sleep, immediately before the retried call starts. */
20
+ onRetryAttemptStart?: () => void | Promise<void>;
21
+ /** Emitted once when the loop ends: success if a later call completed normally. */
22
+ onRetryFinished?: (success: boolean, attempt: number, finalError?: string) => void | Promise<void>;
23
+ }
24
+ /**
25
+ * Run a single assistant-producing call with bounded retry on transient errors.
26
+ *
27
+ * Behavior:
28
+ * - A successful response is returned immediately. Aborts are terminal and never
29
+ * retried, but reported as unsuccessful if they happen after a retry was scheduled.
30
+ * Aborts during the backoff sleep are normalized to an aborted `AssistantMessage`
31
+ * too, so callers do not need to care when cancellation happened.
32
+ * - A non-retryable error (per {@link isRetryableAssistantError}, including quota/
33
+ * billing exhaustion) is returned immediately so deterministic errors fail fast.
34
+ * - Otherwise retries up to `maxRetries` times with exponential backoff, emitting
35
+ * `onRetryScheduled` before each sleep, `onRetryAttemptStart` after each sleep before
36
+ * the retried call starts, and `onRetryFinished` once at the end (whether the loop
37
+ * ends in success, exhausted retries, or an aborted backoff).
38
+ *
39
+ * When `policy` is undefined or disabled, the first response is returned unchanged
40
+ * (equivalent to calling `produce()` directly).
41
+ */
42
+ export declare function retryAssistantCall(produce: () => Promise<AssistantMessage>, policy: RetryPolicy | undefined, signal: AbortSignal | undefined, callbacks?: RetryCallbacks): Promise<AssistantMessage>;
43
+ /**
44
+ * Classifies whether a failed assistant message looks like a transient provider
45
+ * or transport error, so callers can decide if the last assistant turn should be
46
+ * restarted.
47
+ *
48
+ * This does not implement retry policy. Callers should first handle context
49
+ * overflow separately, then apply their own retry budget, backoff, and reporting
50
+ * before restarting the assistant turn.
51
+ */
52
+ export declare function isRetryableAssistantError(message: AssistantMessage): boolean;
53
+ //# sourceMappingURL=retry.d.ts.map
@@ -0,0 +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;AAuFpD;;;;;GAKG;AACH,MAAM,WAAW,WAAW;IAC3B,OAAO,EAAE,OAAO,CAAC;IACjB,qFAAqF;IACrF,UAAU,EAAE,MAAM,CAAC;IACnB,0FAA0F;IAC1F,WAAW,EAAE,MAAM,CAAC;CACpB;AAED,kFAAkF;AAClF,MAAM,WAAW,cAAc;IAC9B,0EAA0E;IAC1E,gBAAgB,CAAC,EAAE,CAClB,OAAO,EAAE,MAAM,EACf,WAAW,EAAE,MAAM,EACnB,OAAO,EAAE,MAAM,EACf,YAAY,EAAE,MAAM,KAChB,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC1B,mFAAmF;IACnF,mBAAmB,CAAC,EAAE,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACjD,mFAAmF;IACnF,eAAe,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACnG;AA0BD;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAsB,kBAAkB,CACvC,OAAO,EAAE,MAAM,OAAO,CAAC,gBAAgB,CAAC,EACxC,MAAM,EAAE,WAAW,GAAG,SAAS,EAC/B,MAAM,EAAE,WAAW,GAAG,SAAS,EAC/B,SAAS,CAAC,EAAE,cAAc,GACxB,OAAO,CAAC,gBAAgB,CAAC,CA4C3B;AAED;;;;;;;;GAQG;AACH,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAK5E","sourcesContent":["import type { AssistantMessage } from \"../types.ts\";\n\nfunction buildProviderErrorPattern(patterns: readonly string[]): RegExp {\n\treturn new RegExp(patterns.join(\"|\"), \"i\");\n}\n\nconst NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN = buildProviderErrorPattern([\n\t// OpenCode Go/free-tier limits returned as 429 JSON error types by OpenCode's\n\t// Zen API. These are subscription/account limits, not transient throttles.\n\t\"GoUsageLimitError\",\n\t\"FreeUsageLimitError\",\n\n\t// OpenCode Go subscription-limit text asks users to enable available-balance\n\t// usage after rolling/weekly/monthly limits are reached.\n\t\"Monthly usage limit reached\",\n\t\"available balance\",\n\n\t// Generic quota/budget/billing exhaustion. `insufficient_quota` is OpenAI's\n\t// quota/billing error code; the other strings cover common gateway wording.\n\t\"insufficient_quota\",\n\t\"out of budget\",\n\t\"quota exceeded\",\n\t\"billing\",\n]);\n\nconst RETRYABLE_PROVIDER_ERROR_PATTERN = buildProviderErrorPattern([\n\t// Generic provider load, HTTP status, and server-side transient failures.\n\t\"overloaded\",\n\t\"rate.?limit\",\n\t\"too many requests\",\n\t\"429\",\n\t\"500\",\n\t\"502\",\n\t\"503\",\n\t\"504\",\n\t\"524\",\n\t\"service.?unavailable\",\n\t\"server.?error\",\n\t\"internal.?error\",\n\n\t// Wrapper/provider text for transient upstream failures, including OpenRouter\n\t// \"Provider returned error\" responses (#2264).\n\t\"provider.?returned.?error\",\n\n\t// Network, proxy, and fetch transport failures. This includes OpenAI Codex\n\t// raw-fetch failures such as \"upstream connect\", \"connection refused\", and\n\t// \"reset before headers\" (#733), plus OpenRouter connection drops (#3317).\n\t\"network.?error\",\n\t\"connection.?error\",\n\t\"connection.?refused\",\n\t\"connection.?lost\",\n\t\"other side closed\",\n\t\"fetch failed\",\n\t\"upstream.?connect\",\n\t\"reset before headers\",\n\t\"socket hang up\",\n\t\"socket connection was closed\",\n\t\"timed? out\",\n\t\"timeout\",\n\t\"terminated\",\n\n\t// WebSocket transports can report close/error text instead of HTTP/fetch text.\n\t\"websocket.?closed\",\n\t\"websocket.?error\",\n\n\t// Premature stream endings from SDKs and transports. Anthropic can throw\n\t// \"stream ended without ...\" and \"Anthropic stream ended before message_stop\"\n\t// (#4433); Bedrock/Smithy can throw an HTTP/2 no-response error (#3594).\n\t\"ended without\",\n\t\"stream ended before message_stop\",\n\t\"stream ended before a terminal response event\",\n\t\"http2 request did not get a response\",\n\n\t// Provider-requested retry delay cap failures should flow through the outer\n\t// retry policy so callers can surface/abort the backoff (#1123).\n\t\"retry delay\",\n\n\t// Explicit retry guidance emitted mid-stream by OpenAI Responses and Bedrock\n\t// stream exceptions (#6019).\n\t\"you can retry your request\",\n\t\"try your request again\",\n\t\"please retry your request\",\n\n\t// gRPC based providers (e.g. NVIDIA NIM)\n\t\"ResourceExhausted\",\n]);\n\n/**\n * Retry policy: bounded attempts with exponential backoff (`baseDelayMs * 2^(attempt-1)`).\n * Matches `settings.retry` (`enabled`, `maxRetries`, `baseDelayMs`) in coding-agent; kept\n * here so the classifier and the policy-driven retry loop live together and stay reusable\n * by the SDK and other callers.\n */\nexport interface RetryPolicy {\n\tenabled: boolean;\n\t/** Max retry attempts (0 = no retries). The initial call never counts as a retry. */\n\tmaxRetries: number;\n\t/** Base delay in ms. Per-attempt delay is `baseDelayMs * 2^(attempt-1)` before jitter. */\n\tbaseDelayMs: number;\n}\n\n/** Optional callbacks emitted by {@link retryAssistantCall} around each retry. */\nexport interface RetryCallbacks {\n\t/** Emitted before the backoff sleep of each retry attempt (1-indexed). */\n\tonRetryScheduled?: (\n\t\tattempt: number,\n\t\tmaxAttempts: number,\n\t\tdelayMs: number,\n\t\terrorMessage: string,\n\t) => void | Promise<void>;\n\t/** Emitted after the backoff sleep, immediately before the retried call starts. */\n\tonRetryAttemptStart?: () => void | Promise<void>;\n\t/** Emitted once when the loop ends: success if a later call completed normally. */\n\tonRetryFinished?: (success: boolean, attempt: number, finalError?: string) => void | Promise<void>;\n}\n\nclass RetrySleepAbortError extends Error {\n\tconstructor() {\n\t\tsuper(\"Aborted\");\n\t}\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(new RetrySleepAbortError());\n\t\t\treturn;\n\t\t}\n\t\tconst timeout = setTimeout(resolve, ms);\n\t\tsignal?.addEventListener(\n\t\t\t\"abort\",\n\t\t\t() => {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t\treject(new RetrySleepAbortError());\n\t\t\t},\n\t\t\t{ once: true },\n\t\t);\n\t});\n}\n\n/**\n * Run a single assistant-producing call with bounded retry on transient errors.\n *\n * Behavior:\n * - A successful response is returned immediately. Aborts are terminal and never\n * retried, but reported as unsuccessful if they happen after a retry was scheduled.\n * Aborts during the backoff sleep are normalized to an aborted `AssistantMessage`\n * too, so callers do not need to care when cancellation happened.\n * - A non-retryable error (per {@link isRetryableAssistantError}, including quota/\n * billing exhaustion) is returned immediately so deterministic errors fail fast.\n * - Otherwise retries up to `maxRetries` times with exponential backoff, emitting\n * `onRetryScheduled` before each sleep, `onRetryAttemptStart` after each sleep before\n * the retried call starts, and `onRetryFinished` once at the end (whether the loop\n * ends in success, exhausted retries, or an aborted backoff).\n *\n * When `policy` is undefined or disabled, the first response is returned unchanged\n * (equivalent to calling `produce()` directly).\n */\nexport async function retryAssistantCall(\n\tproduce: () => Promise<AssistantMessage>,\n\tpolicy: RetryPolicy | undefined,\n\tsignal: AbortSignal | undefined,\n\tcallbacks?: RetryCallbacks,\n): Promise<AssistantMessage> {\n\tconst maxAttempts = policy?.enabled ? policy.maxRetries : 0;\n\n\tlet attempt = 0;\n\tlet lastRetry: { attempt: number; errorMessage: string } | undefined;\n\tfor (;;) {\n\t\tconst response = await produce();\n\n\t\t// Abort: terminal but not successful. Never retry an aborted message.\n\t\tif (response.stopReason === \"aborted\") {\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(false, lastRetry.attempt);\n\t\t\treturn response;\n\t\t}\n\n\t\t// Success: non-error, non-abort responses return as-is.\n\t\tif (response.stopReason !== \"error\") {\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(true, lastRetry.attempt);\n\t\t\treturn response;\n\t\t}\n\n\t\t// Non-retryable, or budget exhausted: return the final error message.\n\t\tif (attempt >= maxAttempts || !isRetryableAssistantError(response)) {\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(false, lastRetry.attempt, response.errorMessage);\n\t\t\treturn response;\n\t\t}\n\n\t\tattempt++;\n\t\tlastRetry = { attempt, errorMessage: response.errorMessage || \"Unknown error\" };\n\t\tconst delayMs = policy!.baseDelayMs * 2 ** (attempt - 1);\n\t\tawait callbacks?.onRetryScheduled?.(attempt, maxAttempts, delayMs, lastRetry.errorMessage);\n\n\t\t// Normalize aborts during retry backoff to the same AssistantMessage shape as\n\t\t// provider stream aborts, so callers do not need to care when cancellation happened.\n\t\ttry {\n\t\t\tawait sleep(delayMs, signal);\n\t\t} catch (error) {\n\t\t\tawait callbacks?.onRetryFinished?.(false, attempt, lastRetry.errorMessage);\n\t\t\tif (error instanceof RetrySleepAbortError) {\n\t\t\t\treturn { ...response, stopReason: \"aborted\", errorMessage: undefined };\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\tawait callbacks?.onRetryAttemptStart?.();\n\t}\n}\n\n/**\n * Classifies whether a failed assistant message looks like a transient provider\n * or transport error, so callers can decide if the last assistant turn should be\n * restarted.\n *\n * This does not implement retry policy. Callers should first handle context\n * overflow separately, then apply their own retry budget, backoff, and reporting\n * before restarting the assistant turn.\n */\nexport function isRetryableAssistantError(message: AssistantMessage): boolean {\n\tif (message.stopReason !== \"error\" || !message.errorMessage) return false;\n\tconst errorMessage = message.errorMessage;\n\tif (NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN.test(errorMessage)) return false;\n\treturn RETRYABLE_PROVIDER_ERROR_PATTERN.test(errorMessage);\n}\n"]}
@@ -0,0 +1,170 @@
1
+ function buildProviderErrorPattern(patterns) {
2
+ return new RegExp(patterns.join("|"), "i");
3
+ }
4
+ const NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN = buildProviderErrorPattern([
5
+ // OpenCode Go/free-tier limits returned as 429 JSON error types by OpenCode's
6
+ // Zen API. These are subscription/account limits, not transient throttles.
7
+ "GoUsageLimitError",
8
+ "FreeUsageLimitError",
9
+ // OpenCode Go subscription-limit text asks users to enable available-balance
10
+ // usage after rolling/weekly/monthly limits are reached.
11
+ "Monthly usage limit reached",
12
+ "available balance",
13
+ // Generic quota/budget/billing exhaustion. `insufficient_quota` is OpenAI's
14
+ // quota/billing error code; the other strings cover common gateway wording.
15
+ "insufficient_quota",
16
+ "out of budget",
17
+ "quota exceeded",
18
+ "billing",
19
+ ]);
20
+ const RETRYABLE_PROVIDER_ERROR_PATTERN = buildProviderErrorPattern([
21
+ // Generic provider load, HTTP status, and server-side transient failures.
22
+ "overloaded",
23
+ "rate.?limit",
24
+ "too many requests",
25
+ "429",
26
+ "500",
27
+ "502",
28
+ "503",
29
+ "504",
30
+ "524",
31
+ "service.?unavailable",
32
+ "server.?error",
33
+ "internal.?error",
34
+ // Wrapper/provider text for transient upstream failures, including OpenRouter
35
+ // "Provider returned error" responses (#2264).
36
+ "provider.?returned.?error",
37
+ // Network, proxy, and fetch transport failures. This includes OpenAI Codex
38
+ // raw-fetch failures such as "upstream connect", "connection refused", and
39
+ // "reset before headers" (#733), plus OpenRouter connection drops (#3317).
40
+ "network.?error",
41
+ "connection.?error",
42
+ "connection.?refused",
43
+ "connection.?lost",
44
+ "other side closed",
45
+ "fetch failed",
46
+ "upstream.?connect",
47
+ "reset before headers",
48
+ "socket hang up",
49
+ "socket connection was closed",
50
+ "timed? out",
51
+ "timeout",
52
+ "terminated",
53
+ // WebSocket transports can report close/error text instead of HTTP/fetch text.
54
+ "websocket.?closed",
55
+ "websocket.?error",
56
+ // Premature stream endings from SDKs and transports. Anthropic can throw
57
+ // "stream ended without ..." and "Anthropic stream ended before message_stop"
58
+ // (#4433); Bedrock/Smithy can throw an HTTP/2 no-response error (#3594).
59
+ "ended without",
60
+ "stream ended before message_stop",
61
+ "stream ended before a terminal response event",
62
+ "http2 request did not get a response",
63
+ // Provider-requested retry delay cap failures should flow through the outer
64
+ // retry policy so callers can surface/abort the backoff (#1123).
65
+ "retry delay",
66
+ // Explicit retry guidance emitted mid-stream by OpenAI Responses and Bedrock
67
+ // stream exceptions (#6019).
68
+ "you can retry your request",
69
+ "try your request again",
70
+ "please retry your request",
71
+ // gRPC based providers (e.g. NVIDIA NIM)
72
+ "ResourceExhausted",
73
+ ]);
74
+ class RetrySleepAbortError extends Error {
75
+ constructor() {
76
+ super("Aborted");
77
+ }
78
+ }
79
+ function sleep(ms, signal) {
80
+ return new Promise((resolve, reject) => {
81
+ if (signal?.aborted) {
82
+ reject(new RetrySleepAbortError());
83
+ return;
84
+ }
85
+ const timeout = setTimeout(resolve, ms);
86
+ signal?.addEventListener("abort", () => {
87
+ clearTimeout(timeout);
88
+ reject(new RetrySleepAbortError());
89
+ }, { once: true });
90
+ });
91
+ }
92
+ /**
93
+ * Run a single assistant-producing call with bounded retry on transient errors.
94
+ *
95
+ * Behavior:
96
+ * - A successful response is returned immediately. Aborts are terminal and never
97
+ * retried, but reported as unsuccessful if they happen after a retry was scheduled.
98
+ * Aborts during the backoff sleep are normalized to an aborted `AssistantMessage`
99
+ * too, so callers do not need to care when cancellation happened.
100
+ * - A non-retryable error (per {@link isRetryableAssistantError}, including quota/
101
+ * billing exhaustion) is returned immediately so deterministic errors fail fast.
102
+ * - Otherwise retries up to `maxRetries` times with exponential backoff, emitting
103
+ * `onRetryScheduled` before each sleep, `onRetryAttemptStart` after each sleep before
104
+ * the retried call starts, and `onRetryFinished` once at the end (whether the loop
105
+ * ends in success, exhausted retries, or an aborted backoff).
106
+ *
107
+ * When `policy` is undefined or disabled, the first response is returned unchanged
108
+ * (equivalent to calling `produce()` directly).
109
+ */
110
+ export async function retryAssistantCall(produce, policy, signal, callbacks) {
111
+ const maxAttempts = policy?.enabled ? policy.maxRetries : 0;
112
+ let attempt = 0;
113
+ let lastRetry;
114
+ for (;;) {
115
+ const response = await produce();
116
+ // Abort: terminal but not successful. Never retry an aborted message.
117
+ if (response.stopReason === "aborted") {
118
+ if (lastRetry)
119
+ await callbacks?.onRetryFinished?.(false, lastRetry.attempt);
120
+ return response;
121
+ }
122
+ // Success: non-error, non-abort responses return as-is.
123
+ if (response.stopReason !== "error") {
124
+ if (lastRetry)
125
+ await callbacks?.onRetryFinished?.(true, lastRetry.attempt);
126
+ return response;
127
+ }
128
+ // Non-retryable, or budget exhausted: return the final error message.
129
+ if (attempt >= maxAttempts || !isRetryableAssistantError(response)) {
130
+ if (lastRetry)
131
+ await callbacks?.onRetryFinished?.(false, lastRetry.attempt, response.errorMessage);
132
+ return response;
133
+ }
134
+ attempt++;
135
+ lastRetry = { attempt, errorMessage: response.errorMessage || "Unknown error" };
136
+ const delayMs = policy.baseDelayMs * 2 ** (attempt - 1);
137
+ await callbacks?.onRetryScheduled?.(attempt, maxAttempts, delayMs, lastRetry.errorMessage);
138
+ // Normalize aborts during retry backoff to the same AssistantMessage shape as
139
+ // provider stream aborts, so callers do not need to care when cancellation happened.
140
+ try {
141
+ await sleep(delayMs, signal);
142
+ }
143
+ catch (error) {
144
+ await callbacks?.onRetryFinished?.(false, attempt, lastRetry.errorMessage);
145
+ if (error instanceof RetrySleepAbortError) {
146
+ return { ...response, stopReason: "aborted", errorMessage: undefined };
147
+ }
148
+ throw error;
149
+ }
150
+ await callbacks?.onRetryAttemptStart?.();
151
+ }
152
+ }
153
+ /**
154
+ * Classifies whether a failed assistant message looks like a transient provider
155
+ * or transport error, so callers can decide if the last assistant turn should be
156
+ * restarted.
157
+ *
158
+ * This does not implement retry policy. Callers should first handle context
159
+ * overflow separately, then apply their own retry budget, backoff, and reporting
160
+ * before restarting the assistant turn.
161
+ */
162
+ export function isRetryableAssistantError(message) {
163
+ if (message.stopReason !== "error" || !message.errorMessage)
164
+ return false;
165
+ const errorMessage = message.errorMessage;
166
+ if (NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN.test(errorMessage))
167
+ return false;
168
+ return RETRYABLE_PROVIDER_ERROR_PATTERN.test(errorMessage);
169
+ }
170
+ //# sourceMappingURL=retry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"retry.js","sourceRoot":"","sources":["../../src/utils/retry.ts"],"names":[],"mappings":"AAEA,SAAS,yBAAyB,CAAC,QAA2B,EAAU;IACvE,OAAO,IAAI,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC;AAAA,CAC3C;AAED,MAAM,0CAA0C,GAAG,yBAAyB,CAAC;IAC5E,8EAA8E;IAC9E,2EAA2E;IAC3E,mBAAmB;IACnB,qBAAqB;IAErB,6EAA6E;IAC7E,yDAAyD;IACzD,6BAA6B;IAC7B,mBAAmB;IAEnB,4EAA4E;IAC5E,4EAA4E;IAC5E,oBAAoB;IACpB,eAAe;IACf,gBAAgB;IAChB,SAAS;CACT,CAAC,CAAC;AAEH,MAAM,gCAAgC,GAAG,yBAAyB,CAAC;IAClE,0EAA0E;IAC1E,YAAY;IACZ,aAAa;IACb,mBAAmB;IACnB,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,sBAAsB;IACtB,eAAe;IACf,iBAAiB;IAEjB,8EAA8E;IAC9E,+CAA+C;IAC/C,2BAA2B;IAE3B,2EAA2E;IAC3E,2EAA2E;IAC3E,2EAA2E;IAC3E,gBAAgB;IAChB,mBAAmB;IACnB,qBAAqB;IACrB,kBAAkB;IAClB,mBAAmB;IACnB,cAAc;IACd,mBAAmB;IACnB,sBAAsB;IACtB,gBAAgB;IAChB,8BAA8B;IAC9B,YAAY;IACZ,SAAS;IACT,YAAY;IAEZ,+EAA+E;IAC/E,mBAAmB;IACnB,kBAAkB;IAElB,yEAAyE;IACzE,8EAA8E;IAC9E,yEAAyE;IACzE,eAAe;IACf,kCAAkC;IAClC,+CAA+C;IAC/C,sCAAsC;IAEtC,4EAA4E;IAC5E,iEAAiE;IACjE,aAAa;IAEb,6EAA6E;IAC7E,6BAA6B;IAC7B,4BAA4B;IAC5B,wBAAwB;IACxB,2BAA2B;IAE3B,yCAAyC;IACzC,mBAAmB;CACnB,CAAC,CAAC;AA+BH,MAAM,oBAAqB,SAAQ,KAAK;IACvC,cAAc;QACb,KAAK,CAAC,SAAS,CAAC,CAAC;IAAA,CACjB;CACD;AAED,SAAS,KAAK,CAAC,EAAU,EAAE,MAAoB,EAAiB;IAC/D,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE,CAAC;QACvC,IAAI,MAAM,EAAE,OAAO,EAAE,CAAC;YACrB,MAAM,CAAC,IAAI,oBAAoB,EAAE,CAAC,CAAC;YACnC,OAAO;QACR,CAAC;QACD,MAAM,OAAO,GAAG,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;QACxC,MAAM,EAAE,gBAAgB,CACvB,OAAO,EACP,GAAG,EAAE,CAAC;YACL,YAAY,CAAC,OAAO,CAAC,CAAC;YACtB,MAAM,CAAC,IAAI,oBAAoB,EAAE,CAAC,CAAC;QAAA,CACnC,EACD,EAAE,IAAI,EAAE,IAAI,EAAE,CACd,CAAC;IAAA,CACF,CAAC,CAAC;AAAA,CACH;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,CAAC,KAAK,UAAU,kBAAkB,CACvC,OAAwC,EACxC,MAA+B,EAC/B,MAA+B,EAC/B,SAA0B,EACE;IAC5B,MAAM,WAAW,GAAG,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC;IAE5D,IAAI,OAAO,GAAG,CAAC,CAAC;IAChB,IAAI,SAAgE,CAAC;IACrE,SAAS,CAAC;QACT,MAAM,QAAQ,GAAG,MAAM,OAAO,EAAE,CAAC;QAEjC,sEAAsE;QACtE,IAAI,QAAQ,CAAC,UAAU,KAAK,SAAS,EAAE,CAAC;YACvC,IAAI,SAAS;gBAAE,MAAM,SAAS,EAAE,eAAe,EAAE,CAAC,KAAK,EAAE,SAAS,CAAC,OAAO,CAAC,CAAC;YAC5E,OAAO,QAAQ,CAAC;QACjB,CAAC;QAED,wDAAwD;QACxD,IAAI,QAAQ,CAAC,UAAU,KAAK,OAAO,EAAE,CAAC;YACrC,IAAI,SAAS;gBAAE,MAAM,SAAS,EAAE,eAAe,EAAE,CAAC,IAAI,EAAE,SAAS,CAAC,OAAO,CAAC,CAAC;YAC3E,OAAO,QAAQ,CAAC;QACjB,CAAC;QAED,sEAAsE;QACtE,IAAI,OAAO,IAAI,WAAW,IAAI,CAAC,yBAAyB,CAAC,QAAQ,CAAC,EAAE,CAAC;YACpE,IAAI,SAAS;gBAAE,MAAM,SAAS,EAAE,eAAe,EAAE,CAAC,KAAK,EAAE,SAAS,CAAC,OAAO,EAAE,QAAQ,CAAC,YAAY,CAAC,CAAC;YACnG,OAAO,QAAQ,CAAC;QACjB,CAAC;QAED,OAAO,EAAE,CAAC;QACV,SAAS,GAAG,EAAE,OAAO,EAAE,YAAY,EAAE,QAAQ,CAAC,YAAY,IAAI,eAAe,EAAE,CAAC;QAChF,MAAM,OAAO,GAAG,MAAO,CAAC,WAAW,GAAG,CAAC,IAAI,CAAC,OAAO,GAAG,CAAC,CAAC,CAAC;QACzD,MAAM,SAAS,EAAE,gBAAgB,EAAE,CAAC,OAAO,EAAE,WAAW,EAAE,OAAO,EAAE,SAAS,CAAC,YAAY,CAAC,CAAC;QAE3F,8EAA8E;QAC9E,qFAAqF;QACrF,IAAI,CAAC;YACJ,MAAM,KAAK,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;QAC9B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YAChB,MAAM,SAAS,EAAE,eAAe,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,SAAS,CAAC,YAAY,CAAC,CAAC;YAC3E,IAAI,KAAK,YAAY,oBAAoB,EAAE,CAAC;gBAC3C,OAAO,EAAE,GAAG,QAAQ,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,SAAS,EAAE,CAAC;YACxE,CAAC;YACD,MAAM,KAAK,CAAC;QACb,CAAC;QACD,MAAM,SAAS,EAAE,mBAAmB,EAAE,EAAE,CAAC;IAC1C,CAAC;AAAA,CACD;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,yBAAyB,CAAC,OAAyB,EAAW;IAC7E,IAAI,OAAO,CAAC,UAAU,KAAK,OAAO,IAAI,CAAC,OAAO,CAAC,YAAY;QAAE,OAAO,KAAK,CAAC;IAC1E,MAAM,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC;IAC1C,IAAI,0CAA0C,CAAC,IAAI,CAAC,YAAY,CAAC;QAAE,OAAO,KAAK,CAAC;IAChF,OAAO,gCAAgC,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;AAAA,CAC3D","sourcesContent":["import type { AssistantMessage } from \"../types.ts\";\n\nfunction buildProviderErrorPattern(patterns: readonly string[]): RegExp {\n\treturn new RegExp(patterns.join(\"|\"), \"i\");\n}\n\nconst NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN = buildProviderErrorPattern([\n\t// OpenCode Go/free-tier limits returned as 429 JSON error types by OpenCode's\n\t// Zen API. These are subscription/account limits, not transient throttles.\n\t\"GoUsageLimitError\",\n\t\"FreeUsageLimitError\",\n\n\t// OpenCode Go subscription-limit text asks users to enable available-balance\n\t// usage after rolling/weekly/monthly limits are reached.\n\t\"Monthly usage limit reached\",\n\t\"available balance\",\n\n\t// Generic quota/budget/billing exhaustion. `insufficient_quota` is OpenAI's\n\t// quota/billing error code; the other strings cover common gateway wording.\n\t\"insufficient_quota\",\n\t\"out of budget\",\n\t\"quota exceeded\",\n\t\"billing\",\n]);\n\nconst RETRYABLE_PROVIDER_ERROR_PATTERN = buildProviderErrorPattern([\n\t// Generic provider load, HTTP status, and server-side transient failures.\n\t\"overloaded\",\n\t\"rate.?limit\",\n\t\"too many requests\",\n\t\"429\",\n\t\"500\",\n\t\"502\",\n\t\"503\",\n\t\"504\",\n\t\"524\",\n\t\"service.?unavailable\",\n\t\"server.?error\",\n\t\"internal.?error\",\n\n\t// Wrapper/provider text for transient upstream failures, including OpenRouter\n\t// \"Provider returned error\" responses (#2264).\n\t\"provider.?returned.?error\",\n\n\t// Network, proxy, and fetch transport failures. This includes OpenAI Codex\n\t// raw-fetch failures such as \"upstream connect\", \"connection refused\", and\n\t// \"reset before headers\" (#733), plus OpenRouter connection drops (#3317).\n\t\"network.?error\",\n\t\"connection.?error\",\n\t\"connection.?refused\",\n\t\"connection.?lost\",\n\t\"other side closed\",\n\t\"fetch failed\",\n\t\"upstream.?connect\",\n\t\"reset before headers\",\n\t\"socket hang up\",\n\t\"socket connection was closed\",\n\t\"timed? out\",\n\t\"timeout\",\n\t\"terminated\",\n\n\t// WebSocket transports can report close/error text instead of HTTP/fetch text.\n\t\"websocket.?closed\",\n\t\"websocket.?error\",\n\n\t// Premature stream endings from SDKs and transports. Anthropic can throw\n\t// \"stream ended without ...\" and \"Anthropic stream ended before message_stop\"\n\t// (#4433); Bedrock/Smithy can throw an HTTP/2 no-response error (#3594).\n\t\"ended without\",\n\t\"stream ended before message_stop\",\n\t\"stream ended before a terminal response event\",\n\t\"http2 request did not get a response\",\n\n\t// Provider-requested retry delay cap failures should flow through the outer\n\t// retry policy so callers can surface/abort the backoff (#1123).\n\t\"retry delay\",\n\n\t// Explicit retry guidance emitted mid-stream by OpenAI Responses and Bedrock\n\t// stream exceptions (#6019).\n\t\"you can retry your request\",\n\t\"try your request again\",\n\t\"please retry your request\",\n\n\t// gRPC based providers (e.g. NVIDIA NIM)\n\t\"ResourceExhausted\",\n]);\n\n/**\n * Retry policy: bounded attempts with exponential backoff (`baseDelayMs * 2^(attempt-1)`).\n * Matches `settings.retry` (`enabled`, `maxRetries`, `baseDelayMs`) in coding-agent; kept\n * here so the classifier and the policy-driven retry loop live together and stay reusable\n * by the SDK and other callers.\n */\nexport interface RetryPolicy {\n\tenabled: boolean;\n\t/** Max retry attempts (0 = no retries). The initial call never counts as a retry. */\n\tmaxRetries: number;\n\t/** Base delay in ms. Per-attempt delay is `baseDelayMs * 2^(attempt-1)` before jitter. */\n\tbaseDelayMs: number;\n}\n\n/** Optional callbacks emitted by {@link retryAssistantCall} around each retry. */\nexport interface RetryCallbacks {\n\t/** Emitted before the backoff sleep of each retry attempt (1-indexed). */\n\tonRetryScheduled?: (\n\t\tattempt: number,\n\t\tmaxAttempts: number,\n\t\tdelayMs: number,\n\t\terrorMessage: string,\n\t) => void | Promise<void>;\n\t/** Emitted after the backoff sleep, immediately before the retried call starts. */\n\tonRetryAttemptStart?: () => void | Promise<void>;\n\t/** Emitted once when the loop ends: success if a later call completed normally. */\n\tonRetryFinished?: (success: boolean, attempt: number, finalError?: string) => void | Promise<void>;\n}\n\nclass RetrySleepAbortError extends Error {\n\tconstructor() {\n\t\tsuper(\"Aborted\");\n\t}\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(new RetrySleepAbortError());\n\t\t\treturn;\n\t\t}\n\t\tconst timeout = setTimeout(resolve, ms);\n\t\tsignal?.addEventListener(\n\t\t\t\"abort\",\n\t\t\t() => {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t\treject(new RetrySleepAbortError());\n\t\t\t},\n\t\t\t{ once: true },\n\t\t);\n\t});\n}\n\n/**\n * Run a single assistant-producing call with bounded retry on transient errors.\n *\n * Behavior:\n * - A successful response is returned immediately. Aborts are terminal and never\n * retried, but reported as unsuccessful if they happen after a retry was scheduled.\n * Aborts during the backoff sleep are normalized to an aborted `AssistantMessage`\n * too, so callers do not need to care when cancellation happened.\n * - A non-retryable error (per {@link isRetryableAssistantError}, including quota/\n * billing exhaustion) is returned immediately so deterministic errors fail fast.\n * - Otherwise retries up to `maxRetries` times with exponential backoff, emitting\n * `onRetryScheduled` before each sleep, `onRetryAttemptStart` after each sleep before\n * the retried call starts, and `onRetryFinished` once at the end (whether the loop\n * ends in success, exhausted retries, or an aborted backoff).\n *\n * When `policy` is undefined or disabled, the first response is returned unchanged\n * (equivalent to calling `produce()` directly).\n */\nexport async function retryAssistantCall(\n\tproduce: () => Promise<AssistantMessage>,\n\tpolicy: RetryPolicy | undefined,\n\tsignal: AbortSignal | undefined,\n\tcallbacks?: RetryCallbacks,\n): Promise<AssistantMessage> {\n\tconst maxAttempts = policy?.enabled ? policy.maxRetries : 0;\n\n\tlet attempt = 0;\n\tlet lastRetry: { attempt: number; errorMessage: string } | undefined;\n\tfor (;;) {\n\t\tconst response = await produce();\n\n\t\t// Abort: terminal but not successful. Never retry an aborted message.\n\t\tif (response.stopReason === \"aborted\") {\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(false, lastRetry.attempt);\n\t\t\treturn response;\n\t\t}\n\n\t\t// Success: non-error, non-abort responses return as-is.\n\t\tif (response.stopReason !== \"error\") {\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(true, lastRetry.attempt);\n\t\t\treturn response;\n\t\t}\n\n\t\t// Non-retryable, or budget exhausted: return the final error message.\n\t\tif (attempt >= maxAttempts || !isRetryableAssistantError(response)) {\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(false, lastRetry.attempt, response.errorMessage);\n\t\t\treturn response;\n\t\t}\n\n\t\tattempt++;\n\t\tlastRetry = { attempt, errorMessage: response.errorMessage || \"Unknown error\" };\n\t\tconst delayMs = policy!.baseDelayMs * 2 ** (attempt - 1);\n\t\tawait callbacks?.onRetryScheduled?.(attempt, maxAttempts, delayMs, lastRetry.errorMessage);\n\n\t\t// Normalize aborts during retry backoff to the same AssistantMessage shape as\n\t\t// provider stream aborts, so callers do not need to care when cancellation happened.\n\t\ttry {\n\t\t\tawait sleep(delayMs, signal);\n\t\t} catch (error) {\n\t\t\tawait callbacks?.onRetryFinished?.(false, attempt, lastRetry.errorMessage);\n\t\t\tif (error instanceof RetrySleepAbortError) {\n\t\t\t\treturn { ...response, stopReason: \"aborted\", errorMessage: undefined };\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\tawait callbacks?.onRetryAttemptStart?.();\n\t}\n}\n\n/**\n * Classifies whether a failed assistant message looks like a transient provider\n * or transport error, so callers can decide if the last assistant turn should be\n * restarted.\n *\n * This does not implement retry policy. Callers should first handle context\n * overflow separately, then apply their own retry budget, backoff, and reporting\n * before restarting the assistant turn.\n */\nexport function isRetryableAssistantError(message: AssistantMessage): boolean {\n\tif (message.stopReason !== \"error\" || !message.errorMessage) return false;\n\tconst errorMessage = message.errorMessage;\n\tif (NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN.test(errorMessage)) return false;\n\treturn RETRYABLE_PROVIDER_ERROR_PATTERN.test(errorMessage);\n}\n"]}