@eum-agent/integration-acp 1.0.0 → 1.1.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/index.js +1763 -553
- package/package.json +4 -4
- package/ui/ui.js +31 -27
package/dist/index.js
CHANGED
|
@@ -3,9 +3,10 @@ import { createHash, randomUUID } from "node:crypto";
|
|
|
3
3
|
import { accessSync, constants, existsSync, readFileSync, realpathSync, statSync } from "node:fs";
|
|
4
4
|
import { fileURLToPath } from "node:url";
|
|
5
5
|
import { z } from "zod";
|
|
6
|
-
import protocolSchema from "@agentclientprotocol/sdk/schema/schema.json" with { type: "json" };
|
|
7
6
|
import { Readable, Transform, Writable } from "node:stream";
|
|
7
|
+
import { setImmediate } from "node:timers/promises";
|
|
8
8
|
import { ClientSideConnection, PROTOCOL_VERSION, ndJsonStream } from "@agentclientprotocol/sdk";
|
|
9
|
+
import protocolSchema from "@agentclientprotocol/sdk/schema/schema.json" with { type: "json" };
|
|
9
10
|
import { mkdtemp, rm } from "node:fs/promises";
|
|
10
11
|
import { tmpdir } from "node:os";
|
|
11
12
|
import { dirname, join, posix, resolve, win32 } from "node:path";
|
|
@@ -31,54 +32,95 @@ async function control(promise, ms = 3e4) {
|
|
|
31
32
|
}
|
|
32
33
|
/** Initializes ACP over raw pipes, rejecting messages above 8 MiB before JSON decoding. */
|
|
33
34
|
async function connectAcp(process, callbacks) {
|
|
34
|
-
|
|
35
|
+
const messageLimit = 8388608;
|
|
36
|
+
const fragments = [];
|
|
37
|
+
let bufferedBytes = 0;
|
|
38
|
+
let tail;
|
|
39
|
+
let tailBytes = 0;
|
|
40
|
+
const append = (chunk) => {
|
|
41
|
+
let offset = 0;
|
|
42
|
+
while (offset < chunk.length) {
|
|
43
|
+
if (!tail || tailBytes === tail.length) {
|
|
44
|
+
tail = Buffer.allocUnsafe(Math.min(65536, messageLimit - bufferedBytes));
|
|
45
|
+
tailBytes = 0;
|
|
46
|
+
fragments.push(tail);
|
|
47
|
+
}
|
|
48
|
+
const length = Math.min(chunk.length - offset, tail.length - tailBytes);
|
|
49
|
+
chunk.copy(tail, tailBytes, offset, offset + length);
|
|
50
|
+
tailBytes += length;
|
|
51
|
+
bufferedBytes += length;
|
|
52
|
+
offset += length;
|
|
53
|
+
}
|
|
54
|
+
};
|
|
35
55
|
const pending = /* @__PURE__ */ new Set();
|
|
36
56
|
const bounded = new Transform({
|
|
37
57
|
transform(chunk, _encoding, done) {
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
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();
|
|
58
|
+
(async () => {
|
|
59
|
+
let offset = 0;
|
|
60
|
+
let frames = 0;
|
|
61
|
+
let processedBytes = 0;
|
|
62
|
+
while (offset < chunk.length) {
|
|
63
|
+
if (frames >= 16 || processedBytes >= 65536) {
|
|
64
|
+
await setImmediate();
|
|
65
|
+
if (this.destroyed) {
|
|
66
|
+
done(/* @__PURE__ */ new Error("connection-closed"));
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
frames = 0;
|
|
70
|
+
processedBytes = 0;
|
|
63
71
|
}
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
72
|
+
const newline = chunk.indexOf(10, offset);
|
|
73
|
+
const end = newline === -1 ? chunk.length : newline;
|
|
74
|
+
if (bufferedBytes + end - offset > messageLimit) {
|
|
75
|
+
done(/* @__PURE__ */ new Error("protocol-message-limit"));
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
append(chunk.subarray(offset, end));
|
|
79
|
+
if (newline === -1) break;
|
|
80
|
+
if (tail) fragments[fragments.length - 1] = tail.subarray(0, tailBytes);
|
|
81
|
+
const framed = Buffer.concat([...fragments, Buffer.from("\n")], bufferedBytes + 1);
|
|
82
|
+
const line = framed.subarray(0, bufferedBytes);
|
|
83
|
+
frames += 1;
|
|
84
|
+
processedBytes += bufferedBytes;
|
|
85
|
+
fragments.length = 0;
|
|
86
|
+
bufferedBytes = 0;
|
|
87
|
+
tail = void 0;
|
|
88
|
+
tailBytes = 0;
|
|
89
|
+
offset = newline + 1;
|
|
90
|
+
if (!line.length) continue;
|
|
91
|
+
let value;
|
|
92
|
+
try {
|
|
93
|
+
const parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(line));
|
|
94
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error();
|
|
95
|
+
value = parsed;
|
|
96
|
+
if (value.jsonrpc !== "2.0") throw new Error();
|
|
97
|
+
if ("method" in value) {
|
|
98
|
+
if (typeof value.method !== "string") throw new Error();
|
|
99
|
+
if (value.method === "session/update" && !Update.safeParse(value.params).success) throw new Error();
|
|
100
|
+
if (value.method === "session/request_permission" && !Permission.safeParse(value.params).success) throw new Error();
|
|
101
|
+
if (!("id" in value) && value.method !== "session/update") continue;
|
|
102
|
+
} else {
|
|
103
|
+
if (typeof value.id !== "string" && typeof value.id !== "number") throw new Error();
|
|
104
|
+
if (!pending.delete(value.id)) continue;
|
|
105
|
+
if (!("result" in value) && !("error" in value)) throw new Error();
|
|
106
|
+
}
|
|
107
|
+
} catch {
|
|
108
|
+
done(/* @__PURE__ */ new Error("invalid-protocol-message"));
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
this.push(framed);
|
|
67
112
|
}
|
|
68
|
-
|
|
69
|
-
}
|
|
70
|
-
if (buffered.length > 8388608) {
|
|
71
|
-
done(/* @__PURE__ */ new Error("protocol-message-limit"));
|
|
72
|
-
return;
|
|
73
|
-
}
|
|
74
|
-
done();
|
|
113
|
+
done();
|
|
114
|
+
})().catch(done);
|
|
75
115
|
},
|
|
76
116
|
flush(done) {
|
|
77
|
-
done(
|
|
117
|
+
done(bufferedBytes ? /* @__PURE__ */ new Error("truncated-protocol-message") : void 0);
|
|
78
118
|
}
|
|
79
119
|
});
|
|
80
120
|
process.stdout.pipe(bounded);
|
|
81
|
-
process.stdout.on("close", () =>
|
|
121
|
+
process.stdout.on("close", () => {
|
|
122
|
+
if (!process.stdout.readableEnded) bounded.destroy();
|
|
123
|
+
});
|
|
82
124
|
process.stdout.on("error", () => bounded.destroy(/* @__PURE__ */ new Error("connection-lost")));
|
|
83
125
|
bounded.on("error", () => {
|
|
84
126
|
process.stop().catch(() => {});
|
|
@@ -139,43 +181,6 @@ async function connectAcp(process, callbacks) {
|
|
|
139
181
|
}
|
|
140
182
|
}
|
|
141
183
|
//#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
184
|
//#region src/adapters.ts
|
|
180
185
|
const require = createRequire(import.meta.url);
|
|
181
186
|
const adapters = {
|
|
@@ -269,157 +274,258 @@ async function prepareLaunch(authority, instance, cwd, services) {
|
|
|
269
274
|
if (cli.status !== "found") throw new Error(`command-unavailable: ${cli.reason}`);
|
|
270
275
|
}
|
|
271
276
|
cwd = await commands.directory(cwd);
|
|
272
|
-
const
|
|
273
|
-
|
|
274
|
-
let
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
cwd,
|
|
285
|
-
tmp,
|
|
286
|
-
permissions,
|
|
287
|
-
argv: exact
|
|
277
|
+
const observation = await commands.observeDirectory(cwd);
|
|
278
|
+
let released = false;
|
|
279
|
+
let releasing;
|
|
280
|
+
let retained = false;
|
|
281
|
+
let processOwnsObservation = false;
|
|
282
|
+
const closeObservation = () => {
|
|
283
|
+
if (released) return Promise.resolve();
|
|
284
|
+
releasing ??= observation.close().then(() => {
|
|
285
|
+
released = true;
|
|
286
|
+
}).catch((error) => {
|
|
287
|
+
releasing = void 0;
|
|
288
|
+
throw error;
|
|
288
289
|
});
|
|
289
|
-
|
|
290
|
-
return result.plan;
|
|
290
|
+
return releasing;
|
|
291
291
|
};
|
|
292
|
-
const
|
|
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;
|
|
292
|
+
const release = () => processOwnsObservation ? Promise.resolve() : closeObservation();
|
|
314
293
|
try {
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
294
|
+
if (observation.observation.kind !== "existing" || observation.observation.targetType !== "directory" || !observation.verify()) throw new Error("cwd-changed: request launch again");
|
|
295
|
+
const trusted = instance.executionMode === "trusted";
|
|
296
|
+
const route = () => services.network.environment();
|
|
297
|
+
let proxy = await route();
|
|
298
|
+
const permissions = {
|
|
299
|
+
read: [...executable.read, ...instance.authPaths.map((item) => item.path)],
|
|
300
|
+
write: [cwd, ...instance.authPaths.filter((item) => item.access === "write").map((item) => item.path)],
|
|
301
|
+
network: instance.networkHosts
|
|
321
302
|
};
|
|
322
|
-
|
|
323
|
-
const
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
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
|
|
303
|
+
const availability = trusted ? void 0 : JSON.stringify(services.sandbox.status());
|
|
304
|
+
const plan = async (tmp) => {
|
|
305
|
+
if (trusted) return void 0;
|
|
306
|
+
const result = await services.sandbox.planSandboxed(authority, {
|
|
307
|
+
cwd,
|
|
308
|
+
tmp,
|
|
309
|
+
permissions,
|
|
310
|
+
argv: exact
|
|
311
|
+
});
|
|
312
|
+
if (!result.ok) throw new Error(`sandbox-refused: ${result.reason}`);
|
|
313
|
+
return result.plan;
|
|
352
314
|
};
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
315
|
+
const environment = (mode, work) => {
|
|
316
|
+
const inherited = commands.childEnvironment(commands.env, mode === "sandboxed" ? "acp-minimal" : "protocol");
|
|
317
|
+
if (mode === "sandboxed" && commands.platform !== "win32") {
|
|
318
|
+
inherited.PATH ??= "/usr/bin:/bin";
|
|
319
|
+
inherited.HOME ??= "/";
|
|
320
|
+
inherited.LANG ??= "en_US.UTF-8";
|
|
321
|
+
}
|
|
322
|
+
if (commands.platform === "win32" && !inherited.SYSTEMROOT) throw new Error("required-host-environment-unavailable: SYSTEMROOT");
|
|
323
|
+
return commands.environment([
|
|
324
|
+
inherited,
|
|
325
|
+
executable.env,
|
|
326
|
+
proxy.env,
|
|
327
|
+
commands.temporaryEnvironment(work)
|
|
328
|
+
]);
|
|
356
329
|
};
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
330
|
+
const tmp = await mkdtemp(join(realpathSync(tmpdir()), "yaoguang-acp-"));
|
|
331
|
+
let initialMode = "direct";
|
|
332
|
+
let initialNames;
|
|
333
|
+
let fallbackReason;
|
|
334
|
+
let approvalFailure;
|
|
335
|
+
let approvalFailed = false;
|
|
336
|
+
let refused;
|
|
337
|
+
try {
|
|
338
|
+
const initial = await plan(tmp);
|
|
339
|
+
initialMode = initial?.mode ?? "direct";
|
|
340
|
+
fallbackReason = initial?.mode === "direct" ? initial.fallbackReason : void 0;
|
|
341
|
+
if (initial) proxy = {
|
|
342
|
+
...proxy,
|
|
343
|
+
env: { ...initial.proxyEnvironment }
|
|
344
|
+
};
|
|
345
|
+
initialNames = Object.keys(environment(initialMode, tmp)).sort();
|
|
346
|
+
const key = `acp:${createHash("sha256").update(JSON.stringify({
|
|
347
|
+
id: instance.id,
|
|
348
|
+
revision: instance.revision,
|
|
349
|
+
proxy: proxy.revision,
|
|
350
|
+
cwd,
|
|
351
|
+
cwdIdentity: observation.observation.identity,
|
|
352
|
+
argv: exact,
|
|
353
|
+
mode: initialMode,
|
|
354
|
+
envNames: initialNames,
|
|
355
|
+
env: commands.environment([executable.env])
|
|
356
|
+
})).digest("hex")}`;
|
|
357
|
+
const decision = services.approval.decide(authority, {
|
|
358
|
+
id: key,
|
|
359
|
+
subject: `Delegate to ${instance.label} in ${cwd}`,
|
|
360
|
+
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(", ")}.`,
|
|
361
|
+
accepts: [
|
|
362
|
+
"allowed-once",
|
|
363
|
+
"allowed-session",
|
|
364
|
+
"allowed-always",
|
|
365
|
+
"rejected"
|
|
366
|
+
],
|
|
367
|
+
remember: {
|
|
368
|
+
key,
|
|
369
|
+
label: `启动 ${instance.label}(${cwd})`
|
|
370
|
+
}
|
|
371
|
+
});
|
|
372
|
+
if (decision.kind === "ask") refused = decision.result;
|
|
373
|
+
else if (decision.result.kind === "record-failed") refused = {
|
|
374
|
+
content: `ACP launch was allowed, but recording it failed: ${decision.result.message}`,
|
|
375
|
+
isError: true
|
|
376
|
+
};
|
|
377
|
+
else if (!decision.result.kind.startsWith("allowed-")) refused = {
|
|
378
|
+
content: "ACP launch was not authorized.",
|
|
379
|
+
isError: true
|
|
380
|
+
};
|
|
381
|
+
} catch (primary) {
|
|
382
|
+
approvalFailed = true;
|
|
383
|
+
approvalFailure = primary;
|
|
384
|
+
}
|
|
385
|
+
try {
|
|
386
|
+
await rm(tmp, {
|
|
387
|
+
recursive: true,
|
|
388
|
+
force: true
|
|
389
|
+
});
|
|
390
|
+
} catch (cleanup) {
|
|
391
|
+
if (approvalFailed) throw new AggregateError([approvalFailure, cleanup], `ACP cleanup failed: ${tmp}`, { cause: approvalFailure });
|
|
392
|
+
throw cleanup;
|
|
393
|
+
}
|
|
394
|
+
if (approvalFailed) throw approvalFailure;
|
|
395
|
+
if (refused) return { result: refused };
|
|
396
|
+
retained = true;
|
|
397
|
+
return {
|
|
398
|
+
release,
|
|
399
|
+
execution: {
|
|
400
|
+
mode: initialMode,
|
|
401
|
+
...fallbackReason ? { fallbackReason } : {}
|
|
402
|
+
},
|
|
403
|
+
async launch() {
|
|
404
|
+
const work = await mkdtemp(join(realpathSync(tmpdir()), "yaoguang-acp-"));
|
|
405
|
+
let transferred = false;
|
|
406
|
+
let prepared;
|
|
407
|
+
try {
|
|
408
|
+
if ((await route()).revision !== proxy.revision) throw new Error("proxy-changed: request launch again");
|
|
393
409
|
if (!trusted && JSON.stringify(services.sandbox.status()) !== availability) throw new Error("execution-mode-changed: request launch again");
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
env
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
}
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
410
|
+
if (!observation.verify() || await commands.directory(cwd) !== cwd) throw new Error("cwd-changed: request launch again");
|
|
411
|
+
const found = await commands.inspect(executable.command);
|
|
412
|
+
if (found.status !== "found" || found.path !== executable.command) throw new Error("command-changed: request launch again");
|
|
413
|
+
const current = await plan(work);
|
|
414
|
+
if ((current?.mode ?? "direct") !== initialMode) throw new Error("execution-mode-changed: request launch again");
|
|
415
|
+
if (current && JSON.stringify(current.proxyEnvironment ?? {}) !== JSON.stringify(proxy.env)) throw new Error("proxy-changed: request launch again");
|
|
416
|
+
prepared = current ? services.sandbox.prepare(current, exact) : void 0;
|
|
417
|
+
const env = environment(initialMode, work);
|
|
418
|
+
if (JSON.stringify(Object.keys(env).sort()) !== JSON.stringify(initialNames)) throw new Error("environment-changed: request launch again");
|
|
419
|
+
const assertCurrent = () => {
|
|
420
|
+
if (!observation.verify()) throw new Error("cwd-changed: request launch again");
|
|
421
|
+
if (!trusted && JSON.stringify(services.sandbox.status()) !== availability) throw new Error("execution-mode-changed: request launch again");
|
|
422
|
+
prepared?.assertCurrent();
|
|
423
|
+
};
|
|
424
|
+
assertCurrent();
|
|
425
|
+
const attempt = services.processes.start({
|
|
426
|
+
owner: "@eum-agent/integration-acp",
|
|
427
|
+
sessionId: authority.sessionId,
|
|
428
|
+
argv: prepared?.argv ?? exact,
|
|
429
|
+
cwd: current?.cwd ?? cwd,
|
|
430
|
+
env,
|
|
431
|
+
beforeSpawn: (launchAttemptId) => {
|
|
432
|
+
assertCurrent();
|
|
433
|
+
prepared?.beforeSpawn(launchAttemptId);
|
|
434
|
+
},
|
|
435
|
+
release: async () => {
|
|
436
|
+
const failures = (await Promise.allSettled([
|
|
437
|
+
rm(work, {
|
|
438
|
+
recursive: true,
|
|
439
|
+
force: true
|
|
440
|
+
}),
|
|
441
|
+
closeObservation(),
|
|
442
|
+
...prepared ? [prepared.release()] : []
|
|
443
|
+
])).filter((item) => item.status === "rejected").map((item) => item.reason);
|
|
444
|
+
if (failures.length) throw new AggregateError(failures, "ACP launch cleanup failed");
|
|
445
|
+
}
|
|
416
446
|
});
|
|
417
|
-
|
|
418
|
-
|
|
447
|
+
transferred = true;
|
|
448
|
+
processOwnsObservation = true;
|
|
449
|
+
return await attempt.ready;
|
|
450
|
+
} catch (error) {
|
|
451
|
+
if (!transferred) try {
|
|
452
|
+
await rm(work, {
|
|
453
|
+
recursive: true,
|
|
454
|
+
force: true
|
|
455
|
+
});
|
|
456
|
+
await closeObservation();
|
|
457
|
+
await prepared?.release();
|
|
458
|
+
} catch (cleanup) {
|
|
459
|
+
throw new AggregateError([error, cleanup], `ACP cleanup failed: ${work}`, { cause: error });
|
|
460
|
+
}
|
|
461
|
+
throw error;
|
|
419
462
|
}
|
|
420
|
-
throw error;
|
|
421
463
|
}
|
|
422
|
-
}
|
|
464
|
+
};
|
|
465
|
+
} finally {
|
|
466
|
+
if (!retained) await closeObservation();
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
//#endregion
|
|
470
|
+
//#region src/inspection.ts
|
|
471
|
+
/** Inspects one command using the explicitly supplied physical host, without running it. */
|
|
472
|
+
function inspectCommand(command, commands, searchPath) {
|
|
473
|
+
return commands.inspect(command, searchPath === void 0 ? commands.env : commands.environment([commands.env, { PATH: searchPath }]));
|
|
474
|
+
}
|
|
475
|
+
//#endregion
|
|
476
|
+
//#region src/presets.ts
|
|
477
|
+
/** Known ACP launch recipes; installation and authentication remain local prerequisites. */
|
|
478
|
+
const ACP_PRESETS = [
|
|
479
|
+
{
|
|
480
|
+
id: "codex",
|
|
481
|
+
label: "Codex",
|
|
482
|
+
command: "codex",
|
|
483
|
+
args: [],
|
|
484
|
+
docs: "https://github.com/agentclientprotocol/codex-acp"
|
|
485
|
+
},
|
|
486
|
+
{
|
|
487
|
+
id: "claude",
|
|
488
|
+
label: "Claude",
|
|
489
|
+
command: "claude",
|
|
490
|
+
args: [],
|
|
491
|
+
docs: "https://github.com/agentclientprotocol/claude-agent-acp"
|
|
492
|
+
},
|
|
493
|
+
{
|
|
494
|
+
id: "openclaw",
|
|
495
|
+
label: "OpenClaw",
|
|
496
|
+
command: "openclaw",
|
|
497
|
+
args: ["acp"],
|
|
498
|
+
docs: "https://docs.openclaw.ai/cli/acp"
|
|
499
|
+
}
|
|
500
|
+
];
|
|
501
|
+
//#endregion
|
|
502
|
+
//#region src/preset-inspection.ts
|
|
503
|
+
/** Inspects a preset's CLI and bundled adapter without starting either or checking login. */
|
|
504
|
+
async function inspectPreset(id, commands, searchPath) {
|
|
505
|
+
const preset = ACP_PRESETS.find((item) => item.id === id);
|
|
506
|
+
const paths = searchPath ?? (commands.platform === "win32" ? void 0 : [
|
|
507
|
+
commands.env.PATH ?? "",
|
|
508
|
+
posix.join(commands.homedir(), ".local", "bin"),
|
|
509
|
+
"/opt/homebrew/bin",
|
|
510
|
+
"/usr/local/bin"
|
|
511
|
+
].join(":"));
|
|
512
|
+
const cli = await inspectCommand(preset.command, commands, paths);
|
|
513
|
+
if (cli.status !== "found") return {
|
|
514
|
+
status: cli.status === "missing" ? "missing-cli" : cli.status === "unsupported" ? "unsupported-cli" : "unavailable-cli",
|
|
515
|
+
path: cli.path,
|
|
516
|
+
reason: cli.reason
|
|
517
|
+
};
|
|
518
|
+
if (id !== "openclaw") try {
|
|
519
|
+
bundledAdapter(id);
|
|
520
|
+
} catch {
|
|
521
|
+
return {
|
|
522
|
+
status: "missing-adapter",
|
|
523
|
+
path: cli.path
|
|
524
|
+
};
|
|
525
|
+
}
|
|
526
|
+
return {
|
|
527
|
+
status: "found",
|
|
528
|
+
path: cli.path
|
|
423
529
|
};
|
|
424
530
|
}
|
|
425
531
|
//#endregion
|
|
@@ -502,6 +608,27 @@ const TaskSchema = z.object({
|
|
|
502
608
|
createdAt: z.number(),
|
|
503
609
|
revision: z.number().int()
|
|
504
610
|
}).strict();
|
|
611
|
+
/** Metadata read by model status pages without accepted task or output bodies. */
|
|
612
|
+
const AcpTaskSummarySchema = z.strictObject({
|
|
613
|
+
taskId: z.string(),
|
|
614
|
+
delegationId: z.string(),
|
|
615
|
+
title: z.string(),
|
|
616
|
+
state: TaskSchema.shape.state,
|
|
617
|
+
outcome: TaskSchema.shape.outcome,
|
|
618
|
+
revision: z.number(),
|
|
619
|
+
createdAt: z.number(),
|
|
620
|
+
resultAvailable: z.boolean(),
|
|
621
|
+
error: z.string().nullable()
|
|
622
|
+
});
|
|
623
|
+
/** Delegation identity excludes command, environment, configuration and permissions. */
|
|
624
|
+
const AcpDelegationSummarySchema = z.strictObject({
|
|
625
|
+
delegationId: z.string(),
|
|
626
|
+
instanceId: z.string(),
|
|
627
|
+
label: z.string(),
|
|
628
|
+
connectionState: DelegationSchema.shape.connectionState,
|
|
629
|
+
createdAt: z.number(),
|
|
630
|
+
execution: LaunchExecutionSchema.nullable()
|
|
631
|
+
});
|
|
505
632
|
/** ACP storage, always under the host-issued owner table prefix. */
|
|
506
633
|
function createAcpStore(storage) {
|
|
507
634
|
const { db, tableName } = storage;
|
|
@@ -513,6 +640,15 @@ function createAcpStore(storage) {
|
|
|
513
640
|
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
641
|
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
642
|
INSERT OR IGNORE INTO ${settings} VALUES(1,4,8);`);
|
|
643
|
+
let membership = 0, configuration = 0;
|
|
644
|
+
const taskSummaryProjection = `json_object('taskId',id,'delegationId',delegation_id,
|
|
645
|
+
'title',substr(json_extract(payload,'$.input'),1,256),'state',json_extract(payload,'$.state'),
|
|
646
|
+
'outcome',json_extract(payload,'$.outcome'),'revision',json_extract(payload,'$.revision'),
|
|
647
|
+
'createdAt',json_extract(payload,'$.createdAt'),'resultAvailable',CASE WHEN json_extract(payload,'$.state')='finished' THEN json('true') ELSE json('false') END,
|
|
648
|
+
'error',substr(json_extract(payload,'$.error'),1,256)) AS summary`;
|
|
649
|
+
const delegationSummaryProjection = `json_object('delegationId',id,'instanceId',json_extract(payload,'$.instance.id'),
|
|
650
|
+
'label',substr(json_extract(payload,'$.instance.label'),1,256),'connectionState',json_extract(payload,'$.connectionState'),
|
|
651
|
+
'createdAt',json_extract(payload,'$.createdAt'),'execution',json_extract(payload,'$.execution')) AS summary`;
|
|
516
652
|
return {
|
|
517
653
|
transaction(write) {
|
|
518
654
|
db.exec("BEGIN IMMEDIATE");
|
|
@@ -541,18 +677,24 @@ function createAcpStore(storage) {
|
|
|
541
677
|
return db.prepare(`SELECT payload FROM ${instances} ORDER BY id`).all().map((row) => InstanceSchema.parse(JSON.parse(String(row.payload))));
|
|
542
678
|
},
|
|
543
679
|
saveInstance(input) {
|
|
680
|
+
configuration++;
|
|
544
681
|
const value = InstanceSchema.parse(input);
|
|
545
682
|
db.prepare(`INSERT INTO ${instances} VALUES(?,?) ON CONFLICT(id) DO UPDATE SET payload=excluded.payload`).run(value.id, JSON.stringify(value));
|
|
546
683
|
return value;
|
|
547
684
|
},
|
|
548
685
|
removeInstance(id) {
|
|
686
|
+
configuration++;
|
|
549
687
|
db.prepare(`DELETE FROM ${instances} WHERE id=?`).run(id);
|
|
550
688
|
},
|
|
551
689
|
delegation(id) {
|
|
552
690
|
const row = db.prepare(`SELECT payload FROM ${delegations} WHERE id=?`).get(id);
|
|
553
691
|
return row ? DelegationSchema.parse(JSON.parse(String(row.payload))) : void 0;
|
|
554
692
|
},
|
|
555
|
-
task(id) {
|
|
693
|
+
task(id, maxBytes) {
|
|
694
|
+
if (maxBytes !== void 0) {
|
|
695
|
+
const size = db.prepare(`SELECT length(CAST(payload AS BLOB)) AS bytes FROM ${tasks} WHERE id=?`).get(id);
|
|
696
|
+
if (size && Number(size.bytes) > maxBytes) throw Object.assign(/* @__PURE__ */ new Error("stored task exceeds declared budget"), { code: "read-limit" });
|
|
697
|
+
}
|
|
556
698
|
const row = db.prepare(`SELECT payload FROM ${tasks} WHERE id=?`).get(id);
|
|
557
699
|
return row ? TaskSchema.parse(JSON.parse(String(row.payload))) : void 0;
|
|
558
700
|
},
|
|
@@ -561,13 +703,185 @@ function createAcpStore(storage) {
|
|
|
561
703
|
},
|
|
562
704
|
saveDelegation(input) {
|
|
563
705
|
const value = DelegationSchema.parse(input);
|
|
706
|
+
if (!db.prepare(`SELECT id FROM ${delegations} WHERE id=?`).get(value.id)) membership++;
|
|
564
707
|
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
708
|
},
|
|
566
709
|
tasks(id) {
|
|
567
710
|
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
711
|
},
|
|
712
|
+
/** Reads one bounded history page after checking stored payload bytes before decoding. */
|
|
713
|
+
tasksPage(id, offset, limit, maxBytes) {
|
|
714
|
+
const bytes = db.prepare(`SELECT COALESCE(SUM(length(CAST(payload AS BLOB))),0) AS bytes FROM (SELECT payload FROM ${tasks} WHERE delegation_id=? ORDER BY rowid DESC LIMIT ? OFFSET ?)`).get(id, limit, offset);
|
|
715
|
+
if (Number(bytes.bytes) > maxBytes) throw Object.assign(/* @__PURE__ */ new Error("stored task page exceeds declared budget"), { code: "read-limit" });
|
|
716
|
+
const total = Number(db.prepare(`SELECT COUNT(*) AS count FROM ${tasks} WHERE delegation_id=?`).get(id).count);
|
|
717
|
+
return {
|
|
718
|
+
tasks: db.prepare(`SELECT payload FROM ${tasks} WHERE delegation_id=? ORDER BY rowid DESC LIMIT ? OFFSET ?`).all(id, limit, offset).map((row) => TaskSchema.parse(JSON.parse(String(row.payload)))),
|
|
719
|
+
total
|
|
720
|
+
};
|
|
721
|
+
},
|
|
722
|
+
/** Returns immutable visibility facts without launch configuration. */
|
|
723
|
+
delegationIdentity(id) {
|
|
724
|
+
const row = db.prepare(`SELECT id,parent_session_id,root_session_id FROM ${delegations} WHERE id=?`).get(id);
|
|
725
|
+
return row ? {
|
|
726
|
+
id: String(row.id),
|
|
727
|
+
parentSessionId: String(row.parent_session_id),
|
|
728
|
+
rootSessionId: String(row.root_session_id)
|
|
729
|
+
} : void 0;
|
|
730
|
+
},
|
|
731
|
+
/** Projects a single current or named task status before decoding. */
|
|
732
|
+
summary(id, taskId) {
|
|
733
|
+
const row = taskId === void 0 ? db.prepare(`SELECT ${taskSummaryProjection} FROM ${tasks} WHERE delegation_id=? ORDER BY rowid DESC LIMIT 1`).get(id) : db.prepare(`SELECT ${taskSummaryProjection} FROM ${tasks} WHERE delegation_id=? AND id=?`).get(id, taskId);
|
|
734
|
+
return row ? AcpTaskSummarySchema.parse(JSON.parse(String(row.summary))) : void 0;
|
|
735
|
+
},
|
|
736
|
+
/** One public identity, without adapter arguments or credential-bearing environment. */
|
|
737
|
+
delegationSummary(id) {
|
|
738
|
+
const row = db.prepare(`SELECT ${delegationSummaryProjection} FROM ${delegations} WHERE id=?`).get(id);
|
|
739
|
+
return row ? AcpDelegationSummarySchema.parse(JSON.parse(String(row.summary))) : void 0;
|
|
740
|
+
},
|
|
741
|
+
/** Reads bounded summaries in a keyset range; status changes do not mutate membership. */
|
|
742
|
+
summaryPage(id, input) {
|
|
743
|
+
if (!Number.isSafeInteger(input.limit) || input.limit < 1 || input.limit > 100) throw new Error("Invalid task page limit");
|
|
744
|
+
const observed = db.prepare(`SELECT COUNT(*) AS count,COALESCE(MAX(rowid),0) AS upper FROM ${tasks} WHERE delegation_id=?`).get(id);
|
|
745
|
+
const source = `${membership}:${observed.count}:${observed.upper}`;
|
|
746
|
+
if (input.source !== void 0 && source !== input.source) throw new Error("source_changed: ACP task membership changed");
|
|
747
|
+
const upper = input.upper ?? Number(observed.upper);
|
|
748
|
+
const rows = db.prepare(`SELECT rowid AS task_key,${taskSummaryProjection} FROM ${tasks} WHERE delegation_id=? AND rowid>? AND rowid<=? ORDER BY rowid LIMIT ?`).all(id, input.after ?? 0, upper, input.limit + 1);
|
|
749
|
+
return {
|
|
750
|
+
items: rows.slice(0, input.limit).map((row) => ({
|
|
751
|
+
key: Number(row.task_key),
|
|
752
|
+
value: AcpTaskSummarySchema.parse(JSON.parse(String(row.summary)))
|
|
753
|
+
})),
|
|
754
|
+
source,
|
|
755
|
+
upper,
|
|
756
|
+
complete: rows.length <= input.limit
|
|
757
|
+
};
|
|
758
|
+
},
|
|
759
|
+
/** Reads root-scoped identity metadata without restoring historical delegation bodies. */
|
|
760
|
+
delegationSummaryPage(root, input) {
|
|
761
|
+
const observed = db.prepare(`SELECT COUNT(*) AS count,COALESCE(MAX(rowid),0) AS upper FROM ${delegations} WHERE root_session_id=?`).get(root);
|
|
762
|
+
const source = `${membership}:${observed.count}:${observed.upper}`;
|
|
763
|
+
if (input.source !== void 0 && input.source !== source) throw new Error("source_changed: ACP delegation membership changed");
|
|
764
|
+
const upper = input.upper ?? Number(observed.upper);
|
|
765
|
+
const rows = db.prepare(`SELECT rowid AS delegation_key,parent_session_id,${delegationSummaryProjection} FROM ${delegations} WHERE root_session_id=? AND rowid>? AND rowid<=? ORDER BY rowid LIMIT ?`).all(root, input.after ?? 0, upper, input.limit + 1);
|
|
766
|
+
return {
|
|
767
|
+
items: rows.slice(0, input.limit).map((row) => ({
|
|
768
|
+
key: Number(row.delegation_key),
|
|
769
|
+
parentSessionId: String(row.parent_session_id),
|
|
770
|
+
value: AcpDelegationSummarySchema.parse(JSON.parse(String(row.summary)))
|
|
771
|
+
})),
|
|
772
|
+
source,
|
|
773
|
+
upper,
|
|
774
|
+
complete: rows.length <= input.limit
|
|
775
|
+
};
|
|
776
|
+
},
|
|
777
|
+
/** Public adapter discovery uses only bounded identity columns inside SQLite. */
|
|
778
|
+
instanceSummaryPage(input) {
|
|
779
|
+
const source = String(configuration);
|
|
780
|
+
if (input.source !== void 0 && input.source !== source) throw new Error("source_changed: ACP instances changed");
|
|
781
|
+
const rows = db.prepare(`SELECT id,substr(json_extract(payload,'$.label'),1,256) AS label,json_extract(payload,'$.adapter') AS adapter,json_extract(payload,'$.executionMode') AS mode FROM ${instances} WHERE id>? AND json_extract(payload,'$.enabled')=1 ORDER BY id LIMIT ?`).all(input.after ?? "", input.limit + 1);
|
|
782
|
+
return {
|
|
783
|
+
source,
|
|
784
|
+
complete: rows.length <= input.limit,
|
|
785
|
+
items: rows.slice(0, input.limit).map((row) => ({
|
|
786
|
+
instanceId: String(row.id),
|
|
787
|
+
label: String(row.label),
|
|
788
|
+
...row.adapter ? { adapter: String(row.adapter) } : {},
|
|
789
|
+
executionMode: String(row.mode)
|
|
790
|
+
}))
|
|
791
|
+
};
|
|
792
|
+
},
|
|
793
|
+
/** Reads UTF-8 byte positions and at most limit code points through the existing task/sequence primary key. */
|
|
794
|
+
readResult(taskId, input) {
|
|
795
|
+
if (!Number.isSafeInteger(input.seq) || input.seq < 0 || !Number.isSafeInteger(input.offset) || input.offset < 0 || !Number.isSafeInteger(input.limit) || input.limit < 1 || input.limit > 4096) throw new Error("Invalid result range");
|
|
796
|
+
const textFilter = `json_extract(payload,'$.sessionUpdate')='agent_message_chunk' AND json_extract(payload,'$.content.type')='text'`;
|
|
797
|
+
const row = db.prepare(`SELECT seq,substr(CAST(json_extract(payload,'$.content.text') AS BLOB),?,?) AS bytes,length(CAST(json_extract(payload,'$.content.text') AS BLOB)) AS total FROM ${updates} WHERE task_id=? AND seq>=? AND ${textFilter} ORDER BY seq LIMIT 1`).get(input.offset + 1, input.limit * 4 + 3, taskId, Math.max(1, input.seq));
|
|
798
|
+
if (!row && input.seq > 0) throw new Error("source_changed: original update disappeared");
|
|
799
|
+
if (!row) return {
|
|
800
|
+
taskId,
|
|
801
|
+
text: "",
|
|
802
|
+
start: {
|
|
803
|
+
seq: input.seq,
|
|
804
|
+
offset: input.offset
|
|
805
|
+
},
|
|
806
|
+
end: {
|
|
807
|
+
seq: input.seq,
|
|
808
|
+
offset: input.offset
|
|
809
|
+
},
|
|
810
|
+
total: 0,
|
|
811
|
+
complete: true,
|
|
812
|
+
next: null
|
|
813
|
+
};
|
|
814
|
+
const seq = Number(row.seq), total = Number(row.total);
|
|
815
|
+
if (input.seq > 0 && seq !== input.seq) throw new Error("source_changed: original update disappeared");
|
|
816
|
+
if (!(row.bytes instanceof Uint8Array)) throw new Error("Stored original text has invalid bytes");
|
|
817
|
+
const bytes = row.bytes;
|
|
818
|
+
let usable = bytes.length;
|
|
819
|
+
if (input.offset + usable < total) {
|
|
820
|
+
while (usable && (bytes[usable - 1] & 192) === 128) usable--;
|
|
821
|
+
if (usable < bytes.length || usable && bytes[usable - 1] >= 192) {
|
|
822
|
+
const leading = Math.max(0, usable - 1), first = bytes[leading], width = first >= 240 ? 4 : first >= 224 ? 3 : 2;
|
|
823
|
+
usable = bytes.length - leading < width ? leading : bytes.length;
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
const text = [...new TextDecoder("utf-8", {
|
|
827
|
+
fatal: true,
|
|
828
|
+
ignoreBOM: true
|
|
829
|
+
}).decode(bytes.subarray(0, usable))].slice(0, input.limit).join("");
|
|
830
|
+
const end = input.offset + Buffer.byteLength(text);
|
|
831
|
+
if (input.offset > total) throw new Error("source_changed: result position is beyond original text");
|
|
832
|
+
const nextRow = end === total ? db.prepare(`SELECT seq FROM ${updates} WHERE task_id=? AND seq>? AND ${textFilter} ORDER BY seq LIMIT 1`).get(taskId, seq) : void 0;
|
|
833
|
+
const next = end < total ? {
|
|
834
|
+
seq,
|
|
835
|
+
offset: end
|
|
836
|
+
} : nextRow ? {
|
|
837
|
+
seq: Number(nextRow.seq),
|
|
838
|
+
offset: 0
|
|
839
|
+
} : null;
|
|
840
|
+
return {
|
|
841
|
+
taskId,
|
|
842
|
+
text,
|
|
843
|
+
start: {
|
|
844
|
+
seq,
|
|
845
|
+
offset: input.offset
|
|
846
|
+
},
|
|
847
|
+
end: {
|
|
848
|
+
seq,
|
|
849
|
+
offset: end
|
|
850
|
+
},
|
|
851
|
+
total,
|
|
852
|
+
complete: next === null,
|
|
853
|
+
next
|
|
854
|
+
};
|
|
855
|
+
},
|
|
856
|
+
/** Streams visibility identities without decoding historical delegation bodies. */
|
|
857
|
+
*delegationIdentities() {
|
|
858
|
+
for (const row of db.prepare(`SELECT id,parent_session_id FROM ${delegations} ORDER BY rowid DESC`).iterate()) yield {
|
|
859
|
+
id: String(row.id),
|
|
860
|
+
parentSessionId: String(row.parent_session_id)
|
|
861
|
+
};
|
|
862
|
+
},
|
|
863
|
+
/** Projects the latest bounded summary inside SQLite before returning text to the host. */
|
|
864
|
+
taskSummary(id) {
|
|
865
|
+
const row = db.prepare(`SELECT json_set(payload,'$.input',substr(json_extract(payload,'$.input'),1,2048),'$.result',substr(json_extract(payload,'$.result'),1,2048)) AS payload FROM ${tasks} WHERE delegation_id=? ORDER BY rowid DESC LIMIT 1`).get(id);
|
|
866
|
+
return row ? TaskSchema.parse(JSON.parse(String(row.payload))) : void 0;
|
|
867
|
+
},
|
|
868
|
+
/** Returns bounded queue identities in persistent admission order for one root. */
|
|
869
|
+
queued(root) {
|
|
870
|
+
return db.prepare(`SELECT t.id,t.delegation_id FROM ${tasks} AS t JOIN ${delegations} AS d ON d.id=t.delegation_id WHERE d.root_session_id=? AND json_extract(t.payload,'$.state')='queued' ORDER BY t.rowid LIMIT 64`).all(root).map((row) => ({
|
|
871
|
+
id: String(row.id),
|
|
872
|
+
delegationId: String(row.delegation_id)
|
|
873
|
+
}));
|
|
874
|
+
},
|
|
875
|
+
/** Counts root resource reservations without allocating historical task bodies. */
|
|
876
|
+
rootUsage(root, except) {
|
|
877
|
+
return {
|
|
878
|
+
active: Number(db.prepare(`SELECT COUNT(*) AS count FROM ${tasks} AS t JOIN ${delegations} AS d ON d.id=t.delegation_id WHERE d.root_session_id=? AND json_extract(t.payload,'$.state') NOT IN ('queued','finished')`).get(root).count),
|
|
879
|
+
connections: Number(db.prepare(`SELECT COUNT(*) AS count FROM ${delegations} WHERE root_session_id=? AND id<>? AND json_extract(payload,'$.connectionState') NOT IN ('closed','interrupted')`).get(root, except ?? "").count)
|
|
880
|
+
};
|
|
881
|
+
},
|
|
569
882
|
saveTask(input) {
|
|
570
883
|
const value = TaskSchema.parse(input);
|
|
884
|
+
if (!db.prepare(`SELECT id FROM ${tasks} WHERE id=?`).get(value.id)) membership++;
|
|
571
885
|
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
886
|
},
|
|
573
887
|
append(taskId, payload) {
|
|
@@ -592,6 +906,248 @@ function createAcpStore(storage) {
|
|
|
592
906
|
};
|
|
593
907
|
}
|
|
594
908
|
//#endregion
|
|
909
|
+
//#region src/collections.ts
|
|
910
|
+
/** Bounded owner collections and durable preset configuration intents. */
|
|
911
|
+
const PresetId = z.enum([
|
|
912
|
+
"claude",
|
|
913
|
+
"codex",
|
|
914
|
+
"openclaw"
|
|
915
|
+
]);
|
|
916
|
+
const Inspection = z.strictObject({
|
|
917
|
+
status: z.enum([
|
|
918
|
+
"found",
|
|
919
|
+
"missing-cli",
|
|
920
|
+
"missing-adapter",
|
|
921
|
+
"unsupported-cli",
|
|
922
|
+
"unavailable-cli"
|
|
923
|
+
]),
|
|
924
|
+
path: z.string().nullable(),
|
|
925
|
+
reason: z.string().optional()
|
|
926
|
+
});
|
|
927
|
+
const Failure = z.strictObject({
|
|
928
|
+
code: z.string().max(64),
|
|
929
|
+
message: z.string().max(512)
|
|
930
|
+
});
|
|
931
|
+
const Instances = z.strictObject({ instances: z.array(InstanceSchema) });
|
|
932
|
+
const Added = z.discriminatedUnion("operationState", [
|
|
933
|
+
z.strictObject({
|
|
934
|
+
operationState: z.literal("committed"),
|
|
935
|
+
operationId: z.uuid(),
|
|
936
|
+
value: Instances
|
|
937
|
+
}),
|
|
938
|
+
z.strictObject({
|
|
939
|
+
operationState: z.literal("admitted"),
|
|
940
|
+
operationId: z.uuid(),
|
|
941
|
+
uncertain: z.literal(true)
|
|
942
|
+
}),
|
|
943
|
+
z.strictObject({
|
|
944
|
+
operationState: z.literal("cleanup-pending"),
|
|
945
|
+
operationId: z.uuid(),
|
|
946
|
+
value: Instances,
|
|
947
|
+
cleanup: z.array(Failure)
|
|
948
|
+
})
|
|
949
|
+
]);
|
|
950
|
+
/** An owner-local ordered result that exposes only the target identity. */
|
|
951
|
+
function collectionResult(value) {
|
|
952
|
+
const identity = {
|
|
953
|
+
index: z.number().int().nonnegative(),
|
|
954
|
+
target: z.string()
|
|
955
|
+
};
|
|
956
|
+
return z.strictObject({ results: z.array(z.discriminatedUnion("ok", [z.strictObject({
|
|
957
|
+
...identity,
|
|
958
|
+
ok: z.literal(true),
|
|
959
|
+
value
|
|
960
|
+
}), z.strictObject({
|
|
961
|
+
...identity,
|
|
962
|
+
ok: z.literal(false),
|
|
963
|
+
error: Failure
|
|
964
|
+
})])) });
|
|
965
|
+
}
|
|
966
|
+
/** Checks complete input bytes and declared member budgets before starting work. */
|
|
967
|
+
function collectionInput(shape, key) {
|
|
968
|
+
return z.strictObject(shape).superRefine((value, context) => {
|
|
969
|
+
const input = value;
|
|
970
|
+
if (Buffer.byteLength(JSON.stringify(value)) > 8388608) context.addIssue({
|
|
971
|
+
code: "custom",
|
|
972
|
+
message: "batch input exceeds 8 MiB"
|
|
973
|
+
});
|
|
974
|
+
const items = input[key];
|
|
975
|
+
if (Array.isArray(items) && typeof input.maxItemBytes === "number" && typeof input.maxTotalBytes === "number" && items.length * input.maxItemBytes + 8192 > input.maxTotalBytes) context.addIssue({
|
|
976
|
+
code: "custom",
|
|
977
|
+
message: "declared member budgets exceed total budget"
|
|
978
|
+
});
|
|
979
|
+
});
|
|
980
|
+
}
|
|
981
|
+
/** Settles every member and refuses oversized encoded results without losing other members. */
|
|
982
|
+
async function settleCollection(ids, work, limits) {
|
|
983
|
+
const results = [];
|
|
984
|
+
let bytes = 8192;
|
|
985
|
+
for (const [index, target] of ids.entries()) {
|
|
986
|
+
let item;
|
|
987
|
+
try {
|
|
988
|
+
item = {
|
|
989
|
+
index,
|
|
990
|
+
target,
|
|
991
|
+
ok: true,
|
|
992
|
+
value: await work(target, index)
|
|
993
|
+
};
|
|
994
|
+
const size = Buffer.byteLength(JSON.stringify(item));
|
|
995
|
+
if (size > (limits?.maxItemBytes ?? 8388608) || bytes + size > (limits?.maxTotalBytes ?? 8388608)) throw Object.assign(/* @__PURE__ */ new Error("encoded member exceeds declared budget"), { code: "read-limit" });
|
|
996
|
+
bytes += size;
|
|
997
|
+
} catch (error) {
|
|
998
|
+
item = {
|
|
999
|
+
index,
|
|
1000
|
+
target,
|
|
1001
|
+
ok: false,
|
|
1002
|
+
error: {
|
|
1003
|
+
code: error instanceof Error && "code" in error && typeof error.code === "string" ? error.code.slice(0, 64) : "operation-failed",
|
|
1004
|
+
message: error instanceof Error ? error.message.slice(0, 512) : "Operation failed"
|
|
1005
|
+
}
|
|
1006
|
+
};
|
|
1007
|
+
bytes += Buffer.byteLength(JSON.stringify(item));
|
|
1008
|
+
}
|
|
1009
|
+
results.push(item);
|
|
1010
|
+
}
|
|
1011
|
+
return { results };
|
|
1012
|
+
}
|
|
1013
|
+
/** Registers array preset inspection, atomic creation and independent removal. */
|
|
1014
|
+
function registerPresetCollections(ctx, store, commands) {
|
|
1015
|
+
const changed = ctx.client.registerFrame({
|
|
1016
|
+
name: "instancesChanged",
|
|
1017
|
+
delivery: "broadcast",
|
|
1018
|
+
payload: Instances
|
|
1019
|
+
});
|
|
1020
|
+
ctx.client.registerMethod({
|
|
1021
|
+
name: "inspectPresets",
|
|
1022
|
+
params: collectionInput({
|
|
1023
|
+
ids: z.array(PresetId).min(1).max(3),
|
|
1024
|
+
maxItemBytes: z.number().int().min(1).max(8388608).default(262144),
|
|
1025
|
+
maxTotalBytes: z.number().int().min(1).max(8388608).default(8388608)
|
|
1026
|
+
}, "ids"),
|
|
1027
|
+
result: collectionResult(Inspection),
|
|
1028
|
+
handle: (input) => settleCollection(input.ids, (id) => inspectPreset(PresetId.parse(id), commands), input)
|
|
1029
|
+
});
|
|
1030
|
+
ctx.client.registerMethod({
|
|
1031
|
+
name: "addPresets",
|
|
1032
|
+
params: collectionInput({
|
|
1033
|
+
operationId: z.uuid(),
|
|
1034
|
+
ids: z.array(PresetId).min(1).max(3)
|
|
1035
|
+
}, "ids"),
|
|
1036
|
+
result: Added,
|
|
1037
|
+
async handle(input) {
|
|
1038
|
+
const operations = ctx.services.get("owner-operations");
|
|
1039
|
+
const intent = {
|
|
1040
|
+
scope: "settings",
|
|
1041
|
+
method: "addPresets",
|
|
1042
|
+
operationId: input.operationId,
|
|
1043
|
+
params: input
|
|
1044
|
+
};
|
|
1045
|
+
const previous = operations.lookup(intent);
|
|
1046
|
+
if (previous) return previous;
|
|
1047
|
+
const prepared = [];
|
|
1048
|
+
for (const id of input.ids) {
|
|
1049
|
+
const result = await inspectPreset(id, commands);
|
|
1050
|
+
if (result.status !== "found" || !result.path) throw new Error(result.status);
|
|
1051
|
+
const preset = ACP_PRESETS.find((item) => item.id === id);
|
|
1052
|
+
const instance = InstanceSchema.parse({
|
|
1053
|
+
id: `${id}-${randomUUID()}`,
|
|
1054
|
+
label: preset.label,
|
|
1055
|
+
command: result.path,
|
|
1056
|
+
args: [...preset.args],
|
|
1057
|
+
...id === "openclaw" ? {} : { adapter: id },
|
|
1058
|
+
executionMode: "trusted"
|
|
1059
|
+
});
|
|
1060
|
+
validateInstance(instance, commands.platform);
|
|
1061
|
+
prepared.push(instance);
|
|
1062
|
+
}
|
|
1063
|
+
return operations.atomic(intent, (scope) => {
|
|
1064
|
+
ctx.signal.throwIfAborted();
|
|
1065
|
+
const existing = store.instances();
|
|
1066
|
+
for (const instance of prepared) {
|
|
1067
|
+
if (existing.some((row) => instance.adapter ? row.adapter === instance.adapter : !row.adapter && row.command === instance.command && JSON.stringify(row.args) === JSON.stringify(instance.args))) throw new Error("preset-already-added");
|
|
1068
|
+
existing.push(instance);
|
|
1069
|
+
}
|
|
1070
|
+
for (const instance of prepared) store.saveInstance(instance);
|
|
1071
|
+
const value = { instances: store.instances() };
|
|
1072
|
+
scope.afterCommit(() => changed.emit(value));
|
|
1073
|
+
return value;
|
|
1074
|
+
});
|
|
1075
|
+
}
|
|
1076
|
+
});
|
|
1077
|
+
ctx.client.registerMethod({
|
|
1078
|
+
name: "removeInstances",
|
|
1079
|
+
params: collectionInput({ ids: z.array(z.string().min(1)).min(1).max(64) }, "ids"),
|
|
1080
|
+
result: collectionResult(z.strictObject({ removed: z.boolean() })),
|
|
1081
|
+
async handle(input) {
|
|
1082
|
+
const value = await settleCollection(input.ids, (id) => {
|
|
1083
|
+
if (!store.instances().some((row) => row.id === id)) throw new Error("instance-missing");
|
|
1084
|
+
store.removeInstance(id);
|
|
1085
|
+
return { removed: true };
|
|
1086
|
+
});
|
|
1087
|
+
changed.emit({ instances: store.instances() });
|
|
1088
|
+
return value;
|
|
1089
|
+
}
|
|
1090
|
+
});
|
|
1091
|
+
}
|
|
1092
|
+
/** Stops or closes independent delegation members only after their actual cleanup settles. */
|
|
1093
|
+
function registerDelegationCollections(ctx, manager) {
|
|
1094
|
+
const params = collectionInput({
|
|
1095
|
+
sessionId: z.string().min(1),
|
|
1096
|
+
delegationIds: z.array(z.string().min(1)).min(1).max(64)
|
|
1097
|
+
}, "delegationIds");
|
|
1098
|
+
ctx.client.registerMethod({
|
|
1099
|
+
name: "stopDelegations",
|
|
1100
|
+
params,
|
|
1101
|
+
result: collectionResult(z.strictObject({ stopped: z.boolean() })),
|
|
1102
|
+
handle: (input) => manager.collection(input.delegationIds, () => settleCollection(input.delegationIds, async (id) => {
|
|
1103
|
+
const before = manager.get(input.sessionId, id, 0, 200);
|
|
1104
|
+
await manager.stop(input.sessionId, id);
|
|
1105
|
+
return { stopped: before.tasks.some((task) => task.state !== "finished" && task.state !== "queued") };
|
|
1106
|
+
}))
|
|
1107
|
+
});
|
|
1108
|
+
ctx.client.registerMethod({
|
|
1109
|
+
name: "closeDelegations",
|
|
1110
|
+
params,
|
|
1111
|
+
result: collectionResult(z.strictObject({ closed: z.boolean() })),
|
|
1112
|
+
handle: (input) => manager.collection(input.delegationIds, () => settleCollection(input.delegationIds, async (id) => {
|
|
1113
|
+
manager.get(input.sessionId, id);
|
|
1114
|
+
await manager.close(input.sessionId, id);
|
|
1115
|
+
return { closed: true };
|
|
1116
|
+
}))
|
|
1117
|
+
});
|
|
1118
|
+
}
|
|
1119
|
+
//#endregion
|
|
1120
|
+
//#region src/guidance.ts
|
|
1121
|
+
const ACP_GUIDANCE = {
|
|
1122
|
+
title: "Delegating to external agents",
|
|
1123
|
+
entries: [
|
|
1124
|
+
{
|
|
1125
|
+
tools: ["acp_instances"],
|
|
1126
|
+
text: "`acp_instances` pages enabled external adapter identities without launch configuration; read it before delegating. Default limit 50, hard maximum 100; copy next.arguments unchanged."
|
|
1127
|
+
},
|
|
1128
|
+
{
|
|
1129
|
+
tools: ["acp_delegate"],
|
|
1130
|
+
text: "`acp_delegate` accepts items of tasks and launches them after one approval binds the complete collection. Each result retains its original index; valid tasks queue FIFO under the shared root budget. 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."
|
|
1131
|
+
},
|
|
1132
|
+
{
|
|
1133
|
+
tools: ["acp_get"],
|
|
1134
|
+
text: "`acp_get` accepts items of owned delegation targets and defaults to status summaries without prompts or result bodies. Use view=result with taskId to read original final agent text from retained updates. A positive waitMs also requires taskId for every target and shares one deadline of at most 60000 milliseconds; cancelling a wait leaves tasks running. Default limit 50, hard maximum 100; small allowances can return fewer members or partial text. Copy next.arguments unchanged. outputTokens requests an allowance; effective reports the actual allocation. Check originalComplete before treating retained text as a complete result."
|
|
1135
|
+
},
|
|
1136
|
+
{
|
|
1137
|
+
tools: ["acp_list"],
|
|
1138
|
+
text: "`acp_list` pages owned delegation identities and latest short task statuses without prompts, result bodies or launch configuration. Default limit 50, hard maximum 100; copy next.arguments unchanged."
|
|
1139
|
+
},
|
|
1140
|
+
{
|
|
1141
|
+
tools: ["acp_send"],
|
|
1142
|
+
text: "`acp_send` continues a delegation and returns a short acceptance receipt. Keep its task ID and query status; do not resend accepted work because the receipt was shortened."
|
|
1143
|
+
},
|
|
1144
|
+
{
|
|
1145
|
+
tools: ["acp_stop"],
|
|
1146
|
+
text: "`acp_stop` accepts items with delegationId and optional close; results report actual settled cleanup per member. Changes already made stay."
|
|
1147
|
+
}
|
|
1148
|
+
]
|
|
1149
|
+
};
|
|
1150
|
+
//#endregion
|
|
595
1151
|
//#region src/manager.ts
|
|
596
1152
|
/** The question id an ACP permission is asked under: one question per request. */
|
|
597
1153
|
const PERMISSION_QUESTION = "permission";
|
|
@@ -626,16 +1182,25 @@ function createAcpManager(deps) {
|
|
|
626
1182
|
const permissions = /* @__PURE__ */ new Map();
|
|
627
1183
|
let closed = false;
|
|
628
1184
|
let withdrawn = false;
|
|
1185
|
+
const collections = /* @__PURE__ */ new Set();
|
|
629
1186
|
const changed = (delegation, task) => {
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
1187
|
+
const targets = /* @__PURE__ */ new Set([delegation.parentSessionId, delegation.rootSessionId]);
|
|
1188
|
+
let held = false;
|
|
1189
|
+
for (const collection of collections) {
|
|
1190
|
+
if (collection.admission?.sessionId === delegation.parentSessionId && task?.requestKey.startsWith(collection.admission.requestKeyPrefix)) collection.ids.add(delegation.id);
|
|
1191
|
+
if (!collection.ids.has(delegation.id)) continue;
|
|
1192
|
+
held = true;
|
|
1193
|
+
for (const sessionId of targets) {
|
|
1194
|
+
const ids = collection.changed.get(sessionId) ?? /* @__PURE__ */ new Set();
|
|
1195
|
+
ids.add(delegation.id);
|
|
1196
|
+
collection.changed.set(sessionId, ids);
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
if (held) return;
|
|
1200
|
+
for (const sessionId of targets) try {
|
|
1201
|
+
deps.changed(sessionId, {
|
|
1202
|
+
delegationIds: [delegation.id],
|
|
1203
|
+
invalidated: false
|
|
639
1204
|
});
|
|
640
1205
|
} catch {}
|
|
641
1206
|
};
|
|
@@ -653,10 +1218,18 @@ function createAcpManager(deps) {
|
|
|
653
1218
|
const owner = sessions.resolve(row.parentSessionId);
|
|
654
1219
|
if (caller !== row.parentSessionId && !owner.ancestors.includes(caller)) throw new Error("forbidden");
|
|
655
1220
|
}
|
|
656
|
-
function capacity(root, connection) {
|
|
657
|
-
const
|
|
658
|
-
|
|
659
|
-
if (
|
|
1221
|
+
function capacity(root, connection, queued = false, reservation) {
|
|
1222
|
+
const usage = store.rootUsage(root, reservation);
|
|
1223
|
+
const limits = store.settings();
|
|
1224
|
+
if (usage.active >= limits.maxConcurrent && (!queued || connection && usage.connections >= limits.maxRetainedConnections)) throw new Error("capacity-exceeded");
|
|
1225
|
+
if (connection && usage.connections >= limits.maxRetainedConnections) throw new Error("retained-limit: close an existing delegation first");
|
|
1226
|
+
return usage.active < limits.maxConcurrent;
|
|
1227
|
+
}
|
|
1228
|
+
function schedule(root) {
|
|
1229
|
+
if (closed) return;
|
|
1230
|
+
queueMicrotask(() => {
|
|
1231
|
+
for (const row of store.queued(root)) run(row.delegationId);
|
|
1232
|
+
});
|
|
660
1233
|
}
|
|
661
1234
|
function update(input, fields) {
|
|
662
1235
|
const next = {
|
|
@@ -744,12 +1317,16 @@ function createAcpManager(deps) {
|
|
|
744
1317
|
connections.delete(id);
|
|
745
1318
|
processes.delete(id);
|
|
746
1319
|
if (process) await process.stop();
|
|
1320
|
+
await launches.get(id)?.release?.();
|
|
1321
|
+
launches.delete(id);
|
|
747
1322
|
return;
|
|
748
1323
|
}
|
|
749
1324
|
const row = get(id);
|
|
750
1325
|
try {
|
|
751
1326
|
const process = connection?.process ?? processes.get(id);
|
|
752
1327
|
if (process) await process.stop();
|
|
1328
|
+
await launches.get(id)?.release?.();
|
|
1329
|
+
launches.delete(id);
|
|
753
1330
|
processes.delete(id);
|
|
754
1331
|
connections.delete(id);
|
|
755
1332
|
if (withdrawn) return;
|
|
@@ -764,9 +1341,11 @@ function createAcpManager(deps) {
|
|
|
764
1341
|
...row,
|
|
765
1342
|
connectionState: "cleanup-failed"
|
|
766
1343
|
});
|
|
1344
|
+
changed(get(id));
|
|
767
1345
|
throw new Error("cleanup-failed");
|
|
768
1346
|
}
|
|
769
1347
|
changed(get(id));
|
|
1348
|
+
schedule(row.rootSessionId);
|
|
770
1349
|
}
|
|
771
1350
|
async function connect(row) {
|
|
772
1351
|
const launch = launches.get(row.id);
|
|
@@ -922,10 +1501,19 @@ function createAcpManager(deps) {
|
|
|
922
1501
|
if (closed || running.has(id)) return;
|
|
923
1502
|
const current = store.tasks(id).find((one) => one.state !== "finished");
|
|
924
1503
|
if (!current) return;
|
|
1504
|
+
if (current.state === "queued") {
|
|
1505
|
+
const row = get(id);
|
|
1506
|
+
if (store.queued(row.rootSessionId)[0]?.id !== current.id) return;
|
|
1507
|
+
try {
|
|
1508
|
+
capacity(row.rootSessionId, !connections.has(id), false, id);
|
|
1509
|
+
} catch (error) {
|
|
1510
|
+
if (error instanceof Error && (error.message === "capacity-exceeded" || error.message.startsWith("retained-limit"))) return;
|
|
1511
|
+
throw error;
|
|
1512
|
+
}
|
|
1513
|
+
}
|
|
925
1514
|
const work = (async () => {
|
|
926
1515
|
try {
|
|
927
1516
|
const row = get(id);
|
|
928
|
-
if (current.state === "queued") capacity(row.rootSessionId, !connections.has(id));
|
|
929
1517
|
update(current, { state: "starting" });
|
|
930
1518
|
let connection = connections.get(id);
|
|
931
1519
|
if (!connection) {
|
|
@@ -976,9 +1564,7 @@ function createAcpManager(deps) {
|
|
|
976
1564
|
finish(task(current.id), "failed", safe);
|
|
977
1565
|
} finally {
|
|
978
1566
|
running.delete(id);
|
|
979
|
-
if (!closed
|
|
980
|
-
run(id);
|
|
981
|
-
});
|
|
1567
|
+
if (!closed) schedule(get(id).rootSessionId);
|
|
982
1568
|
}
|
|
983
1569
|
})();
|
|
984
1570
|
running.set(id, work);
|
|
@@ -1029,80 +1615,117 @@ function createAcpManager(deps) {
|
|
|
1029
1615
|
for (const current of store.tasks(row.id)) if (current.state !== "finished") finish(current, "interrupted", "gateway-restarted");
|
|
1030
1616
|
}
|
|
1031
1617
|
},
|
|
1618
|
+
/** Publishes one bounded final invalidation per affected session after all owned members settle. */
|
|
1619
|
+
async collection(ids, work, admission) {
|
|
1620
|
+
const context = {
|
|
1621
|
+
ids: new Set(ids),
|
|
1622
|
+
changed: /* @__PURE__ */ new Map(),
|
|
1623
|
+
admission
|
|
1624
|
+
};
|
|
1625
|
+
collections.add(context);
|
|
1626
|
+
try {
|
|
1627
|
+
return await work();
|
|
1628
|
+
} finally {
|
|
1629
|
+
collections.delete(context);
|
|
1630
|
+
for (const [sessionId, ids] of context.changed) try {
|
|
1631
|
+
deps.changed(sessionId, {
|
|
1632
|
+
delegationIds: [...ids].slice(0, 64),
|
|
1633
|
+
invalidated: ids.size > 64
|
|
1634
|
+
});
|
|
1635
|
+
} catch {}
|
|
1636
|
+
}
|
|
1637
|
+
},
|
|
1032
1638
|
/** Accepts one prompt and records its effective execution only after its launch succeeds. */
|
|
1033
|
-
async start(input, launch, execution) {
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
const
|
|
1040
|
-
if (previous
|
|
1041
|
-
|
|
1639
|
+
async start(input, launch, execution, release) {
|
|
1640
|
+
let adopted = false;
|
|
1641
|
+
try {
|
|
1642
|
+
if (closed) throw new Error("stopping");
|
|
1643
|
+
const selectedExecution = LaunchExecutionSchema.parse(execution);
|
|
1644
|
+
const context = sessions.resolve(input.sessionId);
|
|
1645
|
+
const previous = store.tasks().find((one) => one.requestKey === input.requestKey && get(one.delegationId).parentSessionId === input.sessionId);
|
|
1646
|
+
if (previous) {
|
|
1647
|
+
const row = get(previous.delegationId);
|
|
1648
|
+
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");
|
|
1649
|
+
return previous;
|
|
1650
|
+
}
|
|
1651
|
+
const instance = store.instances().find((row) => row.id === input.instanceId && row.enabled);
|
|
1652
|
+
if (!instance) throw new Error("instance-missing");
|
|
1653
|
+
const available = capacity(context.rootSessionId, true, true) && store.queued(context.rootSessionId).length === 0;
|
|
1654
|
+
const row = {
|
|
1655
|
+
id: randomUUID(),
|
|
1656
|
+
parentSessionId: input.sessionId,
|
|
1657
|
+
rootSessionId: context.rootSessionId,
|
|
1658
|
+
instance,
|
|
1659
|
+
cwd: input.cwd,
|
|
1660
|
+
...input.model ? { model: input.model } : {},
|
|
1661
|
+
config: input.config ?? {},
|
|
1662
|
+
remoteSessionId: null,
|
|
1663
|
+
generation: randomUUID(),
|
|
1664
|
+
processId: null,
|
|
1665
|
+
execution: null,
|
|
1666
|
+
connectionState: "starting",
|
|
1667
|
+
createdAt: Date.now()
|
|
1668
|
+
};
|
|
1669
|
+
launches.set(row.id, {
|
|
1670
|
+
launch,
|
|
1671
|
+
execution: selectedExecution,
|
|
1672
|
+
release
|
|
1673
|
+
});
|
|
1674
|
+
const value = {
|
|
1675
|
+
id: randomUUID(),
|
|
1676
|
+
delegationId: row.id,
|
|
1677
|
+
requestKey: input.requestKey,
|
|
1678
|
+
targetGeneration: delivery.captureGeneration(input.sessionId),
|
|
1679
|
+
input: input.task,
|
|
1680
|
+
state: available ? "starting" : "queued",
|
|
1681
|
+
outcome: null,
|
|
1682
|
+
error: null,
|
|
1683
|
+
result: "",
|
|
1684
|
+
truncated: false,
|
|
1685
|
+
createdAt: Date.now(),
|
|
1686
|
+
revision: 0
|
|
1687
|
+
};
|
|
1688
|
+
store.transaction(() => {
|
|
1689
|
+
store.saveDelegation(row);
|
|
1690
|
+
store.saveTask(value);
|
|
1691
|
+
});
|
|
1692
|
+
adopted = true;
|
|
1693
|
+
changed(row, value);
|
|
1694
|
+
queueMicrotask(() => {
|
|
1695
|
+
run(row.id);
|
|
1696
|
+
});
|
|
1697
|
+
return value;
|
|
1698
|
+
} finally {
|
|
1699
|
+
if (!adopted) await release?.();
|
|
1042
1700
|
}
|
|
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
1701
|
},
|
|
1089
1702
|
/** Reuses a live connection, or requires a fresh approved factory and isolation facts. */
|
|
1090
|
-
send(caller, id, input, requestKey, prepared) {
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1703
|
+
async send(caller, id, input, requestKey, prepared) {
|
|
1704
|
+
let adopted = false;
|
|
1705
|
+
try {
|
|
1706
|
+
if (closed) throw new Error("stopping");
|
|
1707
|
+
authorize(caller, get(id));
|
|
1708
|
+
if (prepared) {
|
|
1709
|
+
await launches.get(id)?.release?.();
|
|
1710
|
+
launches.set(id, {
|
|
1711
|
+
launch: prepared.launch,
|
|
1712
|
+
execution: LaunchExecutionSchema.parse(prepared.execution),
|
|
1713
|
+
release: prepared.release
|
|
1714
|
+
});
|
|
1715
|
+
adopted = true;
|
|
1716
|
+
}
|
|
1717
|
+
if (!connections.has(id) && !prepared) throw new Error("resume-unavailable: launch authorization required");
|
|
1718
|
+
const result = accepted(id, input, requestKey);
|
|
1719
|
+
if (!connections.has(id)) store.saveDelegation({
|
|
1720
|
+
...get(id),
|
|
1721
|
+
generation: randomUUID(),
|
|
1722
|
+
connectionState: "starting",
|
|
1723
|
+
execution: null
|
|
1724
|
+
});
|
|
1725
|
+
return result;
|
|
1726
|
+
} finally {
|
|
1727
|
+
if (prepared && !adopted) await prepared.release?.();
|
|
1728
|
+
}
|
|
1106
1729
|
},
|
|
1107
1730
|
usage(caller) {
|
|
1108
1731
|
const root = sessions.resolve(caller).rootSessionId;
|
|
@@ -1114,42 +1737,111 @@ function createAcpManager(deps) {
|
|
|
1114
1737
|
connections: rows.filter((row) => row.connectionState !== "closed" && row.connectionState !== "interrupted").length
|
|
1115
1738
|
};
|
|
1116
1739
|
},
|
|
1117
|
-
|
|
1740
|
+
summary(caller, id, taskId) {
|
|
1741
|
+
const identity = store.delegationIdentity(id);
|
|
1742
|
+
if (!identity) throw new Error("not-found");
|
|
1743
|
+
authorize(caller, identity);
|
|
1744
|
+
const delegation = store.delegationSummary(id);
|
|
1745
|
+
const task = store.summary(id, taskId);
|
|
1746
|
+
if (taskId !== void 0 && !task) throw new Error("not-found");
|
|
1747
|
+
return {
|
|
1748
|
+
delegation,
|
|
1749
|
+
task: task ?? null
|
|
1750
|
+
};
|
|
1751
|
+
},
|
|
1752
|
+
summaryPage(caller, id, input) {
|
|
1753
|
+
const identity = store.delegationIdentity(id);
|
|
1754
|
+
if (!identity) throw new Error("not-found");
|
|
1755
|
+
authorize(caller, identity);
|
|
1756
|
+
return {
|
|
1757
|
+
delegation: store.delegationSummary(id),
|
|
1758
|
+
...store.summaryPage(id, input)
|
|
1759
|
+
};
|
|
1760
|
+
},
|
|
1761
|
+
summaryDelegations(caller, input) {
|
|
1762
|
+
const own = sessions.resolve(caller);
|
|
1763
|
+
const page = store.delegationSummaryPage(own.rootSessionId, input);
|
|
1764
|
+
return {
|
|
1765
|
+
...page,
|
|
1766
|
+
items: page.items.filter((item) => {
|
|
1767
|
+
try {
|
|
1768
|
+
authorize(caller, item);
|
|
1769
|
+
return true;
|
|
1770
|
+
} catch {
|
|
1771
|
+
return false;
|
|
1772
|
+
}
|
|
1773
|
+
}),
|
|
1774
|
+
after: page.items.at(-1)?.key ?? input.after ?? 0
|
|
1775
|
+
};
|
|
1776
|
+
},
|
|
1777
|
+
readResult(caller, id, taskId, input) {
|
|
1778
|
+
const identity = store.delegationIdentity(id);
|
|
1779
|
+
if (!identity) throw new Error("not-found");
|
|
1780
|
+
authorize(caller, identity);
|
|
1781
|
+
const task = store.summary(id, taskId);
|
|
1782
|
+
if (!task) throw new Error("not-found");
|
|
1783
|
+
const status = { task };
|
|
1784
|
+
if (status.task?.state !== "finished") throw new Error("unavailable: ACP task has no final result yet");
|
|
1785
|
+
return {
|
|
1786
|
+
...store.readResult(taskId, input),
|
|
1787
|
+
revision: status.task.revision,
|
|
1788
|
+
originalComplete: status.task.outcome === "completed",
|
|
1789
|
+
source: {
|
|
1790
|
+
delegationId: id,
|
|
1791
|
+
taskId
|
|
1792
|
+
}
|
|
1793
|
+
};
|
|
1794
|
+
},
|
|
1795
|
+
get(caller, id, offset = 0, limit = 50, maxBytes = 8388608) {
|
|
1118
1796
|
const row = get(id);
|
|
1119
1797
|
authorize(caller, row);
|
|
1798
|
+
const effective = Math.min(200, limit);
|
|
1799
|
+
const page = store.tasksPage(id, offset, effective, maxBytes);
|
|
1120
1800
|
return {
|
|
1121
1801
|
delegation: row,
|
|
1122
|
-
tasks:
|
|
1802
|
+
tasks: page.tasks,
|
|
1803
|
+
offset,
|
|
1804
|
+
limit: effective,
|
|
1805
|
+
nextOffset: offset + page.tasks.length < page.total ? offset + page.tasks.length : null,
|
|
1806
|
+
...limit > effective ? { notice: `limit clamped from ${limit} to ${effective}` } : {}
|
|
1123
1807
|
};
|
|
1124
1808
|
},
|
|
1125
|
-
task(caller, id, taskId) {
|
|
1809
|
+
task(caller, id, taskId, maxBytes = 8388608) {
|
|
1126
1810
|
authorize(caller, get(id));
|
|
1127
|
-
const current = task(taskId);
|
|
1811
|
+
const current = store.task(taskId, maxBytes);
|
|
1812
|
+
if (!current) throw new Error("not-found");
|
|
1128
1813
|
if (current.delegationId !== id) throw new Error("not-found");
|
|
1129
1814
|
return current;
|
|
1130
1815
|
},
|
|
1131
1816
|
list(caller, offset = 0, limit = 50) {
|
|
1132
1817
|
sessions.resolve(caller);
|
|
1133
|
-
|
|
1818
|
+
const rows = [];
|
|
1819
|
+
let skipped = 0;
|
|
1820
|
+
let bytes = 8192;
|
|
1821
|
+
for (const identity of store.delegationIdentities()) {
|
|
1134
1822
|
try {
|
|
1135
|
-
authorize(caller,
|
|
1136
|
-
return true;
|
|
1823
|
+
authorize(caller, identity);
|
|
1137
1824
|
} catch {
|
|
1138
|
-
|
|
1825
|
+
continue;
|
|
1139
1826
|
}
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
}
|
|
1152
|
-
|
|
1827
|
+
if (skipped++ < offset) continue;
|
|
1828
|
+
const row = get(identity.id);
|
|
1829
|
+
const last = store.taskSummary(row.id);
|
|
1830
|
+
const entry = {
|
|
1831
|
+
delegation: row,
|
|
1832
|
+
tasks: last ? [last] : [],
|
|
1833
|
+
permissions: [...permissions.entries()].filter(([, value]) => value.delegationId === row.id).map(([id, value]) => ({
|
|
1834
|
+
id,
|
|
1835
|
+
generation: value.generation,
|
|
1836
|
+
request: value.request
|
|
1837
|
+
}))
|
|
1838
|
+
};
|
|
1839
|
+
bytes += Buffer.byteLength(JSON.stringify(entry));
|
|
1840
|
+
if (bytes > 8388608) throw Object.assign(/* @__PURE__ */ new Error("delegation summary page exceeds 8 MiB"), { code: "read-limit" });
|
|
1841
|
+
rows.push(entry);
|
|
1842
|
+
if (rows.length >= Math.min(200, limit)) break;
|
|
1843
|
+
}
|
|
1844
|
+
return rows;
|
|
1153
1845
|
},
|
|
1154
1846
|
hasConnection: (id) => connections.has(id),
|
|
1155
1847
|
async stop(caller, id) {
|
|
@@ -1191,12 +1883,14 @@ function createAcpManager(deps) {
|
|
|
1191
1883
|
closed = true;
|
|
1192
1884
|
for (const pending of [...permissions.values()]) expire(pending.delegationId);
|
|
1193
1885
|
const live = [.../* @__PURE__ */ new Set([...processes.values(), ...[...connections.values()].map((one) => one.process)])];
|
|
1194
|
-
|
|
1195
|
-
processes.clear();
|
|
1196
|
-
launches.clear();
|
|
1886
|
+
const preparations = [...launches.values()];
|
|
1197
1887
|
const stopped = await Promise.allSettled(live.map((process) => process.stop()));
|
|
1198
1888
|
await Promise.allSettled([...starting.values(), ...running.values()]);
|
|
1199
|
-
|
|
1889
|
+
const released = await Promise.allSettled(preparations.map((plan) => plan.release?.()));
|
|
1890
|
+
if (stopped.some((result) => result.status === "rejected") || released.some((result) => result.status === "rejected")) throw new Error("cleanup-failed");
|
|
1891
|
+
launches.clear();
|
|
1892
|
+
connections.clear();
|
|
1893
|
+
processes.clear();
|
|
1200
1894
|
},
|
|
1201
1895
|
async shutdown() {
|
|
1202
1896
|
closed = true;
|
|
@@ -1207,62 +1901,6 @@ function createAcpManager(deps) {
|
|
|
1207
1901
|
};
|
|
1208
1902
|
}
|
|
1209
1903
|
//#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
1904
|
//#region src/tool-names.ts
|
|
1267
1905
|
/** Canonical names shared by tool registration and browser presentation. */
|
|
1268
1906
|
const TOOL_NAMES = [
|
|
@@ -1274,25 +1912,704 @@ const TOOL_NAMES = [
|
|
|
1274
1912
|
"acp_stop"
|
|
1275
1913
|
];
|
|
1276
1914
|
//#endregion
|
|
1915
|
+
//#region src/pages.ts
|
|
1916
|
+
/** ACP model reads retain identity-only discovery and bounded original-update ranges. */
|
|
1917
|
+
const tokens = z.number().int().positive().optional().describe("Desired output tokens; the host may allocate less.");
|
|
1918
|
+
const limit = z.number().int().min(1).max(100).default(50).describe("Maximum summaries per page, default 50 and hard maximum 100.");
|
|
1919
|
+
const target = z.strictObject({
|
|
1920
|
+
delegationId: z.string().min(1).max(512).describe("Owned external delegation ID."),
|
|
1921
|
+
taskId: z.string().min(1).max(512).optional().describe("Named task; omit to page the delegation task summaries.")
|
|
1922
|
+
});
|
|
1923
|
+
const getInitial = z.strictObject({
|
|
1924
|
+
items: z.array(target).min(1).max(64).describe("One to 64 ordered task targets; a positive wait or result view requires taskId for every member."),
|
|
1925
|
+
view: z.enum(["status", "result"]).default("status").describe("status returns metadata without prompts/output bodies; result pages original final agent text from retained updates."),
|
|
1926
|
+
waitMs: z.number().int().min(0).max(6e4).optional().describe("One shared deadline in milliseconds. Positive waits require taskId for every member; cancellation leaves tasks running."),
|
|
1927
|
+
limit,
|
|
1928
|
+
outputTokens: tokens
|
|
1929
|
+
}).superRefine((input, issues) => {
|
|
1930
|
+
if (((input.waitMs ?? 0) > 0 || input.view === "result") && input.items.some((item) => !item.taskId)) issues.addIssue({
|
|
1931
|
+
code: "custom",
|
|
1932
|
+
path: ["items"],
|
|
1933
|
+
message: "Every result or positive wait target requires taskId"
|
|
1934
|
+
});
|
|
1935
|
+
});
|
|
1936
|
+
const listInitial = z.strictObject({
|
|
1937
|
+
limit,
|
|
1938
|
+
outputTokens: tokens
|
|
1939
|
+
});
|
|
1940
|
+
const continuation = z.strictObject({
|
|
1941
|
+
cursor: z.string().min(1).max(512).describe("Opaque cursor copied unchanged from next.arguments; status and result cursors are distinct."),
|
|
1942
|
+
outputTokens: tokens
|
|
1943
|
+
});
|
|
1944
|
+
const coordinates = z.strictObject({
|
|
1945
|
+
seq: z.number().int().nonnegative(),
|
|
1946
|
+
byte: z.number().int().nonnegative()
|
|
1947
|
+
});
|
|
1948
|
+
const resultValue = z.strictObject({
|
|
1949
|
+
taskId: z.string(),
|
|
1950
|
+
text: z.string(),
|
|
1951
|
+
start: coordinates,
|
|
1952
|
+
end: coordinates,
|
|
1953
|
+
totalBytes: z.number().int().nonnegative(),
|
|
1954
|
+
unit: z.literal("utf8-bytes"),
|
|
1955
|
+
source: z.object({
|
|
1956
|
+
delegationId: z.string(),
|
|
1957
|
+
taskId: z.string()
|
|
1958
|
+
}),
|
|
1959
|
+
revision: z.number(),
|
|
1960
|
+
originalComplete: z.boolean()
|
|
1961
|
+
});
|
|
1962
|
+
const getMember = z.strictObject({
|
|
1963
|
+
index: z.number().int().nonnegative(),
|
|
1964
|
+
target,
|
|
1965
|
+
value: z.union([z.strictObject({
|
|
1966
|
+
delegation: AcpDelegationSummarySchema,
|
|
1967
|
+
task: AcpTaskSummarySchema.nullable()
|
|
1968
|
+
}), resultValue]).optional(),
|
|
1969
|
+
error: z.object({
|
|
1970
|
+
code: z.string(),
|
|
1971
|
+
message: z.string()
|
|
1972
|
+
}).optional()
|
|
1973
|
+
});
|
|
1974
|
+
const listMember = z.strictObject({
|
|
1975
|
+
delegation: AcpDelegationSummarySchema,
|
|
1976
|
+
latest: AcpTaskSummarySchema.nullable()
|
|
1977
|
+
});
|
|
1978
|
+
const instanceMember = z.strictObject({
|
|
1979
|
+
instanceId: z.string(),
|
|
1980
|
+
label: z.string(),
|
|
1981
|
+
adapter: z.string().optional(),
|
|
1982
|
+
executionMode: z.enum(["sandbox", "trusted"])
|
|
1983
|
+
});
|
|
1984
|
+
const failure = z.strictObject({
|
|
1985
|
+
ok: z.literal(false),
|
|
1986
|
+
error: z.object({
|
|
1987
|
+
code: z.string(),
|
|
1988
|
+
message: z.string(),
|
|
1989
|
+
retryable: z.boolean()
|
|
1990
|
+
}),
|
|
1991
|
+
next: z.unknown()
|
|
1992
|
+
});
|
|
1993
|
+
const output = (items) => z.union([z.strictObject({
|
|
1994
|
+
ok: z.literal(true),
|
|
1995
|
+
complete: z.boolean(),
|
|
1996
|
+
items,
|
|
1997
|
+
next: z.unknown(),
|
|
1998
|
+
effective: z.object({
|
|
1999
|
+
limit: z.number(),
|
|
2000
|
+
outputTokens: z.number()
|
|
2001
|
+
})
|
|
2002
|
+
}), failure]);
|
|
2003
|
+
/** Every root query has one cross-owner lease, shared by its fixed pages and successors. */
|
|
2004
|
+
function acpReadTools(store, manager, resources, signal) {
|
|
2005
|
+
const cursors = /* @__PURE__ */ new Map();
|
|
2006
|
+
let queue = Promise.resolve();
|
|
2007
|
+
const cleanupQuery = (query) => {
|
|
2008
|
+
if (query.closed) return;
|
|
2009
|
+
query.closed = true;
|
|
2010
|
+
query.sources.clear();
|
|
2011
|
+
query.revisions.clear();
|
|
2012
|
+
for (const [id, cursor] of cursors) if (cursor.query === query) {
|
|
2013
|
+
cursor.result = void 0;
|
|
2014
|
+
cursors.delete(id);
|
|
2015
|
+
}
|
|
2016
|
+
};
|
|
2017
|
+
const close = (query) => query.lease.close("completed");
|
|
2018
|
+
const error = (code, message, next = null) => ({
|
|
2019
|
+
content: JSON.stringify({
|
|
2020
|
+
ok: false,
|
|
2021
|
+
error: {
|
|
2022
|
+
code,
|
|
2023
|
+
message: [...message].slice(0, 256).join(""),
|
|
2024
|
+
retryable: next !== null
|
|
2025
|
+
},
|
|
2026
|
+
next
|
|
2027
|
+
}),
|
|
2028
|
+
isError: true
|
|
2029
|
+
});
|
|
2030
|
+
const tool = (kind) => ({
|
|
2031
|
+
name: kind,
|
|
2032
|
+
preload: false,
|
|
2033
|
+
description: kind === "acp_get" ? "Read owned ACP task status summaries by default. view=result reads original final agent text in bounded UTF-8 ranges, including text beyond the 64 KiB task summary; every result or positive wait target requires taskId. A positive waitMs shares one deadline of at most 60000 milliseconds and never stops tasks. Follow next.arguments unchanged; hard member limit 100." : kind === "acp_list" ? "List owned external delegation identities and short task status summaries. No prompts, output bodies, commands, environment or permission payloads are included. Default 50, hard maximum 100 per page; follow next.arguments unchanged." : "List enabled external adapter identities accepted by acp_delegate. No launch configuration is included. Default 50, hard maximum 100 per page; follow next.arguments unchanged.",
|
|
2034
|
+
inputSchema: z.union([kind === "acp_get" ? getInitial : listInitial, continuation]),
|
|
2035
|
+
outputSchema: output(z.array(kind === "acp_get" ? getMember : kind === "acp_list" ? listMember : instanceMember)),
|
|
2036
|
+
deliveryKind: "exact-page",
|
|
2037
|
+
async execute(raw, ctx) {
|
|
2038
|
+
ctx.signal.throwIfAborted();
|
|
2039
|
+
signal.throwIfAborted();
|
|
2040
|
+
const input = z.union([kind === "acp_get" ? getInitial : listInitial, continuation]).parse(raw), now = performance.now();
|
|
2041
|
+
let selected, id;
|
|
2042
|
+
if ("cursor" in input) {
|
|
2043
|
+
id = input.cursor;
|
|
2044
|
+
const found = cursors.get(id);
|
|
2045
|
+
if (!found || found.query.kind !== kind || found.query.session !== ctx.sessionId || found.query.address !== JSON.stringify(ctx.address) || found.query.generation !== ctx.historyGeneration) return error("cursor_invalid", "Cursor is unavailable for this session and history.");
|
|
2046
|
+
selected = found;
|
|
2047
|
+
if (now - found.query.touched > 6e5 || now - found.query.created > 36e5) {
|
|
2048
|
+
close(found.query);
|
|
2049
|
+
return error("cursor_expired", "Restart this expired ACP query.", {
|
|
2050
|
+
tool: kind,
|
|
2051
|
+
arguments: found.query.input
|
|
2052
|
+
});
|
|
2053
|
+
}
|
|
2054
|
+
} else {
|
|
2055
|
+
for (const query of new Set([...cursors.values()].map((cursor) => cursor.query))) if (now - query.touched > 6e5 || now - query.created > 36e5 || query.session === ctx.sessionId && query.generation !== ctx.historyGeneration) close(query);
|
|
2056
|
+
const bytes = Buffer.byteLength(JSON.stringify(input)) + 512;
|
|
2057
|
+
let lease;
|
|
2058
|
+
try {
|
|
2059
|
+
lease = await resources.reserve(ctx, {
|
|
2060
|
+
bytes,
|
|
2061
|
+
scratchBytes: 0,
|
|
2062
|
+
cleanup: async () => {
|
|
2063
|
+
cleanupQuery(query);
|
|
2064
|
+
return { status: "complete" };
|
|
2065
|
+
}
|
|
2066
|
+
});
|
|
2067
|
+
} catch (failure) {
|
|
2068
|
+
if (resources.isAdmissionFailure(failure)) throw failure;
|
|
2069
|
+
return error("query_capacity_exceeded", "ACP query metadata exceeds temporary capacity.");
|
|
2070
|
+
}
|
|
2071
|
+
const query = {
|
|
2072
|
+
kind,
|
|
2073
|
+
session: ctx.sessionId,
|
|
2074
|
+
address: JSON.stringify(ctx.address),
|
|
2075
|
+
generation: ctx.historyGeneration,
|
|
2076
|
+
created: now,
|
|
2077
|
+
touched: now,
|
|
2078
|
+
input,
|
|
2079
|
+
lease,
|
|
2080
|
+
bytes,
|
|
2081
|
+
sources: /* @__PURE__ */ new Map(),
|
|
2082
|
+
revisions: /* @__PURE__ */ new Map()
|
|
2083
|
+
};
|
|
2084
|
+
id = randomUUID();
|
|
2085
|
+
selected = {
|
|
2086
|
+
query,
|
|
2087
|
+
member: 0,
|
|
2088
|
+
after: 0,
|
|
2089
|
+
instanceAfter: "",
|
|
2090
|
+
seq: 0,
|
|
2091
|
+
offset: 0
|
|
2092
|
+
};
|
|
2093
|
+
cursors.set(id, selected);
|
|
2094
|
+
if ("items" in input && (input.waitMs ?? 0) > 0) await query.lease.withUse(ctx, async () => {
|
|
2095
|
+
const deadline = performance.now() + input.waitMs;
|
|
2096
|
+
for (const item of input.items) for (;;) {
|
|
2097
|
+
ctx.signal.throwIfAborted();
|
|
2098
|
+
signal.throwIfAborted();
|
|
2099
|
+
let state;
|
|
2100
|
+
try {
|
|
2101
|
+
state = manager.summary(ctx.sessionId, item.delegationId, item.taskId).task?.state;
|
|
2102
|
+
} catch (failure) {
|
|
2103
|
+
if (resources.isAdmissionFailure(failure)) throw failure;
|
|
2104
|
+
break;
|
|
2105
|
+
}
|
|
2106
|
+
const remaining = deadline - performance.now();
|
|
2107
|
+
if (state === "finished" || remaining <= 0) break;
|
|
2108
|
+
await new Promise((resolve) => {
|
|
2109
|
+
const complete = () => {
|
|
2110
|
+
clearTimeout(timer);
|
|
2111
|
+
ctx.signal.removeEventListener("abort", complete);
|
|
2112
|
+
resolve();
|
|
2113
|
+
};
|
|
2114
|
+
const timer = setTimeout(complete, Math.min(50, remaining));
|
|
2115
|
+
ctx.signal.addEventListener("abort", complete, { once: true });
|
|
2116
|
+
});
|
|
2117
|
+
}
|
|
2118
|
+
});
|
|
2119
|
+
}
|
|
2120
|
+
const query = selected.query;
|
|
2121
|
+
try {
|
|
2122
|
+
return await query.lease.withUse(ctx, async () => {
|
|
2123
|
+
query.touched = now;
|
|
2124
|
+
const source = query.input, restart = (message) => {
|
|
2125
|
+
close(query);
|
|
2126
|
+
return error("source_changed", message, {
|
|
2127
|
+
tool: kind,
|
|
2128
|
+
arguments: source
|
|
2129
|
+
});
|
|
2130
|
+
};
|
|
2131
|
+
if (selected.result) {
|
|
2132
|
+
try {
|
|
2133
|
+
if ("items" in source && source.view === "result") {
|
|
2134
|
+
const cached = output(z.array(getMember)).parse(JSON.parse(selected.result.content));
|
|
2135
|
+
if (cached.ok) for (const member of z.array(getMember).parse(cached.items)) {
|
|
2136
|
+
if (!member.value || !("text" in member.value)) continue;
|
|
2137
|
+
const original = manager.readResult(ctx.sessionId, member.target.delegationId, member.target.taskId, {
|
|
2138
|
+
seq: member.value.start.seq,
|
|
2139
|
+
offset: member.value.start.byte,
|
|
2140
|
+
limit: 1
|
|
2141
|
+
});
|
|
2142
|
+
if (original.revision !== member.value.revision || JSON.stringify(original.source) !== JSON.stringify(member.value.source)) return restart("ACP original result changed; restart the query.");
|
|
2143
|
+
}
|
|
2144
|
+
}
|
|
2145
|
+
} catch (cause) {
|
|
2146
|
+
return restart(cause instanceof Error ? cause.message : "ACP original source unavailable");
|
|
2147
|
+
}
|
|
2148
|
+
try {
|
|
2149
|
+
if ("items" in source) for (const item of source.items) manager.summary(ctx.sessionId, item.delegationId, item.taskId);
|
|
2150
|
+
else if (kind === "acp_instances") store.instanceSummaryPage({
|
|
2151
|
+
after: selected.instanceAfter,
|
|
2152
|
+
source: query.source,
|
|
2153
|
+
limit: 1
|
|
2154
|
+
});
|
|
2155
|
+
else manager.summaryDelegations(ctx.sessionId, {
|
|
2156
|
+
after: selected.after,
|
|
2157
|
+
upper: query.upper,
|
|
2158
|
+
source: query.source,
|
|
2159
|
+
limit: 1
|
|
2160
|
+
});
|
|
2161
|
+
} catch (cause) {
|
|
2162
|
+
return restart(cause instanceof Error ? cause.message : "ACP source unavailable");
|
|
2163
|
+
}
|
|
2164
|
+
const needed = ctx.output.measure(selected.result);
|
|
2165
|
+
if (needed > ctx.output.outputTokens) return error("page_too_small", "The fixed ACP page requires more allowance.", needed <= ctx.output.maximumTokens ? {
|
|
2166
|
+
tool: kind,
|
|
2167
|
+
arguments: {
|
|
2168
|
+
cursor: id,
|
|
2169
|
+
outputTokens: needed
|
|
2170
|
+
}
|
|
2171
|
+
} : null);
|
|
2172
|
+
ctx.output.acceptExact(selected.result);
|
|
2173
|
+
return selected.result;
|
|
2174
|
+
}
|
|
2175
|
+
const nextId = randomUUID(), items = [];
|
|
2176
|
+
let at = selected.member, after = selected.after, instanceAfter = selected.instanceAfter, seq = selected.seq, offset = selected.offset, complete = false;
|
|
2177
|
+
const page = () => ({ content: JSON.stringify({
|
|
2178
|
+
ok: true,
|
|
2179
|
+
complete,
|
|
2180
|
+
items,
|
|
2181
|
+
next: complete ? null : {
|
|
2182
|
+
tool: kind,
|
|
2183
|
+
arguments: { cursor: nextId }
|
|
2184
|
+
},
|
|
2185
|
+
effective: {
|
|
2186
|
+
limit: source.limit,
|
|
2187
|
+
outputTokens: ctx.output.outputTokens
|
|
2188
|
+
}
|
|
2189
|
+
}) });
|
|
2190
|
+
if ("items" in source) {
|
|
2191
|
+
while (at < source.items.length && items.length < source.limit) {
|
|
2192
|
+
const priorAfter = after;
|
|
2193
|
+
const item = source.items[at], statusSource = query.sources.get(at);
|
|
2194
|
+
let row, memberComplete = true, nextPosition = null;
|
|
2195
|
+
try {
|
|
2196
|
+
const status = manager.summary(ctx.sessionId, item.delegationId, item.taskId);
|
|
2197
|
+
if (source.view === "result") {
|
|
2198
|
+
const part = manager.readResult(ctx.sessionId, item.delegationId, item.taskId, {
|
|
2199
|
+
seq,
|
|
2200
|
+
offset,
|
|
2201
|
+
limit: 4096
|
|
2202
|
+
});
|
|
2203
|
+
const prior = query.revisions.get(at);
|
|
2204
|
+
if (prior !== void 0 && prior !== part.revision) return restart("ACP original result changed; restart the query.");
|
|
2205
|
+
query.revisions.set(at, part.revision);
|
|
2206
|
+
let points = [...part.text];
|
|
2207
|
+
const value = () => ({
|
|
2208
|
+
taskId: item.taskId,
|
|
2209
|
+
text: points.join(""),
|
|
2210
|
+
start: {
|
|
2211
|
+
seq: part.start.seq,
|
|
2212
|
+
byte: part.start.offset
|
|
2213
|
+
},
|
|
2214
|
+
end: {
|
|
2215
|
+
seq: part.start.seq,
|
|
2216
|
+
byte: part.start.offset + Buffer.byteLength(points.join(""))
|
|
2217
|
+
},
|
|
2218
|
+
totalBytes: part.total,
|
|
2219
|
+
unit: "utf8-bytes",
|
|
2220
|
+
source: part.source,
|
|
2221
|
+
revision: part.revision,
|
|
2222
|
+
originalComplete: part.originalComplete
|
|
2223
|
+
});
|
|
2224
|
+
row = {
|
|
2225
|
+
index: at,
|
|
2226
|
+
target: item,
|
|
2227
|
+
value: value()
|
|
2228
|
+
};
|
|
2229
|
+
items.push(row);
|
|
2230
|
+
while (points.length && ctx.output.measure(page()) > ctx.output.outputTokens) {
|
|
2231
|
+
points = points.slice(0, Math.floor(points.length / 2));
|
|
2232
|
+
row.value = value();
|
|
2233
|
+
}
|
|
2234
|
+
items.pop();
|
|
2235
|
+
if (part.text.length && !points.length) break;
|
|
2236
|
+
const end = row.value.end.byte;
|
|
2237
|
+
nextPosition = end < part.total ? {
|
|
2238
|
+
seq: part.start.seq,
|
|
2239
|
+
offset: end
|
|
2240
|
+
} : part.next;
|
|
2241
|
+
memberComplete = nextPosition === null;
|
|
2242
|
+
} else if (item.taskId) row = {
|
|
2243
|
+
index: at,
|
|
2244
|
+
target: item,
|
|
2245
|
+
value: status
|
|
2246
|
+
};
|
|
2247
|
+
else {
|
|
2248
|
+
const found = manager.summaryPage(ctx.sessionId, item.delegationId, {
|
|
2249
|
+
after,
|
|
2250
|
+
limit: 1,
|
|
2251
|
+
...statusSource
|
|
2252
|
+
});
|
|
2253
|
+
query.sources.set(at, {
|
|
2254
|
+
source: found.source,
|
|
2255
|
+
upper: found.upper
|
|
2256
|
+
});
|
|
2257
|
+
const current = found.items[0];
|
|
2258
|
+
row = {
|
|
2259
|
+
index: at,
|
|
2260
|
+
target: item,
|
|
2261
|
+
value: {
|
|
2262
|
+
delegation: found.delegation,
|
|
2263
|
+
task: current?.value ?? null
|
|
2264
|
+
}
|
|
2265
|
+
};
|
|
2266
|
+
memberComplete = found.complete;
|
|
2267
|
+
if (current) after = current.key;
|
|
2268
|
+
}
|
|
2269
|
+
} catch (cause) {
|
|
2270
|
+
ctx.signal.throwIfAborted();
|
|
2271
|
+
if (cause instanceof Error && cause.message.startsWith("source_changed")) return restart(cause.message);
|
|
2272
|
+
row = {
|
|
2273
|
+
index: at,
|
|
2274
|
+
target: item,
|
|
2275
|
+
error: {
|
|
2276
|
+
code: cause instanceof Error && cause.message.startsWith("unavailable") ? "unavailable" : "not-owned",
|
|
2277
|
+
message: cause instanceof Error ? cause.message.slice(0, 256) : "Task is absent or inaccessible"
|
|
2278
|
+
}
|
|
2279
|
+
};
|
|
2280
|
+
}
|
|
2281
|
+
items.push(row);
|
|
2282
|
+
if (ctx.output.measure(page()) > ctx.output.outputTokens) {
|
|
2283
|
+
items.pop();
|
|
2284
|
+
after = priorAfter;
|
|
2285
|
+
break;
|
|
2286
|
+
}
|
|
2287
|
+
if (!memberComplete) {
|
|
2288
|
+
if (source.view === "status" && !item.taskId) continue;
|
|
2289
|
+
if (nextPosition) {
|
|
2290
|
+
seq = nextPosition.seq;
|
|
2291
|
+
offset = nextPosition.offset;
|
|
2292
|
+
} else {
|
|
2293
|
+
seq = 0;
|
|
2294
|
+
offset = 0;
|
|
2295
|
+
}
|
|
2296
|
+
break;
|
|
2297
|
+
}
|
|
2298
|
+
at++;
|
|
2299
|
+
after = 0;
|
|
2300
|
+
seq = 0;
|
|
2301
|
+
offset = 0;
|
|
2302
|
+
}
|
|
2303
|
+
complete = at === source.items.length;
|
|
2304
|
+
} else if (kind === "acp_instances") {
|
|
2305
|
+
let found;
|
|
2306
|
+
try {
|
|
2307
|
+
found = store.instanceSummaryPage({
|
|
2308
|
+
after: instanceAfter,
|
|
2309
|
+
source: query.source,
|
|
2310
|
+
limit: source.limit
|
|
2311
|
+
});
|
|
2312
|
+
} catch (cause) {
|
|
2313
|
+
return restart(cause instanceof Error ? cause.message : "ACP instance source changed");
|
|
2314
|
+
}
|
|
2315
|
+
query.source = found.source;
|
|
2316
|
+
for (const row of found.items) {
|
|
2317
|
+
items.push(row);
|
|
2318
|
+
if (ctx.output.measure(page()) > ctx.output.outputTokens) {
|
|
2319
|
+
items.pop();
|
|
2320
|
+
break;
|
|
2321
|
+
}
|
|
2322
|
+
instanceAfter = row.instanceId;
|
|
2323
|
+
}
|
|
2324
|
+
complete = found.complete && items.length === found.items.length;
|
|
2325
|
+
} else {
|
|
2326
|
+
let found;
|
|
2327
|
+
try {
|
|
2328
|
+
found = manager.summaryDelegations(ctx.sessionId, {
|
|
2329
|
+
after,
|
|
2330
|
+
upper: query.upper,
|
|
2331
|
+
source: query.source,
|
|
2332
|
+
limit: source.limit
|
|
2333
|
+
});
|
|
2334
|
+
} catch (cause) {
|
|
2335
|
+
return restart(cause instanceof Error ? cause.message : "ACP delegation source changed");
|
|
2336
|
+
}
|
|
2337
|
+
query.source = found.source;
|
|
2338
|
+
query.upper = found.upper;
|
|
2339
|
+
for (const item of found.items) {
|
|
2340
|
+
const row = {
|
|
2341
|
+
delegation: item.value,
|
|
2342
|
+
latest: store.summary(item.value.delegationId) ?? null
|
|
2343
|
+
};
|
|
2344
|
+
items.push(row);
|
|
2345
|
+
if (ctx.output.measure(page()) > ctx.output.outputTokens) {
|
|
2346
|
+
items.pop();
|
|
2347
|
+
break;
|
|
2348
|
+
}
|
|
2349
|
+
after = item.key;
|
|
2350
|
+
}
|
|
2351
|
+
if (items.length === found.items.length) after = found.after;
|
|
2352
|
+
complete = found.complete && items.length === found.items.length;
|
|
2353
|
+
}
|
|
2354
|
+
if (!items.length && !complete && kind !== "acp_list" || ctx.output.measure(page()) > ctx.output.outputTokens) return error("page_too_small", "No complete ACP member fits this allowance.", ctx.output.outputTokens < ctx.output.maximumTokens ? {
|
|
2355
|
+
tool: kind,
|
|
2356
|
+
arguments: {
|
|
2357
|
+
cursor: id,
|
|
2358
|
+
outputTokens: ctx.output.maximumTokens
|
|
2359
|
+
}
|
|
2360
|
+
} : null);
|
|
2361
|
+
const result = page();
|
|
2362
|
+
const growth = Buffer.byteLength(result.content) + 512;
|
|
2363
|
+
try {
|
|
2364
|
+
await query.lease.grow(ctx, {
|
|
2365
|
+
bytes: growth,
|
|
2366
|
+
scratchBytes: 0
|
|
2367
|
+
});
|
|
2368
|
+
query.bytes += growth;
|
|
2369
|
+
} catch (failure) {
|
|
2370
|
+
if (resources.isAdmissionFailure(failure)) throw failure;
|
|
2371
|
+
close(query);
|
|
2372
|
+
return error("query_capacity_exceeded", "ACP cursor cache exceeds temporary capacity.");
|
|
2373
|
+
}
|
|
2374
|
+
ctx.output.acceptExact(result);
|
|
2375
|
+
query.lease.retain({
|
|
2376
|
+
reason: "public-cursor",
|
|
2377
|
+
idleMs: 6e5,
|
|
2378
|
+
maxAgeMs: 36e5
|
|
2379
|
+
});
|
|
2380
|
+
selected.result = result;
|
|
2381
|
+
if (!complete) cursors.set(nextId, {
|
|
2382
|
+
query,
|
|
2383
|
+
member: at,
|
|
2384
|
+
after,
|
|
2385
|
+
instanceAfter,
|
|
2386
|
+
seq,
|
|
2387
|
+
offset
|
|
2388
|
+
});
|
|
2389
|
+
return result;
|
|
2390
|
+
});
|
|
2391
|
+
} catch (cause) {
|
|
2392
|
+
await query.lease.close("failed");
|
|
2393
|
+
throw cause;
|
|
2394
|
+
}
|
|
2395
|
+
}
|
|
2396
|
+
});
|
|
2397
|
+
const wrap = (definition) => ({
|
|
2398
|
+
...definition,
|
|
2399
|
+
execute(input, ctx) {
|
|
2400
|
+
const pending = queue.then(() => definition.execute(input, ctx));
|
|
2401
|
+
queue = pending.catch(() => {});
|
|
2402
|
+
return pending;
|
|
2403
|
+
}
|
|
2404
|
+
});
|
|
2405
|
+
return {
|
|
2406
|
+
get: wrap(tool("acp_get")),
|
|
2407
|
+
list: wrap(tool("acp_list")),
|
|
2408
|
+
instances: wrap(tool("acp_instances")),
|
|
2409
|
+
async close() {
|
|
2410
|
+
await queue;
|
|
2411
|
+
for (const query of new Set([...cursors.values()].map((cursor) => cursor.query))) await close(query);
|
|
2412
|
+
}
|
|
2413
|
+
};
|
|
2414
|
+
}
|
|
2415
|
+
//#endregion
|
|
2416
|
+
//#region src/tools.ts
|
|
2417
|
+
/** Array tool intents, one launch approval and bounded paginated reads. */
|
|
2418
|
+
/** One immutable external task proposal. */
|
|
2419
|
+
const Start = z.strictObject({
|
|
2420
|
+
instanceId: z.string().min(1).describe("Enabled adapter identity from acp_instances."),
|
|
2421
|
+
cwd: z.string().min(1).describe("Absolute working directory for the external task."),
|
|
2422
|
+
task: z.string().min(1).describe("Self-contained task with goal, relevant facts and requested result."),
|
|
2423
|
+
model: z.string().optional().describe("Remote adapter model identity; omit to retain its default."),
|
|
2424
|
+
config: z.record(z.string(), z.string()).optional().describe("Remote model or thought-level settings accepted by the adapter; permission modes are forbidden.")
|
|
2425
|
+
});
|
|
2426
|
+
/** Positive safe page sizes are normalized by the owner rather than refused at the cap. */
|
|
2427
|
+
const Page = z.strictObject({
|
|
2428
|
+
offset: z.number().int().nonnegative().default(0),
|
|
2429
|
+
limit: z.number().int().min(1).default(50)
|
|
2430
|
+
});
|
|
2431
|
+
/** The browser management list page, independent of model cursor pagination. */
|
|
2432
|
+
function listPage(manager, sessionId, offset, requested) {
|
|
2433
|
+
const limit = Math.min(200, requested);
|
|
2434
|
+
const entries = manager.list(sessionId, offset, limit);
|
|
2435
|
+
return {
|
|
2436
|
+
entries,
|
|
2437
|
+
offset,
|
|
2438
|
+
limit,
|
|
2439
|
+
nextOffset: entries.length === limit && manager.list(sessionId, offset + entries.length, 1).length > 0 ? offset + entries.length : null,
|
|
2440
|
+
...requested > limit ? { notice: `limit clamped from ${requested} to ${limit}` } : {}
|
|
2441
|
+
};
|
|
2442
|
+
}
|
|
2443
|
+
/** Registers all collection tools while retaining approved physical process factories. */
|
|
2444
|
+
function registerCollectionTools(deps) {
|
|
2445
|
+
const { register, store, manager, services } = deps;
|
|
2446
|
+
const pages = acpReadTools(store, manager, deps.resources, deps.signal);
|
|
2447
|
+
deps.onDispose(() => pages.close());
|
|
2448
|
+
register(pages.get);
|
|
2449
|
+
register(pages.list);
|
|
2450
|
+
register(pages.instances);
|
|
2451
|
+
register({
|
|
2452
|
+
name: "acp_stop",
|
|
2453
|
+
preload: false,
|
|
2454
|
+
outputSchema: collectionResult(z.strictObject({
|
|
2455
|
+
stopped: z.boolean(),
|
|
2456
|
+
closed: z.boolean()
|
|
2457
|
+
})),
|
|
2458
|
+
deliveryKind: "receipt",
|
|
2459
|
+
description: "Stop or close independent external tasks, returning actual per-member cleanup results.",
|
|
2460
|
+
inputSchema: collectionInput({ items: z.array(z.strictObject({
|
|
2461
|
+
delegationId: z.string().min(1).describe("Owned delegation identity to stop."),
|
|
2462
|
+
close: z.boolean().default(false).describe("Also cancel its queue and close the retained connection; default false.")
|
|
2463
|
+
})).min(1).max(64).describe("Ordered stop targets; one to 64 members, with duplicate resources settled once.") }, "items"),
|
|
2464
|
+
async execute(input, call) {
|
|
2465
|
+
const ids = input.items.map((item) => item.delegationId);
|
|
2466
|
+
const batch = await manager.collection(ids, () => settleCollection(ids, async (id, index) => {
|
|
2467
|
+
const before = manager.get(call.sessionId, id, 0, 200);
|
|
2468
|
+
if (input.items[index].close) await manager.close(call.sessionId, id);
|
|
2469
|
+
else await manager.stop(call.sessionId, id);
|
|
2470
|
+
return {
|
|
2471
|
+
stopped: before.tasks.some((task) => task.state !== "finished" && task.state !== "queued"),
|
|
2472
|
+
closed: input.items[index].close
|
|
2473
|
+
};
|
|
2474
|
+
}));
|
|
2475
|
+
return {
|
|
2476
|
+
content: JSON.stringify(batch),
|
|
2477
|
+
delivery: {
|
|
2478
|
+
kind: "receipt",
|
|
2479
|
+
outputTokens: call.output.outputTokens,
|
|
2480
|
+
execution: batch.results.some((row) => row.ok) ? "committed" : "unknown"
|
|
2481
|
+
}
|
|
2482
|
+
};
|
|
2483
|
+
}
|
|
2484
|
+
});
|
|
2485
|
+
register({
|
|
2486
|
+
name: "acp_delegate",
|
|
2487
|
+
preload: false,
|
|
2488
|
+
outputSchema: z.union([collectionResult(z.strictObject({
|
|
2489
|
+
id: z.string(),
|
|
2490
|
+
delegationId: z.string(),
|
|
2491
|
+
state: z.string(),
|
|
2492
|
+
targetGeneration: z.number(),
|
|
2493
|
+
createdAt: z.number(),
|
|
2494
|
+
revision: z.number()
|
|
2495
|
+
})), z.string()]),
|
|
2496
|
+
deliveryKind: "receipt",
|
|
2497
|
+
description: "Propose an ordered collection of independent external tasks. One approval binds every executable plan, instance revision, real cwd, model/config and task digest before any launch.",
|
|
2498
|
+
inputSchema: collectionInput({ items: z.array(Start).min(1).max(8).describe("One to eight independent external tasks covered by one launch approval.") }, "items"),
|
|
2499
|
+
async execute(input, call) {
|
|
2500
|
+
const requests = [];
|
|
2501
|
+
const prepared = /* @__PURE__ */ new Map();
|
|
2502
|
+
const failures = /* @__PURE__ */ new Map();
|
|
2503
|
+
for (const [index, item] of input.items.entries()) try {
|
|
2504
|
+
const instance = store.instances().find((row) => row.id === item.instanceId && row.enabled);
|
|
2505
|
+
if (!instance) throw new Error("instance-missing");
|
|
2506
|
+
const launch = await prepareLaunch(call, instance, item.cwd, {
|
|
2507
|
+
...services,
|
|
2508
|
+
approval: {
|
|
2509
|
+
...services.approval,
|
|
2510
|
+
questionId: (id) => services.approval.questionId(id),
|
|
2511
|
+
decide(_authority, request) {
|
|
2512
|
+
requests.push(request);
|
|
2513
|
+
return {
|
|
2514
|
+
kind: "result",
|
|
2515
|
+
result: { kind: "allowed-once" }
|
|
2516
|
+
};
|
|
2517
|
+
}
|
|
2518
|
+
}
|
|
2519
|
+
});
|
|
2520
|
+
if ("result" in launch) throw new Error("launch-refused");
|
|
2521
|
+
prepared.set(index, {
|
|
2522
|
+
instance,
|
|
2523
|
+
launch
|
|
2524
|
+
});
|
|
2525
|
+
} catch (error) {
|
|
2526
|
+
failures.set(index, error instanceof Error ? error : /* @__PURE__ */ new Error("launch-refused"));
|
|
2527
|
+
}
|
|
2528
|
+
const admit = async () => {
|
|
2529
|
+
if (prepared.size) {
|
|
2530
|
+
const key = `acp-batch:${createHash("sha256").update(JSON.stringify({
|
|
2531
|
+
plans: requests.map((request) => request.id),
|
|
2532
|
+
items: input.items
|
|
2533
|
+
})).digest("hex")}`;
|
|
2534
|
+
const decision = services.approval.decide(call, {
|
|
2535
|
+
id: key,
|
|
2536
|
+
subject: `Delegate ${prepared.size} external tasks`,
|
|
2537
|
+
reason: requests.map((request) => request.reason).join("\n"),
|
|
2538
|
+
accepts: [
|
|
2539
|
+
"allowed-once",
|
|
2540
|
+
"allowed-session",
|
|
2541
|
+
"allowed-always",
|
|
2542
|
+
"rejected"
|
|
2543
|
+
],
|
|
2544
|
+
remember: {
|
|
2545
|
+
key,
|
|
2546
|
+
label: `Launch ${prepared.size} ACP tasks`
|
|
2547
|
+
}
|
|
2548
|
+
});
|
|
2549
|
+
if (decision.kind === "ask") return decision.result;
|
|
2550
|
+
if (!decision.result.kind.startsWith("allowed-")) return {
|
|
2551
|
+
content: decision.result.kind === "record-failed" ? `ACP approval recording failed: ${decision.result.message}` : "ACP launch was not authorized.",
|
|
2552
|
+
isError: true
|
|
2553
|
+
};
|
|
2554
|
+
}
|
|
2555
|
+
const batch = await manager.collection([], () => settleCollection(input.items.map((item) => item.instanceId), async (_id, index) => {
|
|
2556
|
+
const failed = failures.get(index);
|
|
2557
|
+
if (failed) throw failed;
|
|
2558
|
+
const plan = prepared.get(index);
|
|
2559
|
+
const current = store.instances().find((row) => row.id === plan.instance.id && row.enabled);
|
|
2560
|
+
if (!current || current.revision !== plan.instance.revision) throw new Error("configuration-changed: request launch again");
|
|
2561
|
+
const task = await manager.start({
|
|
2562
|
+
...input.items[index],
|
|
2563
|
+
sessionId: call.sessionId,
|
|
2564
|
+
requestKey: `${call.turn}:${call.toolCallId}:${index}`
|
|
2565
|
+
}, async () => {
|
|
2566
|
+
const current = store.instances().find((row) => row.id === plan.instance.id && row.enabled);
|
|
2567
|
+
if (!current || current.revision !== plan.instance.revision) throw new Error("configuration-changed: request launch again");
|
|
2568
|
+
return plan.launch.launch();
|
|
2569
|
+
}, plan.launch.execution, plan.launch.release);
|
|
2570
|
+
prepared.delete(index);
|
|
2571
|
+
return {
|
|
2572
|
+
id: task.id,
|
|
2573
|
+
delegationId: task.delegationId,
|
|
2574
|
+
state: task.state,
|
|
2575
|
+
targetGeneration: task.targetGeneration,
|
|
2576
|
+
createdAt: task.createdAt,
|
|
2577
|
+
revision: task.revision
|
|
2578
|
+
};
|
|
2579
|
+
}), {
|
|
2580
|
+
sessionId: call.sessionId,
|
|
2581
|
+
requestKeyPrefix: `${call.turn}:${call.toolCallId}:`
|
|
2582
|
+
});
|
|
2583
|
+
return {
|
|
2584
|
+
content: JSON.stringify(batch),
|
|
2585
|
+
delivery: {
|
|
2586
|
+
kind: "receipt",
|
|
2587
|
+
outputTokens: call.output.outputTokens,
|
|
2588
|
+
execution: batch.results.some((row) => row.ok) ? "committed" : "not-started"
|
|
2589
|
+
}
|
|
2590
|
+
};
|
|
2591
|
+
};
|
|
2592
|
+
const [outcome] = await Promise.allSettled([admit()]);
|
|
2593
|
+
const cleanupFailures = (await Promise.allSettled([...prepared.values()].map((plan) => plan.launch.release()))).filter((item) => item.status === "rejected").map((item) => item.reason);
|
|
2594
|
+
if (cleanupFailures.length) throw new AggregateError([...outcome.status === "rejected" ? [outcome.reason] : [], ...cleanupFailures], "ACP preparation cleanup failed");
|
|
2595
|
+
if (outcome.status === "rejected") throw outcome.reason;
|
|
2596
|
+
return outcome.value;
|
|
2597
|
+
}
|
|
2598
|
+
});
|
|
2599
|
+
}
|
|
2600
|
+
//#endregion
|
|
1277
2601
|
//#region src/index.ts
|
|
1278
2602
|
const Session = z.object({ sessionId: z.string().min(1) }).strict();
|
|
1279
2603
|
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
2604
|
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)
|
|
2605
|
+
delegationId: z.string().describe("Owned retained delegation to continue."),
|
|
2606
|
+
task: z.string().min(1).describe("Self-contained follow-up task; an accepted task is queued and must not be resubmitted.")
|
|
1294
2607
|
}).strict();
|
|
1295
2608
|
const Result = z.unknown();
|
|
2609
|
+
const Changed = z.strictObject({
|
|
2610
|
+
delegationIds: z.array(z.string()).max(64),
|
|
2611
|
+
invalidated: z.boolean()
|
|
2612
|
+
});
|
|
1296
2613
|
const acpPlugin = {
|
|
1297
2614
|
name: "@eum-agent/integration-acp",
|
|
1298
2615
|
configSchema: z.object({ disabled: z.array(z.enum(TOOL_NAMES)).default([]) }).strict().optional(),
|
|
@@ -1304,7 +2621,9 @@ const acpPlugin = {
|
|
|
1304
2621
|
"protocol-processes",
|
|
1305
2622
|
"session-context",
|
|
1306
2623
|
"session-delivery",
|
|
1307
|
-
"work-lifecycle"
|
|
2624
|
+
"work-lifecycle",
|
|
2625
|
+
"owner-operations",
|
|
2626
|
+
"query-resources"
|
|
1308
2627
|
],
|
|
1309
2628
|
async apply(ctx, config) {
|
|
1310
2629
|
const register = (definition) => config?.disabled.includes(definition.name) ? () => {} : ctx.tools.register(definition);
|
|
@@ -1322,13 +2641,13 @@ const acpPlugin = {
|
|
|
1322
2641
|
const changed = ctx.client.registerFrame({
|
|
1323
2642
|
name: "changed",
|
|
1324
2643
|
delivery: "session",
|
|
1325
|
-
payload:
|
|
2644
|
+
payload: Changed
|
|
1326
2645
|
});
|
|
1327
2646
|
const manager = createAcpManager({
|
|
1328
2647
|
store,
|
|
1329
2648
|
sessions,
|
|
1330
2649
|
delivery: ctx.services.get("session-delivery"),
|
|
1331
|
-
changed: (id, value) => changed.emit(id, value),
|
|
2650
|
+
changed: (id, value) => changed.emit(id, Changed.parse(value)),
|
|
1332
2651
|
ask: (sessionId, request, options) => ctx.sessions.ask(sessionId, request, options)
|
|
1333
2652
|
});
|
|
1334
2653
|
await services.processes.recover();
|
|
@@ -1356,38 +2675,27 @@ const acpPlugin = {
|
|
|
1356
2675
|
const find = (caller, id) => {
|
|
1357
2676
|
return manager.get(caller, id);
|
|
1358
2677
|
};
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
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
|
-
}
|
|
2678
|
+
registerCollectionTools({
|
|
2679
|
+
register,
|
|
2680
|
+
store,
|
|
2681
|
+
manager,
|
|
2682
|
+
services,
|
|
2683
|
+
resources: ctx.services.get("query-resources"),
|
|
2684
|
+
signal: ctx.signal,
|
|
2685
|
+
onDispose: (cleanup) => ctx.onDispose(cleanup)
|
|
1388
2686
|
});
|
|
1389
2687
|
register({
|
|
1390
2688
|
name: "acp_send",
|
|
2689
|
+
preload: false,
|
|
2690
|
+
outputSchema: z.strictObject({
|
|
2691
|
+
id: z.string(),
|
|
2692
|
+
delegationId: z.string(),
|
|
2693
|
+
state: z.string(),
|
|
2694
|
+
targetGeneration: z.number(),
|
|
2695
|
+
createdAt: z.number(),
|
|
2696
|
+
revision: z.number()
|
|
2697
|
+
}),
|
|
2698
|
+
deliveryKind: "receipt",
|
|
1391
2699
|
description: "Continue an external delegation. Tasks queue FIFO; reconnecting requires renewed launch authorization.",
|
|
1392
2700
|
inputSchema: Send,
|
|
1393
2701
|
async execute(input, call) {
|
|
@@ -1401,52 +2709,22 @@ const acpPlugin = {
|
|
|
1401
2709
|
if ("result" in prepared) return prepared.result;
|
|
1402
2710
|
admitted = prepared;
|
|
1403
2711
|
}
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
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." };
|
|
2712
|
+
const task = await manager.send(call.sessionId, row.id, input.task, `${call.turn}:${call.toolCallId}`, admitted);
|
|
2713
|
+
return {
|
|
2714
|
+
content: JSON.stringify({
|
|
2715
|
+
id: task.id,
|
|
2716
|
+
delegationId: task.delegationId,
|
|
2717
|
+
state: task.state,
|
|
2718
|
+
targetGeneration: task.targetGeneration,
|
|
2719
|
+
createdAt: task.createdAt,
|
|
2720
|
+
revision: task.revision
|
|
2721
|
+
}),
|
|
2722
|
+
delivery: {
|
|
2723
|
+
kind: "receipt",
|
|
2724
|
+
outputTokens: call.output.outputTokens,
|
|
2725
|
+
execution: "committed"
|
|
2726
|
+
}
|
|
2727
|
+
};
|
|
1450
2728
|
}
|
|
1451
2729
|
});
|
|
1452
2730
|
const tickets = /* @__PURE__ */ new Map();
|
|
@@ -1481,7 +2759,10 @@ const acpPlugin = {
|
|
|
1481
2759
|
}
|
|
1482
2760
|
if (input.probe) {
|
|
1483
2761
|
const root = sessions.resolve(input.sessionId).rootSessionId;
|
|
1484
|
-
if (probes.has(root))
|
|
2762
|
+
if (probes.has(root)) {
|
|
2763
|
+
await prepared.release();
|
|
2764
|
+
throw new Error("preflight-in-progress");
|
|
2765
|
+
}
|
|
1485
2766
|
const work = (async () => {
|
|
1486
2767
|
const process = await prepared.launch();
|
|
1487
2768
|
try {
|
|
@@ -1507,7 +2788,7 @@ const acpPlugin = {
|
|
|
1507
2788
|
probes.delete(root);
|
|
1508
2789
|
}
|
|
1509
2790
|
}
|
|
1510
|
-
return { task: input.delegationId ? manager.send(input.sessionId, input.delegationId, input.task, input.requestKey, prepared) : await manager.start(input, prepared.launch, prepared.execution) };
|
|
2791
|
+
return { task: input.delegationId ? await manager.send(input.sessionId, input.delegationId, input.task, input.requestKey, prepared) : await manager.start(input, prepared.launch, prepared.execution, prepared.release) };
|
|
1511
2792
|
};
|
|
1512
2793
|
ctx.client.registerMethod({
|
|
1513
2794
|
name: "preflight",
|
|
@@ -1592,7 +2873,7 @@ const acpPlugin = {
|
|
|
1592
2873
|
name: "list",
|
|
1593
2874
|
params: Session.extend(Page.shape),
|
|
1594
2875
|
result: Result,
|
|
1595
|
-
handle: (input) => manager
|
|
2876
|
+
handle: (input) => listPage(manager, input.sessionId, input.offset, input.limit)
|
|
1596
2877
|
});
|
|
1597
2878
|
ctx.client.registerMethod({
|
|
1598
2879
|
name: "get",
|
|
@@ -1609,24 +2890,7 @@ const acpPlugin = {
|
|
|
1609
2890
|
result: Result,
|
|
1610
2891
|
handle: (input) => manager.send(input.sessionId, input.delegationId, input.task, input.requestKey)
|
|
1611
2892
|
});
|
|
1612
|
-
ctx
|
|
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
|
-
});
|
|
2893
|
+
registerDelegationCollections(ctx, manager);
|
|
1630
2894
|
ctx.client.registerMethod({
|
|
1631
2895
|
name: "updates",
|
|
1632
2896
|
params: Target.extend({
|
|
@@ -1671,52 +2935,7 @@ const acpPlugin = {
|
|
|
1671
2935
|
}).strict(),
|
|
1672
2936
|
handle: ({ command }) => inspectCommand(command, commands)
|
|
1673
2937
|
});
|
|
1674
|
-
ctx
|
|
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
|
-
});
|
|
2938
|
+
registerPresetCollections(ctx, store, commands);
|
|
1720
2939
|
ctx.client.registerMethod({
|
|
1721
2940
|
name: "saveInstance",
|
|
1722
2941
|
params: InstanceSchema,
|
|
@@ -1730,15 +2949,6 @@ const acpPlugin = {
|
|
|
1730
2949
|
});
|
|
1731
2950
|
}
|
|
1732
2951
|
});
|
|
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
2952
|
const ui = fileURLToPath(new URL("../ui/ui.js", import.meta.url));
|
|
1743
2953
|
if (existsSync(ui)) ctx.client.registerUi({ module: ui });
|
|
1744
2954
|
}
|