@yukino.js/yukino 0.0.4 → 0.0.5

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 (71) hide show
  1. package/README.md +90 -64
  2. package/dist/acp-LOU6R4C7.js +14 -0
  3. package/dist/{agent-56R4TACG.js → agent-5NW5ZV5P.js} +1 -1
  4. package/dist/anthropic-UXFSBFXM.js +4 -0
  5. package/dist/{bwrap-MLSZLWHD.js → bwrap-BZ7Q2A5B.js} +1 -1
  6. package/dist/chunk-2HUCPWD6.js +29 -0
  7. package/dist/{chunk-XO7ITAWR.js → chunk-3EQYWNP6.js} +1 -1
  8. package/dist/chunk-3SPUH3TD.js +164 -0
  9. package/dist/chunk-5HF4GLFR.js +865 -0
  10. package/dist/{chunk-JNCMSXQZ.js → chunk-BPA7URET.js} +1 -1
  11. package/dist/chunk-HBXZ6MB4.js +4 -0
  12. package/dist/chunk-KILUTRHM.js +4 -0
  13. package/dist/chunk-MQAQBW7F.js +35 -0
  14. package/dist/chunk-NAQRFHUX.js +4 -0
  15. package/dist/chunk-SDXAS44V.js +4 -0
  16. package/dist/chunk-TJVN4NL5.js +5 -0
  17. package/dist/chunk-VM26JJ6N.js +4 -0
  18. package/dist/chunk-VM4YKTHC.js +10 -0
  19. package/dist/chunk-WNHTKUKK.js +4 -0
  20. package/dist/chunk-YVLW4WBA.js +241 -0
  21. package/dist/chunk-ZPYQCXWT.js +5 -0
  22. package/dist/{devtools-YWVUN4HX.js → devtools-UVGRIXO2.js} +1 -1
  23. package/dist/esm-5V3TYPZK.js +229 -0
  24. package/dist/lib/{agent-INEHZXP3.js → agent-UGEA6EVB.js} +5 -5
  25. package/dist/lib/{anthropic-MSGL4VBM.js → anthropic-UC7XIWCM.js} +5 -4
  26. package/dist/lib/{bwrap-2OL7VPSO.js → bwrap-STOJ4TEH.js} +1 -1
  27. package/dist/lib/{chunk-E6VFL5IO.js → chunk-64Z3SMSG.js} +32 -30
  28. package/dist/lib/{chunk-6AKRDUQF.js → chunk-65EUCQOF.js} +1 -1
  29. package/dist/lib/{chunk-FLKB4BK7.js → chunk-DXUJGZ5F.js} +16 -4
  30. package/dist/lib/{chunk-ENTAZT2J.js → chunk-GAWWN3TY.js} +44 -32
  31. package/dist/lib/{chunk-YIWNQ7OA.js → chunk-MGPT7DWP.js} +1 -0
  32. package/dist/lib/{chunk-DF3ITW4K.js → chunk-NIJXTKNM.js} +342 -184
  33. package/dist/lib/{chunk-MDX24JQ5.js → chunk-OCTB6YMC.js} +23 -17
  34. package/dist/lib/{chunk-24L3QT3J.js → chunk-OYQY3Q45.js} +68 -27
  35. package/dist/lib/chunk-R3NJ2EET.js +540 -0
  36. package/dist/lib/{chunk-7SU77J32.js → chunk-UKINFW65.js} +55 -2
  37. package/dist/lib/chunk-V2EYBIAU.js +323 -0
  38. package/dist/lib/{chunk-P3HXGEQQ.js → chunk-WDO5MWH2.js} +1 -1
  39. package/dist/lib/index.d.ts +3431 -2269
  40. package/dist/lib/index.js +14801 -12912
  41. package/dist/lib/{openai-DL5VBJR4.js → openai-OL5HXQUU.js} +4 -3
  42. package/dist/lib/{permissions-Q4FBU5VD.js → permissions-EAKP6IZ3.js} +7 -3
  43. package/dist/lib/{providers-SMRZVJ7O.js → providers-N35WJDJM.js} +1 -1
  44. package/dist/lib/{seatbelt-WO7YWKLR.js → seatbelt-G5Z5QEDD.js} +1 -1
  45. package/dist/lib/{tool-filter-PY6XY254.js → tool-filter-HUVHJN3O.js} +3 -3
  46. package/dist/main.js +201 -192
  47. package/dist/{openai-AQNX24XU.js → openai-NIBMRDVB.js} +5 -5
  48. package/dist/permissions-5EQWZS7O.js +4 -0
  49. package/dist/{providers-FZUDVU4M.js → providers-TG3LGHNS.js} +1 -1
  50. package/dist/{seatbelt-JOCANLYS.js → seatbelt-IOLIYZZX.js} +1 -1
  51. package/dist/server-7ENYPCYC.js +4 -0
  52. package/dist/tool-filter-XZ7I6KU7.js +4 -0
  53. package/package.json +85 -32
  54. package/dist/acp-JCR6GVC3.js +0 -14
  55. package/dist/anthropic-CEUDAJL2.js +0 -4
  56. package/dist/chunk-6DXHDARX.js +0 -607
  57. package/dist/chunk-77W2UPS2.js +0 -4
  58. package/dist/chunk-7DLUKIPE.js +0 -5
  59. package/dist/chunk-HLE7243Q.js +0 -4
  60. package/dist/chunk-K4BYVVW7.js +0 -5
  61. package/dist/chunk-L2BWSPCF.js +0 -10
  62. package/dist/chunk-RCXKUD3Y.js +0 -4
  63. package/dist/chunk-SAJCBGHL.js +0 -4
  64. package/dist/chunk-U2CS2E2F.js +0 -237
  65. package/dist/chunk-UPNNYP7M.js +0 -60
  66. package/dist/chunk-ZETIYALB.js +0 -164
  67. package/dist/esm-NCEEJIH3.js +0 -229
  68. package/dist/lib/chunk-BMODZ6SU.js +0 -673
  69. package/dist/permissions-VCDMNX3L.js +0 -4
  70. package/dist/server-VLJWUETV.js +0 -4
  71. package/dist/tool-filter-BQZDV3TF.js +0 -4
package/README.md CHANGED
@@ -6,47 +6,47 @@ 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, and a teammate mode that lets one lead agent coordinate multiple subagents 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 ACP (Agent Client Protocol) mode for editor integration, and team coordination where one leader agent manages multiple teammates (in-process, or as separate processes in tmux/iTerm panes) working in parallel.
10
10
 
11
11
  ## Features
12
12
 
13
13
  ### Core Capabilities
14
14
 
15
- - Multi-provider LLM support with Anthropic, OpenAI, and OpenAI-compatible protocols
15
+ - Multi-provider LLM support with Anthropic (Anthropic Messages), OpenAI (OpenAI Responses), and OpenAI-compatible (OpenAI Chat Completions) protocols
16
16
  - Interactive terminal UI with streaming text, thinking indicators, and tool execution display
17
- - Built-in tool set: ReadFile, WriteFile, EditFile, Bash, Glob, Grep, ToolSearch, EnterWorktree, ExitWorktree, ExitPlanMode
17
+ - Built-in tool set: ReadFile, WriteFile, EditFile, Bash, PowerShell, Glob, Grep, WebFetch, ComputerUse, ToolSearch, McpCall, EnterWorktree, ExitWorktree, ExitPlanMode, the TaskCreate/TaskGet/TaskList/TaskUpdate todo tools, plus the orchestration and interaction tools: Agent, LoadSkill, InstallSkill, AskUserQuestion, SyntheticOutput, TeamCreate, SpawnTeammate, SendMessage, ListTeams, TeamDelete, and TaskStop
18
18
  - MCP (Model Context Protocol) server integration for extending the tool set with external services
19
19
  - Permission system with four modes: default, acceptEdits, plan (read-only), and bypassPermissions
20
- - Sandbox support via bwrap (Linux) and seatbelt (macOS) for isolated command execution
21
- - Dangerous command pattern detection with human-in-the-loop approval dialogs
20
+ - Sandbox support for isolated command execution: the native backend (bwrap on Linux, seatbelt on macOS) or the sandbox-runtime backend
21
+ - Human-in-the-loop approval dialogs for file writes and shell commands, driven by permission mode and allow/deny rules
22
22
 
23
23
  ### Conversation and Memory
24
24
 
25
25
  - Session persistence with JSONL-based storage for cross-session resume
26
26
  - Automatic context compaction when conversations approach the model's context window
27
- - Long-term memory extraction and recall across sessions
28
- - Instructions file support for persistent project-level guidance
27
+ - Long-term memory extraction and recall across sessions (disable with `memory: false` in `~/.yukino/config.yaml`)
28
+ - Instructions files for persistent guidance: user-global `~/.yukino/AGENTS.md`, plus `AGENTS.md` and `.yukino/AGENTS.md` in every directory from the git root down to the working directory, with `@include` expansion
29
29
 
30
30
  ### Skills and Commands
31
31
 
32
- - Skill catalog with three-tier loading: built-in, user-global (~/.agents/skills/), and project-level (.agents/skills/)
32
+ - Skill catalog with two-tier loading: user-global (~/.agents/skills/) and project-level (.agents/skills/), where the project level wins on a name collision
33
33
  - Hot-reload support for skills edited on disk
34
34
  - Inline and fork execution modes for skills
35
- - Slash command system with built-in commands and user-defined commands from .yukino/commands/
36
- - Skill installation from URLs
35
+ - Slash command system with built-in commands and user-defined commands from two tiers: user-global (~/.yukino/commands/) and project-level (.yukino/commands/), where the project level wins on a name collision
36
+ - Skill installation from a local path or a raw SKILL.md URL
37
37
 
38
38
  ### Agent Orchestration
39
39
 
40
40
  - Subagent spawning with built-in agent types: general-purpose, plan (read-only architect), explore (read-only code explorer)
41
- - Team coordination with file-based mailboxes and lead/member communication
41
+ - Team coordination with file-based mailboxes and leader/member communication
42
42
  - Coordinator mode for managing multi-agent workflows
43
43
  - Git worktree isolation for parallel agent tasks
44
44
 
45
45
  ### Hooks
46
46
 
47
47
  - Event-driven hook engine supporting: session_start, session_end, turn_start, turn_end, pre_send, post_receive, pre_tool_use, post_tool_use, shutdown
48
- - Hook actions: shell commands, HTTP requests, prompt injection
49
- - Conditional execution, reject-on-failure, and async options
48
+ - Hook actions: shell commands, HTTP requests, prompt injection, and subagent (`agent`) execution
49
+ - Conditional execution, one-shot (`once`) hooks, `reject` (blocks a tool call on pre_tool_use), `on_error` handling (ignore, fail, reject), and fire-and-forget `async` execution (`reject` and `async` are mutually exclusive)
50
50
 
51
51
  ### Remote Mode
52
52
 
@@ -86,26 +86,26 @@ Yukino reads a single global YAML configuration file:
86
86
 
87
87
  - ~/.yukino/config.yaml
88
88
 
89
- At least one provider must be configured. Example config.yaml:
89
+ Print, remote, and ACP modes require at least one configured provider; the interactive UI instead opens the provider login form when none is configured. Example config.yaml:
90
90
 
91
91
  ```yaml
92
92
  providers:
93
93
  - name: anthropic
94
94
  protocol: anthropic
95
- base_url: https://api.anthropic.com
96
- model: claude-sonnet-4-6
95
+ base_url: https://api.deepseek.com
96
+ model: deepseek-flash
97
97
  # api_key defaults to $ANTHROPIC_API_KEY
98
98
  thinking: high # off | minimal | low | medium | high | xhigh | max
99
99
 
100
100
  permission_mode: default
101
101
 
102
102
  mcp_servers:
103
- - name: database
103
+ - name: yukino-mcp
104
104
  command: npx
105
- args: ["-y", "@yukino-db/mcp@latest"]
105
+ args: ["-y", "@yukino.js/mcp@latest"]
106
106
  env: # map<string, string>; supports ${VAR}, ${VAR:-default}, and $VAR
107
- API_BASE_URL: "https://yukino-db.dev"
108
- API_KEY: "${DATABASE_API_KEY}"
107
+ API_BASE_URL: "https://yukino-js.dev"
108
+ API_KEY: "${YUKINO_MCP_API_KEY}"
109
109
 
110
110
  hooks:
111
111
  - event: pre_tool_use
@@ -116,26 +116,35 @@ hooks:
116
116
 
117
117
  sandbox:
118
118
  enabled: false
119
+ backend: native # native (bwrap/seatbelt) | sandbox-runtime
119
120
  auto_allow: false
120
121
  network_enabled: true
121
122
 
122
123
  enable_coordinator_mode: false
124
+
125
+ # Auto memory: index injection, recall, background extraction, and consolidation
126
+ # (consolidation currently runs only in remote mode).
127
+ # Set to false to disable the whole automatic memory pipeline (default: true).
128
+ memory: true
123
129
  ```
124
130
 
125
131
  Provider fields:
126
132
 
127
- | Field | Required | Description |
128
- | ----------------- | -------- | -------------------------------------------------------------------------------------------------------------------------- |
129
- | name | yes | Display name for the provider |
130
- | protocol | yes | One of: anthropic, openai, openai-compat |
131
- | base_url | yes | API base URL |
132
- | model | yes | Model identifier |
133
- | api_key | no | API key (falls back to environment variable) |
134
- | thinking | no | Thinking level: off, minimal, low, medium, high, xhigh, max (default: `high` for every protocol). |
135
- | context_window | no | Context window in tokens (default: 1000000; no model-name inference) |
136
- | max_output_tokens | no | Output cap for the model (default: 128000, never above `context_window`). Set this for models with a smaller output limit. |
137
-
138
- The thinking level controls reasoning depth. For `anthropic` it maps to a thinking token budget (minimal 1024, low 2048, medium 8192, high 16384, xhigh 32768, max 65536); for `openai` and `openai-compat` it maps to the provider reasoning effort. The budget shares `max_output_tokens` and always leaves at least 1024 answer tokens, so lower `max_output_tokens` shrinks the thinking budget instead of disabling it (below a 2048-token cap no valid budget remains and thinking falls back to disabled). On `openai`/`openai-compat`, the effort string is passed through verbatim, and only levels supported by the model are accepted (`xhigh`/`max` are model-specific). Use `/thinking <level>` to change it at runtime (the change is applied to the active client and saved to `~/.yukino/config.yaml`), or `/thinking` to show the current level.
133
+ | Field | Required | Description |
134
+ | ------------------ | -------- | -------------------------------------------------------------------------------------------------------------------------- |
135
+ | name | yes | Display name for the provider |
136
+ | protocol | yes | One of: anthropic, openai, openai-compat |
137
+ | base_url | yes | API base URL |
138
+ | model | yes | Model identifier |
139
+ | api_key | no | API key (falls back to environment variable) |
140
+ | thinking | no | Thinking level: off, minimal, low, medium, high, xhigh, max (default: `high` for every protocol). |
141
+ | reasoning | no | Explicit capability switch: `false` disables reasoning entirely; omitted leaves the provider default in place. |
142
+ | thinking_level_map | no | Per-level overrides mapping a logical level to a provider effort string (or `null` to disable that level). |
143
+ | thinking_mode | no | Anthropic only: `budget` (default) or `adaptive`; adaptive sends effort-based `output_config` instead of a token budget. |
144
+ | context_window | no | Context window in tokens (default: 1000000; no model-name inference) |
145
+ | max_output_tokens | no | Output cap for the model (default: 128000, never above `context_window`). Set this for models with a smaller output limit. |
146
+
147
+ The thinking level controls reasoning depth. For `anthropic` in the default `budget` mode it maps to a thinking token budget (minimal 1024, low 2048, medium 8192, high 16384, xhigh 32768, max 65536); with `thinking_mode: adaptive` it maps to an effort-based `output_config` instead (minimal resolves to low, xhigh to high). For `openai` and `openai-compat` it maps to the provider reasoning effort, passed through verbatim unless `thinking_level_map` remaps it. The budget shares `max_output_tokens` and always leaves at least 1024 answer tokens, so lower `max_output_tokens` shrinks the thinking budget instead of disabling it (below a 2048-token cap no valid budget remains and thinking falls back to disabled). Levels the model does not support are declared through `thinking_level_map` (map to a supported effort, or `null` to disable) and `reasoning: false`; an unsupported request is clamped down to the nearest available level. Use `/thinking <level>` to change it at runtime (the change is applied to the active client and saved to `~/.yukino/config.yaml`), or bare `/thinking` to open a picker of the levels the active provider supports.
139
148
 
140
149
  API keys are resolved in this order: explicit api_key field, then environment variables (ANTHROPIC_API_KEY for anthropic, OPENAI_API_KEY for openai and openai-compat).
141
150
 
@@ -210,10 +219,10 @@ In addition to `mcp_servers` in `config.yaml`, Yukino reads a project-level `.mc
210
219
  ```json
211
220
  {
212
221
  "mcpServers": {
213
- "database": {
222
+ "yukino-mcp": {
214
223
  "command": "npx",
215
- "args": ["-y", "@yukino-db/mcp@latest"],
216
- "env": { "API_KEY": "${DATABASE_API_KEY}" }
224
+ "args": ["-y", "@yukino.js/mcp@latest"],
225
+ "env": { "API_KEY": "${YUKINO_MCP_API_KEY}" }
217
226
  },
218
227
  "remote": {
219
228
  "type": "http",
@@ -234,11 +243,13 @@ After editing `.mcp.json` or `config.yaml`, use `/mcp reload` in the UI to re-re
234
243
 
235
244
  ```bash
236
245
  yukino
246
+ yukino --resume # open the session picker at startup
247
+ yukino --resume <session-id> # restore a specific session at startup
237
248
  ```
238
249
 
239
- Launches the terminal interface. If multiple providers are configured, a provider selection screen appears first.
250
+ Launches the terminal interface with the provider recorded as `default_provider` in `~/.yukino/config.yaml` (the one last selected via `/provider` or `/login`; the first provider by default). Use `/provider` to switch providers at runtime. When no provider is configured, the login form opens automatically.
240
251
 
241
- Use `/login` to configure and activate a provider from the UI. When no provider is configured, the login form opens automatically. Name, protocol, base URL, API key, and model are required in the form. Use ↑↓ or Tab to move between fields, ←→ to select protocol or cycle the thinking level, Enter to save, and Esc to cancel. Changing the protocol also moves an untouched thinking level to that protocol's default.
252
+ Use `/login` to configure and activate a provider from the UI. Name, protocol, base URL, API key, and model are required in the form. Use ↑↓ or Tab to move between fields, ←→ to select protocol or cycle the thinking level, Enter to save, and Esc to cancel. Changing the protocol keeps the thinking level; levels the new protocol cannot support display clamped to the nearest available level.
242
253
 
243
254
  The form saves to `~/.yukino/config.yaml`, retaining existing providers and other settings. `base_url` is the provider identity: saving a provider whose `base_url` already exists replaces that entry in place instead of adding another one, and names may repeat freely. Context window accepts integers from 1000 to 10000000; max output accepts integers from 1 to 1000000 and must not exceed the context window. Empty optional fields use the defaults above.
244
255
 
@@ -249,7 +260,7 @@ yukino -p "explain this codebase"
249
260
  yukino -p "fix the failing test" --output-format stream-json
250
261
  ```
251
262
 
252
- The -p flag sends a single prompt, runs the agent loop, and prints the result to stdout. Useful for scripting and CI pipelines.
263
+ The -p flag sends a single prompt, runs the agent loop, and prints the result to stdout (`text` by default, or one JSON line per event with `--output-format stream-json`). Print mode intentionally bypasses permission prompts, so only run it on trusted prompts. Useful for scripting and CI pipelines.
253
264
 
254
265
  ### Remote Mode (Browser UI)
255
266
 
@@ -261,30 +272,44 @@ yukino --remote 0.0.0.0:9000 # explicitly expose on all interfaces (no buil
261
272
 
262
273
  Starts a Koa HTTP server and WebSocket bridge. The bundled React frontend is served at the configured address for browser-based interaction.
263
274
 
275
+ ### ACP Mode (Editor Integration)
276
+
277
+ ```bash
278
+ yukino --acp # Agent Client Protocol over stdio (cannot be combined with other flags)
279
+ yukino --acp-ws # ACP over WebSocket, listens on 127.0.0.1:18889
280
+ yukino --acp-ws host:port # ACP over WebSocket at a custom loopback address
281
+ ```
282
+
283
+ 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.
284
+
264
285
  ### Slash Commands
265
286
 
266
287
  Inside the UI, these commands are available:
267
288
 
268
- | Command | Description |
269
- | -------------------- | ------------------------------------------------------------------------------------------------------------------------- |
270
- | /login | Configure, save, and activate an LLM provider |
271
- | /status | Show current session status (model, tokens, tools, sandbox, memories, skills, MCP) |
272
- | /memory | List stored memories |
273
- | /memory clear | Clear all memories |
274
- | /skills | List available skills |
275
- | /skills reload | Hot-reload skills from disk |
276
- | /skill <name> [args] | Run a skill by name |
277
- | /plan | Enter plan mode (read-only investigation) |
278
- | /compact | Force conversation compaction |
279
- | /clear | Reset the session and clear the terminal |
280
- | /resume [id] | List or restore a previous session |
281
- | /rewind | Open checkpoint rewind dialog |
282
- | /sandbox [1/2/3] | Configure sandbox (1=on+auto, 2=on+manual, 3=off) |
283
- | /worktree | List git worktrees |
284
- | /mcp | Show MCP server status |
285
- | /mcp reload | Re-read MCP config; reconcile unchanged, removed, new, and changed servers |
286
- | /thinking [level] | Show or set the thinking level (off, minimal, low, medium, high, xhigh, max); setting persists to `~/.yukino/config.yaml` |
287
- | /quit | Exit the application |
289
+ | Command | Description |
290
+ | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
291
+ | /login | Configure, save, and activate an LLM provider |
292
+ | /provider | Switch the active provider |
293
+ | /help [command] | Show available commands, or details for a single command |
294
+ | /status | Show current session status (model, tokens, tools, sandbox, memories, skills, MCP) |
295
+ | /session | Confirm the session is active; use /resume to list past sessions |
296
+ | /memory | List stored memories |
297
+ | /memory clear | Clear all memories |
298
+ | /skills | List available skills |
299
+ | /skills reload | Hot-reload skills from disk |
300
+ | /skill <name> [args] | Run a skill by name (shorthand for `/<name> [args]`; `/skill reload` routes to `/skills reload`) |
301
+ | /plan | Enter plan mode (read-only investigation) |
302
+ | /compact | Force conversation compaction |
303
+ | /clear | Reset the session and clear the terminal |
304
+ | /resume [id] | List or restore a previous session |
305
+ | /rewind | Open checkpoint rewind dialog |
306
+ | /sandbox [mode] | Configure sandbox (auto=on+auto, manual=on+manual, off) |
307
+ | /worktree | List git worktrees |
308
+ | /mcp | Show MCP server status |
309
+ | /mcp reload | Re-read MCP config; reconcile unchanged, removed, new, and changed servers |
310
+ | /thinking [level] | Without an argument, open a picker of the supported thinking levels; with one, set the level (off, minimal, low, medium, high, xhigh, max). The setting persists to `~/.yukino/config.yaml` |
311
+ | /code-review | Open the code review form for workspace, branch-range, or commit review |
312
+ | /quit | Exit the application |
288
313
 
289
314
  ### Keyboard Shortcuts
290
315
 
@@ -292,7 +317,8 @@ Inside the UI, these commands are available:
292
317
  | --------- | ----------------------------------------------------------------------------------- |
293
318
  | Ctrl+C | Clear input or interrupt streaming (first press), exit app (second press within 2s) |
294
319
  | Ctrl+O | Toggle full vs. truncated tool output |
295
- | Ctrl+T | Toggle Teams dialog overlay |
320
+ | Ctrl+T | Toggle Teams dialog overlay (when not streaming) |
321
+ | Ctrl+B | Move running foreground Bash/PowerShell tasks to the background |
296
322
  | Ctrl+V | Paste a clipboard image (Alt+V on Windows) |
297
323
  | Shift+Tab | Cycle permission modes |
298
324
 
@@ -304,10 +330,10 @@ Pasting an image saves it as a PNG under `.yukino/file-history/<session-id>/`. I
304
330
 
305
331
  Besides the `yukino` CLI, the package ships a library entry for embedding Yukino in another host process.
306
332
 
307
- | Entry | Output | Contents |
308
- | -------------- | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------- |
309
- | CLI (`yukino`) | `dist/main.js` | Fully bundled, minified single file with a shebang; only Node built-ins stay external. |
310
- | Library | `dist/lib/index.js`, `dist/lib/index.d.ts` | The `src/index.ts` barrel; runtime dependencies stay external and resolve from the consumer's `node_modules`. |
333
+ | Entry | Output | Contents |
334
+ | -------------- | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
335
+ | CLI (`yukino`) | `dist/main.js` | Fully bundled, minified single file with a shebang; Node built-ins plus modules with native binaries or runtime assets (`sharp`, `@anthropic-ai/sandbox-runtime`, ink's `react-devtools-core` peer) stay external. |
336
+ | Library | `dist/lib/index.js`, `dist/lib/index.d.ts` | The `src/index.ts` barrel; runtime dependencies stay external and resolve from the consumer's `node_modules`. |
311
337
 
312
338
  The library entry is terminal-independent by contract: it must never reach `src/ui/**` or a ui-only dependency, so a host without a TTY (a server, an editor extension, a test harness) can import it. `pnpm build` enforces that contract:
313
339
 
@@ -315,4 +341,4 @@ The library entry is terminal-independent by contract: it must never reach `src/
315
341
  - **`react` is banned, `react-dom` never appears** — the barrel does not re-export `src/ui/**`, so `react` is reached exclusively from the terminal layer; `react-dom` is imported only by the standalone browser bundle (`src/remote/fe`, built separately via `pnpm build:fe`), which is not part of the library graph.
316
342
  - **Ambiguous export scan** — once the bundle is written, the build runs the TypeScript ambiguous-export check (`TS2308`) over the library graph. A name exported by two `export *` sources is dropped by the bundler without any warning; the scan turns that into a build failure instead of a quietly smaller public API.
317
343
 
318
- In a long-lived host process, prefer the composable modules (`Agent`, `ToolRegistry`, …) over the process-level entry points (`print-mode`, `recover`, `teammate`), which may write crash dumps or call `process.exit()`.
344
+ In a long-lived host process, prefer the composable modules (`Agent`, `ToolRegistry`, …) over the process-level entry points (`print-mode`, `recover`, `teammate`), which own process lifecycle — `recover` installs crash logging to `.yukino/crash.log` and calls `process.exit()`, and `print-mode` exits on invalid flags.
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __yukinoCreateRequire } from "node:module";
3
+ const require = __yukinoCreateRequire(import.meta.url);
4
+ import{a as $n,b as Jn}from"./chunk-YVLW4WBA.js";import"./chunk-5HF4GLFR.js";import"./chunk-NAQRFHUX.js";import{p as Hn,q as Ln,s as Gn,t as Fn,v as Un,x as Bn,y as Wn}from"./chunk-3SPUH3TD.js";import{a as Pn}from"./chunk-BPA7URET.js";import"./chunk-JFKC4VCA.js";import"./chunk-VM26JJ6N.js";import"./chunk-OFC2GD5K.js";import{b as On,c as Dn,d as jn,e as qn}from"./chunk-WNHTKUKK.js";import"./chunk-ZPYQCXWT.js";import"./chunk-HBXZ6MB4.js";import"./chunk-SDXAS44V.js";import"./chunk-3EQYWNP6.js";import"./chunk-MQAQBW7F.js";import{k as Qe,t as Ze}from"./chunk-2HUCPWD6.js";import{D as ee,g as i,h as Nn,i as T,j as I,k as A,n as c,o as v,p as r,r as g,t as J,u as d,w as l}from"./chunk-GYBJR2RB.js";import{b as Mn}from"./chunk-VM4YKTHC.js";import"./chunk-HMZQYFYG.js";import"./chunk-3QL446GD.js";import"./chunk-AGSYLE4E.js";import"./chunk-CU3IISCC.js";import"./chunk-VCIRD267.js";import{d as ve}from"./chunk-7MKA3SHV.js";var Js={};ve(Js,{runAcpStdio:()=>xn});import{Readable as sc,Writable as ic}from"stream";var h={initialize:"initialize",authenticate:"authenticate",providers_list:"providers/list",providers_set:"providers/set",providers_disable:"providers/disable",session_new:"session/new",session_load:"session/load",session_set_mode:"session/set_mode",session_set_config_option:"session/set_config_option",session_prompt:"session/prompt",session_cancel:"session/cancel",mcp_message:"mcp/message",session_list:"session/list",session_delete:"session/delete",session_fork:"session/fork",session_resume:"session/resume",session_close:"session/close",logout:"logout",nes_start:"nes/start",nes_suggest:"nes/suggest",nes_accept:"nes/accept",nes_reject:"nes/reject",nes_close:"nes/close",document_did_open:"document/didOpen",document_did_change:"document/didChange",document_did_close:"document/didClose",document_did_save:"document/didSave",document_did_focus:"document/didFocus"},_={session_request_permission:"session/request_permission",session_update:"session/update",fs_write_text_file:"fs/write_text_file",fs_read_text_file:"fs/read_text_file",terminal_create:"terminal/create",terminal_output:"terminal/output",terminal_release:"terminal/release",terminal_wait_for_exit:"terminal/wait_for_exit",terminal_kill:"terminal/kill",mcp_connect:"mcp/connect",mcp_message:"mcp/message",mcp_disconnect:"mcp/disconnect",elicitation_create:"elicitation/create",elicitation_complete:"elicitation/complete"},et={cancel_request:"$/cancel_request"},tt=1;var Vn=Symbol("skippedItem");function o(n,e){return n.catch(e)}function D(n,e){let t=n.catch(e);return ee.unknown().transform((s,a)=>s!==void 0?t.parse(s):(a.addIssue({code:"custom",message:"Required value is missing"}),ee.NEVER))}function Kn(n,e){if(n===null||typeof n!="object"||Array.isArray(n))return;let t=n[e];return typeof t=="string"?t:void 0}function fe(n,e,t){return n.superRefine((s,a)=>{let u=Kn(s,e);u!==void 0&&t.includes(u)&&a.addIssue({code:"custom",path:[e],message:`${e} ${JSON.stringify(u)} is reserved by a known variant, but the value does not match that variant's schema`})})}function pe(n,e,t){return ee.unknown().transform((s,a)=>{let u=n.safeParse(s);if(!u.success){for(let p of u.error.issues)a.addIssue({...p,input:s});return ee.NEVER}let f=u.data,z=Kn(s,e);if(z!==void 0&&!t.includes(z)){let p=s;for(let[w,m]of Object.entries(p))w!=="__proto__"&&(Object.hasOwn(f,w)||(f[w]=m))}return f})}function E(n){return ee.array(n.catch(Vn)).transform(e=>e.filter(t=>t!==Vn))}var V=g([T(),i()]).nullable(),x=i(),st=r({sessionId:x,path:i(),content:i(),_meta:o(d(i(),c()).nullish(),()=>{})}),it=r({sessionId:x,path:i(),line:o(I().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),limit:o(I().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),ot=i(),Yn=g([l("read"),l("edit"),l("delete"),l("move"),l("search"),l("execute"),l("think"),l("fetch"),l("switch_mode"),l("other")]),Xn=g([l("pending"),l("in_progress"),l("completed"),l("failed")]),Ei=g([l("assistant"),l("user")]),ze=r({audience:o(E(Ei).nullish(),()=>{}),lastModified:o(i().nullish(),()=>{}),priority:o(T().nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),yi=r({annotations:o(ze.nullish(),()=>{}),text:i(),_meta:o(d(i(),c()).nullish(),()=>{})}),xi=r({annotations:o(ze.nullish(),()=>{}),data:i(),mimeType:i(),uri:o(i().nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),Ri=r({annotations:o(ze.nullish(),()=>{}),data:i(),mimeType:i(),_meta:o(d(i(),c()).nullish(),()=>{})}),Ti=r({annotations:o(ze.nullish(),()=>{}),description:o(i().nullish(),()=>{}),mimeType:o(i().nullish(),()=>{}),name:i(),size:o(T().nullish(),()=>{}),title:o(i().nullish(),()=>{}),uri:i(),_meta:o(d(i(),c()).nullish(),()=>{})}),Ci=r({mimeType:o(i().nullish(),()=>{}),text:i(),uri:i(),_meta:o(d(i(),c()).nullish(),()=>{})}),vi=r({blob:i(),mimeType:o(i().nullish(),()=>{}),uri:i(),_meta:o(d(i(),c()).nullish(),()=>{})}),ki=g([Ci,vi]),Ai=r({annotations:o(ze.nullish(),()=>{}),resource:ki,_meta:o(d(i(),c()).nullish(),()=>{})}),me=g([yi.and(r({type:l("text")})),xi.and(r({type:l("image")})),Ri.and(r({type:l("audio")})),Ti.and(r({type:l("resource_link")})),Ai.and(r({type:l("resource")}))]),Ii=r({content:me,_meta:o(d(i(),c()).nullish(),()=>{})}),Mi=r({path:i(),oldText:o(i().nullish(),()=>{}),newText:i(),_meta:o(d(i(),c()).nullish(),()=>{})}),oe=i(),Ni=r({terminalId:oe,_meta:o(d(i(),c()).nullish(),()=>{})}),Qn=g([Ii.and(r({type:l("content")})),Mi.and(r({type:l("diff")})),Ni.and(r({type:l("terminal")}))]),Zn=r({path:i(),line:o(I().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),es=r({toolCallId:ot,kind:o(Yn.nullish(),()=>{}),status:o(Xn.nullish(),()=>{}),title:o(i().nullish(),()=>{}),name:o(i().nullish(),()=>{}),content:o(E(Qn).nullish(),()=>{}),locations:o(E(Zn).nullish(),()=>{}),rawInput:o(c().optional(),()=>{}),rawOutput:o(c().optional(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),ts=i(),Oi=g([l("allow_once"),l("allow_always"),l("reject_once"),l("reject_always")]),Di=r({optionId:ts,name:i(),kind:Oi,_meta:o(d(i(),c()).nullish(),()=>{})}),rt=r({sessionId:x,toolCall:es,options:v(Di),_meta:o(d(i(),c()).nullish(),()=>{})}),ns=r({name:i(),value:i(),_meta:o(d(i(),c()).nullish(),()=>{})}),at=r({sessionId:x,command:i(),args:o(E(i()).optional(),()=>[]),env:o(E(ns).optional(),()=>[]),cwd:o(i().nullish(),()=>{}),outputByteLimit:o(T().nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),ct=r({sessionId:x,terminalId:oe,_meta:o(d(i(),c()).nullish(),()=>{})}),dt=r({sessionId:x,terminalId:oe,_meta:o(d(i(),c()).nullish(),()=>{})}),ut=r({sessionId:x,terminalId:oe,_meta:o(d(i(),c()).nullish(),()=>{})}),lt=r({sessionId:x,terminalId:oe,_meta:o(d(i(),c()).nullish(),()=>{})}),ge=r({sessionId:x,toolCallId:o(ot.nullish(),()=>{})}),be=r({requestId:V}),ji=l("object"),qi=g([l("email"),l("uri"),l("date"),l("date-time")]),ss=r({const:i(),title:i(),description:o(i().nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),ht=r({title:o(i().nullish(),()=>{}),description:o(i().nullish(),()=>{}),minLength:I().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),maxLength:I().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),pattern:i().nullish(),format:qi.nullish(),default:o(i().nullish(),()=>{}),enum:v(i()).nullish(),oneOf:v(ss).nullish(),_meta:o(d(i(),c()).nullish(),()=>{})}),ft=r({title:o(i().nullish(),()=>{}),description:o(i().nullish(),()=>{}),minimum:T().nullish(),maximum:T().nullish(),default:o(T().nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),pt=r({title:o(i().nullish(),()=>{}),description:o(i().nullish(),()=>{}),minimum:T().nullish(),maximum:T().nullish(),default:o(T().nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),zt=r({title:o(i().nullish(),()=>{}),description:o(i().nullish(),()=>{}),default:o(A().nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),mt=r({enum:v(i()),_meta:o(d(i(),c()).nullish(),()=>{})}),is=r({anyOf:v(ss),_meta:o(d(i(),c()).nullish(),()=>{})}),Pi=pe(g([mt.and(r({type:l("string")})),fe(r({type:i()}),"type",["string"]),is]),"type",["string"]),gt=r({title:o(i().nullish(),()=>{}),description:o(i().nullish(),()=>{}),minItems:T().nullish(),maxItems:T().nullish(),items:Pi,default:o(E(i()).nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),Hi=pe(g([ht.and(r({type:l("string")})),ft.and(r({type:l("number")})),pt.and(r({type:l("integer")})),zt.and(r({type:l("boolean")})),gt.and(r({type:l("array")})),fe(r({type:i()}),"type",["array","boolean","integer","number","string"])]),"type",["array","boolean","integer","number","string"]),Li=r({type:o(ji.optional().default("object"),()=>"object"),title:o(i().nullish(),()=>{}),properties:d(i(),Hi).optional().default({}),required:v(i()).nullish(),description:o(i().nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),bt=J(g([ge,be]),r({requestedSchema:Li})),os=i(),_t=J(g([ge,be]),r({elicitationId:os,url:Nn()})),wt=pe(J(g([bt.and(r({mode:l("form")})),_t.and(r({mode:l("url")})),fe(J(g([ge,be]),r({mode:i()})),"mode",["form","url"])]),r({message:i(),_meta:o(d(i(),c()).nullish(),()=>{})})),"mode",["form","url"]),rs=i(),Gi=r({serverId:rs,_meta:o(d(i(),c()).nullish(),()=>{})}),ke=i(),as=r({connectionId:ke,method:i(),params:d(i(),c()).nullish(),_meta:o(d(i(),c()).nullish(),()=>{})}),Fi=r({connectionId:ke,_meta:o(d(i(),c()).nullish(),()=>{})}),cs=c(),Uc=r({id:V,method:i(),params:g([st,it,rt,at,ct,dt,ut,lt,wt,Gi,as,Fi,cs]).nullish()}),ds=I().gte(0).lte(65535),Ui=r({image:o(A().optional().default(!1),()=>!1),audio:o(A().optional().default(!1),()=>!1),embeddedContext:o(A().optional().default(!1),()=>!1),_meta:o(d(i(),c()).nullish(),()=>{})}),Bi=r({http:o(A().optional().default(!1),()=>!1),sse:o(A().optional().default(!1),()=>!1),acp:o(A().optional().default(!1),()=>!1),_meta:o(d(i(),c()).nullish(),()=>{})}),Wi=r({_meta:o(d(i(),c()).nullish(),()=>{})}),$i=r({_meta:o(d(i(),c()).nullish(),()=>{})}),Ji=r({_meta:o(d(i(),c()).nullish(),()=>{})}),Vi=r({_meta:o(d(i(),c()).nullish(),()=>{})}),Ki=r({_meta:o(d(i(),c()).nullish(),()=>{})}),Yi=r({_meta:o(d(i(),c()).nullish(),()=>{})}),Xi=r({list:o(Wi.nullish(),()=>{}),delete:o($i.nullish(),()=>{}),additionalDirectories:o(Ji.nullish(),()=>{}),fork:o(Vi.nullish(),()=>{}),resume:o(Ki.nullish(),()=>{}),close:o(Yi.nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),Qi=r({_meta:o(d(i(),c()).nullish(),()=>{})}),Zi=r({logout:o(Qi.nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),eo=r({_meta:o(d(i(),c()).nullish(),()=>{})}),to=r({_meta:o(d(i(),c()).nullish(),()=>{})}),no=g([l("full"),l("incremental")]),so=r({syncKind:no,_meta:o(d(i(),c()).nullish(),()=>{})}),io=r({_meta:o(d(i(),c()).nullish(),()=>{})}),oo=r({_meta:o(d(i(),c()).nullish(),()=>{})}),ro=r({_meta:o(d(i(),c()).nullish(),()=>{})}),ao=r({didOpen:o(to.nullish(),()=>{}),didChange:o(so.nullish(),()=>{}),didClose:o(io.nullish(),()=>{}),didSave:o(oo.nullish(),()=>{}),didFocus:o(ro.nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),co=r({document:o(ao.nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),uo=r({maxCount:o(I().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),lo=r({_meta:o(d(i(),c()).nullish(),()=>{})}),ho=r({maxCount:o(I().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),fo=r({maxCount:o(I().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),po=r({_meta:o(d(i(),c()).nullish(),()=>{})}),zo=r({_meta:o(d(i(),c()).nullish(),()=>{})}),mo=r({recentFiles:o(uo.nullish(),()=>{}),relatedSnippets:o(lo.nullish(),()=>{}),editHistory:o(ho.nullish(),()=>{}),userActions:o(fo.nullish(),()=>{}),openFiles:o(po.nullish(),()=>{}),diagnostics:o(zo.nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),go=r({events:o(co.nullish(),()=>{}),context:o(mo.nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),us=g([l("utf-16"),l("utf-32"),l("utf-8")]),bo=r({loadSession:o(A().optional().default(!1),()=>!1),promptCapabilities:o(Ui.optional().default({image:!1,audio:!1,embeddedContext:!1}),()=>({image:!1,audio:!1,embeddedContext:!1})),mcpCapabilities:o(Bi.optional().default({http:!1,sse:!1,acp:!1}),()=>({http:!1,sse:!1,acp:!1})),sessionCapabilities:o(Xi.optional().default({}),()=>({})),auth:o(Zi.optional().default({}),()=>({})),providers:o(eo.nullish(),()=>{}),nes:o(go.nullish(),()=>{}),positionEncoding:o(us.nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),St=i(),_o=r({id:St,name:i(),description:o(i().nullish(),()=>{}),args:o(E(i()).optional(),()=>[]),env:o(d(i(),i()).optional(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),wo=r({id:St,name:i(),description:o(i().nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),So=g([_o.and(r({type:l("terminal")})),wo]),ls=r({name:i(),title:o(i().nullish(),()=>{}),version:i(),_meta:o(d(i(),c()).nullish(),()=>{})}),Eo=r({protocolVersion:ds,agentCapabilities:o(bo.optional().default({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}}),()=>({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}})),authMethods:o(E(So).optional().default([]),()=>[]),agentInfo:o(ls.nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),yo=r({_meta:o(d(i(),c()).nullish(),()=>{})}),Et=i(),yt=g([l("anthropic"),l("openai"),l("azure"),l("vertex"),l("bedrock"),i()]),xo=r({apiType:yt,baseUrl:i(),_meta:o(d(i(),c()).nullish(),()=>{})}),Ro=r({providerId:Et,supported:D(E(yt),()=>[]),required:A(),current:xo.nullish(),_meta:o(d(i(),c()).nullish(),()=>{})}),To=r({providers:v(Ro),_meta:o(d(i(),c()).nullish(),()=>{})}),Co=r({_meta:o(d(i(),c()).nullish(),()=>{})}),vo=r({_meta:o(d(i(),c()).nullish(),()=>{})}),ko=r({_meta:o(d(i(),c()).nullish(),()=>{})}),Ae=i(),Ao=r({id:Ae,name:i(),description:o(i().nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),Ie=r({currentModeId:Ae,availableModes:D(E(Ao),()=>[]),_meta:o(d(i(),c()).nullish(),()=>{})}),hs=i(),Io=g([l("mode"),l("model"),l("model_config"),l("thought_level"),i()]),xt=i(),fs=r({value:xt,name:i(),description:o(i().nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),Mo=i(),No=r({group:Mo,name:i(),options:D(E(fs),()=>[]),_meta:o(d(i(),c()).nullish(),()=>{})}),Oo=g([v(fs),v(No)]),Do=r({currentValue:xt,options:Oo}),jo=r({currentValue:A()}),re=J(g([Do.and(r({type:l("select")})),jo.and(r({type:l("boolean")}))]),r({id:hs,name:i(),description:o(i().nullish(),()=>{}),category:o(Io.nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})})),qo=r({sessionId:x,modes:o(Ie.nullish(),()=>{}),configOptions:o(E(re).nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),Po=r({modes:o(Ie.nullish(),()=>{}),configOptions:o(E(re).nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),Ho=r({sessionId:x,cwd:i(),additionalDirectories:o(E(i()).optional(),()=>[]),title:o(i().nullish(),()=>{}),updatedAt:o(i().nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),Lo=r({sessions:D(E(Ho),()=>[]),nextCursor:o(i().nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),Go=r({_meta:o(d(i(),c()).nullish(),()=>{})}),Fo=r({sessionId:x,modes:o(Ie.nullish(),()=>{}),configOptions:o(E(re).nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),Uo=r({modes:o(Ie.nullish(),()=>{}),configOptions:o(E(re).nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),Bo=r({_meta:o(d(i(),c()).nullish(),()=>{})}),Wo=r({_meta:o(d(i(),c()).nullish(),()=>{})}),$o=r({configOptions:D(E(re),()=>[]),_meta:o(d(i(),c()).nullish(),()=>{})}),Jo=g([l("end_turn"),l("max_tokens"),l("max_turn_requests"),l("refusal"),l("cancelled")]),Vo=r({totalTokens:T(),inputTokens:T(),outputTokens:T(),thoughtTokens:o(T().nullish(),()=>{}),cachedReadTokens:o(T().nullish(),()=>{}),cachedWriteTokens:o(T().nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),Ko=r({stopReason:Jo,usage:o(Vo.nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),Yo=r({sessionId:x,_meta:o(d(i(),c()).nullish(),()=>{})}),ae=i(),K=r({line:I().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}),character:I().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}),_meta:o(d(i(),c()).nullish(),()=>{})}),ce=r({start:K,end:K,_meta:o(d(i(),c()).nullish(),()=>{})}),Xo=r({range:ce,newText:i(),_meta:o(d(i(),c()).nullish(),()=>{})}),Qo=r({id:ae,uri:i(),edits:v(Xo),cursorPosition:o(K.nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),Zo=r({id:ae,uri:i(),position:K,_meta:o(d(i(),c()).nullish(),()=>{})}),er=r({id:ae,uri:i(),position:K,newName:i(),_meta:o(d(i(),c()).nullish(),()=>{})}),tr=r({id:ae,uri:i(),search:i(),replace:i(),isRegex:A().nullish(),_meta:o(d(i(),c()).nullish(),()=>{})}),nr=g([Qo.and(r({kind:l("edit")})),Zo.and(r({kind:l("jump")})),er.and(r({kind:l("rename")})),tr.and(r({kind:l("searchAndReplace")}))]),sr=r({suggestions:v(nr),_meta:o(d(i(),c()).nullish(),()=>{})}),ir=r({_meta:o(d(i(),c()).nullish(),()=>{})}),ps=c(),zs=c(),or=g([l(-32700),l(-32600),l(-32601),l(-32602),l(-32603),l(-32800),l(-32e3),l(-32002),I().min(-2147483648,{error:"Invalid value: Expected int32 to be >= -2147483648"}).max(2147483647,{error:"Invalid value: Expected int32 to be <= 2147483647"})]),ms=r({code:or,message:i(),data:o(c().optional(),()=>{})}),Bc=g([r({id:V,result:g([Eo,yo,To,Co,vo,ko,qo,Po,Lo,Go,Fo,Uo,Bo,Wo,$o,Ko,Yo,sr,ir,ps,zs])}),r({id:V,error:ms})]),rr=i(),nt=r({content:me,messageId:o(rr.nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),ar=r({toolCallId:ot,title:i(),name:o(i().nullish(),()=>{}),kind:o(Yn.optional(),()=>{}),status:o(Xn.optional(),()=>{}),content:o(E(Qn).optional(),()=>[]),locations:o(E(Zn).optional(),()=>[]),rawInput:o(c().optional(),()=>{}),rawOutput:o(c().optional(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),cr=g([l("high"),l("medium"),l("low")]),dr=g([l("pending"),l("in_progress"),l("completed")]),gs=r({content:i(),priority:cr,status:dr,_meta:o(d(i(),c()).nullish(),()=>{})}),ur=r({entries:D(E(gs),()=>[]),_meta:o(d(i(),c()).nullish(),()=>{})}),Me=i(),lr=r({planId:Me,entries:D(E(gs),()=>[]),_meta:o(d(i(),c()).nullish(),()=>{})}),hr=r({planId:Me,uri:i(),_meta:o(d(i(),c()).nullish(),()=>{})}),fr=r({planId:Me,content:i(),_meta:o(d(i(),c()).nullish(),()=>{})}),pr=g([lr.and(r({type:l("items")})),hr.and(r({type:l("file")})),fr.and(r({type:l("markdown")}))]),zr=r({plan:pr,_meta:o(d(i(),c()).nullish(),()=>{})}),mr=r({planId:Me,_meta:o(d(i(),c()).nullish(),()=>{})}),gr=r({hint:i(),_meta:o(d(i(),c()).nullish(),()=>{})}),br=gr,_r=r({name:i(),description:i(),input:o(br.nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),wr=r({availableCommands:D(E(_r),()=>[]),_meta:o(d(i(),c()).nullish(),()=>{})}),Sr=r({currentModeId:Ae,_meta:o(d(i(),c()).nullish(),()=>{})}),Er=r({configOptions:D(E(re),()=>[]),_meta:o(d(i(),c()).nullish(),()=>{})}),yr=r({title:o(i().nullish(),()=>{}),updatedAt:o(i().nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),xr=r({amount:T(),currency:i(),_meta:o(d(i(),c()).nullish(),()=>{})}),Rr=r({used:T(),size:T(),cost:o(xr.nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),Tr=g([l("info"),l("warning"),l("error"),i()]),Cr=r({severity:Tr,title:i().min(1),description:o(i().nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),bs=i(),vr=g([l("in_progress"),l("completed"),l("failed"),l("cancelled"),i()]),kr=r({compactionId:bs,status:vr,summary:o(E(me).nullish(),()=>{}),error:o(i().nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),Ar=r({compactionId:bs,content:me,_meta:o(d(i(),c()).nullish(),()=>{})}),Ir=g([nt.and(r({sessionUpdate:l("user_message_chunk")})),nt.and(r({sessionUpdate:l("agent_message_chunk")})),nt.and(r({sessionUpdate:l("agent_thought_chunk")})),ar.and(r({sessionUpdate:l("tool_call")})),es.and(r({sessionUpdate:l("tool_call_update")})),ur.and(r({sessionUpdate:l("plan")})),zr.and(r({sessionUpdate:l("plan_update")})),mr.and(r({sessionUpdate:l("plan_removed")})),wr.and(r({sessionUpdate:l("available_commands_update")})),Sr.and(r({sessionUpdate:l("current_mode_update")})),Er.and(r({sessionUpdate:l("config_option_update")})),yr.and(r({sessionUpdate:l("session_info_update")})),Rr.and(r({sessionUpdate:l("usage_update")})),Cr.and(r({sessionUpdate:l("notice")})),kr.and(r({sessionUpdate:l("compaction_update")})),Ar.and(r({sessionUpdate:l("compaction_summary_chunk")}))]),Ne=r({sessionId:x,update:Ir,_meta:o(d(i(),c()).nullish(),()=>{})}),Rt=r({elicitationId:os,_meta:o(d(i(),c()).nullish(),()=>{})}),_s=r({connectionId:ke,method:i(),params:o(d(i(),c()).nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),ws=c(),Wc=r({method:i(),params:g([Ne,Rt,_s,ws]).nullish()}),Mr=r({readTextFile:o(A().optional().default(!1),()=>!1),writeTextFile:o(A().optional().default(!1),()=>!1),_meta:o(d(i(),c()).nullish(),()=>{})}),Nr=d(i(),c()),Or=r({_meta:o(d(i(),c()).nullish(),()=>{})}),Dr=r({boolean:o(Or.nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),jr=d(i(),c()),qr=r({compaction:o(Nr.nullish(),()=>{}),configOptions:o(Dr.nullish(),()=>{}),notices:o(jr.nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),Pr=r({_meta:o(d(i(),c()).nullish(),()=>{})}),Hr=r({terminal:o(A().optional().default(!1),()=>!1),_meta:o(d(i(),c()).nullish(),()=>{})}),Lr=r({_meta:o(d(i(),c()).nullish(),()=>{})}),Gr=r({_meta:o(d(i(),c()).nullish(),()=>{})}),Fr=r({form:o(Lr.nullish(),()=>{}),url:o(Gr.nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),Ur=r({_meta:o(d(i(),c()).nullish(),()=>{})}),Br=r({_meta:o(d(i(),c()).nullish(),()=>{})}),Wr=r({_meta:o(d(i(),c()).nullish(),()=>{})}),$r=r({jump:o(Ur.nullish(),()=>{}),rename:o(Br.nullish(),()=>{}),searchAndReplace:o(Wr.nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),Jr=r({fs:o(Mr.optional().default({readTextFile:!1,writeTextFile:!1}),()=>({readTextFile:!1,writeTextFile:!1})),terminal:o(A().optional().default(!1),()=>!1),session:o(qr.nullish(),()=>{}),plan:o(Pr.nullish(),()=>{}),auth:o(Hr.optional().default({terminal:!1}),()=>({terminal:!1})),elicitation:o(Fr.nullish(),()=>{}),nes:o($r.nullish(),()=>{}),positionEncodings:o(E(us).optional(),()=>[]),_meta:o(d(i(),c()).nullish(),()=>{})}),Tt=r({protocolVersion:ds,clientCapabilities:o(Jr.optional().default({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}}),()=>({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}})),clientInfo:o(ls.nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),Ct=r({methodId:St,_meta:o(d(i(),c()).nullish(),()=>{})}),vt=r({_meta:o(d(i(),c()).nullish(),()=>{})}),kt=r({providerId:Et,apiType:yt,baseUrl:i(),headers:d(i(),i()).optional(),_meta:o(d(i(),c()).nullish(),()=>{})}),At=r({providerId:Et,_meta:o(d(i(),c()).nullish(),()=>{})}),It=r({_meta:o(d(i(),c()).nullish(),()=>{})}),Ss=r({name:i(),value:i(),_meta:o(d(i(),c()).nullish(),()=>{})}),Vr=r({name:i(),url:i(),headers:v(Ss),_meta:o(d(i(),c()).nullish(),()=>{})}),Kr=r({name:i(),url:i(),headers:v(Ss),_meta:o(d(i(),c()).nullish(),()=>{})}),Yr=r({name:i(),serverId:rs,_meta:o(d(i(),c()).nullish(),()=>{})}),Xr=r({name:i(),command:i(),args:v(i()),env:v(ns),_meta:o(d(i(),c()).nullish(),()=>{})}),Oe=g([Vr.and(r({type:l("http")})),Kr.and(r({type:l("sse")})),Yr.and(r({type:l("acp")})),Xr]),Mt=r({cwd:i(),additionalDirectories:o(E(i()).optional(),()=>[]),mcpServers:D(E(Oe),()=>[]),_meta:o(d(i(),c()).nullish(),()=>{})}),Nt=r({mcpServers:D(E(Oe),()=>[]),cwd:i(),additionalDirectories:o(E(i()).optional(),()=>[]),sessionId:x,_meta:o(d(i(),c()).nullish(),()=>{})}),Ot=r({cwd:i().nullish(),cursor:i().nullish(),_meta:o(d(i(),c()).nullish(),()=>{})}),Dt=r({sessionId:x,_meta:o(d(i(),c()).nullish(),()=>{})}),jt=r({sessionId:x,cwd:i(),additionalDirectories:o(E(i()).optional(),()=>[]),mcpServers:o(E(Oe).optional(),()=>[]),_meta:o(d(i(),c()).nullish(),()=>{})}),qt=r({sessionId:x,cwd:i(),additionalDirectories:o(E(i()).optional(),()=>[]),mcpServers:o(E(Oe).optional(),()=>[]),_meta:o(d(i(),c()).nullish(),()=>{})}),Pt=r({sessionId:x,_meta:o(d(i(),c()).nullish(),()=>{})}),Ht=r({sessionId:x,modeId:Ae,_meta:o(d(i(),c()).nullish(),()=>{})}),Lt=J(g([r({value:A(),type:l("boolean")}),r({value:xt})]),r({sessionId:x,configId:hs,_meta:o(d(i(),c()).nullish(),()=>{})})),Gt=r({sessionId:x,prompt:v(me),_meta:o(d(i(),c()).nullish(),()=>{})}),Qr=r({uri:i(),name:i(),_meta:o(d(i(),c()).nullish(),()=>{})}),Zr=r({name:i(),owner:i(),remoteUrl:i(),_meta:o(d(i(),c()).nullish(),()=>{})}),Ft=r({workspaceUri:o(i().nullish(),()=>{}),workspaceFolders:v(Qr).nullish(),repository:o(Zr.nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),ea=g([l("automatic"),l("diagnostic"),l("manual")]),ta=r({uri:i(),languageId:i(),text:i(),_meta:o(d(i(),c()).nullish(),()=>{})}),na=r({startLine:I().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}),endLine:I().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}),text:i(),_meta:o(d(i(),c()).nullish(),()=>{})}),sa=r({uri:i(),excerpts:v(na),_meta:o(d(i(),c()).nullish(),()=>{})}),ia=r({uri:i(),diff:i(),_meta:o(d(i(),c()).nullish(),()=>{})}),oa=r({action:i(),uri:i(),position:K,timestampMs:T(),_meta:o(d(i(),c()).nullish(),()=>{})}),ra=r({uri:i(),languageId:i(),visibleRange:o(ce.nullish(),()=>{}),lastFocusedMs:o(T().nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),aa=g([l("error"),l("warning"),l("information"),l("hint")]),ca=r({uri:i(),range:ce,severity:aa,message:i(),_meta:o(d(i(),c()).nullish(),()=>{})}),da=r({recentFiles:v(ta).nullish(),relatedSnippets:v(sa).nullish(),editHistory:v(ia).nullish(),userActions:v(oa).nullish(),openFiles:v(ra).nullish(),diagnostics:v(ca).nullish(),_meta:o(d(i(),c()).nullish(),()=>{})}),Ut=r({sessionId:x,uri:i(),version:T(),position:K,selection:ce.nullish(),triggerKind:ea,context:da.nullish(),_meta:o(d(i(),c()).nullish(),()=>{})}),Bt=r({sessionId:x,_meta:o(d(i(),c()).nullish(),()=>{})}),$c=r({id:V,method:i(),params:g([Tt,Ct,vt,kt,At,It,Mt,Nt,Ot,Dt,jt,qt,Pt,Ht,Lt,Gt,Ft,Ut,Bt,as,cs]).nullish()}),ua=r({_meta:o(d(i(),c()).nullish(),()=>{})}),la=r({content:i(),_meta:o(d(i(),c()).nullish(),()=>{})}),ha=r({optionId:ts,_meta:o(d(i(),c()).nullish(),()=>{})}),fa=g([r({outcome:l("cancelled")}),ha.and(r({outcome:l("selected")}))]),pa=r({outcome:fa,_meta:o(d(i(),c()).nullish(),()=>{})}),za=r({terminalId:oe,_meta:o(d(i(),c()).nullish(),()=>{})}),ma=r({exitCode:o(I().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),signal:o(i().nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),ga=r({output:i(),truncated:A(),exitStatus:o(ma.nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),ba=r({_meta:o(d(i(),c()).nullish(),()=>{})}),_a=r({exitCode:o(I().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),signal:o(i().nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),wa=r({_meta:o(d(i(),c()).nullish(),()=>{})}),Sa=g([i(),T(),T(),A(),v(i())]),Wt=r({content:d(i(),Sa).nullish()}),Ea=pe(J(g([Wt.and(r({action:l("accept")})),r({action:l("decline")}),r({action:l("cancel")}),fe(r({action:i()}),"action",["accept","cancel","decline"])]),r({_meta:o(d(i(),c()).nullish(),()=>{})})),"action",["accept","cancel","decline"]),ya=r({connectionId:ke,_meta:o(d(i(),c()).nullish(),()=>{})}),xa=r({_meta:o(d(i(),c()).nullish(),()=>{})}),Jc=g([r({id:V,result:g([ua,la,pa,za,ga,ba,_a,wa,Ea,ya,xa,zs,ps])}),r({id:V,error:ms})]),$t=r({sessionId:x,_meta:o(d(i(),c()).nullish(),()=>{})}),Jt=r({sessionId:x,uri:i(),languageId:i(),version:T(),text:i(),_meta:o(d(i(),c()).nullish(),()=>{})}),Ra=r({range:ce.nullish(),text:i(),_meta:o(d(i(),c()).nullish(),()=>{})}),Vt=r({sessionId:x,uri:i(),version:T(),contentChanges:D(E(Ra),()=>[]),_meta:o(d(i(),c()).nullish(),()=>{})}),Kt=r({sessionId:x,uri:i(),_meta:o(d(i(),c()).nullish(),()=>{})}),Yt=r({sessionId:x,uri:i(),_meta:o(d(i(),c()).nullish(),()=>{})}),Xt=r({sessionId:x,uri:i(),version:T(),position:K,visibleRange:ce,_meta:o(d(i(),c()).nullish(),()=>{})}),Qt=r({sessionId:x,id:ae,_meta:o(d(i(),c()).nullish(),()=>{})}),Ta=g([l("rejected"),l("ignored"),l("replaced"),l("cancelled")]),Zt=r({sessionId:x,id:ae,reason:o(Ta.nullish(),()=>{}),_meta:o(d(i(),c()).nullish(),()=>{})}),Vc=r({method:i(),params:g([$t,Jt,Vt,Kt,Yt,Xt,Qt,Zt,_s,ws]).nullish()}),Kc=r({requestId:V,_meta:o(d(i(),c()).nullish(),()=>{})});var ys="$/cancel_request";function G(n){return sn(n)&&"id"in n&&typeof n.method=="string"&&on(n.id)}function Y(n){if(!sn(n)||"method"in n||!("id"in n)||!on(n.id))return!1;let e=Object.hasOwn(n,"result"),t=Object.hasOwn(n,"error");return e===t?!1:!t||va(n.error)}function j(n){return sn(n)&&!("id"in n)&&typeof n.method=="string"}function M(n){return typeof n=="object"&&n!==null}function sn(n){return M(n)&&n.jsonrpc==="2.0"}function on(n){return n===null||typeof n=="string"||typeof n=="number"&&Number.isFinite(n)}function de(n){return M(n)&&!("method"in n)&&("id"in n||"result"in n||"error"in n)}function rn(n){let e=!1,t=!1,s=!1,a=!1;for(let u of n)e||=G(u)||j(u),t||=Y(u),M(u)&&(s||="method"in u,a||="result"in u||"error"in u);return e?!1:t?!0:a&&!s}function Ca(n){if(!(!M(n)||!on(n.requestId)))return n.requestId}function va(n){return M(n)&&typeof n.code=="number"&&Number.isInteger(n.code)&&typeof n.message=="string"}var q={yes(){return{handled:!0}},no(n,e=!1){return{handled:!1,message:n,retry:e}}};function te(n){let e=Promise.reject(n);return e.catch(()=>{}),e}function ka(n){if(n instanceof Error||typeof n=="object"&&n!=null&&"message"in n&&typeof n.message=="string")return n.message}function Aa(n){return typeof n=="object"&&n!==null&&"name"in n&&n.name==="ZodError"&&"issues"in n&&Array.isArray(n.issues)&&"format"in n&&typeof n.format=="function"}function xs(n){if(n instanceof S)return n.toResult();if(Aa(n))return S.invalidParams(n.format()).toResult();let e=ka(n);try{return S.internalError(e?JSON.parse(e):{}).toResult()}catch{return S.internalError({details:e}).toResult()}}function Ia(n){return n instanceof S&&n.code===-32800?n:S.requestCancelled(n)}function Ma(n,e){let t=Na(n,e);return t?t.toResult():xs(n)}function Na(n,e){if(!(!e.aborted||!Oa(n)))return Ia(e.reason)}function Oa(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.name==="AbortError"||e.code==="ABORT_ERR"}var en=class{id;sendResult;signal;finishRequest;didRespond=!1;constructor(e,t,s=new AbortController().signal,a){this.id=e,this.sendResult=t,this.signal=s,this.finishRequest=a}get responded(){return this.didRespond}respond(e){return this.respondWithResult({result:e??null})}respondWithError(e){let t=e instanceof S?e.toErrorResponse():e;return this.respondWithResult({error:t})}respondWithResult(e){return this.didRespond?te(new Error("JSON-RPC request already responded")):(this.didRespond=!0,this.sendResult(e).finally(()=>{this.finishRequest?.()}))}},Da=new WeakMap;var ue=class{disposeHandler;active=!0;constructor(e){this.disposeHandler=e}dispose(){this.active&&(this.active=!1,this.disposeHandler())}[Symbol.dispose](){this.dispose()}runIndefinitely(){return this}},tn=class{connection;constructor(e){this.connection=e}sendRequest(e,t,s,a){return this.connection.sendRequest(e,t,s,a)}sendNotification(e,t){return this.connection.sendNotification(e,t)}sendBatch(e){return this.connection.sendBatch(e)}sendCancelRequest(e){return this.connection.sendCancelRequest(e)}addDynamicHandler(e){return this.connection.addDynamicHandler(e)}get signal(){return this.connection.signal}get closed(){return this.connection.closed}},le=class{pendingResponses=new Map;incomingRequests=new Map;nextRequestId=0;staticHandlers=[];dynamicHandlers=new Set;stream;writeQueue=Promise.resolve();abortController=new AbortController;closedPromise;retryQueue=[];context=new tn(this);receiveReader;allowBatches=!0;constructor(e,t,s,a){if(typeof e=="function"){let p=e,w=t,m=s;this.initialize(m,[...a?.handlers??[],this.legacyHandler(p,w)],a);return}let u=e,f=t,z=s;this.initialize(u,[...z?.handlers??[],...f],z)}static builder(){return new nn}runUntil(e){let t=!1,s=Promise.resolve().then(()=>e(this.context)).finally(()=>{t=!0}),a=this.closed.then(()=>{if(t)return new Promise(()=>{});throw this.closedReason()});return Promise.race([s,a]).finally(()=>{t=!0,this.close()})}addDynamicHandler(e){if(this.dynamicHandlers.add(e),this.retryQueue.length>0)for(let t of this.retryQueue.splice(0))this.processIncomingMessage(t).catch(s=>this.close(s));return new ue(()=>{this.dynamicHandlers.delete(e)})}get signal(){return this.abortController.signal}get closed(){return this.closedPromise}getContext(){return this.context}sendRequest(e,t,s,a={}){if(this.abortController.signal.aborted)return te(this.closedReason());let u=this.prepareRequest(e,t,s,a);return this.sendWireMessage(u.message).catch(()=>{}),a.cancellationSignal?.aborted&&u.cancel(),u.response}sendBatch(e){if(this.abortController.signal.aborted)return te(this.closedReason());if(!this.allowBatches)return te(new TypeError("JSON-RPC batches are not supported on this connection"));if(e.length===0)return te(new TypeError("JSON-RPC batch must contain at least one entry"));let t=[],s=[],a=[];for(let p of e){if(p.kind==="notification"){t.push({jsonrpc:"2.0",method:p.method,params:p.params}),a.push(Promise.resolve(void 0));continue}let w=this.prepareRequest(p.method,p.params,p.mapResponse,p.options);t.push(w.message),a.push(w.response),s.push({signal:p.options?.cancellationSignal,cancel:w.cancel})}let u=t,f=this.sendWireMessage(u);for(let p of s)p.signal?.aborted&&p.cancel();let z=Promise.all([f,...a]).then(([,...p])=>p);return z.catch(()=>{}),z}sendCancelRequest(e){return this.sendNotification(ys,{requestId:e})}sendNotification(e,t){return this.abortController.signal.aborted?te(this.closedReason()):this.sendWireMessage({jsonrpc:"2.0",method:e,params:t})}prepareRequest(e,t,s,a={}){let u=this.nextRequestId++,f=()=>{},z=new Promise((p,w)=>{let m={resolve:y=>{try{p(s?s(y):y)}catch(b){w(b)}},reject:w};f=()=>{m.cancellationSent||(m.cancellationSent=!0,m.cleanup?.(),this.sendCancelRequest(u).catch(()=>{}))},a.cancellationSignal?.addEventListener("abort",f,{once:!0}),m.cleanup=()=>{a.cancellationSignal?.removeEventListener("abort",f)},this.pendingResponses.set(u,m)});return z.catch(()=>{}),{message:{jsonrpc:"2.0",id:u,method:e,params:t},response:z,cancel:()=>f()}}close(e){if(this.abortController.signal.aborted)return;let t=e??new Error("ACP connection closed");this.abortController.abort(t);for(let s of this.pendingResponses.values())s.cleanup?.(),s.reject(t);this.pendingResponses.clear();for(let s of this.incomingRequests.values())s.abort(t);this.incomingRequests.clear(),this.receiveReader?.cancel(t).catch(()=>{})}initialize(e,t,s){this.stream=e,this.staticHandlers=t,this.allowBatches=s?.allowBatches??!0,this.closedPromise=new Promise(a=>{this.abortController.signal.addEventListener("abort",()=>a())}),this.receive()}legacyHandler(e,t){return{handleMessage:async(s,a)=>{if(s.kind==="request"){let u=await e(s.method,s.params,a);await s.responder.respond(u)}else await t(s.method,s.params,a);return q.yes()}}}async receive(){let e;try{let t=this.stream.readable.getReader();this.receiveReader=t;try{for(;!this.abortController.signal.aborted;){let{value:s,done:a}=await t.read();if(this.abortController.signal.aborted||a)break;this.receiveWireMessage(s)}}finally{this.receiveReader===t&&(this.receiveReader=void 0),t.releaseLock()}}catch(t){e=t}finally{this.close(e)}}receiveWireMessage(e){if(Array.isArray(e)){if(!this.allowBatches){this.close(new TypeError("JSON-RPC batches are not supported on this connection"));return}this.receiveBatch(e);return}if(!G(e)&&!j(e)&&!de(e)){this.sendWireMessage(B(S.invalidRequest(e))).catch(()=>{});return}this.receiveMessage(e)}receiveBatch(e){if(e.length===0){this.sendWireMessage(B(S.invalidRequest(e))).catch(()=>{});return}let t=rn(e),a=t?0:e.reduce((m,y)=>m+(j(y)?0:1),0),u=e.reduce((m,y)=>m+(j(y)?1:0),0),f=!1,z=[],p=async()=>{f||a!==0||u!==0||z.length===0||(f=!0,await this.sendWireMessage(z))},w=async m=>{z.push(m),a-=1,await p()};for(let m of e){if(t){de(m)&&this.receiveMessage(m);continue}if(!G(m)&&!j(m)){w(B(S.invalidRequest(m))).catch(()=>{});continue}let y=this.receiveMessage(m,G(m)?w:void 0,e.length);j(m)&&y.finally(()=>{u-=1,p().catch(b=>this.close(b))})}}receiveMessage(e,t,s){return this.abortController.signal.aborted?Promise.resolve():M(e)?"method"in e?("id"in e||this.handleProtocolNotification(e),this.processIncomingMessage(this.toIncomingMessage(e,t,s)).catch(a=>this.close(a))):("id"in e?this.handleResponse(e):console.error("Invalid message",{message:e}),Promise.resolve()):(console.error("Invalid message",{message:e}),Promise.resolve())}async processIncomingMessage(e){if(this.abortController.signal.aborted)return;let t=e,s=!1;try{for(let a of[...this.staticHandlers,...this.dynamicHandlers.values()]){if(this.abortController.signal.aborted)return;let u=await a.handleMessage(t,this.context)??{handled:!0};if(u.handled)return;t=u.message??t,s=s||!!u.retry}s?this.retryQueue.push(t):t.kind==="request"&&await t.responder.respondWithError(S.methodNotFound(t.method))}catch(a){if(this.abortController.signal.aborted)return;if(t.kind==="request"&&!t.responder.responded)await t.responder.respondWithResult(Ma(a,t.responder.signal));else{let u=xs(a);"error"in u&&console.error("Error handling notification",e.raw,u.error)}}}toIncomingMessage(e,t,s){if("id"in e){let a=new AbortController;this.incomingRequests.set(e.id,a);let u=()=>{this.incomingRequests.get(e.id)===a&&this.incomingRequests.delete(e.id)},f=new en(e.id,z=>{let p={jsonrpc:"2.0",id:e.id,...z};return t?t(p):this.sendWireMessage(p)},a.signal,u);return s!==void 0&&Da.set(f,s),{kind:"request",method:e.method,params:e.params,raw:e,signal:a.signal,responder:f}}return{kind:"notification",method:e.method,params:e.params,raw:e}}handleResponse(e){let t=this.pendingResponses.get(e.id);if(t)if(this.pendingResponses.delete(e.id),t.cleanup?.(),!Y(e))t.reject(S.invalidRequest(e));else if("result"in e)t.resolve(e.result);else{let{code:s,message:a,data:u}=e.error;t.reject(new S(s,a,u))}else console.error("Got response to unknown request",e.id)}handleProtocolNotification(e){if(e.method!==ys)return;let t=Ca(e.params);if(t===void 0)return;let s=this.incomingRequests.get(t);!s||s.signal.aborted||s.abort(S.requestCancelled({requestId:t}))}closedReason(){return this.abortController.signal.reason??new Error("ACP connection closed")}async sendWireMessage(e){return this.abortController.signal.aborted?te(this.closedReason()):(this.writeQueue=this.writeQueue.then(async()=>{if(this.abortController.signal.aborted)throw this.closedReason();let t=this.stream.writable.getWriter();try{await t.write(e)}finally{t.releaseLock()}}).catch(t=>{throw this.close(t),t}),this.writeQueue)}},nn=class{handlers=[];connectionName;name(e){return this.connectionName=e,this}withHandler(e){return this.handlers.push(e),this}onReceiveMessage(e){return this.withHandler({handleMessage:async(t,s)=>await e(t,s)??q.no(t),describe:()=>this.connectionName??"onReceiveMessage"})}onReceiveRequest(e,t,s){return this.withHandler({handleMessage:async(a,u)=>{if(a.kind!=="request"||a.method!==e)return q.no(a);let f=t(a.params);return await s(f,a.responder,u)??q.yes()},describe:()=>`${this.connectionName??"request"}:${e}`})}onReceiveNotification(e,t,s){return this.withHandler({handleMessage:async(a,u)=>{if(a.kind!=="notification"||a.method!==e)return q.no(a);let f=t(a.params);return await s(f,u)??q.yes()},describe:()=>`${this.connectionName??"notification"}:${e}`})}connect(e,t){return new le(e,this.handlers,t)}connectWith(e,t,s){return this.connect(e,s).runUntil(t)}},S=class n extends Error{code;data;constructor(e,t,s){super(t),this.code=e,this.name="RequestError",this.data=s}static parseError(e,t){return new n(-32700,`Parse error${t?`: ${t}`:""}`,e)}static invalidRequest(e,t){return new n(-32600,`Invalid request${t?`: ${t}`:""}`,e)}static methodNotFound(e){return new n(-32601,`"Method not found": ${e}`,{method:e})}static invalidParams(e,t){return new n(-32602,`Invalid params${t?`: ${t}`:""}`,e)}static internalError(e,t){return new n(-32603,`Internal error${t?`: ${t}`:""}`,e)}static requestCancelled(e,t){return new n(-32800,`Request cancelled${t?`: ${t}`:""}`,e)}static authRequired(e,t){return new n(-32e3,`Authentication required${t?`: ${t}`:""}`,e)}static resourceNotFound(e){return new n(-32002,`Resource not found${e?`: ${e}`:""}`,e&&{uri:e})}toResult(){return{error:{code:this.code,message:this.message,data:this.data}}}toErrorResponse(){return{code:this.code,message:this.message,data:this.data}}};function B(n){return{jsonrpc:"2.0",id:null,error:n.toErrorResponse()}}var ne=class extends Error{maxMessageBytes;constructor(e){super(`Incoming ACP data exceeds the configured ${e} byte limit`),this.maxMessageBytes=e,this.name="MessageTooLargeError"}};function we(n){let e=n??33554432;if(!Number.isSafeInteger(e)||e<=0)throw new RangeError("maxMessageBytes must be a positive safe integer");return e}var _e=class{#e=new Uint8Array(0);#t=0;#n;constructor(e){this.#n=we(e)}get byteLength(){return this.#t}get lastByte(){return this.#e[this.#t-1]}#s(e){if(e>this.#n-this.#t)throw this.clear(),new ne(this.#n)}append(e){this.#s(e.byteLength);let t=this.#t+e.byteLength;if(t>this.#e.byteLength){let s=Math.min(this.#n,Math.max(t,this.#e.byteLength*2,1024)),a=new Uint8Array(s);a.set(this.#e.subarray(0,this.#t)),this.#e=a}this.#e.set(e,this.#t),this.#t=t}take(){let e=this.#e.subarray(0,this.#t);return this.clear(),e}clear(){this.#e=new Uint8Array(0),this.#t=0}};var Rs=10,Se=class{#e;#t;constructor(e){this.#t=we(e),this.#e=new _e(Math.min(Number.MAX_SAFE_INTEGER,this.#t+1))}*push(e){let t=0,s=e.indexOf(Rs,t);for(;s!==-1;)yield this.#n(e.subarray(t,s)),t=s+1,s=e.indexOf(Rs,t);if(t<e.byteLength){let a=e.subarray(t);this.#s(a),this.#e.append(a)}}flush(){if(this.#e.byteLength!==0)return an(this.#e.take())}clear(){this.#e.clear()}#n(e){return this.#s(e),this.#e.byteLength===0?an(e):(this.#e.append(e),an(this.#e.take()))}#s(e){let t=e.byteLength>0?e[e.byteLength-1]:this.#e.lastByte;if(this.#e.byteLength+e.byteLength-(t===13?1:0)>this.#t)throw this.clear(),new ne(this.#t)}};function an(n){return n[n.byteLength-1]===13?n.subarray(0,-1):n}function Ts(n,e,t={}){let s=we(t.maxMessageBytes),a=new TextEncoder,u=new TextDecoder,f=!1,z,p=Promise.resolve(),w=b=>{let R=JSON.stringify(b)+`
5
+ `,O=p.then(async()=>{let H=n.getWriter();try{await H.write(a.encode(R))}finally{H.releaseLock()}});return p=O.catch(()=>{}),O},m=new ReadableStream({async start(b){let R=new Se(s),O=async L=>{let Q=u.decode(L).trim();if(!Q)return;let Z;try{Z=JSON.parse(Q)}catch{await w(B(S.parseError()));return}M(Z)||Array.isArray(Z)?b.enqueue(Z):await w(B(S.invalidRequest(Z)))},H=e.getReader();z=H;try{for(;;){let{value:Q,done:Z}=await H.read();if(f)return;if(Z)break;if(Q){for(let _i of R.push(Q))if(await O(_i),f)return}}if(f)return;let L=R.flush();L&&await O(L)}catch(L){if(f)return;b.error(L),H.cancel(L).catch(()=>{});return}finally{R.clear(),z===H&&(z=void 0),H.releaseLock()}f||b.close()},cancel(b){return f=!0,z?.cancel(b)}}),y=new WritableStream({write(b){return w(b)}});return{readable:m,writable:y}}var id=bt.and(r({mode:l("form")})).and(r({message:i()})),od=_t.and(r({mode:l("url")})).and(r({message:i()})),rd=g([ge,be]).and(r({message:i()})),ad=ht.and(r({type:l("string")})),cd=ft.and(r({type:l("number")})),dd=pt.and(r({type:l("integer")})),ud=zt.and(r({type:l("boolean")})),ld=gt.and(r({type:l("array")})),hd=mt.and(r({type:l("string")}));var fd=Wt.and(r({action:l("accept")})),pd=r({action:l("decline")}),zd=r({action:l("cancel")});function As(n,e,t){return Ts(n,e,t)}function N(n){return n??{}}function Is(n){return typeof n=="object"&&n!==null&&"readable"in n&&"writable"in n}function Ms(){let n=new TransformStream,e=new TransformStream;return[{readable:e.readable,writable:n.writable},{readable:n.readable,writable:e.writable}]}var P={agent:{initialize:h.initialize,authenticate:h.authenticate,logout:h.logout,providers:{list:h.providers_list,set:h.providers_set,disable:h.providers_disable},session:{new:h.session_new,load:h.session_load,list:h.session_list,delete:h.session_delete,fork:h.session_fork,resume:h.session_resume,close:h.session_close,setMode:h.session_set_mode,setConfigOption:h.session_set_config_option,prompt:h.session_prompt,cancel:h.session_cancel},nes:{start:h.nes_start,suggest:h.nes_suggest,accept:h.nes_accept,reject:h.nes_reject,close:h.nes_close},document:{didOpen:h.document_did_open,didChange:h.document_did_change,didClose:h.document_did_close,didSave:h.document_did_save,didFocus:h.document_did_focus}},client:{session:{requestPermission:_.session_request_permission,update:_.session_update},fs:{writeTextFile:_.fs_write_text_file,readTextFile:_.fs_read_text_file},terminal:{create:_.terminal_create,output:_.terminal_output,release:_.terminal_release,waitForExit:_.terminal_wait_for_exit,kill:_.terminal_kill},elicitation:{create:_.elicitation_create,complete:_.elicitation_complete}},protocol:{cancelRequest:et.cancel_request}},Ns=Symbol("startActiveSession"),qe=class{cx;currentRequestId;constructor(e,t){this.cx=e,this.currentRequestId=t}get requestId(){return this.currentRequestId}get connectionContext(){return this.cx}sendRequest(e,t,s,a){return this.cx.sendRequest(e,t,s,a)}sendNotification(e,t){return this.cx.sendNotification(e,t)}addDynamicHandler(e){return this.cx.addDynamicHandler(e)}},Ee=class n extends qe{constructor(e,t){super(e,t)}static create(e,t){return new n(e,t)}request(e,t,s){let a=zn[e];return this.sendRequest(e,t,a?.mapResponse,s)}notify(e,t){return this.sendNotification(e,t)}},ye=class n extends qe{constructor(e,t){super(e,t)}static create(e,t){return new n(e,t)}[Ns](e,t){return this.sendRequest(h.session_new,e,s=>this.attachSession(s),t)}buildSession(e){return typeof e=="string"?He.create(this,{cwd:e,mcpServers:[]}):He.create(this,e)}attachSession(e){let t=new un,s=this.connectionContext.signal,a=()=>{t.fail(s.reason??new Error("ACP connection closed"))};s.aborted?a():s.addEventListener("abort",a);let u=Ls(this.connectionContext).attach(e,t),f=new ue(()=>{s.removeEventListener("abort",a)});return ln.create(this,e,t,[u,f])}request(e,t,s){let a=Hs[e];return this.sendRequest(e,t,a?.mapResponse,s)}notify(e,t){return this.sendNotification(e,t)}},Pe=class{connection;constructor(e){this.connection=e}get signal(){return this.connection.signal}get closed(){return this.connection.closed}close(e){this.connection.close(e)}},cn=class extends Pe{connectHandlers;client;didStartConnectHandlers=!1;constructor(e,t=[]){super(e),this.connectHandlers=t,this.client=Ee.create(e.getContext())}startConnectHandlers(){this.didStartConnectHandlers||(this.didStartConnectHandlers=!0,Fe(this,this.connectHandlers))}},dn=class extends Pe{connectHandlers;agent;didStartConnectHandlers=!1;constructor(e,t=[]){super(e),this.connectHandlers=t,this.agent=ye.create(e.getContext())}startConnectHandlers(){this.didStartConnectHandlers||(this.didStartConnectHandlers=!0,Fe(this,this.connectHandlers))}};function Os(n,e=[]){return new cn(n,e)}function Ds(n,e=[]){return new dn(n,e)}var un=class{values=[];waiters=[];failed=!1;failure;enqueue(e){if(this.failed)return;let t=this.waiters.shift();t?t.resolve(e):this.values.push({kind:"value",value:e})}reject(e){if(!this.failed){if(this.waiters.length>0){for(let t of this.waiters.splice(0))t.reject(e);return}this.values.push({kind:"error",error:e})}}clearErrors(){this.values=this.values.filter(e=>e.kind==="value")}fail(e){if(!this.failed){this.failed=!0,this.failure=e;for(let t of this.waiters.splice(0))t.reject(e)}}next(){if(this.values.length>0){let e=this.values.shift();return e.kind==="error"?Promise.reject(e.error):Promise.resolve(e.value)}return this.failed?Promise.reject(this.failure):new Promise((e,t)=>{this.waiters.push({resolve:e,reject:t})})}};function Cs(n){return{...n,additionalDirectories:n.additionalDirectories?[...n.additionalDirectories]:void 0,mcpServers:[...n.mcpServers]}}var He=class n{cx;request;constructor(e,t){this.cx=e,this.request=Cs(t)}static create(e,t){return new n(e,t)}toRequest(){return Cs(this.request)}withAdditionalDirectories(e){return this.request={...this.request,additionalDirectories:[...e]},this}withMcpServer(e){return this.request={...this.request,mcpServers:[...this.request.mcpServers,e]},this}async start(e){return this.cx[Ns](this.toRequest(),e)}async withSession(e){let t=await this.start();try{return await e(t)}finally{t.dispose()}}},ln=class n{cx;sessionResponse;updates;registrations;constructor(e,t,s,a){this.cx=e,this.sessionResponse=t,this.updates=s,this.registrations=a}static create(e,t,s,a){return new n(e,t,s,a)}get sessionId(){return this.sessionResponse.sessionId}get modes(){return this.sessionResponse.modes}get meta(){return this.sessionResponse._meta}get newSessionResponse(){return this.sessionResponse}prompt(e,t){this.updates.clearErrors();let s=this.cx.request(h.session_prompt,{sessionId:this.sessionId,prompt:this.promptBlocks(e)},t);return s.then(a=>{this.updates.enqueue({kind:"stop",response:a,stopReason:a.stopReason})},a=>{this.updates.reject(a)}),s}nextUpdate(){return this.updates.next()}async readText(){let e="";for(;;){let t=await this.nextUpdate();if(t.kind==="stop")return e;let{update:s}=t;s.sessionUpdate==="agent_message_chunk"&&s.content.type==="text"&&(e+=s.content.text)}}dispose(){for(let e of this.registrations.splice(0))e.dispose();this.updates.fail(new Error("Active session disposed"))}[Symbol.dispose](){this.dispose()}promptBlocks(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e:[e]}};function js(n,e){return n?typeof n=="function"?n(e):n.parse(e):e}function C(n,e,t){return{method:n,params:e,mapResponse:t}}function W(n,e){return{method:n,params:e}}function qs(n,e,t,s){n.onReceiveRequest(e.method,a=>js(e.params,a),async(a,u,f)=>{let z=await s(t(a,f,u.signal,u.id));await u.respond(e.mapResponse?e.mapResponse(z):z)})}function Ps(n,e,t,s){n.onReceiveNotification(e.method,a=>js(e.params,a),(a,u)=>s(t(a,u,u.signal)))}function Ge(n){let e={};for(let t of Object.values(n))e[t.method]=t;return e}var qa={initialize:C(h.initialize,Tt),newSession:C(h.session_new,Mt),loadSession:C(h.session_load,Nt,N),unstable_forkSession:C(h.session_fork,jt),listSessions:C(h.session_list,Ot),deleteSession:C(h.session_delete,Dt,N),resumeSession:C(h.session_resume,qt),closeSession:C(h.session_close,Pt,N),setSessionMode:C(h.session_set_mode,Ht,N),setSessionConfigOption:C(h.session_set_config_option,Lt),authenticate:C(h.authenticate,Ct,N),unstable_listProviders:C(h.providers_list,vt),unstable_setProvider:C(h.providers_set,kt,N),unstable_disableProvider:C(h.providers_disable,At,N),logout:C(h.logout,It,N),prompt:C(h.session_prompt,Gt),unstable_startNes:C(h.nes_start,Ft),unstable_suggestNes:C(h.nes_suggest,Ut),unstable_closeNes:C(h.nes_close,Bt,N)},Pa={cancel:W(h.session_cancel,$t),unstable_didOpenDocument:W(h.document_did_open,Jt),unstable_didChangeDocument:W(h.document_did_change,Vt),unstable_didCloseDocument:W(h.document_did_close,Kt),unstable_didSaveDocument:W(h.document_did_save,Yt),unstable_didFocusDocument:W(h.document_did_focus,Xt),unstable_acceptNes:W(h.nes_accept,Qt),unstable_rejectNes:W(h.nes_reject,Zt)},Ha={requestPermission:C(_.session_request_permission,rt),writeTextFile:C(_.fs_write_text_file,st,N),readTextFile:C(_.fs_read_text_file,it),createTerminal:C(_.terminal_create,at),terminalOutput:C(_.terminal_output,ct),releaseTerminal:C(_.terminal_release,dt,N),waitForTerminalExit:C(_.terminal_wait_for_exit,ut),killTerminal:C(_.terminal_kill,lt,N),createElicitation:C(_.elicitation_create,wt)},La={sessionUpdate:W(_.session_update,Ne),completeElicitation:W(_.elicitation_complete,Rt)},Hs=Ge(qa),Ga=Ge(Pa),zn=Ge(Ha),Fa=Ge(La);function Ua(n,e,t,s){return{params:n,requestId:s,signal:t,client:e}}function Ba(n,e,t){return{params:n,signal:t,client:e}}function Wa(n,e,t,s){return{params:n,requestId:s,signal:t,agent:e}}function $a(n,e,t){return{params:n,signal:t,agent:e}}var hn=class{activeSessions=new Map;handleMessage(e){if(e.kind!=="notification"||e.method!==_.session_update)return q.no(e);let t=Ne.parse(e.params),s={kind:"session_update",notification:t,update:t.update},a=this.activeSessions.get(t.sessionId);if(a&&a.size>0)for(let u of a)u.enqueue(s);return q.no(e)}attach(e,t){let s=this.activeSessions.get(e.sessionId)??new Set;return s.add(t),this.activeSessions.set(e.sessionId,s),new ue(()=>{s.delete(t),s.size===0&&this.activeSessions.delete(e.sessionId)})}},vs=new WeakMap;function Ls(n){let e=vs.get(n);return e||(e=new hn,vs.set(n,e)),e}function Fe(n,e){for(let t of e){let s;try{s=t(n)}catch(a){throw n.close(a),a}Promise.resolve(s).catch(a=>{n.close(a)})}}var se=Symbol("appBuilder"),De=Symbol("runAgentConnectHandlers"),je=Symbol("runClientConnectHandlers"),xe={allowBatches:!1};function mn(n){return new fn(n)}var fn=class{builder=le.builder();connectHandlers=[];constructor(e={}){e.name&&this.builder.name(e.name)}[se](){return this.builder}[De](e){Fe(e,this.connectHandlers)}connect(e,t={}){return this.connectConnection(e,t).connection}connectWith(e,t){let{rawConnection:s,connection:a}=this.connectConnection(e);return s.runUntil(()=>t(a.client))}onConnect(e){return this.connectHandlers.push(e),this}onRequest(e,t,s){if(s)return this.request({method:e,params:t},s);let a=Hs[e];if(!a)throw new Error(`Unknown ACP request method '${e}'. Pass a params parser for custom methods.`);return this.request(a,t)}onNotification(e,t,s){if(s)return this.notification({method:e,params:t},s);let a=Ga[e];if(!a)throw new Error(`Unknown ACP notification method '${e}'. Pass a params parser for custom methods.`);return this.notification(a,t)}request(e,t){return qs(this.builder,e,(s,a,u,f)=>Ua(s,Ee.create(a,f),u,f),t),this}notification(e,t){return Ps(this.builder,e,(s,a,u)=>Ba(s,Ee.create(a),u),t),this}connectConnection(e,t={}){if(Is(e)){let p=this.openStreamConnection(e);return t.deferConnectHandlers||this[De](p.connection),p}let[s,a]=Ms(),u=e[se]().connect(a,xe),f=Ds(u),z=this.openStreamConnection(s);z.rawConnection.closed.then(()=>f.close()),u.closed.then(()=>z.connection.close());try{e[je](f),this[De](z.connection)}catch(p){throw f.close(p),z.connection.close(p),p}return z}openStreamConnection(e){let t=this.builder.connect(e,xe);return{rawConnection:t,connection:Os(t,this.connectHandlers)}}};var ks=class{builder=le.builder();connectHandlers=[];constructor(e={}){e.name&&this.builder.name(e.name),this.builder.withHandler({handleMessage:(t,s)=>Ls(s).handleMessage(t),describe:()=>"client-session-update-router"})}[se](){return this.builder}[je](e){Fe(e,this.connectHandlers)}connect(e){return this.connectConnection(e).connection}connectWith(e,t){let{rawConnection:s,connection:a}=this.connectConnection(e);return s.runUntil(()=>t(a.agent))}onConnect(e){return this.connectHandlers.push(e),this}onRequest(e,t,s){if(s)return this.request({method:e,params:t},s);let a=zn[e];if(!a)throw new Error(`Unknown ACP request method '${e}'. Pass a params parser for custom methods.`);return this.request(a,t)}onNotification(e,t,s){if(s)return this.notification({method:e,params:t},s);let a=Fa[e];if(!a)throw new Error(`Unknown ACP notification method '${e}'. Pass a params parser for custom methods.`);return this.notification(a,t)}request(e,t){return qs(this.builder,e,(s,a,u,f)=>Wa(s,ye.create(a,f),u,f),t),this}notification(e,t){return Ps(this.builder,e,(s,a,u)=>$a(s,ye.create(a),u),t),this}connectConnection(e){if(Is(e)){let z=this.openStreamConnection(e);return this[je](z.connection),z}let[t,s]=Ms(),a=e[se]().connect(s,xe),u=Os(a),f=this.openStreamConnection(t);f.rawConnection.closed.then(()=>u.close()),a.closed.then(()=>f.connection.close());try{e[De](u),this[je](f.connection)}catch(z){throw u.close(z),f.connection.close(z),z}return f}openStreamConnection(e){let t=this.builder.connect(e,xe);return{rawConnection:t,connection:Ds(t,this.connectHandlers)}}},Ja=new Set([h.initialize,h.authenticate,h.providers_list,h.providers_set,h.providers_disable,h.session_new,h.session_load,h.session_set_mode,h.session_set_config_option,h.session_prompt,h.session_list,h.session_delete,h.session_fork,h.session_resume,h.session_close,h.logout,h.nes_start,h.nes_suggest,h.nes_close]),Va=new Set([h.session_cancel,h.nes_accept,h.nes_reject,h.document_did_open,h.document_did_change,h.document_did_close,h.document_did_save,h.document_did_focus]),yd=new Set([_.session_request_permission,_.fs_write_text_file,_.fs_read_text_file,_.terminal_create,_.terminal_output,_.terminal_release,_.terminal_wait_for_exit,_.terminal_kill,_.elicitation_create]),xd=new Set([_.session_update,_.elicitation_complete]);function Ka(n){let e=mn().onRequest(h.initialize,t=>n.initialize(t.params)).onRequest(h.session_new,t=>n.newSession(t.params)).onRequest(h.authenticate,async t=>await n.authenticate(t.params)??{}).onRequest(h.session_prompt,t=>n.prompt(t.params)).onNotification(h.session_cancel,t=>n.cancel(t.params));return n.loadSession&&e.onRequest(h.session_load,t=>n.loadSession(t.params)),n.listSessions&&e.onRequest(h.session_list,t=>n.listSessions(t.params)),n.deleteSession&&e.onRequest(h.session_delete,async t=>await n.deleteSession(t.params)??{}),n.unstable_forkSession&&e.onRequest(h.session_fork,t=>n.unstable_forkSession(t.params)),n.resumeSession&&e.onRequest(h.session_resume,t=>n.resumeSession(t.params)),n.closeSession&&e.onRequest(h.session_close,async t=>await n.closeSession(t.params)??{}),n.setSessionMode&&e.onRequest(h.session_set_mode,async t=>await n.setSessionMode(t.params)??{}),n.setSessionConfigOption&&e.onRequest(h.session_set_config_option,t=>n.setSessionConfigOption(t.params)),n.unstable_listProviders&&e.onRequest(h.providers_list,t=>n.unstable_listProviders(t.params)),n.unstable_setProvider&&e.onRequest(h.providers_set,async t=>await n.unstable_setProvider(t.params)??{}),n.unstable_disableProvider&&e.onRequest(h.providers_disable,async t=>await n.unstable_disableProvider(t.params)??{}),n.logout&&e.onRequest(h.logout,async t=>await n.logout(t.params)??{}),n.unstable_startNes&&e.onRequest(h.nes_start,t=>n.unstable_startNes(t.params)),n.unstable_suggestNes&&e.onRequest(h.nes_suggest,t=>n.unstable_suggestNes(t.params)),n.unstable_closeNes&&e.onRequest(h.nes_close,async t=>await n.unstable_closeNes(t.params)??{}),n.unstable_didOpenDocument&&e.onNotification(h.document_did_open,t=>n.unstable_didOpenDocument(t.params)),n.unstable_didChangeDocument&&e.onNotification(h.document_did_change,t=>n.unstable_didChangeDocument(t.params)),n.unstable_didCloseDocument&&e.onNotification(h.document_did_close,t=>n.unstable_didCloseDocument(t.params)),n.unstable_didSaveDocument&&e.onNotification(h.document_did_save,t=>n.unstable_didSaveDocument(t.params)),n.unstable_didFocusDocument&&e.onNotification(h.document_did_focus,t=>n.unstable_didFocusDocument(t.params)),n.unstable_acceptNes&&e.onNotification(h.nes_accept,t=>n.unstable_acceptNes(t.params)),n.unstable_rejectNes&&e.onNotification(h.nes_reject,t=>n.unstable_rejectNes(t.params)),n.extMethod&&e[se]().withHandler({handleMessage:async t=>t.kind!=="request"||Ja.has(t.method)?q.no(t):(await t.responder.respond(await n.extMethod(t.method,t.params)),q.yes()),describe:()=>"legacy-agent-extension-request"}),n.extNotification&&e[se]().withHandler({handleMessage:async t=>t.kind!=="notification"||Va.has(t.method)?q.no(t):(await n.extNotification(t.method,t.params),q.yes()),describe:()=>"legacy-agent-extension-notification"}),e}var Le=class{connection;constructor(e,t){this.connection=Ka(e(this))[se]().connect(t,xe)}sessionUpdate(e){return this.connection.sendNotification(_.session_update,e)}requestPermission(e){return this.connection.sendRequest(_.session_request_permission,e)}readTextFile(e){return this.connection.sendRequest(_.fs_read_text_file,e)}writeTextFile(e){return this.connection.sendRequest(_.fs_write_text_file,e,N)}createTerminal(e){return this.connection.sendRequest(_.terminal_create,e,t=>pn.create(t.terminalId,e.sessionId,this.connection))}createElicitation(e){return this.connection.sendRequest(_.elicitation_create,e)}completeElicitation(e){return this.connection.sendNotification(_.elicitation_complete,e)}request(e,t,s){let a=zn[e];return this.connection.sendRequest(e,t,a?.mapResponse,s)}notify(e,t){return this.connection.sendNotification(e,t)}extMethod(e,t){return this.request(e,t)}extNotification(e,t){return this.notify(e,t)}get signal(){return this.connection.signal}get closed(){return this.connection.closed}},pn=class n{id;sessionId;connection;constructor(e,t,s){this.id=e,this.sessionId=t,this.connection=s}static create(e,t,s){return new n(e,t,s)}currentOutput(){return this.connection.sendRequest(_.terminal_output,{sessionId:this.sessionId,terminalId:this.id})}waitForExit(){return this.connection.sendRequest(_.terminal_wait_for_exit,{sessionId:this.sessionId,terminalId:this.id})}kill(){return this.connection.sendRequest(_.terminal_kill,{sessionId:this.sessionId,terminalId:this.id},N)}release(){return this.connection.sendRequest(_.terminal_release,{sessionId:this.sessionId,terminalId:this.id},N)}async[Symbol.asyncDispose](){await this.release()}};var $s={};ve($s,{YukinoAcpAgent:()=>We,createYukinoAcpApp:()=>Re});import{existsSync as Za}from"fs";import{isAbsolute as ec}from"path";var Us={};ve(Us,{addUsage:()=>_n,agentEventToUpdate:()=>bn,emptyUsage:()=>wn,historyNotifications:()=>En,promptToText:()=>gn,stopReason:()=>Sn,toolKind:()=>Ue,toolLocations:()=>Be});import{isAbsolute as Xa,resolve as Qa}from"path";function gn(n){let e=[];for(let s of n)switch(s.type){case"text":s.text.trim()&&e.push(s.text);break;case"resource_link":e.push(`Resource: ${s.name} (${s.uri})`);break;case"resource":if("text"in s.resource){e.push(`Resource: ${s.resource.uri}
6
+ ${s.resource.text}`);break}throw S.invalidParams(void 0,"Binary resources are not supported.");case"image":throw S.invalidParams(void 0,"Image prompts are not supported.");case"audio":throw S.invalidParams(void 0,"Audio prompts are not supported.")}let t=e.join(`
7
+
8
+ `).trim();if(!t)throw S.invalidParams(void 0,"Prompt must contain text or a resource link.");return t}function Ue(n){return/^(ReadFile)$/u.test(n)?"read":/^(WriteFile|EditFile)$/u.test(n)?"edit":/^(Glob|Grep|ToolSearch)$/u.test(n)?"search":/^(Bash|PowerShell|ComputerUse)$/u.test(n)?"execute":/^(Agent|TaskCreate|TaskGet|TaskList|TaskUpdate|TaskStop)$/u.test(n)?"think":n==="ExitPlanMode"?"switch_mode":"other"}function Be(n,e){let t=Ze(n,"file_path")||Ze(n,"path");if(t)return[{path:Xa(t)?t:Qa(e,t)}]}function Gs(n,e,t,s){return{sessionUpdate:"tool_call",toolCallId:e,title:n,kind:Ue(n),status:"pending",rawInput:t,locations:Be(t,s)}}function Fs(n,e,t,s){return{sessionUpdate:"tool_call_update",toolCallId:n,status:t?"failed":"completed",content:e?[{type:"content",content:{type:"text",text:e}}]:void 0,rawOutput:{output:e,isError:t,...s===void 0?{}:{elapsed:s}}}}function bn(n,e,t){switch(n.type){case"stream_text":return{sessionUpdate:"agent_message_chunk",content:{type:"text",text:n.text}};case"thinking_text":return{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:n.text}};case"tool_use":return Gs(n.toolName,n.toolId,n.args,e);case"tool_result":return Fs(n.toolId,n.output,n.isError,n.elapsed);case"usage":return{sessionUpdate:"usage_update",used:n.usage.inputTokens+n.usage.cacheReadInputTokens+n.usage.cacheCreationInputTokens,size:t};default:return null}}function _n(n,e){let t=n.inputTokens+e.usage.inputTokens,s=n.outputTokens+e.usage.outputTokens,a=(n.cachedReadTokens??0)+e.usage.cacheReadInputTokens,u=(n.cachedWriteTokens??0)+e.usage.cacheCreationInputTokens;return{inputTokens:t,outputTokens:s,cachedReadTokens:a,cachedWriteTokens:u,totalTokens:t+s+a+u}}function wn(){return{totalTokens:0,inputTokens:0,outputTokens:0,cachedReadTokens:0,cachedWriteTokens:0}}function Sn(n){switch(n){case"max_tokens":return"max_tokens";case"max_turn_requests":return"max_turn_requests";case"refusal":return"refusal";case"cancelled":case"interrupted":return"cancelled";default:return"end_turn"}}function*En(n,e,t){for(let s of e){if(s.type===Hn||s.role!=="user"&&s.role!=="assistant")continue;let a=Qe(s.content);a&&(yield{sessionId:n,update:{sessionUpdate:s.role==="assistant"?"agent_message_chunk":"user_message_chunk",content:{type:"text",text:a}}});for(let u of s.tool_uses??[])yield{sessionId:n,update:Gs(u.tool_name,u.tool_use_id,u.arguments??{},t)};for(let u of s.tool_results??[]){let f=Qe(u.content);yield{sessionId:n,update:Fs(u.tool_use_id,f,u.is_error??!1)}}}}var tc=/^[a-z0-9]+-[a-f0-9]{8}$/u;async function nc(n,e){let t=jn(qn(),n),s=t.providers[0];if(!s)throw S.internalError(void 0,"No provider configured.");let a=await Jn({provider:s,workDir:n,hooks:t.hooks,mcpServers:t.mcp_servers,enableCoordinatorMode:t.enable_coordinator_mode??!1,forkDisabled:!On(t),memoryEnabled:Dn(t),sessionId:e});return{sessionId:a.sessionId,workDir:a.workDir,contextWindow:a.contextWindow,conv:a.conv,run:a.run.bind(a),abort:()=>{a.abort()},dispose:async()=>{a.abort(),await Promise.all([a.backgroundTaskManager.stopAll(),a.teamManager.stopAll(),a.mcpManager?.disconnectAll()??Promise.resolve()])}}}function Ws(n){if(!ec(n))throw S.invalidParams(void 0,"Session cwd must be absolute.")}function yn(n){if(!tc.test(n))throw S.invalidParams(void 0,"Invalid session ID.")}function Bs(n){if(Ws(n.cwd),(n.mcpServers?.length??0)>0)throw S.invalidParams(void 0,"Client-provided MCP servers are not supported.");if((n.additionalDirectories?.length??0)>0)throw S.invalidParams(void 0,"Additional workspace directories are not supported.")}var We=class{constructor(e=nc){this.runtimeFactory=e}runtimeFactory;sessions=new Map;initialize(e){return{protocolVersion:tt,authMethods:[],agentInfo:{name:"yukino",title:"Yukino",version:Pn},agentCapabilities:{loadSession:!0,promptCapabilities:{embeddedContext:!0},sessionCapabilities:{list:{},resume:{},close:{}}}}}authenticate(){return{}}addSession(e){let t={runtime:e,generation:0,tail:Promise.resolve(),turnAbort:null,closed:!1,usage:wn()};return this.sessions.set(e.sessionId,t),t}async newSession(e){Bs(e);let t=await this.runtimeFactory(e.cwd);return this.addSession(t),{sessionId:t.sessionId}}async loadSession(e,t,s){Bs(e),yn(e.sessionId);let a=this.sessions.get(e.sessionId);if(a&&a.runtime.workDir!==e.cwd)throw S.invalidParams(void 0,"Session cwd does not match.");if(a&&!s)return{};let u=Un(e.cwd,e.sessionId);if(!a&&!Za(Ln(e.cwd,e.sessionId)))throw S.resourceNotFound(e.sessionId);if(!a){let f=await this.runtimeFactory(e.cwd,e.sessionId);f.conv.reset(),f.conv.appendMessages(Bn(u)),a=this.addSession(f)}if(s)for(let f of En(e.sessionId,u,e.cwd))await t.notify(P.client.session.update,f);return{}}listSessions(e){if(e.cursor)throw S.invalidParams(void 0,"Session pagination is not supported.");let t=e.cwd??process.cwd();return Ws(t),{sessions:Wn(t).map(s=>({sessionId:s.id,cwd:t,title:s.firstMessage||void 0,updatedAt:s.modTime.toISOString()}))}}prompt(e,t){let s=this.requireSession(e.sessionId),a=gn(e.prompt),u=s.generation,f=s.tail.catch(()=>{}).then(async()=>{if(s.closed||u!==s.generation||t.signal.aborted)return{stopReason:"cancelled"};let z=new AbortController;s.turnAbort=z;let p=AbortSignal.any([t.signal,z.signal]),w=()=>{s.runtime.abort()};p.aborted?w():p.addEventListener("abort",w,{once:!0});try{return await this.runPrompt(s,e.sessionId,a,t,p)}finally{p.removeEventListener("abort",w),s.turnAbort===z&&(s.turnAbort=null)}});return s.tail=f.then(()=>{},()=>{}),f}cancel(e){let t=this.sessions.get(e.sessionId);t&&(t.generation+=1,t.turnAbort?.abort(),t.runtime.abort())}async closeSession(e){yn(e.sessionId);let t=this.sessions.get(e.sessionId);return t?(t.closed=!0,t.generation+=1,t.turnAbort?.abort(),t.runtime.abort(),await t.tail.catch(()=>{}),await t.runtime.dispose(),this.sessions.delete(e.sessionId),{}):{}}async dispose(){let e=[...this.sessions.values()];this.sessions.clear();for(let t of e)t.closed=!0,t.generation+=1,t.turnAbort?.abort(),t.runtime.abort();await Promise.all(e.map(async t=>{await t.tail.catch(()=>{}),await t.runtime.dispose()}))}requireSession(e){yn(e);let t=this.sessions.get(e);if(!t||t.closed)throw S.resourceNotFound(e);return t}async runPrompt(e,t,s,a,u){Gn(e.runtime.workDir,t,{role:"user",content:s,timestamp:Math.floor(Date.now()/1e3)});let f="end_turn",z=!1;for await(let p of e.runtime.run(s,{onPermissionRequest:async(w,m,y,b)=>{let R=a.client.request(P.client.session.requestPermission,{sessionId:t,toolCall:{toolCallId:b,title:`${w}: ${y.reason}`,kind:Ue(w),status:"pending",rawInput:m,locations:Be(m,e.runtime.workDir)},options:[{optionId:"allow",name:"Allow once",kind:"allow_once"},{optionId:"allowAlways",name:"Always allow",kind:"allow_always"},{optionId:"deny",name:"Reject",kind:"reject_once"}]}),O=()=>{},H=new Promise(Q=>{O=()=>{Q(null)},u.aborted?O():u.addEventListener("abort",O,{once:!0})}),L=await Promise.race([R,H]);return u.removeEventListener("abort",O),!L||L.outcome.outcome==="cancelled"?(e.runtime.abort(),"deny"):L.outcome.optionId==="allowAlways"?"allowAlways":L.outcome.optionId==="allow"?"allow":"deny"}})){if(p.type==="compact"&&p.boundary&&Fn(e.runtime.workDir,t,p.boundary),p.type==="error")throw S.internalError(void 0,p.error.message);p.type==="loop_complete"&&(f=Sn(p.stopReason)),p.type==="usage"&&(e.usage=_n(e.usage,p),z=!0);let w=bn(p,e.runtime.workDir,e.runtime.contextWindow);if(w){let m={sessionId:t,update:w};await a.client.notify(P.client.session.update,m)}}return{stopReason:f,...z?{usage:e.usage}:{}}}};function Re(n){let e=new We(n);return{app:mn({name:"yukino"}).onRequest(P.agent.initialize,s=>e.initialize(s.params)).onRequest(P.agent.authenticate,()=>e.authenticate()).onRequest(P.agent.session.new,s=>e.newSession(s.params)).onRequest(P.agent.session.prompt,s=>e.prompt(s.params,s)).onRequest(P.agent.session.list,s=>e.listSessions(s.params)).onRequest(P.agent.session.load,s=>e.loadSession(s.params,s.client,!0)).onRequest(P.agent.session.resume,s=>e.loadSession(s.params,s.client,!1)).onRequest(P.agent.session.close,s=>e.closeSession(s.params)).onNotification(P.agent.session.cancel,s=>{e.cancel(s.params)}).onConnect(s=>{s.signal.addEventListener("abort",()=>{e.dispose()},{once:!0})}),dispose:()=>e.dispose()}}function oc(){let n=(...e)=>{process.stderr.write(`${e.map(String).join(" ")}
9
+ `)};console.log=n,console.info=n,console.warn=n,console.debug=n}async function xn(){oc();let n=Re(),e=As(ic.toWeb(process.stdout),sc.toWeb(process.stdin)),t=n.app.connect(e);process.stdin.resume();try{await t.closed}finally{await n.dispose()}}var bi={};ve(bi,{parseAcpWebSocketAddress:()=>mi,runAcpWebSocket:()=>In,startAcpWebSocketServer:()=>gi});import{createServer as Oc}from"http";var ie="Acp-Connection-Id",$e="Acp-Session-Id",Rn="text/event-stream",Tn="application/json",rc=new Set([h.session_cancel,h.session_close,h.session_delete,h.session_fork,h.session_load,h.session_prompt,h.session_resume,h.session_set_config_option,h.session_set_mode,"session/set_model",h.nes_suggest,h.nes_accept,h.nes_reject,h.nes_close,h.document_did_open,h.document_did_change,h.document_did_close,h.document_did_save,h.document_did_focus]);function Vs(n){return rc.has(n)}function Te(n){if(!M(n))return;let e=n.sessionId;return typeof e=="string"?e:void 0}function Ks(n){return"method"in n?Te(n.params):void 0}function Ys(n){if(!Y(n)||!("result"in n)||!M(n.result))return;let e=n.result.sessionId;return typeof e=="string"?e:void 0}function he(n){return n.jsonrpc==="2.0"&&"id"in n&&"method"in n&&n.method===h.initialize}function $(n){if(typeof n=="string")return`string:${n}`;if(typeof n=="number")return`number:${n}`;if(n===null)return"null"}var Jd=16*1024*1024;function Xs(n,e){return(t,s,a)=>{let u,f=!1,z=()=>{e.off("headers",p),s.off("close",w),s.off("error",w)},p=(m,y)=>{y!==t||!u||m.push(`${ie}: ${u.connectionId}`)},w=()=>{f||(z(),u?.reject())};try{u=n.prepareWebSocketUpgrade(),e.on("headers",p),s.once("close",w),s.once("error",w),e.handleUpgrade(t,s,a,m=>{f=!0,z(),u?.accept(m)})}catch(m){z(),u?.reject(),ac(s,m)}}}function ac(n,e){n.destroy(e instanceof Error?e:void 0)}var Zs=64*1024*1024,ei=6e4,ti=1024,ni=1024,Qs=2**31-1,U=class extends Error{constructor(e){super(e),this.name="ConnectionLimitError"}};function Je(n,e){return new U(`Connection exceeds ${n} (${e[n]})`)}function vn(n){return new U(`Connection output stalled for maxOutputStallMs (${n.maxOutputStallMs})`)}var F=class extends Error{constructor(){super("ACP connection is closed"),this.name="ConnectionClosedError"}},Ce=class{enabled;onReceiverChange;observer;queue=[];head=0;activeLease;isFinished=!1;isAborted=!1;abortError;constructor(e=!0,t,s){this.enabled=e,this.onReceiverChange=t,this.observer=s}push(e){!this.enabled||this.isFinished||(this.queue.push(e),this.observer?.queued?.(e),this.activeLease?.wake())}get hasReceiver(){return this.activeLease!==void 0}get hasQueuedMessages(){return this.head<this.queue.length}tryAcquire(){if(!this.enabled||this.isAborted||this.activeLease)return;let e=new Cn(this);return this.activeLease=e,this.onReceiverChange?.(),e}finish(){this.isFinished||(this.isFinished=!0,this.activeLease?.wake())}abort(e){if(!this.isAborted){for(this.isAborted=!0,this.abortError=e,this.isFinished=!0;this.hasQueuedMessages;)this.dequeue();this.observer=void 0,this.onReceiverChange=void 0,this.activeLease?.stop(e??new F)}}async receive(e){for(;;){if(e.released||this.activeLease!==e)return{done:!0,value:void 0};if(this.isAborted){if(this.abortError!==void 0)throw this.abortError;return{done:!0,value:void 0}}if(this.hasQueuedMessages)return{done:!1,value:this.dequeue()};if(this.isFinished)return{done:!0,value:void 0};await e.wait()}}release(e){this.activeLease===e&&(this.activeLease=void 0,e.markReleased(),this.onReceiverChange?.())}dequeue(){let e=this.queue[this.head];return this.queue[this.head]=void 0,this.head+=1,this.head===this.queue.length?(this.queue=[],this.head=0):this.head>=1024&&this.head*2>=this.queue.length&&(this.queue=this.queue.slice(this.head),this.head=0),this.observer?.dequeued(e),e}},Ve=class{transport;limits;connectionId;inboundTx;outboundRx;connectionStream;allOutbound;sessionStreams=new Map;pendingRoutes=new Map;clientResponseRoutes=new Map;closed;agentConnection;bufferedBytes=0;streamObserver={queued:e=>{this.bufferedBytes+=e.length},dequeued:e=>{this.bufferedBytes-=e.length,this.notifyOutboundProgress()}};bufferedSessionStreams=0;progressWaiters=new Set;supportsBatches=!1;hasStartedRouter=!1;hasAgentOutputEnded=!1;hasFinishedRouting=!1;hasStartedShutdown=!1;inboundWriteChain=Promise.resolve();initialReader;outboundReader;routerPromise;shutdownPromise;hasResolvedClosed=!1;abortAgentInbound=()=>{};endAgentOutbound=()=>{};resolveClosed=()=>{};constructor(e,t,s){this.transport=t,this.limits=s,this.connectionId=globalThis.crypto.randomUUID(),this.connectionStream=new Ce(t==="http",void 0,this.streamObserver),this.allOutbound=new Ce(t==="websocket",void 0,{dequeued:()=>{this.notifyOutboundProgress()}}),this.closed=new Promise(z=>{this.resolveClosed=z});let a=new TransformStream({start:z=>{this.abortAgentInbound=p=>z.error(p)}}),u=dc(z=>{if(!this.supportsBatches&&Array.isArray(z))throw new TypeError("AcpServer transports do not support outbound JSON-RPC batch messages")},()=>{this.hasAgentOutputEnded=!0,this.notifyOutboundProgress()});this.inboundTx=a.writable,this.outboundRx=u.readable,this.endAgentOutbound=u.end;let f={readable:a.readable,writable:u.writable};this.agentConnection=e.connect(f,{deferConnectHandlers:!0}),this.observeAgentConnection()}async recvInitial(e){let t=this.outboundRx.getReader();this.initialReader=t;try{let s=await t.read();if(s.done||!s.value||!uc(s.value,e))throw this.shutdownPromise||await this.shutdown(),new Error("Expected initialize response from agent");return s.value}finally{this.initialReader===t&&(this.initialReader=void 0),t.releaseLock()}}async writeInbound(e){if(!this.supportsBatches&&Array.isArray(e))throw new TypeError("AcpServer transports do not support inbound JSON-RPC batch messages");let t=this.inboundWriteChain.then(()=>this.writeInboundMessage(e));this.inboundWriteChain=t.catch(()=>{}),await t}startRouter(){this.hasStartedRouter||(this.hasStartedRouter=!0,this.routerPromise=this.runRouter())}startConnectHandlers(){typeof this.agentConnection=="object"&&this.agentConnection!==null&&"startConnectHandlers"in this.agentConnection&&typeof this.agentConnection.startConnectHandlers=="function"&&this.agentConnection.startConnectHandlers()}enableBatches(){this.supportsBatches=!0}get batchesEnabled(){return this.supportsBatches}get isClosed(){return this.hasStartedShutdown}get hasOutboundBacklog(){return this.transport==="http"?this.bufferedBytes>=this.limits.maxBufferedBytes:this.allOutbound.hasQueuedMessages}validateSessionId(e){this.validateIdLength("Session ID",e)}validateRequestId(e){typeof e=="string"&&this.validateIdLength("Request ID",e)}async waitForOutboundCapacity(e){await this.waitForRoom(()=>this.hasFinishedRouting,e)}ensureSession(e){if(this.validateSessionId(e),this.transport==="websocket")return this.connectionStream;let t=this.sessionStreams.get(e);if(t)return t;if(this.bufferedSessionStreams>=this.limits.maxBufferedSessionStreams)throw Je("maxBufferedSessionStreams",this.limits);return this.createSessionStream(e)}acquireSessionStream(e){if(this.validateSessionId(e),this.transport==="websocket")return;let t=this.sessionStreams.get(e);if(t)return t.tryAcquire();if(this.isClosed||this.hasFinishedRouting)throw new F;return this.createSessionStream(e).tryAcquire()}async shutdown(e){return this.shutdownPromise||(this.shutdownPromise=this.runShutdown(e)),this.shutdownPromise}async runShutdown(e){try{this.hasStartedShutdown=!0,this.notifyOutboundProgress(),this.connectionStream.abort(e),this.allOutbound.abort(e);for(let t of this.sessionStreams.values())t.abort(e);this.sessionStreams.clear(),this.bufferedSessionStreams=0,this.pendingRoutes.clear(),this.clientResponseRoutes.clear(),await Promise.allSettled([this.closeInbound(e),this.cancelOutboundReader()])}finally{this.resolveClosedOnce()}}observeAgentConnection(){typeof this.agentConnection!="object"||this.agentConnection===null||!("closed"in this.agentConnection)||!this.agentConnection.closed||Promise.resolve(this.agentConnection.closed).finally(async()=>{if(!this.hasStartedRouter){await this.shutdown();return}this.endAgentOutbound(),await this.routerPromise})}cancelOutboundReader(){let e=this.initialReader??this.outboundReader;return e?e.cancel():this.outboundRx.cancel()}closeInbound(e){return e!==void 0||this.inboundTx.locked?(this.abortAgentInbound(e??new F),Promise.resolve()):this.inboundTx.close()}async writeInboundMessage(e){if(this.isClosed||this.hasFinishedRouting)throw new F;let t=this.inboundTx.getWriter();try{await t.write(e)}catch(s){throw this.isClosed?new F:s}finally{t.releaseLock()}}async runRouter(){let e=this.outboundRx.getReader();this.outboundReader=e;try{for(;;){let t=await e.read();if(t.done||this.isClosed)return;this.routeOutbound(t.value),await this.waitForRoom(()=>this.hasAgentOutputEnded)}}catch(t){t instanceof U?this.closeForLimit(t):(console.error(`ACP connection ${this.connectionId} router stopped unexpectedly:`,t),this.shutdown(t))}finally{this.hasFinishedRouting=!0,this.notifyOutboundProgress(),this.outboundReader===e&&(this.outboundReader=void 0),e.releaseLock(),this.connectionStream.finish(),this.allOutbound.finish();for(let t of this.sessionStreams.values())t.finish();this.resolveClosedOnce()}}resolveClosedOnce(){this.hasResolvedClosed||(this.hasResolvedClosed=!0,this.resolveClosed())}async waitForRoom(e,t){for(;!this.isClosed&&!e()&&this.hasOutboundBacklog;)if(!await this.waitForProgress(t)){this.closeForLimit(vn(this.limits));return}}waitForProgress(e){let t=this.transport==="http"?this.limits.maxOutputStallMs:void 0;return new Promise((s,a)=>{if(e?.aborted){a(e.reason);return}let u,f=()=>{this.progressWaiters.delete(z),e?.removeEventListener("abort",p),clearTimeout(u)},z=()=>{f(),s(!0)},p=()=>{f(),a(e?.reason)};this.progressWaiters.add(z),e?.addEventListener("abort",p,{once:!0}),t!==void 0&&(u=setTimeout(()=>{f(),s(!1)},t))})}notifyOutboundProgress(){for(let e of[...this.progressWaiters])e()}routeOutbound(e){if(Array.isArray(e))for(let t of e)this.routeOutboundMessage(t);else this.routeOutboundMessage(e);this.allOutbound.push(e)}routeOutboundMessage(e){if(Y(e)){this.routeOutboundResponse(e);return}this.routeOutboundRequestOrNotification(e)}routeOutboundResponse(e){let t=$(e.id),s=t?this.pendingRoutes.get(t):void 0,a=Ys(e);a&&this.validateSessionId(a),t&&this.pendingRoutes.delete(t),this.pushToRoute(s??"connection",e)}createSessionStream(e){let t=new Ce(!0,()=>{this.onSessionReceiverChange(e,t)},this.streamObserver);return this.sessionStreams.set(e,t),this.bufferedSessionStreams+=1,t}onSessionReceiverChange(e,t){if(!this.isClosed){if(t.hasReceiver){this.bufferedSessionStreams-=1;return}if(!t.hasQueuedMessages){this.sessionStreams.delete(e),t.abort();return}this.bufferedSessionStreams+=1,!this.hasFinishedRouting&&this.bufferedSessionStreams>this.limits.maxBufferedSessionStreams&&this.closeForLimit(Je("maxBufferedSessionStreams",this.limits))}}closeForLimit(e){console.warn(`Closing ACP connection ${this.connectionId}:`,e.message),this.shutdown(e)}validateIdLength(e,t){if(t.length>this.limits.maxIdLength)throw new U(`${e} exceeds maxIdLength (${this.limits.maxIdLength})`)}routeOutboundRequestOrNotification(e){let t=Ks(e);if(t){let s=this.ensureSession(t);this.trackClientResponseRoute(e,{session:t}),this.deliver(s,e);return}this.trackClientResponseRoute(e,"connection"),this.deliver(this.connectionStream,e)}trackClientResponseRoute(e,t){if(!("id"in e)||!("method"in e))return;let s=$(e.id);s&&this.clientResponseRoutes.set(s,t)}pushToRoute(e,t){if(e==="connection"){this.deliver(this.connectionStream,t);return}this.deliver(this.ensureSession(e.session),t)}deliver(e,t){this.transport==="http"&&e.push(JSON.stringify(t))}},Ke=class{limits;connections=new Map;pendingConnections=new Map;constructor(e={}){this.limits=cc(e)}createConnection(e,t="http"){let s=new Ve(e,t,this.limits);return this.connections.set(s.connectionId,s),this.trackConnectionClose(s),s}createPendingConnection(e,t="websocket"){let s=new Ve(e,t,this.limits);return this.pendingConnections.set(s.connectionId,s),this.trackConnectionClose(s),s}register(e){this.pendingConnections.delete(e.connectionId),this.connections.set(e.connectionId,e)}get(e){let t=this.connections.get(e);return t?.isClosed?void 0:t}remove(e){let t=this.connections.get(e);if(t)return this.connections.delete(e),t.shutdown(),t}discard(e){let t=this.connections.get(e)??this.pendingConnections.get(e);if(t)return this.connections.delete(e),this.pendingConnections.delete(e),t.shutdown(),t}async closeAll(){let e=new Set([...this.connections.values(),...this.pendingConnections.values()]);this.connections.clear(),this.pendingConnections.clear(),await Promise.all(Array.from(e,t=>t.shutdown()))}trackConnectionClose(e){e.closed.then(()=>{this.connections.get(e.connectionId)===e&&this.connections.delete(e.connectionId),this.pendingConnections.get(e.connectionId)===e&&this.pendingConnections.delete(e.connectionId)})}};function cc(n){let e={maxBufferedBytes:n.maxBufferedBytes??Zs,maxOutputStallMs:n.maxOutputStallMs??ei,maxBufferedSessionStreams:n.maxBufferedSessionStreams??ti,maxIdLength:n.maxIdLength??ni};for(let[t,s]of Object.entries(e))if(!Number.isSafeInteger(s)||s<=0)throw new RangeError(`${t} must be a positive safe integer`);if(e.maxOutputStallMs>Qs)throw new RangeError(`maxOutputStallMs must be at most ${Qs}`);return e}var Cn=class{mailbox;released=!1;stoppedController=new AbortController;receiving=!1;wakePromise;resolveWake;constructor(e){this.mailbox=e}get stopped(){return this.stoppedController.signal}async receive(){if(this.receiving)throw new Error("ACP outbound mailbox lease already has a pending receive");this.receiving=!0;try{return await this.mailbox.receive(this)}finally{this.receiving=!1}}release(){this.mailbox.release(this)}wake(){this.resolveWake?.(),this.wakePromise=void 0,this.resolveWake=void 0}wait(){return this.wakePromise||(this.wakePromise=new Promise(e=>{this.resolveWake=e})),this.wakePromise}markReleased(){this.released=!0,this.wake()}stop(e){this.stoppedController.abort(e),this.wake()}};function dc(n,e){let t,s=!1,a=!1,u,f=()=>{let m=u;u=void 0,m?.()},z=()=>{if(!s){s=!0;try{t?.close()}catch{}f(),e()}},p=m=>{if(!s){s=!0;try{t?.error(m)}catch{}f(),e()}},w=()=>{s||a||(a=!0,f(),setTimeout(z,0))};return{readable:new ReadableStream({start(m){t=m},pull:f,cancel(){s=!0,f()}},{highWaterMark:0}),writable:new WritableStream({async write(m){if(s)throw new Error("ACP outbound channel is closed");try{n(m),t?.enqueue(m)}catch(y){throw p(y),y}!s&&!a&&(t?.desiredSize??0)<0&&await new Promise(y=>{u=y})},close:z,abort:p}),end:w}}function uc(n,e){return!Array.isArray(n)&&"id"in n&&!("method"in n)&&n.id===e}var tu=new TextEncoder().encode("data:"),nu=new Uint8Array([10]);function si(n){return`data: ${n}
10
+
11
+ `}function ii(){return`:
12
+
13
+ `}function oi(n){return new ReadableStream(lc(n),{highWaterMark:0})}function lc(n){let e=new TextEncoder,t,s=!1,a=!1,u=!1,f=()=>{t&&(clearInterval(t),t=void 0)},z=(b,R)=>{s=!1;try{return b.enqueue(e.encode(R)),!0}catch{return!1}},p=b=>{if(!u){u=!0,f(),n.release();try{b.close()}catch{}}},w=(b,R)=>{u||(u=!0,f(),n.release(),b.error(R))},m=b=>{n.stopped.aborted&&!s&&w(b,n.stopped.reason)},y=async b=>{if(!a){a=!0;try{for(;s&&!u;){let R=await n.receive();if(u)return;if(R.done){p(b);return}if(!z(b,si(R.value))){p(b);return}m(b)}}catch(R){w(b,R)}finally{a=!1}}};return{start(b){n.stopped.addEventListener("abort",()=>{m(b)},{once:!0}),t=setInterval(()=>{u||!s||z(b,ii())||p(b)},15e3)},pull(b){s=!0,y(b)},cancel(){u=!0,f(),n.release()}}}function Ye(n,e,t){if(n.on){let s=(...a)=>{t(...hc(e,a))};return n.on(e,s),()=>{if(n.off){n.off(e,s);return}n.removeListener?.(e,s)}}if(n.addEventListener){let s=a=>t(a);return n.addEventListener(e,s),()=>{n.removeEventListener?.(e,s)}}throw new Error("WebSocket object does not support event listeners")}function ri(n){let e=pc(n);if(typeof e=="string")return e}function hc(n,e){return n!=="message"||typeof e[1]!="boolean"?e:e[1]?[void 0]:[fc(e[0])]}function fc(n){if(typeof n=="string")return n;if(n instanceof ArrayBuffer)return new TextDecoder().decode(n);if(ArrayBuffer.isView(n))return new TextDecoder().decode(n);if(mc(n))return gc(n)}function pc(n){let[e]=n;return zc(e)?e.data:e}function zc(n){return typeof n=="object"&&n!==null&&"data"in n}function mc(n){return Array.isArray(n)&&n.every(ArrayBuffer.isView)}function gc(n){let e=n.reduce((a,u)=>a+u.byteLength,0),t=new Uint8Array(e),s=0;for(let a of n)t.set(new Uint8Array(a.buffer,a.byteOffset,a.byteLength),s),s+=a.byteLength;return new TextDecoder().decode(t)}var bc=10,_c=1e3,wc=1024;function di(n,e){let t=new kn(n,e);return t.start(),t}var kn=class{socket;options;connection;preparedConnection;outboundLease;inboundWriteChain=Promise.resolve();messageChain=Promise.resolve();waitingInboundBytes=0;isClosed=!1;closedPromise;resolveClosed=()=>{};detachListeners=[];constructor(e,t){this.socket=e,this.options=t,this.preparedConnection=t.connection,this.closedPromise=new Promise(s=>{this.resolveClosed=s})}get closed(){return this.closedPromise}start(){this.detachListeners.push(Ye(this.socket,"message",(...e)=>{this.enqueueSocketMessage(e)})),this.detachListeners.push(Ye(this.socket,"close",()=>{this.closeSession()})),this.detachListeners.push(Ye(this.socket,"error",()=>{this.shutdown(1011,"WebSocket error")}))}close(e=1001,t="Server shutting down"){return this.shutdown(e,t)}enqueueSocketMessage(e){if(this.isClosed)return;let t=ri(e);if(t===void 0){console.warn("Ignoring non-text ACP WebSocket frame");return}let s=t.length+wc,{limits:a}=this.options.registry;if(this.waitingInboundBytes>0&&s>a.maxBufferedBytes-this.waitingInboundBytes){this.closeForLimit(Je("maxBufferedBytes",a));return}this.waitingInboundBytes+=s;let u=this.messageChain.then(()=>(this.waitingInboundBytes-=s,this.handleSocketMessage(t)));this.messageChain=u.catch(f=>{if(!(this.isClosed||f instanceof F)){if(f instanceof U){this.closeForLimit(f);return}console.error("ACP WebSocket message handling failed:",f),this.shutdown(1011,"Message handling failed")}})}async handleSocketMessage(e){if(this.isClosed)return;let t;try{t=JSON.parse(e)}catch{await this.waitForSocketCapacity(),this.send(B(S.parseError()));return}if(!Array.isArray(t)&&!M(t)){await this.waitForSocketCapacity(),this.send(B(S.invalidRequest(t)));return}if(!this.connection&&Array.isArray(t)){if(t.length===1&&G(t[0])){await this.handleInitialize(t[0],!0);return}console.warn("First ACP WebSocket message must be initialize or a single-entry initialize batch"),await this.shutdown(1002,"First message must be initialize");return}let s=t;if(!this.connection){if(de(s))return;if(!G(s)&&!j(s)){await this.waitForSocketCapacity(),this.send(B(S.invalidRequest(s)));return}await this.handleInitialize(s,!1);return}let a=await this.forwardMessage(s);a.ok||console.warn("Ignoring ACP WebSocket message:",a.message)}async handleInitialize(e,t){if(!he(e)){console.warn("First ACP WebSocket message must be initialize"),await this.shutdown(1002,"First message must be initialize");return}if(!("id"in e)||e.id===null){console.warn("ACP WebSocket initialize request must include an ID"),await this.shutdown(1002,"Initialize request must include an ID");return}let s=this.preparedConnection??this.options.registry.createPendingConnection(this.options.agent);this.preparedConnection=s;try{await ai(s,e);let a=await s.recvInitial(e.id);if(this.isClosed){this.options.registry.discard(s.connectionId);return}this.preparedConnection=void 0,yc(a)===2&&s.enableBatches(),this.connection=s,this.options.registry.register(s),s.startRouter(),s.startConnectHandlers(),this.send(t?[a]:a),this.startOutboundPump(s)}catch(a){this.preparedConnection=void 0,this.options.registry.discard(s.connectionId);let u={jsonrpc:"2.0",id:e.id,error:{code:-32603,message:"Initialize failed",data:a instanceof Error?a.message:void 0}};this.send(t?[u]:u),await this.shutdown(1011,"Initialize failed")}}async forwardMessage(e){let t=this.connection;if(!t)return{ok:!1,message:"ACP WebSocket connection is not initialized"};if(Array.isArray(e)){if(!t.batchesEnabled)return await this.shutdown(1002,"JSON-RPC batches require ACP v2"),{ok:!1,message:"JSON-RPC batches require ACP v2"};if(e.some(Ec))return await this.shutdown(1002,"Initialize not allowed on existing connection"),{ok:!1,message:"Initialize not allowed on existing connection"};for(let s of e)this.trackInboundRoutes(s);return await this.forwardToAgent(t,e)}return G(e)&&he(e)?(await this.waitForSocketCapacity(),this.send({jsonrpc:"2.0",id:e.id,error:{code:-32600,message:"Initialize not allowed on existing connection"}}),{ok:!1,message:"Initialize not allowed on existing connection"}):(this.trackInboundRoutes(e),await this.forwardToAgent(t,e))}async forwardToAgent(e,t){return Sc(t)&&(await e.waitForOutboundCapacity(),await this.waitForSocketCapacity()),await this.writeInbound(t),{ok:!0}}async waitForSocketCapacity(){let{limits:e}=this.options.registry,t=bc,s=this.socket.bufferedAmount??0,a=0;for(;!this.isClosed&&s>=e.maxBufferedBytes;){if(a>=e.maxOutputStallMs){this.closeForLimit(vn(e));return}await new Promise(f=>setTimeout(f,t)),a+=t,t=Math.min(t*2,_c);let u=s;s=this.socket.bufferedAmount??0,s<u&&(a=0)}}trackInboundRoutes(e){let t=this.connection;if(t){if(G(e)){let s=ci(e);s!=="connection"&&t.validateSessionId(s.session),t.validateRequestId(e.id);let a=$(e.id);a&&t.pendingRoutes.set(a,e.method===h.session_load?"connection":s);return}if(j(e)){let s=ci(e);s!=="connection"&&t.validateSessionId(s.session);return}if(de(e)){let s=e.id,a=s===null||typeof s=="string"||typeof s=="number"&&Number.isFinite(s)?$(s):void 0;a&&t.clientResponseRoutes.delete(a)}}}async writeInbound(e){let t=this.connection;if(!t)throw new Error("ACP WebSocket connection is not initialized");let s=this.inboundWriteChain.then(()=>ai(t,e));this.inboundWriteChain=s.catch(()=>{}),await s}startOutboundPump(e){let t=e.allOutbound.tryAcquire();if(!t){this.shutdown(1011,"Outbound stream already has an active receiver");return}this.outboundLease=t,t.stopped.addEventListener("abort",()=>{this.closeForStoppedConnection(t.stopped.reason)},{once:!0}),(async()=>{try{for(;!this.isClosed;){let s=await t.receive();if(s.done||!this.send(s.value))return;await this.waitForSocketCapacity()}}catch(s){t.stopped.aborted||console.error("ACP WebSocket outbound pump failed:",s),await this.closeForStoppedConnection(s)}finally{this.outboundLease===t&&(this.outboundLease=void 0),t.release(),this.isClosed||this.shutdown()}})()}send(e){if(this.isClosed)return!1;try{return this.socket.send(JSON.stringify(e)),!0}catch(t){return console.warn("Failed to send ACP WebSocket message:",t),this.shutdown(1011,"Failed to send message"),!1}}closeForLimit(e){let t=this.connection?.connectionId??this.preparedConnection?.connectionId,s=t?`ACP connection ${t}`:"ACP connection";console.warn(`Closing ${s}:`,e.message),this.shutdown(1008,e.message)}async closeForStoppedConnection(e){this.isClosed||(e instanceof U?await this.shutdown(1008,e.message):e instanceof F?await this.shutdown():await this.shutdown(1011,"Internal error"))}async shutdownIfUninitialized(e,t){this.connection||await this.shutdown(e,t)}async shutdown(e,t){this.closeSocket(e,t),await this.closeSession()}closeSocket(e,t){try{this.socket.close(e,t)}catch(s){console.warn("Failed to close ACP WebSocket:",s)}}async closeSession(){if(!this.isClosed){this.isClosed=!0;try{for(let t of this.detachListeners.splice(0))t();let e=this.outboundLease;this.outboundLease=void 0,e?.release(),this.connection&&(this.options.registry.discard(this.connection.connectionId),this.connection=void 0),this.preparedConnection&&(this.options.registry.discard(this.preparedConnection.connectionId),this.preparedConnection=void 0)}finally{this.resolveClosed()}}}};async function ai(n,e){await n.writeInbound(e)}function ci(n){let e=Te(n.params);return e?{session:e}:"connection"}function Sc(n){return Array.isArray(n)?n.length===0||!rn(n)&&!n.every(e=>j(e)):!j(n)&&!de(n)}function Ec(n){return G(n)&&he(n)}function yc(n){if(!("result"in n)||!M(n.result))return;let e=n.result.protocolVersion;return typeof e=="number"?e:void 0}var Xe=class{agent;registry;webSocketSessions=new Set;constructor(e){this.agent=fi(e),this.registry=new Ke(e)}async handleRequest(e,t={}){try{return e.method==="POST"?await this.handlePost(e,t):e.method==="GET"?this.handleGet(e):e.method==="DELETE"?this.handleDelete(e):k("Method Not Allowed",405)}catch(s){if(s instanceof U)return k(s.message,400);if(s instanceof F)return k("Unknown Acp-Connection-Id",404);if(s instanceof X)return k("Request aborted",499);throw s}}prepareWebSocketUpgrade(e={}){let t=ui(e,this.agent),s=this.registry.createPendingConnection(t),a=!1;return{connectionId:s.connectionId,accept:u=>{if(a)throw new Error("ACP WebSocket upgrade has already been settled");a=!0;let f=di(u,{registry:this.registry,agent:t,connection:s});this.webSocketSessions.add(f),f.closed.finally(()=>{this.webSocketSessions.delete(f)})},reject:()=>{a||(a=!0,this.registry.discard(s.connectionId))}}}async close(){let e=this.registry.closeAll(),t=Promise.all(Array.from(this.webSocketSessions,s=>s.close()));await Promise.all([e,t])}async handlePost(e,t){let s=e.headers.get("Content-Type");if(!Mc(s))return k("Unsupported Media Type",415);let a=await Rc(e);if(!a.ok)return k("Invalid JSON",400);if(Array.isArray(a.value))return k("Batch JSON-RPC requests are not implemented",501);if(!M(a.value))return k("Invalid JSON-RPC message",400);let u=a.value,f=e.headers.get(ie);if(he(u))return f?k("Initialize not allowed on existing connection",400):await this.handleInitialize(u,e.signal,t);if(!f)return k("Missing Acp-Connection-Id",400);let z=this.registry.get(f);if(!z)return k("Unknown Acp-Connection-Id",404);let p=await this.forwardConnectedMessage(z,u,e.headers,e.signal);return p.ok?hi(202):k(p.message,p.status)}handleGet(e){if(e.headers.get("Upgrade")?.toLowerCase()==="websocket")return k("WebSocket upgrade is not implemented",426);if(!e.headers.get("Accept")?.toLowerCase()?.includes(Rn))return k("Not Acceptable",406);let s=e.headers.get(ie);if(!s)return k("Missing Acp-Connection-Id",400);let a=this.registry.get(s);if(!a)return k("Unknown Acp-Connection-Id",404);let u=e.headers.get($e),f=u?a.acquireSessionStream(u):a.connectionStream.tryAcquire();return f?Nc(f):k("Outbound stream already has an active receiver",409)}handleDelete(e){let t=e.headers.get(ie);return t?this.registry.remove(t)?hi(202):k("Unknown Acp-Connection-Id",404):k("Missing Acp-Connection-Id",400)}async handleInitialize(e,t,s){if(!("id"in e)||e.id===null)return k("Initialize request must include an ID",400);if(t.aborted)return k("Request aborted",499);let a;try{a=this.registry.createConnection(ui(s,this.agent));let u=Tc(a,e);u.catch(()=>{});let f=await Cc(u,t);if(t.aborted)throw new X;return a.startRouter(),a.startConnectHandlers(),li(f,200,{[ie]:a.connectionId})}catch(u){return a&&this.registry.remove(a.connectionId),u instanceof X?k("Request aborted",499):li({jsonrpc:"2.0",id:e.id,error:{code:-32603,message:"Initialize failed",data:u instanceof Error?u.message:void 0}},500)}}async forwardConnectedMessage(e,t,s,a){return Y(t)?await kc(e,t,s):await vc(e,t,s,a)}};function ui(n,e){return xc(n)?fi(n):e}function xc(n){return!!(n.agent||n.createAgent||n.createLegacyAgent)}function fi(n){if((n.agent?1:0)+(n.createAgent?1:0)+(n.createLegacyAgent?1:0)!==1)throw new Error("AcpServer requires exactly one of agent, createAgent, or createLegacyAgent");return n.agent?n.agent:n.createAgent?{connect:(t,s)=>n.createAgent().connect(t,s??{})}:{connect:t=>{new Le(n.createLegacyAgent,t)}}}var X=class extends Error{constructor(){super("Request aborted"),this.name="RequestAbortedError"}};async function Rc(n){try{return{ok:!0,value:await n.json()}}catch{return{ok:!1}}}async function An(n,e){await n.writeInbound(e)}async function Tc(n,e){if(await An(n,e),!("id"in e)||e.id===null)throw new Error("Initialize request must include an ID");return await n.recvInitial(e.id)}async function Cc(n,e){if(e.aborted)throw new X;let t=()=>{},s=new Promise((a,u)=>{let f=()=>{u(new X)};e.addEventListener("abort",f,{once:!0}),t=()=>{e.removeEventListener("abort",f)}});try{return await Promise.race([n,s])}finally{t()}}async function vc(n,e,t,s){let a=Ic(e,t);if(!a.ok)return a;a.value!=="connection"&&n.validateSessionId(a.value.session),j(e)||(n.validateRequestId(e.id),await n.waitForOutboundCapacity(s).catch(f=>{throw s.aborted?new X:f}));let u=G(e)?$(e.id):void 0;return u&&n.pendingRoutes.set(u,Ac(e,a.value)),await An(n,e),{ok:!0}}async function kc(n,e,t){let s=$(e.id),a=s?n.clientResponseRoutes.get(s):void 0,u=t.get($e);return a&&a!=="connection"&&!u?{ok:!1,status:400,message:"Missing Acp-Session-Id"}:a&&a!=="connection"&&u!==a.session?{ok:!1,status:400,message:"Mismatched Acp-Session-Id"}:(s&&n.clientResponseRoutes.delete(s),await An(n,e),{ok:!0})}function Ac(n,e){return n.method===h.session_load?"connection":e}function Ic(n,e){let t=e.get($e),s=Te(n.params);return(Vs(n.method)||s!==void 0)&&!t?{ok:!1,status:400,message:"Missing Acp-Session-Id"}:t!==null&&s!==void 0&&t!==s?{ok:!1,status:400,message:"Mismatched Acp-Session-Id"}:t?{ok:!0,value:{session:t}}:s?{ok:!0,value:{session:s}}:{ok:!0,value:"connection"}}function Mc(n){return n?.split(";",1)[0]?.trim().toLowerCase()===Tn}function Nc(n){return new Response(oi(n),{status:200,headers:{"Content-Type":Rn,"Cache-Control":"no-cache",Connection:"keep-alive"}})}function li(n,e,t){return new Response(JSON.stringify(n),{status:e,headers:{"Content-Type":Tn,...t}})}function k(n,e){return new Response(n,{status:e,headers:{"Content-Type":"text/plain"}})}function hi(n){return new Response(null,{status:n})}var pi="/acp",Dc="127.0.0.1:18889",jc=new Set(["127.0.0.1","::1","localhost"]);function mi(n){let e=$n(n??Dc);if(!jc.has(e.host))throw new Error("ACP WebSocket must listen on a loopback address.");return e}async function gi(n){let{host:e,port:t}=mi(n),s=new Xe({createAgent:()=>Re().app}),a=new Mn.default({noServer:!0}),u=Xs(s,a),f=Oc((y,b)=>{b.writeHead(404,{"content-type":"text/plain; charset=utf-8"}),b.end("Not Found")});f.on("upgrade",(y,b,R)=>{if(new URL(y.url??"/","http://localhost").pathname!==pi){b.destroy();return}u(y,b,R)}),await new Promise((y,b)=>{let R=H=>{f.off("listening",O),b(H)},O=()=>{f.off("error",R),y()};f.once("error",R),f.once("listening",O),f.listen(t,e)});let z=f.address();if(!z||typeof z=="string")throw new Error("ACP WebSocket server did not bind to a TCP address.");let p=z,w=p.family==="IPv6"?`[${p.address}]`:p.address,m=!1;return{url:`ws://${w}:${String(p.port)}${pi}`,async close(){if(m)return;m=!0;let y,b=R=>{y=y??(R instanceof Error?R:new Error(String(R)))};try{await s.close()}catch(R){b(R)}try{await zi(a)}catch(R){b(R)}try{await zi(f)}catch(R){b(R)}if(y!==void 0)throw y}}}function zi(n){return new Promise((e,t)=>{n.close(s=>{s?t(s):e()})})}async function In(n){let e=await gi(n);process.stderr.write(`ACP WebSocket listening at ${e.url}
14
+ `),await new Promise(t=>{let s=()=>{process.off("SIGINT",s),process.off("SIGTERM",s),e.close().finally(t)};process.once("SIGINT",s),process.once("SIGTERM",s)})}function qc(n){let e=n.indexOf("--acp"),t=n.indexOf("--acp-ws");if(e===-1&&t===-1)return null;if(e!==-1&&t!==-1)throw new Error("Use either --acp or --acp-ws, not both.");if(e!==-1){if(n.length!==1)throw new Error("--acp cannot be combined with other CLI options.");return{transport:"stdio"}}let s=n[t+1],a=s&&!s.startsWith("-")?2:1;if(n.length!==a)throw new Error("--acp-ws accepts only an optional host:port address.");return{transport:"websocket",...a===2?{address:s}:{}}}async function Au(n){let e=qc(n);if(!e)throw new Error("ACP mode was not selected.");if(e.transport==="stdio"){await xn();return}await In(e.address)}export{$s as Agent,Us as Conversion,Js as Stdio,bi as Websocket,qc as parseAcpMode,Au as runAcp};
@@ -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{I as b,J as c,g as a}from"./chunk-ZETIYALB.js";import"./chunk-JNCMSXQZ.js";import"./chunk-JFKC4VCA.js";import"./chunk-OFC2GD5K.js";import"./chunk-7DLUKIPE.js";import"./chunk-XO7ITAWR.js";import"./chunk-UPNNYP7M.js";import"./chunk-GYBJR2RB.js";import"./chunk-HMZQYFYG.js";import"./chunk-3QL446GD.js";import"./chunk-AGSYLE4E.js";import"./chunk-CU3IISCC.js";import"./chunk-VCIRD267.js";import"./chunk-7MKA3SHV.js";export{c as Agent,b as Events,a as StreamingExecutor};
4
+ import{K as b,L as c,g as a}from"./chunk-3SPUH3TD.js";import"./chunk-BPA7URET.js";import"./chunk-JFKC4VCA.js";import"./chunk-OFC2GD5K.js";import"./chunk-HBXZ6MB4.js";import"./chunk-3EQYWNP6.js";import"./chunk-2HUCPWD6.js";import"./chunk-GYBJR2RB.js";import"./chunk-HMZQYFYG.js";import"./chunk-3QL446GD.js";import"./chunk-AGSYLE4E.js";import"./chunk-CU3IISCC.js";import"./chunk-VCIRD267.js";import"./chunk-7MKA3SHV.js";export{c as Agent,b as Events,a as StreamingExecutor};