@eum-agent/integration-acp 0.0.0-stage → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/LICENSES.txt +666 -0
- package/dist/adapters/codex-acp.js +31004 -0
- package/dist/adapters/codex.js +14 -0
- package/dist/index.js +2957 -0
- package/package.json +49 -3
- package/ui/ui.js +1621 -0
- package/README.md +0 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,2957 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
3
|
+
import { accessSync, constants, existsSync, readFileSync, realpathSync, statSync } from "node:fs";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
import { Readable, Transform, Writable } from "node:stream";
|
|
7
|
+
import { setImmediate } from "node:timers/promises";
|
|
8
|
+
import { ClientSideConnection, PROTOCOL_VERSION, ndJsonStream } from "@agentclientprotocol/sdk";
|
|
9
|
+
import protocolSchema from "@agentclientprotocol/sdk/schema/schema.json" with { type: "json" };
|
|
10
|
+
import { mkdtemp, rm } from "node:fs/promises";
|
|
11
|
+
import { tmpdir } from "node:os";
|
|
12
|
+
import { dirname, join, posix, resolve, win32 } from "node:path";
|
|
13
|
+
//#region src/client.ts
|
|
14
|
+
const Update = z.fromJSONSchema({
|
|
15
|
+
$ref: "#/$defs/SessionNotification",
|
|
16
|
+
$defs: protocolSchema.$defs
|
|
17
|
+
});
|
|
18
|
+
const Permission = z.fromJSONSchema({
|
|
19
|
+
$ref: "#/$defs/RequestPermissionRequest",
|
|
20
|
+
$defs: protocolSchema.$defs
|
|
21
|
+
});
|
|
22
|
+
/** Times out protocol control operations without retrying or exposing remote error text. */
|
|
23
|
+
async function control(promise, ms = 3e4) {
|
|
24
|
+
let timer;
|
|
25
|
+
try {
|
|
26
|
+
return await Promise.race([promise, new Promise((_, reject) => {
|
|
27
|
+
timer = setTimeout(() => reject(/* @__PURE__ */ new Error("protocol-timeout")), ms);
|
|
28
|
+
})]);
|
|
29
|
+
} finally {
|
|
30
|
+
if (timer) clearTimeout(timer);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
/** Initializes ACP over raw pipes, rejecting messages above 8 MiB before JSON decoding. */
|
|
34
|
+
async function connectAcp(process, callbacks) {
|
|
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
|
+
};
|
|
55
|
+
const pending = /* @__PURE__ */ new Set();
|
|
56
|
+
const bounded = new Transform({
|
|
57
|
+
transform(chunk, _encoding, done) {
|
|
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;
|
|
71
|
+
}
|
|
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);
|
|
112
|
+
}
|
|
113
|
+
done();
|
|
114
|
+
})().catch(done);
|
|
115
|
+
},
|
|
116
|
+
flush(done) {
|
|
117
|
+
done(bufferedBytes ? /* @__PURE__ */ new Error("truncated-protocol-message") : void 0);
|
|
118
|
+
}
|
|
119
|
+
});
|
|
120
|
+
process.stdout.pipe(bounded);
|
|
121
|
+
process.stdout.on("close", () => {
|
|
122
|
+
if (!process.stdout.readableEnded) bounded.destroy();
|
|
123
|
+
});
|
|
124
|
+
process.stdout.on("error", () => bounded.destroy(/* @__PURE__ */ new Error("connection-lost")));
|
|
125
|
+
bounded.on("error", () => {
|
|
126
|
+
process.stop().catch(() => {});
|
|
127
|
+
});
|
|
128
|
+
const raw = ndJsonStream(Writable.toWeb(process.stdin), Readable.toWeb(bounded));
|
|
129
|
+
const writer = raw.writable.getWriter();
|
|
130
|
+
const client = new ClientSideConnection(() => ({
|
|
131
|
+
async requestPermission(request) {
|
|
132
|
+
try {
|
|
133
|
+
return await callbacks.permission(request);
|
|
134
|
+
} catch {
|
|
135
|
+
process.stop().catch(() => {});
|
|
136
|
+
return { outcome: { outcome: "cancelled" } };
|
|
137
|
+
}
|
|
138
|
+
},
|
|
139
|
+
sessionUpdate(notification) {
|
|
140
|
+
try {
|
|
141
|
+
callbacks.update(notification);
|
|
142
|
+
} catch {
|
|
143
|
+
process.stop().catch(() => {});
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}), {
|
|
147
|
+
readable: raw.readable,
|
|
148
|
+
writable: new WritableStream({
|
|
149
|
+
async write(value) {
|
|
150
|
+
if (Buffer.byteLength(JSON.stringify(value)) > 8388608) throw new Error("protocol-message-limit");
|
|
151
|
+
if ("method" in value && "id" in value && value.id !== null) pending.add(value.id);
|
|
152
|
+
try {
|
|
153
|
+
await control(writer.write(value));
|
|
154
|
+
} catch {
|
|
155
|
+
process.stop().catch(() => {});
|
|
156
|
+
throw new Error("protocol-write-failed");
|
|
157
|
+
}
|
|
158
|
+
},
|
|
159
|
+
close: () => writer.close(),
|
|
160
|
+
abort: () => writer.abort(/* @__PURE__ */ new Error("connection-closed"))
|
|
161
|
+
})
|
|
162
|
+
});
|
|
163
|
+
try {
|
|
164
|
+
const initialized = await control(client.initialize({
|
|
165
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
166
|
+
clientCapabilities: {},
|
|
167
|
+
clientInfo: {
|
|
168
|
+
name: "yaoguang",
|
|
169
|
+
version: "1.0.0"
|
|
170
|
+
}
|
|
171
|
+
}));
|
|
172
|
+
if (initialized.protocolVersion !== PROTOCOL_VERSION) throw new Error("protocol-version-mismatch");
|
|
173
|
+
return {
|
|
174
|
+
client,
|
|
175
|
+
initialized,
|
|
176
|
+
process
|
|
177
|
+
};
|
|
178
|
+
} catch {
|
|
179
|
+
await process.stop();
|
|
180
|
+
throw new Error("initialize-failed");
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
//#endregion
|
|
184
|
+
//#region src/adapters.ts
|
|
185
|
+
const require = createRequire(import.meta.url);
|
|
186
|
+
const adapters = {
|
|
187
|
+
claude: {
|
|
188
|
+
package: "@zed-industries/claude-agent-acp",
|
|
189
|
+
bin: "claude-agent-acp",
|
|
190
|
+
variable: "CLAUDE_CODE_EXECUTABLE"
|
|
191
|
+
},
|
|
192
|
+
codex: {
|
|
193
|
+
package: "@agentclientprotocol/codex-acp",
|
|
194
|
+
bin: "codex-acp",
|
|
195
|
+
variable: "CODEX_PATH"
|
|
196
|
+
}
|
|
197
|
+
};
|
|
198
|
+
/** Resolves the installed adapter without importing or executing its program. */
|
|
199
|
+
function bundledAdapter(id) {
|
|
200
|
+
const adapter = adapters[id];
|
|
201
|
+
if (id === "codex") {
|
|
202
|
+
const entry = fileURLToPath(new URL("../dist/adapters/codex.js", import.meta.url));
|
|
203
|
+
if (!statSync(entry).isFile()) throw new Error("bundled-adapter-entry-missing");
|
|
204
|
+
accessSync(entry, constants.R_OK);
|
|
205
|
+
return {
|
|
206
|
+
entry,
|
|
207
|
+
root: dirname(entry),
|
|
208
|
+
variable: adapter.variable
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
const manifestPath = require.resolve(`${adapter.package}/package.json`);
|
|
212
|
+
const bin = JSON.parse(readFileSync(manifestPath, "utf8")).bin[adapter.bin];
|
|
213
|
+
if (!bin) throw new Error("bundled-adapter-entry-missing");
|
|
214
|
+
const root = dirname(manifestPath);
|
|
215
|
+
const entry = resolve(root, bin);
|
|
216
|
+
if (!statSync(entry).isFile()) throw new Error("bundled-adapter-entry-missing");
|
|
217
|
+
accessSync(entry, constants.R_OK);
|
|
218
|
+
return {
|
|
219
|
+
entry,
|
|
220
|
+
root,
|
|
221
|
+
variable: adapter.variable
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
/** Resolves bundled adapters at launch so stored instances survive plugin relocation and updates.
|
|
225
|
+
* For bundled instances command is the local CLI; args belong to the adapter.
|
|
226
|
+
* The caller supplies the same host Node executable used to admit this launch.
|
|
227
|
+
*/
|
|
228
|
+
function instanceLaunch(instance, execPath) {
|
|
229
|
+
if (!instance.adapter) return {
|
|
230
|
+
command: instance.command,
|
|
231
|
+
args: instance.args,
|
|
232
|
+
env: instance.env,
|
|
233
|
+
read: [instance.command]
|
|
234
|
+
};
|
|
235
|
+
const adapter = bundledAdapter(instance.adapter);
|
|
236
|
+
return {
|
|
237
|
+
command: execPath,
|
|
238
|
+
args: [adapter.entry, ...instance.args],
|
|
239
|
+
env: {
|
|
240
|
+
...instance.env,
|
|
241
|
+
[adapter.variable]: instance.command
|
|
242
|
+
},
|
|
243
|
+
read: [
|
|
244
|
+
execPath,
|
|
245
|
+
adapter.root,
|
|
246
|
+
instance.command
|
|
247
|
+
]
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
//#endregion
|
|
251
|
+
//#region src/launch.ts
|
|
252
|
+
/** Rejects relative paths, reserved variables, credentials and invalid values before launch. */
|
|
253
|
+
function validateInstance(instance, platform = process.platform) {
|
|
254
|
+
const absolute = (path) => platform === "win32" ? /^(?:[A-Za-z]:[\\/]|[\\/]{2}(?![?.][\\/])[^\\/]+[\\/][^\\/]+(?:[\\/]|$))/.test(path) && win32.isAbsolute(path) : posix.isAbsolute(path);
|
|
255
|
+
if (!absolute(instance.command) || instance.command.includes("\0") || instance.authPaths.some((item) => !absolute(item.path) || item.path.includes("\0"))) throw new Error("absolute-path-required");
|
|
256
|
+
if (instance.args.some((arg) => arg.includes("\0"))) throw new Error("invalid-command-argument");
|
|
257
|
+
for (const [key, value] of Object.entries(instance.env)) {
|
|
258
|
+
if (/^(?:https?|all|ftp|no)_proxy$/i.test(key)) throw new Error("proxy-environment-managed-by-gateway");
|
|
259
|
+
if (!(platform === "win32" ? /^[A-Za-z_][A-Za-z0-9_]*$/ : /^[A-Z_][A-Z0-9_]*$/).test(key) || /KEY|SECRET|TOKEN|PASSWORD|YAOGUANG/i.test(key)) throw new Error("credential-environment-forbidden");
|
|
260
|
+
if (value.includes("\0")) throw new Error("invalid-environment-input");
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
/** Authorizes the effective argv, real cwd, environment names and mode, then rechecks admission. */
|
|
264
|
+
async function prepareLaunch(authority, instance, cwd, services) {
|
|
265
|
+
const { commands } = services;
|
|
266
|
+
validateInstance(instance, commands.platform);
|
|
267
|
+
commands.environment([instance.env]);
|
|
268
|
+
const executable = instanceLaunch(instance, commands.execPath);
|
|
269
|
+
const exact = [executable.command, ...executable.args];
|
|
270
|
+
const selected = await commands.inspect(executable.command);
|
|
271
|
+
if (selected.status !== "found" || selected.path !== executable.command) throw new Error(`command-unavailable: ${selected.reason ?? "command-resolution-changed"}`);
|
|
272
|
+
if (instance.adapter) {
|
|
273
|
+
const cli = await commands.inspect(instance.command);
|
|
274
|
+
if (cli.status !== "found") throw new Error(`command-unavailable: ${cli.reason}`);
|
|
275
|
+
}
|
|
276
|
+
cwd = await commands.directory(cwd);
|
|
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;
|
|
289
|
+
});
|
|
290
|
+
return releasing;
|
|
291
|
+
};
|
|
292
|
+
const release = () => processOwnsObservation ? Promise.resolve() : closeObservation();
|
|
293
|
+
try {
|
|
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
|
|
302
|
+
};
|
|
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;
|
|
314
|
+
};
|
|
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
|
+
]);
|
|
329
|
+
};
|
|
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");
|
|
409
|
+
if (!trusted && JSON.stringify(services.sandbox.status()) !== availability) throw new Error("execution-mode-changed: request launch again");
|
|
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
|
+
}
|
|
446
|
+
});
|
|
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;
|
|
462
|
+
}
|
|
463
|
+
}
|
|
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
|
|
529
|
+
};
|
|
530
|
+
}
|
|
531
|
+
//#endregion
|
|
532
|
+
//#region src/store.ts
|
|
533
|
+
/** One user-configured, already installed and authenticated adapter command. */
|
|
534
|
+
const InstanceSchema = z.object({
|
|
535
|
+
id: z.string().regex(/^[a-z0-9][a-z0-9-]*$/),
|
|
536
|
+
label: z.string().min(1),
|
|
537
|
+
enabled: z.boolean().default(true),
|
|
538
|
+
executionMode: z.enum(["sandbox", "trusted"]).default("sandbox"),
|
|
539
|
+
adapter: z.enum(["claude", "codex"]).optional(),
|
|
540
|
+
command: z.string().min(1),
|
|
541
|
+
args: z.array(z.string()).default([]),
|
|
542
|
+
env: z.record(z.string(), z.string()).default({}),
|
|
543
|
+
authPaths: z.array(z.object({
|
|
544
|
+
path: z.string(),
|
|
545
|
+
access: z.enum(["read", "write"])
|
|
546
|
+
}).strict()).default([]),
|
|
547
|
+
networkHosts: z.array(z.string()).default([]),
|
|
548
|
+
revision: z.number().int().nonnegative().default(0)
|
|
549
|
+
}).strict();
|
|
550
|
+
/** Independent per-root limits shared by all adapter instances. */
|
|
551
|
+
const SettingsSchema = z.object({
|
|
552
|
+
maxConcurrent: z.number().int().positive().default(4),
|
|
553
|
+
maxRetainedConnections: z.number().int().positive().default(8)
|
|
554
|
+
}).strict();
|
|
555
|
+
/** Physical execution facts of an admitted ACP root, separate from its configured preference. */
|
|
556
|
+
const LaunchExecutionSchema = z.object({
|
|
557
|
+
mode: z.enum(["sandboxed", "direct"]),
|
|
558
|
+
fallbackReason: z.string().optional()
|
|
559
|
+
}).strict();
|
|
560
|
+
/** Local delegate identity, separate from the remote session id. */
|
|
561
|
+
const DelegationSchema = z.object({
|
|
562
|
+
id: z.string(),
|
|
563
|
+
parentSessionId: z.string(),
|
|
564
|
+
rootSessionId: z.string(),
|
|
565
|
+
instance: InstanceSchema,
|
|
566
|
+
cwd: z.string(),
|
|
567
|
+
model: z.string().optional(),
|
|
568
|
+
config: z.record(z.string(), z.string()).default({}),
|
|
569
|
+
capabilities: z.record(z.string(), z.unknown()).optional(),
|
|
570
|
+
configOptions: z.array(z.unknown()).optional(),
|
|
571
|
+
remoteSessionId: z.string().nullable(),
|
|
572
|
+
generation: z.string(),
|
|
573
|
+
processId: z.string().nullable(),
|
|
574
|
+
execution: LaunchExecutionSchema.nullable(),
|
|
575
|
+
connectionState: z.enum([
|
|
576
|
+
"starting",
|
|
577
|
+
"connected",
|
|
578
|
+
"closed",
|
|
579
|
+
"interrupted",
|
|
580
|
+
"cleanup-failed"
|
|
581
|
+
]),
|
|
582
|
+
createdAt: z.number()
|
|
583
|
+
}).strict();
|
|
584
|
+
/** One accepted external prompt, queued or executing. */
|
|
585
|
+
const TaskSchema = z.object({
|
|
586
|
+
id: z.string(),
|
|
587
|
+
delegationId: z.string(),
|
|
588
|
+
requestKey: z.string(),
|
|
589
|
+
targetGeneration: z.number().int().nonnegative(),
|
|
590
|
+
input: z.string(),
|
|
591
|
+
state: z.enum([
|
|
592
|
+
"queued",
|
|
593
|
+
"starting",
|
|
594
|
+
"running",
|
|
595
|
+
"awaiting-permission",
|
|
596
|
+
"stopping",
|
|
597
|
+
"finished"
|
|
598
|
+
]),
|
|
599
|
+
outcome: z.enum([
|
|
600
|
+
"completed",
|
|
601
|
+
"cancelled",
|
|
602
|
+
"failed",
|
|
603
|
+
"interrupted"
|
|
604
|
+
]).nullable(),
|
|
605
|
+
error: z.string().nullable(),
|
|
606
|
+
result: z.string(),
|
|
607
|
+
truncated: z.boolean(),
|
|
608
|
+
createdAt: z.number(),
|
|
609
|
+
revision: z.number().int()
|
|
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
|
+
});
|
|
632
|
+
/** ACP storage, always under the host-issued owner table prefix. */
|
|
633
|
+
function createAcpStore(storage) {
|
|
634
|
+
const { db, tableName } = storage;
|
|
635
|
+
const settings = tableName("settings"), instances = tableName("instance"), delegations = tableName("delegation"), tasks = tableName("task"), updates = tableName("update");
|
|
636
|
+
db.exec(`CREATE TABLE IF NOT EXISTS ${settings}(singleton INTEGER NOT NULL PRIMARY KEY CHECK(singleton=1),max_concurrent INTEGER NOT NULL CHECK(max_concurrent>0),max_retained_connections INTEGER NOT NULL CHECK(max_retained_connections>0)) STRICT;
|
|
637
|
+
CREATE TABLE IF NOT EXISTS ${instances}(id TEXT NOT NULL PRIMARY KEY,payload TEXT NOT NULL) STRICT;
|
|
638
|
+
CREATE TABLE IF NOT EXISTS ${delegations}(id TEXT NOT NULL PRIMARY KEY,root_session_id TEXT NOT NULL,parent_session_id TEXT NOT NULL,payload TEXT NOT NULL) STRICT;
|
|
639
|
+
CREATE INDEX IF NOT EXISTS ${tableName("delegation_root")} ON ${delegations}(root_session_id);
|
|
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;
|
|
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;
|
|
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`;
|
|
652
|
+
return {
|
|
653
|
+
transaction(write) {
|
|
654
|
+
db.exec("BEGIN IMMEDIATE");
|
|
655
|
+
try {
|
|
656
|
+
const result = write();
|
|
657
|
+
db.exec("COMMIT");
|
|
658
|
+
return result;
|
|
659
|
+
} catch (error) {
|
|
660
|
+
db.exec("ROLLBACK");
|
|
661
|
+
throw error;
|
|
662
|
+
}
|
|
663
|
+
},
|
|
664
|
+
settings() {
|
|
665
|
+
const row = db.prepare(`SELECT max_concurrent,max_retained_connections FROM ${settings} WHERE singleton=1`).get();
|
|
666
|
+
return SettingsSchema.parse({
|
|
667
|
+
maxConcurrent: row.max_concurrent,
|
|
668
|
+
maxRetainedConnections: row.max_retained_connections
|
|
669
|
+
});
|
|
670
|
+
},
|
|
671
|
+
setSettings(input) {
|
|
672
|
+
const value = SettingsSchema.parse(input);
|
|
673
|
+
db.prepare(`UPDATE ${settings} SET max_concurrent=?,max_retained_connections=? WHERE singleton=1`).run(value.maxConcurrent, value.maxRetainedConnections);
|
|
674
|
+
return value;
|
|
675
|
+
},
|
|
676
|
+
instances() {
|
|
677
|
+
return db.prepare(`SELECT payload FROM ${instances} ORDER BY id`).all().map((row) => InstanceSchema.parse(JSON.parse(String(row.payload))));
|
|
678
|
+
},
|
|
679
|
+
saveInstance(input) {
|
|
680
|
+
configuration++;
|
|
681
|
+
const value = InstanceSchema.parse(input);
|
|
682
|
+
db.prepare(`INSERT INTO ${instances} VALUES(?,?) ON CONFLICT(id) DO UPDATE SET payload=excluded.payload`).run(value.id, JSON.stringify(value));
|
|
683
|
+
return value;
|
|
684
|
+
},
|
|
685
|
+
removeInstance(id) {
|
|
686
|
+
configuration++;
|
|
687
|
+
db.prepare(`DELETE FROM ${instances} WHERE id=?`).run(id);
|
|
688
|
+
},
|
|
689
|
+
delegation(id) {
|
|
690
|
+
const row = db.prepare(`SELECT payload FROM ${delegations} WHERE id=?`).get(id);
|
|
691
|
+
return row ? DelegationSchema.parse(JSON.parse(String(row.payload))) : void 0;
|
|
692
|
+
},
|
|
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
|
+
}
|
|
698
|
+
const row = db.prepare(`SELECT payload FROM ${tasks} WHERE id=?`).get(id);
|
|
699
|
+
return row ? TaskSchema.parse(JSON.parse(String(row.payload))) : void 0;
|
|
700
|
+
},
|
|
701
|
+
delegations() {
|
|
702
|
+
return db.prepare(`SELECT payload FROM ${delegations} ORDER BY rowid`).all().map((row) => DelegationSchema.parse(JSON.parse(String(row.payload))));
|
|
703
|
+
},
|
|
704
|
+
saveDelegation(input) {
|
|
705
|
+
const value = DelegationSchema.parse(input);
|
|
706
|
+
if (!db.prepare(`SELECT id FROM ${delegations} WHERE id=?`).get(value.id)) membership++;
|
|
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));
|
|
708
|
+
},
|
|
709
|
+
tasks(id) {
|
|
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))));
|
|
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
|
+
},
|
|
882
|
+
saveTask(input) {
|
|
883
|
+
const value = TaskSchema.parse(input);
|
|
884
|
+
if (!db.prepare(`SELECT id FROM ${tasks} WHERE id=?`).get(value.id)) membership++;
|
|
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));
|
|
886
|
+
},
|
|
887
|
+
append(taskId, payload) {
|
|
888
|
+
const encoded = JSON.stringify(payload), bytes = Buffer.byteLength(encoded);
|
|
889
|
+
const own = !db.isTransaction;
|
|
890
|
+
if (own) db.exec("BEGIN IMMEDIATE");
|
|
891
|
+
try {
|
|
892
|
+
if (db.prepare(`UPDATE ${tasks} SET output_bytes=output_bytes+? WHERE id=? AND output_bytes+?<=33554432`).run(bytes, taskId, bytes).changes !== 1) throw new Error("task-output-limit");
|
|
893
|
+
db.prepare(`INSERT INTO ${updates}(task_id,seq,payload) SELECT ?,COALESCE(MAX(seq),0)+1,? FROM ${updates} WHERE task_id=?`).run(taskId, encoded, taskId);
|
|
894
|
+
if (own) db.exec("COMMIT");
|
|
895
|
+
} catch (error) {
|
|
896
|
+
if (own) db.exec("ROLLBACK");
|
|
897
|
+
throw error;
|
|
898
|
+
}
|
|
899
|
+
},
|
|
900
|
+
updates(taskId, after = 0) {
|
|
901
|
+
return db.prepare(`SELECT seq,payload FROM ${updates} WHERE task_id=? AND seq>? ORDER BY seq LIMIT 200`).all(taskId, after).map((row) => ({
|
|
902
|
+
seq: Number(row.seq),
|
|
903
|
+
payload: JSON.parse(String(row.payload))
|
|
904
|
+
}));
|
|
905
|
+
}
|
|
906
|
+
};
|
|
907
|
+
}
|
|
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
|
|
1151
|
+
//#region src/manager.ts
|
|
1152
|
+
/** The question id an ACP permission is asked under: one question per request. */
|
|
1153
|
+
const PERMISSION_QUESTION = "permission";
|
|
1154
|
+
/** An ACP permission as the host draws it: the delegate's label and the
|
|
1155
|
+
* tool call's title, one single-choice question whose options are ACP's
|
|
1156
|
+
* own, ids and names unchanged, so the chosen id goes back as it is. */
|
|
1157
|
+
function permissionQuestion(label, request) {
|
|
1158
|
+
const subject = request.toolCall.title?.trim() || "permission requested";
|
|
1159
|
+
return {
|
|
1160
|
+
title: `${label}: ${subject}`,
|
|
1161
|
+
kind: "approval",
|
|
1162
|
+
questions: [{
|
|
1163
|
+
id: PERMISSION_QUESTION,
|
|
1164
|
+
text: subject,
|
|
1165
|
+
freeText: false,
|
|
1166
|
+
options: request.options.map((option) => ({
|
|
1167
|
+
id: option.optionId,
|
|
1168
|
+
label: option.name.trim() || option.optionId
|
|
1169
|
+
}))
|
|
1170
|
+
}]
|
|
1171
|
+
};
|
|
1172
|
+
}
|
|
1173
|
+
/** Creates a coordinator that accepts background prompts without waiting for completion. */
|
|
1174
|
+
function createAcpManager(deps) {
|
|
1175
|
+
const { store, sessions, delivery } = deps;
|
|
1176
|
+
const connections = /* @__PURE__ */ new Map();
|
|
1177
|
+
const processes = /* @__PURE__ */ new Map();
|
|
1178
|
+
const running = /* @__PURE__ */ new Map();
|
|
1179
|
+
const starting = /* @__PURE__ */ new Map();
|
|
1180
|
+
const stopping = /* @__PURE__ */ new Set();
|
|
1181
|
+
const launches = /* @__PURE__ */ new Map();
|
|
1182
|
+
const permissions = /* @__PURE__ */ new Map();
|
|
1183
|
+
let closed = false;
|
|
1184
|
+
let withdrawn = false;
|
|
1185
|
+
const collections = /* @__PURE__ */ new Set();
|
|
1186
|
+
const changed = (delegation, task) => {
|
|
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
|
|
1204
|
+
});
|
|
1205
|
+
} catch {}
|
|
1206
|
+
};
|
|
1207
|
+
const get = (id) => {
|
|
1208
|
+
const row = store.delegation(id);
|
|
1209
|
+
if (!row) throw new Error("not-found");
|
|
1210
|
+
return row;
|
|
1211
|
+
};
|
|
1212
|
+
const task = (id) => {
|
|
1213
|
+
const row = store.task(id);
|
|
1214
|
+
if (!row) throw new Error("not-found");
|
|
1215
|
+
return row;
|
|
1216
|
+
};
|
|
1217
|
+
function authorize(caller, row) {
|
|
1218
|
+
const owner = sessions.resolve(row.parentSessionId);
|
|
1219
|
+
if (caller !== row.parentSessionId && !owner.ancestors.includes(caller)) throw new Error("forbidden");
|
|
1220
|
+
}
|
|
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
|
+
});
|
|
1233
|
+
}
|
|
1234
|
+
function update(input, fields) {
|
|
1235
|
+
const next = {
|
|
1236
|
+
...input,
|
|
1237
|
+
...fields,
|
|
1238
|
+
revision: input.revision + 1
|
|
1239
|
+
};
|
|
1240
|
+
store.saveTask(next);
|
|
1241
|
+
changed(get(next.delegationId), next);
|
|
1242
|
+
return next;
|
|
1243
|
+
}
|
|
1244
|
+
function finish(current, outcome, error = null) {
|
|
1245
|
+
if (task(current.id).state === "finished") return;
|
|
1246
|
+
const row = get(current.delegationId);
|
|
1247
|
+
const next = {
|
|
1248
|
+
...current,
|
|
1249
|
+
state: "finished",
|
|
1250
|
+
outcome,
|
|
1251
|
+
error,
|
|
1252
|
+
revision: current.revision + 1
|
|
1253
|
+
};
|
|
1254
|
+
delivery.commit((view) => view.update("task", { payload: JSON.stringify(next) }, { id: next.id }), [{
|
|
1255
|
+
target: row.parentSessionId,
|
|
1256
|
+
sourceKey: next.id,
|
|
1257
|
+
taskId: next.id,
|
|
1258
|
+
targetGeneration: next.targetGeneration,
|
|
1259
|
+
text: `ACP ${row.id}, task ${next.id}: ${outcome}${error ? ` (${error})` : ""}\n${next.result}${next.truncated ? "\n[Truncated; open delegation details.]" : ""}`
|
|
1260
|
+
}]);
|
|
1261
|
+
changed(row, next);
|
|
1262
|
+
}
|
|
1263
|
+
function expire(id) {
|
|
1264
|
+
for (const [key, value] of permissions) if (value.delegationId === id) {
|
|
1265
|
+
permissions.delete(key);
|
|
1266
|
+
value.withdraw.abort();
|
|
1267
|
+
value.resolve({ outcome: { outcome: "cancelled" } });
|
|
1268
|
+
}
|
|
1269
|
+
}
|
|
1270
|
+
/** The person's reply to one permission, while ACP still waits for it. */
|
|
1271
|
+
function answered(id, reply) {
|
|
1272
|
+
if (withdrawn) return;
|
|
1273
|
+
const pending = permissions.get(id);
|
|
1274
|
+
if (!pending) return;
|
|
1275
|
+
const optionId = reply.answers.find((answer) => answer.questionId === PERMISSION_QUESTION)?.optionIds?.[0];
|
|
1276
|
+
const current = store.tasks(pending.delegationId).find((one) => one.state === "awaiting-permission" || one.state === "running");
|
|
1277
|
+
if (optionId === void 0 || !pending.request.options.some((option) => option.optionId === optionId) || !current) {
|
|
1278
|
+
cancelled(id);
|
|
1279
|
+
return;
|
|
1280
|
+
}
|
|
1281
|
+
const waiting = [...permissions].some(([key, other]) => key !== id && other.delegationId === pending.delegationId);
|
|
1282
|
+
store.transaction(() => {
|
|
1283
|
+
store.append(current.id, {
|
|
1284
|
+
kind: "permission-answered",
|
|
1285
|
+
id,
|
|
1286
|
+
optionId
|
|
1287
|
+
});
|
|
1288
|
+
store.saveTask({
|
|
1289
|
+
...current,
|
|
1290
|
+
state: waiting ? "awaiting-permission" : "running",
|
|
1291
|
+
revision: current.revision + 1
|
|
1292
|
+
});
|
|
1293
|
+
});
|
|
1294
|
+
permissions.delete(id);
|
|
1295
|
+
pending.resolve({ outcome: {
|
|
1296
|
+
outcome: "selected",
|
|
1297
|
+
optionId
|
|
1298
|
+
} });
|
|
1299
|
+
changed(get(pending.delegationId), task(current.id));
|
|
1300
|
+
}
|
|
1301
|
+
/** The question ended without an answer: ACP reads it as cancelled. */
|
|
1302
|
+
function cancelled(id) {
|
|
1303
|
+
if (withdrawn) return;
|
|
1304
|
+
const pending = permissions.get(id);
|
|
1305
|
+
if (!pending) return;
|
|
1306
|
+
permissions.delete(id);
|
|
1307
|
+
pending.resolve({ outcome: { outcome: "cancelled" } });
|
|
1308
|
+
changed(get(pending.delegationId));
|
|
1309
|
+
}
|
|
1310
|
+
async function disconnect(id) {
|
|
1311
|
+
expire(id);
|
|
1312
|
+
const pending = starting.get(id);
|
|
1313
|
+
if (pending) await pending.catch(() => {});
|
|
1314
|
+
const connection = connections.get(id);
|
|
1315
|
+
if (withdrawn) {
|
|
1316
|
+
const process = connection?.process ?? processes.get(id);
|
|
1317
|
+
connections.delete(id);
|
|
1318
|
+
processes.delete(id);
|
|
1319
|
+
if (process) await process.stop();
|
|
1320
|
+
await launches.get(id)?.release?.();
|
|
1321
|
+
launches.delete(id);
|
|
1322
|
+
return;
|
|
1323
|
+
}
|
|
1324
|
+
const row = get(id);
|
|
1325
|
+
try {
|
|
1326
|
+
const process = connection?.process ?? processes.get(id);
|
|
1327
|
+
if (process) await process.stop();
|
|
1328
|
+
await launches.get(id)?.release?.();
|
|
1329
|
+
launches.delete(id);
|
|
1330
|
+
processes.delete(id);
|
|
1331
|
+
connections.delete(id);
|
|
1332
|
+
if (withdrawn) return;
|
|
1333
|
+
store.saveDelegation({
|
|
1334
|
+
...row,
|
|
1335
|
+
connectionState: "closed",
|
|
1336
|
+
processId: null
|
|
1337
|
+
});
|
|
1338
|
+
} catch {
|
|
1339
|
+
if (withdrawn) throw new Error("cleanup-failed");
|
|
1340
|
+
store.saveDelegation({
|
|
1341
|
+
...row,
|
|
1342
|
+
connectionState: "cleanup-failed"
|
|
1343
|
+
});
|
|
1344
|
+
changed(get(id));
|
|
1345
|
+
throw new Error("cleanup-failed");
|
|
1346
|
+
}
|
|
1347
|
+
changed(get(id));
|
|
1348
|
+
schedule(row.rootSessionId);
|
|
1349
|
+
}
|
|
1350
|
+
async function connect(row) {
|
|
1351
|
+
const launch = launches.get(row.id);
|
|
1352
|
+
if (!launch) throw new Error("resume-unavailable: explicit launch authorization required");
|
|
1353
|
+
const process = await launch.launch();
|
|
1354
|
+
if (withdrawn) {
|
|
1355
|
+
await process.stop();
|
|
1356
|
+
throw new Error("stopping");
|
|
1357
|
+
}
|
|
1358
|
+
processes.set(row.id, process);
|
|
1359
|
+
store.saveDelegation({
|
|
1360
|
+
...get(row.id),
|
|
1361
|
+
processId: process.processId,
|
|
1362
|
+
execution: launch.execution
|
|
1363
|
+
});
|
|
1364
|
+
const connection = await connectAcp(process, {
|
|
1365
|
+
permission(request) {
|
|
1366
|
+
if (withdrawn) return Promise.resolve({ outcome: { outcome: "cancelled" } });
|
|
1367
|
+
const current = store.tasks(row.id).find((one) => one.state === "running" || one.state === "awaiting-permission");
|
|
1368
|
+
if (!current || request.sessionId !== get(row.id).remoteSessionId) return Promise.resolve({ outcome: { outcome: "cancelled" } });
|
|
1369
|
+
const id = randomUUID();
|
|
1370
|
+
const withdraw = new AbortController();
|
|
1371
|
+
return new Promise((resolve) => {
|
|
1372
|
+
permissions.set(id, {
|
|
1373
|
+
delegationId: row.id,
|
|
1374
|
+
generation: row.generation,
|
|
1375
|
+
request,
|
|
1376
|
+
resolve,
|
|
1377
|
+
withdraw
|
|
1378
|
+
});
|
|
1379
|
+
store.append(current.id, {
|
|
1380
|
+
kind: "permission-requested",
|
|
1381
|
+
id,
|
|
1382
|
+
generation: row.generation,
|
|
1383
|
+
request
|
|
1384
|
+
});
|
|
1385
|
+
update(current, { state: "awaiting-permission" });
|
|
1386
|
+
deps.ask(get(row.id).parentSessionId, permissionQuestion(row.instance.label, request), { signal: withdraw.signal }).then((reply) => answered(id, reply), () => cancelled(id));
|
|
1387
|
+
});
|
|
1388
|
+
},
|
|
1389
|
+
update(notification) {
|
|
1390
|
+
if (withdrawn) return;
|
|
1391
|
+
const current = store.tasks(row.id).find((one) => one.state !== "queued" && one.state !== "finished");
|
|
1392
|
+
if (!current || current.state === "starting") return;
|
|
1393
|
+
if (notification.sessionId !== get(row.id).remoteSessionId) throw new Error("remote-session-mismatch");
|
|
1394
|
+
store.append(current.id, notification.update);
|
|
1395
|
+
if (notification.update.sessionUpdate === "config_option_update") {
|
|
1396
|
+
store.saveDelegation({
|
|
1397
|
+
...get(row.id),
|
|
1398
|
+
configOptions: notification.update.configOptions
|
|
1399
|
+
});
|
|
1400
|
+
changed(get(row.id), current);
|
|
1401
|
+
}
|
|
1402
|
+
if (notification.update.sessionUpdate === "agent_message_chunk" && notification.update.content.type === "text") {
|
|
1403
|
+
const text = current.result + notification.update.content.text;
|
|
1404
|
+
const bytes = Buffer.from(text);
|
|
1405
|
+
let end = Math.min(bytes.length, 65536);
|
|
1406
|
+
if (end < bytes.length) while (end > 0 && (bytes[end] & 192) === 128) end--;
|
|
1407
|
+
update(current, {
|
|
1408
|
+
result: bytes.subarray(0, end).toString("utf8"),
|
|
1409
|
+
truncated: current.truncated || bytes.length > 65536
|
|
1410
|
+
});
|
|
1411
|
+
}
|
|
1412
|
+
}
|
|
1413
|
+
});
|
|
1414
|
+
if (withdrawn) {
|
|
1415
|
+
await process.stop();
|
|
1416
|
+
throw new Error("stopping");
|
|
1417
|
+
}
|
|
1418
|
+
store.saveDelegation({
|
|
1419
|
+
...get(row.id),
|
|
1420
|
+
capabilities: connection.initialized.agentCapabilities ?? {}
|
|
1421
|
+
});
|
|
1422
|
+
connections.set(row.id, connection);
|
|
1423
|
+
try {
|
|
1424
|
+
let configuration = [];
|
|
1425
|
+
if (row.remoteSessionId) {
|
|
1426
|
+
const capabilities = connection.initialized.agentCapabilities;
|
|
1427
|
+
if (capabilities?.sessionCapabilities?.resume) configuration = (await control(connection.client.resumeSession({
|
|
1428
|
+
sessionId: row.remoteSessionId,
|
|
1429
|
+
cwd: row.cwd,
|
|
1430
|
+
mcpServers: []
|
|
1431
|
+
}))).configOptions ?? [];
|
|
1432
|
+
else if (capabilities?.loadSession) configuration = (await control(connection.client.loadSession({
|
|
1433
|
+
sessionId: row.remoteSessionId,
|
|
1434
|
+
cwd: row.cwd,
|
|
1435
|
+
mcpServers: []
|
|
1436
|
+
}))).configOptions ?? [];
|
|
1437
|
+
else throw new Error("resume-unavailable");
|
|
1438
|
+
} else {
|
|
1439
|
+
const remote = await control(connection.client.newSession({
|
|
1440
|
+
cwd: row.cwd,
|
|
1441
|
+
mcpServers: []
|
|
1442
|
+
}));
|
|
1443
|
+
if (withdrawn) throw new Error("stopping");
|
|
1444
|
+
store.saveDelegation({
|
|
1445
|
+
...get(row.id),
|
|
1446
|
+
remoteSessionId: remote.sessionId
|
|
1447
|
+
});
|
|
1448
|
+
configuration = remote.configOptions ?? [];
|
|
1449
|
+
}
|
|
1450
|
+
if (withdrawn) throw new Error("stopping");
|
|
1451
|
+
store.saveDelegation({
|
|
1452
|
+
...get(row.id),
|
|
1453
|
+
configOptions: configuration
|
|
1454
|
+
});
|
|
1455
|
+
const requested = { ...row.config };
|
|
1456
|
+
if (row.model) {
|
|
1457
|
+
const selector = configuration.find((option) => option.category === "model");
|
|
1458
|
+
if (!selector) throw new Error("model-selection-unavailable");
|
|
1459
|
+
requested[selector.id] = row.model;
|
|
1460
|
+
}
|
|
1461
|
+
for (const [configId, value] of Object.entries(requested)) {
|
|
1462
|
+
const option = configuration.find((option) => option.id === configId);
|
|
1463
|
+
if (!option || option.type !== "select") throw new Error("config-option-unavailable");
|
|
1464
|
+
if (option.category !== "model" && option.category !== "thought_level") throw new Error("config-option-forbidden");
|
|
1465
|
+
if (!option.options.flatMap((entry) => "options" in entry ? entry.options : [entry]).some((choice) => choice.value === value)) throw new Error("invalid-config-value");
|
|
1466
|
+
configuration = (await control(connection.client.setSessionConfigOption({
|
|
1467
|
+
sessionId: get(row.id).remoteSessionId,
|
|
1468
|
+
configId,
|
|
1469
|
+
value
|
|
1470
|
+
}))).configOptions;
|
|
1471
|
+
}
|
|
1472
|
+
if (withdrawn) throw new Error("stopping");
|
|
1473
|
+
store.saveDelegation({
|
|
1474
|
+
...get(row.id),
|
|
1475
|
+
connectionState: "connected",
|
|
1476
|
+
configOptions: configuration
|
|
1477
|
+
});
|
|
1478
|
+
connection.client.closed.then(async () => {
|
|
1479
|
+
if (withdrawn || connections.get(row.id) !== connection) return;
|
|
1480
|
+
try {
|
|
1481
|
+
await disconnect(row.id);
|
|
1482
|
+
} catch {}
|
|
1483
|
+
});
|
|
1484
|
+
return connection;
|
|
1485
|
+
} catch (error) {
|
|
1486
|
+
await connection.process.stop();
|
|
1487
|
+
connections.delete(row.id);
|
|
1488
|
+
if (error && typeof error === "object" && "code" in error && error.code === -32e3) throw new Error("auth-required");
|
|
1489
|
+
if (error instanceof Error && [
|
|
1490
|
+
"resume-unavailable",
|
|
1491
|
+
"model-selection-unavailable",
|
|
1492
|
+
"config-option-unavailable",
|
|
1493
|
+
"config-option-forbidden",
|
|
1494
|
+
"invalid-config-value",
|
|
1495
|
+
"protocol-timeout"
|
|
1496
|
+
].includes(error.message)) throw error;
|
|
1497
|
+
throw new Error("session-setup-failed");
|
|
1498
|
+
}
|
|
1499
|
+
}
|
|
1500
|
+
async function run(id) {
|
|
1501
|
+
if (closed || running.has(id)) return;
|
|
1502
|
+
const current = store.tasks(id).find((one) => one.state !== "finished");
|
|
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
|
+
}
|
|
1514
|
+
const work = (async () => {
|
|
1515
|
+
try {
|
|
1516
|
+
const row = get(id);
|
|
1517
|
+
update(current, { state: "starting" });
|
|
1518
|
+
let connection = connections.get(id);
|
|
1519
|
+
if (!connection) {
|
|
1520
|
+
const opening = connect(row);
|
|
1521
|
+
starting.set(id, opening);
|
|
1522
|
+
try {
|
|
1523
|
+
connection = await opening;
|
|
1524
|
+
} finally {
|
|
1525
|
+
starting.delete(id);
|
|
1526
|
+
}
|
|
1527
|
+
}
|
|
1528
|
+
if (withdrawn) return;
|
|
1529
|
+
if (task(current.id).state === "finished" || closed || stopping.has(id)) {
|
|
1530
|
+
await disconnect(id);
|
|
1531
|
+
return;
|
|
1532
|
+
}
|
|
1533
|
+
update(task(current.id), { state: "running" });
|
|
1534
|
+
const response = await connection.client.prompt({
|
|
1535
|
+
sessionId: get(id).remoteSessionId,
|
|
1536
|
+
prompt: [{
|
|
1537
|
+
type: "text",
|
|
1538
|
+
text: current.input
|
|
1539
|
+
}]
|
|
1540
|
+
});
|
|
1541
|
+
if (withdrawn) return;
|
|
1542
|
+
expire(id);
|
|
1543
|
+
const cancelled = task(current.id).state === "stopping" || response.stopReason === "cancelled";
|
|
1544
|
+
const failure = response.stopReason === "refusal" ? "external-refusal" : response.stopReason === "max_tokens" || response.stopReason === "max_turn_requests" ? "external-limit" : void 0;
|
|
1545
|
+
finish(task(current.id), cancelled ? "cancelled" : failure ? "failed" : "completed", cancelled ? void 0 : failure);
|
|
1546
|
+
} catch (error) {
|
|
1547
|
+
if (withdrawn) return;
|
|
1548
|
+
try {
|
|
1549
|
+
await disconnect(id);
|
|
1550
|
+
} catch {}
|
|
1551
|
+
if (withdrawn) return;
|
|
1552
|
+
const safe = error && typeof error === "object" && "code" in error && error.code === -32e3 ? "auth-required" : error instanceof Error && [
|
|
1553
|
+
"resume-unavailable",
|
|
1554
|
+
"model-selection-unavailable",
|
|
1555
|
+
"config-option-unavailable",
|
|
1556
|
+
"config-option-forbidden",
|
|
1557
|
+
"invalid-config-value",
|
|
1558
|
+
"protocol-timeout",
|
|
1559
|
+
"session-setup-failed",
|
|
1560
|
+
"auth-required",
|
|
1561
|
+
"initialize-failed",
|
|
1562
|
+
"capacity-exceeded"
|
|
1563
|
+
].includes(error.message) ? error.message : "external-task-failed";
|
|
1564
|
+
finish(task(current.id), "failed", safe);
|
|
1565
|
+
} finally {
|
|
1566
|
+
running.delete(id);
|
|
1567
|
+
if (!closed) schedule(get(id).rootSessionId);
|
|
1568
|
+
}
|
|
1569
|
+
})();
|
|
1570
|
+
running.set(id, work);
|
|
1571
|
+
await work;
|
|
1572
|
+
}
|
|
1573
|
+
function accepted(id, input, requestKey) {
|
|
1574
|
+
if (stopping.has(id)) throw new Error("stopping");
|
|
1575
|
+
const row = get(id);
|
|
1576
|
+
if (row.connectionState === "cleanup-failed") throw new Error("cleanup-required");
|
|
1577
|
+
const previous = store.tasks(id).find((one) => one.requestKey === requestKey);
|
|
1578
|
+
if (previous) {
|
|
1579
|
+
if (previous.input !== input) throw new Error("request-key-conflict");
|
|
1580
|
+
return previous;
|
|
1581
|
+
}
|
|
1582
|
+
const busy = store.tasks(id).some((one) => one.state !== "finished");
|
|
1583
|
+
if (!busy) capacity(row.rootSessionId, !connections.has(id));
|
|
1584
|
+
if (store.tasks(id).filter((one) => one.state === "queued").length >= 32) throw new Error("queue-full");
|
|
1585
|
+
const value = {
|
|
1586
|
+
id: randomUUID(),
|
|
1587
|
+
delegationId: id,
|
|
1588
|
+
requestKey,
|
|
1589
|
+
targetGeneration: delivery.captureGeneration(row.parentSessionId),
|
|
1590
|
+
input,
|
|
1591
|
+
state: busy ? "queued" : "starting",
|
|
1592
|
+
outcome: null,
|
|
1593
|
+
error: null,
|
|
1594
|
+
result: "",
|
|
1595
|
+
truncated: false,
|
|
1596
|
+
createdAt: Date.now(),
|
|
1597
|
+
revision: 0
|
|
1598
|
+
};
|
|
1599
|
+
store.saveTask(value);
|
|
1600
|
+
changed(row, value);
|
|
1601
|
+
queueMicrotask(() => {
|
|
1602
|
+
run(id);
|
|
1603
|
+
});
|
|
1604
|
+
return value;
|
|
1605
|
+
}
|
|
1606
|
+
return {
|
|
1607
|
+
recover() {
|
|
1608
|
+
for (const row of store.delegations()) {
|
|
1609
|
+
store.saveDelegation({
|
|
1610
|
+
...row,
|
|
1611
|
+
connectionState: "interrupted",
|
|
1612
|
+
processId: null,
|
|
1613
|
+
generation: randomUUID()
|
|
1614
|
+
});
|
|
1615
|
+
for (const current of store.tasks(row.id)) if (current.state !== "finished") finish(current, "interrupted", "gateway-restarted");
|
|
1616
|
+
}
|
|
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
|
+
},
|
|
1638
|
+
/** Accepts one prompt and records its effective execution only after its launch succeeds. */
|
|
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?.();
|
|
1700
|
+
}
|
|
1701
|
+
},
|
|
1702
|
+
/** Reuses a live connection, or requires a fresh approved factory and isolation facts. */
|
|
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
|
+
}
|
|
1729
|
+
},
|
|
1730
|
+
usage(caller) {
|
|
1731
|
+
const root = sessions.resolve(caller).rootSessionId;
|
|
1732
|
+
const rows = store.delegations().filter((row) => row.rootSessionId === root);
|
|
1733
|
+
const ids = new Set(rows.map((row) => row.id));
|
|
1734
|
+
return {
|
|
1735
|
+
limits: store.settings(),
|
|
1736
|
+
tasks: store.tasks().filter((row) => ids.has(row.delegationId) && row.state !== "queued" && row.state !== "finished").length,
|
|
1737
|
+
connections: rows.filter((row) => row.connectionState !== "closed" && row.connectionState !== "interrupted").length
|
|
1738
|
+
};
|
|
1739
|
+
},
|
|
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) {
|
|
1796
|
+
const row = get(id);
|
|
1797
|
+
authorize(caller, row);
|
|
1798
|
+
const effective = Math.min(200, limit);
|
|
1799
|
+
const page = store.tasksPage(id, offset, effective, maxBytes);
|
|
1800
|
+
return {
|
|
1801
|
+
delegation: row,
|
|
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}` } : {}
|
|
1807
|
+
};
|
|
1808
|
+
},
|
|
1809
|
+
task(caller, id, taskId, maxBytes = 8388608) {
|
|
1810
|
+
authorize(caller, get(id));
|
|
1811
|
+
const current = store.task(taskId, maxBytes);
|
|
1812
|
+
if (!current) throw new Error("not-found");
|
|
1813
|
+
if (current.delegationId !== id) throw new Error("not-found");
|
|
1814
|
+
return current;
|
|
1815
|
+
},
|
|
1816
|
+
list(caller, offset = 0, limit = 50) {
|
|
1817
|
+
sessions.resolve(caller);
|
|
1818
|
+
const rows = [];
|
|
1819
|
+
let skipped = 0;
|
|
1820
|
+
let bytes = 8192;
|
|
1821
|
+
for (const identity of store.delegationIdentities()) {
|
|
1822
|
+
try {
|
|
1823
|
+
authorize(caller, identity);
|
|
1824
|
+
} catch {
|
|
1825
|
+
continue;
|
|
1826
|
+
}
|
|
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;
|
|
1845
|
+
},
|
|
1846
|
+
hasConnection: (id) => connections.has(id),
|
|
1847
|
+
async stop(caller, id) {
|
|
1848
|
+
const row = get(id);
|
|
1849
|
+
authorize(caller, row);
|
|
1850
|
+
expire(id);
|
|
1851
|
+
const current = store.tasks(id).find((one) => one.state !== "finished" && one.state !== "queued");
|
|
1852
|
+
if (!current) return;
|
|
1853
|
+
if (current.state === "starting") {
|
|
1854
|
+
stopping.add(id);
|
|
1855
|
+
try {
|
|
1856
|
+
await disconnect(id);
|
|
1857
|
+
finish(task(current.id), "cancelled");
|
|
1858
|
+
} finally {
|
|
1859
|
+
stopping.delete(id);
|
|
1860
|
+
}
|
|
1861
|
+
return;
|
|
1862
|
+
}
|
|
1863
|
+
update(current, { state: "stopping" });
|
|
1864
|
+
const connection = connections.get(id);
|
|
1865
|
+
try {
|
|
1866
|
+
if (connection && row.remoteSessionId) await connection.client.cancel({ sessionId: row.remoteSessionId });
|
|
1867
|
+
const work = running.get(id);
|
|
1868
|
+
if (work) await control(work, 5e3);
|
|
1869
|
+
} catch {
|
|
1870
|
+
await disconnect(id);
|
|
1871
|
+
finish(task(current.id), "interrupted", "cancel-timeout");
|
|
1872
|
+
}
|
|
1873
|
+
},
|
|
1874
|
+
async close(caller, id) {
|
|
1875
|
+
authorize(caller, get(id));
|
|
1876
|
+
for (const current of store.tasks(id)) if (current.state === "queued") finish(current, "cancelled");
|
|
1877
|
+
await this.stop(caller, id);
|
|
1878
|
+
await disconnect(id);
|
|
1879
|
+
},
|
|
1880
|
+
/** Releases live resources after owner revocation without reading withdrawn persistence. */
|
|
1881
|
+
async withdraw() {
|
|
1882
|
+
withdrawn = true;
|
|
1883
|
+
closed = true;
|
|
1884
|
+
for (const pending of [...permissions.values()]) expire(pending.delegationId);
|
|
1885
|
+
const live = [.../* @__PURE__ */ new Set([...processes.values(), ...[...connections.values()].map((one) => one.process)])];
|
|
1886
|
+
const preparations = [...launches.values()];
|
|
1887
|
+
const stopped = await Promise.allSettled(live.map((process) => process.stop()));
|
|
1888
|
+
await Promise.allSettled([...starting.values(), ...running.values()]);
|
|
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();
|
|
1894
|
+
},
|
|
1895
|
+
async shutdown() {
|
|
1896
|
+
closed = true;
|
|
1897
|
+
const results = await Promise.allSettled(store.delegations().map((row) => this.close(row.parentSessionId, row.id)));
|
|
1898
|
+
await Promise.allSettled([...running.values()]);
|
|
1899
|
+
if (results.some((row) => row.status === "rejected")) throw new Error("cleanup-failed");
|
|
1900
|
+
}
|
|
1901
|
+
};
|
|
1902
|
+
}
|
|
1903
|
+
//#endregion
|
|
1904
|
+
//#region src/tool-names.ts
|
|
1905
|
+
/** Canonical names shared by tool registration and browser presentation. */
|
|
1906
|
+
const TOOL_NAMES = [
|
|
1907
|
+
"acp_instances",
|
|
1908
|
+
"acp_delegate",
|
|
1909
|
+
"acp_send",
|
|
1910
|
+
"acp_get",
|
|
1911
|
+
"acp_list",
|
|
1912
|
+
"acp_stop"
|
|
1913
|
+
];
|
|
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
|
|
2601
|
+
//#region src/index.ts
|
|
2602
|
+
const Session = z.object({ sessionId: z.string().min(1) }).strict();
|
|
2603
|
+
const Target = Session.extend({ delegationId: z.string().min(1) }).strict();
|
|
2604
|
+
const Send = z.object({
|
|
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.")
|
|
2607
|
+
}).strict();
|
|
2608
|
+
const Result = z.unknown();
|
|
2609
|
+
const Changed = z.strictObject({
|
|
2610
|
+
delegationIds: z.array(z.string()).max(64),
|
|
2611
|
+
invalidated: z.boolean()
|
|
2612
|
+
});
|
|
2613
|
+
const acpPlugin = {
|
|
2614
|
+
name: "@eum-agent/integration-acp",
|
|
2615
|
+
configSchema: z.object({ disabled: z.array(z.enum(TOOL_NAMES)).default([]) }).strict().optional(),
|
|
2616
|
+
requires: [
|
|
2617
|
+
"sandbox",
|
|
2618
|
+
"host-commands",
|
|
2619
|
+
"network",
|
|
2620
|
+
"approval",
|
|
2621
|
+
"protocol-processes",
|
|
2622
|
+
"session-context",
|
|
2623
|
+
"session-delivery",
|
|
2624
|
+
"work-lifecycle",
|
|
2625
|
+
"owner-operations",
|
|
2626
|
+
"query-resources"
|
|
2627
|
+
],
|
|
2628
|
+
async apply(ctx, config) {
|
|
2629
|
+
const register = (definition) => config?.disabled.includes(definition.name) ? () => {} : ctx.tools.register(definition);
|
|
2630
|
+
ctx.tools.guide(ACP_GUIDANCE);
|
|
2631
|
+
const store = createAcpStore(ctx.storage.open());
|
|
2632
|
+
const sessions = ctx.services.get("session-context");
|
|
2633
|
+
const commands = ctx.services.get("host-commands");
|
|
2634
|
+
const services = {
|
|
2635
|
+
commands,
|
|
2636
|
+
network: ctx.services.get("network"),
|
|
2637
|
+
sandbox: ctx.services.get("sandbox"),
|
|
2638
|
+
approval: ctx.services.get("approval"),
|
|
2639
|
+
processes: ctx.services.get("protocol-processes")
|
|
2640
|
+
};
|
|
2641
|
+
const changed = ctx.client.registerFrame({
|
|
2642
|
+
name: "changed",
|
|
2643
|
+
delivery: "session",
|
|
2644
|
+
payload: Changed
|
|
2645
|
+
});
|
|
2646
|
+
const manager = createAcpManager({
|
|
2647
|
+
store,
|
|
2648
|
+
sessions,
|
|
2649
|
+
delivery: ctx.services.get("session-delivery"),
|
|
2650
|
+
changed: (id, value) => changed.emit(id, Changed.parse(value)),
|
|
2651
|
+
ask: (sessionId, request, options) => ctx.sessions.ask(sessionId, request, options)
|
|
2652
|
+
});
|
|
2653
|
+
await services.processes.recover();
|
|
2654
|
+
manager.recover();
|
|
2655
|
+
const probes = /* @__PURE__ */ new Map();
|
|
2656
|
+
let draining = false;
|
|
2657
|
+
let withdrawn = false;
|
|
2658
|
+
let unbind = () => {};
|
|
2659
|
+
const drain = async () => {
|
|
2660
|
+
draining = true;
|
|
2661
|
+
const results = await Promise.allSettled([withdrawn ? manager.withdraw() : manager.shutdown(), ...probes.values()]);
|
|
2662
|
+
results.push(...await Promise.allSettled([services.processes.shutdown()]));
|
|
2663
|
+
const failures = results.filter((row) => row.status === "rejected");
|
|
2664
|
+
if (failures.length) throw new AggregateError(failures.map((row) => row.reason), "cleanup-failed");
|
|
2665
|
+
if (withdrawn) {
|
|
2666
|
+
unbind();
|
|
2667
|
+
unbind = () => {};
|
|
2668
|
+
}
|
|
2669
|
+
};
|
|
2670
|
+
unbind = ctx.services.get("work-lifecycle").register(drain);
|
|
2671
|
+
ctx.onDispose(async () => {
|
|
2672
|
+
withdrawn = true;
|
|
2673
|
+
await drain();
|
|
2674
|
+
});
|
|
2675
|
+
const find = (caller, id) => {
|
|
2676
|
+
return manager.get(caller, id);
|
|
2677
|
+
};
|
|
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)
|
|
2686
|
+
});
|
|
2687
|
+
register({
|
|
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",
|
|
2699
|
+
description: "Continue an external delegation. Tasks queue FIFO; reconnecting requires renewed launch authorization.",
|
|
2700
|
+
inputSchema: Send,
|
|
2701
|
+
async execute(input, call) {
|
|
2702
|
+
const row = find(call.sessionId, input.delegationId).delegation;
|
|
2703
|
+
let admitted;
|
|
2704
|
+
if (!manager.hasConnection(row.id)) {
|
|
2705
|
+
const configured = store.instances().find((instance) => instance.id === row.instance.id && instance.enabled);
|
|
2706
|
+
if (!configured) throw new Error("instance-missing");
|
|
2707
|
+
if (configured.revision !== row.instance.revision) throw new Error("configuration-changed: create a new delegation");
|
|
2708
|
+
const prepared = await prepareLaunch(call, row.instance, row.cwd, services);
|
|
2709
|
+
if ("result" in prepared) return prepared.result;
|
|
2710
|
+
admitted = prepared;
|
|
2711
|
+
}
|
|
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
|
+
};
|
|
2728
|
+
}
|
|
2729
|
+
});
|
|
2730
|
+
const tickets = /* @__PURE__ */ new Map();
|
|
2731
|
+
const startManaged = async (input, answer) => {
|
|
2732
|
+
if (draining) throw new Error("stopping");
|
|
2733
|
+
const instance = input.delegationId ? find(input.sessionId, input.delegationId).delegation.instance : store.instances().find((row) => row.id === input.instanceId && row.enabled);
|
|
2734
|
+
if (!instance) throw new Error("instance-missing");
|
|
2735
|
+
const configured = store.instances().find((row) => row.id === instance.id && row.enabled);
|
|
2736
|
+
if (!configured) throw new Error("instance-missing");
|
|
2737
|
+
if (configured.revision !== instance.revision) throw new Error("configuration-changed: create a new delegation");
|
|
2738
|
+
const prepared = await prepareLaunch({
|
|
2739
|
+
sessionId: input.sessionId,
|
|
2740
|
+
address: sessions.resolve(input.sessionId).address,
|
|
2741
|
+
...answer ? { answer } : {}
|
|
2742
|
+
}, instance, input.cwd, services);
|
|
2743
|
+
if ("result" in prepared) {
|
|
2744
|
+
if (!("awaitHuman" in prepared.result)) throw new Error("launch-refused");
|
|
2745
|
+
for (const [id, ticket] of tickets) if (ticket.expires < Date.now()) tickets.delete(id);
|
|
2746
|
+
if (tickets.size >= 128) throw new Error("approval-capacity-exceeded");
|
|
2747
|
+
const id = randomUUID();
|
|
2748
|
+
tickets.set(id, {
|
|
2749
|
+
input,
|
|
2750
|
+
instance,
|
|
2751
|
+
expires: Date.now() + 3e5,
|
|
2752
|
+
request: prepared.result.awaitHuman,
|
|
2753
|
+
questions: prepared.result.awaitHuman.questions
|
|
2754
|
+
});
|
|
2755
|
+
return { approval: {
|
|
2756
|
+
id,
|
|
2757
|
+
request: prepared.result.awaitHuman
|
|
2758
|
+
} };
|
|
2759
|
+
}
|
|
2760
|
+
if (input.probe) {
|
|
2761
|
+
const root = sessions.resolve(input.sessionId).rootSessionId;
|
|
2762
|
+
if (probes.has(root)) {
|
|
2763
|
+
await prepared.release();
|
|
2764
|
+
throw new Error("preflight-in-progress");
|
|
2765
|
+
}
|
|
2766
|
+
const work = (async () => {
|
|
2767
|
+
const process = await prepared.launch();
|
|
2768
|
+
try {
|
|
2769
|
+
const connection = await connectAcp(process, {
|
|
2770
|
+
update() {},
|
|
2771
|
+
permission: async () => ({ outcome: { outcome: "cancelled" } })
|
|
2772
|
+
});
|
|
2773
|
+
return { preflight: {
|
|
2774
|
+
execution: prepared.execution,
|
|
2775
|
+
protocolVersion: connection.initialized.protocolVersion,
|
|
2776
|
+
capabilities: connection.initialized.agentCapabilities ?? {},
|
|
2777
|
+
authentication: "unverified",
|
|
2778
|
+
authMethods: connection.initialized.authMethods ?? []
|
|
2779
|
+
} };
|
|
2780
|
+
} finally {
|
|
2781
|
+
await process.stop();
|
|
2782
|
+
}
|
|
2783
|
+
})();
|
|
2784
|
+
probes.set(root, work);
|
|
2785
|
+
try {
|
|
2786
|
+
return await work;
|
|
2787
|
+
} finally {
|
|
2788
|
+
probes.delete(root);
|
|
2789
|
+
}
|
|
2790
|
+
}
|
|
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) };
|
|
2792
|
+
};
|
|
2793
|
+
ctx.client.registerMethod({
|
|
2794
|
+
name: "preflight",
|
|
2795
|
+
params: Session.extend({
|
|
2796
|
+
instanceId: z.string(),
|
|
2797
|
+
cwd: z.string()
|
|
2798
|
+
}),
|
|
2799
|
+
result: Result,
|
|
2800
|
+
handle: (input) => startManaged({
|
|
2801
|
+
...input,
|
|
2802
|
+
task: "",
|
|
2803
|
+
requestKey: randomUUID(),
|
|
2804
|
+
probe: true
|
|
2805
|
+
})
|
|
2806
|
+
});
|
|
2807
|
+
ctx.client.registerMethod({
|
|
2808
|
+
name: "start",
|
|
2809
|
+
params: Start.extend({
|
|
2810
|
+
sessionId: z.string(),
|
|
2811
|
+
requestKey: z.string()
|
|
2812
|
+
}),
|
|
2813
|
+
result: Result,
|
|
2814
|
+
handle: (input) => startManaged(input)
|
|
2815
|
+
});
|
|
2816
|
+
ctx.client.registerMethod({
|
|
2817
|
+
name: "resume",
|
|
2818
|
+
params: Target.extend({
|
|
2819
|
+
task: z.string().min(1),
|
|
2820
|
+
requestKey: z.string()
|
|
2821
|
+
}),
|
|
2822
|
+
result: Result,
|
|
2823
|
+
handle(input) {
|
|
2824
|
+
const row = find(input.sessionId, input.delegationId).delegation;
|
|
2825
|
+
return startManaged({
|
|
2826
|
+
...input,
|
|
2827
|
+
instanceId: row.instance.id,
|
|
2828
|
+
cwd: row.cwd,
|
|
2829
|
+
...row.model ? { model: row.model } : {},
|
|
2830
|
+
config: row.config
|
|
2831
|
+
});
|
|
2832
|
+
}
|
|
2833
|
+
});
|
|
2834
|
+
ctx.client.registerMethod({
|
|
2835
|
+
name: "launchApprovals",
|
|
2836
|
+
params: Session,
|
|
2837
|
+
result: Result,
|
|
2838
|
+
handle: (input) => [...tickets.entries()].filter(([, ticket]) => ticket.input.sessionId === input.sessionId && ticket.expires > Date.now()).map(([id, ticket]) => ({
|
|
2839
|
+
id,
|
|
2840
|
+
request: ticket.request
|
|
2841
|
+
}))
|
|
2842
|
+
});
|
|
2843
|
+
ctx.client.registerMethod({
|
|
2844
|
+
name: "usage",
|
|
2845
|
+
params: Session,
|
|
2846
|
+
result: Result,
|
|
2847
|
+
handle: (input) => manager.usage(input.sessionId)
|
|
2848
|
+
});
|
|
2849
|
+
ctx.client.registerMethod({
|
|
2850
|
+
name: "confirmLaunch",
|
|
2851
|
+
params: z.object({
|
|
2852
|
+
id: z.string(),
|
|
2853
|
+
allow: z.boolean()
|
|
2854
|
+
}).strict(),
|
|
2855
|
+
result: Result,
|
|
2856
|
+
async handle(input) {
|
|
2857
|
+
const ticket = tickets.get(input.id);
|
|
2858
|
+
tickets.delete(input.id);
|
|
2859
|
+
if (!ticket || ticket.expires < Date.now()) throw new Error("request-expired");
|
|
2860
|
+
if (!input.allow) return { rejected: true };
|
|
2861
|
+
const configured = store.instances().find((row) => row.id === ticket.instance.id);
|
|
2862
|
+
if (!configured || !configured.enabled || configured.revision !== ticket.instance.revision) throw new Error("configuration-changed: request launch again");
|
|
2863
|
+
return startManaged(ticket.input, {
|
|
2864
|
+
requestId: input.id,
|
|
2865
|
+
answers: ticket.questions.map((question) => ({
|
|
2866
|
+
questionId: question.id,
|
|
2867
|
+
optionIds: ["allowed-once"]
|
|
2868
|
+
}))
|
|
2869
|
+
});
|
|
2870
|
+
}
|
|
2871
|
+
});
|
|
2872
|
+
ctx.client.registerMethod({
|
|
2873
|
+
name: "list",
|
|
2874
|
+
params: Session.extend(Page.shape),
|
|
2875
|
+
result: Result,
|
|
2876
|
+
handle: (input) => listPage(manager, input.sessionId, input.offset, input.limit)
|
|
2877
|
+
});
|
|
2878
|
+
ctx.client.registerMethod({
|
|
2879
|
+
name: "get",
|
|
2880
|
+
params: Target.extend(Page.shape),
|
|
2881
|
+
result: Result,
|
|
2882
|
+
handle: (input) => manager.get(input.sessionId, input.delegationId, input.offset, input.limit)
|
|
2883
|
+
});
|
|
2884
|
+
ctx.client.registerMethod({
|
|
2885
|
+
name: "send",
|
|
2886
|
+
params: Target.extend({
|
|
2887
|
+
task: z.string().min(1),
|
|
2888
|
+
requestKey: z.string()
|
|
2889
|
+
}),
|
|
2890
|
+
result: Result,
|
|
2891
|
+
handle: (input) => manager.send(input.sessionId, input.delegationId, input.task, input.requestKey)
|
|
2892
|
+
});
|
|
2893
|
+
registerDelegationCollections(ctx, manager);
|
|
2894
|
+
ctx.client.registerMethod({
|
|
2895
|
+
name: "updates",
|
|
2896
|
+
params: Target.extend({
|
|
2897
|
+
taskId: z.string(),
|
|
2898
|
+
after: z.number().int().nonnegative().default(0)
|
|
2899
|
+
}),
|
|
2900
|
+
result: Result,
|
|
2901
|
+
handle(input) {
|
|
2902
|
+
manager.task(input.sessionId, input.delegationId, input.taskId);
|
|
2903
|
+
return store.updates(input.taskId, input.after);
|
|
2904
|
+
}
|
|
2905
|
+
});
|
|
2906
|
+
ctx.client.registerMethod({
|
|
2907
|
+
name: "settings",
|
|
2908
|
+
params: z.object({}).strict(),
|
|
2909
|
+
result: Result,
|
|
2910
|
+
handle: () => ({
|
|
2911
|
+
limits: store.settings(),
|
|
2912
|
+
instances: store.instances()
|
|
2913
|
+
})
|
|
2914
|
+
});
|
|
2915
|
+
ctx.client.registerMethod({
|
|
2916
|
+
name: "setLimits",
|
|
2917
|
+
params: SettingsSchema,
|
|
2918
|
+
result: SettingsSchema,
|
|
2919
|
+
handle: (input) => store.setSettings(input)
|
|
2920
|
+
});
|
|
2921
|
+
ctx.client.registerMethod({
|
|
2922
|
+
name: "inspectCommand",
|
|
2923
|
+
params: z.object({ command: z.string().min(1).max(4096) }).strict(),
|
|
2924
|
+
result: z.object({
|
|
2925
|
+
status: z.enum([
|
|
2926
|
+
"found",
|
|
2927
|
+
"missing",
|
|
2928
|
+
"directory",
|
|
2929
|
+
"unreadable",
|
|
2930
|
+
"unsupported",
|
|
2931
|
+
"relative-path"
|
|
2932
|
+
]),
|
|
2933
|
+
path: z.string().nullable(),
|
|
2934
|
+
reason: z.string().optional()
|
|
2935
|
+
}).strict(),
|
|
2936
|
+
handle: ({ command }) => inspectCommand(command, commands)
|
|
2937
|
+
});
|
|
2938
|
+
registerPresetCollections(ctx, store, commands);
|
|
2939
|
+
ctx.client.registerMethod({
|
|
2940
|
+
name: "saveInstance",
|
|
2941
|
+
params: InstanceSchema,
|
|
2942
|
+
result: InstanceSchema,
|
|
2943
|
+
handle(input) {
|
|
2944
|
+
validateInstance(input, commands.platform);
|
|
2945
|
+
const prior = store.instances().find((row) => row.id === input.id);
|
|
2946
|
+
return store.saveInstance({
|
|
2947
|
+
...input,
|
|
2948
|
+
revision: (prior?.revision ?? -1) + 1
|
|
2949
|
+
});
|
|
2950
|
+
}
|
|
2951
|
+
});
|
|
2952
|
+
const ui = fileURLToPath(new URL("../ui/ui.js", import.meta.url));
|
|
2953
|
+
if (existsSync(ui)) ctx.client.registerUi({ module: ui });
|
|
2954
|
+
}
|
|
2955
|
+
};
|
|
2956
|
+
//#endregion
|
|
2957
|
+
export { TOOL_NAMES, acpPlugin, acpPlugin as default };
|