@eum-agent/integration-acp 0.0.0-stage → 1.0.0

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/ui/ui.js ADDED
@@ -0,0 +1,1617 @@
1
+ import { useEffect, useRef, useState, useSyncExternalStore } from "react";
2
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
3
+ //#region src/preset-logos.ts
4
+ /*!
5
+ MIT License
6
+
7
+ Copyright (c) 2023 LobeHub
8
+
9
+ Permission is hereby granted, free of charge, to any person obtaining a copy
10
+ of this software and associated documentation files (the "Software"), to deal
11
+ in the Software without restriction, including without limitation the rights
12
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
+ copies of the Software, and to permit persons to whom the Software is
14
+ furnished to do so, subject to the following conditions:
15
+
16
+ The above copyright notice and this permission notice shall be included in all
17
+ copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
+ SOFTWARE.
26
+
27
+ */
28
+ /** Bundled Lobe Icons (MIT); see preset-logos.LICENSE. No remote image requests. */
29
+ var presetLogos = {
30
+ codex: "data:image/svg+xml,%3Csvg%20fill%3D%22%233b82f6%22%20fill-rule%3D%22evenodd%22%20height%3D%221em%22%20style%3D%22flex%3Anone%3Bline-height%3A1%22%20viewBox%3D%220%200%2024%2024%22%20width%3D%221em%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Ctitle%3ECodex%3C%2Ftitle%3E%3Cpath%20clip-rule%3D%22evenodd%22%20d%3D%22M8.086.457a6.105%206.105%200%20013.046-.415c1.333.153%202.521.72%203.564%201.7a.117.117%200%2000.107.029c1.408-.346%202.762-.224%204.061.366l.063.03.154.076c1.357.703%202.33%201.77%202.918%203.198.278.679.418%201.388.421%202.126a5.655%205.655%200%2001-.18%201.631.167.167%200%2000.04.155%205.982%205.982%200%20011.578%202.891c.385%201.901-.01%203.615-1.183%205.14l-.182.22a6.063%206.063%200%2001-2.934%201.851.162.162%200%2000-.108.102c-.255.736-.511%201.364-.987%201.992-1.199%201.582-2.962%202.462-4.948%202.451-1.583-.008-2.986-.587-4.21-1.736a.145.145%200%2000-.14-.032c-.518.167-1.04.191-1.604.185a5.924%205.924%200%2001-2.595-.622%206.058%206.058%200%2001-2.146-1.781c-.203-.269-.404-.522-.551-.821a7.74%207.74%200%2001-.495-1.283%206.11%206.11%200%2001-.017-3.064.166.166%200%2000.008-.074.115.115%200%2000-.037-.064%205.958%205.958%200%2001-1.38-2.202%205.196%205.196%200%2001-.333-1.589%206.915%206.915%200%2001.188-2.132c.45-1.484%201.309-2.648%202.577-3.493.282-.188.55-.334.802-.438.286-.12.573-.22.861-.304a.129.129%200%2000.087-.087A6.016%206.016%200%20015.635%202.31C6.315%201.464%207.132.846%208.086.457zm-.804%207.85a.848.848%200%2000-1.473.842l1.694%202.965-1.688%202.848a.849.849%200%20001.46.864l1.94-3.272a.849.849%200%2000.007-.854l-1.94-3.393zm5.446%206.24a.849.849%200%20000%201.695h4.848a.849.849%200%20000-1.696h-4.848z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E",
31
+ claude: "data:image/svg+xml,%3Csvg%20fill%3D%22%23d97757%22%20fill-rule%3D%22evenodd%22%20height%3D%221em%22%20style%3D%22flex%3Anone%3Bline-height%3A1%22%20viewBox%3D%220%200%2024%2024%22%20width%3D%221em%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Ctitle%3EClaude%3C%2Ftitle%3E%3Cpath%20d%3D%22M4.709%2015.955l4.72-2.647.08-.23-.08-.128H9.2l-.79-.048-2.698-.073-2.339-.097-2.266-.122-.571-.121L0%2011.784l.055-.352.48-.321.686.06%201.52.103%202.278.158%201.652.097%202.449.255h.389l.055-.157-.134-.098-.103-.097-2.358-1.596-2.552-1.688-1.336-.972-.724-.491-.364-.462-.158-1.008.656-.722.881.06.225.061.893.686%201.908%201.476%202.491%201.833.365.304.145-.103.019-.073-.164-.274-1.355-2.446-1.446-2.49-.644-1.032-.17-.619a2.97%202.97%200%2001-.104-.729L6.283.134%206.696%200l.996.134.42.364.62%201.414%201.002%202.229%201.555%203.03.456.898.243.832.091.255h.158V9.01l.128-1.706.237-2.095.23-2.695.08-.76.376-.91.747-.492.584.28.48.685-.067.444-.286%201.851-.559%202.903-.364%201.942h.212l.243-.242.985-1.306%201.652-2.064.73-.82.85-.904.547-.431h1.033l.76%201.129-.34%201.166-1.064%201.347-.881%201.142-1.264%201.7-.79%201.36.073.11.188-.02%202.856-.606%201.543-.28%201.841-.315.833.388.091.395-.328.807-1.969.486-2.309.462-3.439.813-.042.03.049.061%201.549.146.662.036h1.622l3.02.225.79.522.474.638-.079.485-1.215.62-1.64-.389-3.829-.91-1.312-.329h-.182v.11l1.093%201.068%202.006%201.81%202.509%202.33.127.578-.322.455-.34-.049-2.205-1.657-.851-.747-1.926-1.62h-.128v.17l.444.649%202.345%203.521.122%201.08-.17.353-.608.213-.668-.122-1.374-1.925-1.415-2.167-1.143-1.943-.14.08-.674%207.254-.316.37-.729.28-.607-.461-.322-.747.322-1.476.389-1.924.315-1.53.286-1.9.17-.632-.012-.042-.14.018-1.434%201.967-2.18%202.945-1.726%201.845-.414.164-.717-.37.067-.662.401-.589%202.388-3.036%201.44-1.882.93-1.086-.006-.158h-.055L4.132%2018.56l-1.13.146-.487-.456.061-.746.231-.243%201.908-1.312-.006.006z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E",
32
+ openclaw: "data:image/svg+xml,%3Csvg%20fill%3D%22%23ef5350%22%20fill-rule%3D%22evenodd%22%20height%3D%221em%22%20style%3D%22flex%3Anone%3Bline-height%3A1%22%20viewBox%3D%220%200%2024%2024%22%20width%3D%221em%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Ctitle%3EOpenClaw%3C%2Ftitle%3E%3Cg%20clip-path%3D%22url%28%23a%29%22%3E%3Cpath%20d%3D%22M9.046%207.104a.527.527%200%20110%201.055.527.527%200%20010-1.055z%22%3E%3C%2Fpath%3E%3Cpath%20d%3D%22M15.376%207.104a.528.528%200%20110%201.056.528.528%200%20010-1.056z%22%3E%3C%2Fpath%3E%3Cpath%20clip-rule%3D%22evenodd%22%20d%3D%22M16.877%201.912c.58-.27%201.14-.323%201.616-.037a.317.317%200%2001-.326.542c-.227-.136-.547-.153-1.022.068-.352.165-.765.45-1.234.866%202.683%201.17%204.4%203.5%205.148%205.921a6.421%206.421%200%2000-.704.184c-.578.016-1.174.204-1.502.735-.338.55-.268%201.276.072%202.069l.005.012.007.014c.523%201.045%201.318%201.91%202.2%202.284-.912%203.274-3.44%206.144-5.972%206.988v2.109h-2.11v-2.11c-1.043.417-2.086.01-2.11%200v2.11h-2.11v-2.11c-2.531-.843-5.061-3.713-5.973-6.987.882-.373%201.678-1.238%202.2-2.284l.007-.014.006-.012c.34-.793.41-1.518.071-2.069-.327-.531-.923-.719-1.503-.735a6.409%206.409%200%2000-.704-.183c.749-2.421%202.466-4.751%205.149-5.922-.47-.416-.88-.701-1.234-.866-.474-.221-.794-.204-1.021-.068a.318.318%200%2001-.435-.109.317.317%200%2001.109-.433c.476-.286%201.036-.233%201.615.037.49.229%201.031.628%201.621%201.182A9.924%209.924%200%200112%202.568c1.199%200%202.284.19%203.256.526.59-.554%201.13-.953%201.62-1.182zM8.835%206.577a1.266%201.266%200%20100%202.532%201.266%201.266%200%20000-2.532zm6.33%200a1.267%201.267%200%20100%202.533%201.267%201.267%200%20000-2.533z%22%3E%3C%2Fpath%3E%3Cpath%20d%3D%22M.395%2013.118c-.966-1.932-.163-3.863%202.41-3.365v-.001l.05.01c.084.018.17.038.26.06.033.009.067.017.1.027.084.022.168.048.255.076l.09.027c.528%200%20.95.158%201.16.501.212.343.212.87-.105%201.61-.085.17-.178.333-.276.489l-.01.017a4.967%204.967%200%2001-.62.791l-.019.02c-1.092%201.117-2.496%201.336-3.295-.262z%22%3E%3C%2Fpath%3E%3Cpath%20d%3D%22M21.193%209.753c2.574-.5%203.378%201.433%202.411%203.365-.58%201.159-1.476%201.361-2.342.96l-.011-.005a2.419%202.419%200%2001-.114-.056l-.019-.01a2.751%202.751%200%2001-.115-.067l-.023-.014c-.035-.022-.071-.044-.106-.068l-.05-.035c-.55-.388-1.062-1.007-1.44-1.76-.276-.647-.311-1.132-.174-1.472.176-.439.636-.639%201.23-.639.032-.011.066-.02.099-.03.08-.026.16-.05.238-.072l.117-.03a5.502%205.502%200%2001.3-.067z%22%3E%3C%2Fpath%3E%3C%2Fg%3E%3Cdefs%3E%3ClinearGradient%20gradientUnits%3D%22userSpaceOnUse%22%20id%3D%22b%22%20x1%3D%22-.659%22%20x2%3D%2227.023%22%20y1%3D%22.458%22%20y2%3D%2222.855%22%3E%3Cstop%20stop-color%3D%22%23FF4D4D%22%3E%3C%2Fstop%3E%3Cstop%20offset%3D%221%22%20stop-color%3D%22%23991B1B%22%3E%3C%2Fstop%3E%3C%2FlinearGradient%3E%3ClinearGradient%20gradientUnits%3D%22userSpaceOnUse%22%20id%3D%22c%22%20x1%3D%22-.659%22%20x2%3D%2227.023%22%20y1%3D%22.458%22%20y2%3D%2222.855%22%3E%3Cstop%20stop-color%3D%22%23FF4D4D%22%3E%3C%2Fstop%3E%3Cstop%20offset%3D%221%22%20stop-color%3D%22%23991B1B%22%3E%3C%2Fstop%3E%3C%2FlinearGradient%3E%3ClinearGradient%20gradientUnits%3D%22userSpaceOnUse%22%20id%3D%22d%22%20x1%3D%22-.659%22%20x2%3D%2227.023%22%20y1%3D%22.458%22%20y2%3D%2222.855%22%3E%3Cstop%20stop-color%3D%22%23FF4D4D%22%3E%3C%2Fstop%3E%3Cstop%20offset%3D%221%22%20stop-color%3D%22%23991B1B%22%3E%3C%2Fstop%3E%3C%2FlinearGradient%3E%3ClinearGradient%20gradientUnits%3D%22userSpaceOnUse%22%20id%3D%22e%22%20x1%3D%22-.659%22%20x2%3D%2227.023%22%20y1%3D%22.458%22%20y2%3D%2222.855%22%3E%3Cstop%20stop-color%3D%22%23FF4D4D%22%3E%3C%2Fstop%3E%3Cstop%20offset%3D%221%22%20stop-color%3D%22%23991B1B%22%3E%3C%2Fstop%3E%3C%2FlinearGradient%3E%3ClinearGradient%20gradientUnits%3D%22userSpaceOnUse%22%20id%3D%22f%22%20x1%3D%22-.659%22%20x2%3D%2227.023%22%20y1%3D%22.458%22%20y2%3D%2222.855%22%3E%3Cstop%20stop-color%3D%22%23FF4D4D%22%3E%3C%2Fstop%3E%3Cstop%20offset%3D%221%22%20stop-color%3D%22%23991B1B%22%3E%3C%2Fstop%3E%3C%2FlinearGradient%3E%3CclipPath%20id%3D%22a%22%3E%3Cpath%20d%3D%22M0%200h24v24H0z%22%3E%3C%2Fpath%3E%3C%2FclipPath%3E%3C%2Fdefs%3E%3C%2Fsvg%3E"
33
+ };
34
+ //#endregion
35
+ //#region src/presets.ts
36
+ /** Known ACP launch recipes; installation and authentication remain local prerequisites. */
37
+ var ACP_PRESETS = [
38
+ {
39
+ id: "codex",
40
+ label: "Codex",
41
+ command: "codex",
42
+ args: [],
43
+ docs: "https://github.com/agentclientprotocol/codex-acp"
44
+ },
45
+ {
46
+ id: "claude",
47
+ label: "Claude",
48
+ command: "claude",
49
+ args: [],
50
+ docs: "https://github.com/agentclientprotocol/claude-agent-acp"
51
+ },
52
+ {
53
+ id: "openclaw",
54
+ label: "OpenClaw",
55
+ command: "openclaw",
56
+ args: ["acp"],
57
+ docs: "https://docs.openclaw.ai/cli/acp"
58
+ }
59
+ ];
60
+ //#endregion
61
+ //#region src/settings-ui.tsx
62
+ /** Settings-specific guidance, separate from live delegation controls. */
63
+ /** Keeps feature refusals visible while the host handles gateway transport failures. */
64
+ function failureText(error) {
65
+ const failure = error?.failure;
66
+ if (failure === "offline" || failure === "authentication") return null;
67
+ return error instanceof Error ? error.message : String(error);
68
+ }
69
+ /** Settings translations keyed by the product's supported language-region IDs. */
70
+ var settingsCopy = {
71
+ "zh-CN": {
72
+ command: "启动程序",
73
+ addAgent: "添加 ACP 智能体",
74
+ runSettings: "运行设置",
75
+ chooseAgent: "添加 ACP 智能体",
76
+ available: "可添加",
77
+ unavailable: "未找到本机 CLI",
78
+ adapterMissing: "内置适配器缺失",
79
+ localCli: "本机 CLI",
80
+ launchCommand: "启动命令",
81
+ authorizationMode: "授权模式",
82
+ authorizationHelp: "本机权限:以本机用户权限运行,外部智能体自身审批仍生效。瑶光沙箱:优先使用可用后端限制访问;后端不可用时以无隔离模式运行,文件、网络、状态根和 gateway 不受隔离。",
83
+ bundledHelp: "由插件内置的 ACP 适配器调用此程序,使用本机已有登录。",
84
+ alreadyAdded: "已添加",
85
+ retryDetection: "重新检测",
86
+ detectFailed: "检测失败",
87
+ customIdHelp: "使用小写字母、数字和连字符,创建后不可修改。",
88
+ optionalArgs: "启动参数(可选)",
89
+ emptyAgents: "尚未添加 ACP 智能体",
90
+ emptyAgentsHelp: "添加 Claude、Codex 等智能体,或支持 ACP 协议的任意程序。",
91
+ customAgent: "自定义 ACP",
92
+ customHelp: "填写支持 ACP 标准输入 / 输出通信的程序及参数。",
93
+ presetHelp: "内置启动配置",
94
+ installGuide: "安装与使用说明",
95
+ installation: "启动配置",
96
+ commandHelp: "填写程序名或绝对路径;检测在瑶光网关所在机器上进行。不要把参数拼进程序路径。",
97
+ argsHelp: "每行是一个独立参数,不需要添加 shell 引号。",
98
+ inspect: "检测安装",
99
+ checking: "正在检测…",
100
+ found: "已找到可执行程序",
101
+ missing: "未找到可执行程序",
102
+ missingHelp: "请先安装,或填写正确的绝对路径,然后重新检测。",
103
+ directoryHelp: "该路径指向目录,请填写可执行程序的路径。",
104
+ unreadableHelp: "程序已找到,但网关没有读取或执行权限。请检查文件权限。",
105
+ unsupportedHelp: "程序已找到,但此启动格式不支持直接执行。请填写原生可执行程序的路径。",
106
+ relativePathHelp: "请填写完整绝对路径或仅填写程序名,不能使用相对路径。",
107
+ launcherUnsupported: "CLI 已找到,但启动格式不受支持",
108
+ launcherUnavailable: "CLI 已找到,但不可访问",
109
+ inspectionHelp: "仅检查文件和执行权限,不会启动程序。ACP 协议及登录状态尚未验证。",
110
+ openclawHelp: "启动前需配置并运行 OpenClaw Gateway,完成对应认证。",
111
+ adapterHelp: "需要安装 ACP 适配器;仅安装普通 CLI 并不代表已具备 ACP 接口。",
112
+ basic: "基本信息",
113
+ enabled: "允许委派",
114
+ toggleAgent: "启用",
115
+ disableAgent: "停用",
116
+ trustedMode: "本机权限",
117
+ sandboxMode: "瑶光沙箱",
118
+ trustedModeHelp: "以本机用户权限运行,不受瑶光沙箱限制;外部智能体自身的审批仍生效。",
119
+ detailCommandHelp: "填写程序名或绝对路径,启动参数单独填写。",
120
+ enabledHelp: "停用后不接受新委派,不会停止已经运行的任务。",
121
+ permissions: "执行权限",
122
+ advanced: "高级设置",
123
+ idHelp: "自动生成,用于引用此配置;创建后不可修改。",
124
+ saveAgent: "检测并保存",
125
+ saving: "正在保存…",
126
+ saved: "外部 Agent 已保存",
127
+ removed: "外部 Agent 已移除",
128
+ savedLimits: "运行设置已保存",
129
+ cancel: "取消",
130
+ closeSettings: "关闭",
131
+ deleteTitle: "移除外部 Agent?",
132
+ deleteHelp: "仅移除瑶光中的配置,不会卸载程序,也不会停止已在运行的任务。",
133
+ leaveTitle: "放弃未保存的修改?",
134
+ leaveHelp: "离开后,本次编辑的内容将不会保存。",
135
+ discard: "放弃修改",
136
+ stay: "继续编辑",
137
+ taskLimit: "并发任务上限",
138
+ connectionLimit: "保留连接上限",
139
+ tasksHelp: "包含正在执行和等待授权的任务。",
140
+ connectionsHelp: "任务结束后保留连接,供后续任务复用。",
141
+ limitsHelp: "每个主会话及其子会话共享以下额度。",
142
+ installedState: "配置已保存",
143
+ enabledState: "已启用",
144
+ disabledState: "已停用",
145
+ checkingFailed: "检测失败,请检查网关连接后重试。",
146
+ operationFailed: "操作失败,请重试。"
147
+ },
148
+ "en-US": {
149
+ command: "Executable",
150
+ addAgent: "Add ACP agent",
151
+ runSettings: "Runtime settings",
152
+ chooseAgent: "Add ACP agent",
153
+ available: "Available",
154
+ unavailable: "Local CLI not found",
155
+ adapterMissing: "Bundled adapter missing",
156
+ localCli: "Local CLI",
157
+ launchCommand: "Launch command",
158
+ authorizationMode: "Authorization mode",
159
+ authorizationHelp: "Local permissions: runs as your local user, retaining the external agent’s approvals. YaoGuang sandbox: uses an available backend first; otherwise runs without isolation of files, network, state roots or gateway.",
160
+ bundledHelp: "The plugin’s bundled ACP adapter calls this CLI using its existing sign-in.",
161
+ alreadyAdded: "Added",
162
+ retryDetection: "Check again",
163
+ detectFailed: "Check failed",
164
+ customIdHelp: "Use lowercase letters, numbers and hyphens. Cannot be changed after creation.",
165
+ optionalArgs: "Arguments (optional)",
166
+ emptyAgents: "No ACP agents yet",
167
+ emptyAgentsHelp: "Add agents such as Claude and Codex, or any program that supports ACP.",
168
+ customAgent: "Custom ACP",
169
+ customHelp: "Configure a program that speaks ACP over standard input and output.",
170
+ presetHelp: "Launch preset",
171
+ installGuide: "Installation and usage",
172
+ installation: "Launch configuration",
173
+ commandHelp: "Enter an executable name or absolute path on the gateway machine. Keep arguments in the field below.",
174
+ argsHelp: "One argument per line, without shell quoting.",
175
+ inspect: "Check installation",
176
+ checking: "Checking…",
177
+ found: "Executable found",
178
+ missing: "Executable not found",
179
+ missingHelp: "Install the program or enter its correct absolute path, then check again.",
180
+ directoryHelp: "This path names a directory. Enter the executable file path.",
181
+ unreadableHelp: "The program exists, but the gateway cannot read or execute it. Check its permissions.",
182
+ unsupportedHelp: "The program exists, but this launcher format cannot run directly. Enter a native executable path.",
183
+ relativePathHelp: "Enter a complete absolute path or a bare program name. Relative paths are unsupported.",
184
+ launcherUnsupported: "CLI found; launcher format unsupported",
185
+ launcherUnavailable: "CLI found; inaccessible",
186
+ inspectionHelp: "Checks the file and execute permission without starting it. ACP and authentication remain unverified.",
187
+ openclawHelp: "Configure and start the OpenClaw Gateway and complete its authentication before delegating.",
188
+ adapterHelp: "Install the ACP adapter. The ordinary CLI alone may not provide an ACP interface.",
189
+ basic: "Basic information",
190
+ enabled: "Allow delegation",
191
+ toggleAgent: "Enable",
192
+ disableAgent: "Disable",
193
+ trustedMode: "Local permissions",
194
+ sandboxMode: "YaoGuang sandbox",
195
+ trustedModeHelp: "Runs with local user permissions outside the YaoGuang sandbox. The external agent’s own approvals still apply.",
196
+ detailCommandHelp: "Enter an executable name or absolute path. Keep arguments separate.",
197
+ enabledHelp: "Disabling prevents new delegations without stopping running tasks.",
198
+ permissions: "Execution permissions",
199
+ advanced: "Advanced settings",
200
+ idHelp: "Generated automatically to identify this configuration; immutable after creation.",
201
+ saveAgent: "Check and save",
202
+ saving: "Saving…",
203
+ saved: "External agent saved",
204
+ removed: "External agent removed",
205
+ savedLimits: "Runtime settings saved",
206
+ cancel: "Cancel",
207
+ closeSettings: "Close",
208
+ deleteTitle: "Remove external agent?",
209
+ deleteHelp: "Removes this configuration without uninstalling the program or stopping running tasks.",
210
+ leaveTitle: "Discard unsaved changes?",
211
+ leaveHelp: "Your edits will not be saved if you leave.",
212
+ discard: "Discard changes",
213
+ stay: "Keep editing",
214
+ taskLimit: "Concurrent tasks",
215
+ connectionLimit: "Retained connections",
216
+ tasksHelp: "Includes running tasks and tasks awaiting permission.",
217
+ connectionsHelp: "Keep connections after tasks finish for follow-up work.",
218
+ limitsHelp: "Each root session shares these limits with its descendants.",
219
+ installedState: "Configuration saved",
220
+ enabledState: "Enabled",
221
+ disabledState: "Disabled",
222
+ checkingFailed: "Check failed. Verify the gateway connection and retry.",
223
+ operationFailed: "Operation failed. Please retry."
224
+ }
225
+ };
226
+ var INSPECTION_COPY = {
227
+ found: "found",
228
+ missing: "missingHelp",
229
+ directory: "directoryHelp",
230
+ unreadable: "unreadableHelp",
231
+ unsupported: "unsupportedHelp",
232
+ "relative-path": "relativePathHelp"
233
+ };
234
+ /** List, preset selection and detail editor for locally installed ACP agents. */
235
+ function settingsFor(ctx) {
236
+ return function Settings({ onLeaveGuard }) {
237
+ const host = useSyncExternalStore(ctx.host.subscribe, ctx.host.get);
238
+ const t = ctx.i18n.t;
239
+ const toast = ctx.ui.useToast();
240
+ const [instances, setInstances] = useState([]);
241
+ const [limits, setLimits] = useState({
242
+ maxConcurrent: 4,
243
+ maxRetainedConnections: 8
244
+ });
245
+ const [limitDraft, setLimitDraft] = useState(null);
246
+ const [choosing, setChoosing] = useState(false);
247
+ const [detectionRound, setDetectionRound] = useState(0);
248
+ const [availability, setAvailability] = useState({});
249
+ const [editor, setEditor] = useState(null);
250
+ const [removing, setRemoving] = useState(null);
251
+ const [inspection, setInspection] = useState(null);
252
+ const [checking, setChecking] = useState(false);
253
+ const [pending, setPending] = useState(false);
254
+ const [loading, setLoading] = useState(true);
255
+ const [loadError, setLoadError] = useState(null);
256
+ const [leavePrompt, setLeavePrompt] = useState(false);
257
+ const leaveResolve = useRef(null);
258
+ const busy = useRef(false);
259
+ const checkEpoch = useRef(0);
260
+ const mounted = useRef(true);
261
+ const dirty = editor !== null && JSON.stringify(editor.draft) !== JSON.stringify(editor.original) || limitDraft !== null && JSON.stringify(limitDraft) !== JSON.stringify(limits);
262
+ useEffect(() => {
263
+ mounted.current = true;
264
+ return () => {
265
+ mounted.current = false;
266
+ checkEpoch.current++;
267
+ leaveResolve.current?.(false);
268
+ };
269
+ }, []);
270
+ useEffect(() => {
271
+ let active = true;
272
+ setLoadError(null);
273
+ if (host.connection !== "online") {
274
+ setLoading(false);
275
+ return;
276
+ }
277
+ setLoading(true);
278
+ ctx.invoke("settings", {}).then((value) => {
279
+ if (!active) return;
280
+ setInstances(value.instances);
281
+ setLimits(value.limits);
282
+ setLoadError(null);
283
+ }, (error) => {
284
+ if (active) setLoadError(failureText(error));
285
+ }).finally(() => {
286
+ if (active) setLoading(false);
287
+ });
288
+ return () => {
289
+ active = false;
290
+ };
291
+ }, [host.connection]);
292
+ useEffect(() => {
293
+ if (!choosing || host.connection !== "online") return;
294
+ let active = true;
295
+ setAvailability({});
296
+ for (const preset of ACP_PRESETS) ctx.invoke("inspectPreset", { id: preset.id }).then((result) => {
297
+ if (active) setAvailability((previous) => ({
298
+ ...previous,
299
+ [preset.id]: result
300
+ }));
301
+ }, (error) => {
302
+ if (active && failureText(error) !== null) setAvailability((previous) => ({
303
+ ...previous,
304
+ [preset.id]: "error"
305
+ }));
306
+ });
307
+ return () => {
308
+ active = false;
309
+ };
310
+ }, [
311
+ choosing,
312
+ detectionRound,
313
+ host.connection
314
+ ]);
315
+ const askLeave = () => {
316
+ if (busy.current) return Promise.resolve(false);
317
+ if (!dirty) return Promise.resolve(true);
318
+ if (leaveResolve.current) return Promise.resolve(false);
319
+ setLeavePrompt(true);
320
+ return new Promise((resolve) => {
321
+ leaveResolve.current = resolve;
322
+ });
323
+ };
324
+ const guard = useRef(askLeave);
325
+ guard.current = askLeave;
326
+ useEffect(() => {
327
+ onLeaveGuard?.(() => guard.current());
328
+ return () => onLeaveGuard?.(null);
329
+ }, [onLeaveGuard]);
330
+ useEffect(() => {
331
+ if (!dirty) return;
332
+ const prevent = (event) => event.preventDefault();
333
+ window.addEventListener("beforeunload", prevent);
334
+ return () => window.removeEventListener("beforeunload", prevent);
335
+ }, [dirty]);
336
+ function resolveLeave(allow) {
337
+ setLeavePrompt(false);
338
+ leaveResolve.current?.(allow);
339
+ leaveResolve.current = null;
340
+ }
341
+ function closeEditor() {
342
+ askLeave().then((allow) => {
343
+ if (allow) {
344
+ checkEpoch.current++;
345
+ setChecking(false);
346
+ setEditor(null);
347
+ setInspection(null);
348
+ }
349
+ });
350
+ }
351
+ function change(fields) {
352
+ checkEpoch.current++;
353
+ setChecking(false);
354
+ setInspection(null);
355
+ setEditor((previous) => previous && {
356
+ ...previous,
357
+ draft: {
358
+ ...previous.draft,
359
+ ...fields
360
+ }
361
+ });
362
+ }
363
+ async function inspect(command) {
364
+ const epoch = ++checkEpoch.current;
365
+ setChecking(true);
366
+ setInspection(null);
367
+ try {
368
+ const result = await ctx.invoke("inspectCommand", { command });
369
+ if (!mounted.current || epoch !== checkEpoch.current) return null;
370
+ setInspection(result);
371
+ return result;
372
+ } catch (error) {
373
+ if (mounted.current && epoch === checkEpoch.current && failureText(error) !== null) toast.add({
374
+ tone: "destructive",
375
+ title: t("checkingFailed")
376
+ });
377
+ return null;
378
+ } finally {
379
+ if (mounted.current && epoch === checkEpoch.current) setChecking(false);
380
+ }
381
+ }
382
+ function choose(presetId) {
383
+ const preset = ACP_PRESETS.find((item) => item.id === presetId);
384
+ const draft = {
385
+ id: `${preset?.id ?? "custom"}-${ctx.uuid()}`,
386
+ label: preset?.label ?? "",
387
+ command: preset?.command ?? "",
388
+ args: preset ? [...preset.args] : [],
389
+ enabled: true,
390
+ executionMode: "trusted",
391
+ authPaths: [],
392
+ networkHosts: [],
393
+ env: {},
394
+ revision: 0
395
+ };
396
+ if (preset) run(async () => {
397
+ const saved = await ctx.invoke("addPreset", { id: preset.id });
398
+ setInstances((rows) => [...rows, saved]);
399
+ setChoosing(false);
400
+ setEditor(null);
401
+ toast.add({
402
+ tone: "success",
403
+ title: t("saved")
404
+ });
405
+ });
406
+ else {
407
+ setEditor({
408
+ draft,
409
+ original: draft,
410
+ preset: null,
411
+ fresh: true
412
+ });
413
+ setInspection(null);
414
+ }
415
+ }
416
+ async function run(action) {
417
+ if (busy.current) return;
418
+ busy.current = true;
419
+ setPending(true);
420
+ try {
421
+ await action();
422
+ } catch (error) {
423
+ if (mounted.current && failureText(error) !== null) {
424
+ toast.add({
425
+ tone: "destructive",
426
+ title: t("operationFailed")
427
+ });
428
+ if (choosing) setDetectionRound((round) => round + 1);
429
+ }
430
+ } finally {
431
+ busy.current = false;
432
+ if (mounted.current) setPending(false);
433
+ }
434
+ }
435
+ async function saveAgent() {
436
+ if (!editor) return;
437
+ const current = editor.draft;
438
+ await run(async () => {
439
+ const result = await inspect(current.command);
440
+ if (result?.status !== "found" || !result.path) return;
441
+ const saved = await ctx.invoke("saveInstance", {
442
+ ...current,
443
+ label: current.label.trim(),
444
+ command: result.path,
445
+ args: current.args
446
+ });
447
+ setInstances((rows) => [...rows.filter((row) => row.id !== saved.id), saved]);
448
+ setEditor(null);
449
+ setChoosing(false);
450
+ setInspection(null);
451
+ toast.add({
452
+ tone: "success",
453
+ title: t("saved")
454
+ });
455
+ });
456
+ }
457
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
458
+ /* @__PURE__ */ jsxs("div", {
459
+ className: "acp-stack acp-settings",
460
+ children: [/* @__PURE__ */ jsxs("div", {
461
+ className: "acp-toolbar",
462
+ children: [/* @__PURE__ */ jsx(ctx.ui.Button, {
463
+ variant: "outline",
464
+ icon: "plus",
465
+ disabled: loading || loadError !== null || host.connection !== "online",
466
+ onClick: () => setChoosing(true),
467
+ children: t("addAgent")
468
+ }), /* @__PURE__ */ jsx(ctx.ui.Button, {
469
+ variant: "ghost",
470
+ disabled: loading || loadError !== null,
471
+ icon: "settings",
472
+ onClick: () => setLimitDraft(limits),
473
+ children: t("runSettings")
474
+ })]
475
+ }), loadError ? /* @__PURE__ */ jsx(ctx.ui.Alert, {
476
+ tone: "destructive",
477
+ children: loadError
478
+ }) : loading ? /* @__PURE__ */ jsx("p", {
479
+ className: "acp-help",
480
+ children: t("checking")
481
+ }) : instances.length === 0 ? /* @__PURE__ */ jsx(ctx.ui.EmptyState, {
482
+ title: t("emptyAgents"),
483
+ description: t("emptyAgentsHelp")
484
+ }) : /* @__PURE__ */ jsx("div", {
485
+ className: "acp-stack",
486
+ children: instances.map((row) => /* @__PURE__ */ jsxs("div", {
487
+ className: "acp-agent-row",
488
+ children: [
489
+ /* @__PURE__ */ jsxs(ctx.ui.Button, {
490
+ variant: "plain",
491
+ className: "acp-agent-link",
492
+ disabled: pending,
493
+ onClick: () => {
494
+ checkEpoch.current++;
495
+ setInspection(null);
496
+ setChecking(false);
497
+ setEditor({
498
+ draft: row,
499
+ original: row,
500
+ preset: null,
501
+ fresh: false
502
+ });
503
+ },
504
+ children: [
505
+ /* @__PURE__ */ jsx(ctx.ui.Tooltip, {
506
+ content: t(row.enabled ? "enabledState" : "disabledState"),
507
+ children: /* @__PURE__ */ jsx("span", {
508
+ className: "acp-agent-dot",
509
+ "data-enabled": row.enabled,
510
+ role: "img",
511
+ "aria-label": t(row.enabled ? "enabledState" : "disabledState")
512
+ })
513
+ }),
514
+ /* @__PURE__ */ jsxs("span", {
515
+ className: "acp-agent-summary",
516
+ children: [/* @__PURE__ */ jsx("span", { children: row.label }), /* @__PURE__ */ jsx("span", {
517
+ className: "acp-help acp-command",
518
+ children: [row.command, ...row.args].join(" ")
519
+ })]
520
+ }),
521
+ /* @__PURE__ */ jsx("span", {
522
+ className: "acp-agent-chevron",
523
+ "aria-hidden": "true",
524
+ children: "›"
525
+ })
526
+ ]
527
+ }),
528
+ /* @__PURE__ */ jsx("div", {
529
+ className: "acp-agent-toggle",
530
+ children: /* @__PURE__ */ jsx(ctx.ui.Button, {
531
+ variant: "ghost",
532
+ size: "sm",
533
+ icon: row.enabled ? "stop" : "play",
534
+ title: `${t(row.enabled ? "disableAgent" : "toggleAgent")} ${row.label}`,
535
+ "aria-label": `${t(row.enabled ? "disableAgent" : "toggleAgent")} ${row.label}`,
536
+ disabled: pending || host.connection !== "online",
537
+ onClick: () => void run(async () => {
538
+ const saved = await ctx.invoke("saveInstance", {
539
+ ...row,
540
+ enabled: !row.enabled
541
+ });
542
+ setInstances((rows) => rows.map((item) => item.id === saved.id ? saved : item));
543
+ toast.add({
544
+ tone: "success",
545
+ title: `${row.label} · ${t(saved.enabled ? "enabledState" : "disabledState")}`
546
+ });
547
+ })
548
+ })
549
+ }),
550
+ /* @__PURE__ */ jsx(ctx.ui.Button, {
551
+ variant: "ghost",
552
+ icon: "trash",
553
+ size: "sm",
554
+ className: "acp-agent-delete",
555
+ disabled: pending,
556
+ title: `${t("remove")} · ${row.label}`,
557
+ "aria-label": `${t("remove")} · ${row.label}`,
558
+ onClick: () => setRemoving(row)
559
+ })
560
+ ]
561
+ }, row.id))
562
+ })]
563
+ }),
564
+ /* @__PURE__ */ jsx(ctx.ui.Dialog, {
565
+ open: choosing,
566
+ onOpenChange: (open) => {
567
+ if (open) setChoosing(true);
568
+ else askLeave().then((allow) => {
569
+ if (allow) {
570
+ setChoosing(false);
571
+ setEditor(null);
572
+ setInspection(null);
573
+ checkEpoch.current++;
574
+ setChecking(false);
575
+ }
576
+ });
577
+ },
578
+ title: t("chooseAgent"),
579
+ closeLabel: t("closeSettings"),
580
+ children: /* @__PURE__ */ jsxs("div", {
581
+ className: "acp-editor",
582
+ children: [
583
+ /* @__PURE__ */ jsxs("div", {
584
+ className: "acp-preset-grid",
585
+ children: [ACP_PRESETS.map((item) => {
586
+ const result = availability[item.id];
587
+ const found = result && result !== "error" && result.status === "found";
588
+ const added = instances.some((row) => row.adapter === item.id || !row.adapter && item.id === "openclaw" && (row.command === item.command || found && row.command === result.path) && JSON.stringify(row.args) === JSON.stringify(item.args));
589
+ const status = added ? "alreadyAdded" : !result ? "checking" : result === "error" ? "detectFailed" : found ? "available" : result.status === "missing-adapter" ? "adapterMissing" : result.status === "unsupported-cli" ? "launcherUnsupported" : result.status === "unavailable-cli" ? "launcherUnavailable" : "unavailable";
590
+ return /* @__PURE__ */ jsxs(ctx.ui.Button, {
591
+ variant: "option",
592
+ className: "acp-preset",
593
+ disabled: !found || added || pending || host.connection !== "online",
594
+ "data-available": !!found && !added,
595
+ onClick: () => void askLeave().then((allow) => {
596
+ if (allow) {
597
+ setEditor(null);
598
+ choose(item.id);
599
+ }
600
+ }),
601
+ children: [
602
+ /* @__PURE__ */ jsx("img", {
603
+ className: "acp-preset-logo",
604
+ src: presetLogos[item.id],
605
+ alt: ""
606
+ }),
607
+ /* @__PURE__ */ jsx("span", { children: item.label }),
608
+ /* @__PURE__ */ jsx("span", {
609
+ className: "acp-help",
610
+ children: t(status)
611
+ })
612
+ ]
613
+ }, item.id);
614
+ }), /* @__PURE__ */ jsxs(ctx.ui.Button, {
615
+ variant: "option",
616
+ className: "acp-preset",
617
+ "data-available": "true",
618
+ "aria-pressed": !!editor?.fresh,
619
+ disabled: pending,
620
+ onClick: () => {
621
+ if (!editor) choose(null);
622
+ },
623
+ children: [/* @__PURE__ */ jsxs("svg", {
624
+ className: "acp-preset-logo",
625
+ viewBox: "0 0 24 24",
626
+ fill: "none",
627
+ stroke: "currentColor",
628
+ strokeWidth: "1.5",
629
+ "aria-hidden": "true",
630
+ children: [/* @__PURE__ */ jsx("rect", {
631
+ x: "2",
632
+ y: "3",
633
+ width: "20",
634
+ height: "18",
635
+ rx: "3"
636
+ }), /* @__PURE__ */ jsx("path", { d: "m6 8 4 4-4 4m7 0h5" })]
637
+ }), /* @__PURE__ */ jsx("span", { children: t("customAgent") })]
638
+ })]
639
+ }),
640
+ editor?.fresh && /* @__PURE__ */ jsxs("form", {
641
+ className: "acp-editor",
642
+ onSubmit: (event) => {
643
+ event.preventDefault();
644
+ saveAgent();
645
+ },
646
+ children: [
647
+ /* @__PURE__ */ jsxs("fieldset", {
648
+ className: "acp-editor-fields",
649
+ disabled: pending,
650
+ children: [
651
+ /* @__PURE__ */ jsx(ctx.ui.Field, {
652
+ inline: true,
653
+ required: true,
654
+ label: t("name"),
655
+ children: (binding) => /* @__PURE__ */ jsx(ctx.ui.Input, {
656
+ ...binding,
657
+ autoFocus: true,
658
+ value: editor.draft.label,
659
+ onChange: (event) => change({ label: event.target.value })
660
+ })
661
+ }),
662
+ /* @__PURE__ */ jsx(ctx.ui.Field, {
663
+ inline: true,
664
+ required: true,
665
+ label: t("id"),
666
+ help: t("customIdHelp"),
667
+ error: instances.some((row) => row.id === editor.draft.id) ? t("alreadyAdded") : void 0,
668
+ children: (binding) => /* @__PURE__ */ jsx(ctx.ui.Input, {
669
+ ...binding,
670
+ pattern: "[a-z0-9][a-z0-9-]*",
671
+ value: editor.draft.id,
672
+ onChange: (event) => change({ id: event.target.value })
673
+ })
674
+ }),
675
+ /* @__PURE__ */ jsx(ctx.ui.Field, {
676
+ inline: true,
677
+ required: true,
678
+ label: t("command"),
679
+ help: t("commandHelp"),
680
+ children: (binding) => /* @__PURE__ */ jsx(ctx.ui.Input, {
681
+ ...binding,
682
+ value: editor.draft.command,
683
+ onChange: (event) => change({ command: event.target.value })
684
+ })
685
+ }),
686
+ /* @__PURE__ */ jsxs(ctx.ui.Disclosure, { children: [/* @__PURE__ */ jsx(ctx.ui.DisclosureSummary, { children: t("optionalArgs") }), /* @__PURE__ */ jsx("div", {
687
+ className: "acp-disclosure-body",
688
+ children: /* @__PURE__ */ jsx(ctx.ui.Field, {
689
+ label: t("args"),
690
+ help: t("argsHelp"),
691
+ children: (binding) => /* @__PURE__ */ jsx(ctx.ui.Textarea, {
692
+ ...binding,
693
+ rows: 2,
694
+ value: editor.draft.args.join("\n"),
695
+ onChange: (event) => change({ args: event.target.value.split("\n") })
696
+ })
697
+ })
698
+ })] })
699
+ ]
700
+ }),
701
+ inspection && inspection.status !== "found" && /* @__PURE__ */ jsx(ctx.ui.Alert, {
702
+ tone: "destructive",
703
+ role: "status",
704
+ children: t(INSPECTION_COPY[inspection.status])
705
+ }),
706
+ /* @__PURE__ */ jsxs("div", {
707
+ className: "acp-actions",
708
+ children: [/* @__PURE__ */ jsx(ctx.ui.Button, {
709
+ variant: "ghost",
710
+ disabled: pending,
711
+ onClick: () => void askLeave().then((allow) => {
712
+ if (allow) {
713
+ setEditor(null);
714
+ setInspection(null);
715
+ }
716
+ }),
717
+ children: t("cancel")
718
+ }), /* @__PURE__ */ jsx(ctx.ui.Button, {
719
+ type: "submit",
720
+ variant: "primary",
721
+ disabled: pending || checking || !editor.draft.label.trim() || !editor.draft.command.trim() || !/^[a-z0-9][a-z0-9-]*$/.test(editor.draft.id) || instances.some((row) => row.id === editor.draft.id) || host.connection !== "online",
722
+ children: t(pending ? "saving" : "saveAgent")
723
+ })]
724
+ })
725
+ ]
726
+ }),
727
+ /* @__PURE__ */ jsx("div", {
728
+ className: "acp-recheck",
729
+ children: /* @__PURE__ */ jsx(ctx.ui.Button, {
730
+ variant: "ghost",
731
+ icon: "refresh",
732
+ disabled: pending || checking,
733
+ onClick: () => setDetectionRound((round) => round + 1),
734
+ children: t("retryDetection")
735
+ })
736
+ })
737
+ ]
738
+ })
739
+ }),
740
+ /* @__PURE__ */ jsx(ctx.ui.SettingsDetail, {
741
+ open: editor !== null && !editor.fresh,
742
+ onOpenChange: (open) => {
743
+ if (!open) closeEditor();
744
+ },
745
+ title: editor?.fresh ? t("addAgent") : editor?.original.label ?? "",
746
+ children: editor && !editor.fresh && /* @__PURE__ */ jsxs("form", {
747
+ className: "acp-editor acp-detail-editor",
748
+ onSubmit: (event) => {
749
+ event.preventDefault();
750
+ saveAgent();
751
+ },
752
+ children: [/* @__PURE__ */ jsxs("fieldset", {
753
+ className: "acp-editor-fields",
754
+ disabled: pending,
755
+ children: [
756
+ /* @__PURE__ */ jsx(ctx.ui.Field, {
757
+ inline: true,
758
+ required: true,
759
+ label: t("name"),
760
+ children: (binding) => /* @__PURE__ */ jsx(ctx.ui.Input, {
761
+ ...binding,
762
+ value: editor.draft.label,
763
+ onChange: (event) => change({ label: event.target.value })
764
+ })
765
+ }),
766
+ /* @__PURE__ */ jsx(ctx.ui.Field, {
767
+ inline: true,
768
+ label: t("authorizationMode"),
769
+ help: t("authorizationHelp"),
770
+ children: () => /* @__PURE__ */ jsx(ctx.ui.Segmented, {
771
+ label: t("authorizationMode"),
772
+ disabled: pending,
773
+ value: editor.draft.executionMode,
774
+ options: [{
775
+ value: "trusted",
776
+ label: t("trustedMode")
777
+ }, {
778
+ value: "sandbox",
779
+ label: t("sandboxMode")
780
+ }],
781
+ onSelect: (value) => change({ executionMode: value })
782
+ })
783
+ }),
784
+ /* @__PURE__ */ jsx(ctx.ui.Field, {
785
+ inline: true,
786
+ required: true,
787
+ label: t("launchCommand"),
788
+ children: (binding) => /* @__PURE__ */ jsxs("div", {
789
+ className: "acp-command-field",
790
+ children: [/* @__PURE__ */ jsx(ctx.ui.Input, {
791
+ ...binding,
792
+ value: editor.draft.command,
793
+ onChange: (event) => change({ command: event.target.value })
794
+ }), /* @__PURE__ */ jsx(ctx.ui.Button, {
795
+ type: "button",
796
+ variant: "outline",
797
+ icon: "refresh",
798
+ disabled: checking || !editor.draft.command.trim() || host.connection !== "online",
799
+ onClick: () => {
800
+ inspect(editor.draft.command);
801
+ },
802
+ children: t(checking ? "checking" : "inspect")
803
+ })]
804
+ })
805
+ }),
806
+ inspection && /* @__PURE__ */ jsx(ctx.ui.Alert, {
807
+ tone: inspection.status === "found" ? "success" : "warning",
808
+ role: "status",
809
+ children: t(INSPECTION_COPY[inspection.status])
810
+ }),
811
+ /* @__PURE__ */ jsx(ctx.ui.Field, {
812
+ inline: true,
813
+ label: t("args"),
814
+ children: (binding) => /* @__PURE__ */ jsx(ctx.ui.Textarea, {
815
+ ...binding,
816
+ rows: 2,
817
+ value: editor.draft.args.join("\n"),
818
+ onChange: (event) => change({ args: event.target.value.split("\n") })
819
+ })
820
+ })
821
+ ]
822
+ }), /* @__PURE__ */ jsxs("div", {
823
+ className: "acp-actions",
824
+ children: [/* @__PURE__ */ jsx(ctx.ui.Button, {
825
+ type: "button",
826
+ variant: "ghost",
827
+ disabled: pending,
828
+ onClick: closeEditor,
829
+ children: t("cancel")
830
+ }), /* @__PURE__ */ jsx(ctx.ui.Button, {
831
+ type: "submit",
832
+ variant: "primary",
833
+ disabled: pending || checking || !editor.draft.label.trim() || !editor.draft.command.trim() || host.connection !== "online",
834
+ children: t(pending ? "saving" : "saveAgent")
835
+ })]
836
+ })]
837
+ })
838
+ }),
839
+ /* @__PURE__ */ jsx(ctx.ui.Dialog, {
840
+ open: limitDraft !== null,
841
+ onOpenChange: (open) => {
842
+ if (!open) askLeave().then((allow) => {
843
+ if (allow) setLimitDraft(null);
844
+ });
845
+ },
846
+ size: "sm",
847
+ title: t("runSettings"),
848
+ closeLabel: t("closeSettings"),
849
+ children: limitDraft && /* @__PURE__ */ jsxs("form", {
850
+ className: "acp-editor",
851
+ onSubmit: (event) => {
852
+ event.preventDefault();
853
+ run(async () => {
854
+ const saved = await ctx.invoke("setLimits", limitDraft);
855
+ setLimits(saved);
856
+ setLimitDraft(null);
857
+ toast.add({
858
+ tone: "success",
859
+ title: t("savedLimits")
860
+ });
861
+ });
862
+ },
863
+ children: [
864
+ /* @__PURE__ */ jsx("p", {
865
+ className: "acp-help",
866
+ children: t("limitsHelp")
867
+ }),
868
+ ["maxConcurrent", "maxRetainedConnections"].map((key) => /* @__PURE__ */ jsx(ctx.ui.Field, {
869
+ inline: true,
870
+ required: true,
871
+ className: "acp-limit-field",
872
+ label: t(key === "maxConcurrent" ? "taskLimit" : "connectionLimit"),
873
+ help: t(key === "maxConcurrent" ? "tasksHelp" : "connectionsHelp"),
874
+ children: (binding) => /* @__PURE__ */ jsx(ctx.ui.InputNumber, {
875
+ ...binding,
876
+ required: true,
877
+ min: 1,
878
+ disabled: pending,
879
+ value: limitDraft[key] || null,
880
+ label: t(key === "maxConcurrent" ? "taskLimit" : "connectionLimit"),
881
+ incrementLabel: t("increase"),
882
+ decrementLabel: t("decrease"),
883
+ onValueChange: (value) => setLimitDraft((current) => current && {
884
+ ...current,
885
+ [key]: value ?? 0
886
+ })
887
+ })
888
+ }, key)),
889
+ /* @__PURE__ */ jsx("div", {
890
+ className: "acp-actions",
891
+ children: /* @__PURE__ */ jsx(ctx.ui.Button, {
892
+ type: "submit",
893
+ variant: "primary",
894
+ disabled: pending || limitDraft.maxConcurrent < 1 || limitDraft.maxRetainedConnections < 1 || host.connection !== "online",
895
+ children: t("save")
896
+ })
897
+ })
898
+ ]
899
+ })
900
+ }),
901
+ /* @__PURE__ */ jsxs(ctx.ui.AlertDialog, {
902
+ open: removing !== null,
903
+ onOpenChange: (open) => {
904
+ if (!pending && !open) setRemoving(null);
905
+ },
906
+ title: t("deleteTitle"),
907
+ actions: /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(ctx.ui.Button, {
908
+ variant: "ghost",
909
+ disabled: pending,
910
+ onClick: () => setRemoving(null),
911
+ children: t("cancel")
912
+ }), /* @__PURE__ */ jsx(ctx.ui.Button, {
913
+ variant: "destructive",
914
+ disabled: pending,
915
+ onClick: () => {
916
+ if (removing) run(async () => {
917
+ await ctx.invoke("removeInstance", { id: removing.id });
918
+ setInstances((rows) => rows.filter((row) => row.id !== removing.id));
919
+ setRemoving(null);
920
+ toast.add({
921
+ tone: "success",
922
+ title: t("removed")
923
+ });
924
+ });
925
+ },
926
+ children: t("remove")
927
+ })] }),
928
+ children: [/* @__PURE__ */ jsx("p", { children: removing?.label }), /* @__PURE__ */ jsx("p", { children: t("deleteHelp") })]
929
+ }),
930
+ /* @__PURE__ */ jsx(ctx.ui.AlertDialog, {
931
+ open: leavePrompt,
932
+ onOpenChange: (open) => {
933
+ if (!open) resolveLeave(false);
934
+ },
935
+ title: t("leaveTitle"),
936
+ actions: /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(ctx.ui.Button, {
937
+ variant: "ghost",
938
+ onClick: () => resolveLeave(false),
939
+ children: t("stay")
940
+ }), /* @__PURE__ */ jsx(ctx.ui.Button, {
941
+ variant: "destructive",
942
+ onClick: () => resolveLeave(true),
943
+ children: t("discard")
944
+ })] }),
945
+ children: /* @__PURE__ */ jsx("p", { children: t("leaveHelp") })
946
+ })
947
+ ] });
948
+ };
949
+ }
950
+ //#endregion
951
+ //#region src/tool-names.ts
952
+ /** Canonical names shared by tool registration and browser presentation. */
953
+ var TOOL_NAMES = [
954
+ "acp_instances",
955
+ "acp_delegate",
956
+ "acp_send",
957
+ "acp_get",
958
+ "acp_list",
959
+ "acp_stop"
960
+ ];
961
+ //#endregion
962
+ //#region src/ui/metadata.ts
963
+ var CATALOGUES = {
964
+ "en-US": {
965
+ section: "Built-in plugins",
966
+ group: "External agents",
967
+ acp_instances: "List delegable agents",
968
+ acp_delegate: "Delegate to agent",
969
+ acp_send: "Send agent task",
970
+ acp_get: "Inspect agent task",
971
+ acp_list: "List agent tasks",
972
+ acp_stop: "Stop agent task"
973
+ },
974
+ "zh-CN": {
975
+ section: "内置插件",
976
+ group: "外部智能体",
977
+ acp_instances: "列出可委派智能体",
978
+ acp_delegate: "委派外部智能体",
979
+ acp_send: "发送智能体任务",
980
+ acp_get: "查看智能体进度",
981
+ acp_list: "查看智能体任务",
982
+ acp_stop: "停止智能体任务"
983
+ }
984
+ };
985
+ var names = new Set(TOOL_NAMES);
986
+ /** Registers presentation facets with the same activation lifetime as the tools. */
987
+ function registerMetadata(ctx) {
988
+ ctx.i18n.register(CATALOGUES, "en-US");
989
+ ctx.i18n.contribute(Object.fromEntries(Object.entries(CATALOGUES).map(([language, catalogue]) => [language, Object.fromEntries([...names].map((tool) => [`transcript.actions.${tool}`, catalogue[tool] ?? tool]))])), "en-US");
990
+ ctx.slots.register("chat.tool.presentation", {
991
+ id: "tool-metadata",
992
+ describe: ({ call }) => {
993
+ if (!names.has(call.name)) return void 0;
994
+ const input = call.input !== null && typeof call.input === "object" ? call.input : {};
995
+ const summary = [
996
+ "path",
997
+ "url",
998
+ "query",
999
+ "command",
1000
+ "skill",
1001
+ "id",
1002
+ "name",
1003
+ "task",
1004
+ "prompt"
1005
+ ].flatMap((key) => typeof input[key] === "string" ? [input[key]] : []).slice(0, 2).join(" · ").replace(/\s+/g, " ").slice(0, 240);
1006
+ return {
1007
+ label: names.has(call.name) ? ctx.i18n.t(call.name) : call.name,
1008
+ icon: "hammer",
1009
+ summary
1010
+ };
1011
+ }
1012
+ });
1013
+ ctx.slots.register("shell.tools.group", {
1014
+ id: "tool-groups",
1015
+ describe: (tool) => {
1016
+ if (tool.plugin !== ctx.plugin) return void 0;
1017
+ return {
1018
+ key: `plugin:${ctx.plugin}`,
1019
+ label: ctx.i18n.t("group"),
1020
+ source: ctx.plugin,
1021
+ sectionLabel: ctx.i18n.t("section"),
1022
+ sectionOrder: 1,
1023
+ order: 8
1024
+ };
1025
+ }
1026
+ });
1027
+ }
1028
+ //#endregion
1029
+ //#region src/ui.tsx
1030
+ var runtimeVersion = 5;
1031
+ var errorHelp = {
1032
+ "auth-required": "errorAuth",
1033
+ "session-setup-failed": "errorSetup",
1034
+ "resume-unavailable": "errorSetup",
1035
+ "external-refusal": "errorRefusal",
1036
+ "external-limit": "errorLimit"
1037
+ };
1038
+ var copy = {
1039
+ "zh-CN": {
1040
+ increase: "增加",
1041
+ loading: "加载中…",
1042
+ retry: "重试",
1043
+ decrease: "减少",
1044
+ errorAuth: "创建外部会话前缺少认证。请在本机 CLI 登录后重新委派。",
1045
+ errorSetup: "外部会话创建或恢复失败。请检查 CLI 版本、执行模式和认证路径;无法恢复时新建委派。",
1046
+ errorRefusal: "外部代理拒绝了任务。请调整任务要求后再试。",
1047
+ errorLimit: "外部代理达到执行限制,任务未完成。可缩小任务或明确追加后续任务。",
1048
+ errorOther: "请检查适配器安装、网络与本机登录状态,再明确重试。",
1049
+ mode: "执行模式",
1050
+ effectiveMode: "实际执行模式",
1051
+ directMode: "无隔离",
1052
+ fallbackWarning: "沙箱不可用,文件、网络、瑶光状态和 gateway 均未隔离。",
1053
+ trusted: "受信本机代理(Codex / Claude 推荐)",
1054
+ sandbox: "瑶光沙箱",
1055
+ trustHint: "受信模式以你的本机权限运行,瑶光不限制其文件访问;外部代理自身权限与审批仍生效。代理连接统一使用网关网络设置,修改后需重建已有连接。",
1056
+ sandboxHint: "优先使用可用沙箱;后端不可用时以本地用户权限运行,不隔离文件、网络或瑶光状态。代理设置不授予联网权限。",
1057
+ title: "ACP",
1058
+ pending: "待执行",
1059
+ running: "进行中",
1060
+ waiting: "等待授权",
1061
+ completed: "已完成",
1062
+ cancelled: "已取消",
1063
+ failed: "执行失败",
1064
+ retained: "连接已保留",
1065
+ settings: "ACP 设置",
1066
+ stop: "停止任务",
1067
+ close: "关闭连接",
1068
+ send: "追加任务",
1069
+ save: "保存",
1070
+ add: "添加适配器",
1071
+ name: "名称",
1072
+ id: "标识",
1073
+ command: "可执行文件绝对路径",
1074
+ args: "启动参数",
1075
+ cwd: "工作目录",
1076
+ read: "认证只读路径(每行一个)",
1077
+ write: "认证可写路径(每行一个)",
1078
+ hosts: "网络主机(每行一个)",
1079
+ concurrency: "每个主会话的任务上限",
1080
+ connections: "每个主会话的连接上限",
1081
+ remove: "移除配置",
1082
+ offline: "连接已断开",
1083
+ permission: "外部代理正在等待授权,请在对话末尾的请求卡片里处理",
1084
+ start: "新建委派",
1085
+ preflight: "检查连接(不发送任务)",
1086
+ checked: "协议连接可用;登录状态需由实际任务验证。",
1087
+ task: "任务",
1088
+ allow: "允许启动",
1089
+ reject: "拒绝",
1090
+ hint: "请先安装适配器并在本机完成登录。选择执行模式后保存。",
1091
+ history: "任务记录",
1092
+ older: "加载较早任务",
1093
+ next: "加载后续记录"
1094
+ },
1095
+ "en-US": {
1096
+ increase: "Increase",
1097
+ loading: "Loading…",
1098
+ retry: "Retry",
1099
+ decrease: "Decrease",
1100
+ errorAuth: "Authentication was unavailable before session creation. Sign in through the local CLI, then delegate again.",
1101
+ errorSetup: "Session creation or recovery failed. Check the CLI version, execution mode and authentication paths; create a new delegation if recovery remains unavailable.",
1102
+ errorRefusal: "The external agent refused the task. Revise the request before retrying.",
1103
+ errorLimit: "The external agent reached an execution limit. Narrow the task or explicitly append follow-up work.",
1104
+ errorOther: "Check the adapter installation, network and local sign-in, then explicitly retry.",
1105
+ mode: "Execution mode",
1106
+ effectiveMode: "Actual execution mode",
1107
+ directMode: "Without isolation",
1108
+ fallbackWarning: "Sandbox unavailable. Files, network, YaoGuang state and gateway are not isolated.",
1109
+ trusted: "Trusted local agent (recommended for Codex / Claude)",
1110
+ sandbox: "YaoGuang sandbox",
1111
+ trustHint: "Runs with your local user permissions, outside YaoGuang file restrictions. External permissions and approvals remain active. Gateway network settings apply to new connections; recreate existing connections after changes.",
1112
+ sandboxHint: "Uses an available sandbox first. When unavailable, runs with local user permissions without file, network or YaoGuang state isolation. Proxy settings do not grant network access.",
1113
+ title: "ACP",
1114
+ pending: "Pending",
1115
+ running: "Running",
1116
+ waiting: "Awaiting permission",
1117
+ completed: "Completed",
1118
+ cancelled: "Cancelled",
1119
+ failed: "Failed",
1120
+ retained: "Connection retained",
1121
+ settings: "ACP settings",
1122
+ stop: "Stop task",
1123
+ close: "Close connection",
1124
+ send: "Append task",
1125
+ save: "Save",
1126
+ add: "Add adapter",
1127
+ name: "Name",
1128
+ id: "ID",
1129
+ command: "Absolute executable path",
1130
+ args: "Arguments",
1131
+ cwd: "Working directory",
1132
+ read: "Read-only authentication paths (one per line)",
1133
+ write: "Writable authentication paths (one per line)",
1134
+ hosts: "Network hosts (one per line)",
1135
+ concurrency: "Tasks per root session",
1136
+ connections: "Connections per root session",
1137
+ remove: "Remove configuration",
1138
+ offline: "Disconnected",
1139
+ permission: "The external agent is waiting for permission; answer it on the request card at the end of the conversation",
1140
+ start: "New delegation",
1141
+ preflight: "Check connection (no task)",
1142
+ checked: "Protocol connection is available; authentication is not yet verified.",
1143
+ task: "Task",
1144
+ allow: "Allow launch",
1145
+ reject: "Reject",
1146
+ hint: "Install the adapter and sign in locally, then choose an execution mode and save.",
1147
+ history: "Task history",
1148
+ older: "Load earlier tasks",
1149
+ next: "Load subsequent records"
1150
+ }
1151
+ };
1152
+ /** A failed call as a toast: the gateway's own sentence, never the error's
1153
+ * class name; an offline failure says nothing, because the host's
1154
+ * connection dialog owns the outage. */
1155
+ function showFailure(toast, error) {
1156
+ const failure = error?.failure;
1157
+ if (failure === "offline" || failure === "authentication") return;
1158
+ const text = error instanceof Error ? error.message : String(error);
1159
+ toast.add({
1160
+ id: `failure::${text}`,
1161
+ title: text,
1162
+ tone: "destructive"
1163
+ });
1164
+ }
1165
+ /** Still running: a task in flight or waiting, or a connection that holds a
1166
+ * live process. The section shows running work only, so a delegation that
1167
+ * has finished and let go of its process is not listed. */
1168
+ function activeOf(entry) {
1169
+ const state = statusOf(entry);
1170
+ return state === "running" || state === "pending" || state === "waiting" || entry.delegation.connectionState === "starting" || entry.delegation.connectionState === "connected";
1171
+ }
1172
+ function statusOf(entry) {
1173
+ const task = entry.tasks[0];
1174
+ if (entry.permissions.length) return "waiting";
1175
+ if (!task && entry.delegation.connectionState === "starting") return "running";
1176
+ if (!task) return entry.delegation.connectionState === "interrupted" || entry.delegation.connectionState === "cleanup-failed" ? "failed" : "completed";
1177
+ if (task.state === "finished") return task.outcome === "completed" ? "completed" : task.outcome === "cancelled" ? "cancelled" : "failed";
1178
+ return task.state === "queued" ? "pending" : task.state === "awaiting-permission" ? "waiting" : "running";
1179
+ }
1180
+ /** A delegation's STATE column. */
1181
+ var LINE_STATES = {
1182
+ pending: "pending",
1183
+ running: "running",
1184
+ waiting: "waiting",
1185
+ completed: "success",
1186
+ cancelled: "stopped",
1187
+ failed: "failed"
1188
+ };
1189
+ /** The delegation an `acp_delegate` or `acp_send` call answered with. */
1190
+ function delegationOf(name, content) {
1191
+ if (name !== "acp_delegate" && name !== "acp_send" || content === void 0) return null;
1192
+ try {
1193
+ const task = JSON.parse(content);
1194
+ return typeof task.delegationId === "string" ? task.delegationId : null;
1195
+ } catch {
1196
+ return null;
1197
+ }
1198
+ }
1199
+ /** Collapses owner notifications while a list or detail request is in flight. */
1200
+ function coalesceReads(read) {
1201
+ let flight;
1202
+ let again = false;
1203
+ return () => {
1204
+ again = true;
1205
+ if (flight) return flight;
1206
+ flight = (async () => {
1207
+ while (again) {
1208
+ again = false;
1209
+ await read();
1210
+ }
1211
+ })().finally(() => {
1212
+ flight = void 0;
1213
+ });
1214
+ return flight;
1215
+ };
1216
+ }
1217
+ async function readEntry(ctx, sessionId, delegationId) {
1218
+ for (let offset = 0;; offset += 200) {
1219
+ const rows = await ctx.invoke("list", {
1220
+ sessionId,
1221
+ offset,
1222
+ limit: 200
1223
+ });
1224
+ const entry = rows.find((row) => row.delegation.id === delegationId);
1225
+ if (entry) return entry;
1226
+ if (rows.length < 200) return null;
1227
+ }
1228
+ }
1229
+ function detailFor(ctx) {
1230
+ return function Detail({ sessionId, delegationId }) {
1231
+ const host = useSyncExternalStore(ctx.host.subscribe, ctx.host.get);
1232
+ const [entry, setEntry] = useState(null);
1233
+ const [tasks, setTasks] = useState([]);
1234
+ const [pages, setPages] = useState(1);
1235
+ const [hasMore, setHasMore] = useState(false);
1236
+ const [history, setHistory] = useState({});
1237
+ const toast = ctx.ui.useToast();
1238
+ const [loading, setLoading] = useState(true);
1239
+ const [readFailed, setReadFailed] = useState(false);
1240
+ const [attempt, setAttempt] = useState(0);
1241
+ const [historyPending, setHistoryPending] = useState(/* @__PURE__ */ new Set());
1242
+ const historyReads = useRef(/* @__PURE__ */ new Set());
1243
+ const pageReading = useRef(false);
1244
+ useEffect(() => {
1245
+ let live = true, revision = 0;
1246
+ const read = coalesceReads(async () => {
1247
+ if (!live) return;
1248
+ setLoading(true);
1249
+ const current = ++revision;
1250
+ try {
1251
+ const [rows, ...batches] = await Promise.all([readEntry(ctx, sessionId, delegationId), ...Array.from({ length: pages }, (_, index) => ctx.invoke("get", {
1252
+ sessionId,
1253
+ delegationId,
1254
+ offset: index * 20,
1255
+ limit: 20
1256
+ }))]);
1257
+ if (!live || current !== revision) return;
1258
+ setEntry(rows);
1259
+ const pagesRead = batches;
1260
+ setTasks(pagesRead.flatMap((row) => row.tasks));
1261
+ setHasMore(pagesRead.at(-1)?.tasks.length === 20);
1262
+ setReadFailed(false);
1263
+ } catch (error) {
1264
+ if (live) {
1265
+ setReadFailed(true);
1266
+ showFailure(toast, error);
1267
+ }
1268
+ } finally {
1269
+ if (live) {
1270
+ setLoading(false);
1271
+ pageReading.current = false;
1272
+ }
1273
+ }
1274
+ });
1275
+ read();
1276
+ const off = ctx.on("changed", (event) => {
1277
+ if (event.sessionId === sessionId) read();
1278
+ });
1279
+ return () => {
1280
+ live = false;
1281
+ off();
1282
+ };
1283
+ }, [
1284
+ host.connection,
1285
+ pages,
1286
+ attempt,
1287
+ sessionId,
1288
+ delegationId
1289
+ ]);
1290
+ return /* @__PURE__ */ jsxs("div", {
1291
+ className: "acp-stack",
1292
+ children: [
1293
+ loading && /* @__PURE__ */ jsx("p", {
1294
+ role: "status",
1295
+ children: ctx.i18n.t("loading")
1296
+ }),
1297
+ readFailed && /* @__PURE__ */ jsx(ctx.ui.Button, {
1298
+ loading,
1299
+ disabled: loading,
1300
+ onClick: () => setAttempt((value) => value + 1),
1301
+ children: ctx.i18n.t("retry")
1302
+ }),
1303
+ entry && /* @__PURE__ */ jsxs("p", { children: [
1304
+ entry.delegation.instance.label,
1305
+ " · ",
1306
+ entry.delegation.connectionState
1307
+ ] }),
1308
+ entry?.delegation.execution && /* @__PURE__ */ jsxs(ctx.ui.Alert, {
1309
+ tone: entry.delegation.execution.mode === "direct" ? "warning" : "success",
1310
+ children: [
1311
+ ctx.i18n.t("effectiveMode"),
1312
+ ":",
1313
+ " ",
1314
+ ctx.i18n.t(entry.delegation.execution.mode === "direct" ? "directMode" : "sandbox"),
1315
+ entry.delegation.execution.fallbackReason && /* @__PURE__ */ jsxs("p", { children: [
1316
+ ctx.i18n.t("fallbackWarning"),
1317
+ " ",
1318
+ entry.delegation.execution.fallbackReason
1319
+ ] })
1320
+ ]
1321
+ }),
1322
+ entry?.permissions.map((permission) => /* @__PURE__ */ jsx(ctx.ui.Alert, {
1323
+ tone: "warning",
1324
+ children: /* @__PURE__ */ jsxs("div", {
1325
+ className: "acp-alert-content",
1326
+ children: [
1327
+ /* @__PURE__ */ jsx("p", { children: ctx.i18n.t("permission") }),
1328
+ /* @__PURE__ */ jsx("strong", { children: permission.request.toolCall.title }),
1329
+ /* @__PURE__ */ jsx("pre", {
1330
+ className: "acp-output",
1331
+ children: JSON.stringify(permission.request.toolCall.rawInput, null, 2)
1332
+ })
1333
+ ]
1334
+ })
1335
+ }, permission.id)),
1336
+ tasks.map((task) => /* @__PURE__ */ jsxs("section", {
1337
+ className: "acp-stack",
1338
+ children: [
1339
+ /* @__PURE__ */ jsx("strong", { children: task.input }),
1340
+ /* @__PURE__ */ jsx("span", { children: ctx.i18n.t(task.state === "finished" ? task.outcome === "interrupted" ? "failed" : task.outcome ?? "completed" : task.state === "queued" ? "pending" : task.state === "awaiting-permission" ? "waiting" : "running") }),
1341
+ task.result && /* @__PURE__ */ jsx("pre", {
1342
+ className: "acp-output",
1343
+ children: task.result
1344
+ }),
1345
+ task.error && /* @__PURE__ */ jsxs(ctx.ui.Alert, {
1346
+ tone: "destructive",
1347
+ children: [
1348
+ task.error,
1349
+ " · ",
1350
+ ctx.i18n.t(errorHelp[task.error] ?? "errorOther")
1351
+ ]
1352
+ }),
1353
+ /* @__PURE__ */ jsx(ctx.ui.Button, {
1354
+ variant: "ghost",
1355
+ loading: historyPending.has(task.id),
1356
+ disabled: historyPending.has(task.id) || host.connection !== "online",
1357
+ onClick: () => {
1358
+ if (historyReads.current.has(task.id)) return;
1359
+ historyReads.current.add(task.id);
1360
+ setHistoryPending(new Set(historyReads.current));
1361
+ ctx.invoke("updates", {
1362
+ sessionId,
1363
+ delegationId,
1364
+ taskId: task.id,
1365
+ after: history[task.id]?.at(-1)?.seq ?? 0
1366
+ }).then((value) => setHistory((before) => ({
1367
+ ...before,
1368
+ [task.id]: [...before[task.id] ?? [], ...value]
1369
+ }))).catch((error) => showFailure(toast, error)).finally(() => {
1370
+ historyReads.current.delete(task.id);
1371
+ setHistoryPending(new Set(historyReads.current));
1372
+ });
1373
+ },
1374
+ children: ctx.i18n.t(history[task.id] ? "next" : "history")
1375
+ }),
1376
+ history[task.id]?.map((update) => /* @__PURE__ */ jsx("pre", {
1377
+ className: "acp-output",
1378
+ children: JSON.stringify(update.payload, null, 2)
1379
+ }, update.seq))
1380
+ ]
1381
+ }, task.id)),
1382
+ hasMore && /* @__PURE__ */ jsx(ctx.ui.Button, {
1383
+ variant: "ghost",
1384
+ disabled: loading,
1385
+ loading,
1386
+ onClick: () => {
1387
+ if (pageReading.current) return;
1388
+ pageReading.current = true;
1389
+ setPages((p) => p + 1);
1390
+ },
1391
+ children: ctx.i18n.t("older")
1392
+ })
1393
+ ]
1394
+ });
1395
+ };
1396
+ }
1397
+ /**
1398
+ * The delegation section: the external delegations a call of this run
1399
+ * started or continued, one line each — the instance and its task, with stop
1400
+ * and close at the end — and the whole record opened in place beneath the
1401
+ * line. A delegation outlives its call, and often the run: in the run block
1402
+ * it is there for as long as it runs; on the process's dispatch board every
1403
+ * one is listed, finished ones included, under a heading.
1404
+ */
1405
+ function sectionFor(ctx) {
1406
+ const Detail = detailFor(ctx);
1407
+ return function Section({ sessionId, where, calls }) {
1408
+ const host = useSyncExternalStore(ctx.host.subscribe, ctx.host.get);
1409
+ const [rows, setRows] = useState([]), [busy, setBusy] = useState(/* @__PURE__ */ new Set());
1410
+ const toast = ctx.ui.useToast();
1411
+ const actions = useRef(/* @__PURE__ */ new Set());
1412
+ const [loading, setLoading] = useState(false);
1413
+ const [readFailed, setReadFailed] = useState(false);
1414
+ const [attempt, setAttempt] = useState(0);
1415
+ const mine = new Set(calls.flatMap((one) => {
1416
+ const id = delegationOf(one.call.name, one.result?.content);
1417
+ return id === null ? [] : [id];
1418
+ }));
1419
+ const any = mine.size > 0;
1420
+ const mineKey = JSON.stringify([...mine].sort());
1421
+ async function listMine(current = () => true) {
1422
+ const remaining = new Set(mine);
1423
+ const found = [];
1424
+ for (let offset = 0; current() && remaining.size > 0; offset += 200) {
1425
+ const page = await ctx.invoke("list", {
1426
+ sessionId,
1427
+ offset,
1428
+ limit: 200
1429
+ });
1430
+ if (!current()) break;
1431
+ for (const entry of page) if (remaining.delete(entry.delegation.id)) found.push(entry);
1432
+ if (page.length < 200) break;
1433
+ }
1434
+ return found;
1435
+ }
1436
+ useEffect(() => {
1437
+ if (!any) return;
1438
+ let live = true, revision = 0;
1439
+ const read = coalesceReads(async () => {
1440
+ if (!live) return;
1441
+ const request = ++revision;
1442
+ setLoading(true);
1443
+ try {
1444
+ const value = await listMine(() => live && request === revision);
1445
+ if (live && request === revision) {
1446
+ setRows(value);
1447
+ setReadFailed(false);
1448
+ }
1449
+ } catch (error) {
1450
+ if (live) {
1451
+ setReadFailed(true);
1452
+ showFailure(toast, error);
1453
+ }
1454
+ } finally {
1455
+ if (live) setLoading(false);
1456
+ }
1457
+ });
1458
+ read();
1459
+ const off = ctx.on("changed", (event) => {
1460
+ if (event.sessionId === sessionId) read();
1461
+ });
1462
+ return () => {
1463
+ live = false;
1464
+ off();
1465
+ };
1466
+ }, [
1467
+ sessionId,
1468
+ host.connection,
1469
+ any,
1470
+ mineKey,
1471
+ attempt
1472
+ ]);
1473
+ const invoke = async (method, id) => {
1474
+ if (actions.current.has(id)) return;
1475
+ actions.current.add(id);
1476
+ setBusy((before) => new Set(before).add(id));
1477
+ try {
1478
+ await ctx.invoke(method, {
1479
+ sessionId,
1480
+ delegationId: id
1481
+ });
1482
+ setRows(await listMine());
1483
+ } catch (error) {
1484
+ showFailure(toast, error);
1485
+ } finally {
1486
+ actions.current.delete(id);
1487
+ setBusy((before) => {
1488
+ const next = new Set(before);
1489
+ next.delete(id);
1490
+ return next;
1491
+ });
1492
+ }
1493
+ };
1494
+ const board = where === "process";
1495
+ const active = rows.filter((entry) => mine.has(entry.delegation.id) && (board || activeOf(entry)));
1496
+ if (any && loading && active.length === 0) return /* @__PURE__ */ jsx("p", {
1497
+ role: "status",
1498
+ children: ctx.i18n.t("loading")
1499
+ });
1500
+ if (any && readFailed && active.length === 0) return /* @__PURE__ */ jsx(ctx.ui.Button, {
1501
+ loading,
1502
+ disabled: loading,
1503
+ onClick: () => setAttempt((value) => value + 1),
1504
+ children: ctx.i18n.t("retry")
1505
+ });
1506
+ if (active.length === 0) return null;
1507
+ return /* @__PURE__ */ jsxs("section", {
1508
+ className: board ? "acp-board" : "acp-section",
1509
+ "aria-label": ctx.i18n.t("title"),
1510
+ children: [board && /* @__PURE__ */ jsx("h3", {
1511
+ className: "acp-heading",
1512
+ children: ctx.i18n.t("title")
1513
+ }), active.map((entry) => {
1514
+ const { delegation, tasks } = entry, task = tasks[0], state = statusOf(entry), disabled = host.connection !== "online" || busy.has(delegation.id);
1515
+ const retained = [
1516
+ "starting",
1517
+ "connected",
1518
+ "cleanup-failed"
1519
+ ].includes(delegation.connectionState);
1520
+ return /* @__PURE__ */ jsx(ctx.ui.RunItem, {
1521
+ icon: "boxes",
1522
+ state: LINE_STATES[state],
1523
+ stateLabel: ctx.i18n.t(busy.has(delegation.id) ? "loading" : state),
1524
+ title: delegation.instance.label,
1525
+ summary: task?.input ?? ctx.i18n.t("retained"),
1526
+ actions: [...task && task.state !== "finished" && task.state !== "queued" ? [{
1527
+ icon: "stop",
1528
+ label: ctx.i18n.t("stop"),
1529
+ disabled: disabled || task.state === "stopping",
1530
+ onClick: () => void invoke("stop", delegation.id)
1531
+ }] : [], ...retained && (!task || task.state === "finished") ? [{
1532
+ icon: "close",
1533
+ label: ctx.i18n.t("close"),
1534
+ disabled,
1535
+ onClick: () => void invoke("close", delegation.id)
1536
+ }] : []],
1537
+ children: /* @__PURE__ */ jsx(Detail, {
1538
+ sessionId,
1539
+ delegationId: delegation.id
1540
+ })
1541
+ }, delegation.id);
1542
+ })]
1543
+ });
1544
+ };
1545
+ }
1546
+ var register = (ctx) => {
1547
+ registerMetadata(ctx);
1548
+ ctx.i18n.register({
1549
+ "zh-CN": {
1550
+ ...copy["zh-CN"],
1551
+ ...settingsCopy["zh-CN"]
1552
+ },
1553
+ "en-US": {
1554
+ ...copy["en-US"],
1555
+ ...settingsCopy["en-US"]
1556
+ }
1557
+ }, "en-US");
1558
+ ctx.styles.add(`
1559
+ .acp-section { min-width: 0; margin-inline-start: 7px; padding-inline-start: 1.25rem; }
1560
+ .acp-board { min-width: 0; }
1561
+ .acp-heading { margin: 0 0 .25rem; font-size: .75rem; font-weight: 600; color: var(--muted-foreground); }
1562
+ .acp-stack { display: flex; min-width: 0; flex-direction: column; gap: .75rem; font-size: .875rem; }
1563
+ .acp-alert-content { display: flex; min-width: 0; flex-direction: column; gap: .75rem; }
1564
+ .acp-actions { display: flex; min-width: 0; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: .5rem; }
1565
+ .acp-task-body { display: flex; min-width: 0; flex-direction: column; gap: .75rem; margin-top: .5rem; }
1566
+ .acp-output { box-sizing: border-box; min-width: 0; max-width: 100%; max-height: 18rem; margin: 0; overflow: auto; border-radius: var(--radius-control); background: color-mix(in oklch, var(--muted) 40%, transparent); padding: .5rem .625rem; color: var(--muted-foreground); font-family: var(--font-mono, monospace); font-size: .75rem; line-height: 1.5; white-space: pre-wrap; overflow-wrap: anywhere; }
1567
+ .acp-settings { gap: 1.25rem; }
1568
+ .acp-toolbar { display: flex; align-items: center; justify-content: space-between; gap: .75rem; flex-wrap: wrap; }
1569
+ .acp-help { color: var(--muted-foreground); font-size: .75rem; line-height: 1.6; margin: 0; }
1570
+ .acp-agent-row { position: relative; min-width: 0; border: 1px solid var(--border); border-radius: var(--radius-control); transition: background-color 150ms; }
1571
+ .acp-agent-row:hover { background: var(--muted); }
1572
+ .acp-agent-link { width: 100%; min-width: 0; display: flex; align-items: center; gap: .75rem; padding: .875rem 1rem; text-align: left; border-radius: var(--radius-control); }
1573
+ .acp-agent-link .acp-agent-summary { padding-right: 4.5rem; }
1574
+ .acp-agent-toggle { position: absolute; right: 4rem; top: 50%; transform: translateY(-50%); display: flex; align-items: center; }
1575
+ .acp-detail-editor { padding-right: .5rem; }
1576
+ .acp-agent-row .acp-agent-delete { position: absolute; right: 2rem; top: 50%; transform: translateY(-50%); }
1577
+ .acp-agent-chevron { flex: none; font-size: 1.25rem; color: var(--muted-foreground); }
1578
+ .acp-agent-summary { display: flex; flex: 1; min-width: 0; flex-direction: column; gap: .25rem; }
1579
+ .acp-agent-summary > span:first-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
1580
+ .acp-command { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
1581
+ .acp-agent-dot { width: .5rem; height: .5rem; border-radius: var(--radius-pill); flex: none; background: var(--muted-foreground); }
1582
+ .acp-agent-dot[data-enabled="true"] { background: var(--success); }
1583
+ .acp-recheck { display: flex; justify-content: center; }
1584
+ .acp-preset-grid { --choice-row-gap: 0px; display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: .75rem; }
1585
+ .acp-preset { border-radius: var(--radius-control); flex-direction: column; justify-content: center; gap: .5rem; padding: 1rem .375rem; min-height: 7rem; border: 1px solid var(--border); text-align: center; }
1586
+ .acp-preset-logo { width: 2rem; height: 2rem; flex: none; }
1587
+ .acp-preset[data-available="false"] .acp-preset-logo { filter: grayscale(1); }
1588
+ .acp-preset[aria-pressed="true"] { border-color: var(--primary); background: var(--muted); }
1589
+ .acp-preset[data-available="true"] { color: var(--foreground); }
1590
+ .acp-preset[data-available="true"] svg { color: var(--primary); }
1591
+ .acp-editor, .acp-editor-fields { display: flex; min-width: 0; flex-direction: column; gap: 1.5rem; }
1592
+ .acp-editor-fields { margin: 0; padding: 0; border: 0; }
1593
+ .acp-limit-field[data-slot="field"] { grid-template-columns: minmax(0, 1fr) 9rem; column-gap: 1rem; row-gap: .25rem; }
1594
+ .acp-limit-field[data-slot="field"] > div:first-child { padding-top: .375rem; }
1595
+ .acp-command-field { display: flex; min-width: 0; gap: .5rem; }
1596
+ .acp-command-field > input { flex: 1; }
1597
+ .acp-wrap { overflow-wrap: anywhere; }
1598
+ .acp-doc-link { display: inline-block; margin-top: .375rem; color: var(--primary); text-decoration: underline; text-underline-offset: .2em; }
1599
+ .acp-disclosure-body { padding-top: 1rem; }
1600
+ @media (max-width: 480px) { .acp-command-field { flex-wrap: wrap; } .acp-command-field > input { flex-basis: 100%; } }
1601
+ `);
1602
+ ctx.slots.register("chat.run.section", {
1603
+ id: "delegations",
1604
+ order: 30,
1605
+ component: sectionFor(ctx)
1606
+ });
1607
+ ctx.slots.register("shell.settings.category", {
1608
+ parent: "agents",
1609
+ order: 30,
1610
+ id: "acp",
1611
+ label: () => ctx.i18n.t("settings"),
1612
+ icon: "boxes",
1613
+ component: settingsFor(ctx)
1614
+ });
1615
+ };
1616
+ //#endregion
1617
+ export { register, runtimeVersion };