pi-plus 0.1.10 → 0.1.12

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 CHANGED
@@ -4,6 +4,39 @@
4
4
 
5
5
  ### Added
6
6
 
7
- - Compiled `pi-plus` CLI artifact: `build.mjs` bundles `pp` (pi + the plus override layer) into `dist/npm/`, a self-contained staging tree for `npm link` / `npm publish`. Exposes a single `pi-plus` bin — never `pi`, and not `pp` (collides with Homebrew nss's `pp` on macOS).
7
+ - A `<tasks>` system-prompt section (registered by the `pi-plus-tasks` extension on every agent start) nudging the model to break non-trivial multi-step work into TaskCreate tasks and update statuses as it goes, and listing the session's current tasks (with status and blockers) when non-empty so resumed sessions can pick up where they left off.
8
+ - A `<subagents>` system-prompt section (registered by the `pi-plus-subagent` extension on every agent start) nudging the model to delegate self-contained work units via the `subagent` tool — including complete, self-contained prompts and concurrent calls in one turn — and listing the agent types available in this session (built-in `worker`/`explore` plus user- and project-defined agents) with their source, tools, and model.
9
+ - `PI_AUTOCOMPACT_FAILURE_COOLDOWN_MS` env override (minimum 10s, values below the floor fall back to the 5-minute default) for the auto-compact circuit breaker: after 3 consecutive failures the breaker now cools down instead of latching forever — one attempt is allowed through once the cooldown elapses (half-open), and a failed attempt re-trips it.
10
+ - Layered context defense (pi-plus-context-guard extension + AgentSession constructor hook, ported from openclaude): a message-count force trigger compacts when the active message count exceeds `PI_MAX_ACTIVE_MESSAGES` (default 1000) regardless of the token threshold; relevance pruning omits low-relevance old text entries via durable `context_edit` overlays once the projected request reaches the auto-compact threshold, protecting the recent `PI_PRUNE_TAIL_TURNS` (default 3) turns, tool interactions, errors, and prior compaction summaries; time-based micro-compact clears the content of stale tool results (`PI_MICROCOMPACT_IDLE_MINUTES`, default 60; keeps the newest `PI_MICROCOMPACT_KEEP_RECENT`, default 5) when a session is opened after an idle gap, since the server prompt cache is dead anyway; and resuming a session already at ≥ 70% of the auto-compact threshold offers a "Compact now?" confirmation in the TUI.
11
+ - Post-compact re-injection of the active plan file and invoked skills into the compaction summary (openclaude's `createPlanAttachmentIfNeeded` / `createSkillAttachmentIfNeeded`), alongside the existing recent-files re-injection.
12
+ - Recompaction analytics (openclaude's `RecompactionInfo`) persisted in the compaction entry's `details`: whether the compaction continues a chain, turns consumed since the previous compaction, the previous pre-compact token count, and a `willRetriggerNextTurn` prediction; set `PI_COMPACT_ANALYTICS` for a stderr diagnostic line.
13
+ - `/settings` gains an "Auto-compact threshold" row (70%/80%/85%/90%/95%, default 80%), injected into the settings selector by the plus wrapper. The choice persists to `~/.pi/agent/pi-plus-settings.json` and applies as a percent of the effective context window, replacing the CC buffer math as the user-facing default — unlike `PI_AUTOCOMPACT_PCT_OVERRIDE`, which stays a session-scoped test knob capped at the CC buffer.
14
+ - `/settings` gains a "Context floor" row (13000–65536 tokens, default 13000) for the floor under the effective context window: the window used for auto-compact math never drops below the output reserve plus this many tokens, even for small-context models. The choice persists to `~/.pi/agent/pi-plus-settings.json` and can only raise the built-in 13k floor (the issue-#635 guarantee stays intact); `PI_CONTEXT_FLOOR_TOKENS` overrides it for the session.
15
+
16
+ ### Changed
17
+
18
+ - The window used for threshold math is now ceilinged at 256K tokens (`AUTOCOMPACT_MAX_WINDOW_TOKENS`) before the output reservation: models advertising windows far beyond practical agentic session sizes (e.g. the 1M-token DeepSeek V4.1 Flash) previously got an ~800K auto-compact threshold that effectively never fired, letting the transcript grow unbounded. A 1M model now triggers at ~194K (80% of the 242K effective window). `PI_AUTO_COMPACT_WINDOW` keeps its cap semantics and can only lower this further. The footer's context fullness percentage uses the same effective window as its denominator when the ceiling engages, so the meter reads "percent of the usable window" (e.g. `14.4%/242K`) instead of crawling against the unreachable 1M capacity; models at or below the ceiling are unchanged.
19
+
20
+ - The CC buffer math (ramped 13k–30k by effective window size, openclaude issue #1949; floored effective window for small-context models, issue #635) no longer sets the auto-compact threshold directly — it survives only as the cap for the `PI_AUTOCOMPACT_PCT_OVERRIDE` test knob. The user-facing threshold is now a percent of the effective window chosen in `/settings` (default 80%). `percentLeft` is computed against the raw context window so the displayed percentage reflects full model capacity.
21
+
22
+ ### Fixed
23
+
24
+ - `pipi remove`/`pipi install` under a profile now update the source `~/.pi/agent/settings.json` `packages` list, not just the per-profile copy that the next materialization would discard. The wrapper registers a process-exit sync (`syncProfilePackagesToSource` from pi-hub) for profile launches, so the removed extension is not reinstalled on next launch.
25
+ - Context usage detection now sees the whole request, not just conversation messages: heuristic estimates (footer percentage before the first response and after `/compact`, zero-usage/error fallback, mid-session prompt/tool changes) include the folded system prompt and tool declarations, the usage anchor is invalidated when a newer-timestamp message is inserted into the prefix, Anthropic 1h cache writes (`cacheWrite1h`) are counted, and the footer shows a real estimate instead of `?` right after compaction. Wired via `estimateContextTokens`/`calculateContextTokens` shadows in the compaction wrapper plus a 9th module redirect for `coding-agent/src/core/agent-session.ts` (`getContextUsage` override).
26
+
27
+ ### Added
28
+
29
+ - Plan mode (openclaude/Claude Code style) via the `EnterPlanMode` / `ExitPlanMode` tools, a `/plan` command (`/plan`, `/plan show`, `/plan edit`), a `ctrl+alt+p` toggle, and a `--plan` launch flag. While active the model is read-only: `edit`/`write` are restricted to the session plan file (`<agent dir>/plans/<sessionId>.md`, the only writable target), `bash` is restricted to a read-only command allowlist, `powershell` and non-allowlisted custom tools (including the `subagent` tool unless the read-only `explore` agent type) are blocked via the `tool_call` event, and a `<plan_mode>` system-prompt section drives a research-then-plan workflow. `EnterPlanMode` asks the user to confirm; `ExitPlanMode` presents the plan with Approve / Stay / Edit options and, on approval, returns the approved plan with full tool access restored. The footer shows a `⏸ plan` indicator; state is per-session in memory (reset on new/resume/fork).
30
+ - `subagent` tool — delegate a task to a specialized sub-agent running in an isolated `pi -p --no-session` subprocess with its own context window (ported from the coding-agent subagent example, single mode only). Agent types are markdown files with frontmatter (`name`, `description`, `tools`, `model`) in `<agent dir>/agents/` (user) or the nearest `.pi/agents/` walking up from the project dir (project); two built-in types always exist: `worker` (full toolset) and `explore` (read-only). Sub-agents cannot spawn further sub-agents unless their definition lists the `subagent` tool; project-local agent definitions require a one-time trust confirmation in the TUI. The tool runs with `executionMode: "parallel"` (issue multiple calls in one turn for concurrency), inherits the session model/thinking by default (`model` param overrides), propagates aborts to the child process, reports child token usage/cost on the result, and truncates oversized final output.
31
+ - Task tools — `TaskCreate` / `TaskUpdate` / `TaskList` / `TaskGet` (openclaude V2 style), file-backed under `<agent dir>/tasks/<sessionId>/` with a monotonic `.highwatermark` id allocator, per-task `owner` and `blocks`/`blockedBy` dependencies, and atomic tmp+rename writes. A `/tasks` command and the `ctrl+shift+t` shortcut open a task-list overlay in the TUI.
32
+ - π+ welcome banner now shows the boxed banner on every launch (the first-run-per-project gate and its `pi-plus-banner.json` state are gone); the condensed tier remains the fallback only where the box cannot fit.
33
+ - `pipi completion <bash|zsh>` prints a shell completion script owned by pi-plus, covering the whole CLI: hub subcommands (dynamic profile names and per-profile models, providers, thinking levels) plus pi's native commands and flags. Moved here from the hub package, which no longer ships completion.
34
+ - `pipi --help` now ends with a "Profile commands (pi-plus)" section documenting `profile`, `use`/`unuse`, `completion`, and `--as` (via a `cli/args.ts` printHelp wrapper; 8th module redirect).
35
+ - Compiled `pi-plus` CLI artifact: `build.mjs` bundles `pipi` (pi + the plus override layer) into `dist/npm/`, a self-contained staging tree for `npm link` / `npm publish`. Exposes a single `pipi` bin — never `pi`. The CLI (command, help text, hub usage strings) is named `pipi`; the npm package stays `pi-plus`.
8
36
  - The plus config wrapper now resolves package assets (themes, HTML export template, interactive assets) from the staged bundle layout.
9
37
  - The version check against pi's release train (pi.dev) is skipped.
38
+ - Vim modal editing for the prompt input (core subset ported from [pi-vimmode](https://github.com/pekochan069/pi-vimmode), MIT, (c) 2026 pekochan069), registered as a hidden built-in extension. Modes: insert/normal/visual (`v`)/visual-line (`V`). Motions: `h j k l w b e 0 $ ^ f F t T` with counts. Operators/edits: `x s r J p P`, operator+motion `d/c/y`, linewise `dd cc yy`, insert entries `i a I A o O C`, `u`/Ctrl-r undo/redo, prompt search `/ ? n N`. Enabled with `"vim": true` in settings (project `.pi/settings.json` > agent dir > `~/.pi/settings.json`) or toggled with `/vim`, which persists the new state to the agent dir `settings.json` so it sticks across launches. Excluded: ex commands, macros, marks, named registers, easymotion, visual-block, JS config, cursor-shape escapes.
39
+
40
+ ### Removed
41
+
42
+ - The deprecated `pipi run` command. `pipi --as <name>` (one-off launch under a profile) and plain `pipi` (default profile, if set) replace it; hub dispatch is now management-only (`profile`, `use`, `unuse`).
package/README.md CHANGED
@@ -6,30 +6,59 @@ All override/custom logic lives here. Direct updates to any other folder under `
6
6
 
7
7
  Ports Claude Code semantics (reference: `../free-code/`, CC v2.1.87) onto pi's context detection, compaction, and reasoning — with pi-style env var names:
8
8
 
9
- 1. **Context usage detection** (`src/context/detection.ts`) — effective context window = `contextWindow − min(maxTokens, 20000)`; auto-compact threshold = effective window − 13k; warning/error = threshold ∓ 20k; blocking limit = effective window − 3k; 3-failure circuit breaker.
9
+ 1. **Context usage detection** (`src/context/detection.ts`) — effective context window = `min(contextWindow, 256K) − min(maxTokens, 20000)`, so 1M-context models (e.g. DeepSeek V4.1 Flash) get a sane ~190K auto-compact threshold instead of ~800K that never fires; auto-compact threshold = a percent of the effective window (**default 80%**, adjustable 70–95% in `/settings`); warning/error = threshold ∓ 20k; blocking limit = effective window − 3k; 3-failure circuit breaker. When the 256K ceiling engages, the footer's fullness percentage is also measured against the effective window (e.g. `14.4%/242K`), so the meter tracks the usable window instead of crawling against raw 1M capacity. The "Auto-compact threshold" row persists to `~/.pi/agent/pi-plus-settings.json` (`src/context/threshold-setting.ts`); `PI_AUTOCOMPACT_PCT_OVERRIDE` keeps its session-scoped, capped-at-the-CC-buffer test semantics. The effective window is also floored at the output reserve plus a context floor buffer (**default 13k**, adjustable 13000–65536 in `/settings`); the floor only ever raises the built-in 13k minimum so small-context models keep a usable (non-negative-threshold) window, and `PI_CONTEXT_FLOOR_TOKENS` overrides it for the session.
10
10
  2. **Compaction** (`src/compaction/`) — single full-conversation summary using the CC 9-section prompt (`prompt.ts`); prompt-too-long retries drop the oldest turn (`compact.ts`); post-compact re-injection of up to 5 recently read files (50k token budget).
11
11
  3. **Reasoning effort** (`src/reasoning/effort.ts`) — CC effort levels (`low`/`medium`/`high`/`max`, `max` → `xhigh` → `high` downgrading), adaptive thinking default, `ultrathink` keyword → high effort for that turn, thinking budgets from env.
12
- 4. **Hub profiles** (`src/coding-agent/main.ts` wrapper, backed by `@earendil-works/pi-hub` = `packages/hub`) — named pi profiles (provider/models/thinking/token/base URL) stored in `~/.pi/profiles.json`, materialized into isolated agent dirs under `~/.pi/pi-hub/profiles/<name>/`. Adds `pp profile …`, `pp use` / `pp unuse`, the deprecated `pp run`, and the `pp --profile <name>` flag. The wrapper resolves the profile, sets `PI_CODING_AGENT_DIR` in-process (read lazily by `getAgentDir()`), and delegates to the original `main`.
13
-
14
- The CLI identifies as **`pp`** (pi-plus) via the `config.ts` wrapper (`APP_NAME`/`APP_TITLE` shadow). Scope is the display name only — config dir (`.pi`), `PI_`-prefixed env vars, and session layout stay pi's.
12
+ 4. **Hub profiles** (`src/coding-agent/main.ts` wrapper, backed by `@earendil-works/pi-hub` = `packages/hub`) — named pi profiles (provider/models/thinking/token/base URL) stored in `~/.pi/profiles.json`, materialized into isolated agent dirs under `~/.pi/pi-hub/profiles/<name>/`. Adds `pipi profile …`, `pipi use` / `pipi unuse`, and the `pipi --as <name>` flag. The wrapper resolves the profile, sets `PI_CODING_AGENT_DIR` in-process (read lazily by `getAgentDir()`), and delegates to the original `main`.
13
+ 5. **CLI surface** (`src/completion/`, `src/coding-agent/cli/args.ts` wrapper) — `pipi --help` gains a "Profile commands (pi-plus)" section, and `pipi completion <bash|zsh>` prints a shell completion script covering the whole CLI: hub subcommands (with dynamic profile/model names from `~/.pi/profiles.json`) plus pi's native commands and flags.
14
+ 6. **Welcome banner** (`src/coding-agent/ui/banner.ts`, registered as a hidden built-in extension from the `main.ts` wrapper) — pipi's TUI startup header becomes a CC-style banner (ported from better-claude-code-ui) with a block-character π+ mark: condensed logo by default, boxed variant with Extensions/Skills feeds on first run in a project or version change, compact/plain degradation on narrow terminals, `resumed <id> · <title>` on resume/fork. `setHeader` replaces pi's built-in header, so no settings changes are needed.
15
+ 7. **Vim modal editing** (`src/coding-agent/ui/vim/`, core subset ported from [pi-vimmode](https://github.com/pekochan069/pi-vimmode), MIT, (c) 2026 pekochan069) — vim-style modal editing for the prompt input, as a hidden built-in extension replacing the editor component. Supported: insert/normal/visual (`v`)/visual-line (`V`) modes; motions `h j k l w b e 0 $ ^ f F t T` with counts; operators `d c y` over motions, linewise `dd cc yy`; `x s r J p P i a I A o O C`; `u`/Ctrl-r undo/redo; prompt search `/ ? n N`. Excluded (vs full pi-vimmode): ex commands, macros, marks, named registers, easymotion, visual-block, JS config, cursor-shape escapes. Enable with `"vim": true` in settings — project `.pi/settings.json` wins over the agent dir, which wins over `~/.pi/settings.json` — or toggle with `/vim`, which applies immediately and persists the new state to the agent dir `settings.json` (project settings still override per project).
16
+ 8. **Subagent tool** (`src/extensions/subagent/`, ported from pi's subagent example, single mode only) — delegates a task to a specialized sub-agent in an isolated `pi -p --no-session` subprocess with its own context window. Agent types are markdown files with frontmatter (`name`, `description`, `tools`, `model`) in `<agent dir>/agents/` or the project's `.pi/agents/`; built-in types `worker` (full toolset) and `explore` (read-only) always exist. Parallel-safe (`executionMode: "parallel"`), abort propagates to the child, child usage/cost is reported, and sub-agents can't recurse unless their definition allows it.
17
+ 9. **Task tools** (`src/extensions/tasks/`, openclaude V2 style) — `TaskCreate`/`TaskUpdate`/`TaskList`/`TaskGet` backed by one JSON file per task under `<agent dir>/tasks/<sessionId>/` (monotonic ids via `.highwatermark`, atomic tmp+rename writes), with per-task `owner` and `blocks`/`blockedBy` dependencies. `/tasks` or `ctrl+shift+t` opens a task-list overlay in the TUI.
18
+ 10. **ask_user tool** (`src/extensions/ask-user/`, openclaude AskUserQuestion style) — the model can ask 1–4 structured questions per call (2–4 options with descriptions each, optional `multiSelect`, automatic "Other" free-text). In TUI mode a tabbed overlay dialog collects the answers; RPC mode falls back to sequential select/input dialogs; print/JSON mode makes the tool fail with an error result so the model proceeds with its own assumptions. Guardrails: unique question texts and option labels, no model-supplied "Other" option, header chips ≤ 12 chars.
19
+ 11. **User command hooks** (`src/extensions/hooks/`) — fires command hooks declared in `settings.json` under a `"hooks"` key (per-event matcher groups of `{type:"command", command, async}` entries; hooks from `~/.pi`, the agent dir, and the project `.pi` settings files are merged) at CC-analogue moments: `PermissionRequest` when any blocking prompt opens (ask_user dialog, plan-mode entry/approval), `PreToolUse` per tool call (`ask_user` matches `AskUserQuestion` matchers), `Stop` when the agent settles. Fire-and-forget detached spawns; never blocks or fails the agent.
20
+ 12. **Long-term memory** (`src/extensions/memory/`, openclaude memdir/extractMemories style) — per-project memories as markdown files with frontmatter (`name`, `description`, `type`: user/feedback/project/reference) under `<agent dir>/memory/<project-key>/`, indexed in `MEMORY.md` (200-line / 25 KB caps). The `memory_save`/`memory_recall` tools let the model persist and search durable facts; the index is injected as a `<memory>` system-prompt section each run; `/memory` browses/edits/adds/forgets. At `agent_settled` a background sub-agent restricted to the two memory tools reviews the conversation and saves noteworthy facts (skipped when the main agent already saved one, below `extractMinMessages` new messages, or within `extractCooldownMs`). Toggle via the `"memory"` key in settings.json (`enabled`, `autoExtract`, `extractMinMessages`, `extractCooldownMs`; project > agent dir > `~/.pi`).
21
+ 13. **Tab title + busy spinner** (`src/extensions/tab-title/`) — the terminal window/tab title brands as `pi+ - [sessionName -] cwdBasename` (via the `config.ts` wrapper's `APP_TITLE`, which upstream's `updateTerminalTitle` also uses, so both paths agree). While the agent is working (`agent_start` until `agent_settled`/`turn_end`), a braille spinner frame is prepended to the title and ticks every 120 ms, so a backgrounded tab shows at a glance that pi+ is busy. TUI mode only; the ticker is cleared on session shutdown.
22
+ 14. **Plain tool blocks** (`src/extensions/plain-tools/`) — strips the background fills upstream paints on tool result blocks (`toolPendingBg` while running, `toolSuccessBg`/`toolErrorBg` on completion, including edit diff boxes), so tool status reads as text — words like `Command exited with code 3` and the subagent tool's `running` / `✓ done` / `✗ failed` — instead of colored blocks. Implemented as a one-time `Theme.prototype.bg` wrapper (idempotent, applied at extension registration), so it holds across theme switches and spares every other background token (selections, user message bubble).
23
+
24
+ The CLI identifies as **`pipi`** (pi-plus) in CLI text via the `config.ts` wrapper's `APP_NAME` shadow; the terminal tab title brands as **`pi+`** via the `APP_TITLE` shadow. Scope is the display name only — config dir (`.pi`), `PI_`-prefixed env vars, and session layout stay pi's.
15
25
 
16
26
  ## Mechanism
17
27
 
18
28
  - `loader/hooks.mjs` — Node module customization hook. Two jobs: (a) map `@earendil-works/*` specifiers to `packages/*/src` (mirrors root tsconfig paths), (b) redirect selected upstream modules to the wrapper modules below. Importers inside `packages/plus/` are never redirected, so wrappers can import the true original via relative path without a loop.
19
- - `loader/run-plus.mjs` + `pp` — entry point. Runs pi from TypeScript sources on Node's native type stripping (the repo is `erasableSyntaxOnly`). tsx is intentionally not used: its load hook silently produces empty modules when another customization hook is registered alongside it (Node 25).
29
+ - `loader/run-plus.mjs` + `pipi` — entry point. Runs pi from TypeScript sources on Node's native type stripping (the repo is `erasableSyntaxOnly`). tsx is intentionally not used: its load hook silently produces empty modules when another customization hook is registered alongside it (Node 25).
20
30
  - `src/<upstream-path>.ts` — wrapper modules. Each does `export * from "<relative path to original>"` and redefines selected exports; per ESM spec, explicit named exports shadow star exports, so everything not overridden passes through untouched.
21
- - Redirect map: `loader/redirects.mjs` (7 modules: coding-agent compaction/model-resolver/defaults/config/main, agent agent.ts, agent harness compaction).
31
+ - Redirect map: `loader/redirects.mjs` (10 modules: coding-agent compaction/agent-session/model-resolver/defaults/config/main/cli-args/settings-selector, agent agent.ts, agent harness compaction).
32
+
33
+ ## Shell completion
34
+
35
+ `pipi completion <bash|zsh>` prints a completion script for the whole CLI — hub subcommands
36
+ (dynamic profile names and per-profile models from `~/.pi/profiles.json`, providers, thinking
37
+ levels) plus pi's native commands and flags. Install with:
38
+
39
+ ```bash
40
+ source <(pipi completion zsh) # add to ~/.zshrc
41
+ source <(pipi completion bash) # add to ~/.bashrc
42
+ ```
22
43
 
23
44
  ## Env vars (pi-style names)
24
45
 
25
46
  | Var | Values | Effect |
26
47
  | ----------------------------- | ----------------------------------- | --------------------------------------------------------------- |
27
48
  | `PI_MAX_CONTEXT_TOKENS` | number | Overrides `model.contextWindow` after model resolution |
28
- | `PI_AUTO_COMPACT_WINDOW` | number | Caps the window used for threshold math |
49
+ | `PI_AUTO_COMPACT_WINDOW` | number | Caps the window used for threshold math (cannot raise the 256K ceiling) |
29
50
  | `PI_AUTOCOMPACT_PCT_OVERRIDE` | 1–100 | Auto-compact threshold as % of effective window (capped at default) |
51
+ | `PI_CONTEXT_FLOOR_TOKENS` | number ≥ 13000 | Context floor override (only raises the built-in 13k floor) |
30
52
  | `PI_BLOCKING_LIMIT_OVERRIDE` | number | Blocking limit override |
31
53
  | `PI_DISABLE_COMPACT` | truthy | Disables all compaction (incl. manual) |
32
54
  | `PI_DISABLE_AUTO_COMPACT` | truthy | Disables threshold-triggered auto-compaction |
55
+ | `PI_AUTOCOMPACT_FAILURE_COOLDOWN_MS` | ms ≥ 10000 | Circuit-breaker cooldown after 3 consecutive auto-compact failures |
56
+ | `PI_MAX_ACTIVE_MESSAGES` | number (`0`/invalid = off, default 1000) | Forces compaction when the active message count exceeds the cap |
57
+ | `PI_PRUNE_TAIL_TURNS` | number ≥ 1 (default 3) | Recent turns preserved verbatim by relevance pruning |
58
+ | `PI_MICROCOMPACT_IDLE_MINUTES` | minutes (default 60; ≤ 0 disables) | Idle gap that triggers clearing of stale tool-result content on session open |
59
+ | `PI_MICROCOMPACT_KEEP_RECENT` | number (default 5) | Tool results preserved verbatim by idle micro-compact |
60
+ | `PI_COMPACT_ANALYTICS` | truthy | Emits recompaction diagnostics to stderr after compaction |
61
+ | `PI_PLUS_SETTINGS_FILE` | path | Overrides `~/.pi/agent/pi-plus-settings.json` (test/debug knob) |
33
62
  | `PI_EFFORT_LEVEL` | `off`/`auto`/`low`/`medium`/`high`/`max` | Per-request reasoning effort override |
34
63
  | `PI_MAX_THINKING_TOKENS` | number (`0` disables) | Thinking budget (enables thinking at `high` when > 0) |
35
64
  | `PI_DISABLE_THINKING` | truthy | Disables thinking entirely |
@@ -44,33 +73,32 @@ The CLI identifies as **`pp`** (pi-plus) via the `config.ts` wrapper (`APP_NAME`
44
73
 
45
74
  ## Compiled artifact (npm)
46
75
 
47
- `build.mjs` bundles `pp` into `dist/npm/` — a self-contained staging tree that `npm link` /
76
+ `build.mjs` bundles `pipi` into `dist/npm/` — a self-contained staging tree that `npm link` /
48
77
  `npm publish` operate on (this package itself stays private). The published artifact is
49
- **`pi-plus`** on npmjs; it installs a single global command, **`pi-plus`** — deliberately
50
- not `pi` (pi-plus must not own pi's command) and not `pp` (collides with Homebrew nss's
51
- `pp` on macOS). The CLI itself still identifies as `pp` everywhere (help text, hub
52
- commands); add `alias pp=pi-plus` to your shell rc for the short name.
78
+ **`pi-plus`** on npmjs; it installs a single global command, **`pipi`** — deliberately
79
+ not `pi` (pi-plus must not own pi's command). The CLI identifies as `pipi` everywhere
80
+ (help text, hub commands).
53
81
 
54
82
  ```bash
55
83
  npm run build # in packages/plus; requires `npm run build:offline` at the repo root first
56
- npm link # in packages/plus/dist/npm — global `pp`
84
+ npm link # in packages/plus/dist/npm — global `pipi`
57
85
  npm publish --access public --ignore-scripts # in packages/plus/dist/npm
58
86
  ```
59
87
 
60
88
  The bundle applies `loader/redirects.mjs` at bundle time (esbuild plugin) and keeps each
61
89
  module a singleton by funneling every `packages/*/src/**` import with a compiled `dist/`
62
90
  counterpart to that dist file. `--no-env` is preserved via a banner scrub. Provider
63
- credentials, config dir (`~/.pi`), and session layout are identical to source-mode `pp`.
91
+ credentials, config dir (`~/.pi`), and session layout are identical to source-mode `pipi`.
64
92
 
65
93
  Known limitations of the compiled artifact:
66
94
 
67
- - `pp server` / `pp client` experimental subcommands (`PI_EXPERIMENTAL=1`) spawn sibling JS
68
- files that are not emitted next to the bundle; use source-mode `./pp` for those.
95
+ - `pipi server` / `pipi client` experimental subcommands (`PI_EXPERIMENTAL=1`) spawn sibling JS
96
+ files that are not emitted next to the bundle; use source-mode `./pipi` for those.
69
97
  - `docs/` and `examples/` are not shipped, so `/docs`-style paths into them are absent.
70
98
 
71
99
  ## Tests
72
100
 
73
101
  ```
74
102
  npx vitest run # from packages/plus; unit tests under test/ (faux streamFn, no real APIs)
75
- ./pp --no-env # run pp (pi-plus) from sources with the override layer active
103
+ ./pipi --no-env # run pipi (pi-plus) from sources with the override layer active
76
104
  ```
@@ -84,7 +84,7 @@ Reference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.ht
84
84
  `);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{incoming=[];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=new FifoQueue;waiting=new FifoQueue;done=!1;finalResultPromise;resolveFinalResult;isComplete;extractResult;constructor(isComplete,extractResult){this.isComplete=isComplete,this.extractResult=extractResult,this.finalResultPromise=new Promise(resolve=>{this.resolveFinalResult=resolve})}push(event){if(this.done)return;this.isComplete(event)&&(this.done=!0,this.resolveFinalResult(this.extractResult(event)));let waiter=this.waiting.dequeue();waiter?waiter({value:event,done:!1}):this.queue.enqueue(event)}end(result){for(this.done=!0,result!==void 0&&this.resolveFinalResult(result);this.waiting.length>0;)this.waiting.dequeue()({value:void 0,done:!0})}async*[Symbol.asyncIterator](){for(;;)if(this.queue.length>0)yield this.queue.dequeue();else{if(this.done)return;{let result=await new Promise(resolve=>this.waiting.enqueue(resolve));if(result.done)return;yield result.value}}}result(){return this.finalResultPromise}},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]}var DEFAULT_OAUTH_MINIMUM_VALIDITY_MS=300*1e3;function contentText(content,separator=`
85
85
  `){return typeof content=="string"?content:content.filter(block=>block.type==="text").map(block=>block.text).join(separator)}function getSystemMessageText(message){let parts=[contentText(message.content)];for(let text of Object.values(message.sections??{}))text!==null&&parts.push(text);return parts.filter(part=>part.length>0).join(`
86
86
 
87
- `)}function isSystemMessage(message){return message.role==="system"}function getInitialSystemMessage(messages){let first=messages[0];return first&&isSystemMessage(first)?first:void 0}function withoutInitialSystemMessage(messages){return getInitialSystemMessage(messages)?messages.slice(1):messages}function getCurrentTools(messages){let tools=new Map;for(let message of messages)if(isSystemMessage(message)){message.replace&&tools.clear();for(let tool of message.toolsRemoved??[])tools.delete(tool.name);for(let tool of message.toolsAdded??[])tools.set(tool.name,tool)}return[...tools.values()]}function getCurrentSystemMessage(messages){let content=[],sections=new Map,timestamp;for(let message of messages){if(!isSystemMessage(message))continue;message.replace&&(content.length=0,sections.clear()),timestamp??=message.timestamp;let text=contentText(message.content);text.length>0&&content.push(text);for(let[name,value]of Object.entries(message.sections??{}))value===null?sections.delete(name):sections.set(name,value)}let tools=getCurrentTools(messages);if(!(timestamp===void 0&&tools.length===0))return{role:"system",content:content.join(`
87
+ `)}function isSystemMessage(message){return message.role==="system"}function getInitialSystemMessage(messages){let first=messages[0];return first&&isSystemMessage(first)?first:void 0}function withoutInitialSystemMessage(messages){return getInitialSystemMessage(messages)?messages.slice(1):messages}function getCurrentTools(messages){let tools=new Map;for(let message of messages)if(isSystemMessage(message)){for(let tool of message.toolsRemoved??[])tools.delete(tool.name);for(let tool of message.toolsAdded??[])tools.set(tool.name,tool)}return[...tools.values()]}function getCurrentSystemMessage(messages){let content=[],sections=new Map,timestamp;for(let message of messages){if(!isSystemMessage(message))continue;timestamp??=message.timestamp;let text=contentText(message.content);text.length>0&&content.push(text);for(let[name,value]of Object.entries(message.sections??{}))value===null?sections.delete(name):sections.set(name,value)}let tools=getCurrentTools(messages);if(!(timestamp===void 0&&tools.length===0))return{role:"system",content:content.join(`
88
88
 
89
- `),...sections.size>0?{sections:Object.fromEntries(sections)}:{},...tools.length>0?{toolsAdded:tools}:{},timestamp:timestamp??0}}function collapseSystemMessages(context){let head=getCurrentSystemMessage(context.messages),messages=context.messages.filter(message=>message.role!=="system");return{messages:head?[head,...messages]:messages}}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()),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`
90
- `: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"),data2=readFileSync("/proc/self/environ","utf-8");for(let entry of data2.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 sanitizeSurrogates(text){return text.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,"")}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||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.`)}}var CHARS_PER_TOKEN=4,ESTIMATED_IMAGE_CHARS=4800;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:ESTIMATED_IMAGE_CHARS;return chars2}function estimateTextTokens(text){return Math.ceil(text.length/CHARS_PER_TOKEN)}function estimateTextAndImageContentTokens(content){return Math.ceil(estimateTextAndImageContentChars(content)/CHARS_PER_TOKEN)}function estimateMessageTokens(message){let chars2=0;if(message.role==="system")return estimateTextTokens(getSystemMessageText(message))+estimateToolsTokens(message.toolsAdded)+estimateToolsTokens(message.toolsRemoved);if(message.role==="user"||message.role==="toolResult")return estimateTextAndImageContentTokens(message.content);for(let block of message.content)block.type==="text"?chars2+=block.text.length:block.type==="thinking"?chars2+=block.thinking.length:chars2+=block.name.length+safeJsonStringify2(block.arguments).length;return Math.ceil(chars2/CHARS_PER_TOKEN)}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 estimateContextTokens(context){let messages="messages"in context?context.messages:context,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))}var CONTEXT_SAFETY_TOKENS=4096,MIN_MAX_TOKENS=1;function clampMaxTokensToContext(model,context,maxTokens){if(model.contextWindow<=0)return Math.max(MIN_MAX_TOKENS,maxTokens);let available=model.contextWindow-estimateContextTokens(context).tokens-CONTEXT_SAFETY_TOKENS;return Math.min(maxTokens,Math.max(MIN_MAX_TOKENS,available))}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,telemetryContext:options?.telemetryContext,apiKey:apiKey||options?.apiKey,fetch:options?.fetch,transport:options?.transport,cacheRetention:options?.cacheRetention,sessionId:options?.sessionId,headers:options?.headers,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 MIN_ANSWER_TOKENS=1024,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 thinkingBudget=thinkingBudgetForLevel(reasoningLevel,customBudgets),maxTokens=baseMaxTokens===void 0?modelMaxTokens:Math.min(baseMaxTokens+thinkingBudget,modelMaxTokens);return maxTokens<=thinkingBudget&&(thinkingBudget=clampThinkingBudgetToAnswerRoom(thinkingBudget,maxTokens)),{maxTokens,thinkingBudget}}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)";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){return model.input.includes("image")?messages:messages.map(msg=>msg.role==="user"&&Array.isArray(msg.content)?{...msg,content:replaceImagesWithPlaceholder(msg.content,NON_VISION_USER_IMAGE_PLACEHOLDER)}:msg.role==="toolResult"?{...msg,content:replaceImagesWithPlaceholder(msg.content,NON_VISION_TOOL_IMAGE_PLACEHOLDER)}:msg)}function transformMessages(messages,model,normalizeToolCallId2){let toolCallIdMap=new Map,normalizedMessages=messages.map(msg=>msg.content==null?{...msg,content:[]}:msg),transformed=downgradeUnsupportedImages(normalizedMessages,model).map(msg=>{if(msg.role==="system"||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,transformedContent=assistantMsg.content.flatMap(block=>{if(block.type==="thinking")return block.redacted?isSameModel?block:[]:isSameModel&&block.thinkingSignature?block:!block.thinking||block.thinking.trim()===""?[]:isSameModel?block:{type:"text",text:block.thinking};if(block.type==="text")return isSameModel?block:{type:"text",text:block.text};if(block.type==="toolCall"){let toolCall=block,normalizedToolCall=toolCall;if(!isSameModel&&toolCall.thoughtSignature&&(normalizedToolCall={...toolCall},delete normalizedToolCall.thoughtSignature),!isSameModel&&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=[],pendingToolCalls=[],existingToolResultIds=new Set,heldSystemMessages=[],closePendingToolCalls=()=>{if(pendingToolCalls.length>0){for(let tc of pendingToolCalls)existingToolResultIds.has(tc.id)||result.push({role:"toolResult",toolCallId:tc.id,toolName:tc.name,content:[{type:"text",text:"No result provided"}],isError:!0,timestamp:Date.now()});pendingToolCalls=[],existingToolResultIds=new Set}result.push(...heldSystemMessages),heldSystemMessages.length=0};for(let i5=0;i5<transformed.length;i5++){let msg=transformed[i5];if(msg.role==="assistant"){closePendingToolCalls();let assistantMsg=msg;if(assistantMsg.stopReason==="error"||assistantMsg.stopReason==="aborted")continue;let toolCalls=assistantMsg.content.filter(b5=>b5.type==="toolCall");toolCalls.length>0&&(pendingToolCalls=toolCalls,existingToolResultIds=new Set),result.push(msg)}else msg.role==="toolResult"?(existingToolResultIds.add(msg.toolCallId),result.push(msg)):msg.role==="system"?pendingToolCalls.length>0?heldSystemMessages.push(msg):result.push(msg):(msg.role==="user"&&closePendingToolCalls(),result.push(msg))}return closePendingToolCalls(),result}var EMPTY_TEXT_PLACEHOLDER="<empty>",REDACTED_THINKING_PLACEHOLDER="[Reasoning redacted]",stream=(model,context,options={})=>{let stream2=new AssistantMessageEventStream,normalizedContext=collapseSystemMessages(context);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&&addCustomHeadersMiddleware(client,customHeaders);let cacheRetention=resolveCacheRetention(options.cacheRetention,options.env),inferenceMaxTokens=options.maxTokens??(isAnthropicClaudeModel(model)?model.maxTokens:void 0),initialSystemMessage=getInitialSystemMessage(normalizedContext.messages),initialSystemPrompt=initialSystemMessage?getSystemMessageText(initialSystemMessage):void 0,commandInput={modelId:model.id,messages:convertMessages(normalizedContext,model,cacheRetention,options.env),system:buildSystemPrompt(initialSystemPrompt,model,cacheRetention,options.env),inferenceConfig:{...inferenceMaxTokens!==void 0&&{maxTokens:inferenceMaxTokens},...options.temperature!==void 0&&{temperature:options.temperature}},toolConfig:convertToolConfig(getCurrentTools(normalizedContext.messages),options.toolChoice,supportsStrictMode),additionalModelRequestFields:buildAdditionalModelRequestFields(model,options),...options.requestMetadata!==void 0&&{requestMetadata:options.requestMetadata}},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 addCustomHeadersMiddleware(client,headers){let middleware=next=>async args=>{let request=args.request;if(request&&typeof request=="object"&&"headers"in request){let requestHeaders=request.headers;for(let[key,value]of Object.entries(headers))isReservedHeader(key)||(requestHeaders[key]=value)}return next(args)};client.middlewareStack.add(middleware,{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){let middleware=next=>async args=>{let result=await next(args),providerResponse=toProviderResponse(result.response);return providerResponse&&(onObserved(),await onResponse(providerResponse,model)),result};client.middlewareStack.add(middleware,{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.cacheWrite1h=event.usage.cacheDetails?.reduce((total,detail)=>total+(detail.ttl===import_client_bedrock_runtime.CacheTTL.ONE_HOUR?detail.inputTokens??0:0),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 getModelMatchCandidates(modelId,modelName){return(modelName?[modelId,modelName]:[modelId]).flatMap(value=>{let lower=value.toLowerCase();return[lower,lower.replace(/[\s_.:]+/g,"-")]})}function supportsAdaptiveThinking(modelId,modelName){return getModelMatchCandidates(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"))}function supportsNativeXhighEffort(model){return getModelMatchCandidates(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"))}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";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 supportsPromptCaching(model,env2){let candidates=getModelMatchCandidates(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 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"?{ttl:import_client_bedrock_runtime.CacheTTL.ONE_HOUR}:{}}}),blocks}function normalizeToolCallId(id){let sanitized=id.replace(/[^a-zA-Z0-9_-]/g,"_");return sanitized.length>64?sanitized.slice(0,64):sanitized}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 convertMessages(context,model,cacheRetention,env2){let result=[],transformedMessages=transformMessages(withoutInitialSystemMessage(context.messages),model,normalizeToolCallId);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})}result.push({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;result.push({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,result.push({role:import_client_bedrock_runtime.ConversationRole.USER,content:toolResults});break}default:continue}}if(cacheRetention!=="none"&&supportsPromptCaching(model,env2)&&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"?{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: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 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(!(!options.reasoning||!model.reasoning)&&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,data2){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(data2)},format:format2}}function base64ToBytes(data2){let binaryString=atob(data2),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};
89
+ `),...sections.size>0?{sections:Object.fromEntries(sections)}:{},...tools.length>0?{toolsAdded:tools}:{},timestamp:timestamp??0}}function collapseSystemMessages(context){let head=getCurrentSystemMessage(context.messages),messages=context.messages.filter(message=>message.role!=="system");return{messages:head?[head,...messages]:messages}}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(...headerSources){let merged=new Map;for(let source of headerSources)for(let[name,value]of Object.entries(source??{})){let normalizedName=name.toLowerCase();merged.delete(normalizedName),value!==null&&merged.set(normalizedName,[name,value])}return merged.size>0?Object.fromEntries(merged.values()):void 0}var import_partial_json=__toESM(require_dist()),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`
90
+ `: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"),data2=readFileSync("/proc/self/environ","utf-8");for(let entry of data2.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 sanitizeSurrogates(text){return text.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,"")}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||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.`)}}var CHARS_PER_TOKEN=4,ESTIMATED_IMAGE_CHARS=4800;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:ESTIMATED_IMAGE_CHARS;return chars2}function estimateTextTokens(text){return Math.ceil(text.length/CHARS_PER_TOKEN)}function estimateTextAndImageContentTokens(content){return Math.ceil(estimateTextAndImageContentChars(content)/CHARS_PER_TOKEN)}function estimateMessageTokens(message){let chars2=0;if(message.role==="system")return estimateTextTokens(getSystemMessageText(message))+estimateToolsTokens(message.toolsAdded)+estimateToolsTokens(message.toolsRemoved);if(message.role==="user"||message.role==="toolResult")return estimateTextAndImageContentTokens(message.content);for(let block of message.content)block.type==="text"?chars2+=block.text.length:block.type==="thinking"?chars2+=block.thinking.length:chars2+=block.name.length+safeJsonStringify2(block.arguments).length;return Math.ceil(chars2/CHARS_PER_TOKEN)}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 estimateContextTokens(context){let messages="messages"in context?context.messages:context,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))}var CONTEXT_SAFETY_TOKENS=4096,MIN_MAX_TOKENS=1;function clampMaxTokensToContext(model,context,maxTokens){if(model.contextWindow<=0)return Math.max(MIN_MAX_TOKENS,maxTokens);let available=model.contextWindow-estimateContextTokens(context).tokens-CONTEXT_SAFETY_TOKENS;return Math.min(maxTokens,Math.max(MIN_MAX_TOKENS,available))}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,telemetryContext:options?.telemetryContext,apiKey:apiKey||options?.apiKey,fetch:options?.fetch,transport:options?.transport,cacheRetention:options?.cacheRetention,sessionId:options?.sessionId,headers:options?.headers,onPayload:options?.onPayload,onResponse:options?.onResponse,onProviderStreamEvent:options?.onProviderStreamEvent,timeoutMs:options?.timeoutMs,websocketConnectTimeoutMs:options?.websocketConnectTimeoutMs,maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,metadata:options?.metadata,env:options?.env}}var MIN_ANSWER_TOKENS=1024,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 thinkingBudget=thinkingBudgetForLevel(reasoningLevel,customBudgets),maxTokens=baseMaxTokens===void 0?modelMaxTokens:Math.min(baseMaxTokens+thinkingBudget,modelMaxTokens);return maxTokens<=thinkingBudget&&(thinkingBudget=clampThinkingBudgetToAnswerRoom(thinkingBudget,maxTokens)),{maxTokens,thinkingBudget}}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)";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){return model.input.includes("image")?messages:messages.map(msg=>msg.role==="user"&&Array.isArray(msg.content)?{...msg,content:replaceImagesWithPlaceholder(msg.content,NON_VISION_USER_IMAGE_PLACEHOLDER)}:msg.role==="toolResult"?{...msg,content:replaceImagesWithPlaceholder(msg.content,NON_VISION_TOOL_IMAGE_PLACEHOLDER)}:msg)}function transformMessages(messages,model,normalizeToolCallId2){let toolCallIdMap=new Map,normalizedMessages=messages.map(msg=>msg.content==null?{...msg,content:[]}:msg),transformed=downgradeUnsupportedImages(normalizedMessages,model).map(msg=>{if(msg.role==="system"||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,transformedContent=assistantMsg.content.flatMap(block=>{if(block.type==="thinking")return block.redacted?isSameModel?block:[]:isSameModel&&block.thinkingSignature?block:!block.thinking||block.thinking.trim()===""?[]:isSameModel?block:{type:"text",text:block.thinking};if(block.type==="text")return isSameModel?block:{type:"text",text:block.text};if(block.type==="toolCall"){let toolCall=block,normalizedToolCall=toolCall;if(!isSameModel&&toolCall.thoughtSignature&&(normalizedToolCall={...toolCall},delete normalizedToolCall.thoughtSignature),!isSameModel&&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=[],pendingToolCalls=[],existingToolResultIds=new Set,heldSystemMessages=[],closePendingToolCalls=()=>{if(pendingToolCalls.length>0){for(let tc of pendingToolCalls)existingToolResultIds.has(tc.id)||result.push({role:"toolResult",toolCallId:tc.id,toolName:tc.name,content:[{type:"text",text:"No result provided"}],isError:!0,timestamp:Date.now()});pendingToolCalls=[],existingToolResultIds=new Set}result.push(...heldSystemMessages),heldSystemMessages.length=0};for(let i5=0;i5<transformed.length;i5++){let msg=transformed[i5];if(msg.role==="assistant"){closePendingToolCalls();let assistantMsg=msg;if(assistantMsg.stopReason==="error"||assistantMsg.stopReason==="aborted")continue;let toolCalls=assistantMsg.content.filter(b5=>b5.type==="toolCall");toolCalls.length>0&&(pendingToolCalls=toolCalls,existingToolResultIds=new Set),result.push(msg)}else msg.role==="toolResult"?(existingToolResultIds.add(msg.toolCallId),result.push(msg)):msg.role==="system"?pendingToolCalls.length>0?heldSystemMessages.push(msg):result.push(msg):(msg.role==="user"&&closePendingToolCalls(),result.push(msg))}return closePendingToolCalls(),result}var EMPTY_TEXT_PLACEHOLDER="<empty>",REDACTED_THINKING_PLACEHOLDER="[Reasoning redacted]",stream=(model,context,options={})=>{let stream2=new AssistantMessageEventStream,normalizedContext=collapseSystemMessages(context);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&&addCustomHeadersMiddleware(client,customHeaders);let cacheRetention=resolveCacheRetention(options.cacheRetention,options.env),inferenceMaxTokens=options.maxTokens??(isAnthropicClaudeModel(model)?model.maxTokens:void 0),initialSystemMessage=getInitialSystemMessage(normalizedContext.messages),initialSystemPrompt=initialSystemMessage?getSystemMessageText(initialSystemMessage):void 0,commandInput={modelId:model.id,messages:convertMessages(normalizedContext,model,cacheRetention,options.env),system:buildSystemPrompt(initialSystemPrompt,model,cacheRetention,options.env),inferenceConfig:{...inferenceMaxTokens!==void 0&&{maxTokens:inferenceMaxTokens},...options.temperature!==void 0&&{temperature:options.temperature}},toolConfig:convertToolConfig(getCurrentTools(normalizedContext.messages),options.toolChoice,supportsStrictMode),additionalModelRequestFields:buildAdditionalModelRequestFields(model,options),...options.requestMetadata!==void 0&&{requestMetadata:options.requestMetadata}},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(await options.onProviderStreamEvent?.(item,model),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 addCustomHeadersMiddleware(client,headers){let middleware=next=>async args=>{let request=args.request;if(request&&typeof request=="object"&&"headers"in request){let requestHeaders=request.headers;for(let[key,value]of Object.entries(headers))isReservedHeader(key)||(requestHeaders[key]=value)}return next(args)};client.middlewareStack.add(middleware,{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){let middleware=next=>async args=>{let result=await next(args),providerResponse=toProviderResponse(result.response);return providerResponse&&(onObserved(),await onResponse(providerResponse,model)),result};client.middlewareStack.add(middleware,{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.cacheWrite1h=event.usage.cacheDetails?.reduce((total,detail)=>total+(detail.ttl===import_client_bedrock_runtime.CacheTTL.ONE_HOUR?detail.inputTokens??0:0),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 getModelMatchCandidates(modelId,modelName){return(modelName?[modelId,modelName]:[modelId]).flatMap(value=>{let lower=value.toLowerCase();return[lower,lower.replace(/[\s_.:]+/g,"-")]})}function supportsAdaptiveThinking(modelId,modelName){return getModelMatchCandidates(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"))}function supportsNativeXhighEffort(model){return getModelMatchCandidates(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"))}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";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 supportsPromptCaching(model,env2){let candidates=getModelMatchCandidates(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 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"?{ttl:import_client_bedrock_runtime.CacheTTL.ONE_HOUR}:{}}}),blocks}function normalizeToolCallId(id){let sanitized=id.replace(/[^a-zA-Z0-9_-]/g,"_");return sanitized.length>64?sanitized.slice(0,64):sanitized}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 convertMessages(context,model,cacheRetention,env2){let result=[],transformedMessages=transformMessages(withoutInitialSystemMessage(context.messages),model,normalizeToolCallId);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})}result.push({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;result.push({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,result.push({role:import_client_bedrock_runtime.ConversationRole.USER,content:toolResults});break}default:continue}}if(cacheRetention!=="none"&&supportsPromptCaching(model,env2)&&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"?{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: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 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(!(!options.reasoning||!model.reasoning)&&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,data2){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(data2)},format:format2}}function base64ToBytes(data2){let binaryString=atob(data2),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};
@@ -300,6 +300,12 @@
300
300
  border-color: var(--borderAccent);
301
301
  }
302
302
 
303
+ .header-toggle-btn[aria-pressed="true"] {
304
+ color: var(--accent);
305
+ border-color: var(--accent);
306
+ font-weight: bold;
307
+ }
308
+
303
309
  /* Header */
304
310
  .header {
305
311
  background: var(--container-bg);
@@ -786,6 +792,10 @@
786
792
  border-radius: 4px;
787
793
  }
788
794
 
795
+ body:not(.show-hidden-messages) .hook-message-hidden {
796
+ display: none;
797
+ }
798
+
789
799
  .hook-type {
790
800
  color: var(--customMessageLabel);
791
801
  font-weight: bold;