@code-yeongyu/senpi 2026.9.27-4 → 2026.9.28-2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (294) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/dist/bundle/chunks/{app-server-command-3GVJZFFH.js → app-server-command-H6LFICZ2.js} +1 -1
  3. package/dist/bundle/chunks/{azure-openai-responses-4SUOOZZ4.js → azure-openai-responses-FCZNBRWE.js} +1 -1
  4. package/dist/bundle/chunks/bedrock-converse-stream.js +1 -1
  5. package/dist/bundle/chunks/{chunk-PSCNHY7D.js → chunk-3GMFUEU7.js} +1 -1
  6. package/dist/bundle/chunks/{chunk-HBG6SQU5.js → chunk-62XHQXCZ.js} +1 -1
  7. package/dist/bundle/chunks/{chunk-EJKCBRYK.js → chunk-6BWCPOCV.js} +4 -4
  8. package/dist/bundle/chunks/{chunk-SLL375O7.js → chunk-6VD3EBQE.js} +1 -1
  9. package/dist/bundle/chunks/chunk-7YUGCTEV.js +15 -0
  10. package/dist/bundle/chunks/{chunk-FWBSGMAE.js → chunk-A4UMPXQF.js} +1 -1
  11. package/dist/bundle/chunks/chunk-BBK6SSYT.js +2 -0
  12. package/dist/bundle/chunks/{chunk-C2425O2Q.js → chunk-CNQ4JB45.js} +1 -1
  13. package/dist/bundle/chunks/{chunk-27IFXX3B.js → chunk-DRN4FQCE.js} +1 -1
  14. package/dist/bundle/chunks/{chunk-22MGY5JQ.js → chunk-EHSZ7UCW.js} +1 -1
  15. package/dist/bundle/chunks/chunk-FHJYIU3U.js +5 -0
  16. package/dist/bundle/chunks/chunk-GJUCSTAG.js +19 -0
  17. package/dist/bundle/chunks/chunk-KOPTADA3.js +8 -0
  18. package/dist/bundle/chunks/{chunk-VMKAYXHL.js → chunk-LSW7QSLV.js} +31 -26
  19. package/dist/bundle/chunks/{chunk-2BMD37YV.js → chunk-LUPPSEQW.js} +1 -1
  20. package/dist/bundle/chunks/{chunk-NRGMT74E.js → chunk-QOVUQZO4.js} +1 -1
  21. package/dist/bundle/chunks/{chunk-IKXPBYSO.js → chunk-SICBVLRH.js} +1 -1
  22. package/dist/bundle/chunks/chunk-SN4ZHPMN.js +135 -0
  23. package/dist/bundle/chunks/{chunk-MUTD2NOH.js → chunk-TFA3YAJK.js} +1 -1
  24. package/dist/bundle/chunks/{chunk-4T4GFAGK.js → chunk-VFSXUT7K.js} +1 -1
  25. package/dist/bundle/chunks/{cli-main-66NFBKVH.js → cli-main-GYRTYPMG.js} +1 -1
  26. package/dist/bundle/chunks/{google-generative-ai-ZTGKZTGU.js → google-generative-ai-LFCBHG3Y.js} +1 -1
  27. package/dist/bundle/chunks/{google-vertex-CCZ376YK.js → google-vertex-C474FXU7.js} +1 -1
  28. package/dist/bundle/chunks/{help-fast-path-NZ3I2UEN.js → help-fast-path-3U3YDEZ6.js} +1 -1
  29. package/dist/bundle/chunks/{host-command-RORPAC5X.js → host-command-6CJ7YM6W.js} +1 -1
  30. package/dist/bundle/chunks/{host-lifecycle-UDMJGLOR.js → host-lifecycle-RZIMOFDM.js} +1 -1
  31. package/dist/bundle/chunks/host-lifecycle.js +6 -6
  32. package/dist/bundle/chunks/interactive-host-runtime-A3GEIFTU.js +4 -0
  33. package/dist/bundle/chunks/{interactive-mode-LOAADKLH.js → interactive-mode-LX665HTP.js} +1 -1
  34. package/dist/bundle/chunks/{list-tips-S5CANO5W.js → list-tips-S4U7TKER.js} +1 -1
  35. package/dist/bundle/chunks/multi-session-host-MFTUM6XQ.js +21 -0
  36. package/dist/bundle/chunks/{openai-codex-responses-YSGZZDD5.js → openai-codex-responses-2LDIFL6Z.js} +1 -1
  37. package/dist/bundle/chunks/{openai-completions-KWHRWCBN.js → openai-completions-7KZLPKYP.js} +1 -1
  38. package/dist/bundle/chunks/{openai-images-6U5FCN5S.js → openai-images-I7DR7ERP.js} +1 -1
  39. package/dist/bundle/chunks/{openai-responses-7PWMBGYX.js → openai-responses-LCHS3AF3.js} +1 -1
  40. package/dist/bundle/chunks/{openrouter-images-QIKWQZUD.js → openrouter-images-IPNDRK6C.js} +1 -1
  41. package/dist/bundle/chunks/{package-manager-cli-5EEDA35I.js → package-manager-cli-6IAE5WG3.js} +1 -1
  42. package/dist/bundle/chunks/{rotation-stream-KZG4OVR7.js → rotation-stream-ZVJEGA2G.js} +1 -1
  43. package/dist/bundle/chunks/{rpc-mode-HOEA5NGQ.js → rpc-mode-XN3HNZMH.js} +1 -1
  44. package/dist/bundle/chunks/session-picker-FPKB4DAC.js +2 -0
  45. package/dist/bundle/chunks/session-worker.js +318 -309
  46. package/dist/bundle/cli.js +1 -1
  47. package/dist/bundle/index.js +1 -1
  48. package/dist/bundle/rpc-entry.js +1 -1
  49. package/dist/cli/args.js +1 -1
  50. package/dist/cli/args.js.map +1 -1
  51. package/dist/cli/host-command.d.ts +8 -1
  52. package/dist/cli/host-command.d.ts.map +1 -1
  53. package/dist/cli/host-command.js +66 -14
  54. package/dist/cli/host-command.js.map +1 -1
  55. package/dist/core/agent-session.d.ts +18 -1
  56. package/dist/core/agent-session.d.ts.map +1 -1
  57. package/dist/core/agent-session.js +119 -3
  58. package/dist/core/agent-session.js.map +1 -1
  59. package/dist/core/extensions/builtin/prompt-preset/gpt-6-astra.d.ts +2 -2
  60. package/dist/core/extensions/builtin/prompt-preset/gpt-6-astra.d.ts.map +1 -1
  61. package/dist/core/extensions/builtin/prompt-preset/gpt-6-astra.js +13 -5
  62. package/dist/core/extensions/builtin/prompt-preset/gpt-6-astra.js.map +1 -1
  63. package/dist/core/extensions/builtin/tool-search/native-search.d.ts.map +1 -1
  64. package/dist/core/extensions/builtin/tool-search/native-search.js +13 -1
  65. package/dist/core/extensions/builtin/tool-search/native-search.js.map +1 -1
  66. package/dist/core/retry-fallback/candidates.d.ts +26 -0
  67. package/dist/core/retry-fallback/candidates.d.ts.map +1 -0
  68. package/dist/core/retry-fallback/candidates.js +41 -0
  69. package/dist/core/retry-fallback/candidates.js.map +1 -0
  70. package/dist/core/retry-fallback/circuit-probes.d.ts +30 -0
  71. package/dist/core/retry-fallback/circuit-probes.d.ts.map +1 -0
  72. package/dist/core/retry-fallback/circuit-probes.js +60 -0
  73. package/dist/core/retry-fallback/circuit-probes.js.map +1 -0
  74. package/dist/core/retry-fallback/circuit.d.ts +101 -0
  75. package/dist/core/retry-fallback/circuit.d.ts.map +1 -0
  76. package/dist/core/retry-fallback/circuit.js +175 -0
  77. package/dist/core/retry-fallback/circuit.js.map +1 -0
  78. package/dist/core/retry-fallback/controller-types.d.ts +58 -0
  79. package/dist/core/retry-fallback/controller-types.d.ts.map +1 -0
  80. package/dist/core/retry-fallback/controller-types.js +2 -0
  81. package/dist/core/retry-fallback/controller-types.js.map +1 -0
  82. package/dist/core/retry-fallback/controller.d.ts +21 -49
  83. package/dist/core/retry-fallback/controller.d.ts.map +1 -1
  84. package/dist/core/retry-fallback/controller.js +88 -42
  85. package/dist/core/retry-fallback/controller.js.map +1 -1
  86. package/dist/core/sdk.d.ts.map +1 -1
  87. package/dist/core/sdk.js +25 -17
  88. package/dist/core/sdk.js.map +1 -1
  89. package/dist/core/session-failure-report.d.ts +33 -0
  90. package/dist/core/session-failure-report.d.ts.map +1 -0
  91. package/dist/core/session-failure-report.js +62 -0
  92. package/dist/core/session-failure-report.js.map +1 -0
  93. package/dist/core/settings-manager.d.ts +3 -0
  94. package/dist/core/settings-manager.d.ts.map +1 -1
  95. package/dist/core/settings-manager.js +4 -0
  96. package/dist/core/settings-manager.js.map +1 -1
  97. package/dist/core/slash-commands.d.ts.map +1 -1
  98. package/dist/core/slash-commands.js +1 -0
  99. package/dist/core/slash-commands.js.map +1 -1
  100. package/dist/index.d.ts +1 -1
  101. package/dist/index.d.ts.map +1 -1
  102. package/dist/index.js +1 -1
  103. package/dist/index.js.map +1 -1
  104. package/dist/modes/index.d.ts +1 -0
  105. package/dist/modes/index.d.ts.map +1 -1
  106. package/dist/modes/index.js +2 -0
  107. package/dist/modes/index.js.map +1 -1
  108. package/dist/modes/interactive/help-content.d.ts.map +1 -1
  109. package/dist/modes/interactive/help-content.js +3 -0
  110. package/dist/modes/interactive/help-content.js.map +1 -1
  111. package/dist/modes/interactive/interactive-host-attach.d.ts +10 -0
  112. package/dist/modes/interactive/interactive-host-attach.d.ts.map +1 -0
  113. package/dist/modes/interactive/interactive-host-attach.js +14 -0
  114. package/dist/modes/interactive/interactive-host-attach.js.map +1 -0
  115. package/dist/modes/interactive/interactive-host-runtime.d.ts.map +1 -1
  116. package/dist/modes/interactive/interactive-host-runtime.js +3 -6
  117. package/dist/modes/interactive/interactive-host-runtime.js.map +1 -1
  118. package/dist/modes/interactive/interactive-mode.d.ts +12 -0
  119. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  120. package/dist/modes/interactive/interactive-mode.js +95 -1
  121. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  122. package/dist/modes/interactive/session-failure-info.d.ts +3 -0
  123. package/dist/modes/interactive/session-failure-info.d.ts.map +1 -0
  124. package/dist/modes/interactive/session-failure-info.js +21 -0
  125. package/dist/modes/interactive/session-failure-info.js.map +1 -0
  126. package/dist/modes/interactive/tips/catalog/model-tips.d.ts +7 -7
  127. package/dist/modes/interactive/tips/catalog/model-tips.d.ts.map +1 -1
  128. package/dist/modes/interactive/tips/catalog/model-tips.js +7 -1
  129. package/dist/modes/interactive/tips/catalog/model-tips.js.map +1 -1
  130. package/dist/modes/interactive/tips/catalog/session-tips.d.ts.map +1 -1
  131. package/dist/modes/interactive/tips/catalog/session-tips.js +1 -1
  132. package/dist/modes/interactive/tips/catalog/session-tips.js.map +1 -1
  133. package/dist/modes/rpc/host-attach-hold.d.ts +16 -0
  134. package/dist/modes/rpc/host-attach-hold.d.ts.map +1 -0
  135. package/dist/modes/rpc/host-attach-hold.js +9 -0
  136. package/dist/modes/rpc/host-attach-hold.js.map +1 -0
  137. package/dist/modes/rpc/host-cleanup-paths.d.ts +20 -0
  138. package/dist/modes/rpc/host-cleanup-paths.d.ts.map +1 -0
  139. package/dist/modes/rpc/host-cleanup-paths.js +13 -0
  140. package/dist/modes/rpc/host-cleanup-paths.js.map +1 -0
  141. package/dist/modes/rpc/host-client-occupancy.d.ts +24 -0
  142. package/dist/modes/rpc/host-client-occupancy.d.ts.map +1 -0
  143. package/dist/modes/rpc/host-client-occupancy.js +53 -0
  144. package/dist/modes/rpc/host-client-occupancy.js.map +1 -0
  145. package/dist/modes/rpc/host-daemon-paths.d.ts +61 -8
  146. package/dist/modes/rpc/host-daemon-paths.d.ts.map +1 -1
  147. package/dist/modes/rpc/host-daemon-paths.js +128 -11
  148. package/dist/modes/rpc/host-daemon-paths.js.map +1 -1
  149. package/dist/modes/rpc/host-daemon-registration.d.ts +11 -1
  150. package/dist/modes/rpc/host-daemon-registration.d.ts.map +1 -1
  151. package/dist/modes/rpc/host-daemon-registration.js +28 -15
  152. package/dist/modes/rpc/host-daemon-registration.js.map +1 -1
  153. package/dist/modes/rpc/host-endpoints.d.ts +12 -0
  154. package/dist/modes/rpc/host-endpoints.d.ts.map +1 -0
  155. package/dist/modes/rpc/host-endpoints.js +59 -0
  156. package/dist/modes/rpc/host-endpoints.js.map +1 -0
  157. package/dist/modes/rpc/host-ensure-lock.d.ts +11 -0
  158. package/dist/modes/rpc/host-ensure-lock.d.ts.map +1 -0
  159. package/dist/modes/rpc/host-ensure-lock.js +49 -0
  160. package/dist/modes/rpc/host-ensure-lock.js.map +1 -0
  161. package/dist/modes/rpc/host-ensure.d.ts +7 -0
  162. package/dist/modes/rpc/host-ensure.d.ts.map +1 -1
  163. package/dist/modes/rpc/host-ensure.js +42 -65
  164. package/dist/modes/rpc/host-ensure.js.map +1 -1
  165. package/dist/modes/rpc/host-gc-evidence.d.ts +18 -0
  166. package/dist/modes/rpc/host-gc-evidence.d.ts.map +1 -0
  167. package/dist/modes/rpc/host-gc-evidence.js +128 -0
  168. package/dist/modes/rpc/host-gc-evidence.js.map +1 -0
  169. package/dist/modes/rpc/host-gc.d.ts +28 -0
  170. package/dist/modes/rpc/host-gc.d.ts.map +1 -0
  171. package/dist/modes/rpc/host-gc.js +110 -0
  172. package/dist/modes/rpc/host-gc.js.map +1 -0
  173. package/dist/modes/rpc/host-generations.d.ts +10 -2
  174. package/dist/modes/rpc/host-generations.d.ts.map +1 -1
  175. package/dist/modes/rpc/host-generations.js +12 -7
  176. package/dist/modes/rpc/host-generations.js.map +1 -1
  177. package/dist/modes/rpc/host-handoff.d.ts +6 -0
  178. package/dist/modes/rpc/host-handoff.d.ts.map +1 -1
  179. package/dist/modes/rpc/host-handoff.js +31 -4
  180. package/dist/modes/rpc/host-handoff.js.map +1 -1
  181. package/dist/modes/rpc/host-lifecycle-policy.d.ts +53 -0
  182. package/dist/modes/rpc/host-lifecycle-policy.d.ts.map +1 -0
  183. package/dist/modes/rpc/host-lifecycle-policy.js +64 -0
  184. package/dist/modes/rpc/host-lifecycle-policy.js.map +1 -0
  185. package/dist/modes/rpc/host-lifecycle.d.ts +1 -44
  186. package/dist/modes/rpc/host-lifecycle.d.ts.map +1 -1
  187. package/dist/modes/rpc/host-lifecycle.js +23 -85
  188. package/dist/modes/rpc/host-lifecycle.js.map +1 -1
  189. package/dist/modes/rpc/host-observe-request.d.ts +17 -0
  190. package/dist/modes/rpc/host-observe-request.d.ts.map +1 -0
  191. package/dist/modes/rpc/host-observe-request.js +30 -0
  192. package/dist/modes/rpc/host-observe-request.js.map +1 -0
  193. package/dist/modes/rpc/host-probe.d.ts +12 -0
  194. package/dist/modes/rpc/host-probe.d.ts.map +1 -1
  195. package/dist/modes/rpc/host-probe.js +28 -1
  196. package/dist/modes/rpc/host-probe.js.map +1 -1
  197. package/dist/modes/rpc/host-protocol-info.d.ts +2 -0
  198. package/dist/modes/rpc/host-protocol-info.d.ts.map +1 -1
  199. package/dist/modes/rpc/host-protocol-info.js +1 -0
  200. package/dist/modes/rpc/host-protocol-info.js.map +1 -1
  201. package/dist/modes/rpc/host-readiness.d.ts +22 -0
  202. package/dist/modes/rpc/host-readiness.d.ts.map +1 -0
  203. package/dist/modes/rpc/host-readiness.js +44 -0
  204. package/dist/modes/rpc/host-readiness.js.map +1 -0
  205. package/dist/modes/rpc/host-runner.d.ts +13 -0
  206. package/dist/modes/rpc/host-runner.d.ts.map +1 -1
  207. package/dist/modes/rpc/host-runner.js +23 -4
  208. package/dist/modes/rpc/host-runner.js.map +1 -1
  209. package/dist/modes/rpc/host-status-all.d.ts +31 -0
  210. package/dist/modes/rpc/host-status-all.d.ts.map +1 -0
  211. package/dist/modes/rpc/host-status-all.js +78 -0
  212. package/dist/modes/rpc/host-status-all.js.map +1 -0
  213. package/dist/modes/rpc/host-status-rows.d.ts +35 -0
  214. package/dist/modes/rpc/host-status-rows.d.ts.map +1 -0
  215. package/dist/modes/rpc/host-status-rows.js +42 -0
  216. package/dist/modes/rpc/host-status-rows.js.map +1 -0
  217. package/dist/modes/rpc/host-status.d.ts +32 -1
  218. package/dist/modes/rpc/host-status.d.ts.map +1 -1
  219. package/dist/modes/rpc/host-status.js +33 -27
  220. package/dist/modes/rpc/host-status.js.map +1 -1
  221. package/dist/modes/rpc/host-successor.d.ts +3 -1
  222. package/dist/modes/rpc/host-successor.d.ts.map +1 -1
  223. package/dist/modes/rpc/host-successor.js +105 -42
  224. package/dist/modes/rpc/host-successor.js.map +1 -1
  225. package/dist/modes/rpc/host-watchdog.d.ts +6 -0
  226. package/dist/modes/rpc/host-watchdog.d.ts.map +1 -1
  227. package/dist/modes/rpc/host-watchdog.js +12 -13
  228. package/dist/modes/rpc/host-watchdog.js.map +1 -1
  229. package/dist/modes/rpc/loop-lag-watchdog.d.ts +16 -0
  230. package/dist/modes/rpc/loop-lag-watchdog.d.ts.map +1 -1
  231. package/dist/modes/rpc/loop-lag-watchdog.js +34 -2
  232. package/dist/modes/rpc/loop-lag-watchdog.js.map +1 -1
  233. package/dist/modes/rpc/multi-session-host.d.ts +2 -1
  234. package/dist/modes/rpc/multi-session-host.d.ts.map +1 -1
  235. package/dist/modes/rpc/multi-session-host.js +33 -6
  236. package/dist/modes/rpc/multi-session-host.js.map +1 -1
  237. package/dist/modes/rpc/rpc-mode.d.ts +2 -2
  238. package/dist/modes/rpc/rpc-mode.js +2 -2
  239. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  240. package/dist/modes/rpc/rpc-types.d.ts +16 -0
  241. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  242. package/dist/modes/rpc/rpc-types.js.map +1 -1
  243. package/dist/modes/rpc/session-command-router.d.ts +9 -1
  244. package/dist/modes/rpc/session-command-router.d.ts.map +1 -1
  245. package/dist/modes/rpc/session-command-router.js +4 -1
  246. package/dist/modes/rpc/session-command-router.js.map +1 -1
  247. package/dist/modes/rpc/session-path-key.d.ts +3 -1
  248. package/dist/modes/rpc/session-path-key.d.ts.map +1 -1
  249. package/dist/modes/rpc/session-path-key.js +3 -1
  250. package/dist/modes/rpc/session-path-key.js.map +1 -1
  251. package/docs/rpc.md +186 -19
  252. package/docs/settings.md +25 -1
  253. package/docs/usage.md +5 -2
  254. package/node_modules/@code-yeongyu/senpi-codemode/CHANGELOG.md +24 -0
  255. package/node_modules/@code-yeongyu/senpi-codemode/package.json +4 -4
  256. package/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
  257. package/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  258. package/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  259. package/node_modules/@earendil-works/pi-ai/dist/utils/error-body.d.ts +6 -0
  260. package/node_modules/@earendil-works/pi-ai/dist/utils/error-body.d.ts.map +1 -1
  261. package/node_modules/@earendil-works/pi-ai/dist/utils/error-body.js +36 -0
  262. package/node_modules/@earendil-works/pi-ai/dist/utils/error-body.js.map +1 -1
  263. package/node_modules/@earendil-works/pi-ai/dist/utils/retry.d.ts +1 -0
  264. package/node_modules/@earendil-works/pi-ai/dist/utils/retry.d.ts.map +1 -1
  265. package/node_modules/@earendil-works/pi-ai/dist/utils/retry.js +14 -1
  266. package/node_modules/@earendil-works/pi-ai/dist/utils/retry.js.map +1 -1
  267. package/node_modules/@earendil-works/pi-ai/package.json +2 -2
  268. package/node_modules/@earendil-works/pi-pty/package.json +1 -1
  269. package/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  270. package/node_modules/@earendil-works/pi-tui/dist/autocomplete.d.ts.map +1 -1
  271. package/node_modules/@earendil-works/pi-tui/dist/autocomplete.js +6 -4
  272. package/node_modules/@earendil-works/pi-tui/dist/autocomplete.js.map +1 -1
  273. package/node_modules/@earendil-works/pi-tui/dist/components/editor.d.ts +3 -0
  274. package/node_modules/@earendil-works/pi-tui/dist/components/editor.d.ts.map +1 -1
  275. package/node_modules/@earendil-works/pi-tui/dist/components/editor.js +20 -0
  276. package/node_modules/@earendil-works/pi-tui/dist/components/editor.js.map +1 -1
  277. package/node_modules/@earendil-works/pi-tui/dist/editor-component.d.ts +2 -0
  278. package/node_modules/@earendil-works/pi-tui/dist/editor-component.d.ts.map +1 -1
  279. package/node_modules/@earendil-works/pi-tui/dist/editor-component.js.map +1 -1
  280. package/node_modules/@earendil-works/pi-tui/dist/slash-command-autocomplete.d.ts +5 -0
  281. package/node_modules/@earendil-works/pi-tui/dist/slash-command-autocomplete.d.ts.map +1 -1
  282. package/node_modules/@earendil-works/pi-tui/dist/slash-command-autocomplete.js +7 -0
  283. package/node_modules/@earendil-works/pi-tui/dist/slash-command-autocomplete.js.map +1 -1
  284. package/node_modules/@earendil-works/pi-tui/package.json +1 -1
  285. package/package.json +7 -7
  286. package/dist/bundle/chunks/chunk-3DEXCYNN.js +0 -135
  287. package/dist/bundle/chunks/chunk-5X4KSPK5.js +0 -12
  288. package/dist/bundle/chunks/chunk-KMD5ZONU.js +0 -5
  289. package/dist/bundle/chunks/chunk-PEHZYGYA.js +0 -8
  290. package/dist/bundle/chunks/chunk-PRC5XIIH.js +0 -2
  291. package/dist/bundle/chunks/chunk-QKY33652.js +0 -18
  292. package/dist/bundle/chunks/interactive-host-runtime-TIFT2SKR.js +0 -4
  293. package/dist/bundle/chunks/multi-session-host-GRHKB7Q2.js +0 -21
  294. package/dist/bundle/chunks/session-picker-FTFCQYHH.js +0 -2
@@ -8,6 +8,12 @@ export interface NormalizedProviderError {
8
8
  message: string;
9
9
  /** True when `message` already contains the body (no separate body to add). */
10
10
  messageCarriesBody: boolean;
11
+ /**
12
+ * Provider-requested wait from the error response's Retry-After headers, for
13
+ * rate-limit and unavailable statuses. Carried into the formatted message as the
14
+ * canonical marker so it survives a terminal failure that no retry consumed.
15
+ */
16
+ retryAfterMs?: number;
11
17
  }
12
18
  export declare function normalizeProviderError(error: unknown): NormalizedProviderError;
13
19
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"error-body.d.ts","sourceRoot":"","sources":["../../src/utils/error-body.ts"],"names":[],"mappings":"AAeA,eAAO,MAAM,6BAA6B,OAAO,CAAC;AAElD,MAAM,WAAW,uBAAuB;IACvC,+EAA+E;IAC/E,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,sEAAsE;IACtE,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,8EAA8E;IAC9E,OAAO,EAAE,MAAM,CAAC;IAChB,+EAA+E;IAC/E,kBAAkB,EAAE,OAAO,CAAC;CAC5B;AAWD,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,OAAO,GAAG,uBAAuB,CAgB9E;AAiED;;;;;;;;GAQG;AACH,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,uBAAuB,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,CAO1F;AAED,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAGxE;AAED,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAOxD"}
1
+ {"version":3,"file":"error-body.d.ts","sourceRoot":"","sources":["../../src/utils/error-body.ts"],"names":[],"mappings":"AAiBA,eAAO,MAAM,6BAA6B,OAAO,CAAC;AAElD,MAAM,WAAW,uBAAuB;IACvC,+EAA+E;IAC/E,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,sEAAsE;IACtE,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,8EAA8E;IAC9E,OAAO,EAAE,MAAM,CAAC;IAChB,+EAA+E;IAC/E,kBAAkB,EAAE,OAAO,CAAC;IAC5B;;;;OAIG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;CACtB;AAYD,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,OAAO,GAAG,uBAAuB,CAkB9E;AAiED;;;;;;;;GAQG;AACH,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,uBAAuB,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,CAE1F;AAsCD,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAGxE;AAED,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAOxD"}
@@ -12,6 +12,7 @@
12
12
  // composes into its display string. The `messageCarriesBody` flag captures the
13
13
  // Anthropic / `@google/genai` happy path where the SDK already folded the body
14
14
  // into the message, so providers can preserve it without double-printing.
15
+ import { appendRetryAfterMsMarker, extract429RetryAfterMs, parseRetryAfterMsMarker } from "./retry-hint.js";
15
16
  export const MAX_PROVIDER_ERROR_BODY_CHARS = 4000;
16
17
  export function normalizeProviderError(error) {
17
18
  if (!(error instanceof Error)) {
@@ -21,11 +22,13 @@ export function normalizeProviderError(error) {
21
22
  const status = extractStatus(sdkError);
22
23
  const body = extractBody(sdkError);
23
24
  const messageCarriesBody = body === undefined || error.message.includes(body);
25
+ const retryAfterMs = extractRetryAfterMs(sdkError, status);
24
26
  return {
25
27
  status,
26
28
  body,
27
29
  message: error.message,
28
30
  messageCarriesBody,
31
+ ...(retryAfterMs === undefined ? {} : { retryAfterMs }),
29
32
  };
30
33
  }
31
34
  /**
@@ -109,6 +112,9 @@ function isPlainNonEmptyObject(value) {
109
112
  * - prefix: `"<prefix> (<status>): <body>"`
110
113
  */
111
114
  export function formatProviderError(norm, prefix) {
115
+ return withRetryAfterMarker(composeProviderError(norm, prefix), norm.retryAfterMs);
116
+ }
117
+ function composeProviderError(norm, prefix) {
112
118
  if (norm.messageCarriesBody || norm.status === undefined || norm.body === undefined) {
113
119
  return prefix !== undefined && norm.status !== undefined
114
120
  ? `${prefix} (${norm.status}): ${norm.message}`
@@ -116,6 +122,36 @@ export function formatProviderError(norm, prefix) {
116
122
  }
117
123
  return prefix !== undefined ? `${prefix} (${norm.status}): ${norm.body}` : `${norm.status}: ${norm.body}`;
118
124
  }
125
+ function withRetryAfterMarker(message, retryAfterMs) {
126
+ if (retryAfterMs === undefined || parseRetryAfterMsMarker(message) !== undefined)
127
+ return message;
128
+ return appendRetryAfterMsMarker(message, retryAfterMs);
129
+ }
130
+ /**
131
+ * Only 429 and 503 carry a Retry-After that means "this provider is unavailable
132
+ * until then" (RFC 9110 section 10.2.3); the header on other statuses is not a
133
+ * wait the fallback chain should honour.
134
+ */
135
+ function extractRetryAfterMs(error, status) {
136
+ if (status !== 429 && status !== 503)
137
+ return undefined;
138
+ const headers = toHeaders(error.headers);
139
+ if (headers === undefined)
140
+ return undefined;
141
+ return extract429RetryAfterMs({ status: 429, headers, bodyText: "" });
142
+ }
143
+ function toHeaders(value) {
144
+ if (value instanceof Headers)
145
+ return value;
146
+ if (typeof value !== "object" || value === null)
147
+ return undefined;
148
+ const headers = new Headers();
149
+ for (const [key, entry] of Object.entries(value)) {
150
+ if (typeof entry === "string")
151
+ headers.set(key, entry);
152
+ }
153
+ return headers;
154
+ }
119
155
  export function truncateErrorText(text, maxChars) {
120
156
  if (text.length <= maxChars)
121
157
  return text;
@@ -1 +1 @@
1
- {"version":3,"file":"error-body.js","sourceRoot":"","sources":["../../src/utils/error-body.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,EAAE;AACF,8EAA8E;AAC9E,gFAAgF;AAChF,gFAAgF;AAChF,6EAA6E;AAC7E,6EAA6E;AAC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AC,CAAC,CAAC,UAAU,CAAC;IAC9D,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC;IACtB,CAAC;AACF,CAAC","sourcesContent":["// Shared normalization for provider HTTP error objects.\n//\n// Endpoints behind a proxy / gateway may return a non-2xx response whose body\n// the provider SDK cannot fold into `error.message`. The SDK error object still\n// carries the HTTP status and the raw/parsed body, but under SDK-specific field\n// names. Provider catch blocks that read only `error.message` therefore drop\n// the body and surface opaque messages like `\"403 status code (no body)\"` or\n// collapse to `\"Unknown: UnknownError\"`.\n//\n// `normalizeProviderError` probes the known SDK field shapes (Mistral,\n// `openai`, `@google/genai`, AWS Bedrock) and returns a struct each provider\n// composes into its display string. The `messageCarriesBody` flag captures the\n// Anthropic / `@google/genai` happy path where the SDK already folded the body\n// into the message, so providers can preserve it without double-printing.\n\nexport const MAX_PROVIDER_ERROR_BODY_CHARS = 4000;\n\nexport interface NormalizedProviderError {\n\t/** HTTP status code, when one could be extracted from the SDK error object. */\n\tstatus?: number;\n\t/** Raw HTTP body reason, already trimmed and truncated to the cap. */\n\tbody?: string;\n\t/** `error.message`, or `safeJsonStringify(error)` for a non-`Error` throw. */\n\tmessage: string;\n\t/** True when `message` already contains the body (no separate body to add). */\n\tmessageCarriesBody: boolean;\n}\n\ntype SdkErrorShape = Error & {\n\tstatusCode?: unknown;\n\tstatus?: unknown;\n\tbody?: unknown;\n\terror?: unknown;\n\t$metadata?: { httpStatusCode?: unknown };\n\t$response?: { statusCode?: unknown; body?: unknown };\n};\n\nexport function normalizeProviderError(error: unknown): NormalizedProviderError {\n\tif (!(error instanceof Error)) {\n\t\treturn { message: safeJsonStringify(error), messageCarriesBody: false };\n\t}\n\n\tconst sdkError = error as SdkErrorShape;\n\tconst status = extractStatus(sdkError);\n\tconst body = extractBody(sdkError);\n\tconst messageCarriesBody = body === undefined || error.message.includes(body);\n\n\treturn {\n\t\tstatus,\n\t\tbody,\n\t\tmessage: error.message,\n\t\tmessageCarriesBody,\n\t} satisfies NormalizedProviderError;\n}\n\n/**\n * Probe the HTTP status, first numeric hit wins, in SDK-field order:\n * `statusCode` (Mistral) → `status` (`openai`, `@google/genai`) →\n * `$metadata.httpStatusCode` (Bedrock) → `$response.statusCode` (Bedrock).\n */\nfunction extractStatus(error: SdkErrorShape): number | undefined {\n\tif (typeof error.statusCode === \"number\") return error.statusCode;\n\tif (typeof error.status === \"number\") return error.status;\n\tif (typeof error.$metadata?.httpStatusCode === \"number\") return error.$metadata.httpStatusCode;\n\tif (typeof error.$response?.statusCode === \"number\") return error.$response.statusCode;\n\treturn undefined;\n}\n\n/**\n * Probe the raw body reason, first usable hit wins, in SDK-field order:\n * `body` string (Mistral) → `error` parsed JSON body object (`openai` SDK's\n * `this.error`) → `$response.body` (Bedrock). Empty objects and unread response\n * streams are treated as no body so they do not surface as `\"{}\"` or serialized\n * stream internals. The chosen body is truncated to the cap.\n */\nfunction extractBody(error: SdkErrorShape): string | undefined {\n\tconst bodyText = pickBodyText(error);\n\tif (bodyText === undefined) return undefined;\n\tconst trimmed = bodyText.trim();\n\tif (trimmed.length === 0) return undefined;\n\treturn truncateErrorText(trimmed, MAX_PROVIDER_ERROR_BODY_CHARS);\n}\n\nfunction pickBodyText(error: SdkErrorShape): string | undefined {\n\tif (typeof error.body === \"string\") return error.body;\n\tif (isPlainNonEmptyObject(error.error)) return safeJsonStringify(error.error);\n\tconst responseBody = error.$response?.body;\n\tif (typeof responseBody === \"string\") return responseBody;\n\tif (isReadableStreamLike(responseBody)) return undefined;\n\tif (isPlainNonEmptyObject(responseBody)) return safeJsonStringify(responseBody);\n\treturn undefined;\n}\n\nfunction isReadableStreamLike(value: unknown): boolean {\n\treturn typeof value === \"object\" && value !== null && \"pipe\" in value && typeof value.pipe === \"function\";\n}\n\n/**\n * Only a PLAIN object counts as an HTTP body. SDK error fields can hold class\n * instances instead of parsed bodies — AWS SDK v3's `$response.body` is an\n * HTTP stream/response wrapper object, and stringifying one produced garbage\n * like `{\"_events\":...}` as the \"body\", which then REPLACED `error.message`\n * in the composed display string. `error.message` is where the SDK puts the\n * real deserialized exception text (\"Input is too long...\", schema validation\n * details, ...), so the one useful string was discarded for noise. A class\n * instance yields no body, `messageCarriesBody` stays true, and the real\n * message survives. Complements the `pipe` sniffing above: web\n * ReadableStreams (pipeTo/pipeThrough, no `pipe`) and non-stream SDK wrapper\n * classes fail the prototype check, while parsed JSON bodies (plain objects\n * by construction) still pass.\n */\nfunction isPlainNonEmptyObject(value: unknown): boolean {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tconst proto = Object.getPrototypeOf(value);\n\tif (proto !== Object.prototype && proto !== null) return false;\n\treturn Object.keys(value).length > 0;\n}\n\n/**\n * Compose a display string from a normalized error. When the message already\n * carries the body (Anthropic / `@google/genai` happy path) or no body/status\n * was extracted, the message is returned unchanged. Otherwise the status and\n * body are surfaced, with an optional provider prefix.\n *\n * - no prefix: `\"<status>: <body>\"`\n * - prefix: `\"<prefix> (<status>): <body>\"`\n */\nexport function formatProviderError(norm: NormalizedProviderError, prefix?: string): string {\n\tif (norm.messageCarriesBody || norm.status === undefined || norm.body === undefined) {\n\t\treturn prefix !== undefined && norm.status !== undefined\n\t\t\t? `${prefix} (${norm.status}): ${norm.message}`\n\t\t\t: norm.message;\n\t}\n\treturn prefix !== undefined ? `${prefix} (${norm.status}): ${norm.body}` : `${norm.status}: ${norm.body}`;\n}\n\nexport function truncateErrorText(text: string, maxChars: number): string {\n\tif (text.length <= maxChars) return text;\n\treturn `${text.slice(0, maxChars)}... [truncated ${text.length - maxChars} chars]`;\n}\n\nexport function safeJsonStringify(value: unknown): string {\n\ttry {\n\t\tconst serialized = JSON.stringify(value);\n\t\treturn serialized === undefined ? String(value) : serialized;\n\t} catch {\n\t\treturn String(value);\n\t}\n}\n"]}
1
+ {"version":3,"file":"error-body.js","sourceRoot":"","sources":["../../src/utils/error-body.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,EAAE;AACF,8EAA8E;AAC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C,KAAK,CAAC,CAAC,EAAE,QAAQ,CAAC,kBAAkB,IAAI,CAAC,MAAM,GAAG,QAAQ,SAAS,CAAC;AACpF,CAAC;AAED,MAAM,UAAU,iBAAiB,CAAC,KAAc;IAC/C,IAAI,CAAC;QACJ,MAAM,UAAU,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;QACzC,OAAO,UAAU,KAAK,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC;IAC9D,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC;IACtB,CAAC;AACF,CAAC","sourcesContent":["// Shared normalization for provider HTTP error objects.\n//\n// Endpoints behind a proxy / gateway may return a non-2xx response whose body\n// the provider SDK cannot fold into `error.message`. The SDK error object still\n// carries the HTTP status and the raw/parsed body, but under SDK-specific field\n// names. Provider catch blocks that read only `error.message` therefore drop\n// the body and surface opaque messages like `\"403 status code (no body)\"` or\n// collapse to `\"Unknown: UnknownError\"`.\n//\n// `normalizeProviderError` probes the known SDK field shapes (Mistral,\n// `openai`, `@google/genai`, AWS Bedrock) and returns a struct each provider\n// composes into its display string. The `messageCarriesBody` flag captures the\n// Anthropic / `@google/genai` happy path where the SDK already folded the body\n// into the message, so providers can preserve it without double-printing.\n\nimport { appendRetryAfterMsMarker, extract429RetryAfterMs, parseRetryAfterMsMarker } from \"./retry-hint.ts\";\n\nexport const MAX_PROVIDER_ERROR_BODY_CHARS = 4000;\n\nexport interface NormalizedProviderError {\n\t/** HTTP status code, when one could be extracted from the SDK error object. */\n\tstatus?: number;\n\t/** Raw HTTP body reason, already trimmed and truncated to the cap. */\n\tbody?: string;\n\t/** `error.message`, or `safeJsonStringify(error)` for a non-`Error` throw. */\n\tmessage: string;\n\t/** True when `message` already contains the body (no separate body to add). */\n\tmessageCarriesBody: boolean;\n\t/**\n\t * Provider-requested wait from the error response's Retry-After headers, for\n\t * rate-limit and unavailable statuses. Carried into the formatted message as the\n\t * canonical marker so it survives a terminal failure that no retry consumed.\n\t */\n\tretryAfterMs?: number;\n}\n\ntype SdkErrorShape = Error & {\n\theaders?: unknown;\n\tstatusCode?: unknown;\n\tstatus?: unknown;\n\tbody?: unknown;\n\terror?: unknown;\n\t$metadata?: { httpStatusCode?: unknown };\n\t$response?: { statusCode?: unknown; body?: unknown };\n};\n\nexport function normalizeProviderError(error: unknown): NormalizedProviderError {\n\tif (!(error instanceof Error)) {\n\t\treturn { message: safeJsonStringify(error), messageCarriesBody: false };\n\t}\n\n\tconst sdkError = error as SdkErrorShape;\n\tconst status = extractStatus(sdkError);\n\tconst body = extractBody(sdkError);\n\tconst messageCarriesBody = body === undefined || error.message.includes(body);\n\tconst retryAfterMs = extractRetryAfterMs(sdkError, status);\n\n\treturn {\n\t\tstatus,\n\t\tbody,\n\t\tmessage: error.message,\n\t\tmessageCarriesBody,\n\t\t...(retryAfterMs === undefined ? {} : { retryAfterMs }),\n\t} satisfies NormalizedProviderError;\n}\n\n/**\n * Probe the HTTP status, first numeric hit wins, in SDK-field order:\n * `statusCode` (Mistral) → `status` (`openai`, `@google/genai`) →\n * `$metadata.httpStatusCode` (Bedrock) → `$response.statusCode` (Bedrock).\n */\nfunction extractStatus(error: SdkErrorShape): number | undefined {\n\tif (typeof error.statusCode === \"number\") return error.statusCode;\n\tif (typeof error.status === \"number\") return error.status;\n\tif (typeof error.$metadata?.httpStatusCode === \"number\") return error.$metadata.httpStatusCode;\n\tif (typeof error.$response?.statusCode === \"number\") return error.$response.statusCode;\n\treturn undefined;\n}\n\n/**\n * Probe the raw body reason, first usable hit wins, in SDK-field order:\n * `body` string (Mistral) → `error` parsed JSON body object (`openai` SDK's\n * `this.error`) → `$response.body` (Bedrock). Empty objects and unread response\n * streams are treated as no body so they do not surface as `\"{}\"` or serialized\n * stream internals. The chosen body is truncated to the cap.\n */\nfunction extractBody(error: SdkErrorShape): string | undefined {\n\tconst bodyText = pickBodyText(error);\n\tif (bodyText === undefined) return undefined;\n\tconst trimmed = bodyText.trim();\n\tif (trimmed.length === 0) return undefined;\n\treturn truncateErrorText(trimmed, MAX_PROVIDER_ERROR_BODY_CHARS);\n}\n\nfunction pickBodyText(error: SdkErrorShape): string | undefined {\n\tif (typeof error.body === \"string\") return error.body;\n\tif (isPlainNonEmptyObject(error.error)) return safeJsonStringify(error.error);\n\tconst responseBody = error.$response?.body;\n\tif (typeof responseBody === \"string\") return responseBody;\n\tif (isReadableStreamLike(responseBody)) return undefined;\n\tif (isPlainNonEmptyObject(responseBody)) return safeJsonStringify(responseBody);\n\treturn undefined;\n}\n\nfunction isReadableStreamLike(value: unknown): boolean {\n\treturn typeof value === \"object\" && value !== null && \"pipe\" in value && typeof value.pipe === \"function\";\n}\n\n/**\n * Only a PLAIN object counts as an HTTP body. SDK error fields can hold class\n * instances instead of parsed bodies — AWS SDK v3's `$response.body` is an\n * HTTP stream/response wrapper object, and stringifying one produced garbage\n * like `{\"_events\":...}` as the \"body\", which then REPLACED `error.message`\n * in the composed display string. `error.message` is where the SDK puts the\n * real deserialized exception text (\"Input is too long...\", schema validation\n * details, ...), so the one useful string was discarded for noise. A class\n * instance yields no body, `messageCarriesBody` stays true, and the real\n * message survives. Complements the `pipe` sniffing above: web\n * ReadableStreams (pipeTo/pipeThrough, no `pipe`) and non-stream SDK wrapper\n * classes fail the prototype check, while parsed JSON bodies (plain objects\n * by construction) still pass.\n */\nfunction isPlainNonEmptyObject(value: unknown): boolean {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tconst proto = Object.getPrototypeOf(value);\n\tif (proto !== Object.prototype && proto !== null) return false;\n\treturn Object.keys(value).length > 0;\n}\n\n/**\n * Compose a display string from a normalized error. When the message already\n * carries the body (Anthropic / `@google/genai` happy path) or no body/status\n * was extracted, the message is returned unchanged. Otherwise the status and\n * body are surfaced, with an optional provider prefix.\n *\n * - no prefix: `\"<status>: <body>\"`\n * - prefix: `\"<prefix> (<status>): <body>\"`\n */\nexport function formatProviderError(norm: NormalizedProviderError, prefix?: string): string {\n\treturn withRetryAfterMarker(composeProviderError(norm, prefix), norm.retryAfterMs);\n}\n\nfunction composeProviderError(norm: NormalizedProviderError, prefix?: string): string {\n\tif (norm.messageCarriesBody || norm.status === undefined || norm.body === undefined) {\n\t\treturn prefix !== undefined && norm.status !== undefined\n\t\t\t? `${prefix} (${norm.status}): ${norm.message}`\n\t\t\t: norm.message;\n\t}\n\treturn prefix !== undefined ? `${prefix} (${norm.status}): ${norm.body}` : `${norm.status}: ${norm.body}`;\n}\n\nfunction withRetryAfterMarker(message: string, retryAfterMs: number | undefined): string {\n\tif (retryAfterMs === undefined || parseRetryAfterMsMarker(message) !== undefined) return message;\n\treturn appendRetryAfterMsMarker(message, retryAfterMs);\n}\n\n/**\n * Only 429 and 503 carry a Retry-After that means \"this provider is unavailable\n * until then\" (RFC 9110 section 10.2.3); the header on other statuses is not a\n * wait the fallback chain should honour.\n */\nfunction extractRetryAfterMs(error: SdkErrorShape, status: number | undefined): number | undefined {\n\tif (status !== 429 && status !== 503) return undefined;\n\tconst headers = toHeaders(error.headers);\n\tif (headers === undefined) return undefined;\n\treturn extract429RetryAfterMs({ status: 429, headers, bodyText: \"\" });\n}\n\nfunction toHeaders(value: unknown): Headers | undefined {\n\tif (value instanceof Headers) return value;\n\tif (typeof value !== \"object\" || value === null) return undefined;\n\tconst headers = new Headers();\n\tfor (const [key, entry] of Object.entries(value)) {\n\t\tif (typeof entry === \"string\") headers.set(key, entry);\n\t}\n\treturn headers;\n}\n\nexport function truncateErrorText(text: string, maxChars: number): string {\n\tif (text.length <= maxChars) return text;\n\treturn `${text.slice(0, maxChars)}... [truncated ${text.length - maxChars} chars]`;\n}\n\nexport function safeJsonStringify(value: unknown): string {\n\ttry {\n\t\tconst serialized = JSON.stringify(value);\n\t\treturn serialized === undefined ? String(value) : serialized;\n\t} catch {\n\t\treturn String(value);\n\t}\n}\n"]}
@@ -15,6 +15,7 @@ export declare const USAGE_LIMIT_EXHAUSTION: {
15
15
  /** Message markers: the codes appear verbatim in bodies, plus the sentence. */
16
16
  readonly markers: readonly ["usage_limit_reached", "usage_not_included", "usage limit has been reached"];
17
17
  };
18
+ export declare function isQuotaExhaustionMessage(errorMessage: string | undefined): boolean;
18
19
  /**
19
20
  * Retry policy: bounded attempts with exponential backoff (`baseDelayMs * 2^(attempt-1)`).
20
21
  * `maxAgentDelayMs` caps each computed delay and defaults to 60 seconds.
@@ -1 +1 @@
1
- {"version":3,"file":"retry.d.ts","sourceRoot":"","sources":["../../src/utils/retry.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAWpD;;;;;;;;;GASG;AACH,eAAO,MAAM,sBAAsB;IAClC,+EAA+E;aAC/E,KAAK,YAAG,qBAAqB,EAAE,oBAAoB;IACnD,+EAA+E;aAC/E,OAAO,YAAG,qBAAqB,EAAE,oBAAoB,EAAE,8BAA8B;CAC5E,CAAC;AAgKX;;;;;;GAMG;AACH,MAAM,WAAW,WAAW;IAC3B,OAAO,EAAE,OAAO,CAAC;IACjB,qFAAqF;IACrF,UAAU,EAAE,MAAM,CAAC;IACnB,0FAA0F;IAC1F,WAAW,EAAE,MAAM,CAAC;IACpB,+EAA+E;IAC/E,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,oEAAoE;IACpE,MAAM,CAAC,EAAE,MAAM,MAAM,CAAC;CACtB;AAED,eAAO,MAAM,gCAAgC,QAAS,CAAC;AAEvD;;;;;;GAMG;AACH,wBAAgB,YAAY,CAC3B,MAAM,EAAE,IAAI,CAAC,WAAW,EAAE,aAAa,GAAG,iBAAiB,GAAG,QAAQ,CAAC,EACvE,OAAO,EAAE,MAAM,GACb,MAAM,CAMR;AAED,kFAAkF;AAClF,MAAM,WAAW,cAAc;IAC9B,0EAA0E;IAC1E,gBAAgB,CAAC,EAAE,CAClB,OAAO,EAAE,MAAM,EACf,WAAW,EAAE,MAAM,EACnB,OAAO,EAAE,MAAM,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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"}
@@ -21,7 +21,13 @@ export const USAGE_LIMIT_EXHAUSTION = {
21
21
  /** Message markers: the codes appear verbatim in bodies, plus the sentence. */
22
22
  markers: ["usage_limit_reached", "usage_not_included", "usage limit has been reached"],
23
23
  };
24
- const NON_RETRYABLE_PROVIDER_ERROR_PATTERN = buildProviderErrorPattern([
24
+ /**
25
+ * Account quota, budget, credit, and billing exhaustion: the account cannot
26
+ * serve more requests until the user pays or the quota resets. Shared by the
27
+ * terminal classifier below and the fallback circuit breaker, so both recognise
28
+ * the same exhaustion wording.
29
+ */
30
+ const QUOTA_EXHAUSTION_PATTERNS = [
25
31
  // OpenCode Go/free-tier limits returned as 429 JSON error types by OpenCode's
26
32
  // Zen API. These are subscription/account limits, not transient throttles.
27
33
  "GoUsageLimitError",
@@ -47,6 +53,13 @@ const NON_RETRYABLE_PROVIDER_ERROR_PATTERN = buildProviderErrorPattern([
47
53
  // stays dead until its quota resets — every same-account retry is guaranteed
48
54
  // to fail, so the failure is terminal, not rate-limited.
49
55
  ...USAGE_LIMIT_EXHAUSTION.markers,
56
+ ];
57
+ const QUOTA_EXHAUSTION_PATTERN = buildProviderErrorPattern(QUOTA_EXHAUSTION_PATTERNS);
58
+ export function isQuotaExhaustionMessage(errorMessage) {
59
+ return errorMessage !== undefined && QUOTA_EXHAUSTION_PATTERN.test(errorMessage);
60
+ }
61
+ const NON_RETRYABLE_PROVIDER_ERROR_PATTERN = buildProviderErrorPattern([
62
+ ...QUOTA_EXHAUSTION_PATTERNS,
50
63
  // Request-shape rejections: the provider refused the payload we built, not the
51
64
  // work it describes. Gateways wrap these in whatever status they like — the
52
65
  // observed Apitopia/Kimi case arrives as `500 server_error: Invalid request:
@@ -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;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,sBAAsB,GAAG;IACrC,+EAA+E;IAC/E,KAAK,EAAE,CAAC,qBAAqB,EAAE,oBAAoB,CAAC;IACpD,+EAA+E;IAC/E,OAAO,EAAE,CAAC,qBAAqB,EAAE,oBAAoB,EAAE,8BAA8B,CAAC;CAC7E,CAAC;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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\n/**\n * OpenAI hard account-quota exhaustion (senpi#1969). The wire evidence is a 429\n * whose body is `{\"type\":\"usage_limit_reached\",\"message\":\"The usage limit has\n * been reached\"}`; `usage_not_included` is the sibling entitlement code. The\n * account cannot serve more requests until its quota resets or its plan changes,\n * so every consumer treats the family as terminal. Declared once here and\n * consumed by both the non-retryable pattern below and the structured terminal\n * provider codes in `retry-profile/classifiers.ts`, so the two lists cannot\n * drift.\n */\nexport const USAGE_LIMIT_EXHAUSTION = {\n\t/** Structured error codes, as extracted into `providerCodes` failure facts. */\n\tcodes: [\"usage_limit_reached\", \"usage_not_included\"],\n\t/** Message markers: the codes appear verbatim in bodies, plus the sentence. */\n\tmarkers: [\"usage_limit_reached\", \"usage_not_included\", \"usage limit has been reached\"],\n} as const;\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// OpenAI hard account-quota exhaustion (senpi#1969): the 429 body carries\n\t// `usage_limit_reached` / \"The usage limit has been reached\", and the account\n\t// stays dead until its quota resets — every same-account retry is guaranteed\n\t// to fail, so the failure is terminal, not rate-limited.\n\t...USAGE_LIMIT_EXHAUSTION.markers,\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// Replayed-reasoning rejections, e.g. \"the reasoning_details at position 1271 entry 0\n\t// must not contain streaming index\". A gateway refuses an input reasoning entry that\n\t// still carries the streaming-assembly `index`, and because the merged array is\n\t// persisted in the assistant block, every later request in that conversation is\n\t// rejected identically. The openai-completions request builder strips the field before\n\t// the retried request is built, so the retry sends a valid payload; same reasoning as\n\t// the pairing class above, and the retry stays bounded by the policy's attempt budget.\n\t\"must not contain streaming index\",\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
+ {"version":3,"file":"retry.js","sourceRoot":"","sources":["../../src/utils/retry.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,8BAA8B,EAAE,8BAA8B,EAAE,M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;;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\n/**\n * OpenAI hard account-quota exhaustion (senpi#1969). The wire evidence is a 429\n * whose body is `{\"type\":\"usage_limit_reached\",\"message\":\"The usage limit has\n * been reached\"}`; `usage_not_included` is the sibling entitlement code. The\n * account cannot serve more requests until its quota resets or its plan changes,\n * so every consumer treats the family as terminal. Declared once here and\n * consumed by both the non-retryable pattern below and the structured terminal\n * provider codes in `retry-profile/classifiers.ts`, so the two lists cannot\n * drift.\n */\nexport const USAGE_LIMIT_EXHAUSTION = {\n\t/** Structured error codes, as extracted into `providerCodes` failure facts. */\n\tcodes: [\"usage_limit_reached\", \"usage_not_included\"],\n\t/** Message markers: the codes appear verbatim in bodies, plus the sentence. */\n\tmarkers: [\"usage_limit_reached\", \"usage_not_included\", \"usage limit has been reached\"],\n} as const;\n\n/**\n * Account quota, budget, credit, and billing exhaustion: the account cannot\n * serve more requests until the user pays or the quota resets. Shared by the\n * terminal classifier below and the fallback circuit breaker, so both recognise\n * the same exhaustion wording.\n */\nconst QUOTA_EXHAUSTION_PATTERNS = [\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// OpenAI hard account-quota exhaustion (senpi#1969): the 429 body carries\n\t// `usage_limit_reached` / \"The usage limit has been reached\", and the account\n\t// stays dead until its quota resets — every same-account retry is guaranteed\n\t// to fail, so the failure is terminal, not rate-limited.\n\t...USAGE_LIMIT_EXHAUSTION.markers,\n] as const;\n\nconst QUOTA_EXHAUSTION_PATTERN = buildProviderErrorPattern(QUOTA_EXHAUSTION_PATTERNS);\n\nexport function isQuotaExhaustionMessage(errorMessage: string | undefined): boolean {\n\treturn errorMessage !== undefined && QUOTA_EXHAUSTION_PATTERN.test(errorMessage);\n}\n\nconst NON_RETRYABLE_PROVIDER_ERROR_PATTERN = buildProviderErrorPattern([\n\t...QUOTA_EXHAUSTION_PATTERNS,\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// Replayed-reasoning rejections, e.g. \"the reasoning_details at position 1271 entry 0\n\t// must not contain streaming index\". A gateway refuses an input reasoning entry that\n\t// still carries the streaming-assembly `index`, and because the merged array is\n\t// persisted in the assistant block, every later request in that conversation is\n\t// rejected identically. The openai-completions request builder strips the field before\n\t// the retried request is built, so the retry sends a valid payload; same reasoning as\n\t// the pairing class above, and the retry stays bounded by the policy's attempt budget.\n\t\"must not contain streaming index\",\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.27-4",
3
+ "version": "2026.9.28-2",
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.27-4",
87
+ "@earendil-works/pi-telemetry": "npm:@code-yeongyu/senpi-telemetry@2026.9.28-2",
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.27-4",
4
+ "version": "2026.9.28-2",
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.27-4",
3
+ "version": "2026.9.28-2",
4
4
  "description": "Vendor-neutral telemetry contracts and typed schema utilities for pi",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1 +1 @@
1
- {"version":3,"file":"autocomplete.d.ts","sourceRoot":"","sources":["../src/autocomplete.ts"],"names":[],"mappings":"AAqOA,MAAM,WAAW,gBAAgB;IAChC,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,KAAK,SAAS,CAAC,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;AAEnC,MAAM,WAAW,YAAY;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,YAAY,CAAC,EAAE,MAAM,CAAC;IAGtB,sBAAsB,CAAC,CAAC,cAAc,EAAE,MAAM,GAAG,SAAS,CAAC,gBAAgB,EAAE,GAAG,IAAI,CAAC,CAAC;CACtF;AAED,MAAM,WAAW,uBAAuB;IACvC,KAAK,EAAE,gBAAgB,EAAE,CAAC;IAC1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import { basename, dirname, join } from "path";
5
5
  import { findDollarSkillMentions, getDollarInvocationContext, getDollarInvocationSuggestions, knownSkillNames, } from "./dollar-invocation-autocomplete.js";
6
- import { getSlashCommandSuggestions } from "./slash-command-autocomplete.js";
6
+ import { getSlashCommandSuggestions, isSlashNamespaceItem } from "./slash-command-autocomplete.js";
7
7
  const PATH_DELIMITERS = new Set([" ", "\t", '"', "'", "="]);
8
8
  function toDisplayPath(value) {
9
9
  return value.replace(/\\/g, "/");
@@ -299,14 +299,16 @@ export class CombinedAutocompleteProvider {
299
299
  (beforePrefix.trim() === "" ||
300
300
  (prefix.startsWith("/skill:") && this.isLeadingKnownSkillCommandRun(beforePrefix)));
301
301
  if (isSlashCommand) {
302
- // This is a command name completion
303
- const newLine = `${beforePrefix}/${item.value} ${adjustedAfterCursor}`;
302
+ // This is a command name completion. A namespace (`skill:`) gets no trailing space so the
303
+ // editor can list that namespace's commands right after it.
304
+ const separator = isSlashNamespaceItem(item.value) ? "" : " ";
305
+ const newLine = `${beforePrefix}/${item.value}${separator}${adjustedAfterCursor}`;
304
306
  const newLines = [...lines];
305
307
  newLines[cursorLine] = newLine;
306
308
  return {
307
309
  lines: newLines,
308
310
  cursorLine,
309
- cursorCol: beforePrefix.length + item.value.length + 2, // +2 for "/" and space
311
+ cursorCol: beforePrefix.length + 1 + item.value.length + separator.length,
310
312
  };
311
313
  }
312
314
  // Check if we're completing a file attachment (prefix starts with "@")