@code-yeongyu/senpi 2026.9.15 → 2026.9.16-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.
- package/CHANGELOG.md +73 -0
- package/README.md +1 -1
- package/dist/core/agent-session.d.ts +28 -0
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +111 -13
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/compaction/compaction.d.ts.map +1 -1
- package/dist/core/compaction/compaction.js +4 -2
- package/dist/core/compaction/compaction.js.map +1 -1
- package/dist/core/compaction/stream-watchdog.d.ts +56 -2
- package/dist/core/compaction/stream-watchdog.d.ts.map +1 -1
- package/dist/core/compaction/stream-watchdog.js +93 -15
- package/dist/core/compaction/stream-watchdog.js.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-binding.d.ts +6 -0
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-binding.d.ts.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-binding.js +17 -0
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-binding.js.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-continuity.d.ts +4 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-continuity.d.ts.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-continuity.js +31 -0
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-continuity.js.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-reattach.d.ts +2 -0
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-reattach.d.ts.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-reattach.js +16 -0
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-reattach.js.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-registry-wiring.d.ts.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-registry-wiring.js +19 -8
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-registry-wiring.js.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-stream.d.ts.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-stream.js +2 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-stream.js.map +1 -1
- package/dist/core/extensions/builtin/compaction/deterministic-fallback.d.ts +13 -1
- package/dist/core/extensions/builtin/compaction/deterministic-fallback.d.ts.map +1 -1
- package/dist/core/extensions/builtin/compaction/deterministic-fallback.js +66 -2
- package/dist/core/extensions/builtin/compaction/deterministic-fallback.js.map +1 -1
- package/dist/core/extensions/builtin/compaction/index.d.ts.map +1 -1
- package/dist/core/extensions/builtin/compaction/index.js +16 -10
- package/dist/core/extensions/builtin/compaction/index.js.map +1 -1
- package/dist/core/extensions/builtin/compaction/speculative-summary.d.ts.map +1 -1
- package/dist/core/extensions/builtin/compaction/speculative-summary.js +4 -2
- package/dist/core/extensions/builtin/compaction/speculative-summary.js.map +1 -1
- package/dist/core/extensions/builtin/compaction/speculative.d.ts +8 -1
- package/dist/core/extensions/builtin/compaction/speculative.d.ts.map +1 -1
- package/dist/core/extensions/builtin/compaction/speculative.js +31 -7
- package/dist/core/extensions/builtin/compaction/speculative.js.map +1 -1
- package/dist/core/extensions/builtin/compaction/transient-failure.d.ts.map +1 -1
- package/dist/core/extensions/builtin/compaction/transient-failure.js +6 -3
- package/dist/core/extensions/builtin/compaction/transient-failure.js.map +1 -1
- package/dist/core/extensions/builtin/config-reload/index.d.ts.map +1 -1
- package/dist/core/extensions/builtin/config-reload/index.js +25 -8
- package/dist/core/extensions/builtin/config-reload/index.js.map +1 -1
- package/dist/core/extensions/builtin/config-reload/watch-engine.d.ts +4 -5
- package/dist/core/extensions/builtin/config-reload/watch-engine.d.ts.map +1 -1
- package/dist/core/extensions/builtin/config-reload/watch-engine.js +14 -18
- package/dist/core/extensions/builtin/config-reload/watch-engine.js.map +1 -1
- package/dist/core/extensions/builtin/config-reload/watch-event-source.d.ts.map +1 -1
- package/dist/core/extensions/builtin/config-reload/watch-event-source.js +32 -9
- package/dist/core/extensions/builtin/config-reload/watch-event-source.js.map +1 -1
- package/dist/core/extensions/builtin/cursor-cli-oauth/catalog-refresh.d.ts +23 -0
- package/dist/core/extensions/builtin/cursor-cli-oauth/catalog-refresh.d.ts.map +1 -0
- package/dist/core/extensions/builtin/cursor-cli-oauth/catalog-refresh.js +48 -0
- package/dist/core/extensions/builtin/cursor-cli-oauth/catalog-refresh.js.map +1 -0
- package/dist/core/extensions/builtin/cursor-cli-oauth/environment.d.ts +13 -0
- package/dist/core/extensions/builtin/cursor-cli-oauth/environment.d.ts.map +1 -0
- package/dist/core/extensions/builtin/cursor-cli-oauth/environment.js +24 -0
- package/dist/core/extensions/builtin/cursor-cli-oauth/environment.js.map +1 -0
- package/dist/core/extensions/builtin/cursor-cli-oauth/executable.d.ts +1 -0
- package/dist/core/extensions/builtin/cursor-cli-oauth/executable.d.ts.map +1 -1
- package/dist/core/extensions/builtin/cursor-cli-oauth/executable.js +7 -1
- package/dist/core/extensions/builtin/cursor-cli-oauth/executable.js.map +1 -1
- package/dist/core/extensions/builtin/cursor-cli-oauth/index.d.ts +2 -0
- package/dist/core/extensions/builtin/cursor-cli-oauth/index.d.ts.map +1 -1
- package/dist/core/extensions/builtin/cursor-cli-oauth/index.js +11 -9
- package/dist/core/extensions/builtin/cursor-cli-oauth/index.js.map +1 -1
- package/dist/core/extensions/builtin/cursor-cli-oauth/models-probe.d.ts +18 -0
- package/dist/core/extensions/builtin/cursor-cli-oauth/models-probe.d.ts.map +1 -0
- package/dist/core/extensions/builtin/cursor-cli-oauth/models-probe.js +61 -0
- package/dist/core/extensions/builtin/cursor-cli-oauth/models-probe.js.map +1 -0
- package/dist/core/extensions/builtin/cursor-cli-oauth/models.d.ts +4 -1
- package/dist/core/extensions/builtin/cursor-cli-oauth/models.d.ts.map +1 -1
- package/dist/core/extensions/builtin/cursor-cli-oauth/models.js +1 -44
- package/dist/core/extensions/builtin/cursor-cli-oauth/models.js.map +1 -1
- package/dist/core/extensions/builtin/cursor-cli-oauth/oauth-login.d.ts +22 -0
- package/dist/core/extensions/builtin/cursor-cli-oauth/oauth-login.d.ts.map +1 -1
- package/dist/core/extensions/builtin/cursor-cli-oauth/oauth-login.js +1 -1
- package/dist/core/extensions/builtin/cursor-cli-oauth/oauth-login.js.map +1 -1
- package/dist/core/extensions/builtin/cursor-cli-oauth/transport.d.ts.map +1 -1
- package/dist/core/extensions/builtin/cursor-cli-oauth/transport.js +2 -13
- package/dist/core/extensions/builtin/cursor-cli-oauth/transport.js.map +1 -1
- package/dist/core/extensions/builtin/terminal/monitor-file-digest.d.ts +3 -0
- package/dist/core/extensions/builtin/terminal/monitor-file-digest.d.ts.map +1 -0
- package/dist/core/extensions/builtin/terminal/monitor-file-digest.js +25 -0
- package/dist/core/extensions/builtin/terminal/monitor-file-digest.js.map +1 -0
- package/dist/core/extensions/builtin/terminal/monitor-file-watch.d.ts +9 -0
- package/dist/core/extensions/builtin/terminal/monitor-file-watch.d.ts.map +1 -0
- package/dist/core/extensions/builtin/terminal/monitor-file-watch.js +33 -0
- package/dist/core/extensions/builtin/terminal/monitor-file-watch.js.map +1 -0
- package/dist/core/extensions/builtin/terminal/monitor-line-buffer.d.ts +6 -0
- package/dist/core/extensions/builtin/terminal/monitor-line-buffer.d.ts.map +1 -0
- package/dist/core/extensions/builtin/terminal/monitor-line-buffer.js +22 -0
- package/dist/core/extensions/builtin/terminal/monitor-line-buffer.js.map +1 -0
- package/dist/core/extensions/builtin/terminal/monitor-registry.d.ts.map +1 -1
- package/dist/core/extensions/builtin/terminal/monitor-registry.js +14 -35
- package/dist/core/extensions/builtin/terminal/monitor-registry.js.map +1 -1
- package/dist/core/extensions/kernel-tools-context.d.ts +13 -0
- package/dist/core/extensions/kernel-tools-context.d.ts.map +1 -0
- package/dist/core/extensions/kernel-tools-context.js +3 -0
- package/dist/core/extensions/kernel-tools-context.js.map +1 -0
- package/dist/core/extensions/runner.d.ts +19 -0
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +103 -1
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +21 -0
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/keybindings.d.ts +5 -0
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/keybindings.js +1 -0
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +9 -17
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/retry-fallback/settings.d.ts +3 -0
- package/dist/core/retry-fallback/settings.d.ts.map +1 -1
- package/dist/core/retry-fallback/settings.js.map +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +1 -0
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-manager.d.ts +30 -1
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +92 -5
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/session-resident-store.d.ts +33 -7
- package/dist/core/session-resident-store.d.ts.map +1 -1
- package/dist/core/session-resident-store.js +163 -14
- package/dist/core/session-resident-store.js.map +1 -1
- package/dist/core/session-write-reservation.d.ts +6 -0
- package/dist/core/session-write-reservation.d.ts.map +1 -1
- package/dist/core/session-write-reservation.js +19 -0
- package/dist/core/session-write-reservation.js.map +1 -1
- package/dist/core/settings-manager.d.ts +35 -1
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +62 -0
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/slash-commands.d.ts.map +1 -1
- package/dist/core/slash-commands.js +2 -1
- package/dist/core/slash-commands.js.map +1 -1
- package/dist/core/tools/index.d.ts +1 -1
- package/dist/core/tools/index.d.ts.map +1 -1
- package/dist/core/tools/index.js +4 -3
- package/dist/core/tools/index.js.map +1 -1
- package/dist/core/tools/read.d.ts +3 -1
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js +16 -2
- package/dist/core/tools/read.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/modes/interactive/components/assistant-render-descriptors.d.ts.map +1 -1
- package/dist/modes/interactive/components/assistant-render-descriptors.js +12 -5
- package/dist/modes/interactive/components/assistant-render-descriptors.js.map +1 -1
- package/dist/modes/interactive/components/extension-input.d.ts +2 -0
- package/dist/modes/interactive/components/extension-input.d.ts.map +1 -1
- package/dist/modes/interactive/components/extension-input.js +5 -0
- package/dist/modes/interactive/components/extension-input.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +19 -2
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +69 -17
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/tips/catalog/session-tips.js +1 -1
- package/dist/modes/interactive/tips/catalog/session-tips.js.map +1 -1
- package/dist/modes/interactive/working-status.d.ts +3 -2
- package/dist/modes/interactive/working-status.d.ts.map +1 -1
- package/dist/modes/interactive/working-status.js +17 -4
- package/dist/modes/interactive/working-status.js.map +1 -1
- package/dist/modes/print-mode.d.ts +1 -1
- package/dist/modes/print-mode.d.ts.map +1 -1
- package/dist/modes/print-mode.js +5 -1
- package/dist/modes/print-mode.js.map +1 -1
- package/dist/modes/rpc/host-watchdog.d.ts.map +1 -1
- package/dist/modes/rpc/host-watchdog.js +5 -24
- package/dist/modes/rpc/host-watchdog.js.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-mode.js +3 -8
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/dist/modes/rpc/session-command-router.d.ts.map +1 -1
- package/dist/modes/rpc/session-command-router.js +3 -0
- package/dist/modes/rpc/session-command-router.js.map +1 -1
- package/dist/modes/rpc/session-worker-client.d.ts +3 -0
- package/dist/modes/rpc/session-worker-client.d.ts.map +1 -1
- package/dist/modes/rpc/session-worker-client.js +17 -6
- package/dist/modes/rpc/session-worker-client.js.map +1 -1
- package/dist/modes/rpc/shutdown.d.ts +3 -0
- package/dist/modes/rpc/shutdown.d.ts.map +1 -0
- package/dist/modes/rpc/shutdown.js +17 -0
- package/dist/modes/rpc/shutdown.js.map +1 -0
- package/docs/extensions.md +5 -2
- package/docs/keybindings.md +1 -0
- package/docs/session-format.md +1 -1
- package/docs/sessions.md +3 -3
- package/docs/settings.md +31 -1
- package/docs/usage.md +1 -1
- package/node_modules/@code-yeongyu/senpi-codemode/CHANGELOG.md +50 -0
- package/node_modules/@code-yeongyu/senpi-codemode/README.md +24 -0
- package/node_modules/@code-yeongyu/senpi-codemode/package.json +4 -4
- package/node_modules/@code-yeongyu/senpi-codemode/src/bridge/http-server.ts +7 -1
- package/node_modules/@code-yeongyu/senpi-codemode/src/bridge/kernel-tools-protocol.ts +85 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/bridge/protocol.ts +6 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/bridges/agent-bridge.ts +30 -11
- package/node_modules/@code-yeongyu/senpi-codemode/src/extension/session-manager.ts +11 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/index.ts +10 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/jl/prelude.jl +46 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/jl/runner.jl +1 -1
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/context-manager.ts +58 -10
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/kernel-contract.ts +12 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/kernel-tools-context.d.ts +13 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/kernel-tools-context.js +7 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/kernel-tools-define.d.ts +10 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/kernel-tools-define.js +12 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/kernel-tools-errors.js +22 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/kernel-tools-errors.ts +26 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/kernel-tools-host.ts +134 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/kernel-tools-naming.js +28 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/kernel-tools-parse.d.ts +5 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/kernel-tools-parse.js +255 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/kernel-tools-pump.js +105 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/kernel-tools-registry.d.ts +27 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/kernel-tools-registry.js +127 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/kernel-tools-schema.js +69 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/kernel-tools-types.ts +42 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/prelude.ts +2 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/worker-core.js +26 -3
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/worker-runtime.js +20 -8
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/worker-slot.ts +6 -1
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/worker-startup.ts +9 -7
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/workpool.js +37 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/kernel-tools-unavailable.ts +5 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/py/kernel.ts +13 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/py/prelude.py +57 -3
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/rb/prelude.rb +13 -2
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/rb/workpool.rb +38 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/shared/subprocess-kernel.ts +13 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/shared/subprocess-queue.ts +9 -1
- package/node_modules/@code-yeongyu/senpi-codemode/src/prompt/eval-prompt-template.ts +4 -2
- package/node_modules/@code-yeongyu/senpi-codemode/src/tool/cell-handler.ts +31 -3
- package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-cell-manager.ts +36 -71
- package/node_modules/@code-yeongyu/senpi-codemode/src/tool/image-resize.ts +52 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/tool/image.ts +37 -72
- package/node_modules/@code-yeongyu/senpi-codemode/src/tool/managed-cell.ts +78 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/tool/render.ts +30 -5
- package/node_modules/@code-yeongyu/senpi-codemode/src/tool/run-eval-cell.ts +52 -30
- package/node_modules/@code-yeongyu/senpi-codemode/src/tool/terminal-snapshot-store.ts +35 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/tool/tool-result-marshal.ts +23 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/tool/types.ts +2 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.js +30 -3
- package/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/agent.d.ts +5 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/agent.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/agent.js +2 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/agent.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/empty-assistant-recovery.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/empty-assistant-recovery.js +51 -12
- package/node_modules/@earendil-works/pi-agent-core/dist/empty-assistant-recovery.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/read.d.ts +3 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/read.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/read.js +18 -3
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/read.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/read-folders/brace-scanner.d.ts +4 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/read-folders/brace-scanner.d.ts.map +1 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/read-folders/brace-scanner.js +268 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/read-folders/brace-scanner.js.map +1 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/read-folders/header-protection.d.ts +18 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/read-folders/header-protection.d.ts.map +1 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/read-folders/header-protection.js +69 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/read-folders/header-protection.js.map +1 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/read-folders/index.d.ts +27 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/read-folders/index.d.ts.map +1 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/read-folders/index.js +118 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/read-folders/index.js.map +1 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/read-folders/lexical-context.d.ts +21 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/read-folders/lexical-context.d.ts.map +1 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/read-folders/lexical-context.js +24 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/read-folders/lexical-context.js.map +1 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/read-folders/lexical-spans.d.ts +12 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/read-folders/lexical-spans.d.ts.map +1 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/read-folders/lexical-spans.js +92 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/read-folders/lexical-spans.js.map +1 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/read-folders/types.d.ts +47 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/read-folders/types.d.ts.map +1 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/read-folders/types.js +8 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/read-folders/types.js.map +1 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/segmented-read-view.d.ts +52 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/segmented-read-view.d.ts.map +1 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/segmented-read-view.js +155 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/segmented-read-view.js.map +1 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/index.d.ts +4 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/index.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/index.js +3 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/index.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/stream-throughput-watchdog.d.ts +101 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/stream-throughput-watchdog.d.ts.map +1 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/stream-throughput-watchdog.js +178 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/stream-throughput-watchdog.js.map +1 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/types.d.ts +9 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/types.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/types.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
- package/node_modules/@earendil-works/pi-ai/dist/index.d.ts +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/index.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/index.js +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/index.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/alibaba-token-plan.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/amazon-bedrock.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/fireworks.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/qwen-token-plan.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/utils/empty-response-errors.d.ts +15 -0
- package/node_modules/@earendil-works/pi-ai/dist/utils/empty-response-errors.d.ts.map +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/utils/empty-response-errors.js +15 -0
- package/node_modules/@earendil-works/pi-ai/dist/utils/empty-response-errors.js.map +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/utils/retry.d.ts +24 -0
- package/node_modules/@earendil-works/pi-ai/dist/utils/retry.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/utils/retry.js +92 -0
- package/node_modules/@earendil-works/pi-ai/dist/utils/retry.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/package.json +2 -2
- package/node_modules/@earendil-works/pi-pty/package.json +1 -1
- package/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
- package/node_modules/@earendil-works/pi-tui/package.json +1 -1
- package/package.json +7 -7
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Terminal error texts for assistant turns that ended without deliverable content. The stream
|
|
3
|
+
* wrapper in pi-agent-core produces them; the turn-retry classifier in ./retry.ts consumes them,
|
|
4
|
+
* so the two halves share one definition.
|
|
5
|
+
*
|
|
6
|
+
* "twice" variants: the wrapper already spent its own silent retry on an attempt that never
|
|
7
|
+
* forwarded anything, so the turn stays terminal. "after streaming thinking" variants: the attempt
|
|
8
|
+
* had already forwarded reasoning live and cannot be replayed inside the stream, so the turn-level
|
|
9
|
+
* retry owns the recovery.
|
|
10
|
+
*/
|
|
11
|
+
export declare const EMPTY_RESPONSE_ERROR = "Model returned an empty response twice";
|
|
12
|
+
export declare const EMPTY_TOOL_USE_ERROR = "Model returned tool_use without a tool call twice";
|
|
13
|
+
export declare const FORWARDED_EMPTY_RESPONSE_ERROR = "Model returned an empty response after streaming thinking";
|
|
14
|
+
export declare const FORWARDED_EMPTY_TOOL_USE_ERROR = "Model returned tool_use without a tool call after streaming thinking";
|
|
15
|
+
//# sourceMappingURL=empty-response-errors.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"empty-response-errors.d.ts","sourceRoot":"","sources":["../../src/utils/empty-response-errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,eAAO,MAAM,oBAAoB,2CAA2C,CAAC;AAC7E,eAAO,MAAM,oBAAoB,sDAAsD,CAAC;AACxF,eAAO,MAAM,8BAA8B,8DAA8D,CAAC;AAC1G,eAAO,MAAM,8BAA8B,yEAAyE,CAAC"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Terminal error texts for assistant turns that ended without deliverable content. The stream
|
|
3
|
+
* wrapper in pi-agent-core produces them; the turn-retry classifier in ./retry.ts consumes them,
|
|
4
|
+
* so the two halves share one definition.
|
|
5
|
+
*
|
|
6
|
+
* "twice" variants: the wrapper already spent its own silent retry on an attempt that never
|
|
7
|
+
* forwarded anything, so the turn stays terminal. "after streaming thinking" variants: the attempt
|
|
8
|
+
* had already forwarded reasoning live and cannot be replayed inside the stream, so the turn-level
|
|
9
|
+
* retry owns the recovery.
|
|
10
|
+
*/
|
|
11
|
+
export const EMPTY_RESPONSE_ERROR = "Model returned an empty response twice";
|
|
12
|
+
export const EMPTY_TOOL_USE_ERROR = "Model returned tool_use without a tool call twice";
|
|
13
|
+
export const FORWARDED_EMPTY_RESPONSE_ERROR = "Model returned an empty response after streaming thinking";
|
|
14
|
+
export const FORWARDED_EMPTY_TOOL_USE_ERROR = "Model returned tool_use without a tool call after streaming thinking";
|
|
15
|
+
//# sourceMappingURL=empty-response-errors.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"empty-response-errors.js","sourceRoot":"","sources":["../../src/utils/empty-response-errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,wCAAwC,CAAC;AAC7E,MAAM,CAAC,MAAM,oBAAoB,GAAG,mDAAmD,CAAC;AACxF,MAAM,CAAC,MAAM,8BAA8B,GAAG,2DAA2D,CAAC;AAC1G,MAAM,CAAC,MAAM,8BAA8B,GAAG,sEAAsE,CAAC","sourcesContent":["/**\n * Terminal error texts for assistant turns that ended without deliverable content. The stream\n * wrapper in pi-agent-core produces them; the turn-retry classifier in ./retry.ts consumes them,\n * so the two halves share one definition.\n *\n * \"twice\" variants: the wrapper already spent its own silent retry on an attempt that never\n * forwarded anything, so the turn stays terminal. \"after streaming thinking\" variants: the attempt\n * had already forwarded reasoning live and cannot be replayed inside the stream, so the turn-level\n * retry owns the recovery.\n */\nexport const EMPTY_RESPONSE_ERROR = \"Model returned an empty response twice\";\nexport const EMPTY_TOOL_USE_ERROR = \"Model returned tool_use without a tool call twice\";\nexport const FORWARDED_EMPTY_RESPONSE_ERROR = \"Model returned an empty response after streaming thinking\";\nexport const FORWARDED_EMPTY_TOOL_USE_ERROR = \"Model returned tool_use without a tool call after streaming thinking\";\n"]}
|
|
@@ -90,6 +90,30 @@ export declare function retryAssistantCall(produce: () => Promise<AssistantMessa
|
|
|
90
90
|
*/
|
|
91
91
|
export declare function isRetryableAssistantError(message: AssistantMessage): boolean;
|
|
92
92
|
export declare function isProviderStreamStallError(message: AssistantMessage): boolean;
|
|
93
|
+
export interface ProviderStallDescriptionOptions {
|
|
94
|
+
/** Same-model attempts already spent on this turn. */
|
|
95
|
+
attempts?: number;
|
|
96
|
+
/** Selector of the model that stalled, for example `anthropic/claude-opus-5`. */
|
|
97
|
+
model?: string;
|
|
98
|
+
/**
|
|
99
|
+
* Appends the "what to do next" sentence. Omit it while the turn can still
|
|
100
|
+
* recover: a retry in flight is not the moment to tell the user to act.
|
|
101
|
+
*/
|
|
102
|
+
recovery?: "no-fallback-configured" | "chain-exhausted";
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Plain-language replacement for a stall watchdog's own `Error.message`.
|
|
106
|
+
*
|
|
107
|
+
* The watchdog wording (`Provider stream start timed out after 180000ms ...`)
|
|
108
|
+
* is a classifier token - {@link isProviderStreamStallError} and the turn retry
|
|
109
|
+
* gate both match on it - so it must stay on the assistant message. It was also
|
|
110
|
+
* the only thing the user ever saw when a turn died on a stall, which explains
|
|
111
|
+
* nothing and names no next step (senpi#1740). Every user-facing surface routes
|
|
112
|
+
* the message through here first and falls back to the raw text for anything
|
|
113
|
+
* that is not a stall.
|
|
114
|
+
*/
|
|
115
|
+
export declare function describeProviderStallForUser(errorMessage: string | undefined, options?: ProviderStallDescriptionOptions): string | undefined;
|
|
116
|
+
export declare function isProviderStreamThroughputDegradedError(message: AssistantMessage): boolean;
|
|
93
117
|
/**
|
|
94
118
|
* Classifies timeout failures that originate from the provider stream or its
|
|
95
119
|
* transport. Transport timeouts may arrive as `aborted`; stream watchdog
|
|
@@ -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;
|
|
1
|
+
{"version":3,"file":"retry.d.ts","sourceRoot":"","sources":["../../src/utils/retry.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AA+JpD;;;;;;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,EACf,YAAY,EAAE,MAAM,KAChB,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC1B,mFAAmF;IACnF,mBAAmB,CAAC,EAAE,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACjD,mFAAmF;IACnF,eAAe,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACnG;AA0BD;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,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MAAM,GAAG,OAAO,CAErE;AAED;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CAAC,YAAY,EAAE,MAAM,GAAG,eAAe,GAAG,WAAW,GAAG,SAAS,CAKpG"}
|
|
@@ -1,6 +1,10 @@
|
|
|
1
|
+
import { FORWARDED_EMPTY_RESPONSE_ERROR, FORWARDED_EMPTY_TOOL_USE_ERROR } from "./empty-response-errors.js";
|
|
1
2
|
function buildProviderErrorPattern(patterns) {
|
|
2
3
|
return new RegExp(patterns.join("|"), "i");
|
|
3
4
|
}
|
|
5
|
+
function escapeRegExp(text) {
|
|
6
|
+
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
7
|
+
}
|
|
4
8
|
const NON_RETRYABLE_PROVIDER_ERROR_PATTERN = buildProviderErrorPattern([
|
|
5
9
|
// OpenCode Go/free-tier limits returned as 429 JSON error types by OpenCode's
|
|
6
10
|
// Zen API. These are subscription/account limits, not transient throttles.
|
|
@@ -114,6 +118,16 @@ const RETRYABLE_PROVIDER_ERROR_PATTERN = buildProviderErrorPattern([
|
|
|
114
118
|
// fallback chain unwedge such a session instead of dead-ending it. The trailing
|
|
115
119
|
// backtick keeps the pattern on Anthropic's pairing-error template.
|
|
116
120
|
"was found without a corresponding `",
|
|
121
|
+
// An empty stop or tool_use-without-tool-call on a model whose reasoning had already streamed
|
|
122
|
+
// live. The stream-level wrapper (pi-agent-core empty-assistant-recovery) cannot replay such an
|
|
123
|
+
// attempt, so it ends the turn with these exact texts for the turn retry to re-request; the
|
|
124
|
+
// "twice" variants are deliberately absent because the wrapper already spent its own retry.
|
|
125
|
+
escapeRegExp(FORWARDED_EMPTY_RESPONSE_ERROR),
|
|
126
|
+
escapeRegExp(FORWARDED_EMPTY_TOOL_USE_ERROR),
|
|
127
|
+
// Agent-loop throughput watchdog verdict (#1739). The upstream is answering,
|
|
128
|
+
// just uselessly slowly, so the turn must move - to the fallback chain, not
|
|
129
|
+
// through the same-model budget (see isProviderStreamThroughputDegradedError).
|
|
130
|
+
"provider stream throughput degraded",
|
|
117
131
|
// gRPC based providers (e.g. NVIDIA NIM)
|
|
118
132
|
"ResourceExhausted",
|
|
119
133
|
// Claude Agent SDK session.json lock contention. A second stream/resume
|
|
@@ -313,6 +327,84 @@ const PROVIDER_TRANSPORT_TIMEOUT_ERROR_PATTERN = /^Request timed out\.?$/i;
|
|
|
313
327
|
export function isProviderStreamStallError(message) {
|
|
314
328
|
return message.stopReason === "error" && PROVIDER_STREAM_STALL_ERROR_PATTERN.test(message.errorMessage ?? "");
|
|
315
329
|
}
|
|
330
|
+
/** One row per stall watchdog: how to read its message, and how to explain it. */
|
|
331
|
+
const PROVIDER_STALL_PHASES = [
|
|
332
|
+
{
|
|
333
|
+
pattern: /^Provider stream start timed out after (\d+)ms/i,
|
|
334
|
+
symptom: "accepted the request but never started sending a response",
|
|
335
|
+
setting: "retry.provider.streamStartTimeoutMs",
|
|
336
|
+
},
|
|
337
|
+
{
|
|
338
|
+
pattern: /^Idle timeout waiting for provider stream after (\d+)ms/i,
|
|
339
|
+
symptom: "started the response and then went silent",
|
|
340
|
+
setting: "retry.provider.timeoutMs",
|
|
341
|
+
},
|
|
342
|
+
{
|
|
343
|
+
pattern: /^WebSocket liveness timeout after (\d+)ms/i,
|
|
344
|
+
symptom: "stopped answering connection health checks",
|
|
345
|
+
},
|
|
346
|
+
{
|
|
347
|
+
pattern: /^Provider stream stalled after the last output item: response\.completed timed out after (\d+)ms/i,
|
|
348
|
+
symptom: "finished its output but never sent the end-of-response event",
|
|
349
|
+
},
|
|
350
|
+
];
|
|
351
|
+
function formatStallDuration(timeoutMs) {
|
|
352
|
+
if (timeoutMs < 1000)
|
|
353
|
+
return `${timeoutMs}ms`;
|
|
354
|
+
if (timeoutMs < 120_000)
|
|
355
|
+
return `${Math.round(timeoutMs / 100) / 10}s`;
|
|
356
|
+
return `${Math.round(timeoutMs / 6000) / 10}m`;
|
|
357
|
+
}
|
|
358
|
+
/**
|
|
359
|
+
* Plain-language replacement for a stall watchdog's own `Error.message`.
|
|
360
|
+
*
|
|
361
|
+
* The watchdog wording (`Provider stream start timed out after 180000ms ...`)
|
|
362
|
+
* is a classifier token - {@link isProviderStreamStallError} and the turn retry
|
|
363
|
+
* gate both match on it - so it must stay on the assistant message. It was also
|
|
364
|
+
* the only thing the user ever saw when a turn died on a stall, which explains
|
|
365
|
+
* nothing and names no next step (senpi#1740). Every user-facing surface routes
|
|
366
|
+
* the message through here first and falls back to the raw text for anything
|
|
367
|
+
* that is not a stall.
|
|
368
|
+
*/
|
|
369
|
+
export function describeProviderStallForUser(errorMessage, options = {}) {
|
|
370
|
+
if (!errorMessage)
|
|
371
|
+
return undefined;
|
|
372
|
+
for (const { pattern, symptom, setting } of PROVIDER_STALL_PHASES) {
|
|
373
|
+
const match = pattern.exec(errorMessage);
|
|
374
|
+
if (!match)
|
|
375
|
+
continue;
|
|
376
|
+
const subject = options.model ? `The provider for ${options.model}` : "The provider";
|
|
377
|
+
const duration = formatStallDuration(Number(match[1]));
|
|
378
|
+
const sentences = [`${subject} ${symptom} within ${duration}, so the request was cancelled.`];
|
|
379
|
+
const attempts = options.attempts ?? 0;
|
|
380
|
+
if (attempts > 0) {
|
|
381
|
+
sentences.push(`Retried ${attempts} time${attempts === 1 ? "" : "s"} on the same model with the same result.`);
|
|
382
|
+
}
|
|
383
|
+
if (options.recovery) {
|
|
384
|
+
const raise = setting ? `, or raise ${setting} in settings (0 disables the bound)` : "";
|
|
385
|
+
const lead = options.recovery === "no-fallback-configured"
|
|
386
|
+
? "No fallback model is configured for it, so nothing could take the turn over: run /fallback to add one"
|
|
387
|
+
: "Every model in its fallback chain was tried as well: run /fallback to review the chain";
|
|
388
|
+
sentences.push(`${lead}, send the message again${raise}.`);
|
|
389
|
+
}
|
|
390
|
+
return sentences.join(" ");
|
|
391
|
+
}
|
|
392
|
+
return undefined;
|
|
393
|
+
}
|
|
394
|
+
/**
|
|
395
|
+
* Matches the agent-loop throughput watchdog verdict ("Provider stream
|
|
396
|
+
* throughput degraded: <n> tok/s over <n>s (floor <n> tok/s)", optionally
|
|
397
|
+
* followed by the settings hint). Deliberately NOT part of the stall pattern
|
|
398
|
+
* above: a stall is silence, which a same-model retry can genuinely fix, while
|
|
399
|
+
* a degraded stream is an upstream that answers too slowly for replaying the
|
|
400
|
+
* same payload to help. Callers use this to skip the same-model retry budget
|
|
401
|
+
* and consult the fallback chain immediately.
|
|
402
|
+
*/
|
|
403
|
+
const PROVIDER_STREAM_THROUGHPUT_DEGRADED_ERROR_PATTERN = /^Provider stream throughput degraded: \d+(?:\.\d+)? tok\/s over \d+(?:\.\d+)?s \(floor \d+(?:\.\d+)? tok\/s\)(?: \([^)]*\))?$/i;
|
|
404
|
+
export function isProviderStreamThroughputDegradedError(message) {
|
|
405
|
+
return (message.stopReason === "error" &&
|
|
406
|
+
PROVIDER_STREAM_THROUGHPUT_DEGRADED_ERROR_PATTERN.test(message.errorMessage ?? ""));
|
|
407
|
+
}
|
|
316
408
|
/**
|
|
317
409
|
* Classifies timeout failures that originate from the provider stream or its
|
|
318
410
|
* transport. Transport timeouts may arrive as `aborted`; stream watchdog
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"retry.js","sourceRoot":"","sources":["../../src/utils/retry.ts"],"names":[],"mappings":"AAEA,SAAS,yBAAyB,CAAC,QAA2B;IAC7D,OAAO,IAAI,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC;AAC5C,CAAC;AAED,MAAM,oCAAoC,GAAG,yBAAyB,CAAC;IACtE,8EAA8E;IAC9E,2EAA2E;IAC3E,mBAAmB;IACnB,qBAAqB;IAErB,6EAA6E;IAC7E,yDAAyD;IACzD,6BAA6B;IAC7B,mBAAmB;IAEnB,4EAA4E;IAC5E,4EAA4E;IAC5E,oBAAoB;IACpB,eAAe;IACf,gBAAgB;IAChB,SAAS;IAET,4EAA4E;IAC5E,0EAA0E;IAC1E,0EAA0E;IAC1E,2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AC,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\";\n\nfunction buildProviderErrorPattern(patterns: readonly string[]): RegExp {\n\treturn new RegExp(patterns.join(\"|\"), \"i\");\n}\n\nconst NON_RETRYABLE_PROVIDER_ERROR_PATTERN = buildProviderErrorPattern([\n\t// OpenCode Go/free-tier limits returned as 429 JSON error types by OpenCode's\n\t// Zen API. These are subscription/account limits, not transient throttles.\n\t\"GoUsageLimitError\",\n\t\"FreeUsageLimitError\",\n\n\t// OpenCode Go subscription-limit text asks users to enable available-balance\n\t// usage after rolling/weekly/monthly limits are reached.\n\t\"Monthly usage limit reached\",\n\t\"available balance\",\n\n\t// Generic quota/budget/billing exhaustion. `insufficient_quota` is OpenAI's\n\t// quota/billing error code; the other strings cover common gateway wording.\n\t\"insufficient_quota\",\n\t\"out of budget\",\n\t\"quota exceeded\",\n\t\"billing\",\n\n\t// Anthropic Console credit exhaustion: a 429 rate_limit_error whose details\n\t// carry error_code credits_required (\"Usage credits are required for this\n\t// model.\"). The account is dead until the user buys credits or raises the\n\t// spend limit, so same-model retries can never recover it.\n\t\"credits_required\",\n\t\"credits are required\",\n\n\t// Request-shape rejections: the provider refused the payload we built, not the\n\t// work it describes. Gateways wrap these in whatever status they like — the\n\t// observed Apitopia/Kimi case arrives as `500 server_error: Invalid request:\n\t// tools.function.parameters.type is required and must be \"object\"` — so the\n\t// status text alone would classify a permanent failure as transient. The same\n\t// bytes are rejected on every attempt and on every fallback model, so retrying\n\t// can only burn the turn. Anchored on the `tools[...]`/`functions[...]` request\n\t// path so unrelated prose mentioning tools stays retryable.\n\t\"invalid request: tools\\\\.\",\n\t\"invalid request: functions\\\\.\",\n\t\"tools\\\\.[^ ]*function\\\\.parameters\",\n\t\"tools\\\\.\\\\d+\\\\.function\\\\.parameters\",\n\t\"invalid tool schema\",\n]);\n\nconst RETRYABLE_PROVIDER_ERROR_PATTERN = buildProviderErrorPattern([\n\t// Local credential/auth sidecar lock exhaustion is infrastructure contention,\n\t// not a provider failure and must stay on the transient retry path.\n\t\"Credential store is busy: lock\",\n\t// Generic provider load, HTTP status, and server-side transient failures.\n\t\"overloaded\",\n\t\"rate.?limit\",\n\t\"too many requests\",\n\t\"429\",\n\t\"500\",\n\t\"502\",\n\t\"503\",\n\t\"504\",\n\t// Cloudflare 522 (Connection timed out): origin stopped responding; transient\n\t// like the other 5xx gateway statuses, surfaced as \"Error: error code: 522\".\n\t\"522\",\n\t\"524\",\n\t\"service.?unavailable\",\n\t\"server.?error\",\n\t\"internal.?error\",\n\n\t// Wrapper/provider text for transient upstream failures, including OpenRouter\n\t// \"Provider returned error\" responses (#2264).\n\t\"provider.?returned.?error\",\n\t\"exceeded request buffer limit while retrying upstream\",\n\n\t// Network, proxy, and fetch transport failures. This includes OpenAI Codex\n\t// raw-fetch failures such as \"upstream connect\", \"connection refused\", and\n\t// \"reset before headers\" (#733), plus OpenRouter connection drops (#3317).\n\t\"network.?error\",\n\t\"connection.?error\",\n\t\"connection.?refused\",\n\t\"connection.?lost\",\n\t\"other side closed\",\n\t\"fetch failed\",\n\t\"getaddrinfo\",\n\t\"ENOTFOUND\",\n\t\"EAI_AGAIN\",\n\t\"upstream.?connect\",\n\t\"upstream.?unavailable\",\n\t\"reset before headers\",\n\t\"socket hang up\",\n\t\"socket connection was closed\",\n\t\"timed? out\",\n\t\"timeout\",\n\t\"terminated\",\n\n\t// WebSocket transports can report close/error text instead of HTTP/fetch text.\n\t\"websocket.?closed\",\n\t\"websocket.?error\",\n\n\t// Premature stream endings from SDKs and transports. Anthropic can throw\n\t// \"stream ended without ...\" and \"Anthropic stream ended before message_stop\"\n\t// (#4433); Bedrock/Smithy can throw an HTTP/2 no-response error (#3594).\n\t\"ended without\",\n\t\"stream ended before message_stop\",\n\t\"stream ended before a terminal response event\",\n\t\"http2 request did not get a response\",\n\n\t// Provider-requested retry delay cap failures should flow through the outer\n\t// retry policy so callers can surface/abort the backoff (#1123).\n\t\"retry delay\",\n\n\t// Explicit retry guidance emitted mid-stream by OpenAI Responses and Bedrock\n\t// stream exceptions (#6019).\n\t\"you can retry your request\",\n\t\"try your request again\",\n\t\"please retry your request\",\n\n\t// Gateway/proxy-side rejection of the whole model request, e.g. \"Error: The\n\t// model request was rejected. Check the request and try again.\" (observed in a\n\t// live session, 2026-08-11). Coupling the rejection sentence to its explicit\n\t// retry instruction keeps unrelated permission, request-shape, and content-\n\t// policy rejections terminal while the bounded retry policy absorbs this\n\t// transient wrapper wording.\n\t\"the model request was rejected\\\\.\\\\s*check the request and try again\\\\.?\",\n\n\t// Anthropic server-tool pairing rejections, e.g. \"`web_search` tool use with id\n\t// `srvtoolu_...` was found without a corresponding `web_search_tool_result`\n\t// block\". A turn closed before its deferred server tool could answer leaves\n\t// the unpairable half in history, and replaying it 400s every later request.\n\t// The Anthropic request builder repairs the replayed history, so a retry sends\n\t// a valid payload; keeping the class retryable is what lets retry and the model\n\t// fallback chain unwedge such a session instead of dead-ending it. The trailing\n\t// backtick keeps the pattern on Anthropic's pairing-error template.\n\t\"was found without a corresponding `\",\n\n\t// 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/**\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":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"../types.ts\";\nimport { FORWARDED_EMPTY_RESPONSE_ERROR, FORWARDED_EMPTY_TOOL_USE_ERROR } from \"./empty-response-errors.ts\";\n\nfunction buildProviderErrorPattern(patterns: readonly string[]): RegExp {\n\treturn new RegExp(patterns.join(\"|\"), \"i\");\n}\n\nfunction escapeRegExp(text: string): string {\n\treturn text.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nconst NON_RETRYABLE_PROVIDER_ERROR_PATTERN = buildProviderErrorPattern([\n\t// OpenCode Go/free-tier limits returned as 429 JSON error types by OpenCode's\n\t// Zen API. These are subscription/account limits, not transient throttles.\n\t\"GoUsageLimitError\",\n\t\"FreeUsageLimitError\",\n\n\t// OpenCode Go subscription-limit text asks users to enable available-balance\n\t// usage after rolling/weekly/monthly limits are reached.\n\t\"Monthly usage limit reached\",\n\t\"available balance\",\n\n\t// Generic quota/budget/billing exhaustion. `insufficient_quota` is OpenAI's\n\t// quota/billing error code; the other strings cover common gateway wording.\n\t\"insufficient_quota\",\n\t\"out of budget\",\n\t\"quota exceeded\",\n\t\"billing\",\n\n\t// Anthropic Console credit exhaustion: a 429 rate_limit_error whose details\n\t// carry error_code credits_required (\"Usage credits are required for this\n\t// model.\"). The account is dead until the user buys credits or raises the\n\t// spend limit, so same-model retries can never recover it.\n\t\"credits_required\",\n\t\"credits are required\",\n\n\t// Request-shape rejections: the provider refused the payload we built, not the\n\t// work it describes. Gateways wrap these in whatever status they like — the\n\t// observed Apitopia/Kimi case arrives as `500 server_error: Invalid request:\n\t// tools.function.parameters.type is required and must be \"object\"` — so the\n\t// status text alone would classify a permanent failure as transient. The same\n\t// bytes are rejected on every attempt and on every fallback model, so retrying\n\t// can only burn the turn. Anchored on the `tools[...]`/`functions[...]` request\n\t// path so unrelated prose mentioning tools stays retryable.\n\t\"invalid request: tools\\\\.\",\n\t\"invalid request: functions\\\\.\",\n\t\"tools\\\\.[^ ]*function\\\\.parameters\",\n\t\"tools\\\\.\\\\d+\\\\.function\\\\.parameters\",\n\t\"invalid tool schema\",\n]);\n\nconst RETRYABLE_PROVIDER_ERROR_PATTERN = buildProviderErrorPattern([\n\t// Local credential/auth sidecar lock exhaustion is infrastructure contention,\n\t// not a provider failure and must stay on the transient retry path.\n\t\"Credential store is busy: lock\",\n\t// Generic provider load, HTTP status, and server-side transient failures.\n\t\"overloaded\",\n\t\"rate.?limit\",\n\t\"too many requests\",\n\t\"429\",\n\t\"500\",\n\t\"502\",\n\t\"503\",\n\t\"504\",\n\t// Cloudflare 522 (Connection timed out): origin stopped responding; transient\n\t// like the other 5xx gateway statuses, surfaced as \"Error: error code: 522\".\n\t\"522\",\n\t\"524\",\n\t\"service.?unavailable\",\n\t\"server.?error\",\n\t\"internal.?error\",\n\n\t// Wrapper/provider text for transient upstream failures, including OpenRouter\n\t// \"Provider returned error\" responses (#2264).\n\t\"provider.?returned.?error\",\n\t\"exceeded request buffer limit while retrying upstream\",\n\n\t// Network, proxy, and fetch transport failures. This includes OpenAI Codex\n\t// raw-fetch failures such as \"upstream connect\", \"connection refused\", and\n\t// \"reset before headers\" (#733), plus OpenRouter connection drops (#3317).\n\t\"network.?error\",\n\t\"connection.?error\",\n\t\"connection.?refused\",\n\t\"connection.?lost\",\n\t\"other side closed\",\n\t\"fetch failed\",\n\t\"getaddrinfo\",\n\t\"ENOTFOUND\",\n\t\"EAI_AGAIN\",\n\t\"upstream.?connect\",\n\t\"upstream.?unavailable\",\n\t\"reset before headers\",\n\t\"socket hang up\",\n\t\"socket connection was closed\",\n\t\"timed? out\",\n\t\"timeout\",\n\t\"terminated\",\n\n\t// WebSocket transports can report close/error text instead of HTTP/fetch text.\n\t\"websocket.?closed\",\n\t\"websocket.?error\",\n\n\t// Premature stream endings from SDKs and transports. Anthropic can throw\n\t// \"stream ended without ...\" and \"Anthropic stream ended before message_stop\"\n\t// (#4433); Bedrock/Smithy can throw an HTTP/2 no-response error (#3594).\n\t\"ended without\",\n\t\"stream ended before message_stop\",\n\t\"stream ended before a terminal response event\",\n\t\"http2 request did not get a response\",\n\n\t// Provider-requested retry delay cap failures should flow through the outer\n\t// retry policy so callers can surface/abort the backoff (#1123).\n\t\"retry delay\",\n\n\t// Explicit retry guidance emitted mid-stream by OpenAI Responses and Bedrock\n\t// stream exceptions (#6019).\n\t\"you can retry your request\",\n\t\"try your request again\",\n\t\"please retry your request\",\n\n\t// Gateway/proxy-side rejection of the whole model request, e.g. \"Error: The\n\t// model request was rejected. Check the request and try again.\" (observed in a\n\t// live session, 2026-08-11). Coupling the rejection sentence to its explicit\n\t// retry instruction keeps unrelated permission, request-shape, and content-\n\t// policy rejections terminal while the bounded retry policy absorbs this\n\t// transient wrapper wording.\n\t\"the model request was rejected\\\\.\\\\s*check the request and try again\\\\.?\",\n\n\t// Anthropic server-tool pairing rejections, e.g. \"`web_search` tool use with id\n\t// `srvtoolu_...` was found without a corresponding `web_search_tool_result`\n\t// block\". A turn closed before its deferred server tool could answer leaves\n\t// the unpairable half in history, and replaying it 400s every later request.\n\t// The Anthropic request builder repairs the replayed history, so a retry sends\n\t// a valid payload; keeping the class retryable is what lets retry and the model\n\t// fallback chain unwedge such a session instead of dead-ending it. The trailing\n\t// backtick keeps the pattern on Anthropic's pairing-error template.\n\t\"was found without a corresponding `\",\n\n\t// An empty stop or tool_use-without-tool-call on a model whose reasoning had already streamed\n\t// live. The stream-level wrapper (pi-agent-core empty-assistant-recovery) cannot replay such an\n\t// attempt, so it ends the turn with these exact texts for the turn retry to re-request; the\n\t// \"twice\" variants are deliberately absent because the wrapper already spent its own retry.\n\tescapeRegExp(FORWARDED_EMPTY_RESPONSE_ERROR),\n\tescapeRegExp(FORWARDED_EMPTY_TOOL_USE_ERROR),\n\n\t// Agent-loop throughput watchdog verdict (#1739). The upstream is answering,\n\t// just uselessly slowly, so the turn must move - to the fallback chain, not\n\t// through the same-model budget (see isProviderStreamThroughputDegradedError).\n\t\"provider stream throughput degraded\",\n\n\t// gRPC based providers (e.g. NVIDIA NIM)\n\t\"ResourceExhausted\",\n\n\t// Claude Agent SDK session.json lock contention. A second stream/resume\n\t// hits proper-lockfile while the previous subprocess still holds the file.\n\t// Same-process retry recovers; hopping providers cannot release that lock.\n\t\"Lock file is already being held\",\n]);\n\n/**\n * Retry policy: bounded attempts with exponential backoff (`baseDelayMs * 2^(attempt-1)`).\n * `maxAgentDelayMs` caps each computed delay and defaults to 60 seconds.\n * Matches `settings.retry` (`enabled`, `maxRetries`, `baseDelayMs`, `maxAgentDelayMs`) in coding-agent; kept\n * here so the classifier and the policy-driven retry loop live together and stay reusable\n * by the SDK and other callers.\n */\nexport interface RetryPolicy {\n\tenabled: boolean;\n\t/** Max retry attempts (0 = no retries). The initial call never counts as a retry. */\n\tmaxRetries: number;\n\t/** Base delay in ms. Per-attempt delay is `baseDelayMs * 2^(attempt-1)` before jitter. */\n\tbaseDelayMs: number;\n\t/** Optional cap for agent-level retry delays in ms. Defaults to 60 seconds. */\n\tmaxAgentDelayMs?: number;\n\t/** Injectable source used for Codex-style +/-10% backoff jitter. */\n\trandom?: () => number;\n}\n\nexport const DEFAULT_MAX_AGENT_RETRY_DELAY_MS = 60_000;\n\n/**\n * Per-attempt backoff: `baseDelayMs * 2^(attempt-1)`, jittered by +/-10% through the\n * injectable `random` source, then clamped to `maxAgentDelayMs` (60s by default). The\n * jitter runs before the clamp so a capped delay stays exactly at the cap instead of\n * scattering above it, and the safe-integer guard keeps a large `attempt` from producing\n * `Infinity` before the clamp.\n */\nexport function retryDelayMs(\n\tpolicy: Pick<RetryPolicy, \"baseDelayMs\" | \"maxAgentDelayMs\" | \"random\">,\n\tattempt: number,\n): number {\n\tconst scheduledDelayMs = policy.baseDelayMs * 2 ** Math.max(0, attempt - 1);\n\tconst sample = Math.min(1, Math.max(0, (policy.random ?? Math.random)()));\n\tconst jitteredDelayMs = Math.round(scheduledDelayMs * (0.9 + sample * 0.2));\n\tconst safeDelay = Number.isSafeInteger(jitteredDelayMs) ? jitteredDelayMs : Number.MAX_SAFE_INTEGER;\n\treturn Math.min(safeDelay, policy.maxAgentDelayMs ?? DEFAULT_MAX_AGENT_RETRY_DELAY_MS);\n}\n\n/** Optional callbacks emitted by {@link retryAssistantCall} around each retry. */\nexport interface RetryCallbacks {\n\t/** Emitted before the backoff sleep of each retry attempt (1-indexed). */\n\tonRetryScheduled?: (\n\t\tattempt: number,\n\t\tmaxAttempts: number,\n\t\tdelayMs: number,\n\t\terrorMessage: string,\n\t) => void | Promise<void>;\n\t/** Emitted after the backoff sleep, immediately before the retried call starts. */\n\tonRetryAttemptStart?: () => void | Promise<void>;\n\t/** Emitted once when the loop ends: success if a later call completed normally. */\n\tonRetryFinished?: (success: boolean, attempt: number, finalError?: string) => void | Promise<void>;\n}\n\nclass RetrySleepAbortError extends Error {\n\tconstructor() {\n\t\tsuper(\"Aborted\");\n\t}\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(new RetrySleepAbortError());\n\t\t\treturn;\n\t\t}\n\t\tconst timeout = setTimeout(resolve, ms);\n\t\tsignal?.addEventListener(\n\t\t\t\"abort\",\n\t\t\t() => {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t\treject(new RetrySleepAbortError());\n\t\t\t},\n\t\t\t{ once: true },\n\t\t);\n\t});\n}\n\n/**\n * Run a producer that signals failure by THROWING, with the same bounded\n * backoff, abort, and callback semantics as {@link retryAssistantCall}.\n *\n * `retryAssistantCall` is value-based: its producer reports failure by resolving\n * an `AssistantMessage` with `stopReason: \"error\"`. Callers that instead reject\n * (compaction summarization, and any other request pipeline that throws) need\n * the identical retry policy without reshaping their failures into assistant\n * messages first, so both live here and share one implementation of the delay,\n * abort, and callback contract.\n *\n * Behavior:\n * - A resolved value is returned immediately.\n * - A throw that `isRetryable` rejects is rethrown at once: deterministic\n * failures never spend a retry.\n * - Otherwise the call is retried up to `policy.maxRetries` times with the same\n * exponential backoff (`baseDelayMs * 2^(attempt-1)`), rethrowing the final\n * error when the budget is exhausted.\n * - An abort during the backoff sleep stops the loop and rethrows; unlike the\n * assistant-message path there is no aborted value to normalize to.\n *\n * When `policy` is undefined or disabled the producer runs exactly once and its\n * error propagates unchanged.\n */\nexport async function retryTransientCall<T>(\n\tproduce: () => Promise<T>,\n\tisRetryable: (error: unknown) => boolean,\n\tpolicy: RetryPolicy | undefined,\n\tsignal: AbortSignal | undefined,\n\tcallbacks?: RetryCallbacks,\n): Promise<T> {\n\tconst maxAttempts = policy?.enabled ? policy.maxRetries : 0;\n\n\tlet attempt = 0;\n\tlet lastRetry: { attempt: number; errorMessage: string } | undefined;\n\tfor (;;) {\n\t\ttry {\n\t\t\tconst value = await produce();\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(true, lastRetry.attempt);\n\t\t\treturn value;\n\t\t} catch (error) {\n\t\t\tif (error instanceof RetrySleepAbortError) throw error;\n\t\t\tif (attempt >= maxAttempts || !isRetryable(error)) {\n\t\t\t\tif (lastRetry) {\n\t\t\t\t\tawait callbacks?.onRetryFinished?.(false, lastRetry.attempt, errorMessageOf(error));\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tattempt++;\n\t\t\tlastRetry = { attempt, errorMessage: errorMessageOf(error) };\n\t\t\tconst delayMs = retryDelayMs(policy!, attempt);\n\t\t\tawait callbacks?.onRetryScheduled?.(attempt, maxAttempts, delayMs, lastRetry.errorMessage);\n\n\t\t\ttry {\n\t\t\t\tawait sleep(delayMs, signal);\n\t\t\t} catch (sleepError) {\n\t\t\t\tawait callbacks?.onRetryFinished?.(false, attempt, lastRetry.errorMessage);\n\t\t\t\tthrow sleepError instanceof RetrySleepAbortError ? error : sleepError;\n\t\t\t}\n\t\t\tawait callbacks?.onRetryAttemptStart?.();\n\t\t}\n\t}\n}\n\nfunction errorMessageOf(error: unknown): string {\n\tif (error instanceof Error) return error.message || \"Unknown error\";\n\treturn String(error) || \"Unknown error\";\n}\n\n/**\n * Run a single assistant-producing call with bounded retry on transient errors.\n *\n * Behavior:\n * - A successful response is returned immediately. Aborts are terminal and never\n * retried, but reported as unsuccessful if they happen after a retry was scheduled.\n * Aborts during the backoff sleep are normalized to an aborted `AssistantMessage`\n * too, so callers do not need to care when cancellation happened.\n * - A non-retryable error (per {@link isRetryableAssistantError}, including quota/\n * billing exhaustion) is returned immediately so deterministic errors fail fast.\n * - Otherwise retries up to `maxRetries` times with exponential backoff, emitting\n * `onRetryScheduled` before each sleep, `onRetryAttemptStart` after each sleep before\n * the retried call starts, and `onRetryFinished` once at the end (whether the loop\n * ends in success, exhausted retries, or an aborted backoff).\n *\n * When `policy` is undefined or disabled, the first response is returned unchanged\n * (equivalent to calling `produce()` directly).\n */\nexport async function retryAssistantCall(\n\tproduce: () => Promise<AssistantMessage>,\n\tpolicy: RetryPolicy | undefined,\n\tsignal: AbortSignal | undefined,\n\tcallbacks?: RetryCallbacks,\n): Promise<AssistantMessage> {\n\tconst maxAttempts = policy?.enabled ? policy.maxRetries : 0;\n\n\tlet attempt = 0;\n\tlet lastRetry: { attempt: number; errorMessage: string } | undefined;\n\tfor (;;) {\n\t\tconst response = await produce();\n\n\t\t// Abort: terminal but not successful. Never retry an aborted message.\n\t\tif (response.stopReason === \"aborted\") {\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(false, lastRetry.attempt);\n\t\t\treturn response;\n\t\t}\n\n\t\t// Success: non-error, non-abort responses return as-is.\n\t\tif (response.stopReason !== \"error\") {\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(true, lastRetry.attempt);\n\t\t\treturn response;\n\t\t}\n\n\t\t// Non-retryable, or budget exhausted: return the final error message.\n\t\tif (attempt >= maxAttempts || !isRetryableAssistantError(response)) {\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(false, lastRetry.attempt, response.errorMessage);\n\t\t\treturn response;\n\t\t}\n\n\t\tattempt++;\n\t\tlastRetry = { attempt, errorMessage: response.errorMessage || \"Unknown error\" };\n\t\tconst delayMs = retryDelayMs(policy!, attempt);\n\t\tawait callbacks?.onRetryScheduled?.(attempt, maxAttempts, delayMs, lastRetry.errorMessage);\n\n\t\t// Normalize aborts during retry backoff to the same AssistantMessage shape as\n\t\t// provider stream aborts, so callers do not need to care when cancellation happened.\n\t\ttry {\n\t\t\tawait sleep(delayMs, signal);\n\t\t} catch (error) {\n\t\t\tawait callbacks?.onRetryFinished?.(false, attempt, lastRetry.errorMessage);\n\t\t\tif (error instanceof RetrySleepAbortError) {\n\t\t\t\tconst { errorMessage: _errorMessage, ...rest } = response;\n\t\t\t\treturn { ...rest, stopReason: \"aborted\" };\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\tawait callbacks?.onRetryAttemptStart?.();\n\t}\n}\n\n/**\n * Classifies whether a failed assistant message looks like a transient provider\n * or transport error, so callers can decide if the last assistant turn should be\n * restarted.\n *\n * This does not implement retry policy. Callers should first handle context\n * overflow separately, then apply their own retry budget, backoff, and reporting\n * before restarting the assistant turn.\n */\nexport function isRetryableAssistantError(message: AssistantMessage): boolean {\n\tif (\n\t\tmessage.stopReason !== \"error\" ||\n\t\tmessage.stopDetails?.type === \"refusal\" ||\n\t\tmessage.stopDetails?.type === \"sensitive\" ||\n\t\t!message.errorMessage\n\t) {\n\t\treturn false;\n\t}\n\treturn isRetryableErrorMessage(message.errorMessage);\n}\n\n/**\n * Matches the agent-loop stream watchdog failures (\"Idle timeout waiting for\n * provider stream after <n>ms\" and \"Provider stream start timed out after\n * <n>ms\"), the WebSocket liveness verdict (\"WebSocket liveness timeout after\n * <n>ms (<k> pings unanswered)\"), and the Responses completion-phase verdict\n * (\"Provider stream stalled after the last output item: response.completed\n * timed out after <n>ms\"). These anchored shapes\n * distinguish provider-stream stalls from unrelated extension, command, or MCP\n * timeout diagnostics.\n */\nconst PROVIDER_STREAM_STALL_ERROR_PATTERN =\n\t/^(?:Idle timeout waiting for provider stream after \\d+ms|Provider stream start timed out after \\d+ms(?: \\([^)]*\\))?|WebSocket liveness timeout after \\d+ms \\(\\d+ pings unanswered\\)|Provider stream stalled after the last output item: response\\.completed timed out after \\d+ms)$/i;\nconst PROVIDER_TRANSPORT_TIMEOUT_ERROR_PATTERN = /^Request timed out\\.?$/i;\n\nexport function isProviderStreamStallError(message: AssistantMessage): boolean {\n\treturn message.stopReason === \"error\" && PROVIDER_STREAM_STALL_ERROR_PATTERN.test(message.errorMessage ?? \"\");\n}\n\n/** One row per stall watchdog: how to read its message, and how to explain it. */\nconst PROVIDER_STALL_PHASES: ReadonlyArray<{\n\tpattern: RegExp;\n\t/** What the provider failed to do, in the user's words. */\n\tsymptom: string;\n\t/** The setting that widens this bound, when one exists. */\n\tsetting?: string;\n}> = [\n\t{\n\t\tpattern: /^Provider stream start timed out after (\\d+)ms/i,\n\t\tsymptom: \"accepted the request but never started sending a response\",\n\t\tsetting: \"retry.provider.streamStartTimeoutMs\",\n\t},\n\t{\n\t\tpattern: /^Idle timeout waiting for provider stream after (\\d+)ms/i,\n\t\tsymptom: \"started the response and then went silent\",\n\t\tsetting: \"retry.provider.timeoutMs\",\n\t},\n\t{\n\t\tpattern: /^WebSocket liveness timeout after (\\d+)ms/i,\n\t\tsymptom: \"stopped answering connection health checks\",\n\t},\n\t{\n\t\tpattern: /^Provider stream stalled after the last output item: response\\.completed timed out after (\\d+)ms/i,\n\t\tsymptom: \"finished its output but never sent the end-of-response event\",\n\t},\n];\n\nexport interface ProviderStallDescriptionOptions {\n\t/** Same-model attempts already spent on this turn. */\n\tattempts?: number;\n\t/** Selector of the model that stalled, for example `anthropic/claude-opus-5`. */\n\tmodel?: string;\n\t/**\n\t * Appends the \"what to do next\" sentence. Omit it while the turn can still\n\t * recover: a retry in flight is not the moment to tell the user to act.\n\t */\n\trecovery?: \"no-fallback-configured\" | \"chain-exhausted\";\n}\n\nfunction formatStallDuration(timeoutMs: number): string {\n\tif (timeoutMs < 1000) return `${timeoutMs}ms`;\n\tif (timeoutMs < 120_000) return `${Math.round(timeoutMs / 100) / 10}s`;\n\treturn `${Math.round(timeoutMs / 6000) / 10}m`;\n}\n\n/**\n * Plain-language replacement for a stall watchdog's own `Error.message`.\n *\n * The watchdog wording (`Provider stream start timed out after 180000ms ...`)\n * is a classifier token - {@link isProviderStreamStallError} and the turn retry\n * gate both match on it - so it must stay on the assistant message. It was also\n * the only thing the user ever saw when a turn died on a stall, which explains\n * nothing and names no next step (senpi#1740). Every user-facing surface routes\n * the message through here first and falls back to the raw text for anything\n * that is not a stall.\n */\nexport function describeProviderStallForUser(\n\terrorMessage: string | undefined,\n\toptions: ProviderStallDescriptionOptions = {},\n): string | undefined {\n\tif (!errorMessage) return undefined;\n\tfor (const { pattern, symptom, setting } of PROVIDER_STALL_PHASES) {\n\t\tconst match = pattern.exec(errorMessage);\n\t\tif (!match) continue;\n\t\tconst subject = options.model ? `The provider for ${options.model}` : \"The provider\";\n\t\tconst duration = formatStallDuration(Number(match[1]));\n\t\tconst sentences = [`${subject} ${symptom} within ${duration}, so the request was cancelled.`];\n\t\tconst attempts = options.attempts ?? 0;\n\t\tif (attempts > 0) {\n\t\t\tsentences.push(`Retried ${attempts} time${attempts === 1 ? \"\" : \"s\"} on the same model with the same result.`);\n\t\t}\n\t\tif (options.recovery) {\n\t\t\tconst raise = setting ? `, or raise ${setting} in settings (0 disables the bound)` : \"\";\n\t\t\tconst lead =\n\t\t\t\toptions.recovery === \"no-fallback-configured\"\n\t\t\t\t\t? \"No fallback model is configured for it, so nothing could take the turn over: run /fallback to add one\"\n\t\t\t\t\t: \"Every model in its fallback chain was tried as well: run /fallback to review the chain\";\n\t\t\tsentences.push(`${lead}, send the message again${raise}.`);\n\t\t}\n\t\treturn sentences.join(\" \");\n\t}\n\treturn undefined;\n}\n\n/**\n * Matches the agent-loop throughput watchdog verdict (\"Provider stream\n * throughput degraded: <n> tok/s over <n>s (floor <n> tok/s)\", optionally\n * followed by the settings hint). Deliberately NOT part of the stall pattern\n * above: a stall is silence, which a same-model retry can genuinely fix, while\n * a degraded stream is an upstream that answers too slowly for replaying the\n * same payload to help. Callers use this to skip the same-model retry budget\n * and consult the fallback chain immediately.\n */\nconst PROVIDER_STREAM_THROUGHPUT_DEGRADED_ERROR_PATTERN =\n\t/^Provider stream throughput degraded: \\d+(?:\\.\\d+)? tok\\/s over \\d+(?:\\.\\d+)?s \\(floor \\d+(?:\\.\\d+)? tok\\/s\\)(?: \\([^)]*\\))?$/i;\n\nexport function isProviderStreamThroughputDegradedError(message: AssistantMessage): boolean {\n\treturn (\n\t\tmessage.stopReason === \"error\" &&\n\t\tPROVIDER_STREAM_THROUGHPUT_DEGRADED_ERROR_PATTERN.test(message.errorMessage ?? \"\")\n\t);\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.
|
|
3
|
+
"version": "2026.9.16-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.123.0",
|
|
86
86
|
"@aws-sdk/client-bedrock-runtime": "3.1127.0",
|
|
87
|
-
"@earendil-works/pi-telemetry": "npm:@code-yeongyu/senpi-telemetry@2026.9.
|
|
87
|
+
"@earendil-works/pi-telemetry": "npm:@code-yeongyu/senpi-telemetry@2026.9.16-2",
|
|
88
88
|
"@google/genai": "2.21.0",
|
|
89
89
|
"@smithy/node-http-handler": "4.12.1",
|
|
90
90
|
"http-proxy-agent": "9.1.0",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@code-yeongyu/senpi",
|
|
3
|
-
"version": "2026.9.
|
|
3
|
+
"version": "2026.9.16-2",
|
|
4
4
|
"description": "Coding agent CLI with read, bash, edit, write tools and session management",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"piConfig": {
|
|
@@ -55,9 +55,9 @@
|
|
|
55
55
|
},
|
|
56
56
|
"dependencies": {
|
|
57
57
|
"@earendil-works/chord": "0.85.1",
|
|
58
|
-
"@earendil-works/pi-agent-core": "npm:@code-yeongyu/senpi-agent-core@2026.9.
|
|
59
|
-
"@earendil-works/pi-ai": "npm:@code-yeongyu/senpi-ai@2026.9.
|
|
60
|
-
"@earendil-works/pi-tui": "npm:@code-yeongyu/senpi-tui@2026.9.
|
|
58
|
+
"@earendil-works/pi-agent-core": "npm:@code-yeongyu/senpi-agent-core@2026.9.16-2",
|
|
59
|
+
"@earendil-works/pi-ai": "npm:@code-yeongyu/senpi-ai@2026.9.16-2",
|
|
60
|
+
"@earendil-works/pi-tui": "npm:@code-yeongyu/senpi-tui@2026.9.16-2",
|
|
61
61
|
"@silvia-odwyer/photon-node": "0.3.4",
|
|
62
62
|
"chalk": "6.0.0",
|
|
63
63
|
"cross-spawn": "7.0.6",
|
|
@@ -78,8 +78,8 @@
|
|
|
78
78
|
"@anthropic-ai/sdk": "0.123.0",
|
|
79
79
|
"@aws-sdk/client-bedrock-runtime": "3.1127.0",
|
|
80
80
|
"@bufbuild/protobuf": "2.14.0",
|
|
81
|
-
"@code-yeongyu/senpi-codemode": "2026.9.
|
|
82
|
-
"@earendil-works/pi-pty": "npm:@code-yeongyu/senpi-pty@2026.9.
|
|
81
|
+
"@code-yeongyu/senpi-codemode": "2026.9.16-2",
|
|
82
|
+
"@earendil-works/pi-pty": "npm:@code-yeongyu/senpi-pty@2026.9.16-2",
|
|
83
83
|
"@modelcontextprotocol/sdk": "1.30.0",
|
|
84
84
|
"@mozilla/readability": "0.6.0",
|
|
85
85
|
"@opentelemetry/api": "1.9.1",
|
|
@@ -118,7 +118,7 @@
|
|
|
118
118
|
"@aws-sdk/xml-builder": "3.972.40",
|
|
119
119
|
"@aws/lambda-invoke-store": "0.3.0",
|
|
120
120
|
"@babel/runtime": "7.29.2",
|
|
121
|
-
"@earendil-works/pi-telemetry": "npm:@code-yeongyu/senpi-telemetry@2026.9.
|
|
121
|
+
"@earendil-works/pi-telemetry": "npm:@code-yeongyu/senpi-telemetry@2026.9.16-2",
|
|
122
122
|
"@google/genai": "2.21.0",
|
|
123
123
|
"@hono/node-server": "2.1.1",
|
|
124
124
|
"@mixmark-io/domino": "2.2.0",
|