@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/dist/adapters/LICENSES.txt +666 -0
- package/dist/adapters/codex-acp.js +31004 -0
- package/dist/adapters/codex.js +14 -0
- package/dist/index.js +1747 -0
- package/package.json +49 -3
- package/ui/ui.js +1617 -0
- package/README.md +0 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,1747 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
3
|
+
import { accessSync, constants, existsSync, readFileSync, realpathSync, statSync } from "node:fs";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
import protocolSchema from "@agentclientprotocol/sdk/schema/schema.json" with { type: "json" };
|
|
7
|
+
import { Readable, Transform, Writable } from "node:stream";
|
|
8
|
+
import { ClientSideConnection, PROTOCOL_VERSION, ndJsonStream } from "@agentclientprotocol/sdk";
|
|
9
|
+
import { mkdtemp, rm } from "node:fs/promises";
|
|
10
|
+
import { tmpdir } from "node:os";
|
|
11
|
+
import { dirname, join, posix, resolve, win32 } from "node:path";
|
|
12
|
+
//#region src/client.ts
|
|
13
|
+
const Update = z.fromJSONSchema({
|
|
14
|
+
$ref: "#/$defs/SessionNotification",
|
|
15
|
+
$defs: protocolSchema.$defs
|
|
16
|
+
});
|
|
17
|
+
const Permission = z.fromJSONSchema({
|
|
18
|
+
$ref: "#/$defs/RequestPermissionRequest",
|
|
19
|
+
$defs: protocolSchema.$defs
|
|
20
|
+
});
|
|
21
|
+
/** Times out protocol control operations without retrying or exposing remote error text. */
|
|
22
|
+
async function control(promise, ms = 3e4) {
|
|
23
|
+
let timer;
|
|
24
|
+
try {
|
|
25
|
+
return await Promise.race([promise, new Promise((_, reject) => {
|
|
26
|
+
timer = setTimeout(() => reject(/* @__PURE__ */ new Error("protocol-timeout")), ms);
|
|
27
|
+
})]);
|
|
28
|
+
} finally {
|
|
29
|
+
if (timer) clearTimeout(timer);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/** Initializes ACP over raw pipes, rejecting messages above 8 MiB before JSON decoding. */
|
|
33
|
+
async function connectAcp(process, callbacks) {
|
|
34
|
+
let buffered = Buffer.alloc(0);
|
|
35
|
+
const pending = /* @__PURE__ */ new Set();
|
|
36
|
+
const bounded = new Transform({
|
|
37
|
+
transform(chunk, _encoding, done) {
|
|
38
|
+
buffered = Buffer.concat([buffered, chunk]);
|
|
39
|
+
while (buffered.includes(10)) {
|
|
40
|
+
const newline = buffered.indexOf(10);
|
|
41
|
+
if (newline > 8388608) {
|
|
42
|
+
done(/* @__PURE__ */ new Error("protocol-message-limit"));
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
const line = buffered.subarray(0, newline);
|
|
46
|
+
buffered = buffered.subarray(newline + 1);
|
|
47
|
+
if (!line.length) continue;
|
|
48
|
+
let value;
|
|
49
|
+
try {
|
|
50
|
+
const parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(line));
|
|
51
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error();
|
|
52
|
+
value = parsed;
|
|
53
|
+
if (value.jsonrpc !== "2.0") throw new Error();
|
|
54
|
+
if ("method" in value) {
|
|
55
|
+
if (typeof value.method !== "string") throw new Error();
|
|
56
|
+
if (value.method === "session/update" && !Update.safeParse(value.params).success) throw new Error();
|
|
57
|
+
if (value.method === "session/request_permission" && !Permission.safeParse(value.params).success) throw new Error();
|
|
58
|
+
if (!("id" in value) && value.method !== "session/update") continue;
|
|
59
|
+
} else {
|
|
60
|
+
if (typeof value.id !== "string" && typeof value.id !== "number") throw new Error();
|
|
61
|
+
if (!pending.delete(value.id)) continue;
|
|
62
|
+
if (!("result" in value) && !("error" in value)) throw new Error();
|
|
63
|
+
}
|
|
64
|
+
} catch {
|
|
65
|
+
done(/* @__PURE__ */ new Error("invalid-protocol-message"));
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
this.push(Buffer.concat([line, Buffer.from("\n")]));
|
|
69
|
+
}
|
|
70
|
+
if (buffered.length > 8388608) {
|
|
71
|
+
done(/* @__PURE__ */ new Error("protocol-message-limit"));
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
done();
|
|
75
|
+
},
|
|
76
|
+
flush(done) {
|
|
77
|
+
done(buffered.length ? /* @__PURE__ */ new Error("truncated-protocol-message") : void 0);
|
|
78
|
+
}
|
|
79
|
+
});
|
|
80
|
+
process.stdout.pipe(bounded);
|
|
81
|
+
process.stdout.on("close", () => bounded.destroy());
|
|
82
|
+
process.stdout.on("error", () => bounded.destroy(/* @__PURE__ */ new Error("connection-lost")));
|
|
83
|
+
bounded.on("error", () => {
|
|
84
|
+
process.stop().catch(() => {});
|
|
85
|
+
});
|
|
86
|
+
const raw = ndJsonStream(Writable.toWeb(process.stdin), Readable.toWeb(bounded));
|
|
87
|
+
const writer = raw.writable.getWriter();
|
|
88
|
+
const client = new ClientSideConnection(() => ({
|
|
89
|
+
async requestPermission(request) {
|
|
90
|
+
try {
|
|
91
|
+
return await callbacks.permission(request);
|
|
92
|
+
} catch {
|
|
93
|
+
process.stop().catch(() => {});
|
|
94
|
+
return { outcome: { outcome: "cancelled" } };
|
|
95
|
+
}
|
|
96
|
+
},
|
|
97
|
+
sessionUpdate(notification) {
|
|
98
|
+
try {
|
|
99
|
+
callbacks.update(notification);
|
|
100
|
+
} catch {
|
|
101
|
+
process.stop().catch(() => {});
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}), {
|
|
105
|
+
readable: raw.readable,
|
|
106
|
+
writable: new WritableStream({
|
|
107
|
+
async write(value) {
|
|
108
|
+
if (Buffer.byteLength(JSON.stringify(value)) > 8388608) throw new Error("protocol-message-limit");
|
|
109
|
+
if ("method" in value && "id" in value && value.id !== null) pending.add(value.id);
|
|
110
|
+
try {
|
|
111
|
+
await control(writer.write(value));
|
|
112
|
+
} catch {
|
|
113
|
+
process.stop().catch(() => {});
|
|
114
|
+
throw new Error("protocol-write-failed");
|
|
115
|
+
}
|
|
116
|
+
},
|
|
117
|
+
close: () => writer.close(),
|
|
118
|
+
abort: () => writer.abort(/* @__PURE__ */ new Error("connection-closed"))
|
|
119
|
+
})
|
|
120
|
+
});
|
|
121
|
+
try {
|
|
122
|
+
const initialized = await control(client.initialize({
|
|
123
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
124
|
+
clientCapabilities: {},
|
|
125
|
+
clientInfo: {
|
|
126
|
+
name: "yaoguang",
|
|
127
|
+
version: "1.0.0"
|
|
128
|
+
}
|
|
129
|
+
}));
|
|
130
|
+
if (initialized.protocolVersion !== PROTOCOL_VERSION) throw new Error("protocol-version-mismatch");
|
|
131
|
+
return {
|
|
132
|
+
client,
|
|
133
|
+
initialized,
|
|
134
|
+
process
|
|
135
|
+
};
|
|
136
|
+
} catch {
|
|
137
|
+
await process.stop();
|
|
138
|
+
throw new Error("initialize-failed");
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
//#endregion
|
|
142
|
+
//#region src/guidance.ts
|
|
143
|
+
const ACP_GUIDANCE = {
|
|
144
|
+
title: "Delegating to external agents",
|
|
145
|
+
entries: [
|
|
146
|
+
{
|
|
147
|
+
tools: ["acp_instances"],
|
|
148
|
+
text: "`acp_instances` lists the external coding agents configured on this machine; read it before delegating."
|
|
149
|
+
},
|
|
150
|
+
{
|
|
151
|
+
tools: ["acp_delegate"],
|
|
152
|
+
text: "`acp_delegate` hands a task to one of them, after the person authorizes the launch. An agent launched in trusted mode runs outside the sandbox with this user's full access, so treat delegating to it as you would running an unconfined command. It starts with none of this conversation: give it the goal, the relevant paths and facts, and what to hand back. The task keeps running if your own turn is stopped."
|
|
153
|
+
},
|
|
154
|
+
{
|
|
155
|
+
tools: ["acp_get"],
|
|
156
|
+
text: "`acp_get` reads one delegation and its tasks, or one task with `taskId`; add `waitMs` to wait for that task, up to a minute at a time, and stopping the wait leaves the task running. Check a result before you rely on it."
|
|
157
|
+
},
|
|
158
|
+
{
|
|
159
|
+
tools: ["acp_list"],
|
|
160
|
+
text: "`acp_list` lists the delegations this session started."
|
|
161
|
+
},
|
|
162
|
+
{
|
|
163
|
+
tools: ["acp_send"],
|
|
164
|
+
text: "`acp_send` continues a delegation with a further task."
|
|
165
|
+
},
|
|
166
|
+
{
|
|
167
|
+
tools: ["acp_stop"],
|
|
168
|
+
text: "`acp_stop` stops a delegation's current task, or closes it; changes it already made stay."
|
|
169
|
+
}
|
|
170
|
+
]
|
|
171
|
+
};
|
|
172
|
+
//#endregion
|
|
173
|
+
//#region src/inspection.ts
|
|
174
|
+
/** Inspects one command using the explicitly supplied physical host, without running it. */
|
|
175
|
+
function inspectCommand(command, commands, searchPath) {
|
|
176
|
+
return commands.inspect(command, searchPath === void 0 ? commands.env : commands.environment([commands.env, { PATH: searchPath }]));
|
|
177
|
+
}
|
|
178
|
+
//#endregion
|
|
179
|
+
//#region src/adapters.ts
|
|
180
|
+
const require = createRequire(import.meta.url);
|
|
181
|
+
const adapters = {
|
|
182
|
+
claude: {
|
|
183
|
+
package: "@zed-industries/claude-agent-acp",
|
|
184
|
+
bin: "claude-agent-acp",
|
|
185
|
+
variable: "CLAUDE_CODE_EXECUTABLE"
|
|
186
|
+
},
|
|
187
|
+
codex: {
|
|
188
|
+
package: "@agentclientprotocol/codex-acp",
|
|
189
|
+
bin: "codex-acp",
|
|
190
|
+
variable: "CODEX_PATH"
|
|
191
|
+
}
|
|
192
|
+
};
|
|
193
|
+
/** Resolves the installed adapter without importing or executing its program. */
|
|
194
|
+
function bundledAdapter(id) {
|
|
195
|
+
const adapter = adapters[id];
|
|
196
|
+
if (id === "codex") {
|
|
197
|
+
const entry = fileURLToPath(new URL("../dist/adapters/codex.js", import.meta.url));
|
|
198
|
+
if (!statSync(entry).isFile()) throw new Error("bundled-adapter-entry-missing");
|
|
199
|
+
accessSync(entry, constants.R_OK);
|
|
200
|
+
return {
|
|
201
|
+
entry,
|
|
202
|
+
root: dirname(entry),
|
|
203
|
+
variable: adapter.variable
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
const manifestPath = require.resolve(`${adapter.package}/package.json`);
|
|
207
|
+
const bin = JSON.parse(readFileSync(manifestPath, "utf8")).bin[adapter.bin];
|
|
208
|
+
if (!bin) throw new Error("bundled-adapter-entry-missing");
|
|
209
|
+
const root = dirname(manifestPath);
|
|
210
|
+
const entry = resolve(root, bin);
|
|
211
|
+
if (!statSync(entry).isFile()) throw new Error("bundled-adapter-entry-missing");
|
|
212
|
+
accessSync(entry, constants.R_OK);
|
|
213
|
+
return {
|
|
214
|
+
entry,
|
|
215
|
+
root,
|
|
216
|
+
variable: adapter.variable
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
/** Resolves bundled adapters at launch so stored instances survive plugin relocation and updates.
|
|
220
|
+
* For bundled instances command is the local CLI; args belong to the adapter.
|
|
221
|
+
* The caller supplies the same host Node executable used to admit this launch.
|
|
222
|
+
*/
|
|
223
|
+
function instanceLaunch(instance, execPath) {
|
|
224
|
+
if (!instance.adapter) return {
|
|
225
|
+
command: instance.command,
|
|
226
|
+
args: instance.args,
|
|
227
|
+
env: instance.env,
|
|
228
|
+
read: [instance.command]
|
|
229
|
+
};
|
|
230
|
+
const adapter = bundledAdapter(instance.adapter);
|
|
231
|
+
return {
|
|
232
|
+
command: execPath,
|
|
233
|
+
args: [adapter.entry, ...instance.args],
|
|
234
|
+
env: {
|
|
235
|
+
...instance.env,
|
|
236
|
+
[adapter.variable]: instance.command
|
|
237
|
+
},
|
|
238
|
+
read: [
|
|
239
|
+
execPath,
|
|
240
|
+
adapter.root,
|
|
241
|
+
instance.command
|
|
242
|
+
]
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
//#endregion
|
|
246
|
+
//#region src/launch.ts
|
|
247
|
+
/** Rejects relative paths, reserved variables, credentials and invalid values before launch. */
|
|
248
|
+
function validateInstance(instance, platform = process.platform) {
|
|
249
|
+
const absolute = (path) => platform === "win32" ? /^(?:[A-Za-z]:[\\/]|[\\/]{2}(?![?.][\\/])[^\\/]+[\\/][^\\/]+(?:[\\/]|$))/.test(path) && win32.isAbsolute(path) : posix.isAbsolute(path);
|
|
250
|
+
if (!absolute(instance.command) || instance.command.includes("\0") || instance.authPaths.some((item) => !absolute(item.path) || item.path.includes("\0"))) throw new Error("absolute-path-required");
|
|
251
|
+
if (instance.args.some((arg) => arg.includes("\0"))) throw new Error("invalid-command-argument");
|
|
252
|
+
for (const [key, value] of Object.entries(instance.env)) {
|
|
253
|
+
if (/^(?:https?|all|ftp|no)_proxy$/i.test(key)) throw new Error("proxy-environment-managed-by-gateway");
|
|
254
|
+
if (!(platform === "win32" ? /^[A-Za-z_][A-Za-z0-9_]*$/ : /^[A-Z_][A-Z0-9_]*$/).test(key) || /KEY|SECRET|TOKEN|PASSWORD|YAOGUANG/i.test(key)) throw new Error("credential-environment-forbidden");
|
|
255
|
+
if (value.includes("\0")) throw new Error("invalid-environment-input");
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
/** Authorizes the effective argv, real cwd, environment names and mode, then rechecks admission. */
|
|
259
|
+
async function prepareLaunch(authority, instance, cwd, services) {
|
|
260
|
+
const { commands } = services;
|
|
261
|
+
validateInstance(instance, commands.platform);
|
|
262
|
+
commands.environment([instance.env]);
|
|
263
|
+
const executable = instanceLaunch(instance, commands.execPath);
|
|
264
|
+
const exact = [executable.command, ...executable.args];
|
|
265
|
+
const selected = await commands.inspect(executable.command);
|
|
266
|
+
if (selected.status !== "found" || selected.path !== executable.command) throw new Error(`command-unavailable: ${selected.reason ?? "command-resolution-changed"}`);
|
|
267
|
+
if (instance.adapter) {
|
|
268
|
+
const cli = await commands.inspect(instance.command);
|
|
269
|
+
if (cli.status !== "found") throw new Error(`command-unavailable: ${cli.reason}`);
|
|
270
|
+
}
|
|
271
|
+
cwd = await commands.directory(cwd);
|
|
272
|
+
const trusted = instance.executionMode === "trusted";
|
|
273
|
+
const route = () => services.network.environment();
|
|
274
|
+
let proxy = await route();
|
|
275
|
+
const permissions = {
|
|
276
|
+
read: [...executable.read, ...instance.authPaths.map((item) => item.path)],
|
|
277
|
+
write: [cwd, ...instance.authPaths.filter((item) => item.access === "write").map((item) => item.path)],
|
|
278
|
+
network: instance.networkHosts
|
|
279
|
+
};
|
|
280
|
+
const availability = trusted ? void 0 : JSON.stringify(services.sandbox.status());
|
|
281
|
+
const plan = async (tmp) => {
|
|
282
|
+
if (trusted) return void 0;
|
|
283
|
+
const result = await services.sandbox.planSandboxed(authority, {
|
|
284
|
+
cwd,
|
|
285
|
+
tmp,
|
|
286
|
+
permissions,
|
|
287
|
+
argv: exact
|
|
288
|
+
});
|
|
289
|
+
if (!result.ok) throw new Error(`sandbox-refused: ${result.reason}`);
|
|
290
|
+
return result.plan;
|
|
291
|
+
};
|
|
292
|
+
const environment = (mode, work) => {
|
|
293
|
+
const inherited = commands.childEnvironment(commands.env, mode === "sandboxed" ? "acp-minimal" : "protocol");
|
|
294
|
+
if (mode === "sandboxed" && commands.platform !== "win32") {
|
|
295
|
+
inherited.PATH ??= "/usr/bin:/bin";
|
|
296
|
+
inherited.HOME ??= "/";
|
|
297
|
+
inherited.LANG ??= "en_US.UTF-8";
|
|
298
|
+
}
|
|
299
|
+
if (commands.platform === "win32" && !inherited.SYSTEMROOT) throw new Error("required-host-environment-unavailable: SYSTEMROOT");
|
|
300
|
+
return commands.environment([
|
|
301
|
+
inherited,
|
|
302
|
+
executable.env,
|
|
303
|
+
proxy.env,
|
|
304
|
+
commands.temporaryEnvironment(work)
|
|
305
|
+
]);
|
|
306
|
+
};
|
|
307
|
+
const tmp = await mkdtemp(join(realpathSync(tmpdir()), "yaoguang-acp-"));
|
|
308
|
+
let initialMode = "direct";
|
|
309
|
+
let initialNames;
|
|
310
|
+
let fallbackReason;
|
|
311
|
+
let approvalFailure;
|
|
312
|
+
let approvalFailed = false;
|
|
313
|
+
let refused;
|
|
314
|
+
try {
|
|
315
|
+
const initial = await plan(tmp);
|
|
316
|
+
initialMode = initial?.mode ?? "direct";
|
|
317
|
+
fallbackReason = initial?.mode === "direct" ? initial.fallbackReason : void 0;
|
|
318
|
+
if (initial) proxy = {
|
|
319
|
+
...proxy,
|
|
320
|
+
env: { ...initial.proxyEnvironment }
|
|
321
|
+
};
|
|
322
|
+
initialNames = Object.keys(environment(initialMode, tmp)).sort();
|
|
323
|
+
const key = `acp:${createHash("sha256").update(JSON.stringify({
|
|
324
|
+
id: instance.id,
|
|
325
|
+
revision: instance.revision,
|
|
326
|
+
proxy: proxy.revision,
|
|
327
|
+
cwd,
|
|
328
|
+
argv: exact,
|
|
329
|
+
mode: initialMode,
|
|
330
|
+
envNames: initialNames,
|
|
331
|
+
env: commands.environment([executable.env])
|
|
332
|
+
})).digest("hex")}`;
|
|
333
|
+
const decision = services.approval.decide(authority, {
|
|
334
|
+
id: key,
|
|
335
|
+
subject: `Delegate to ${instance.label} in ${cwd}`,
|
|
336
|
+
reason: (initialMode === "direct" ? "Local agent: this process runs with your local user permissions, outside the YaoGuang file sandbox. " : "Sandboxed agent. ") + (initial?.mode === "direct" && initial.fallbackReason ? `Sandbox unavailable: ${initial.fallbackReason}. ` : "") + `Proxy snapshot: ${proxy.revision}. Run ${JSON.stringify(exact)} in ${cwd} with environment names ${initialNames.join(", ")}; read paths ${permissions.read.join(", ")}, write paths ${permissions.write.join(", ")}, network hosts ${permissions.network.join(", ")}.`,
|
|
337
|
+
accepts: [
|
|
338
|
+
"allowed-once",
|
|
339
|
+
"allowed-session",
|
|
340
|
+
"allowed-always",
|
|
341
|
+
"rejected"
|
|
342
|
+
],
|
|
343
|
+
remember: {
|
|
344
|
+
key,
|
|
345
|
+
label: `启动 ${instance.label}(${cwd})`
|
|
346
|
+
}
|
|
347
|
+
});
|
|
348
|
+
if (decision.kind === "ask") refused = decision.result;
|
|
349
|
+
else if (decision.result.kind === "record-failed") refused = {
|
|
350
|
+
content: `ACP launch was allowed, but recording it failed: ${decision.result.message}`,
|
|
351
|
+
isError: true
|
|
352
|
+
};
|
|
353
|
+
else if (!decision.result.kind.startsWith("allowed-")) refused = {
|
|
354
|
+
content: "ACP launch was not authorized.",
|
|
355
|
+
isError: true
|
|
356
|
+
};
|
|
357
|
+
} catch (primary) {
|
|
358
|
+
approvalFailed = true;
|
|
359
|
+
approvalFailure = primary;
|
|
360
|
+
}
|
|
361
|
+
try {
|
|
362
|
+
await rm(tmp, {
|
|
363
|
+
recursive: true,
|
|
364
|
+
force: true
|
|
365
|
+
});
|
|
366
|
+
} catch (cleanup) {
|
|
367
|
+
if (approvalFailed) throw new AggregateError([approvalFailure, cleanup], `ACP cleanup failed: ${tmp}`, { cause: approvalFailure });
|
|
368
|
+
throw cleanup;
|
|
369
|
+
}
|
|
370
|
+
if (approvalFailed) throw approvalFailure;
|
|
371
|
+
if (refused) return { result: refused };
|
|
372
|
+
return {
|
|
373
|
+
execution: {
|
|
374
|
+
mode: initialMode,
|
|
375
|
+
...fallbackReason ? { fallbackReason } : {}
|
|
376
|
+
},
|
|
377
|
+
async launch() {
|
|
378
|
+
const work = await mkdtemp(join(realpathSync(tmpdir()), "yaoguang-acp-"));
|
|
379
|
+
let transferred = false;
|
|
380
|
+
try {
|
|
381
|
+
if ((await route()).revision !== proxy.revision) throw new Error("proxy-changed: request launch again");
|
|
382
|
+
if (!trusted && JSON.stringify(services.sandbox.status()) !== availability) throw new Error("execution-mode-changed: request launch again");
|
|
383
|
+
if (await commands.directory(cwd) !== cwd) throw new Error("cwd-changed: request launch again");
|
|
384
|
+
const found = await commands.inspect(executable.command);
|
|
385
|
+
if (found.status !== "found" || found.path !== executable.command) throw new Error("command-changed: request launch again");
|
|
386
|
+
const current = await plan(work);
|
|
387
|
+
if ((current?.mode ?? "direct") !== initialMode) throw new Error("execution-mode-changed: request launch again");
|
|
388
|
+
if (current && JSON.stringify(current.proxyEnvironment ?? {}) !== JSON.stringify(proxy.env)) throw new Error("proxy-changed: request launch again");
|
|
389
|
+
const prepared = current ? services.sandbox.prepare(current, exact) : void 0;
|
|
390
|
+
const env = environment(initialMode, work);
|
|
391
|
+
if (JSON.stringify(Object.keys(env).sort()) !== JSON.stringify(initialNames)) throw new Error("environment-changed: request launch again");
|
|
392
|
+
const assertCurrent = () => {
|
|
393
|
+
if (!trusted && JSON.stringify(services.sandbox.status()) !== availability) throw new Error("execution-mode-changed: request launch again");
|
|
394
|
+
prepared?.assertCurrent();
|
|
395
|
+
};
|
|
396
|
+
assertCurrent();
|
|
397
|
+
const attempt = services.processes.start({
|
|
398
|
+
owner: "@eum-agent/integration-acp",
|
|
399
|
+
sessionId: authority.sessionId,
|
|
400
|
+
argv: prepared?.argv ?? exact,
|
|
401
|
+
cwd: current?.cwd ?? cwd,
|
|
402
|
+
env,
|
|
403
|
+
beforeSpawn: assertCurrent,
|
|
404
|
+
release: () => rm(work, {
|
|
405
|
+
recursive: true,
|
|
406
|
+
force: true
|
|
407
|
+
})
|
|
408
|
+
});
|
|
409
|
+
transferred = true;
|
|
410
|
+
return await attempt.ready;
|
|
411
|
+
} catch (error) {
|
|
412
|
+
if (!transferred) try {
|
|
413
|
+
await rm(work, {
|
|
414
|
+
recursive: true,
|
|
415
|
+
force: true
|
|
416
|
+
});
|
|
417
|
+
} catch (cleanup) {
|
|
418
|
+
throw new AggregateError([error, cleanup], `ACP cleanup failed: ${work}`, { cause: error });
|
|
419
|
+
}
|
|
420
|
+
throw error;
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
};
|
|
424
|
+
}
|
|
425
|
+
//#endregion
|
|
426
|
+
//#region src/store.ts
|
|
427
|
+
/** One user-configured, already installed and authenticated adapter command. */
|
|
428
|
+
const InstanceSchema = z.object({
|
|
429
|
+
id: z.string().regex(/^[a-z0-9][a-z0-9-]*$/),
|
|
430
|
+
label: z.string().min(1),
|
|
431
|
+
enabled: z.boolean().default(true),
|
|
432
|
+
executionMode: z.enum(["sandbox", "trusted"]).default("sandbox"),
|
|
433
|
+
adapter: z.enum(["claude", "codex"]).optional(),
|
|
434
|
+
command: z.string().min(1),
|
|
435
|
+
args: z.array(z.string()).default([]),
|
|
436
|
+
env: z.record(z.string(), z.string()).default({}),
|
|
437
|
+
authPaths: z.array(z.object({
|
|
438
|
+
path: z.string(),
|
|
439
|
+
access: z.enum(["read", "write"])
|
|
440
|
+
}).strict()).default([]),
|
|
441
|
+
networkHosts: z.array(z.string()).default([]),
|
|
442
|
+
revision: z.number().int().nonnegative().default(0)
|
|
443
|
+
}).strict();
|
|
444
|
+
/** Independent per-root limits shared by all adapter instances. */
|
|
445
|
+
const SettingsSchema = z.object({
|
|
446
|
+
maxConcurrent: z.number().int().positive().default(4),
|
|
447
|
+
maxRetainedConnections: z.number().int().positive().default(8)
|
|
448
|
+
}).strict();
|
|
449
|
+
/** Physical execution facts of an admitted ACP root, separate from its configured preference. */
|
|
450
|
+
const LaunchExecutionSchema = z.object({
|
|
451
|
+
mode: z.enum(["sandboxed", "direct"]),
|
|
452
|
+
fallbackReason: z.string().optional()
|
|
453
|
+
}).strict();
|
|
454
|
+
/** Local delegate identity, separate from the remote session id. */
|
|
455
|
+
const DelegationSchema = z.object({
|
|
456
|
+
id: z.string(),
|
|
457
|
+
parentSessionId: z.string(),
|
|
458
|
+
rootSessionId: z.string(),
|
|
459
|
+
instance: InstanceSchema,
|
|
460
|
+
cwd: z.string(),
|
|
461
|
+
model: z.string().optional(),
|
|
462
|
+
config: z.record(z.string(), z.string()).default({}),
|
|
463
|
+
capabilities: z.record(z.string(), z.unknown()).optional(),
|
|
464
|
+
configOptions: z.array(z.unknown()).optional(),
|
|
465
|
+
remoteSessionId: z.string().nullable(),
|
|
466
|
+
generation: z.string(),
|
|
467
|
+
processId: z.string().nullable(),
|
|
468
|
+
execution: LaunchExecutionSchema.nullable(),
|
|
469
|
+
connectionState: z.enum([
|
|
470
|
+
"starting",
|
|
471
|
+
"connected",
|
|
472
|
+
"closed",
|
|
473
|
+
"interrupted",
|
|
474
|
+
"cleanup-failed"
|
|
475
|
+
]),
|
|
476
|
+
createdAt: z.number()
|
|
477
|
+
}).strict();
|
|
478
|
+
/** One accepted external prompt, queued or executing. */
|
|
479
|
+
const TaskSchema = z.object({
|
|
480
|
+
id: z.string(),
|
|
481
|
+
delegationId: z.string(),
|
|
482
|
+
requestKey: z.string(),
|
|
483
|
+
targetGeneration: z.number().int().nonnegative(),
|
|
484
|
+
input: z.string(),
|
|
485
|
+
state: z.enum([
|
|
486
|
+
"queued",
|
|
487
|
+
"starting",
|
|
488
|
+
"running",
|
|
489
|
+
"awaiting-permission",
|
|
490
|
+
"stopping",
|
|
491
|
+
"finished"
|
|
492
|
+
]),
|
|
493
|
+
outcome: z.enum([
|
|
494
|
+
"completed",
|
|
495
|
+
"cancelled",
|
|
496
|
+
"failed",
|
|
497
|
+
"interrupted"
|
|
498
|
+
]).nullable(),
|
|
499
|
+
error: z.string().nullable(),
|
|
500
|
+
result: z.string(),
|
|
501
|
+
truncated: z.boolean(),
|
|
502
|
+
createdAt: z.number(),
|
|
503
|
+
revision: z.number().int()
|
|
504
|
+
}).strict();
|
|
505
|
+
/** ACP storage, always under the host-issued owner table prefix. */
|
|
506
|
+
function createAcpStore(storage) {
|
|
507
|
+
const { db, tableName } = storage;
|
|
508
|
+
const settings = tableName("settings"), instances = tableName("instance"), delegations = tableName("delegation"), tasks = tableName("task"), updates = tableName("update");
|
|
509
|
+
db.exec(`CREATE TABLE IF NOT EXISTS ${settings}(singleton INTEGER NOT NULL PRIMARY KEY CHECK(singleton=1),max_concurrent INTEGER NOT NULL CHECK(max_concurrent>0),max_retained_connections INTEGER NOT NULL CHECK(max_retained_connections>0)) STRICT;
|
|
510
|
+
CREATE TABLE IF NOT EXISTS ${instances}(id TEXT NOT NULL PRIMARY KEY,payload TEXT NOT NULL) STRICT;
|
|
511
|
+
CREATE TABLE IF NOT EXISTS ${delegations}(id TEXT NOT NULL PRIMARY KEY,root_session_id TEXT NOT NULL,parent_session_id TEXT NOT NULL,payload TEXT NOT NULL) STRICT;
|
|
512
|
+
CREATE INDEX IF NOT EXISTS ${tableName("delegation_root")} ON ${delegations}(root_session_id);
|
|
513
|
+
CREATE TABLE IF NOT EXISTS ${tasks}(id TEXT NOT NULL PRIMARY KEY,delegation_id TEXT NOT NULL,request_key TEXT NOT NULL,payload TEXT NOT NULL,output_bytes INTEGER NOT NULL DEFAULT 0 CHECK(output_bytes>=0),UNIQUE(delegation_id,request_key)) STRICT;
|
|
514
|
+
CREATE TABLE IF NOT EXISTS ${updates}(task_id TEXT NOT NULL,seq INTEGER NOT NULL,payload TEXT NOT NULL,PRIMARY KEY(task_id,seq)) STRICT;
|
|
515
|
+
INSERT OR IGNORE INTO ${settings} VALUES(1,4,8);`);
|
|
516
|
+
return {
|
|
517
|
+
transaction(write) {
|
|
518
|
+
db.exec("BEGIN IMMEDIATE");
|
|
519
|
+
try {
|
|
520
|
+
const result = write();
|
|
521
|
+
db.exec("COMMIT");
|
|
522
|
+
return result;
|
|
523
|
+
} catch (error) {
|
|
524
|
+
db.exec("ROLLBACK");
|
|
525
|
+
throw error;
|
|
526
|
+
}
|
|
527
|
+
},
|
|
528
|
+
settings() {
|
|
529
|
+
const row = db.prepare(`SELECT max_concurrent,max_retained_connections FROM ${settings} WHERE singleton=1`).get();
|
|
530
|
+
return SettingsSchema.parse({
|
|
531
|
+
maxConcurrent: row.max_concurrent,
|
|
532
|
+
maxRetainedConnections: row.max_retained_connections
|
|
533
|
+
});
|
|
534
|
+
},
|
|
535
|
+
setSettings(input) {
|
|
536
|
+
const value = SettingsSchema.parse(input);
|
|
537
|
+
db.prepare(`UPDATE ${settings} SET max_concurrent=?,max_retained_connections=? WHERE singleton=1`).run(value.maxConcurrent, value.maxRetainedConnections);
|
|
538
|
+
return value;
|
|
539
|
+
},
|
|
540
|
+
instances() {
|
|
541
|
+
return db.prepare(`SELECT payload FROM ${instances} ORDER BY id`).all().map((row) => InstanceSchema.parse(JSON.parse(String(row.payload))));
|
|
542
|
+
},
|
|
543
|
+
saveInstance(input) {
|
|
544
|
+
const value = InstanceSchema.parse(input);
|
|
545
|
+
db.prepare(`INSERT INTO ${instances} VALUES(?,?) ON CONFLICT(id) DO UPDATE SET payload=excluded.payload`).run(value.id, JSON.stringify(value));
|
|
546
|
+
return value;
|
|
547
|
+
},
|
|
548
|
+
removeInstance(id) {
|
|
549
|
+
db.prepare(`DELETE FROM ${instances} WHERE id=?`).run(id);
|
|
550
|
+
},
|
|
551
|
+
delegation(id) {
|
|
552
|
+
const row = db.prepare(`SELECT payload FROM ${delegations} WHERE id=?`).get(id);
|
|
553
|
+
return row ? DelegationSchema.parse(JSON.parse(String(row.payload))) : void 0;
|
|
554
|
+
},
|
|
555
|
+
task(id) {
|
|
556
|
+
const row = db.prepare(`SELECT payload FROM ${tasks} WHERE id=?`).get(id);
|
|
557
|
+
return row ? TaskSchema.parse(JSON.parse(String(row.payload))) : void 0;
|
|
558
|
+
},
|
|
559
|
+
delegations() {
|
|
560
|
+
return db.prepare(`SELECT payload FROM ${delegations} ORDER BY rowid`).all().map((row) => DelegationSchema.parse(JSON.parse(String(row.payload))));
|
|
561
|
+
},
|
|
562
|
+
saveDelegation(input) {
|
|
563
|
+
const value = DelegationSchema.parse(input);
|
|
564
|
+
db.prepare(`INSERT INTO ${delegations} VALUES(?,?,?,?) ON CONFLICT(id) DO UPDATE SET payload=excluded.payload`).run(value.id, value.rootSessionId, value.parentSessionId, JSON.stringify(value));
|
|
565
|
+
},
|
|
566
|
+
tasks(id) {
|
|
567
|
+
return (id === void 0 ? db.prepare(`SELECT payload FROM ${tasks} ORDER BY rowid`).all() : db.prepare(`SELECT payload FROM ${tasks} WHERE delegation_id=? ORDER BY rowid`).all(id)).map((row) => TaskSchema.parse(JSON.parse(String(row.payload))));
|
|
568
|
+
},
|
|
569
|
+
saveTask(input) {
|
|
570
|
+
const value = TaskSchema.parse(input);
|
|
571
|
+
db.prepare(`INSERT INTO ${tasks}(id,delegation_id,request_key,payload) VALUES(?,?,?,?) ON CONFLICT(id) DO UPDATE SET payload=excluded.payload`).run(value.id, value.delegationId, value.requestKey, JSON.stringify(value));
|
|
572
|
+
},
|
|
573
|
+
append(taskId, payload) {
|
|
574
|
+
const encoded = JSON.stringify(payload), bytes = Buffer.byteLength(encoded);
|
|
575
|
+
const own = !db.isTransaction;
|
|
576
|
+
if (own) db.exec("BEGIN IMMEDIATE");
|
|
577
|
+
try {
|
|
578
|
+
if (db.prepare(`UPDATE ${tasks} SET output_bytes=output_bytes+? WHERE id=? AND output_bytes+?<=33554432`).run(bytes, taskId, bytes).changes !== 1) throw new Error("task-output-limit");
|
|
579
|
+
db.prepare(`INSERT INTO ${updates}(task_id,seq,payload) SELECT ?,COALESCE(MAX(seq),0)+1,? FROM ${updates} WHERE task_id=?`).run(taskId, encoded, taskId);
|
|
580
|
+
if (own) db.exec("COMMIT");
|
|
581
|
+
} catch (error) {
|
|
582
|
+
if (own) db.exec("ROLLBACK");
|
|
583
|
+
throw error;
|
|
584
|
+
}
|
|
585
|
+
},
|
|
586
|
+
updates(taskId, after = 0) {
|
|
587
|
+
return db.prepare(`SELECT seq,payload FROM ${updates} WHERE task_id=? AND seq>? ORDER BY seq LIMIT 200`).all(taskId, after).map((row) => ({
|
|
588
|
+
seq: Number(row.seq),
|
|
589
|
+
payload: JSON.parse(String(row.payload))
|
|
590
|
+
}));
|
|
591
|
+
}
|
|
592
|
+
};
|
|
593
|
+
}
|
|
594
|
+
//#endregion
|
|
595
|
+
//#region src/manager.ts
|
|
596
|
+
/** The question id an ACP permission is asked under: one question per request. */
|
|
597
|
+
const PERMISSION_QUESTION = "permission";
|
|
598
|
+
/** An ACP permission as the host draws it: the delegate's label and the
|
|
599
|
+
* tool call's title, one single-choice question whose options are ACP's
|
|
600
|
+
* own, ids and names unchanged, so the chosen id goes back as it is. */
|
|
601
|
+
function permissionQuestion(label, request) {
|
|
602
|
+
const subject = request.toolCall.title?.trim() || "permission requested";
|
|
603
|
+
return {
|
|
604
|
+
title: `${label}: ${subject}`,
|
|
605
|
+
kind: "approval",
|
|
606
|
+
questions: [{
|
|
607
|
+
id: PERMISSION_QUESTION,
|
|
608
|
+
text: subject,
|
|
609
|
+
freeText: false,
|
|
610
|
+
options: request.options.map((option) => ({
|
|
611
|
+
id: option.optionId,
|
|
612
|
+
label: option.name.trim() || option.optionId
|
|
613
|
+
}))
|
|
614
|
+
}]
|
|
615
|
+
};
|
|
616
|
+
}
|
|
617
|
+
/** Creates a coordinator that accepts background prompts without waiting for completion. */
|
|
618
|
+
function createAcpManager(deps) {
|
|
619
|
+
const { store, sessions, delivery } = deps;
|
|
620
|
+
const connections = /* @__PURE__ */ new Map();
|
|
621
|
+
const processes = /* @__PURE__ */ new Map();
|
|
622
|
+
const running = /* @__PURE__ */ new Map();
|
|
623
|
+
const starting = /* @__PURE__ */ new Map();
|
|
624
|
+
const stopping = /* @__PURE__ */ new Set();
|
|
625
|
+
const launches = /* @__PURE__ */ new Map();
|
|
626
|
+
const permissions = /* @__PURE__ */ new Map();
|
|
627
|
+
let closed = false;
|
|
628
|
+
let withdrawn = false;
|
|
629
|
+
const changed = (delegation, task) => {
|
|
630
|
+
for (const id of /* @__PURE__ */ new Set([delegation.parentSessionId, delegation.rootSessionId])) try {
|
|
631
|
+
deps.changed(id, {
|
|
632
|
+
delegation,
|
|
633
|
+
task,
|
|
634
|
+
permissions: [...permissions.entries()].filter(([, row]) => row.delegationId === delegation.id).map(([id, row]) => ({
|
|
635
|
+
id,
|
|
636
|
+
generation: row.generation,
|
|
637
|
+
request: row.request
|
|
638
|
+
}))
|
|
639
|
+
});
|
|
640
|
+
} catch {}
|
|
641
|
+
};
|
|
642
|
+
const get = (id) => {
|
|
643
|
+
const row = store.delegation(id);
|
|
644
|
+
if (!row) throw new Error("not-found");
|
|
645
|
+
return row;
|
|
646
|
+
};
|
|
647
|
+
const task = (id) => {
|
|
648
|
+
const row = store.task(id);
|
|
649
|
+
if (!row) throw new Error("not-found");
|
|
650
|
+
return row;
|
|
651
|
+
};
|
|
652
|
+
function authorize(caller, row) {
|
|
653
|
+
const owner = sessions.resolve(row.parentSessionId);
|
|
654
|
+
if (caller !== row.parentSessionId && !owner.ancestors.includes(caller)) throw new Error("forbidden");
|
|
655
|
+
}
|
|
656
|
+
function capacity(root, connection) {
|
|
657
|
+
const ids = new Set(store.delegations().filter((row) => row.rootSessionId === root).map((row) => row.id));
|
|
658
|
+
if (store.tasks().filter((row) => ids.has(row.delegationId) && row.state !== "queued" && row.state !== "finished").length >= store.settings().maxConcurrent) throw new Error("capacity-exceeded");
|
|
659
|
+
if (connection && store.delegations().filter((row) => row.rootSessionId === root && row.connectionState !== "closed" && row.connectionState !== "interrupted").length >= store.settings().maxRetainedConnections) throw new Error("retained-limit: close an existing delegation first");
|
|
660
|
+
}
|
|
661
|
+
function update(input, fields) {
|
|
662
|
+
const next = {
|
|
663
|
+
...input,
|
|
664
|
+
...fields,
|
|
665
|
+
revision: input.revision + 1
|
|
666
|
+
};
|
|
667
|
+
store.saveTask(next);
|
|
668
|
+
changed(get(next.delegationId), next);
|
|
669
|
+
return next;
|
|
670
|
+
}
|
|
671
|
+
function finish(current, outcome, error = null) {
|
|
672
|
+
if (task(current.id).state === "finished") return;
|
|
673
|
+
const row = get(current.delegationId);
|
|
674
|
+
const next = {
|
|
675
|
+
...current,
|
|
676
|
+
state: "finished",
|
|
677
|
+
outcome,
|
|
678
|
+
error,
|
|
679
|
+
revision: current.revision + 1
|
|
680
|
+
};
|
|
681
|
+
delivery.commit((view) => view.update("task", { payload: JSON.stringify(next) }, { id: next.id }), [{
|
|
682
|
+
target: row.parentSessionId,
|
|
683
|
+
sourceKey: next.id,
|
|
684
|
+
taskId: next.id,
|
|
685
|
+
targetGeneration: next.targetGeneration,
|
|
686
|
+
text: `ACP ${row.id}, task ${next.id}: ${outcome}${error ? ` (${error})` : ""}\n${next.result}${next.truncated ? "\n[Truncated; open delegation details.]" : ""}`
|
|
687
|
+
}]);
|
|
688
|
+
changed(row, next);
|
|
689
|
+
}
|
|
690
|
+
function expire(id) {
|
|
691
|
+
for (const [key, value] of permissions) if (value.delegationId === id) {
|
|
692
|
+
permissions.delete(key);
|
|
693
|
+
value.withdraw.abort();
|
|
694
|
+
value.resolve({ outcome: { outcome: "cancelled" } });
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
/** The person's reply to one permission, while ACP still waits for it. */
|
|
698
|
+
function answered(id, reply) {
|
|
699
|
+
if (withdrawn) return;
|
|
700
|
+
const pending = permissions.get(id);
|
|
701
|
+
if (!pending) return;
|
|
702
|
+
const optionId = reply.answers.find((answer) => answer.questionId === PERMISSION_QUESTION)?.optionIds?.[0];
|
|
703
|
+
const current = store.tasks(pending.delegationId).find((one) => one.state === "awaiting-permission" || one.state === "running");
|
|
704
|
+
if (optionId === void 0 || !pending.request.options.some((option) => option.optionId === optionId) || !current) {
|
|
705
|
+
cancelled(id);
|
|
706
|
+
return;
|
|
707
|
+
}
|
|
708
|
+
const waiting = [...permissions].some(([key, other]) => key !== id && other.delegationId === pending.delegationId);
|
|
709
|
+
store.transaction(() => {
|
|
710
|
+
store.append(current.id, {
|
|
711
|
+
kind: "permission-answered",
|
|
712
|
+
id,
|
|
713
|
+
optionId
|
|
714
|
+
});
|
|
715
|
+
store.saveTask({
|
|
716
|
+
...current,
|
|
717
|
+
state: waiting ? "awaiting-permission" : "running",
|
|
718
|
+
revision: current.revision + 1
|
|
719
|
+
});
|
|
720
|
+
});
|
|
721
|
+
permissions.delete(id);
|
|
722
|
+
pending.resolve({ outcome: {
|
|
723
|
+
outcome: "selected",
|
|
724
|
+
optionId
|
|
725
|
+
} });
|
|
726
|
+
changed(get(pending.delegationId), task(current.id));
|
|
727
|
+
}
|
|
728
|
+
/** The question ended without an answer: ACP reads it as cancelled. */
|
|
729
|
+
function cancelled(id) {
|
|
730
|
+
if (withdrawn) return;
|
|
731
|
+
const pending = permissions.get(id);
|
|
732
|
+
if (!pending) return;
|
|
733
|
+
permissions.delete(id);
|
|
734
|
+
pending.resolve({ outcome: { outcome: "cancelled" } });
|
|
735
|
+
changed(get(pending.delegationId));
|
|
736
|
+
}
|
|
737
|
+
async function disconnect(id) {
|
|
738
|
+
expire(id);
|
|
739
|
+
const pending = starting.get(id);
|
|
740
|
+
if (pending) await pending.catch(() => {});
|
|
741
|
+
const connection = connections.get(id);
|
|
742
|
+
if (withdrawn) {
|
|
743
|
+
const process = connection?.process ?? processes.get(id);
|
|
744
|
+
connections.delete(id);
|
|
745
|
+
processes.delete(id);
|
|
746
|
+
if (process) await process.stop();
|
|
747
|
+
return;
|
|
748
|
+
}
|
|
749
|
+
const row = get(id);
|
|
750
|
+
try {
|
|
751
|
+
const process = connection?.process ?? processes.get(id);
|
|
752
|
+
if (process) await process.stop();
|
|
753
|
+
processes.delete(id);
|
|
754
|
+
connections.delete(id);
|
|
755
|
+
if (withdrawn) return;
|
|
756
|
+
store.saveDelegation({
|
|
757
|
+
...row,
|
|
758
|
+
connectionState: "closed",
|
|
759
|
+
processId: null
|
|
760
|
+
});
|
|
761
|
+
} catch {
|
|
762
|
+
if (withdrawn) throw new Error("cleanup-failed");
|
|
763
|
+
store.saveDelegation({
|
|
764
|
+
...row,
|
|
765
|
+
connectionState: "cleanup-failed"
|
|
766
|
+
});
|
|
767
|
+
throw new Error("cleanup-failed");
|
|
768
|
+
}
|
|
769
|
+
changed(get(id));
|
|
770
|
+
}
|
|
771
|
+
async function connect(row) {
|
|
772
|
+
const launch = launches.get(row.id);
|
|
773
|
+
if (!launch) throw new Error("resume-unavailable: explicit launch authorization required");
|
|
774
|
+
const process = await launch.launch();
|
|
775
|
+
if (withdrawn) {
|
|
776
|
+
await process.stop();
|
|
777
|
+
throw new Error("stopping");
|
|
778
|
+
}
|
|
779
|
+
processes.set(row.id, process);
|
|
780
|
+
store.saveDelegation({
|
|
781
|
+
...get(row.id),
|
|
782
|
+
processId: process.processId,
|
|
783
|
+
execution: launch.execution
|
|
784
|
+
});
|
|
785
|
+
const connection = await connectAcp(process, {
|
|
786
|
+
permission(request) {
|
|
787
|
+
if (withdrawn) return Promise.resolve({ outcome: { outcome: "cancelled" } });
|
|
788
|
+
const current = store.tasks(row.id).find((one) => one.state === "running" || one.state === "awaiting-permission");
|
|
789
|
+
if (!current || request.sessionId !== get(row.id).remoteSessionId) return Promise.resolve({ outcome: { outcome: "cancelled" } });
|
|
790
|
+
const id = randomUUID();
|
|
791
|
+
const withdraw = new AbortController();
|
|
792
|
+
return new Promise((resolve) => {
|
|
793
|
+
permissions.set(id, {
|
|
794
|
+
delegationId: row.id,
|
|
795
|
+
generation: row.generation,
|
|
796
|
+
request,
|
|
797
|
+
resolve,
|
|
798
|
+
withdraw
|
|
799
|
+
});
|
|
800
|
+
store.append(current.id, {
|
|
801
|
+
kind: "permission-requested",
|
|
802
|
+
id,
|
|
803
|
+
generation: row.generation,
|
|
804
|
+
request
|
|
805
|
+
});
|
|
806
|
+
update(current, { state: "awaiting-permission" });
|
|
807
|
+
deps.ask(get(row.id).parentSessionId, permissionQuestion(row.instance.label, request), { signal: withdraw.signal }).then((reply) => answered(id, reply), () => cancelled(id));
|
|
808
|
+
});
|
|
809
|
+
},
|
|
810
|
+
update(notification) {
|
|
811
|
+
if (withdrawn) return;
|
|
812
|
+
const current = store.tasks(row.id).find((one) => one.state !== "queued" && one.state !== "finished");
|
|
813
|
+
if (!current || current.state === "starting") return;
|
|
814
|
+
if (notification.sessionId !== get(row.id).remoteSessionId) throw new Error("remote-session-mismatch");
|
|
815
|
+
store.append(current.id, notification.update);
|
|
816
|
+
if (notification.update.sessionUpdate === "config_option_update") {
|
|
817
|
+
store.saveDelegation({
|
|
818
|
+
...get(row.id),
|
|
819
|
+
configOptions: notification.update.configOptions
|
|
820
|
+
});
|
|
821
|
+
changed(get(row.id), current);
|
|
822
|
+
}
|
|
823
|
+
if (notification.update.sessionUpdate === "agent_message_chunk" && notification.update.content.type === "text") {
|
|
824
|
+
const text = current.result + notification.update.content.text;
|
|
825
|
+
const bytes = Buffer.from(text);
|
|
826
|
+
let end = Math.min(bytes.length, 65536);
|
|
827
|
+
if (end < bytes.length) while (end > 0 && (bytes[end] & 192) === 128) end--;
|
|
828
|
+
update(current, {
|
|
829
|
+
result: bytes.subarray(0, end).toString("utf8"),
|
|
830
|
+
truncated: current.truncated || bytes.length > 65536
|
|
831
|
+
});
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
});
|
|
835
|
+
if (withdrawn) {
|
|
836
|
+
await process.stop();
|
|
837
|
+
throw new Error("stopping");
|
|
838
|
+
}
|
|
839
|
+
store.saveDelegation({
|
|
840
|
+
...get(row.id),
|
|
841
|
+
capabilities: connection.initialized.agentCapabilities ?? {}
|
|
842
|
+
});
|
|
843
|
+
connections.set(row.id, connection);
|
|
844
|
+
try {
|
|
845
|
+
let configuration = [];
|
|
846
|
+
if (row.remoteSessionId) {
|
|
847
|
+
const capabilities = connection.initialized.agentCapabilities;
|
|
848
|
+
if (capabilities?.sessionCapabilities?.resume) configuration = (await control(connection.client.resumeSession({
|
|
849
|
+
sessionId: row.remoteSessionId,
|
|
850
|
+
cwd: row.cwd,
|
|
851
|
+
mcpServers: []
|
|
852
|
+
}))).configOptions ?? [];
|
|
853
|
+
else if (capabilities?.loadSession) configuration = (await control(connection.client.loadSession({
|
|
854
|
+
sessionId: row.remoteSessionId,
|
|
855
|
+
cwd: row.cwd,
|
|
856
|
+
mcpServers: []
|
|
857
|
+
}))).configOptions ?? [];
|
|
858
|
+
else throw new Error("resume-unavailable");
|
|
859
|
+
} else {
|
|
860
|
+
const remote = await control(connection.client.newSession({
|
|
861
|
+
cwd: row.cwd,
|
|
862
|
+
mcpServers: []
|
|
863
|
+
}));
|
|
864
|
+
if (withdrawn) throw new Error("stopping");
|
|
865
|
+
store.saveDelegation({
|
|
866
|
+
...get(row.id),
|
|
867
|
+
remoteSessionId: remote.sessionId
|
|
868
|
+
});
|
|
869
|
+
configuration = remote.configOptions ?? [];
|
|
870
|
+
}
|
|
871
|
+
if (withdrawn) throw new Error("stopping");
|
|
872
|
+
store.saveDelegation({
|
|
873
|
+
...get(row.id),
|
|
874
|
+
configOptions: configuration
|
|
875
|
+
});
|
|
876
|
+
const requested = { ...row.config };
|
|
877
|
+
if (row.model) {
|
|
878
|
+
const selector = configuration.find((option) => option.category === "model");
|
|
879
|
+
if (!selector) throw new Error("model-selection-unavailable");
|
|
880
|
+
requested[selector.id] = row.model;
|
|
881
|
+
}
|
|
882
|
+
for (const [configId, value] of Object.entries(requested)) {
|
|
883
|
+
const option = configuration.find((option) => option.id === configId);
|
|
884
|
+
if (!option || option.type !== "select") throw new Error("config-option-unavailable");
|
|
885
|
+
if (option.category !== "model" && option.category !== "thought_level") throw new Error("config-option-forbidden");
|
|
886
|
+
if (!option.options.flatMap((entry) => "options" in entry ? entry.options : [entry]).some((choice) => choice.value === value)) throw new Error("invalid-config-value");
|
|
887
|
+
configuration = (await control(connection.client.setSessionConfigOption({
|
|
888
|
+
sessionId: get(row.id).remoteSessionId,
|
|
889
|
+
configId,
|
|
890
|
+
value
|
|
891
|
+
}))).configOptions;
|
|
892
|
+
}
|
|
893
|
+
if (withdrawn) throw new Error("stopping");
|
|
894
|
+
store.saveDelegation({
|
|
895
|
+
...get(row.id),
|
|
896
|
+
connectionState: "connected",
|
|
897
|
+
configOptions: configuration
|
|
898
|
+
});
|
|
899
|
+
connection.client.closed.then(async () => {
|
|
900
|
+
if (withdrawn || connections.get(row.id) !== connection) return;
|
|
901
|
+
try {
|
|
902
|
+
await disconnect(row.id);
|
|
903
|
+
} catch {}
|
|
904
|
+
});
|
|
905
|
+
return connection;
|
|
906
|
+
} catch (error) {
|
|
907
|
+
await connection.process.stop();
|
|
908
|
+
connections.delete(row.id);
|
|
909
|
+
if (error && typeof error === "object" && "code" in error && error.code === -32e3) throw new Error("auth-required");
|
|
910
|
+
if (error instanceof Error && [
|
|
911
|
+
"resume-unavailable",
|
|
912
|
+
"model-selection-unavailable",
|
|
913
|
+
"config-option-unavailable",
|
|
914
|
+
"config-option-forbidden",
|
|
915
|
+
"invalid-config-value",
|
|
916
|
+
"protocol-timeout"
|
|
917
|
+
].includes(error.message)) throw error;
|
|
918
|
+
throw new Error("session-setup-failed");
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
async function run(id) {
|
|
922
|
+
if (closed || running.has(id)) return;
|
|
923
|
+
const current = store.tasks(id).find((one) => one.state !== "finished");
|
|
924
|
+
if (!current) return;
|
|
925
|
+
const work = (async () => {
|
|
926
|
+
try {
|
|
927
|
+
const row = get(id);
|
|
928
|
+
if (current.state === "queued") capacity(row.rootSessionId, !connections.has(id));
|
|
929
|
+
update(current, { state: "starting" });
|
|
930
|
+
let connection = connections.get(id);
|
|
931
|
+
if (!connection) {
|
|
932
|
+
const opening = connect(row);
|
|
933
|
+
starting.set(id, opening);
|
|
934
|
+
try {
|
|
935
|
+
connection = await opening;
|
|
936
|
+
} finally {
|
|
937
|
+
starting.delete(id);
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
if (withdrawn) return;
|
|
941
|
+
if (task(current.id).state === "finished" || closed || stopping.has(id)) {
|
|
942
|
+
await disconnect(id);
|
|
943
|
+
return;
|
|
944
|
+
}
|
|
945
|
+
update(task(current.id), { state: "running" });
|
|
946
|
+
const response = await connection.client.prompt({
|
|
947
|
+
sessionId: get(id).remoteSessionId,
|
|
948
|
+
prompt: [{
|
|
949
|
+
type: "text",
|
|
950
|
+
text: current.input
|
|
951
|
+
}]
|
|
952
|
+
});
|
|
953
|
+
if (withdrawn) return;
|
|
954
|
+
expire(id);
|
|
955
|
+
const cancelled = task(current.id).state === "stopping" || response.stopReason === "cancelled";
|
|
956
|
+
const failure = response.stopReason === "refusal" ? "external-refusal" : response.stopReason === "max_tokens" || response.stopReason === "max_turn_requests" ? "external-limit" : void 0;
|
|
957
|
+
finish(task(current.id), cancelled ? "cancelled" : failure ? "failed" : "completed", cancelled ? void 0 : failure);
|
|
958
|
+
} catch (error) {
|
|
959
|
+
if (withdrawn) return;
|
|
960
|
+
try {
|
|
961
|
+
await disconnect(id);
|
|
962
|
+
} catch {}
|
|
963
|
+
if (withdrawn) return;
|
|
964
|
+
const safe = error && typeof error === "object" && "code" in error && error.code === -32e3 ? "auth-required" : error instanceof Error && [
|
|
965
|
+
"resume-unavailable",
|
|
966
|
+
"model-selection-unavailable",
|
|
967
|
+
"config-option-unavailable",
|
|
968
|
+
"config-option-forbidden",
|
|
969
|
+
"invalid-config-value",
|
|
970
|
+
"protocol-timeout",
|
|
971
|
+
"session-setup-failed",
|
|
972
|
+
"auth-required",
|
|
973
|
+
"initialize-failed",
|
|
974
|
+
"capacity-exceeded"
|
|
975
|
+
].includes(error.message) ? error.message : "external-task-failed";
|
|
976
|
+
finish(task(current.id), "failed", safe);
|
|
977
|
+
} finally {
|
|
978
|
+
running.delete(id);
|
|
979
|
+
if (!closed && store.tasks(id).some((one) => one.state === "queued")) queueMicrotask(() => {
|
|
980
|
+
run(id);
|
|
981
|
+
});
|
|
982
|
+
}
|
|
983
|
+
})();
|
|
984
|
+
running.set(id, work);
|
|
985
|
+
await work;
|
|
986
|
+
}
|
|
987
|
+
function accepted(id, input, requestKey) {
|
|
988
|
+
if (stopping.has(id)) throw new Error("stopping");
|
|
989
|
+
const row = get(id);
|
|
990
|
+
if (row.connectionState === "cleanup-failed") throw new Error("cleanup-required");
|
|
991
|
+
const previous = store.tasks(id).find((one) => one.requestKey === requestKey);
|
|
992
|
+
if (previous) {
|
|
993
|
+
if (previous.input !== input) throw new Error("request-key-conflict");
|
|
994
|
+
return previous;
|
|
995
|
+
}
|
|
996
|
+
const busy = store.tasks(id).some((one) => one.state !== "finished");
|
|
997
|
+
if (!busy) capacity(row.rootSessionId, !connections.has(id));
|
|
998
|
+
if (store.tasks(id).filter((one) => one.state === "queued").length >= 32) throw new Error("queue-full");
|
|
999
|
+
const value = {
|
|
1000
|
+
id: randomUUID(),
|
|
1001
|
+
delegationId: id,
|
|
1002
|
+
requestKey,
|
|
1003
|
+
targetGeneration: delivery.captureGeneration(row.parentSessionId),
|
|
1004
|
+
input,
|
|
1005
|
+
state: busy ? "queued" : "starting",
|
|
1006
|
+
outcome: null,
|
|
1007
|
+
error: null,
|
|
1008
|
+
result: "",
|
|
1009
|
+
truncated: false,
|
|
1010
|
+
createdAt: Date.now(),
|
|
1011
|
+
revision: 0
|
|
1012
|
+
};
|
|
1013
|
+
store.saveTask(value);
|
|
1014
|
+
changed(row, value);
|
|
1015
|
+
queueMicrotask(() => {
|
|
1016
|
+
run(id);
|
|
1017
|
+
});
|
|
1018
|
+
return value;
|
|
1019
|
+
}
|
|
1020
|
+
return {
|
|
1021
|
+
recover() {
|
|
1022
|
+
for (const row of store.delegations()) {
|
|
1023
|
+
store.saveDelegation({
|
|
1024
|
+
...row,
|
|
1025
|
+
connectionState: "interrupted",
|
|
1026
|
+
processId: null,
|
|
1027
|
+
generation: randomUUID()
|
|
1028
|
+
});
|
|
1029
|
+
for (const current of store.tasks(row.id)) if (current.state !== "finished") finish(current, "interrupted", "gateway-restarted");
|
|
1030
|
+
}
|
|
1031
|
+
},
|
|
1032
|
+
/** Accepts one prompt and records its effective execution only after its launch succeeds. */
|
|
1033
|
+
async start(input, launch, execution) {
|
|
1034
|
+
if (closed) throw new Error("stopping");
|
|
1035
|
+
const selectedExecution = LaunchExecutionSchema.parse(execution);
|
|
1036
|
+
const context = sessions.resolve(input.sessionId);
|
|
1037
|
+
const previous = store.tasks().find((one) => one.requestKey === input.requestKey && get(one.delegationId).parentSessionId === input.sessionId);
|
|
1038
|
+
if (previous) {
|
|
1039
|
+
const row = get(previous.delegationId);
|
|
1040
|
+
if (previous.input !== input.task || row.instance.id !== input.instanceId || row.cwd !== input.cwd || row.model !== input.model || JSON.stringify(row.config) !== JSON.stringify(input.config ?? {})) throw new Error("request-key-conflict");
|
|
1041
|
+
return previous;
|
|
1042
|
+
}
|
|
1043
|
+
const instance = store.instances().find((row) => row.id === input.instanceId && row.enabled);
|
|
1044
|
+
if (!instance) throw new Error("instance-missing");
|
|
1045
|
+
capacity(context.rootSessionId, true);
|
|
1046
|
+
const row = {
|
|
1047
|
+
id: randomUUID(),
|
|
1048
|
+
parentSessionId: input.sessionId,
|
|
1049
|
+
rootSessionId: context.rootSessionId,
|
|
1050
|
+
instance,
|
|
1051
|
+
cwd: input.cwd,
|
|
1052
|
+
...input.model ? { model: input.model } : {},
|
|
1053
|
+
config: input.config ?? {},
|
|
1054
|
+
remoteSessionId: null,
|
|
1055
|
+
generation: randomUUID(),
|
|
1056
|
+
processId: null,
|
|
1057
|
+
execution: null,
|
|
1058
|
+
connectionState: "starting",
|
|
1059
|
+
createdAt: Date.now()
|
|
1060
|
+
};
|
|
1061
|
+
launches.set(row.id, {
|
|
1062
|
+
launch,
|
|
1063
|
+
execution: selectedExecution
|
|
1064
|
+
});
|
|
1065
|
+
const value = {
|
|
1066
|
+
id: randomUUID(),
|
|
1067
|
+
delegationId: row.id,
|
|
1068
|
+
requestKey: input.requestKey,
|
|
1069
|
+
targetGeneration: delivery.captureGeneration(input.sessionId),
|
|
1070
|
+
input: input.task,
|
|
1071
|
+
state: "starting",
|
|
1072
|
+
outcome: null,
|
|
1073
|
+
error: null,
|
|
1074
|
+
result: "",
|
|
1075
|
+
truncated: false,
|
|
1076
|
+
createdAt: Date.now(),
|
|
1077
|
+
revision: 0
|
|
1078
|
+
};
|
|
1079
|
+
store.transaction(() => {
|
|
1080
|
+
store.saveDelegation(row);
|
|
1081
|
+
store.saveTask(value);
|
|
1082
|
+
});
|
|
1083
|
+
changed(row, value);
|
|
1084
|
+
queueMicrotask(() => {
|
|
1085
|
+
run(row.id);
|
|
1086
|
+
});
|
|
1087
|
+
return value;
|
|
1088
|
+
},
|
|
1089
|
+
/** Reuses a live connection, or requires a fresh approved factory and isolation facts. */
|
|
1090
|
+
send(caller, id, input, requestKey, prepared) {
|
|
1091
|
+
if (closed) throw new Error("stopping");
|
|
1092
|
+
authorize(caller, get(id));
|
|
1093
|
+
if (prepared) launches.set(id, {
|
|
1094
|
+
launch: prepared.launch,
|
|
1095
|
+
execution: LaunchExecutionSchema.parse(prepared.execution)
|
|
1096
|
+
});
|
|
1097
|
+
if (!connections.has(id) && !prepared) throw new Error("resume-unavailable: launch authorization required");
|
|
1098
|
+
const result = accepted(id, input, requestKey);
|
|
1099
|
+
if (!connections.has(id)) store.saveDelegation({
|
|
1100
|
+
...get(id),
|
|
1101
|
+
generation: randomUUID(),
|
|
1102
|
+
connectionState: "starting",
|
|
1103
|
+
execution: null
|
|
1104
|
+
});
|
|
1105
|
+
return result;
|
|
1106
|
+
},
|
|
1107
|
+
usage(caller) {
|
|
1108
|
+
const root = sessions.resolve(caller).rootSessionId;
|
|
1109
|
+
const rows = store.delegations().filter((row) => row.rootSessionId === root);
|
|
1110
|
+
const ids = new Set(rows.map((row) => row.id));
|
|
1111
|
+
return {
|
|
1112
|
+
limits: store.settings(),
|
|
1113
|
+
tasks: store.tasks().filter((row) => ids.has(row.delegationId) && row.state !== "queued" && row.state !== "finished").length,
|
|
1114
|
+
connections: rows.filter((row) => row.connectionState !== "closed" && row.connectionState !== "interrupted").length
|
|
1115
|
+
};
|
|
1116
|
+
},
|
|
1117
|
+
get(caller, id, offset = 0, limit = 20) {
|
|
1118
|
+
const row = get(id);
|
|
1119
|
+
authorize(caller, row);
|
|
1120
|
+
return {
|
|
1121
|
+
delegation: row,
|
|
1122
|
+
tasks: store.tasks(id).slice().reverse().slice(offset, offset + Math.min(20, limit))
|
|
1123
|
+
};
|
|
1124
|
+
},
|
|
1125
|
+
task(caller, id, taskId) {
|
|
1126
|
+
authorize(caller, get(id));
|
|
1127
|
+
const current = task(taskId);
|
|
1128
|
+
if (current.delegationId !== id) throw new Error("not-found");
|
|
1129
|
+
return current;
|
|
1130
|
+
},
|
|
1131
|
+
list(caller, offset = 0, limit = 50) {
|
|
1132
|
+
sessions.resolve(caller);
|
|
1133
|
+
return store.delegations().filter((row) => {
|
|
1134
|
+
try {
|
|
1135
|
+
authorize(caller, row);
|
|
1136
|
+
return true;
|
|
1137
|
+
} catch {
|
|
1138
|
+
return false;
|
|
1139
|
+
}
|
|
1140
|
+
}).slice().reverse().slice(offset, offset + Math.min(200, limit)).map((row) => ({
|
|
1141
|
+
delegation: row,
|
|
1142
|
+
tasks: store.tasks(row.id).slice(-1).map((task) => ({
|
|
1143
|
+
...task,
|
|
1144
|
+
input: task.input.slice(0, 2048),
|
|
1145
|
+
result: task.result.slice(0, 2048)
|
|
1146
|
+
})),
|
|
1147
|
+
permissions: [...permissions.entries()].filter(([, value]) => value.delegationId === row.id).map(([id, value]) => ({
|
|
1148
|
+
id,
|
|
1149
|
+
generation: value.generation,
|
|
1150
|
+
request: value.request
|
|
1151
|
+
}))
|
|
1152
|
+
}));
|
|
1153
|
+
},
|
|
1154
|
+
hasConnection: (id) => connections.has(id),
|
|
1155
|
+
async stop(caller, id) {
|
|
1156
|
+
const row = get(id);
|
|
1157
|
+
authorize(caller, row);
|
|
1158
|
+
expire(id);
|
|
1159
|
+
const current = store.tasks(id).find((one) => one.state !== "finished" && one.state !== "queued");
|
|
1160
|
+
if (!current) return;
|
|
1161
|
+
if (current.state === "starting") {
|
|
1162
|
+
stopping.add(id);
|
|
1163
|
+
try {
|
|
1164
|
+
await disconnect(id);
|
|
1165
|
+
finish(task(current.id), "cancelled");
|
|
1166
|
+
} finally {
|
|
1167
|
+
stopping.delete(id);
|
|
1168
|
+
}
|
|
1169
|
+
return;
|
|
1170
|
+
}
|
|
1171
|
+
update(current, { state: "stopping" });
|
|
1172
|
+
const connection = connections.get(id);
|
|
1173
|
+
try {
|
|
1174
|
+
if (connection && row.remoteSessionId) await connection.client.cancel({ sessionId: row.remoteSessionId });
|
|
1175
|
+
const work = running.get(id);
|
|
1176
|
+
if (work) await control(work, 5e3);
|
|
1177
|
+
} catch {
|
|
1178
|
+
await disconnect(id);
|
|
1179
|
+
finish(task(current.id), "interrupted", "cancel-timeout");
|
|
1180
|
+
}
|
|
1181
|
+
},
|
|
1182
|
+
async close(caller, id) {
|
|
1183
|
+
authorize(caller, get(id));
|
|
1184
|
+
for (const current of store.tasks(id)) if (current.state === "queued") finish(current, "cancelled");
|
|
1185
|
+
await this.stop(caller, id);
|
|
1186
|
+
await disconnect(id);
|
|
1187
|
+
},
|
|
1188
|
+
/** Releases live resources after owner revocation without reading withdrawn persistence. */
|
|
1189
|
+
async withdraw() {
|
|
1190
|
+
withdrawn = true;
|
|
1191
|
+
closed = true;
|
|
1192
|
+
for (const pending of [...permissions.values()]) expire(pending.delegationId);
|
|
1193
|
+
const live = [.../* @__PURE__ */ new Set([...processes.values(), ...[...connections.values()].map((one) => one.process)])];
|
|
1194
|
+
connections.clear();
|
|
1195
|
+
processes.clear();
|
|
1196
|
+
launches.clear();
|
|
1197
|
+
const stopped = await Promise.allSettled(live.map((process) => process.stop()));
|
|
1198
|
+
await Promise.allSettled([...starting.values(), ...running.values()]);
|
|
1199
|
+
if (stopped.some((result) => result.status === "rejected")) throw new Error("cleanup-failed");
|
|
1200
|
+
},
|
|
1201
|
+
async shutdown() {
|
|
1202
|
+
closed = true;
|
|
1203
|
+
const results = await Promise.allSettled(store.delegations().map((row) => this.close(row.parentSessionId, row.id)));
|
|
1204
|
+
await Promise.allSettled([...running.values()]);
|
|
1205
|
+
if (results.some((row) => row.status === "rejected")) throw new Error("cleanup-failed");
|
|
1206
|
+
}
|
|
1207
|
+
};
|
|
1208
|
+
}
|
|
1209
|
+
//#endregion
|
|
1210
|
+
//#region src/presets.ts
|
|
1211
|
+
/** Known ACP launch recipes; installation and authentication remain local prerequisites. */
|
|
1212
|
+
const ACP_PRESETS = [
|
|
1213
|
+
{
|
|
1214
|
+
id: "codex",
|
|
1215
|
+
label: "Codex",
|
|
1216
|
+
command: "codex",
|
|
1217
|
+
args: [],
|
|
1218
|
+
docs: "https://github.com/agentclientprotocol/codex-acp"
|
|
1219
|
+
},
|
|
1220
|
+
{
|
|
1221
|
+
id: "claude",
|
|
1222
|
+
label: "Claude",
|
|
1223
|
+
command: "claude",
|
|
1224
|
+
args: [],
|
|
1225
|
+
docs: "https://github.com/agentclientprotocol/claude-agent-acp"
|
|
1226
|
+
},
|
|
1227
|
+
{
|
|
1228
|
+
id: "openclaw",
|
|
1229
|
+
label: "OpenClaw",
|
|
1230
|
+
command: "openclaw",
|
|
1231
|
+
args: ["acp"],
|
|
1232
|
+
docs: "https://docs.openclaw.ai/cli/acp"
|
|
1233
|
+
}
|
|
1234
|
+
];
|
|
1235
|
+
//#endregion
|
|
1236
|
+
//#region src/preset-inspection.ts
|
|
1237
|
+
/** Inspects a preset's CLI and bundled adapter without starting either or checking login. */
|
|
1238
|
+
async function inspectPreset(id, commands, searchPath) {
|
|
1239
|
+
const preset = ACP_PRESETS.find((item) => item.id === id);
|
|
1240
|
+
const paths = searchPath ?? (commands.platform === "win32" ? void 0 : [
|
|
1241
|
+
commands.env.PATH ?? "",
|
|
1242
|
+
posix.join(commands.homedir(), ".local", "bin"),
|
|
1243
|
+
"/opt/homebrew/bin",
|
|
1244
|
+
"/usr/local/bin"
|
|
1245
|
+
].join(":"));
|
|
1246
|
+
const cli = await inspectCommand(preset.command, commands, paths);
|
|
1247
|
+
if (cli.status !== "found") return {
|
|
1248
|
+
status: cli.status === "missing" ? "missing-cli" : cli.status === "unsupported" ? "unsupported-cli" : "unavailable-cli",
|
|
1249
|
+
path: cli.path,
|
|
1250
|
+
reason: cli.reason
|
|
1251
|
+
};
|
|
1252
|
+
if (id !== "openclaw") try {
|
|
1253
|
+
bundledAdapter(id);
|
|
1254
|
+
} catch {
|
|
1255
|
+
return {
|
|
1256
|
+
status: "missing-adapter",
|
|
1257
|
+
path: cli.path
|
|
1258
|
+
};
|
|
1259
|
+
}
|
|
1260
|
+
return {
|
|
1261
|
+
status: "found",
|
|
1262
|
+
path: cli.path
|
|
1263
|
+
};
|
|
1264
|
+
}
|
|
1265
|
+
//#endregion
|
|
1266
|
+
//#region src/tool-names.ts
|
|
1267
|
+
/** Canonical names shared by tool registration and browser presentation. */
|
|
1268
|
+
const TOOL_NAMES = [
|
|
1269
|
+
"acp_instances",
|
|
1270
|
+
"acp_delegate",
|
|
1271
|
+
"acp_send",
|
|
1272
|
+
"acp_get",
|
|
1273
|
+
"acp_list",
|
|
1274
|
+
"acp_stop"
|
|
1275
|
+
];
|
|
1276
|
+
//#endregion
|
|
1277
|
+
//#region src/index.ts
|
|
1278
|
+
const Session = z.object({ sessionId: z.string().min(1) }).strict();
|
|
1279
|
+
const Target = Session.extend({ delegationId: z.string().min(1) }).strict();
|
|
1280
|
+
const Start = z.object({
|
|
1281
|
+
instanceId: z.string(),
|
|
1282
|
+
cwd: z.string(),
|
|
1283
|
+
task: z.string().min(1),
|
|
1284
|
+
model: z.string().optional(),
|
|
1285
|
+
config: z.record(z.string(), z.string()).optional()
|
|
1286
|
+
}).strict();
|
|
1287
|
+
const Send = z.object({
|
|
1288
|
+
delegationId: z.string(),
|
|
1289
|
+
task: z.string().min(1)
|
|
1290
|
+
}).strict();
|
|
1291
|
+
const Page = z.object({
|
|
1292
|
+
offset: z.number().int().nonnegative().default(0),
|
|
1293
|
+
limit: z.number().int().min(1).max(200).default(50)
|
|
1294
|
+
}).strict();
|
|
1295
|
+
const Result = z.unknown();
|
|
1296
|
+
const acpPlugin = {
|
|
1297
|
+
name: "@eum-agent/integration-acp",
|
|
1298
|
+
configSchema: z.object({ disabled: z.array(z.enum(TOOL_NAMES)).default([]) }).strict().optional(),
|
|
1299
|
+
requires: [
|
|
1300
|
+
"sandbox",
|
|
1301
|
+
"host-commands",
|
|
1302
|
+
"network",
|
|
1303
|
+
"approval",
|
|
1304
|
+
"protocol-processes",
|
|
1305
|
+
"session-context",
|
|
1306
|
+
"session-delivery",
|
|
1307
|
+
"work-lifecycle"
|
|
1308
|
+
],
|
|
1309
|
+
async apply(ctx, config) {
|
|
1310
|
+
const register = (definition) => config?.disabled.includes(definition.name) ? () => {} : ctx.tools.register(definition);
|
|
1311
|
+
ctx.tools.guide(ACP_GUIDANCE);
|
|
1312
|
+
const store = createAcpStore(ctx.storage.open());
|
|
1313
|
+
const sessions = ctx.services.get("session-context");
|
|
1314
|
+
const commands = ctx.services.get("host-commands");
|
|
1315
|
+
const services = {
|
|
1316
|
+
commands,
|
|
1317
|
+
network: ctx.services.get("network"),
|
|
1318
|
+
sandbox: ctx.services.get("sandbox"),
|
|
1319
|
+
approval: ctx.services.get("approval"),
|
|
1320
|
+
processes: ctx.services.get("protocol-processes")
|
|
1321
|
+
};
|
|
1322
|
+
const changed = ctx.client.registerFrame({
|
|
1323
|
+
name: "changed",
|
|
1324
|
+
delivery: "session",
|
|
1325
|
+
payload: Result
|
|
1326
|
+
});
|
|
1327
|
+
const manager = createAcpManager({
|
|
1328
|
+
store,
|
|
1329
|
+
sessions,
|
|
1330
|
+
delivery: ctx.services.get("session-delivery"),
|
|
1331
|
+
changed: (id, value) => changed.emit(id, value),
|
|
1332
|
+
ask: (sessionId, request, options) => ctx.sessions.ask(sessionId, request, options)
|
|
1333
|
+
});
|
|
1334
|
+
await services.processes.recover();
|
|
1335
|
+
manager.recover();
|
|
1336
|
+
const probes = /* @__PURE__ */ new Map();
|
|
1337
|
+
let draining = false;
|
|
1338
|
+
let withdrawn = false;
|
|
1339
|
+
let unbind = () => {};
|
|
1340
|
+
const drain = async () => {
|
|
1341
|
+
draining = true;
|
|
1342
|
+
const results = await Promise.allSettled([withdrawn ? manager.withdraw() : manager.shutdown(), ...probes.values()]);
|
|
1343
|
+
results.push(...await Promise.allSettled([services.processes.shutdown()]));
|
|
1344
|
+
const failures = results.filter((row) => row.status === "rejected");
|
|
1345
|
+
if (failures.length) throw new AggregateError(failures.map((row) => row.reason), "cleanup-failed");
|
|
1346
|
+
if (withdrawn) {
|
|
1347
|
+
unbind();
|
|
1348
|
+
unbind = () => {};
|
|
1349
|
+
}
|
|
1350
|
+
};
|
|
1351
|
+
unbind = ctx.services.get("work-lifecycle").register(drain);
|
|
1352
|
+
ctx.onDispose(async () => {
|
|
1353
|
+
withdrawn = true;
|
|
1354
|
+
await drain();
|
|
1355
|
+
});
|
|
1356
|
+
const find = (caller, id) => {
|
|
1357
|
+
return manager.get(caller, id);
|
|
1358
|
+
};
|
|
1359
|
+
register({
|
|
1360
|
+
name: "acp_instances",
|
|
1361
|
+
description: "List the enabled ACP adapter instances acp_delegate accepts as instanceId. Read it before delegating; the set follows user configuration.",
|
|
1362
|
+
inputSchema: z.object({}).strict(),
|
|
1363
|
+
async execute() {
|
|
1364
|
+
const rows = store.instances().filter((row) => row.enabled).map((row) => ({
|
|
1365
|
+
instanceId: row.id,
|
|
1366
|
+
label: row.label,
|
|
1367
|
+
...row.adapter === void 0 ? {} : { adapter: row.adapter },
|
|
1368
|
+
executionMode: row.executionMode
|
|
1369
|
+
}));
|
|
1370
|
+
return { content: JSON.stringify(rows) };
|
|
1371
|
+
}
|
|
1372
|
+
});
|
|
1373
|
+
register({
|
|
1374
|
+
name: "acp_delegate",
|
|
1375
|
+
description: "Delegate work to a configured local ACP adapter; instanceId comes from acp_instances. Returns immediately after human launch authorization; stopping the parent does not stop this task.",
|
|
1376
|
+
inputSchema: Start,
|
|
1377
|
+
async execute(input, call) {
|
|
1378
|
+
const instance = store.instances().find((row) => row.id === input.instanceId && row.enabled);
|
|
1379
|
+
if (!instance) throw new Error("instance-missing");
|
|
1380
|
+
const prepared = await prepareLaunch(call, instance, input.cwd, services);
|
|
1381
|
+
if ("result" in prepared) return prepared.result;
|
|
1382
|
+
return { content: JSON.stringify(await manager.start({
|
|
1383
|
+
...input,
|
|
1384
|
+
sessionId: call.sessionId,
|
|
1385
|
+
requestKey: `${call.turn}:${call.toolCallId}`
|
|
1386
|
+
}, prepared.launch, prepared.execution)) };
|
|
1387
|
+
}
|
|
1388
|
+
});
|
|
1389
|
+
register({
|
|
1390
|
+
name: "acp_send",
|
|
1391
|
+
description: "Continue an external delegation. Tasks queue FIFO; reconnecting requires renewed launch authorization.",
|
|
1392
|
+
inputSchema: Send,
|
|
1393
|
+
async execute(input, call) {
|
|
1394
|
+
const row = find(call.sessionId, input.delegationId).delegation;
|
|
1395
|
+
let admitted;
|
|
1396
|
+
if (!manager.hasConnection(row.id)) {
|
|
1397
|
+
const configured = store.instances().find((instance) => instance.id === row.instance.id && instance.enabled);
|
|
1398
|
+
if (!configured) throw new Error("instance-missing");
|
|
1399
|
+
if (configured.revision !== row.instance.revision) throw new Error("configuration-changed: create a new delegation");
|
|
1400
|
+
const prepared = await prepareLaunch(call, row.instance, row.cwd, services);
|
|
1401
|
+
if ("result" in prepared) return prepared.result;
|
|
1402
|
+
admitted = prepared;
|
|
1403
|
+
}
|
|
1404
|
+
return { content: JSON.stringify(manager.send(call.sessionId, row.id, input.task, `${call.turn}:${call.toolCallId}`, admitted)) };
|
|
1405
|
+
}
|
|
1406
|
+
});
|
|
1407
|
+
register({
|
|
1408
|
+
name: "acp_list",
|
|
1409
|
+
description: "List external delegations owned by this session or its descendants.",
|
|
1410
|
+
inputSchema: Page,
|
|
1411
|
+
async execute(input, call) {
|
|
1412
|
+
return { content: JSON.stringify(manager.list(call.sessionId, input.offset, input.limit)) };
|
|
1413
|
+
}
|
|
1414
|
+
});
|
|
1415
|
+
register({
|
|
1416
|
+
name: "acp_get",
|
|
1417
|
+
description: "Read one external delegation and its recorded tasks. With `taskId`, read that task instead; with `waitMs` as well, wait up to that long (at most 60 seconds) for it to finish. Cancelling the wait leaves the task running. `offset` and `limit` page the delegation read only.",
|
|
1418
|
+
inputSchema: Page.extend({
|
|
1419
|
+
delegationId: z.string(),
|
|
1420
|
+
taskId: z.string().optional(),
|
|
1421
|
+
waitMs: z.number().int().min(0).max(6e4).optional()
|
|
1422
|
+
}).superRefine((input, issues) => {
|
|
1423
|
+
if (input.waitMs !== void 0 && input.taskId === void 0) issues.addIssue({
|
|
1424
|
+
code: "custom",
|
|
1425
|
+
path: ["taskId"],
|
|
1426
|
+
message: "waitMs needs the taskId to wait for"
|
|
1427
|
+
});
|
|
1428
|
+
}),
|
|
1429
|
+
async execute(input, call) {
|
|
1430
|
+
if (input.taskId === void 0) return { content: JSON.stringify(manager.get(call.sessionId, input.delegationId, input.offset, input.limit)) };
|
|
1431
|
+
const deadline = Date.now() + (input.waitMs ?? 0);
|
|
1432
|
+
while (true) {
|
|
1433
|
+
const task = manager.task(call.sessionId, input.delegationId, input.taskId);
|
|
1434
|
+
if (task.state === "finished" || Date.now() >= deadline || call.signal.aborted) return { content: JSON.stringify(task) };
|
|
1435
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(100, deadline - Date.now())));
|
|
1436
|
+
}
|
|
1437
|
+
}
|
|
1438
|
+
});
|
|
1439
|
+
register({
|
|
1440
|
+
name: "acp_stop",
|
|
1441
|
+
description: "Stop the current external task, or close its connection and cancel queued work. Changes already made are retained.",
|
|
1442
|
+
inputSchema: z.object({
|
|
1443
|
+
delegationId: z.string(),
|
|
1444
|
+
close: z.boolean().default(false)
|
|
1445
|
+
}).strict(),
|
|
1446
|
+
async execute(input, call) {
|
|
1447
|
+
if (input.close) await manager.close(call.sessionId, input.delegationId);
|
|
1448
|
+
else await manager.stop(call.sessionId, input.delegationId);
|
|
1449
|
+
return { content: "Stopped requested external work." };
|
|
1450
|
+
}
|
|
1451
|
+
});
|
|
1452
|
+
const tickets = /* @__PURE__ */ new Map();
|
|
1453
|
+
const startManaged = async (input, answer) => {
|
|
1454
|
+
if (draining) throw new Error("stopping");
|
|
1455
|
+
const instance = input.delegationId ? find(input.sessionId, input.delegationId).delegation.instance : store.instances().find((row) => row.id === input.instanceId && row.enabled);
|
|
1456
|
+
if (!instance) throw new Error("instance-missing");
|
|
1457
|
+
const configured = store.instances().find((row) => row.id === instance.id && row.enabled);
|
|
1458
|
+
if (!configured) throw new Error("instance-missing");
|
|
1459
|
+
if (configured.revision !== instance.revision) throw new Error("configuration-changed: create a new delegation");
|
|
1460
|
+
const prepared = await prepareLaunch({
|
|
1461
|
+
sessionId: input.sessionId,
|
|
1462
|
+
address: sessions.resolve(input.sessionId).address,
|
|
1463
|
+
...answer ? { answer } : {}
|
|
1464
|
+
}, instance, input.cwd, services);
|
|
1465
|
+
if ("result" in prepared) {
|
|
1466
|
+
if (!("awaitHuman" in prepared.result)) throw new Error("launch-refused");
|
|
1467
|
+
for (const [id, ticket] of tickets) if (ticket.expires < Date.now()) tickets.delete(id);
|
|
1468
|
+
if (tickets.size >= 128) throw new Error("approval-capacity-exceeded");
|
|
1469
|
+
const id = randomUUID();
|
|
1470
|
+
tickets.set(id, {
|
|
1471
|
+
input,
|
|
1472
|
+
instance,
|
|
1473
|
+
expires: Date.now() + 3e5,
|
|
1474
|
+
request: prepared.result.awaitHuman,
|
|
1475
|
+
questions: prepared.result.awaitHuman.questions
|
|
1476
|
+
});
|
|
1477
|
+
return { approval: {
|
|
1478
|
+
id,
|
|
1479
|
+
request: prepared.result.awaitHuman
|
|
1480
|
+
} };
|
|
1481
|
+
}
|
|
1482
|
+
if (input.probe) {
|
|
1483
|
+
const root = sessions.resolve(input.sessionId).rootSessionId;
|
|
1484
|
+
if (probes.has(root)) throw new Error("preflight-in-progress");
|
|
1485
|
+
const work = (async () => {
|
|
1486
|
+
const process = await prepared.launch();
|
|
1487
|
+
try {
|
|
1488
|
+
const connection = await connectAcp(process, {
|
|
1489
|
+
update() {},
|
|
1490
|
+
permission: async () => ({ outcome: { outcome: "cancelled" } })
|
|
1491
|
+
});
|
|
1492
|
+
return { preflight: {
|
|
1493
|
+
execution: prepared.execution,
|
|
1494
|
+
protocolVersion: connection.initialized.protocolVersion,
|
|
1495
|
+
capabilities: connection.initialized.agentCapabilities ?? {},
|
|
1496
|
+
authentication: "unverified",
|
|
1497
|
+
authMethods: connection.initialized.authMethods ?? []
|
|
1498
|
+
} };
|
|
1499
|
+
} finally {
|
|
1500
|
+
await process.stop();
|
|
1501
|
+
}
|
|
1502
|
+
})();
|
|
1503
|
+
probes.set(root, work);
|
|
1504
|
+
try {
|
|
1505
|
+
return await work;
|
|
1506
|
+
} finally {
|
|
1507
|
+
probes.delete(root);
|
|
1508
|
+
}
|
|
1509
|
+
}
|
|
1510
|
+
return { task: input.delegationId ? manager.send(input.sessionId, input.delegationId, input.task, input.requestKey, prepared) : await manager.start(input, prepared.launch, prepared.execution) };
|
|
1511
|
+
};
|
|
1512
|
+
ctx.client.registerMethod({
|
|
1513
|
+
name: "preflight",
|
|
1514
|
+
params: Session.extend({
|
|
1515
|
+
instanceId: z.string(),
|
|
1516
|
+
cwd: z.string()
|
|
1517
|
+
}),
|
|
1518
|
+
result: Result,
|
|
1519
|
+
handle: (input) => startManaged({
|
|
1520
|
+
...input,
|
|
1521
|
+
task: "",
|
|
1522
|
+
requestKey: randomUUID(),
|
|
1523
|
+
probe: true
|
|
1524
|
+
})
|
|
1525
|
+
});
|
|
1526
|
+
ctx.client.registerMethod({
|
|
1527
|
+
name: "start",
|
|
1528
|
+
params: Start.extend({
|
|
1529
|
+
sessionId: z.string(),
|
|
1530
|
+
requestKey: z.string()
|
|
1531
|
+
}),
|
|
1532
|
+
result: Result,
|
|
1533
|
+
handle: (input) => startManaged(input)
|
|
1534
|
+
});
|
|
1535
|
+
ctx.client.registerMethod({
|
|
1536
|
+
name: "resume",
|
|
1537
|
+
params: Target.extend({
|
|
1538
|
+
task: z.string().min(1),
|
|
1539
|
+
requestKey: z.string()
|
|
1540
|
+
}),
|
|
1541
|
+
result: Result,
|
|
1542
|
+
handle(input) {
|
|
1543
|
+
const row = find(input.sessionId, input.delegationId).delegation;
|
|
1544
|
+
return startManaged({
|
|
1545
|
+
...input,
|
|
1546
|
+
instanceId: row.instance.id,
|
|
1547
|
+
cwd: row.cwd,
|
|
1548
|
+
...row.model ? { model: row.model } : {},
|
|
1549
|
+
config: row.config
|
|
1550
|
+
});
|
|
1551
|
+
}
|
|
1552
|
+
});
|
|
1553
|
+
ctx.client.registerMethod({
|
|
1554
|
+
name: "launchApprovals",
|
|
1555
|
+
params: Session,
|
|
1556
|
+
result: Result,
|
|
1557
|
+
handle: (input) => [...tickets.entries()].filter(([, ticket]) => ticket.input.sessionId === input.sessionId && ticket.expires > Date.now()).map(([id, ticket]) => ({
|
|
1558
|
+
id,
|
|
1559
|
+
request: ticket.request
|
|
1560
|
+
}))
|
|
1561
|
+
});
|
|
1562
|
+
ctx.client.registerMethod({
|
|
1563
|
+
name: "usage",
|
|
1564
|
+
params: Session,
|
|
1565
|
+
result: Result,
|
|
1566
|
+
handle: (input) => manager.usage(input.sessionId)
|
|
1567
|
+
});
|
|
1568
|
+
ctx.client.registerMethod({
|
|
1569
|
+
name: "confirmLaunch",
|
|
1570
|
+
params: z.object({
|
|
1571
|
+
id: z.string(),
|
|
1572
|
+
allow: z.boolean()
|
|
1573
|
+
}).strict(),
|
|
1574
|
+
result: Result,
|
|
1575
|
+
async handle(input) {
|
|
1576
|
+
const ticket = tickets.get(input.id);
|
|
1577
|
+
tickets.delete(input.id);
|
|
1578
|
+
if (!ticket || ticket.expires < Date.now()) throw new Error("request-expired");
|
|
1579
|
+
if (!input.allow) return { rejected: true };
|
|
1580
|
+
const configured = store.instances().find((row) => row.id === ticket.instance.id);
|
|
1581
|
+
if (!configured || !configured.enabled || configured.revision !== ticket.instance.revision) throw new Error("configuration-changed: request launch again");
|
|
1582
|
+
return startManaged(ticket.input, {
|
|
1583
|
+
requestId: input.id,
|
|
1584
|
+
answers: ticket.questions.map((question) => ({
|
|
1585
|
+
questionId: question.id,
|
|
1586
|
+
optionIds: ["allowed-once"]
|
|
1587
|
+
}))
|
|
1588
|
+
});
|
|
1589
|
+
}
|
|
1590
|
+
});
|
|
1591
|
+
ctx.client.registerMethod({
|
|
1592
|
+
name: "list",
|
|
1593
|
+
params: Session.extend(Page.shape),
|
|
1594
|
+
result: Result,
|
|
1595
|
+
handle: (input) => manager.list(input.sessionId, input.offset, input.limit)
|
|
1596
|
+
});
|
|
1597
|
+
ctx.client.registerMethod({
|
|
1598
|
+
name: "get",
|
|
1599
|
+
params: Target.extend(Page.shape),
|
|
1600
|
+
result: Result,
|
|
1601
|
+
handle: (input) => manager.get(input.sessionId, input.delegationId, input.offset, input.limit)
|
|
1602
|
+
});
|
|
1603
|
+
ctx.client.registerMethod({
|
|
1604
|
+
name: "send",
|
|
1605
|
+
params: Target.extend({
|
|
1606
|
+
task: z.string().min(1),
|
|
1607
|
+
requestKey: z.string()
|
|
1608
|
+
}),
|
|
1609
|
+
result: Result,
|
|
1610
|
+
handle: (input) => manager.send(input.sessionId, input.delegationId, input.task, input.requestKey)
|
|
1611
|
+
});
|
|
1612
|
+
ctx.client.registerMethod({
|
|
1613
|
+
name: "stop",
|
|
1614
|
+
params: Target,
|
|
1615
|
+
result: Result,
|
|
1616
|
+
async handle(input) {
|
|
1617
|
+
await manager.stop(input.sessionId, input.delegationId);
|
|
1618
|
+
return {};
|
|
1619
|
+
}
|
|
1620
|
+
});
|
|
1621
|
+
ctx.client.registerMethod({
|
|
1622
|
+
name: "close",
|
|
1623
|
+
params: Target,
|
|
1624
|
+
result: Result,
|
|
1625
|
+
async handle(input) {
|
|
1626
|
+
await manager.close(input.sessionId, input.delegationId);
|
|
1627
|
+
return {};
|
|
1628
|
+
}
|
|
1629
|
+
});
|
|
1630
|
+
ctx.client.registerMethod({
|
|
1631
|
+
name: "updates",
|
|
1632
|
+
params: Target.extend({
|
|
1633
|
+
taskId: z.string(),
|
|
1634
|
+
after: z.number().int().nonnegative().default(0)
|
|
1635
|
+
}),
|
|
1636
|
+
result: Result,
|
|
1637
|
+
handle(input) {
|
|
1638
|
+
manager.task(input.sessionId, input.delegationId, input.taskId);
|
|
1639
|
+
return store.updates(input.taskId, input.after);
|
|
1640
|
+
}
|
|
1641
|
+
});
|
|
1642
|
+
ctx.client.registerMethod({
|
|
1643
|
+
name: "settings",
|
|
1644
|
+
params: z.object({}).strict(),
|
|
1645
|
+
result: Result,
|
|
1646
|
+
handle: () => ({
|
|
1647
|
+
limits: store.settings(),
|
|
1648
|
+
instances: store.instances()
|
|
1649
|
+
})
|
|
1650
|
+
});
|
|
1651
|
+
ctx.client.registerMethod({
|
|
1652
|
+
name: "setLimits",
|
|
1653
|
+
params: SettingsSchema,
|
|
1654
|
+
result: SettingsSchema,
|
|
1655
|
+
handle: (input) => store.setSettings(input)
|
|
1656
|
+
});
|
|
1657
|
+
ctx.client.registerMethod({
|
|
1658
|
+
name: "inspectCommand",
|
|
1659
|
+
params: z.object({ command: z.string().min(1).max(4096) }).strict(),
|
|
1660
|
+
result: z.object({
|
|
1661
|
+
status: z.enum([
|
|
1662
|
+
"found",
|
|
1663
|
+
"missing",
|
|
1664
|
+
"directory",
|
|
1665
|
+
"unreadable",
|
|
1666
|
+
"unsupported",
|
|
1667
|
+
"relative-path"
|
|
1668
|
+
]),
|
|
1669
|
+
path: z.string().nullable(),
|
|
1670
|
+
reason: z.string().optional()
|
|
1671
|
+
}).strict(),
|
|
1672
|
+
handle: ({ command }) => inspectCommand(command, commands)
|
|
1673
|
+
});
|
|
1674
|
+
ctx.client.registerMethod({
|
|
1675
|
+
name: "inspectPreset",
|
|
1676
|
+
params: z.object({ id: z.enum([
|
|
1677
|
+
"claude",
|
|
1678
|
+
"codex",
|
|
1679
|
+
"openclaw"
|
|
1680
|
+
]) }).strict(),
|
|
1681
|
+
result: z.object({
|
|
1682
|
+
status: z.enum([
|
|
1683
|
+
"found",
|
|
1684
|
+
"missing-cli",
|
|
1685
|
+
"missing-adapter",
|
|
1686
|
+
"unsupported-cli",
|
|
1687
|
+
"unavailable-cli"
|
|
1688
|
+
]),
|
|
1689
|
+
path: z.string().nullable(),
|
|
1690
|
+
reason: z.string().optional()
|
|
1691
|
+
}).strict(),
|
|
1692
|
+
handle: ({ id }) => inspectPreset(id, commands)
|
|
1693
|
+
});
|
|
1694
|
+
ctx.client.registerMethod({
|
|
1695
|
+
name: "addPreset",
|
|
1696
|
+
params: z.object({ id: z.enum([
|
|
1697
|
+
"claude",
|
|
1698
|
+
"codex",
|
|
1699
|
+
"openclaw"
|
|
1700
|
+
]) }).strict(),
|
|
1701
|
+
result: InstanceSchema,
|
|
1702
|
+
async handle({ id }) {
|
|
1703
|
+
const result = await inspectPreset(id, commands);
|
|
1704
|
+
if (result.status !== "found" || !result.path) throw new Error(result.status);
|
|
1705
|
+
const preset = ACP_PRESETS.find((item) => item.id === id);
|
|
1706
|
+
const adapter = id === "openclaw" ? void 0 : id;
|
|
1707
|
+
if (store.instances().some((row) => adapter ? row.adapter === adapter : !row.adapter && row.command === result.path && JSON.stringify(row.args) === JSON.stringify(preset.args))) throw new Error("preset-already-added");
|
|
1708
|
+
const instance = InstanceSchema.parse({
|
|
1709
|
+
id: `${id}-${randomUUID()}`,
|
|
1710
|
+
label: preset.label,
|
|
1711
|
+
command: result.path,
|
|
1712
|
+
args: [...preset.args],
|
|
1713
|
+
adapter,
|
|
1714
|
+
executionMode: "trusted"
|
|
1715
|
+
});
|
|
1716
|
+
validateInstance(instance, commands.platform);
|
|
1717
|
+
return store.saveInstance(instance);
|
|
1718
|
+
}
|
|
1719
|
+
});
|
|
1720
|
+
ctx.client.registerMethod({
|
|
1721
|
+
name: "saveInstance",
|
|
1722
|
+
params: InstanceSchema,
|
|
1723
|
+
result: InstanceSchema,
|
|
1724
|
+
handle(input) {
|
|
1725
|
+
validateInstance(input, commands.platform);
|
|
1726
|
+
const prior = store.instances().find((row) => row.id === input.id);
|
|
1727
|
+
return store.saveInstance({
|
|
1728
|
+
...input,
|
|
1729
|
+
revision: (prior?.revision ?? -1) + 1
|
|
1730
|
+
});
|
|
1731
|
+
}
|
|
1732
|
+
});
|
|
1733
|
+
ctx.client.registerMethod({
|
|
1734
|
+
name: "removeInstance",
|
|
1735
|
+
params: z.object({ id: z.string() }).strict(),
|
|
1736
|
+
result: Result,
|
|
1737
|
+
handle(input) {
|
|
1738
|
+
store.removeInstance(input.id);
|
|
1739
|
+
return {};
|
|
1740
|
+
}
|
|
1741
|
+
});
|
|
1742
|
+
const ui = fileURLToPath(new URL("../ui/ui.js", import.meta.url));
|
|
1743
|
+
if (existsSync(ui)) ctx.client.registerUi({ module: ui });
|
|
1744
|
+
}
|
|
1745
|
+
};
|
|
1746
|
+
//#endregion
|
|
1747
|
+
export { TOOL_NAMES, acpPlugin, acpPlugin as default };
|