@code-yeongyu/senpi 2026.9.21-2 → 2026.9.22

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 (239) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/dist/bundle/chunks/{anthropic-messages-C3ZY2ANT.js → anthropic-messages-2P7APOOQ.js} +1 -1
  3. package/dist/bundle/chunks/{app-server-command-HSX5RFAP.js → app-server-command-DLBXJ5K5.js} +1 -1
  4. package/dist/bundle/chunks/{azure-openai-responses-7TAGS2VU.js → azure-openai-responses-3AH7MJWF.js} +1 -1
  5. package/dist/bundle/chunks/{chunk-3SLCHXZO.js → chunk-4AXZDO3E.js} +2 -2
  6. package/dist/bundle/chunks/{chunk-Z3KQB2R3.js → chunk-7ICH7UFW.js} +12 -12
  7. package/dist/bundle/chunks/{chunk-KNM6SRPE.js → chunk-AAVNXTGQ.js} +1 -1
  8. package/dist/bundle/chunks/{chunk-IDTLJYJ5.js → chunk-AY37SZJZ.js} +4 -4
  9. package/dist/bundle/chunks/{chunk-XHMOFY4T.js → chunk-BUPX33Q4.js} +3 -3
  10. package/dist/bundle/chunks/{chunk-GLKVDRNP.js → chunk-CWCY7LXK.js} +1 -1
  11. package/dist/bundle/chunks/{chunk-POMPEGWQ.js → chunk-F3DXL5MX.js} +1 -1
  12. package/dist/bundle/chunks/{chunk-GVI2HP7N.js → chunk-I2HIIJPI.js} +1 -1
  13. package/dist/bundle/chunks/{chunk-T6XA2IZR.js → chunk-JR4X6ECO.js} +1 -1
  14. package/dist/bundle/chunks/{chunk-M2XAY6I7.js → chunk-M2HSO7MH.js} +1 -1
  15. package/dist/bundle/chunks/{chunk-MIVOQT3Q.js → chunk-N5AQJAQ2.js} +1 -1
  16. package/dist/bundle/chunks/{chunk-UYVPLEOL.js → chunk-NK2RNX25.js} +1 -1
  17. package/dist/bundle/chunks/chunk-NMB4C6ZZ.js +2 -0
  18. package/dist/bundle/chunks/{chunk-B7W62BM7.js → chunk-P4OHEJ7P.js} +1 -1
  19. package/dist/bundle/chunks/{chunk-I425CMTO.js → chunk-VBNHBSBD.js} +1 -1
  20. package/dist/bundle/chunks/{chunk-B2IM56LB.js → chunk-VYIJQQ5I.js} +1 -1
  21. package/dist/bundle/chunks/chunk-XRHUMMIW.js +8 -0
  22. package/dist/bundle/chunks/{chunk-47GF6XYZ.js → chunk-YT2ZSZOY.js} +1 -1
  23. package/dist/bundle/chunks/{chunk-OSDJ2SYO.js → chunk-ZCBX2K34.js} +1 -1
  24. package/dist/bundle/chunks/{chunk-D5CL7PPD.js → chunk-ZMVXBX33.js} +2 -2
  25. package/dist/bundle/chunks/{cli-main-GQTEEZ2V.js → cli-main-D2VPNIQ3.js} +1 -1
  26. package/dist/bundle/chunks/{google-generative-ai-JWIH75VF.js → google-generative-ai-Y2IYMUVC.js} +1 -1
  27. package/dist/bundle/chunks/{google-vertex-IRGAY5XR.js → google-vertex-TKBBMPHV.js} +1 -1
  28. package/dist/bundle/chunks/{host-command-KOEKIHIZ.js → host-command-IFIIOX5S.js} +1 -1
  29. package/dist/bundle/chunks/host-lifecycle-3OJZA4QQ.js +3 -0
  30. package/dist/bundle/chunks/host-lifecycle.js +3 -3
  31. package/dist/bundle/chunks/{interactive-host-runtime-2KTFEW7O.js → interactive-host-runtime-V7PBDIOJ.js} +1 -1
  32. package/dist/bundle/chunks/{interactive-mode-I3ILWXQB.js → interactive-mode-RFMMGQCT.js} +1 -1
  33. package/dist/bundle/chunks/kimi-coding.js +2 -2
  34. package/dist/bundle/chunks/{mistral-conversations-VOBYATVJ.js → mistral-conversations-ZYDVFRYF.js} +1 -1
  35. package/dist/bundle/chunks/{multi-session-host-S5FWCIWE.js → multi-session-host-45YMCQIH.js} +8 -7
  36. package/dist/bundle/chunks/openai-codex-responses-MEIUNROM.js +10 -0
  37. package/dist/bundle/chunks/{openai-completions-YK6QTYOH.js → openai-completions-4V76L5ZJ.js} +1 -1
  38. package/dist/bundle/chunks/openai-responses-YR7WRBG3.js +2 -0
  39. package/dist/bundle/chunks/{package-manager-cli-HOL6CAI6.js → package-manager-cli-7DQKRSI5.js} +1 -1
  40. package/dist/bundle/chunks/rotation-stream-YPZP3VJS.js +2 -0
  41. package/dist/bundle/chunks/{rpc-mode-L3DSGTVM.js → rpc-mode-4GWZCJKI.js} +1 -1
  42. package/dist/bundle/chunks/{session-picker-L3FYEQBL.js → session-picker-ZKRYWZGC.js} +1 -1
  43. package/dist/bundle/chunks/session-worker.js +38 -37
  44. package/dist/bundle/cli.js +1 -1
  45. package/dist/bundle/index.js +1 -1
  46. package/dist/bundle/rpc-entry.js +1 -1
  47. package/dist/core/agent-session.d.ts +6 -4
  48. package/dist/core/agent-session.d.ts.map +1 -1
  49. package/dist/core/agent-session.js +9 -7
  50. package/dist/core/agent-session.js.map +1 -1
  51. package/dist/core/credential-pool/classify.d.ts.map +1 -1
  52. package/dist/core/credential-pool/classify.js +12 -0
  53. package/dist/core/credential-pool/classify.js.map +1 -1
  54. package/dist/core/credential-pool/failover.d.ts +37 -5
  55. package/dist/core/credential-pool/failover.d.ts.map +1 -1
  56. package/dist/core/credential-pool/failover.js +60 -24
  57. package/dist/core/credential-pool/failover.js.map +1 -1
  58. package/dist/core/credential-pool/rotation-events.d.ts +5 -0
  59. package/dist/core/credential-pool/rotation-events.d.ts.map +1 -0
  60. package/dist/core/credential-pool/rotation-events.js +25 -0
  61. package/dist/core/credential-pool/rotation-events.js.map +1 -0
  62. package/dist/core/credential-pool/rotation-stream.d.ts +4 -3
  63. package/dist/core/credential-pool/rotation-stream.d.ts.map +1 -1
  64. package/dist/core/credential-pool/rotation-stream.js +8 -11
  65. package/dist/core/credential-pool/rotation-stream.js.map +1 -1
  66. package/dist/core/extensions/builtin/ask-user/schema.d.ts +2 -25
  67. package/dist/core/extensions/builtin/ask-user/schema.d.ts.map +1 -1
  68. package/dist/core/extensions/builtin/ask-user/schema.js.map +1 -1
  69. package/dist/core/extensions/builtin/compaction/deterministic-fallback.d.ts +2 -7
  70. package/dist/core/extensions/builtin/compaction/deterministic-fallback.d.ts.map +1 -1
  71. package/dist/core/extensions/builtin/compaction/deterministic-fallback.js +2 -8
  72. package/dist/core/extensions/builtin/compaction/deterministic-fallback.js.map +1 -1
  73. package/dist/core/extensions/builtin/mcp/expose/naming.d.ts +0 -1
  74. package/dist/core/extensions/builtin/mcp/expose/naming.d.ts.map +1 -1
  75. package/dist/core/extensions/builtin/mcp/expose/naming.js +0 -3
  76. package/dist/core/extensions/builtin/mcp/expose/naming.js.map +1 -1
  77. package/dist/core/extensions/builtin/mcp/expose/register.d.ts +1 -2
  78. package/dist/core/extensions/builtin/mcp/expose/register.d.ts.map +1 -1
  79. package/dist/core/extensions/builtin/mcp/expose/register.js +0 -21
  80. package/dist/core/extensions/builtin/mcp/expose/register.js.map +1 -1
  81. package/dist/core/extensions/builtin/mcp/expose/schema-compat.d.ts +2 -2
  82. package/dist/core/extensions/builtin/mcp/expose/schema-compat.d.ts.map +1 -1
  83. package/dist/core/extensions/builtin/mcp/expose/schema-compat.js +2 -2
  84. package/dist/core/extensions/builtin/mcp/expose/schema-compat.js.map +1 -1
  85. package/dist/core/http-dispatcher.d.ts +29 -0
  86. package/dist/core/http-dispatcher.d.ts.map +1 -1
  87. package/dist/core/http-dispatcher.js +30 -3
  88. package/dist/core/http-dispatcher.js.map +1 -1
  89. package/dist/modes/interactive/components/assistant-render-descriptors.d.ts.map +1 -1
  90. package/dist/modes/interactive/components/assistant-render-descriptors.js +8 -7
  91. package/dist/modes/interactive/components/assistant-render-descriptors.js.map +1 -1
  92. package/dist/modes/print-mode.d.ts.map +1 -1
  93. package/dist/modes/print-mode.js +7 -5
  94. package/dist/modes/print-mode.js.map +1 -1
  95. package/dist/modes/rpc/handoff-activity.d.ts +4 -0
  96. package/dist/modes/rpc/handoff-activity.d.ts.map +1 -0
  97. package/dist/modes/rpc/handoff-activity.js +6 -0
  98. package/dist/modes/rpc/handoff-activity.js.map +1 -0
  99. package/dist/modes/rpc/host-ensure.d.ts.map +1 -1
  100. package/dist/modes/rpc/host-ensure.js +60 -17
  101. package/dist/modes/rpc/host-ensure.js.map +1 -1
  102. package/dist/modes/rpc/host-lifecycle.d.ts +3 -0
  103. package/dist/modes/rpc/host-lifecycle.d.ts.map +1 -1
  104. package/dist/modes/rpc/host-lifecycle.js +25 -5
  105. package/dist/modes/rpc/host-lifecycle.js.map +1 -1
  106. package/dist/modes/rpc/multi-session-host.d.ts +1 -0
  107. package/dist/modes/rpc/multi-session-host.d.ts.map +1 -1
  108. package/dist/modes/rpc/multi-session-host.js +40 -7
  109. package/dist/modes/rpc/multi-session-host.js.map +1 -1
  110. package/dist/modes/rpc/rpc-types.d.ts +13 -0
  111. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  112. package/dist/modes/rpc/rpc-types.js.map +1 -1
  113. package/dist/modes/rpc/session-command-router.d.ts +10 -4
  114. package/dist/modes/rpc/session-command-router.d.ts.map +1 -1
  115. package/dist/modes/rpc/session-command-router.js +90 -18
  116. package/dist/modes/rpc/session-command-router.js.map +1 -1
  117. package/dist/modes/rpc/session-event-writer.d.ts +5 -3
  118. package/dist/modes/rpc/session-event-writer.d.ts.map +1 -1
  119. package/dist/modes/rpc/session-event-writer.js +21 -2
  120. package/dist/modes/rpc/session-event-writer.js.map +1 -1
  121. package/dist/modes/rpc/session-worker-client.d.ts +1 -0
  122. package/dist/modes/rpc/session-worker-client.d.ts.map +1 -1
  123. package/dist/modes/rpc/session-worker-client.js +3 -0
  124. package/dist/modes/rpc/session-worker-client.js.map +1 -1
  125. package/dist/modes/rpc/session-worker-protocol.d.ts +3 -1
  126. package/dist/modes/rpc/session-worker-protocol.d.ts.map +1 -1
  127. package/dist/modes/rpc/session-worker-protocol.js.map +1 -1
  128. package/dist/modes/rpc/session-worker.js +7 -1
  129. package/dist/modes/rpc/session-worker.js.map +1 -1
  130. package/docs/providers.md +9 -1
  131. package/docs/rpc.md +58 -8
  132. package/node_modules/@code-yeongyu/senpi-codemode/CHANGELOG.md +15 -0
  133. package/node_modules/@code-yeongyu/senpi-codemode/README.md +51 -13
  134. package/node_modules/@code-yeongyu/senpi-codemode/package.json +4 -4
  135. package/node_modules/@code-yeongyu/senpi-codemode/src/bridges/agent-bridge.ts +53 -9
  136. package/node_modules/@code-yeongyu/senpi-codemode/src/bridges/reserved-dispatch.ts +1 -0
  137. package/node_modules/@code-yeongyu/senpi-codemode/src/config/settings.ts +18 -0
  138. package/node_modules/@code-yeongyu/senpi-codemode/src/extension/eval-status.ts +9 -4
  139. package/node_modules/@code-yeongyu/senpi-codemode/src/index.ts +3 -0
  140. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/AGENTS.md +2 -2
  141. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/jl/prelude.jl +10 -0
  142. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/context-manager.ts +18 -6
  143. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/kernel-contract.ts +2 -6
  144. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/prelude.ts +1 -1
  145. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/run-queue.ts +17 -7
  146. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/worker-runtime.js +6 -1
  147. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/py/kernel-contract.ts +2 -5
  148. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/py/kernel.ts +37 -5
  149. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/py/prelude.py +11 -2
  150. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/rb/prelude.rb +6 -0
  151. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/shared/subprocess-contract.ts +2 -5
  152. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/shared/subprocess-kernel.ts +14 -4
  153. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/shared/subprocess-queue.ts +18 -5
  154. package/node_modules/@code-yeongyu/senpi-codemode/src/prompt/eval-prompt-template.ts +3 -2
  155. package/node_modules/@code-yeongyu/senpi-codemode/src/prompt/eval-prompt.ts +4 -1
  156. package/node_modules/@code-yeongyu/senpi-codemode/src/timeouts/idle-timeout.ts +9 -2
  157. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/AGENTS.md +2 -0
  158. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/cell-execution.ts +19 -2
  159. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/cell-runtime.ts +11 -3
  160. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-cell-contract.ts +6 -1
  161. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-cell-manager.ts +72 -20
  162. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-cell-snapshot.ts +28 -4
  163. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-cell-state.ts +5 -4
  164. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-cell-status.ts +5 -2
  165. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-eval-result.ts +76 -25
  166. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/eval-execution-event.ts +4 -0
  167. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/eval-kernel-reset-refused-error.ts +12 -0
  168. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/eval-request.ts +2 -1
  169. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/eval-tool-options.ts +3 -1
  170. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/eval-tool.ts +58 -37
  171. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/managed-cell.ts +15 -8
  172. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/render.ts +20 -6
  173. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/run-eval-cell.ts +89 -25
  174. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/terminal-snapshot-store.ts +4 -0
  175. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/types.ts +51 -10
  176. package/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
  177. package/node_modules/@earendil-works/pi-ai/README.md +1 -1
  178. package/node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses.js +14 -56
  179. package/node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses.js.map +1 -1
  180. package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.d.ts.map +1 -1
  181. package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.js +18 -27
  182. package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.js.map +1 -1
  183. package/node_modules/@earendil-works/pi-ai/dist/api/websocket-transport-failure.d.ts +40 -0
  184. package/node_modules/@earendil-works/pi-ai/dist/api/websocket-transport-failure.d.ts.map +1 -0
  185. package/node_modules/@earendil-works/pi-ai/dist/api/websocket-transport-failure.js +102 -0
  186. package/node_modules/@earendil-works/pi-ai/dist/api/websocket-transport-failure.js.map +1 -0
  187. package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/kimi-coding.d.ts +4 -3
  188. package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/kimi-coding.d.ts.map +1 -1
  189. package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/kimi-coding.js +28 -14
  190. package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/kimi-coding.js.map +1 -1
  191. package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/kimi-region.d.ts +44 -0
  192. package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/kimi-region.d.ts.map +1 -0
  193. package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/kimi-region.js +120 -0
  194. package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/kimi-region.js.map +1 -0
  195. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/failover.d.ts +2 -2
  196. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/failover.d.ts.map +1 -1
  197. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/failover.js +2 -2
  198. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/failover.js.map +1 -1
  199. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/slots.d.ts +3 -0
  200. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/slots.d.ts.map +1 -1
  201. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/slots.js +21 -15
  202. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/slots.js.map +1 -1
  203. package/node_modules/@earendil-works/pi-ai/dist/index.d.ts +1 -0
  204. package/node_modules/@earendil-works/pi-ai/dist/index.d.ts.map +1 -1
  205. package/node_modules/@earendil-works/pi-ai/dist/index.js +1 -0
  206. package/node_modules/@earendil-works/pi-ai/dist/index.js.map +1 -1
  207. package/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  208. package/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-ai-gateway.json +1 -1
  209. package/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-workers-ai.json +1 -1
  210. package/node_modules/@earendil-works/pi-ai/dist/providers/data/huggingface.json +1 -1
  211. package/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode-go.json +1 -1
  212. package/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  213. package/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  214. package/node_modules/@earendil-works/pi-ai/dist/providers/kimi-coding-auth.d.ts +9 -0
  215. package/node_modules/@earendil-works/pi-ai/dist/providers/kimi-coding-auth.d.ts.map +1 -0
  216. package/node_modules/@earendil-works/pi-ai/dist/providers/kimi-coding-auth.js +43 -0
  217. package/node_modules/@earendil-works/pi-ai/dist/providers/kimi-coding-auth.js.map +1 -0
  218. package/node_modules/@earendil-works/pi-ai/dist/providers/kimi-coding.d.ts.map +1 -1
  219. package/node_modules/@earendil-works/pi-ai/dist/providers/kimi-coding.js +3 -2
  220. package/node_modules/@earendil-works/pi-ai/dist/providers/kimi-coding.js.map +1 -1
  221. package/node_modules/@earendil-works/pi-ai/dist/utils/provider-failure-description.d.ts +19 -0
  222. package/node_modules/@earendil-works/pi-ai/dist/utils/provider-failure-description.d.ts.map +1 -0
  223. package/node_modules/@earendil-works/pi-ai/dist/utils/provider-failure-description.js +63 -0
  224. package/node_modules/@earendil-works/pi-ai/dist/utils/provider-failure-description.js.map +1 -0
  225. package/node_modules/@earendil-works/pi-ai/dist/utils/retry.d.ts +1 -0
  226. package/node_modules/@earendil-works/pi-ai/dist/utils/retry.d.ts.map +1 -1
  227. package/node_modules/@earendil-works/pi-ai/dist/utils/retry.js +1 -1
  228. package/node_modules/@earendil-works/pi-ai/dist/utils/retry.js.map +1 -1
  229. package/node_modules/@earendil-works/pi-ai/package.json +2 -2
  230. package/node_modules/@earendil-works/pi-pty/package.json +1 -1
  231. package/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  232. package/node_modules/@earendil-works/pi-tui/package.json +1 -1
  233. package/package.json +7 -7
  234. package/dist/bundle/chunks/chunk-5J5R5AMP.js +0 -8
  235. package/dist/bundle/chunks/chunk-I3F6VZZF.js +0 -2
  236. package/dist/bundle/chunks/host-lifecycle-DGZJTBDJ.js +0 -3
  237. package/dist/bundle/chunks/openai-codex-responses-L2PO2D6F.js +0 -10
  238. package/dist/bundle/chunks/openai-responses-YDUBVF4S.js +0 -2
  239. package/dist/bundle/chunks/rotation-stream-Y4YU6HV4.js +0 -2
@@ -0,0 +1,9 @@
1
+ import type { ApiKeyAuth } from "../auth/types.ts";
2
+ /**
3
+ * Kimi Code api-key auth: the key resolves like `envApiKeyAuth` (stored key,
4
+ * then `KIMI_API_KEY`), and the account's region rides along as credential env
5
+ * so an international key is routed to kimi.ai. No client identity headers:
6
+ * a platform key is not a subscription session (#1504).
7
+ */
8
+ export declare function kimiCodeApiKeyAuth(): ApiKeyAuth;
9
+ //# sourceMappingURL=kimi-coding-auth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"kimi-coding-auth.d.ts","sourceRoot":"","sources":["../../src/providers/kimi-coding-auth.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,UAAU,EAAe,MAAM,kBAAkB,CAAC;AAUhE;;;;;GAKG;AACH,wBAAgB,kBAAkB,IAAI,UAAU,CA4B/C"}
@@ -0,0 +1,43 @@
1
+ import { chooseKimiCodeLoginEndpoints, KIMI_CODE_OAUTH_HOST_ENV, KIMI_CODE_REGION_ENV, KIMI_OAUTH_HOST_ENV, resolveKimiCodeEndpoints, } from "../auth/oauth/kimi-region.js";
2
+ const KIMI_API_KEY_ENV = "KIMI_API_KEY";
3
+ async function envValue(ctx, name, signal) {
4
+ const value = await ctx.env(name);
5
+ signal.throwIfAborted();
6
+ return value || undefined;
7
+ }
8
+ /**
9
+ * Kimi Code api-key auth: the key resolves like `envApiKeyAuth` (stored key,
10
+ * then `KIMI_API_KEY`), and the account's region rides along as credential env
11
+ * so an international key is routed to kimi.ai. No client identity headers:
12
+ * a platform key is not a subscription session (#1504).
13
+ */
14
+ export function kimiCodeApiKeyAuth() {
15
+ return {
16
+ name: "Kimi API key",
17
+ login: async (interaction) => {
18
+ const endpoints = await chooseKimiCodeLoginEndpoints(interaction);
19
+ const key = await interaction.prompt({ type: "secret", message: "Enter Kimi API key" });
20
+ interaction.signal.throwIfAborted();
21
+ return { type: "api_key", key, ...(endpoints.env ? { env: endpoints.env } : {}) };
22
+ },
23
+ resolve: async ({ ctx, credential, signal }) => {
24
+ signal.throwIfAborted();
25
+ const key = credential?.key || (await envValue(ctx, KIMI_API_KEY_ENV, signal));
26
+ if (!key)
27
+ return undefined;
28
+ const endpoints = resolveKimiCodeEndpoints({
29
+ storedRegion: credential?.env?.[KIMI_CODE_REGION_ENV],
30
+ storedOauthHost: credential?.env?.[KIMI_CODE_OAUTH_HOST_ENV],
31
+ envOauthHost: (await envValue(ctx, KIMI_CODE_OAUTH_HOST_ENV, signal)) ??
32
+ (await envValue(ctx, KIMI_OAUTH_HOST_ENV, signal)),
33
+ envRegion: await envValue(ctx, KIMI_CODE_REGION_ENV, signal),
34
+ });
35
+ return {
36
+ auth: { apiKey: key, ...(endpoints.apiBaseUrl ? { baseUrl: endpoints.apiBaseUrl } : {}) },
37
+ ...(credential?.env ? { env: credential.env } : {}),
38
+ source: credential?.key ? "stored credential" : KIMI_API_KEY_ENV,
39
+ };
40
+ },
41
+ };
42
+ }
43
+ //# sourceMappingURL=kimi-coding-auth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"kimi-coding-auth.js","sourceRoot":"","sources":["../../src/providers/kimi-coding-auth.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,4BAA4B,EAC5B,wBAAwB,EACxB,oBAAoB,EACpB,mBAAmB,EACnB,wBAAwB,GACxB,MAAM,8BAA8B,CAAC;AAGtC,MAAM,gBAAgB,GAAG,cAAc,CAAC;AAExC,KAAK,UAAU,QAAQ,CAAC,GAAgB,EAAE,IAAY,EAAE,MAAmB;IAC1E,MAAM,KAAK,GAAG,MAAM,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IAClC,MAAM,CAAC,cAAc,EAAE,CAAC;IACxB,OAAO,KAAK,IAAI,SAAS,CAAC;AAC3B,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,kBAAkB;IACjC,OAAO;QACN,IAAI,EAAE,cAAc;QACpB,KAAK,EAAE,KAAK,EAAE,WAAW,EAAE,EAAE;YAC5B,MAAM,SAAS,GAAG,MAAM,4BAA4B,CAAC,WAAW,CAAC,CAAC;YAClE,MAAM,GAAG,GAAG,MAAM,WAAW,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,oBAAoB,EAAE,CAAC,CAAC;YACxF,WAAW,CAAC,MAAM,CAAC,cAAc,EAAE,CAAC;YACpC,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,GAAG,EAAE,GAAG,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,SAAS,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,E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ints,\n\tKIMI_CODE_OAUTH_HOST_ENV,\n\tKIMI_CODE_REGION_ENV,\n\tKIMI_OAUTH_HOST_ENV,\n\tresolveKimiCodeEndpoints,\n} from \"../auth/oauth/kimi-region.ts\";\nimport type { ApiKeyAuth, AuthContext } from \"../auth/types.ts\";\n\nconst KIMI_API_KEY_ENV = \"KIMI_API_KEY\";\n\nasync function envValue(ctx: AuthContext, name: string, signal: AbortSignal): Promise<string | undefined> {\n\tconst value = await ctx.env(name);\n\tsignal.throwIfAborted();\n\treturn value || undefined;\n}\n\n/**\n * Kimi Code api-key auth: the key resolves like `envApiKeyAuth` (stored key,\n * then `KIMI_API_KEY`), and the account's region rides along as credential env\n * so an international key is routed to kimi.ai. No client identity headers:\n * a platform key is not a subscription session (#1504).\n */\nexport function kimiCodeApiKeyAuth(): ApiKeyAuth {\n\treturn {\n\t\tname: \"Kimi API key\",\n\t\tlogin: async (interaction) => {\n\t\t\tconst endpoints = await chooseKimiCodeLoginEndpoints(interaction);\n\t\t\tconst key = await interaction.prompt({ type: \"secret\", message: \"Enter Kimi API key\" });\n\t\t\tinteraction.signal.throwIfAborted();\n\t\t\treturn { type: \"api_key\", key, ...(endpoints.env ? { env: endpoints.env } : {}) };\n\t\t},\n\t\tresolve: async ({ ctx, credential, signal }) => {\n\t\t\tsignal.throwIfAborted();\n\t\t\tconst key = credential?.key || (await envValue(ctx, KIMI_API_KEY_ENV, signal));\n\t\t\tif (!key) return undefined;\n\t\t\tconst endpoints = resolveKimiCodeEndpoints({\n\t\t\t\tstoredRegion: credential?.env?.[KIMI_CODE_REGION_ENV],\n\t\t\t\tstoredOauthHost: credential?.env?.[KIMI_CODE_OAUTH_HOST_ENV],\n\t\t\t\tenvOauthHost:\n\t\t\t\t\t(await envValue(ctx, KIMI_CODE_OAUTH_HOST_ENV, signal)) ??\n\t\t\t\t\t(await envValue(ctx, KIMI_OAUTH_HOST_ENV, signal)),\n\t\t\t\tenvRegion: await envValue(ctx, KIMI_CODE_REGION_ENV, signal),\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tauth: { apiKey: key, ...(endpoints.apiBaseUrl ? { baseUrl: endpoints.apiBaseUrl } : {}) },\n\t\t\t\t...(credential?.env ? { env: credential.env } : {}),\n\t\t\t\tsource: credential?.key ? \"stored credential\" : KIMI_API_KEY_ENV,\n\t\t\t};\n\t\t},\n\t};\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"kimi-coding.d.ts","sourceRoot":"","sources":["../../src/providers/kimi-coding.ts"],"names":[],"mappings":"AAGA,OAAO,EAAkB,KAAK,QAAQ,EAAE,MAAM,cAAc,CAAC;AAI7D,wBAAgB,kBAAkB,IAAI,QAAQ,CAAC,oBAAoB,CAAC,CAoBnE"}
1
+ {"version":3,"file":"kimi-coding.d.ts","sourceRoot":"","sources":["../../src/providers/kimi-coding.ts"],"names":[],"mappings":"AAGA,OAAO,EAAkB,KAAK,QAAQ,EAAE,MAAM,cAAc,CAAC;AAK7D,wBAAgB,kBAAkB,IAAI,QAAQ,CAAC,oBAAoB,CAAC,CAoBnE"}
@@ -1,16 +1,17 @@
1
1
  import { anthropicMessagesApi } from "../api/anthropic-messages.lazy.js";
2
- import { envApiKeyAuth, lazyOAuth } from "../auth/helpers.js";
2
+ import { lazyOAuth } from "../auth/helpers.js";
3
3
  import { loadKimiCodingOAuth } from "../auth/oauth/load.js";
4
4
  import { createProvider } from "../models.js";
5
5
  import { KIMI_CODE_RETRY_PROFILE } from "../utils/retry-profile/profiles.js";
6
6
  import { KIMI_CODING_MODELS } from "./kimi-coding.models.js";
7
+ import { kimiCodeApiKeyAuth } from "./kimi-coding-auth.js";
7
8
  export function kimiCodingProvider() {
8
9
  return createProvider({
9
10
  id: "kimi-coding",
10
11
  name: "Kimi For Coding",
11
12
  baseUrl: "https://api.kimi.com/coding",
12
13
  auth: {
13
- apiKey: envApiKeyAuth("Kimi API key", ["KIMI_API_KEY"]),
14
+ apiKey: kimiCodeApiKeyAuth(),
14
15
  oauth: lazyOAuth({
15
16
  name: "Kimi Code (subscription)",
16
17
  isSubscription: true,
@@ -1 +1 @@
1
- {"version":3,"file":"kimi-coding.js","sourceRoot":"","sources":["../../src/providers/kimi-coding.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,mCAAmC,CAAC;AACzE,OAAO,EAAE,aAAa,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC9D,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EAAE,cAAc,EAAiB,MAAM,cAAc,CAAC;AAC7D,OAAO,EAAE,uBAAuB,EAAE,MAAM,oCAAoC,CAAC;AAC7E,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAE7D,MAAM,UAAU,kBAAkB;IACjC,OAAO,cAAc,CAAC;QACrB,EAAE,EAAE,aAAa;QACjB,IAAI,EAAE,iBAAiB;QACvB,OAAO,EAAE,6BAA6B;QACtC,IAAI,EAAE;YACL,MAAM,EAAE,aAAa,CAAC,cAAc,EAAE,CAAC,cAAc,CAAC,CAAC;YACvD,KAAK,EAAE,SAAS,CAAC;gBAChB,IAAI,EAAE,0BAA0B;gBAChC,cAAc,EAAE,IAAI;gBACpB,UAAU,EAAE,wBAAwB;gBACpC,IAAI,EAAE,mBAAmB;aACzB,CAAC;SACF;QACD,MAAM,EAAE,MAAM,CAAC,MAAM,CAAC,kBAAkB,CAAC;QACzC,GAAG,EAAE,oBAAoB,EAAE;QAC3B,yEAAyE;QACzE,2DAA2D;QAC3D,WAAW,EAAE,uBAAuB;KACpC,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { anthropicMessagesApi } from \"../api/anthropic-messages.lazy.ts\";\nimport { envApiKeyAuth, lazyOAuth } from \"../auth/helpers.ts\";\nimport { loadKimiCodingOAuth } from \"../auth/oauth/load.ts\";\nimport { createProvider, type Provider } from \"../models.ts\";\nimport { KIMI_CODE_RETRY_PROFILE } from \"../utils/retry-profile/profiles.ts\";\nimport { KIMI_CODING_MODELS } from \"./kimi-coding.models.ts\";\n\nexport function kimiCodingProvider(): Provider<\"anthropic-messages\"> {\n\treturn createProvider({\n\t\tid: \"kimi-coding\",\n\t\tname: \"Kimi For Coding\",\n\t\tbaseUrl: \"https://api.kimi.com/coding\",\n\t\tauth: {\n\t\t\tapiKey: envApiKeyAuth(\"Kimi API key\", [\"KIMI_API_KEY\"]),\n\t\t\toauth: lazyOAuth({\n\t\t\t\tname: \"Kimi Code (subscription)\",\n\t\t\t\tisSubscription: true,\n\t\t\t\tloginLabel: \"Sign in with Kimi Code\",\n\t\t\t\tload: loadKimiCodingOAuth,\n\t\t\t}),\n\t\t},\n\t\tmodels: Object.values(KIMI_CODING_MODELS),\n\t\tapi: anthropicMessagesApi(),\n\t\t// Same upstream service (api.kimi.com/coding, protocol anthropic) as the\n\t\t// kimi-code CLI, so its own retry policy applies verbatim.\n\t\tretryPolicy: KIMI_CODE_RETRY_PROFILE,\n\t});\n}\n"]}
1
+ {"version":3,"file":"kimi-coding.js","sourceRoot":"","sources":["../../src/providers/kimi-coding.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,mCAAmC,CAAC;AACzE,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EAAE,cAAc,EAAiB,MAAM,cAAc,CAAC;AAC7D,OAAO,EAAE,uBAAuB,EAAE,MAAM,oCAAoC,CAAC;AAC7E,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAC7D,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAE3D,MAAM,UAAU,kBAAkB;IACjC,OAAO,cAAc,CAAC;QACrB,EAAE,EAAE,aAAa;QACjB,IAAI,EAAE,iBAAiB;QACvB,OAAO,EAAE,6BAA6B;QACtC,IAAI,EAAE;YACL,MAAM,EAAE,kBAAkB,EAAE;YAC5B,KAAK,EAAE,SAAS,CAAC;gBAChB,IAAI,EAAE,0BAA0B;gBAChC,cAAc,EAAE,IAAI;gBACpB,UAAU,EAAE,wBAAwB;gBACpC,IAAI,EAAE,mBAAmB;aACzB,CAAC;SACF;QACD,MAAM,EAAE,MAAM,CAAC,MAAM,CAAC,kBAAkB,CAAC;QACzC,GAAG,EAAE,oBAAoB,EAAE;QAC3B,yEAAyE;QACzE,2DAA2D;QAC3D,WAAW,EAAE,uBAAuB;KACpC,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { anthropicMessagesApi } from \"../api/anthropic-messages.lazy.ts\";\nimport { lazyOAuth } from \"../auth/helpers.ts\";\nimport { loadKimiCodingOAuth } from \"../auth/oauth/load.ts\";\nimport { createProvider, type Provider } from \"../models.ts\";\nimport { KIMI_CODE_RETRY_PROFILE } from \"../utils/retry-profile/profiles.ts\";\nimport { KIMI_CODING_MODELS } from \"./kimi-coding.models.ts\";\nimport { kimiCodeApiKeyAuth } from \"./kimi-coding-auth.ts\";\n\nexport function kimiCodingProvider(): Provider<\"anthropic-messages\"> {\n\treturn createProvider({\n\t\tid: \"kimi-coding\",\n\t\tname: \"Kimi For Coding\",\n\t\tbaseUrl: \"https://api.kimi.com/coding\",\n\t\tauth: {\n\t\t\tapiKey: kimiCodeApiKeyAuth(),\n\t\t\toauth: lazyOAuth({\n\t\t\t\tname: \"Kimi Code (subscription)\",\n\t\t\t\tisSubscription: true,\n\t\t\t\tloginLabel: \"Sign in with Kimi Code\",\n\t\t\t\tload: loadKimiCodingOAuth,\n\t\t\t}),\n\t\t},\n\t\tmodels: Object.values(KIMI_CODING_MODELS),\n\t\tapi: anthropicMessagesApi(),\n\t\t// Same upstream service (api.kimi.com/coding, protocol anthropic) as the\n\t\t// kimi-code CLI, so its own retry policy applies verbatim.\n\t\tretryPolicy: KIMI_CODE_RETRY_PROFILE,\n\t});\n}\n"]}
@@ -0,0 +1,19 @@
1
+ import { type ProviderStallDescriptionOptions } from "./retry.ts";
2
+ /**
3
+ * Session-internal replay-suppression signal, read off the error text by the
4
+ * retry predicates. A failover lane stamps it when replaying the turn could
5
+ * duplicate side effects that already happened mid-stream. It must stay on the
6
+ * message those predicates inspect and must never reach anything a person
7
+ * reads; byte-identical across every lane that stamps or checks it.
8
+ */
9
+ export declare const TURN_RETRY_SUPPRESSION_PREFIX = "senpi:no-turn-retry:";
10
+ export declare function stripTurnRetrySuppressionPrefix(message: string): string;
11
+ /**
12
+ * Plain-language replacement for a provider failure's own `Error.message`,
13
+ * with the internal replay marker removed. Covers the stream-stall watchdogs
14
+ * (delegated to {@link describeProviderStallForUser}) and WebSocket transport
15
+ * interruptions; returns undefined for failures that have no wording here so
16
+ * the caller can fall back to the (marker-stripped) raw text.
17
+ */
18
+ export declare function describeProviderFailureForUser(errorMessage: string | undefined, options?: ProviderStallDescriptionOptions): string | undefined;
19
+ //# sourceMappingURL=provider-failure-description.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider-failure-description.d.ts","sourceRoot":"","sources":["../../src/utils/provider-failure-description.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqD,KAAK,+BAA+B,EAAE,MAAM,YAAY,CAAC;AAErH;;;;;;GAMG;AACH,eAAO,MAAM,6BAA6B,yBAAyB,CAAC;AAEpE,wBAAgB,+BAA+B,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAEvE;AA4BD;;;;;;GAMG;AACH,wBAAgB,8BAA8B,CAC7C,YAAY,EAAE,MAAM,GAAG,SAAS,EAChC,OAAO,GAAE,+BAAoC,GAC3C,MAAM,GAAG,SAAS,CAkBpB"}
@@ -0,0 +1,63 @@
1
+ import { describeProviderStallForUser, formatStallDuration } from "./retry.js";
2
+ /**
3
+ * Session-internal replay-suppression signal, read off the error text by the
4
+ * retry predicates. A failover lane stamps it when replaying the turn could
5
+ * duplicate side effects that already happened mid-stream. It must stay on the
6
+ * message those predicates inspect and must never reach anything a person
7
+ * reads; byte-identical across every lane that stamps or checks it.
8
+ */
9
+ export const TURN_RETRY_SUPPRESSION_PREFIX = "senpi:no-turn-retry:";
10
+ export function stripTurnRetrySuppressionPrefix(message) {
11
+ return message.replaceAll(TURN_RETRY_SUPPRESSION_PREFIX, "");
12
+ }
13
+ const WEBSOCKET_CLOSED_PATTERN = /^WebSocket closed\b/i;
14
+ const WEBSOCKET_ERROR_PATTERN = /^WebSocket error$/i;
15
+ const WEBSOCKET_CONNECT_TIMEOUT_PATTERN = /^WebSocket connect timeout after (\d+)ms/i;
16
+ const RECOVERY_SENTENCE = {
17
+ "no-fallback-configured": "No fallback model is configured for it, so nothing could take the turn over: run /fallback to add one, or send the message again to continue from the partial reply.",
18
+ "chain-exhausted": "Every model in its fallback chain was tried as well: run /fallback to review the chain, or send the message again to continue from the partial reply.",
19
+ };
20
+ function transportSymptom(errorMessage, subject) {
21
+ if (WEBSOCKET_CLOSED_PATTERN.test(errorMessage)) {
22
+ return `The connection to ${subject} dropped before the reply finished (${errorMessage}).`;
23
+ }
24
+ if (WEBSOCKET_ERROR_PATTERN.test(errorMessage)) {
25
+ return `The connection to ${subject} reported an error before the reply finished (${errorMessage}).`;
26
+ }
27
+ const connectTimeout = WEBSOCKET_CONNECT_TIMEOUT_PATTERN.exec(errorMessage);
28
+ if (connectTimeout) {
29
+ const provider = subject.replace(/^the provider/, "The provider");
30
+ return `${provider} did not accept the connection within ${formatStallDuration(Number(connectTimeout[1]))}.`;
31
+ }
32
+ return undefined;
33
+ }
34
+ /**
35
+ * Plain-language replacement for a provider failure's own `Error.message`,
36
+ * with the internal replay marker removed. Covers the stream-stall watchdogs
37
+ * (delegated to {@link describeProviderStallForUser}) and WebSocket transport
38
+ * interruptions; returns undefined for failures that have no wording here so
39
+ * the caller can fall back to the (marker-stripped) raw text.
40
+ */
41
+ export function describeProviderFailureForUser(errorMessage, options = {}) {
42
+ if (!errorMessage)
43
+ return undefined;
44
+ const message = stripTurnRetrySuppressionPrefix(errorMessage).trim();
45
+ if (!message)
46
+ return undefined;
47
+ const stall = describeProviderStallForUser(message, options);
48
+ if (stall !== undefined)
49
+ return stall;
50
+ const subject = options.model ? `the provider for ${options.model}` : "the provider";
51
+ const symptom = transportSymptom(message, subject);
52
+ if (symptom === undefined)
53
+ return undefined;
54
+ const sentences = [symptom];
55
+ const attempts = options.attempts ?? 0;
56
+ if (attempts > 0) {
57
+ sentences.push(`Retried ${attempts} time${attempts === 1 ? "" : "s"} on the same model with the same result.`);
58
+ }
59
+ if (options.recovery)
60
+ sentences.push(RECOVERY_SENTENCE[options.recovery]);
61
+ return sentences.join(" ");
62
+ }
63
+ //# sourceMappingURL=provider-failure-description.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider-failure-description.js","sourceRoot":"","sources":["../../src/utils/provider-failure-description.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,4BAA4B,EAAE,mBAAmB,EAAwC,MAAM,YAAY,CAAC;AAErH;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,6BAA6B,GAAG,sBAAsB,CAAC;AAEpE,MAAM,UAAU,+BAA+B,CAAC,OAAe;IAC9D,OAAO,OAAO,CAAC,UAAU,CAAC,6BAA6B,EAAE,EAAE,CAAC,CAAC;AAC9D,CAAC;AAED,MAAM,wBAAwB,GAAG,sBAAsB,CAAC;AACxD,MAAM,uBAAuB,GAAG,oBAAoB,CAAC;AACrD,MAAM,iCAAiC,GAAG,2CAA2C,CAAC;AAEtF,MAAM,iBAAiB,GAA6E;IACnG,wBAAwB,EACvB,sKAAsK;IACvK,iBAAiB,EAChB,uJAAuJ;CACxJ,CAAC;AAEF,SAAS,gBAAgB,CAAC,YAAoB,EAAE,OAAe;IAC9D,IAAI,wBAAwB,CAAC,IAAI,CAAC,YAAY,CAAC,EAAE,CAAC;QACjD,OAAO,qBAAqB,OAAO,uCAAuC,YAAY,IAAI,CAAC;IAC5F,CAAC;IACD,IAAI,uBAAuB,CAAC,IAAI,CAAC,YAAY,CAAC,EAAE,CAAC;QAChD,OAAO,qBAAqB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CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,0CAA0C,CAAC,CAAC;IAChH,CAAC;IACD,IAAI,OAAO,CAAC,QAAQ;QAAE,SAAS,CAAC,IAAI,CAAC,iBAAiB,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC;IAC1E,OAAO,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAC5B,CAAC","sourcesContent":["import { describeProviderStallForUser, formatStallDuration, type ProviderStallDescriptionOptions } from \"./retry.ts\";\n\n/**\n * Session-internal replay-suppression signal, read off the error text by the\n * retry predicates. A failover lane stamps it when replaying the turn could\n * duplicate side effects that already happened mid-stream. It must stay on the\n * message those predicates inspect and must never reach anything a person\n * reads; byte-identical across every lane that stamps or checks it.\n */\nexport const TURN_RETRY_SUPPRESSION_PREFIX = \"senpi:no-turn-retry:\";\n\nexport function stripTurnRetrySuppressionPrefix(message: string): string {\n\treturn message.replaceAll(TURN_RETRY_SUPPRESSION_PREFIX, \"\");\n}\n\nconst WEBSOCKET_CLOSED_PATTERN = /^WebSocket closed\\b/i;\nconst WEBSOCKET_ERROR_PATTERN = /^WebSocket error$/i;\nconst WEBSOCKET_CONNECT_TIMEOUT_PATTERN = /^WebSocket connect timeout after (\\d+)ms/i;\n\nconst RECOVERY_SENTENCE: Record<NonNullable<ProviderStallDescriptionOptions[\"recovery\"]>, string> = {\n\t\"no-fallback-configured\":\n\t\t\"No fallback model is configured for it, so nothing could take the turn over: run /fallback to add one, or send the message again to continue from the partial reply.\",\n\t\"chain-exhausted\":\n\t\t\"Every model in its fallback chain was tried as well: run /fallback to review the chain, or send the message again to continue from the partial reply.\",\n};\n\nfunction transportSymptom(errorMessage: string, subject: string): string | undefined {\n\tif (WEBSOCKET_CLOSED_PATTERN.test(errorMessage)) {\n\t\treturn `The connection to ${subject} dropped before the reply finished (${errorMessage}).`;\n\t}\n\tif (WEBSOCKET_ERROR_PATTERN.test(errorMessage)) {\n\t\treturn `The connection to ${subject} reported an error before the reply finished (${errorMessage}).`;\n\t}\n\tconst connectTimeout = WEBSOCKET_CONNECT_TIMEOUT_PATTERN.exec(errorMessage);\n\tif (connectTimeout) {\n\t\tconst provider = subject.replace(/^the provider/, \"The provider\");\n\t\treturn `${provider} did not accept the connection within ${formatStallDuration(Number(connectTimeout[1]))}.`;\n\t}\n\treturn undefined;\n}\n\n/**\n * Plain-language replacement for a provider failure's own `Error.message`,\n * with the internal replay marker removed. Covers the stream-stall watchdogs\n * (delegated to {@link describeProviderStallForUser}) and WebSocket transport\n * interruptions; returns undefined for failures that have no wording here so\n * the caller can fall back to the (marker-stripped) raw text.\n */\nexport function describeProviderFailureForUser(\n\terrorMessage: string | undefined,\n\toptions: ProviderStallDescriptionOptions = {},\n): string | undefined {\n\tif (!errorMessage) return undefined;\n\tconst message = stripTurnRetrySuppressionPrefix(errorMessage).trim();\n\tif (!message) return undefined;\n\tconst stall = describeProviderStallForUser(message, options);\n\tif (stall !== undefined) return stall;\n\n\tconst subject = options.model ? `the provider for ${options.model}` : \"the provider\";\n\tconst symptom = transportSymptom(message, subject);\n\tif (symptom === undefined) return undefined;\n\n\tconst sentences = [symptom];\n\tconst attempts = options.attempts ?? 0;\n\tif (attempts > 0) {\n\t\tsentences.push(`Retried ${attempts} time${attempts === 1 ? \"\" : \"s\"} on the same model with the same result.`);\n\t}\n\tif (options.recovery) sentences.push(RECOVERY_SENTENCE[options.recovery]);\n\treturn sentences.join(\" \");\n}\n"]}
@@ -101,6 +101,7 @@ export interface ProviderStallDescriptionOptions {
101
101
  */
102
102
  recovery?: "no-fallback-configured" | "chain-exhausted";
103
103
  }
104
+ export declare function formatStallDuration(timeoutMs: number): string;
104
105
  /**
105
106
  * Plain-language replacement for a stall watchdog's own `Error.message`.
106
107
  *
@@ -1 +1 @@
1
- {"version":3,"file":"retry.d.ts","sourceRoot":"","sources":["../../src/utils/retry.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,aAA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O,CAAC,CAAC,CAAC,CAiCZ;AAOD;;;;;;;;;;;;;;;;;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,CA6C3B;AAED;;;;;;;;GAQG;AACH,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAU5E;AAgBD,wBAAgB,0BAA0B,CAAC,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAE7E;AA8BD,MAAM,WAAW,+BAA+B;IAC/C,sDAAsD;IACtD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,iFAAiF;IACjF,KAAK,CAAC,EAAE,MAAM,CAAC;IACf;;;OAGG;IACH,QAAQ,CAAC,EAAE,wBAAwB,GAAG,iBAAiB,CAAC;CACxD;AAED,wBAAgB,mBAAmB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAI7D;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,4BAA4B,CAC3C,YAAY,EAAE,MAAM,GAAG,SAAS,EAChC,OAAO,GAAE,+BAAoC,GAC3C,MAAM,GAAG,SAAS,CAuBpB;AAED;;;;GAIG;AACH,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAKzE;AAED;;;;;GAKG;AACH,wBAAgB,uBAAuB,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAErE;AAED;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CAAC,YAAY,EAAE,MAAM,GAAG,eAAe,GAAG,WAAW,GAAG,SAAS,CAKpG"}
@@ -344,7 +344,7 @@ const PROVIDER_STALL_PHASES = [
344
344
  symptom: "finished its output but never sent the end-of-response event",
345
345
  },
346
346
  ];
347
- function formatStallDuration(timeoutMs) {
347
+ export function formatStallDuration(timeoutMs) {
348
348
  if (timeoutMs < 1000)
349
349
  return `${timeoutMs}ms`;
350
350
  if (timeoutMs < 120_000)
@@ -1 +1 @@
1
- {"version":3,"file":"retry.js","sourceRoot":"","sources":["../../src/utils/retry.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,8BAA8B,EAAE,8BAA8B,EAAE,MAAM,4BAA4B,CAAC;AAE5G,SAAS,yBAAyB,CAAC,QAA2B;IAC7D,OAAO,IAAI,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC;AAC5C,CAAC;AAED,SAAS,YAAY,CAAC,IAAY;IACjC,OAAO,IAAI,CAAC,OAAO,CAAC,qBAAqB,EAAE,MAAM,CAAC,CAAC;AACpD,CAAC;AAED,MAAM,oCAAoC,GAAG,yBAAyB,CAAC;IACtE,8EAA8E;IAC9E,2EAA2E;IAC3E,mBAAmB;IACnB,qBAAqB;IAErB,6EAA6E;IAC7E,yDAAyD;IACzD,6BAA6B;IAC7B,mBAAmB;IAEnB,4EAA4E;IAC5E,4EAA4E;IAC5E,oBAAoB;IACpB,eAAe;IACf,gBAAgB;IAChB,SAAS;IAET,4EAA4E;IAC5E,0EAA0E;IAC1E,0EAA0E;IAC1E,2DAA2D;IAC3D,kBAAkB;IAClB,sBAAsB;IAEtB,+EAA+E;IAC/E,4EAA4E;IAC5E,6EAA6E;IAC7E,4EAA4E;IAC5E,8EAA8E;IAC9E,+EAA+E;IAC/E,gFAAgF;IAChF,4DAA4D;IAC5D,2BAA2B;IAC3B,+BAA+B;IAC/B,oCAAoC;IACpC,sCAAsC;IACtC,qBAAqB;CACrB,CAAC,CAAC;AAEH,MAAM,gCAAgC,GAAG,yBAAyB,CAAC;IAClE,8EAA8E;IAC9E,oEAAoE;IACpE,gCAAgC;IAChC,0EAA0E;IAC1E,YAAY;IACZ,aAAa;IACb,mBAAmB;IACnB,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK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AC,CAAC,uGAAuG;gBACzG,CAAC,CAAC,wFAAwF,CAAC;YAC7F,SAAS,CAAC,IAAI,CAAC,GAAG,IAAI,2BAA2B,KAAK,GAAG,CAAC,CAAC;QAC5D,CAAC;QACD,OAAO,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAC5B,CAAC;IACD,OAAO,SAAS,CAAC;AAClB,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,sBAAsB,CAAC,OAAyB;IAC/D,IAAI,OAAO,CAAC,WAAW,KAAK,UAAU;QAAE,OAAO,IAAI,CAAC;IACpD,IAAI,0BAA0B,CAAC,OAAO,CAAC;QAAE,OAAO,IAAI,CAAC;IACrD,IAAI,OAAO,CAAC,UAAU,KAAK,OAAO,IAAI,OAAO,CAAC,UAAU,KAAK,SAAS;QAAE,OAAO,KAAK,CAAC;IACrF,OAAO,wCAAwC,CAAC,IAAI,CAAC,OAAO,CAAC,YAAY,IAAI,EAAE,CAAC,CAAC;AAClF,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,uBAAuB,CAAC,YAAoB;IAC3D,OAAO,oBAAoB,CAAC,YAAY,CAAC,KAAK,WAAW,CAAC;AAC3D,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,oBAAoB,CAAC,YAAoB;IACxD,IAAI,CAAC,YAAY;QAAE,OAAO,SAAS,CAAC;IACpC,IAAI,oCAAoC,CAAC,IAAI,CAAC,YAAY,CAAC;QAAE,OAAO,eAAe,CAAC;IACpF,IAAI,gCAAgC,CAAC,IAAI,CAAC,YAAY,CAAC;QAAE,OAAO,WAAW,CAAC;IAC5E,OAAO,SAAS,CAAC;AAClB,CAAC","sourcesContent":["import type { AssistantMessage } from \"../types.ts\";\nimport { FORWARDED_EMPTY_RESPONSE_ERROR, FORWARDED_EMPTY_TOOL_USE_ERROR } from \"./empty-response-errors.ts\";\n\nfunction buildProviderErrorPattern(patterns: readonly string[]): RegExp {\n\treturn new RegExp(patterns.join(\"|\"), \"i\");\n}\n\nfunction escapeRegExp(text: string): string {\n\treturn text.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nconst NON_RETRYABLE_PROVIDER_ERROR_PATTERN = buildProviderErrorPattern([\n\t// OpenCode Go/free-tier limits returned as 429 JSON error types by OpenCode's\n\t// Zen API. These are subscription/account limits, not transient throttles.\n\t\"GoUsageLimitError\",\n\t\"FreeUsageLimitError\",\n\n\t// OpenCode Go subscription-limit text asks users to enable available-balance\n\t// usage after rolling/weekly/monthly limits are reached.\n\t\"Monthly usage limit reached\",\n\t\"available balance\",\n\n\t// Generic quota/budget/billing exhaustion. `insufficient_quota` is OpenAI's\n\t// quota/billing error code; the other strings cover common gateway wording.\n\t\"insufficient_quota\",\n\t\"out of budget\",\n\t\"quota exceeded\",\n\t\"billing\",\n\n\t// Anthropic Console credit exhaustion: a 429 rate_limit_error whose details\n\t// carry error_code credits_required (\"Usage credits are required for this\n\t// model.\"). The account is dead until the user buys credits or raises the\n\t// spend limit, so same-model retries can never recover it.\n\t\"credits_required\",\n\t\"credits are required\",\n\n\t// Request-shape rejections: the provider refused the payload we built, not the\n\t// work it describes. Gateways wrap these in whatever status they like — the\n\t// observed Apitopia/Kimi case arrives as `500 server_error: Invalid request:\n\t// tools.function.parameters.type is required and must be \"object\"` — so the\n\t// status text alone would classify a permanent failure as transient. The same\n\t// bytes are rejected on every attempt and on every fallback model, so retrying\n\t// can only burn the turn. Anchored on the `tools[...]`/`functions[...]` request\n\t// path so unrelated prose mentioning tools stays retryable.\n\t\"invalid request: tools\\\\.\",\n\t\"invalid request: functions\\\\.\",\n\t\"tools\\\\.[^ ]*function\\\\.parameters\",\n\t\"tools\\\\.\\\\d+\\\\.function\\\\.parameters\",\n\t\"invalid tool schema\",\n]);\n\nconst RETRYABLE_PROVIDER_ERROR_PATTERN = buildProviderErrorPattern([\n\t// Local credential/auth sidecar lock exhaustion is infrastructure contention,\n\t// not a provider failure and must stay on the transient retry path.\n\t\"Credential store is busy: lock\",\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// Cloudflare 522 (Connection timed out): origin stopped responding; transient\n\t// like the other 5xx gateway statuses, surfaced as \"Error: error code: 522\".\n\t\"522\",\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\t\"exceeded request buffer limit while retrying upstream\",\n\n\t// Network, proxy, and fetch transport failures. This includes OpenAI Codex\n\t// raw-fetch failures such as \"upstream connect\", \"connection refused\", and\n\t// \"reset before headers\" (#733), plus OpenRouter connection drops (#3317).\n\t\"network.?error\",\n\t\"connection.?error\",\n\t\"connection.?refused\",\n\t\"connection.?lost\",\n\t\"other side closed\",\n\t\"fetch failed\",\n\t\"getaddrinfo\",\n\t\"ENOTFOUND\",\n\t\"EAI_AGAIN\",\n\t\"upstream.?connect\",\n\t\"upstream.?unavailable\",\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// Gateway/proxy-side rejection of the whole model request, e.g. \"Error: The\n\t// model request was rejected. Check the request and try again.\" (observed in a\n\t// live session, 2026-08-11). Coupling the rejection sentence to its explicit\n\t// retry instruction keeps unrelated permission, request-shape, and content-\n\t// policy rejections terminal while the bounded retry policy absorbs this\n\t// transient wrapper wording.\n\t\"the model request was rejected\\\\.\\\\s*check the request and try again\\\\.?\",\n\n\t// Anthropic server-tool pairing rejections, e.g. \"`web_search` tool use with id\n\t// `srvtoolu_...` was found without a corresponding `web_search_tool_result`\n\t// block\". A turn closed before its deferred server tool could answer leaves\n\t// the unpairable half in history, and replaying it 400s every later request.\n\t// The Anthropic request builder repairs the replayed history, so a retry sends\n\t// a valid payload; keeping the class retryable is what lets retry and the model\n\t// fallback chain unwedge such a session instead of dead-ending it. The trailing\n\t// backtick keeps the pattern on Anthropic's pairing-error template.\n\t\"was found without a corresponding `\",\n\n\t// An empty stop or tool_use-without-tool-call on a model whose reasoning had already streamed\n\t// live. The stream-level wrapper (pi-agent-core empty-assistant-recovery) cannot replay such an\n\t// attempt, so it ends the turn with these exact texts for the turn retry to re-request; the\n\t// \"twice\" variants are deliberately absent because the wrapper already spent its own retry.\n\tescapeRegExp(FORWARDED_EMPTY_RESPONSE_ERROR),\n\tescapeRegExp(FORWARDED_EMPTY_TOOL_USE_ERROR),\n\n\t// gRPC based providers (e.g. NVIDIA NIM)\n\t\"ResourceExhausted\",\n\n\t// Claude Agent SDK session.json lock contention. A second stream/resume\n\t// hits proper-lockfile while the previous subprocess still holds the file.\n\t// Same-process retry recovers; hopping providers cannot release that lock.\n\t\"Lock file is already being held\",\n]);\n\n/**\n * Retry policy: bounded attempts with exponential backoff (`baseDelayMs * 2^(attempt-1)`).\n * `maxAgentDelayMs` caps each computed delay and defaults to 60 seconds.\n * Matches `settings.retry` (`enabled`, `maxRetries`, `baseDelayMs`, `maxAgentDelayMs`) in coding-agent; kept\n * here so the classifier and the policy-driven retry loop live together and stay reusable\n * by the SDK and other callers.\n */\nexport interface RetryPolicy {\n\tenabled: boolean;\n\t/** Max retry attempts (0 = no retries). The initial call never counts as a retry. */\n\tmaxRetries: number;\n\t/** Base delay in ms. Per-attempt delay is `baseDelayMs * 2^(attempt-1)` before jitter. */\n\tbaseDelayMs: number;\n\t/** Optional cap for agent-level retry delays in ms. Defaults to 60 seconds. */\n\tmaxAgentDelayMs?: number;\n\t/** Injectable source used for Codex-style +/-10% backoff jitter. */\n\trandom?: () => number;\n}\n\nexport const DEFAULT_MAX_AGENT_RETRY_DELAY_MS = 60_000;\n\n/**\n * Per-attempt backoff: `baseDelayMs * 2^(attempt-1)`, jittered by +/-10% through the\n * injectable `random` source, then clamped to `maxAgentDelayMs` (60s by default). The\n * jitter runs before the clamp so a capped delay stays exactly at the cap instead of\n * scattering above it, and the safe-integer guard keeps a large `attempt` from producing\n * `Infinity` before the clamp.\n */\nexport function retryDelayMs(\n\tpolicy: Pick<RetryPolicy, \"baseDelayMs\" | \"maxAgentDelayMs\" | \"random\">,\n\tattempt: number,\n): number {\n\tconst scheduledDelayMs = policy.baseDelayMs * 2 ** Math.max(0, attempt - 1);\n\tconst sample = Math.min(1, Math.max(0, (policy.random ?? Math.random)()));\n\tconst jitteredDelayMs = Math.round(scheduledDelayMs * (0.9 + sample * 0.2));\n\tconst safeDelay = Number.isSafeInteger(jitteredDelayMs) ? jitteredDelayMs : Number.MAX_SAFE_INTEGER;\n\treturn Math.min(safeDelay, policy.maxAgentDelayMs ?? DEFAULT_MAX_AGENT_RETRY_DELAY_MS);\n}\n\n/** Optional callbacks emitted by {@link retryAssistantCall} around each retry. */\nexport interface RetryCallbacks {\n\t/** Emitted before the backoff sleep of each retry attempt (1-indexed). */\n\tonRetryScheduled?: (\n\t\tattempt: number,\n\t\tmaxAttempts: number,\n\t\tdelayMs: number,\n\t\terrorMessage: string,\n\t) => void | Promise<void>;\n\t/** Emitted after the backoff sleep, immediately before the retried call starts. */\n\tonRetryAttemptStart?: () => void | Promise<void>;\n\t/** Emitted once when the loop ends: success if a later call completed normally. */\n\tonRetryFinished?: (success: boolean, attempt: number, finalError?: string) => void | Promise<void>;\n}\n\nclass RetrySleepAbortError extends Error {\n\tconstructor() {\n\t\tsuper(\"Aborted\");\n\t}\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(new RetrySleepAbortError());\n\t\t\treturn;\n\t\t}\n\t\tconst timeout = setTimeout(resolve, ms);\n\t\tsignal?.addEventListener(\n\t\t\t\"abort\",\n\t\t\t() => {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t\treject(new RetrySleepAbortError());\n\t\t\t},\n\t\t\t{ once: true },\n\t\t);\n\t});\n}\n\n/**\n * Run a producer that signals failure by THROWING, with the same bounded\n * backoff, abort, and callback semantics as {@link retryAssistantCall}.\n *\n * `retryAssistantCall` is value-based: its producer reports failure by resolving\n * an `AssistantMessage` with `stopReason: \"error\"`. Callers that instead reject\n * (compaction summarization, and any other request pipeline that throws) need\n * the identical retry policy without reshaping their failures into assistant\n * messages first, so both live here and share one implementation of the delay,\n * abort, and callback contract.\n *\n * Behavior:\n * - A resolved value is returned immediately.\n * - A throw that `isRetryable` rejects is rethrown at once: deterministic\n * failures never spend a retry.\n * - Otherwise the call is retried up to `policy.maxRetries` times with the same\n * exponential backoff (`baseDelayMs * 2^(attempt-1)`), rethrowing the final\n * error when the budget is exhausted.\n * - An abort during the backoff sleep stops the loop and rethrows; unlike the\n * assistant-message path there is no aborted value to normalize to.\n *\n * When `policy` is undefined or disabled the producer runs exactly once and its\n * error propagates unchanged.\n */\nexport async function retryTransientCall<T>(\n\tproduce: () => Promise<T>,\n\tisRetryable: (error: unknown) => boolean,\n\tpolicy: RetryPolicy | undefined,\n\tsignal: AbortSignal | undefined,\n\tcallbacks?: RetryCallbacks,\n): Promise<T> {\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\ttry {\n\t\t\tconst value = await produce();\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(true, lastRetry.attempt);\n\t\t\treturn value;\n\t\t} catch (error) {\n\t\t\tif (error instanceof RetrySleepAbortError) throw error;\n\t\t\tif (attempt >= maxAttempts || !isRetryable(error)) {\n\t\t\t\tif (lastRetry) {\n\t\t\t\t\tawait callbacks?.onRetryFinished?.(false, lastRetry.attempt, errorMessageOf(error));\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tattempt++;\n\t\t\tlastRetry = { attempt, errorMessage: errorMessageOf(error) };\n\t\t\tconst delayMs = retryDelayMs(policy!, attempt);\n\t\t\tawait callbacks?.onRetryScheduled?.(attempt, maxAttempts, delayMs, lastRetry.errorMessage);\n\n\t\t\ttry {\n\t\t\t\tawait sleep(delayMs, signal);\n\t\t\t} catch (sleepError) {\n\t\t\t\tawait callbacks?.onRetryFinished?.(false, attempt, lastRetry.errorMessage);\n\t\t\t\tthrow sleepError instanceof RetrySleepAbortError ? error : sleepError;\n\t\t\t}\n\t\t\tawait callbacks?.onRetryAttemptStart?.();\n\t\t}\n\t}\n}\n\nfunction errorMessageOf(error: unknown): string {\n\tif (error instanceof Error) return error.message || \"Unknown error\";\n\treturn String(error) || \"Unknown error\";\n}\n\n/**\n * Run a single assistant-producing call with bounded retry on transient errors.\n *\n * Behavior:\n * - A successful response is returned immediately. Aborts are terminal and never\n * retried, but reported as unsuccessful if they happen after a retry was scheduled.\n * Aborts during the backoff sleep are normalized to an aborted `AssistantMessage`\n * too, so callers do not need to care when cancellation happened.\n * - A non-retryable error (per {@link isRetryableAssistantError}, including quota/\n * billing exhaustion) is returned immediately so deterministic errors fail fast.\n * - Otherwise retries up to `maxRetries` times with exponential backoff, emitting\n * `onRetryScheduled` before each sleep, `onRetryAttemptStart` after each sleep before\n * the retried call starts, and `onRetryFinished` once at the end (whether the loop\n * ends in success, exhausted retries, or an aborted backoff).\n *\n * When `policy` is undefined or disabled, the first response is returned unchanged\n * (equivalent to calling `produce()` directly).\n */\nexport async function retryAssistantCall(\n\tproduce: () => Promise<AssistantMessage>,\n\tpolicy: RetryPolicy | undefined,\n\tsignal: AbortSignal | undefined,\n\tcallbacks?: RetryCallbacks,\n): Promise<AssistantMessage> {\n\tconst maxAttempts = policy?.enabled ? policy.maxRetries : 0;\n\n\tlet attempt = 0;\n\tlet lastRetry: { attempt: number; errorMessage: string } | undefined;\n\tfor (;;) {\n\t\tconst response = await produce();\n\n\t\t// Abort: terminal but not successful. Never retry an aborted message.\n\t\tif (response.stopReason === \"aborted\") {\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(false, lastRetry.attempt);\n\t\t\treturn response;\n\t\t}\n\n\t\t// Success: non-error, non-abort responses return as-is.\n\t\tif (response.stopReason !== \"error\") {\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(true, lastRetry.attempt);\n\t\t\treturn response;\n\t\t}\n\n\t\t// Non-retryable, or budget exhausted: return the final error message.\n\t\tif (attempt >= maxAttempts || !isRetryableAssistantError(response)) {\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(false, lastRetry.attempt, response.errorMessage);\n\t\t\treturn response;\n\t\t}\n\n\t\tattempt++;\n\t\tlastRetry = { attempt, errorMessage: response.errorMessage || \"Unknown error\" };\n\t\tconst delayMs = retryDelayMs(policy!, attempt);\n\t\tawait callbacks?.onRetryScheduled?.(attempt, maxAttempts, delayMs, lastRetry.errorMessage);\n\n\t\t// Normalize aborts during retry backoff to the same AssistantMessage shape as\n\t\t// provider stream aborts, so callers do not need to care when cancellation happened.\n\t\ttry {\n\t\t\tawait sleep(delayMs, signal);\n\t\t} catch (error) {\n\t\t\tawait callbacks?.onRetryFinished?.(false, attempt, lastRetry.errorMessage);\n\t\t\tif (error instanceof RetrySleepAbortError) {\n\t\t\t\tconst { errorMessage: _errorMessage, ...rest } = response;\n\t\t\t\treturn { ...rest, stopReason: \"aborted\" };\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\tawait callbacks?.onRetryAttemptStart?.();\n\t}\n}\n\n/**\n * Classifies whether a failed assistant message looks like a transient provider\n * or transport error, so callers can decide if the last assistant turn should be\n * restarted.\n *\n * This does not implement retry policy. Callers should first handle context\n * overflow separately, then apply their own retry budget, backoff, and reporting\n * before restarting the assistant turn.\n */\nexport function isRetryableAssistantError(message: AssistantMessage): boolean {\n\tif (\n\t\tmessage.stopReason !== \"error\" ||\n\t\tmessage.stopDetails?.type === \"refusal\" ||\n\t\tmessage.stopDetails?.type === \"sensitive\" ||\n\t\t!message.errorMessage\n\t) {\n\t\treturn false;\n\t}\n\treturn isRetryableErrorMessage(message.errorMessage);\n}\n\n/**\n * Matches the agent-loop stream watchdog failures (\"Idle timeout waiting for\n * provider stream after <n>ms\" and \"Provider stream start timed out after\n * <n>ms\"), the WebSocket liveness verdict (\"WebSocket liveness timeout after\n * <n>ms (<k> pings unanswered)\"), and the Responses completion-phase verdict\n * (\"Provider stream stalled after the last output item: response.completed\n * timed out after <n>ms\"). These anchored shapes\n * distinguish provider-stream stalls from unrelated extension, command, or MCP\n * timeout diagnostics.\n */\nconst PROVIDER_STREAM_STALL_ERROR_PATTERN =\n\t/^(?:Idle timeout waiting for provider stream after \\d+ms|Provider stream start timed out after \\d+ms(?: \\([^)]*\\))?|WebSocket liveness timeout after \\d+ms \\(\\d+ pings unanswered\\)|Provider stream stalled after the last output item: response\\.completed timed out after \\d+ms)$/i;\nconst PROVIDER_TRANSPORT_TIMEOUT_ERROR_PATTERN = /^Request timed out\\.?$/i;\n\nexport function isProviderStreamStallError(message: AssistantMessage): boolean {\n\treturn message.stopReason === \"error\" && PROVIDER_STREAM_STALL_ERROR_PATTERN.test(message.errorMessage ?? \"\");\n}\n\n/** One row per stall watchdog: how to read its message, and how to explain it. */\nconst PROVIDER_STALL_PHASES: ReadonlyArray<{\n\tpattern: RegExp;\n\t/** What the provider failed to do, in the user's words. */\n\tsymptom: string;\n\t/** The setting that widens this bound, when one exists. */\n\tsetting?: string;\n}> = [\n\t{\n\t\tpattern: /^Provider stream start timed out after (\\d+)ms/i,\n\t\tsymptom: \"accepted the request but never started sending a response\",\n\t\tsetting: \"retry.provider.streamStartTimeoutMs\",\n\t},\n\t{\n\t\tpattern: /^Idle timeout waiting for provider stream after (\\d+)ms/i,\n\t\tsymptom: \"started the response and then went silent\",\n\t\tsetting: \"retry.provider.timeoutMs\",\n\t},\n\t{\n\t\tpattern: /^WebSocket liveness timeout after (\\d+)ms/i,\n\t\tsymptom: \"stopped answering connection health checks\",\n\t},\n\t{\n\t\tpattern: /^Provider stream stalled after the last output item: response\\.completed timed out after (\\d+)ms/i,\n\t\tsymptom: \"finished its output but never sent the end-of-response event\",\n\t},\n];\n\nexport interface ProviderStallDescriptionOptions {\n\t/** Same-model attempts already spent on this turn. */\n\tattempts?: number;\n\t/** Selector of the model that stalled, for example `anthropic/claude-opus-5`. */\n\tmodel?: string;\n\t/**\n\t * Appends the \"what to do next\" sentence. Omit it while the turn can still\n\t * recover: a retry in flight is not the moment to tell the user to act.\n\t */\n\trecovery?: \"no-fallback-configured\" | \"chain-exhausted\";\n}\n\nfunction formatStallDuration(timeoutMs: number): string {\n\tif (timeoutMs < 1000) return `${timeoutMs}ms`;\n\tif (timeoutMs < 120_000) return `${Math.round(timeoutMs / 100) / 10}s`;\n\treturn `${Math.round(timeoutMs / 6000) / 10}m`;\n}\n\n/**\n * Plain-language replacement for a stall watchdog's own `Error.message`.\n *\n * The watchdog wording (`Provider stream start timed out after 180000ms ...`)\n * is a classifier token - {@link isProviderStreamStallError} and the turn retry\n * gate both match on it - so it must stay on the assistant message. It was also\n * the only thing the user ever saw when a turn died on a stall, which explains\n * nothing and names no next step (senpi#1740). Every user-facing surface routes\n * the message through here first and falls back to the raw text for anything\n * that is not a stall.\n */\nexport function describeProviderStallForUser(\n\terrorMessage: string | undefined,\n\toptions: ProviderStallDescriptionOptions = {},\n): string | undefined {\n\tif (!errorMessage) return undefined;\n\tfor (const { pattern, symptom, setting } of PROVIDER_STALL_PHASES) {\n\t\tconst match = pattern.exec(errorMessage);\n\t\tif (!match) continue;\n\t\tconst subject = options.model ? `The provider for ${options.model}` : \"The provider\";\n\t\tconst duration = formatStallDuration(Number(match[1]));\n\t\tconst sentences = [`${subject} ${symptom} within ${duration}, so the request was cancelled.`];\n\t\tconst attempts = options.attempts ?? 0;\n\t\tif (attempts > 0) {\n\t\t\tsentences.push(`Retried ${attempts} time${attempts === 1 ? \"\" : \"s\"} on the same model with the same result.`);\n\t\t}\n\t\tif (options.recovery) {\n\t\t\tconst raise = setting ? `, or raise ${setting} in settings (0 disables the bound)` : \"\";\n\t\t\tconst lead =\n\t\t\t\toptions.recovery === \"no-fallback-configured\"\n\t\t\t\t\t? \"No fallback model is configured for it, so nothing could take the turn over: run /fallback to add one\"\n\t\t\t\t\t: \"Every model in its fallback chain was tried as well: run /fallback to review the chain\";\n\t\t\tsentences.push(`${lead}, send the message again${raise}.`);\n\t\t}\n\t\treturn sentences.join(\" \");\n\t}\n\treturn undefined;\n}\n\n/**\n * Classifies timeout failures that originate from the provider stream or its\n * transport. Transport timeouts may arrive as `aborted`; stream watchdog\n * failures are ordinary error responses.\n */\nexport function isProviderTimeoutError(message: AssistantMessage): boolean {\n\tif (message.abortSource === \"provider\") return true;\n\tif (isProviderStreamStallError(message)) return true;\n\tif (message.stopReason !== \"error\" && message.stopReason !== \"aborted\") return false;\n\treturn PROVIDER_TRANSPORT_TIMEOUT_ERROR_PATTERN.test(message.errorMessage ?? \"\");\n}\n\n/**\n * Classifies a raw error-message string with the same transient-vs-terminal\n * rules as {@link isRetryableAssistantError}, for callers that hold a thrown\n * `Error` instead of an `AssistantMessage` (e.g. compaction summarization\n * failures that must decide between degrading and surfacing loudly).\n */\nexport function isRetryableErrorMessage(errorMessage: string): boolean {\n\treturn classifyErrorMessage(errorMessage) === \"retryable\";\n}\n\n/**\n * Tri-state form of {@link isRetryableErrorMessage}. The regexes only carry\n * three outcomes — a non-retryable match, a retryable match, or no match at\n * all — and callers that hold structured failure facts (status codes, provider\n * error codes) need to distinguish \"the regexes say terminal\" from \"the\n * regexes say nothing\" so they can consult the structured facts only in the\n * latter case. Non-retryable still outranks retryable, exactly as before.\n */\nexport function classifyErrorMessage(errorMessage: string): \"non-retryable\" | \"retryable\" | \"unknown\" {\n\tif (!errorMessage) return \"unknown\";\n\tif (NON_RETRYABLE_PROVIDER_ERROR_PATTERN.test(errorMessage)) return \"non-retryable\";\n\tif (RETRYABLE_PROVIDER_ERROR_PATTERN.test(errorMessage)) return \"retryable\";\n\treturn \"unknown\";\n}\n"]}
1
+ {"version":3,"file":"retry.js","sourceRoot":"","sources":["../../src/utils/retry.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,8BAA8B,EAAE,8BAA8B,EAAE,MAAM,4BAA4B,CAAC;AAE5G,SAAS,yBAAyB,CAAC,QAA2B;IAC7D,OAAO,IAAI,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC;AAC5C,CAAC;AAED,SAAS,YAAY,CAAC,IAAY;IACjC,OAAO,IAAI,CAAC,OAAO,CAAC,qBAAqB,EAAE,MAAM,CAAC,CAAC;AACpD,CAAC;AAED,MAAM,oCAAoC,GAAG,yBAAyB,CAAC;IACtE,8EAA8E;IAC9E,2EAA2E;IAC3E,mBAAmB;IACnB,qBAAqB;IAErB,6EAA6E;IAC7E,yDAAyD;IACzD,6BAA6B;IAC7B,mBAAmB;IAEnB,4EAA4E;IAC5E,4EAA4E;IAC5E,oBAAoB;IACpB,eAAe;IACf,gBAAgB;IAChB,SAAS;IAET,4EAA4E;IAC5E,0EAA0E;IAC1E,0EAA0E;IAC1E,2DAA2D;IAC3D,kBAAkB;IAClB,sBAAsB;IAEtB,+EAA+E;IAC/E,4EAA4E;IAC5E,6EAA6E;IAC7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I,CAAC,YAAY,CAAC;QAAE,OAAO,eAAe,CAAC;IACpF,IAAI,gCAAgC,CAAC,IAAI,CAAC,YAAY,CAAC;QAAE,OAAO,WAAW,CAAC;IAC5E,OAAO,SAAS,CAAC;AAClB,CAAC","sourcesContent":["import type { AssistantMessage } from \"../types.ts\";\nimport { FORWARDED_EMPTY_RESPONSE_ERROR, FORWARDED_EMPTY_TOOL_USE_ERROR } from \"./empty-response-errors.ts\";\n\nfunction buildProviderErrorPattern(patterns: readonly string[]): RegExp {\n\treturn new RegExp(patterns.join(\"|\"), \"i\");\n}\n\nfunction escapeRegExp(text: string): string {\n\treturn text.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nconst NON_RETRYABLE_PROVIDER_ERROR_PATTERN = buildProviderErrorPattern([\n\t// OpenCode Go/free-tier limits returned as 429 JSON error types by OpenCode's\n\t// Zen API. These are subscription/account limits, not transient throttles.\n\t\"GoUsageLimitError\",\n\t\"FreeUsageLimitError\",\n\n\t// OpenCode Go subscription-limit text asks users to enable available-balance\n\t// usage after rolling/weekly/monthly limits are reached.\n\t\"Monthly usage limit reached\",\n\t\"available balance\",\n\n\t// Generic quota/budget/billing exhaustion. `insufficient_quota` is OpenAI's\n\t// quota/billing error code; the other strings cover common gateway wording.\n\t\"insufficient_quota\",\n\t\"out of budget\",\n\t\"quota exceeded\",\n\t\"billing\",\n\n\t// Anthropic Console credit exhaustion: a 429 rate_limit_error whose details\n\t// carry error_code credits_required (\"Usage credits are required for this\n\t// model.\"). The account is dead until the user buys credits or raises the\n\t// spend limit, so same-model retries can never recover it.\n\t\"credits_required\",\n\t\"credits are required\",\n\n\t// Request-shape rejections: the provider refused the payload we built, not the\n\t// work it describes. Gateways wrap these in whatever status they like — the\n\t// observed Apitopia/Kimi case arrives as `500 server_error: Invalid request:\n\t// tools.function.parameters.type is required and must be \"object\"` — so the\n\t// status text alone would classify a permanent failure as transient. The same\n\t// bytes are rejected on every attempt and on every fallback model, so retrying\n\t// can only burn the turn. Anchored on the `tools[...]`/`functions[...]` request\n\t// path so unrelated prose mentioning tools stays retryable.\n\t\"invalid request: tools\\\\.\",\n\t\"invalid request: functions\\\\.\",\n\t\"tools\\\\.[^ ]*function\\\\.parameters\",\n\t\"tools\\\\.\\\\d+\\\\.function\\\\.parameters\",\n\t\"invalid tool schema\",\n]);\n\nconst RETRYABLE_PROVIDER_ERROR_PATTERN = buildProviderErrorPattern([\n\t// Local credential/auth sidecar lock exhaustion is infrastructure contention,\n\t// not a provider failure and must stay on the transient retry path.\n\t\"Credential store is busy: lock\",\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// Cloudflare 522 (Connection timed out): origin stopped responding; transient\n\t// like the other 5xx gateway statuses, surfaced as \"Error: error code: 522\".\n\t\"522\",\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\t\"exceeded request buffer limit while retrying upstream\",\n\n\t// Network, proxy, and fetch transport failures. This includes OpenAI Codex\n\t// raw-fetch failures such as \"upstream connect\", \"connection refused\", and\n\t// \"reset before headers\" (#733), plus OpenRouter connection drops (#3317).\n\t\"network.?error\",\n\t\"connection.?error\",\n\t\"connection.?refused\",\n\t\"connection.?lost\",\n\t\"other side closed\",\n\t\"fetch failed\",\n\t\"getaddrinfo\",\n\t\"ENOTFOUND\",\n\t\"EAI_AGAIN\",\n\t\"upstream.?connect\",\n\t\"upstream.?unavailable\",\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// Gateway/proxy-side rejection of the whole model request, e.g. \"Error: The\n\t// model request was rejected. Check the request and try again.\" (observed in a\n\t// live session, 2026-08-11). Coupling the rejection sentence to its explicit\n\t// retry instruction keeps unrelated permission, request-shape, and content-\n\t// policy rejections terminal while the bounded retry policy absorbs this\n\t// transient wrapper wording.\n\t\"the model request was rejected\\\\.\\\\s*check the request and try again\\\\.?\",\n\n\t// Anthropic server-tool pairing rejections, e.g. \"`web_search` tool use with id\n\t// `srvtoolu_...` was found without a corresponding `web_search_tool_result`\n\t// block\". A turn closed before its deferred server tool could answer leaves\n\t// the unpairable half in history, and replaying it 400s every later request.\n\t// The Anthropic request builder repairs the replayed history, so a retry sends\n\t// a valid payload; keeping the class retryable is what lets retry and the model\n\t// fallback chain unwedge such a session instead of dead-ending it. The trailing\n\t// backtick keeps the pattern on Anthropic's pairing-error template.\n\t\"was found without a corresponding `\",\n\n\t// An empty stop or tool_use-without-tool-call on a model whose reasoning had already streamed\n\t// live. The stream-level wrapper (pi-agent-core empty-assistant-recovery) cannot replay such an\n\t// attempt, so it ends the turn with these exact texts for the turn retry to re-request; the\n\t// \"twice\" variants are deliberately absent because the wrapper already spent its own retry.\n\tescapeRegExp(FORWARDED_EMPTY_RESPONSE_ERROR),\n\tescapeRegExp(FORWARDED_EMPTY_TOOL_USE_ERROR),\n\n\t// gRPC based providers (e.g. NVIDIA NIM)\n\t\"ResourceExhausted\",\n\n\t// Claude Agent SDK session.json lock contention. A second stream/resume\n\t// hits proper-lockfile while the previous subprocess still holds the file.\n\t// Same-process retry recovers; hopping providers cannot release that lock.\n\t\"Lock file is already being held\",\n]);\n\n/**\n * Retry policy: bounded attempts with exponential backoff (`baseDelayMs * 2^(attempt-1)`).\n * `maxAgentDelayMs` caps each computed delay and defaults to 60 seconds.\n * Matches `settings.retry` (`enabled`, `maxRetries`, `baseDelayMs`, `maxAgentDelayMs`) in coding-agent; kept\n * here so the classifier and the policy-driven retry loop live together and stay reusable\n * by the SDK and other callers.\n */\nexport interface RetryPolicy {\n\tenabled: boolean;\n\t/** Max retry attempts (0 = no retries). The initial call never counts as a retry. */\n\tmaxRetries: number;\n\t/** Base delay in ms. Per-attempt delay is `baseDelayMs * 2^(attempt-1)` before jitter. */\n\tbaseDelayMs: number;\n\t/** Optional cap for agent-level retry delays in ms. Defaults to 60 seconds. */\n\tmaxAgentDelayMs?: number;\n\t/** Injectable source used for Codex-style +/-10% backoff jitter. */\n\trandom?: () => number;\n}\n\nexport const DEFAULT_MAX_AGENT_RETRY_DELAY_MS = 60_000;\n\n/**\n * Per-attempt backoff: `baseDelayMs * 2^(attempt-1)`, jittered by +/-10% through the\n * injectable `random` source, then clamped to `maxAgentDelayMs` (60s by default). The\n * jitter runs before the clamp so a capped delay stays exactly at the cap instead of\n * scattering above it, and the safe-integer guard keeps a large `attempt` from producing\n * `Infinity` before the clamp.\n */\nexport function retryDelayMs(\n\tpolicy: Pick<RetryPolicy, \"baseDelayMs\" | \"maxAgentDelayMs\" | \"random\">,\n\tattempt: number,\n): number {\n\tconst scheduledDelayMs = policy.baseDelayMs * 2 ** Math.max(0, attempt - 1);\n\tconst sample = Math.min(1, Math.max(0, (policy.random ?? Math.random)()));\n\tconst jitteredDelayMs = Math.round(scheduledDelayMs * (0.9 + sample * 0.2));\n\tconst safeDelay = Number.isSafeInteger(jitteredDelayMs) ? jitteredDelayMs : Number.MAX_SAFE_INTEGER;\n\treturn Math.min(safeDelay, policy.maxAgentDelayMs ?? DEFAULT_MAX_AGENT_RETRY_DELAY_MS);\n}\n\n/** Optional callbacks emitted by {@link retryAssistantCall} around each retry. */\nexport interface RetryCallbacks {\n\t/** Emitted before the backoff sleep of each retry attempt (1-indexed). */\n\tonRetryScheduled?: (\n\t\tattempt: number,\n\t\tmaxAttempts: number,\n\t\tdelayMs: number,\n\t\terrorMessage: string,\n\t) => void | Promise<void>;\n\t/** Emitted after the backoff sleep, immediately before the retried call starts. */\n\tonRetryAttemptStart?: () => void | Promise<void>;\n\t/** Emitted once when the loop ends: success if a later call completed normally. */\n\tonRetryFinished?: (success: boolean, attempt: number, finalError?: string) => void | Promise<void>;\n}\n\nclass RetrySleepAbortError extends Error {\n\tconstructor() {\n\t\tsuper(\"Aborted\");\n\t}\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(new RetrySleepAbortError());\n\t\t\treturn;\n\t\t}\n\t\tconst timeout = setTimeout(resolve, ms);\n\t\tsignal?.addEventListener(\n\t\t\t\"abort\",\n\t\t\t() => {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t\treject(new RetrySleepAbortError());\n\t\t\t},\n\t\t\t{ once: true },\n\t\t);\n\t});\n}\n\n/**\n * Run a producer that signals failure by THROWING, with the same bounded\n * backoff, abort, and callback semantics as {@link retryAssistantCall}.\n *\n * `retryAssistantCall` is value-based: its producer reports failure by resolving\n * an `AssistantMessage` with `stopReason: \"error\"`. Callers that instead reject\n * (compaction summarization, and any other request pipeline that throws) need\n * the identical retry policy without reshaping their failures into assistant\n * messages first, so both live here and share one implementation of the delay,\n * abort, and callback contract.\n *\n * Behavior:\n * - A resolved value is returned immediately.\n * - A throw that `isRetryable` rejects is rethrown at once: deterministic\n * failures never spend a retry.\n * - Otherwise the call is retried up to `policy.maxRetries` times with the same\n * exponential backoff (`baseDelayMs * 2^(attempt-1)`), rethrowing the final\n * error when the budget is exhausted.\n * - An abort during the backoff sleep stops the loop and rethrows; unlike the\n * assistant-message path there is no aborted value to normalize to.\n *\n * When `policy` is undefined or disabled the producer runs exactly once and its\n * error propagates unchanged.\n */\nexport async function retryTransientCall<T>(\n\tproduce: () => Promise<T>,\n\tisRetryable: (error: unknown) => boolean,\n\tpolicy: RetryPolicy | undefined,\n\tsignal: AbortSignal | undefined,\n\tcallbacks?: RetryCallbacks,\n): Promise<T> {\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\ttry {\n\t\t\tconst value = await produce();\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(true, lastRetry.attempt);\n\t\t\treturn value;\n\t\t} catch (error) {\n\t\t\tif (error instanceof RetrySleepAbortError) throw error;\n\t\t\tif (attempt >= maxAttempts || !isRetryable(error)) {\n\t\t\t\tif (lastRetry) {\n\t\t\t\t\tawait callbacks?.onRetryFinished?.(false, lastRetry.attempt, errorMessageOf(error));\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tattempt++;\n\t\t\tlastRetry = { attempt, errorMessage: errorMessageOf(error) };\n\t\t\tconst delayMs = retryDelayMs(policy!, attempt);\n\t\t\tawait callbacks?.onRetryScheduled?.(attempt, maxAttempts, delayMs, lastRetry.errorMessage);\n\n\t\t\ttry {\n\t\t\t\tawait sleep(delayMs, signal);\n\t\t\t} catch (sleepError) {\n\t\t\t\tawait callbacks?.onRetryFinished?.(false, attempt, lastRetry.errorMessage);\n\t\t\t\tthrow sleepError instanceof RetrySleepAbortError ? error : sleepError;\n\t\t\t}\n\t\t\tawait callbacks?.onRetryAttemptStart?.();\n\t\t}\n\t}\n}\n\nfunction errorMessageOf(error: unknown): string {\n\tif (error instanceof Error) return error.message || \"Unknown error\";\n\treturn String(error) || \"Unknown error\";\n}\n\n/**\n * Run a single assistant-producing call with bounded retry on transient errors.\n *\n * Behavior:\n * - A successful response is returned immediately. Aborts are terminal and never\n * retried, but reported as unsuccessful if they happen after a retry was scheduled.\n * Aborts during the backoff sleep are normalized to an aborted `AssistantMessage`\n * too, so callers do not need to care when cancellation happened.\n * - A non-retryable error (per {@link isRetryableAssistantError}, including quota/\n * billing exhaustion) is returned immediately so deterministic errors fail fast.\n * - Otherwise retries up to `maxRetries` times with exponential backoff, emitting\n * `onRetryScheduled` before each sleep, `onRetryAttemptStart` after each sleep before\n * the retried call starts, and `onRetryFinished` once at the end (whether the loop\n * ends in success, exhausted retries, or an aborted backoff).\n *\n * When `policy` is undefined or disabled, the first response is returned unchanged\n * (equivalent to calling `produce()` directly).\n */\nexport async function retryAssistantCall(\n\tproduce: () => Promise<AssistantMessage>,\n\tpolicy: RetryPolicy | undefined,\n\tsignal: AbortSignal | undefined,\n\tcallbacks?: RetryCallbacks,\n): Promise<AssistantMessage> {\n\tconst maxAttempts = policy?.enabled ? policy.maxRetries : 0;\n\n\tlet attempt = 0;\n\tlet lastRetry: { attempt: number; errorMessage: string } | undefined;\n\tfor (;;) {\n\t\tconst response = await produce();\n\n\t\t// Abort: terminal but not successful. Never retry an aborted message.\n\t\tif (response.stopReason === \"aborted\") {\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(false, lastRetry.attempt);\n\t\t\treturn response;\n\t\t}\n\n\t\t// Success: non-error, non-abort responses return as-is.\n\t\tif (response.stopReason !== \"error\") {\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(true, lastRetry.attempt);\n\t\t\treturn response;\n\t\t}\n\n\t\t// Non-retryable, or budget exhausted: return the final error message.\n\t\tif (attempt >= maxAttempts || !isRetryableAssistantError(response)) {\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(false, lastRetry.attempt, response.errorMessage);\n\t\t\treturn response;\n\t\t}\n\n\t\tattempt++;\n\t\tlastRetry = { attempt, errorMessage: response.errorMessage || \"Unknown error\" };\n\t\tconst delayMs = retryDelayMs(policy!, attempt);\n\t\tawait callbacks?.onRetryScheduled?.(attempt, maxAttempts, delayMs, lastRetry.errorMessage);\n\n\t\t// Normalize aborts during retry backoff to the same AssistantMessage shape as\n\t\t// provider stream aborts, so callers do not need to care when cancellation happened.\n\t\ttry {\n\t\t\tawait sleep(delayMs, signal);\n\t\t} catch (error) {\n\t\t\tawait callbacks?.onRetryFinished?.(false, attempt, lastRetry.errorMessage);\n\t\t\tif (error instanceof RetrySleepAbortError) {\n\t\t\t\tconst { errorMessage: _errorMessage, ...rest } = response;\n\t\t\t\treturn { ...rest, stopReason: \"aborted\" };\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\tawait callbacks?.onRetryAttemptStart?.();\n\t}\n}\n\n/**\n * Classifies whether a failed assistant message looks like a transient provider\n * or transport error, so callers can decide if the last assistant turn should be\n * restarted.\n *\n * This does not implement retry policy. Callers should first handle context\n * overflow separately, then apply their own retry budget, backoff, and reporting\n * before restarting the assistant turn.\n */\nexport function isRetryableAssistantError(message: AssistantMessage): boolean {\n\tif (\n\t\tmessage.stopReason !== \"error\" ||\n\t\tmessage.stopDetails?.type === \"refusal\" ||\n\t\tmessage.stopDetails?.type === \"sensitive\" ||\n\t\t!message.errorMessage\n\t) {\n\t\treturn false;\n\t}\n\treturn isRetryableErrorMessage(message.errorMessage);\n}\n\n/**\n * Matches the agent-loop stream watchdog failures (\"Idle timeout waiting for\n * provider stream after <n>ms\" and \"Provider stream start timed out after\n * <n>ms\"), the WebSocket liveness verdict (\"WebSocket liveness timeout after\n * <n>ms (<k> pings unanswered)\"), and the Responses completion-phase verdict\n * (\"Provider stream stalled after the last output item: response.completed\n * timed out after <n>ms\"). These anchored shapes\n * distinguish provider-stream stalls from unrelated extension, command, or MCP\n * timeout diagnostics.\n */\nconst PROVIDER_STREAM_STALL_ERROR_PATTERN =\n\t/^(?:Idle timeout waiting for provider stream after \\d+ms|Provider stream start timed out after \\d+ms(?: \\([^)]*\\))?|WebSocket liveness timeout after \\d+ms \\(\\d+ pings unanswered\\)|Provider stream stalled after the last output item: response\\.completed timed out after \\d+ms)$/i;\nconst PROVIDER_TRANSPORT_TIMEOUT_ERROR_PATTERN = /^Request timed out\\.?$/i;\n\nexport function isProviderStreamStallError(message: AssistantMessage): boolean {\n\treturn message.stopReason === \"error\" && PROVIDER_STREAM_STALL_ERROR_PATTERN.test(message.errorMessage ?? \"\");\n}\n\n/** One row per stall watchdog: how to read its message, and how to explain it. */\nconst PROVIDER_STALL_PHASES: ReadonlyArray<{\n\tpattern: RegExp;\n\t/** What the provider failed to do, in the user's words. */\n\tsymptom: string;\n\t/** The setting that widens this bound, when one exists. */\n\tsetting?: string;\n}> = [\n\t{\n\t\tpattern: /^Provider stream start timed out after (\\d+)ms/i,\n\t\tsymptom: \"accepted the request but never started sending a response\",\n\t\tsetting: \"retry.provider.streamStartTimeoutMs\",\n\t},\n\t{\n\t\tpattern: /^Idle timeout waiting for provider stream after (\\d+)ms/i,\n\t\tsymptom: \"started the response and then went silent\",\n\t\tsetting: \"retry.provider.timeoutMs\",\n\t},\n\t{\n\t\tpattern: /^WebSocket liveness timeout after (\\d+)ms/i,\n\t\tsymptom: \"stopped answering connection health checks\",\n\t},\n\t{\n\t\tpattern: /^Provider stream stalled after the last output item: response\\.completed timed out after (\\d+)ms/i,\n\t\tsymptom: \"finished its output but never sent the end-of-response event\",\n\t},\n];\n\nexport interface ProviderStallDescriptionOptions {\n\t/** Same-model attempts already spent on this turn. */\n\tattempts?: number;\n\t/** Selector of the model that stalled, for example `anthropic/claude-opus-5`. */\n\tmodel?: string;\n\t/**\n\t * Appends the \"what to do next\" sentence. Omit it while the turn can still\n\t * recover: a retry in flight is not the moment to tell the user to act.\n\t */\n\trecovery?: \"no-fallback-configured\" | \"chain-exhausted\";\n}\n\nexport function formatStallDuration(timeoutMs: number): string {\n\tif (timeoutMs < 1000) return `${timeoutMs}ms`;\n\tif (timeoutMs < 120_000) return `${Math.round(timeoutMs / 100) / 10}s`;\n\treturn `${Math.round(timeoutMs / 6000) / 10}m`;\n}\n\n/**\n * Plain-language replacement for a stall watchdog's own `Error.message`.\n *\n * The watchdog wording (`Provider stream start timed out after 180000ms ...`)\n * is a classifier token - {@link isProviderStreamStallError} and the turn retry\n * gate both match on it - so it must stay on the assistant message. It was also\n * the only thing the user ever saw when a turn died on a stall, which explains\n * nothing and names no next step (senpi#1740). Every user-facing surface routes\n * the message through here first and falls back to the raw text for anything\n * that is not a stall.\n */\nexport function describeProviderStallForUser(\n\terrorMessage: string | undefined,\n\toptions: ProviderStallDescriptionOptions = {},\n): string | undefined {\n\tif (!errorMessage) return undefined;\n\tfor (const { pattern, symptom, setting } of PROVIDER_STALL_PHASES) {\n\t\tconst match = pattern.exec(errorMessage);\n\t\tif (!match) continue;\n\t\tconst subject = options.model ? `The provider for ${options.model}` : \"The provider\";\n\t\tconst duration = formatStallDuration(Number(match[1]));\n\t\tconst sentences = [`${subject} ${symptom} within ${duration}, so the request was cancelled.`];\n\t\tconst attempts = options.attempts ?? 0;\n\t\tif (attempts > 0) {\n\t\t\tsentences.push(`Retried ${attempts} time${attempts === 1 ? \"\" : \"s\"} on the same model with the same result.`);\n\t\t}\n\t\tif (options.recovery) {\n\t\t\tconst raise = setting ? `, or raise ${setting} in settings (0 disables the bound)` : \"\";\n\t\t\tconst lead =\n\t\t\t\toptions.recovery === \"no-fallback-configured\"\n\t\t\t\t\t? \"No fallback model is configured for it, so nothing could take the turn over: run /fallback to add one\"\n\t\t\t\t\t: \"Every model in its fallback chain was tried as well: run /fallback to review the chain\";\n\t\t\tsentences.push(`${lead}, send the message again${raise}.`);\n\t\t}\n\t\treturn sentences.join(\" \");\n\t}\n\treturn undefined;\n}\n\n/**\n * Classifies timeout failures that originate from the provider stream or its\n * transport. Transport timeouts may arrive as `aborted`; stream watchdog\n * failures are ordinary error responses.\n */\nexport function isProviderTimeoutError(message: AssistantMessage): boolean {\n\tif (message.abortSource === \"provider\") return true;\n\tif (isProviderStreamStallError(message)) return true;\n\tif (message.stopReason !== \"error\" && message.stopReason !== \"aborted\") return false;\n\treturn PROVIDER_TRANSPORT_TIMEOUT_ERROR_PATTERN.test(message.errorMessage ?? \"\");\n}\n\n/**\n * Classifies a raw error-message string with the same transient-vs-terminal\n * rules as {@link isRetryableAssistantError}, for callers that hold a thrown\n * `Error` instead of an `AssistantMessage` (e.g. compaction summarization\n * failures that must decide between degrading and surfacing loudly).\n */\nexport function isRetryableErrorMessage(errorMessage: string): boolean {\n\treturn classifyErrorMessage(errorMessage) === \"retryable\";\n}\n\n/**\n * Tri-state form of {@link isRetryableErrorMessage}. The regexes only carry\n * three outcomes — a non-retryable match, a retryable match, or no match at\n * all — and callers that hold structured failure facts (status codes, provider\n * error codes) need to distinguish \"the regexes say terminal\" from \"the\n * regexes say nothing\" so they can consult the structured facts only in the\n * latter case. Non-retryable still outranks retryable, exactly as before.\n */\nexport function classifyErrorMessage(errorMessage: string): \"non-retryable\" | \"retryable\" | \"unknown\" {\n\tif (!errorMessage) return \"unknown\";\n\tif (NON_RETRYABLE_PROVIDER_ERROR_PATTERN.test(errorMessage)) return \"non-retryable\";\n\tif (RETRYABLE_PROVIDER_ERROR_PATTERN.test(errorMessage)) return \"retryable\";\n\treturn \"unknown\";\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@earendil-works/pi-ai",
3
- "version": "2026.9.21-2",
3
+ "version": "2026.9.22",
4
4
  "description": "Unified LLM API with automatic model discovery and provider configuration",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -84,7 +84,7 @@
84
84
  "dependencies": {
85
85
  "@anthropic-ai/sdk": "0.127.0",
86
86
  "@aws-sdk/client-bedrock-runtime": "3.1136.0",
87
- "@earendil-works/pi-telemetry": "npm:@code-yeongyu/senpi-telemetry@2026.9.21-2",
87
+ "@earendil-works/pi-telemetry": "npm:@code-yeongyu/senpi-telemetry@2026.9.22",
88
88
  "@google/genai": "2.23.0",
89
89
  "@smithy/node-http-handler": "4.12.1",
90
90
  "http-proxy-agent": "9.1.0",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@earendil-works/pi-pty",
3
3
  "private": true,
4
- "version": "2026.9.21-2",
4
+ "version": "2026.9.22",
5
5
  "description": "Typed PTY session loader for Senpi persistent terminals",
6
6
  "type": "module",
7
7
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@earendil-works/pi-telemetry",
3
- "version": "2026.9.21-2",
3
+ "version": "2026.9.22",
4
4
  "description": "Vendor-neutral telemetry contracts and typed schema utilities for pi",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@earendil-works/pi-tui",
3
- "version": "2026.9.21-2",
3
+ "version": "2026.9.22",
4
4
  "description": "Terminal User Interface library with differential rendering for efficient text-based applications",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@code-yeongyu/senpi",
3
- "version": "2026.9.21-2",
3
+ "version": "2026.9.22",
4
4
  "description": "Coding agent CLI with read, bash, edit, write tools and session management",
5
5
  "type": "module",
6
6
  "piConfig": {
@@ -56,9 +56,9 @@
56
56
  },
57
57
  "dependencies": {
58
58
  "@earendil-works/chord": "0.85.1",
59
- "@earendil-works/pi-agent-core": "npm:@code-yeongyu/senpi-agent-core@2026.9.21-2",
60
- "@earendil-works/pi-ai": "npm:@code-yeongyu/senpi-ai@2026.9.21-2",
61
- "@earendil-works/pi-tui": "npm:@code-yeongyu/senpi-tui@2026.9.21-2",
59
+ "@earendil-works/pi-agent-core": "npm:@code-yeongyu/senpi-agent-core@2026.9.22",
60
+ "@earendil-works/pi-ai": "npm:@code-yeongyu/senpi-ai@2026.9.22",
61
+ "@earendil-works/pi-tui": "npm:@code-yeongyu/senpi-tui@2026.9.22",
62
62
  "@silvia-odwyer/photon-node": "0.3.4",
63
63
  "chalk": "6.0.0",
64
64
  "cross-spawn": "7.0.6",
@@ -80,8 +80,8 @@
80
80
  "@anthropic-ai/sdk": "0.127.0",
81
81
  "@aws-sdk/client-bedrock-runtime": "3.1136.0",
82
82
  "@bufbuild/protobuf": "2.15.0",
83
- "@code-yeongyu/senpi-codemode": "2026.9.21-2",
84
- "@earendil-works/pi-pty": "npm:@code-yeongyu/senpi-pty@2026.9.21-2",
83
+ "@code-yeongyu/senpi-codemode": "2026.9.22",
84
+ "@earendil-works/pi-pty": "npm:@code-yeongyu/senpi-pty@2026.9.22",
85
85
  "@modelcontextprotocol/sdk": "1.30.0",
86
86
  "@mozilla/readability": "0.6.0",
87
87
  "@opentelemetry/api": "1.9.1",
@@ -120,7 +120,7 @@
120
120
  "@aws-sdk/xml-builder": "3.972.40",
121
121
  "@aws/lambda-invoke-store": "0.3.0",
122
122
  "@babel/runtime": "7.29.2",
123
- "@earendil-works/pi-telemetry": "npm:@code-yeongyu/senpi-telemetry@2026.9.21-2",
123
+ "@earendil-works/pi-telemetry": "npm:@code-yeongyu/senpi-telemetry@2026.9.22",
124
124
  "@google/genai": "2.23.0",
125
125
  "@hono/node-server": "2.1.1",
126
126
  "@mixmark-io/domino": "2.2.0",