@diffra-ai/cli 0.1.2 → 0.1.3

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 (43) hide show
  1. package/CHANGELOG.md +53 -47
  2. package/dist/bundle/chunks/{anthropic-messages-HME6WDIM.js → anthropic-messages-5EMOURYI.js} +1 -1
  3. package/dist/bundle/chunks/{azure-openai-responses-WKSFBZF5.js → azure-openai-responses-N67KWG2X.js} +1 -1
  4. package/dist/bundle/chunks/bedrock-converse-stream.js +1 -1
  5. package/dist/bundle/chunks/{chunk-SMYD2SB5.js → chunk-3UNTEQ65.js} +1 -1
  6. package/dist/bundle/chunks/{chunk-MJRIJM22.js → chunk-BF423NQ7.js} +1 -1
  7. package/dist/bundle/chunks/{chunk-QMZGTPRI.js → chunk-CES65UJH.js} +1 -1
  8. package/dist/bundle/chunks/{chunk-PXE534VH.js → chunk-HFTZ6OJJ.js} +2 -2
  9. package/dist/bundle/chunks/{chunk-RUI3NOFB.js → chunk-NEFH2K3C.js} +1 -1
  10. package/dist/bundle/chunks/{chunk-E3MJ4MPN.js → chunk-PISJX26Y.js} +1 -1
  11. package/dist/bundle/chunks/{chunk-6L2FT6AE.js → chunk-QYYUGS66.js} +1 -1
  12. package/dist/bundle/chunks/{chunk-3MKQN3ZR.js → chunk-RLMZZV4Q.js} +1 -1
  13. package/dist/bundle/chunks/{chunk-GRDBYTYT.js → chunk-RTPG7C5I.js} +4 -4
  14. package/dist/bundle/chunks/{chunk-MITPYV3F.js → chunk-VOKUVFV4.js} +1 -1
  15. package/dist/bundle/chunks/{chunk-PQGGR7SQ.js → chunk-VWWMBH3G.js} +1 -1
  16. package/dist/bundle/chunks/{cli-GKHAGQO6.js → cli-55VO5MAJ.js} +1 -1
  17. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-PVUECIVD.js → cloudflare-workers-ai-system-one-HB5U67WC.js} +1 -1
  18. package/dist/bundle/chunks/{google-generative-ai-2YH7DK5J.js → google-generative-ai-XRHE7R52.js} +1 -1
  19. package/dist/bundle/chunks/{google-vertex-QNIS4SPE.js → google-vertex-75CQOPKC.js} +1 -1
  20. package/dist/bundle/chunks/{llama-cpp-classify-EMBT3ZMY.js → llama-cpp-classify-LKIRB7ZR.js} +1 -1
  21. package/dist/bundle/chunks/{mistral-conversations-RCHJWX2M.js → mistral-conversations-KLGIHK73.js} +1 -1
  22. package/dist/bundle/chunks/{openai-codex-responses-LBZQ7HUY.js → openai-codex-responses-7L5VV67U.js} +1 -1
  23. package/dist/bundle/chunks/{openai-completions-U7NS5GFY.js → openai-completions-RBF6UXDW.js} +1 -1
  24. package/dist/bundle/chunks/{openai-decisions-YC4ZEGAR.js → openai-decisions-W3PJQIOF.js} +1 -1
  25. package/dist/bundle/chunks/{openai-responses-4YX6XMEO.js → openai-responses-W5ZMLOTR.js} +1 -1
  26. package/dist/bundle/chunks/{openrouter-images-QPPGKFJY.js → openrouter-images-4FW6VFV4.js} +1 -1
  27. package/dist/bundle/chunks/{pi-messages-5W3GZ7B6.js → pi-messages-RT7FVQ4G.js} +1 -1
  28. package/dist/bundle/chunks/{typesafe-system-one-GWMQ2NLX.js → typesafe-system-one-DSJ7OYVL.js} +1 -1
  29. package/dist/bundle/chunks/{virtual-modules-ENTYMDSQ.js → virtual-modules-M75O3ECA.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/docs/approval-modes.md +99 -99
  37. package/docs/cli.md +380 -380
  38. package/docs/docs.json +264 -264
  39. package/docs/environment-variables.md +110 -110
  40. package/docs/extensions.md +3 -2
  41. package/docs/security.md +100 -100
  42. package/docs/settings.md +198 -198
  43. package/package.json +6 -6
package/CHANGELOG.md CHANGED
@@ -1,47 +1,53 @@
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.3] - 2026-11-22
6
+
7
+ ### Added
8
+
9
+ - `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.
10
+
11
+ ## [0.1.2] - 2026-11-21
12
+
13
+ ### Added
14
+
15
+ - `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.
16
+ - `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).
17
+ - `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.
18
+ - 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).
19
+ - 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).
20
+ - 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).
21
+ - 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).
22
+ - 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).
23
+ - 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.
24
+ - 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).
25
+ - 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).
26
+ - 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).
27
+ - `diffra.getGlobalSettings()` returns the user's global settings alone, for options a project must not turn on.
28
+ - 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).
29
+
30
+ ### Changed
31
+
32
+ - The plan-mode example extension's command is now `/plan-mode`, so it no longer collides with the built-in `/plan`.
33
+ - 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.
34
+ - 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.
35
+ - 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.
36
+ - 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.
37
+ - 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.
38
+
39
+ ### Fixed
40
+
41
+ - 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.
42
+
43
+ ## [0.1.1] - 2026-11-20
44
+
45
+ ### Changed
46
+
47
+ - 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.
48
+
49
+ ## [0.1.0] - 2026-11-20
50
+
51
+ ### Added
52
+
53
+ - 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-3UNTEQ65.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{retryProviderRequest}from"./chunk-PMRZO46Y.js";import{withCauseDetail}from"./chunk-PISJX26Y.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-RLMZZV4Q.js";import{AssistantMessageEventStream,appendAssistantMessageDiagnostic}from"./chunk-LPXNMA2W.js";import{getIdentityHeaders,getSystemMessageText,renderSystemMessageUpdate}from"./chunk-QYYUGS66.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-BF423NQ7.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-3UNTEQ65.js";import"./chunk-L2ZPNLYD.js";import{retryProviderRequest}from"./chunk-PMRZO46Y.js";import{formatProviderError,normalizeProviderError}from"./chunk-PISJX26Y.js";import{headersToRecord}from"./chunk-UTB4DTYQ.js";import"./chunk-FFMDRXC4.js";import"./chunk-7DDKXS2Q.js";import{clampThinkingLevel,getDeclaredTools,resolveTranscript,resolveTranscriptTools}from"./chunk-RLMZZV4Q.js";import{AssistantMessageEventStream}from"./chunk-LPXNMA2W.js";import{getIdentityHeaders}from"./chunk-QYYUGS66.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.3";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,2 +1,2 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{clampThinkingLevel}from"./chunk-3MKQN3ZR.js";import{getSystemMessageText}from"./chunk-6L2FT6AE.js";var UnsupportedStrictJsonSchemaError=class extends Error{},UNSUPPORTED_STRICT_SCHEMA_KEYS=["$ref","$defs","definitions","allOf","oneOf","patternProperties","dependentSchemas","dependencies","unevaluatedProperties","propertyNames","contains","prefixItems","not","if","then","else"];function isJsonSchemaObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isStructuredSchema(schema){if(!isJsonSchemaObject(schema))return!1;let types=typeof schema.type=="string"?[schema.type]:Array.isArray(schema.type)?schema.type:[];return types.includes("object")||types.includes("array")||schema.properties!==void 0||schema.items!==void 0}function schemaAllowsNull(schema){return isJsonSchemaObject(schema)?schema.type==="null"||Array.isArray(schema.type)&&schema.type.includes("null")||schema.const===null||Array.isArray(schema.enum)&&schema.enum.includes(null)?!0:Array.isArray(schema.anyOf)&&schema.anyOf.some(variant=>schemaAllowsNull(variant)):!1}function makeJsonSchemaNodeStrict(schema,isUnsupportedKeyword){if(!isJsonSchemaObject(schema))throw new UnsupportedStrictJsonSchemaError("boolean schemas are unsupported");for(let key of UNSUPPORTED_STRICT_SCHEMA_KEYS)if(schema[key]!==void 0)throw new UnsupportedStrictJsonSchemaError(`${key} schemas are unsupported`);if(isUnsupportedKeyword){for(let[key,value]of Object.entries(schema))if(isUnsupportedKeyword(key,value))throw new UnsupportedStrictJsonSchemaError(`${key}: ${JSON.stringify(value)} is unsupported`)}if(schema.type===void 0&&schema.anyOf===void 0&&schema.enum===void 0)throw new UnsupportedStrictJsonSchemaError("schemas without a type are unsupported");if(schema.anyOf!==void 0){if(!Array.isArray(schema.anyOf)||schema.anyOf.length===0)throw new UnsupportedStrictJsonSchemaError("anyOf must contain at least one schema");for(let variant of schema.anyOf){if(isStructuredSchema(variant))throw new UnsupportedStrictJsonSchemaError("object and array unions are unsupported");makeJsonSchemaNodeStrict(variant,isUnsupportedKeyword)}}if(schema.items!==void 0){if(Array.isArray(schema.items))throw new UnsupportedStrictJsonSchemaError("tuple schemas are unsupported");makeJsonSchemaNodeStrict(schema.items,isUnsupportedKeyword)}let isObjectSchema=schema.type==="object";if(schema.properties!==void 0&&!isObjectSchema)throw new UnsupportedStrictJsonSchemaError("properties require type object");if(!isObjectSchema)return;if(schema.additionalProperties!==void 0&&schema.additionalProperties!==!1)throw new UnsupportedStrictJsonSchemaError("schema-valued or true additionalProperties is unsupported");if(schema.properties!==void 0&&!isJsonSchemaObject(schema.properties))throw new UnsupportedStrictJsonSchemaError("object properties must be a schema map");if(schema.required!==void 0&&(!Array.isArray(schema.required)||schema.required.some(key=>typeof key!="string")))throw new UnsupportedStrictJsonSchemaError("object required must be a string array");let properties=schema.properties??{},propertyNames=Object.keys(properties),required=new Set(Array.isArray(schema.required)?schema.required:[]);if([...required].some(key=>!propertyNames.includes(key)))throw new UnsupportedStrictJsonSchemaError("required contains an unknown property");for(let[key,property]of Object.entries(properties))makeJsonSchemaNodeStrict(property,isUnsupportedKeyword),!required.has(key)&&!schemaAllowsNull(property)&&(properties[key]={anyOf:[property,{type:"null"}]});schema.required=propertyNames,schema.additionalProperties=!1}function makeStrictJsonSchema(schema,isUnsupportedKeyword){let cloned=structuredClone(schema);if(!isJsonSchemaObject(cloned))throw new UnsupportedStrictJsonSchemaError("root schema must have type object");if(makeJsonSchemaNodeStrict(cloned,isUnsupportedKeyword),cloned.type!=="object")throw new UnsupportedStrictJsonSchemaError("root schema must have type object");return cloned}function prefersJsonSchemaStrictSampling(tool){let config=tool.constrainedSampling;return!!config&&config.type==="json_schema"&&config.strict==="prefer"}function getJsonSchemaToolParameters(tool,strict){return strict===!0?makeStrictJsonSchema(tool.parameters):tool.parameters}function getGrammarToolInput(toolName,arguments_,inputProperty){let input=arguments_[inputProperty];if(typeof input!="string")throw new Error(`Grammar tool call "${toolName}" requires argument "${inputProperty}" to be a string.`);return input}function appendGrammarToolInputJsonDelta(buffer,inputProperty,inputDelta){if(buffer.closed)throw new Error(`grammar tool input for property "${inputProperty}" changed after it was closed`);if(inputDelta.length!==0)return buffer.input+=inputDelta,grammarToolInputJsonStart(buffer,inputProperty)+JSON.stringify(inputDelta).slice(1,-1)}function closeGrammarToolInputJson(buffer,inputProperty,finalInput){if(buffer.closed){if(finalInput===void 0||finalInput===buffer.input)return;throw new Error(`grammar tool input for property "${inputProperty}" changed after it was closed`)}if(finalInput!==void 0&&!finalInput.startsWith(buffer.input))throw new Error(`grammar tool input for property "${inputProperty}" changed non-monotonically`);let rest=finalInput===void 0?"":finalInput.slice(buffer.input.length);return finalInput!==void 0&&(buffer.input=finalInput),buffer.closed=!0,`${grammarToolInputJsonStart(buffer,inputProperty)}${JSON.stringify(rest).slice(1,-1)}"}`}function grammarToolInputJsonStart(buffer,inputProperty){return buffer.started?"":(buffer.started=!0,`{${JSON.stringify(inputProperty)}:"`)}function inferGrammarInputProperty(tool){let schema=tool.parameters;if(schema.type!=="object")throw new Error("grammar constrained sampling requires an object parameter schema");if(!Array.isArray(schema.required)||schema.required.length!==1||typeof schema.required[0]!="string")throw new Error("grammar constrained sampling requires exactly one required string property");let inputProperty=schema.required[0];if(!schema.properties?.[inputProperty])throw new Error(`grammar constrained sampling requires a properties entry for ${inputProperty}`);if(schema.properties[inputProperty]?.type!=="string")throw new Error(`grammar constrained sampling property ${inputProperty} must have type string`);return inputProperty}function resolveJsonSchemaStrictSampling(tool,supportsStrictMode,isUnsupportedKeyword){let config=tool.constrainedSampling;if(!(!config||config.type!=="json_schema")){if(supportsStrictMode)try{return makeStrictJsonSchema(tool.parameters,isUnsupportedKeyword),!0}catch(error){if(!(error instanceof UnsupportedStrictJsonSchemaError))throw error;if(config.strict!=="require")return;throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but ${error.message}.`)}if(config.strict==="require")throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`)}}function resolveGrammarConstrainedSampling(tool,supportsOpenAIGrammarTools){let config=tool.constrainedSampling;if(!config||config.type!=="grammar"||!supportsOpenAIGrammarTools)return;let larkDefinition=config.variants.openai_lark,regexDefinition=config.variants.openai_regex,hasLarkDefinition=typeof larkDefinition=="string"&&larkDefinition.trim().length>0,hasRegexDefinition=typeof regexDefinition=="string"&&regexDefinition.trim().length>0;if(!hasLarkDefinition&&!hasRegexDefinition)throw new Error(`Tool "${tool.name}" cannot use grammar constrained sampling: no supported grammar variant was provided.`);try{return{format:hasLarkDefinition?"lark":"regex",definition:hasLarkDefinition?larkDefinition:regexDefinition,inputProperty:inferGrammarInputProperty(tool)}}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`Tool "${tool.name}" cannot use grammar constrained sampling: ${message}.`)}}function createGrammarToolInputProperties(tools,supportsOpenAIGrammarTools){let properties=new Map;for(let tool of tools??[]){let grammar=resolveGrammarConstrainedSampling(tool,supportsOpenAIGrammarTools);grammar&&properties.set(tool.name,grammar.inputProperty)}return properties}var CHARS_PER_TOKEN=3.5,ESTIMATED_IMAGE_CHARS=4800;function calculateContextTokens(usage){return usage.totalTokens||usage.input+usage.output+usage.cacheRead+usage.cacheWrite}function safeJsonStringify(value){try{return JSON.stringify(value)??"undefined"}catch{return"[unserializable]"}}function estimateTextAndImageContentChars(content){if(typeof content=="string")return content.length;let chars=0;for(let block of content)chars+=block.type==="text"?block.text.length:ESTIMATED_IMAGE_CHARS;return chars}function estimateTextTokens(text){return Math.ceil(text.length/CHARS_PER_TOKEN)}function estimateTextAndImageContentTokens(content){return Math.ceil(estimateTextAndImageContentChars(content)/CHARS_PER_TOKEN)}function estimateMessageTokens(message){let chars=0;if(message.role==="system")return estimateTextTokens(getSystemMessageText(message))+estimateToolsTokens(message.toolsAdded)+estimateToolsTokens(message.toolsRemoved);if(message.role==="user"||message.role==="toolResult")return estimateTextAndImageContentTokens(message.content);for(let block of message.content)block.type==="text"?chars+=block.text.length:block.type==="thinking"?chars+=block.thinking.length:chars+=block.name.length+safeJsonStringify(block.arguments).length;return Math.ceil(chars/CHARS_PER_TOKEN)}function getLastAssistantUsageInfo(messages){let latestPrefixTimestamp=Number.NEGATIVE_INFINITY,usageInfo;for(let i=0;i<messages.length;i++){let message=messages[i];if(message.role==="assistant"){let assistant=message;assistant.timestamp>=latestPrefixTimestamp&&assistant.stopReason!=="aborted"&&assistant.stopReason!=="error"&&calculateContextTokens(assistant.usage)>0&&(usageInfo={usage:assistant.usage,index:i})}latestPrefixTimestamp=Math.max(latestPrefixTimestamp,message.timestamp)}return usageInfo}function estimateContextTokens(context){let messages="messages"in context?context.messages:context,usageInfo=getLastAssistantUsageInfo(messages);if(usageInfo){let usageTokens=calculateContextTokens(usageInfo.usage),trailingTokens=0;for(let i=usageInfo.index+1;i<messages.length;i++)trailingTokens+=estimateMessageTokens(messages[i]);return{tokens:usageTokens+trailingTokens,usageTokens,trailingTokens,lastUsageIndex:usageInfo.index}}let tokens=0;for(let message of messages)tokens+=estimateMessageTokens(message);return{tokens,usageTokens:0,trailingTokens:tokens,lastUsageIndex:null}}function estimateToolsTokens(tools){return!tools||tools.length===0?0:estimateTextTokens(safeJsonStringify(tools))}var CONTEXT_SAFETY_TOKENS=4096,CONTEXT_SAFETY_RATIO=.15,MIN_OUTPUT_WITH_RATIO_MARGIN=32768,MIN_MAX_TOKENS=1;function clampMaxTokensToContext(model,context,maxTokens){if(model.contextWindow<=0)return Math.max(MIN_MAX_TOKENS,maxTokens);let input=estimateContextTokens(context).tokens,margin=Math.max(CONTEXT_SAFETY_TOKENS,Math.ceil(input*CONTEXT_SAFETY_RATIO)),room=model.contextWindow-input-margin;return room<MIN_OUTPUT_WITH_RATIO_MARGIN&&(room=Math.min(MIN_OUTPUT_WITH_RATIO_MARGIN,model.contextWindow-input-CONTEXT_SAFETY_TOKENS)),Math.min(maxTokens,Math.max(MIN_MAX_TOKENS,room))}function resolveSamplingParams(model,thinkingLevel,requestParams){let effectiveThinkingLevel=clampThinkingLevel(model,thinkingLevel),thinkingLevelParams=model.samplingParamsByThinkingLevel?.[effectiveThinkingLevel];return model.samplingParams||thinkingLevelParams||requestParams?{...model.samplingParams,...thinkingLevelParams,...requestParams}:void 0}function buildBaseOptions(model,context,options,apiKey){let samplingParams=resolveSamplingParams(model,options?.reasoning??"off",options?.samplingParams);return{temperature:options?.temperature,samplingParams,maxTokens:clampMaxTokensToContext(model,context,options?.maxTokens??model.maxTokens),signal:options?.signal,telemetry:options?.telemetry,apiKey:apiKey||options?.apiKey,fetch:options?.fetch,transport:options?.transport,cacheRetention:options?.cacheRetention,sessionId:options?.sessionId,disableContinuation:options?.disableContinuation,headers:options?.headers,identity:options?.identity,onPayload:options?.onPayload,onResponse:options?.onResponse,onProviderStreamEvent:options?.onProviderStreamEvent,timeoutMs:options?.timeoutMs,websocketConnectTimeoutMs:options?.websocketConnectTimeoutMs,maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,metadata:options?.metadata,env:options?.env}}var MIN_ANSWER_TOKENS=1024,DEFAULT_THINKING_BUDGETS={minimal:1024,low:2048,medium:8192,high:16384};function clampReasoning(effort){return effort==="xhigh"||effort==="max"?"high":effort}function thinkingBudgetForLevel(reasoningLevel,customBudgets){let budgets={...DEFAULT_THINKING_BUDGETS,...customBudgets},level=clampReasoning(reasoningLevel);return budgets[level]}function clampThinkingBudgetToAnswerRoom(thinkingBudget,ceiling){return Math.min(thinkingBudget,Math.max(0,ceiling-MIN_ANSWER_TOKENS))}function adjustMaxTokensForThinking(baseMaxTokens,modelMaxTokens,reasoningLevel,customBudgets){let thinkingBudget=thinkingBudgetForLevel(reasoningLevel,customBudgets),maxTokens=baseMaxTokens===void 0?modelMaxTokens:Math.min(baseMaxTokens+thinkingBudget,modelMaxTokens);return maxTokens<=thinkingBudget&&(thinkingBudget=clampThinkingBudgetToAnswerRoom(thinkingBudget,maxTokens)),{maxTokens,thinkingBudget}}var NON_VISION_USER_IMAGE_PLACEHOLDER="(image omitted: model does not support images)",NON_VISION_TOOL_IMAGE_PLACEHOLDER="(tool image omitted: model does not support images)",ERROR_TOOL_IMAGE_PLACEHOLDER="(image attached after the tool results)";function splitErrorToolResultImages(msg){if(!msg.isError)return;let images=msg.content.filter(block=>block.type==="image");if(images.length!==0)return{content:replaceImagesWithPlaceholder(msg.content,ERROR_TOOL_IMAGE_PLACEHOLDER),caption:`Images from the error result of tool call ${msg.toolCallId} (${msg.toolName}):`,images}}function replaceImagesWithPlaceholder(content,placeholder){let result=[],previousWasPlaceholder=!1;for(let block of content){if(block.type==="image"){previousWasPlaceholder||result.push({type:"text",text:placeholder}),previousWasPlaceholder=!0;continue}result.push(block),previousWasPlaceholder=block.text===placeholder}return result}function downgradeUnsupportedImages(messages,model){return model.input.includes("image")?messages:messages.map(msg=>msg.role==="user"&&Array.isArray(msg.content)?{...msg,content:replaceImagesWithPlaceholder(msg.content,NON_VISION_USER_IMAGE_PLACEHOLDER)}:msg.role==="toolResult"?{...msg,content:replaceImagesWithPlaceholder(msg.content,NON_VISION_TOOL_IMAGE_PLACEHOLDER)}:msg)}function transformMessages(messages,model,normalizeToolCallId){let toolCallIdMap=new Map,normalizedMessages=messages.map(msg=>msg.content==null?{...msg,content:[]}:msg),transformed=downgradeUnsupportedImages(normalizedMessages,model).map(msg=>{if(msg.role==="system"||msg.role==="user")return msg;if(msg.role==="toolResult"){let normalizedId=toolCallIdMap.get(msg.toolCallId);return normalizedId&&normalizedId!==msg.toolCallId?{...msg,toolCallId:normalizedId}:msg}if(msg.role==="assistant"){let assistantMsg=msg,isSameModel=assistantMsg.provider===model.provider&&assistantMsg.api===model.api&&assistantMsg.model===model.id,transformedContent=assistantMsg.content.flatMap(block=>{if(block.type==="thinking")return isSameModel?block.redacted||block.thinkingSignature?block:!block.thinking||block.thinking.trim()===""?[]:block:[];if(block.type==="text")return isSameModel?block:{type:"text",text:block.text};if(block.type==="toolCall"){let toolCall=block,normalizedToolCall=toolCall;if(!isSameModel&&toolCall.thoughtSignature&&(normalizedToolCall={...toolCall},delete normalizedToolCall.thoughtSignature),!isSameModel&&normalizeToolCallId){let normalizedId=normalizeToolCallId(toolCall.id,model,assistantMsg);normalizedId!==toolCall.id&&(toolCallIdMap.set(toolCall.id,normalizedId),normalizedToolCall={...normalizedToolCall,id:normalizedId})}return normalizedToolCall}return block});return{...assistantMsg,content:transformedContent}}return msg}),result=[],pendingToolCalls=[],existingToolResultIds=new Set,heldSystemMessages=[],closePendingToolCalls=()=>{if(pendingToolCalls.length>0){for(let tc of pendingToolCalls)existingToolResultIds.has(tc.id)||result.push({role:"toolResult",toolCallId:tc.id,toolName:tc.name,content:[{type:"text",text:"No result provided"}],isError:!0,timestamp:Date.now()});pendingToolCalls=[],existingToolResultIds=new Set}result.push(...heldSystemMessages),heldSystemMessages.length=0};for(let i=0;i<transformed.length;i++){let msg=transformed[i];if(msg.role==="assistant"){closePendingToolCalls();let assistantMsg=msg;if(assistantMsg.stopReason==="error"||assistantMsg.stopReason==="aborted")continue;let toolCalls=assistantMsg.content.filter(b=>b.type==="toolCall");toolCalls.length>0&&(pendingToolCalls=toolCalls,existingToolResultIds=new Set),result.push(msg)}else msg.role==="toolResult"?(existingToolResultIds.add(msg.toolCallId),result.push(msg)):msg.role==="system"?pendingToolCalls.length>0?heldSystemMessages.push(msg):result.push(msg):(msg.role==="user"&&closePendingToolCalls(),result.push(msg))}return closePendingToolCalls(),result}export{prefersJsonSchemaStrictSampling,getJsonSchemaToolParameters,getGrammarToolInput,appendGrammarToolInputJsonDelta,closeGrammarToolInputJson,resolveJsonSchemaStrictSampling,resolveGrammarConstrainedSampling,createGrammarToolInputProperties,clampMaxTokensToContext,resolveSamplingParams,buildBaseOptions,thinkingBudgetForLevel,clampThinkingBudgetToAnswerRoom,adjustMaxTokensForThinking,splitErrorToolResultImages,transformMessages};
2
+ import{clampThinkingLevel}from"./chunk-RLMZZV4Q.js";import{getSystemMessageText}from"./chunk-QYYUGS66.js";var UnsupportedStrictJsonSchemaError=class extends Error{},UNSUPPORTED_STRICT_SCHEMA_KEYS=["$ref","$defs","definitions","allOf","oneOf","patternProperties","dependentSchemas","dependencies","unevaluatedProperties","propertyNames","contains","prefixItems","not","if","then","else"];function isJsonSchemaObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isStructuredSchema(schema){if(!isJsonSchemaObject(schema))return!1;let types=typeof schema.type=="string"?[schema.type]:Array.isArray(schema.type)?schema.type:[];return types.includes("object")||types.includes("array")||schema.properties!==void 0||schema.items!==void 0}function schemaAllowsNull(schema){return isJsonSchemaObject(schema)?schema.type==="null"||Array.isArray(schema.type)&&schema.type.includes("null")||schema.const===null||Array.isArray(schema.enum)&&schema.enum.includes(null)?!0:Array.isArray(schema.anyOf)&&schema.anyOf.some(variant=>schemaAllowsNull(variant)):!1}function makeJsonSchemaNodeStrict(schema,isUnsupportedKeyword){if(!isJsonSchemaObject(schema))throw new UnsupportedStrictJsonSchemaError("boolean schemas are unsupported");for(let key of UNSUPPORTED_STRICT_SCHEMA_KEYS)if(schema[key]!==void 0)throw new UnsupportedStrictJsonSchemaError(`${key} schemas are unsupported`);if(isUnsupportedKeyword){for(let[key,value]of Object.entries(schema))if(isUnsupportedKeyword(key,value))throw new UnsupportedStrictJsonSchemaError(`${key}: ${JSON.stringify(value)} is unsupported`)}if(schema.type===void 0&&schema.anyOf===void 0&&schema.enum===void 0)throw new UnsupportedStrictJsonSchemaError("schemas without a type are unsupported");if(schema.anyOf!==void 0){if(!Array.isArray(schema.anyOf)||schema.anyOf.length===0)throw new UnsupportedStrictJsonSchemaError("anyOf must contain at least one schema");for(let variant of schema.anyOf){if(isStructuredSchema(variant))throw new UnsupportedStrictJsonSchemaError("object and array unions are unsupported");makeJsonSchemaNodeStrict(variant,isUnsupportedKeyword)}}if(schema.items!==void 0){if(Array.isArray(schema.items))throw new UnsupportedStrictJsonSchemaError("tuple schemas are unsupported");makeJsonSchemaNodeStrict(schema.items,isUnsupportedKeyword)}let isObjectSchema=schema.type==="object";if(schema.properties!==void 0&&!isObjectSchema)throw new UnsupportedStrictJsonSchemaError("properties require type object");if(!isObjectSchema)return;if(schema.additionalProperties!==void 0&&schema.additionalProperties!==!1)throw new UnsupportedStrictJsonSchemaError("schema-valued or true additionalProperties is unsupported");if(schema.properties!==void 0&&!isJsonSchemaObject(schema.properties))throw new UnsupportedStrictJsonSchemaError("object properties must be a schema map");if(schema.required!==void 0&&(!Array.isArray(schema.required)||schema.required.some(key=>typeof key!="string")))throw new UnsupportedStrictJsonSchemaError("object required must be a string array");let properties=schema.properties??{},propertyNames=Object.keys(properties),required=new Set(Array.isArray(schema.required)?schema.required:[]);if([...required].some(key=>!propertyNames.includes(key)))throw new UnsupportedStrictJsonSchemaError("required contains an unknown property");for(let[key,property]of Object.entries(properties))makeJsonSchemaNodeStrict(property,isUnsupportedKeyword),!required.has(key)&&!schemaAllowsNull(property)&&(properties[key]={anyOf:[property,{type:"null"}]});schema.required=propertyNames,schema.additionalProperties=!1}function makeStrictJsonSchema(schema,isUnsupportedKeyword){let cloned=structuredClone(schema);if(!isJsonSchemaObject(cloned))throw new UnsupportedStrictJsonSchemaError("root schema must have type object");if(makeJsonSchemaNodeStrict(cloned,isUnsupportedKeyword),cloned.type!=="object")throw new UnsupportedStrictJsonSchemaError("root schema must have type object");return cloned}function prefersJsonSchemaStrictSampling(tool){let config=tool.constrainedSampling;return!!config&&config.type==="json_schema"&&config.strict==="prefer"}function getJsonSchemaToolParameters(tool,strict){return strict===!0?makeStrictJsonSchema(tool.parameters):tool.parameters}function getGrammarToolInput(toolName,arguments_,inputProperty){let input=arguments_[inputProperty];if(typeof input!="string")throw new Error(`Grammar tool call "${toolName}" requires argument "${inputProperty}" to be a string.`);return input}function appendGrammarToolInputJsonDelta(buffer,inputProperty,inputDelta){if(buffer.closed)throw new Error(`grammar tool input for property "${inputProperty}" changed after it was closed`);if(inputDelta.length!==0)return buffer.input+=inputDelta,grammarToolInputJsonStart(buffer,inputProperty)+JSON.stringify(inputDelta).slice(1,-1)}function closeGrammarToolInputJson(buffer,inputProperty,finalInput){if(buffer.closed){if(finalInput===void 0||finalInput===buffer.input)return;throw new Error(`grammar tool input for property "${inputProperty}" changed after it was closed`)}if(finalInput!==void 0&&!finalInput.startsWith(buffer.input))throw new Error(`grammar tool input for property "${inputProperty}" changed non-monotonically`);let rest=finalInput===void 0?"":finalInput.slice(buffer.input.length);return finalInput!==void 0&&(buffer.input=finalInput),buffer.closed=!0,`${grammarToolInputJsonStart(buffer,inputProperty)}${JSON.stringify(rest).slice(1,-1)}"}`}function grammarToolInputJsonStart(buffer,inputProperty){return buffer.started?"":(buffer.started=!0,`{${JSON.stringify(inputProperty)}:"`)}function inferGrammarInputProperty(tool){let schema=tool.parameters;if(schema.type!=="object")throw new Error("grammar constrained sampling requires an object parameter schema");if(!Array.isArray(schema.required)||schema.required.length!==1||typeof schema.required[0]!="string")throw new Error("grammar constrained sampling requires exactly one required string property");let inputProperty=schema.required[0];if(!schema.properties?.[inputProperty])throw new Error(`grammar constrained sampling requires a properties entry for ${inputProperty}`);if(schema.properties[inputProperty]?.type!=="string")throw new Error(`grammar constrained sampling property ${inputProperty} must have type string`);return inputProperty}function resolveJsonSchemaStrictSampling(tool,supportsStrictMode,isUnsupportedKeyword){let config=tool.constrainedSampling;if(!(!config||config.type!=="json_schema")){if(supportsStrictMode)try{return makeStrictJsonSchema(tool.parameters,isUnsupportedKeyword),!0}catch(error){if(!(error instanceof UnsupportedStrictJsonSchemaError))throw error;if(config.strict!=="require")return;throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but ${error.message}.`)}if(config.strict==="require")throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`)}}function resolveGrammarConstrainedSampling(tool,supportsOpenAIGrammarTools){let config=tool.constrainedSampling;if(!config||config.type!=="grammar"||!supportsOpenAIGrammarTools)return;let larkDefinition=config.variants.openai_lark,regexDefinition=config.variants.openai_regex,hasLarkDefinition=typeof larkDefinition=="string"&&larkDefinition.trim().length>0,hasRegexDefinition=typeof regexDefinition=="string"&&regexDefinition.trim().length>0;if(!hasLarkDefinition&&!hasRegexDefinition)throw new Error(`Tool "${tool.name}" cannot use grammar constrained sampling: no supported grammar variant was provided.`);try{return{format:hasLarkDefinition?"lark":"regex",definition:hasLarkDefinition?larkDefinition:regexDefinition,inputProperty:inferGrammarInputProperty(tool)}}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`Tool "${tool.name}" cannot use grammar constrained sampling: ${message}.`)}}function createGrammarToolInputProperties(tools,supportsOpenAIGrammarTools){let properties=new Map;for(let tool of tools??[]){let grammar=resolveGrammarConstrainedSampling(tool,supportsOpenAIGrammarTools);grammar&&properties.set(tool.name,grammar.inputProperty)}return properties}var CHARS_PER_TOKEN=3.5,ESTIMATED_IMAGE_CHARS=4800;function calculateContextTokens(usage){return usage.totalTokens||usage.input+usage.output+usage.cacheRead+usage.cacheWrite}function safeJsonStringify(value){try{return JSON.stringify(value)??"undefined"}catch{return"[unserializable]"}}function estimateTextAndImageContentChars(content){if(typeof content=="string")return content.length;let chars=0;for(let block of content)chars+=block.type==="text"?block.text.length:ESTIMATED_IMAGE_CHARS;return chars}function estimateTextTokens(text){return Math.ceil(text.length/CHARS_PER_TOKEN)}function estimateTextAndImageContentTokens(content){return Math.ceil(estimateTextAndImageContentChars(content)/CHARS_PER_TOKEN)}function estimateMessageTokens(message){let chars=0;if(message.role==="system")return estimateTextTokens(getSystemMessageText(message))+estimateToolsTokens(message.toolsAdded)+estimateToolsTokens(message.toolsRemoved);if(message.role==="user"||message.role==="toolResult")return estimateTextAndImageContentTokens(message.content);for(let block of message.content)block.type==="text"?chars+=block.text.length:block.type==="thinking"?chars+=block.thinking.length:chars+=block.name.length+safeJsonStringify(block.arguments).length;return Math.ceil(chars/CHARS_PER_TOKEN)}function getLastAssistantUsageInfo(messages){let latestPrefixTimestamp=Number.NEGATIVE_INFINITY,usageInfo;for(let i=0;i<messages.length;i++){let message=messages[i];if(message.role==="assistant"){let assistant=message;assistant.timestamp>=latestPrefixTimestamp&&assistant.stopReason!=="aborted"&&assistant.stopReason!=="error"&&calculateContextTokens(assistant.usage)>0&&(usageInfo={usage:assistant.usage,index:i})}latestPrefixTimestamp=Math.max(latestPrefixTimestamp,message.timestamp)}return usageInfo}function estimateContextTokens(context){let messages="messages"in context?context.messages:context,usageInfo=getLastAssistantUsageInfo(messages);if(usageInfo){let usageTokens=calculateContextTokens(usageInfo.usage),trailingTokens=0;for(let i=usageInfo.index+1;i<messages.length;i++)trailingTokens+=estimateMessageTokens(messages[i]);return{tokens:usageTokens+trailingTokens,usageTokens,trailingTokens,lastUsageIndex:usageInfo.index}}let tokens=0;for(let message of messages)tokens+=estimateMessageTokens(message);return{tokens,usageTokens:0,trailingTokens:tokens,lastUsageIndex:null}}function estimateToolsTokens(tools){return!tools||tools.length===0?0:estimateTextTokens(safeJsonStringify(tools))}var CONTEXT_SAFETY_TOKENS=4096,CONTEXT_SAFETY_RATIO=.15,MIN_OUTPUT_WITH_RATIO_MARGIN=32768,MIN_MAX_TOKENS=1;function clampMaxTokensToContext(model,context,maxTokens){if(model.contextWindow<=0)return Math.max(MIN_MAX_TOKENS,maxTokens);let input=estimateContextTokens(context).tokens,margin=Math.max(CONTEXT_SAFETY_TOKENS,Math.ceil(input*CONTEXT_SAFETY_RATIO)),room=model.contextWindow-input-margin;return room<MIN_OUTPUT_WITH_RATIO_MARGIN&&(room=Math.min(MIN_OUTPUT_WITH_RATIO_MARGIN,model.contextWindow-input-CONTEXT_SAFETY_TOKENS)),Math.min(maxTokens,Math.max(MIN_MAX_TOKENS,room))}function resolveSamplingParams(model,thinkingLevel,requestParams){let effectiveThinkingLevel=clampThinkingLevel(model,thinkingLevel),thinkingLevelParams=model.samplingParamsByThinkingLevel?.[effectiveThinkingLevel];return model.samplingParams||thinkingLevelParams||requestParams?{...model.samplingParams,...thinkingLevelParams,...requestParams}:void 0}function buildBaseOptions(model,context,options,apiKey){let samplingParams=resolveSamplingParams(model,options?.reasoning??"off",options?.samplingParams);return{temperature:options?.temperature,samplingParams,maxTokens:clampMaxTokensToContext(model,context,options?.maxTokens??model.maxTokens),signal:options?.signal,telemetry:options?.telemetry,apiKey:apiKey||options?.apiKey,fetch:options?.fetch,transport:options?.transport,cacheRetention:options?.cacheRetention,sessionId:options?.sessionId,disableContinuation:options?.disableContinuation,headers:options?.headers,identity:options?.identity,onPayload:options?.onPayload,onResponse:options?.onResponse,onProviderStreamEvent:options?.onProviderStreamEvent,timeoutMs:options?.timeoutMs,websocketConnectTimeoutMs:options?.websocketConnectTimeoutMs,maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,metadata:options?.metadata,env:options?.env}}var MIN_ANSWER_TOKENS=1024,DEFAULT_THINKING_BUDGETS={minimal:1024,low:2048,medium:8192,high:16384};function clampReasoning(effort){return effort==="xhigh"||effort==="max"?"high":effort}function thinkingBudgetForLevel(reasoningLevel,customBudgets){let budgets={...DEFAULT_THINKING_BUDGETS,...customBudgets},level=clampReasoning(reasoningLevel);return budgets[level]}function clampThinkingBudgetToAnswerRoom(thinkingBudget,ceiling){return Math.min(thinkingBudget,Math.max(0,ceiling-MIN_ANSWER_TOKENS))}function adjustMaxTokensForThinking(baseMaxTokens,modelMaxTokens,reasoningLevel,customBudgets){let thinkingBudget=thinkingBudgetForLevel(reasoningLevel,customBudgets),maxTokens=baseMaxTokens===void 0?modelMaxTokens:Math.min(baseMaxTokens+thinkingBudget,modelMaxTokens);return maxTokens<=thinkingBudget&&(thinkingBudget=clampThinkingBudgetToAnswerRoom(thinkingBudget,maxTokens)),{maxTokens,thinkingBudget}}var NON_VISION_USER_IMAGE_PLACEHOLDER="(image omitted: model does not support images)",NON_VISION_TOOL_IMAGE_PLACEHOLDER="(tool image omitted: model does not support images)",ERROR_TOOL_IMAGE_PLACEHOLDER="(image attached after the tool results)";function splitErrorToolResultImages(msg){if(!msg.isError)return;let images=msg.content.filter(block=>block.type==="image");if(images.length!==0)return{content:replaceImagesWithPlaceholder(msg.content,ERROR_TOOL_IMAGE_PLACEHOLDER),caption:`Images from the error result of tool call ${msg.toolCallId} (${msg.toolName}):`,images}}function replaceImagesWithPlaceholder(content,placeholder){let result=[],previousWasPlaceholder=!1;for(let block of content){if(block.type==="image"){previousWasPlaceholder||result.push({type:"text",text:placeholder}),previousWasPlaceholder=!0;continue}result.push(block),previousWasPlaceholder=block.text===placeholder}return result}function downgradeUnsupportedImages(messages,model){return model.input.includes("image")?messages:messages.map(msg=>msg.role==="user"&&Array.isArray(msg.content)?{...msg,content:replaceImagesWithPlaceholder(msg.content,NON_VISION_USER_IMAGE_PLACEHOLDER)}:msg.role==="toolResult"?{...msg,content:replaceImagesWithPlaceholder(msg.content,NON_VISION_TOOL_IMAGE_PLACEHOLDER)}:msg)}function transformMessages(messages,model,normalizeToolCallId){let toolCallIdMap=new Map,normalizedMessages=messages.map(msg=>msg.content==null?{...msg,content:[]}:msg),transformed=downgradeUnsupportedImages(normalizedMessages,model).map(msg=>{if(msg.role==="system"||msg.role==="user")return msg;if(msg.role==="toolResult"){let normalizedId=toolCallIdMap.get(msg.toolCallId);return normalizedId&&normalizedId!==msg.toolCallId?{...msg,toolCallId:normalizedId}:msg}if(msg.role==="assistant"){let assistantMsg=msg,isSameModel=assistantMsg.provider===model.provider&&assistantMsg.api===model.api&&assistantMsg.model===model.id,transformedContent=assistantMsg.content.flatMap(block=>{if(block.type==="thinking")return isSameModel?block.redacted||block.thinkingSignature?block:!block.thinking||block.thinking.trim()===""?[]:block:[];if(block.type==="text")return isSameModel?block:{type:"text",text:block.text};if(block.type==="toolCall"){let toolCall=block,normalizedToolCall=toolCall;if(!isSameModel&&toolCall.thoughtSignature&&(normalizedToolCall={...toolCall},delete normalizedToolCall.thoughtSignature),!isSameModel&&normalizeToolCallId){let normalizedId=normalizeToolCallId(toolCall.id,model,assistantMsg);normalizedId!==toolCall.id&&(toolCallIdMap.set(toolCall.id,normalizedId),normalizedToolCall={...normalizedToolCall,id:normalizedId})}return normalizedToolCall}return block});return{...assistantMsg,content:transformedContent}}return msg}),result=[],pendingToolCalls=[],existingToolResultIds=new Set,heldSystemMessages=[],closePendingToolCalls=()=>{if(pendingToolCalls.length>0){for(let tc of pendingToolCalls)existingToolResultIds.has(tc.id)||result.push({role:"toolResult",toolCallId:tc.id,toolName:tc.name,content:[{type:"text",text:"No result provided"}],isError:!0,timestamp:Date.now()});pendingToolCalls=[],existingToolResultIds=new Set}result.push(...heldSystemMessages),heldSystemMessages.length=0};for(let i=0;i<transformed.length;i++){let msg=transformed[i];if(msg.role==="assistant"){closePendingToolCalls();let assistantMsg=msg;if(assistantMsg.stopReason==="error"||assistantMsg.stopReason==="aborted")continue;let toolCalls=assistantMsg.content.filter(b=>b.type==="toolCall");toolCalls.length>0&&(pendingToolCalls=toolCalls,existingToolResultIds=new Set),result.push(msg)}else msg.role==="toolResult"?(existingToolResultIds.add(msg.toolCallId),result.push(msg)):msg.role==="system"?pendingToolCalls.length>0?heldSystemMessages.push(msg):result.push(msg):(msg.role==="user"&&closePendingToolCalls(),result.push(msg))}return closePendingToolCalls(),result}export{prefersJsonSchemaStrictSampling,getJsonSchemaToolParameters,getGrammarToolInput,appendGrammarToolInputJsonDelta,closeGrammarToolInputJson,resolveJsonSchemaStrictSampling,resolveGrammarConstrainedSampling,createGrammarToolInputProperties,clampMaxTokensToContext,resolveSamplingParams,buildBaseOptions,thinkingBudgetForLevel,clampThinkingBudgetToAnswerRoom,adjustMaxTokensForThinking,splitErrorToolResultImages,transformMessages};
@@ -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-3UNTEQ65.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{ToolCallArgumentsStream}from"./chunk-FFMDRXC4.js";import{calculateCost,resolveTranscript,resolveTranscriptTools}from"./chunk-RLMZZV4Q.js";import{appendAssistantMessageDiagnostic}from"./chunk-LPXNMA2W.js";import{getSystemMessageText,renderSystemMessageUpdate}from"./chunk-QYYUGS66.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(`
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{isRecord,parseClassifierUsage,postClassifierRequest,requiredNumber}from"./chunk-RUI3NOFB.js";import{formatProviderError,normalizeProviderError}from"./chunk-E3MJ4MPN.js";var IMAGE_OPT_IN_HEADERS={"TypeSafe-Danger-Zone-Images":"true"};function probabilities(label,value,id){if(!isRecord(value))throw new Error(`${label} returned invalid probabilities for ${id}`);return Object.fromEntries(Object.entries(value).map(([key,probability])=>[key,requiredNumber(label,probability,`probability for ${id}.${key}`)]))}function parseAnswers(label,value,context){if(!isRecord(value))throw new Error(`${label} returned an unexpected response`);let answers=[];for(let[id,question]of Object.entries(context.questions)){let answer=value[id];if(!isRecord(answer))throw new Error(`${label} did not return an answer for ${id}`);if(question.type==="choice"){if(answer.type!=="choice"||typeof answer.choice!="string")throw new Error(`${label} did not return a choice answer for ${id}`);answers.push([id,{type:"choice",choice:answer.choice,probabilities:probabilities(label,answer.probabilities,id),confidence:requiredNumber(label,answer.confidence,`confidence for ${id}`)}])}else if(question.type==="score"){if(answer.type!=="score")throw new Error(`${label} did not return a score answer for ${id}`);answers.push([id,{type:"score",score:requiredNumber(label,answer.score,`score for ${id}`),confidence:requiredNumber(label,answer.confidence,`confidence for ${id}`)}])}else{if(answer.type!=="noul")throw new Error(`${label} did not return a bool answer for ${id}`);answers.push([id,{type:"bool",probability:requiredNumber(label,answer.noul,`probability for ${id}`)}])}}return Object.fromEntries(answers)}var ASSET_FORMATS={"image/png":"png","image/jpeg":"jpeg"},DATA_URL_TYPES=new Set(["image/png","image/jpeg","image/webp"]),MAX_DATA_URL_IMAGES=4;function addImages(label,model,input,images,request){if(input==="images"){if(images.length>MAX_DATA_URL_IMAGES)throw new Error(`${label} accepts at most ${MAX_DATA_URL_IMAGES} images for ${model.id}, got ${images.length}`);request.images=images.map(image=>{if(!DATA_URL_TYPES.has(image.mimeType))throw new Error(`${label} accepts PNG, JPEG, and WebP images for ${model.id}, got ${image.mimeType}`);return`data:${image.mimeType};base64,${image.data}`});return}if(input==="state-image-urls"){let parts=images.map(image=>({type:"image_url",image_url:{url:`data:${image.mimeType};base64,${image.data}`}}));request.state=[...parts,request.state];return}let assets={};images.forEach((image,index)=>{let format=ASSET_FORMATS[image.mimeType];if(!format)throw new Error(`${label} accepts PNG and JPEG images for ${model.id}, got ${image.mimeType}`);assets[`<image-${index+1}>`]={type:"image",format,data_base64:image.data}}),request.assets=assets,request.state=[...Object.keys(assets),request.state]}function wireRequest(context){return{state:context.state,questions:Object.fromEntries(Object.entries(context.questions).map(([id,question])=>[id,question.type==="bool"?{...question,type:"noul"}:question]))}}async function classifySystemOne(transport,model,context,options){let output={api:model.api,provider:model.provider,model:model.id,answers:{},stopReason:"stop",timestamp:Date.now()};try{if(model.api!==transport.api)throw new Error(`Unsupported classifier API: ${model.api}`);let request=wireRequest(context),requestOptions=options;if(context.images?.length){if(!model.input.includes("image"))throw new Error(`${transport.label} does not support image input for ${model.id}`);let detected=transport.detectCompat(model),imageInput=model.compat?.imageInput??detected.imageInput;addImages(transport.label,model,imageInput,context.images,request),(model.compat?.sendImageOptInHeader??detected.sendImageOptInHeader)&&(requestOptions={...options,headers:{...IMAGE_OPT_IN_HEADERS,...options?.headers}})}let body=await postClassifierRequest(transport.label,transport.url(model),model,transport.payload(model,request),requestOptions),result=transport.output(body),usage=parseClassifierUsage(result.usage,model);return usage&&(output.usage=usage),output.answers=parseAnswers(transport.label,result.answers,context),output}catch(error){return output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error),`${transport.label} error`),output}}export{classifySystemOne};
2
+ import{isRecord,parseClassifierUsage,postClassifierRequest,requiredNumber}from"./chunk-NEFH2K3C.js";import{formatProviderError,normalizeProviderError}from"./chunk-PISJX26Y.js";var IMAGE_OPT_IN_HEADERS={"TypeSafe-Danger-Zone-Images":"true"};function probabilities(label,value,id){if(!isRecord(value))throw new Error(`${label} returned invalid probabilities for ${id}`);return Object.fromEntries(Object.entries(value).map(([key,probability])=>[key,requiredNumber(label,probability,`probability for ${id}.${key}`)]))}function parseAnswers(label,value,context){if(!isRecord(value))throw new Error(`${label} returned an unexpected response`);let answers=[];for(let[id,question]of Object.entries(context.questions)){let answer=value[id];if(!isRecord(answer))throw new Error(`${label} did not return an answer for ${id}`);if(question.type==="choice"){if(answer.type!=="choice"||typeof answer.choice!="string")throw new Error(`${label} did not return a choice answer for ${id}`);answers.push([id,{type:"choice",choice:answer.choice,probabilities:probabilities(label,answer.probabilities,id),confidence:requiredNumber(label,answer.confidence,`confidence for ${id}`)}])}else if(question.type==="score"){if(answer.type!=="score")throw new Error(`${label} did not return a score answer for ${id}`);answers.push([id,{type:"score",score:requiredNumber(label,answer.score,`score for ${id}`),confidence:requiredNumber(label,answer.confidence,`confidence for ${id}`)}])}else{if(answer.type!=="noul")throw new Error(`${label} did not return a bool answer for ${id}`);answers.push([id,{type:"bool",probability:requiredNumber(label,answer.noul,`probability for ${id}`)}])}}return Object.fromEntries(answers)}var ASSET_FORMATS={"image/png":"png","image/jpeg":"jpeg"},DATA_URL_TYPES=new Set(["image/png","image/jpeg","image/webp"]),MAX_DATA_URL_IMAGES=4;function addImages(label,model,input,images,request){if(input==="images"){if(images.length>MAX_DATA_URL_IMAGES)throw new Error(`${label} accepts at most ${MAX_DATA_URL_IMAGES} images for ${model.id}, got ${images.length}`);request.images=images.map(image=>{if(!DATA_URL_TYPES.has(image.mimeType))throw new Error(`${label} accepts PNG, JPEG, and WebP images for ${model.id}, got ${image.mimeType}`);return`data:${image.mimeType};base64,${image.data}`});return}if(input==="state-image-urls"){let parts=images.map(image=>({type:"image_url",image_url:{url:`data:${image.mimeType};base64,${image.data}`}}));request.state=[...parts,request.state];return}let assets={};images.forEach((image,index)=>{let format=ASSET_FORMATS[image.mimeType];if(!format)throw new Error(`${label} accepts PNG and JPEG images for ${model.id}, got ${image.mimeType}`);assets[`<image-${index+1}>`]={type:"image",format,data_base64:image.data}}),request.assets=assets,request.state=[...Object.keys(assets),request.state]}function wireRequest(context){return{state:context.state,questions:Object.fromEntries(Object.entries(context.questions).map(([id,question])=>[id,question.type==="bool"?{...question,type:"noul"}:question]))}}async function classifySystemOne(transport,model,context,options){let output={api:model.api,provider:model.provider,model:model.id,answers:{},stopReason:"stop",timestamp:Date.now()};try{if(model.api!==transport.api)throw new Error(`Unsupported classifier API: ${model.api}`);let request=wireRequest(context),requestOptions=options;if(context.images?.length){if(!model.input.includes("image"))throw new Error(`${transport.label} does not support image input for ${model.id}`);let detected=transport.detectCompat(model),imageInput=model.compat?.imageInput??detected.imageInput;addImages(transport.label,model,imageInput,context.images,request),(model.compat?.sendImageOptInHeader??detected.sendImageOptInHeader)&&(requestOptions={...options,headers:{...IMAGE_OPT_IN_HEADERS,...options?.headers}})}let body=await postClassifierRequest(transport.label,transport.url(model),model,transport.payload(model,request),requestOptions),result=transport.output(body),usage=parseClassifierUsage(result.usage,model);return usage&&(output.usage=usage),output.answers=parseAnswers(transport.label,result.answers,context),output}catch(error){return output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error),`${transport.label} error`),output}}export{classifySystemOne};