@diffra-ai/cli 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/CHANGELOG.md +59 -47
  2. package/dist/bundle/chunks/{anthropic-messages-HME6WDIM.js → anthropic-messages-YTASKTAG.js} +1 -1
  3. package/dist/bundle/chunks/{azure-openai-responses-WKSFBZF5.js → azure-openai-responses-2JI3BQFX.js} +1 -1
  4. package/dist/bundle/chunks/bedrock-converse-stream.js +1 -1
  5. package/dist/bundle/chunks/{chunk-MITPYV3F.js → chunk-6RKODDUE.js} +1 -1
  6. package/dist/bundle/chunks/{chunk-MJRIJM22.js → chunk-7QEHJ36J.js} +1 -1
  7. package/dist/bundle/chunks/{chunk-PXE534VH.js → chunk-AI3Y7XHP.js} +2 -2
  8. package/dist/bundle/chunks/{chunk-QMZGTPRI.js → chunk-CAD23HR7.js} +1 -1
  9. package/dist/bundle/chunks/{chunk-E3MJ4MPN.js → chunk-GNFHDZLP.js} +1 -1
  10. package/dist/bundle/chunks/{chunk-SMYD2SB5.js → chunk-IDYI4NPC.js} +1 -1
  11. package/dist/bundle/chunks/{chunk-RUI3NOFB.js → chunk-MPWP6WCT.js} +1 -1
  12. package/dist/bundle/chunks/{chunk-GRDBYTYT.js → chunk-PCXT7GLW.js} +273 -273
  13. package/dist/bundle/chunks/chunk-RAT6HXXD.js +2 -0
  14. package/dist/bundle/chunks/{chunk-3MKQN3ZR.js → chunk-YDKIXS42.js} +1 -1
  15. package/dist/bundle/chunks/{chunk-6L2FT6AE.js → chunk-ZW3S4FQY.js} +1 -1
  16. package/dist/bundle/chunks/{cli-GKHAGQO6.js → cli-2W6362ZV.js} +1 -1
  17. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-PVUECIVD.js → cloudflare-workers-ai-system-one-MN7VZOHO.js} +1 -1
  18. package/dist/bundle/chunks/{google-generative-ai-2YH7DK5J.js → google-generative-ai-QROUBJ3Y.js} +1 -1
  19. package/dist/bundle/chunks/{google-vertex-QNIS4SPE.js → google-vertex-RHSCDEG4.js} +1 -1
  20. package/dist/bundle/chunks/{llama-cpp-classify-EMBT3ZMY.js → llama-cpp-classify-QCKHKADQ.js} +1 -1
  21. package/dist/bundle/chunks/{mistral-conversations-RCHJWX2M.js → mistral-conversations-WO6QUI4U.js} +1 -1
  22. package/dist/bundle/chunks/{openai-codex-responses-LBZQ7HUY.js → openai-codex-responses-XFI3MXBY.js} +1 -1
  23. package/dist/bundle/chunks/{openai-completions-U7NS5GFY.js → openai-completions-2UHGTBTY.js} +1 -1
  24. package/dist/bundle/chunks/{openai-decisions-YC4ZEGAR.js → openai-decisions-BPJODLLR.js} +1 -1
  25. package/dist/bundle/chunks/{openai-responses-4YX6XMEO.js → openai-responses-CCD734Z2.js} +1 -1
  26. package/dist/bundle/chunks/{openrouter-images-QPPGKFJY.js → openrouter-images-WSQ42OX2.js} +1 -1
  27. package/dist/bundle/chunks/{pi-messages-5W3GZ7B6.js → pi-messages-I264JUT4.js} +1 -1
  28. package/dist/bundle/chunks/{typesafe-system-one-GWMQ2NLX.js → typesafe-system-one-O3PSKAI2.js} +1 -1
  29. package/dist/bundle/chunks/{virtual-modules-ENTYMDSQ.js → virtual-modules-CMUMO27Q.js} +1 -1
  30. package/dist/bundle/cli-runtime.js +1 -1
  31. package/dist/bundle/index.js +1 -1
  32. package/dist/bundle/rpc-entry.js +1 -1
  33. package/dist/core/extensions/types.d.ts +2 -2
  34. package/dist/core/extensions/types.d.ts.map +1 -1
  35. package/dist/core/extensions/types.js.map +1 -1
  36. package/dist/index.d.ts +2 -1
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.js +2 -1
  39. package/dist/index.js.map +1 -1
  40. package/docs/approval-modes.md +99 -99
  41. package/docs/cli.md +380 -380
  42. package/docs/docs.json +264 -264
  43. package/docs/environment-variables.md +110 -110
  44. package/docs/extensions.md +3 -2
  45. package/docs/sdk.md +2 -0
  46. package/docs/security.md +100 -100
  47. package/docs/settings.md +198 -198
  48. package/package.json +6 -6
  49. package/dist/bundle/chunks/chunk-PQGGR7SQ.js +0 -2
package/CHANGELOG.md CHANGED
@@ -1,47 +1,59 @@
1
- # Changelog
2
-
3
- ## [Unreleased]
4
-
5
- ## [0.1.2] - 2026-11-21
6
-
7
- ### Added
8
-
9
- - `todo_write`, a built-in tool (`builtin:todo`) for a user-visible task list, following Qwen Code's `todo_write`. It is off by default; enable it with `"defaultTools": ["+todo_write"]` or `--tools +todo_write`. Todos have an id, content, a status, and optional `blockedBy` dependencies. The list is stored in the session, so it survives resume and follows `/tree` and `/fork`, and a "Current tasks" panel shows unfinished todos during a run.
10
- - `web_fetch` (`builtin:web-fetch`, active by default) fetches a URL, converts HTML to Markdown with turndown, and answers a prompt about the page with the new `fastModel` setting or the session model, following Qwen Code's `web_fetch`. Redirects to other hosts are reported instead of followed, binary content is saved to a temporary file (with a PDF's text extracted when `pdftotext` is installed), and pages are cached for 15 minutes. See [Fetch and Search the Web](docs/web-tools.md).
11
- - `web_search` (`builtin:web-search`) searches through a DashScope search agent, following Qwen Code. It turns on when the session model is on a DashScope-compatible endpoint, or with the new `webSearch` setting or `WEB_SEARCH_*` environment variables; when it was turned on but cannot work, Diffra warns what is missing.
12
- - Approval modes, following Qwen Code: `plan` (read-only, with the `exit_plan_mode` tool to approve a plan), `default` (ask before edits and commands), `auto-edit`, `auto` (a classifier model decides, with `permissions.autoMode` hints), and `yolo`. The default stays `yolo`, so nothing asks unless you switch. Switch with `/approval-mode`, `/plan`, `alt+m` (`app.approvalMode.cycle`), `--approval-mode`, or the `approvalMode` setting; "always allow" answers last for the session. Extensions get `diffra.getApprovalMode()`, `diffra.setApprovalMode()`, and the `approval_mode_change` event. See [Approve Tool Calls](docs/approval-modes.md).
13
- - Subagents, following Qwen Code: the `agent` tool delegates a task to an agent with its own prompt, tools, and context, in the foreground or (by default) in the background with a `<task-notification>` when it finishes. Agents are defined in `.diffra/agents/` and the agent directory's `agents/`, with `general-purpose` and `Explore` built in; `/agents` creates and manages them, `/tasks` and `task_stop` list and cancel background ones, and the new `agents` setting controls background default, nesting depth, and parallel runs. See [Delegate to Subagents](docs/subagents.md).
14
- - Hooks, following Qwen Code: command, http, and prompt hooks in the `hooks` setting run on `PreToolUse` (block, ask, or replace the input), `PostToolUse`, `PostToolUseFailure`, `UserPromptSubmit` (block or add context), `Stop` (keep the agent working), `SessionStart`, `SessionEnd`, `StopFailure`, `SubagentStart`, `SubagentStop`, `PreCompact`, `PostCompact`, and `FileChanged`, with Qwen Code's JSON input and output and exit-code contract. Hooks of user and project settings add up; `disableAllHooks` turns them off and `/hooks` lists them. See [Run Hooks on Events](docs/hooks.md).
15
- - Auto memory, following Qwen Code and on by default: memories live as Markdown files in a user directory and a per-repository project directory under the agent directory, with a rebuilt `MEMORY.md` index. Each run gets the memory policy and indexes in its system prompt plus memories that match the prompt; after a run a background agent saves durable facts you stated, and a daily background dream consolidates them. `/memory`, `/remember`, `/forget`, and `/dream` manage it; the new `memory` setting turns the background agents off. See [Keep Auto Memory](docs/memory.md).
16
- - Goals, following Qwen Code: `/goal <objective>` keeps the agent working across turns until it proposes with the `update_goal` tool that the Goal is complete or blocked and an independent verifier model accepts the proposal from the evidence of the Goal's turns. `/goal edit`, `pause`, `resume`, and `clear` control it; Escape, three idle turns, or a failure pause it, and the new `goals` setting sets token, turn, and active-time budgets, after which the Goal gets one hand-off turn and stops. Goal state is recorded in the session and shown in the footer and as transcript cards. See [Work Toward a Goal](docs/goals.md).
17
- - Scheduled tasks and `/loop`, following Qwen Code and on by default: `/loop 5m <prompt>` (or `<prompt> every 5m`) runs a prompt now and on an even cron schedule, `/loop <prompt>` lets the model pace follow-up checks with the new `loop_wakeup` tool, and a bare `/loop` keeps the conversation's work moving autonomously; `/loop list` and `/loop clear` manage them, and loops can work a `loop.md` task list. The new `cron_create`, `cron_list`, and `cron_delete` tools let the model schedule prompts in local time. Jobs are session-only, run only while Diffra is idle, and recurring ones expire after 7 days; the new `experimental.cron` and `experimental.cronRecurringMaxAgeDays` settings and `DIFFRA_DISABLE_CRON` control them. See [Schedule Prompts and Loops](docs/scheduled-tasks.md), which also covers time zones and daylight saving time.
18
- - Git worktrees, following Qwen Code: `--worktree [name|#N|PR-url]` runs the session in a worktree under `.diffra/worktrees/` on a new `worktree-<name>` branch (or re-attaches to an existing one, or checks out a pull request), and the new `enter_worktree` and `exit_worktree` tools let the agent work in one mid-session. Removing a worktree refuses to lose uncommitted changes, unmerged commits, or another session's worktree. The active worktree shows in the footer and survives `/resume`; the new `worktree.symlinkDirectories` and `ui.hideBuiltinWorktreeIndicator` settings tune it. See [Work in a Git Worktree](docs/worktrees.md).
19
- - LSP code intelligence, following Qwen Code, experimental and off by default: with `--experimental-lsp`, `DIFFRA_ENABLE_LSP=1`, or `tools.lspEnabled` in user settings, the language servers listed in the project's `.lsp.json` start with the session (only in an explicitly trusted folder), and the new `lsp` tool asks them for definitions, references, hover, document and workspace symbols, implementations, call hierarchy, diagnostics, and code actions. `/lsp` lists the servers. See [Use Language Servers](docs/lsp.md).
20
- - Built-in skills `review` and `batch` with the commands `/review` and `/batch`, and the `/learn` command, following Qwen Code (`builtin:skills`): `/review` reviews local changes, a pull request, or a file with parallel reviewer subagents, verified findings with failure scenarios, a verdict, `--fix`, and `--comment` to post one GitHub review; `/batch` applies one operation to many files in parallel chunks; `/learn` turns a file, URL, or text into a project skill in `.diffra/skills/learned-skill-<name>/`. See [Review, Batch, and Learn](docs/builtin-skills.md).
21
- - `diffra.getGlobalSettings()` returns the user's global settings alone, for options a project must not turn on.
22
- - A sandbox for the model's commands and edits, off by default. The `sandbox` user setting (`mode`: `read-only` or `workspace-write`, `network`, `writableRoots`) limits what the `bash` and `powershell` tools and the `write` and `edit` tools may change: the working folder, the temp folder, and `writableRoots`, with `.git`, `.diffra`, and `.agents` kept read-only. macOS enforces it with Seatbelt. Windows runs commands through `diffra-sandbox.exe`, downloaded on first use: the default `unelevated` backend blocks writes but not deletes, reads, or the network, and uses the `powershell` tool instead of `bash`; the `elevated` backend, set up once with `diffra sandbox setup`, runs commands as a separate sandbox user that the firewall keeps offline. In `default`, `auto-edit`, and `auto` mode Diffra asks before running a blocked action without the sandbox. `diffra sandbox status` shows the settings. See [Sandbox Commands and Edits](docs/sandbox.md).
23
-
24
- ### Changed
25
-
26
- - The plan-mode example extension's command is now `/plan-mode`, so it no longer collides with the built-in `/plan`.
27
- - The input box is a rounded frame with a `❯` prompt and the diffra name on top. The model, thinking level, and context usage moved into its bottom border, and the footer fits on one line while it shows. Extension editors and terminals narrower than 20 columns keep the previous layout.
28
- - The system theme keeps the accent, list bullets, custom message labels, and inline code on the logo's violet and cyan instead of the terminal palette's magenta slot, which some palettes make red.
29
- - What's New and Extension Updates use the logo gradient for their title and rules, and the rules of selectors and dialogs run from the logo's cyan to violet.
30
- - Your messages show in a graphite band, instead of blue, with a cyan-to-violet edge and the input box's `❯` prompt. Terminals that do not report their colors now get the dark or light theme's message band instead of none, so your messages no longer read like replies.
31
- - Tool calls are rows instead of colored panels: a status dot (violet while running, green or red once finished) before the title, the duration after it, and the result hanging under `⎿`. Bash and codemode show `Took` only for results stored without a duration. Tools with `renderShell: "self"` still draw their own shell; the edit tool draws a matching row.
32
-
33
- ### Fixed
34
-
35
- - On Windows, Bash commands no longer hang and fail when Git for Windows is installed outside `%ProgramFiles%` (for example `D:\Program Files\Git`). Diffra now finds Git Bash next to `git.exe` on `PATH` before falling back to the first `bash.exe` on `PATH`, which can be the WSL Store alias when WSL is not set up.
36
-
37
- ## [0.1.1] - 2026-11-20
38
-
39
- ### Changed
40
-
41
- - Automatic `fd` and `ripgrep` downloads are pinned to fd 10.5.2 and ripgrep 15.2.0 and checked against built-in SHA-256 hashes before anything is written to disk. An archive that does not match is rejected with a warning. Intel macOS now gets fd 10.5.2 instead of 10.3.0.
42
-
43
- ## [0.1.0] - 2026-11-20
44
-
45
- ### Added
46
-
47
- - First diffra release, forked from pi at [earendil-works/pi@780bf31](https://github.com/earendil-works/pi/tree/780bf31fcaeb252fa9b68df3964c735eae75bde3). Earlier history is in [pi's changelog for this package](https://github.com/earendil-works/pi/blob/780bf31fcaeb252fa9b68df3964c735eae75bde3/packages/coding-agent/CHANGELOG.md).
1
+ # Changelog
2
+
3
+ ## [Unreleased]
4
+
5
+ ## [0.1.4] - 2026-11-22
6
+
7
+ ### Added
8
+
9
+ - The SDK exports `builtInExtensions`, the extensions the CLI loads (approval modes, hooks, MCP, subagents, todo, memory, goals, loops and the others), so an SDK host can give its sessions the CLI's behavior by passing them to `extensionFactories`. It also exports `theme`, the current theme after `initTheme()`, for hosts that implement `ExtensionUIContext`.
10
+
11
+ ## [0.1.3] - 2026-11-22
12
+
13
+ ### Added
14
+
15
+ - `ExtensionMode` has a `"desktop"` value for SDK hosts that show extension UI in a desktop app, such as Diffra Desktop; bind it with `session.bindExtensions({ uiContext, mode: "desktop" })`. `ctx.hasUI` is true there, and as in RPC mode `custom()` returns `undefined` and component factories are ignored.
16
+
17
+ ## [0.1.2] - 2026-11-21
18
+
19
+ ### Added
20
+
21
+ - `todo_write`, a built-in tool (`builtin:todo`) for a user-visible task list, following Qwen Code's `todo_write`. It is off by default; enable it with `"defaultTools": ["+todo_write"]` or `--tools +todo_write`. Todos have an id, content, a status, and optional `blockedBy` dependencies. The list is stored in the session, so it survives resume and follows `/tree` and `/fork`, and a "Current tasks" panel shows unfinished todos during a run.
22
+ - `web_fetch` (`builtin:web-fetch`, active by default) fetches a URL, converts HTML to Markdown with turndown, and answers a prompt about the page with the new `fastModel` setting or the session model, following Qwen Code's `web_fetch`. Redirects to other hosts are reported instead of followed, binary content is saved to a temporary file (with a PDF's text extracted when `pdftotext` is installed), and pages are cached for 15 minutes. See [Fetch and Search the Web](docs/web-tools.md).
23
+ - `web_search` (`builtin:web-search`) searches through a DashScope search agent, following Qwen Code. It turns on when the session model is on a DashScope-compatible endpoint, or with the new `webSearch` setting or `WEB_SEARCH_*` environment variables; when it was turned on but cannot work, Diffra warns what is missing.
24
+ - Approval modes, following Qwen Code: `plan` (read-only, with the `exit_plan_mode` tool to approve a plan), `default` (ask before edits and commands), `auto-edit`, `auto` (a classifier model decides, with `permissions.autoMode` hints), and `yolo`. The default stays `yolo`, so nothing asks unless you switch. Switch with `/approval-mode`, `/plan`, `alt+m` (`app.approvalMode.cycle`), `--approval-mode`, or the `approvalMode` setting; "always allow" answers last for the session. Extensions get `diffra.getApprovalMode()`, `diffra.setApprovalMode()`, and the `approval_mode_change` event. See [Approve Tool Calls](docs/approval-modes.md).
25
+ - Subagents, following Qwen Code: the `agent` tool delegates a task to an agent with its own prompt, tools, and context, in the foreground or (by default) in the background with a `<task-notification>` when it finishes. Agents are defined in `.diffra/agents/` and the agent directory's `agents/`, with `general-purpose` and `Explore` built in; `/agents` creates and manages them, `/tasks` and `task_stop` list and cancel background ones, and the new `agents` setting controls background default, nesting depth, and parallel runs. See [Delegate to Subagents](docs/subagents.md).
26
+ - Hooks, following Qwen Code: command, http, and prompt hooks in the `hooks` setting run on `PreToolUse` (block, ask, or replace the input), `PostToolUse`, `PostToolUseFailure`, `UserPromptSubmit` (block or add context), `Stop` (keep the agent working), `SessionStart`, `SessionEnd`, `StopFailure`, `SubagentStart`, `SubagentStop`, `PreCompact`, `PostCompact`, and `FileChanged`, with Qwen Code's JSON input and output and exit-code contract. Hooks of user and project settings add up; `disableAllHooks` turns them off and `/hooks` lists them. See [Run Hooks on Events](docs/hooks.md).
27
+ - Auto memory, following Qwen Code and on by default: memories live as Markdown files in a user directory and a per-repository project directory under the agent directory, with a rebuilt `MEMORY.md` index. Each run gets the memory policy and indexes in its system prompt plus memories that match the prompt; after a run a background agent saves durable facts you stated, and a daily background dream consolidates them. `/memory`, `/remember`, `/forget`, and `/dream` manage it; the new `memory` setting turns the background agents off. See [Keep Auto Memory](docs/memory.md).
28
+ - Goals, following Qwen Code: `/goal <objective>` keeps the agent working across turns until it proposes with the `update_goal` tool that the Goal is complete or blocked and an independent verifier model accepts the proposal from the evidence of the Goal's turns. `/goal edit`, `pause`, `resume`, and `clear` control it; Escape, three idle turns, or a failure pause it, and the new `goals` setting sets token, turn, and active-time budgets, after which the Goal gets one hand-off turn and stops. Goal state is recorded in the session and shown in the footer and as transcript cards. See [Work Toward a Goal](docs/goals.md).
29
+ - Scheduled tasks and `/loop`, following Qwen Code and on by default: `/loop 5m <prompt>` (or `<prompt> every 5m`) runs a prompt now and on an even cron schedule, `/loop <prompt>` lets the model pace follow-up checks with the new `loop_wakeup` tool, and a bare `/loop` keeps the conversation's work moving autonomously; `/loop list` and `/loop clear` manage them, and loops can work a `loop.md` task list. The new `cron_create`, `cron_list`, and `cron_delete` tools let the model schedule prompts in local time. Jobs are session-only, run only while Diffra is idle, and recurring ones expire after 7 days; the new `experimental.cron` and `experimental.cronRecurringMaxAgeDays` settings and `DIFFRA_DISABLE_CRON` control them. See [Schedule Prompts and Loops](docs/scheduled-tasks.md), which also covers time zones and daylight saving time.
30
+ - Git worktrees, following Qwen Code: `--worktree [name|#N|PR-url]` runs the session in a worktree under `.diffra/worktrees/` on a new `worktree-<name>` branch (or re-attaches to an existing one, or checks out a pull request), and the new `enter_worktree` and `exit_worktree` tools let the agent work in one mid-session. Removing a worktree refuses to lose uncommitted changes, unmerged commits, or another session's worktree. The active worktree shows in the footer and survives `/resume`; the new `worktree.symlinkDirectories` and `ui.hideBuiltinWorktreeIndicator` settings tune it. See [Work in a Git Worktree](docs/worktrees.md).
31
+ - LSP code intelligence, following Qwen Code, experimental and off by default: with `--experimental-lsp`, `DIFFRA_ENABLE_LSP=1`, or `tools.lspEnabled` in user settings, the language servers listed in the project's `.lsp.json` start with the session (only in an explicitly trusted folder), and the new `lsp` tool asks them for definitions, references, hover, document and workspace symbols, implementations, call hierarchy, diagnostics, and code actions. `/lsp` lists the servers. See [Use Language Servers](docs/lsp.md).
32
+ - Built-in skills `review` and `batch` with the commands `/review` and `/batch`, and the `/learn` command, following Qwen Code (`builtin:skills`): `/review` reviews local changes, a pull request, or a file with parallel reviewer subagents, verified findings with failure scenarios, a verdict, `--fix`, and `--comment` to post one GitHub review; `/batch` applies one operation to many files in parallel chunks; `/learn` turns a file, URL, or text into a project skill in `.diffra/skills/learned-skill-<name>/`. See [Review, Batch, and Learn](docs/builtin-skills.md).
33
+ - `diffra.getGlobalSettings()` returns the user's global settings alone, for options a project must not turn on.
34
+ - A sandbox for the model's commands and edits, off by default. The `sandbox` user setting (`mode`: `read-only` or `workspace-write`, `network`, `writableRoots`) limits what the `bash` and `powershell` tools and the `write` and `edit` tools may change: the working folder, the temp folder, and `writableRoots`, with `.git`, `.diffra`, and `.agents` kept read-only. macOS enforces it with Seatbelt. Windows runs commands through `diffra-sandbox.exe`, downloaded on first use: the default `unelevated` backend blocks writes but not deletes, reads, or the network, and uses the `powershell` tool instead of `bash`; the `elevated` backend, set up once with `diffra sandbox setup`, runs commands as a separate sandbox user that the firewall keeps offline. In `default`, `auto-edit`, and `auto` mode Diffra asks before running a blocked action without the sandbox. `diffra sandbox status` shows the settings. See [Sandbox Commands and Edits](docs/sandbox.md).
35
+
36
+ ### Changed
37
+
38
+ - The plan-mode example extension's command is now `/plan-mode`, so it no longer collides with the built-in `/plan`.
39
+ - The input box is a rounded frame with a `❯` prompt and the diffra name on top. The model, thinking level, and context usage moved into its bottom border, and the footer fits on one line while it shows. Extension editors and terminals narrower than 20 columns keep the previous layout.
40
+ - The system theme keeps the accent, list bullets, custom message labels, and inline code on the logo's violet and cyan instead of the terminal palette's magenta slot, which some palettes make red.
41
+ - What's New and Extension Updates use the logo gradient for their title and rules, and the rules of selectors and dialogs run from the logo's cyan to violet.
42
+ - Your messages show in a graphite band, instead of blue, with a cyan-to-violet edge and the input box's `❯` prompt. Terminals that do not report their colors now get the dark or light theme's message band instead of none, so your messages no longer read like replies.
43
+ - Tool calls are rows instead of colored panels: a status dot (violet while running, green or red once finished) before the title, the duration after it, and the result hanging under `⎿`. Bash and codemode show `Took` only for results stored without a duration. Tools with `renderShell: "self"` still draw their own shell; the edit tool draws a matching row.
44
+
45
+ ### Fixed
46
+
47
+ - On Windows, Bash commands no longer hang and fail when Git for Windows is installed outside `%ProgramFiles%` (for example `D:\Program Files\Git`). Diffra now finds Git Bash next to `git.exe` on `PATH` before falling back to the first `bash.exe` on `PATH`, which can be the WSL Store alias when WSL is not set up.
48
+
49
+ ## [0.1.1] - 2026-11-20
50
+
51
+ ### Changed
52
+
53
+ - Automatic `fd` and `ripgrep` downloads are pinned to fd 10.5.2 and ripgrep 15.2.0 and checked against built-in SHA-256 hashes before anything is written to disk. An archive that does not match is rejected with a warning. Intel macOS now gets fd 10.5.2 instead of 10.3.0.
54
+
55
+ ## [0.1.0] - 2026-11-20
56
+
57
+ ### Added
58
+
59
+ - First diffra release, forked from pi at [earendil-works/pi@780bf31](https://github.com/earendil-works/pi/tree/780bf31fcaeb252fa9b68df3964c735eae75bde3). Earlier history is in [pi's changelog for this package](https://github.com/earendil-works/pi/blob/780bf31fcaeb252fa9b68df3964c735eae75bde3/packages/coding-agent/CHANGELOG.md).
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{ANTHROPIC_FEDERATION_RULE_ID_ENV,ANTHROPIC_IDENTITY_TOKEN_FILE_ENV,ANTHROPIC_ORGANIZATION_ID_ENV,ANTHROPIC_SERVICE_ACCOUNT_ID_ENV,ANTHROPIC_WORKSPACE_ID_ENV}from"./chunk-INODY4DR.js";import{registerSessionResourceCleanup}from"./chunk-ZG74NES2.js";import{applyOpenRouterReportedCost,isOpenRouterModel}from"./chunk-P7FPUEYA.js";import{buildCopilotDynamicHeaders,hasCopilotVisionInput}from"./chunk-PGXDEOVV.js";import{Anthropic}from"./chunk-7CBJINYJ.js";import{shortHash}from"./chunk-PJACZCIR.js";import{adjustMaxTokensForThinking,buildBaseOptions,clampMaxTokensToContext,getJsonSchemaToolParameters,prefersJsonSchemaStrictSampling,resolveJsonSchemaStrictSampling,splitErrorToolResultImages,transformMessages}from"./chunk-SMYD2SB5.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{retryProviderRequest}from"./chunk-PMRZO46Y.js";import{withCauseDetail}from"./chunk-E3MJ4MPN.js";import{headersToRecord}from"./chunk-UTB4DTYQ.js";import{ToolCallArgumentsStream,parseJsonWithRepair}from"./chunk-FFMDRXC4.js";import{getProviderEnvValue}from"./chunk-7DDKXS2Q.js";import{calculateCost,getCurrentTools,getInitialSystemMessage,resolveTranscript}from"./chunk-3MKQN3ZR.js";import{AssistantMessageEventStream,appendAssistantMessageDiagnostic}from"./chunk-LPXNMA2W.js";import{getIdentityHeaders,getSystemMessageText,renderSystemMessageUpdate}from"./chunk-6L2FT6AE.js";import"./chunk-JXWJOIH4.js";var STRICT_TOOL_LIMIT_ERROR_MESSAGES=["The compiled grammar is too large","Too many strict tools (","Schemas contains too many parameters with union types ("];function isStrictToolLimitErrorMessage(message){return STRICT_TOOL_LIMIT_ERROR_MESSAGES.some(limitMessage=>message.includes(limitMessage))}var sessionsOverStrictToolLimits=new Set,MAX_SESSIONS_OVER_STRICT_TOOL_LIMITS=1e4;function markStrictToolLimitsExceeded(sessionId){if(sessionId!==void 0&&(sessionsOverStrictToolLimits.add(sessionId),sessionsOverStrictToolLimits.size>MAX_SESSIONS_OVER_STRICT_TOOL_LIMITS)){let oldest=sessionsOverStrictToolLimits.values().next().value;oldest!==void 0&&sessionsOverStrictToolLimits.delete(oldest)}}function hasExceededStrictToolLimits(sessionId){return sessionId!==void 0&&sessionsOverStrictToolLimits.has(sessionId)}registerSessionResourceCleanup(sessionId=>{sessionId?sessionsOverStrictToolLimits.delete(sessionId):sessionsOverStrictToolLimits.clear()});function resolveCacheRetention(cacheRetention,env){return cacheRetention||(getProviderEnvValue("DIFFRA_CACHE_RETENTION",env)==="long"?"long":"short")}function getCacheControl(model,cacheRetention,env){let retention=resolveCacheRetention(cacheRetention,env);if(retention==="none")return{retention};let ttl=retention==="long"&&getAnthropicCompat(model).supportsLongCacheRetention?"1h":void 0;return{retention,cacheControl:{type:"ephemeral",...ttl&&{ttl}}}}var claudeCodeVersion="2.1.322",claudeCodeTools=["Read","Write","Edit","Bash","Grep","Glob","AskUserQuestion","EnterPlanMode","ExitPlanMode","KillShell","NotebookEdit","Skill","Task","TaskOutput","TodoWrite","WebFetch","WebSearch"],ccToolLookup=new Map(claudeCodeTools.map(t=>[t.toLowerCase(),t])),toClaudeCodeName=name=>ccToolLookup.get(name.toLowerCase())??name,fromClaudeCodeName=(name,tools)=>{if(tools&&tools.length>0){let lowerName=name.toLowerCase(),matchedTool=tools.find(tool=>tool.name.toLowerCase()===lowerName);if(matchedTool)return matchedTool.name}return name};function convertImageBlock(image){return{type:"image",source:{type:"base64",media_type:image.mimeType,data:image.data}}}function convertContentBlocks(content){if(!content.some(c=>c.type==="image"))return sanitizeSurrogates(content.map(c=>c.text).join(`
2
+ import{ANTHROPIC_FEDERATION_RULE_ID_ENV,ANTHROPIC_IDENTITY_TOKEN_FILE_ENV,ANTHROPIC_ORGANIZATION_ID_ENV,ANTHROPIC_SERVICE_ACCOUNT_ID_ENV,ANTHROPIC_WORKSPACE_ID_ENV}from"./chunk-INODY4DR.js";import{registerSessionResourceCleanup}from"./chunk-ZG74NES2.js";import{applyOpenRouterReportedCost,isOpenRouterModel}from"./chunk-P7FPUEYA.js";import{buildCopilotDynamicHeaders,hasCopilotVisionInput}from"./chunk-PGXDEOVV.js";import{Anthropic}from"./chunk-7CBJINYJ.js";import{shortHash}from"./chunk-PJACZCIR.js";import{adjustMaxTokensForThinking,buildBaseOptions,clampMaxTokensToContext,getJsonSchemaToolParameters,prefersJsonSchemaStrictSampling,resolveJsonSchemaStrictSampling,splitErrorToolResultImages,transformMessages}from"./chunk-IDYI4NPC.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{retryProviderRequest}from"./chunk-PMRZO46Y.js";import{withCauseDetail}from"./chunk-GNFHDZLP.js";import{headersToRecord}from"./chunk-UTB4DTYQ.js";import{ToolCallArgumentsStream,parseJsonWithRepair}from"./chunk-FFMDRXC4.js";import{getProviderEnvValue}from"./chunk-7DDKXS2Q.js";import{calculateCost,getCurrentTools,getInitialSystemMessage,resolveTranscript}from"./chunk-YDKIXS42.js";import{AssistantMessageEventStream,appendAssistantMessageDiagnostic}from"./chunk-LPXNMA2W.js";import{getIdentityHeaders,getSystemMessageText,renderSystemMessageUpdate}from"./chunk-ZW3S4FQY.js";import"./chunk-JXWJOIH4.js";var STRICT_TOOL_LIMIT_ERROR_MESSAGES=["The compiled grammar is too large","Too many strict tools (","Schemas contains too many parameters with union types ("];function isStrictToolLimitErrorMessage(message){return STRICT_TOOL_LIMIT_ERROR_MESSAGES.some(limitMessage=>message.includes(limitMessage))}var sessionsOverStrictToolLimits=new Set,MAX_SESSIONS_OVER_STRICT_TOOL_LIMITS=1e4;function markStrictToolLimitsExceeded(sessionId){if(sessionId!==void 0&&(sessionsOverStrictToolLimits.add(sessionId),sessionsOverStrictToolLimits.size>MAX_SESSIONS_OVER_STRICT_TOOL_LIMITS)){let oldest=sessionsOverStrictToolLimits.values().next().value;oldest!==void 0&&sessionsOverStrictToolLimits.delete(oldest)}}function hasExceededStrictToolLimits(sessionId){return sessionId!==void 0&&sessionsOverStrictToolLimits.has(sessionId)}registerSessionResourceCleanup(sessionId=>{sessionId?sessionsOverStrictToolLimits.delete(sessionId):sessionsOverStrictToolLimits.clear()});function resolveCacheRetention(cacheRetention,env){return cacheRetention||(getProviderEnvValue("DIFFRA_CACHE_RETENTION",env)==="long"?"long":"short")}function getCacheControl(model,cacheRetention,env){let retention=resolveCacheRetention(cacheRetention,env);if(retention==="none")return{retention};let ttl=retention==="long"&&getAnthropicCompat(model).supportsLongCacheRetention?"1h":void 0;return{retention,cacheControl:{type:"ephemeral",...ttl&&{ttl}}}}var claudeCodeVersion="2.1.322",claudeCodeTools=["Read","Write","Edit","Bash","Grep","Glob","AskUserQuestion","EnterPlanMode","ExitPlanMode","KillShell","NotebookEdit","Skill","Task","TaskOutput","TodoWrite","WebFetch","WebSearch"],ccToolLookup=new Map(claudeCodeTools.map(t=>[t.toLowerCase(),t])),toClaudeCodeName=name=>ccToolLookup.get(name.toLowerCase())??name,fromClaudeCodeName=(name,tools)=>{if(tools&&tools.length>0){let lowerName=name.toLowerCase(),matchedTool=tools.find(tool=>tool.name.toLowerCase()===lowerName);if(matchedTool)return matchedTool.name}return name};function convertImageBlock(image){return{type:"image",source:{type:"base64",media_type:image.mimeType,data:image.data}}}function convertContentBlocks(content){if(!content.some(c=>c.type==="image"))return sanitizeSurrogates(content.map(c=>c.text).join(`
3
3
  `));let blocks=content.map(block=>block.type==="text"?{type:"text",text:sanitizeSurrogates(block.text)}:convertImageBlock(block));return blocks.some(b=>b.type==="text")||blocks.unshift({type:"text",text:"(see attached image)"}),blocks}var FINE_GRAINED_TOOL_STREAMING_BETA="fine-grained-tool-streaming-2025-05-14",INTERLEAVED_THINKING_BETA="interleaved-thinking-2025-05-14",SERVER_SIDE_FALLBACK_BETA="server-side-fallback-2026-07-01",MID_CONVERSATION_OUTPUT_CONFIG_BETA="mid-conversation-output-config-2026-07-01",THINKING_BINDING_CONTROLS_BETA="thinking-binding-controls-2026-08-01",INLINE_TOOLS_BETA="inline-tools-2026-09-15",MESSAGE_THREADS_BETA="message-threads-2026-08-12",DEFERRED_TOOL_PLACEHOLDER={name:"__pi_deferred_placeholder__",description:"Reserved placeholder. Never available. Never call this.",input_schema:{type:"object",properties:{},required:[]},defer_loading:!0};function shouldUseServerSideFallbackBeta(model){return(model.compat?.allowedFallbackModels?.length??0)>0}function getAnthropicCompat(model){let isOpenRouter=model.provider==="openrouter"||model.baseUrl.includes("openrouter.ai");return{supportsEagerToolInputStreaming:model.compat?.supportsEagerToolInputStreaming??!0,supportsLongCacheRetention:model.compat?.supportsLongCacheRetention??!0,sendSessionAffinityHeaders:model.compat?.sendSessionAffinityHeaders??isOpenRouter,sessionAffinityFormat:model.compat?.sessionAffinityFormat??(isOpenRouter?"openrouter":void 0),supportsCacheControlOnTools:model.compat?.supportsCacheControlOnTools??!0,supportsTemperature:model.compat?.supportsTemperature??!0,allowEmptySignature:model.compat?.allowEmptySignature??!1,supportsStrictTools:model.compat?.supportsStrictTools??!1,supportsMidConvoSystemMessages:model.compat?.supportsMidConvoSystemMessages??!1,supportsMidConvoToolChanges:model.compat?.supportsMidConvoToolChanges??!1,supportsMessageThreads:model.compat?.supportsMessageThreads??model.baseUrl.includes("api.anthropic.com")}}var threadState=new Map,MAX_THREAD_STATE_ENTRIES=1e4,NEW_THREAD_ERRORS=new Set(["thread_not_found","thread_already_continued","thread_continue_in_flight","thread_fingerprint_mismatch"]);function setThreadState(sessionId,value){if(threadState.delete(sessionId),threadState.set(sessionId,value),threadState.size>MAX_THREAD_STATE_ENTRIES){let oldest=threadState.keys().next().value;oldest!==void 0&&threadState.delete(oldest)}}registerSessionResourceCleanup(sessionId=>{sessionId?threadState.delete(sessionId):threadState.clear()});function hashThreadPrefix(model,params,messages){let{system,tools,thinking,output_config,tool_choice,betas,fallbacks}=params,settings=JSON.stringify([model.provider,model.baseUrl,params.model,system,tools,thinking,output_config,tool_choice,betas,fallbacks]),conversation=JSON.stringify(messages,(key,value)=>{if(key!=="cache_control")return key==="content"&&typeof value=="string"?[{type:"text",text:value}]:value});return shortHash(settings+conversation)}function createThreadRequest(sessionId,params){return{sessionId,body:{...params,thread:{type:"create"}}}}function prepareThreadRequest(model,sessionId,params){let state=threadState.get(sessionId);if(state!=="off"){if(state!==void 0&&params.messages.length>state.prefixCount&&hashThreadPrefix(model,params,params.messages.slice(0,state.prefixCount))===state.prefixHash){threadState.delete(sessionId);let{system:_system,tools:_tools,...rest}=params;return{body:{...rest,messages:params.messages.slice(state.prefixCount),thread:{type:"continue",previous_message_id:state.replyId}},sessionId}}return createThreadRequest(sessionId,params)}}function getThreadErrorCode(error){let code=error.error?.error?.details?.error_code;return typeof code=="string"?code:void 0}async function sendThreadRequest(thread,params,send,output,signal){try{return{response:await send(thread.body),thread}}catch(error){if(signal?.aborted||!(error instanceof Anthropic.APIError))throw error;let errorCode=getThreadErrorCode(error),startNewThread=errorCode!==void 0&&NEW_THREAD_ERRORS.has(errorCode),threadsUnsupported=errorCode==="thread_unsupported_request"||errorCode===void 0&&error.status===400&&error.message.includes("thread");if(!startNewThread&&!threadsUnsupported)throw error;if(appendAssistantMessageDiagnostic(output,{type:"anthropic_thread_fallback",timestamp:Date.now(),error:{message:error.message},details:{reason:errorCode??String(error.status)}}),startNewThread){let created=createThreadRequest(thread.sessionId,params);return{response:await send(created.body),thread:created}}let response=await send(params);return setThreadState(thread.sessionId,"off"),{response,thread:void 0}}}function recordThreadReply(model,thread,params,output,isOAuth,allowEmptySignature){if(output.responseId===void 0||output.responseModel!==void 0)return;let reply=convertMessages(transformMessages([output],model,normalizeToolCallId),isOAuth,void 0,allowEmptySignature).messages.filter(message=>message.role==="assistant"),prefix=[...params.messages,...reply];setThreadState(thread.sessionId,{prefixCount:prefix.length,prefixHash:hashThreadPrefix(model,params,prefix),replyId:output.responseId})}function mergeHeaders(...headerSources){let merged={};for(let headers of headerSources)headers&&Object.assign(merged,headers);return merged}function hasHeader(headers,name){if(!headers)return!1;let expected=name.toLowerCase();for(let[key,value]of Object.entries(headers))if(key.toLowerCase()===expected&&value!==null&&value.trim().length>0)return!0;return!1}function hasRequestAuth(apiKey,headers){return!!apiKey||hasHeader(headers,"authorization")||hasHeader(headers,"x-api-key")||hasHeader(headers,"cf-aig-authorization")}function assertRequestAuth(provider,apiKey,headers){if(!hasRequestAuth(apiKey,headers))throw new Error(`No API key for provider: ${provider}`)}var DiffraAnthropic=class extends Anthropic{_shouldResolveDefaultCredentials(){return!1}};function getAnthropicFederation(model,apiKey,headers,env){if(model.provider!=="anthropic"||hasRequestAuth(apiKey,headers))return;let federationRuleId=getProviderEnvValue(ANTHROPIC_FEDERATION_RULE_ID_ENV,env),organizationId=getProviderEnvValue(ANTHROPIC_ORGANIZATION_ID_ENV,env),identityTokenFile=getProviderEnvValue(ANTHROPIC_IDENTITY_TOKEN_FILE_ENV,env);if(!(!federationRuleId||!organizationId||!identityTokenFile))return{organization_id:organizationId,workspace_id:getProviderEnvValue(ANTHROPIC_WORKSPACE_ID_ENV,env),authentication:{type:"oidc_federation",federation_rule_id:federationRuleId,service_account_id:getProviderEnvValue(ANTHROPIC_SERVICE_ACCOUNT_ID_ENV,env),identity_token:{source:"file",path:identityTokenFile}}}}var federationClient,ANTHROPIC_MESSAGE_EVENTS=new Set(["message_start","message_delta","message_stop","content_block_start","content_block_delta","content_block_stop"]);function flushSseEvent(state){if(!state.event&&state.data.length===0)return null;let event={event:state.event,data:state.data.join(`
4
4
  `),raw:[...state.raw]};return state.event=null,state.data=[],state.raw=[],event}function decodeSseLine(line,state){if(line==="")return flushSseEvent(state);if(state.raw.push(line),line.startsWith(":"))return null;let delimiterIndex=line.indexOf(":"),fieldName=delimiterIndex===-1?line:line.slice(0,delimiterIndex),value=delimiterIndex===-1?"":line.slice(delimiterIndex+1);return value.startsWith(" ")&&(value=value.slice(1)),fieldName==="event"?state.event=value:fieldName==="data"&&state.data.push(value),null}function nextLineBreakIndex(text){let carriageReturnIndex=text.indexOf("\r"),newlineIndex=text.indexOf(`
5
5
  `);return carriageReturnIndex===-1?newlineIndex:newlineIndex===-1?carriageReturnIndex:Math.min(carriageReturnIndex,newlineIndex)}function consumeLine(text){let lineBreakIndex=nextLineBreakIndex(text);if(lineBreakIndex===-1)return null;let nextIndex=lineBreakIndex+1;return text[lineBreakIndex]==="\r"&&text[nextIndex]===`
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{convertResponsesMessages,convertResponsesTools,getResponsesToolSupport,processResponsesStream}from"./chunk-MJRIJM22.js";import{resolveAzureConfig,resolveDeploymentName}from"./chunk-TMTOQ7H7.js";import{clampOpenAIPromptCacheKey}from"./chunk-PRRNXB7S.js";import{AzureOpenAI}from"./chunk-LWG2CUTI.js";import"./chunk-PJACZCIR.js";import{buildBaseOptions,createGrammarToolInputProperties,resolveSamplingParams}from"./chunk-SMYD2SB5.js";import"./chunk-L2ZPNLYD.js";import{retryProviderRequest}from"./chunk-PMRZO46Y.js";import{formatProviderError,normalizeProviderError}from"./chunk-E3MJ4MPN.js";import{headersToRecord}from"./chunk-UTB4DTYQ.js";import"./chunk-FFMDRXC4.js";import"./chunk-7DDKXS2Q.js";import{clampThinkingLevel,getDeclaredTools,resolveTranscript,resolveTranscriptTools}from"./chunk-3MKQN3ZR.js";import{AssistantMessageEventStream}from"./chunk-LPXNMA2W.js";import{getIdentityHeaders}from"./chunk-6L2FT6AE.js";import"./chunk-JXWJOIH4.js";var AZURE_TOOL_CALL_PROVIDERS=new Set(["openai","openai-codex","opencode","azure"]),OPENAI_RESPONSES_MIN_OUTPUT_TOKENS=16;function formatAzureOpenAIError(error){return formatProviderError(normalizeProviderError(error),"Azure OpenAI API error")}var stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=resolveTranscript(context,model.compat?.supportsMidConvoSystemMessages);return(async()=>{let deploymentName=resolveDeploymentName(model,options),output={role:"assistant",content:[],api:"azure-openai-responses",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let client=createClient(model,apiKey,options),grammarToolInputProperties=createGrammarToolInputProperties(getDeclaredTools(normalizedContext.messages),model.compat?.supportsOpenAIGrammarTools??!1),params=buildParams(model,normalizedContext,options,deploymentName,grammarToolInputProperties),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let requestOptions={...options?.signal?{signal:options.signal}:{},...options?.timeoutMs!==void 0?{timeout:options.timeoutMs}:{},maxRetries:0},{data:openaiStream,response}=await retryProviderRequest(()=>client.responses.create(params,requestOptions).withResponse(),{maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,signal:options?.signal});if(await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),stream2.push({type:"start",partial:output}),await processResponsesStream(openaiStream,output,stream2,model,{onProviderStreamEvent:options?.onProviderStreamEvent,grammarToolInputProperties}),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Azure OpenAI Responses stream ended without a stop reason");if(output.stopReason==="aborted"||output.stopReason==="error")throw new Error(output.errorMessage||"An unknown error occurred");stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatAzureOpenAIError(error),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let base={...buildBaseOptions(model,context,options,apiKey),toolChoice:options?.toolChoice},clampedReasoning=options?.reasoning?clampThinkingLevel(model,options.reasoning):void 0;return stream(model,context,{...base,reasoningEffort:clampedReasoning==="off"?void 0:clampedReasoning})};function createClient(model,apiKey,options){let headers={...getIdentityHeaders(model,options?.identity),...model.headers};options?.headers&&Object.assign(headers,options.headers);let{baseUrl,apiVersion}=resolveAzureConfig(model,options);return new AzureOpenAI({apiKey,apiVersion,dangerouslyAllowBrowser:!0,fetch:options?.fetch,defaultHeaders:headers,baseURL:baseUrl})}function buildParams(model,context,options,deploymentName,grammarToolInputProperties=createGrammarToolInputProperties(getDeclaredTools(context.messages),model.compat?.supportsOpenAIGrammarTools??!1)){let supportsAdditionalTools=model.compat?.supportsAdditionalTools??!1,supportsToolSearch=model.compat?.supportsToolSearch??!1,transcriptTools=resolveTranscriptTools(context.messages,getResponsesToolSupport({supportsMidConvoSystemMessages:model.compat?.supportsMidConvoSystemMessages??!1,supportsAdditionalTools,supportsToolSearch})),messages=convertResponsesMessages(model,context,AZURE_TOOL_CALL_PROVIDERS,{grammarToolInputProperties,supportsMidConvoSystemMessages:model.compat?.supportsMidConvoSystemMessages??!1,supportsAdditionalTools,supportsToolSearch,toolOptions:{supportsStrictMode:model.compat?.supportsStrictMode??!0,supportsOpenAIGrammarTools:model.compat?.supportsOpenAIGrammarTools??!1}}),params={model:deploymentName,input:messages,stream:!0,prompt_cache_key:model.compat?.promptCacheKeyMode==="disabled"?void 0:clampOpenAIPromptCacheKey(options?.sessionId),store:!1};options?.maxTokens&&(params.max_output_tokens=Math.max(options.maxTokens,OPENAI_RESPONSES_MIN_OUTPUT_TOKENS)),options?.temperature!==void 0&&(params.temperature=options?.temperature),transcriptTools.requestTools.length>0&&(params.tools=convertResponsesTools(transcriptTools.requestTools,{supportsStrictMode:model.compat?.supportsStrictMode??!0,supportsOpenAIGrammarTools:model.compat?.supportsOpenAIGrammarTools??!1})),options?.toolChoice!==void 0&&(params.tool_choice=options.toolChoice);let reasoningEffort=options?.reasoningEffort??(options?.reasoningSummary?"medium":void 0);if(model.reasoning)if(reasoningEffort){let effort=options?.reasoningEffort?model.thinkingLevelMap?.[options.reasoningEffort]??options.reasoningEffort:reasoningEffort;params.reasoning={effort,summary:options?.reasoningSummary||"auto"},params.include=["reasoning.encrypted_content"]}else model.thinkingLevelMap?.off!==null&&(params.reasoning={effort:model.thinkingLevelMap?.off??"none"});let samplingParams=resolveSamplingParams(model,reasoningEffort??"off",options?.samplingParams);return samplingParams&&Object.assign(params,samplingParams),params}export{stream,streamSimple};
2
+ import{convertResponsesMessages,convertResponsesTools,getResponsesToolSupport,processResponsesStream}from"./chunk-7QEHJ36J.js";import{resolveAzureConfig,resolveDeploymentName}from"./chunk-TMTOQ7H7.js";import{clampOpenAIPromptCacheKey}from"./chunk-PRRNXB7S.js";import{AzureOpenAI}from"./chunk-LWG2CUTI.js";import"./chunk-PJACZCIR.js";import{buildBaseOptions,createGrammarToolInputProperties,resolveSamplingParams}from"./chunk-IDYI4NPC.js";import"./chunk-L2ZPNLYD.js";import{retryProviderRequest}from"./chunk-PMRZO46Y.js";import{formatProviderError,normalizeProviderError}from"./chunk-GNFHDZLP.js";import{headersToRecord}from"./chunk-UTB4DTYQ.js";import"./chunk-FFMDRXC4.js";import"./chunk-7DDKXS2Q.js";import{clampThinkingLevel,getDeclaredTools,resolveTranscript,resolveTranscriptTools}from"./chunk-YDKIXS42.js";import{AssistantMessageEventStream}from"./chunk-LPXNMA2W.js";import{getIdentityHeaders}from"./chunk-ZW3S4FQY.js";import"./chunk-JXWJOIH4.js";var AZURE_TOOL_CALL_PROVIDERS=new Set(["openai","openai-codex","opencode","azure"]),OPENAI_RESPONSES_MIN_OUTPUT_TOKENS=16;function formatAzureOpenAIError(error){return formatProviderError(normalizeProviderError(error),"Azure OpenAI API error")}var stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=resolveTranscript(context,model.compat?.supportsMidConvoSystemMessages);return(async()=>{let deploymentName=resolveDeploymentName(model,options),output={role:"assistant",content:[],api:"azure-openai-responses",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let client=createClient(model,apiKey,options),grammarToolInputProperties=createGrammarToolInputProperties(getDeclaredTools(normalizedContext.messages),model.compat?.supportsOpenAIGrammarTools??!1),params=buildParams(model,normalizedContext,options,deploymentName,grammarToolInputProperties),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let requestOptions={...options?.signal?{signal:options.signal}:{},...options?.timeoutMs!==void 0?{timeout:options.timeoutMs}:{},maxRetries:0},{data:openaiStream,response}=await retryProviderRequest(()=>client.responses.create(params,requestOptions).withResponse(),{maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,signal:options?.signal});if(await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),stream2.push({type:"start",partial:output}),await processResponsesStream(openaiStream,output,stream2,model,{onProviderStreamEvent:options?.onProviderStreamEvent,grammarToolInputProperties}),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Azure OpenAI Responses stream ended without a stop reason");if(output.stopReason==="aborted"||output.stopReason==="error")throw new Error(output.errorMessage||"An unknown error occurred");stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatAzureOpenAIError(error),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let base={...buildBaseOptions(model,context,options,apiKey),toolChoice:options?.toolChoice},clampedReasoning=options?.reasoning?clampThinkingLevel(model,options.reasoning):void 0;return stream(model,context,{...base,reasoningEffort:clampedReasoning==="off"?void 0:clampedReasoning})};function createClient(model,apiKey,options){let headers={...getIdentityHeaders(model,options?.identity),...model.headers};options?.headers&&Object.assign(headers,options.headers);let{baseUrl,apiVersion}=resolveAzureConfig(model,options);return new AzureOpenAI({apiKey,apiVersion,dangerouslyAllowBrowser:!0,fetch:options?.fetch,defaultHeaders:headers,baseURL:baseUrl})}function buildParams(model,context,options,deploymentName,grammarToolInputProperties=createGrammarToolInputProperties(getDeclaredTools(context.messages),model.compat?.supportsOpenAIGrammarTools??!1)){let supportsAdditionalTools=model.compat?.supportsAdditionalTools??!1,supportsToolSearch=model.compat?.supportsToolSearch??!1,transcriptTools=resolveTranscriptTools(context.messages,getResponsesToolSupport({supportsMidConvoSystemMessages:model.compat?.supportsMidConvoSystemMessages??!1,supportsAdditionalTools,supportsToolSearch})),messages=convertResponsesMessages(model,context,AZURE_TOOL_CALL_PROVIDERS,{grammarToolInputProperties,supportsMidConvoSystemMessages:model.compat?.supportsMidConvoSystemMessages??!1,supportsAdditionalTools,supportsToolSearch,toolOptions:{supportsStrictMode:model.compat?.supportsStrictMode??!0,supportsOpenAIGrammarTools:model.compat?.supportsOpenAIGrammarTools??!1}}),params={model:deploymentName,input:messages,stream:!0,prompt_cache_key:model.compat?.promptCacheKeyMode==="disabled"?void 0:clampOpenAIPromptCacheKey(options?.sessionId),store:!1};options?.maxTokens&&(params.max_output_tokens=Math.max(options.maxTokens,OPENAI_RESPONSES_MIN_OUTPUT_TOKENS)),options?.temperature!==void 0&&(params.temperature=options?.temperature),transcriptTools.requestTools.length>0&&(params.tools=convertResponsesTools(transcriptTools.requestTools,{supportsStrictMode:model.compat?.supportsStrictMode??!0,supportsOpenAIGrammarTools:model.compat?.supportsOpenAIGrammarTools??!1})),options?.toolChoice!==void 0&&(params.tool_choice=options.toolChoice);let reasoningEffort=options?.reasoningEffort??(options?.reasoningSummary?"medium":void 0);if(model.reasoning)if(reasoningEffort){let effort=options?.reasoningEffort?model.thinkingLevelMap?.[options.reasoningEffort]??options.reasoningEffort:reasoningEffort;params.reasoning={effort,summary:options?.reasoningSummary||"auto"},params.include=["reasoning.encrypted_content"]}else model.thinkingLevelMap?.off!==null&&(params.reasoning={effort:model.thinkingLevelMap?.off??"none"});let samplingParams=resolveSamplingParams(model,reasoningEffort??"off",options?.samplingParams);return samplingParams&&Object.assign(params,samplingParams),params}export{stream,streamSimple};
@@ -77,7 +77,7 @@ Reference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.ht
77
77
  `);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{#startedAt=Date.now();#startedAtMonotonic=performance.now();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")})}push(event){event.type==="done"?this.#time(event.message):event.type==="error"&&this.#time(event.error),super.push(event)}end(result){result!==void 0&&this.#time(result),super.end(result)}#time(message){this.done||message.durationMs!==void 0||message.timestamp<this.#startedAt||(message.durationMs=Math.max(0,Math.round(performance.now()-this.#startedAtMonotonic)))}};function appendAssistantMessageDiagnostic(message,diagnostic){message.diagnostics=[...message.diagnostics??[],diagnostic]}function contentText(content,separator=`
78
78
  `){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(`
79
79
 
80
- `)}function ownedSlice(text,start,end2=text.length){return`${text.slice(start,end2)} `.slice(0,-1)}var DIFFRA_AI_VERSION="0.1.2";function getClientVersion(identity){return identity?.version??DIFFRA_AI_VERSION}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(`
80
+ `)}function ownedSlice(text,start,end2=text.length){return`${text.slice(start,end2)} `.slice(0,-1)}var DIFFRA_AI_VERSION="0.1.4";function getClientVersion(identity){return identity?.version??DIFFRA_AI_VERSION}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(`
81
81
 
82
82
  `),...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.totalFromProvider=!1,usage.cost}var EXTENDED_THINKING_LEVELS=["off","minimal","low","medium","high","xhigh","max"];function getSupportedThinkingLevels(model){return model.reasoning?EXTENDED_THINKING_LEVELS.filter(level=>{let mapped=model.thinkingLevelMap?.[level];return mapped===null?!1:level==="xhigh"||level==="max"?mapped!==void 0:!0}):["off"]}function clampThinkingLevel(model,level){let availableLevels=getSupportedThinkingLevels(model);if(availableLevels.includes(level))return level;let requestedIndex=EXTENDED_THINKING_LEVELS.indexOf(level);if(requestedIndex===-1)return availableLevels[0]??"off";for(let i5=requestedIndex;i5<EXTENDED_THINKING_LEVELS.length;i5++){let candidate=EXTENDED_THINKING_LEVELS[i5];if(availableLevels.includes(candidate))return candidate}for(let i5=requestedIndex-1;i5>=0;i5--){let candidate=EXTENDED_THINKING_LEVELS[i5];if(availableLevels.includes(candidate))return candidate}return availableLevels[0]??"off"}var MAX_PROVIDER_ERROR_BODY_CHARS=4e3;function normalizeProviderError(error2){if(!(error2 instanceof Error))return{message:safeJsonStringify(error2),messageCarriesBody:!1};let sdkError=error2,status=extractStatus(sdkError),body=extractBody(sdkError),messageCarriesBody=body===void 0||error2.message.includes(body),message=status===void 0&&body===void 0?withCauseDetail(error2):error2.message;return{status,body,message,messageCarriesBody}}var MAX_CAUSE_DEPTH=5;function withCauseDetail(error2){let deepest,current=error2.cause;for(let depth=0;depth<MAX_CAUSE_DEPTH&&current instanceof Error;depth++)deepest=current,current=current.cause;if(!deepest)return error2.message;let detail=(deepest.message||deepest.name).trim(),code=deepest.code;return(typeof code=="string"||typeof code=="number")&&!detail.includes(String(code))&&(detail=detail?`${detail} (${code})`:String(code)),!detail||error2.message.includes(detail)?error2.message:error2.message?`${error2.message}: ${detail}`:detail}function extractStatus(error2){if(typeof error2.statusCode=="number")return error2.statusCode;if(typeof error2.status=="number")return error2.status;if(typeof error2.$metadata?.httpStatusCode=="number")return error2.$metadata.httpStatusCode;if(typeof error2.$response?.statusCode=="number")return error2.$response.statusCode}function extractBody(error2){let bodyText=pickBodyText(error2);if(bodyText===void 0)return;let trimmed=bodyText.trim();if(trimmed.length!==0)return truncateErrorText(trimmed,MAX_PROVIDER_ERROR_BODY_CHARS)}function pickBodyText(error2){if(typeof error2.body=="string")return error2.body;if(isPlainNonEmptyObject(error2.error))return safeJsonStringify(error2.error);let responseBody=error2.$response?.body;if(typeof responseBody=="string")return responseBody;if(!isReadableStreamLike(responseBody)&&isPlainNonEmptyObject(responseBody))return safeJsonStringify(responseBody)}function isReadableStreamLike(value){return typeof value=="object"&&value!==null&&"pipe"in value&&typeof value.pipe=="function"}function isPlainNonEmptyObject(value){if(typeof value!="object"||value===null)return!1;let proto=Object.getPrototypeOf(value);return proto!==Object.prototype&&proto!==null?!1:Object.keys(value).length>0}function truncateErrorText(text,maxChars){return text.length<=maxChars?text:`${ownedSlice(text,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 procEnvCache=null;function getBunSandboxEnvValue(name){if(!(typeof process>"u"||!process.versions?.bun||Object.keys(process.env).length>0)){if(procEnvCache===null){procEnvCache=new Map;try{let{readFileSync}=__require("node:fs"),data=readFileSync("/proc/self/environ","utf-8");for(let entry of data.split("\0")){let idx=entry.indexOf("=");idx>0&&procEnvCache.set(entry.slice(0,idx),entry.slice(idx+1))}}catch{}}return procEnvCache.get(name)}}function getProviderEnvValue(name,env3){return env3?.[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,env3){let lowercaseKey=key.toLowerCase(),uppercaseKey=key.toUpperCase();return env3?.[lowercaseKey]||env3?.[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,env3){let noProxy=getProxyEnv("no_proxy",env3).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,env3){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,env3))return"";let proxy=getProxyEnv(`${protocol}_proxy`,env3)||getProxyEnv("all_proxy",env3);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,env3){let proxy=getProxyForUrl(targetUrl,env3);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 import_partial_json=__toESM(require_dist(),1),VALID_JSON_ESCAPES=new Set(['"',"\\","/","b","f","n","r","t"]);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`
83
83
  `: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 parseToolCallArguments(json){if(!json?.trim())return{arguments:{}};try{let parsed=parseJsonWithRepair(json);if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))throw new Error("Tool arguments must be a JSON object");return{arguments:parsed}}catch(error2){return{arguments:{},argumentsError:`${error2 instanceof Error?error2.message:String(error2)}
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{getJsonSchemaToolParameters,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-SMYD2SB5.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{retryProviderRequest}from"./chunk-PMRZO46Y.js";import{clampThinkingLevel,collapseSystemMessages,withoutInitialSystemMessage}from"./chunk-3MKQN3ZR.js";import{__commonJS,__require,__toESM}from"./chunk-JXWJOIH4.js";var require_retry_operation=__commonJS({"node_modules/retry/lib/retry_operation.js"(exports,module){function RetryOperation(timeouts,options){typeof options=="boolean"&&(options={forever:options}),this._originalTimeouts=JSON.parse(JSON.stringify(timeouts)),this._timeouts=timeouts,this._options=options||{},this._maxRetryTime=options&&options.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}module.exports=RetryOperation;RetryOperation.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};RetryOperation.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};RetryOperation.prototype.retry=function(err){if(this._timeout&&clearTimeout(this._timeout),!err)return!1;var currentTime=new Date().getTime();if(err&&currentTime-this._operationStart>=this._maxRetryTime)return this._errors.push(err),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(err);var timeout=this._timeouts.shift();if(timeout===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),timeout=this._cachedTimeouts.slice(-1);else return!1;var self2=this;return this._timer=setTimeout(function(){self2._attempts++,self2._operationTimeoutCb&&(self2._timeout=setTimeout(function(){self2._operationTimeoutCb(self2._attempts)},self2._operationTimeout),self2._options.unref&&self2._timeout.unref()),self2._fn(self2._attempts)},timeout),this._options.unref&&this._timer.unref(),!0};RetryOperation.prototype.attempt=function(fn,timeoutOps){this._fn=fn,timeoutOps&&(timeoutOps.timeout&&(this._operationTimeout=timeoutOps.timeout),timeoutOps.cb&&(this._operationTimeoutCb=timeoutOps.cb));var self2=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){self2._operationTimeoutCb()},self2._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};RetryOperation.prototype.try=function(fn){console.log("Using RetryOperation.try() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=function(fn){console.log("Using RetryOperation.start() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=RetryOperation.prototype.try;RetryOperation.prototype.errors=function(){return this._errors};RetryOperation.prototype.attempts=function(){return this._attempts};RetryOperation.prototype.mainError=function(){if(this._errors.length===0)return null;for(var counts={},mainError=null,mainErrorCount=0,i=0;i<this._errors.length;i++){var error=this._errors[i],message=error.message,count=(counts[message]||0)+1;counts[message]=count,count>=mainErrorCount&&(mainError=error,mainErrorCount=count)}return mainError}}});var require_retry=__commonJS({"node_modules/retry/lib/retry.js"(exports){var RetryOperation=require_retry_operation();exports.operation=function(options){var timeouts=exports.timeouts(options);return new RetryOperation(timeouts,{forever:options&&(options.forever||options.retries===1/0),unref:options&&options.unref,maxRetryTime:options&&options.maxRetryTime})};exports.timeouts=function(options){if(options instanceof Array)return[].concat(options);var opts={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var key in options)opts[key]=options[key];if(opts.minTimeout>opts.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var timeouts=[],i=0;i<opts.retries;i++)timeouts.push(this.createTimeout(i,opts));return options&&options.forever&&!timeouts.length&&timeouts.push(this.createTimeout(i,opts)),timeouts.sort(function(a,b){return a-b}),timeouts};exports.createTimeout=function(attempt,opts){var random=opts.randomize?Math.random()+1:1,timeout=Math.round(random*Math.max(opts.minTimeout,1)*Math.pow(opts.factor,attempt));return timeout=Math.min(timeout,opts.maxTimeout),timeout};exports.wrap=function(obj,options,methods){if(options instanceof Array&&(methods=options,options=null),!methods){methods=[];for(var key in obj)typeof obj[key]=="function"&&methods.push(key)}for(var i=0;i<methods.length;i++){var method=methods[i],original=obj[method];obj[method]=function(original2){var op=exports.operation(options),args=Array.prototype.slice.call(arguments,1),callback=args.pop();args.push(function(err){op.retry(err)||(err&&(arguments[0]=op.mainError()),callback.apply(this,arguments))}),op.attempt(function(){original2.apply(obj,args)})}.bind(obj,original),obj[method].options=options}}}});var require_retry2=__commonJS({"node_modules/retry/index.js"(exports,module){module.exports=require_retry()}});var require_p_retry=__commonJS({"node_modules/p-retry/index.js"(exports,module){"use strict";var retry2=require_retry2(),networkErrorMsgs=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"],AbortError=class extends Error{constructor(message){super(),message instanceof Error?(this.originalError=message,{message}=message):(this.originalError=new Error(message),this.originalError.stack=this.stack),this.name="AbortError",this.message=message}},decorateErrorWithCounts=(error,attemptNumber,options)=>{let retriesLeft=options.retries-(attemptNumber-1);return error.attemptNumber=attemptNumber,error.retriesLeft=retriesLeft,error},isNetworkError=errorMessage=>networkErrorMsgs.includes(errorMessage),pRetry2=(input,options)=>new Promise((resolve,reject)=>{options={onFailedAttempt:()=>{},retries:10,...options};let operation=retry2.operation(options);operation.attempt(async attemptNumber=>{try{resolve(await input(attemptNumber))}catch(error){if(!(error instanceof Error)){reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`));return}if(error instanceof AbortError)operation.stop(),reject(error.originalError);else if(error instanceof TypeError&&!isNetworkError(error.message))operation.stop(),reject(error);else{decorateErrorWithCounts(error,attemptNumber,options);try{await options.onFailedAttempt(error)}catch(error2){reject(error2);return}operation.retry(error)||reject(operation.mainError())}}})});module.exports=pRetry2;module.exports.default=pRetry2;module.exports.AbortError=AbortError}});var require_extend=__commonJS({"node_modules/extend/index.js"(exports,module){"use strict";var hasOwn2=Object.prototype.hasOwnProperty,toStr=Object.prototype.toString,defineProperty=Object.defineProperty,gOPD=Object.getOwnPropertyDescriptor,isArray=function(arr){return typeof Array.isArray=="function"?Array.isArray(arr):toStr.call(arr)==="[object Array]"},isPlainObject2=function(obj){if(!obj||toStr.call(obj)!=="[object Object]")return!1;var hasOwnConstructor=hasOwn2.call(obj,"constructor"),hasIsPrototypeOf=obj.constructor&&obj.constructor.prototype&&hasOwn2.call(obj.constructor.prototype,"isPrototypeOf");if(obj.constructor&&!hasOwnConstructor&&!hasIsPrototypeOf)return!1;var key;for(key in obj);return typeof key>"u"||hasOwn2.call(obj,key)},setProperty=function(target,options){defineProperty&&options.name==="__proto__"?defineProperty(target,options.name,{enumerable:!0,configurable:!0,value:options.newValue,writable:!0}):target[options.name]=options.newValue},getProperty=function(obj,name){if(name==="__proto__")if(hasOwn2.call(obj,name)){if(gOPD)return gOPD(obj,name).value}else return;return obj[name]};module.exports=function extend(){var options,name,src,copy,copyIsArray,clone,target=arguments[0],i=1,length=arguments.length,deep=!1;for(typeof target=="boolean"&&(deep=target,target=arguments[1]||{},i=2),(target==null||typeof target!="object"&&typeof target!="function")&&(target={});i<length;++i)if(options=arguments[i],options!=null)for(name in options)src=getProperty(target,name),copy=getProperty(options,name),target!==copy&&(deep&&copy&&(isPlainObject2(copy)||(copyIsArray=isArray(copy)))?(copyIsArray?(copyIsArray=!1,clone=src&&isArray(src)?src:[]):clone=src&&isPlainObject2(src)?src:{},setProperty(target,{name,newValue:extend(deep,clone,copy)})):typeof copy<"u"&&setProperty(target,{name,newValue:copy}));return target}}});var require_package=__commonJS({"node_modules/gaxios/package.json"(exports,module){module.exports={name:"gaxios",version:"7.1.4",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","docs-test":"linkinator docs","predocs-test":"npm run docs","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"packages/gaxios",url:"https://github.com/googleapis/google-cloud-node-core.git"},keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^22.13.1","@types/sinon":"^17.0.3","@types/tmp":"^0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.1.3",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",linkinator:"^6.1.2",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.1","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","stream-browserify":"^3.0.0",tmp:"0.2.5","ts-loader":"^9.5.2",typescript:"5.8.3",webpack:"^5.97.1","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"},homepage:"https://github.com/googleapis/google-cloud-node-core/tree/main/packages/gaxios"}}});var require_util=__commonJS({"node_modules/gaxios/build/cjs/src/util.cjs"(exports,module){"use strict";var pkg=require_package();module.exports={pkg}}});var require_common=__commonJS({"node_modules/gaxios/build/cjs/src/common.js"(exports){"use strict";var __importDefault=exports&&exports.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0});exports.GaxiosError=exports.GAXIOS_ERROR_SYMBOL=void 0;exports.defaultErrorRedactor=defaultErrorRedactor;var extend_1=__importDefault(require_extend()),util_cjs_1=__importDefault(require_util()),pkg=util_cjs_1.default.pkg;exports.GAXIOS_ERROR_SYMBOL=Symbol.for(`${pkg.name}-gaxios-error`);var GaxiosError=class _GaxiosError extends Error{config;response;code;status;error;[exports.GAXIOS_ERROR_SYMBOL]=pkg.version;static[Symbol.hasInstance](instance){return instance&&typeof instance=="object"&&exports.GAXIOS_ERROR_SYMBOL in instance&&instance[exports.GAXIOS_ERROR_SYMBOL]===pkg.version?!0:Function.prototype[Symbol.hasInstance].call(_GaxiosError,instance)}constructor(message,config,response,cause){if(super(message,{cause}),this.config=config,this.response=response,this.error=cause instanceof Error?cause:void 0,this.config=(0,extend_1.default)(!0,{},config),this.response&&(this.response.config=(0,extend_1.default)(!0,{},this.response.config)),this.response){try{this.response.data=translateData(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}cause instanceof DOMException?this.code=cause.name:cause&&typeof cause=="object"&&"code"in cause&&(typeof cause.code=="string"||typeof cause.code=="number")&&(this.code=cause.code)}static extractAPIErrorFromResponse(res,defaultErrorMessage="The request failed"){let message=defaultErrorMessage;if(typeof res.data=="string"&&(message=res.data),res.data&&typeof res.data=="object"&&"error"in res.data&&res.data.error&&!res.ok){if(typeof res.data.error=="string")return{message:res.data.error,code:res.status,status:res.statusText};if(typeof res.data.error=="object"){message="message"in res.data.error&&typeof res.data.error.message=="string"?res.data.error.message:message;let status="status"in res.data.error&&typeof res.data.error.status=="string"?res.data.error.status:res.statusText,code="code"in res.data.error&&typeof res.data.error.code=="number"?res.data.error.code:res.status;if("errors"in res.data.error&&Array.isArray(res.data.error.errors)){let errorMessages=[];for(let e of res.data.error.errors)typeof e=="object"&&"message"in e&&typeof e.message=="string"&&errorMessages.push(e.message);return Object.assign({message:errorMessages.join(`
2
+ import{getJsonSchemaToolParameters,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-IDYI4NPC.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{retryProviderRequest}from"./chunk-PMRZO46Y.js";import{clampThinkingLevel,collapseSystemMessages,withoutInitialSystemMessage}from"./chunk-YDKIXS42.js";import{__commonJS,__require,__toESM}from"./chunk-JXWJOIH4.js";var require_retry_operation=__commonJS({"node_modules/retry/lib/retry_operation.js"(exports,module){function RetryOperation(timeouts,options){typeof options=="boolean"&&(options={forever:options}),this._originalTimeouts=JSON.parse(JSON.stringify(timeouts)),this._timeouts=timeouts,this._options=options||{},this._maxRetryTime=options&&options.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}module.exports=RetryOperation;RetryOperation.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};RetryOperation.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};RetryOperation.prototype.retry=function(err){if(this._timeout&&clearTimeout(this._timeout),!err)return!1;var currentTime=new Date().getTime();if(err&&currentTime-this._operationStart>=this._maxRetryTime)return this._errors.push(err),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(err);var timeout=this._timeouts.shift();if(timeout===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),timeout=this._cachedTimeouts.slice(-1);else return!1;var self2=this;return this._timer=setTimeout(function(){self2._attempts++,self2._operationTimeoutCb&&(self2._timeout=setTimeout(function(){self2._operationTimeoutCb(self2._attempts)},self2._operationTimeout),self2._options.unref&&self2._timeout.unref()),self2._fn(self2._attempts)},timeout),this._options.unref&&this._timer.unref(),!0};RetryOperation.prototype.attempt=function(fn,timeoutOps){this._fn=fn,timeoutOps&&(timeoutOps.timeout&&(this._operationTimeout=timeoutOps.timeout),timeoutOps.cb&&(this._operationTimeoutCb=timeoutOps.cb));var self2=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){self2._operationTimeoutCb()},self2._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};RetryOperation.prototype.try=function(fn){console.log("Using RetryOperation.try() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=function(fn){console.log("Using RetryOperation.start() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=RetryOperation.prototype.try;RetryOperation.prototype.errors=function(){return this._errors};RetryOperation.prototype.attempts=function(){return this._attempts};RetryOperation.prototype.mainError=function(){if(this._errors.length===0)return null;for(var counts={},mainError=null,mainErrorCount=0,i=0;i<this._errors.length;i++){var error=this._errors[i],message=error.message,count=(counts[message]||0)+1;counts[message]=count,count>=mainErrorCount&&(mainError=error,mainErrorCount=count)}return mainError}}});var require_retry=__commonJS({"node_modules/retry/lib/retry.js"(exports){var RetryOperation=require_retry_operation();exports.operation=function(options){var timeouts=exports.timeouts(options);return new RetryOperation(timeouts,{forever:options&&(options.forever||options.retries===1/0),unref:options&&options.unref,maxRetryTime:options&&options.maxRetryTime})};exports.timeouts=function(options){if(options instanceof Array)return[].concat(options);var opts={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var key in options)opts[key]=options[key];if(opts.minTimeout>opts.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var timeouts=[],i=0;i<opts.retries;i++)timeouts.push(this.createTimeout(i,opts));return options&&options.forever&&!timeouts.length&&timeouts.push(this.createTimeout(i,opts)),timeouts.sort(function(a,b){return a-b}),timeouts};exports.createTimeout=function(attempt,opts){var random=opts.randomize?Math.random()+1:1,timeout=Math.round(random*Math.max(opts.minTimeout,1)*Math.pow(opts.factor,attempt));return timeout=Math.min(timeout,opts.maxTimeout),timeout};exports.wrap=function(obj,options,methods){if(options instanceof Array&&(methods=options,options=null),!methods){methods=[];for(var key in obj)typeof obj[key]=="function"&&methods.push(key)}for(var i=0;i<methods.length;i++){var method=methods[i],original=obj[method];obj[method]=function(original2){var op=exports.operation(options),args=Array.prototype.slice.call(arguments,1),callback=args.pop();args.push(function(err){op.retry(err)||(err&&(arguments[0]=op.mainError()),callback.apply(this,arguments))}),op.attempt(function(){original2.apply(obj,args)})}.bind(obj,original),obj[method].options=options}}}});var require_retry2=__commonJS({"node_modules/retry/index.js"(exports,module){module.exports=require_retry()}});var require_p_retry=__commonJS({"node_modules/p-retry/index.js"(exports,module){"use strict";var retry2=require_retry2(),networkErrorMsgs=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"],AbortError=class extends Error{constructor(message){super(),message instanceof Error?(this.originalError=message,{message}=message):(this.originalError=new Error(message),this.originalError.stack=this.stack),this.name="AbortError",this.message=message}},decorateErrorWithCounts=(error,attemptNumber,options)=>{let retriesLeft=options.retries-(attemptNumber-1);return error.attemptNumber=attemptNumber,error.retriesLeft=retriesLeft,error},isNetworkError=errorMessage=>networkErrorMsgs.includes(errorMessage),pRetry2=(input,options)=>new Promise((resolve,reject)=>{options={onFailedAttempt:()=>{},retries:10,...options};let operation=retry2.operation(options);operation.attempt(async attemptNumber=>{try{resolve(await input(attemptNumber))}catch(error){if(!(error instanceof Error)){reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`));return}if(error instanceof AbortError)operation.stop(),reject(error.originalError);else if(error instanceof TypeError&&!isNetworkError(error.message))operation.stop(),reject(error);else{decorateErrorWithCounts(error,attemptNumber,options);try{await options.onFailedAttempt(error)}catch(error2){reject(error2);return}operation.retry(error)||reject(operation.mainError())}}})});module.exports=pRetry2;module.exports.default=pRetry2;module.exports.AbortError=AbortError}});var require_extend=__commonJS({"node_modules/extend/index.js"(exports,module){"use strict";var hasOwn2=Object.prototype.hasOwnProperty,toStr=Object.prototype.toString,defineProperty=Object.defineProperty,gOPD=Object.getOwnPropertyDescriptor,isArray=function(arr){return typeof Array.isArray=="function"?Array.isArray(arr):toStr.call(arr)==="[object Array]"},isPlainObject2=function(obj){if(!obj||toStr.call(obj)!=="[object Object]")return!1;var hasOwnConstructor=hasOwn2.call(obj,"constructor"),hasIsPrototypeOf=obj.constructor&&obj.constructor.prototype&&hasOwn2.call(obj.constructor.prototype,"isPrototypeOf");if(obj.constructor&&!hasOwnConstructor&&!hasIsPrototypeOf)return!1;var key;for(key in obj);return typeof key>"u"||hasOwn2.call(obj,key)},setProperty=function(target,options){defineProperty&&options.name==="__proto__"?defineProperty(target,options.name,{enumerable:!0,configurable:!0,value:options.newValue,writable:!0}):target[options.name]=options.newValue},getProperty=function(obj,name){if(name==="__proto__")if(hasOwn2.call(obj,name)){if(gOPD)return gOPD(obj,name).value}else return;return obj[name]};module.exports=function extend(){var options,name,src,copy,copyIsArray,clone,target=arguments[0],i=1,length=arguments.length,deep=!1;for(typeof target=="boolean"&&(deep=target,target=arguments[1]||{},i=2),(target==null||typeof target!="object"&&typeof target!="function")&&(target={});i<length;++i)if(options=arguments[i],options!=null)for(name in options)src=getProperty(target,name),copy=getProperty(options,name),target!==copy&&(deep&&copy&&(isPlainObject2(copy)||(copyIsArray=isArray(copy)))?(copyIsArray?(copyIsArray=!1,clone=src&&isArray(src)?src:[]):clone=src&&isPlainObject2(src)?src:{},setProperty(target,{name,newValue:extend(deep,clone,copy)})):typeof copy<"u"&&setProperty(target,{name,newValue:copy}));return target}}});var require_package=__commonJS({"node_modules/gaxios/package.json"(exports,module){module.exports={name:"gaxios",version:"7.1.4",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","docs-test":"linkinator docs","predocs-test":"npm run docs","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"packages/gaxios",url:"https://github.com/googleapis/google-cloud-node-core.git"},keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^22.13.1","@types/sinon":"^17.0.3","@types/tmp":"^0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.1.3",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",linkinator:"^6.1.2",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.1","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","stream-browserify":"^3.0.0",tmp:"0.2.5","ts-loader":"^9.5.2",typescript:"5.8.3",webpack:"^5.97.1","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"},homepage:"https://github.com/googleapis/google-cloud-node-core/tree/main/packages/gaxios"}}});var require_util=__commonJS({"node_modules/gaxios/build/cjs/src/util.cjs"(exports,module){"use strict";var pkg=require_package();module.exports={pkg}}});var require_common=__commonJS({"node_modules/gaxios/build/cjs/src/common.js"(exports){"use strict";var __importDefault=exports&&exports.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0});exports.GaxiosError=exports.GAXIOS_ERROR_SYMBOL=void 0;exports.defaultErrorRedactor=defaultErrorRedactor;var extend_1=__importDefault(require_extend()),util_cjs_1=__importDefault(require_util()),pkg=util_cjs_1.default.pkg;exports.GAXIOS_ERROR_SYMBOL=Symbol.for(`${pkg.name}-gaxios-error`);var GaxiosError=class _GaxiosError extends Error{config;response;code;status;error;[exports.GAXIOS_ERROR_SYMBOL]=pkg.version;static[Symbol.hasInstance](instance){return instance&&typeof instance=="object"&&exports.GAXIOS_ERROR_SYMBOL in instance&&instance[exports.GAXIOS_ERROR_SYMBOL]===pkg.version?!0:Function.prototype[Symbol.hasInstance].call(_GaxiosError,instance)}constructor(message,config,response,cause){if(super(message,{cause}),this.config=config,this.response=response,this.error=cause instanceof Error?cause:void 0,this.config=(0,extend_1.default)(!0,{},config),this.response&&(this.response.config=(0,extend_1.default)(!0,{},this.response.config)),this.response){try{this.response.data=translateData(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}cause instanceof DOMException?this.code=cause.name:cause&&typeof cause=="object"&&"code"in cause&&(typeof cause.code=="string"||typeof cause.code=="number")&&(this.code=cause.code)}static extractAPIErrorFromResponse(res,defaultErrorMessage="The request failed"){let message=defaultErrorMessage;if(typeof res.data=="string"&&(message=res.data),res.data&&typeof res.data=="object"&&"error"in res.data&&res.data.error&&!res.ok){if(typeof res.data.error=="string")return{message:res.data.error,code:res.status,status:res.statusText};if(typeof res.data.error=="object"){message="message"in res.data.error&&typeof res.data.error.message=="string"?res.data.error.message:message;let status="status"in res.data.error&&typeof res.data.error.status=="string"?res.data.error.status:res.statusText,code="code"in res.data.error&&typeof res.data.error.code=="number"?res.data.error.code:res.status;if("errors"in res.data.error&&Array.isArray(res.data.error.errors)){let errorMessages=[];for(let e of res.data.error.errors)typeof e=="object"&&"message"in e&&typeof e.message=="string"&&errorMessages.push(e.message);return Object.assign({message:errorMessages.join(`
3
3
  `)||message,code,status},res.data.error)}return Object.assign({message,code,status},res.data.error)}}return{message,code:res.status,status:res.statusText}}};exports.GaxiosError=GaxiosError;function translateData(responseType,data){switch(responseType){case"stream":return data;case"json":return JSON.parse(JSON.stringify(data));case"arraybuffer":return JSON.parse(Buffer.from(data).toString("utf8"));case"blob":return JSON.parse(data.text());default:return data}}function defaultErrorRedactor(data){let REDACT="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function redactHeaders(headers){headers&&headers.forEach((_,key)=>{(/^authentication$/i.test(key)||/^authorization$/i.test(key)||/secret/i.test(key))&&headers.set(key,REDACT)})}function redactString(obj,key){if(typeof obj=="object"&&obj!==null&&typeof obj[key]=="string"){let text=obj[key];(/grant_type=/i.test(text)||/assertion=/i.test(text)||/secret/i.test(text))&&(obj[key]=REDACT)}}function redactObject(obj){!obj||typeof obj!="object"||(obj instanceof FormData||obj instanceof URLSearchParams||"forEach"in obj&&"set"in obj?obj.forEach((_,key)=>{(["grant_type","assertion"].includes(key)||/secret/.test(key))&&obj.set(key,REDACT)}):("grant_type"in obj&&(obj.grant_type=REDACT),"assertion"in obj&&(obj.assertion=REDACT),"client_secret"in obj&&(obj.client_secret=REDACT)))}return data.config&&(redactHeaders(data.config.headers),redactString(data.config,"data"),redactObject(data.config.data),redactString(data.config,"body"),redactObject(data.config.body),data.config.url.searchParams.has("token")&&data.config.url.searchParams.set("token",REDACT),data.config.url.searchParams.has("client_secret")&&data.config.url.searchParams.set("client_secret",REDACT)),data.response&&(defaultErrorRedactor({config:data.response.config}),redactHeaders(data.response.headers),data.response.bodyUsed&&(redactString(data.response,"data"),redactObject(data.response.data))),data}}});var require_retry3=__commonJS({"node_modules/gaxios/build/cjs/src/retry.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.getRetryConfig=getRetryConfig;async function getRetryConfig(err){let config=getConfig(err);if(!err||!err.config||!config&&!err.config.retry)return{shouldRetry:!1};config=config||{},config.currentRetryAttempt=config.currentRetryAttempt||0,config.retry=config.retry===void 0||config.retry===null?3:config.retry,config.httpMethodsToRetry=config.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],config.noResponseRetries=config.noResponseRetries===void 0||config.noResponseRetries===null?2:config.noResponseRetries,config.retryDelayMultiplier=config.retryDelayMultiplier?config.retryDelayMultiplier:2,config.timeOfFirstRequest=config.timeOfFirstRequest?config.timeOfFirstRequest:Date.now(),config.totalTimeout=config.totalTimeout?config.totalTimeout:Number.MAX_SAFE_INTEGER,config.maxRetryDelay=config.maxRetryDelay?config.maxRetryDelay:Number.MAX_SAFE_INTEGER;let retryRanges=[[100,199],[408,408],[429,429],[500,599]];if(config.statusCodesToRetry=config.statusCodesToRetry||retryRanges,err.config.retryConfig=config,!await(config.shouldRetry||shouldRetryRequest)(err))return{shouldRetry:!1,config:err.config};let delay2=getNextRetryDelay(config);err.config.retryConfig.currentRetryAttempt+=1;let backoff=config.retryBackoff?config.retryBackoff(err,delay2):new Promise(resolve=>{setTimeout(resolve,delay2)});return config.onRetryAttempt&&await config.onRetryAttempt(err),await backoff,{shouldRetry:!0,config:err.config}}function shouldRetryRequest(err){let config=getConfig(err);if(err.config.signal?.aborted&&err.code!=="TimeoutError"||err.code==="AbortError"||!config||config.retry===0||!err.response&&(config.currentRetryAttempt||0)>=config.noResponseRetries||!config.httpMethodsToRetry||!config.httpMethodsToRetry.includes(err.config.method?.toUpperCase()||"GET"))return!1;if(err.response&&err.response.status){let isInRange=!1;for(let[min,max]of config.statusCodesToRetry){let status=err.response.status;if(status>=min&&status<=max){isInRange=!0;break}}if(!isInRange)return!1}return config.currentRetryAttempt=config.currentRetryAttempt||0,!(config.currentRetryAttempt>=config.retry)}function getConfig(err){if(err&&err.config&&err.config.retryConfig)return err.config.retryConfig}function getNextRetryDelay(config){let calculatedDelay=(config.currentRetryAttempt?0:config.retryDelay??100)+(Math.pow(config.retryDelayMultiplier,config.currentRetryAttempt)-1)/2*1e3,maxAllowableDelay=config.totalTimeout-(Date.now()-config.timeOfFirstRequest);return Math.min(calculatedDelay,maxAllowableDelay,config.maxRetryDelay)}}});var require_interceptor=__commonJS({"node_modules/gaxios/build/cjs/src/interceptor.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.GaxiosInterceptorManager=void 0;var GaxiosInterceptorManager=class extends Set{};exports.GaxiosInterceptorManager=GaxiosInterceptorManager}});var require_gaxios=__commonJS({"node_modules/gaxios/build/cjs/src/gaxios.js"(exports){"use strict";var __importDefault=exports&&exports.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}},_a2;Object.defineProperty(exports,"__esModule",{value:!0});exports.Gaxios=void 0;var extend_1=__importDefault(require_extend()),https_1=__require("https"),common_js_1=require_common(),retry_js_1=require_retry3(),stream_1=__require("stream"),interceptor_js_1=require_interceptor(),randomUUID=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),HTTP_STATUS_NO_CONTENT=204,Gaxios=class{agentCache=new Map;defaults;interceptors;constructor(defaults){this.defaults=defaults||{},this.interceptors={request:new interceptor_js_1.GaxiosInterceptorManager,response:new interceptor_js_1.GaxiosInterceptorManager}}fetch(...args){let input=args[0],init=args[1],url,headers=new Headers;return typeof input=="string"?url=new URL(input):input instanceof URL?url=input:input&&input.url&&(url=new URL(input.url)),input&&typeof input=="object"&&"headers"in input&&_a2.mergeHeaders(headers,input.headers),init&&_a2.mergeHeaders(headers,new Headers(init.headers)),typeof input=="object"&&!(input instanceof URL)?this.request({...init,...input,headers,url}):this.request({...init,headers,url})}async request(opts={}){let prepared=await this.#prepareRequest(opts);return prepared=await this.#applyRequestInterceptors(prepared),this.#applyResponseInterceptors(this._request(prepared))}async _defaultAdapter(config){let fetchImpl=config.fetchImplementation||this.defaults.fetchImplementation||await _a2.#getFetch(),preparedOpts={...config};delete preparedOpts.data;let res=await fetchImpl(config.url,preparedOpts),data=await this.getResponseData(config,res);return Object.getOwnPropertyDescriptor(res,"data")?.configurable||Object.defineProperties(res,{data:{configurable:!0,writable:!0,enumerable:!0,value:data}}),Object.assign(res,{config,data})}async _request(opts){try{let translatedResponse;if(opts.adapter?translatedResponse=await opts.adapter(opts,this._defaultAdapter.bind(this)):translatedResponse=await this._defaultAdapter(opts),!opts.validateStatus(translatedResponse.status)){if(opts.responseType==="stream"){let response=[];for await(let chunk of translatedResponse.data)response.push(chunk);translatedResponse.data=response.toString()}let errorInfo=common_js_1.GaxiosError.extractAPIErrorFromResponse(translatedResponse,`Request failed with status code ${translatedResponse.status}`);throw new common_js_1.GaxiosError(errorInfo?.message,opts,translatedResponse,errorInfo)}return translatedResponse}catch(e){let err;e instanceof common_js_1.GaxiosError?err=e:e instanceof Error?err=new common_js_1.GaxiosError(e.message,opts,void 0,e):err=new common_js_1.GaxiosError("Unexpected Gaxios Error",opts,void 0,e);let{shouldRetry,config}=await(0,retry_js_1.getRetryConfig)(err);if(shouldRetry&&config)return err.config.retryConfig.currentRetryAttempt=config.retryConfig.currentRetryAttempt,opts.retryConfig=err.config?.retryConfig,this.#appendTimeoutToSignal(opts),this._request(opts);throw opts.errorRedactor&&opts.errorRedactor(err),err}}async getResponseData(opts,res){if(res.status===HTTP_STATUS_NO_CONTENT)return"";if(opts.maxContentLength&&res.headers.has("content-length")&&opts.maxContentLength<Number.parseInt(res.headers?.get("content-length")||""))throw new common_js_1.GaxiosError("Response's `Content-Length` is over the limit.",opts,Object.assign(res,{config:opts}));switch(opts.responseType){case"stream":return res.body;case"json":{let data=await res.text();try{return JSON.parse(data)}catch{return data}}case"arraybuffer":return res.arrayBuffer();case"blob":return res.blob();case"text":return res.text();default:return this.getResponseDataFromContentType(res)}}#urlMayUseProxy(url,noProxy=[]){let candidate=new URL(url),noProxyList=[...noProxy],noProxyEnvList=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let rule of noProxyEnvList)noProxyList.push(rule.trim());for(let rule of noProxyList)if(rule instanceof RegExp){if(rule.test(candidate.toString()))return!1}else if(rule instanceof URL){if(rule.origin===candidate.origin)return!1}else if(rule.startsWith("*.")||rule.startsWith(".")){let cleanedRule=rule.replace(/^\*\./,".");if(candidate.hostname.endsWith(cleanedRule))return!1}else if(rule===candidate.origin||rule===candidate.hostname||rule===candidate.href)return!1;return!0}async#applyRequestInterceptors(options){let promiseChain=Promise.resolve(options);for(let interceptor of this.interceptors.request.values())interceptor&&(promiseChain=promiseChain.then(interceptor.resolved,interceptor.rejected));return promiseChain}async#applyResponseInterceptors(response){let promiseChain=Promise.resolve(response);for(let interceptor of this.interceptors.response.values())interceptor&&(promiseChain=promiseChain.then(interceptor.resolved,interceptor.rejected));return promiseChain}async#prepareRequest(options){let preparedHeaders=new Headers(this.defaults.headers);_a2.mergeHeaders(preparedHeaders,options.headers);let opts=(0,extend_1.default)(!0,{},this.defaults,options);if(!opts.url)throw new Error("URL is required.");if(opts.baseURL&&(opts.url=new URL(opts.url,opts.baseURL)),opts.url=new URL(opts.url),opts.params)if(opts.paramsSerializer){let additionalQueryParams=opts.paramsSerializer(opts.params);additionalQueryParams.startsWith("?")&&(additionalQueryParams=additionalQueryParams.slice(1));let prefix=opts.url.toString().includes("?")?"&":"?";opts.url=opts.url+prefix+additionalQueryParams}else{let url=opts.url instanceof URL?opts.url:new URL(opts.url);for(let[key,value]of new URLSearchParams(opts.params))url.searchParams.append(key,value);opts.url=url}typeof options.maxContentLength=="number"&&(opts.size=options.maxContentLength),typeof options.maxRedirects=="number"&&(opts.follow=options.maxRedirects);let shouldDirectlyPassData=typeof opts.data=="string"||opts.data instanceof ArrayBuffer||opts.data instanceof Blob||globalThis.File&&opts.data instanceof File||opts.data instanceof FormData||opts.data instanceof stream_1.Readable||opts.data instanceof ReadableStream||opts.data instanceof String||opts.data instanceof URLSearchParams||ArrayBuffer.isView(opts.data)||["Blob","File","FormData"].includes(opts.data?.constructor?.name||"");if(opts.multipart?.length){let boundary=await randomUUID();preparedHeaders.set("content-type",`multipart/related; boundary=${boundary}`),opts.body=stream_1.Readable.from(this.getMultipartRequest(opts.multipart,boundary))}else shouldDirectlyPassData?opts.body=opts.data:typeof opts.data=="object"?preparedHeaders.get("Content-Type")==="application/x-www-form-urlencoded"?opts.body=opts.paramsSerializer?opts.paramsSerializer(opts.data):new URLSearchParams(opts.data):(preparedHeaders.has("content-type")||preparedHeaders.set("content-type","application/json"),opts.body=JSON.stringify(opts.data)):opts.data&&(opts.body=opts.data);opts.validateStatus=opts.validateStatus||this.validateStatus,opts.responseType=opts.responseType||"unknown",!preparedHeaders.has("accept")&&opts.responseType==="json"&&preparedHeaders.set("accept","application/json");let proxy=opts.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(!opts.agent)if(proxy&&this.#urlMayUseProxy(opts.url,opts.noProxy)){let HttpsProxyAgent=await _a2.#getProxyAgent();this.agentCache.has(proxy)?opts.agent=this.agentCache.get(proxy):(opts.agent=new HttpsProxyAgent(proxy,{cert:opts.cert,key:opts.key}),this.agentCache.set(proxy,opts.agent))}else opts.cert&&opts.key&&(this.agentCache.has(opts.key)?opts.agent=this.agentCache.get(opts.key):(opts.agent=new https_1.Agent({cert:opts.cert,key:opts.key}),this.agentCache.set(opts.key,opts.agent)));return typeof opts.errorRedactor!="function"&&opts.errorRedactor!==!1&&(opts.errorRedactor=common_js_1.defaultErrorRedactor),opts.body&&!("duplex"in opts)&&(opts.duplex="half"),this.#appendTimeoutToSignal(opts),Object.assign(opts,{headers:preparedHeaders,url:opts.url instanceof URL?opts.url:new URL(opts.url)})}#appendTimeoutToSignal(opts){if(opts.timeout){let timeoutSignal=AbortSignal.timeout(opts.timeout);opts.signal&&!opts.signal.aborted?opts.signal=AbortSignal.any([opts.signal,timeoutSignal]):opts.signal=timeoutSignal}}validateStatus(status){return status>=200&&status<300}async getResponseDataFromContentType(response){let contentType=response.headers.get("Content-Type");if(contentType===null)return response.text();if(contentType=contentType.toLowerCase(),contentType.includes("application/json")){let data=await response.text();try{data=JSON.parse(data)}catch{}return data}else return contentType.match(/^text\//)?response.text():response.blob()}async*getMultipartRequest(multipartOptions,boundary){let finale=`--${boundary}--`;for(let currentPart of multipartOptions){let partContentType=currentPart.headers.get("Content-Type")||"application/octet-stream";yield`--${boundary}\r
4
4
  Content-Type: ${partContentType}\r
5
5
  \r
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{shortHash}from"./chunk-PJACZCIR.js";import{appendGrammarToolInputJsonDelta,closeGrammarToolInputJson,getGrammarToolInput,getJsonSchemaToolParameters,resolveGrammarConstrainedSampling,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-SMYD2SB5.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{ToolCallArgumentsStream}from"./chunk-FFMDRXC4.js";import{calculateCost,resolveTranscript,resolveTranscriptTools}from"./chunk-3MKQN3ZR.js";import{appendAssistantMessageDiagnostic}from"./chunk-LPXNMA2W.js";import{getSystemMessageText,renderSystemMessageUpdate}from"./chunk-6L2FT6AE.js";function encodeTextSignatureV1(id,phase){let payload={v:1,id};return phase&&(payload.phase=phase),JSON.stringify(payload)}function parseTextSignature(signature){if(signature){if(signature.startsWith("{"))try{let parsed=JSON.parse(signature);if(parsed.v===1&&typeof parsed.id=="string")return parsed.phase==="commentary"||parsed.phase==="final_answer"?{id:parsed.id,phase:parsed.phase}:{id:parsed.id}}catch{}return{id:signature}}}function convertToolResultOutput(model,content){let textResult=content.filter(c=>c.type==="text").map(c=>c.text).join(`
2
+ import{shortHash}from"./chunk-PJACZCIR.js";import{appendGrammarToolInputJsonDelta,closeGrammarToolInputJson,getGrammarToolInput,getJsonSchemaToolParameters,resolveGrammarConstrainedSampling,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-IDYI4NPC.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{ToolCallArgumentsStream}from"./chunk-FFMDRXC4.js";import{calculateCost,resolveTranscript,resolveTranscriptTools}from"./chunk-YDKIXS42.js";import{appendAssistantMessageDiagnostic}from"./chunk-LPXNMA2W.js";import{getSystemMessageText,renderSystemMessageUpdate}from"./chunk-ZW3S4FQY.js";function encodeTextSignatureV1(id,phase){let payload={v:1,id};return phase&&(payload.phase=phase),JSON.stringify(payload)}function parseTextSignature(signature){if(signature){if(signature.startsWith("{"))try{let parsed=JSON.parse(signature);if(parsed.v===1&&typeof parsed.id=="string")return parsed.phase==="commentary"||parsed.phase==="final_answer"?{id:parsed.id,phase:parsed.phase}:{id:parsed.id}}catch{}return{id:signature}}}function convertToolResultOutput(model,content){let textResult=content.filter(c=>c.type==="text").map(c=>c.text).join(`
3
3
  `),images=content.filter(c=>c.type==="image"),hasText=textResult.trim().length>0;if(images.length===0||!model.input.includes("image"))return sanitizeSurrogates(hasText?textResult:images.length>0?"(see attached image)":"(no tool output)");let output=[];hasText&&output.push({type:"input_text",text:sanitizeSurrogates(textResult)});for(let image of images)output.push({type:"input_image",detail:"auto",image_url:`data:${image.mimeType};base64,${image.data}`});return output}function getResponsesToolSupport(options){return options.supportsMidConvoSystemMessages&&options.supportsAdditionalTools?"changes":options.supportsToolSearch?"additions":"none"}function renderIncrementalToolsNotice(unavailable){let notice="This is an incremental tools update. Previously declared tools remain available unless explicitly marked unavailable. A tool declared again here is available again, and its latest definition replaces the earlier one.";return unavailable.size>0?`${notice}
4
4
  Still unavailable: ${[...unavailable].join(", ")}.`:notice}function renderToolRemovalNotice(names){return`The following tools are no longer available. Do not call them:
5
5
  ${names.map(name=>`- ${name}`).join(`