@code-yeongyu/senpi 2026.9.27-4 → 2026.9.28
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 +32 -0
- package/dist/bundle/chunks/{app-server-command-3GVJZFFH.js → app-server-command-TOPTGVQB.js} +1 -1
- package/dist/bundle/chunks/{azure-openai-responses-4SUOOZZ4.js → azure-openai-responses-FCZNBRWE.js} +1 -1
- package/dist/bundle/chunks/bedrock-converse-stream.js +1 -1
- package/dist/bundle/chunks/{chunk-PSCNHY7D.js → chunk-3GMFUEU7.js} +1 -1
- package/dist/bundle/chunks/{chunk-HBG6SQU5.js → chunk-62XHQXCZ.js} +1 -1
- package/dist/bundle/chunks/{chunk-SLL375O7.js → chunk-7DY2JPUX.js} +1 -1
- package/dist/bundle/chunks/chunk-7YUGCTEV.js +15 -0
- package/dist/bundle/chunks/{chunk-FWBSGMAE.js → chunk-A4UMPXQF.js} +1 -1
- package/dist/bundle/chunks/chunk-BBK6SSYT.js +2 -0
- package/dist/bundle/chunks/{chunk-C2425O2Q.js → chunk-CNQ4JB45.js} +1 -1
- package/dist/bundle/chunks/{chunk-27IFXX3B.js → chunk-DRN4FQCE.js} +1 -1
- package/dist/bundle/chunks/{chunk-22MGY5JQ.js → chunk-EHSZ7UCW.js} +1 -1
- package/dist/bundle/chunks/chunk-FHJYIU3U.js +5 -0
- package/dist/bundle/chunks/chunk-GJUCSTAG.js +19 -0
- package/dist/bundle/chunks/{chunk-VMKAYXHL.js → chunk-KIOTFUG6.js} +25 -20
- package/dist/bundle/chunks/{chunk-2BMD37YV.js → chunk-LUPPSEQW.js} +1 -1
- package/dist/bundle/chunks/chunk-OAIVTS5X.js +8 -0
- package/dist/bundle/chunks/{chunk-NRGMT74E.js → chunk-QOVUQZO4.js} +1 -1
- package/dist/bundle/chunks/chunk-SN4ZHPMN.js +135 -0
- package/dist/bundle/chunks/{chunk-IKXPBYSO.js → chunk-UJFLZ2M2.js} +1 -1
- package/dist/bundle/chunks/{chunk-4T4GFAGK.js → chunk-VFSXUT7K.js} +1 -1
- package/dist/bundle/chunks/{cli-main-66NFBKVH.js → cli-main-ARR54ET6.js} +1 -1
- package/dist/bundle/chunks/{google-generative-ai-ZTGKZTGU.js → google-generative-ai-LFCBHG3Y.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-CCZ376YK.js → google-vertex-C474FXU7.js} +1 -1
- package/dist/bundle/chunks/{help-fast-path-NZ3I2UEN.js → help-fast-path-3U3YDEZ6.js} +1 -1
- package/dist/bundle/chunks/{host-command-RORPAC5X.js → host-command-6CJ7YM6W.js} +1 -1
- package/dist/bundle/chunks/{host-lifecycle-UDMJGLOR.js → host-lifecycle-RZIMOFDM.js} +1 -1
- package/dist/bundle/chunks/host-lifecycle.js +6 -6
- package/dist/bundle/chunks/interactive-host-runtime-A3GEIFTU.js +4 -0
- package/dist/bundle/chunks/{interactive-mode-LOAADKLH.js → interactive-mode-ITSFLGF6.js} +1 -1
- package/dist/bundle/chunks/{list-tips-S5CANO5W.js → list-tips-FPXDXN7R.js} +1 -1
- package/dist/bundle/chunks/multi-session-host-B4WMZE2G.js +21 -0
- package/dist/bundle/chunks/{openai-codex-responses-YSGZZDD5.js → openai-codex-responses-2LDIFL6Z.js} +1 -1
- package/dist/bundle/chunks/{openai-completions-KWHRWCBN.js → openai-completions-7KZLPKYP.js} +1 -1
- package/dist/bundle/chunks/{openai-images-6U5FCN5S.js → openai-images-I7DR7ERP.js} +1 -1
- package/dist/bundle/chunks/{openai-responses-7PWMBGYX.js → openai-responses-LCHS3AF3.js} +1 -1
- package/dist/bundle/chunks/{openrouter-images-QIKWQZUD.js → openrouter-images-IPNDRK6C.js} +1 -1
- package/dist/bundle/chunks/{package-manager-cli-5EEDA35I.js → package-manager-cli-DXHQ6RKA.js} +1 -1
- package/dist/bundle/chunks/{rotation-stream-KZG4OVR7.js → rotation-stream-ZVJEGA2G.js} +1 -1
- package/dist/bundle/chunks/{rpc-mode-HOEA5NGQ.js → rpc-mode-PFPNP65F.js} +1 -1
- package/dist/bundle/chunks/session-picker-KOPOV6Q4.js +2 -0
- package/dist/bundle/chunks/session-worker.js +311 -302
- package/dist/bundle/cli.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/cli/args.js +1 -1
- package/dist/cli/args.js.map +1 -1
- package/dist/cli/host-command.d.ts +8 -1
- package/dist/cli/host-command.d.ts.map +1 -1
- package/dist/cli/host-command.js +66 -14
- package/dist/cli/host-command.js.map +1 -1
- package/dist/core/agent-session.d.ts +18 -1
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +119 -3
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/retry-fallback/candidates.d.ts +26 -0
- package/dist/core/retry-fallback/candidates.d.ts.map +1 -0
- package/dist/core/retry-fallback/candidates.js +41 -0
- package/dist/core/retry-fallback/candidates.js.map +1 -0
- package/dist/core/retry-fallback/circuit-probes.d.ts +30 -0
- package/dist/core/retry-fallback/circuit-probes.d.ts.map +1 -0
- package/dist/core/retry-fallback/circuit-probes.js +60 -0
- package/dist/core/retry-fallback/circuit-probes.js.map +1 -0
- package/dist/core/retry-fallback/circuit.d.ts +101 -0
- package/dist/core/retry-fallback/circuit.d.ts.map +1 -0
- package/dist/core/retry-fallback/circuit.js +175 -0
- package/dist/core/retry-fallback/circuit.js.map +1 -0
- package/dist/core/retry-fallback/controller-types.d.ts +58 -0
- package/dist/core/retry-fallback/controller-types.d.ts.map +1 -0
- package/dist/core/retry-fallback/controller-types.js +2 -0
- package/dist/core/retry-fallback/controller-types.js.map +1 -0
- package/dist/core/retry-fallback/controller.d.ts +21 -49
- package/dist/core/retry-fallback/controller.d.ts.map +1 -1
- package/dist/core/retry-fallback/controller.js +88 -42
- package/dist/core/retry-fallback/controller.js.map +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +25 -17
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-failure-report.d.ts +33 -0
- package/dist/core/session-failure-report.d.ts.map +1 -0
- package/dist/core/session-failure-report.js +62 -0
- package/dist/core/session-failure-report.js.map +1 -0
- package/dist/core/settings-manager.d.ts +3 -0
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +4 -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 +1 -0
- package/dist/core/slash-commands.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/modes/index.d.ts +1 -0
- package/dist/modes/index.d.ts.map +1 -1
- package/dist/modes/index.js +2 -0
- package/dist/modes/index.js.map +1 -1
- package/dist/modes/interactive/help-content.d.ts.map +1 -1
- package/dist/modes/interactive/help-content.js +3 -0
- package/dist/modes/interactive/help-content.js.map +1 -1
- package/dist/modes/interactive/interactive-host-attach.d.ts +10 -0
- package/dist/modes/interactive/interactive-host-attach.d.ts.map +1 -0
- package/dist/modes/interactive/interactive-host-attach.js +14 -0
- package/dist/modes/interactive/interactive-host-attach.js.map +1 -0
- package/dist/modes/interactive/interactive-host-runtime.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-host-runtime.js +3 -6
- package/dist/modes/interactive/interactive-host-runtime.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +7 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +66 -1
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/session-failure-info.d.ts +3 -0
- package/dist/modes/interactive/session-failure-info.d.ts.map +1 -0
- package/dist/modes/interactive/session-failure-info.js +21 -0
- package/dist/modes/interactive/session-failure-info.js.map +1 -0
- package/dist/modes/interactive/tips/catalog/model-tips.d.ts +7 -7
- package/dist/modes/interactive/tips/catalog/model-tips.d.ts.map +1 -1
- package/dist/modes/interactive/tips/catalog/model-tips.js +7 -1
- package/dist/modes/interactive/tips/catalog/model-tips.js.map +1 -1
- package/dist/modes/interactive/tips/catalog/session-tips.d.ts.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/rpc/host-attach-hold.d.ts +16 -0
- package/dist/modes/rpc/host-attach-hold.d.ts.map +1 -0
- package/dist/modes/rpc/host-attach-hold.js +9 -0
- package/dist/modes/rpc/host-attach-hold.js.map +1 -0
- package/dist/modes/rpc/host-cleanup-paths.d.ts +20 -0
- package/dist/modes/rpc/host-cleanup-paths.d.ts.map +1 -0
- package/dist/modes/rpc/host-cleanup-paths.js +13 -0
- package/dist/modes/rpc/host-cleanup-paths.js.map +1 -0
- package/dist/modes/rpc/host-client-occupancy.d.ts +24 -0
- package/dist/modes/rpc/host-client-occupancy.d.ts.map +1 -0
- package/dist/modes/rpc/host-client-occupancy.js +53 -0
- package/dist/modes/rpc/host-client-occupancy.js.map +1 -0
- package/dist/modes/rpc/host-daemon-paths.d.ts +61 -8
- package/dist/modes/rpc/host-daemon-paths.d.ts.map +1 -1
- package/dist/modes/rpc/host-daemon-paths.js +128 -11
- package/dist/modes/rpc/host-daemon-paths.js.map +1 -1
- package/dist/modes/rpc/host-daemon-registration.d.ts +11 -1
- package/dist/modes/rpc/host-daemon-registration.d.ts.map +1 -1
- package/dist/modes/rpc/host-daemon-registration.js +28 -15
- package/dist/modes/rpc/host-daemon-registration.js.map +1 -1
- package/dist/modes/rpc/host-endpoints.d.ts +12 -0
- package/dist/modes/rpc/host-endpoints.d.ts.map +1 -0
- package/dist/modes/rpc/host-endpoints.js +59 -0
- package/dist/modes/rpc/host-endpoints.js.map +1 -0
- package/dist/modes/rpc/host-ensure-lock.d.ts +11 -0
- package/dist/modes/rpc/host-ensure-lock.d.ts.map +1 -0
- package/dist/modes/rpc/host-ensure-lock.js +49 -0
- package/dist/modes/rpc/host-ensure-lock.js.map +1 -0
- package/dist/modes/rpc/host-ensure.d.ts +7 -0
- package/dist/modes/rpc/host-ensure.d.ts.map +1 -1
- package/dist/modes/rpc/host-ensure.js +42 -65
- package/dist/modes/rpc/host-ensure.js.map +1 -1
- package/dist/modes/rpc/host-gc-evidence.d.ts +18 -0
- package/dist/modes/rpc/host-gc-evidence.d.ts.map +1 -0
- package/dist/modes/rpc/host-gc-evidence.js +128 -0
- package/dist/modes/rpc/host-gc-evidence.js.map +1 -0
- package/dist/modes/rpc/host-gc.d.ts +28 -0
- package/dist/modes/rpc/host-gc.d.ts.map +1 -0
- package/dist/modes/rpc/host-gc.js +110 -0
- package/dist/modes/rpc/host-gc.js.map +1 -0
- package/dist/modes/rpc/host-generations.d.ts +10 -2
- package/dist/modes/rpc/host-generations.d.ts.map +1 -1
- package/dist/modes/rpc/host-generations.js +12 -7
- package/dist/modes/rpc/host-generations.js.map +1 -1
- package/dist/modes/rpc/host-handoff.d.ts +6 -0
- package/dist/modes/rpc/host-handoff.d.ts.map +1 -1
- package/dist/modes/rpc/host-handoff.js +31 -4
- package/dist/modes/rpc/host-handoff.js.map +1 -1
- package/dist/modes/rpc/host-lifecycle-policy.d.ts +53 -0
- package/dist/modes/rpc/host-lifecycle-policy.d.ts.map +1 -0
- package/dist/modes/rpc/host-lifecycle-policy.js +64 -0
- package/dist/modes/rpc/host-lifecycle-policy.js.map +1 -0
- package/dist/modes/rpc/host-lifecycle.d.ts +1 -44
- package/dist/modes/rpc/host-lifecycle.d.ts.map +1 -1
- package/dist/modes/rpc/host-lifecycle.js +23 -85
- package/dist/modes/rpc/host-lifecycle.js.map +1 -1
- package/dist/modes/rpc/host-observe-request.d.ts +17 -0
- package/dist/modes/rpc/host-observe-request.d.ts.map +1 -0
- package/dist/modes/rpc/host-observe-request.js +30 -0
- package/dist/modes/rpc/host-observe-request.js.map +1 -0
- package/dist/modes/rpc/host-probe.d.ts +12 -0
- package/dist/modes/rpc/host-probe.d.ts.map +1 -1
- package/dist/modes/rpc/host-probe.js +28 -1
- package/dist/modes/rpc/host-probe.js.map +1 -1
- package/dist/modes/rpc/host-protocol-info.d.ts +2 -0
- package/dist/modes/rpc/host-protocol-info.d.ts.map +1 -1
- package/dist/modes/rpc/host-protocol-info.js +1 -0
- package/dist/modes/rpc/host-protocol-info.js.map +1 -1
- package/dist/modes/rpc/host-readiness.d.ts +22 -0
- package/dist/modes/rpc/host-readiness.d.ts.map +1 -0
- package/dist/modes/rpc/host-readiness.js +44 -0
- package/dist/modes/rpc/host-readiness.js.map +1 -0
- package/dist/modes/rpc/host-runner.d.ts +13 -0
- package/dist/modes/rpc/host-runner.d.ts.map +1 -1
- package/dist/modes/rpc/host-runner.js +23 -4
- package/dist/modes/rpc/host-runner.js.map +1 -1
- package/dist/modes/rpc/host-status-all.d.ts +31 -0
- package/dist/modes/rpc/host-status-all.d.ts.map +1 -0
- package/dist/modes/rpc/host-status-all.js +78 -0
- package/dist/modes/rpc/host-status-all.js.map +1 -0
- package/dist/modes/rpc/host-status-rows.d.ts +35 -0
- package/dist/modes/rpc/host-status-rows.d.ts.map +1 -0
- package/dist/modes/rpc/host-status-rows.js +42 -0
- package/dist/modes/rpc/host-status-rows.js.map +1 -0
- package/dist/modes/rpc/host-status.d.ts +32 -1
- package/dist/modes/rpc/host-status.d.ts.map +1 -1
- package/dist/modes/rpc/host-status.js +33 -27
- package/dist/modes/rpc/host-status.js.map +1 -1
- package/dist/modes/rpc/host-successor.d.ts +3 -1
- package/dist/modes/rpc/host-successor.d.ts.map +1 -1
- package/dist/modes/rpc/host-successor.js +105 -42
- package/dist/modes/rpc/host-successor.js.map +1 -1
- package/dist/modes/rpc/host-watchdog.d.ts +6 -0
- package/dist/modes/rpc/host-watchdog.d.ts.map +1 -1
- package/dist/modes/rpc/host-watchdog.js +12 -13
- package/dist/modes/rpc/host-watchdog.js.map +1 -1
- package/dist/modes/rpc/loop-lag-watchdog.d.ts +16 -0
- package/dist/modes/rpc/loop-lag-watchdog.d.ts.map +1 -1
- package/dist/modes/rpc/loop-lag-watchdog.js +34 -2
- package/dist/modes/rpc/loop-lag-watchdog.js.map +1 -1
- package/dist/modes/rpc/multi-session-host.d.ts +2 -1
- package/dist/modes/rpc/multi-session-host.d.ts.map +1 -1
- package/dist/modes/rpc/multi-session-host.js +33 -6
- package/dist/modes/rpc/multi-session-host.js.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts +2 -2
- package/dist/modes/rpc/rpc-mode.js +2 -2
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +16 -0
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/dist/modes/rpc/session-command-router.d.ts +9 -1
- package/dist/modes/rpc/session-command-router.d.ts.map +1 -1
- package/dist/modes/rpc/session-command-router.js +4 -1
- package/dist/modes/rpc/session-command-router.js.map +1 -1
- package/dist/modes/rpc/session-path-key.d.ts +3 -1
- package/dist/modes/rpc/session-path-key.d.ts.map +1 -1
- package/dist/modes/rpc/session-path-key.js +3 -1
- package/dist/modes/rpc/session-path-key.js.map +1 -1
- package/docs/rpc.md +186 -19
- package/docs/settings.md +25 -1
- package/docs/usage.md +5 -2
- package/node_modules/@code-yeongyu/senpi-codemode/CHANGELOG.md +12 -0
- package/node_modules/@code-yeongyu/senpi-codemode/package.json +4 -4
- package/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.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/utils/error-body.d.ts +6 -0
- package/node_modules/@earendil-works/pi-ai/dist/utils/error-body.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/utils/error-body.js +36 -0
- package/node_modules/@earendil-works/pi-ai/dist/utils/error-body.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/utils/retry.d.ts +1 -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 +14 -1
- 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
- package/dist/bundle/chunks/chunk-3DEXCYNN.js +0 -135
- package/dist/bundle/chunks/chunk-5X4KSPK5.js +0 -12
- package/dist/bundle/chunks/chunk-KMD5ZONU.js +0 -5
- package/dist/bundle/chunks/chunk-PEHZYGYA.js +0 -8
- package/dist/bundle/chunks/chunk-PRC5XIIH.js +0 -2
- package/dist/bundle/chunks/chunk-QKY33652.js +0 -18
- package/dist/bundle/chunks/interactive-host-runtime-TIFT2SKR.js +0 -4
- package/dist/bundle/chunks/multi-session-host-GRHKB7Q2.js +0 -21
- package/dist/bundle/chunks/session-picker-FTFCQYHH.js +0 -2
package/CHANGELOG.md
CHANGED
|
@@ -6,12 +6,44 @@
|
|
|
6
6
|
|
|
7
7
|
### Added
|
|
8
8
|
|
|
9
|
+
### Changed
|
|
10
|
+
|
|
11
|
+
### Fixed
|
|
12
|
+
|
|
13
|
+
### Removed
|
|
14
|
+
|
|
15
|
+
## [2026.9.28] - 2026-09-28
|
|
16
|
+
|
|
17
|
+
### Breaking Changes
|
|
18
|
+
|
|
19
|
+
### Added
|
|
20
|
+
|
|
21
|
+
- `/sessions` opens the session picker as an alias of `/resume`, and `/help` and the startup tips now say how to change the thinking level (`/thinking <level>`, Shift+Tab, `/efforts <level>`) and how to reopen a past session (`/resume` or `/sessions` in the TUI, `-r` or `-c` from the shell) ([#1437](https://github.com/code-yeongyu/senpi/issues/1437)).
|
|
9
22
|
- `senpi models discover <provider>` fetches `<baseUrl>/models` once for an OpenAI-compatible provider in `models.json` and adds every listed model to that provider's `models` array (the previous file is kept as a timestamped backup). When the provider sets `"compat": { "supportsReasoningEffort": true }`, the `reasoning_efforts` each entry advertises become its `thinkingLevelMap` (the endpoint's own names are sent on the wire, levels it does not list are hidden) and its `default` becomes the model's new `defaultThinkingLevel`. A model's `defaultThinkingLevel` is where a session starts when you have not chosen a level for that model. ([#2196](https://github.com/code-yeongyu/senpi/issues/2196))
|
|
23
|
+
- A model fallback-chain entry that keeps failing is circuit-broken. Once it fails out of its chain (a transient or 5xx failure after the retry budget, or a quota/credit failure), every session in the process on the same agent directory (including `/new` sessions and in-process subagents) skips it without sending a request, for a cooldown that starts at `fallback.circuitCooldownMs` (default 60s, `0` disables) and doubles on each consecutive failure up to `fallback.circuitMaxCooldownMs` (default 30 minutes). Billing, credit, quota, and budget exhaustion open it at once, even on the last entry, while authentication and request-shape errors never do. A provider `Retry-After` header (seconds or HTTP-date, on 429 and 503, now kept on terminal OpenAI-compatible errors) keeps it open until that time, a success closes it, and after the cooldown exactly one session probes it: the probe holds the circuit exclusively until it settles - even against a background probe-back of the same session - falls back on its first failure without same-model retries, and 429 probe-backs wait for the circuit too. The chain still sends the request when every entry is open. `/session` and `get_session_stats` gain a failure-cost report: failed requests and their share, time spent in them, and the retries after a failure in the same turn that missed the prompt cache, with their uncached input tokens. ([#2198](https://github.com/code-yeongyu/senpi/issues/2198))
|
|
24
|
+
- `senpi host status` (and each `senpi host status --all` row) shows `memory_pressure`: `true` while that endpoint's host reads its memory above `SENPI_RPC_HOST_RSS_WARN_MB`, `false` otherwise, `null` when nothing answers. Multi-session hosts report the same flag in `get_protocol_info`. It is informational only: a pressured host still admits every session.
|
|
25
|
+
- `senpi host gc [--agent-dir <dir>] [--json]` removes the state (directory, `endpoint.json`, socket, successor/shield siblings) of RPC host endpoints whose host is provably gone - no live generation, no live session-path claim, a socket that refuses - checked under that endpoint's ensure lock. A refused connection counts only when the entry is a socket, and a handoff successor is recorded from the moment it starts, so gc never judges an endpoint by a dead predecessor. It removes the siblings and the socket before the directory, leaves a sibling that is a directory in place (reported under `skipped`), and reports an endpoint whose removal fails as `failed` while it goes on to the others. It never signals a process, never runs on its own inside `ensure` or `status`, and reports every endpoint it keeps with the reason (`live_generation`, `live_claim`, `reachable`, `locked`, `legacy_layout`, `unknown_identity`). ([#2226](https://github.com/code-yeongyu/senpi/issues/2226))
|
|
26
|
+
- `senpi host status --all` lists every RPC host endpoint under the agent directory - including ones whose host exited or crashed - without removing anything, reading up to 64 of them at once so a batch of hung hosts costs one 10 s probe, and hundreds of them cannot exhaust the file descriptors, and `senpi host status` adds `crashes`, `shard`, `claims_live`, and (with `--include-workers`) `session_rows` and `claims`. Each endpoint directory now keeps a durable `endpoint.json`, written atomically (a plain exclusive create on exFAT and other filesystems without hard links); the next `senpi host ensure` rewrites one that is torn instead of leaving the endpoint unaddressable. `senpi host shard-path --kind <p|i> --owner <id>` prints the per-session/per-thread shard socket, and `shardKey`, `shardSocketPath`, `shardSocketPathForKey` and `daemonDirectoryName` are exported from `@code-yeongyu/senpi` for clients that compute the same names. Every session on a socket host sees `host_socket` (the endpoint's resolved path, identical for every generation of that endpoint) and `host_instance` in its session context; a client-supplied value for either key is overwritten. ([#2226](https://github.com/code-yeongyu/senpi/issues/2226))
|
|
10
27
|
|
|
11
28
|
### Changed
|
|
12
29
|
|
|
30
|
+
- `ensureHost()` returns `release()` on `EnsuredHost` (public SDK type), and every caller must call it once its own client is attached, or right away when it attaches later: until then the host counts the calling process as attached, so a running process that never releases keeps a transient host from idle-exiting. The interactive host runtime and `senpi host ensure` release after attaching; embedders that call `ensureHost()` directly need the same call. ([#2227](https://github.com/code-yeongyu/senpi/issues/2227))
|
|
31
|
+
- Upgrading from 2026.9.27-4 or older: a host that an older build started through a socket path that is not canonical (a `/tmp/...` path on macOS, or a path through a symlinked directory) keeps its registration in the directory named after that spelling. This build attaches to such a host with `pid: 0` and cannot hand it off to a new generation, and `senpi host stop` and `senpi host handoff` through this build refuse it as `unknown_owner`. Stop it with the build that started it, or let it idle out; the next ensure then registers its host in the canonical directory. Until every client on the machine runs this release, an older build's ensure and this build's ensure, handoff or gc through such a spelling take different locks and do not wait for each other, so do not run `senpi host gc` while older clients may still be starting hosts there. A socket path whose directories contain no symlink is not affected: its directory and its lock stay the same.
|
|
32
|
+
- A shared RPC host's stall report now says whether the host was busy or was not running: the stderr line gains `cpu=<ms> heap=<+/-MB>` for the stalled window, and the `host_stalled` record gains `processCpuMs` and `heapDeltaMb`. CPU close to the stall length means the host's own work (or a garbage collection) held the loop; CPU close to zero means the machine did not schedule the process. ([#2211](https://github.com/code-yeongyu/senpi/issues/2211))
|
|
33
|
+
|
|
13
34
|
### Fixed
|
|
14
35
|
|
|
36
|
+
- `/thinking` and `/thinking <level>` now open the thinking-level selector or set the session level instead of being sent to the model as a user message; the interactive dispatch dropped by the upstream sync merge is restored with argument completions ([#1437](https://github.com/code-yeongyu/senpi/issues/1437)).
|
|
37
|
+
- A transient RPC host with a short idle window no longer exits between `ensureHost()` and the ensuring client's first attach. `ensureHost()` now keeps the connection that proved the host ready as an attach hold and returns `release()` on `EnsuredHost`; the interactive host runtime and `senpi host ensure` release it once attached. A slow attach (a loaded machine, a slow lock release) found the host already gone (`connect ENOENT`). ([#2227](https://github.com/code-yeongyu/senpi/issues/2227))
|
|
38
|
+
- An RPC host that goes away removes its registration pointer last, after `settings.json` and its generation record, on the graceful and the crash path alike, so "no host registered" is never observable while the rest of its daemon state still exists. On Windows the crash path removed the pointer first and then the other files one by one. ([#2241](https://github.com/code-yeongyu/senpi/issues/2241))
|
|
39
|
+
|
|
40
|
+
- A refused `senpi host handoff` (the new generation failed before or after it started, or never answered) no longer leaves traces behind. The endpoint's `settings.json` kept naming the killed successor, so the running host's next restart read the refused generation's settings. The successor's generation record is now released once it has exited, and `settings.json` is restored byte for byte, so `senpi host status --all` never lists the refused generation either.
|
|
41
|
+
- `senpi host handoff` now holds the endpoint's ensure lock while it brings the successor up, like `senpi host ensure` and `senpi host gc`. A concurrent ensure used to probe the endpoint mid-handoff and attach to the generation that was about to drain; it now waits and attaches to the successor the handoff registered.
|
|
42
|
+
- Two spellings of one RPC host socket (`/tmp/...` and `/private/tmp/...`, or a path through a symlinked directory) now share one daemon directory, not only one ensure lock. Each spelling used to keep its own directory, so an ensure through the second spelling attached without knowing which process it attached to and `senpi host stop` through it refused a host the first spelling had started. A socket spelled canonically keeps the directory it already had; a directory an older build named after another spelling is still listed and collected by `senpi host gc`.
|
|
43
|
+
- Two spellings of one RPC host socket (`/tmp/...` and `/private/tmp/...`, or a path through a symlinked directory) now share one ensure lock. `senpi host gc` working through one spelling could otherwise remove a socket that a `senpi host ensure` through the other spelling had just started.
|
|
44
|
+
- A socket host started with `--listen` now exits after its empty-host window even while a client keeps a connection open that only sends `observe: true` reads. Such a connection used to count as a client, so a status panel that stayed connected kept an empty host running forever.
|
|
45
|
+
- Polling `senpi host status` or `senpi host status --all` no longer keeps an RPC host alive. Each poll used to count as a client attaching and restarted the host's idle window, so a panel or doctor loop polling faster than the window (15 minutes by default) kept every host it looked at running forever. Status reads now mark themselves `observe: true` on `get_protocol_info`/`list_sessions`, and a connection that only sends such reads never counts as activity.
|
|
46
|
+
|
|
15
47
|
### Removed
|
|
16
48
|
|
|
17
49
|
## [2026.9.27-4] - 2026-09-27
|
package/dist/bundle/chunks/{app-server-command-3GVJZFFH.js → app-server-command-TOPTGVQB.js}
RENAMED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{import_websocket_server,wrapper_default}from"./chunk-YBZDAABT.js";import{AuthStorage,DefaultResourceLoader,GOAL_STORE_CHANGED_EVENT,ModelRegistry,clearGoal,createAgentSession,createGoal,createPendingQuestion,defaultModelPerProvider,formatProviderNativeBody,formatProviderNativeSummary,getMcpService,goalStoreRef,loadMcpConfig,loadSkills,readGoal,resolveAuthMode,updateGoal}from"./chunk-
|
|
2
|
+
import{import_websocket_server,wrapper_default}from"./chunk-YBZDAABT.js";import{AuthStorage,DefaultResourceLoader,GOAL_STORE_CHANGED_EVENT,ModelRegistry,clearGoal,createAgentSession,createGoal,createPendingQuestion,defaultModelPerProvider,formatProviderNativeBody,formatProviderNativeSummary,getMcpService,goalStoreRef,loadMcpConfig,loadSkills,readGoal,resolveAuthMode,updateGoal}from"./chunk-KIOTFUG6.js";import{require_ignore}from"./chunk-UJFLZ2M2.js";import"./chunk-A4UMPXQF.js";import"./chunk-MUTD2NOH.js";import{SessionManager,loadEntriesFromFile}from"./chunk-DRN4FQCE.js";import"./chunk-YS5YEX4S.js";import{getCredentialAccounts,getModels,getProviders,getSupportedThinkingLevels,pinCredentialAccount,removeCredentialAccount,subscribeProviderAccountEvents}from"./chunk-OAIVTS5X.js";import{getAvailableThemesWithPaths,getThemeByName,takeOverStdout,theme,waitForRawStdoutBackpressure,writeRawStdout}from"./chunk-7DY2JPUX.js";import{x}from"./chunk-EJKCBRYK.js";import"./chunk-CNQ4JB45.js";import{SettingsManager}from"./chunk-SN4ZHPMN.js";import"./chunk-YU2P3CAR.js";import"./chunk-BMX2U22F.js";import"./chunk-7YUGCTEV.js";import{acquireOwnershipSafeLock}from"./chunk-FHJYIU3U.js";import"./chunk-HH3KJDWA.js";import{parseDaemonPidFile,processMatchesPidFile,readProcessStartTime,stopValidatedPid,waitForGone,waitForStartTime}from"./chunk-GJUCSTAG.js";import{attachJsonlLineReader}from"./chunk-QOVUQZO4.js";import"./chunk-DA4W77J7.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-VFSXUT7K.js";import"./chunk-62XHQXCZ.js";import"./chunk-TRSQVD6V.js";import"./chunk-36ACNYQR.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-EHSZ7UCW.js";import"./chunk-Y5A6TKBN.js";import"./chunk-LUPPSEQW.js";import"./chunk-26UBFF6N.js";import"./chunk-3GMFUEU7.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-ELFCNCBY.js";import"./chunk-BBK6SSYT.js";import"./chunk-4LVZQRDG.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import{APP_NAME,CONFIG_DIR_NAME,ENV_SESSION_DIR,VERSION,getAgentDir,getSessionsDir,resolvePath}from"./chunk-PBWQK23Z.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-WASCMT6Y.js";import"./chunk-X4Q5YSTE.js";import"./chunk-IXAUDPOK.js";import"./chunk-L6QV7NZI.js";import"./chunk-45SZOLCU.js";import"./chunk-WVGCQOLJ.js";import"./chunk-BPX6QWPD.js";import{normalizeProviderId}from"./chunk-WL5EQYNL.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import{__toESM}from"./chunk-IKOFCODM.js";import{isIP}from"node:net";var APP_SERVER_LISTEN_USAGE="Invalid --listen value. Use stdio://, unix://, unix:///abs/path, or ws://IP:PORT.";function formatAppServerUsage(){let listenForms="stdio://|unix://|unix:///abs/path|ws://IP:PORT";return[`Usage: ${APP_NAME} app-server [--listen <${listenForms}>] [--ws-auth <token-file|off>] [--json-logs]`,` ${APP_NAME} app-server daemon <start|stop|status|restart> [--listen <${listenForms}>]`].join(`
|
|
3
3
|
`)}function parseListen(value){if(value==="stdio://")return{kind:"stdio",url:"stdio://"};if(value==="unix://")return{kind:"unix",url:"unix://"};if(value.startsWith("unix:///")){let path=value.slice(7);return path.startsWith("/")?{kind:"unix",url:value,path}:void 0}if(!value.startsWith("ws://"))return;let parsed;try{parsed=new URL(value)}catch(error){if(error instanceof TypeError)return;throw error}let port=Number(parsed.port);if(!(parsed.protocol!=="ws:"||parsed.username!==""||parsed.password!==""||parsed.pathname!=="/"||parsed.search!==""||parsed.hash!==""||parsed.port===""||!Number.isInteger(port)||port<1||port>65535||isIP(parsed.hostname)===0))return{kind:"ws",url:value,host:parsed.hostname,port}}function parseDaemonVerb(value){switch(value){case"start":case"stop":case"status":case"restart":return value;default:return}}function parseWsAuth(value){return value==="off"?{kind:"off"}:{kind:"token-file",path:value}}function parseServerArgs(args){let listen3={kind:"stdio",url:"stdio://"},wsAuth,jsonLogs=!1;for(let index=0;index<args.length;index++){let arg=args[index];if(arg==="--listen"){let value=args[index+1];if(value===void 0)return{kind:"usage-error",message:APP_SERVER_LISTEN_USAGE};let parsed=parseListen(value);if(parsed===void 0)return{kind:"usage-error",message:APP_SERVER_LISTEN_USAGE};listen3=parsed,index++;continue}if(arg==="--ws-auth"){let value=args[index+1];if(value===void 0)return{kind:"usage-error",message:"--ws-auth requires <token-file|off>."};wsAuth=parseWsAuth(value),index++;continue}if(arg==="--json-logs"){jsonLogs=!0;continue}return{kind:"usage-error",message:`Unexpected app-server argument: ${arg}`}}return{kind:"server",listen:listen3,wsAuth,jsonLogs}}function parseDaemonArgs(args){let verb=parseDaemonVerb(args[0]);if(verb===void 0)return{kind:"usage-error",message:"Usage: app-server daemon <start|stop|status|restart>."};let listen3={kind:"ws",url:"ws://127.0.0.1:18800",host:"127.0.0.1",port:18800};for(let index=1;index<args.length;index++){let arg=args[index];if(arg==="--listen"){let value=args[index+1];if(value===void 0)return{kind:"usage-error",message:APP_SERVER_LISTEN_USAGE};let parsed=parseListen(value);if(parsed===void 0)return{kind:"usage-error",message:APP_SERVER_LISTEN_USAGE};listen3=parsed,index++;continue}return{kind:"usage-error",message:`Unexpected app-server daemon argument: ${arg}`}}return{kind:"daemon",verb,listen:listen3}}function parseAppServerCliArgs(args){return args[0]==="daemon"?parseDaemonArgs(args.slice(1)):parseServerArgs(args)}var RpcHandlerError=class extends Error{constructor(error){super(error.message),this.name="RpcHandlerError",this.rpcError=error}};function invalidRequestError(){return{code:-32600,message:"Invalid request"}}function methodNotFoundError(method){return{code:-32601,message:`Method not found: ${method}`}}function invalidParamsError(){return{code:-32602,message:"Invalid params"}}function internalError(message="Internal error"){return{code:-32603,message}}function notInitializedError(){return{code:-32600,message:"Not initialized"}}function alreadyInitializedError(){return{code:-32600,message:"Already initialized"}}function experimentalCapabilityError(method){return{code:-32600,message:`${method} requires experimentalApi capability`}}function registerExtensionRequestMethod(registry,getThread){registry.register("extension_request",{scope:"thread",handler:async({request})=>{let params=request.params;if(typeof params!="object"||params===null||Array.isArray(params))throw new RpcHandlerError({code:-32602,message:"Invalid params"});let threadId=Reflect.get(params,"threadId"),name=Reflect.get(params,"name");if(typeof threadId!="string"||threadId.length===0||typeof name!="string"||name.length===0)throw new RpcHandlerError({code:-32602,message:"Invalid params"});try{return await getThread(threadId).extensionRunner.requestRpc(name,Reflect.get(params,"data"))}catch(error){throw new RpcHandlerError(internalError(error instanceof Error?error.message:String(error)))}}})}function createRegistry(){return new InMemoryMethodRegistry}var InMemoryMethodRegistry=class{constructor(){this.methods=new Map}register(method,registration){this.methods.set(method,registration)}async dispatch(connection,request){if(!connection.initialized){let registration2=this.methods.get(request.method);if(request.method!=="initialize"||registration2?.requiresInit!==!1)return{id:request.id,error:notInitializedError()}}if(connection.initialized&&request.method==="initialize")return{id:request.id,error:alreadyInitializedError()};let registration=this.methods.get(request.method);if(!registration)return{id:request.id,error:methodNotFoundError(request.method)};if(registration.experimental===!0&&connection.capabilities?.experimentalApi!==!0)return{id:request.id,error:experimentalCapabilityError(request.method)};try{let result=await registration.handler({connection,request});return{id:request.id,result}}catch(error){return error instanceof RpcHandlerError?{id:request.id,error:error.rpcError}:{id:request.id,error:internalError(error instanceof Error?error.message:String(error))}}}};function registerFuzzyFileSearchMethods(registry,service){registry.register("fuzzyFileSearch",{scope:"global",handler:({request})=>service.search(parseOneShotParams(request.params))}),registry.register("fuzzyFileSearch/sessionStart",{experimental:!0,scope:"global",handler:({request})=>service.startSession(parseSessionStartParams(request.params))}),registry.register("fuzzyFileSearch/sessionUpdate",{experimental:!0,scope:"global",handler:({request})=>service.updateSession(parseSessionUpdateParams(request.params))}),registry.register("fuzzyFileSearch/sessionStop",{experimental:!0,scope:"global",handler:({request})=>service.stopSession(parseSessionStopParams(request.params))})}function parseOneShotParams(value){let params=objectParams(value,"fuzzyFileSearch");return{query:requiredString(params.query,"fuzzyFileSearch query"),roots:requiredStringArray(params.roots,"fuzzyFileSearch roots"),cancellationToken:optionalString(params.cancellationToken,"fuzzyFileSearch cancellationToken")}}function parseSessionStartParams(value){let params=objectParams(value,"fuzzyFileSearch/sessionStart");return{sessionId:requiredString(params.sessionId,"fuzzyFileSearch/sessionStart sessionId"),roots:requiredStringArray(params.roots,"fuzzyFileSearch/sessionStart roots")}}function parseSessionUpdateParams(value){let params=objectParams(value,"fuzzyFileSearch/sessionUpdate");return{sessionId:requiredString(params.sessionId,"fuzzyFileSearch/sessionUpdate sessionId"),query:requiredString(params.query,"fuzzyFileSearch/sessionUpdate query")}}function parseSessionStopParams(value){let params=objectParams(value,"fuzzyFileSearch/sessionStop");return{sessionId:requiredString(params.sessionId,"fuzzyFileSearch/sessionStop sessionId")}}function objectParams(value,method){if(!isRecord(value))throw invalidRequest(`${method} params must be an object`);return value}function requiredString(value,field){if(typeof value!="string")throw invalidRequest(`${field} must be a string`);return value}function requiredStringArray(value,field){if(!Array.isArray(value)||value.some(entry=>typeof entry!="string"))throw invalidRequest(`${field} must be an array of strings`);return value}function optionalString(value,field){if(value==null)return null;if(typeof value!="string")throw invalidRequest(`${field} must be a string or null`);return value}function invalidRequest(message){return new RpcHandlerError({code:-32600,message})}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}import{lstat,readdir}from"node:fs/promises";import{basename,join as join2,relative as relative2,resolve,sep as sep2}from"node:path";var import_ignore=__toESM(require_ignore(),1);import{readFile}from"node:fs/promises";import{join,relative,sep}from"node:path";async function addGitignoreScope(matchers,directory){let gitignore=await readableText(join(directory,".gitignore"));return gitignore===void 0?matchers:[...matchers,{directory,matcher:(0,import_ignore.default)().add(gitignore)}]}function isIgnored(matchers,path,isDirectory){let ignored=!1;for(let scope of matchers){let relativePath=relative(scope.directory,path).split(sep).join("/"),result=scope.matcher.test(isDirectory?`${relativePath}/`:relativePath);result.ignored&&(ignored=!0),result.unignored&&(ignored=!1)}return ignored}async function readableText(path){try{return await readFile(path,"utf8")}catch(error){if(error instanceof Error)return;throw error}}var FUZZY_SEARCH_MAX_DEPTH=12,FUZZY_SEARCH_MAX_VISITED_ENTRIES=5e4,FUZZY_SEARCH_RESULT_LIMIT=50,FILENAME_MATCH_BONUS=1e6,CHARACTER_MATCH_SCORE=10,CONTIGUOUS_MATCH_BONUS=20,BOUNDARY_MATCH_BONUS=5,CANCELLATION_YIELD_INTERVAL=256;async function collectFuzzyFileEntries(roots,options={}){let entries=[],state={visitedEntries:0,stopped:!1},maxDepth=options.maxDepth??FUZZY_SEARCH_MAX_DEPTH,maxVisitedEntries=options.maxVisitedEntries??FUZZY_SEARCH_MAX_VISITED_ENTRIES;for(let root of roots){if(options.signal?.aborted||state.stopped)break;let absoluteRoot=resolve(root),rootStat=await readableStat(absoluteRoot);!rootStat?.isDirectory()||rootStat.isSymbolicLink()||await walkDirectory({wireRoot:root,absoluteRoot,absoluteDirectory:absoluteRoot,depth:0,matchers:[],entries,state,signal:options.signal,maxDepth,maxVisitedEntries})}return entries}function rankFuzzyFileEntries(query,entries){if(query.length===0)return[];let results=[];for(let entry of entries){let filenameMatch=scoreSubsequence(entry.fileName,query),pathMatch=filenameMatch??scoreSubsequence(entry.path,query);if(!pathMatch)continue;let filenameOffset=Array.from(entry.path).length-Array.from(entry.fileName).length,indices=filenameMatch?filenameMatch.indices.map(index=>index+filenameOffset):pathMatch.indices;results.push({root:entry.root,path:entry.path,match_type:entry.matchType,file_name:entry.fileName,score:pathMatch.score+(filenameMatch?FILENAME_MATCH_BONUS:0),indices})}return results.sort(compareResults),results.slice(0,FUZZY_SEARCH_RESULT_LIMIT)}async function walkDirectory(input){let matchers=await addGitignoreScope(input.matchers,input.absoluteDirectory),directoryEntries=await readableDirectory(input.absoluteDirectory);directoryEntries.sort((left,right)=>compareText(left.name,right.name));for(let directoryEntry of directoryEntries){if(input.signal?.aborted||input.state.stopped)return;if(input.state.visitedEntries>=input.maxVisitedEntries){input.state.stopped=!0;return}if(input.state.visitedEntries+=1,directoryEntry.name===".git"||directoryEntry.name==="node_modules"||directoryEntry.isSymbolicLink())continue;let isDirectory=directoryEntry.isDirectory();if(!isDirectory&&!directoryEntry.isFile())continue;let absolutePath=join2(input.absoluteDirectory,directoryEntry.name),relativePath=toPosixPath(relative2(input.absoluteRoot,absolutePath));if(isIgnored(matchers,absolutePath,isDirectory))continue;input.entries.push({root:input.wireRoot,path:relativePath,matchType:isDirectory?"directory":"file",fileName:basename(relativePath)});let entryDepth=input.depth+1;isDirectory&&entryDepth<input.maxDepth&&await walkDirectory({...input,absoluteDirectory:absolutePath,depth:entryDepth,matchers}),input.state.visitedEntries%CANCELLATION_YIELD_INTERVAL===0&&await yieldToEventLoop()}}function scoreSubsequence(candidate,query){let normalizedCandidate=normalizeText(candidate),normalizedQuery=query.toLowerCase(),contiguousStart=normalizedCandidate.value.indexOf(normalizedQuery),normalizedIndices=[];if(contiguousStart>=0){let cursor=contiguousStart;for(let character of normalizedQuery)normalizedIndices.push(cursor),cursor+=character.length}else{let cursor=0;for(let character of normalizedQuery){let matchIndex=normalizedCandidate.value.indexOf(character,cursor);if(matchIndex<0)return;normalizedIndices.push(matchIndex),cursor=matchIndex+character.length}}let indices=[];for(let normalizedIndex of normalizedIndices){let sourceIndex=normalizedCandidate.sourceIndices[normalizedIndex];if(sourceIndex===void 0)return;indices.at(-1)!==sourceIndex&&indices.push(sourceIndex)}let candidateCharacters=Array.from(candidate),score=indices.length*CHARACTER_MATCH_SCORE;for(let index=0;index<indices.length;index++){let current=indices[index];if(current===void 0)continue;let previous=indices[index-1];previous!==void 0&¤t===previous+1&&(score+=CONTIGUOUS_MATCH_BONUS),(current===0||isBoundary(candidateCharacters[current-1]))&&(score+=BOUNDARY_MATCH_BONUS)}return{score,indices}}function normalizeText(value){let sourceIndices=[];for(let[sourceIndex,character]of Array.from(value).entries())for(let index=0;index<character.toLowerCase().length;index++)sourceIndices.push(sourceIndex);return{value:value.toLowerCase(),sourceIndices}}function compareResults(left,right){return left.score!==right.score?right.score-left.score:compareText(left.path,right.path)}function compareText(left,right){return left<right?-1:left>right?1:0}function isBoundary(character){return character==="/"||character==="-"||character==="_"||character==="."||character===" "}async function readableDirectory(path){try{return await readdir(path,{withFileTypes:!0})}catch(error){if(error instanceof Error)return[];throw error}}async function readableStat(path){try{return await lstat(path)}catch(error){if(error instanceof Error)return;throw error}}function toPosixPath(path){return path.split(sep2).join("/")}function yieldToEventLoop(){return new Promise(resolve4=>setImmediate(resolve4))}var FuzzyFileSearchService=class{constructor(options){this.activeSearches=new Set,this.pendingSearches=new Map,this.sessions=new Map,this.disposed=!1,this.broadcast=options.broadcast,this.collectEntries=options.collectEntries??((roots,signal)=>collectFuzzyFileEntries(roots,{signal})),this.rankEntries=options.rankEntries??rankFuzzyFileEntries}async search(params){if(this.disposed)return{files:[]};let controller=new AbortController;this.activeSearches.add(controller);let token=params.cancellationToken;token!==null&&(this.pendingSearches.get(token)?.abort(),this.pendingSearches.set(token,controller));try{if(params.query.length===0)return{files:[]};let entries=await this.collectEntries(params.roots,controller.signal);return controller.signal.aborted||this.disposed?{files:[]}:{files:this.rankEntries(params.query,entries)}}finally{this.activeSearches.delete(controller),token!==null&&this.pendingSearches.get(token)===controller&&this.pendingSearches.delete(token)}}startSession(params){if(params.sessionId.length===0)throw invalidRequest2("sessionId must not be empty");this.cancelSession(params.sessionId);let session={id:params.sessionId,roots:params.roots,controller:new AbortController,query:"",version:0,entries:void 0,active:!this.disposed,completedVersion:void 0};return this.sessions.set(session.id,session),this.runTraversal(session),{}}updateSession(params){let session=this.sessions.get(params.sessionId);if(!session?.active)throw invalidRequest2(`fuzzy file search session not found: ${params.sessionId}`);return session.query=params.query,session.version+=1,session.entries!==void 0&&this.emitVersion(session,session.version),{}}stopSession(params){return this.cancelSession(params.sessionId),{}}dispose(){if(!this.disposed){this.disposed=!0;for(let controller of this.activeSearches)controller.abort();this.activeSearches.clear(),this.pendingSearches.clear();for(let session of this.sessions.values())this.deactivate(session);this.sessions.clear()}}async runTraversal(session){let entries;try{entries=await this.collectEntries(session.roots,session.controller.signal)}catch(error){if(!(error instanceof Error))throw error;entries=[]}if(this.isLive(session))for(session.entries=entries;this.isLive(session);){let version=session.version;if(await this.emitVersion(session,version))break}}async emitVersion(session,version){if(await Promise.resolve(),!this.isLive(session)||session.version!==version||session.entries===void 0)return!1;if(session.completedVersion===version)return!0;let query=session.query,files=query.length===0?[]:this.rankEntries(query,session.entries);return!this.isLive(session)||session.version!==version||(this.broadcast({method:"fuzzyFileSearch/sessionUpdated",params:{sessionId:session.id,query,files}}),!this.isLive(session)||session.version!==version)?!1:(session.completedVersion=version,this.broadcast({method:"fuzzyFileSearch/sessionCompleted",params:{sessionId:session.id}}),!0)}cancelSession(sessionId){let session=this.sessions.get(sessionId);session&&(this.deactivate(session),this.sessions.get(sessionId)===session&&this.sessions.delete(sessionId))}deactivate(session){session.active=!1,session.controller.abort()}isLive(session){return!this.disposed&&session.active&&this.sessions.get(session.id)===session}};function invalidRequest2(message){return new RpcHandlerError({code:-32600,message})}var APPROVAL_DECISIONS=["accept","acceptForSession","decline","cancel"],PERMISSION_OPTIONS=["Allow once","Allow always","Deny","Deny with feedback"],CANCEL_REASON="approval request was cancelled because the turn ended",NO_SUBSCRIBER_REASON="no client connected to approve";var ApprovalBridge=class{constructor(sendToThreadSubscribers){this.nextServerRequestId=0,this.pending=new Map,this.sessionAllows=new Set,this.sendToThreadSubscribers=sendToThreadSubscribers}get pendingCount(){return this.pending.size}requestApproval(threadId,kind,payload){let allowKey=createAllowKey(threadId,kind,payload);if(allowKey&&this.sessionAllows.has(allowKey))return Promise.resolve({allow:!0,decision:"acceptForSession"});let requestId=this.nextServerRequestId;this.nextServerRequestId+=1;let request=buildApprovalRequest(threadId,requestId,kind,payload);return new Promise(resolve4=>{this.pending.set(requestId,{threadId,request,allowKey,resolve:resolve4}),!(this.sendToThreadSubscribers(threadId,request)>0)&&(this.pending.delete(requestId),resolve4({allow:!1,decision:"decline",reason:NO_SUBSCRIBER_REASON}))})}resolveResponse(response){let pending=this.pending.get(response.id);if(!pending)return!1;let decision=readDecision(response);return this.pending.delete(response.id),decision==="acceptForSession"&&pending.allowKey&&this.sessionAllows.add(pending.allowKey),this.emitResolved(pending.threadId,response.id),pending.resolve(decisionToOutcome(decision,readReason(response))),!0}replayPendingForThread(threadId){let replayed=0;for(let pending of this.pending.values())pending.threadId===threadId&&(this.sendToThreadSubscribers(threadId,pending.request),replayed+=1);return replayed}cancelPendingForThread(threadId){let cancelled=0;for(let[requestId,pending]of Array.from(this.pending.entries()))pending.threadId===threadId&&(this.pending.delete(requestId),this.emitResolved(threadId,requestId),pending.resolve({allow:!1,decision:"cancel",reason:CANCEL_REASON}),cancelled+=1);return cancelled}emitResolved(threadId,requestId){this.sendToThreadSubscribers(threadId,{method:"serverRequest/resolved",params:{threadId,requestId}})}};function buildApprovalRequest(threadId,requestId,kind,payload){let base={threadId,turnId:payload.turnId??"turn-approval",itemId:payload.itemId??(kind==="commandExecution"?"approval-command":"approval-file-change"),startedAtMs:Date.now()};return kind==="fileChange"?{id:requestId,method:"item/fileChange/requestApproval",params:{...base,reason:payload.reason??null,grantRoot:payload.grantRoot??null}}:{id:requestId,method:"item/commandExecution/requestApproval",params:{...base,approvalId:payload.approvalId??null,environmentId:payload.environmentId??null,reason:payload.reason??null,command:payload.command??null,cwd:payload.cwd??null,availableDecisions:[...APPROVAL_DECISIONS]}}}function decisionToOutcome(decision,reason){return decision==="accept"||decision==="acceptForSession"?{allow:!0,decision}:reason?{allow:!1,decision,reason}:{allow:!1,decision}}function readDecision(response){let decision=isRecord2(response.result)?response.result.decision:void 0;return isApprovalDecision(decision)?decision:"cancel"}function readReason(response){let resultReason=isRecord2(response.result)?response.result.reason??response.result.message:void 0,errorReason=isRecord2(response.error)?response.error.message:void 0,reason=typeof resultReason=="string"?resultReason:errorReason;return typeof reason=="string"&&reason.length>0?reason:void 0}function createAllowKey(threadId,kind,payload){if(!(!payload.toolName||typeof payload.command!="string"))return`${threadId}\0${kind}\0${payload.toolName}\0${payload.command}`}function isApprovalDecision(value){return value==="accept"||value==="acceptForSession"||value==="decline"||value==="cancel"}function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function createAppServerUIContext(bridge,threadId,userInput,getTurnId=()=>"turn-user-input"){let pendingInput,editorText="",editorFactory,toolsExpanded=!1;return{question(request,opts){return userInput?.requestUserInput(threadId,getTurnId(),request.requestId,request,opts)??Promise.resolve({status:"unavailable",answers:{},unanswered:request.questions.map(question=>question.id)})},async select(title,options){let prompt=parsePermissionPrompt(title);if(!prompt||!isPermissionOptions(options))return;let outcome=await bridge.requestApproval(threadId,prompt.kind,{turnId:"turn-approval",itemId:`approval-${prompt.toolName}`,toolName:prompt.toolName,command:prompt.command,reason:prompt.reason});return outcome.decision==="accept"?"Allow once":outcome.decision==="acceptForSession"?"Allow always":outcome.reason&&outcome.reason!==NO_SUBSCRIBER_REASON&&outcome.reason!==CANCEL_REASON?(pendingInput=outcome.reason,"Deny with feedback"):"Deny"},async confirm(title,message){return(await bridge.requestApproval(threadId,"commandExecution",{turnId:"turn-approval",itemId:"approval-confirm",toolName:"confirm",command:title,reason:message})).allow},async input(){let value=pendingInput;return pendingInput=void 0,value},notify(){},onTerminalInput(){return()=>{}},setStatus(){},setWorkingMessage(){},setWorkingVisible(){},setWorkingIndicator(){},setHiddenThinkingLabel(){},setWidget(){},setFooter(){},setHeader(){},setTitle(){},custom(){return Promise.reject(new Error("Custom UI is not available in app-server mode."))},pasteToEditor(text){editorText=text},setEditorText(text){editorText=text},getEditorText(){return editorText},async editor(_title,prefill){return prefill},addAutocompleteProvider(){},setEditorComponent(factory){editorFactory=factory},getEditorComponent(){return editorFactory},theme,getAllThemes:getAvailableThemesWithPaths,getTheme(name){return getThemeByName(name)},setTheme(_nextTheme){return{success:!1,error:"Theme switching is not available in app-server mode."}},getToolsExpanded(){return toolsExpanded},setToolsExpanded(expanded){toolsExpanded=expanded}}}function parsePermissionPrompt(title){let[firstLine="",...rest]=title.split(`
|
|
4
4
|
`),prefix="Permission required: ";if(!firstLine.startsWith(prefix))return;let toolName=firstLine.slice(prefix.length).trim(),reason=rest.join(`
|
|
5
5
|
`).trim();return{kind:permissionKind(toolName),toolName,command:readLineValue(reason,"Command: $ ")??readLineValue(reason,"File: ")??readLineValue(reason,"Path: ")??null,reason}}function permissionKind(toolName){return toolName==="edit"||toolName==="write"||toolName==="apply_patch"||toolName==="multiedit"?"fileChange":"commandExecution"}function readLineValue(text,prefix){return text.split(`
|
package/dist/bundle/chunks/{azure-openai-responses-4SUOOZZ4.js → azure-openai-responses-FCZNBRWE.js}
RENAMED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{AzureOpenAI}from"./chunk-CD2HJK4C.js";import{clampOpenAIPromptCacheKey}from"./chunk-AEJUOQ7U.js";import{convertResponsesMessages,convertResponsesTools,processResponsesStream}from"./chunk-ELFCNCBY.js";import{formatProviderError,normalizeProviderError}from"./chunk-
|
|
2
|
+
import{AzureOpenAI}from"./chunk-CD2HJK4C.js";import{clampOpenAIPromptCacheKey}from"./chunk-AEJUOQ7U.js";import{convertResponsesMessages,convertResponsesTools,processResponsesStream}from"./chunk-ELFCNCBY.js";import{formatProviderError,normalizeProviderError}from"./chunk-BBK6SSYT.js";import{getPiUserAgent}from"./chunk-QTG7MY2X.js";import{retryProviderRequest}from"./chunk-KLBKUBDV.js";import{buildBaseOptions}from"./chunk-SYQVC7UM.js";import"./chunk-45SZOLCU.js";import"./chunk-BPX6QWPD.js";import{clampThinkingLevel,createGrammarToolInputProperties,supportsMax}from"./chunk-WL5EQYNL.js";import"./chunk-WDTJ6JKE.js";import{getProviderEnvValue}from"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import{AssistantMessageEventStream}from"./chunk-DMI55M2N.js";import{headersToRecord}from"./chunk-BQVVQ2LQ.js";import"./chunk-IKOFCODM.js";var DEFAULT_AZURE_API_VERSION="v1",AZURE_TOOL_CALL_PROVIDERS=new Set(["openai","chatgpt-subscription","opencode","azure-openai-responses"]),OPENAI_RESPONSES_MIN_OUTPUT_TOKENS=16;function parseDeploymentNameMap(value){let map=new Map;if(!value)return map;for(let entry of value.split(",")){let trimmed=entry.trim();if(!trimmed)continue;let[modelId,deploymentName]=trimmed.split("=",2);!modelId||!deploymentName||map.set(modelId.trim(),deploymentName.trim())}return map}function resolveDeploymentName(model,options){return options?.azureDeploymentName?options.azureDeploymentName:parseDeploymentNameMap(getProviderEnvValue("AZURE_OPENAI_DEPLOYMENT_NAME_MAP",options?.env)).get(model.id)||model.id}function formatAzureOpenAIError(error){return formatProviderError(normalizeProviderError(error),"Azure OpenAI API error")}var stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream;return(async()=>{let deploymentName=resolveDeploymentName(model,options),output={role:"assistant",content:[],api:"azure-openai-responses",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let client=createClient(model,apiKey,options),grammarToolInputProperties=createGrammarToolInputProperties(context.tools,model.compat?.supportsOpenAIGrammarTools??!1),params=buildParams(model,context,options,deploymentName,grammarToolInputProperties),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let requestOptions={...options?.signal?{signal:options.signal}:{},...options?.timeoutMs!==void 0?{timeout:options.timeoutMs}:{},maxRetries:0},{data:openaiStream,response}=await retryProviderRequest(()=>client.responses.create(params,requestOptions).withResponse(),{maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,signal:options?.signal});if(await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),stream2.push({type:"start",partial:output}),await processResponsesStream(openaiStream,output,stream2,model,{grammarToolInputProperties}),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Azure OpenAI Responses stream ended without a stop reason");if(output.stopReason==="aborted"||output.stopReason==="error")throw new Error(output.errorMessage||"An unknown error occurred");stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)delete block.index,delete block.partialJson,delete block.customInput;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatAzureOpenAIError(error),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let base={...buildBaseOptions(model,context,options,apiKey),toolChoice:options?.toolChoice},clampedReasoning=options?.reasoning?clampThinkingLevel(model,options.reasoning):void 0,reasoningEffort=clampedReasoning==="off"?void 0:clampedReasoning==="max"&&supportsMax(model)?"max":clampedReasoning==="max"?"high":clampedReasoning;return stream(model,context,{...base,reasoningEffort})};function normalizeAzureBaseUrl(baseUrl){let trimmed=baseUrl.trim().replace(/\/+$/,""),url;try{url=new URL(trimmed)}catch{throw new Error(`Invalid Azure OpenAI base URL: ${baseUrl}`)}let isAzureHost=url.hostname.endsWith(".openai.azure.com")||url.hostname.endsWith(".cognitiveservices.azure.com")||url.hostname.endsWith(".ai.azure.com"),normalizedPath=url.pathname.replace(/\/+$/,"");return isAzureHost&&(normalizedPath===""||normalizedPath==="/"||normalizedPath==="/openai"||normalizedPath==="/openai/v1/responses")&&(url.pathname="/openai/v1",url.search=""),url.toString().replace(/\/+$/,"")}function buildDefaultBaseUrl(resourceName){return`https://${resourceName}.openai.azure.com/openai/v1`}function resolveAzureConfig(model,options){let apiVersion=options?.azureApiVersion||getProviderEnvValue("AZURE_OPENAI_API_VERSION",options?.env)||DEFAULT_AZURE_API_VERSION,baseUrl=options?.azureBaseUrl?.trim()||getProviderEnvValue("AZURE_OPENAI_BASE_URL",options?.env)?.trim()||void 0,resourceName=options?.azureResourceName||getProviderEnvValue("AZURE_OPENAI_RESOURCE_NAME",options?.env),resolvedBaseUrl=baseUrl;if(!resolvedBaseUrl&&resourceName&&(resolvedBaseUrl=buildDefaultBaseUrl(resourceName)),!resolvedBaseUrl&&model.baseUrl&&(resolvedBaseUrl=model.baseUrl),!resolvedBaseUrl)throw new Error("Azure OpenAI base URL is required. Set AZURE_OPENAI_BASE_URL or AZURE_OPENAI_RESOURCE_NAME, or pass azureBaseUrl, azureResourceName, or model.baseUrl.");return{baseUrl:normalizeAzureBaseUrl(resolvedBaseUrl),apiVersion}}function createClient(model,apiKey,options){let headers={"User-Agent":getPiUserAgent(),...model.headers};options?.headers&&Object.assign(headers,options.headers);let{baseUrl,apiVersion}=resolveAzureConfig(model,options);return new AzureOpenAI({apiKey,apiVersion,dangerouslyAllowBrowser:!0,fetch:options?.fetch,defaultHeaders:headers,baseURL:baseUrl})}function buildParams(model,context,options,deploymentName,grammarToolInputProperties=createGrammarToolInputProperties(context.tools,model.compat?.supportsOpenAIGrammarTools??!1)){let requestedReasoningEffort=options?.reasoningEffort??(options?.reasoningSummary?"medium":void 0),mappedReasoningEffort=requestedReasoningEffort===void 0?void 0:model.thinkingLevelMap?.[requestedReasoningEffort],reasoningEffort=mappedReasoningEffort===void 0?requestedReasoningEffort:mappedReasoningEffort,reasoningRequested=reasoningEffort!=null,reasoningUnavailable=reasoningEffort===null,messages=convertResponsesMessages(model,context,AZURE_TOOL_CALL_PROVIDERS,{grammarToolInputProperties}),params={model:deploymentName,input:messages,stream:!0,...(options?.cacheRetention??model.cacheRetention)==="none"?{}:{prompt_cache_key:clampOpenAIPromptCacheKey(options?.sessionId)},store:!1};return options?.maxTokens&&(params.max_output_tokens=Math.max(options.maxTokens,OPENAI_RESPONSES_MIN_OUTPUT_TOKENS)),options?.temperature!==void 0&&(params.temperature=options?.temperature),context.tools&&context.tools.length>0&&(params.tools=convertResponsesTools(context.tools,{supportsStrictMode:model.compat?.supportsStrictMode??!0,supportsOpenAIGrammarTools:model.compat?.supportsOpenAIGrammarTools??!1})),options?.toolChoice!==void 0&&(params.tool_choice=options.toolChoice),model.reasoning&&(reasoningRequested?(params.reasoning={effort:reasoningEffort,...options?.reasoningSummary===null?{}:{summary:options?.reasoningSummary||"auto"}},params.include=["reasoning.encrypted_content"]):!reasoningUnavailable&&model.thinkingLevelMap?.off!==null&&(params.reasoning={effort:model.thinkingLevelMap?.off??"none"})),options?.samplingParams&&Object.assign(params,options.samplingParams),params}export{stream,streamSimple};
|
|
@@ -73,5 +73,5 @@ Reference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.ht
|
|
|
73
73
|
`);let{connect:connect5,buffered}=await proxyResponsePromise;if(req.emit("proxyConnect",connect5),this.emit("proxyConnect",connect5,req),req.emit("proxy",{proxy:this.proxy.href,socket}),connect5.statusCode===200)return req.once("socket",resume),opts.secureEndpoint?(debug3("Upgrading socket connection to TLS"),tls2.connect({...omit2(setServernameFromNonIpHost(opts),"host","path","port"),socket})):socket;if(connect5.statusCode===407&&this.onProxyAuth){debug3("Got 407 response, invoking onProxyAuth callback"),socket.destroy();let proxyAuthenticate=connect5.headers["proxy-authenticate"]||"",scheme=Array.isArray(proxyAuthenticate)?proxyAuthenticate[0].split(/\s/)[0]:proxyAuthenticate.split(/\s/)[0],authResponse=await this.onProxyAuth({response:connect5,scheme});return this._connectWithAuth(req,opts,authResponse.headers)}socket.destroy();let fakeSocket=new net3.Socket({writable:!1});return fakeSocket.readable=!0,req.once("socket",s2=>{debug3("Replaying proxy buffer for failed request"),assert(s2.listenerCount("data")>0),s2.push(buffered),s2.push(null)}),fakeSocket}async _connectWithAuth(req,opts,authHeaders){let{proxy}=this,socket;proxy.protocol==="https:"?socket=tls2.connect(setServernameFromNonIpHost(this.connectOpts)):socket=net3.connect(this.connectOpts);let headers=typeof this.proxyHeaders=="function"?this.proxyHeaders():{...this.proxyHeaders},host=net3.isIPv6(opts.host)?`[${opts.host}]`:opts.host,payload2=`CONNECT ${host}:${opts.port} HTTP/1.1\r
|
|
74
74
|
`;if(proxy.username||proxy.password){let auth=`${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;headers["Proxy-Authorization"]=`Basic ${Buffer.from(auth).toString("base64")}`}Object.assign(headers,authHeaders),headers.Host=`${host}:${opts.port}`,headers["Proxy-Connection"]||(headers["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close");for(let name of Object.keys(headers))payload2+=`${name}: ${headers[name]}\r
|
|
75
75
|
`;let proxyResponsePromise=parseProxyResponse(socket);socket.write(`${payload2}\r
|
|
76
|
-
`);let{connect:connect5}=await proxyResponsePromise;if(req.emit("proxyConnect",connect5),this.emit("proxyConnect",connect5,req),connect5.statusCode===200)return req.once("socket",resume),opts.secureEndpoint?(debug3("Upgrading socket connection to TLS"),tls2.connect({...omit2(setServernameFromNonIpHost(opts),"host","path","port"),socket})):socket;throw socket.destroy(),new Error(`Proxy authentication failed with status ${connect5.statusCode} after retry`)}};HttpsProxyAgent.protocols=["http","https"];function resume(socket){setImmediate(()=>{socket.resume()})}function omit2(obj,...keys){let ret={},key;for(key in obj)keys.includes(key)||(ret[key]=obj[key]);return ret}var FifoQueue=class{constructor(){this.incoming=[],this.outgoing=[]}get length(){return this.incoming.length+this.outgoing.length}enqueue(value){this.incoming.push(value)}dequeue(){if(this.outgoing.length===0)for(;this.incoming.length>0;)this.outgoing.push(this.incoming.pop());return this.outgoing.pop()}},EventStream=class{#queue;#queueHead;#failed;#error;#localWorkDepth;constructor(isComplete,extractResult){this.#queue=[],this.#queueHead=0,this.waiting=new FifoQueue,this.done=!1,this.#failed=!1,this.#localWorkDepth=0,this.isComplete=isComplete,this.extractResult=extractResult,this.finalResultPromise=new Promise((resolve,reject)=>{this.resolveFinalResult=resolve,this.rejectFinalResult=reject}),this.finalResultPromise.catch(()=>{})}get queue(){return this.#queue.slice(this.#queueHead)}#enqueue(event){this.#queue.push(event)}#dequeue(){let event=this.#queue[this.#queueHead];if(event===void 0)throw new Error("EventStream queue underflow");return this.#queueHead++,this.#queueHead>1024&&this.#queueHead*2>=this.#queue.length&&(this.#queue=this.#queue.slice(this.#queueHead),this.#queueHead=0),event}push(event){if(this.done)return;this.isComplete(event)&&(this.done=!0,this.resolveFinalResult(this.extractResult(event)));let waiter=this.waiting.dequeue();waiter?waiter.resolve({value:event,done:!1}):this.#enqueue(event)}end(result){for(this.done=!0,result!==void 0&&this.resolveFinalResult(result);this.waiting.length>0;){let waiter=this.waiting.dequeue();waiter&&waiter.resolve({value:void 0,done:!0})}}fail(error2){if(!this.done)for(this.done=!0,this.#failed=!0,this.#error=error2,this.rejectFinalResult(error2);this.waiting.length>0;){let waiter=this.waiting.dequeue();waiter&&waiter.reject(error2)}}[Symbol.asyncIterator](){return{next:()=>this.#queueHead<this.#queue.length?Promise.resolve({value:this.#dequeue(),done:!1}):this.#failed?Promise.reject(this.#error):this.done?Promise.resolve({value:void 0,done:!0}):new Promise((resolve,reject)=>this.waiting.enqueue({resolve,reject}))}}result(){return this.finalResultPromise}async trackLocalWork(work){this.#localWorkDepth++;try{return await work}finally{this.#localWorkDepth--}}hasPendingLocalWork(){return this.#localWorkDepth>0}},AssistantMessageEventStream=class extends EventStream{constructor(){super(event=>event.type==="done"||event.type==="error",event=>{if(event.type==="done")return event.message;if(event.type==="error")return event.error;throw new Error("Unexpected event type for final result")})}};function appendAssistantMessageDiagnostic(message,diagnostic){message.diagnostics=[...message.diagnostics??[],diagnostic]}function calculateCost(model,usage){let inputTokens=usage.input+usage.cacheRead+usage.cacheWrite,rates=model.cost,matchedThreshold=-1;for(let tier of model.cost.tiers??[])inputTokens>tier.inputTokensAbove&&tier.inputTokensAbove>matchedThreshold&&(rates=tier,matchedThreshold=tier.inputTokensAbove);let longWrite=usage.cacheWrite1h??0,shortWrite=usage.cacheWrite-longWrite;return usage.cost.input=rates.input/1e6*usage.input,usage.cost.output=rates.output/1e6*usage.output,usage.cost.cacheRead=rates.cacheRead/1e6*usage.cacheRead,usage.cost.cacheWrite=(rates.cacheWrite*shortWrite+rates.input*2*longWrite)/1e6,usage.cost.total=usage.cost.input+usage.cost.output+usage.cost.cacheRead+usage.cost.cacheWrite,usage.cost}function normalizeProviderError(error2){if(!(error2 instanceof Error))return{message:safeJsonStringify(error2),messageCarriesBody:!1};let sdkError=error2,status=extractStatus(sdkError),body=extractBody(sdkError),messageCarriesBody=body===void 0||error2.message.includes(body);return{status,body,message:error2.message,messageCarriesBody}}function extractStatus(error2){if(typeof error2.statusCode=="number")return error2.statusCode;if(typeof error2.status=="number")return error2.status;if(typeof error2.$metadata?.httpStatusCode=="number")return error2.$metadata.httpStatusCode;if(typeof error2.$response?.statusCode=="number")return error2.$response.statusCode}function extractBody(error2){let bodyText=pickBodyText(error2);if(bodyText===void 0)return;let trimmed=bodyText.trim();if(trimmed.length!==0)return truncateErrorText(trimmed,4e3)}function pickBodyText(error2){if(typeof error2.body=="string")return error2.body;if(isPlainNonEmptyObject(error2.error))return safeJsonStringify(error2.error);let responseBody=error2.$response?.body;if(typeof responseBody=="string")return responseBody;if(!isReadableStreamLike(responseBody)&&isPlainNonEmptyObject(responseBody))return safeJsonStringify(responseBody)}function isReadableStreamLike(value){return typeof value=="object"&&value!==null&&"pipe"in value&&typeof value.pipe=="function"}function isPlainNonEmptyObject(value){if(typeof value!="object"||value===null)return!1;let proto=Object.getPrototypeOf(value);return proto!==Object.prototype&&proto!==null?!1:Object.keys(value).length>0}function truncateErrorText(text,maxChars){return text.length<=maxChars?text:`${text.slice(0,maxChars)}... [truncated ${text.length-maxChars} chars]`}function safeJsonStringify(value){try{let serialized=JSON.stringify(value);return serialized===void 0?String(value):serialized}catch{return String(value)}}function providerHeadersToRecord(headers){if(!headers)return;let result={};for(let[key,value]of Object.entries(headers))value!==null&&(result[key]=value);return Object.keys(result).length>0?result:void 0}var import_partial_json=__toESM(require_dist(),1),VALID_JSON_ESCAPES=new Set(['"',"\\","/","b","f","n","r","t","u"]);function isControlCharacter(char){let codePoint=char.codePointAt(0);return codePoint!==void 0&&codePoint>=0&&codePoint<=31}function escapeControlCharacter(char){switch(char){case"\b":return"\\b";case"\f":return"\\f";case`
|
|
76
|
+
`);let{connect:connect5}=await proxyResponsePromise;if(req.emit("proxyConnect",connect5),this.emit("proxyConnect",connect5,req),connect5.statusCode===200)return req.once("socket",resume),opts.secureEndpoint?(debug3("Upgrading socket connection to TLS"),tls2.connect({...omit2(setServernameFromNonIpHost(opts),"host","path","port"),socket})):socket;throw socket.destroy(),new Error(`Proxy authentication failed with status ${connect5.statusCode} after retry`)}};HttpsProxyAgent.protocols=["http","https"];function resume(socket){setImmediate(()=>{socket.resume()})}function omit2(obj,...keys){let ret={},key;for(key in obj)keys.includes(key)||(ret[key]=obj[key]);return ret}var FifoQueue=class{constructor(){this.incoming=[],this.outgoing=[]}get length(){return this.incoming.length+this.outgoing.length}enqueue(value){this.incoming.push(value)}dequeue(){if(this.outgoing.length===0)for(;this.incoming.length>0;)this.outgoing.push(this.incoming.pop());return this.outgoing.pop()}},EventStream=class{#queue;#queueHead;#failed;#error;#localWorkDepth;constructor(isComplete,extractResult){this.#queue=[],this.#queueHead=0,this.waiting=new FifoQueue,this.done=!1,this.#failed=!1,this.#localWorkDepth=0,this.isComplete=isComplete,this.extractResult=extractResult,this.finalResultPromise=new Promise((resolve,reject)=>{this.resolveFinalResult=resolve,this.rejectFinalResult=reject}),this.finalResultPromise.catch(()=>{})}get queue(){return this.#queue.slice(this.#queueHead)}#enqueue(event){this.#queue.push(event)}#dequeue(){let event=this.#queue[this.#queueHead];if(event===void 0)throw new Error("EventStream queue underflow");return this.#queueHead++,this.#queueHead>1024&&this.#queueHead*2>=this.#queue.length&&(this.#queue=this.#queue.slice(this.#queueHead),this.#queueHead=0),event}push(event){if(this.done)return;this.isComplete(event)&&(this.done=!0,this.resolveFinalResult(this.extractResult(event)));let waiter=this.waiting.dequeue();waiter?waiter.resolve({value:event,done:!1}):this.#enqueue(event)}end(result){for(this.done=!0,result!==void 0&&this.resolveFinalResult(result);this.waiting.length>0;){let waiter=this.waiting.dequeue();waiter&&waiter.resolve({value:void 0,done:!0})}}fail(error2){if(!this.done)for(this.done=!0,this.#failed=!0,this.#error=error2,this.rejectFinalResult(error2);this.waiting.length>0;){let waiter=this.waiting.dequeue();waiter&&waiter.reject(error2)}}[Symbol.asyncIterator](){return{next:()=>this.#queueHead<this.#queue.length?Promise.resolve({value:this.#dequeue(),done:!1}):this.#failed?Promise.reject(this.#error):this.done?Promise.resolve({value:void 0,done:!0}):new Promise((resolve,reject)=>this.waiting.enqueue({resolve,reject}))}}result(){return this.finalResultPromise}async trackLocalWork(work){this.#localWorkDepth++;try{return await work}finally{this.#localWorkDepth--}}hasPendingLocalWork(){return this.#localWorkDepth>0}},AssistantMessageEventStream=class extends EventStream{constructor(){super(event=>event.type==="done"||event.type==="error",event=>{if(event.type==="done")return event.message;if(event.type==="error")return event.error;throw new Error("Unexpected event type for final result")})}};function appendAssistantMessageDiagnostic(message,diagnostic){message.diagnostics=[...message.diagnostics??[],diagnostic]}function calculateCost(model,usage){let inputTokens=usage.input+usage.cacheRead+usage.cacheWrite,rates=model.cost,matchedThreshold=-1;for(let tier of model.cost.tiers??[])inputTokens>tier.inputTokensAbove&&tier.inputTokensAbove>matchedThreshold&&(rates=tier,matchedThreshold=tier.inputTokensAbove);let longWrite=usage.cacheWrite1h??0,shortWrite=usage.cacheWrite-longWrite;return usage.cost.input=rates.input/1e6*usage.input,usage.cost.output=rates.output/1e6*usage.output,usage.cost.cacheRead=rates.cacheRead/1e6*usage.cacheRead,usage.cost.cacheWrite=(rates.cacheWrite*shortWrite+rates.input*2*longWrite)/1e6,usage.cost.total=usage.cost.input+usage.cost.output+usage.cost.cacheRead+usage.cost.cacheWrite,usage.cost}var RATE_LIMIT_BODY_RE=/\b(rate_limit_error|rate_limit_exceeded|too_many_requests|resource_exhausted|rate limit (?:exceeded|hit)|too many requests)\b/i,RATE_LIMIT_JSON_VALUES=new Set(["rate_limit_error","rate_limit_exceeded","too_many_requests","resource_exhausted"]),RETRY_AFTER_MS_RE=/^\d+(?:\.\d+)?$/,DELTA_SECONDS_RE=/^\d+$/;function isRateLimited(status,bodyText){if(status===429||RATE_LIMIT_BODY_RE.test(bodyText))return!0;let json=tryParseJSON(bodyText);return!!(json!==void 0&&scanValue(json,(v,k5)=>!!(k5!==void 0&&k5.toLowerCase()==="retrydelay"&&typeof v=="string"||typeof v=="string"&&RATE_LIMIT_JSON_VALUES.has(v)||v===429)))}function fromRetryAfterMsHeader(h5){let raw=h5?.get("retry-after-ms");if(raw==null||!RETRY_AFTER_MS_RE.test(raw))return;let val=Number.parseFloat(raw);if(!(!Number.isFinite(val)||val<0))return Math.ceil(val)}function fromRetryAfterHeader(h5,nowMs){let raw=h5?.get("retry-after");if(raw!=null){if(DELTA_SECONDS_RE.test(raw))return Number.parseInt(raw,10)*1e3;if(/[a-zA-Z]/.test(raw)){let parsed=Date.parse(raw);if(!Number.isNaN(parsed)){let base=dateHeaderMs(h5)??nowMs;return clampAbsolute(parsed,base)}}}}function fromXRateLimitReset(h5,nowMs){let best;for(let key of["x-ratelimit-reset","x-ratelimit-reset-requests","x-ratelimit-reset-tokens"]){let raw=h5?.get(key);if(raw==null)continue;let epoch=Number.parseFloat(raw);if(!Number.isFinite(epoch)||epoch<0||!/^\d+(?:\.\d+)?$/.test(raw))continue;let delta=Math.ceil(epoch*1e3-nowMs),clamped=Math.max(0,delta);(best===void 0||clamped>best)&&(best=clamped)}return best}var RETRY_DELAY_RE=/^(\d+(?:\.\d+)?)\s*(ms|s|m)$/;function fromJsonRetryDelay(bodyText){let json=tryParseJSON(bodyText);if(json===void 0)return;let best;return scanValue(json,v=>{if(typeof v!="string")return!1;let m3=v.match(RETRY_DELAY_RE);if(!m3)return!1;let num=Number.parseFloat(m3[1]),unit=m3[2],ms=unit==="ms"?num:unit==="s"?num*1e3:num*6e4,intMs=Math.ceil(ms);return(best===void 0||intMs>best)&&(best=intMs),!1}),best}function fromBodyProse(bodyText,nowMs){let m3=bodyText.match(/retry-after-ms:\s*(\d+)/i);if(m3)return Number.parseInt(m3[1],10);if(m3=bodyText.match(/retry-after:\s*(\d+)/i),m3)return Number.parseInt(m3[1],10)*1e3;if(m3=bodyText.match(/(?:try again|retry|wait after).*?(?:in\s+)?(\d+(?:\.\d+)?)\s*(ms|s|sec|seconds?|m|min|minutes?)\b/i),m3)return convertUnit(Number.parseFloat(m3[1]),m3[2]);if(m3=bodyText.match(/resets?\s+at\s+(\S+)/i),m3){let parsed=Date.parse(m3[1]);if(!Number.isNaN(parsed))return clampAbsolute(parsed,nowMs)}}function dateHeaderMs(h5){let raw=h5?.get("date");if(raw==null)return;let parsed=Date.parse(raw);return Number.isNaN(parsed)?void 0:parsed}function clampAbsolute(targetMs,baseMs){return Math.max(0,targetMs-baseMs)}function convertUnit(num,unit){let u=unit.toLowerCase();return Math.ceil(u==="ms"?num:u==="s"||u==="sec"||u==="second"||u==="seconds"?num*1e3:num*6e4)}function scanValue(value,fn,key){if(value===null)return fn(null,key);if(typeof value=="string"||typeof value=="number"||typeof value=="boolean")return fn(value,key);if(Array.isArray(value)){for(let item of value)if(scanValue(item,fn,key))return!0;return!1}if(typeof value=="object"){for(let[k5,v]of Object.entries(value))if(scanValue(v,fn,k5))return!0;return!1}return!1}function tryParseJSON(text){let cleaned=text.replace(/^data:\s*/gm,"").trim();if(!(!cleaned.startsWith("{")&&!cleaned.startsWith("[")))try{return JSON.parse(cleaned)}catch{return}}function extract429RetryAfterMs(input,nowMs){let now=nowMs??Date.now();if(!isRateLimited(input.status,input.bodyText))return;let fromMs=fromRetryAfterMsHeader(input.headers);if(fromMs!==void 0)return fromMs;let fromRa=fromRetryAfterHeader(input.headers,now);if(fromRa!==void 0)return fromRa;let fromXrl=fromXRateLimitReset(input.headers,now);if(fromXrl!==void 0)return fromXrl;let fromJson=fromJsonRetryDelay(input.bodyText);return fromJson!==void 0?fromJson:fromBodyProse(input.bodyText,now)}var MAX_PROVIDER_ERROR_BODY_CHARS=4e3;function normalizeProviderError(error2){if(!(error2 instanceof Error))return{message:safeJsonStringify(error2),messageCarriesBody:!1};let sdkError=error2,status=extractStatus(sdkError),body=extractBody(sdkError),messageCarriesBody=body===void 0||error2.message.includes(body),retryAfterMs=extractRetryAfterMs(sdkError,status);return{status,body,message:error2.message,messageCarriesBody,...retryAfterMs===void 0?{}:{retryAfterMs}}}function extractStatus(error2){if(typeof error2.statusCode=="number")return error2.statusCode;if(typeof error2.status=="number")return error2.status;if(typeof error2.$metadata?.httpStatusCode=="number")return error2.$metadata.httpStatusCode;if(typeof error2.$response?.statusCode=="number")return error2.$response.statusCode}function extractBody(error2){let bodyText=pickBodyText(error2);if(bodyText===void 0)return;let trimmed=bodyText.trim();if(trimmed.length!==0)return truncateErrorText(trimmed,MAX_PROVIDER_ERROR_BODY_CHARS)}function pickBodyText(error2){if(typeof error2.body=="string")return error2.body;if(isPlainNonEmptyObject(error2.error))return safeJsonStringify(error2.error);let responseBody=error2.$response?.body;if(typeof responseBody=="string")return responseBody;if(!isReadableStreamLike(responseBody)&&isPlainNonEmptyObject(responseBody))return safeJsonStringify(responseBody)}function isReadableStreamLike(value){return typeof value=="object"&&value!==null&&"pipe"in value&&typeof value.pipe=="function"}function isPlainNonEmptyObject(value){if(typeof value!="object"||value===null)return!1;let proto=Object.getPrototypeOf(value);return proto!==Object.prototype&&proto!==null?!1:Object.keys(value).length>0}function extractRetryAfterMs(error2,status){if(status!==429&&status!==503)return;let headers=toHeaders(error2.headers);if(headers!==void 0)return extract429RetryAfterMs({status:429,headers,bodyText:""})}function toHeaders(value){if(value instanceof Headers)return value;if(typeof value!="object"||value===null)return;let headers=new Headers;for(let[key,entry]of Object.entries(value))typeof entry=="string"&&headers.set(key,entry);return headers}function truncateErrorText(text,maxChars){return text.length<=maxChars?text:`${text.slice(0,maxChars)}... [truncated ${text.length-maxChars} chars]`}function safeJsonStringify(value){try{let serialized=JSON.stringify(value);return serialized===void 0?String(value):serialized}catch{return String(value)}}function providerHeadersToRecord(headers){if(!headers)return;let result={};for(let[key,value]of Object.entries(headers))value!==null&&(result[key]=value);return Object.keys(result).length>0?result:void 0}var import_partial_json=__toESM(require_dist(),1),VALID_JSON_ESCAPES=new Set(['"',"\\","/","b","f","n","r","t","u"]);function isControlCharacter(char){let codePoint=char.codePointAt(0);return codePoint!==void 0&&codePoint>=0&&codePoint<=31}function escapeControlCharacter(char){switch(char){case"\b":return"\\b";case"\f":return"\\f";case`
|
|
77
77
|
`:return"\\n";case"\r":return"\\r";case" ":return"\\t";default:return`\\u${char.codePointAt(0)?.toString(16).padStart(4,"0")??"0000"}`}}function repairJson(json){let repaired="",inString=!1;for(let index=0;index<json.length;index++){let char=json[index];if(!inString){repaired+=char,char==='"'&&(inString=!0);continue}if(char==='"'){repaired+=char,inString=!1;continue}if(char==="\\"){let nextChar=json[index+1];if(nextChar===void 0){repaired+="\\\\";continue}if(nextChar==="u"){let unicodeDigits=json.slice(index+2,index+6);if(/^[0-9a-fA-F]{4}$/.test(unicodeDigits)){repaired+=`\\u${unicodeDigits}`,index+=5;continue}}if(VALID_JSON_ESCAPES.has(nextChar)){repaired+=`\\${nextChar}`,index+=1;continue}repaired+="\\\\";continue}repaired+=isControlCharacter(char)?escapeControlCharacter(char):char}return repaired}function parseJsonWithRepair(json){try{return JSON.parse(json)}catch(error2){let repairedJson=repairJson(json);if(repairedJson!==json)return JSON.parse(repairedJson);throw error2}}function parseStreamingJson(partialJson){if(!partialJson||partialJson.trim()==="")return{};try{return parseJsonWithRepair(partialJson)}catch{try{return(0,import_partial_json.parse)(partialJson)??{}}catch{try{return(0,import_partial_json.parse)(repairJson(partialJson))??{}}catch{return{}}}}}var procEnvCache=null;function getBunSandboxEnvValue(name){if(!(typeof process>"u"||!process.versions?.bun||Object.keys(process.env).length>0)){if(procEnvCache===null){procEnvCache=new Map;try{let{readFileSync}=__require("node:fs"),data=readFileSync("/proc/self/environ","utf-8");for(let entry of data.split("\0")){let idx=entry.indexOf("=");idx>0&&procEnvCache.set(entry.slice(0,idx),entry.slice(idx+1))}}catch{}}return procEnvCache.get(name)}}function getProviderEnvValue(name,env2){return env2?.[name]||(typeof process<"u"?process.env[name]:void 0)||getBunSandboxEnvValue(name)||void 0}var DEFAULT_PROXY_PORTS={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function getProxyEnv(key,env2){let lowercaseKey=key.toLowerCase(),uppercaseKey=key.toUpperCase();return env2?.[lowercaseKey]||env2?.[uppercaseKey]||getProviderEnvValue(lowercaseKey)||getProviderEnvValue(uppercaseKey)||""}function parseProxyTargetUrl(targetUrl){if(targetUrl instanceof URL)return targetUrl;try{return new URL(targetUrl)}catch{return}}function stripBrackets(host){return host.startsWith("[")&&host.endsWith("]")?host.slice(1,-1):host}function parseNoProxyEntry(entry){let trimmed=entry.trim().toLowerCase();if(!trimmed)return;if(trimmed.startsWith("[")){let closingBracket=trimmed.indexOf("]");if(closingBracket!==-1){let host=trimmed.slice(1,closingBracket),rest=trimmed.slice(closingBracket+1);if(rest.startsWith(":")){let port=Number.parseInt(rest.slice(1),10);return{host,port:Number.isNaN(port)?0:port}}return{host,port:0}}}if(trimmed.includes(":")&&trimmed.split(":").length>2)return{host:trimmed,port:0};let colonIndex=trimmed.lastIndexOf(":");if(colonIndex!==-1&&colonIndex===trimmed.indexOf(":")){let host=trimmed.slice(0,colonIndex),port=Number.parseInt(trimmed.slice(colonIndex+1),10);if(!Number.isNaN(port))return{host,port}}return{host:trimmed,port:0}}function shouldProxyHostname(hostname,port,env2){let noProxy=getProxyEnv("no_proxy",env2).toLowerCase();if(!noProxy)return!0;if(noProxy==="*")return!1;let normalizedTargetHost=stripBrackets(hostname.toLowerCase());return noProxy.split(/[,\s]/).every(entry=>{let parsed=parseNoProxyEntry(entry);if(!parsed||parsed.port&&parsed.port!==port)return!0;let domain=stripBrackets(parsed.host);return domain.startsWith("*.")?domain=domain.slice(2):(domain.startsWith(".")||domain.startsWith("*"))&&(domain=domain.slice(1)),domain?!(normalizedTargetHost===domain||normalizedTargetHost.endsWith(`.${domain}`)):!0})}function getProxyForUrl(targetUrl,env2){let parsedUrl=parseProxyTargetUrl(targetUrl);if(!parsedUrl?.protocol||!parsedUrl.host)return"";let protocol=parsedUrl.protocol.split(":",1)[0],hostname=stripBrackets(parsedUrl.hostname||parsedUrl.host.replace(/:\d*$/,"")),port=Number.parseInt(parsedUrl.port,10)||DEFAULT_PROXY_PORTS[protocol]||0;if(!shouldProxyHostname(hostname,port,env2))return"";let proxy=getProxyEnv(`${protocol}_proxy`,env2)||getProxyEnv("all_proxy",env2);return proxy&&!proxy.includes("://")&&(proxy=`${protocol}://${proxy}`),proxy}var UNSUPPORTED_PROXY_PROTOCOL_MESSAGE="Unsupported proxy protocol. SOCKS and PAC proxy URLs are not supported; use an HTTP or HTTPS proxy URL.";function resolveHttpProxyUrlForTarget(targetUrl,env2){let proxy=getProxyForUrl(targetUrl,env2);if(!proxy)return;let proxyUrl;try{proxyUrl=new URL(proxy)}catch(error2){throw new Error(`Invalid proxy URL ${JSON.stringify(proxy)}: ${error2 instanceof Error?error2.message:String(error2)}`)}if(proxyUrl.protocol!=="http:"&&proxyUrl.protocol!=="https:")throw new Error(`${UNSUPPORTED_PROXY_PROTOCOL_MESSAGE} Got ${proxyUrl.protocol}`);return proxyUrl}function getBedrockModelMatchCandidates(modelId,modelName){return(modelName?[modelId,modelName]:[modelId]).flatMap(value=>{let lower=value.toLowerCase();return[lower,lower.replace(/[\s_.:]+/g,"-")]})}function supportsOneHourCacheTtl(model){return getBedrockModelMatchCandidates(model.id,model.name).some(candidate=>["opus-4-5","sonnet-4-5","haiku-4-5"].some(modelVersion=>candidate.includes(modelVersion)))}function supportsPromptCaching(model,env2){let candidates=getBedrockModelMatchCandidates(model.id,model.name);return candidates.some(s2=>s2.includes("claude"))?!!(candidates.some(s2=>s2.includes("fable-5")||s2.includes("opus-5")||s2.includes("sonnet-5"))||candidates.some(s2=>s2.includes("-4-"))||candidates.some(s2=>s2.includes("claude-3-7-sonnet"))||candidates.some(s2=>s2.includes("claude-3-5-haiku"))):getProviderEnvValue("AWS_BEDROCK_FORCE_CACHE",env2)==="1"}function sanitizeSurrogates(text){return text.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,"")}function shortHash(str){let h1=3735928559,h22=1103547991;for(let i5=0;i5<str.length;i5++){let ch=str.charCodeAt(i5);h1=Math.imul(h1^ch,2654435761),h22=Math.imul(h22^ch,1597334677)}return h1=Math.imul(h1^h1>>>16,2246822507)^Math.imul(h22^h22>>>13,3266489909),h22=Math.imul(h22^h22>>>16,2246822507)^Math.imul(h1^h1>>>13,3266489909),(h22>>>0).toString(36)+(h1>>>0).toString(36)}var TOOL_CALL_ID_MAX_LENGTH=64;function normalizeToolCallId(id){let sanitized=id.replace(/[^a-zA-Z0-9_-]/g,"_");if(sanitized.length<=TOOL_CALL_ID_MAX_LENGTH)return sanitized;let suffix=`_${shortHash(id)}`;return`${sanitized.slice(0,TOOL_CALL_ID_MAX_LENGTH-suffix.length)}${suffix}`}var UnsupportedStrictJsonSchemaError=class extends Error{},UNSUPPORTED_STRICT_SCHEMA_KEYS=["$ref","$defs","definitions","allOf","oneOf","patternProperties","dependentSchemas","dependencies","unevaluatedProperties","propertyNames","contains","prefixItems","not","if","then","else"];function isJsonSchemaObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isStructuredSchema(schema){if(!isJsonSchemaObject(schema))return!1;let types=typeof schema.type=="string"?[schema.type]:Array.isArray(schema.type)?schema.type:[];return types.includes("object")||types.includes("array")||schema.properties!==void 0||schema.items!==void 0}function schemaAllowsNull(schema){return isJsonSchemaObject(schema)?schema.type==="null"||Array.isArray(schema.type)&&schema.type.includes("null")||schema.const===null||Array.isArray(schema.enum)&&schema.enum.includes(null)?!0:Array.isArray(schema.anyOf)&&schema.anyOf.some(variant=>schemaAllowsNull(variant)):!1}function makeJsonSchemaNodeStrict(schema){if(!isJsonSchemaObject(schema))throw new UnsupportedStrictJsonSchemaError("boolean schemas are unsupported");for(let key of UNSUPPORTED_STRICT_SCHEMA_KEYS)if(schema[key]!==void 0)throw new UnsupportedStrictJsonSchemaError(`${key} schemas are unsupported`);if(schema.anyOf!==void 0){if(!Array.isArray(schema.anyOf)||schema.anyOf.length===0)throw new UnsupportedStrictJsonSchemaError("anyOf must contain at least one schema");for(let variant of schema.anyOf){if(isStructuredSchema(variant))throw new UnsupportedStrictJsonSchemaError("object and array unions are unsupported");makeJsonSchemaNodeStrict(variant)}}if(schema.items!==void 0){if(Array.isArray(schema.items))throw new UnsupportedStrictJsonSchemaError("tuple schemas are unsupported");makeJsonSchemaNodeStrict(schema.items)}let isObjectSchema=schema.type==="object";if(schema.properties!==void 0&&!isObjectSchema)throw new UnsupportedStrictJsonSchemaError("properties require type object");if(!isObjectSchema)return;if(schema.additionalProperties!==void 0&&schema.additionalProperties!==!1)throw new UnsupportedStrictJsonSchemaError("schema-valued or true additionalProperties is unsupported");if(schema.properties!==void 0&&!isJsonSchemaObject(schema.properties))throw new UnsupportedStrictJsonSchemaError("object properties must be a schema map");if(schema.required!==void 0&&(!Array.isArray(schema.required)||schema.required.some(key=>typeof key!="string")))throw new UnsupportedStrictJsonSchemaError("object required must be a string array");let properties=schema.properties??{},propertyNames=Object.keys(properties),required=new Set(Array.isArray(schema.required)?schema.required:[]);if([...required].some(key=>!propertyNames.includes(key)))throw new UnsupportedStrictJsonSchemaError("required contains an unknown property");for(let[key,property]of Object.entries(properties))makeJsonSchemaNodeStrict(property),!required.has(key)&&!schemaAllowsNull(property)&&(properties[key]={anyOf:[property,{type:"null"}]});schema.required=propertyNames,schema.additionalProperties=!1}function makeStrictJsonSchema(schema){let cloned=structuredClone(schema);if(!isJsonSchemaObject(cloned))throw new UnsupportedStrictJsonSchemaError("root schema must have type object");if(makeJsonSchemaNodeStrict(cloned),cloned.type!=="object")throw new UnsupportedStrictJsonSchemaError("root schema must have type object");return cloned}function getJsonSchemaToolParameters(tool,strict){return strict===!0?makeStrictJsonSchema(tool.parameters):tool.parameters}function resolveJsonSchemaStrictSampling(tool,supportsStrictMode){let config=tool.constrainedSampling;if(!(config===!1||config?.type!=="json_schema")){if(supportsStrictMode)try{return makeStrictJsonSchema(tool.parameters),!0}catch(error2){if(!(error2 instanceof UnsupportedStrictJsonSchemaError))throw error2;if(config.strict!=="require")return;throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but ${error2.message}.`)}if(config.strict==="require")throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`)}}function calculateContextTokens(usage){return usage.totalTokens||usage.input+usage.output+usage.cacheRead+usage.cacheWrite}function safeJsonStringify2(value){try{return JSON.stringify(value)??"undefined"}catch{return"[unserializable]"}}function estimateTextAndImageContentChars(content){if(typeof content=="string")return content.length;let chars2=0;for(let block of content)chars2+=block.type==="text"?block.text.length:4800;return chars2}function estimateTextTokens(text){return Math.ceil(text.length/4)}function estimateTextAndImageContentTokens(content){return Math.ceil(estimateTextAndImageContentChars(content)/4)}function estimateMessageTokens(message){let chars2=0;if(message.role==="user"||message.role==="toolResult")return estimateTextAndImageContentTokens(message.content);if(message.role==="configurationUpdate")return 0;for(let block of message.content)block.type==="text"?chars2+=block.text.length:block.type==="thinking"?chars2+=block.thinking.length:block.type==="toolCall"?chars2+=block.name.length+safeJsonStringify2(block.arguments).length:chars2+=block.subtype.length+safeJsonStringify2(block.raw).length;return Math.ceil(chars2/4)}function getLastAssistantUsageInfo(messages){let latestPrefixTimestamp=Number.NEGATIVE_INFINITY,usageInfo;for(let i5=0;i5<messages.length;i5++){let message=messages[i5];if(message.role==="assistant"){let assistant=message;assistant.timestamp>=latestPrefixTimestamp&&assistant.stopReason!=="aborted"&&assistant.stopReason!=="error"&&calculateContextTokens(assistant.usage)>0&&(usageInfo={usage:assistant.usage,index:i5})}latestPrefixTimestamp=Math.max(latestPrefixTimestamp,message.timestamp)}return usageInfo}function estimateMessages(messages){let usageInfo=getLastAssistantUsageInfo(messages);if(usageInfo){let usageTokens=calculateContextTokens(usageInfo.usage),trailingTokens=0;for(let i5=usageInfo.index+1;i5<messages.length;i5++)trailingTokens+=estimateMessageTokens(messages[i5]);return{tokens:usageTokens+trailingTokens,usageTokens,trailingTokens,lastUsageIndex:usageInfo.index}}let tokens=0;for(let message of messages)tokens+=estimateMessageTokens(message);return{tokens,usageTokens:0,trailingTokens:tokens,lastUsageIndex:null}}function estimateToolsTokens(tools){return!tools||tools.length===0?0:estimateTextTokens(safeJsonStringify2(tools))}function isMessageArray(value){return Array.isArray(value)}function estimateContextTokens(context){if(isMessageArray(context))return estimateMessages(context);let estimate=estimateMessages(context.messages);if(estimate.lastUsageIndex!==null){let addedNames=new Set(context.messages.slice(estimate.lastUsageIndex+1).filter(message=>message.role==="toolResult").flatMap(message=>message.addedToolNames??[])),addedToolTokens=estimateToolsTokens(context.tools?.filter(tool=>addedNames.has(tool.name)));return{tokens:estimate.tokens+addedToolTokens,usageTokens:estimate.usageTokens,trailingTokens:estimate.trailingTokens+addedToolTokens,lastUsageIndex:estimate.lastUsageIndex}}let prefixTokens=(context.systemPrompt?estimateTextTokens(context.systemPrompt):0)+estimateToolsTokens(context.tools);return{tokens:estimate.tokens+prefixTokens,usageTokens:estimate.usageTokens,trailingTokens:estimate.trailingTokens+prefixTokens,lastUsageIndex:estimate.lastUsageIndex}}var CONTEXT_SAFETY_TOKENS=4096,MIN_ANSWER_TOKENS=1024,MIN_MAX_TOKENS=1,CONTEXT_GUARD_MIN_WINDOW=CONTEXT_SAFETY_TOKENS+MIN_ANSWER_TOKENS,ContextWindowExhaustedError=class extends Error{constructor(estimatedTokens,contextWindow){super(`Context window exhausted: the conversation is estimated at ${estimatedTokens} of ${contextWindow} tokens, leaving fewer than ${MIN_ANSWER_TOKENS} tokens for a response. Compact the conversation, enable auto-compaction, or start a new session before retrying.`),this.name="ContextWindowExhaustedError",this.estimatedTokens=estimatedTokens,this.contextWindow=contextWindow}};function clampMaxTokensToContext(model,context,maxTokens){if(model.contextWindow<=0)return Number.isFinite(maxTokens)&&maxTokens>0?Math.max(MIN_MAX_TOKENS,Math.floor(maxTokens)):MIN_MAX_TOKENS;let estimatedTokens=estimateContextTokens(context).tokens,available=model.contextWindow-estimatedTokens-CONTEXT_SAFETY_TOKENS;if(model.contextWindow>=CONTEXT_GUARD_MIN_WINDOW&&available<MIN_ANSWER_TOKENS)throw new ContextWindowExhaustedError(estimatedTokens,model.contextWindow);let safeAvailable=Math.max(MIN_MAX_TOKENS,available),requested=Number.isFinite(maxTokens)&&maxTokens>0?Math.floor(maxTokens):safeAvailable;return Math.min(requested,safeAvailable)}function applyExtraBody(target,extraBody,reservedKeys){if(extraBody)for(let[key,value]of Object.entries(extraBody))reservedKeys.has(key)||Reflect.set(target,key,value)}var BEDROCK_RESERVED_BODY_KEYS=new Set(["modelId","messages","system","toolConfig","additionalModelRequestFields","inferenceConfig","requestMetadata"]);function buildBaseOptions(model,context,options,apiKey){let samplingParams=model.samplingParams||options?.samplingParams?{...model.samplingParams,...options?.samplingParams}:void 0;return{temperature:options?.temperature,samplingParams,maxTokens:clampMaxTokensToContext(model,context,options?.maxTokens??model.maxTokens),signal:options?.signal,abortServerSideFallback:options?.abortServerSideFallback,telemetryContext:options?.telemetryContext,apiKey:apiKey||options?.apiKey,fetch:options?.fetch,transport:options?.transport,cacheRetention:options?.cacheRetention??model.cacheRetention,sessionId:options?.sessionId,headers:options?.headers,extraBody:options?.extraBody,onPayload:options?.onPayload,onResponse:options?.onResponse,timeoutMs:options?.timeoutMs,websocketConnectTimeoutMs:options?.websocketConnectTimeoutMs,maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,metadata:options?.metadata,env:options?.env}}var DEFAULT_THINKING_BUDGETS={minimal:1024,low:2048,medium:8192,high:16384};function clampReasoning(effort){return effort==="xhigh"||effort==="max"?"high":effort}function thinkingBudgetForLevel(reasoningLevel,customBudgets){let budgets={...DEFAULT_THINKING_BUDGETS,...customBudgets},level=clampReasoning(reasoningLevel);return budgets[level]}function clampThinkingBudgetToAnswerRoom(thinkingBudget,ceiling){return Math.min(thinkingBudget,Math.max(0,ceiling-MIN_ANSWER_TOKENS))}function adjustMaxTokensForThinking(baseMaxTokens,modelMaxTokens,reasoningLevel,customBudgets){let level=clampReasoning(reasoningLevel);if(!level)return{maxTokens:baseMaxTokens??modelMaxTokens,thinkingBudget:0};let thinkingBudget=thinkingBudgetForLevel(level,customBudgets),maxTokens=baseMaxTokens===void 0?modelMaxTokens:Math.min(baseMaxTokens+thinkingBudget,modelMaxTokens);return maxTokens<=thinkingBudget&&(thinkingBudget=clampThinkingBudgetToAnswerRoom(thinkingBudget,maxTokens)),{maxTokens,thinkingBudget}}function isVideoMimeType(mimeType){return mimeType.toLowerCase().startsWith("video/")}var NON_VISION_USER_IMAGE_PLACEHOLDER="(image omitted: model does not support images)",NON_VISION_TOOL_IMAGE_PLACEHOLDER="(tool image omitted: model does not support images)",NO_VIDEO_USER_PLACEHOLDER="(video omitted: model does not support video input)",NO_VIDEO_TOOL_PLACEHOLDER="(tool video omitted: model does not support video input)";function replaceMediaWithPlaceholder(content,placeholder,matches){if(!content.some(block=>block.type==="image"&&matches(block)))return content;let result=[],previousWasPlaceholder=!1;for(let block of content){if(block.type==="image"&&matches(block)){previousWasPlaceholder||result.push({type:"text",text:placeholder}),previousWasPlaceholder=!0;continue}result.push(block),previousWasPlaceholder=block.type==="text"&&block.text===placeholder}return result}function replaceImagesWithPlaceholder(content,placeholder){let result=[],previousWasPlaceholder=!1;for(let block of content){if(block.type==="image"){previousWasPlaceholder||result.push({type:"text",text:placeholder}),previousWasPlaceholder=!0;continue}result.push(block),previousWasPlaceholder=block.text===placeholder}return result}function downgradeUnsupportedImages(messages,model){let supportsImages=model.input.includes("image"),supportsVideo=model.input.includes("video");return supportsImages&&supportsVideo?messages:messages.map(msg=>{if(msg.role==="user"&&Array.isArray(msg.content)){let content=msg.content;return supportsVideo||(content=replaceMediaWithPlaceholder(content,NO_VIDEO_USER_PLACEHOLDER,b5=>isVideoMimeType(b5.mimeType))),supportsImages||(content=replaceImagesWithPlaceholder(content,NON_VISION_USER_IMAGE_PLACEHOLDER)),{...msg,content}}if(msg.role==="toolResult"){let content=msg.content;return supportsVideo||(content=replaceMediaWithPlaceholder(content,NO_VIDEO_TOOL_PLACEHOLDER,b5=>isVideoMimeType(b5.mimeType))),supportsImages||(content=replaceImagesWithPlaceholder(content,NON_VISION_TOOL_IMAGE_PLACEHOLDER)),{...msg,content}}return msg})}function transformMessages(messages,model,normalizeToolCallId2,options={}){let toolCallIdMap=new Map,normalizedMessages=messages.map(msg=>msg.content==null?{...msg,content:[]}:msg),imageAwareMessages=downgradeUnsupportedImages(normalizedMessages,model),preserveThinking=options.preserveThinking??!0,preserveTextSignatures=options.preserveTextSignatures??!1,preserveUnsignedThinking=options.preserveUnsignedThinking??!1,normalizeSameModelToolCallIds=options.normalizeSameModelToolCallIds??!1,transformed=imageAwareMessages.map(msg=>{if(msg.role==="user")return msg;if(msg.role==="toolResult"){let normalizedId=toolCallIdMap.get(msg.toolCallId);return normalizedId&&normalizedId!==msg.toolCallId?{...msg,toolCallId:normalizedId}:msg}if(msg.role==="assistant"){let assistantMsg=msg,isSameModel=assistantMsg.provider===model.provider&&assistantMsg.api===model.api&&assistantMsg.model===model.id,hasToolCalls=assistantMsg.content.some(block=>block.type==="toolCall"),preserveProviderState=preserveThinking||hasToolCalls,transformedContent=assistantMsg.content.flatMap(block=>{if(block.type==="thinking"){if(block.redacted)return isSameModel?{...block}:[];let hasUsableSignature=typeof block.thinkingSignature=="string"&&block.thinkingSignature.trim().length>0;return isSameModel&&hasUsableSignature&&(preserveProviderState||block.thinking.trim()==="")?{...block}:!block.thinking||block.thinking.trim()===""?[]:isSameModel?preserveProviderState||preserveUnsignedThinking&&!hasUsableSignature?{...block}:[]:{type:"text",text:block.thinking}}if(block.type==="text")return isSameModel&&(preserveProviderState||preserveTextSignatures)?{...block}:{type:"text",text:block.text};if(block.type==="toolCall"){let toolCall=block,normalizedToolCall={...toolCall};if((!isSameModel||!preserveProviderState)&&toolCall.thoughtSignature&&delete normalizedToolCall.thoughtSignature,(!isSameModel||normalizeSameModelToolCallIds)&&normalizeToolCallId2){let normalizedId=normalizeToolCallId2(toolCall.id,model,assistantMsg);normalizedId!==toolCall.id&&(toolCallIdMap.set(toolCall.id,normalizedId),normalizedToolCall={...normalizedToolCall,id:normalizedId})}return normalizedToolCall}return block});return{...assistantMsg,content:transformedContent}}return msg}),result=[],toolResultsById=new Map,nextToolCallIndexById=new Map,droppedCallIds=new Set;for(let sourceIndex=0;sourceIndex<transformed.length;sourceIndex++){let message=transformed[sourceIndex];if(message.role==="toolResult"){let entries=toolResultsById.get(message.toolCallId)??[];entries.push({message,sourceIndex,consumed:!1}),toolResultsById.set(message.toolCallId,entries);continue}if(message.role==="assistant"){if(message.stopReason==="error"||message.stopReason==="aborted"){for(let block of message.content)block.type==="toolCall"&&droppedCallIds.add(block.id);continue}for(let block of message.content){if(block.type!=="toolCall")continue;let indexes=nextToolCallIndexById.get(block.id)??[];indexes.push(sourceIndex),nextToolCallIndexById.set(block.id,indexes)}}}for(let sourceIndex=0;sourceIndex<transformed.length;sourceIndex++){let message=transformed[sourceIndex];if(message.role==="toolResult"){toolResultsById.get(message.toolCallId)?.find(candidate=>candidate.sourceIndex===sourceIndex)?.consumed||(!droppedCallIds.has(message.toolCallId)||nextToolCallIndexById.has(message.toolCallId))&&result.push(message);continue}if(message.role!=="assistant"){result.push(message);continue}if(!(message.stopReason==="error"||message.stopReason==="aborted")){result.push(message);for(let block of message.content){if(block.type!=="toolCall")continue;let nextDeclarationIndex=(nextToolCallIndexById.get(block.id)??[]).find(index=>index>sourceIndex)??1/0,matchedResult=toolResultsById.get(block.id)?.find(candidate=>!candidate.consumed&&candidate.sourceIndex>sourceIndex&&candidate.sourceIndex<nextDeclarationIndex);if(matchedResult){matchedResult.consumed=!0,result.push(matchedResult.message);continue}result.push({role:"toolResult",toolCallId:block.id,toolName:block.name,content:[{type:"text",text:"No result provided"}],isError:!0,timestamp:Date.now()})}}}return result}var EMPTY_TEXT_PLACEHOLDER="<empty>",REDACTED_THINKING_PLACEHOLDER="[Reasoning redacted]",stream=(model,context,options={})=>{let stream2=new AssistantMessageEventStream;return(async()=>{let output={role:"assistant",content:[],api:"bedrock-converse-stream",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()},blocks=output.content,optionsProfile=options.profile||options.env?.AWS_PROFILE,config={profile:optionsProfile||getProviderEnvValue("AWS_PROFILE",options.env)},configuredRegion=getConfiguredBedrockRegion(options),hasAmbientConfiguredProfile=!!getProviderEnvValue("AWS_PROFILE"),endpointRegion=getStandardBedrockEndpointRegion(model.baseUrl),useExplicitEndpoint=shouldUseExplicitBedrockEndpoint(model.baseUrl,configuredRegion,hasAmbientConfiguredProfile);useExplicitEndpoint&&(config.endpoint=model.baseUrl);let skipAuth=getProviderEnvValue("AWS_BEDROCK_SKIP_AUTH",options.env)==="1",bearerToken=options.bearerToken||options.apiKey||getProviderEnvValue("AWS_BEARER_TOKEN_BEDROCK",options.env)||void 0,useBearerToken=bearerToken!==void 0&&!skipAuth;if(typeof process<"u"&&(process.versions?.node||process.versions?.bun)){let arnRegionMatch=model.id.match(/^arn:aws(?:-[a-z0-9-]+)?:bedrock:([a-z0-9-]+):/);arnRegionMatch?config.region=arnRegionMatch[1]:configuredRegion?config.region=configuredRegion:endpointRegion&&useExplicitEndpoint?config.region=endpointRegion:hasAmbientConfiguredProfile||(config.region="us-east-1"),skipAuth&&(config.credentials={accessKeyId:"dummy-access-key",secretAccessKey:"dummy-secret-key"});let credentials=getConfiguredBedrockCredentials(options.env);!skipAuth&&credentials&&!optionsProfile&&(config.credentials=credentials);let proxyUrl=resolveHttpProxyUrlForTarget(model.baseUrl,options.env);proxyUrl?config.requestHandler=new import_node_http_handler5.NodeHttpHandler({httpAgent:new HttpProxyAgent(proxyUrl),httpsAgent:new HttpsProxyAgent(proxyUrl)}):getProviderEnvValue("AWS_BEDROCK_FORCE_HTTP1",options.env)==="1"&&(config.requestHandler=new import_node_http_handler5.NodeHttpHandler)}else config.region=configuredRegion||(endpointRegion&&useExplicitEndpoint?endpointRegion:void 0)||"us-east-1";useBearerToken&&(config.token={token:bearerToken},config.authSchemePreference=["httpBearerAuth"]);let responseRequestId;try{let supportsStrictMode=model.compat?.supportsStrictMode??!1,client=new import_client_bedrock_runtime.BedrockRuntimeClient(config),observedRawResponse=!1;options.onResponse&&addResponseHeadersMiddleware(client,options.onResponse,model,()=>{observedRawResponse=!0});let customHeaders=providerHeadersToRecord(options.headers);customHeaders&&Object.keys(customHeaders).length>0&&addCustomHeadersMiddleware(client,customHeaders);let cacheRetention=resolveCacheRetention(options.cacheRetention??model.cacheRetention,options.env),inferenceMaxTokens=options.maxTokens??(isAnthropicClaudeModel(model)?model.maxTokens:void 0),commandInput={modelId:model.id,messages:convertMessages(context,model,cacheRetention,{preserveThinking:options.reasoning!==void 0,env:options.env}),system:buildSystemPrompt(context.systemPrompt,model,cacheRetention,options.env),inferenceConfig:{...inferenceMaxTokens!==void 0&&{maxTokens:inferenceMaxTokens},...options.temperature!==void 0&&{temperature:options.temperature}},toolConfig:convertToolConfig(context.tools,options.toolChoice,supportsStrictMode),additionalModelRequestFields:buildAdditionalModelRequestFields(model,options),...options.requestMetadata!==void 0&&{requestMetadata:options.requestMetadata}};applyExtraBody(commandInput,options.extraBody,BEDROCK_RESERVED_BODY_KEYS);let nextCommandInput=await options?.onPayload?.(commandInput,model);nextCommandInput!==void 0&&(commandInput=nextCommandInput);let command5=new import_client_bedrock_runtime.ConverseStreamCommand(commandInput),response=await client.send(command5,{abortSignal:options.signal});if(responseRequestId=normalizeDiagnosticValue(response.$metadata.requestId),!observedRawResponse&&response.$metadata.httpStatusCode!==void 0){let responseHeaders={};response.$metadata.requestId&&(responseHeaders["x-amzn-requestid"]=response.$metadata.requestId),await options?.onResponse?.({status:response.$metadata.httpStatusCode,headers:responseHeaders},model)}for await(let item of response.stream)if(item.messageStart){if(item.messageStart.role!==import_client_bedrock_runtime.ConversationRole.ASSISTANT)throw new Error("Unexpected assistant message start but got user message start instead");stream2.push({type:"start",partial:output})}else if(item.contentBlockStart)handleContentBlockStart(item.contentBlockStart,blocks,output,stream2);else if(item.contentBlockDelta)handleContentBlockDelta(item.contentBlockDelta,blocks,output,stream2);else if(item.contentBlockStop)handleContentBlockStop(item.contentBlockStop,blocks,output,stream2);else if(item.messageStop){output.rawStopReason=item.messageStop.stopReason;let{stopReason,errorMessage}=mapStopReason(item.messageStop.stopReason);output.stopReason=stopReason,errorMessage&&(output.errorMessage=errorMessage)}else if(item.metadata)handleMetadata(item.metadata,model,output);else{if(item.internalServerException)throw item.internalServerException;if(item.modelStreamErrorException)throw item.modelStreamErrorException;if(item.validationException)throw item.validationException;if(item.throttlingException)throw item.throttlingException;if(item.serviceUnavailableException)throw item.serviceUnavailableException}if(options.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Bedrock stream ended without a stop reason");if(output.stopReason==="error"||output.stopReason==="aborted")throw new Error(output.errorMessage||"An unknown error occurred");for(let block of output.content)finalizeStreamingBlock(block);stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error2){for(let block of output.content)finalizeStreamingBlock(block);output.stopReason=options.signal?.aborted?"aborted":"error",output.errorMessage=formatBedrockError(error2),output.stopReason==="error"&&appendBedrockFailureDiagnostic(output,error2,responseRequestId),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},BEDROCK_ERROR_PREFIXES={InternalServerException:"Internal server error",ModelStreamErrorException:"Model stream error",ValidationException:"Validation error",ThrottlingException:"Throttling error",ServiceUnavailableException:"Service unavailable"},BEDROCK_DATA_RETENTION_DOCS_URL="https://docs.aws.amazon.com/bedrock/latest/userguide/data-retention.html";function formatBedrockError(error2){let norm=normalizeProviderError(error2),core=!norm.messageCarriesBody&&norm.status!==void 0&&norm.body!==void 0?`${norm.status}: ${norm.body}`:norm.message,dataRetentionHint=/data retention mode/i.test(core)?` See ${BEDROCK_DATA_RETENTION_DOCS_URL} for supported data retention modes.`:"";return error2 instanceof import_client_bedrock_runtime.BedrockRuntimeServiceException?`${BEDROCK_ERROR_PREFIXES[error2.name]??error2.name}: ${core}${dataRetentionHint}`:`${core}${dataRetentionHint}`}var MAX_BEDROCK_DIAGNOSTIC_VALUE_CHARS=200;function normalizeDiagnosticValue(value){if(typeof value!="string")return;let trimmed=value.trim();if(!(trimmed.length===0||trimmed.length>MAX_BEDROCK_DIAGNOSTIC_VALUE_CHARS))return trimmed}function extractBedrockErrorCode(error2){if(!(!(error2 instanceof Error)||!error2.name.endsWith("Exception")))return normalizeDiagnosticValue(error2.name)}function appendBedrockFailureDiagnostic(output,error2,fallbackRequestId){let metadata=error2?.$metadata,details={};typeof metadata?.httpStatusCode=="number"&&(details.status=metadata.httpStatusCode);let errorCode=extractBedrockErrorCode(error2);errorCode!==void 0&&(details.errorCode=errorCode);let requestId=normalizeDiagnosticValue(metadata?.requestId)??fallbackRequestId;requestId!==void 0&&(details.requestId=requestId),Object.keys(details).length!==0&&appendAssistantMessageDiagnostic(output,{type:"bedrock_response_failure",timestamp:Date.now(),details})}var RESERVED_HEADER_EXACT=new Set(["authorization","host"]);function isReservedHeader(key){let lower=key.toLowerCase();return lower.startsWith("x-amz-")||RESERVED_HEADER_EXACT.has(lower)}function hasHeaders(request){return typeof request!="object"||request===null||!("headers"in request)?!1:typeof request.headers=="object"&&request.headers!==null}function addCustomHeadersMiddleware(client,headers){client.middlewareStack.add(next=>async args=>{let request=args.request;if(hasHeaders(request)){let requestHeaders=request.headers;for(let[key,value]of Object.entries(headers))isReservedHeader(key)||(requestHeaders[key]=value)}return next(args)},{step:"build",name:"pi-ai-custom-headers",priority:"low"})}function isSmithyHttpResponse(response){if(!response||typeof response!="object")return!1;let candidate=response;return typeof candidate.statusCode=="number"&&!!candidate.headers&&typeof candidate.headers=="object"}function toProviderResponse(response){if(isSmithyHttpResponse(response))return{status:response.statusCode,headers:{...response.headers}}}function addResponseHeadersMiddleware(client,onResponse,model,onObserved){client.middlewareStack.add(next=>async args=>{let result=await next(args),providerResponse=toProviderResponse(result.response);return providerResponse&&(onObserved(),await onResponse(providerResponse,model)),result},{step:"deserialize",name:"pi-ai-response-headers"})}var streamSimple=(model,context,options)=>{let base={...buildBaseOptions(model,context,options,void 0),toolChoice:options?.toolChoice};if(!options?.reasoning)return stream(model,context,{...base,reasoning:void 0});if(isAnthropicClaudeModel(model)){if(supportsAdaptiveThinking(model.id,model.name))return stream(model,context,{...base,reasoning:options.reasoning,thinkingBudgets:options.thinkingBudgets});let adjusted=adjustMaxTokensForThinking(base.maxTokens,model.maxTokens,options.reasoning,options.thinkingBudgets),maxTokens=clampMaxTokensToContext(model,context,adjusted.maxTokens);return stream(model,context,{...base,maxTokens,reasoning:options.reasoning,thinkingBudgets:{...options.thinkingBudgets||{},[clampReasoning(options.reasoning)]:Math.min(adjusted.thinkingBudget,Math.max(0,maxTokens-1024))}})}return stream(model,context,{...base,reasoning:options.reasoning,thinkingBudgets:options.thinkingBudgets})};function handleContentBlockStart(event,blocks,output,stream2){let index=event.contentBlockIndex,start=event.start;if(start?.toolUse){let block={type:"toolCall",id:start.toolUse.toolUseId||"",name:start.toolUse.name||"",arguments:{},partialJson:"",index};output.content.push(block),stream2.push({type:"toolcall_start",contentIndex:blocks.length-1,partial:output})}}function handleContentBlockDelta(event,blocks,output,stream2){let contentBlockIndex=event.contentBlockIndex,delta=event.delta,index=blocks.findIndex(b5=>b5.index===contentBlockIndex),block=blocks[index];if(delta?.text!==void 0){if(!block){let newBlock={type:"text",text:"",index:contentBlockIndex};output.content.push(newBlock),index=blocks.length-1,block=blocks[index],stream2.push({type:"text_start",contentIndex:index,partial:output})}block.type==="text"&&(block.text+=delta.text,stream2.push({type:"text_delta",contentIndex:index,delta:delta.text,partial:output}))}else if(delta?.toolUse&&block?.type==="toolCall")block.partialJson=(block.partialJson||"")+(delta.toolUse.input||""),block.arguments=parseStreamingJson(block.partialJson),stream2.push({type:"toolcall_delta",contentIndex:index,delta:delta.toolUse.input||"",partial:output});else if(delta?.reasoningContent){let thinkingBlock=block,thinkingIndex=index;if(!thinkingBlock){let newBlock={type:"thinking",thinking:"",thinkingSignature:"",index:contentBlockIndex};output.content.push(newBlock),thinkingIndex=blocks.length-1,thinkingBlock=blocks[thinkingIndex],stream2.push({type:"thinking_start",contentIndex:thinkingIndex,partial:output})}thinkingBlock?.type==="thinking"&&(delta.reasoningContent.text&&(thinkingBlock.thinking+=delta.reasoningContent.text,stream2.push({type:"thinking_delta",contentIndex:thinkingIndex,delta:delta.reasoningContent.text,partial:output})),delta.reasoningContent.signature&&!thinkingBlock.redacted&&(thinkingBlock.thinkingSignature=(thinkingBlock.thinkingSignature||"")+delta.reasoningContent.signature),delta.reasoningContent.redactedContent?.length&&(thinkingBlock.redacted||(thinkingBlock.redacted=!0,thinkingBlock.thinkingSignature="",thinkingBlock.thinking+=REDACTED_THINKING_PLACEHOLDER,stream2.push({type:"thinking_delta",contentIndex:thinkingIndex,delta:REDACTED_THINKING_PLACEHOLDER,partial:output})),thinkingBlock.redactedChunks??=[],thinkingBlock.redactedChunks.push(delta.reasoningContent.redactedContent)))}}function flushRedactedContent(block){block.type!=="thinking"||!block.redactedChunks||(block.thinkingSignature=bytesToBase64(block.redactedChunks),delete block.redactedChunks)}function finalizeStreamingBlock(block){delete block.index,delete block.partialJson,flushRedactedContent(block)}function handleMetadata(event,model,output){event.usage&&(output.usage.input=event.usage.inputTokens||0,output.usage.output=event.usage.outputTokens||0,output.usage.cacheRead=event.usage.cacheReadInputTokens||0,output.usage.cacheWrite=event.usage.cacheWriteInputTokens||0,output.usage.totalTokens=event.usage.totalTokens||output.usage.input+output.usage.output,calculateCost(model,output.usage))}function handleContentBlockStop(event,blocks,output,stream2){let index=blocks.findIndex(b5=>b5.index===event.contentBlockIndex),block=blocks[index];if(block)switch(delete block.index,block.type){case"text":stream2.push({type:"text_end",contentIndex:index,content:block.text,partial:output});break;case"thinking":flushRedactedContent(block),stream2.push({type:"thinking_end",contentIndex:index,content:block.thinking,partial:output});break;case"toolCall":block.arguments=parseStreamingJson(block.partialJson),delete block.partialJson,stream2.push({type:"toolcall_end",contentIndex:index,toolCall:block,partial:output});break}}function supportsAdaptiveThinking(modelId,modelName){return getBedrockModelMatchCandidates(modelId,modelName).some(s2=>s2.includes("opus-4-6")||s2.includes("opus-4-7")||s2.includes("opus-4-8")||s2.includes("opus-5")||s2.includes("sonnet-4-6")||s2.includes("sonnet-5")||s2.includes("fable-5")||s2.includes("mythos-5"))}function supportsNativeXhighEffort(model){return getBedrockModelMatchCandidates(model.id,model.name).some(s2=>s2.includes("opus-4-7")||s2.includes("opus-4-8")||s2.includes("opus-5")||s2.includes("sonnet-5")||s2.includes("fable-5")||s2.includes("mythos-5"))}function rejectsDisabledThinking(model){return model.thinkingLevelMap?.off===null?!0:getBedrockModelMatchCandidates(model.id,model.name).some(s2=>s2.includes("fable-5")||s2.includes("mythos-5")||s2.includes("opus-5-5")||s2.includes("opus-5.5"))}function mapThinkingLevelToEffort(model,level){if(level==="xhigh"&&supportsNativeXhighEffort(model))return"xhigh";let mapped=level?model.thinkingLevelMap?.[level]:void 0;if(typeof mapped=="string")return mapped;switch(level){case"minimal":case"low":return"low";case"medium":return"medium";case"high":return"high";case"xhigh":case"max":return"max";default:return"high"}}function resolveCacheRetention(cacheRetention,env2){return cacheRetention||(getProviderEnvValue("PI_CACHE_RETENTION",env2)==="long"?"long":"short")}function isAnthropicClaudeModel(model){let id=model.id.toLowerCase(),name=model.name?.toLowerCase()??"";return id.includes("anthropic.claude")||id.includes("anthropic/claude")||name.includes("anthropic.claude")||name.includes("anthropic/claude")||name.includes("claude")}function supportsThinkingSignature(model){return isAnthropicClaudeModel(model)}function buildSystemPrompt(systemPrompt,model,cacheRetention,env2){if(!systemPrompt)return;let blocks=[{text:sanitizeSurrogates(systemPrompt)}];return cacheRetention!=="none"&&supportsPromptCaching(model,env2)&&blocks.push({cachePoint:{type:import_client_bedrock_runtime.CachePointType.DEFAULT,...cacheRetention==="long"&&supportsOneHourCacheTtl(model)?{ttl:import_client_bedrock_runtime.CacheTTL.ONE_HOUR}:{}}}),blocks}function createNonBlankTextBlock(text){let sanitized=sanitizeSurrogates(text);return sanitized.trim().length===0?void 0:{text:sanitized}}function createRequiredTextBlock(text){return createNonBlankTextBlock(text)??{text:EMPTY_TEXT_PLACEHOLDER}}function sanitizeBedrockDocument(value){return Array.isArray(value)?value.map(sanitizeBedrockDocument):value!==null&&typeof value=="object"?Object.fromEntries(Object.entries(value).filter(([key])=>key.length>0).map(([key,nestedValue])=>[key,sanitizeBedrockDocument(nestedValue)])):value}function convertToolResultContent(content){let result=[];for(let c5 of content)if(c5.type==="image")result.push({image:createImageBlock(c5.mimeType,c5.data)});else{let textBlock=createNonBlankTextBlock(c5.text);textBlock&&result.push(textBlock)}return result.length===0&&result.push({text:EMPTY_TEXT_PLACEHOLDER}),result}function appendMessage(result,message){let previous=result[result.length-1];if(previous?.role===message.role&&previous.content&&message.content){previous.content.push(...message.content);return}result.push(message)}function convertMessages(context,model,cacheRetention,options={}){let result=[],transformedMessages=transformMessages(context.messages,model,normalizeToolCallId,{preserveThinking:options.preserveThinking});for(let i5=0;i5<transformedMessages.length;i5++){let m3=transformedMessages[i5];switch(m3.role){case"user":{let content=[];if(typeof m3.content=="string")content.push(createRequiredTextBlock(m3.content));else{for(let c5 of m3.content)switch(c5.type){case"text":{let textBlock=createNonBlankTextBlock(c5.text);textBlock&&content.push(textBlock);break}case"image":content.push({image:createImageBlock(c5.mimeType,c5.data)});break;default:continue}content.length===0&&content.push({text:EMPTY_TEXT_PLACEHOLDER})}appendMessage(result,{role:import_client_bedrock_runtime.ConversationRole.USER,content});break}case"assistant":{if(m3.content.length===0)continue;let contentBlocks=[];for(let c5 of m3.content)switch(c5.type){case"text":{let textBlock=createNonBlankTextBlock(c5.text);if(!textBlock)continue;contentBlocks.push(textBlock);break}case"toolCall":contentBlocks.push({toolUse:{toolUseId:c5.id,name:c5.name,input:sanitizeBedrockDocument(c5.arguments)}});break;case"thinking":{if(c5.redacted){let redactedContent=decodeRedactedContent(c5.thinkingSignature);redactedContent?.length&&contentBlocks.push({reasoningContent:{redactedContent}});continue}let thinking=sanitizeSurrogates(c5.thinking);if(thinking.trim().length===0)continue;supportsThinkingSignature(model)?!c5.thinkingSignature||c5.thinkingSignature.trim().length===0?contentBlocks.push({text:thinking}):contentBlocks.push({reasoningContent:{reasoningText:{text:thinking,signature:c5.thinkingSignature}}}):contentBlocks.push({reasoningContent:{reasoningText:{text:thinking}}});break}default:continue}if(contentBlocks.length===0)continue;appendMessage(result,{role:import_client_bedrock_runtime.ConversationRole.ASSISTANT,content:contentBlocks});break}case"toolResult":{let toolResults=[];toolResults.push({toolResult:{toolUseId:m3.toolCallId,content:convertToolResultContent(m3.content),status:m3.isError?import_client_bedrock_runtime.ToolResultStatus.ERROR:import_client_bedrock_runtime.ToolResultStatus.SUCCESS}});let j5=i5+1;for(;j5<transformedMessages.length&&transformedMessages[j5].role==="toolResult";){let nextMsg=transformedMessages[j5];toolResults.push({toolResult:{toolUseId:nextMsg.toolCallId,content:convertToolResultContent(nextMsg.content),status:nextMsg.isError?import_client_bedrock_runtime.ToolResultStatus.ERROR:import_client_bedrock_runtime.ToolResultStatus.SUCCESS}}),j5++}i5=j5-1,appendMessage(result,{role:import_client_bedrock_runtime.ConversationRole.USER,content:toolResults});break}default:continue}}if(cacheRetention!=="none"&&supportsPromptCaching(model,options.env)&&result.length>0){let lastMessage=result[result.length-1];lastMessage.role===import_client_bedrock_runtime.ConversationRole.USER&&lastMessage.content&&lastMessage.content.push({cachePoint:{type:import_client_bedrock_runtime.CachePointType.DEFAULT,...cacheRetention==="long"&&supportsOneHourCacheTtl(model)?{ttl:import_client_bedrock_runtime.CacheTTL.ONE_HOUR}:{}}})}return result}function convertToolConfig(tools,toolChoice,supportsStrictMode){if(!tools?.length||toolChoice==="none")return;let bedrockTools=tools.map(tool=>{let strict=resolveJsonSchemaStrictSampling(tool,supportsStrictMode);return{toolSpec:{name:tool.name,description:tool.description,inputSchema:{json:toDocumentType(getJsonSchemaToolParameters(tool,strict))},...strict===!0?{strict:!0}:{}}}}),bedrockToolChoice;switch(toolChoice){case"auto":bedrockToolChoice={auto:{}};break;case"any":bedrockToolChoice={any:{}};break;default:toolChoice?.type==="tool"&&(bedrockToolChoice={tool:{name:toolChoice.name}})}return{tools:bedrockTools,toolChoice:bedrockToolChoice}}function toDocumentType(value){return JSON.parse(JSON.stringify(value))}function mapStopReason(reason){switch(reason){case import_client_bedrock_runtime.StopReason.END_TURN:case import_client_bedrock_runtime.StopReason.STOP_SEQUENCE:return{stopReason:"stop"};case import_client_bedrock_runtime.StopReason.MAX_TOKENS:case import_client_bedrock_runtime.StopReason.MODEL_CONTEXT_WINDOW_EXCEEDED:return{stopReason:"length"};case import_client_bedrock_runtime.StopReason.TOOL_USE:return{stopReason:"toolUse"};default:return reason?{stopReason:"error",errorMessage:`Provider stopped with: ${reason}`}:{stopReason:"error"}}}function getConfiguredBedrockRegion(options){return options.region||getProviderEnvValue("AWS_REGION",options.env)||getProviderEnvValue("AWS_DEFAULT_REGION",options.env)||void 0}function getConfiguredBedrockCredentials(env2){let accessKeyId=getProviderEnvValue("AWS_ACCESS_KEY_ID",env2),secretAccessKey=getProviderEnvValue("AWS_SECRET_ACCESS_KEY",env2);if(!accessKeyId||!secretAccessKey)return;let sessionToken=getProviderEnvValue("AWS_SESSION_TOKEN",env2);return{accessKeyId,secretAccessKey,...sessionToken?{sessionToken}:{}}}function getStandardBedrockEndpointRegion(baseUrl){if(baseUrl)try{let{hostname}=new URL(baseUrl);return hostname.toLowerCase().match(/^bedrock-runtime(?:-fips)?\.([a-z0-9-]+)\.amazonaws\.com(?:\.cn)?$/)?.[1]}catch{return}}function shouldUseExplicitBedrockEndpoint(baseUrl,configuredRegion,hasAmbientConfiguredProfile){return getStandardBedrockEndpointRegion(baseUrl)?!configuredRegion&&!hasAmbientConfiguredProfile:!0}function isGovCloudBedrockTarget(model,options){if(getConfiguredBedrockRegion(options)?.toLowerCase().startsWith("us-gov-"))return!0;let modelId=model.id.toLowerCase();return modelId.startsWith("us-gov.")||modelId.startsWith("arn:aws-us-gov:")}function buildAdditionalModelRequestFields(model,options){if(model.reasoning){if(!options.reasoning)return!isAnthropicClaudeModel(model)||!supportsAdaptiveThinking(model.id,model.name)?void 0:rejectsDisabledThinking(model)?{output_config:{effort:"low"}}:{thinking:{type:"disabled"}};if(isAnthropicClaudeModel(model)){let display=isGovCloudBedrockTarget(model,options)?void 0:options.thinkingDisplay??"summarized",result=supportsAdaptiveThinking(model.id,model.name)?{thinking:{type:"adaptive",...display!==void 0?{display}:{}},output_config:{effort:mapThinkingLevelToEffort(model,options.reasoning)}}:(()=>{let defaultBudgets={minimal:1024,low:2048,medium:8192,high:16384,xhigh:16384,max:16384},level=options.reasoning==="xhigh"||options.reasoning==="max"?"high":options.reasoning;return{thinking:{type:"enabled",budget_tokens:options.thinkingBudgets?.[level]??defaultBudgets[options.reasoning],...display!==void 0?{display}:{}}}})();return!supportsAdaptiveThinking(model.id,model.name)&&(options.interleavedThinking??!0)&&(result.anthropic_beta=["interleaved-thinking-2025-05-14"]),result}}}function createImageBlock(mimeType,data){let format2;switch(mimeType){case"image/jpeg":case"image/jpg":format2=import_client_bedrock_runtime.ImageFormat.JPEG;break;case"image/png":format2=import_client_bedrock_runtime.ImageFormat.PNG;break;case"image/gif":format2=import_client_bedrock_runtime.ImageFormat.GIF;break;case"image/webp":format2=import_client_bedrock_runtime.ImageFormat.WEBP;break;default:throw new Error(`Unknown image type: ${mimeType}`)}return{source:{bytes:base64ToBytes(data)},format:format2}}function base64ToBytes(data){let binaryString=atob(data),bytes=new Uint8Array(binaryString.length);for(let i5=0;i5<binaryString.length;i5++)bytes[i5]=binaryString.charCodeAt(i5);return bytes}function decodeRedactedContent(signature){if(signature)try{return base64ToBytes(signature)}catch{return}}function bytesToBase64(chunks){let binary="";for(let chunk of chunks)for(let i5=0;i5<chunk.length;i5+=32768)binary+=String.fromCharCode(...chunk.subarray(i5,i5+32768));return btoa(binary)}export{stream,streamSimple,supportsPromptCaching};
|
|
@@ -323,4 +323,4 @@ ${yamlBody.length>0?yamlBody:"null"}
|
|
|
323
323
|
`).map(line=>` ${line}`),"</tool_response>"].join(`
|
|
324
324
|
`)}function parseYamlXmlGeneratedText(text,tools,options){if(tools.length===0||text.length===0)return[];let parsedToolCalls=[],toolNames=tools.map(tool=>tool.name),cursor=0;for(;cursor<text.length;){let openingTag=findEarliestXmlToolTag(text.slice(cursor),toolNames);if(!openingTag)break;let absoluteIndex=cursor+openingTag.index;if(openingTag.selfClosing){parsedToolCalls.push({name:openingTag.name,arguments:{}}),cursor=absoluteIndex+openingTag.tag.length;continue}let contentStart=absoluteIndex+openingTag.tag.length,closingTagEnd=findClosingTagEnd(text,contentStart,openingTag.name);if(closingTagEnd===-1)break;let closingTagText=text.slice(contentStart,closingTagEnd),closingTagIndex=new RegExp(`</\\s*${escapeRegExp4(openingTag.name)}\\s*>`).exec(closingTagText)?.index;if(closingTagIndex===void 0){cursor=closingTagEnd;continue}let yamlContent=closingTagText.slice(0,closingTagIndex),parsedArguments=parseYamlMapping(yamlContent);parsedArguments!==null?parsedToolCalls.push({name:openingTag.name,arguments:parsedArguments}):options?.onError?.("Could not process YAML XML tool call, keeping original text.",{toolCall:text.slice(absoluteIndex,closingTagEnd)}),cursor=closingTagEnd}return parsedToolCalls}function createYamlXmlStreamParser(tools,options){let toolNames=tools.map(tool=>tool.name),buffer="",currentToolState=null,nextToolCallIndex=0;function emitSnapshot(events,yamlContent){if(!currentToolState)return;let parsedArguments=parseYamlMapping(yamlContent);if(parsedArguments===null)return;let snapshot=JSON.stringify(parsedArguments);snapshot==="{}"||snapshot===currentToolState.lastArgumentsSnapshot||(currentToolState.lastArgumentsSnapshot===null&&events.push({type:"toolcall_start",index:currentToolState.index,name:currentToolState.name,id:currentToolState.id}),currentToolState.lastArgumentsSnapshot=snapshot,events.push({type:"toolcall_delta",index:currentToolState.index,argumentsDelta:snapshot}))}function processBuffer(){let events=[];for(;buffer.length>0;){if(currentToolState){let closingTagMatch=new RegExp(`</\\s*${escapeRegExp4(currentToolState.name)}\\s*>`).exec(buffer);if(!closingTagMatch||closingTagMatch.index===void 0){emitSnapshot(events,buffer);break}let yamlContent=buffer.slice(0,closingTagMatch.index),originalCallText=`<${currentToolState.name}>${yamlContent}${closingTagMatch[0]}`,parsedArguments=parseYamlMapping(yamlContent);if(buffer=buffer.slice(closingTagMatch.index+closingTagMatch[0].length),parsedArguments===null){options?.onError?.("Could not process YAML XML tool call, keeping original text.",{toolCall:originalCallText}),currentToolState.lastArgumentsSnapshot!==null&&events.push({type:"toolcall_end",index:currentToolState.index,name:currentToolState.name,id:currentToolState.id,arguments:{},incomplete:!0,errorMessage:"Tool call arguments could not be parsed"}),shouldEmitRawToolCallTextOnError4(options)&&events.push({type:"text",text:originalCallText}),currentToolState=null;continue}emitSnapshot(events,yamlContent),currentToolState.lastArgumentsSnapshot===null&&events.push({type:"toolcall_start",index:currentToolState.index,name:currentToolState.name,id:currentToolState.id}),events.push({type:"toolcall_end",index:currentToolState.index,name:currentToolState.name,id:currentToolState.id,arguments:parsedArguments}),currentToolState=null;continue}let openingTag=findEarliestXmlToolTag(buffer,toolNames);if(!openingTag){let textLength=getSafeXmlTextLength(buffer,toolNames);if(textLength===0)break;events.push({type:"text",text:buffer.slice(0,textLength)}),buffer=buffer.slice(textLength);continue}if(openingTag.index>0&&events.push({type:"text",text:buffer.slice(0,openingTag.index)}),buffer=buffer.slice(openingTag.index+openingTag.tag.length),openingTag.selfClosing){let id=`yaml-xml-tool-${nextToolCallIndex}`,index=nextToolCallIndex;nextToolCallIndex+=1,events.push({type:"toolcall_start",index,name:openingTag.name,id}),events.push({type:"toolcall_end",index,name:openingTag.name,id,arguments:{}});continue}currentToolState={id:`yaml-xml-tool-${nextToolCallIndex}`,index:nextToolCallIndex,name:openingTag.name,lastArgumentsSnapshot:null},nextToolCallIndex+=1}return events}return{feed(textDelta){return textDelta.length===0?[]:(buffer+=textDelta,processBuffer())},finish(){let events=processBuffer();if(!currentToolState&&buffer.length>0&&(events.push({type:"text",text:buffer}),buffer=""),currentToolState){let state=currentToolState,parsedArguments=parseYamlMapping(buffer),tool=tools.find(candidate=>candidate.name===state.name),validatedArguments=null;if(parsedArguments!==null&&tool)try{validatedArguments=validateToolArguments(tool,{type:"toolCall",id:state.id,name:state.name,arguments:parsedArguments})}catch{validatedArguments=null}validatedArguments!==null?(emitSnapshot(events,buffer),state.lastArgumentsSnapshot===null&&events.push({type:"toolcall_start",index:state.index,name:state.name,id:state.id}),events.push({type:"toolcall_end",index:state.index,name:state.name,id:state.id,arguments:validatedArguments})):(state.lastArgumentsSnapshot===null&&events.push({type:"toolcall_start",index:state.index,name:state.name,id:state.id}),events.push({type:"toolcall_end",index:state.index,name:state.name,id:state.id,arguments:parsedArguments??{},incomplete:!0,errorMessage:"Tool call was truncated mid-arguments"}),options?.onError?.("Could not complete streaming YAML XML tool call at finish.",{protocol:"yaml-xml",retainedLength:buffer.length})),buffer="",currentToolState=null}return events}}}var hermesProtocol={formatToolsSystemPrompt:hermesFormatToolsSystemPrompt,formatToolResponse:hermesFormatToolResponse,formatToolCall:hermesFormatToolCall,parseGeneratedText:hermesParseGeneratedText,createStreamParser:hermesCreateStreamParser},morphXmlProtocol={formatToolsSystemPrompt:morphXmlFormatToolsSystemPrompt,formatToolResponse:morphXmlFormatToolResponse,formatToolCall:morphXmlFormatToolCall,parseGeneratedText:parseMorphXmlGeneratedText,createStreamParser:createMorphXmlStreamParser},yamlXmlProtocol={formatToolsSystemPrompt:yamlXmlFormatToolsSystemPrompt,formatToolResponse:yamlXmlFormatToolResponse,formatToolCall:yamlXmlFormatToolCall,parseGeneratedText:parseYamlXmlGeneratedText,createStreamParser:createYamlXmlStreamParser},gemma4Protocol={formatToolsSystemPrompt:gemma4FormatToolsSystemPrompt,formatToolResponse:gemma4FormatToolResponse,formatToolCall:gemma4FormatToolCall,parseGeneratedText:gemma4ParseGeneratedText,createStreamParser:gemma4CreateStreamParser},antmlProtocol={formatToolsSystemPrompt:antmlFormatToolsSystemPrompt,formatToolResponse:antmlFormatToolResponse,formatToolCall:antmlFormatToolCall,parseGeneratedText:parseAntmlGeneratedText,createStreamParser:createAntmlStreamParser},kimiXtmlProtocol={formatToolsSystemPrompt:kimiXtmlFormatToolsSystemPrompt,formatToolResponse:kimiXtmlFormatToolResponse,formatToolCall:kimiXtmlFormatToolCall,parseGeneratedText:parseKimiXtmlGeneratedText,createStreamParser:createKimiXtmlStreamParser},anthropicXmlProtocol={formatToolsSystemPrompt:anthropicXmlFormatToolsSystemPrompt,formatToolResponse:anthropicXmlFormatToolResponse,formatToolCall:anthropicXmlFormatToolCall,parseGeneratedText:parseAnthropicXmlGeneratedText,createStreamParser:createAnthropicXmlStreamParser},protocolRegistry={"anthropic-xml":anthropicXmlProtocol,antml:antmlProtocol,hermes:hermesProtocol,xml:morphXmlProtocol,"morph-xml":morphXmlProtocol,"yaml-xml":yamlXmlProtocol,"gemma4-delimiter":gemma4Protocol,"kimi-xtml":kimiXtmlProtocol};function getProtocol(format){let protocol=protocolRegistry[format];if(!protocol)throw new Error(`Unsupported tool call format: ${format}`);return protocol}function transformContext(context,protocol){let transformed={systemPrompt:context.systemPrompt,messages:context.messages.map(msg=>transformMessage(msg,protocol)),tools:void 0};if(context.tools&&context.tools.length>0){let toolPrompt=protocol.formatToolsSystemPrompt(context.tools);toolPrompt&&(transformed.systemPrompt=context.systemPrompt?`${toolPrompt}
|
|
325
325
|
|
|
326
|
-
${context.systemPrompt}`:toolPrompt)}return transformed}function transformMessage(message,protocol){switch(message.role){case"assistant":return transformAssistantMessage(message,protocol);case"toolResult":return transformToolResultMessage(message,protocol);default:return message}}function transformAssistantMessage(message,protocol){if(!message.content.some(block=>block.type==="toolCall"))return message;let newContent=[];for(let block of message.content)switch(block.type){case"text":{newContent.push(block);break}case"thinking":{newContent.push(block);break}case"toolCall":{let toolCallText=protocol.formatToolCall(block.name,block.arguments);newContent.push({type:"text",text:toolCallText});break}}return{...message,content:newContent}}function transformToolResultMessage(message,protocol){return{role:"user",content:protocol.formatToolResponse(message.toolName,message.toolCallId,message.content),timestamp:message.timestamp}}function wrapStreamWithToolCallMiddleware(innerStream,protocol,tools){let outerStream=new AssistantMessageEventStream,parser=protocol.createStreamParser(tools);return(async()=>{let projection=null,sawToolCall=!1,parserHasPendingInput=!1,flushParser=()=>{if(!projection||!parserHasPendingInput)return;let result=projection.projectParserEvents(parser.finish());sawToolCall=sawToolCall||result.sawToolCall,projection.finishText(),parserHasPendingInput=!1};try{for await(let event of innerStream)switch(event.type){case"start":projection=new StreamMessageProjection(outerStream,event.partial),outerStream.push({type:"start",partial:projection.message});break;case"text_start":if(!projection)break;projection.sync(event.partial),projection.startText(event.contentIndex,event.partial.content[event.contentIndex]);break;case"text_delta":{if(!projection)break;projection.sync(event.partial),event.delta.length>0&&(parserHasPendingInput=!0);let result=projection.projectParserEvents(parser.feed(event.delta));sawToolCall=sawToolCall||result.sawToolCall;break}case"text_end":if(!projection)break;projection.sync(event.partial),flushParser();break;case"thinking_start":if(!projection)break;projection.sync(event.partial),projection.startThinking(event.contentIndex,event.partial);break;case"thinking_delta":if(!projection)break;projection.sync(event.partial),projection.projectThinkingDelta(event.contentIndex,event.delta,event.partial);break;case"thinking_end":if(!projection)break;projection.sync(event.partial),projection.finishThinking(event.contentIndex,event.content,event.partial);break;case"done":{projection??=new StreamMessageProjection(outerStream,event.message),flushParser(),projection.finalizeDanglingToolCalls();let message=projection.finalize(event.message,sawToolCall),reason=(sawToolCall||projection.hasFinalizedToolCallContent())&&(event.reason==="stop"||event.reason==="length")?"toolUse":event.reason;outerStream.push({type:"done",reason,message}),outerStream.end();return}case"error":{if(!projection){outerStream.push(event),outerStream.end(event.error);return}projection.sync(event.error),flushParser(),projection.finalizeDanglingToolCalls();let message=projection.finalize(event.error,sawToolCall);if(projection.hasFinalizedToolCallContent()){let recovered={...message,stopReason:"toolUse"};outerStream.push({type:"done",reason:"toolUse",message:recovered}),outerStream.end(recovered);return}outerStream.push({type:"error",reason:event.reason,error:message}),outerStream.end(message);return}case"toolcall_start":case"toolcall_delta":case"toolcall_end":break}let innerMessage=await innerStream.result();projection??=new StreamMessageProjection(outerStream,innerMessage),flushParser(),projection.finalizeDanglingToolCalls(),outerStream.end(projection.finalize(innerMessage,sawToolCall))}catch(error){flushParser(),projection??=new StreamMessageProjection(outerStream,await innerStream.result()),projection.finalizeDanglingToolCalls();let fallback=projection.message;fallback.stopReason="error",fallback.errorMessage=error instanceof Error?error.message:JSON.stringify(error),outerStream.push({type:"error",reason:"error",error:fallback}),outerStream.end()}})(),outerStream}function getToolCallFormat(model){if(model.api!=="openai-completions")return;let format=model.compat?.toolCallFormat;if(format&&(format==="hermes"||format==="xml"||format==="morph-xml"||format==="yaml-xml"||format==="gemma4-delimiter"||format==="anthropic-xml"||format==="antml"||format==="kimi-xtml"))return format}function shouldRecoverTextToolCalls(model){return getToolCallFormat(model)!==void 0?!1:model.recoverTextToolCalls!==void 0?typeof model.recoverTextToolCalls=="boolean"?model.recoverTextToolCalls:!1:model.api==="cursor-agent"?!1:CLAUDE_MODEL_ID_PATTERN.test(model.id)||KIMI_MODEL_ID_PATTERN.test(model.id)}var CLAUDE_MODEL_ID_PATTERN=/(^|[^a-z0-9])claude([^a-z0-9]|$)/i,KIMI_MODEL_ID_PATTERN=/(^|[^a-z0-9])kimi([^a-z0-9]|$)/i;function hasKimiTextToolCallRecovery(model){return KIMI_MODEL_ID_PATTERN.test(model.id)}function wrapStreamWithModelRecovery(innerStream,model,tools){let recoveredStream=hasKimiTextToolCallRecovery(model)?wrapStreamWithKimiThinkingRecovery(innerStream):innerStream;return!shouldRecoverTextToolCalls(model)||tools.length===0?recoveredStream:wrapStreamWithInvokeRecovery(recoveredStream,tools,hasKimiTextToolCallRecovery(model)?{createParser:createXtmlRecoveryStreamParser,protocol:"kimi-xtml"}:void 0)}function cloneTextContent(content){return{type:"text",text:content.text,...content.textSignature===void 0?{}:{textSignature:content.textSignature}}}function cloneThinkingContent(content){return{type:"thinking",thinking:content.thinking,...content.thinkingSignature===void 0?{}:{thinkingSignature:content.thinkingSignature},...content.redacted===void 0?{}:{redacted:content.redacted}}}function cloneToolCall2(toolCall){return{type:"toolCall",id:toolCall.id,name:toolCall.name,arguments:structuredClone(toolCall.arguments),...toolCall.thoughtSignature===void 0?{}:{thoughtSignature:toolCall.thoughtSignature},...toolCall.namespace===void 0?{}:{namespace:toolCall.namespace}}}function cloneStartMessage(message){return{role:"assistant",content:[],api:message.api,provider:message.provider,model:message.model,...message.responseModel===void 0?{}:{responseModel:message.responseModel},...message.responseId===void 0?{}:{responseId:message.responseId},...message.providerThinkingLevel===void 0?{}:{providerThinkingLevel:message.providerThinkingLevel},...message.diagnostics===void 0?{}:{diagnostics:structuredClone(message.diagnostics)},usage:structuredClone(message.usage),stopReason:"pending",timestamp:message.timestamp}}function assertContentIndex(contentIndex){if(!Number.isSafeInteger(contentIndex)||contentIndex<0)throw new Error(`Invalid assistant message frame contentIndex: ${contentIndex}`)}function eventBlock(event){assertContentIndex(event.contentIndex);let block=event.partial.content[event.contentIndex];if(!block)throw new Error(`${event.type} event has no content block at index ${event.contentIndex}`);return block}function serializedArguments(argumentsValue){let serialized=JSON.stringify(argumentsValue);if(serialized===void 0)throw new Error("Tool-call arguments are not JSON-serializable");return serialized}var EMPTY_PARSED_TOOL_ARGUMENTS=serializedArguments(parseStreamingJson(""));function isJsonPrefix(snapshot,current){if(typeof snapshot=="string")return typeof current=="string"&¤t.startsWith(snapshot);if(Array.isArray(snapshot))return Array.isArray(current)&&snapshot.length<=current.length&&snapshot.every((value,index)=>isJsonPrefix(value,current[index]));if(typeof snapshot!="object"||snapshot===null)return Object.is(snapshot,current);if(typeof current!="object"||current===null||Array.isArray(current))return!1;let currentRecord=current;return Object.entries(snapshot).every(([key,value])=>Object.hasOwn(currentRecord,key)&&isJsonPrefix(value,currentRecord[key]))}var AssistantMessageFrameEncoder=class{constructor(){this.started=!1,this.terminal=!1,this.blocks=new Map}encode(event){if(this.terminal)throw new Error(`Assistant message event ${event.type} follows a terminal event`);switch(event.type){case"start":if(this.started)throw new Error("Assistant message stream contains more than one start event");return this.started=!0,{type:"start",partial:cloneStartMessage(event.partial)};case"done":if(!this.started)throw new Error("Assistant message done event appears before start");this.terminal=!0;return;case"error":this.terminal=!0;return}if(!this.started)throw new Error(`Assistant message ${event.type} event appears before start`);switch(event.type){case"text_start":{let content=eventBlock(event);if(content.type!=="text")throw new Error(`text_start event points to ${content.type} block at index ${event.contentIndex}`);return this.startBlock(event.contentIndex,{kind:"text",coveredChars:content.text.length,deltaChars:0}),{type:"text_start",contentIndex:event.contentIndex,content:cloneTextContent(content)}}case"text_delta":return this.encodeTextDelta(event.contentIndex,event.delta,"text");case"text_end":{let content=eventBlock(event);if(content.type!=="text")throw new Error(`text_end event points to ${content.type} block at index ${event.contentIndex}`);return this.endBlock(event.contentIndex,"text"),{type:"text_end",contentIndex:event.contentIndex,content:event.content,...content.textSignature===void 0?{}:{textSignature:content.textSignature}}}case"thinking_start":{let content=eventBlock(event);if(content.type!=="thinking")throw new Error(`thinking_start event points to ${content.type} block at index ${event.contentIndex}`);return this.startBlock(event.contentIndex,{kind:"thinking",coveredChars:content.thinking.length,deltaChars:0}),{type:"thinking_start",contentIndex:event.contentIndex,content:cloneThinkingContent(content)}}case"thinking_delta":return this.encodeTextDelta(event.contentIndex,event.delta,"thinking");case"thinking_end":{let content=eventBlock(event);if(content.type!=="thinking")throw new Error(`thinking_end event points to ${content.type} block at index ${event.contentIndex}`);return this.endBlock(event.contentIndex,"thinking"),{type:"thinking_end",contentIndex:event.contentIndex,content:event.content,...content.thinkingSignature===void 0?{}:{thinkingSignature:content.thinkingSignature},...content.redacted===void 0?{}:{redacted:content.redacted}}}case"toolcall_start":{let content=eventBlock(event);if(content.type!=="toolCall")throw new Error(`toolcall_start event points to ${content.type} block at index ${event.contentIndex}`);let snapshotArguments=serializedArguments(content.arguments),caughtUp=snapshotArguments===EMPTY_PARSED_TOOL_ARGUMENTS;return this.startBlock(event.contentIndex,{kind:"toolCall",caughtUp,catchupJson:"",snapshotArguments:caughtUp?"":snapshotArguments}),{type:"toolcall_start",contentIndex:event.contentIndex,toolCall:cloneToolCall2(content)}}case"toolcall_delta":{let state=this.block(event.contentIndex,"toolCall");if(state.kind!=="toolCall")throw new Error("Unreachable tool-call encoder state");if(state.caughtUp)return event.delta.length===0?void 0:{type:"toolcall_delta",contentIndex:event.contentIndex,delta:event.delta};state.catchupJson+=event.delta;let argumentsValue=parseStreamingJson(state.catchupJson);if(serializedArguments(argumentsValue)!==state.snapshotArguments){let snapshotArguments=parseStreamingJson(state.snapshotArguments);if(!isJsonPrefix(snapshotArguments,argumentsValue))return}state.caughtUp=!0,state.snapshotArguments="";let json=state.catchupJson;return state.catchupJson="",json.length===0?void 0:{type:"toolcall_checkpoint",contentIndex:event.contentIndex,json}}case"toolcall_end":{let content=eventBlock(event);if(content.type!=="toolCall")throw new Error(`toolcall_end event points to ${content.type} block at index ${event.contentIndex}`);if(event.toolCall.type!=="toolCall")throw new Error(`toolcall_end event has invalid tool call at index ${event.contentIndex}`);return this.endBlock(event.contentIndex,"toolCall"),{type:"toolcall_end",contentIndex:event.contentIndex,id:event.toolCall.id,name:event.toolCall.name,arguments:structuredClone(event.toolCall.arguments),...event.toolCall.thoughtSignature===void 0?{}:{thoughtSignature:event.toolCall.thoughtSignature},...event.toolCall.namespace===void 0?{}:{namespace:event.toolCall.namespace}}}}}startBlock(contentIndex,state){if(assertContentIndex(contentIndex),this.blocks.has(contentIndex))throw new Error(`Assistant message block ${contentIndex} starts more than once`);this.blocks.set(contentIndex,state)}block(contentIndex,kind){assertContentIndex(contentIndex);let state=this.blocks.get(contentIndex);if(state===void 0)throw new Error(`Assistant message ${kind} block ${contentIndex} has not started`);if(state.kind!==kind)throw new Error(`Assistant message block ${contentIndex} is ${state.kind}, not ${kind}`);return state}endBlock(contentIndex,kind){this.block(contentIndex,kind),this.blocks.delete(contentIndex)}encodeTextDelta(contentIndex,delta,kind){let state=this.block(contentIndex,kind);if(state.kind==="toolCall")throw new Error("Unreachable text encoder state");let deltaStart=state.deltaChars;state.deltaChars+=delta.length;let covered=Math.max(0,state.coveredChars-deltaStart);if(covered>=delta.length)return;let uncovered=covered===0?delta:delta.slice(covered);return kind==="text"?{type:"text_delta",contentIndex,delta:uncovered}:{type:"thinking_delta",contentIndex,delta:uncovered}}};function appendBlock(message,states,contentIndex,block,state){if(assertContentIndex(contentIndex),contentIndex!==message.content.length){let reason=contentIndex<message.content.length?"already exists":"would leave a gap";throw new Error(`Cannot start assistant message block at index ${contentIndex}: ${reason}`)}message.content.push(structuredClone(block)),states.set(contentIndex,state)}function activeBlock(message,states,contentIndex,expectedKind,frameType){assertContentIndex(contentIndex);let state=states.get(contentIndex),block=message.content[contentIndex];if(!state||!block)throw new Error(`${frameType} frame has no started block at index ${contentIndex}`);if(state.kind!==expectedKind||block.type!==expectedKind)throw new Error(`${frameType} frame expected ${expectedKind} block at index ${contentIndex}, found ${block.type}`);if(state.ended)throw new Error(`${frameType} frame follows the end of block at index ${contentIndex}`);return{block,state}}function reduceAssistantMessageFrames(frames){let message,frameBeforeStart,states=new Map;for(let frame of frames){if(frame.type==="start"){if(message)throw new Error("Assistant message frame sequence contains more than one start frame");if(frameBeforeStart!==void 0)throw new Error(`${frameBeforeStart} frame appears before the start frame`);message=structuredClone(frame.partial);continue}if(!message){frameBeforeStart??=frame.type;continue}switch(frame.type){case"text_start":if(frame.content.type!=="text")throw new Error(`text_start frame contains ${frame.content.type} content`);appendBlock(message,states,frame.contentIndex,frame.content,{kind:"text",ended:!1});break;case"text_delta":{let{block}=activeBlock(message,states,frame.contentIndex,"text",frame.type);if(block.type!=="text")throw new Error("Unreachable text frame state");block.text+=frame.delta;break}case"text_end":{let{block,state}=activeBlock(message,states,frame.contentIndex,"text",frame.type);if(block.type!=="text")throw new Error("Unreachable text frame state");block.text=frame.content,delete block.textSignature,frame.textSignature!==void 0&&(block.textSignature=frame.textSignature),state.ended=!0;break}case"thinking_start":if(frame.content.type!=="thinking")throw new Error(`thinking_start frame contains ${frame.content.type} content`);appendBlock(message,states,frame.contentIndex,frame.content,{kind:"thinking",ended:!1});break;case"thinking_delta":{let{block}=activeBlock(message,states,frame.contentIndex,"thinking",frame.type);if(block.type!=="thinking")throw new Error("Unreachable thinking frame state");block.thinking+=frame.delta;break}case"thinking_end":{let{block,state}=activeBlock(message,states,frame.contentIndex,"thinking",frame.type);if(block.type!=="thinking")throw new Error("Unreachable thinking frame state");block.thinking=frame.content,delete block.thinkingSignature,delete block.redacted,frame.thinkingSignature!==void 0&&(block.thinkingSignature=frame.thinkingSignature),frame.redacted!==void 0&&(block.redacted=frame.redacted),state.ended=!0;break}case"toolcall_start":if(frame.toolCall.type!=="toolCall")throw new Error(`toolcall_start frame contains ${frame.toolCall.type} content`);appendBlock(message,states,frame.contentIndex,frame.toolCall,{kind:"toolCall",ended:!1,json:""});break;case"toolcall_checkpoint":{let{block,state}=activeBlock(message,states,frame.contentIndex,"toolCall",frame.type);if(block.type!=="toolCall"||state.kind!=="toolCall")throw new Error("Unreachable tool-call checkpoint state");state.json=frame.json,block.arguments=parseStreamingJson(frame.json);break}case"toolcall_delta":{let{block,state}=activeBlock(message,states,frame.contentIndex,"toolCall",frame.type);if(block.type!=="toolCall"||state.kind!=="toolCall")throw new Error("Unreachable tool-call frame state");state.json+=frame.delta;break}case"toolcall_end":{let{block,state}=activeBlock(message,states,frame.contentIndex,"toolCall",frame.type);if(block.type!=="toolCall")throw new Error("Unreachable tool-call frame state");block.id=frame.id,block.name=frame.name,block.arguments=structuredClone(frame.arguments),delete block.thoughtSignature,delete block.namespace,frame.thoughtSignature!==void 0&&(block.thoughtSignature=frame.thoughtSignature),frame.namespace!==void 0&&(block.namespace=frame.namespace),state.ended=!0;break}}}if(message){for(let[contentIndex,state]of states){if(state.kind!=="toolCall"||state.ended||state.json.length===0)continue;let block=message.content[contentIndex];if(block?.type!=="toolCall")throw new Error("Unreachable tool-call frame state");block.arguments=parseStreamingJson(state.json)}return message}}var kCursorExecResolved=Symbol("provider.block.cursorExecResolved");function isCursorExecResolved(block){return block?.[kCursorExecResolved]===!0}function copyCursorExecResolved(target,source){source[kCursorExecResolved]===!0&&(target[kCursorExecResolved]=!0)}function dropFailedAssistantTurns(messages){let callIdsByKeptAssistants=new Set,callIdsByFailedAssistants=new Set;for(let message of messages){let assistant=asAssistantTurn(message);if(!assistant)continue;let declared=isFailedStop(assistant.stopReason)?callIdsByFailedAssistants:callIdsByKeptAssistants;for(let block of assistant.content)block.type==="toolCall"&&typeof block.id=="string"&&declared.add(block.id)}for(let id of callIdsByKeptAssistants)callIdsByFailedAssistants.delete(id);return messages.filter(message=>{let assistant=asAssistantTurn(message);return assistant?!isFailedStop(assistant.stopReason):message.role==="toolResult"&&"toolCallId"in message&&typeof message.toolCallId=="string"?!callIdsByFailedAssistants.has(message.toolCallId):!0})}function asAssistantTurn(message){if(message.role==="assistant"&&!(!("content"in message)||!Array.isArray(message.content)))return{stopReason:"stopReason"in message?message.stopReason:void 0,content:message.content}}function isFailedStop(stopReason){return stopReason==="error"||stopReason==="aborted"}var EMPTY_RESPONSE_ERROR="Model returned an empty response twice",EMPTY_TOOL_USE_ERROR="Model returned tool_use without a tool call twice",FORWARDED_EMPTY_RESPONSE_ERROR="Model returned an empty response after streaming thinking",FORWARDED_EMPTY_TOOL_USE_ERROR="Model returned tool_use without a tool call after streaming thinking";var OVERFLOW_PATTERNS=[/^Context window exhausted: /,/prompt is too long/i,/request_too_large/i,/input is too long for requested model/i,/exceeds (?:(?:the|this) )?(?:model'?s )?context window/i,/exceeds (?:the )?(?:model'?s )?maximum context length(?: of [\d,]+ tokens?|\s*\([\d,]+\))/i,/input token count.*exceeds the maximum/i,/maximum prompt length is \d+/i,/reduce the length of the messages/i,/maximum context length is \d+ tokens/i,/exceeds (?:the )?maximum allowed input length of [\d,]+ tokens?/i,/input \(\d+ tokens\) is longer than the model'?s context length \(\d+ tokens\)/i,/exceeds the limit of \d+/i,/exceeds the available context size/i,/greater than the context length/i,/context window exceeds limit/i,/exceeded model token limit/i,/too large for model with \d+ maximum context length/i,/prompt has [\d,]+ tokens?, but the configured context size is [\d,]+ tokens?/i,/model_context_window_exceeded/i,/prompt too long; exceeded (?:max )?context length/i,/range of input length should be/i,/context[_ ]length[_ ]exceeded/i,/too many tokens/i,/token limit exceeded/i,/^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i,/(?:request[ _])?(?:body|entity|payload)[_ ]too[_ ]large/i,/Request payload is \d+ (?:bytes, over the \d+ byte|tokens, over the \d+ token) limit Kiro accepts\./,/Model context limit reached\. Conversation size exceeds model capacity\./],NON_OVERFLOW_PATTERNS=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i,/tokens per (?:min|minute|hour|day)/i,/\bTPM\b/i,/\bRPM\b/i,/quota exceeded/i,/retry (?:after|in) \d/i,/^429\b/,/status code 429/i,/overloaded/i],RESOURCE_EXHAUSTED_PATTERN=/resource.?exhausted/i;function isContextOverflow(message,contextWindow){if(message.stopReason==="error"&&message.errorMessage){let isNonOverflow=NON_OVERFLOW_PATTERNS.some(p=>p.test(message.errorMessage));if(!isNonOverflow&&OVERFLOW_PATTERNS.some(p=>p.test(message.errorMessage)))return!0;let usage=message.usage,hasTokenEvidence=(usage.totalTokens||usage.input+usage.output+usage.cacheRead+usage.cacheWrite)>0;if(!isNonOverflow&&hasTokenEvidence&&RESOURCE_EXHAUSTED_PATTERN.test(message.errorMessage)&&(contextWindow===void 0||contextWindow<=0||cursorZeroTokenCount(message)>=contextWindow*.5))return!0}return!!(contextWindow&&message.stopReason==="stop"&&message.usage.input+message.usage.cacheRead>contextWindow||contextWindow&&message.stopReason==="length"&&message.usage.output===0&&message.usage.input+message.usage.cacheRead>=contextWindow*.99)}function isRecoverableLength(message,desiredMaxOutput){return message.stopReason==="length"&&desiredMaxOutput>0&&message.usage.output<desiredMaxOutput}function getOverflowPatterns(){return[...OVERFLOW_PATTERNS]}function cursorZeroTokenCount(message){let usage=message.usage;return usage?usage.totalTokens||(usage.input??0)+(usage.output??0)+(usage.cacheRead??0)+(usage.cacheWrite??0):0}function isCursorPayloadResourceExhausted(message,_estimateTokens){return message.stopReason!=="error"||!/resource.?exhausted/i.test(message.errorMessage||"")?!1:!(cursorZeroTokenCount(message)>0)}function isCursorQuotaResourceExhausted(message,contextWindow){let tokens=cursorZeroTokenCount(message);return message.stopReason==="error"&&RESOURCE_EXHAUSTED_PATTERN.test(message.errorMessage||"")&&contextWindow>0&&tokens>0&&tokens<contextWindow*.5}function isCursorZeroTokenResourceExhausted(message){return message.stopReason!=="error"||!/resource.?exhausted/i.test(message.errorMessage||"")?!1:!(cursorZeroTokenCount(message)>0)}function shouldSkipProviderFallbackForCursorZeroRe(options){return options?.sameModelRemint===!0}function shouldRetryOverflowWithoutCompact(compacted,errorMessage){return compacted?!1:/Nothing to compact/i.test(errorMessage||"")}function cursorOverflowCompactionSettings(settings,provider,reason){return reason!=="overflow"||provider!=="cursor"&&provider!=="cursor-cli-oauth"?settings:{...settings,keepRecentTokens:0,restorationEnabled:!1}}function buildProviderErrorPattern(patterns){return new RegExp(patterns.join("|"),"i")}function escapeRegExp5(text){return text.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var USAGE_LIMIT_EXHAUSTION={codes:["usage_limit_reached","usage_not_included"],markers:["usage_limit_reached","usage_not_included","usage limit has been reached"]},NON_RETRYABLE_PROVIDER_ERROR_PATTERN=buildProviderErrorPattern(["GoUsageLimitError","FreeUsageLimitError","Monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing","credits_required","credits are required",...USAGE_LIMIT_EXHAUSTION.markers,"invalid request: tools\\.","invalid request: functions\\.","tools\\.[^ ]*function\\.parameters","tools\\.\\d+\\.function\\.parameters","invalid tool schema"]),RETRYABLE_PROVIDER_ERROR_PATTERN=buildProviderErrorPattern(["Credential store is busy: lock","overloaded","rate.?limit","too many requests","429","500","502","503","504","522","524","service.?unavailable","server.?error","internal.?error","provider.?returned.?error","exceeded request buffer limit while retrying upstream","network.?error","connection.?error","connection.?refused","connection.?lost","other side closed","fetch failed","getaddrinfo","ENOTFOUND","EAI_AGAIN","upstream.?connect","upstream.?unavailable","reset before headers","socket hang up","socket connection was closed","timed? out","timeout","terminated","websocket.?closed","websocket.?error","ended without","stream ended before message_stop","stream ended before a terminal response event","http2 request did not get a response","retry delay","you can retry your request","try your request again","please retry your request","the model request was rejected\\.\\s*check the request and try again\\.?","was found without a corresponding `","must not contain streaming index",escapeRegExp5(FORWARDED_EMPTY_RESPONSE_ERROR),escapeRegExp5(FORWARDED_EMPTY_TOOL_USE_ERROR),"ResourceExhausted","Lock file is already being held"]),DEFAULT_MAX_AGENT_RETRY_DELAY_MS=6e4;function retryDelayMs(policy,attempt){let scheduledDelayMs=policy.baseDelayMs*2**Math.max(0,attempt-1),sample=Math.min(1,Math.max(0,(policy.random??Math.random)())),jitteredDelayMs=Math.round(scheduledDelayMs*(.9+sample*.2)),safeDelay=Number.isSafeInteger(jitteredDelayMs)?jitteredDelayMs:Number.MAX_SAFE_INTEGER;return Math.min(safeDelay,policy.maxAgentDelayMs??DEFAULT_MAX_AGENT_RETRY_DELAY_MS)}var RetrySleepAbortError=class extends Error{constructor(){super("Aborted")}};function sleep(ms,signal){return new Promise((resolve,reject)=>{if(signal?.aborted){reject(new RetrySleepAbortError);return}let timeout=setTimeout(resolve,ms);signal?.addEventListener("abort",()=>{clearTimeout(timeout),reject(new RetrySleepAbortError)},{once:!0})})}async function retryTransientCall(produce,isRetryable,policy,signal,callbacks){let maxAttempts=policy?.enabled?policy.maxRetries:0,attempt=0,lastRetry;for(;;)try{let value=await produce();return lastRetry&&await callbacks?.onRetryFinished?.(!0,lastRetry.attempt),value}catch(error){if(error instanceof RetrySleepAbortError)throw error;if(attempt>=maxAttempts||!isRetryable(error))throw lastRetry&&await callbacks?.onRetryFinished?.(!1,lastRetry.attempt,errorMessageOf(error)),error;attempt++,lastRetry={attempt,errorMessage:errorMessageOf(error)};let delayMs=retryDelayMs(policy,attempt);await callbacks?.onRetryScheduled?.(attempt,maxAttempts,delayMs,lastRetry.errorMessage);try{await sleep(delayMs,signal)}catch(sleepError){throw await callbacks?.onRetryFinished?.(!1,attempt,lastRetry.errorMessage),sleepError instanceof RetrySleepAbortError?error:sleepError}await callbacks?.onRetryAttemptStart?.()}}function errorMessageOf(error){return error instanceof Error?error.message||"Unknown error":String(error)||"Unknown error"}async function retryAssistantCall(produce,policy,signal,callbacks){let maxAttempts=policy?.enabled?policy.maxRetries:0,attempt=0,lastRetry;for(;;){let response=await produce();if(response.stopReason==="aborted")return lastRetry&&await callbacks?.onRetryFinished?.(!1,lastRetry.attempt),response;if(response.stopReason!=="error")return lastRetry&&await callbacks?.onRetryFinished?.(!0,lastRetry.attempt),response;if(attempt>=maxAttempts||!isRetryableAssistantError(response))return lastRetry&&await callbacks?.onRetryFinished?.(!1,lastRetry.attempt,response.errorMessage),response;attempt++,lastRetry={attempt,errorMessage:response.errorMessage||"Unknown error"};let delayMs=retryDelayMs(policy,attempt);await callbacks?.onRetryScheduled?.(attempt,maxAttempts,delayMs,lastRetry.errorMessage);try{await sleep(delayMs,signal)}catch(error){if(await callbacks?.onRetryFinished?.(!1,attempt,lastRetry.errorMessage),error instanceof RetrySleepAbortError){let{errorMessage:_errorMessage,...rest}=response;return{...rest,stopReason:"aborted"}}throw error}await callbacks?.onRetryAttemptStart?.()}}function isRetryableAssistantError(message){return message.stopReason!=="error"||message.stopDetails?.type==="refusal"||message.stopDetails?.type==="sensitive"||!message.errorMessage?!1:isRetryableErrorMessage(message.errorMessage)}var PROVIDER_STREAM_STALL_ERROR_PATTERN=/^(?: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,PROVIDER_TRANSPORT_TIMEOUT_ERROR_PATTERN=/^Request timed out\.?$/i;function isProviderStreamStallError(message){return message.stopReason==="error"&&PROVIDER_STREAM_STALL_ERROR_PATTERN.test(message.errorMessage??"")}var PROVIDER_STALL_PHASES=[{pattern:/^Provider stream start timed out after (\d+)ms/i,symptom:"accepted the request but never started sending a response",setting:"retry.provider.streamStartTimeoutMs"},{pattern:/^Idle timeout waiting for provider stream after (\d+)ms/i,symptom:"started the response and then went silent",setting:"retry.provider.timeoutMs"},{pattern:/^WebSocket liveness timeout after (\d+)ms/i,symptom:"stopped answering connection health checks"},{pattern:/^Provider stream stalled after the last output item: response\.completed timed out after (\d+)ms/i,symptom:"finished its output but never sent the end-of-response event"}];function formatStallDuration(timeoutMs){return timeoutMs<1e3?`${timeoutMs}ms`:timeoutMs<12e4?`${Math.round(timeoutMs/100)/10}s`:`${Math.round(timeoutMs/6e3)/10}m`}function describeProviderStallForUser(errorMessage,options={}){if(errorMessage)for(let{pattern,symptom,setting}of PROVIDER_STALL_PHASES){let match=pattern.exec(errorMessage);if(!match)continue;let subject=options.model?`The provider for ${options.model}`:"The provider",duration=formatStallDuration(Number(match[1])),sentences=[`${subject} ${symptom} within ${duration}, so the request was cancelled.`],attempts=options.attempts??0;if(attempts>0&&sentences.push(`Retried ${attempts} time${attempts===1?"":"s"} on the same model with the same result.`),options.recovery){let raise=setting?`, or raise ${setting} in settings (0 disables the bound)`:"",lead=options.recovery==="no-fallback-configured"?"No fallback model is configured for it, so nothing could take the turn over: run /fallback to add one":"Every model in its fallback chain was tried as well: run /fallback to review the chain";sentences.push(`${lead}, send the message again${raise}.`)}return sentences.join(" ")}}function isProviderTimeoutError(message){return message.abortSource==="provider"||isProviderStreamStallError(message)?!0:message.stopReason!=="error"&&message.stopReason!=="aborted"?!1:PROVIDER_TRANSPORT_TIMEOUT_ERROR_PATTERN.test(message.errorMessage??"")}function isRetryableErrorMessage(errorMessage){return classifyErrorMessage(errorMessage)==="retryable"}function classifyErrorMessage(errorMessage){return errorMessage?NON_RETRYABLE_PROVIDER_ERROR_PATTERN.test(errorMessage)?"non-retryable":RETRYABLE_PROVIDER_ERROR_PATTERN.test(errorMessage)?"retryable":"unknown":"unknown"}var TURN_RETRY_SUPPRESSION_PREFIX="senpi:no-turn-retry:";function stripTurnRetrySuppressionPrefix(message){return message.replaceAll(TURN_RETRY_SUPPRESSION_PREFIX,"")}var WEBSOCKET_CLOSED_PATTERN=/^WebSocket closed\b/i,WEBSOCKET_ERROR_PATTERN=/^WebSocket error$/i,WEBSOCKET_CONNECT_TIMEOUT_PATTERN=/^WebSocket connect timeout after (\d+)ms/i,RECOVERY_SENTENCE={"no-fallback-configured":"No fallback model is configured for it, so nothing could take the turn over: run /fallback to add one, or send the message again to continue from the partial reply.","chain-exhausted":"Every model in its fallback chain was tried as well: run /fallback to review the chain, or send the message again to continue from the partial reply."};function transportSymptom(errorMessage,subject){if(WEBSOCKET_CLOSED_PATTERN.test(errorMessage))return`The connection to ${subject} dropped before the reply finished (${errorMessage}).`;if(WEBSOCKET_ERROR_PATTERN.test(errorMessage))return`The connection to ${subject} reported an error before the reply finished (${errorMessage}).`;let connectTimeout=WEBSOCKET_CONNECT_TIMEOUT_PATTERN.exec(errorMessage);if(connectTimeout)return`${subject.replace(/^the provider/,"The provider")} did not accept the connection within ${formatStallDuration(Number(connectTimeout[1]))}.`}function describeProviderFailureForUser(errorMessage,options={}){if(!errorMessage)return;let message=stripTurnRetrySuppressionPrefix(errorMessage).trim();if(!message)return;let stall=describeProviderStallForUser(message,options);if(stall!==void 0)return stall;let subject=options.model?`the provider for ${options.model}`:"the provider",symptom=transportSymptom(message,subject);if(symptom===void 0)return;let sentences=[symptom],attempts=options.attempts??0;return attempts>0&&sentences.push(`Retried ${attempts} time${attempts===1?"":"s"} on the same model with the same result.`),options.recovery&&sentences.push(RECOVERY_SENTENCE[options.recovery]),sentences.join(" ")}var ANTHROPIC_POLICY_REFUSAL_PATTERN=/This request triggered restrictions on [\s\S]+? and was blocked under Anthropic's Usage Policy\b/i;function isClassifierRefusal(message){return message.stopReason!=="error"&&message.stopReason!=="toolUse"?!1:message.stopDetails?.type==="refusal"||message.stopDetails?.type==="sensitive"?!0:message.errorMessage?ANTHROPIC_POLICY_REFUSAL_PATTERN.test(message.errorMessage):!1}var TOOL_RESULT_PLACEHOLDER="Tool output unavailable (context compacted)";function incompleteToolCallRetryText(name,errorMessage){return errorMessage!==void 0?`${errorMessage}${errorMessage.endsWith(".")?"":"."} Re-issue the tool call with complete arguments.`:`Tool call "${name}" was not executed: the response ended before the tool call was complete. Re-issue the tool call with complete arguments.`}function repairOrphanedToolResults(messages){let toolCallIds=new Set,toolResultIds=new Set;for(let message of messages){if(message.role==="assistant")for(let block of message.content)block.type==="toolCall"&&toolCallIds.add(block.id);message.role==="toolResult"&&toolResultIds.add(message.toolCallId)}let output=[],dangling=new Set([...toolCallIds].filter(id=>!toolResultIds.has(id)));for(let message of messages){if(message.role==="toolResult"){if(!toolCallIds.has(message.toolCallId)){output.push({...message,content:[{type:"text",text:TOOL_RESULT_PLACEHOLDER}]});continue}output.push(message);continue}if(output.push(message),message.role==="assistant"){if(message.stopReason==="error"||message.stopReason==="aborted")continue;for(let block of message.content){if(block.type!=="toolCall"||!dangling.has(block.id))continue;let incomplete=block.incomplete===!0,text=incomplete?incompleteToolCallRetryText(block.name,block.errorMessage):TOOL_RESULT_PLACEHOLDER;output.push({role:"toolResult",toolCallId:block.id,toolName:block.name,content:[{type:"text",text}],isError:incomplete,timestamp:message.timestamp?message.timestamp+1:Date.now()}),dangling.delete(block.id)}}}return output}function StringEnum(values,options){return typebox_exports.Unsafe({type:"string",enum:values,...options?.description&&{description:options.description},...options?.default&&{default:options.default}})}var INVISIBLE_FORMAT_CHARS=new RegExp("\\p{Cf}","gu");function hasVisibleText(text){return text.replace(INVISIBLE_FORMAT_CHARS,"").trim().length>0}function hasVisibleAssistantContent(message){return message.content.some(block=>block.type==="toolCall"||block.type==="text"&&hasVisibleText(block.text))}export{create,messageDesc,fromBinary,fileDesc,toBinary,measureCursorModelInputSerializedBytes,measureCursorHistorySerializedBytes,piReadArgs,piLsPath,piLimit,piTimeout,composeShellCommand,omitUndefinedArgs,registerPromptCacheWarmer,warmPromptCache,fauxText,fauxThinking,fauxToolCall,fauxAssistantMessage,createFauxCore,getRegisteredFauxProvider,fauxOverflowError,fauxProvider,installProviderScopeAccessor,registerApiProvider,registerBuiltinApiProvider,getApiProvider,getApiProviders,unregisterApiProviders,clearApiProviders,envApiKeyAuth,lazyOAuth,CURSOR_MODEL_CAPABILITIES,parseCursorVariantId,getCursorVariantAlias,getCursorBaseIdForVariant,getCursorCapabilityForBase,deriveCursorVariantAliases,normalizeCursorCatalog,resolveCursorSelectionDescriptor,renderCursorCliModelString,parseEndpointReasoningEfforts,ANTHROPIC_AUTH_TOKEN_ENV,ANTHROPIC_OAUTH_TOKEN_ENV,ANTHROPIC_API_KEY_ENV,getApiKeyEnvVars,findEnvKeys,getEnvApiKey,createImagesModels,createImagesProvider,supportsAllowedToolChoice,createXtmlRecoveryStreamParser,wrapStreamWithInvokeRecovery,Compile,compile_exports,validateToolCall,validateToolArguments,require_dist,getProtocol,transformContext,wrapStreamWithToolCallMiddleware,getToolCallFormat,shouldRecoverTextToolCalls,hasKimiTextToolCallRecovery,wrapStreamWithModelRecovery,AssistantMessageFrameEncoder,reduceAssistantMessageFrames,kCursorExecResolved,isCursorExecResolved,copyCursorExecResolved,dropFailedAssistantTurns,EMPTY_RESPONSE_ERROR,EMPTY_TOOL_USE_ERROR,FORWARDED_EMPTY_RESPONSE_ERROR,FORWARDED_EMPTY_TOOL_USE_ERROR,isContextOverflow,isRecoverableLength,getOverflowPatterns,isCursorPayloadResourceExhausted,isCursorQuotaResourceExhausted,isCursorZeroTokenResourceExhausted,shouldSkipProviderFallbackForCursorZeroRe,shouldRetryOverflowWithoutCompact,cursorOverflowCompactionSettings,USAGE_LIMIT_EXHAUSTION,DEFAULT_MAX_AGENT_RETRY_DELAY_MS,retryDelayMs,retryTransientCall,retryAssistantCall,isRetryableAssistantError,isProviderStreamStallError,formatStallDuration,describeProviderStallForUser,isProviderTimeoutError,isRetryableErrorMessage,classifyErrorMessage,TURN_RETRY_SUPPRESSION_PREFIX,stripTurnRetrySuppressionPrefix,describeProviderFailureForUser,isClassifierRefusal,contentText,TOOL_RESULT_PLACEHOLDER,repairOrphanedToolResults,StringEnum,hasVisibleText,hasVisibleAssistantContent};
|
|
326
|
+
${context.systemPrompt}`:toolPrompt)}return transformed}function transformMessage(message,protocol){switch(message.role){case"assistant":return transformAssistantMessage(message,protocol);case"toolResult":return transformToolResultMessage(message,protocol);default:return message}}function transformAssistantMessage(message,protocol){if(!message.content.some(block=>block.type==="toolCall"))return message;let newContent=[];for(let block of message.content)switch(block.type){case"text":{newContent.push(block);break}case"thinking":{newContent.push(block);break}case"toolCall":{let toolCallText=protocol.formatToolCall(block.name,block.arguments);newContent.push({type:"text",text:toolCallText});break}}return{...message,content:newContent}}function transformToolResultMessage(message,protocol){return{role:"user",content:protocol.formatToolResponse(message.toolName,message.toolCallId,message.content),timestamp:message.timestamp}}function wrapStreamWithToolCallMiddleware(innerStream,protocol,tools){let outerStream=new AssistantMessageEventStream,parser=protocol.createStreamParser(tools);return(async()=>{let projection=null,sawToolCall=!1,parserHasPendingInput=!1,flushParser=()=>{if(!projection||!parserHasPendingInput)return;let result=projection.projectParserEvents(parser.finish());sawToolCall=sawToolCall||result.sawToolCall,projection.finishText(),parserHasPendingInput=!1};try{for await(let event of innerStream)switch(event.type){case"start":projection=new StreamMessageProjection(outerStream,event.partial),outerStream.push({type:"start",partial:projection.message});break;case"text_start":if(!projection)break;projection.sync(event.partial),projection.startText(event.contentIndex,event.partial.content[event.contentIndex]);break;case"text_delta":{if(!projection)break;projection.sync(event.partial),event.delta.length>0&&(parserHasPendingInput=!0);let result=projection.projectParserEvents(parser.feed(event.delta));sawToolCall=sawToolCall||result.sawToolCall;break}case"text_end":if(!projection)break;projection.sync(event.partial),flushParser();break;case"thinking_start":if(!projection)break;projection.sync(event.partial),projection.startThinking(event.contentIndex,event.partial);break;case"thinking_delta":if(!projection)break;projection.sync(event.partial),projection.projectThinkingDelta(event.contentIndex,event.delta,event.partial);break;case"thinking_end":if(!projection)break;projection.sync(event.partial),projection.finishThinking(event.contentIndex,event.content,event.partial);break;case"done":{projection??=new StreamMessageProjection(outerStream,event.message),flushParser(),projection.finalizeDanglingToolCalls();let message=projection.finalize(event.message,sawToolCall),reason=(sawToolCall||projection.hasFinalizedToolCallContent())&&(event.reason==="stop"||event.reason==="length")?"toolUse":event.reason;outerStream.push({type:"done",reason,message}),outerStream.end();return}case"error":{if(!projection){outerStream.push(event),outerStream.end(event.error);return}projection.sync(event.error),flushParser(),projection.finalizeDanglingToolCalls();let message=projection.finalize(event.error,sawToolCall);if(projection.hasFinalizedToolCallContent()){let recovered={...message,stopReason:"toolUse"};outerStream.push({type:"done",reason:"toolUse",message:recovered}),outerStream.end(recovered);return}outerStream.push({type:"error",reason:event.reason,error:message}),outerStream.end(message);return}case"toolcall_start":case"toolcall_delta":case"toolcall_end":break}let innerMessage=await innerStream.result();projection??=new StreamMessageProjection(outerStream,innerMessage),flushParser(),projection.finalizeDanglingToolCalls(),outerStream.end(projection.finalize(innerMessage,sawToolCall))}catch(error){flushParser(),projection??=new StreamMessageProjection(outerStream,await innerStream.result()),projection.finalizeDanglingToolCalls();let fallback=projection.message;fallback.stopReason="error",fallback.errorMessage=error instanceof Error?error.message:JSON.stringify(error),outerStream.push({type:"error",reason:"error",error:fallback}),outerStream.end()}})(),outerStream}function getToolCallFormat(model){if(model.api!=="openai-completions")return;let format=model.compat?.toolCallFormat;if(format&&(format==="hermes"||format==="xml"||format==="morph-xml"||format==="yaml-xml"||format==="gemma4-delimiter"||format==="anthropic-xml"||format==="antml"||format==="kimi-xtml"))return format}function shouldRecoverTextToolCalls(model){return getToolCallFormat(model)!==void 0?!1:model.recoverTextToolCalls!==void 0?typeof model.recoverTextToolCalls=="boolean"?model.recoverTextToolCalls:!1:model.api==="cursor-agent"?!1:CLAUDE_MODEL_ID_PATTERN.test(model.id)||KIMI_MODEL_ID_PATTERN.test(model.id)}var CLAUDE_MODEL_ID_PATTERN=/(^|[^a-z0-9])claude([^a-z0-9]|$)/i,KIMI_MODEL_ID_PATTERN=/(^|[^a-z0-9])kimi([^a-z0-9]|$)/i;function hasKimiTextToolCallRecovery(model){return KIMI_MODEL_ID_PATTERN.test(model.id)}function wrapStreamWithModelRecovery(innerStream,model,tools){let recoveredStream=hasKimiTextToolCallRecovery(model)?wrapStreamWithKimiThinkingRecovery(innerStream):innerStream;return!shouldRecoverTextToolCalls(model)||tools.length===0?recoveredStream:wrapStreamWithInvokeRecovery(recoveredStream,tools,hasKimiTextToolCallRecovery(model)?{createParser:createXtmlRecoveryStreamParser,protocol:"kimi-xtml"}:void 0)}function cloneTextContent(content){return{type:"text",text:content.text,...content.textSignature===void 0?{}:{textSignature:content.textSignature}}}function cloneThinkingContent(content){return{type:"thinking",thinking:content.thinking,...content.thinkingSignature===void 0?{}:{thinkingSignature:content.thinkingSignature},...content.redacted===void 0?{}:{redacted:content.redacted}}}function cloneToolCall2(toolCall){return{type:"toolCall",id:toolCall.id,name:toolCall.name,arguments:structuredClone(toolCall.arguments),...toolCall.thoughtSignature===void 0?{}:{thoughtSignature:toolCall.thoughtSignature},...toolCall.namespace===void 0?{}:{namespace:toolCall.namespace}}}function cloneStartMessage(message){return{role:"assistant",content:[],api:message.api,provider:message.provider,model:message.model,...message.responseModel===void 0?{}:{responseModel:message.responseModel},...message.responseId===void 0?{}:{responseId:message.responseId},...message.providerThinkingLevel===void 0?{}:{providerThinkingLevel:message.providerThinkingLevel},...message.diagnostics===void 0?{}:{diagnostics:structuredClone(message.diagnostics)},usage:structuredClone(message.usage),stopReason:"pending",timestamp:message.timestamp}}function assertContentIndex(contentIndex){if(!Number.isSafeInteger(contentIndex)||contentIndex<0)throw new Error(`Invalid assistant message frame contentIndex: ${contentIndex}`)}function eventBlock(event){assertContentIndex(event.contentIndex);let block=event.partial.content[event.contentIndex];if(!block)throw new Error(`${event.type} event has no content block at index ${event.contentIndex}`);return block}function serializedArguments(argumentsValue){let serialized=JSON.stringify(argumentsValue);if(serialized===void 0)throw new Error("Tool-call arguments are not JSON-serializable");return serialized}var EMPTY_PARSED_TOOL_ARGUMENTS=serializedArguments(parseStreamingJson(""));function isJsonPrefix(snapshot,current){if(typeof snapshot=="string")return typeof current=="string"&¤t.startsWith(snapshot);if(Array.isArray(snapshot))return Array.isArray(current)&&snapshot.length<=current.length&&snapshot.every((value,index)=>isJsonPrefix(value,current[index]));if(typeof snapshot!="object"||snapshot===null)return Object.is(snapshot,current);if(typeof current!="object"||current===null||Array.isArray(current))return!1;let currentRecord=current;return Object.entries(snapshot).every(([key,value])=>Object.hasOwn(currentRecord,key)&&isJsonPrefix(value,currentRecord[key]))}var AssistantMessageFrameEncoder=class{constructor(){this.started=!1,this.terminal=!1,this.blocks=new Map}encode(event){if(this.terminal)throw new Error(`Assistant message event ${event.type} follows a terminal event`);switch(event.type){case"start":if(this.started)throw new Error("Assistant message stream contains more than one start event");return this.started=!0,{type:"start",partial:cloneStartMessage(event.partial)};case"done":if(!this.started)throw new Error("Assistant message done event appears before start");this.terminal=!0;return;case"error":this.terminal=!0;return}if(!this.started)throw new Error(`Assistant message ${event.type} event appears before start`);switch(event.type){case"text_start":{let content=eventBlock(event);if(content.type!=="text")throw new Error(`text_start event points to ${content.type} block at index ${event.contentIndex}`);return this.startBlock(event.contentIndex,{kind:"text",coveredChars:content.text.length,deltaChars:0}),{type:"text_start",contentIndex:event.contentIndex,content:cloneTextContent(content)}}case"text_delta":return this.encodeTextDelta(event.contentIndex,event.delta,"text");case"text_end":{let content=eventBlock(event);if(content.type!=="text")throw new Error(`text_end event points to ${content.type} block at index ${event.contentIndex}`);return this.endBlock(event.contentIndex,"text"),{type:"text_end",contentIndex:event.contentIndex,content:event.content,...content.textSignature===void 0?{}:{textSignature:content.textSignature}}}case"thinking_start":{let content=eventBlock(event);if(content.type!=="thinking")throw new Error(`thinking_start event points to ${content.type} block at index ${event.contentIndex}`);return this.startBlock(event.contentIndex,{kind:"thinking",coveredChars:content.thinking.length,deltaChars:0}),{type:"thinking_start",contentIndex:event.contentIndex,content:cloneThinkingContent(content)}}case"thinking_delta":return this.encodeTextDelta(event.contentIndex,event.delta,"thinking");case"thinking_end":{let content=eventBlock(event);if(content.type!=="thinking")throw new Error(`thinking_end event points to ${content.type} block at index ${event.contentIndex}`);return this.endBlock(event.contentIndex,"thinking"),{type:"thinking_end",contentIndex:event.contentIndex,content:event.content,...content.thinkingSignature===void 0?{}:{thinkingSignature:content.thinkingSignature},...content.redacted===void 0?{}:{redacted:content.redacted}}}case"toolcall_start":{let content=eventBlock(event);if(content.type!=="toolCall")throw new Error(`toolcall_start event points to ${content.type} block at index ${event.contentIndex}`);let snapshotArguments=serializedArguments(content.arguments),caughtUp=snapshotArguments===EMPTY_PARSED_TOOL_ARGUMENTS;return this.startBlock(event.contentIndex,{kind:"toolCall",caughtUp,catchupJson:"",snapshotArguments:caughtUp?"":snapshotArguments}),{type:"toolcall_start",contentIndex:event.contentIndex,toolCall:cloneToolCall2(content)}}case"toolcall_delta":{let state=this.block(event.contentIndex,"toolCall");if(state.kind!=="toolCall")throw new Error("Unreachable tool-call encoder state");if(state.caughtUp)return event.delta.length===0?void 0:{type:"toolcall_delta",contentIndex:event.contentIndex,delta:event.delta};state.catchupJson+=event.delta;let argumentsValue=parseStreamingJson(state.catchupJson);if(serializedArguments(argumentsValue)!==state.snapshotArguments){let snapshotArguments=parseStreamingJson(state.snapshotArguments);if(!isJsonPrefix(snapshotArguments,argumentsValue))return}state.caughtUp=!0,state.snapshotArguments="";let json=state.catchupJson;return state.catchupJson="",json.length===0?void 0:{type:"toolcall_checkpoint",contentIndex:event.contentIndex,json}}case"toolcall_end":{let content=eventBlock(event);if(content.type!=="toolCall")throw new Error(`toolcall_end event points to ${content.type} block at index ${event.contentIndex}`);if(event.toolCall.type!=="toolCall")throw new Error(`toolcall_end event has invalid tool call at index ${event.contentIndex}`);return this.endBlock(event.contentIndex,"toolCall"),{type:"toolcall_end",contentIndex:event.contentIndex,id:event.toolCall.id,name:event.toolCall.name,arguments:structuredClone(event.toolCall.arguments),...event.toolCall.thoughtSignature===void 0?{}:{thoughtSignature:event.toolCall.thoughtSignature},...event.toolCall.namespace===void 0?{}:{namespace:event.toolCall.namespace}}}}}startBlock(contentIndex,state){if(assertContentIndex(contentIndex),this.blocks.has(contentIndex))throw new Error(`Assistant message block ${contentIndex} starts more than once`);this.blocks.set(contentIndex,state)}block(contentIndex,kind){assertContentIndex(contentIndex);let state=this.blocks.get(contentIndex);if(state===void 0)throw new Error(`Assistant message ${kind} block ${contentIndex} has not started`);if(state.kind!==kind)throw new Error(`Assistant message block ${contentIndex} is ${state.kind}, not ${kind}`);return state}endBlock(contentIndex,kind){this.block(contentIndex,kind),this.blocks.delete(contentIndex)}encodeTextDelta(contentIndex,delta,kind){let state=this.block(contentIndex,kind);if(state.kind==="toolCall")throw new Error("Unreachable text encoder state");let deltaStart=state.deltaChars;state.deltaChars+=delta.length;let covered=Math.max(0,state.coveredChars-deltaStart);if(covered>=delta.length)return;let uncovered=covered===0?delta:delta.slice(covered);return kind==="text"?{type:"text_delta",contentIndex,delta:uncovered}:{type:"thinking_delta",contentIndex,delta:uncovered}}};function appendBlock(message,states,contentIndex,block,state){if(assertContentIndex(contentIndex),contentIndex!==message.content.length){let reason=contentIndex<message.content.length?"already exists":"would leave a gap";throw new Error(`Cannot start assistant message block at index ${contentIndex}: ${reason}`)}message.content.push(structuredClone(block)),states.set(contentIndex,state)}function activeBlock(message,states,contentIndex,expectedKind,frameType){assertContentIndex(contentIndex);let state=states.get(contentIndex),block=message.content[contentIndex];if(!state||!block)throw new Error(`${frameType} frame has no started block at index ${contentIndex}`);if(state.kind!==expectedKind||block.type!==expectedKind)throw new Error(`${frameType} frame expected ${expectedKind} block at index ${contentIndex}, found ${block.type}`);if(state.ended)throw new Error(`${frameType} frame follows the end of block at index ${contentIndex}`);return{block,state}}function reduceAssistantMessageFrames(frames){let message,frameBeforeStart,states=new Map;for(let frame of frames){if(frame.type==="start"){if(message)throw new Error("Assistant message frame sequence contains more than one start frame");if(frameBeforeStart!==void 0)throw new Error(`${frameBeforeStart} frame appears before the start frame`);message=structuredClone(frame.partial);continue}if(!message){frameBeforeStart??=frame.type;continue}switch(frame.type){case"text_start":if(frame.content.type!=="text")throw new Error(`text_start frame contains ${frame.content.type} content`);appendBlock(message,states,frame.contentIndex,frame.content,{kind:"text",ended:!1});break;case"text_delta":{let{block}=activeBlock(message,states,frame.contentIndex,"text",frame.type);if(block.type!=="text")throw new Error("Unreachable text frame state");block.text+=frame.delta;break}case"text_end":{let{block,state}=activeBlock(message,states,frame.contentIndex,"text",frame.type);if(block.type!=="text")throw new Error("Unreachable text frame state");block.text=frame.content,delete block.textSignature,frame.textSignature!==void 0&&(block.textSignature=frame.textSignature),state.ended=!0;break}case"thinking_start":if(frame.content.type!=="thinking")throw new Error(`thinking_start frame contains ${frame.content.type} content`);appendBlock(message,states,frame.contentIndex,frame.content,{kind:"thinking",ended:!1});break;case"thinking_delta":{let{block}=activeBlock(message,states,frame.contentIndex,"thinking",frame.type);if(block.type!=="thinking")throw new Error("Unreachable thinking frame state");block.thinking+=frame.delta;break}case"thinking_end":{let{block,state}=activeBlock(message,states,frame.contentIndex,"thinking",frame.type);if(block.type!=="thinking")throw new Error("Unreachable thinking frame state");block.thinking=frame.content,delete block.thinkingSignature,delete block.redacted,frame.thinkingSignature!==void 0&&(block.thinkingSignature=frame.thinkingSignature),frame.redacted!==void 0&&(block.redacted=frame.redacted),state.ended=!0;break}case"toolcall_start":if(frame.toolCall.type!=="toolCall")throw new Error(`toolcall_start frame contains ${frame.toolCall.type} content`);appendBlock(message,states,frame.contentIndex,frame.toolCall,{kind:"toolCall",ended:!1,json:""});break;case"toolcall_checkpoint":{let{block,state}=activeBlock(message,states,frame.contentIndex,"toolCall",frame.type);if(block.type!=="toolCall"||state.kind!=="toolCall")throw new Error("Unreachable tool-call checkpoint state");state.json=frame.json,block.arguments=parseStreamingJson(frame.json);break}case"toolcall_delta":{let{block,state}=activeBlock(message,states,frame.contentIndex,"toolCall",frame.type);if(block.type!=="toolCall"||state.kind!=="toolCall")throw new Error("Unreachable tool-call frame state");state.json+=frame.delta;break}case"toolcall_end":{let{block,state}=activeBlock(message,states,frame.contentIndex,"toolCall",frame.type);if(block.type!=="toolCall")throw new Error("Unreachable tool-call frame state");block.id=frame.id,block.name=frame.name,block.arguments=structuredClone(frame.arguments),delete block.thoughtSignature,delete block.namespace,frame.thoughtSignature!==void 0&&(block.thoughtSignature=frame.thoughtSignature),frame.namespace!==void 0&&(block.namespace=frame.namespace),state.ended=!0;break}}}if(message){for(let[contentIndex,state]of states){if(state.kind!=="toolCall"||state.ended||state.json.length===0)continue;let block=message.content[contentIndex];if(block?.type!=="toolCall")throw new Error("Unreachable tool-call frame state");block.arguments=parseStreamingJson(state.json)}return message}}var kCursorExecResolved=Symbol("provider.block.cursorExecResolved");function isCursorExecResolved(block){return block?.[kCursorExecResolved]===!0}function copyCursorExecResolved(target,source){source[kCursorExecResolved]===!0&&(target[kCursorExecResolved]=!0)}function dropFailedAssistantTurns(messages){let callIdsByKeptAssistants=new Set,callIdsByFailedAssistants=new Set;for(let message of messages){let assistant=asAssistantTurn(message);if(!assistant)continue;let declared=isFailedStop(assistant.stopReason)?callIdsByFailedAssistants:callIdsByKeptAssistants;for(let block of assistant.content)block.type==="toolCall"&&typeof block.id=="string"&&declared.add(block.id)}for(let id of callIdsByKeptAssistants)callIdsByFailedAssistants.delete(id);return messages.filter(message=>{let assistant=asAssistantTurn(message);return assistant?!isFailedStop(assistant.stopReason):message.role==="toolResult"&&"toolCallId"in message&&typeof message.toolCallId=="string"?!callIdsByFailedAssistants.has(message.toolCallId):!0})}function asAssistantTurn(message){if(message.role==="assistant"&&!(!("content"in message)||!Array.isArray(message.content)))return{stopReason:"stopReason"in message?message.stopReason:void 0,content:message.content}}function isFailedStop(stopReason){return stopReason==="error"||stopReason==="aborted"}var EMPTY_RESPONSE_ERROR="Model returned an empty response twice",EMPTY_TOOL_USE_ERROR="Model returned tool_use without a tool call twice",FORWARDED_EMPTY_RESPONSE_ERROR="Model returned an empty response after streaming thinking",FORWARDED_EMPTY_TOOL_USE_ERROR="Model returned tool_use without a tool call after streaming thinking";var OVERFLOW_PATTERNS=[/^Context window exhausted: /,/prompt is too long/i,/request_too_large/i,/input is too long for requested model/i,/exceeds (?:(?:the|this) )?(?:model'?s )?context window/i,/exceeds (?:the )?(?:model'?s )?maximum context length(?: of [\d,]+ tokens?|\s*\([\d,]+\))/i,/input token count.*exceeds the maximum/i,/maximum prompt length is \d+/i,/reduce the length of the messages/i,/maximum context length is \d+ tokens/i,/exceeds (?:the )?maximum allowed input length of [\d,]+ tokens?/i,/input \(\d+ tokens\) is longer than the model'?s context length \(\d+ tokens\)/i,/exceeds the limit of \d+/i,/exceeds the available context size/i,/greater than the context length/i,/context window exceeds limit/i,/exceeded model token limit/i,/too large for model with \d+ maximum context length/i,/prompt has [\d,]+ tokens?, but the configured context size is [\d,]+ tokens?/i,/model_context_window_exceeded/i,/prompt too long; exceeded (?:max )?context length/i,/range of input length should be/i,/context[_ ]length[_ ]exceeded/i,/too many tokens/i,/token limit exceeded/i,/^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i,/(?:request[ _])?(?:body|entity|payload)[_ ]too[_ ]large/i,/Request payload is \d+ (?:bytes, over the \d+ byte|tokens, over the \d+ token) limit Kiro accepts\./,/Model context limit reached\. Conversation size exceeds model capacity\./],NON_OVERFLOW_PATTERNS=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i,/tokens per (?:min|minute|hour|day)/i,/\bTPM\b/i,/\bRPM\b/i,/quota exceeded/i,/retry (?:after|in) \d/i,/^429\b/,/status code 429/i,/overloaded/i],RESOURCE_EXHAUSTED_PATTERN=/resource.?exhausted/i;function isContextOverflow(message,contextWindow){if(message.stopReason==="error"&&message.errorMessage){let isNonOverflow=NON_OVERFLOW_PATTERNS.some(p=>p.test(message.errorMessage));if(!isNonOverflow&&OVERFLOW_PATTERNS.some(p=>p.test(message.errorMessage)))return!0;let usage=message.usage,hasTokenEvidence=(usage.totalTokens||usage.input+usage.output+usage.cacheRead+usage.cacheWrite)>0;if(!isNonOverflow&&hasTokenEvidence&&RESOURCE_EXHAUSTED_PATTERN.test(message.errorMessage)&&(contextWindow===void 0||contextWindow<=0||cursorZeroTokenCount(message)>=contextWindow*.5))return!0}return!!(contextWindow&&message.stopReason==="stop"&&message.usage.input+message.usage.cacheRead>contextWindow||contextWindow&&message.stopReason==="length"&&message.usage.output===0&&message.usage.input+message.usage.cacheRead>=contextWindow*.99)}function isRecoverableLength(message,desiredMaxOutput){return message.stopReason==="length"&&desiredMaxOutput>0&&message.usage.output<desiredMaxOutput}function getOverflowPatterns(){return[...OVERFLOW_PATTERNS]}function cursorZeroTokenCount(message){let usage=message.usage;return usage?usage.totalTokens||(usage.input??0)+(usage.output??0)+(usage.cacheRead??0)+(usage.cacheWrite??0):0}function isCursorPayloadResourceExhausted(message,_estimateTokens){return message.stopReason!=="error"||!/resource.?exhausted/i.test(message.errorMessage||"")?!1:!(cursorZeroTokenCount(message)>0)}function isCursorQuotaResourceExhausted(message,contextWindow){let tokens=cursorZeroTokenCount(message);return message.stopReason==="error"&&RESOURCE_EXHAUSTED_PATTERN.test(message.errorMessage||"")&&contextWindow>0&&tokens>0&&tokens<contextWindow*.5}function isCursorZeroTokenResourceExhausted(message){return message.stopReason!=="error"||!/resource.?exhausted/i.test(message.errorMessage||"")?!1:!(cursorZeroTokenCount(message)>0)}function shouldSkipProviderFallbackForCursorZeroRe(options){return options?.sameModelRemint===!0}function shouldRetryOverflowWithoutCompact(compacted,errorMessage){return compacted?!1:/Nothing to compact/i.test(errorMessage||"")}function cursorOverflowCompactionSettings(settings,provider,reason){return reason!=="overflow"||provider!=="cursor"&&provider!=="cursor-cli-oauth"?settings:{...settings,keepRecentTokens:0,restorationEnabled:!1}}function buildProviderErrorPattern(patterns){return new RegExp(patterns.join("|"),"i")}function escapeRegExp5(text){return text.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var USAGE_LIMIT_EXHAUSTION={codes:["usage_limit_reached","usage_not_included"],markers:["usage_limit_reached","usage_not_included","usage limit has been reached"]},QUOTA_EXHAUSTION_PATTERNS=["GoUsageLimitError","FreeUsageLimitError","Monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing","credits_required","credits are required",...USAGE_LIMIT_EXHAUSTION.markers],QUOTA_EXHAUSTION_PATTERN=buildProviderErrorPattern(QUOTA_EXHAUSTION_PATTERNS);function isQuotaExhaustionMessage(errorMessage){return errorMessage!==void 0&"A_EXHAUSTION_PATTERN.test(errorMessage)}var NON_RETRYABLE_PROVIDER_ERROR_PATTERN=buildProviderErrorPattern([...QUOTA_EXHAUSTION_PATTERNS,"invalid request: tools\\.","invalid request: functions\\.","tools\\.[^ ]*function\\.parameters","tools\\.\\d+\\.function\\.parameters","invalid tool schema"]),RETRYABLE_PROVIDER_ERROR_PATTERN=buildProviderErrorPattern(["Credential store is busy: lock","overloaded","rate.?limit","too many requests","429","500","502","503","504","522","524","service.?unavailable","server.?error","internal.?error","provider.?returned.?error","exceeded request buffer limit while retrying upstream","network.?error","connection.?error","connection.?refused","connection.?lost","other side closed","fetch failed","getaddrinfo","ENOTFOUND","EAI_AGAIN","upstream.?connect","upstream.?unavailable","reset before headers","socket hang up","socket connection was closed","timed? out","timeout","terminated","websocket.?closed","websocket.?error","ended without","stream ended before message_stop","stream ended before a terminal response event","http2 request did not get a response","retry delay","you can retry your request","try your request again","please retry your request","the model request was rejected\\.\\s*check the request and try again\\.?","was found without a corresponding `","must not contain streaming index",escapeRegExp5(FORWARDED_EMPTY_RESPONSE_ERROR),escapeRegExp5(FORWARDED_EMPTY_TOOL_USE_ERROR),"ResourceExhausted","Lock file is already being held"]),DEFAULT_MAX_AGENT_RETRY_DELAY_MS=6e4;function retryDelayMs(policy,attempt){let scheduledDelayMs=policy.baseDelayMs*2**Math.max(0,attempt-1),sample=Math.min(1,Math.max(0,(policy.random??Math.random)())),jitteredDelayMs=Math.round(scheduledDelayMs*(.9+sample*.2)),safeDelay=Number.isSafeInteger(jitteredDelayMs)?jitteredDelayMs:Number.MAX_SAFE_INTEGER;return Math.min(safeDelay,policy.maxAgentDelayMs??DEFAULT_MAX_AGENT_RETRY_DELAY_MS)}var RetrySleepAbortError=class extends Error{constructor(){super("Aborted")}};function sleep(ms,signal){return new Promise((resolve,reject)=>{if(signal?.aborted){reject(new RetrySleepAbortError);return}let timeout=setTimeout(resolve,ms);signal?.addEventListener("abort",()=>{clearTimeout(timeout),reject(new RetrySleepAbortError)},{once:!0})})}async function retryTransientCall(produce,isRetryable,policy,signal,callbacks){let maxAttempts=policy?.enabled?policy.maxRetries:0,attempt=0,lastRetry;for(;;)try{let value=await produce();return lastRetry&&await callbacks?.onRetryFinished?.(!0,lastRetry.attempt),value}catch(error){if(error instanceof RetrySleepAbortError)throw error;if(attempt>=maxAttempts||!isRetryable(error))throw lastRetry&&await callbacks?.onRetryFinished?.(!1,lastRetry.attempt,errorMessageOf(error)),error;attempt++,lastRetry={attempt,errorMessage:errorMessageOf(error)};let delayMs=retryDelayMs(policy,attempt);await callbacks?.onRetryScheduled?.(attempt,maxAttempts,delayMs,lastRetry.errorMessage);try{await sleep(delayMs,signal)}catch(sleepError){throw await callbacks?.onRetryFinished?.(!1,attempt,lastRetry.errorMessage),sleepError instanceof RetrySleepAbortError?error:sleepError}await callbacks?.onRetryAttemptStart?.()}}function errorMessageOf(error){return error instanceof Error?error.message||"Unknown error":String(error)||"Unknown error"}async function retryAssistantCall(produce,policy,signal,callbacks){let maxAttempts=policy?.enabled?policy.maxRetries:0,attempt=0,lastRetry;for(;;){let response=await produce();if(response.stopReason==="aborted")return lastRetry&&await callbacks?.onRetryFinished?.(!1,lastRetry.attempt),response;if(response.stopReason!=="error")return lastRetry&&await callbacks?.onRetryFinished?.(!0,lastRetry.attempt),response;if(attempt>=maxAttempts||!isRetryableAssistantError(response))return lastRetry&&await callbacks?.onRetryFinished?.(!1,lastRetry.attempt,response.errorMessage),response;attempt++,lastRetry={attempt,errorMessage:response.errorMessage||"Unknown error"};let delayMs=retryDelayMs(policy,attempt);await callbacks?.onRetryScheduled?.(attempt,maxAttempts,delayMs,lastRetry.errorMessage);try{await sleep(delayMs,signal)}catch(error){if(await callbacks?.onRetryFinished?.(!1,attempt,lastRetry.errorMessage),error instanceof RetrySleepAbortError){let{errorMessage:_errorMessage,...rest}=response;return{...rest,stopReason:"aborted"}}throw error}await callbacks?.onRetryAttemptStart?.()}}function isRetryableAssistantError(message){return message.stopReason!=="error"||message.stopDetails?.type==="refusal"||message.stopDetails?.type==="sensitive"||!message.errorMessage?!1:isRetryableErrorMessage(message.errorMessage)}var PROVIDER_STREAM_STALL_ERROR_PATTERN=/^(?: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,PROVIDER_TRANSPORT_TIMEOUT_ERROR_PATTERN=/^Request timed out\.?$/i;function isProviderStreamStallError(message){return message.stopReason==="error"&&PROVIDER_STREAM_STALL_ERROR_PATTERN.test(message.errorMessage??"")}var PROVIDER_STALL_PHASES=[{pattern:/^Provider stream start timed out after (\d+)ms/i,symptom:"accepted the request but never started sending a response",setting:"retry.provider.streamStartTimeoutMs"},{pattern:/^Idle timeout waiting for provider stream after (\d+)ms/i,symptom:"started the response and then went silent",setting:"retry.provider.timeoutMs"},{pattern:/^WebSocket liveness timeout after (\d+)ms/i,symptom:"stopped answering connection health checks"},{pattern:/^Provider stream stalled after the last output item: response\.completed timed out after (\d+)ms/i,symptom:"finished its output but never sent the end-of-response event"}];function formatStallDuration(timeoutMs){return timeoutMs<1e3?`${timeoutMs}ms`:timeoutMs<12e4?`${Math.round(timeoutMs/100)/10}s`:`${Math.round(timeoutMs/6e3)/10}m`}function describeProviderStallForUser(errorMessage,options={}){if(errorMessage)for(let{pattern,symptom,setting}of PROVIDER_STALL_PHASES){let match=pattern.exec(errorMessage);if(!match)continue;let subject=options.model?`The provider for ${options.model}`:"The provider",duration=formatStallDuration(Number(match[1])),sentences=[`${subject} ${symptom} within ${duration}, so the request was cancelled.`],attempts=options.attempts??0;if(attempts>0&&sentences.push(`Retried ${attempts} time${attempts===1?"":"s"} on the same model with the same result.`),options.recovery){let raise=setting?`, or raise ${setting} in settings (0 disables the bound)`:"",lead=options.recovery==="no-fallback-configured"?"No fallback model is configured for it, so nothing could take the turn over: run /fallback to add one":"Every model in its fallback chain was tried as well: run /fallback to review the chain";sentences.push(`${lead}, send the message again${raise}.`)}return sentences.join(" ")}}function isProviderTimeoutError(message){return message.abortSource==="provider"||isProviderStreamStallError(message)?!0:message.stopReason!=="error"&&message.stopReason!=="aborted"?!1:PROVIDER_TRANSPORT_TIMEOUT_ERROR_PATTERN.test(message.errorMessage??"")}function isRetryableErrorMessage(errorMessage){return classifyErrorMessage(errorMessage)==="retryable"}function classifyErrorMessage(errorMessage){return errorMessage?NON_RETRYABLE_PROVIDER_ERROR_PATTERN.test(errorMessage)?"non-retryable":RETRYABLE_PROVIDER_ERROR_PATTERN.test(errorMessage)?"retryable":"unknown":"unknown"}var TURN_RETRY_SUPPRESSION_PREFIX="senpi:no-turn-retry:";function stripTurnRetrySuppressionPrefix(message){return message.replaceAll(TURN_RETRY_SUPPRESSION_PREFIX,"")}var WEBSOCKET_CLOSED_PATTERN=/^WebSocket closed\b/i,WEBSOCKET_ERROR_PATTERN=/^WebSocket error$/i,WEBSOCKET_CONNECT_TIMEOUT_PATTERN=/^WebSocket connect timeout after (\d+)ms/i,RECOVERY_SENTENCE={"no-fallback-configured":"No fallback model is configured for it, so nothing could take the turn over: run /fallback to add one, or send the message again to continue from the partial reply.","chain-exhausted":"Every model in its fallback chain was tried as well: run /fallback to review the chain, or send the message again to continue from the partial reply."};function transportSymptom(errorMessage,subject){if(WEBSOCKET_CLOSED_PATTERN.test(errorMessage))return`The connection to ${subject} dropped before the reply finished (${errorMessage}).`;if(WEBSOCKET_ERROR_PATTERN.test(errorMessage))return`The connection to ${subject} reported an error before the reply finished (${errorMessage}).`;let connectTimeout=WEBSOCKET_CONNECT_TIMEOUT_PATTERN.exec(errorMessage);if(connectTimeout)return`${subject.replace(/^the provider/,"The provider")} did not accept the connection within ${formatStallDuration(Number(connectTimeout[1]))}.`}function describeProviderFailureForUser(errorMessage,options={}){if(!errorMessage)return;let message=stripTurnRetrySuppressionPrefix(errorMessage).trim();if(!message)return;let stall=describeProviderStallForUser(message,options);if(stall!==void 0)return stall;let subject=options.model?`the provider for ${options.model}`:"the provider",symptom=transportSymptom(message,subject);if(symptom===void 0)return;let sentences=[symptom],attempts=options.attempts??0;return attempts>0&&sentences.push(`Retried ${attempts} time${attempts===1?"":"s"} on the same model with the same result.`),options.recovery&&sentences.push(RECOVERY_SENTENCE[options.recovery]),sentences.join(" ")}var ANTHROPIC_POLICY_REFUSAL_PATTERN=/This request triggered restrictions on [\s\S]+? and was blocked under Anthropic's Usage Policy\b/i;function isClassifierRefusal(message){return message.stopReason!=="error"&&message.stopReason!=="toolUse"?!1:message.stopDetails?.type==="refusal"||message.stopDetails?.type==="sensitive"?!0:message.errorMessage?ANTHROPIC_POLICY_REFUSAL_PATTERN.test(message.errorMessage):!1}var TOOL_RESULT_PLACEHOLDER="Tool output unavailable (context compacted)";function incompleteToolCallRetryText(name,errorMessage){return errorMessage!==void 0?`${errorMessage}${errorMessage.endsWith(".")?"":"."} Re-issue the tool call with complete arguments.`:`Tool call "${name}" was not executed: the response ended before the tool call was complete. Re-issue the tool call with complete arguments.`}function repairOrphanedToolResults(messages){let toolCallIds=new Set,toolResultIds=new Set;for(let message of messages){if(message.role==="assistant")for(let block of message.content)block.type==="toolCall"&&toolCallIds.add(block.id);message.role==="toolResult"&&toolResultIds.add(message.toolCallId)}let output=[],dangling=new Set([...toolCallIds].filter(id=>!toolResultIds.has(id)));for(let message of messages){if(message.role==="toolResult"){if(!toolCallIds.has(message.toolCallId)){output.push({...message,content:[{type:"text",text:TOOL_RESULT_PLACEHOLDER}]});continue}output.push(message);continue}if(output.push(message),message.role==="assistant"){if(message.stopReason==="error"||message.stopReason==="aborted")continue;for(let block of message.content){if(block.type!=="toolCall"||!dangling.has(block.id))continue;let incomplete=block.incomplete===!0,text=incomplete?incompleteToolCallRetryText(block.name,block.errorMessage):TOOL_RESULT_PLACEHOLDER;output.push({role:"toolResult",toolCallId:block.id,toolName:block.name,content:[{type:"text",text}],isError:incomplete,timestamp:message.timestamp?message.timestamp+1:Date.now()}),dangling.delete(block.id)}}}return output}function StringEnum(values,options){return typebox_exports.Unsafe({type:"string",enum:values,...options?.description&&{description:options.description},...options?.default&&{default:options.default}})}var INVISIBLE_FORMAT_CHARS=new RegExp("\\p{Cf}","gu");function hasVisibleText(text){return text.replace(INVISIBLE_FORMAT_CHARS,"").trim().length>0}function hasVisibleAssistantContent(message){return message.content.some(block=>block.type==="toolCall"||block.type==="text"&&hasVisibleText(block.text))}export{create,messageDesc,fromBinary,fileDesc,toBinary,measureCursorModelInputSerializedBytes,measureCursorHistorySerializedBytes,piReadArgs,piLsPath,piLimit,piTimeout,composeShellCommand,omitUndefinedArgs,registerPromptCacheWarmer,warmPromptCache,fauxText,fauxThinking,fauxToolCall,fauxAssistantMessage,createFauxCore,getRegisteredFauxProvider,fauxOverflowError,fauxProvider,installProviderScopeAccessor,registerApiProvider,registerBuiltinApiProvider,getApiProvider,getApiProviders,unregisterApiProviders,clearApiProviders,envApiKeyAuth,lazyOAuth,CURSOR_MODEL_CAPABILITIES,parseCursorVariantId,getCursorVariantAlias,getCursorBaseIdForVariant,getCursorCapabilityForBase,deriveCursorVariantAliases,normalizeCursorCatalog,resolveCursorSelectionDescriptor,renderCursorCliModelString,parseEndpointReasoningEfforts,ANTHROPIC_AUTH_TOKEN_ENV,ANTHROPIC_OAUTH_TOKEN_ENV,ANTHROPIC_API_KEY_ENV,getApiKeyEnvVars,findEnvKeys,getEnvApiKey,createImagesModels,createImagesProvider,supportsAllowedToolChoice,createXtmlRecoveryStreamParser,wrapStreamWithInvokeRecovery,Compile,compile_exports,validateToolCall,validateToolArguments,require_dist,getProtocol,transformContext,wrapStreamWithToolCallMiddleware,getToolCallFormat,shouldRecoverTextToolCalls,hasKimiTextToolCallRecovery,wrapStreamWithModelRecovery,AssistantMessageFrameEncoder,reduceAssistantMessageFrames,kCursorExecResolved,isCursorExecResolved,copyCursorExecResolved,dropFailedAssistantTurns,EMPTY_RESPONSE_ERROR,EMPTY_TOOL_USE_ERROR,FORWARDED_EMPTY_RESPONSE_ERROR,FORWARDED_EMPTY_TOOL_USE_ERROR,isContextOverflow,isRecoverableLength,getOverflowPatterns,isCursorPayloadResourceExhausted,isCursorQuotaResourceExhausted,isCursorZeroTokenResourceExhausted,shouldSkipProviderFallbackForCursorZeroRe,shouldRetryOverflowWithoutCompact,cursorOverflowCompactionSettings,USAGE_LIMIT_EXHAUSTION,isQuotaExhaustionMessage,DEFAULT_MAX_AGENT_RETRY_DELAY_MS,retryDelayMs,retryTransientCall,retryAssistantCall,isRetryableAssistantError,isProviderStreamStallError,formatStallDuration,describeProviderStallForUser,isProviderTimeoutError,isRetryableErrorMessage,classifyErrorMessage,TURN_RETRY_SUPPRESSION_PREFIX,stripTurnRetrySuppressionPrefix,describeProviderFailureForUser,isClassifierRefusal,contentText,TOOL_RESULT_PLACEHOLDER,repairOrphanedToolResults,StringEnum,hasVisibleText,hasVisibleAssistantContent};
|