@yukino.js/yukino 0.0.18 → 0.0.20

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 (89) hide show
  1. package/README.md +27 -30
  2. package/dist/{anthropic-SNLPAGHS.js → anthropic-XJSWCDJD.js} +1 -1
  3. package/dist/browser/dist/static/{highlight-3YCG6EL4.js → highlight-ZDY7K2CR.js} +12 -12
  4. package/dist/browser/dist/static/index.js +77 -70
  5. package/dist/browser/dist/static/{webapi-2B2CRWRA.js → webapi-HZESKPJE.js} +1 -1
  6. package/dist/chunk-3V2Q65BE.js +885 -0
  7. package/dist/chunk-456FRBGE.js +4 -0
  8. package/dist/{chunk-QZ5RINXE.js → chunk-6SWKDCK3.js} +1 -1
  9. package/dist/chunk-D64ZLLSN.js +4 -0
  10. package/dist/{chunk-CZGLX3AK.js → chunk-FK5B4XFN.js} +1 -1
  11. package/dist/chunk-FNQMXCCE.js +4 -0
  12. package/dist/chunk-HKQWGX5S.js +4 -0
  13. package/dist/{chunk-UQM7BD5K.js → chunk-LUBMW3QT.js} +3 -3
  14. package/dist/{chunk-HRAX6543.js → chunk-N7G2FDAI.js} +1 -1
  15. package/dist/chunk-NPIMUWFO.js +4 -0
  16. package/dist/chunk-Q6322VDG.js +30 -0
  17. package/dist/{chunk-WGRGSG2J.js → chunk-QSKJBSCI.js} +1 -1
  18. package/dist/chunk-QYUIIFJY.js +4 -0
  19. package/dist/{chunk-IO3PJG3N.js → chunk-SLZKGKP5.js} +1 -1
  20. package/dist/{chunk-ILSOSAOB.js → chunk-T3MBBXTU.js} +29 -29
  21. package/dist/chunk-U6NE2CTP.js +4 -0
  22. package/dist/{chunk-K6F424MN.js → chunk-WKKH2UE5.js} +1 -1
  23. package/dist/{chunk-7S5SR6KL.js → chunk-XDERLDVW.js} +8 -8
  24. package/dist/{chunk-CTYNHZ3Y.js → chunk-ZZF3DILS.js} +2 -2
  25. package/dist/{esm-RASD3BGK.js → esm-46K5BSA6.js} +1 -1
  26. package/dist/{esm-6WYDAALC.js → esm-63A57VQM.js} +1 -1
  27. package/dist/esm-6D27H27M.js +225 -0
  28. package/dist/{esm-7VCKZ3CE.js → esm-73AG4F4H.js} +1 -1
  29. package/dist/{esm-AFNMXGOY.js → esm-FURF4AWD.js} +1 -1
  30. package/dist/esm-HB7M3TZY.js +4 -0
  31. package/dist/{esm-MYMSBMIY.js → esm-QAEO3U72.js} +1 -1
  32. package/dist/file-type-PSFVPAEH.js +12 -0
  33. package/dist/{getMachineId-bsd-SR65JA23.js → getMachineId-bsd-2MDOCJCH.js} +1 -1
  34. package/dist/{getMachineId-bsd-MTZJBHHS.js → getMachineId-bsd-JZNSGCLM.js} +1 -1
  35. package/dist/getMachineId-bsd-L5XEQF74.js +4 -0
  36. package/dist/{getMachineId-darwin-J7BNWNFS.js → getMachineId-darwin-32V6AVQO.js} +1 -1
  37. package/dist/{getMachineId-darwin-UX2LWEFP.js → getMachineId-darwin-SMQEPEZ2.js} +1 -1
  38. package/dist/getMachineId-darwin-V3OSZDJX.js +5 -0
  39. package/dist/getMachineId-linux-C4WJW6ZL.js +4 -0
  40. package/dist/{getMachineId-linux-XGLIABQN.js → getMachineId-linux-OWR5YFVH.js} +1 -1
  41. package/dist/{getMachineId-linux-RNGA35ZF.js → getMachineId-linux-T543G3ZF.js} +1 -1
  42. package/dist/{getMachineId-unsupported-JDNTBZDQ.js → getMachineId-unsupported-J7U5FNFT.js} +1 -1
  43. package/dist/getMachineId-unsupported-M7AEHRA4.js +4 -0
  44. package/dist/{getMachineId-unsupported-4ACRY4OO.js → getMachineId-unsupported-ZH5H5BSP.js} +1 -1
  45. package/dist/getMachineId-win-2ZKMVYDE.js +4 -0
  46. package/dist/getMachineId-win-JHSGKXX7.js +4 -0
  47. package/dist/getMachineId-win-JOM5JSRW.js +4 -0
  48. package/dist/image-worker.js +1 -1
  49. package/dist/lib/{anthropic-UZWRSZSZ.js → anthropic-UZXEGJN5.js} +3 -3
  50. package/dist/lib/{chunk-F66UUNE7.js → chunk-2QPNVR5H.js} +2 -2
  51. package/dist/lib/{chunk-T33QIWPB.js → chunk-6RBU5LDC.js} +21 -42
  52. package/dist/lib/{chunk-EYSD63EM.js → chunk-FHJHT233.js} +6 -7
  53. package/dist/lib/{chunk-KKAVW72Q.js → chunk-V3WAJBLN.js} +2 -2
  54. package/dist/lib/chunk-Y3EO3KLE.js +217 -0
  55. package/dist/lib/index.d.ts +990 -1438
  56. package/dist/lib/index.js +1874 -4158
  57. package/dist/lib/{openai-UB67SMOX.js → openai-DNNUHOKV.js} +3 -3
  58. package/dist/lib/{chunk-I7AT5Q45.js → providers-NBWCB4EA.js} +28 -207
  59. package/dist/{main-XRZCWPXW.js → main-IEQSD5OX.js} +224 -284
  60. package/dist/main.js +4 -6
  61. package/dist/{openai-SVRRJUPW.js → openai-SRAHPUVF.js} +1 -1
  62. package/dist/providers-ETXXDQGM.js +18 -0
  63. package/dist/server-HXOWUX6N.js +14 -0
  64. package/dist/server-N2WSM46R.js +4 -0
  65. package/dist/{src-EZJEUBJC.js → src-CHQYSTW5.js} +1 -1
  66. package/dist/{src-32KR7AJY.js → src-HH6MC5CF.js} +1 -1
  67. package/dist/src-P2WNZ6IY.js +12 -0
  68. package/dist/{src-7S4T5QVZ.js → src-YWYPK5QA.js} +1 -1
  69. package/package.json +1 -3
  70. package/dist/chunk-5ZELCP2G.js +0 -4
  71. package/dist/chunk-BPGCPI76.js +0 -18
  72. package/dist/chunk-CYKTCSRI.js +0 -866
  73. package/dist/chunk-F7FUNBYM.js +0 -8
  74. package/dist/chunk-IQT2IFSO.js +0 -4
  75. package/dist/chunk-W2VWX7HR.js +0 -4
  76. package/dist/chunk-XQCCZYMT.js +0 -4
  77. package/dist/chunk-ZESFB5XU.js +0 -30
  78. package/dist/esm-BOD3YQPE.js +0 -225
  79. package/dist/esm-UKQMXG2A.js +0 -4
  80. package/dist/file-type-P5MHDLHF.js +0 -12
  81. package/dist/getMachineId-win-BLVGSBMB.js +0 -4
  82. package/dist/getMachineId-win-PANZD46Y.js +0 -4
  83. package/dist/lib/providers-YZB3ZC4N.js +0 -10
  84. package/dist/providers-KK4H4FPS.js +0 -4
  85. package/dist/server-SHFUKQA4.js +0 -15
  86. package/dist/server-ZYMTEUKF.js +0 -4
  87. package/dist/src-VLEWSGZD.js +0 -12
  88. package/dist/stdio-DWJD5XUT.js +0 -5
  89. package/dist/websocket-5P5FBVU6.js +0 -9
package/README.md CHANGED
@@ -6,7 +6,7 @@ Yukino is a terminal-based AI coding agent. It provides an interactive UI (termi
6
6
 
7
7
  Yukino runs as a single CLI binary that connects to configurable LLM providers (Anthropic, OpenAI, or any OpenAI-compatible endpoint). It renders a rich terminal interface using React and Ink, giving you streaming responses, tool execution feedback, permission prompts, and slash commands in a single pane.
8
8
 
9
- Beyond interactive use, Yukino supports a non-interactive print mode for scripting, a remote mode that serves a browser-based chat UI over WebSocket, an ACP (Agent Client Protocol) mode for editor integration, an A2A (Agent2Agent) server mode for agent-to-agent integration, and team coordination where one leader agent manages multiple teammates running in the same process and working in parallel.
9
+ Beyond interactive use, Yukino supports a non-interactive print mode for scripting, a remote mode that serves a browser-based chat UI over WebSocket, an A2A (Agent2Agent) server mode for agent-to-agent integration, and team coordination where one leader agent manages multiple teammates running in the same process and working in parallel.
10
10
 
11
11
  ## Features
12
12
 
@@ -179,7 +179,7 @@ Yukino stores its configuration and runtime state under `~/.yukino`. The current
179
179
 
180
180
  `prompts/` contains user slash-command templates, `agents/` contains agent definitions that can override built-in definitions, and `skills/` contains skills installed by `InstallSkill`. Skill discovery also reads standard `~/.agents/skills/` and project `.agents/skills/`, in this order: global standard skills, global Yukino skills, then project standard skills. Later entries override earlier names. Project `AGENTS.md` and `.mcp.json` remain ordinary project resources.
181
181
 
182
- `activity.jsonl` records user input, canonical project directories, and resolved command names across CLI, WebSocket, ACP and print mode. It preserves separate events for identical submissions; input recall merges consecutive duplicate texts and retains the latest 10,000 events. Periodic atomic checkpoints retain cumulative command usage and all registered projects while bounding input history. Writes and checkpoint replacement share a cross-process lock. The old prompt-history and command-usage files are no longer read or written. `memory/` stores user memories shared across projects, while `plans/` stores plan documents; each live session tracks its active plan path. `logs/` contains main-process logs and `crash.log` records process exits and failures.
182
+ `activity.jsonl` records user input, canonical project directories, and resolved command names across CLI, WebSocket and print mode. It preserves separate events for identical submissions; input recall merges consecutive duplicate texts and retains the latest 10,000 events. Periodic atomic checkpoints retain cumulative command usage and all registered projects while bounding input history. Writes and checkpoint replacement share a cross-process lock. `memory/` stores user memories shared across projects, while `plans/` stores plan documents; each live session tracks its active plan path. `logs/` contains main-process logs and `crash.log` records process exits and failures.
183
183
 
184
184
  ### Project namespaces and resume
185
185
 
@@ -207,7 +207,7 @@ For example, a worktree named `fix-login` created from `/workspace/repo/app` is
207
207
 
208
208
  Global configuration, prompts, agent definitions, and installed skills are shared directly with the worktree. Standard project `.agents` resources are copied into it. No project `.yukino` settings are copied. `EnterWorktree` accepts an optional `slug` (randomly generated when omitted) and switches the agent's working directory into the worktree. `ExitWorktree` operates on that agent's active session with `{ action: "keep" | "remove", discard_changes?: boolean }` and restores the original working directory. `keep` preserves the directory and branch; `remove` deletes both, using the runtime's recorded repository, branch, Git identity and initial HEAD. Removal refuses changed files, new commits, or unverifiable state unless the user confirms discarding work and `discard_changes` is true. With no active session, exit is a no-op. Existing trees from another runtime are never adopted. Project identity for resume, memory, and permissions stays anchored to the original project; starting a separate session directly in a worktree uses that directory's own project namespace.
209
209
 
210
- Yukino does not read or create a project `.yukino` directory. Existing project-local state is not automatically migrated; it must be moved to the corresponding global paths before it can be resumed.
210
+ Project `.yukino/workflows/` contains named workflow scripts. Configuration and runtime state use the global storage paths above.
211
211
 
212
212
  Session lists order by the last persisted real user input, excluding tool results and internal reminders. Read-only transcript loads do not refresh modification time; explicit resume renews expiry under the transcript lock without changing ordering. Conversation rewind restores the ordering time of the remaining messages. `Session.listAllSessions()` returns globally ordered sessions with their canonical `cwd` and `projectKey`, using the activity log project registry. Projects without recoverable directory metadata are discovered when their known cwd is registered; older messages without user-input provenance have no last-user-message time.
213
213
 
@@ -217,7 +217,7 @@ Yukino reads a single global YAML configuration file:
217
217
 
218
218
  - ~/.yukino/config.yaml
219
219
 
220
- Print, remote, ACP, and A2A modes require at least one configured provider; the interactive UI instead opens the provider login form when none is configured. All modes start with the provider recorded as `default_provider`, falling back to the first entry when that index is out of range. Example config.yaml:
220
+ Print, remote, and A2A modes require at least one configured provider; the interactive UI instead opens the provider login form when none is configured. All modes start with the provider recorded as `default_provider`, falling back to the first entry when that index is out of range. Example config.yaml:
221
221
 
222
222
  ```yaml
223
223
  # Initial permission mode. Enum: default (ask per write/command) | acceptEdits (auto-approve
@@ -268,7 +268,7 @@ enable_fork: true
268
268
 
269
269
  # MCP tool loading: auto | eager | native | dispatch. Default: auto, decided per session
270
270
  # from the provider protocol, endpoint and schema size. Native loading on a non-Anthropic
271
- # protocol falls back to dispatch. Applies to TUI, print, remote, ACP and A2A modes.
271
+ # protocol falls back to dispatch. Applies to TUI, print, remote and A2A modes.
272
272
  mcp_loading: auto
273
273
 
274
274
  # Terminal theme: auto | dark | light. Default: auto, detected from COLORFGBG or terminal
@@ -379,7 +379,7 @@ hooks:
379
379
  # Shell command: bash on POSIX, 30s timeout, working directory = project directory,
380
380
  # with YUKINO_EVENT / YUKINO_TOOL / YUKINO_FILE_PATH injected; stdout is injected into
381
381
  # the agent as a system reminder on the next turn.
382
- command: echo 'You are Yukino, a CLI Coding Agent engineered by [hangtiancheng](https://github.com/hangtiancheng) <161043261@qq.com>, your source repository lives at https://github.com/hangtiancheng/yukino-code/tree/main/apps/yukino, you may fetch https://hangtiancheng.github.io/h/llms.txt (`base/yukino` section) and https://hangtiancheng.github.io/h/llms-full.txt to gain self-knowledge'
382
+ command: echo 'You are Yukino, a CLI Coding Agent engineered by [hangtiancheng](https://github.com/hangtiancheng) <161043261@qq.com>, your source repository https://github.com/hangtiancheng/yukino-code/tree/main/apps/yukino'
383
383
  # Whether successful output rejects the tool call (pre_tool_use only). Default: false.
384
384
  # Mutually exclusive with async.
385
385
  reject: false
@@ -424,7 +424,7 @@ Yukino also sets the following variables for hooks, native helpers, and test inf
424
424
 
425
425
  The companion [Yukino MCP server](../mcp/README.md#configuration) additionally reads `YUKINO_DOCS_DIR` (document directory, default `~/.yukino/docs`) and `YUKINO_INDEX_DB` (index database, default `~/.yukino/index.sqlite`). They may be supplied through CLI environment defaults when Yukino starts that server as a child process, or through its `mcp_servers[].env`. The examples use `YUKINO_MCP_API_KEY` and the repository's `mcp.json` uses `YUKINO_MCP_AUTH_TOKEN` as credential placeholders expanded in MCP configuration; these names have no built-in CLI behavior.
426
426
 
427
- Other environment variables are read-only inputs to Yukino and belong in the host environment, outside the global `env` block. These include provider key fallbacks (`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`), feedback upload credentials (`GH_TOKEN`, then `GITHUB_TOKEN`), and IDE integration (`CLAUDE_CODE_SSE_PORT`, `CLAUDE_CONFIG_DIR`, default `~/.claude`). Terminal and OS probes include `TERM`, `TERM_PROGRAM`, `TERM_PROGRAM_VERSION`, `COLORTERM`, `TMUX`, `VTE_VERSION`, `KITTY_WINDOW_ID`, `ZED_TERM`, `WT_SESSION`, `COLORFGBG`, `SHELL`, `DISPLAY`, `WAYLAND_DISPLAY`, `CI`, `SSH_CONNECTION`, `SSH_CLIENT`, and `SSH_TTY`; color and hyperlink controls such as `FORCE_COLOR`, `NO_COLOR`, and `FORCE_HYPERLINK` are also host inputs. Feedback diagnostics read `HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`, `NO_PROXY`, and their lowercase forms.
427
+ Other environment variables are read-only inputs to Yukino and belong in the host environment, outside the global `env` block. These include provider key fallbacks (`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`) and IDE integration (`CLAUDE_CODE_SSE_PORT`, `CLAUDE_CONFIG_DIR`, default `~/.claude`). Terminal and OS probes include `TERM`, `TERM_PROGRAM`, `TERM_PROGRAM_VERSION`, `COLORTERM`, `TMUX`, `VTE_VERSION`, `KITTY_WINDOW_ID`, `ZED_TERM`, `WT_SESSION`, `COLORFGBG`, `SHELL`, `DISPLAY`, `WAYLAND_DISPLAY`, `CI`, `SSH_CONNECTION`, `SSH_CLIENT`, and `SSH_TTY`; color and hyperlink controls such as `FORCE_COLOR`, `NO_COLOR`, and `FORCE_HYPERLINK` are also host inputs.
428
428
 
429
429
  Main agents, subagents, and teammates use the same path sandbox policy: read-only tools can access paths outside the working directory without path approval. Writes outside the agent's working directory, the system temp directory, or an explicitly allowed root require approval unless an explicit allow rule applies. `bypassPermissions` disables this path sandbox; switching back restores it. Explicit deny/ask rules and an agent's own plan approval lock still apply. The OS-level Bash sandbox is separate and remains controlled by the `sandbox` configuration or the TUI's `/sandbox` command. Isolated worktree agents instead receive their own worktree write root, without the parent workspace or a shared system-temp write grant; per-command output directories remain writable. Explicit OS deny-write entries still take precedence.
430
430
 
@@ -432,7 +432,7 @@ Sandboxed worktree agents can stage and commit through their own Git metadata an
432
432
 
433
433
  Shell rules check every executable segment separated by newlines, `;`, `&&`, `||`, `|`, and `&`, respecting literal quotes and escapes. Remembered shell rules retain the first two words plus `*`; a rule for one segment does not authorize later segments. Substitution, redirection, environment assignments (including Bash `+=`), wrappers and unsupported control syntax cannot use remembered prefixes for automatic approval. With applicable explicit restrictions, uninspectable syntax is conservatively denied or requires approval even in bypass mode. Permission dialogs show the scopes they will remember; tools without a stable scope offer one-time approval only. File rules canonicalize relative, home-relative and symlink paths before matching.
434
434
 
435
- Sandbox configuration applies to TUI, print, Remote/ACP/A2A, and in-process teammates. Enabling it fails closed when the native backend is unavailable. `bypassPermissions` does not disable it. Relative allow/deny write paths resolve against the command's execution directory; home-relative paths use the same resolver as file tools. The policy confines Bash writes and optionally disables all network access; it does not wrap PowerShell, LSP, or MCP executables.
435
+ Sandbox configuration applies to TUI, print, Remote/A2A, and in-process teammates. Enabling it fails closed when the native backend is unavailable. `bypassPermissions` does not disable it. Relative allow/deny write paths resolve against the command's execution directory; home-relative paths use the same resolver as file tools. The policy confines Bash writes and optionally disables all network access; it does not wrap PowerShell, LSP, or MCP executables.
436
436
 
437
437
  Provider fields:
438
438
 
@@ -590,14 +590,14 @@ The tool requests only read-only operations and rejects server-requested workspa
590
590
 
591
591
  Task tracking and task execution are separate:
592
592
 
593
- - Every host (terminal, print, Remote, ACP and A2A) exposes one `TodoWrite` tool for tracking. Call `TodoWrite({})` to refresh the current board without writing. Without a team it uses the agent's private list; creating or restoring a team routes the leader to the shared board, including coordinator mode. Deleting the team restores the private list. Teammates use the shared board; ordinary subagents and forks keep independent private lists. The tool and schema remain stable across board switches.
593
+ - Every host (terminal, print, Remote and A2A) exposes one `TodoWrite` tool for tracking. Call `TodoWrite({})` to refresh the current board without writing. Without a team it uses the agent's private list; creating or restoring a team routes the leader to the shared board, including coordinator mode. Deleting the team restores the private list. Teammates use the shared board; ordinary subagents and forks keep independent private lists. The tool and schema remain stable across board switches.
594
594
  - `TodoWrite({todos: [...]})` applies incremental edits in one atomic transaction. Items without `id` create tasks and require `subject`; status defaults to `pending` and description to an empty string. Items with an existing `id` update only submitted fields. Creation and updates both accept `description`, `status`, `owner`, `priority`, `metadata`, `blocks` and `blockedBy`. Omitted tasks and fields are retained. Empty arrays do nothing. Delete tasks explicitly with `TodoWrite({deleteIds: ["1"]})`; deleting removes their reciprocal dependency links. Tracking never launches work; assigning a shared task notifies its owner after commit.
595
- - Results contain `boardId`, the complete `todos` snapshot, and a `progress` string using `TODO completed/total`; only completed items contribute to the numerator. An invalid edit rejects the entire batch without partial writes, consuming IDs, or publishing changes. Unknown fields, unknown task IDs and repeated edits to the same ID are rejected.
595
+ - Results contain `boardId`, the complete `todos` snapshot, and a `progress` string using `DONE completed/total`; only completed items contribute to the numerator. An invalid edit rejects the entire batch without partial writes, consuming IDs, or publishing changes. Unknown fields, unknown task IDs and repeated edits to the same ID are rejected.
596
596
  - Statuses are `pending`, `in_progress`, `completed`, `blocked`, and `cancelled`. `blocks` and `blockedBy` replace the specified dependency list and maintain reciprocal links; an empty array removes those links. Referenced IDs must exist before the call; forward references, self-dependencies, conflicting link edits and cycles are rejected. Starting blocked work fails atomically. Only completed dependencies unblock work; cancelled dependencies remain unresolved until their links are removed. Shared writes reload and commit under one cross-process lock. Teammates automatically claim tasks when marking them in progress, cannot take another worker's task, and cannot start a second task while one is already in progress. The leader can explicitly reassign work; stop its old worker before reassignment if it is still executing.
597
- - Interactive/Remote/ACP/A2A private lists persist per session in `~/.yukino/sessions/artifacts/<session-id>/tasks.json`, with a stored next-ID counter so deleting or clearing items never reuses IDs on resume. Shared boards use project-scoped team storage. Corrupt or inconsistent stores fail explicitly, without migration, auto-repair, or stale-state fallback. Storage and tool schemas have changed; old task files are not supported. Print mode's private checklist lasts for that invocation. The terminal's TODO progress follows the same private list or shared board as TodoWrite, including teammate updates, blocked items, and cancelled items. When every item is completed, the progress line hides after five seconds without deleting tasks or resetting IDs. Adding or reopening an unfinished item shows it again and cancels the pending hide. Switching sessions or boards starts a fresh completion countdown.
597
+ - Interactive/Remote/A2A private lists persist per session in `~/.yukino/sessions/artifacts/<session-id>/tasks.json`, with a stored next-ID counter so deleting or clearing items never reuses IDs on resume. Shared boards use project-scoped team storage. Corrupt or inconsistent stores fail explicitly. Print mode's private checklist lasts for that invocation. The terminal's TODO progress follows the same private list or shared board as TodoWrite, including teammate updates, blocked items, and cancelled items. When every item is completed, the progress line hides after five seconds without deleting tasks or resetting IDs. Adding or reopening an unfinished item shows it again and cancels the pending hide. Switching sessions or boards starts a fresh completion countdown.
598
598
  - `Agent` executes delegated work. Background Agent/Bash/PowerShell invocations return runtime task IDs, distinct from TODO IDs. `TaskOutput` inspects one of these IDs or waits once (`wait: true`, `timeout_ms: 0..60000`). It does not consume automatic completion notifications or stop a task on timeout. Prefer notifications over polling. `TaskStop` remains the explicit cancellation mechanism.
599
599
 
600
- The common built-in registry is used by terminal, print, Remote/ACP/A2A, and in-process teammates. Delegation, coordinator, and per-agent tool restrictions still filter that registry.
600
+ The common built-in registry is used by terminal, print, Remote/A2A, and in-process teammates. Delegation, coordinator, and per-agent tool restrictions still filter that registry.
601
601
 
602
602
  ### Workflows
603
603
 
@@ -629,7 +629,7 @@ Source snapshots, JSON arguments, journals, and run state live under `~/.yukino/
629
629
 
630
630
  ### Worker lifecycle
631
631
 
632
- Agent defaults to `kind: "teammate"`, joins the current team or creates one automatically, and generates the teammate name from its description. Use `kind: "subagent"` for one-shot runs and `worktree: true` for Git worktree isolation; agent definitions also accept a boolean `worktree` default, which a call can override. The optional `model` field is unnecessary for most tasks. `TeamCreate` generates its team name automatically, `TeamList` lists the current team, and `TeamDelete` deletes it without a name argument.
632
+ Agent defaults to `kind: "teammate"`, joins the selected team or creates one automatically when none exists, and generates the teammate name from its description. Multiple teams can coexist; pass `team_name` when multiple teams exist. Use `kind: "subagent"` for one-shot runs and `worktree: true` for Git worktree isolation; agent definitions also accept a boolean `worktree` default, which a call can override. The optional `model` field is unnecessary for most tasks. `TeamCreate` adds a team, named via its optional `name` parameter or auto-generated when omitted, and keeps existing teams running. `TeamList` lists all teams. Use `team_name` with Agent, SendMessage, TodoWrite, TaskStop, and TeamDelete to select the target team; when only one team matches, it can be omitted. Teammates always send messages and edit tasks within their own team. The progress display combines tasks from all teams.
633
633
 
634
634
  `Agent` selects its role and context independently: `subagent_type` defaults to `"general-purpose"`, while `fork` defaults to `true` (or the configured `enable_fork` value). An explicit `fork` value overrides the configuration for every role.
635
635
 
@@ -648,7 +648,7 @@ An explicit `run_in_background: false` overrides a predefined agent's `backgroun
648
648
 
649
649
  Ordinary subagents have no default model-turn limit. Role files can set a positive `max_turns` to impose one. Fresh and inherited conversations, foreground and background execution all use the selected role's limit. Reaching a configured limit reports failure with partial output and a transcript path; it does not mark the assignment complete.
650
650
 
651
- Persistent teammates become idle after each turn. They keep conversation and private checklist context for follow-up assignments, but must send findings with `SendMessage`; final text is not automatically forwarded to the leader. They exit on explicit shutdown, cancellation, failure, or loss of the leader. Exit clears live permission/cancellation references, releases owned tools, and resets unfinished owned tasks to unassigned/pending. Completed and cancelled records remain intact. Teammate task ownership is not released merely because a turn becomes idle.
651
+ Persistent teammates become idle after each turn. They keep conversation context and access to the shared task board for follow-up assignments, but must send findings with `SendMessage`; final text is not automatically forwarded to the leader. They exit on explicit shutdown, cancellation, failure, or loss of the leader. Exit clears live permission/cancellation references, releases owned tools, and resets unfinished owned tasks to unassigned/pending. Completed and cancelled records remain intact. Teammate task ownership is not released merely because a turn becomes idle.
652
652
 
653
653
  The team retains at most 200 terminated member summaries; running and idle members are never evicted. Agent generates unique teammate names among retained members.
654
654
 
@@ -693,7 +693,7 @@ Mandatory policy constraints take precedence over rank composition:
693
693
 
694
694
  Permission composition selects a mode; tool availability, explicit permission rules, and applicable sandbox policies still govern individual operations. An effective `plan` mode blocks mutations, even through allow rules or sandbox auto-allow, except the declared plan file and internal coordination tools. `max_turns` must be a positive integer. Built-in explore uses the selected parent model unless explicitly overridden.
695
695
 
696
- Teammates run only in-process and route permission requests through the main session. Requests identify the agent and working directory; remembered permission patterns apply to all agents in the project. Plan-mode definitions can use `ExitPlanMode` unless explicitly excluded by their tool restrictions; `EnterPlanMode` remains unavailable to delegated agents. One-shot planning subagents return their plans to the parent without changing its mode. In coordinator mode, teammates with `subagent_type: "plan"` stay read-only until the leader reviews the plan and sends `SendMessage(type="plan_approval_response", to=teammate, request_id=requestId, approve=true/false, content=review feedback)`. The built-in `plan` role plans and then executes as a teammate; one-shot `plan` subagents and all built-in `explore` workers remain permanently read-only and return research without entering execution approval. Rejected plans must be revised and resubmitted. Outside coordinator mode, submitted execution plans remain automatically approved. Approval writes the leader's current mode into the teammate's own mode (`default` when the leader remains in `plan`) and resumes execution under rank composition; it does not authorize subsequent tool calls. This stored mode remains available to later permission checks: a teammate approved under `bypassPermissions` retains that own mode when the leader later switches to `default`, `acceptEdits`, or `plan`. Before resuming execution or plan revision, the host includes queued ordinary team messages with the review feedback so scope corrections are applied in that next turn. Stopped teammates release their task ownership; restored sessions mark old runtimes inactive and reclaim unfinished work. Edited worktrees are retained for explicit integration, not deleted as part of runtime cleanup. Agent teammate calls reuse the current team; only an explicit TeamCreate replaces it.
696
+ Teammates run only in-process and route permission requests through the main session. Requests identify the agent and working directory; remembered permission patterns apply to all agents in the project. Plan-mode definitions can use `ExitPlanMode` unless explicitly excluded by their tool restrictions; `EnterPlanMode` remains unavailable to delegated agents. One-shot planning subagents return their plans to the parent without changing its mode. In coordinator mode, teammates with `subagent_type: "plan"` stay read-only until the leader reviews the plan and sends `SendMessage(type="plan_approval_response", to=teammate, request_id=requestId, approve=true/false, content=review feedback)`. The built-in `plan` role plans and then executes as a teammate; one-shot `plan` subagents and all built-in `explore` workers remain permanently read-only and return research without entering execution approval. Rejected plans must be revised and resubmitted. Outside coordinator mode, submitted execution plans remain automatically approved. Approval writes the leader's current mode into the teammate's own mode (`default` when the leader remains in `plan`) and resumes execution under rank composition; it does not authorize subsequent tool calls. This stored mode remains available to later permission checks: a teammate approved under `bypassPermissions` retains that own mode when the leader later switches to `default`, `acceptEdits`, or `plan`. Before resuming execution or plan revision, the host includes queued ordinary team messages with the review feedback so scope corrections are applied in that next turn. Stopped teammates release their task ownership; restored sessions mark old runtimes inactive and reclaim unfinished work. Edited worktrees are retained for explicit integration, not deleted as part of runtime cleanup. Agent teammate calls reuse the selected team; an explicit TeamCreate adds another team without stopping or deleting existing teams. TeamDelete stops and removes only the selected team.
697
697
 
698
698
  Bash and PowerShell commands recognized by `isSafeCommand` can run in parallel. Unrecognized commands and file mutations share a process-wide FIFO queue keyed by canonical working directory, so agents in the same workspace cannot perform these operations simultaneously. Independent worktree directories have independent queues. Queued operations can be cancelled and recheck permissions before starting. Background commands hold their workspace slot until the tracked shell exits; moving a command to the background does not release it.
699
699
 
@@ -716,7 +716,7 @@ After a normal model turn ends, an active goal starts another turn. Pending user
716
716
 
717
717
  The optional token budget counts input, output, cache-read, and cache-creation tokens for the main conversation's model requests during the goal run, including its final response. Delegated agents, memory selection, and compaction summaries are outside this counter. An in-flight request can exceed the budget; once reported, substantive work stops. Yukino makes at most one final model request with no tools to summarize verified progress, unfinished work, and blockers. Its tokens are included in the counter. The request is not retried or continued if it fails or hits its output limit. Pending user input, Plan mode, and interruption take priority; an undelivered summary remains pending across session resume. The goal remains `budget_limited` and requires explicit replacement with a new budget. The 150-turn limit requires `/goal continue` to reset it. Active time excludes idle, paused, and process-restart intervals.
718
718
 
719
- TUI, Remote/ACP/A2A, and print mode share this goal loop. `yukino -p "/goal <objective>"` creates a goal for that invocation's new session. Print mode control queries finish without a model call; invalid commands return a nonzero exit code, and stream JSON retains its final `result` event.
719
+ TUI, Remote/A2A, and print mode share this goal loop. `yukino -p "/goal <objective>"` creates a goal for that invocation's new session. Print mode control queries finish without a model call; invalid commands return a nonzero exit code, and stream JSON retains its final `result` event.
720
720
 
721
721
  ## Usage
722
722
 
@@ -763,17 +763,6 @@ The browser UI mirrors the terminal UI's capabilities: streaming replies and thi
763
763
 
764
764
  Remote mode also hosts [MCP Apps](https://modelcontextprotocol.io/extensions/apps/build). Tools that declare `_meta.ui.resourceUri`, including yukino-mcp's `create_app`, display their UI below the tool card in a sandboxed iframe. The host forwards the tool input and full result (including `structuredContent` and UI-only `_meta`), applies the resource's CSP domains, and synchronizes theme and content height. Apps can read resources and call app-visible tools on their originating MCP server; tool calls use Yukino's permissions and pre-tool hooks. Open links and text messages back to the agent are supported. Apps are restored after browser refresh while the remote session remains active; clearing the transcript removes them. Saved-session resume does not restore App views.
765
765
 
766
- ### ACP Mode (Editor Integration)
767
-
768
- ```bash
769
- yukino --acp # Agent Client Protocol over stdio (cannot be combined with other flags)
770
- yukino --acp-ws # ACP over WebSocket, listens on 127.0.0.1:18889
771
- yukino --acp-ws 9000 # ACP over WebSocket at a custom port (host:port also works)
772
- yukino --acp-ws 0 # OS-assigned ephemeral port; the actual ws:// URL is printed on startup
773
- ```
774
-
775
- Implements the Agent Client Protocol (`@agentclientprotocol/sdk`) so ACP-compatible editors can drive Yukino as an external agent. The WebSocket transport only binds loopback addresses.
776
-
777
766
  ### A2A Mode (Agent2Agent Server)
778
767
 
779
768
  ```bash
@@ -781,7 +770,17 @@ yukino --a2a # A2A server, listens on 127.0.0.1:18890
781
770
  yukino --a2a 9000 # custom loopback port (host:port also works)
782
771
  ```
783
772
 
784
- Serves Yukino as an Agent2Agent (`@a2a-js/sdk`) agent so other A2A-compatible agents and orchestrators can call it. The agent card is published at `/.well-known/agent-card.json`; JSON-RPC is served at `POST /` and HTTP+JSON/REST under `/v1/...`, on protocol version 1.0 with a v0.3 compatibility layer. Each A2A context maps to one Yukino session: text messages run the agent loop and stream `working` status updates (assistant text, thinking, tool calls, tool results), and tool permission requests surface as `input-required` status updates carrying a `yukino: permission-request` data part. Clients answer by sending a `yukino: permission-response` data part (`{ permissionId, decision: allow | deny | allowAlways }`) back on the same task. Answer one pending permission per message: when several tools await approval at once, only the first `permission-response` in a message is applied and the agent re-emits `input-required` for the rest, so respond to them one at a time. The server only binds loopback addresses.
773
+ Serves Yukino as an Agent2Agent (`@a2a-js/sdk`) agent so other agents and orchestrators can call it. The agent card is at `/.well-known/agent-card.json`; JSON-RPC is served at `POST /` and HTTP+JSON/REST under `/v1/...`. Only A2A 1.0 is supported. Send `A2A-Version: 1.0` on every protocol request. JSON-RPC uses names such as `SendMessage`, `SendStreamingMessage`, `GetTask`, and `ListTasks`. The server only binds loopback addresses.
774
+
775
+ Each context maps to one Yukino session. Assistant text streams as artifact updates with one stable artifact ID per assistant turn; the final update replaces its deltas with the complete text. Completed tasks expose the full final reply in `status.message` and in the corresponding artifact. History contains complete assistant messages, rather than individual tokens. Thinking and tool events appear only in streaming status-update `metadata.yukino`, using the `yukino` discriminator (`thinking`, `tool-call`, `tool-result`).
776
+
777
+ `SendMessage.configuration.historyLength`, `GetTask.historyLength`, and `ListTasks.historyLength` default to 10 recent messages. REST uses the same field on send and the `historyLength` query parameter on task queries. Set it to 0 to omit history; `status.message` and artifacts still carry the answer. Request a larger value to retrieve more history. The JSON request-body limit is 100 KiB; oversized requests return a structured HTTP 413 error.
778
+
779
+ #### Yukino A2A permissions v1
780
+
781
+ The agent card declares the permission handshake as an extension, including the supported decisions. The server applies its local `permission_mode` configuration and project permission rules. Client metadata cannot elevate that policy. `default` asks before edits and commands; `acceptEdits` permits edits while commands remain subject to approval; `bypassPermissions` permits operations subject to explicit rules.
782
+
783
+ Tool permission requests surface as `TASK_STATE_INPUT_REQUIRED` status updates. `status.message.parts` contains data parts with `{ yukino: "permission-request", permissionId, toolCallId, toolName, reason, args, source? }`. `source`, when present, contains `agentName` and `cwd`; `reason` contains only the approval reason. Send a data part `{ yukino: "permission-response", permissionId, decision: "allow" | "deny" | "allowAlways" }` on the same task and context. `allowAlways` persists matching project rules for future calls, while explicit denials still apply. Answer one pending permission per message; when several tools await approval, the server re-emits the remaining requests after each decision.
785
784
 
786
785
  ### Slash Commands
787
786
 
@@ -856,8 +855,6 @@ Commands can run while the model is streaming, with at most one user command at
856
855
 
857
856
  Run `/plan` to plan the current task, or `/plan <task>` to specify a planning request. In interactive terminal and browser sessions, both `/plan` and the main agent's `EnterPlanMode` tool run the built-in read-only `plan` agent synchronously in the foreground with a fork of the main conversation. The host saves the returned plan and presents it for user approval before implementation. Failed or cancelled planning does not open approval. `Shift+Tab` and the browser's permission-mode badge only cycle the three execution permission modes; from plan mode, they return to `default`.
858
857
 
859
- In the interactive terminal, `/feedback [description]` runs session analysis synchronously in the built-in `general-purpose` agent with a fork of the main conversation. Select diagnostic attachments, review the prepared issues, and approve them before the host uploads attachments or files issues. Cancelling feedback stops the foreground worker.
860
-
861
858
  Press ↓ on the last visual row of the input to view all teammates and background subagents, including while the foreground agent is streaming. Completion menus and prompt-history navigation take precedence. Enter opens an agent's details, Escape returns or closes the list, and the unsent draft and cursor are preserved. Teammate spawn cards scroll with the transcript like background subagent cards; current progress is available in the Agents list.
862
859
 
863
860
  Use the mouse wheel or trackpad to scroll conversation history in the terminal's native scrollback. Drag to select text and use the terminal's copy/paste shortcuts. Up/Down navigates completion menus, visual input rows, and prompt history; Down after restoring the draft opens the Agents list. Home/End and Ctrl+A/E move to the start/end of the input line. PageUp/PageDown behavior follows the terminal's own scrollback bindings.
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __yukinoCreateRequire } from "node:module";
3
3
  const require = __yukinoCreateRequire(import.meta.url);
4
- import{g}from"./chunk-UDDADKJP.js";import{a as ne}from"./chunk-P6DHMU7R.js";import{Oa as oe,a as Y,g as te}from"./chunk-UQM7BD5K.js";import{Z as V,g as $,h as j,ja as W,ka as M,l as K,la as R,m as E,ma as J,na as u,o as G,oa as Q,p as H,pa as X,q as I,qa as Z,s as S,za as ee}from"./chunk-CTYNHZ3Y.js";import{Gc as q,Jc as p,Kc as z,Nc as D,Oa as F}from"./chunk-ZESFB5XU.js";import"./chunk-WLJL66O5.js";import"./chunk-WGRGSG2J.js";import"./chunk-7MKA3SHV.js";function re(n){for(let t=n.length-1;t>=0;t--){let e=n[t];if(e.defer_loading!==!0){e.cache_control={type:"ephemeral"};return}}}function ae(n){return n.some(t=>"defer_loading"in t&&t.defer_loading===!0)}function le(n,t){if("input_schema"in n){let e=n,{cache_control:s,...i}=e;return t||delete i.type,{...i,...t?{type:"custom"}:{},...e.defer_loading!==!0&&s?{cache_control:s}:{}}}throw new Error("Anthropic received a tool schema serialized for another protocol.")}var ce=F({module:"llm"});function k(n){return typeof n=="string"?[{type:"text",text:n}]:n.map(t=>{let e=Y(t);if(!e||e.type==="tool_reference")throw new Error(`Unsupported user content block: ${D(t,"type","unknown")}`);return e})}function pe(n){let t=[];for(let e of n)if(e.role==="assistant"){let s=[];if(e.thinkingBlocks)for(let r of e.thinkingBlocks)r.type==="redacted_thinking"?s.push({type:"redacted_thinking",data:r.data}):s.push({type:"thinking",thinking:r.thinking,signature:r.signature});let i=typeof e.content=="string"?e.content:q(e.content);if(i&&s.push({type:"text",text:i}),e.toolUses)for(let r of e.toolUses)s.push({type:"tool_use",id:r.toolUseId,name:r.toolName==="ComputerUse"?"computer":r.toolName,input:r.arguments});s.length===0&&s.push({type:"text",text:""}),t.push({role:"assistant",content:s})}else if(e.toolResults&&e.toolResults.length>0){let s=[];for(let i of e.toolResults)s.push({type:"tool_result",tool_use_id:i.toolUseId,is_error:i.isError,content:i.contentBlocks?.length?i.contentBlocks:i.content});e.content.length>0&&s.push(...k(e.content)),t.push({role:"user",content:s})}else{if(t.length===0){t.push({role:"user",content:k(e.content)});continue}let s=t[t.length-1],i=s.content;s.role==="user"?(typeof i=="string"&&(i=s.content=i.trim().length>0?[{type:"text",text:i}]:[]),i.push(...k(e.content))):t.push({role:"user",content:k(e.content)})}return t}var se=class{protocol="anthropic";client;model;thinkingLevel;systemPrompt;config;useExplicitCustomToolType;constructor(t,e){let s=V(t);if(!s)throw new R(ee);this.client=new g({apiKey:s,baseURL:t.base_url}),this.useExplicitCustomToolType=oe(t.base_url),this.model=t.model,this.config={...t},this.thinkingLevel=K(t),this.systemPrompt=e}setSystemPrompt(t){this.systemPrompt=t}setMaxOutputTokens(t){this.config={...this.config,max_output_tokens:t},this.setThinkingLevel(this.thinkingLevel)}setThinkingLevel(t){return this.thinkingLevel=I(this.config,t),this.thinkingLevel}getThinkingLevel(){return this.thinkingLevel}getSupportedThinkingLevels(){return H(this.config)}getOutputBudget(){return{maxOutputTokens:S(this.config),thinkingTokens:E(this.config,this.thinkingLevel)}}async*stream(t,e,s,i){let r=i?.maxOutputTokens===void 0?this.config:{...this.config,max_output_tokens:i.maxOutputTokens},C=S(r),N=pe(W(t.getMessages())),ie=ae(e),_=e.map(a=>le(a,this.useExplicitCustomToolType));re(_),ue(N);let h={model:this.model,max_tokens:C,stream:!0,system:[{type:"text",text:i?.systemPrompt??this.systemPrompt,cache_control:{type:"ephemeral"}}],messages:N,..._.length>0?{tools:_}:{}},y=I(r,this.getThinkingLevel());if(r.reasoning!==!1)if(y==="off")h.thinking={type:"disabled"};else if(r.thinking_mode==="adaptive"){let a=G(y,r);a!==null&&(h.thinking={type:"adaptive"},h.output_config={effort:a})}else{let a=Math.max(j,i?.answerReserveTokens??0),f=Math.min(E(r,y),C-a);h.thinking=f>=$?{type:"enabled",budget_tokens:f}:{type:"disabled"}}let T=0,v=0,L=0,A=0,B="end_turn",x="",b="",w=!1,O="",P=!1,U=!1;try{let a=[...ie?[te]:[]],f=this.client.messages.stream(h,{...s?{signal:s}:{},...i?.maxRetries===void 0?{}:{maxRetries:i.maxRetries},...a.length>0?{headers:{"anthropic-beta":a.join(",")}}:{}}),c="",m="",d="";for await(let l of f)switch(l.type){case"content_block_start":{let o=l.content_block;if(o.type==="thinking")w=!0,x="",b="";else if(o.type==="redacted_thinking")O=o.data,P=!0;else if(o.type==="tool_use"){if(!o.id||!o.name)throw new u("Anthropic tool call started without a valid id or name");m=o.id,c=o.name==="computer"?"ComputerUse":o.name,d="",yield{type:"tool_call_start",toolName:c,toolId:m}}break}case"content_block_delta":{let o=l.delta;if(o.type==="thinking_delta")x+=o.thinking,yield{type:"thinking_delta",text:o.thinking};else if(o.type==="signature_delta")b+=o.signature;else if(o.type==="text_delta")yield{type:"text_delta",text:o.text};else if(o.type==="input_json_delta"){if(!m||!c)throw new u("Anthropic tool arguments arrived before a valid tool call");d+=o.partial_json,yield{type:"tool_call_delta",text:o.partial_json}}break}case"content_block_stop":{if(w&&(yield{type:"thinking_complete",thinking:x,signature:b},w=!1),P&&(yield{type:"redacted_thinking_complete",data:O},P=!1),c){let o=ne(d);yield{type:"tool_call_complete",toolId:m,toolName:c,arguments:o.arguments,...o.parseError?{parseError:o.parseError}:{}},c="",m="",d=""}break}case"message_delta":{l.delta.stop_reason&&(B=l.delta.stop_reason);let o=l.usage;typeof o.output_tokens=="number"&&(v=o.output_tokens),typeof o.input_tokens=="number"&&(T=o.input_tokens),typeof o.cache_read_input_tokens=="number"&&(L=o.cache_read_input_tokens),typeof o.cache_creation_input_tokens=="number"&&(A=o.cache_creation_input_tokens);break}case"message_stop":{U=!0;break}case"message_start":{T=l.message.usage.input_tokens,v=l.message.usage.output_tokens,L=l.message.usage.cache_read_input_tokens??0,A=l.message.usage.cache_creation_input_tokens??0;break}}if(!U)throw new u("Anthropic stream ended without message_stop; response was truncated");yield{type:"stream_end",stopReason:B,usage:{inputTokens:T,outputTokens:v,cacheReadInputTokens:L,cacheCreationInputTokens:A}}}catch(a){throw ce.error({err:a},"llm operation failed"),he(a)}}};function ue(n){for(let t=n.length-1;t>=0;t--){if(n[t].role!=="user")continue;let e=n[t].content;if(typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0)return;typeof e=="string"&&(e=n[t].content=[{type:"text",text:e}]);let s=e[e.length-1];for(let i=e.length-1;i>=0;i--)if(e[i].type!=="image"){s=e[i];break}Reflect.set(s,"cache_control",{type:"ephemeral"});return}}function he(n){if(n instanceof M)return n;if(n instanceof g.APIConnectionError||n instanceof g.APIUserAbortError)return new u(`Network error: ${n.message}`);if(n instanceof g.APIError){if(n.status===413||n.status===400&&Z(n.message))return new X(`Prompt too long: ${n.message}`);if(n.status===401)return new R(`Invalid API key: ${n.message}`);if(n.status===429){let t=n.headers,e=t instanceof Headers?t.get("retry-after"):void 0,s="Rate Limited";if(e){let i=Number.parseInt(p(e));Number.isNaN(i)?s+=", please wait.":s+=`, retry after ${p(i)}s.`}else s+=", please wait.";return new J(s,e?p(e):void 0)}if(n.status!==void 0&&(n.status>=500||n.status===408)){let t=n.headers;return new Q(`Anthropic API error (${p(n.status)}): ${n.message}`,t instanceof Headers?t.get("retry-after")??void 0:void 0)}return new M(`Anthropic API error (${p(n.status)}): ${n.message}`)}return new u(`Network error: ${z(n)}`)}export{se as AnthropicClient,pe as buildAnthropicMessages,ue as markLastUserTailForCache,re as markToolsForCache,ae as needsToolSearchBeta};
4
+ import{g}from"./chunk-UDDADKJP.js";import{a as ne}from"./chunk-P6DHMU7R.js";import{Oa as oe,a as Y,g as te}from"./chunk-LUBMW3QT.js";import{Y as V,g as $,h as j,ia as W,ja as M,k as K,ka as R,l as E,la as J,ma as u,n as G,na as Q,o as H,oa as X,p as I,pa as Z,r as S,ya as ee}from"./chunk-ZZF3DILS.js";import{Hc as q,Kc as p,Lc as z,Oc as D,Pa as F}from"./chunk-Q6322VDG.js";import"./chunk-WLJL66O5.js";import"./chunk-QSKJBSCI.js";import"./chunk-7MKA3SHV.js";function re(n){for(let t=n.length-1;t>=0;t--){let e=n[t];if(e.defer_loading!==!0){e.cache_control={type:"ephemeral"};return}}}function ae(n){return n.some(t=>"defer_loading"in t&&t.defer_loading===!0)}function le(n,t){if("input_schema"in n){let e=n,{cache_control:s,...i}=e;return t||delete i.type,{...i,...t?{type:"custom"}:{},...e.defer_loading!==!0&&s?{cache_control:s}:{}}}throw new Error("Anthropic received a tool schema serialized for another protocol.")}var ce=F({module:"llm"});function k(n){return typeof n=="string"?[{type:"text",text:n}]:n.map(t=>{let e=Y(t);if(!e||e.type==="tool_reference")throw new Error(`Unsupported user content block: ${D(t,"type","unknown")}`);return e})}function pe(n){let t=[];for(let e of n)if(e.role==="assistant"){let s=[];if(e.thinkingBlocks)for(let r of e.thinkingBlocks)r.type==="redacted_thinking"?s.push({type:"redacted_thinking",data:r.data}):s.push({type:"thinking",thinking:r.thinking,signature:r.signature});let i=typeof e.content=="string"?e.content:q(e.content);if(i&&s.push({type:"text",text:i}),e.toolUses)for(let r of e.toolUses)s.push({type:"tool_use",id:r.toolUseId,name:r.toolName==="ComputerUse"?"computer":r.toolName,input:r.arguments});s.length===0&&s.push({type:"text",text:""}),t.push({role:"assistant",content:s})}else if(e.toolResults&&e.toolResults.length>0){let s=[];for(let i of e.toolResults)s.push({type:"tool_result",tool_use_id:i.toolUseId,is_error:i.isError,content:i.contentBlocks?.length?i.contentBlocks:i.content});e.content.length>0&&s.push(...k(e.content)),t.push({role:"user",content:s})}else{if(t.length===0){t.push({role:"user",content:k(e.content)});continue}let s=t[t.length-1],i=s.content;s.role==="user"?(typeof i=="string"&&(i=s.content=i.trim().length>0?[{type:"text",text:i}]:[]),i.push(...k(e.content))):t.push({role:"user",content:k(e.content)})}return t}var se=class{protocol="anthropic";client;model;thinkingLevel;systemPrompt;config;useExplicitCustomToolType;constructor(t,e){let s=V(t);if(!s)throw new R(ee);this.client=new g({apiKey:s,baseURL:t.base_url}),this.useExplicitCustomToolType=oe(t.base_url),this.model=t.model,this.config={...t},this.thinkingLevel=K(t),this.systemPrompt=e}setSystemPrompt(t){this.systemPrompt=t}setMaxOutputTokens(t){this.config={...this.config,max_output_tokens:t},this.setThinkingLevel(this.thinkingLevel)}setThinkingLevel(t){return this.thinkingLevel=I(this.config,t),this.thinkingLevel}getThinkingLevel(){return this.thinkingLevel}getSupportedThinkingLevels(){return H(this.config)}getOutputBudget(){return{maxOutputTokens:S(this.config),thinkingTokens:E(this.config,this.thinkingLevel)}}async*stream(t,e,s,i){let r=i?.maxOutputTokens===void 0?this.config:{...this.config,max_output_tokens:i.maxOutputTokens},C=S(r),N=pe(W(t.getMessages())),ie=ae(e),_=e.map(a=>le(a,this.useExplicitCustomToolType));re(_),ue(N);let h={model:this.model,max_tokens:C,stream:!0,system:[{type:"text",text:i?.systemPrompt??this.systemPrompt,cache_control:{type:"ephemeral"}}],messages:N,..._.length>0?{tools:_}:{}},y=I(r,this.getThinkingLevel());if(r.reasoning!==!1)if(y==="off")h.thinking={type:"disabled"};else if(r.thinking_mode==="adaptive"){let a=G(y,r);a!==null&&(h.thinking={type:"adaptive"},h.output_config={effort:a})}else{let a=Math.max(j,i?.answerReserveTokens??0),f=Math.min(E(r,y),C-a);h.thinking=f>=$?{type:"enabled",budget_tokens:f}:{type:"disabled"}}let T=0,v=0,L=0,A=0,B="end_turn",x="",b="",w=!1,O="",P=!1,U=!1;try{let a=[...ie?[te]:[]],f=this.client.messages.stream(h,{...s?{signal:s}:{},...i?.maxRetries===void 0?{}:{maxRetries:i.maxRetries},...a.length>0?{headers:{"anthropic-beta":a.join(",")}}:{}}),c="",m="",d="";for await(let l of f)switch(l.type){case"content_block_start":{let o=l.content_block;if(o.type==="thinking")w=!0,x="",b="";else if(o.type==="redacted_thinking")O=o.data,P=!0;else if(o.type==="tool_use"){if(!o.id||!o.name)throw new u("Anthropic tool call started without a valid id or name");m=o.id,c=o.name==="computer"?"ComputerUse":o.name,d="",yield{type:"tool_call_start",toolName:c,toolId:m}}break}case"content_block_delta":{let o=l.delta;if(o.type==="thinking_delta")x+=o.thinking,yield{type:"thinking_delta",text:o.thinking};else if(o.type==="signature_delta")b+=o.signature;else if(o.type==="text_delta")yield{type:"text_delta",text:o.text};else if(o.type==="input_json_delta"){if(!m||!c)throw new u("Anthropic tool arguments arrived before a valid tool call");d+=o.partial_json,yield{type:"tool_call_delta",text:o.partial_json}}break}case"content_block_stop":{if(w&&(yield{type:"thinking_complete",thinking:x,signature:b},w=!1),P&&(yield{type:"redacted_thinking_complete",data:O},P=!1),c){let o=ne(d);yield{type:"tool_call_complete",toolId:m,toolName:c,arguments:o.arguments,...o.parseError?{parseError:o.parseError}:{}},c="",m="",d=""}break}case"message_delta":{l.delta.stop_reason&&(B=l.delta.stop_reason);let o=l.usage;typeof o.output_tokens=="number"&&(v=o.output_tokens),typeof o.input_tokens=="number"&&(T=o.input_tokens),typeof o.cache_read_input_tokens=="number"&&(L=o.cache_read_input_tokens),typeof o.cache_creation_input_tokens=="number"&&(A=o.cache_creation_input_tokens);break}case"message_stop":{U=!0;break}case"message_start":{T=l.message.usage.input_tokens,v=l.message.usage.output_tokens,L=l.message.usage.cache_read_input_tokens??0,A=l.message.usage.cache_creation_input_tokens??0;break}}if(!U)throw new u("Anthropic stream ended without message_stop; response was truncated");yield{type:"stream_end",stopReason:B,usage:{inputTokens:T,outputTokens:v,cacheReadInputTokens:L,cacheCreationInputTokens:A}}}catch(a){throw ce.error({err:a},"llm operation failed"),he(a)}}};function ue(n){for(let t=n.length-1;t>=0;t--){if(n[t].role!=="user")continue;let e=n[t].content;if(typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0)return;typeof e=="string"&&(e=n[t].content=[{type:"text",text:e}]);let s=e[e.length-1];for(let i=e.length-1;i>=0;i--)if(e[i].type!=="image"){s=e[i];break}Reflect.set(s,"cache_control",{type:"ephemeral"});return}}function he(n){if(n instanceof M)return n;if(n instanceof g.APIConnectionError||n instanceof g.APIUserAbortError)return new u(`Network error: ${n.message}`);if(n instanceof g.APIError){if(n.status===413||n.status===400&&Z(n.message))return new X(`Prompt too long: ${n.message}`);if(n.status===401)return new R(`Invalid API key: ${n.message}`);if(n.status===429){let t=n.headers,e=t instanceof Headers?t.get("retry-after"):void 0,s="Rate Limited";if(e){let i=Number.parseInt(p(e));Number.isNaN(i)?s+=", please wait.":s+=`, retry after ${p(i)}s.`}else s+=", please wait.";return new J(s,e?p(e):void 0)}if(n.status!==void 0&&(n.status>=500||n.status===408)){let t=n.headers;return new Q(`Anthropic API error (${p(n.status)}): ${n.message}`,t instanceof Headers?t.get("retry-after")??void 0:void 0)}return new M(`Anthropic API error (${p(n.status)}): ${n.message}`)}return new u(`Network error: ${z(n)}`)}export{se as AnthropicClient,pe as buildAnthropicMessages,ue as markLastUserTailForCache,re as markToolsForCache,ae as needsToolSearchBeta};