@yukino.js/yukino 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +320 -0
- package/dist/acp-IVY5HZR4.js +14 -0
- package/dist/agent-QANDY7FO.js +4 -0
- package/dist/anthropic-6YLT4JZR.js +4 -0
- package/dist/bwrap-MLSZLWHD.js +4 -0
- package/dist/chunk-2LHY3FND.js +67 -0
- package/dist/chunk-3KKA6537.js +4 -0
- package/dist/chunk-3QL446GD.js +4 -0
- package/dist/chunk-4GE22WHI.js +4 -0
- package/dist/chunk-5VOCXSSX.js +5 -0
- package/dist/chunk-77W2UPS2.js +4 -0
- package/dist/chunk-7MKA3SHV.js +4 -0
- package/dist/chunk-AGSYLE4E.js +16 -0
- package/dist/chunk-CU3IISCC.js +4 -0
- package/dist/chunk-GYBJR2RB.js +65 -0
- package/dist/chunk-HLE7243Q.js +4 -0
- package/dist/chunk-HMZQYFYG.js +4 -0
- package/dist/chunk-JFKC4VCA.js +4 -0
- package/dist/chunk-K4BYVVW7.js +5 -0
- package/dist/chunk-KCMBAHWU.js +4 -0
- package/dist/chunk-L2BWSPCF.js +10 -0
- package/dist/chunk-MDPSQ6L7.js +44 -0
- package/dist/chunk-OFC2GD5K.js +4 -0
- package/dist/chunk-RAS3ORX3.js +164 -0
- package/dist/chunk-RCXKUD3Y.js +4 -0
- package/dist/chunk-SAJCBGHL.js +4 -0
- package/dist/chunk-SOO5OXX2.js +237 -0
- package/dist/chunk-T4O4GQVL.js +607 -0
- package/dist/chunk-UPNNYP7M.js +60 -0
- package/dist/chunk-VCIRD267.js +4 -0
- package/dist/chunk-VU3JWAJR.js +4 -0
- package/dist/chunk-VWUGGYUP.js +6 -0
- package/dist/chunk-XO7ITAWR.js +4 -0
- package/dist/devtools-YWVUN4HX.js +7 -0
- package/dist/esm-57CJEGGK.js +4 -0
- package/dist/esm-6L5BJ5GT.js +4 -0
- package/dist/esm-DIYJ5HX6.js +4 -0
- package/dist/esm-HW2JMFYC.js +4 -0
- package/dist/esm-RPR2GBJ2.js +4 -0
- package/dist/esm-YKAO4ES6.js +4 -0
- package/dist/esm-ZTIYTMTS.js +229 -0
- package/dist/getMachineId-bsd-E27XJQLX.js +4 -0
- package/dist/getMachineId-darwin-35UPAIXP.js +5 -0
- package/dist/getMachineId-linux-MKXIYT6A.js +4 -0
- package/dist/getMachineId-unsupported-ZXVGGFX2.js +4 -0
- package/dist/getMachineId-win-RNVIYJG5.js +4 -0
- package/dist/lib/agent-6FZX4P2Y.js +16 -0
- package/dist/lib/anthropic-IP23YZ3P.js +21 -0
- package/dist/lib/bwrap-2OL7VPSO.js +7 -0
- package/dist/lib/chunk-2VF3XTGH.js +3382 -0
- package/dist/lib/chunk-5DVQ64YL.js +619 -0
- package/dist/lib/chunk-5TGXH7BX.js +624 -0
- package/dist/lib/chunk-6OMQD7MK.js +591 -0
- package/dist/lib/chunk-AZRC67RW.js +512 -0
- package/dist/lib/chunk-F2YJG72O.js +150 -0
- package/dist/lib/chunk-FFM2LB4C.js +132 -0
- package/dist/lib/chunk-FLKB4BK7.js +50 -0
- package/dist/lib/chunk-I34MAQRE.js +255 -0
- package/dist/lib/chunk-KA6POJKI.js +889 -0
- package/dist/lib/chunk-MLKGABMK.js +9 -0
- package/dist/lib/chunk-O7ELJUEK.js +262 -0
- package/dist/lib/chunk-QYBQT2DM.js +655 -0
- package/dist/lib/chunk-YIWNQ7OA.js +47 -0
- package/dist/lib/index.d.ts +8581 -0
- package/dist/lib/index.js +15905 -0
- package/dist/lib/openai-EMJ6U4FW.js +15 -0
- package/dist/lib/permissions-KZ5ACZAX.js +19 -0
- package/dist/lib/providers-2CGZPBFI.js +9 -0
- package/dist/lib/sandbox-runtime-CCQ3X3SM.js +9 -0
- package/dist/lib/seatbelt-WO7YWKLR.js +7 -0
- package/dist/lib/tool-filter-CKHZUUBQ.js +21 -0
- package/dist/main.js +332 -0
- package/dist/node-634LOHDX.js +15 -0
- package/dist/openai-YXYO5OW6.js +34 -0
- package/dist/permissions-VCDMNX3L.js +4 -0
- package/dist/providers-HNMBGGW6.js +4 -0
- package/dist/sandbox-runtime-ELKAYRIL.js +4 -0
- package/dist/seatbelt-JOCANLYS.js +4 -0
- package/dist/server-ZHQILOBP.js +4 -0
- package/dist/src-43CPCEK2.js +12 -0
- package/dist/src-JBRNH4FA.js +4 -0
- package/dist/src-R4BSSIJJ.js +4 -0
- package/dist/src-X6JWWHHT.js +4 -0
- package/dist/tool-filter-BQZDV3TF.js +4 -0
- package/dist/turndown.es-NQ3KDXM7.js +83 -0
- package/package.json +146 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 hangtiancheng
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
# Yukino
|
|
2
|
+
|
|
3
|
+
Yukino is a terminal-based AI coding agent. It provides an interactive UI (terminal user interface) for conversing with large language models, executing code, manipulating files, and orchestrating multi-agent workflows, all from the command line.
|
|
4
|
+
|
|
5
|
+
## Overview
|
|
6
|
+
|
|
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
|
+
|
|
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.
|
|
10
|
+
|
|
11
|
+
## Features
|
|
12
|
+
|
|
13
|
+
### Core Capabilities
|
|
14
|
+
|
|
15
|
+
- Multi-provider LLM support with Anthropic, OpenAI, and OpenAI-compatible protocols
|
|
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
|
|
18
|
+
- MCP (Model Context Protocol) server integration for extending the tool set with external services
|
|
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
|
|
22
|
+
|
|
23
|
+
### Conversation and Memory
|
|
24
|
+
|
|
25
|
+
- Session persistence with JSONL-based storage for cross-session resume
|
|
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
|
|
29
|
+
|
|
30
|
+
### Skills and Commands
|
|
31
|
+
|
|
32
|
+
- Skill catalog with three-tier loading: built-in, user-global (~/.agents/skills/), and project-level (.agents/skills/)
|
|
33
|
+
- Hot-reload support for skills edited on disk
|
|
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
|
|
37
|
+
|
|
38
|
+
### Agent Orchestration
|
|
39
|
+
|
|
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
|
|
42
|
+
- Coordinator mode for managing multi-agent workflows
|
|
43
|
+
- Git worktree isolation for parallel agent tasks
|
|
44
|
+
|
|
45
|
+
### Hooks
|
|
46
|
+
|
|
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
|
|
50
|
+
|
|
51
|
+
### Remote Mode
|
|
52
|
+
|
|
53
|
+
- Koa HTTP server with WebSocket bridge for browser-based access
|
|
54
|
+
- React frontend served at a configurable address
|
|
55
|
+
- Bidirectional message streaming between browser and agent
|
|
56
|
+
|
|
57
|
+
## Installation
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
npm install -g @yukino.js/yukino
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Or use the one-line installers ([macOS / Linux](../../install.sh), [Windows](../../install.ps1)):
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
# macOS / Linux
|
|
67
|
+
curl -fsSL https://raw.githubusercontent.com/hangtiancheng/yukino-code/main/install.sh | bash
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
```powershell
|
|
71
|
+
# Windows (PowerShell)
|
|
72
|
+
irm https://raw.githubusercontent.com/hangtiancheng/yukino-code/main/install.ps1 | iex
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Both installers write a default `~/.yukino/config.yaml` if none exists, verify Node.js >= 20, and support uninstall / pinned-version / dist-tag options (see their `--help` / `-Help` output).
|
|
76
|
+
|
|
77
|
+
Or run directly from the monorepo:
|
|
78
|
+
|
|
79
|
+
```bash
|
|
80
|
+
pnpm dev
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
## Configuration
|
|
84
|
+
|
|
85
|
+
Yukino reads a single global YAML configuration file:
|
|
86
|
+
|
|
87
|
+
- ~/.yukino/config.yaml
|
|
88
|
+
|
|
89
|
+
At least one provider must be configured. Example config.yaml:
|
|
90
|
+
|
|
91
|
+
```yaml
|
|
92
|
+
providers:
|
|
93
|
+
- name: anthropic
|
|
94
|
+
protocol: anthropic
|
|
95
|
+
base_url: https://api.anthropic.com
|
|
96
|
+
model: claude-sonnet-4-6
|
|
97
|
+
# api_key defaults to $ANTHROPIC_API_KEY
|
|
98
|
+
thinking: high # off | minimal | low | medium | high | xhigh | max
|
|
99
|
+
|
|
100
|
+
permission_mode: default
|
|
101
|
+
|
|
102
|
+
mcp_servers:
|
|
103
|
+
- name: database
|
|
104
|
+
command: npx
|
|
105
|
+
args: ["-y", "@yukino-db/mcp@latest"]
|
|
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}"
|
|
109
|
+
|
|
110
|
+
hooks:
|
|
111
|
+
- event: pre_tool_use
|
|
112
|
+
condition: "Bash"
|
|
113
|
+
action:
|
|
114
|
+
type: command
|
|
115
|
+
command: "echo tool about to run"
|
|
116
|
+
|
|
117
|
+
sandbox:
|
|
118
|
+
enabled: false
|
|
119
|
+
auto_allow: false
|
|
120
|
+
network_enabled: true
|
|
121
|
+
|
|
122
|
+
enable_coordinator_mode: false
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
Provider fields:
|
|
126
|
+
|
|
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.
|
|
139
|
+
|
|
140
|
+
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
|
+
|
|
142
|
+
### Telemetry
|
|
143
|
+
|
|
144
|
+
Telemetry is disabled by default and is configured only through environment variables. Yukino does not send prompts, model output, thinking content, tool arguments, tool results, file paths, API keys, or raw session IDs. Session identifiers included in traces are hashed.
|
|
145
|
+
|
|
146
|
+
#### OpenTelemetry
|
|
147
|
+
|
|
148
|
+
Set at least one exporter variable to enable OpenTelemetry:
|
|
149
|
+
|
|
150
|
+
| Variable | Values / purpose |
|
|
151
|
+
| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
|
|
152
|
+
| `OTEL_SDK_DISABLED` | Set to `true` to disable OpenTelemetry and Langfuse tracing. |
|
|
153
|
+
| `OTEL_SERVICE_NAME` | Service name; defaults to `yukino`. |
|
|
154
|
+
| `OTEL_RESOURCE_ATTRIBUTES` | Comma-separated resource attributes, for example `deployment.environment.name=production`. |
|
|
155
|
+
| `OTEL_TRACES_EXPORTER` | Comma-separated `otlp`, `console`, or `none`. |
|
|
156
|
+
| `OTEL_LOGS_EXPORTER` | Comma-separated `otlp`, `console`, or `none`. |
|
|
157
|
+
| `OTEL_METRICS_EXPORTER` | Comma-separated `otlp`, `console`, `prometheus`, or `none`. |
|
|
158
|
+
| `OTEL_EXPORTER_OTLP_PROTOCOL` | Default OTLP protocol: `grpc`, `http/json`, or `http/protobuf`. |
|
|
159
|
+
| `OTEL_EXPORTER_OTLP_TRACES_PROTOCOL` | Optional trace-specific protocol override. |
|
|
160
|
+
| `OTEL_EXPORTER_OTLP_LOGS_PROTOCOL` | Optional log-specific protocol override. |
|
|
161
|
+
| `OTEL_EXPORTER_OTLP_METRICS_PROTOCOL` | Optional metric-specific protocol override. |
|
|
162
|
+
| `OTEL_EXPORTER_OTLP_ENDPOINT` | Shared OTLP collector endpoint. |
|
|
163
|
+
| `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` | Optional trace-specific endpoint. |
|
|
164
|
+
| `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT` | Optional log-specific endpoint. |
|
|
165
|
+
| `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT` | Optional metric-specific endpoint. |
|
|
166
|
+
| `OTEL_EXPORTER_OTLP_HEADERS` | Shared comma-separated OTLP headers. Signal-specific standard header variables are also supported by the exporters. |
|
|
167
|
+
| `OTEL_METRIC_EXPORT_INTERVAL` | Metric export interval in milliseconds; defaults to `60000`. |
|
|
168
|
+
|
|
169
|
+
Example:
|
|
170
|
+
|
|
171
|
+
```bash
|
|
172
|
+
export OTEL_TRACES_EXPORTER=otlp
|
|
173
|
+
export OTEL_METRICS_EXPORTER=otlp
|
|
174
|
+
export OTEL_LOGS_EXPORTER=otlp
|
|
175
|
+
export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
|
|
176
|
+
export OTEL_EXPORTER_OTLP_ENDPOINT=https://collector.example.com
|
|
177
|
+
export OTEL_EXPORTER_OTLP_HEADERS="authorization=Bearer token"
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
#### Langfuse
|
|
181
|
+
|
|
182
|
+
Langfuse tracing is enabled when both `LANGFUSE_PUBLIC_KEY` and `LANGFUSE_SECRET_KEY` are set. It shares Yukino's trace hierarchy with OpenTelemetry.
|
|
183
|
+
|
|
184
|
+
| Variable | Purpose |
|
|
185
|
+
| ------------------------------ | --------------------------------------------------- |
|
|
186
|
+
| `LANGFUSE_PUBLIC_KEY` | Langfuse project public key. |
|
|
187
|
+
| `LANGFUSE_SECRET_KEY` | Langfuse project secret key. |
|
|
188
|
+
| `LANGFUSE_BASE_URL` | Langfuse cloud or self-hosted endpoint. |
|
|
189
|
+
| `LANGFUSE_TRACING_ENVIRONMENT` | Environment attached to traces. |
|
|
190
|
+
| `LANGFUSE_RELEASE` | Release identifier; defaults to the Yukino version. |
|
|
191
|
+
| `LANGFUSE_FLUSH_AT` | Number of spans accumulated before export. |
|
|
192
|
+
| `LANGFUSE_FLUSH_INTERVAL` | Batch flush interval in seconds. |
|
|
193
|
+
| `LANGFUSE_TIMEOUT` | Export request timeout in seconds. |
|
|
194
|
+
|
|
195
|
+
#### Sentry
|
|
196
|
+
|
|
197
|
+
Sentry is enabled when `SENTRY_DSN` is set. It reports process-level errors only; performance tracing remains handled by OpenTelemetry.
|
|
198
|
+
|
|
199
|
+
| Variable | Purpose |
|
|
200
|
+
| -------------------- | --------------------------------------------------- |
|
|
201
|
+
| `SENTRY_DSN` | Sentry project DSN. |
|
|
202
|
+
| `SENTRY_ENVIRONMENT` | Deployment environment. |
|
|
203
|
+
| `SENTRY_RELEASE` | Release identifier; defaults to the Yukino version. |
|
|
204
|
+
| `SENTRY_DEBUG` | Set to `true` to enable Sentry SDK diagnostics. |
|
|
205
|
+
|
|
206
|
+
### Project-level MCP servers (.mcp.json)
|
|
207
|
+
|
|
208
|
+
In addition to `mcp_servers` in `config.yaml`, Yukino reads a project-level `.mcp.json` from the working directory, using the Claude Code-compatible format:
|
|
209
|
+
|
|
210
|
+
```json
|
|
211
|
+
{
|
|
212
|
+
"mcpServers": {
|
|
213
|
+
"database": {
|
|
214
|
+
"command": "npx",
|
|
215
|
+
"args": ["-y", "@yukino-db/mcp@latest"],
|
|
216
|
+
"env": { "API_KEY": "${DATABASE_API_KEY}" }
|
|
217
|
+
},
|
|
218
|
+
"remote": {
|
|
219
|
+
"type": "http",
|
|
220
|
+
"url": "https://example.com/mcp",
|
|
221
|
+
"headers": { "Authorization": "Bearer ${TOKEN}" }
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
Each entry takes `command`/`args`/`env` (stdio) or `url`/`headers` with `type` of `http` or `sse`. Environment references support `${VAR}`, `${VAR:-default}`, and `$VAR` in commands, arguments, environment values, URLs, and headers; an unset variable without a default prevents that server from connecting. These servers are merged with the user-level `mcp_servers`; on a name collision the user-level entry wins. At startup, a malformed `.mcp.json` is ignored (logged), while an invalid individual server entry is skipped without disabling valid siblings. During `/mcp reload`, invalid config aborts the reload so the current connections remain intact.
|
|
228
|
+
|
|
229
|
+
After editing `.mcp.json` or `config.yaml`, use `/mcp reload` in the UI to re-read both sources. Unchanged connections stay live, removed servers disconnect, new servers connect, and servers whose settings changed restart.
|
|
230
|
+
|
|
231
|
+
## Usage
|
|
232
|
+
|
|
233
|
+
### Interactive UI Mode
|
|
234
|
+
|
|
235
|
+
```bash
|
|
236
|
+
yukino
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
Launches the terminal interface. If multiple providers are configured, a provider selection screen appears first.
|
|
240
|
+
|
|
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.
|
|
242
|
+
|
|
243
|
+
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
|
+
|
|
245
|
+
### Print Mode (Non-Interactive)
|
|
246
|
+
|
|
247
|
+
```bash
|
|
248
|
+
yukino -p "explain this codebase"
|
|
249
|
+
yukino -p "fix the failing test" --output-format stream-json
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
The -p flag sends a single prompt, runs the agent loop, and prints the result to stdout. Useful for scripting and CI pipelines.
|
|
253
|
+
|
|
254
|
+
### Remote Mode (Browser UI)
|
|
255
|
+
|
|
256
|
+
```bash
|
|
257
|
+
yukino --remote # listens on 127.0.0.1:18888
|
|
258
|
+
yukino --remote :9000 # custom loopback port
|
|
259
|
+
yukino --remote 0.0.0.0:9000 # explicitly expose on all interfaces (no built-in authentication)
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
Starts a Koa HTTP server and WebSocket bridge. The bundled React frontend is served at the configured address for browser-based interaction.
|
|
263
|
+
|
|
264
|
+
### Slash Commands
|
|
265
|
+
|
|
266
|
+
Inside the UI, these commands are available:
|
|
267
|
+
|
|
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
|
+
| /permission mode <mode> | Change permission mode (default, acceptEdits, plan, bypassPermissions) |
|
|
273
|
+
| /memory | List stored memories |
|
|
274
|
+
| /memory clear | Clear all memories |
|
|
275
|
+
| /skills | List available skills |
|
|
276
|
+
| /skills reload | Hot-reload skills from disk |
|
|
277
|
+
| /skill <name> [args] | Run a skill by name |
|
|
278
|
+
| /plan | Enter plan mode (read-only investigation) |
|
|
279
|
+
| /do | Exit plan mode and execute the approved plan |
|
|
280
|
+
| /compact | Force conversation compaction |
|
|
281
|
+
| /clear | Reset the session and clear the terminal |
|
|
282
|
+
| /resume [id] | List or restore a previous session |
|
|
283
|
+
| /rewind | Open checkpoint rewind dialog |
|
|
284
|
+
| /sandbox [1/2/3] | Configure sandbox (1=on+auto, 2=on+manual, 3=off) |
|
|
285
|
+
| /worktree | List git worktrees |
|
|
286
|
+
| /mcp | Show MCP server status |
|
|
287
|
+
| /mcp reload | Re-read MCP config; reconcile unchanged, removed, new, and changed servers |
|
|
288
|
+
| /thinking [level] | Show or set the thinking level (off, minimal, low, medium, high, xhigh, max); setting persists to `~/.yukino/config.yaml` |
|
|
289
|
+
| /quit | Exit the application |
|
|
290
|
+
|
|
291
|
+
### Keyboard Shortcuts
|
|
292
|
+
|
|
293
|
+
| Key | Action |
|
|
294
|
+
| --------- | ----------------------------------------------------------------------------------- |
|
|
295
|
+
| Ctrl+C | Clear input or interrupt streaming (first press), exit app (second press within 2s) |
|
|
296
|
+
| Ctrl+O | Toggle full vs. truncated tool output |
|
|
297
|
+
| Ctrl+T | Toggle Teams dialog overlay |
|
|
298
|
+
| Ctrl+V | Paste a clipboard image (Alt+V on Windows) |
|
|
299
|
+
| Shift+Tab | Cycle permission modes |
|
|
300
|
+
|
|
301
|
+
Pastes longer than 10 lines or 1,000 characters collapse to `[paste #1 +124 lines]` or `[paste #1 1234 chars]`. Clipboard images appear as `[Image #1]`. Arrow keys move across each placeholder as a unit, and Backspace/Delete remove it as a unit. Placeholders survive dialog switches; submitting restores the full text and image attachments.
|
|
302
|
+
|
|
303
|
+
Pasting an image saves it as a PNG under `.yukino/file-history/<session-id>/`. Its placeholder expands to a workDir-relative `@` reference on submit and loads as an inline image block. Linux requires `wl-clipboard` (Wayland) or `xclip` (X11).
|
|
304
|
+
|
|
305
|
+
## Library Build
|
|
306
|
+
|
|
307
|
+
Besides the `yukino` CLI, the package ships a library entry for embedding Yukino in another host process.
|
|
308
|
+
|
|
309
|
+
| Entry | Output | Contents |
|
|
310
|
+
| -------------- | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------- |
|
|
311
|
+
| CLI (`yukino`) | `dist/main.js` | Fully bundled, minified single file with a shebang; only Node built-ins stay external. |
|
|
312
|
+
| 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`. |
|
|
313
|
+
|
|
314
|
+
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:
|
|
315
|
+
|
|
316
|
+
- **ui-only dependency ban** — the `ban-ui-only-deps` plugin in `tsup.config.ts` fails the build when a bundle-reachable module imports one of the ui-only packages (`ink`, `react`, `chalk`, `ansi-escapes`, …) or a path inside `src/ui`. The list is declared once in `tsup.config.ts` and re-derived from the actual import sites by `tests/build-guards.test.ts`, which fails if the two drift apart.
|
|
317
|
+
- **`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.
|
|
318
|
+
- **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.
|
|
319
|
+
|
|
320
|
+
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()`.
|
|
@@ -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 Ot,b as Dt}from"./chunk-SOO5OXX2.js";import"./chunk-T4O4GQVL.js";import"./chunk-HLE7243Q.js";import{p as kt,q as vt,s as Nt,t as At,u as It,v as Mt,w as jt}from"./chunk-RAS3ORX3.js";import{a as Ct}from"./chunk-VWUGGYUP.js";import"./chunk-JFKC4VCA.js";import"./chunk-SAJCBGHL.js";import"./chunk-OFC2GD5K.js";import{v as Rt,w as yt,x as Tt}from"./chunk-5VOCXSSX.js";import"./chunk-RCXKUD3Y.js";import"./chunk-XO7ITAWR.js";import{k as Be,s as $e}from"./chunk-UPNNYP7M.js";import{D as K,g as s,h as xt,i as x,j as A,k as v,n as c,o as T,p as r,r as b,t as B,u as d,w as l}from"./chunk-GYBJR2RB.js";import{b as Et}from"./chunk-L2BWSPCF.js";import"./chunk-HMZQYFYG.js";import"./chunk-3QL446GD.js";import"./chunk-AGSYLE4E.js";import"./chunk-CU3IISCC.js";import"./chunk-VCIRD267.js";import{d as Se}from"./chunk-7MKA3SHV.js";var Os={};Se(Os,{runAcpStdio:()=>zt});import{Readable as Oa,Writable as Da}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"},Je={cancel_request:"$/cancel_request"},Ve=1;var qt=Symbol("skippedItem");function o(t,e){return t.catch(e)}function O(t,e){let n=t.catch(e);return K.unknown().transform((i,a)=>i!==void 0?n.parse(i):(a.addIssue({code:"custom",message:"Required value is missing"}),K.NEVER))}function Ht(t,e){if(t===null||typeof t!="object"||Array.isArray(t))return;let n=t[e];return typeof n=="string"?n:void 0}function ae(t,e,n){return t.superRefine((i,a)=>{let u=Ht(i,e);u!==void 0&&n.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 ce(t,e,n){return K.unknown().transform((i,a)=>{let u=t.safeParse(i);if(!u.success){for(let f of u.error.issues)a.addIssue({...f,input:i});return K.NEVER}let p=u.data,z=Ht(i,e);if(z!==void 0&&!n.includes(z)){let f=i;for(let[g,m]of Object.entries(f))g!=="__proto__"&&(Object.hasOwn(p,g)||(p[g]=m))}return p})}function S(t){return K.array(t.catch(qt)).transform(e=>e.filter(n=>n!==qt))}var $=b([x(),s()]).nullable(),E=s(),Ye=r({sessionId:E,path:s(),content:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),Qe=r({sessionId:E,path:s(),line:o(A().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),limit:o(A().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Ze=s(),Pt=b([l("read"),l("edit"),l("delete"),l("move"),l("search"),l("execute"),l("think"),l("fetch"),l("switch_mode"),l("other")]),Lt=b([l("pending"),l("in_progress"),l("completed"),l("failed")]),si=b([l("assistant"),l("user")]),de=r({audience:o(S(si).nullish(),()=>{}),lastModified:o(s().nullish(),()=>{}),priority:o(x().nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),ii=r({annotations:o(de.nullish(),()=>{}),text:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),oi=r({annotations:o(de.nullish(),()=>{}),data:s(),mimeType:s(),uri:o(s().nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),ri=r({annotations:o(de.nullish(),()=>{}),data:s(),mimeType:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),ai=r({annotations:o(de.nullish(),()=>{}),description:o(s().nullish(),()=>{}),mimeType:o(s().nullish(),()=>{}),name:s(),size:o(x().nullish(),()=>{}),title:o(s().nullish(),()=>{}),uri:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),ci=r({mimeType:o(s().nullish(),()=>{}),text:s(),uri:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),di=r({blob:s(),mimeType:o(s().nullish(),()=>{}),uri:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),ui=b([ci,di]),li=r({annotations:o(de.nullish(),()=>{}),resource:ui,_meta:o(d(s(),c()).nullish(),()=>{})}),ue=b([ii.and(r({type:l("text")})),oi.and(r({type:l("image")})),ri.and(r({type:l("audio")})),ai.and(r({type:l("resource_link")})),li.and(r({type:l("resource")}))]),hi=r({content:ue,_meta:o(d(s(),c()).nullish(),()=>{})}),pi=r({path:s(),oldText:o(s().nullish(),()=>{}),newText:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),X=s(),fi=r({terminalId:X,_meta:o(d(s(),c()).nullish(),()=>{})}),Gt=b([hi.and(r({type:l("content")})),pi.and(r({type:l("diff")})),fi.and(r({type:l("terminal")}))]),Ut=r({path:s(),line:o(A().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Ft=r({toolCallId:Ze,kind:o(Pt.nullish(),()=>{}),status:o(Lt.nullish(),()=>{}),title:o(s().nullish(),()=>{}),name:o(s().nullish(),()=>{}),content:o(S(Gt).nullish(),()=>{}),locations:o(S(Ut).nullish(),()=>{}),rawInput:o(c().optional(),()=>{}),rawOutput:o(c().optional(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Wt=s(),zi=b([l("allow_once"),l("allow_always"),l("reject_once"),l("reject_always")]),mi=r({optionId:Wt,name:s(),kind:zi,_meta:o(d(s(),c()).nullish(),()=>{})}),Xe=r({sessionId:E,toolCall:Ft,options:T(mi),_meta:o(d(s(),c()).nullish(),()=>{})}),Bt=r({name:s(),value:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),en=r({sessionId:E,command:s(),args:o(S(s()).optional(),()=>[]),env:o(S(Bt).optional(),()=>[]),cwd:o(s().nullish(),()=>{}),outputByteLimit:o(x().nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),nn=r({sessionId:E,terminalId:X,_meta:o(d(s(),c()).nullish(),()=>{})}),tn=r({sessionId:E,terminalId:X,_meta:o(d(s(),c()).nullish(),()=>{})}),sn=r({sessionId:E,terminalId:X,_meta:o(d(s(),c()).nullish(),()=>{})}),on=r({sessionId:E,terminalId:X,_meta:o(d(s(),c()).nullish(),()=>{})}),le=r({sessionId:E,toolCallId:o(Ze.nullish(),()=>{})}),he=r({requestId:$}),gi=l("object"),bi=b([l("email"),l("uri"),l("date"),l("date-time")]),$t=r({const:s(),title:s(),description:o(s().nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),rn=r({title:o(s().nullish(),()=>{}),description:o(s().nullish(),()=>{}),minLength:A().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),maxLength:A().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),pattern:s().nullish(),format:bi.nullish(),default:o(s().nullish(),()=>{}),enum:T(s()).nullish(),oneOf:T($t).nullish(),_meta:o(d(s(),c()).nullish(),()=>{})}),an=r({title:o(s().nullish(),()=>{}),description:o(s().nullish(),()=>{}),minimum:x().nullish(),maximum:x().nullish(),default:o(x().nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),cn=r({title:o(s().nullish(),()=>{}),description:o(s().nullish(),()=>{}),minimum:x().nullish(),maximum:x().nullish(),default:o(x().nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),dn=r({title:o(s().nullish(),()=>{}),description:o(s().nullish(),()=>{}),default:o(v().nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),un=r({enum:T(s()),_meta:o(d(s(),c()).nullish(),()=>{})}),Jt=r({anyOf:T($t),_meta:o(d(s(),c()).nullish(),()=>{})}),_i=ce(b([un.and(r({type:l("string")})),ae(r({type:s()}),"type",["string"]),Jt]),"type",["string"]),ln=r({title:o(s().nullish(),()=>{}),description:o(s().nullish(),()=>{}),minItems:x().nullish(),maxItems:x().nullish(),items:_i,default:o(S(s()).nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),wi=ce(b([rn.and(r({type:l("string")})),an.and(r({type:l("number")})),cn.and(r({type:l("integer")})),dn.and(r({type:l("boolean")})),ln.and(r({type:l("array")})),ae(r({type:s()}),"type",["array","boolean","integer","number","string"])]),"type",["array","boolean","integer","number","string"]),Si=r({type:o(gi.optional().default("object"),()=>"object"),title:o(s().nullish(),()=>{}),properties:d(s(),wi).optional().default({}),required:T(s()).nullish(),description:o(s().nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),hn=B(b([le,he]),r({requestedSchema:Si})),Vt=s(),pn=B(b([le,he]),r({elicitationId:Vt,url:xt()})),fn=ce(B(b([hn.and(r({mode:l("form")})),pn.and(r({mode:l("url")})),ae(B(b([le,he]),r({mode:s()})),"mode",["form","url"])]),r({message:s(),_meta:o(d(s(),c()).nullish(),()=>{})})),"mode",["form","url"]),Kt=s(),Ei=r({serverId:Kt,_meta:o(d(s(),c()).nullish(),()=>{})}),Ee=s(),Yt=r({connectionId:Ee,method:s(),params:d(s(),c()).nullish(),_meta:o(d(s(),c()).nullish(),()=>{})}),xi=r({connectionId:Ee,_meta:o(d(s(),c()).nullish(),()=>{})}),Qt=c(),mc=r({id:$,method:s(),params:b([Ye,Qe,Xe,en,nn,tn,sn,on,fn,Ei,Yt,xi,Qt]).nullish()}),Zt=A().gte(0).lte(65535),Ri=r({image:o(v().optional().default(!1),()=>!1),audio:o(v().optional().default(!1),()=>!1),embeddedContext:o(v().optional().default(!1),()=>!1),_meta:o(d(s(),c()).nullish(),()=>{})}),yi=r({http:o(v().optional().default(!1),()=>!1),sse:o(v().optional().default(!1),()=>!1),acp:o(v().optional().default(!1),()=>!1),_meta:o(d(s(),c()).nullish(),()=>{})}),Ti=r({_meta:o(d(s(),c()).nullish(),()=>{})}),Ci=r({_meta:o(d(s(),c()).nullish(),()=>{})}),ki=r({_meta:o(d(s(),c()).nullish(),()=>{})}),vi=r({_meta:o(d(s(),c()).nullish(),()=>{})}),Ni=r({_meta:o(d(s(),c()).nullish(),()=>{})}),Ai=r({_meta:o(d(s(),c()).nullish(),()=>{})}),Ii=r({list:o(Ti.nullish(),()=>{}),delete:o(Ci.nullish(),()=>{}),additionalDirectories:o(ki.nullish(),()=>{}),fork:o(vi.nullish(),()=>{}),resume:o(Ni.nullish(),()=>{}),close:o(Ai.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Mi=r({_meta:o(d(s(),c()).nullish(),()=>{})}),ji=r({logout:o(Mi.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Oi=r({_meta:o(d(s(),c()).nullish(),()=>{})}),Di=r({_meta:o(d(s(),c()).nullish(),()=>{})}),qi=b([l("full"),l("incremental")]),Hi=r({syncKind:qi,_meta:o(d(s(),c()).nullish(),()=>{})}),Pi=r({_meta:o(d(s(),c()).nullish(),()=>{})}),Li=r({_meta:o(d(s(),c()).nullish(),()=>{})}),Gi=r({_meta:o(d(s(),c()).nullish(),()=>{})}),Ui=r({didOpen:o(Di.nullish(),()=>{}),didChange:o(Hi.nullish(),()=>{}),didClose:o(Pi.nullish(),()=>{}),didSave:o(Li.nullish(),()=>{}),didFocus:o(Gi.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Fi=r({document:o(Ui.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Wi=r({maxCount:o(A().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Bi=r({_meta:o(d(s(),c()).nullish(),()=>{})}),$i=r({maxCount:o(A().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Ji=r({maxCount:o(A().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Vi=r({_meta:o(d(s(),c()).nullish(),()=>{})}),Ki=r({_meta:o(d(s(),c()).nullish(),()=>{})}),Yi=r({recentFiles:o(Wi.nullish(),()=>{}),relatedSnippets:o(Bi.nullish(),()=>{}),editHistory:o($i.nullish(),()=>{}),userActions:o(Ji.nullish(),()=>{}),openFiles:o(Vi.nullish(),()=>{}),diagnostics:o(Ki.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Qi=r({events:o(Fi.nullish(),()=>{}),context:o(Yi.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Xt=b([l("utf-16"),l("utf-32"),l("utf-8")]),Zi=r({loadSession:o(v().optional().default(!1),()=>!1),promptCapabilities:o(Ri.optional().default({image:!1,audio:!1,embeddedContext:!1}),()=>({image:!1,audio:!1,embeddedContext:!1})),mcpCapabilities:o(yi.optional().default({http:!1,sse:!1,acp:!1}),()=>({http:!1,sse:!1,acp:!1})),sessionCapabilities:o(Ii.optional().default({}),()=>({})),auth:o(ji.optional().default({}),()=>({})),providers:o(Oi.nullish(),()=>{}),nes:o(Qi.nullish(),()=>{}),positionEncoding:o(Xt.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),zn=s(),Xi=r({id:zn,name:s(),description:o(s().nullish(),()=>{}),args:o(S(s()).optional(),()=>[]),env:o(d(s(),s()).optional(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),eo=r({id:zn,name:s(),description:o(s().nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),no=b([Xi.and(r({type:l("terminal")})),eo]),es=r({name:s(),title:o(s().nullish(),()=>{}),version:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),to=r({protocolVersion:Zt,agentCapabilities:o(Zi.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(S(no).optional().default([]),()=>[]),agentInfo:o(es.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),so=r({_meta:o(d(s(),c()).nullish(),()=>{})}),mn=s(),gn=b([l("anthropic"),l("openai"),l("azure"),l("vertex"),l("bedrock"),s()]),io=r({apiType:gn,baseUrl:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),oo=r({providerId:mn,supported:O(S(gn),()=>[]),required:v(),current:io.nullish(),_meta:o(d(s(),c()).nullish(),()=>{})}),ro=r({providers:T(oo),_meta:o(d(s(),c()).nullish(),()=>{})}),ao=r({_meta:o(d(s(),c()).nullish(),()=>{})}),co=r({_meta:o(d(s(),c()).nullish(),()=>{})}),uo=r({_meta:o(d(s(),c()).nullish(),()=>{})}),xe=s(),lo=r({id:xe,name:s(),description:o(s().nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Re=r({currentModeId:xe,availableModes:O(S(lo),()=>[]),_meta:o(d(s(),c()).nullish(),()=>{})}),ns=s(),ho=b([l("mode"),l("model"),l("model_config"),l("thought_level"),s()]),bn=s(),ts=r({value:bn,name:s(),description:o(s().nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),po=s(),fo=r({group:po,name:s(),options:O(S(ts),()=>[]),_meta:o(d(s(),c()).nullish(),()=>{})}),zo=b([T(ts),T(fo)]),mo=r({currentValue:bn,options:zo}),go=r({currentValue:v()}),ee=B(b([mo.and(r({type:l("select")})),go.and(r({type:l("boolean")}))]),r({id:ns,name:s(),description:o(s().nullish(),()=>{}),category:o(ho.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})})),bo=r({sessionId:E,modes:o(Re.nullish(),()=>{}),configOptions:o(S(ee).nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),_o=r({modes:o(Re.nullish(),()=>{}),configOptions:o(S(ee).nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),wo=r({sessionId:E,cwd:s(),additionalDirectories:o(S(s()).optional(),()=>[]),title:o(s().nullish(),()=>{}),updatedAt:o(s().nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),So=r({sessions:O(S(wo),()=>[]),nextCursor:o(s().nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Eo=r({_meta:o(d(s(),c()).nullish(),()=>{})}),xo=r({sessionId:E,modes:o(Re.nullish(),()=>{}),configOptions:o(S(ee).nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Ro=r({modes:o(Re.nullish(),()=>{}),configOptions:o(S(ee).nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),yo=r({_meta:o(d(s(),c()).nullish(),()=>{})}),To=r({_meta:o(d(s(),c()).nullish(),()=>{})}),Co=r({configOptions:O(S(ee),()=>[]),_meta:o(d(s(),c()).nullish(),()=>{})}),ko=b([l("end_turn"),l("max_tokens"),l("max_turn_requests"),l("refusal"),l("cancelled")]),vo=r({totalTokens:x(),inputTokens:x(),outputTokens:x(),thoughtTokens:o(x().nullish(),()=>{}),cachedReadTokens:o(x().nullish(),()=>{}),cachedWriteTokens:o(x().nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),No=r({stopReason:ko,usage:o(vo.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Ao=r({sessionId:E,_meta:o(d(s(),c()).nullish(),()=>{})}),ne=s(),J=r({line:A().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}),character:A().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}),_meta:o(d(s(),c()).nullish(),()=>{})}),te=r({start:J,end:J,_meta:o(d(s(),c()).nullish(),()=>{})}),Io=r({range:te,newText:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),Mo=r({id:ne,uri:s(),edits:T(Io),cursorPosition:o(J.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),jo=r({id:ne,uri:s(),position:J,_meta:o(d(s(),c()).nullish(),()=>{})}),Oo=r({id:ne,uri:s(),position:J,newName:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),Do=r({id:ne,uri:s(),search:s(),replace:s(),isRegex:v().nullish(),_meta:o(d(s(),c()).nullish(),()=>{})}),qo=b([Mo.and(r({kind:l("edit")})),jo.and(r({kind:l("jump")})),Oo.and(r({kind:l("rename")})),Do.and(r({kind:l("searchAndReplace")}))]),Ho=r({suggestions:T(qo),_meta:o(d(s(),c()).nullish(),()=>{})}),Po=r({_meta:o(d(s(),c()).nullish(),()=>{})}),ss=c(),is=c(),Lo=b([l(-32700),l(-32600),l(-32601),l(-32602),l(-32603),l(-32800),l(-32e3),l(-32002),A().min(-2147483648,{error:"Invalid value: Expected int32 to be >= -2147483648"}).max(2147483647,{error:"Invalid value: Expected int32 to be <= 2147483647"})]),os=r({code:Lo,message:s(),data:o(c().optional(),()=>{})}),gc=b([r({id:$,result:b([to,so,ro,ao,co,uo,bo,_o,So,Eo,xo,Ro,yo,To,Co,No,Ao,Ho,Po,ss,is])}),r({id:$,error:os})]),Go=s(),Ke=r({content:ue,messageId:o(Go.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Uo=r({toolCallId:Ze,title:s(),name:o(s().nullish(),()=>{}),kind:o(Pt.optional(),()=>{}),status:o(Lt.optional(),()=>{}),content:o(S(Gt).optional(),()=>[]),locations:o(S(Ut).optional(),()=>[]),rawInput:o(c().optional(),()=>{}),rawOutput:o(c().optional(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Fo=b([l("high"),l("medium"),l("low")]),Wo=b([l("pending"),l("in_progress"),l("completed")]),rs=r({content:s(),priority:Fo,status:Wo,_meta:o(d(s(),c()).nullish(),()=>{})}),Bo=r({entries:O(S(rs),()=>[]),_meta:o(d(s(),c()).nullish(),()=>{})}),ye=s(),$o=r({planId:ye,entries:O(S(rs),()=>[]),_meta:o(d(s(),c()).nullish(),()=>{})}),Jo=r({planId:ye,uri:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),Vo=r({planId:ye,content:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),Ko=b([$o.and(r({type:l("items")})),Jo.and(r({type:l("file")})),Vo.and(r({type:l("markdown")}))]),Yo=r({plan:Ko,_meta:o(d(s(),c()).nullish(),()=>{})}),Qo=r({planId:ye,_meta:o(d(s(),c()).nullish(),()=>{})}),Zo=r({hint:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),Xo=Zo,er=r({name:s(),description:s(),input:o(Xo.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),nr=r({availableCommands:O(S(er),()=>[]),_meta:o(d(s(),c()).nullish(),()=>{})}),tr=r({currentModeId:xe,_meta:o(d(s(),c()).nullish(),()=>{})}),sr=r({configOptions:O(S(ee),()=>[]),_meta:o(d(s(),c()).nullish(),()=>{})}),ir=r({title:o(s().nullish(),()=>{}),updatedAt:o(s().nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),or=r({amount:x(),currency:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),rr=r({used:x(),size:x(),cost:o(or.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),as=s(),ar=b([l("in_progress"),l("completed"),l("failed"),l("cancelled"),s()]),cr=r({compactionId:as,status:ar,summary:o(S(ue).nullish(),()=>{}),error:o(s().nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),dr=r({compactionId:as,content:ue,_meta:o(d(s(),c()).nullish(),()=>{})}),ur=b([Ke.and(r({sessionUpdate:l("user_message_chunk")})),Ke.and(r({sessionUpdate:l("agent_message_chunk")})),Ke.and(r({sessionUpdate:l("agent_thought_chunk")})),Uo.and(r({sessionUpdate:l("tool_call")})),Ft.and(r({sessionUpdate:l("tool_call_update")})),Bo.and(r({sessionUpdate:l("plan")})),Yo.and(r({sessionUpdate:l("plan_update")})),Qo.and(r({sessionUpdate:l("plan_removed")})),nr.and(r({sessionUpdate:l("available_commands_update")})),tr.and(r({sessionUpdate:l("current_mode_update")})),sr.and(r({sessionUpdate:l("config_option_update")})),ir.and(r({sessionUpdate:l("session_info_update")})),rr.and(r({sessionUpdate:l("usage_update")})),cr.and(r({sessionUpdate:l("compaction_update")})),dr.and(r({sessionUpdate:l("compaction_summary_chunk")}))]),Te=r({sessionId:E,update:ur,_meta:o(d(s(),c()).nullish(),()=>{})}),_n=r({elicitationId:Vt,_meta:o(d(s(),c()).nullish(),()=>{})}),cs=r({connectionId:Ee,method:s(),params:o(d(s(),c()).nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),ds=c(),bc=r({method:s(),params:b([Te,_n,cs,ds]).nullish()}),lr=r({readTextFile:o(v().optional().default(!1),()=>!1),writeTextFile:o(v().optional().default(!1),()=>!1),_meta:o(d(s(),c()).nullish(),()=>{})}),hr=d(s(),c()),pr=r({_meta:o(d(s(),c()).nullish(),()=>{})}),fr=r({boolean:o(pr.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),zr=r({compaction:o(hr.nullish(),()=>{}),configOptions:o(fr.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),mr=r({_meta:o(d(s(),c()).nullish(),()=>{})}),gr=r({terminal:o(v().optional().default(!1),()=>!1),_meta:o(d(s(),c()).nullish(),()=>{})}),br=r({_meta:o(d(s(),c()).nullish(),()=>{})}),_r=r({_meta:o(d(s(),c()).nullish(),()=>{})}),wr=r({form:o(br.nullish(),()=>{}),url:o(_r.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Sr=r({_meta:o(d(s(),c()).nullish(),()=>{})}),Er=r({_meta:o(d(s(),c()).nullish(),()=>{})}),xr=r({_meta:o(d(s(),c()).nullish(),()=>{})}),Rr=r({jump:o(Sr.nullish(),()=>{}),rename:o(Er.nullish(),()=>{}),searchAndReplace:o(xr.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),yr=r({fs:o(lr.optional().default({readTextFile:!1,writeTextFile:!1}),()=>({readTextFile:!1,writeTextFile:!1})),terminal:o(v().optional().default(!1),()=>!1),session:o(zr.nullish(),()=>{}),plan:o(mr.nullish(),()=>{}),auth:o(gr.optional().default({terminal:!1}),()=>({terminal:!1})),elicitation:o(wr.nullish(),()=>{}),nes:o(Rr.nullish(),()=>{}),positionEncodings:o(S(Xt).optional(),()=>[]),_meta:o(d(s(),c()).nullish(),()=>{})}),wn=r({protocolVersion:Zt,clientCapabilities:o(yr.optional().default({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}}),()=>({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}})),clientInfo:o(es.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Sn=r({methodId:zn,_meta:o(d(s(),c()).nullish(),()=>{})}),En=r({_meta:o(d(s(),c()).nullish(),()=>{})}),xn=r({providerId:mn,apiType:gn,baseUrl:s(),headers:d(s(),s()).optional(),_meta:o(d(s(),c()).nullish(),()=>{})}),Rn=r({providerId:mn,_meta:o(d(s(),c()).nullish(),()=>{})}),yn=r({_meta:o(d(s(),c()).nullish(),()=>{})}),us=r({name:s(),value:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),Tr=r({name:s(),url:s(),headers:T(us),_meta:o(d(s(),c()).nullish(),()=>{})}),Cr=r({name:s(),url:s(),headers:T(us),_meta:o(d(s(),c()).nullish(),()=>{})}),kr=r({name:s(),serverId:Kt,_meta:o(d(s(),c()).nullish(),()=>{})}),vr=r({name:s(),command:s(),args:T(s()),env:T(Bt),_meta:o(d(s(),c()).nullish(),()=>{})}),Ce=b([Tr.and(r({type:l("http")})),Cr.and(r({type:l("sse")})),kr.and(r({type:l("acp")})),vr]),Tn=r({cwd:s(),additionalDirectories:o(S(s()).optional(),()=>[]),mcpServers:O(S(Ce),()=>[]),_meta:o(d(s(),c()).nullish(),()=>{})}),Cn=r({mcpServers:O(S(Ce),()=>[]),cwd:s(),additionalDirectories:o(S(s()).optional(),()=>[]),sessionId:E,_meta:o(d(s(),c()).nullish(),()=>{})}),kn=r({cwd:s().nullish(),cursor:s().nullish(),_meta:o(d(s(),c()).nullish(),()=>{})}),vn=r({sessionId:E,_meta:o(d(s(),c()).nullish(),()=>{})}),Nn=r({sessionId:E,cwd:s(),additionalDirectories:o(S(s()).optional(),()=>[]),mcpServers:o(S(Ce).optional(),()=>[]),_meta:o(d(s(),c()).nullish(),()=>{})}),An=r({sessionId:E,cwd:s(),additionalDirectories:o(S(s()).optional(),()=>[]),mcpServers:o(S(Ce).optional(),()=>[]),_meta:o(d(s(),c()).nullish(),()=>{})}),In=r({sessionId:E,_meta:o(d(s(),c()).nullish(),()=>{})}),Mn=r({sessionId:E,modeId:xe,_meta:o(d(s(),c()).nullish(),()=>{})}),jn=B(b([r({value:v(),type:l("boolean")}),r({value:bn})]),r({sessionId:E,configId:ns,_meta:o(d(s(),c()).nullish(),()=>{})})),On=r({sessionId:E,prompt:T(ue),_meta:o(d(s(),c()).nullish(),()=>{})}),Nr=r({uri:s(),name:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),Ar=r({name:s(),owner:s(),remoteUrl:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),Dn=r({workspaceUri:o(s().nullish(),()=>{}),workspaceFolders:T(Nr).nullish(),repository:o(Ar.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Ir=b([l("automatic"),l("diagnostic"),l("manual")]),Mr=r({uri:s(),languageId:s(),text:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),jr=r({startLine:A().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}),endLine:A().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}),text:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),Or=r({uri:s(),excerpts:T(jr),_meta:o(d(s(),c()).nullish(),()=>{})}),Dr=r({uri:s(),diff:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),qr=r({action:s(),uri:s(),position:J,timestampMs:x(),_meta:o(d(s(),c()).nullish(),()=>{})}),Hr=r({uri:s(),languageId:s(),visibleRange:o(te.nullish(),()=>{}),lastFocusedMs:o(x().nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Pr=b([l("error"),l("warning"),l("information"),l("hint")]),Lr=r({uri:s(),range:te,severity:Pr,message:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),Gr=r({recentFiles:T(Mr).nullish(),relatedSnippets:T(Or).nullish(),editHistory:T(Dr).nullish(),userActions:T(qr).nullish(),openFiles:T(Hr).nullish(),diagnostics:T(Lr).nullish(),_meta:o(d(s(),c()).nullish(),()=>{})}),qn=r({sessionId:E,uri:s(),version:x(),position:J,selection:te.nullish(),triggerKind:Ir,context:Gr.nullish(),_meta:o(d(s(),c()).nullish(),()=>{})}),Hn=r({sessionId:E,_meta:o(d(s(),c()).nullish(),()=>{})}),_c=r({id:$,method:s(),params:b([wn,Sn,En,xn,Rn,yn,Tn,Cn,kn,vn,Nn,An,In,Mn,jn,On,Dn,qn,Hn,Yt,Qt]).nullish()}),Ur=r({_meta:o(d(s(),c()).nullish(),()=>{})}),Fr=r({content:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),Wr=r({optionId:Wt,_meta:o(d(s(),c()).nullish(),()=>{})}),Br=b([r({outcome:l("cancelled")}),Wr.and(r({outcome:l("selected")}))]),$r=r({outcome:Br,_meta:o(d(s(),c()).nullish(),()=>{})}),Jr=r({terminalId:X,_meta:o(d(s(),c()).nullish(),()=>{})}),Vr=r({exitCode:o(A().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),signal:o(s().nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Kr=r({output:s(),truncated:v(),exitStatus:o(Vr.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Yr=r({_meta:o(d(s(),c()).nullish(),()=>{})}),Qr=r({exitCode:o(A().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),signal:o(s().nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Zr=r({_meta:o(d(s(),c()).nullish(),()=>{})}),Xr=b([s(),x(),x(),v(),T(s())]),Pn=r({content:d(s(),Xr).nullish()}),ea=ce(B(b([Pn.and(r({action:l("accept")})),r({action:l("decline")}),r({action:l("cancel")}),ae(r({action:s()}),"action",["accept","cancel","decline"])]),r({_meta:o(d(s(),c()).nullish(),()=>{})})),"action",["accept","cancel","decline"]),na=r({connectionId:Ee,_meta:o(d(s(),c()).nullish(),()=>{})}),ta=r({_meta:o(d(s(),c()).nullish(),()=>{})}),wc=b([r({id:$,result:b([Ur,Fr,$r,Jr,Kr,Yr,Qr,Zr,ea,na,ta,is,ss])}),r({id:$,error:os})]),Ln=r({sessionId:E,_meta:o(d(s(),c()).nullish(),()=>{})}),Gn=r({sessionId:E,uri:s(),languageId:s(),version:x(),text:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),sa=r({range:te.nullish(),text:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),Un=r({sessionId:E,uri:s(),version:x(),contentChanges:O(S(sa),()=>[]),_meta:o(d(s(),c()).nullish(),()=>{})}),Fn=r({sessionId:E,uri:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),Wn=r({sessionId:E,uri:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),Bn=r({sessionId:E,uri:s(),version:x(),position:J,visibleRange:te,_meta:o(d(s(),c()).nullish(),()=>{})}),$n=r({sessionId:E,id:ne,_meta:o(d(s(),c()).nullish(),()=>{})}),ia=b([l("rejected"),l("ignored"),l("replaced"),l("cancelled")]),Jn=r({sessionId:E,id:ne,reason:o(ia.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Sc=r({method:s(),params:b([Ln,Gn,Un,Fn,Wn,Bn,$n,Jn,cs,ds]).nullish()}),Ec=r({requestId:$,_meta:o(d(s(),c()).nullish(),()=>{})});var hs="$/cancel_request";function P(t){return Qn(t)&&"id"in t&&typeof t.method=="string"&&Zn(t.id)}function V(t){if(!Qn(t)||"method"in t||!("id"in t)||!Zn(t.id))return!1;let e=Object.hasOwn(t,"result"),n=Object.hasOwn(t,"error");return e===n?!1:!n||aa(t.error)}function F(t){return Qn(t)&&!("id"in t)&&typeof t.method=="string"}function I(t){return typeof t=="object"&&t!==null}function Qn(t){return I(t)&&t.jsonrpc==="2.0"}function Zn(t){return t===null||typeof t=="string"||typeof t=="number"&&Number.isFinite(t)}function pe(t){return I(t)&&!("method"in t)&&("id"in t||"result"in t||"error"in t)}function oa(t){let e=!1,n=!1,i=!1,a=!1;for(let u of t)e||=P(u)||F(u),n||=V(u),I(u)&&(i||="method"in u,a||="result"in u||"error"in u);return e?!1:n?!0:a&&!i}function ra(t){if(!(!I(t)||!Zn(t.requestId)))return t.requestId}function aa(t){return I(t)&&typeof t.code=="number"&&Number.isInteger(t.code)&&typeof t.message=="string"}var D={yes(){return{handled:!0}},no(t,e=!1){return{handled:!1,message:t,retry:e}}};function Y(t){let e=Promise.reject(t);return e.catch(()=>{}),e}function ca(t){if(t instanceof Error||typeof t=="object"&&t!=null&&"message"in t&&typeof t.message=="string")return t.message}function da(t){return typeof t=="object"&&t!==null&&"name"in t&&t.name==="ZodError"&&"issues"in t&&Array.isArray(t.issues)&&"format"in t&&typeof t.format=="function"}function ps(t){if(t instanceof w)return t.toResult();if(da(t))return w.invalidParams(t.format()).toResult();let e=ca(t);try{return w.internalError(e?JSON.parse(e):{}).toResult()}catch{return w.internalError({details:e}).toResult()}}function ua(t){return t instanceof w&&t.code===-32800?t:w.requestCancelled(t)}function la(t,e){let n=ha(t,e);return n?n.toResult():ps(t)}function ha(t,e){if(!(!e.aborted||!pa(t)))return ua(e.reason)}function pa(t){if(typeof t!="object"||t===null)return!1;let e=t;return e.name==="AbortError"||e.code==="ABORT_ERR"}var Vn=class{id;sendResult;signal;finishRequest;didRespond=!1;constructor(e,n,i=new AbortController().signal,a){this.id=e,this.sendResult=n,this.signal=i,this.finishRequest=a}get responded(){return this.didRespond}respond(e){return this.respondWithResult({result:e??null})}respondWithError(e){let n=e instanceof w?e.toErrorResponse():e;return this.respondWithResult({error:n})}respondWithResult(e){return this.didRespond?Y(new Error("JSON-RPC request already responded")):(this.didRespond=!0,this.sendResult(e).finally(()=>{this.finishRequest?.()}))}},fa=new WeakMap;var se=class{disposeHandler;active=!0;constructor(e){this.disposeHandler=e}dispose(){this.active&&(this.active=!1,this.disposeHandler())}[Symbol.dispose](){this.dispose()}runIndefinitely(){return this}},Kn=class{connection;constructor(e){this.connection=e}sendRequest(e,n,i,a){return this.connection.sendRequest(e,n,i,a)}sendNotification(e,n){return this.connection.sendNotification(e,n)}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}},ie=class{pendingResponses=new Map;incomingRequests=new Map;nextRequestId=0;staticHandlers=[];dynamicHandlers=new Set;stream;writeQueue=Promise.resolve();abortController=new AbortController;closedPromise;retryQueue=[];context=new Kn(this);receiveReader;allowBatches=!0;constructor(e,n,i,a){if(typeof e=="function"){let f=e,g=n,m=i;this.initialize(m,[...a?.handlers??[],this.legacyHandler(f,g)],a);return}let u=e,p=n,z=i;this.initialize(u,[...z?.handlers??[],...p],z)}static builder(){return new Yn}runUntil(e){let n=!1,i=Promise.resolve().then(()=>e(this.context)).finally(()=>{n=!0}),a=this.closed.then(()=>{if(n)return new Promise(()=>{});throw this.closedReason()});return Promise.race([i,a]).finally(()=>{n=!0,this.close()})}addDynamicHandler(e){if(this.dynamicHandlers.add(e),this.retryQueue.length>0)for(let n of this.retryQueue.splice(0))this.processIncomingMessage(n).catch(i=>this.close(i));return new se(()=>{this.dynamicHandlers.delete(e)})}get signal(){return this.abortController.signal}get closed(){return this.closedPromise}getContext(){return this.context}sendRequest(e,n,i,a={}){if(this.abortController.signal.aborted)return Y(this.closedReason());let u=this.prepareRequest(e,n,i,a);return this.sendWireMessage(u.message).catch(()=>{}),a.cancellationSignal?.aborted&&u.cancel(),u.response}sendBatch(e){if(this.abortController.signal.aborted)return Y(this.closedReason());if(!this.allowBatches)return Y(new TypeError("JSON-RPC batches are not supported on this connection"));if(e.length===0)return Y(new TypeError("JSON-RPC batch must contain at least one entry"));let n=[],i=[],a=[];for(let f of e){if(f.kind==="notification"){n.push({jsonrpc:"2.0",method:f.method,params:f.params}),a.push(Promise.resolve(void 0));continue}let g=this.prepareRequest(f.method,f.params,f.mapResponse,f.options);n.push(g.message),a.push(g.response),i.push({signal:f.options?.cancellationSignal,cancel:g.cancel})}let u=n,p=this.sendWireMessage(u);for(let f of i)f.signal?.aborted&&f.cancel();let z=Promise.all([p,...a]).then(([,...f])=>f);return z.catch(()=>{}),z}sendCancelRequest(e){return this.sendNotification(hs,{requestId:e})}sendNotification(e,n){return this.abortController.signal.aborted?Y(this.closedReason()):this.sendWireMessage({jsonrpc:"2.0",method:e,params:n})}prepareRequest(e,n,i,a={}){let u=this.nextRequestId++,p=()=>{},z=new Promise((f,g)=>{let m={resolve:y=>{try{f(i?i(y):y)}catch(C){g(C)}},reject:g};p=()=>{m.cancellationSent||(m.cancellationSent=!0,m.cleanup?.(),this.sendCancelRequest(u).catch(()=>{}))},a.cancellationSignal?.addEventListener("abort",p,{once:!0}),m.cleanup=()=>{a.cancellationSignal?.removeEventListener("abort",p)},this.pendingResponses.set(u,m)});return z.catch(()=>{}),{message:{jsonrpc:"2.0",id:u,method:e,params:n},response:z,cancel:()=>p()}}close(e){if(this.abortController.signal.aborted)return;let n=e??new Error("ACP connection closed");this.abortController.abort(n);for(let i of this.pendingResponses.values())i.cleanup?.(),i.reject(n);this.pendingResponses.clear();for(let i of this.incomingRequests.values())i.abort(n);this.incomingRequests.clear(),this.receiveReader?.cancel(n).catch(()=>{})}initialize(e,n,i){this.stream=e,this.staticHandlers=n,this.allowBatches=i?.allowBatches??!0,this.closedPromise=new Promise(a=>{this.abortController.signal.addEventListener("abort",()=>a())}),this.receive()}legacyHandler(e,n){return{handleMessage:async(i,a)=>{if(i.kind==="request"){let u=await e(i.method,i.params,a);await i.responder.respond(u)}else await n(i.method,i.params,a);return D.yes()}}}async receive(){let e;try{let n=this.stream.readable.getReader();this.receiveReader=n;try{for(;!this.abortController.signal.aborted;){let{value:i,done:a}=await n.read();if(this.abortController.signal.aborted||a)break;this.receiveWireMessage(i)}}finally{this.receiveReader===n&&(this.receiveReader=void 0),n.releaseLock()}}catch(n){e=n}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(!P(e)&&!F(e)&&!pe(e)){this.sendWireMessage(L(w.invalidRequest(e))).catch(()=>{});return}this.receiveMessage(e)}receiveBatch(e){if(e.length===0){this.sendWireMessage(L(w.invalidRequest(e))).catch(()=>{});return}let n=oa(e),a=n?0:e.reduce((m,y)=>m+(F(y)?0:1),0),u=e.reduce((m,y)=>m+(F(y)?1:0),0),p=!1,z=[],f=async()=>{p||a!==0||u!==0||z.length===0||(p=!0,await this.sendWireMessage(z))},g=async m=>{z.push(m),a-=1,await f()};for(let m of e){if(n){pe(m)&&this.receiveMessage(m);continue}if(!P(m)&&!F(m)){g(L(w.invalidRequest(m))).catch(()=>{});continue}let y=this.receiveMessage(m,P(m)?g:void 0,e.length);F(m)&&y.finally(()=>{u-=1,f().catch(C=>this.close(C))})}}receiveMessage(e,n,i){return this.abortController.signal.aborted?Promise.resolve():I(e)?"method"in e?("id"in e||this.handleProtocolNotification(e),this.processIncomingMessage(this.toIncomingMessage(e,n,i)).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 n=e,i=!1;try{for(let a of[...this.staticHandlers,...this.dynamicHandlers.values()]){if(this.abortController.signal.aborted)return;let u=await a.handleMessage(n,this.context)??{handled:!0};if(u.handled)return;n=u.message??n,i=i||!!u.retry}i?this.retryQueue.push(n):n.kind==="request"&&await n.responder.respondWithError(w.methodNotFound(n.method))}catch(a){if(this.abortController.signal.aborted)return;if(n.kind==="request"&&!n.responder.responded)await n.responder.respondWithResult(la(a,n.responder.signal));else{let u=ps(a);"error"in u&&console.error("Error handling notification",e.raw,u.error)}}}toIncomingMessage(e,n,i){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)},p=new Vn(e.id,z=>{let f={jsonrpc:"2.0",id:e.id,...z};return n?n(f):this.sendWireMessage(f)},a.signal,u);return i!==void 0&&fa.set(p,i),{kind:"request",method:e.method,params:e.params,raw:e,signal:a.signal,responder:p}}return{kind:"notification",method:e.method,params:e.params,raw:e}}handleResponse(e){let n=this.pendingResponses.get(e.id);if(n)if(this.pendingResponses.delete(e.id),n.cleanup?.(),!V(e))n.reject(w.invalidRequest(e));else if("result"in e)n.resolve(e.result);else{let{code:i,message:a,data:u}=e.error;n.reject(new w(i,a,u))}else console.error("Got response to unknown request",e.id)}handleProtocolNotification(e){if(e.method!==hs)return;let n=ra(e.params);if(n===void 0)return;let i=this.incomingRequests.get(n);!i||i.signal.aborted||i.abort(w.requestCancelled({requestId:n}))}closedReason(){return this.abortController.signal.reason??new Error("ACP connection closed")}async sendWireMessage(e){return this.abortController.signal.aborted?Y(this.closedReason()):(this.writeQueue=this.writeQueue.then(async()=>{if(this.abortController.signal.aborted)throw this.closedReason();let n=this.stream.writable.getWriter();try{await n.write(e)}finally{n.releaseLock()}}).catch(n=>{throw this.close(n),n}),this.writeQueue)}},Yn=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(n,i)=>await e(n,i)??D.no(n),describe:()=>this.connectionName??"onReceiveMessage"})}onReceiveRequest(e,n,i){return this.withHandler({handleMessage:async(a,u)=>{if(a.kind!=="request"||a.method!==e)return D.no(a);let p=n(a.params);return await i(p,a.responder,u)??D.yes()},describe:()=>`${this.connectionName??"request"}:${e}`})}onReceiveNotification(e,n,i){return this.withHandler({handleMessage:async(a,u)=>{if(a.kind!=="notification"||a.method!==e)return D.no(a);let p=n(a.params);return await i(p,u)??D.yes()},describe:()=>`${this.connectionName??"notification"}:${e}`})}connect(e,n){return new ie(e,this.handlers,n)}connectWith(e,n,i){return this.connect(e,i).runUntil(n)}},w=class t extends Error{code;data;constructor(e,n,i){super(n),this.code=e,this.name="RequestError",this.data=i}static parseError(e,n){return new t(-32700,`Parse error${n?`: ${n}`:""}`,e)}static invalidRequest(e,n){return new t(-32600,`Invalid request${n?`: ${n}`:""}`,e)}static methodNotFound(e){return new t(-32601,`"Method not found": ${e}`,{method:e})}static invalidParams(e,n){return new t(-32602,`Invalid params${n?`: ${n}`:""}`,e)}static internalError(e,n){return new t(-32603,`Internal error${n?`: ${n}`:""}`,e)}static requestCancelled(e,n){return new t(-32800,`Request cancelled${n?`: ${n}`:""}`,e)}static authRequired(e,n){return new t(-32e3,`Authentication required${n?`: ${n}`:""}`,e)}static resourceNotFound(e){return new t(-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 L(t){return{jsonrpc:"2.0",id:null,error:t.toErrorResponse()}}var fe=class{#e=[];push(e){let n=[],i=0,a=e.indexOf(10,i);for(;a!==-1;)n.push(this.#n(e.subarray(i,a))),i=a+1,a=e.indexOf(10,i);return i<e.byteLength&&this.#e.push(i===0?e:new Uint8Array(e.subarray(i))),n}flush(){if(this.#e.length!==0)return this.#n(new Uint8Array(0))}#n(e){if(this.#e.length===0)return e;let n=e.byteLength;for(let u of this.#e)n+=u.byteLength;let i=new Uint8Array(n),a=0;for(let u of this.#e)i.set(u,a),a+=u.byteLength;return i.set(e,a),this.#e=[],i}};function fs(t,e){let n=new TextEncoder,i=new TextDecoder,a=!1,u,p=Promise.resolve(),z=m=>{let y=JSON.stringify(m)+`
|
|
5
|
+
`,C=p.then(async()=>{let k=t.getWriter();try{await k.write(n.encode(y))}finally{k.releaseLock()}});return p=C.catch(()=>{}),C},f=new ReadableStream({async start(m){let y=new fe,C=async M=>{let U=i.decode(M).trim();if(!U)return;let H;try{H=JSON.parse(U)}catch{await z(L(w.parseError()));return}I(H)||Array.isArray(H)?m.enqueue(H):await z(L(w.invalidRequest(H)))},k=e.getReader();u=k;try{for(;;){let{value:U,done:H}=await k.read();if(a)return;if(H)break;if(U){for(let We of y.push(U))if(await C(We),a)return}}if(a)return;let M=y.flush();M&&await C(M)}catch(M){if(a)return;m.error(M);return}finally{u===k&&(u=void 0),k.releaseLock()}a||m.close()},cancel(m){return a=!0,u?.cancel(m)}}),g=new WritableStream({write(m){return z(m)}});return{readable:f,writable:g}}var kc=hn.and(r({mode:l("form")})).and(r({message:s()})),vc=pn.and(r({mode:l("url")})).and(r({message:s()})),Nc=b([le,he]).and(r({message:s()})),Ac=rn.and(r({type:l("string")})),Ic=an.and(r({type:l("number")})),Mc=cn.and(r({type:l("integer")})),jc=dn.and(r({type:l("boolean")})),Oc=ln.and(r({type:l("array")})),Dc=un.and(r({type:l("string")}));var qc=Pn.and(r({action:l("accept")})),Hc=r({action:l("decline")}),Pc=r({action:l("cancel")});function bs(t,e){return fs(t,e)}function j(t){return t??{}}function _s(t){return typeof t=="object"&&t!==null&&"readable"in t&&"writable"in t}function ws(){let t=new TransformStream,e=new TransformStream;return[{readable:e.readable,writable:t.writable},{readable:t.readable,writable:e.writable}]}var q={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:Je.cancel_request}},Ss=Symbol("startActiveSession"),Ne=class{cx;currentRequestId;constructor(e,n){this.cx=e,this.currentRequestId=n}get requestId(){return this.currentRequestId}get connectionContext(){return this.cx}sendRequest(e,n,i,a){return this.cx.sendRequest(e,n,i,a)}sendNotification(e,n){return this.cx.sendNotification(e,n)}addDynamicHandler(e){return this.cx.addDynamicHandler(e)}},ze=class t extends Ne{constructor(e,n){super(e,n)}static create(e,n){return new t(e,n)}request(e,n,i){let a=rt[e];return this.sendRequest(e,n,a?.mapResponse,i)}notify(e,n){return this.sendNotification(e,n)}},me=class t extends Ne{constructor(e,n){super(e,n)}static create(e,n){return new t(e,n)}[Ss](e,n){return this.sendRequest(h.session_new,e,i=>this.attachSession(i),n)}buildSession(e){return typeof e=="string"?Ie.create(this,{cwd:e,mcpServers:[]}):Ie.create(this,e)}attachSession(e){let n=new nt,i=this.connectionContext.signal,a=()=>{n.fail(i.reason??new Error("ACP connection closed"))};i.aborted?a():i.addEventListener("abort",a);let u=ks(this.connectionContext).attach(e,n),p=new se(()=>{i.removeEventListener("abort",a)});return tt.create(this,e,n,[u,p])}request(e,n,i){let a=Cs[e];return this.sendRequest(e,n,a?.mapResponse,i)}notify(e,n){return this.sendNotification(e,n)}},Ae=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)}},Xn=class extends Ae{connectHandlers;client;didStartConnectHandlers=!1;constructor(e,n=[]){super(e),this.connectHandlers=n,this.client=ze.create(e.getContext())}startConnectHandlers(){this.didStartConnectHandlers||(this.didStartConnectHandlers=!0,Oe(this,this.connectHandlers))}},et=class extends Ae{connectHandlers;agent;didStartConnectHandlers=!1;constructor(e,n=[]){super(e),this.connectHandlers=n,this.agent=me.create(e.getContext())}startConnectHandlers(){this.didStartConnectHandlers||(this.didStartConnectHandlers=!0,Oe(this,this.connectHandlers))}};function Es(t,e=[]){return new Xn(t,e)}function xs(t,e=[]){return new et(t,e)}var nt=class{values=[];waiters=[];failed=!1;failure;enqueue(e){if(this.failed)return;let n=this.waiters.shift();n?n.resolve(e):this.values.push({kind:"value",value:e})}reject(e){if(!this.failed){if(this.waiters.length>0){for(let n of this.waiters.splice(0))n.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 n of this.waiters.splice(0))n.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,n)=>{this.waiters.push({resolve:e,reject:n})})}};function zs(t){return{...t,additionalDirectories:t.additionalDirectories?[...t.additionalDirectories]:void 0,mcpServers:[...t.mcpServers]}}var Ie=class t{cx;request;constructor(e,n){this.cx=e,this.request=zs(n)}static create(e,n){return new t(e,n)}toRequest(){return zs(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[Ss](this.toRequest(),e)}async withSession(e){let n=await this.start();try{return await e(n)}finally{n.dispose()}}},tt=class t{cx;sessionResponse;updates;registrations;constructor(e,n,i,a){this.cx=e,this.sessionResponse=n,this.updates=i,this.registrations=a}static create(e,n,i,a){return new t(e,n,i,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,n){this.updates.clearErrors();let i=this.cx.request(h.session_prompt,{sessionId:this.sessionId,prompt:this.promptBlocks(e)},n);return i.then(a=>{this.updates.enqueue({kind:"stop",response:a,stopReason:a.stopReason})},a=>{this.updates.reject(a)}),i}nextUpdate(){return this.updates.next()}async readText(){let e="";for(;;){let n=await this.nextUpdate();if(n.kind==="stop")return e;let{update:i}=n;i.sessionUpdate==="agent_message_chunk"&&i.content.type==="text"&&(e+=i.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 Rs(t,e){return t?typeof t=="function"?t(e):t.parse(e):e}function R(t,e,n){return{method:t,params:e,mapResponse:n}}function G(t,e){return{method:t,params:e}}function ys(t,e,n,i){t.onReceiveRequest(e.method,a=>Rs(e.params,a),async(a,u,p)=>{let z=await i(n(a,p,u.signal,u.id));await u.respond(e.mapResponse?e.mapResponse(z):z)})}function Ts(t,e,n,i){t.onReceiveNotification(e.method,a=>Rs(e.params,a),(a,u)=>i(n(a,u,u.signal)))}function je(t){let e={};for(let n of Object.values(t))e[n.method]=n;return e}var za={initialize:R(h.initialize,wn),newSession:R(h.session_new,Tn),loadSession:R(h.session_load,Cn,j),unstable_forkSession:R(h.session_fork,Nn),listSessions:R(h.session_list,kn),deleteSession:R(h.session_delete,vn,j),resumeSession:R(h.session_resume,An),closeSession:R(h.session_close,In,j),setSessionMode:R(h.session_set_mode,Mn,j),setSessionConfigOption:R(h.session_set_config_option,jn),authenticate:R(h.authenticate,Sn,j),unstable_listProviders:R(h.providers_list,En),unstable_setProvider:R(h.providers_set,xn,j),unstable_disableProvider:R(h.providers_disable,Rn,j),logout:R(h.logout,yn,j),prompt:R(h.session_prompt,On),unstable_startNes:R(h.nes_start,Dn),unstable_suggestNes:R(h.nes_suggest,qn),unstable_closeNes:R(h.nes_close,Hn,j)},ma={cancel:G(h.session_cancel,Ln),unstable_didOpenDocument:G(h.document_did_open,Gn),unstable_didChangeDocument:G(h.document_did_change,Un),unstable_didCloseDocument:G(h.document_did_close,Fn),unstable_didSaveDocument:G(h.document_did_save,Wn),unstable_didFocusDocument:G(h.document_did_focus,Bn),unstable_acceptNes:G(h.nes_accept,$n),unstable_rejectNes:G(h.nes_reject,Jn)},ga={requestPermission:R(_.session_request_permission,Xe),writeTextFile:R(_.fs_write_text_file,Ye,j),readTextFile:R(_.fs_read_text_file,Qe),createTerminal:R(_.terminal_create,en),terminalOutput:R(_.terminal_output,nn),releaseTerminal:R(_.terminal_release,tn,j),waitForTerminalExit:R(_.terminal_wait_for_exit,sn),killTerminal:R(_.terminal_kill,on,j),createElicitation:R(_.elicitation_create,fn)},ba={sessionUpdate:G(_.session_update,Te),completeElicitation:G(_.elicitation_complete,_n)},Cs=je(za),_a=je(ma),rt=je(ga),wa=je(ba);function Sa(t,e,n,i){return{params:t,requestId:i,signal:n,client:e}}function Ea(t,e,n){return{params:t,signal:n,client:e}}function xa(t,e,n,i){return{params:t,requestId:i,signal:n,agent:e}}function Ra(t,e,n){return{params:t,signal:n,agent:e}}var st=class{activeSessions=new Map;handleMessage(e){if(e.kind!=="notification"||e.method!==_.session_update)return D.no(e);let n=Te.parse(e.params),i={kind:"session_update",notification:n,update:n.update},a=this.activeSessions.get(n.sessionId);if(a&&a.size>0)for(let u of a)u.enqueue(i);return D.no(e)}attach(e,n){let i=this.activeSessions.get(e.sessionId)??new Set;return i.add(n),this.activeSessions.set(e.sessionId,i),new se(()=>{i.delete(n),i.size===0&&this.activeSessions.delete(e.sessionId)})}},ms=new WeakMap;function ks(t){let e=ms.get(t);return e||(e=new st,ms.set(t,e)),e}function Oe(t,e){for(let n of e){let i;try{i=n(t)}catch(a){throw t.close(a),a}Promise.resolve(i).catch(a=>{t.close(a)})}}var Q=Symbol("appBuilder"),ke=Symbol("runAgentConnectHandlers"),ve=Symbol("runClientConnectHandlers"),ge={allowBatches:!1};function at(t){return new it(t)}var it=class{builder=ie.builder();connectHandlers=[];constructor(e={}){e.name&&this.builder.name(e.name)}[Q](){return this.builder}[ke](e){Oe(e,this.connectHandlers)}connect(e,n={}){return this.connectConnection(e,n).connection}connectWith(e,n){let{rawConnection:i,connection:a}=this.connectConnection(e);return i.runUntil(()=>n(a.client))}onConnect(e){return this.connectHandlers.push(e),this}onRequest(e,n,i){if(i)return this.request({method:e,params:n},i);let a=Cs[e];if(!a)throw new Error(`Unknown ACP request method '${e}'. Pass a params parser for custom methods.`);return this.request(a,n)}onNotification(e,n,i){if(i)return this.notification({method:e,params:n},i);let a=_a[e];if(!a)throw new Error(`Unknown ACP notification method '${e}'. Pass a params parser for custom methods.`);return this.notification(a,n)}request(e,n){return ys(this.builder,e,(i,a,u,p)=>Sa(i,ze.create(a,p),u,p),n),this}notification(e,n){return Ts(this.builder,e,(i,a,u)=>Ea(i,ze.create(a),u),n),this}connectConnection(e,n={}){if(_s(e)){let f=this.openStreamConnection(e);return n.deferConnectHandlers||this[ke](f.connection),f}let[i,a]=ws(),u=e[Q]().connect(a,ge),p=xs(u),z=this.openStreamConnection(i);z.rawConnection.closed.then(()=>p.close()),u.closed.then(()=>z.connection.close());try{e[ve](p),this[ke](z.connection)}catch(f){throw p.close(f),z.connection.close(f),f}return z}openStreamConnection(e){let n=this.builder.connect(e,ge);return{rawConnection:n,connection:Es(n,this.connectHandlers)}}};var gs=class{builder=ie.builder();connectHandlers=[];constructor(e={}){e.name&&this.builder.name(e.name),this.builder.withHandler({handleMessage:(n,i)=>ks(i).handleMessage(n),describe:()=>"client-session-update-router"})}[Q](){return this.builder}[ve](e){Oe(e,this.connectHandlers)}connect(e){return this.connectConnection(e).connection}connectWith(e,n){let{rawConnection:i,connection:a}=this.connectConnection(e);return i.runUntil(()=>n(a.agent))}onConnect(e){return this.connectHandlers.push(e),this}onRequest(e,n,i){if(i)return this.request({method:e,params:n},i);let a=rt[e];if(!a)throw new Error(`Unknown ACP request method '${e}'. Pass a params parser for custom methods.`);return this.request(a,n)}onNotification(e,n,i){if(i)return this.notification({method:e,params:n},i);let a=wa[e];if(!a)throw new Error(`Unknown ACP notification method '${e}'. Pass a params parser for custom methods.`);return this.notification(a,n)}request(e,n){return ys(this.builder,e,(i,a,u,p)=>xa(i,me.create(a,p),u,p),n),this}notification(e,n){return Ts(this.builder,e,(i,a,u)=>Ra(i,me.create(a),u),n),this}connectConnection(e){if(_s(e)){let z=this.openStreamConnection(e);return this[ve](z.connection),z}let[n,i]=ws(),a=e[Q]().connect(i,ge),u=Es(a),p=this.openStreamConnection(n);p.rawConnection.closed.then(()=>u.close()),a.closed.then(()=>p.connection.close());try{e[ke](u),this[ve](p.connection)}catch(z){throw u.close(z),p.connection.close(z),z}return p}openStreamConnection(e){let n=this.builder.connect(e,ge);return{rawConnection:n,connection:xs(n,this.connectHandlers)}}},ya=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]),Ta=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]),Jc=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]),Vc=new Set([_.session_update,_.elicitation_complete]);function Ca(t){let e=at().onRequest(h.initialize,n=>t.initialize(n.params)).onRequest(h.session_new,n=>t.newSession(n.params)).onRequest(h.authenticate,async n=>await t.authenticate(n.params)??{}).onRequest(h.session_prompt,n=>t.prompt(n.params)).onNotification(h.session_cancel,n=>t.cancel(n.params));return t.loadSession&&e.onRequest(h.session_load,n=>t.loadSession(n.params)),t.listSessions&&e.onRequest(h.session_list,n=>t.listSessions(n.params)),t.deleteSession&&e.onRequest(h.session_delete,async n=>await t.deleteSession(n.params)??{}),t.unstable_forkSession&&e.onRequest(h.session_fork,n=>t.unstable_forkSession(n.params)),t.resumeSession&&e.onRequest(h.session_resume,n=>t.resumeSession(n.params)),t.closeSession&&e.onRequest(h.session_close,async n=>await t.closeSession(n.params)??{}),t.setSessionMode&&e.onRequest(h.session_set_mode,async n=>await t.setSessionMode(n.params)??{}),t.setSessionConfigOption&&e.onRequest(h.session_set_config_option,n=>t.setSessionConfigOption(n.params)),t.unstable_listProviders&&e.onRequest(h.providers_list,n=>t.unstable_listProviders(n.params)),t.unstable_setProvider&&e.onRequest(h.providers_set,async n=>await t.unstable_setProvider(n.params)??{}),t.unstable_disableProvider&&e.onRequest(h.providers_disable,async n=>await t.unstable_disableProvider(n.params)??{}),t.logout&&e.onRequest(h.logout,async n=>await t.logout(n.params)??{}),t.unstable_startNes&&e.onRequest(h.nes_start,n=>t.unstable_startNes(n.params)),t.unstable_suggestNes&&e.onRequest(h.nes_suggest,n=>t.unstable_suggestNes(n.params)),t.unstable_closeNes&&e.onRequest(h.nes_close,async n=>await t.unstable_closeNes(n.params)??{}),t.unstable_didOpenDocument&&e.onNotification(h.document_did_open,n=>t.unstable_didOpenDocument(n.params)),t.unstable_didChangeDocument&&e.onNotification(h.document_did_change,n=>t.unstable_didChangeDocument(n.params)),t.unstable_didCloseDocument&&e.onNotification(h.document_did_close,n=>t.unstable_didCloseDocument(n.params)),t.unstable_didSaveDocument&&e.onNotification(h.document_did_save,n=>t.unstable_didSaveDocument(n.params)),t.unstable_didFocusDocument&&e.onNotification(h.document_did_focus,n=>t.unstable_didFocusDocument(n.params)),t.unstable_acceptNes&&e.onNotification(h.nes_accept,n=>t.unstable_acceptNes(n.params)),t.unstable_rejectNes&&e.onNotification(h.nes_reject,n=>t.unstable_rejectNes(n.params)),t.extMethod&&e[Q]().withHandler({handleMessage:async n=>n.kind!=="request"||ya.has(n.method)?D.no(n):(await n.responder.respond(await t.extMethod(n.method,n.params)),D.yes()),describe:()=>"legacy-agent-extension-request"}),t.extNotification&&e[Q]().withHandler({handleMessage:async n=>n.kind!=="notification"||Ta.has(n.method)?D.no(n):(await t.extNotification(n.method,n.params),D.yes()),describe:()=>"legacy-agent-extension-notification"}),e}var Me=class{connection;constructor(e,n){this.connection=Ca(e(this))[Q]().connect(n,ge)}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,j)}createTerminal(e){return this.connection.sendRequest(_.terminal_create,e,n=>ot.create(n.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,n,i){let a=rt[e];return this.connection.sendRequest(e,n,a?.mapResponse,i)}notify(e,n){return this.connection.sendNotification(e,n)}extMethod(e,n){return this.request(e,n)}extNotification(e,n){return this.notify(e,n)}get signal(){return this.connection.signal}get closed(){return this.connection.closed}},ot=class t{id;sessionId;connection;constructor(e,n,i){this.id=e,this.sessionId=n,this.connection=i}static create(e,n,i){return new t(e,n,i)}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},j)}release(){return this.connection.sendRequest(_.terminal_release,{sessionId:this.sessionId,terminalId:this.id},j)}async[Symbol.asyncDispose](){await this.release()}};var js={};Se(js,{YukinoAcpAgent:()=>He,createYukinoAcpApp:()=>be});import{existsSync as Aa}from"fs";import{isAbsolute as Ia}from"path";var As={};Se(As,{addUsage:()=>ut,agentEventToUpdate:()=>dt,emptyUsage:()=>lt,historyNotifications:()=>pt,promptToText:()=>ct,stopReason:()=>ht,toolKind:()=>De,toolLocations:()=>qe});import{isAbsolute as va,resolve as Na}from"path";function ct(t){let e=[];for(let i of t)switch(i.type){case"text":i.text.trim()&&e.push(i.text);break;case"resource_link":e.push(`Resource: ${i.name} (${i.uri})`);break;case"resource":if("text"in i.resource){e.push(`Resource: ${i.resource.uri}
|
|
6
|
+
${i.resource.text}`);break}throw w.invalidParams(void 0,"Binary resources are not supported.");case"image":throw w.invalidParams(void 0,"Image prompts are not supported.");case"audio":throw w.invalidParams(void 0,"Audio prompts are not supported.")}let n=e.join(`
|
|
7
|
+
|
|
8
|
+
`).trim();if(!n)throw w.invalidParams(void 0,"Prompt must contain text or a resource link.");return n}function De(t){return/^(ReadFile)$/u.test(t)?"read":/^(WriteFile|EditFile)$/u.test(t)?"edit":/^(Glob|Grep|ToolSearch)$/u.test(t)?"search":/^(Bash|PowerShell|ComputerUse)$/u.test(t)?"execute":/^(Agent|TaskCreate|TaskGet|TaskList|TaskUpdate|TaskStop)$/u.test(t)?"think":t==="ExitPlanMode"?"switch_mode":"other"}function qe(t,e){let n=$e(t,"file_path")||$e(t,"path");if(n)return[{path:va(n)?n:Na(e,n)}]}function vs(t,e,n,i){return{sessionUpdate:"tool_call",toolCallId:e,title:t,kind:De(t),status:"pending",rawInput:n,locations:qe(n,i)}}function Ns(t,e,n,i){return{sessionUpdate:"tool_call_update",toolCallId:t,status:n?"failed":"completed",content:e?[{type:"content",content:{type:"text",text:e}}]:void 0,rawOutput:{output:e,isError:n,...i===void 0?{}:{elapsed:i}}}}function dt(t,e,n){switch(t.type){case"stream_text":return{sessionUpdate:"agent_message_chunk",content:{type:"text",text:t.text}};case"thinking_text":return{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:t.text}};case"tool_use":return vs(t.toolName,t.toolId,t.args,e);case"tool_result":return Ns(t.toolId,t.output,t.isError,t.elapsed);case"usage":return{sessionUpdate:"usage_update",used:t.usage.inputTokens+t.usage.cacheReadInputTokens+t.usage.cacheCreationInputTokens,size:n};default:return null}}function ut(t,e){let n=t.inputTokens+e.usage.inputTokens,i=t.outputTokens+e.usage.outputTokens,a=(t.cachedReadTokens??0)+e.usage.cacheReadInputTokens,u=(t.cachedWriteTokens??0)+e.usage.cacheCreationInputTokens;return{inputTokens:n,outputTokens:i,cachedReadTokens:a,cachedWriteTokens:u,totalTokens:n+i+a+u}}function lt(){return{totalTokens:0,inputTokens:0,outputTokens:0,cachedReadTokens:0,cachedWriteTokens:0}}function ht(t){switch(t){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*pt(t,e,n){for(let i of e){if(i.type===kt||i.role!=="user"&&i.role!=="assistant")continue;let a=Be(i.content);a&&(yield{sessionId:t,update:{sessionUpdate:i.role==="assistant"?"agent_message_chunk":"user_message_chunk",content:{type:"text",text:a}}});for(let u of i.tool_uses??[])yield{sessionId:t,update:vs(u.tool_name,u.tool_use_id,u.arguments??{},n)};for(let u of i.tool_results??[]){let p=Be(u.content);yield{sessionId:t,update:Ns(u.tool_use_id,p,u.is_error??!1)}}}}var Ma=/^[a-z0-9]+-[a-f0-9]{8}$/u;async function ja(t,e){let n=yt(Tt(),t),i=n.providers[0];if(!i)throw w.internalError(void 0,"No provider configured.");let a=await Dt({provider:i,workDir:t,hooks:n.hooks,mcpServers:n.mcp_servers,enableCoordinatorMode:n.enable_coordinator_mode??!1,forkDisabled:!Rt(n),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 Ms(t){if(!Ia(t))throw w.invalidParams(void 0,"Session cwd must be absolute.")}function ft(t){if(!Ma.test(t))throw w.invalidParams(void 0,"Invalid session ID.")}function Is(t){if(Ms(t.cwd),(t.mcpServers?.length??0)>0)throw w.invalidParams(void 0,"Client-provided MCP servers are not supported.");if((t.additionalDirectories?.length??0)>0)throw w.invalidParams(void 0,"Additional workspace directories are not supported.")}var He=class{constructor(e=ja){this.runtimeFactory=e}runtimeFactory;sessions=new Map;initialize(e){return{protocolVersion:Ve,authMethods:[],agentInfo:{name:"yukino",title:"Yukino",version:Ct},agentCapabilities:{loadSession:!0,promptCapabilities:{embeddedContext:!0},sessionCapabilities:{list:{},resume:{},close:{}}}}}authenticate(){return{}}addSession(e){let n={runtime:e,generation:0,tail:Promise.resolve(),turnAbort:null,closed:!1,usage:lt()};return this.sessions.set(e.sessionId,n),n}async newSession(e){Is(e);let n=await this.runtimeFactory(e.cwd);return this.addSession(n),{sessionId:n.sessionId}}async loadSession(e,n,i){Is(e),ft(e.sessionId);let a=this.sessions.get(e.sessionId);if(a&&a.runtime.workDir!==e.cwd)throw w.invalidParams(void 0,"Session cwd does not match.");if(a&&!i)return{};let u=It(e.cwd,e.sessionId);if(!a&&!Aa(vt(e.cwd,e.sessionId)))throw w.resourceNotFound(e.sessionId);if(!a){let p=await this.runtimeFactory(e.cwd,e.sessionId);p.conv.reset(),p.conv.appendMessages(Mt(u)),a=this.addSession(p)}if(i)for(let p of pt(e.sessionId,u,e.cwd))await n.notify(q.client.session.update,p);return{}}listSessions(e){if(e.cursor)throw w.invalidParams(void 0,"Session pagination is not supported.");let n=e.cwd??process.cwd();return Ms(n),{sessions:jt(n).map(i=>({sessionId:i.id,cwd:n,title:i.firstMessage||void 0,updatedAt:i.modTime.toISOString()}))}}prompt(e,n){let i=this.requireSession(e.sessionId),a=ct(e.prompt),u=i.generation,p=i.tail.catch(()=>{}).then(async()=>{if(i.closed||u!==i.generation||n.signal.aborted)return{stopReason:"cancelled"};let z=new AbortController;i.turnAbort=z;let f=AbortSignal.any([n.signal,z.signal]),g=()=>{i.runtime.abort()};f.aborted?g():f.addEventListener("abort",g,{once:!0});try{return await this.runPrompt(i,e.sessionId,a,n,f)}finally{f.removeEventListener("abort",g),i.turnAbort===z&&(i.turnAbort=null)}});return i.tail=p.then(()=>{},()=>{}),p}cancel(e){let n=this.sessions.get(e.sessionId);n&&(n.generation+=1,n.turnAbort?.abort(),n.runtime.abort())}async closeSession(e){ft(e.sessionId);let n=this.sessions.get(e.sessionId);return n?(n.closed=!0,n.generation+=1,n.turnAbort?.abort(),n.runtime.abort(),await n.tail.catch(()=>{}),await n.runtime.dispose(),this.sessions.delete(e.sessionId),{}):{}}async dispose(){let e=[...this.sessions.values()];this.sessions.clear();for(let n of e)n.closed=!0,n.generation+=1,n.turnAbort?.abort(),n.runtime.abort();await Promise.all(e.map(async n=>{await n.tail.catch(()=>{}),await n.runtime.dispose()}))}requireSession(e){ft(e);let n=this.sessions.get(e);if(!n||n.closed)throw w.resourceNotFound(e);return n}async runPrompt(e,n,i,a,u){Nt(e.runtime.workDir,n,{role:"user",content:i,timestamp:Math.floor(Date.now()/1e3)});let p="end_turn",z=!1;for await(let f of e.runtime.run(i,{onPermissionRequest:async(g,m,y,C)=>{let k=a.client.request(q.client.session.requestPermission,{sessionId:n,toolCall:{toolCallId:C,title:`${g}: ${y.reason}`,kind:De(g),status:"pending",rawInput:m,locations:qe(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"}]}),M=()=>{},U=new Promise(We=>{M=()=>{We(null)},u.aborted?M():u.addEventListener("abort",M,{once:!0})}),H=await Promise.race([k,U]);return u.removeEventListener("abort",M),!H||H.outcome.outcome==="cancelled"?(e.runtime.abort(),"deny"):H.outcome.optionId==="allowAlways"?"allowAlways":H.outcome.optionId==="allow"?"allow":"deny"}})){if(f.type==="compact"&&f.boundary&&At(e.runtime.workDir,n,f.boundary),f.type==="error")throw w.internalError(void 0,f.error.message);f.type==="loop_complete"&&(p=ht(f.stopReason)),f.type==="usage"&&(e.usage=ut(e.usage,f),z=!0);let g=dt(f,e.runtime.workDir,e.runtime.contextWindow);if(g){let m={sessionId:n,update:g};await a.client.notify(q.client.session.update,m)}}return{stopReason:p,...z?{usage:e.usage}:{}}}};function be(t){let e=new He(t);return{app:at({name:"yukino"}).onRequest(q.agent.initialize,i=>e.initialize(i.params)).onRequest(q.agent.authenticate,()=>e.authenticate()).onRequest(q.agent.session.new,i=>e.newSession(i.params)).onRequest(q.agent.session.prompt,i=>e.prompt(i.params,i)).onRequest(q.agent.session.list,i=>e.listSessions(i.params)).onRequest(q.agent.session.load,i=>e.loadSession(i.params,i.client,!0)).onRequest(q.agent.session.resume,i=>e.loadSession(i.params,i.client,!1)).onRequest(q.agent.session.close,i=>e.closeSession(i.params)).onNotification(q.agent.session.cancel,i=>{e.cancel(i.params)}).onConnect(i=>{i.signal.addEventListener("abort",()=>{e.dispose()},{once:!0})}),dispose:()=>e.dispose()}}function qa(){let t=(...e)=>{process.stderr.write(`${e.map(String).join(" ")}
|
|
9
|
+
`)};console.log=t,console.info=t,console.warn=t,console.debug=t}async function zt(){qa();let t=be(),e=bs(Da.toWeb(process.stdout),Oa.toWeb(process.stdin)),n=t.app.connect(e);process.stdin.resume();try{await n.closed}finally{await t.dispose()}}var ei={};Se(ei,{parseAcpWebSocketAddress:()=>Zs,runAcpWebSocket:()=>St,startAcpWebSocketServer:()=>Xs});import{createServer as ac}from"http";var Z="Acp-Connection-Id",Pe="Acp-Session-Id",mt="text/event-stream",gt="application/json",Ha=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 Ds(t){return Ha.has(t)}function _e(t){if(!I(t))return;let e=t.sessionId;return typeof e=="string"?e:void 0}function qs(t){return"method"in t?_e(t.params):void 0}function Hs(t){if(!V(t)||!("result"in t)||!I(t.result))return;let e=t.result.sessionId;return typeof e=="string"?e:void 0}function oe(t){return t.jsonrpc==="2.0"&&"id"in t&&"method"in t&&t.method===h.initialize}function W(t){if(typeof t=="string")return`string:${t}`;if(typeof t=="number")return`number:${t}`;if(t===null)return"null"}var md=16*1024*1024;function Ps(t,e){return(n,i,a)=>{let u,p=!1,z=()=>{e.off("headers",f),i.off("close",g),i.off("error",g)},f=(m,y)=>{y!==n||!u||m.push(`${Z}: ${u.connectionId}`)},g=()=>{p||(z(),u?.reject())};try{u=t.prepareWebSocketUpgrade(),e.on("headers",f),i.once("close",g),i.once("error",g),e.handleUpgrade(n,i,a,m=>{p=!0,z(),u?.accept(m)})}catch(m){z(),u?.reject(),Pa(i,m)}}}function Pa(t,e){t.destroy(e instanceof Error?e:void 0)}var we=class{enabled;queue=[];activeLease;isFinished=!1;isAborted=!1;constructor(e=!0){this.enabled=e}push(e){!this.enabled||this.isFinished||(this.queue.push(e),this.activeLease?.wake())}tryAcquire(){if(!this.enabled||this.isAborted||this.activeLease)return;let e=new bt(this);return this.activeLease=e,e}finish(){this.isFinished||(this.isFinished=!0,this.activeLease?.wake())}abort(){this.isAborted||(this.isAborted=!0,this.isFinished=!0,this.queue.length=0,this.activeLease?.wake())}async receive(e){for(;;){if(this.isAborted||e.released||this.activeLease!==e)return{done:!0,value:void 0};if(this.queue.length>0)return{done:!1,value:this.queue.shift()};if(this.isFinished)return{done:!0,value:void 0};await e.wait()}}release(e){this.activeLease===e&&(this.activeLease=void 0,e.markReleased())}},Le=class{transport;connectionId;inboundTx;outboundRx;connectionStream;allOutbound;sessionStreams=new Map;pendingRoutes=new Map;clientResponseRoutes=new Map;closed;agentConnection;supportsBatches=!1;hasStartedRouter=!1;inboundWriteChain=Promise.resolve();initialReader;outboundReader;routerPromise;shutdownPromise;hasResolvedClosed=!1;finishAgentOutbound=()=>{};resolveClosed=()=>{};constructor(e,n="http"){this.transport=n,this.connectionId=globalThis.crypto.randomUUID(),this.connectionStream=new we(n==="http"),this.allOutbound=new we(n==="websocket"),this.closed=new Promise(p=>{this.resolveClosed=p});let i=new TransformStream,a=La(p=>{if(!this.supportsBatches&&Array.isArray(p))throw new TypeError("AcpServer transports do not support outbound JSON-RPC batch messages")});this.inboundTx=i.writable,this.outboundRx=a.readable,this.finishAgentOutbound=a.finish;let u={readable:i.readable,writable:a.writable};this.agentConnection=e.connect(u,{deferConnectHandlers:!0}),this.observeAgentConnection()}async recvInitial(e){let n=this.outboundRx.getReader();this.initialReader=n;try{let i=await n.read();if(i.done||!i.value||!Ga(i.value,e))throw this.shutdownPromise||await this.shutdown(),new Error("Expected initialize response from agent");return i.value}finally{this.initialReader===n&&(this.initialReader=void 0),n.releaseLock()}}async writeInbound(e){if(!this.supportsBatches&&Array.isArray(e))throw new TypeError("AcpServer transports do not support inbound JSON-RPC batch messages");let n=this.inboundWriteChain.then(()=>this.writeInboundMessage(e));this.inboundWriteChain=n.catch(()=>{}),await n}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}ensureSession(e){let n=this.sessionStreams.get(e);if(n)return n;let i=new we(this.transport==="http");return this.sessionStreams.set(e,i),i}async shutdown(){return this.shutdownPromise||(this.shutdownPromise=this.runShutdown()),this.shutdownPromise}async runShutdown(){try{this.connectionStream.abort(),this.allOutbound.abort();for(let e of this.sessionStreams.values())e.abort();this.sessionStreams.clear(),this.pendingRoutes.clear(),this.clientResponseRoutes.clear(),await Promise.allSettled([this.inboundTx.close(),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.finishAgentOutbound(),await this.routerPromise})}cancelOutboundReader(){let e=this.initialReader??this.outboundReader;return e?e.cancel():this.outboundRx.cancel()}async writeInboundMessage(e){let n=this.inboundTx.getWriter();try{await n.write(e)}finally{n.releaseLock()}}async runRouter(){let e=this.outboundRx.getReader();this.outboundReader=e;try{for(;;){let n=await e.read();if(n.done)return;this.routeOutbound(n.value)}}catch(n){console.error("ACP connection router stopped unexpectedly:",n)}finally{this.outboundReader===e&&(this.outboundReader=void 0),e.releaseLock(),this.connectionStream.finish(),this.allOutbound.finish();for(let n of this.sessionStreams.values())n.finish();this.resolveClosedOnce()}}resolveClosedOnce(){this.hasResolvedClosed||(this.hasResolvedClosed=!0,this.resolveClosed())}routeOutbound(e){if(this.allOutbound.push(e),Array.isArray(e)){for(let n of e)this.routeOutboundMessage(n);return}this.routeOutboundMessage(e)}routeOutboundMessage(e){if(V(e)){this.routeOutboundResponse(e);return}this.routeOutboundRequestOrNotification(e)}routeOutboundResponse(e){let n=W(e.id),i=n?this.pendingRoutes.get(n):void 0,a=Hs(e);a&&this.ensureSession(a),n&&this.pendingRoutes.delete(n),this.pushToRoute(i??"connection",e)}routeOutboundRequestOrNotification(e){let n=qs(e);if(n){this.trackClientResponseRoute(e,{session:n}),this.ensureSession(n).push(e);return}this.trackClientResponseRoute(e,"connection"),this.connectionStream.push(e)}trackClientResponseRoute(e,n){if(!("id"in e)||!("method"in e))return;let i=W(e.id);i&&this.clientResponseRoutes.set(i,n)}pushToRoute(e,n){if(e==="connection"){this.connectionStream.push(n);return}this.ensureSession(e.session).push(n)}},Ge=class{connections=new Map;pendingConnections=new Map;createConnection(e,n="http"){let i=new Le(e,n);return this.connections.set(i.connectionId,i),this.trackConnectionClose(i),i}createPendingConnection(e,n="websocket"){let i=new Le(e,n);return this.pendingConnections.set(i.connectionId,i),this.trackConnectionClose(i),i}register(e){this.pendingConnections.delete(e.connectionId),this.connections.set(e.connectionId,e)}get(e){return this.connections.get(e)}remove(e){let n=this.get(e);if(n)return this.connections.delete(e),n.shutdown(),n}discard(e){let n=this.connections.get(e)??this.pendingConnections.get(e);if(n)return this.connections.delete(e),this.pendingConnections.delete(e),n.shutdown(),n}async closeAll(){let e=new Set([...this.connections.values(),...this.pendingConnections.values()]);this.connections.clear(),this.pendingConnections.clear(),await Promise.all(Array.from(e,n=>n.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)})}},bt=class{mailbox;released=!1;receiving=!1;wakePromise;resolveWake;constructor(e){this.mailbox=e}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()}};function La(t){let e,n=!1,i=()=>{if(!n){n=!0;try{e?.close()}catch{}}},a=u=>{if(!n){n=!0;try{e?.error(u)}catch{}}};return{readable:new ReadableStream({start(u){e=u},cancel(){n=!0}}),writable:new WritableStream({write(u){if(n)throw new Error("ACP outbound channel is closed");try{t(u),e?.enqueue(u)}catch(p){throw a(p),p}},close:i,abort:a}),finish:i}}function Ga(t,e){return!Array.isArray(t)&&"id"in t&&!("method"in t)&&t.id===e}function Ls(t){return`data: ${JSON.stringify(t)}
|
|
10
|
+
|
|
11
|
+
`}function Gs(){return`:
|
|
12
|
+
|
|
13
|
+
`}function Us(t){return new ReadableStream(Ua(t))}function Ua(t){let e=new TextEncoder,n,i=!1,a=!1,u=()=>{n&&(clearInterval(n),n=void 0)},p=(g,m)=>{try{return g.enqueue(e.encode(m)),!0}catch{return!1}},z=g=>g.desiredSize!==null&&g.desiredSize>0,f=g=>{if(!a){a=!0,u(),t.release();try{g.close()}catch{}}};return{start(g){n=setInterval(()=>{a||!z(g)||p(g,Gs())||f(g)},15e3)},async pull(g){if(!(a||i||!z(g))){i=!0;try{let m=await t.receive();if(a)return;if(m.done){f(g);return}p(g,Ls(m.value))||f(g)}catch(m){a||(a=!0,u(),g.error(m))}finally{i=!1}}},cancel(){a=!0,u(),t.release()}}}function Ue(t,e,n){if(t.on){let i=(...a)=>{n(...Fa(e,a))};return t.on(e,i),()=>{if(t.off){t.off(e,i);return}t.removeListener?.(e,i)}}if(t.addEventListener){let i=a=>n(a);return t.addEventListener(e,i),()=>{t.removeEventListener?.(e,i)}}throw new Error("WebSocket object does not support event listeners")}function Fs(t){let e=Ba(t);if(typeof e=="string")return e}function Fa(t,e){return t!=="message"||typeof e[1]!="boolean"?e:e[1]?[void 0]:[Wa(e[0])]}function Wa(t){if(typeof t=="string")return t;if(t instanceof ArrayBuffer)return new TextDecoder().decode(t);if(ArrayBuffer.isView(t))return new TextDecoder().decode(t);if(Ja(t))return Va(t)}function Ba(t){let[e]=t;return $a(e)?e.data:e}function $a(t){return typeof t=="object"&&t!==null&&"data"in t}function Ja(t){return Array.isArray(t)&&t.every(ArrayBuffer.isView)}function Va(t){let e=t.reduce((a,u)=>a+u.byteLength,0),n=new Uint8Array(e),i=0;for(let a of t)n.set(new Uint8Array(a.buffer,a.byteOffset,a.byteLength),i),i+=a.byteLength;return new TextDecoder().decode(n)}function $s(t,e){let n=new _t(t,e);return n.start(),n}var _t=class{socket;options;connection;preparedConnection;outboundLease;inboundWriteChain=Promise.resolve();messageChain=Promise.resolve();isClosed=!1;closedPromise;resolveClosed=()=>{};detachListeners=[];constructor(e,n){this.socket=e,this.options=n,this.preparedConnection=n.connection,this.closedPromise=new Promise(i=>{this.resolveClosed=i})}get closed(){return this.closedPromise}start(){this.detachListeners.push(Ue(this.socket,"message",(...e)=>{this.enqueueSocketMessage(e)})),this.detachListeners.push(Ue(this.socket,"close",()=>{this.closeSession()})),this.detachListeners.push(Ue(this.socket,"error",()=>{this.shutdown(1011,"WebSocket error")}))}close(e=1001,n="Server shutting down"){return this.shutdown(e,n)}enqueueSocketMessage(e){let n=this.messageChain.then(()=>this.handleSocketMessage(e));this.messageChain=n.catch(i=>{this.isClosed||(console.error("ACP WebSocket message handling failed:",i),this.shutdown(1011,"Message handling failed"))})}async handleSocketMessage(e){if(this.isClosed)return;let n=Fs(e);if(n===void 0){console.warn("Ignoring non-text ACP WebSocket frame");return}let i;try{i=JSON.parse(n)}catch{this.send(L(w.parseError()));return}if(!Array.isArray(i)&&!I(i)){this.send(L(w.invalidRequest(i)));return}if(!this.connection&&Array.isArray(i)){if(i.length===1&&P(i[0])){await this.handleInitialize(i[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 a=i;if(!this.connection){if(pe(a))return;if(!P(a)&&!F(a)){this.send(L(w.invalidRequest(a)));return}await this.handleInitialize(a,!1);return}let u=await this.forwardMessage(a);u.ok||console.warn("Ignoring ACP WebSocket message:",u.message)}async handleInitialize(e,n){if(!oe(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 i=this.preparedConnection??this.options.registry.createPendingConnection(this.options.agent);this.preparedConnection=i;try{await Ws(i,e);let a=await i.recvInitial(e.id);if(this.isClosed){this.options.registry.discard(i.connectionId);return}this.preparedConnection=void 0,Ya(a)===2&&i.enableBatches(),this.connection=i,this.options.registry.register(i),i.startRouter(),i.startConnectHandlers(),this.send(n?[a]:a),this.startOutboundPump(i)}catch(a){this.preparedConnection=void 0,this.options.registry.discard(i.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(n?[u]:u),await this.shutdown(1011,"Initialize failed")}}async forwardMessage(e){let n=this.connection;if(!n)return{ok:!1,message:"ACP WebSocket connection is not initialized"};if(Array.isArray(e)){if(!n.batchesEnabled)return await this.shutdown(1002,"JSON-RPC batches require ACP v2"),{ok:!1,message:"JSON-RPC batches require ACP v2"};if(e.some(Ka))return await this.shutdown(1002,"Initialize not allowed on existing connection"),{ok:!1,message:"Initialize not allowed on existing connection"};for(let i of e)this.trackInboundRoutes(i);return await this.writeInbound(e),{ok:!0}}return P(e)&&oe(e)?(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.writeInbound(e),{ok:!0})}trackInboundRoutes(e){let n=this.connection;if(n){if(P(e)){let i=Bs(e);i!=="connection"&&n.ensureSession(i.session);let a=W(e.id);a&&n.pendingRoutes.set(a,e.method===h.session_load?"connection":i);return}if(F(e)){let i=Bs(e);i!=="connection"&&n.ensureSession(i.session);return}if(pe(e)){let i=e.id,a=i===null||typeof i=="string"||typeof i=="number"&&Number.isFinite(i)?W(i):void 0;a&&n.clientResponseRoutes.delete(a)}}}async writeInbound(e){let n=this.connection;if(!n)throw new Error("ACP WebSocket connection is not initialized");let i=this.inboundWriteChain.then(()=>Ws(n,e));this.inboundWriteChain=i.catch(()=>{}),await i}startOutboundPump(e){let n=e.allOutbound.tryAcquire();if(!n){this.shutdown(1011,"Outbound stream already has an active receiver");return}this.outboundLease=n,(async()=>{try{for(;!this.isClosed;){let i=await n.receive();if(i.done||!this.send(i.value))return}}catch(i){this.isClosed||console.error("ACP WebSocket outbound pump failed:",i)}finally{this.outboundLease===n&&(this.outboundLease=void 0),n.release(),this.isClosed||this.shutdown()}})()}send(e){if(this.isClosed)return!1;try{return this.socket.send(JSON.stringify(e)),!0}catch(n){return console.warn("Failed to send ACP WebSocket message:",n),this.shutdown(1011,"Failed to send message"),!1}}async shutdownIfUninitialized(e,n){this.connection||await this.shutdown(e,n)}async shutdown(e,n){this.closeSocket(e,n),await this.closeSession()}closeSocket(e,n){try{this.socket.close(e,n)}catch(i){console.warn("Failed to close ACP WebSocket:",i)}}async closeSession(){if(!this.isClosed){this.isClosed=!0;try{for(let n of this.detachListeners.splice(0))n();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 Ws(t,e){await t.writeInbound(e)}function Bs(t){let e=_e(t.params);return e?{session:e}:"connection"}function Ka(t){return P(t)&&oe(t)}function Ya(t){if(!("result"in t)||!I(t.result))return;let e=t.result.protocolVersion;return typeof e=="number"?e:void 0}var Fe=class{agent;registry=new Ge;webSocketSessions=new Set;constructor(e){this.agent=Ys(e)}async handleRequest(e,n={}){return e.method==="POST"?await this.handlePost(e,n):e.method==="GET"?this.handleGet(e):e.method==="DELETE"?this.handleDelete(e):N("Method Not Allowed",405)}prepareWebSocketUpgrade(e={}){let n=Js(e,this.agent),i=this.registry.createPendingConnection(n),a=!1;return{connectionId:i.connectionId,accept:u=>{if(a)throw new Error("ACP WebSocket upgrade has already been settled");a=!0;let p=$s(u,{registry:this.registry,agent:n,connection:i});this.webSocketSessions.add(p),p.closed.finally(()=>{this.webSocketSessions.delete(p)})},reject:()=>{a||(a=!0,this.registry.discard(i.connectionId))}}}async close(){let e=this.registry.closeAll(),n=Promise.all(Array.from(this.webSocketSessions,i=>i.close()));await Promise.all([e,n])}async handlePost(e,n){let i=e.headers.get("Content-Type");if(!oc(i))return N("Unsupported Media Type",415);let a=await Za(e);if(!a.ok)return N("Invalid JSON",400);if(Array.isArray(a.value))return N("Batch JSON-RPC requests are not implemented",501);if(!I(a.value))return N("Invalid JSON-RPC message",400);let u=a.value,p=e.headers.get(Z);if(oe(u))return p?N("Initialize not allowed on existing connection",400):await this.handleInitialize(u,e.signal,n);if(!p)return N("Missing Acp-Connection-Id",400);let z=this.registry.get(p);if(!z)return N("Unknown Acp-Connection-Id",404);let f=await this.forwardConnectedMessage(z,u,e.headers);return f.ok?Ks(202):N(f.message,f.status)}handleGet(e){if(e.headers.get("Upgrade")?.toLowerCase()==="websocket")return N("WebSocket upgrade is not implemented",426);if(!e.headers.get("Accept")?.toLowerCase()?.includes(mt))return N("Not Acceptable",406);let i=e.headers.get(Z);if(!i)return N("Missing Acp-Connection-Id",400);let a=this.registry.get(i);if(!a)return N("Unknown Acp-Connection-Id",404);let u=e.headers.get(Pe),z=(u?a.ensureSession(u):a.connectionStream).tryAcquire();return z?rc(z):N("Outbound stream already has an active receiver",409)}handleDelete(e){let n=e.headers.get(Z);return n?this.registry.remove(n)?Ks(202):N("Unknown Acp-Connection-Id",404):N("Missing Acp-Connection-Id",400)}async handleInitialize(e,n,i){if(!("id"in e)||e.id===null)return N("Initialize request must include an ID",400);if(n.aborted)return N("Request aborted",499);let a;try{a=this.registry.createConnection(Js(i,this.agent));let u=Xa(a,e);u.catch(()=>{});let p=await ec(u,n);if(n.aborted)throw new re;return a.startRouter(),a.startConnectHandlers(),Vs(p,200,{[Z]:a.connectionId})}catch(u){return a&&this.registry.remove(a.connectionId),u instanceof re?N("Request aborted",499):Vs({jsonrpc:"2.0",id:e.id,error:{code:-32603,message:"Initialize failed",data:u instanceof Error?u.message:void 0}},500)}}async forwardConnectedMessage(e,n,i){return V(n)?await tc(e,n,i):await nc(e,n,i)}};function Js(t,e){return Qa(t)?Ys(t):e}function Qa(t){return!!(t.agent||t.createAgent||t.createLegacyAgent)}function Ys(t){if((t.agent?1:0)+(t.createAgent?1:0)+(t.createLegacyAgent?1:0)!==1)throw new Error("AcpServer requires exactly one of agent, createAgent, or createLegacyAgent");return t.agent?t.agent:t.createAgent?{connect:(n,i)=>t.createAgent().connect(n,i??{})}:{connect:n=>{new Me(t.createLegacyAgent,n)}}}var re=class extends Error{constructor(){super("Request aborted"),this.name="RequestAbortedError"}};async function Za(t){try{return{ok:!0,value:await t.json()}}catch{return{ok:!1}}}async function wt(t,e){await t.writeInbound(e)}async function Xa(t,e){if(await wt(t,e),!("id"in e)||e.id===null)throw new Error("Initialize request must include an ID");return await t.recvInitial(e.id)}async function ec(t,e){if(e.aborted)throw new re;let n=()=>{},i=new Promise((a,u)=>{let p=()=>{u(new re)};e.addEventListener("abort",p,{once:!0}),n=()=>{e.removeEventListener("abort",p)}});try{return await Promise.race([t,i])}finally{n()}}async function nc(t,e,n){let i=ic(e,n);if(!i.ok)return i;i.value!=="connection"&&t.ensureSession(i.value.session);let a="id"in e?W(e.id):void 0;return a&&t.pendingRoutes.set(a,sc(e,i.value)),await wt(t,e),{ok:!0}}async function tc(t,e,n){let i=W(e.id),a=i?t.clientResponseRoutes.get(i):void 0,u=n.get(Pe);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"}:(i&&t.clientResponseRoutes.delete(i),await wt(t,e),{ok:!0})}function sc(t,e){return t.method===h.session_load?"connection":e}function ic(t,e){let n=e.get(Pe),i=_e(t.params);return(Ds(t.method)||i!==void 0)&&!n?{ok:!1,status:400,message:"Missing Acp-Session-Id"}:n!==null&&i!==void 0&&n!==i?{ok:!1,status:400,message:"Mismatched Acp-Session-Id"}:n?{ok:!0,value:{session:n}}:i?{ok:!0,value:{session:i}}:{ok:!0,value:"connection"}}function oc(t){return t?.split(";",1)[0]?.trim().toLowerCase()===gt}function rc(t){return new Response(Us(t),{status:200,headers:{"Content-Type":mt,"Cache-Control":"no-cache",Connection:"keep-alive"}})}function Vs(t,e,n){return new Response(JSON.stringify(t),{status:e,headers:{"Content-Type":gt,...n}})}function N(t,e){return new Response(t,{status:e,headers:{"Content-Type":"text/plain"}})}function Ks(t){return new Response(null,{status:t})}var Qs="/acp",cc="127.0.0.1:18889",dc=new Set(["127.0.0.1","::1","localhost"]);function Zs(t){let e=Ot(t??cc);if(!dc.has(e.host))throw new Error("ACP WebSocket must listen on a loopback address.");return e}async function Xs(t){let{host:e,port:n}=Zs(t),i=new Fe({createAgent:()=>be().app}),a=new Et.default({noServer:!0}),u=Ps(i,a),p=ac((y,C)=>{C.writeHead(404,{"content-type":"text/plain; charset=utf-8"}),C.end("Not Found")});p.on("upgrade",(y,C,k)=>{if(new URL(y.url??"/","http://localhost").pathname!==Qs){C.destroy();return}u(y,C,k)}),await new Promise((y,C)=>{let k=U=>{p.off("listening",M),C(U)},M=()=>{p.off("error",k),y()};p.once("error",k),p.once("listening",M),p.listen(n,e)});let z=p.address();if(!z||typeof z=="string")throw new Error("ACP WebSocket server did not bind to a TCP address.");let f=z,g=f.family==="IPv6"?`[${f.address}]`:f.address,m=!1;return{url:`ws://${g}:${String(f.port)}${Qs}`,async close(){m||(m=!0,await i.close(),await new Promise((y,C)=>{a.close(k=>{k?C(k):y()})}),await new Promise((y,C)=>{p.close(k=>{k?C(k):y()})}))}}}async function St(t){let e=await Xs(t);process.stderr.write(`ACP WebSocket listening at ${e.url}
|
|
14
|
+
`),await new Promise(n=>{let i=()=>{process.off("SIGINT",i),process.off("SIGTERM",i),e.close().finally(n)};process.once("SIGINT",i),process.once("SIGTERM",i)})}function uc(t){let e=t.indexOf("--acp"),n=t.indexOf("--acp-ws");if(e===-1&&n===-1)return null;if(e!==-1&&n!==-1)throw new Error("Use either --acp or --acp-ws, not both.");if(e!==-1){if(t.length!==1)throw new Error("--acp cannot be combined with other CLI options.");return{transport:"stdio"}}let i=t[n+1],a=i&&!i.startsWith("-")?2:1;if(t.length!==a)throw new Error("--acp-ws accepts only an optional host:port address.");return{transport:"websocket",...a===2?{address:i}:{}}}async function Vd(t){let e=uc(t);if(!e)throw new Error("ACP mode was not selected.");if(e.transport==="stdio"){await zt();return}await St(e.address)}export{js as Agent,As as Conversion,Os as Stdio,ei as Websocket,uc as parseAcpMode,Vd as runAcp};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __yukinoCreateRequire } from "node:module";
|
|
3
|
+
const require = __yukinoCreateRequire(import.meta.url);
|
|
4
|
+
import{K as b,L as c,g as a}from"./chunk-RAS3ORX3.js";import"./chunk-VWUGGYUP.js";import"./chunk-JFKC4VCA.js";import"./chunk-OFC2GD5K.js";import"./chunk-5VOCXSSX.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};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __yukinoCreateRequire } from "node:module";
|
|
3
|
+
const require = __yukinoCreateRequire(import.meta.url);
|
|
4
|
+
import{g as I}from"./chunk-MDPSQ6L7.js";import{a as X,b as Z}from"./chunk-SAJCBGHL.js";import{a as Q}from"./chunk-OFC2GD5K.js";import{A as D,B as E,C as J,D as V,E as q,k as N,m as O,n as B,o as j,p as U,q as $,r as K,t as w,u as C,z as Y}from"./chunk-5VOCXSSX.js";import"./chunk-XO7ITAWR.js";import{f as R,k as F,l as H,m as z,n as k,o as G,s as W}from"./chunk-UPNNYP7M.js";import{D as P,f as S}from"./chunk-GYBJR2RB.js";import"./chunk-7MKA3SHV.js";function oe(o){for(let t=o.length-1;t>=0;t--){let e=o[t];if(e.defer_loading!==!0){e.cache_control={type:"ephemeral"};return}}}function ne(o){return o.some(t=>"defer_loading"in t&&t.defer_loading===!0)}function se(o,t){if("input_schema"in o){let e=o,{cache_control:n,...s}=e;return t||delete s.type,{...s,...t?{type:"custom"}:{},...e.defer_loading!==!0&&n?{cache_control:n}:{}}}throw new Error("Anthropic received a tool schema serialized for another protocol.")}var v=R({module:"llm"});var re=3e3,ie=P.object({max_input_tokens:P.coerce.number()});async function ye(o){if(o.protocol!=="anthropic")return 0;let t=C(o),n=`${o.base_url.replace(/\/+$/,"")}/v1/models/${encodeURIComponent(o.model)}`,s=new AbortController,r=setTimeout(()=>{s.abort()},re);try{let c=await fetch(n,{method:"GET",headers:{"anthropic-version":"2023-06-01",...t?{"x-api-key":t}:{}},signal:s.signal});if(!c.ok)return 0;let p=await c.json(),{success:u,error:h,data:m}=await S(ie,p);if(!u)return v.warn({message:h.message},"model context window schema validation failed"),0;let g=m.max_input_tokens;return Math.max(g,0)}catch(c){return v.error({err:c},"failed to fetch model context window"),0}finally{clearTimeout(r)}}function T(o){return typeof o=="string"?[{type:"text",text:o}]:o.map(t=>{let e=Q(t);if(!e||e.type==="tool_reference")throw new Error(`Unsupported user content block: ${W(t,"type","unknown")}`);return e})}function ae(o){let t=[];for(let e of o)if(e.role==="assistant"){let n=[];if(e.thinkingBlocks)for(let r of e.thinkingBlocks)n.push({type:"thinking",thinking:r.thinking,signature:r.signature});let s=typeof e.content=="string"?e.content:F(e.content);if(s&&n.push({type:"text",text:s}),e.toolUses)for(let r of e.toolUses)n.push({type:"tool_use",id:r.toolUseId,name:r.toolName==="ComputerUse"?"computer":r.toolName,input:r.arguments});n.length===0&&n.push({type:"text",text:""}),t.push({role:"assistant",content:n})}else if(e.toolResults&&e.toolResults.length>0){let n=[];for(let s of e.toolResults)n.push({type:"tool_result",tool_use_id:s.toolUseId,is_error:s.isError,content:s.contentBlocks?.length?s.contentBlocks:s.content});e.content.length>0&&n.push(...T(e.content)),t.push({role:"user",content:n})}else{if(t.length===0){t.push({role:"user",content:T(e.content)});continue}let n=!1,s=t[t.length-1],r=s.content;s.role==="user"&&(typeof r=="string"||Array.isArray(r)&&r.length>0&&(r[0].type==="text"||r[0].type==="image"))&&(n=!0),n?(typeof r=="string"&&(r=s.content=r.trim().length>0?[{type:"text",text:r}]:[]),r.push(...T(e.content))):t.push({role:"user",content:T(e.content)})}return t}var ee=class{protocol="anthropic";client;model;thinkingLevel;systemPrompt;maxOutputTokens;config;useExplicitCustomToolType;constructor(t,e){let n=C(t);if(!n)throw new E("Anthropic API key not found, set ANTHROPIC_API_KEY in ~/.yukino/config.yaml, or via ANTHROPIC_API_KEY env variable.");this.client=new I({apiKey:n,baseURL:t.base_url}),this.useExplicitCustomToolType=Z(t.base_url),this.model=t.model,this.config={...t},this.thinkingLevel=O(t),this.systemPrompt=e,this.maxOutputTokens=w(t)}setSystemPrompt(t){this.systemPrompt=t}setMaxOutputTokens(t){this.config={...this.config,max_output_tokens:t},this.maxOutputTokens=w(this.config),this.setThinkingLevel(this.thinkingLevel)}setThinkingLevel(t){return this.thinkingLevel=K(this.config,t),this.thinkingLevel}getThinkingLevel(){return this.thinkingLevel}getSupportedThinkingLevels(){return $(this.config)}async*stream(t,e,n){let s=ae(Y(t.getMessages())),r=ne(e),c=e.map(l=>se(l,this.useExplicitCustomToolType));oe(c),le(s);let p={model:this.model,max_tokens:this.maxOutputTokens,stream:!0,system:[{type:"text",text:this.systemPrompt,cache_control:{type:"ephemeral"}}],messages:s,...c.length>0?{tools:c}:{}},u=this.getThinkingLevel();if(this.config.reasoning!==!1)if(u==="off")p.thinking={type:"disabled"};else if(this.config.thinking_mode==="adaptive"){let l=U(u,this.config);l!==null&&(p.thinking={type:"adaptive"},p.output_config={effort:l})}else{let l=j(u,this.config);l!==null&&l!=="none"&&(p.thinking={type:"enabled",budget_tokens:Math.min(B(l),this.maxOutputTokens-N)})}let h=0,m=0,g=0,x=0,M="end_turn",A="",b="",L=!1;try{let l=[...r?[X]:[]],te=this.client.messages.stream(p,{...n?{signal:n}:{},...l.length>0?{headers:{"anthropic-beta":l.join(",")}}:{}}),f="",_="",d="";for await(let a of te)switch(a.type){case"content_block_start":{let i=a.content_block;i.type==="thinking"?(L=!0,A="",b=""):i.type==="tool_use"&&(_=i.id,f=i.name==="computer"?"ComputerUse":i.name,d="",yield{type:"tool_call_start",toolName:f,toolId:_});break}case"content_block_delta":{let i=a.delta;i.type==="thinking_delta"?(A+=i.thinking,yield{type:"thinking_delta",text:i.thinking}):i.type==="signature_delta"?b+=i.signature:i.type==="text_delta"?yield{type:"text_delta",text:i.text}:i.type==="input_json_delta"&&(d+=i.partial_json,yield{type:"tool_call_delta",text:i.partial_json});break}case"content_block_stop":{if(L&&(yield{type:"thinking_complete",thinking:A,signature:b},L=!1),f){let i={};if(d)try{let y=JSON.parse(d);i=H(y)?z(y):{}}catch(y){v.error({err:y},"llm operation failed"),i={}}yield{type:"tool_call_complete",toolId:_,toolName:f,arguments:i},f="",_="",d=""}break}case"message_delta":{a.delta.stop_reason&&(M=a.delta.stop_reason),a.usage.output_tokens&&(m=a.usage.output_tokens,a.usage.input_tokens&&(h=a.usage.input_tokens),a.usage.cache_read_input_tokens&&(g=a.usage.cache_read_input_tokens),a.usage.cache_creation_input_tokens&&(x=a.usage.cache_creation_input_tokens));break}case"message_start":{h=a.message.usage.input_tokens,m=a.message.usage.output_tokens,g=a.message.usage.cache_read_input_tokens??0,x=a.message.usage.cache_creation_input_tokens??0;break}}yield{type:"stream_end",stopReason:M,usage:{inputTokens:h,outputTokens:m,cacheReadInputTokens:g,cacheCreationInputTokens:x}}}catch(l){throw v.error({err:l},"llm operation failed"),ce(l)}}};function le(o){for(let t=o.length-1;t>=0;t--){if(o[t].role!=="user")continue;let e=o[t].content;if(typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0)return;typeof e=="string"&&(e=o[t].content=[{type:"text",text:e}]);let n=e[e.length-1];for(let s=e.length-1;s>=0;s--)if(e[s].type!=="image"){n=e[s];break}Reflect.set(n,"cache_control",{type:"ephemeral"});return}}function ce(o){if(o instanceof I.APIError){if(o.status===413||/prompts?\s+too\s+long/i.test(o.message))return new q(`Prompt too long: ${o.message}`);if(o.status===401)return new E(`Invalid API key: ${o.message}`);if(o.status===429){let t=o.headers,e=t instanceof Headers?t.get("retry-after"):void 0,n="Rate Limited";if(e){let s=Number.parseInt(k(e));Number.isNaN(s)?n+=", please wait.":n+=`, retry after ${k(s)}s.`}else n+=", please wait.";return new J(n,e?k(e):void 0)}return new D(`Anthropic API error (${k(o.status)}): ${o.message}`)}return new V(`Network error: ${G(o)}`)}export{ee as AnthropicClient,ae as buildAnthropicMessages,ye as fetchModelContextWindow,le as markLastUserTailForCache,oe as markToolsForCache,ne as needsToolSearchBeta};
|