@eum-agent/integration-acp 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,184 +1,103 @@
1
+ import { t as control } from "./control-_lHBoljq.js";
1
2
  import { createRequire } from "node:module";
2
3
  import { createHash, randomUUID } from "node:crypto";
3
4
  import { accessSync, constants, existsSync, readFileSync, realpathSync, statSync } from "node:fs";
5
+ import { basename, dirname, join, posix, resolve, win32 } from "node:path";
4
6
  import { fileURLToPath } from "node:url";
5
7
  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
8
  import { mkdtemp, rm } from "node:fs/promises";
11
9
  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
10
+ //#region src/body-document.ts
11
+ const LocalBodyRefSchema = z.strictObject({
12
+ bodyId: z.uuid(),
13
+ codec: z.enum([
14
+ "utf8-text",
15
+ "json",
16
+ "opaque"
17
+ ]),
18
+ formatVersion: z.literal(1),
19
+ byteLength: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
20
+ sha256: z.string().regex(/^[a-f0-9]{64}$/)
21
21
  });
22
- /** Times out protocol control operations without retrying or exposing remote error text. */
23
- async function control(promise, ms = 3e4) {
24
- let timer;
22
+ async function captureTextBody(text, ctx) {
23
+ ctx.signal.throwIfAborted();
24
+ const writer = await ctx.openBody("utf8-text", ctx.signal);
25
+ const encoder = new TextEncoder();
26
+ let offset = 0;
27
+ let index = 0;
25
28
  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);
29
+ while (index < text.length) {
30
+ ctx.signal.throwIfAborted();
31
+ const chunk = /* @__PURE__ */ new Uint8Array(65536);
32
+ let end = Math.min(text.length, index + 32768);
33
+ if (end < text.length && /[\uD800-\uDBFF]/u.test(text[end - 1])) end--;
34
+ const { read, written } = encoder.encodeInto(text.slice(index, end), chunk);
35
+ if (!read) throw new Error("text_encoding_failed");
36
+ await writer.write(offset, chunk.subarray(0, written), ctx.signal);
37
+ offset += written;
38
+ index += read;
39
+ }
40
+ return (await writer.seal(ctx.signal)).body;
41
+ } catch (error) {
42
+ await writer.abort();
43
+ throw error;
31
44
  }
32
45
  }
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);
46
+ function createTextDocuments(render) {
47
+ const documents = /* @__PURE__ */ new WeakMap();
48
+ const prepare = (value, ctx) => {
49
+ const key = typeof value === "object" && value !== null ? value : void 0;
50
+ const prior = key ? documents.get(key) : void 0;
51
+ if (prior) return prior;
52
+ const work = (async () => {
53
+ const input = render(value);
54
+ const literals = input.nodes.filter((node) => node.kind === "literal");
55
+ const lengths = literals.map((node) => new TextEncoder().encode(node.text).byteLength);
56
+ if (literals.length === input.nodes.length && (lengths.some((length) => length > 4096) || lengths.reduce((sum, length) => sum + length, 0) > 16384 || input.nodes.length > 256)) {
57
+ const body = await captureTextBody(literals.map((node) => node.text).join(""), ctx);
58
+ return {
59
+ formatVersion: 1,
60
+ rendererVersion: 1,
61
+ nodes: [{
62
+ id: "text",
63
+ kind: "text-range",
64
+ body,
65
+ startByte: 0,
66
+ endByte: body.byteLength
67
+ }]
68
+ };
47
69
  }
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;
70
+ if (lengths.some((length) => length > 4096) || lengths.reduce((sum, length) => sum + length, 0) > 16384) {
71
+ const nodes = [];
72
+ const all = lengths.reduce((sum, length) => sum + length, 0) > 16384;
73
+ for (const node of input.nodes) {
74
+ if (node.kind !== "literal" || !all && new TextEncoder().encode(node.text).byteLength <= 4096) {
75
+ nodes.push(node);
76
+ continue;
110
77
  }
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");
78
+ const body = await captureTextBody(node.text, ctx);
79
+ nodes.push({
80
+ id: node.id,
81
+ kind: "text-range",
82
+ body,
83
+ startByte: 0,
84
+ endByte: body.byteLength
85
+ });
157
86
  }
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"
87
+ return {
88
+ ...input,
89
+ nodes
90
+ };
170
91
  }
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
- }
92
+ return input;
93
+ })();
94
+ if (key) documents.set(key, work);
95
+ return work;
96
+ };
97
+ return {
98
+ prepare,
99
+ formatModel: prepare
100
+ };
182
101
  }
183
102
  //#endregion
184
103
  //#region src/adapters.ts
@@ -195,7 +114,6 @@ const adapters = {
195
114
  variable: "CODEX_PATH"
196
115
  }
197
116
  };
198
- /** Resolves the installed adapter without importing or executing its program. */
199
117
  function bundledAdapter(id) {
200
118
  const adapter = adapters[id];
201
119
  if (id === "codex") {
@@ -221,10 +139,6 @@ function bundledAdapter(id) {
221
139
  variable: adapter.variable
222
140
  };
223
141
  }
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
142
  function instanceLaunch(instance, execPath) {
229
143
  if (!instance.adapter) return {
230
144
  command: instance.command,
@@ -248,8 +162,168 @@ function instanceLaunch(instance, execPath) {
248
162
  };
249
163
  }
250
164
  //#endregion
165
+ //#region src/tool-document.ts
166
+ const acpResultNodeId = (index) => `acp-result-${index}`;
167
+ function acpReadDocument(data) {
168
+ const nodes = [];
169
+ if (!data.ok) nodes.push({
170
+ id: "failure",
171
+ kind: "literal",
172
+ text: `${data.error.code}: ${data.error.message}\n`
173
+ });
174
+ else for (const [index, row] of data.items.entries()) {
175
+ if ("instanceId" in row) {
176
+ nodes.push({
177
+ id: `adapter-${index}`,
178
+ kind: "literal",
179
+ text: `Configured ACP adapter ${row.instanceId}: ${row.label}; requested execution mode ${row.executionMode}.\n`
180
+ });
181
+ continue;
182
+ }
183
+ if ("delegation" in row) {
184
+ nodes.push({
185
+ id: `delegation-${index}`,
186
+ kind: "literal",
187
+ text: `ACP ${row.delegation.delegationId} (${row.delegation.label}): ${row.delegation.connectionState}; actual execution ${row.delegation.execution?.mode ?? "unrecorded"}; latest task ${row.latest?.taskId ?? "none"} ${row.latest?.state ?? ""}.\n`
188
+ });
189
+ continue;
190
+ }
191
+ if (row.error) nodes.push({
192
+ id: `error-${row.index}`,
193
+ kind: "literal",
194
+ text: `${row.target.delegationId}: ${row.error.code}: ${row.error.message}\n`
195
+ });
196
+ const value = row.value;
197
+ if (!value) continue;
198
+ if ("body" in value) {
199
+ nodes.push({
200
+ id: `source-${row.index}`,
201
+ kind: "literal",
202
+ text: `ACP ${value.source.delegationId}, task ${value.taskId}, original UTF-8 range ${value.start.seq}:${value.start.byte}\u2013${value.end.seq}:${value.end.byte}; task ${value.originalComplete ? "completed" : "did not complete"}; ${value.complete ? "complete original" : "original fragment"}.\n`
203
+ });
204
+ nodes.push({
205
+ id: acpResultNodeId(row.index),
206
+ kind: "text-range",
207
+ body: value.body,
208
+ startByte: value.startByte,
209
+ endByte: value.endByte
210
+ });
211
+ nodes.push({
212
+ id: `end-${row.index}`,
213
+ kind: "literal",
214
+ text: "\n"
215
+ });
216
+ } else nodes.push({
217
+ id: `status-${row.index}`,
218
+ kind: "literal",
219
+ text: `ACP ${value.delegation.delegationId} (${value.delegation.label}): ${value.delegation.connectionState}; actual execution ${value.delegation.execution?.mode ?? "unrecorded"}; task ${value.task?.taskId ?? "none"} ${value.task?.state ?? ""}. ${value.task?.title ?? ""}\n`
220
+ });
221
+ }
222
+ if (data.next) nodes.push({
223
+ id: "continuation",
224
+ kind: "literal",
225
+ text: `Continue with ${JSON.stringify(data.next)}\n`
226
+ });
227
+ return {
228
+ formatVersion: 1,
229
+ rendererVersion: 1,
230
+ nodes
231
+ };
232
+ }
233
+ function acpReadBusiness(data) {
234
+ const items = data.ok ? data.items : [], failed = !data.ok || items.some((row) => "error" in row && row.error);
235
+ const bodies = items.flatMap((row) => "value" in row && row.value && "body" in row.value ? [row.value.body] : []);
236
+ const successes = items.some((row) => !("error" in row) || !row.error);
237
+ return {
238
+ data,
239
+ execution: { state: failed ? successes ? "partial" : "not-started" : "committed" },
240
+ isError: failed,
241
+ ...!data.ok ? { error: {
242
+ code: data.error.code,
243
+ retryable: data.error.retryable
244
+ } } : {},
245
+ ...bodies.length ? { source: {
246
+ complete: !failed && data.ok && data.complete && items.every((row) => !("value" in row) || !row.value || !("body" in row.value) || row.value.complete),
247
+ bodies
248
+ } } : {},
249
+ presentation: {
250
+ type: "acp-read",
251
+ schemaVersion: 1,
252
+ summary: `${items.length} ACP records`,
253
+ state: failed ? "partial" : data.ok && data.complete ? "ready" : "partial",
254
+ fields: {},
255
+ actions: [],
256
+ bodyRefs: bodies
257
+ }
258
+ };
259
+ }
260
+ function acpFailure(code, message) {
261
+ return {
262
+ data: {
263
+ ok: false,
264
+ error: {
265
+ code,
266
+ message: message.slice(0, 512),
267
+ retryable: false
268
+ },
269
+ next: null
270
+ },
271
+ execution: { state: "not-started" },
272
+ isError: true,
273
+ error: {
274
+ code,
275
+ retryable: false
276
+ }
277
+ };
278
+ }
279
+ function acpControlDocument(data) {
280
+ const nodes = [];
281
+ const task = (value) => `Accepted external task ${value.id} in ${value.delegationId}: ${value.state}.\n`;
282
+ if ("error" in data) nodes.push({
283
+ id: "failure",
284
+ kind: "literal",
285
+ text: `${data.error.code}: ${data.error.message}\n`
286
+ });
287
+ else if ("results" in data) for (const row of data.results) nodes.push({
288
+ id: `member-${row.index}`,
289
+ kind: "literal",
290
+ text: !row.ok ? `${row.target}: ${row.error.code}: ${row.error.message}\n` : "delegationId" in row.value ? task(row.value) : `ACP ${row.target}: ${row.value.stopped ? "stopped" : "not stopped"}; connection ${row.value.closed ? "closed" : "retained"}. Existing file edits remain.\n`
291
+ });
292
+ else nodes.push({
293
+ id: "receipt",
294
+ kind: "literal",
295
+ text: task(data)
296
+ });
297
+ return {
298
+ formatVersion: 1,
299
+ rendererVersion: 1,
300
+ nodes
301
+ };
302
+ }
303
+ function acpControlBusiness(data, type) {
304
+ const failed = "error" in data || "results" in data && data.results.some((row) => !row.ok);
305
+ const successful = "results" in data ? data.results.some((row) => row.ok) : !("error" in data);
306
+ return {
307
+ data,
308
+ execution: { state: failed ? successful ? "partial" : type === "acp-stop" ? "unknown" : "not-started" : "committed" },
309
+ isError: failed,
310
+ ...failed ? { error: {
311
+ code: "error" in data ? data.error.code : "acp_members_failed",
312
+ retryable: false
313
+ } } : {},
314
+ presentation: {
315
+ type,
316
+ schemaVersion: 1,
317
+ summary: "error" in data ? data.error.message : "results" in data ? `${data.results.length} external task outcomes` : `Task ${data.id} accepted`,
318
+ state: failed ? successful ? "partial" : "error" : "ready",
319
+ fields: {},
320
+ actions: [],
321
+ bodyRefs: []
322
+ }
323
+ };
324
+ }
325
+ //#endregion
251
326
  //#region src/launch.ts
252
- /** Rejects relative paths, reserved variables, credentials and invalid values before launch. */
253
327
  function validateInstance(instance, platform = process.platform) {
254
328
  const absolute = (path) => platform === "win32" ? /^(?:[A-Za-z]:[\\/]|[\\/]{2}(?![?.][\\/])[^\\/]+[\\/][^\\/]+(?:[\\/]|$))/.test(path) && win32.isAbsolute(path) : posix.isAbsolute(path);
255
329
  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");
@@ -260,8 +334,7 @@ function validateInstance(instance, platform = process.platform) {
260
334
  if (value.includes("\0")) throw new Error("invalid-environment-input");
261
335
  }
262
336
  }
263
- /** Authorizes the effective argv, real cwd, environment names and mode, then rechecks admission. */
264
- async function prepareLaunch(authority, instance, cwd, services) {
337
+ async function prepareLaunch(authority, instance, cwd, services, acquisition) {
265
338
  const { commands } = services;
266
339
  validateInstance(instance, commands.platform);
267
340
  commands.environment([instance.env]);
@@ -328,6 +401,7 @@ async function prepareLaunch(authority, instance, cwd, services) {
328
401
  ]);
329
402
  };
330
403
  const tmp = await mkdtemp(join(realpathSync(tmpdir()), "yaoguang-acp-"));
404
+ acquisition?.root(tmp);
331
405
  let initialMode = "direct";
332
406
  let initialNames;
333
407
  let fallbackReason;
@@ -366,18 +440,12 @@ async function prepareLaunch(authority, instance, cwd, services) {
366
440
  ],
367
441
  remember: {
368
442
  key,
369
- label: `启动 ${instance.label}(${cwd})`
443
+ label: `\u542f\u52a8 ${instance.label}\uff08${cwd}\uff09`
370
444
  }
371
445
  });
372
446
  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
- };
447
+ else if (decision.result.kind === "record-failed") refused = acpFailure("approval_record_failed", `ACP launch was allowed, but recording it failed: ${decision.result.message}`);
448
+ else if (!decision.result.kind.startsWith("allowed-")) refused = acpFailure("approval_rejected", "ACP launch was not authorized.");
381
449
  } catch (primary) {
382
450
  approvalFailed = true;
383
451
  approvalFailure = primary;
@@ -402,6 +470,7 @@ async function prepareLaunch(authority, instance, cwd, services) {
402
470
  },
403
471
  async launch() {
404
472
  const work = await mkdtemp(join(realpathSync(tmpdir()), "yaoguang-acp-"));
473
+ acquisition?.root(work);
405
474
  let transferred = false;
406
475
  let prepared;
407
476
  try {
@@ -446,6 +515,7 @@ async function prepareLaunch(authority, instance, cwd, services) {
446
515
  });
447
516
  transferred = true;
448
517
  processOwnsObservation = true;
518
+ acquisition?.started(attempt);
449
519
  return await attempt.ready;
450
520
  } catch (error) {
451
521
  if (!transferred) try {
@@ -468,27 +538,34 @@ async function prepareLaunch(authority, instance, cwd, services) {
468
538
  }
469
539
  //#endregion
470
540
  //#region src/inspection.ts
471
- /** Inspects one command using the explicitly supplied physical host, without running it. */
472
541
  function inspectCommand(command, commands, searchPath) {
473
542
  return commands.inspect(command, searchPath === void 0 ? commands.env : commands.environment([commands.env, { PATH: searchPath }]));
474
543
  }
475
544
  //#endregion
476
545
  //#region src/presets.ts
477
- /** Known ACP launch recipes; installation and authentication remain local prerequisites. */
478
546
  const ACP_PRESETS = [
547
+ {
548
+ id: "claude",
549
+ label: "Claude",
550
+ command: "claude",
551
+ args: [],
552
+ adapter: "claude",
553
+ docs: "https://github.com/agentclientprotocol/claude-agent-acp"
554
+ },
479
555
  {
480
556
  id: "codex",
481
557
  label: "Codex",
482
558
  command: "codex",
483
559
  args: [],
560
+ adapter: "codex",
484
561
  docs: "https://github.com/agentclientprotocol/codex-acp"
485
562
  },
486
563
  {
487
- id: "claude",
488
- label: "Claude",
489
- command: "claude",
490
- args: [],
491
- docs: "https://github.com/agentclientprotocol/claude-agent-acp"
564
+ id: "antigravity",
565
+ label: "Antigravity",
566
+ command: "agy",
567
+ args: ["acp"],
568
+ docs: "https://antigravity.google/docs/ide/extensions/acp/"
492
569
  },
493
570
  {
494
571
  id: "openclaw",
@@ -498,9 +575,12 @@ const ACP_PRESETS = [
498
575
  docs: "https://docs.openclaw.ai/cli/acp"
499
576
  }
500
577
  ];
578
+ function presetAdapter(id) {
579
+ const preset = ACP_PRESETS.find((item) => item.id === id);
580
+ return "adapter" in preset ? preset.adapter : void 0;
581
+ }
501
582
  //#endregion
502
583
  //#region src/preset-inspection.ts
503
- /** Inspects a preset's CLI and bundled adapter without starting either or checking login. */
504
584
  async function inspectPreset(id, commands, searchPath) {
505
585
  const preset = ACP_PRESETS.find((item) => item.id === id);
506
586
  const paths = searchPath ?? (commands.platform === "win32" ? void 0 : [
@@ -515,8 +595,9 @@ async function inspectPreset(id, commands, searchPath) {
515
595
  path: cli.path,
516
596
  reason: cli.reason
517
597
  };
518
- if (id !== "openclaw") try {
519
- bundledAdapter(id);
598
+ const adapter = presetAdapter(id);
599
+ if (adapter) try {
600
+ bundledAdapter(adapter);
520
601
  } catch {
521
602
  return {
522
603
  status: "missing-adapter",
@@ -530,7 +611,6 @@ async function inspectPreset(id, commands, searchPath) {
530
611
  }
531
612
  //#endregion
532
613
  //#region src/store.ts
533
- /** One user-configured, already installed and authenticated adapter command. */
534
614
  const InstanceSchema = z.object({
535
615
  id: z.string().regex(/^[a-z0-9][a-z0-9-]*$/),
536
616
  label: z.string().min(1),
@@ -547,17 +627,14 @@ const InstanceSchema = z.object({
547
627
  networkHosts: z.array(z.string()).default([]),
548
628
  revision: z.number().int().nonnegative().default(0)
549
629
  }).strict();
550
- /** Independent per-root limits shared by all adapter instances. */
551
630
  const SettingsSchema = z.object({
552
631
  maxConcurrent: z.number().int().positive().default(4),
553
632
  maxRetainedConnections: z.number().int().positive().default(8)
554
633
  }).strict();
555
- /** Physical execution facts of an admitted ACP root, separate from its configured preference. */
556
634
  const LaunchExecutionSchema = z.object({
557
635
  mode: z.enum(["sandboxed", "direct"]),
558
636
  fallbackReason: z.string().optional()
559
637
  }).strict();
560
- /** Local delegate identity, separate from the remote session id. */
561
638
  const DelegationSchema = z.object({
562
639
  id: z.string(),
563
640
  parentSessionId: z.string(),
@@ -581,13 +658,30 @@ const DelegationSchema = z.object({
581
658
  ]),
582
659
  createdAt: z.number()
583
660
  }).strict();
584
- /** One accepted external prompt, queued or executing. */
661
+ const DispatchSettingSchema = z.discriminatedUnion("availability", [z.strictObject({
662
+ availability: z.literal("resolved"),
663
+ value: z.string().min(1).max(1024),
664
+ origin: z.literal("remote")
665
+ }), z.strictObject({ availability: z.enum([
666
+ "unreported",
667
+ "not-applicable",
668
+ "pending"
669
+ ]) })]);
670
+ const DispatchSettingsSchema = z.strictObject({
671
+ capturedAt: z.number(),
672
+ provider: DispatchSettingSchema,
673
+ model: DispatchSettingSchema,
674
+ effort: DispatchSettingSchema
675
+ });
585
676
  const TaskSchema = z.object({
586
677
  id: z.string(),
587
678
  delegationId: z.string(),
588
679
  requestKey: z.string(),
589
680
  targetGeneration: z.number().int().nonnegative(),
681
+ targetStopEpoch: z.number().int().nonnegative(),
682
+ targetRunId: z.string().optional(),
590
683
  input: z.string(),
684
+ dispatchSettings: DispatchSettingsSchema.optional(),
591
685
  state: z.enum([
592
686
  "queued",
593
687
  "starting",
@@ -606,9 +700,10 @@ const TaskSchema = z.object({
606
700
  result: z.string(),
607
701
  truncated: z.boolean(),
608
702
  createdAt: z.number(),
703
+ startedAt: z.number().int().nonnegative().optional(),
704
+ endedAt: z.number().int().nonnegative().optional(),
609
705
  revision: z.number().int()
610
706
  }).strict();
611
- /** Metadata read by model status pages without accepted task or output bodies. */
612
707
  const AcpTaskSummarySchema = z.strictObject({
613
708
  taskId: z.string(),
614
709
  delegationId: z.string(),
@@ -617,10 +712,12 @@ const AcpTaskSummarySchema = z.strictObject({
617
712
  outcome: TaskSchema.shape.outcome,
618
713
  revision: z.number(),
619
714
  createdAt: z.number(),
715
+ startedAt: z.number().int().nonnegative().optional(),
716
+ endedAt: z.number().int().nonnegative().optional(),
620
717
  resultAvailable: z.boolean(),
718
+ dispatchSettings: DispatchSettingsSchema.optional(),
621
719
  error: z.string().nullable()
622
720
  });
623
- /** Delegation identity excludes command, environment, configuration and permissions. */
624
721
  const AcpDelegationSummarySchema = z.strictObject({
625
722
  delegationId: z.string(),
626
723
  instanceId: z.string(),
@@ -629,7 +726,32 @@ const AcpDelegationSummarySchema = z.strictObject({
629
726
  createdAt: z.number(),
630
727
  execution: LaunchExecutionSchema.nullable()
631
728
  });
632
- /** ACP storage, always under the host-issued owner table prefix. */
729
+ const AcpDelegatedTaskSchema = z.strictObject({
730
+ parentSessionId: z.string(),
731
+ rootSessionId: z.string(),
732
+ taskId: z.string(),
733
+ delegationId: z.string(),
734
+ instanceId: z.string(),
735
+ label: z.string(),
736
+ input: z.string(),
737
+ state: TaskSchema.shape.state,
738
+ outcome: TaskSchema.shape.outcome,
739
+ revision: z.number(),
740
+ createdAt: z.number()
741
+ });
742
+ const StatusByTasksParams = z.strictObject({
743
+ sessionId: z.string().min(1).max(256),
744
+ taskIds: z.array(z.string().min(1).max(256)).min(1).max(50).refine((ids) => new Set(ids).size === ids.length, "task ids must be unique")
745
+ });
746
+ const StatusByTasksResult = z.array(z.discriminatedUnion("status", [z.strictObject({
747
+ taskId: z.string(),
748
+ status: z.literal("not-found")
749
+ }), z.strictObject({
750
+ taskId: z.string(),
751
+ status: z.literal("found"),
752
+ task: AcpTaskSummarySchema,
753
+ delegation: AcpDelegationSummarySchema
754
+ })]));
633
755
  function createAcpStore(storage) {
634
756
  const { db, tableName } = storage;
635
757
  const settings = tableName("settings"), instances = tableName("instance"), delegations = tableName("delegation"), tasks = tableName("task"), updates = tableName("update");
@@ -637,19 +759,36 @@ function createAcpStore(storage) {
637
759
  CREATE TABLE IF NOT EXISTS ${instances}(id TEXT NOT NULL PRIMARY KEY,payload TEXT NOT NULL) STRICT;
638
760
  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
761
  CREATE INDEX IF NOT EXISTS ${tableName("delegation_root")} ON ${delegations}(root_session_id);
762
+ CREATE INDEX IF NOT EXISTS ${tableName("delegation_parent")} ON ${delegations}(parent_session_id);
640
763
  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
764
  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
765
  INSERT OR IGNORE INTO ${settings} VALUES(1,4,8);`);
643
766
  let membership = 0, configuration = 0;
644
- const taskSummaryProjection = `json_object('taskId',id,'delegationId',delegation_id,
767
+ const taskSummaryProjection = `json_patch(json_patch(json_object('taskId',id,'delegationId',delegation_id,
645
768
  'title',substr(json_extract(payload,'$.input'),1,256),'state',json_extract(payload,'$.state'),
646
769
  'outcome',json_extract(payload,'$.outcome'),'revision',json_extract(payload,'$.revision'),
647
770
  '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`;
771
+ 'error',substr(json_extract(payload,'$.error'),1,256)),
772
+ json_object('startedAt',json_extract(payload,'$.startedAt'),'endedAt',json_extract(payload,'$.endedAt'))),
773
+ CASE WHEN json_type(payload,'$.dispatchSettings') = 'object'
774
+ THEN json_object('dispatchSettings',json_extract(payload,'$.dispatchSettings'))
775
+ ELSE json('{}') END) AS summary`;
649
776
  const delegationSummaryProjection = `json_object('delegationId',id,'instanceId',json_extract(payload,'$.instance.id'),
650
777
  'label',substr(json_extract(payload,'$.instance.label'),1,256),'connectionState',json_extract(payload,'$.connectionState'),
651
778
  'createdAt',json_extract(payload,'$.createdAt'),'execution',json_extract(payload,'$.execution')) AS summary`;
652
779
  return {
780
+ connectionIdentity: storage.connectionIdentity,
781
+ activityCounts(sessionId) {
782
+ const row = db.prepare(`SELECT
783
+ COALESCE(MAX(json_extract(t.payload,'$.state') NOT IN ('finished','awaiting-permission')),0) AS active,
784
+ COALESCE(MAX(json_extract(t.payload,'$.state') = 'awaiting-permission'),0) AS awaiting_human
785
+ FROM ${delegations} d JOIN ${tasks} t ON t.delegation_id = d.id
786
+ WHERE d.parent_session_id = ?`).get(sessionId);
787
+ return {
788
+ active: Number(row.active) === 1,
789
+ awaitingHuman: Number(row.awaiting_human) === 1
790
+ };
791
+ },
653
792
  transaction(write) {
654
793
  db.exec("BEGIN IMMEDIATE");
655
794
  try {
@@ -690,6 +829,10 @@ function createAcpStore(storage) {
690
829
  const row = db.prepare(`SELECT payload FROM ${delegations} WHERE id=?`).get(id);
691
830
  return row ? DelegationSchema.parse(JSON.parse(String(row.payload))) : void 0;
692
831
  },
832
+ taskDelegation(id) {
833
+ const row = db.prepare(`SELECT delegation_id FROM ${tasks} WHERE id=?`).get(id);
834
+ return row ? String(row.delegation_id) : void 0;
835
+ },
693
836
  task(id, maxBytes) {
694
837
  if (maxBytes !== void 0) {
695
838
  const size = db.prepare(`SELECT length(CAST(payload AS BLOB)) AS bytes FROM ${tasks} WHERE id=?`).get(id);
@@ -709,7 +852,6 @@ function createAcpStore(storage) {
709
852
  tasks(id) {
710
853
  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
854
  },
712
- /** Reads one bounded history page after checking stored payload bytes before decoding. */
713
855
  tasksPage(id, offset, limit, maxBytes) {
714
856
  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
857
  if (Number(bytes.bytes) > maxBytes) throw Object.assign(/* @__PURE__ */ new Error("stored task page exceeds declared budget"), { code: "read-limit" });
@@ -719,7 +861,6 @@ function createAcpStore(storage) {
719
861
  total
720
862
  };
721
863
  },
722
- /** Returns immutable visibility facts without launch configuration. */
723
864
  delegationIdentity(id) {
724
865
  const row = db.prepare(`SELECT id,parent_session_id,root_session_id FROM ${delegations} WHERE id=?`).get(id);
725
866
  return row ? {
@@ -728,17 +869,14 @@ function createAcpStore(storage) {
728
869
  rootSessionId: String(row.root_session_id)
729
870
  } : void 0;
730
871
  },
731
- /** Projects a single current or named task status before decoding. */
732
872
  summary(id, taskId) {
733
873
  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
874
  return row ? AcpTaskSummarySchema.parse(JSON.parse(String(row.summary))) : void 0;
735
875
  },
736
- /** One public identity, without adapter arguments or credential-bearing environment. */
737
876
  delegationSummary(id) {
738
877
  const row = db.prepare(`SELECT ${delegationSummaryProjection} FROM ${delegations} WHERE id=?`).get(id);
739
878
  return row ? AcpDelegationSummarySchema.parse(JSON.parse(String(row.summary))) : void 0;
740
879
  },
741
- /** Reads bounded summaries in a keyset range; status changes do not mutate membership. */
742
880
  summaryPage(id, input) {
743
881
  if (!Number.isSafeInteger(input.limit) || input.limit < 1 || input.limit > 100) throw new Error("Invalid task page limit");
744
882
  const observed = db.prepare(`SELECT COUNT(*) AS count,COALESCE(MAX(rowid),0) AS upper FROM ${tasks} WHERE delegation_id=?`).get(id);
@@ -756,7 +894,6 @@ function createAcpStore(storage) {
756
894
  complete: rows.length <= input.limit
757
895
  };
758
896
  },
759
- /** Reads root-scoped identity metadata without restoring historical delegation bodies. */
760
897
  delegationSummaryPage(root, input) {
761
898
  const observed = db.prepare(`SELECT COUNT(*) AS count,COALESCE(MAX(rowid),0) AS upper FROM ${delegations} WHERE root_session_id=?`).get(root);
762
899
  const source = `${membership}:${observed.count}:${observed.upper}`;
@@ -774,7 +911,6 @@ function createAcpStore(storage) {
774
911
  complete: rows.length <= input.limit
775
912
  };
776
913
  },
777
- /** Public adapter discovery uses only bounded identity columns inside SQLite. */
778
914
  instanceSummaryPage(input) {
779
915
  const source = String(configuration);
780
916
  if (input.source !== void 0 && input.source !== source) throw new Error("source_changed: ACP instances changed");
@@ -790,12 +926,15 @@ function createAcpStore(storage) {
790
926
  }))
791
927
  };
792
928
  },
793
- /** Reads UTF-8 byte positions and at most limit code points through the existing task/sequence primary key. */
794
929
  readResult(taskId, input) {
795
930
  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
931
  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));
932
+ const storedText = `CAST(json_extract(payload,'$.content.text') AS BLOB)`;
933
+ const readRow = db.prepare(`SELECT seq,CASE WHEN length(${storedText})=0 THEN X'' ELSE substr(${storedText},?,?) END AS bytes,length(${storedText}) AS total FROM ${updates} WHERE task_id=? AND seq>=? AND ${textFilter} ORDER BY seq LIMIT 1`);
934
+ const followingRow = db.prepare(`SELECT seq FROM ${updates} WHERE task_id=? AND seq>? AND ${textFilter} ORDER BY seq LIMIT 1`);
935
+ const row = readRow.get(input.offset + 1, input.limit * 4 + 3, taskId, Math.max(1, input.seq));
798
936
  if (!row && input.seq > 0) throw new Error("source_changed: original update disappeared");
937
+ const original = Number(db.prepare(`SELECT COALESCE(SUM(length(${storedText})),0) AS total FROM ${updates} WHERE task_id=? AND ${textFilter}`).get(taskId)?.total ?? 0);
799
938
  if (!row) return {
800
939
  taskId,
801
940
  text: "",
@@ -807,72 +946,125 @@ function createAcpStore(storage) {
807
946
  seq: input.seq,
808
947
  offset: input.offset
809
948
  },
810
- total: 0,
949
+ segments: [],
950
+ total: original,
811
951
  complete: true,
812
952
  next: null
813
953
  };
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", {
954
+ if (input.seq > 0 && Number(row.seq) !== input.seq) throw new Error("source_changed: original update disappeared");
955
+ const decoder = new TextDecoder("utf-8", {
827
956
  fatal: true,
828
957
  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;
958
+ });
959
+ const segments = [];
960
+ let text = "", remaining = input.limit, current = row, offset = input.offset, next = null;
961
+ while (current) {
962
+ const seq = Number(current.seq), total = Number(current.total);
963
+ if (offset > total) throw new Error("source_changed: result position is beyond original text");
964
+ if (!(current.bytes instanceof Uint8Array)) throw new Error("Stored original text has invalid bytes");
965
+ const bytes = current.bytes;
966
+ let usable = bytes.length;
967
+ if (offset + usable < total) {
968
+ while (usable && (bytes[usable - 1] & 192) === 128) usable--;
969
+ if (usable < bytes.length || usable && bytes[usable - 1] >= 192) {
970
+ const leading = Math.max(0, usable - 1), first = bytes[leading], width = first >= 240 ? 4 : first >= 224 ? 3 : 2;
971
+ usable = bytes.length - leading < width ? leading : bytes.length;
972
+ }
973
+ }
974
+ const piece = [...decoder.decode(bytes.subarray(0, usable))].slice(0, remaining).join("");
975
+ const end = offset + Buffer.byteLength(piece);
976
+ segments.push({
977
+ seq,
978
+ offset,
979
+ bytes: end - offset,
980
+ total
981
+ });
982
+ text += piece;
983
+ remaining -= [...piece].length;
984
+ if (end < total) {
985
+ next = {
986
+ seq,
987
+ offset: end
988
+ };
989
+ break;
990
+ }
991
+ const following = followingRow.get(taskId, seq);
992
+ if (!following) break;
993
+ if (remaining === 0) {
994
+ next = {
995
+ seq: Number(following.seq),
996
+ offset: 0
997
+ };
998
+ break;
999
+ }
1000
+ current = readRow.get(1, remaining * 4 + 3, taskId, Number(following.seq));
1001
+ offset = 0;
1002
+ if (!current || Number(current.seq) !== Number(following.seq)) throw new Error("source_changed: original update disappeared");
1003
+ }
1004
+ const last = segments.at(-1);
840
1005
  return {
841
1006
  taskId,
842
1007
  text,
843
1008
  start: {
844
- seq,
1009
+ seq: segments[0].seq,
845
1010
  offset: input.offset
846
1011
  },
847
1012
  end: {
848
- seq,
849
- offset: end
1013
+ seq: last.seq,
1014
+ offset: last.offset + last.bytes
850
1015
  },
851
- total,
1016
+ segments,
1017
+ total: original,
852
1018
  complete: next === null,
853
1019
  next
854
1020
  };
855
1021
  },
856
- /** Streams visibility identities without decoding historical delegation bodies. */
857
1022
  *delegationIdentities() {
858
1023
  for (const row of db.prepare(`SELECT id,parent_session_id FROM ${delegations} ORDER BY rowid DESC`).iterate()) yield {
859
1024
  id: String(row.id),
860
1025
  parentSessionId: String(row.parent_session_id)
861
1026
  };
862
1027
  },
863
- /** Projects the latest bounded summary inside SQLite before returning text to the host. */
1028
+ tasksByParent(parent, input) {
1029
+ const from = `FROM ${tasks} AS t JOIN ${delegations} AS d ON d.id=t.delegation_id
1030
+ WHERE d.parent_session_id=? AND (?=0 OR json_extract(t.payload,'$.state')<>'finished')`;
1031
+ const projection = `json_object('parentSessionId',d.parent_session_id,'rootSessionId',d.root_session_id,
1032
+ 'taskId',t.id,'delegationId',t.delegation_id,'instanceId',json_extract(d.payload,'$.instance.id'),
1033
+ 'label',substr(json_extract(d.payload,'$.instance.label'),1,256),'input',json_extract(t.payload,'$.input'),
1034
+ 'state',json_extract(t.payload,'$.state'),'outcome',json_extract(t.payload,'$.outcome'),
1035
+ 'revision',json_extract(t.payload,'$.revision'),'createdAt',json_extract(t.payload,'$.createdAt'))`;
1036
+ const active = input.activeOnly ? 1 : 0;
1037
+ const size = db.prepare(`SELECT COALESCE(SUM(length(CAST(${projection} AS BLOB))),0) AS bytes ${from}`).get(parent, active);
1038
+ if (Number(size.bytes) > input.maxBytes) throw Object.assign(/* @__PURE__ */ new Error("stored parent tasks exceed declared budget"), { code: "read-limit" });
1039
+ return db.prepare(`SELECT ${projection} AS task ${from} ORDER BY json_extract(t.payload,'$.createdAt'),t.rowid`).all(parent, active).map((row) => AcpDelegatedTaskSchema.parse(JSON.parse(String(row.task))));
1040
+ },
1041
+ parentProgress(parent, retainedOnly = false) {
1042
+ const row = db.prepare(`
1043
+ SELECT COUNT(*) AS total,
1044
+ COALESCE(SUM(CASE WHEN json_extract(t.payload,'$.state')='finished'
1045
+ AND json_extract(t.payload,'$.outcome')='completed' THEN 1 ELSE 0 END),0) AS completed
1046
+ FROM ${delegations} AS d
1047
+ LEFT JOIN ${tasks} AS t ON t.rowid=(
1048
+ SELECT MAX(latest.rowid) FROM ${tasks} AS latest WHERE latest.delegation_id=d.id
1049
+ )
1050
+ WHERE d.parent_session_id=?
1051
+ ${retainedOnly ? "AND json_extract(d.payload,'$.connectionState') NOT IN ('closed','interrupted')" : ""}
1052
+ `).get(parent);
1053
+ return {
1054
+ completed: Number(row.completed),
1055
+ total: Number(row.total)
1056
+ };
1057
+ },
864
1058
  taskSummary(id) {
865
1059
  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
1060
  return row ? TaskSchema.parse(JSON.parse(String(row.payload))) : void 0;
867
1061
  },
868
- /** Returns bounded queue identities in persistent admission order for one root. */
869
1062
  queued(root) {
870
1063
  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
1064
  id: String(row.id),
872
1065
  delegationId: String(row.delegation_id)
873
1066
  }));
874
1067
  },
875
- /** Counts root resource reservations without allocating historical task bodies. */
876
1068
  rootUsage(root, except) {
877
1069
  return {
878
1070
  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),
@@ -905,14 +1097,24 @@ function createAcpStore(storage) {
905
1097
  }
906
1098
  };
907
1099
  }
1100
+ function createAcpRetention(storage, { deleteWhere, prepareDeletion }) {
1101
+ const { db, tableName } = storage;
1102
+ const delegations = tableName("delegation"), tasks = tableName("task");
1103
+ const owned = `SELECT id FROM ${delegations}
1104
+ WHERE root_session_id IN (SELECT value FROM json_each(?))
1105
+ OR parent_session_id IN (SELECT value FROM json_each(?))`;
1106
+ return { purgeSessions(sessionIds, cursor, budget) {
1107
+ const ids = JSON.stringify(sessionIds);
1108
+ return prepareDeletion([
1109
+ deleteWhere(db, tableName("update"), `task_id IN (SELECT id FROM ${tasks} WHERE delegation_id IN (${owned}))`, ids, ids),
1110
+ deleteWhere(db, tasks, `delegation_id IN (${owned})`, ids, ids),
1111
+ deleteWhere(db, delegations, `id IN (${owned})`, ids, ids)
1112
+ ], cursor, budget);
1113
+ } };
1114
+ }
908
1115
  //#endregion
909
1116
  //#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
- ]);
1117
+ const PresetId = z.enum(ACP_PRESETS.map((preset) => preset.id));
916
1118
  const Inspection = z.strictObject({
917
1119
  status: z.enum([
918
1120
  "found",
@@ -947,7 +1149,6 @@ const Added = z.discriminatedUnion("operationState", [
947
1149
  cleanup: z.array(Failure)
948
1150
  })
949
1151
  ]);
950
- /** An owner-local ordered result that exposes only the target identity. */
951
1152
  function collectionResult(value) {
952
1153
  const identity = {
953
1154
  index: z.number().int().nonnegative(),
@@ -963,7 +1164,6 @@ function collectionResult(value) {
963
1164
  error: Failure
964
1165
  })])) });
965
1166
  }
966
- /** Checks complete input bytes and declared member budgets before starting work. */
967
1167
  function collectionInput(shape, key) {
968
1168
  return z.strictObject(shape).superRefine((value, context) => {
969
1169
  const input = value;
@@ -978,7 +1178,6 @@ function collectionInput(shape, key) {
978
1178
  });
979
1179
  });
980
1180
  }
981
- /** Settles every member and refuses oversized encoded results without losing other members. */
982
1181
  async function settleCollection(ids, work, limits) {
983
1182
  const results = [];
984
1183
  let bytes = 8192;
@@ -1010,7 +1209,6 @@ async function settleCollection(ids, work, limits) {
1010
1209
  }
1011
1210
  return { results };
1012
1211
  }
1013
- /** Registers array preset inspection, atomic creation and independent removal. */
1014
1212
  function registerPresetCollections(ctx, store, commands) {
1015
1213
  const changed = ctx.client.registerFrame({
1016
1214
  name: "instancesChanged",
@@ -1020,7 +1218,7 @@ function registerPresetCollections(ctx, store, commands) {
1020
1218
  ctx.client.registerMethod({
1021
1219
  name: "inspectPresets",
1022
1220
  params: collectionInput({
1023
- ids: z.array(PresetId).min(1).max(3),
1221
+ ids: z.array(PresetId).min(1).max(ACP_PRESETS.length),
1024
1222
  maxItemBytes: z.number().int().min(1).max(8388608).default(262144),
1025
1223
  maxTotalBytes: z.number().int().min(1).max(8388608).default(8388608)
1026
1224
  }, "ids"),
@@ -1031,7 +1229,7 @@ function registerPresetCollections(ctx, store, commands) {
1031
1229
  name: "addPresets",
1032
1230
  params: collectionInput({
1033
1231
  operationId: z.uuid(),
1034
- ids: z.array(PresetId).min(1).max(3)
1232
+ ids: z.array(PresetId).min(1).max(ACP_PRESETS.length)
1035
1233
  }, "ids"),
1036
1234
  result: Added,
1037
1235
  async handle(input) {
@@ -1049,12 +1247,13 @@ function registerPresetCollections(ctx, store, commands) {
1049
1247
  const result = await inspectPreset(id, commands);
1050
1248
  if (result.status !== "found" || !result.path) throw new Error(result.status);
1051
1249
  const preset = ACP_PRESETS.find((item) => item.id === id);
1250
+ const adapter = presetAdapter(id);
1052
1251
  const instance = InstanceSchema.parse({
1053
1252
  id: `${id}-${randomUUID()}`,
1054
1253
  label: preset.label,
1055
1254
  command: result.path,
1056
1255
  args: [...preset.args],
1057
- ...id === "openclaw" ? {} : { adapter: id },
1256
+ ...adapter ? { adapter } : {},
1058
1257
  executionMode: "trusted"
1059
1258
  });
1060
1259
  validateInstance(instance, commands.platform);
@@ -1089,7 +1288,6 @@ function registerPresetCollections(ctx, store, commands) {
1089
1288
  }
1090
1289
  });
1091
1290
  }
1092
- /** Stops or closes independent delegation members only after their actual cleanup settles. */
1093
1291
  function registerDelegationCollections(ctx, manager) {
1094
1292
  const params = collectionInput({
1095
1293
  sessionId: z.string().min(1),
@@ -1097,6 +1295,7 @@ function registerDelegationCollections(ctx, manager) {
1097
1295
  }, "delegationIds");
1098
1296
  ctx.client.registerMethod({
1099
1297
  name: "stopDelegations",
1298
+ session: { kind: "read" },
1100
1299
  params,
1101
1300
  result: collectionResult(z.strictObject({ stopped: z.boolean() })),
1102
1301
  handle: (input) => manager.collection(input.delegationIds, () => settleCollection(input.delegationIds, async (id) => {
@@ -1107,6 +1306,7 @@ function registerDelegationCollections(ctx, manager) {
1107
1306
  });
1108
1307
  ctx.client.registerMethod({
1109
1308
  name: "closeDelegations",
1309
+ session: { kind: "read" },
1110
1310
  params,
1111
1311
  result: collectionResult(z.strictObject({ closed: z.boolean() })),
1112
1312
  handle: (input) => manager.collection(input.delegationIds, () => settleCollection(input.delegationIds, async (id) => {
@@ -1131,7 +1331,7 @@ const ACP_GUIDANCE = {
1131
1331
  },
1132
1332
  {
1133
1333
  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."
1334
+ 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. A target awaiting-permission ends the wait early: report that it needs a human answer and do not repeatedly poll or request a final result while it is blocked. Completed results are delivered to the parent session automatically. 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
1335
  },
1136
1336
  {
1137
1337
  tools: ["acp_list"],
@@ -1139,21 +1339,29 @@ const ACP_GUIDANCE = {
1139
1339
  },
1140
1340
  {
1141
1341
  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."
1342
+ text: "`acp_send` continues the original delegationId and returns a short acceptance receipt. A closed connection is relaunched after approval and resumes its saved remote session; unsupported remote recovery fails with resume-unavailable rather than creating a replacement session. Keep its task ID and query status; do not resend accepted work because the receipt was shortened."
1143
1343
  },
1144
1344
  {
1145
1345
  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."
1346
+ text: "`acp_stop` accepts items with delegationId and optional close; results report actual settled cleanup per member. Task completion keeps the connection alive until it has been idle for 30 minutes with no queued or running task and no pending permission; it then closes automatically. close:true cancels queued tasks, closes the process and releases its connection slot at once. Close connections you no longer need; retain delegationId: a later acp_send resumes a closed delegation. Changes already made stay."
1147
1347
  }
1148
1348
  ]
1149
1349
  };
1150
1350
  //#endregion
1151
1351
  //#region src/manager.ts
1152
- /** The question id an ACP permission is asked under: one question per request. */
1352
+ var InvalidConfigValue = class extends Error {
1353
+ hint;
1354
+ constructor(configId, value, accepted) {
1355
+ super("invalid-config-value");
1356
+ this.hint = `${configId} does not accept ${value}; accepted values: ${accepted.join(", ")}`.slice(0, 1024);
1357
+ }
1358
+ };
1359
+ const ACP_IDLE_CLOSE_MS = 18e5;
1360
+ const unrefTimers = {
1361
+ set: (callback, ms) => setTimeout(callback, ms).unref(),
1362
+ clear: (handle) => clearTimeout(handle)
1363
+ };
1153
1364
  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
1365
  function permissionQuestion(label, request) {
1158
1366
  const subject = request.toolCall.title?.trim() || "permission requested";
1159
1367
  return {
@@ -1170,20 +1378,53 @@ function permissionQuestion(label, request) {
1170
1378
  }]
1171
1379
  };
1172
1380
  }
1173
- /** Creates a coordinator that accepts background prompts without waiting for completion. */
1381
+ function dispatchSettings(row) {
1382
+ const read = (category) => {
1383
+ const option = row.configOptions?.find((value) => typeof value === "object" && value !== null && "category" in value && value.category === category);
1384
+ if (!option || option.type !== "select" || typeof option.currentValue !== "string" || option.currentValue.length === 0 || option.currentValue.length > 1024) return { availability: "unreported" };
1385
+ return {
1386
+ availability: "resolved",
1387
+ value: option.currentValue,
1388
+ origin: "remote"
1389
+ };
1390
+ };
1391
+ return {
1392
+ capturedAt: Date.now(),
1393
+ provider: { availability: "unreported" },
1394
+ model: read("model"),
1395
+ effort: read("thought_level")
1396
+ };
1397
+ }
1174
1398
  function createAcpManager(deps) {
1175
1399
  const { store, sessions, delivery } = deps;
1400
+ if (store.connectionIdentity !== deps.unitOfWork.connectionIdentity) throw new Error("ACP tasks and activity must share the host connection");
1176
1401
  const connections = /* @__PURE__ */ new Map();
1177
1402
  const processes = /* @__PURE__ */ new Map();
1178
1403
  const running = /* @__PURE__ */ new Map();
1179
1404
  const starting = /* @__PURE__ */ new Map();
1180
1405
  const stopping = /* @__PURE__ */ new Set();
1181
1406
  const launches = /* @__PURE__ */ new Map();
1407
+ const prompting = /* @__PURE__ */ new Set();
1408
+ const cancelWaitMs = deps.cancelWaitMs ?? 5e3;
1409
+ const idleTimers = deps.idleTimers ?? unrefTimers;
1410
+ const idle = /* @__PURE__ */ new Map();
1182
1411
  const permissions = /* @__PURE__ */ new Map();
1183
1412
  let closed = false;
1184
1413
  let withdrawn = false;
1185
1414
  const collections = /* @__PURE__ */ new Set();
1186
1415
  const changed = (delegation, task) => {
1416
+ const header = task ? Object.freeze({
1417
+ parentSessionId: delegation.parentSessionId,
1418
+ delegationId: delegation.id,
1419
+ taskId: task.id,
1420
+ revision: task.revision,
1421
+ state: task.state,
1422
+ outcome: task.outcome,
1423
+ invalidated: false
1424
+ }) : void 0;
1425
+ if (header) try {
1426
+ deps.observed?.(header);
1427
+ } catch {}
1187
1428
  const targets = /* @__PURE__ */ new Set([delegation.parentSessionId, delegation.rootSessionId]);
1188
1429
  let held = false;
1189
1430
  for (const collection of collections) {
@@ -1237,28 +1478,49 @@ function createAcpManager(deps) {
1237
1478
  ...fields,
1238
1479
  revision: input.revision + 1
1239
1480
  };
1240
- store.saveTask(next);
1241
- changed(get(next.delegationId), next);
1481
+ commitTask(get(next.delegationId), next, () => store.saveTask(next));
1242
1482
  return next;
1243
1483
  }
1244
- function finish(current, outcome, error = null) {
1484
+ function commitTask(row, current, write, scope) {
1485
+ const commit = (joined) => {
1486
+ write(joined);
1487
+ deps.activity.replace(row.parentSessionId, store.activityCounts(row.parentSessionId), joined);
1488
+ joined.afterCommit(() => changed(row, current));
1489
+ };
1490
+ if (scope) deps.unitOfWork.join(scope, commit);
1491
+ else deps.unitOfWork.run(commit);
1492
+ }
1493
+ function saveConnection(next, scope) {
1494
+ const commit = (joined) => {
1495
+ store.saveDelegation(next);
1496
+ if (withdrawn) return;
1497
+ const parent = next.parentSessionId;
1498
+ deps.activity.hold(parent, { connections: store.parentProgress(parent, true).total }, joined);
1499
+ };
1500
+ if (scope) deps.unitOfWork.join(scope, commit);
1501
+ else deps.unitOfWork.run(commit);
1502
+ }
1503
+ function finish(current, outcome, error = null, scope) {
1245
1504
  if (task(current.id).state === "finished") return;
1246
1505
  const row = get(current.delegationId);
1247
1506
  const next = {
1248
1507
  ...current,
1249
1508
  state: "finished",
1509
+ endedAt: Date.now(),
1250
1510
  outcome,
1251
1511
  error,
1252
1512
  revision: current.revision + 1
1253
1513
  };
1254
- delivery.commit((view) => view.update("task", { payload: JSON.stringify(next) }, { id: next.id }), [{
1514
+ commitTask(row, next, (joined) => delivery.commit((view) => view.update("task", { payload: JSON.stringify(next) }, { id: next.id }), [{
1515
+ mode: "completion",
1255
1516
  target: row.parentSessionId,
1256
1517
  sourceKey: next.id,
1257
1518
  taskId: next.id,
1258
1519
  targetGeneration: next.targetGeneration,
1520
+ targetStopEpoch: next.targetStopEpoch,
1521
+ ...next.targetRunId ? { targetRunId: next.targetRunId } : {},
1259
1522
  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);
1523
+ }], joined), scope);
1262
1524
  }
1263
1525
  function expire(id) {
1264
1526
  for (const [key, value] of permissions) if (value.delegationId === id) {
@@ -1267,38 +1529,61 @@ function createAcpManager(deps) {
1267
1529
  value.resolve({ outcome: { outcome: "cancelled" } });
1268
1530
  }
1269
1531
  }
1270
- /** The person's reply to one permission, while ACP still waits for it. */
1532
+ function permissionDecision(row, id, request) {
1533
+ const parent = row.parentSessionId;
1534
+ return deps.approval.decide({
1535
+ sessionId: parent,
1536
+ address: sessions.resolve(parent).address
1537
+ }, {
1538
+ id,
1539
+ subject: request.toolCall.title?.trim() || "ACP permission requested",
1540
+ reason: `Running permission from ${row.instance.label}`,
1541
+ accepts: ["allowed-once", "rejected"]
1542
+ });
1543
+ }
1271
1544
  function answered(id, reply) {
1272
1545
  if (withdrawn) return;
1273
1546
  const pending = permissions.get(id);
1274
1547
  if (!pending) return;
1275
- const optionId = reply.answers.find((answer) => answer.questionId === PERMISSION_QUESTION)?.optionIds?.[0];
1548
+ let optionId = reply.answers.find((answer) => answer.questionId === PERMISSION_QUESTION)?.optionIds?.[0];
1276
1549
  const current = store.tasks(pending.delegationId).find((one) => one.state === "awaiting-permission" || one.state === "running");
1277
1550
  if (optionId === void 0 || !pending.request.options.some((option) => option.optionId === optionId) || !current) {
1278
1551
  cancelled(id);
1279
1552
  return;
1280
1553
  }
1554
+ const decision = permissionDecision(get(pending.delegationId), id, pending.request);
1555
+ if (decision.kind === "result" && decision.result.kind !== "allowed-once") {
1556
+ optionId = pending.request.options.find((option) => option.kind === "reject_once")?.optionId;
1557
+ store.append(current.id, {
1558
+ kind: "permission-policy-refused",
1559
+ id,
1560
+ source: decision.source ?? "unavailable"
1561
+ });
1562
+ if (optionId === void 0) {
1563
+ cancelled(id);
1564
+ return;
1565
+ }
1566
+ }
1281
1567
  const waiting = [...permissions].some(([key, other]) => key !== id && other.delegationId === pending.delegationId);
1282
- store.transaction(() => {
1568
+ const next = {
1569
+ ...current,
1570
+ state: waiting ? "awaiting-permission" : "running",
1571
+ revision: current.revision + 1
1572
+ };
1573
+ commitTask(get(pending.delegationId), next, () => {
1283
1574
  store.append(current.id, {
1284
1575
  kind: "permission-answered",
1285
1576
  id,
1286
1577
  optionId
1287
1578
  });
1288
- store.saveTask({
1289
- ...current,
1290
- state: waiting ? "awaiting-permission" : "running",
1291
- revision: current.revision + 1
1292
- });
1579
+ store.saveTask(next);
1293
1580
  });
1294
1581
  permissions.delete(id);
1295
1582
  pending.resolve({ outcome: {
1296
1583
  outcome: "selected",
1297
1584
  optionId
1298
1585
  } });
1299
- changed(get(pending.delegationId), task(current.id));
1300
1586
  }
1301
- /** The question ended without an answer: ACP reads it as cancelled. */
1302
1587
  function cancelled(id) {
1303
1588
  if (withdrawn) return;
1304
1589
  const pending = permissions.get(id);
@@ -1307,37 +1592,83 @@ function createAcpManager(deps) {
1307
1592
  pending.resolve({ outcome: { outcome: "cancelled" } });
1308
1593
  changed(get(pending.delegationId));
1309
1594
  }
1595
+ function disarm(id) {
1596
+ if (!idle.has(id)) return;
1597
+ idleTimers.clear(idle.get(id));
1598
+ idle.delete(id);
1599
+ }
1600
+ function isIdle(id) {
1601
+ if (closed || withdrawn || stopping.has(id) || !connections.has(id)) return false;
1602
+ if ([...permissions.values()].some((value) => value.delegationId === id)) return false;
1603
+ if (store.tasks(id).some((one) => one.state !== "finished")) return false;
1604
+ return store.delegation(id)?.connectionState === "connected";
1605
+ }
1606
+ function armIdle(id) {
1607
+ disarm(id);
1608
+ if (!isIdle(id)) return;
1609
+ const handle = idleTimers.set(() => {
1610
+ if (idle.get(id) !== handle) return;
1611
+ idle.delete(id);
1612
+ if (!isIdle(id)) return;
1613
+ closeIdle(id);
1614
+ }, ACP_IDLE_CLOSE_MS);
1615
+ idle.set(id, handle);
1616
+ }
1617
+ async function closeIdle(id) {
1618
+ stopping.add(id);
1619
+ try {
1620
+ await closeOwned(get(id));
1621
+ } catch {} finally {
1622
+ stopping.delete(id);
1623
+ }
1624
+ }
1310
1625
  async function disconnect(id) {
1626
+ disarm(id);
1311
1627
  expire(id);
1312
1628
  const pending = starting.get(id);
1313
1629
  if (pending) await pending.catch(() => {});
1314
1630
  const connection = connections.get(id);
1315
1631
  if (withdrawn) {
1316
1632
  const process = connection?.process ?? processes.get(id);
1633
+ const hold = launches.get(id)?.hold;
1317
1634
  connections.delete(id);
1318
1635
  processes.delete(id);
1319
- if (process) await process.stop();
1320
- await launches.get(id)?.release?.();
1321
- launches.delete(id);
1636
+ let cleaned = false;
1637
+ try {
1638
+ if (process) await process.stop();
1639
+ await launches.get(id)?.release?.();
1640
+ cleaned = true;
1641
+ } finally {
1642
+ launches.delete(id);
1643
+ hold?.retire({
1644
+ remote: remoteOutcome(id),
1645
+ cleaned
1646
+ });
1647
+ }
1322
1648
  return;
1323
1649
  }
1324
1650
  const row = get(id);
1325
1651
  try {
1326
1652
  const process = connection?.process ?? processes.get(id);
1327
1653
  if (process) await process.stop();
1328
- await launches.get(id)?.release?.();
1654
+ const launch = launches.get(id);
1655
+ await launch?.release?.();
1329
1656
  launches.delete(id);
1330
1657
  processes.delete(id);
1331
1658
  connections.delete(id);
1659
+ launch?.hold.retire({
1660
+ remote: remoteOutcome(id),
1661
+ cleaned: true
1662
+ });
1332
1663
  if (withdrawn) return;
1333
- store.saveDelegation({
1664
+ saveConnection({
1334
1665
  ...row,
1335
1666
  connectionState: "closed",
1336
1667
  processId: null
1337
1668
  });
1338
1669
  } catch {
1339
1670
  if (withdrawn) throw new Error("cleanup-failed");
1340
- store.saveDelegation({
1671
+ saveConnection({
1341
1672
  ...row,
1342
1673
  connectionState: "cleanup-failed"
1343
1674
  });
@@ -1350,7 +1681,8 @@ function createAcpManager(deps) {
1350
1681
  async function connect(row) {
1351
1682
  const launch = launches.get(row.id);
1352
1683
  if (!launch) throw new Error("resume-unavailable: explicit launch authorization required");
1353
- const process = await launch.launch();
1684
+ const process = await launch.hold.acquire(() => launch.launch());
1685
+ launch.hold.process(process);
1354
1686
  if (withdrawn) {
1355
1687
  await process.stop();
1356
1688
  throw new Error("stopping");
@@ -1361,12 +1693,29 @@ function createAcpManager(deps) {
1361
1693
  processId: process.processId,
1362
1694
  execution: launch.execution
1363
1695
  });
1696
+ const { connectAcp } = await import("./client-B0Rlfsrk.js");
1364
1697
  const connection = await connectAcp(process, {
1365
1698
  permission(request) {
1366
1699
  if (withdrawn) return Promise.resolve({ outcome: { outcome: "cancelled" } });
1367
1700
  const current = store.tasks(row.id).find((one) => one.state === "running" || one.state === "awaiting-permission");
1368
1701
  if (!current || request.sessionId !== get(row.id).remoteSessionId) return Promise.resolve({ outcome: { outcome: "cancelled" } });
1369
1702
  const id = randomUUID();
1703
+ const decision = permissionDecision(row, id, request);
1704
+ if (decision.kind === "result") {
1705
+ const option = request.options.find((option) => decision.result.kind === "allowed-once" ? option.kind === "allow_once" : option.kind === "reject_once");
1706
+ const response = { outcome: option ? {
1707
+ outcome: "selected",
1708
+ optionId: option.optionId
1709
+ } : { outcome: "cancelled" } };
1710
+ store.append(current.id, {
1711
+ kind: "permission-decided",
1712
+ id,
1713
+ request,
1714
+ source: decision.source ?? "unavailable",
1715
+ response
1716
+ });
1717
+ return Promise.resolve(response);
1718
+ }
1370
1719
  const withdraw = new AbortController();
1371
1720
  return new Promise((resolve) => {
1372
1721
  permissions.set(id, {
@@ -1391,7 +1740,25 @@ function createAcpManager(deps) {
1391
1740
  const current = store.tasks(row.id).find((one) => one.state !== "queued" && one.state !== "finished");
1392
1741
  if (!current || current.state === "starting") return;
1393
1742
  if (notification.sessionId !== get(row.id).remoteSessionId) throw new Error("remote-session-mismatch");
1394
- store.append(current.id, notification.update);
1743
+ delivery.progress(() => store.append(current.id, notification.update));
1744
+ if (notification.update.sessionUpdate === "usage_update") {
1745
+ const usage = notification.update;
1746
+ try {
1747
+ deps.performance?.record?.({
1748
+ type: "acp-usage",
1749
+ taskId: current.id,
1750
+ delegationId: row.id,
1751
+ generation: row.generation,
1752
+ remoteSessionKey: createHash("sha256").update(notification.sessionId).digest("hex"),
1753
+ usedTokens: usage.used,
1754
+ contextSize: usage.size,
1755
+ ...usage.cost == null ? {} : {
1756
+ cumulativeCost: usage.cost.amount,
1757
+ currency: usage.cost.currency
1758
+ }
1759
+ });
1760
+ } catch {}
1761
+ }
1395
1762
  if (notification.update.sessionUpdate === "config_option_update") {
1396
1763
  store.saveDelegation({
1397
1764
  ...get(row.id),
@@ -1408,9 +1775,10 @@ function createAcpManager(deps) {
1408
1775
  result: bytes.subarray(0, end).toString("utf8"),
1409
1776
  truncated: current.truncated || bytes.length > 65536
1410
1777
  });
1411
- }
1778
+ } else if (notification.update.sessionUpdate !== "config_option_update") changed(get(row.id), current);
1412
1779
  }
1413
1780
  });
1781
+ launch.hold.connected();
1414
1782
  if (withdrawn) {
1415
1783
  await process.stop();
1416
1784
  throw new Error("stopping");
@@ -1462,7 +1830,8 @@ function createAcpManager(deps) {
1462
1830
  const option = configuration.find((option) => option.id === configId);
1463
1831
  if (!option || option.type !== "select") throw new Error("config-option-unavailable");
1464
1832
  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");
1833
+ const choices = option.options.flatMap((entry) => "options" in entry ? entry.options : [entry]);
1834
+ if (!choices.some((choice) => choice.value === value)) throw new InvalidConfigValue(configId, value, choices.map((choice) => choice.value));
1466
1835
  configuration = (await control(connection.client.setSessionConfigOption({
1467
1836
  sessionId: get(row.id).remoteSessionId,
1468
1837
  configId,
@@ -1470,7 +1839,7 @@ function createAcpManager(deps) {
1470
1839
  }))).configOptions;
1471
1840
  }
1472
1841
  if (withdrawn) throw new Error("stopping");
1473
- store.saveDelegation({
1842
+ saveConnection({
1474
1843
  ...get(row.id),
1475
1844
  connectionState: "connected",
1476
1845
  configOptions: configuration
@@ -1514,7 +1883,10 @@ function createAcpManager(deps) {
1514
1883
  const work = (async () => {
1515
1884
  try {
1516
1885
  const row = get(id);
1517
- update(current, { state: "starting" });
1886
+ update(current, {
1887
+ state: "starting",
1888
+ startedAt: current.startedAt ?? Date.now()
1889
+ });
1518
1890
  let connection = connections.get(id);
1519
1891
  if (!connection) {
1520
1892
  const opening = connect(row);
@@ -1530,7 +1902,11 @@ function createAcpManager(deps) {
1530
1902
  await disconnect(id);
1531
1903
  return;
1532
1904
  }
1533
- update(task(current.id), { state: "running" });
1905
+ update(task(current.id), {
1906
+ state: "running",
1907
+ dispatchSettings: dispatchSettings(get(id))
1908
+ });
1909
+ prompting.add(id);
1534
1910
  const response = await connection.client.prompt({
1535
1911
  sessionId: get(id).remoteSessionId,
1536
1912
  prompt: [{
@@ -1538,6 +1914,7 @@ function createAcpManager(deps) {
1538
1914
  text: current.input
1539
1915
  }]
1540
1916
  });
1917
+ prompting.delete(id);
1541
1918
  if (withdrawn) return;
1542
1919
  expire(id);
1543
1920
  const cancelled = task(current.id).state === "stopping" || response.stopReason === "cancelled";
@@ -1561,16 +1938,66 @@ function createAcpManager(deps) {
1561
1938
  "initialize-failed",
1562
1939
  "capacity-exceeded"
1563
1940
  ].includes(error.message) ? error.message : "external-task-failed";
1564
- finish(task(current.id), "failed", safe);
1941
+ finish(error instanceof InvalidConfigValue ? {
1942
+ ...task(current.id),
1943
+ result: error.hint
1944
+ } : task(current.id), "failed", safe);
1565
1945
  } finally {
1566
1946
  running.delete(id);
1567
- if (!closed) schedule(get(id).rootSessionId);
1947
+ if (!closed) {
1948
+ schedule(get(id).rootSessionId);
1949
+ armIdle(id);
1950
+ }
1568
1951
  }
1569
1952
  })();
1570
1953
  running.set(id, work);
1571
1954
  await work;
1572
1955
  }
1573
- function accepted(id, input, requestKey) {
1956
+ function replayStart(input) {
1957
+ const previous = store.tasks().find((one) => one.requestKey === input.requestKey && get(one.delegationId).parentSessionId === input.sessionId);
1958
+ if (!previous) return void 0;
1959
+ const row = get(previous.delegationId);
1960
+ 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");
1961
+ return previous;
1962
+ }
1963
+ async function prepareStart(input) {
1964
+ if (closed) throw new Error("stopping");
1965
+ sessions.resolve(input.sessionId);
1966
+ if (replayStart(input)) return void 0;
1967
+ if (!store.instances().some((row) => row.id === input.instanceId && row.enabled)) throw new Error("instance-missing");
1968
+ return deps.policies.prepare(input.sessionId, {
1969
+ admissionId: input.requestKey,
1970
+ kind: "acp",
1971
+ operation: "spawn",
1972
+ task: input.task,
1973
+ target: { instanceId: input.instanceId },
1974
+ model: null,
1975
+ cwd: { absolutePath: input.cwd }
1976
+ });
1977
+ }
1978
+ async function prepareSend(caller, id, input, requestKey) {
1979
+ if (closed) throw new Error("stopping");
1980
+ const row = get(id);
1981
+ authorize(caller, row);
1982
+ const previous = store.tasks(id).find((task) => task.requestKey === requestKey);
1983
+ if (previous) {
1984
+ if (previous.input !== input) throw new Error("request-key-conflict");
1985
+ return;
1986
+ }
1987
+ return deps.policies.prepare(caller, {
1988
+ admissionId: requestKey,
1989
+ kind: "acp",
1990
+ operation: "followup",
1991
+ task: input,
1992
+ target: {
1993
+ instanceId: row.instance.id,
1994
+ delegationId: id
1995
+ },
1996
+ model: null,
1997
+ cwd: { absolutePath: row.cwd }
1998
+ });
1999
+ }
2000
+ function accepted(id, input, requestKey, admission) {
1574
2001
  if (stopping.has(id)) throw new Error("stopping");
1575
2002
  const row = get(id);
1576
2003
  if (row.connectionState === "cleanup-failed") throw new Error("cleanup-required");
@@ -1582,11 +2009,14 @@ function createAcpManager(deps) {
1582
2009
  const busy = store.tasks(id).some((one) => one.state !== "finished");
1583
2010
  if (!busy) capacity(row.rootSessionId, !connections.has(id));
1584
2011
  if (store.tasks(id).filter((one) => one.state === "queued").length >= 32) throw new Error("queue-full");
2012
+ const target = delivery.captureTarget(row.parentSessionId);
1585
2013
  const value = {
1586
2014
  id: randomUUID(),
1587
2015
  delegationId: id,
1588
2016
  requestKey,
1589
- targetGeneration: delivery.captureGeneration(row.parentSessionId),
2017
+ targetGeneration: target.targetGeneration,
2018
+ targetStopEpoch: target.targetStopEpoch,
2019
+ ...target.targetRunId ? { targetRunId: target.targetRunId } : {},
1590
2020
  input,
1591
2021
  state: busy ? "queued" : "starting",
1592
2022
  outcome: null,
@@ -1596,26 +2026,103 @@ function createAcpManager(deps) {
1596
2026
  createdAt: Date.now(),
1597
2027
  revision: 0
1598
2028
  };
1599
- store.saveTask(value);
1600
- changed(row, value);
2029
+ commitTask(row, value, (scope) => {
2030
+ admission?.consume(scope);
2031
+ store.saveTask(value);
2032
+ });
2033
+ disarm(id);
1601
2034
  queueMicrotask(() => {
1602
2035
  run(id);
1603
2036
  });
1604
2037
  return value;
1605
2038
  }
2039
+ async function stopOwned(row) {
2040
+ const id = row.id;
2041
+ expire(id);
2042
+ const current = store.tasks(id).find((one) => one.state !== "finished" && one.state !== "queued");
2043
+ if (!current) return;
2044
+ if (current.state === "starting") {
2045
+ stopping.add(id);
2046
+ try {
2047
+ await disconnect(id);
2048
+ finish(task(current.id), "cancelled");
2049
+ } finally {
2050
+ stopping.delete(id);
2051
+ }
2052
+ return;
2053
+ }
2054
+ update(current, { state: "stopping" });
2055
+ const connection = connections.get(id);
2056
+ try {
2057
+ if (connection && row.remoteSessionId) await connection.client.cancel({ sessionId: row.remoteSessionId });
2058
+ const work = running.get(id);
2059
+ if (work) await control(work, 5e3);
2060
+ } catch {
2061
+ await disconnect(id);
2062
+ finish(task(current.id), "interrupted", "cancel-timeout");
2063
+ }
2064
+ }
2065
+ async function closeOwned(row) {
2066
+ for (const current of store.tasks(row.id)) if (current.state === "queued") finish(current, "cancelled");
2067
+ await stopOwned(row);
2068
+ await disconnect(row.id);
2069
+ }
2070
+ function remoteOutcome(id) {
2071
+ return prompting.has(id) ? "unknown" : "not-applicable";
2072
+ }
2073
+ async function archiveOwned(id, hold) {
2074
+ if (launches.get(id)?.hold !== hold) return "not-applicable";
2075
+ if (withdrawn) return remoteOutcome(id);
2076
+ stopping.add(id);
2077
+ try {
2078
+ disarm(id);
2079
+ for (const current of store.tasks(id)) if (current.state === "queued") finish(current, "cancelled");
2080
+ expire(id);
2081
+ const current = store.tasks(id).find((one) => one.state !== "finished" && one.state !== "queued");
2082
+ let remote = "not-applicable";
2083
+ if (current && current.state !== "starting") {
2084
+ if (current.state !== "stopping") update(current, { state: "stopping" });
2085
+ const connection = connections.get(id);
2086
+ const remoteSessionId = get(id).remoteSessionId;
2087
+ try {
2088
+ if (connection && remoteSessionId) await control(connection.client.cancel({ sessionId: remoteSessionId }), cancelWaitMs);
2089
+ const work = running.get(id);
2090
+ if (work) await control(work, cancelWaitMs);
2091
+ remote = remoteOutcome(id) === "unknown" ? "unknown" : "confirmed-ended";
2092
+ } catch {
2093
+ remote = "unknown";
2094
+ finish(task(current.id), "interrupted", "cancel-timeout");
2095
+ }
2096
+ } else remote = remoteOutcome(id);
2097
+ try {
2098
+ await disconnect(id);
2099
+ } catch {}
2100
+ if (current && task(current.id).state !== "finished") finish(task(current.id), "cancelled");
2101
+ return remote;
2102
+ } finally {
2103
+ stopping.delete(id);
2104
+ }
2105
+ }
2106
+ function adopt(id, plan) {
2107
+ plan.hold.onRelease(async () => {
2108
+ await plan.release?.();
2109
+ });
2110
+ plan.hold.onClose(() => archiveOwned(id, plan.hold));
2111
+ launches.set(id, plan);
2112
+ }
1606
2113
  return {
1607
2114
  recover() {
1608
- for (const row of store.delegations()) {
1609
- store.saveDelegation({
2115
+ for (const row of store.delegations()) deps.unitOfWork.run((scope) => {
2116
+ saveConnection({
1610
2117
  ...row,
1611
2118
  connectionState: "interrupted",
1612
2119
  processId: null,
1613
2120
  generation: randomUUID()
1614
- });
1615
- for (const current of store.tasks(row.id)) if (current.state !== "finished") finish(current, "interrupted", "gateway-restarted");
1616
- }
2121
+ }, scope);
2122
+ for (const current of store.tasks(row.id)) if (current.state !== "finished") finish(current, "interrupted", "gateway-restarted", scope);
2123
+ deps.activity.replace(row.parentSessionId, store.activityCounts(row.parentSessionId), scope);
2124
+ });
1617
2125
  },
1618
- /** Publishes one bounded final invalidation per affected session after all owned members settle. */
1619
2126
  async collection(ids, work, admission) {
1620
2127
  const context = {
1621
2128
  ids: new Set(ids),
@@ -1635,21 +2142,25 @@ function createAcpManager(deps) {
1635
2142
  } catch {}
1636
2143
  }
1637
2144
  },
1638
- /** Accepts one prompt and records its effective execution only after its launch succeeds. */
1639
- async start(input, launch, execution, release) {
2145
+ prepareStart,
2146
+ prepareSend,
2147
+ async start(input, launch, execution, release, hold) {
1640
2148
  let adopted = false;
2149
+ let reserved = hold;
1641
2150
  try {
1642
2151
  if (closed) throw new Error("stopping");
1643
2152
  const selectedExecution = LaunchExecutionSchema.parse(execution);
1644
2153
  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
- }
2154
+ const previous = replayStart(input);
2155
+ if (previous) return previous;
1651
2156
  const instance = store.instances().find((row) => row.id === input.instanceId && row.enabled);
1652
2157
  if (!instance) throw new Error("instance-missing");
2158
+ const policyAdmission = await prepareStart(input);
2159
+ const concurrent = replayStart(input);
2160
+ if (concurrent) return concurrent;
2161
+ if (!policyAdmission) throw new Error("delegation_admission_unknown");
2162
+ reserved ??= deps.holds.hold(deps.holds.enter(input.sessionId));
2163
+ reserved.assertCurrent();
1653
2164
  const available = capacity(context.rootSessionId, true, true) && store.queued(context.rootSessionId).length === 0;
1654
2165
  const row = {
1655
2166
  id: randomUUID(),
@@ -1666,16 +2177,14 @@ function createAcpManager(deps) {
1666
2177
  connectionState: "starting",
1667
2178
  createdAt: Date.now()
1668
2179
  };
1669
- launches.set(row.id, {
1670
- launch,
1671
- execution: selectedExecution,
1672
- release
1673
- });
2180
+ const target = delivery.captureTarget(input.sessionId);
1674
2181
  const value = {
1675
2182
  id: randomUUID(),
1676
2183
  delegationId: row.id,
1677
2184
  requestKey: input.requestKey,
1678
- targetGeneration: delivery.captureGeneration(input.sessionId),
2185
+ targetGeneration: target.targetGeneration,
2186
+ targetStopEpoch: target.targetStopEpoch,
2187
+ ...target.targetRunId ? { targetRunId: target.targetRunId } : {},
1679
2188
  input: input.task,
1680
2189
  state: available ? "starting" : "queued",
1681
2190
  outcome: null,
@@ -1685,38 +2194,76 @@ function createAcpManager(deps) {
1685
2194
  createdAt: Date.now(),
1686
2195
  revision: 0
1687
2196
  };
1688
- store.transaction(() => {
1689
- store.saveDelegation(row);
2197
+ commitTask(row, value, (scope) => {
2198
+ const currentInstance = store.instances().find((entry) => entry.id === instance.id && entry.enabled);
2199
+ if (!currentInstance || JSON.stringify(currentInstance) !== JSON.stringify(instance)) throw new Error("instance-stale");
2200
+ sessions.resolve(input.sessionId);
2201
+ policyAdmission.consume(scope);
2202
+ saveConnection(row, scope);
1690
2203
  store.saveTask(value);
1691
2204
  });
2205
+ adopt(row.id, {
2206
+ launch,
2207
+ execution: selectedExecution,
2208
+ release,
2209
+ hold: reserved
2210
+ });
1692
2211
  adopted = true;
1693
- changed(row, value);
1694
2212
  queueMicrotask(() => {
1695
2213
  run(row.id);
1696
2214
  });
1697
2215
  return value;
1698
2216
  } finally {
1699
- if (!adopted) await release?.();
2217
+ if (!adopted) {
2218
+ reserved?.retire();
2219
+ await release?.();
2220
+ }
1700
2221
  }
1701
2222
  },
1702
- /** Reuses a live connection, or requires a fresh approved factory and isolation facts. */
1703
2223
  async send(caller, id, input, requestKey, prepared) {
1704
2224
  let adopted = false;
2225
+ let reserved = prepared?.hold;
1705
2226
  try {
1706
2227
  if (closed) throw new Error("stopping");
1707
- authorize(caller, get(id));
1708
- if (prepared) {
1709
- await launches.get(id)?.release?.();
1710
- launches.set(id, {
2228
+ const row = get(id);
2229
+ authorize(caller, row);
2230
+ const replay = () => {
2231
+ const previous = store.tasks(id).find((task) => task.requestKey === requestKey);
2232
+ if (previous && previous.input !== input) throw new Error("request-key-conflict");
2233
+ return previous;
2234
+ };
2235
+ const previous = replay();
2236
+ if (previous) return previous;
2237
+ const policyAdmission = await prepareSend(caller, id, input, requestKey);
2238
+ const acceptedDuringCheck = replay();
2239
+ if (acceptedDuringCheck) return acceptedDuringCheck;
2240
+ if (!policyAdmission) throw new Error("delegation_admission_unknown");
2241
+ const lease = deps.holds.enter(row.parentSessionId);
2242
+ let replacement;
2243
+ const previousPlan = launches.get(id);
2244
+ if (prepared && !connections.has(id) && !starting.has(id)) {
2245
+ await previousPlan?.release?.();
2246
+ const concurrent = replay();
2247
+ if (concurrent) return concurrent;
2248
+ lease.assertCurrent();
2249
+ reserved ??= deps.holds.hold(lease);
2250
+ reserved.assertCurrent();
2251
+ replacement = {
1711
2252
  launch: prepared.launch,
1712
2253
  execution: LaunchExecutionSchema.parse(prepared.execution),
1713
- release: prepared.release
1714
- });
1715
- adopted = true;
2254
+ release: prepared.release,
2255
+ hold: reserved
2256
+ };
1716
2257
  }
2258
+ lease.assertCurrent();
1717
2259
  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({
2260
+ const result = accepted(id, input, requestKey, policyAdmission);
2261
+ if (replacement) {
2262
+ previousPlan?.hold.retire();
2263
+ adopt(id, replacement);
2264
+ adopted = true;
2265
+ }
2266
+ if (!connections.has(id)) saveConnection({
1720
2267
  ...get(id),
1721
2268
  generation: randomUUID(),
1722
2269
  connectionState: "starting",
@@ -1724,7 +2271,10 @@ function createAcpManager(deps) {
1724
2271
  });
1725
2272
  return result;
1726
2273
  } finally {
1727
- if (prepared && !adopted) await prepared.release?.();
2274
+ if (prepared && !adopted) {
2275
+ reserved?.retire();
2276
+ await prepared.release?.();
2277
+ }
1728
2278
  }
1729
2279
  },
1730
2280
  usage(caller) {
@@ -1737,6 +2287,35 @@ function createAcpManager(deps) {
1737
2287
  connections: rows.filter((row) => row.connectionState !== "closed" && row.connectionState !== "interrupted").length
1738
2288
  };
1739
2289
  },
2290
+ statusByTasks(caller, taskIds) {
2291
+ StatusByTasksParams.parse({
2292
+ sessionId: caller,
2293
+ taskIds
2294
+ });
2295
+ sessions.resolve(caller);
2296
+ const rows = taskIds.map((taskId) => {
2297
+ const missing = {
2298
+ taskId,
2299
+ status: "not-found"
2300
+ };
2301
+ const delegationId = store.taskDelegation(taskId);
2302
+ if (!delegationId) return missing;
2303
+ const identity = store.delegationIdentity(delegationId);
2304
+ if (!identity) return missing;
2305
+ const owner = sessions.resolve(identity.parentSessionId);
2306
+ if (caller !== identity.parentSessionId && !owner.ancestors.includes(caller)) return missing;
2307
+ const task = store.summary(delegationId, taskId);
2308
+ const delegation = store.delegationSummary(delegationId);
2309
+ return task && delegation ? {
2310
+ taskId,
2311
+ status: "found",
2312
+ task,
2313
+ delegation
2314
+ } : missing;
2315
+ });
2316
+ if (Buffer.byteLength(JSON.stringify(rows), "utf8") > 262144) throw new Error("batch-limit: split the task status request");
2317
+ return rows;
2318
+ },
1740
2319
  summary(caller, id, taskId) {
1741
2320
  const identity = store.delegationIdentity(id);
1742
2321
  if (!identity) throw new Error("not-found");
@@ -1792,9 +2371,20 @@ function createAcpManager(deps) {
1792
2371
  }
1793
2372
  };
1794
2373
  },
1795
- get(caller, id, offset = 0, limit = 50, maxBytes = 8388608) {
2374
+ get(caller, id, offset = 0, limit = 50, maxBytes = 8388608, taskId) {
1796
2375
  const row = get(id);
1797
2376
  authorize(caller, row);
2377
+ if (taskId !== void 0) {
2378
+ const current = store.task(taskId, maxBytes);
2379
+ if (!current || current.delegationId !== id) throw new Error("not-found");
2380
+ return {
2381
+ delegation: row,
2382
+ tasks: [current],
2383
+ offset: 0,
2384
+ limit: 1,
2385
+ nextOffset: null
2386
+ };
2387
+ }
1798
2388
  const effective = Math.min(200, limit);
1799
2389
  const page = store.tasksPage(id, offset, effective, maxBytes);
1800
2390
  return {
@@ -1813,7 +2403,11 @@ function createAcpManager(deps) {
1813
2403
  if (current.delegationId !== id) throw new Error("not-found");
1814
2404
  return current;
1815
2405
  },
1816
- list(caller, offset = 0, limit = 50) {
2406
+ progress(caller, retainedOnly = false) {
2407
+ sessions.resolve(caller);
2408
+ return store.parentProgress(caller, retainedOnly);
2409
+ },
2410
+ list(caller, offset = 0, limit = 50, retainedOnly = false) {
1817
2411
  sessions.resolve(caller);
1818
2412
  const rows = [];
1819
2413
  let skipped = 0;
@@ -1824,8 +2418,9 @@ function createAcpManager(deps) {
1824
2418
  } catch {
1825
2419
  continue;
1826
2420
  }
1827
- if (skipped++ < offset) continue;
1828
2421
  const row = get(identity.id);
2422
+ if (retainedOnly && (row.parentSessionId !== caller || row.connectionState === "closed" || row.connectionState === "interrupted")) continue;
2423
+ if (skipped++ < offset) continue;
1829
2424
  const last = store.taskSummary(row.id);
1830
2425
  const entry = {
1831
2426
  delegation: row,
@@ -1847,46 +2442,24 @@ function createAcpManager(deps) {
1847
2442
  async stop(caller, id) {
1848
2443
  const row = get(id);
1849
2444
  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
- }
2445
+ await stopOwned(row);
1873
2446
  },
1874
2447
  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);
2448
+ const row = get(id);
2449
+ authorize(caller, row);
2450
+ await closeOwned(row);
1879
2451
  },
1880
- /** Releases live resources after owner revocation without reading withdrawn persistence. */
1881
2452
  async withdraw() {
1882
2453
  withdrawn = true;
1883
2454
  closed = true;
2455
+ for (const id of [...idle.keys()]) disarm(id);
1884
2456
  for (const pending of [...permissions.values()]) expire(pending.delegationId);
1885
2457
  const live = [.../* @__PURE__ */ new Set([...processes.values(), ...[...connections.values()].map((one) => one.process)])];
1886
- const preparations = [...launches.values()];
2458
+ const preparations = [...launches.entries()];
1887
2459
  const stopped = await Promise.allSettled(live.map((process) => process.stop()));
1888
2460
  await Promise.allSettled([...starting.values(), ...running.values()]);
1889
- const released = await Promise.allSettled(preparations.map((plan) => plan.release?.()));
2461
+ const released = await Promise.allSettled(preparations.map(([, plan]) => plan.release?.()));
2462
+ for (const [id, plan] of preparations) plan.hold.retire({ remote: remoteOutcome(id) });
1890
2463
  if (stopped.some((result) => result.status === "rejected") || released.some((result) => result.status === "rejected")) throw new Error("cleanup-failed");
1891
2464
  launches.clear();
1892
2465
  connections.clear();
@@ -1894,60 +2467,100 @@ function createAcpManager(deps) {
1894
2467
  },
1895
2468
  async shutdown() {
1896
2469
  closed = true;
1897
- const results = await Promise.allSettled(store.delegations().map((row) => this.close(row.parentSessionId, row.id)));
2470
+ for (const id of [...idle.keys()]) disarm(id);
2471
+ const results = await Promise.allSettled(store.delegations().map((row) => closeOwned(row)));
1898
2472
  await Promise.allSettled([...running.values()]);
1899
2473
  if (results.some((row) => row.status === "rejected")) throw new Error("cleanup-failed");
1900
2474
  }
1901
2475
  };
1902
2476
  }
1903
2477
  //#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
- ];
2478
+ //#region src/observer.ts
2479
+ const ListByParentsParams = z.strictObject({
2480
+ parentSessionIds: z.array(z.string().min(1).max(512)).min(1).max(64),
2481
+ activeOnly: z.boolean().optional(),
2482
+ maxItemBytes: z.number().int().min(1).max(8388608).default(262144),
2483
+ maxTotalBytes: z.number().int().min(1).max(8388608).default(8388608)
2484
+ }).refine((input) => input.parentSessionIds.length * input.maxItemBytes + 8192 <= input.maxTotalBytes, "batch-limit: declared member budgets exceed total");
2485
+ const READ_LIMIT = {
2486
+ code: "read-limit",
2487
+ message: "ACP tasks exceed their member byte budget"
2488
+ };
2489
+ function createAcpDelegationObserver(store, failed = () => {}) {
2490
+ const listeners = /* @__PURE__ */ new Map();
2491
+ return {
2492
+ subscribe(scope, listener) {
2493
+ const held = listeners.get(scope.sessionId) ?? /* @__PURE__ */ new Set();
2494
+ listeners.set(scope.sessionId, held);
2495
+ held.add(listener);
2496
+ return () => {
2497
+ held.delete(listener);
2498
+ if (!held.size && listeners.get(scope.sessionId) === held) listeners.delete(scope.sessionId);
2499
+ };
2500
+ },
2501
+ publish(event) {
2502
+ for (const listener of [...listeners.get(event.parentSessionId) ?? []]) try {
2503
+ const result = listener(event);
2504
+ if (result instanceof Promise) result.catch(failed);
2505
+ } catch (error) {
2506
+ failed(error);
2507
+ }
2508
+ },
2509
+ listByParents(params) {
2510
+ const input = ListByParentsParams.parse(params);
2511
+ for (const [index, target] of input.parentSessionIds.entries()) if (Buffer.byteLength(JSON.stringify({
2512
+ index,
2513
+ target,
2514
+ ok: false,
2515
+ error: READ_LIMIT
2516
+ })) > input.maxItemBytes) throw new Error("batch-limit: parent metadata exceeds member byte budget");
2517
+ return { results: input.parentSessionIds.map((target, index) => {
2518
+ const failed = {
2519
+ index,
2520
+ target,
2521
+ ok: false,
2522
+ error: READ_LIMIT
2523
+ };
2524
+ const overhead = Buffer.byteLength(JSON.stringify({
2525
+ index,
2526
+ target,
2527
+ ok: true,
2528
+ value: []
2529
+ }));
2530
+ try {
2531
+ const result = {
2532
+ index,
2533
+ target,
2534
+ ok: true,
2535
+ value: store.tasksByParent(target, {
2536
+ activeOnly: input.activeOnly === true,
2537
+ maxBytes: input.maxItemBytes - overhead
2538
+ })
2539
+ };
2540
+ return Buffer.byteLength(JSON.stringify(result)) <= input.maxItemBytes ? result : failed;
2541
+ } catch (cause) {
2542
+ if (cause.code === "read-limit") return failed;
2543
+ throw cause;
2544
+ }
2545
+ }) };
2546
+ }
2547
+ };
2548
+ }
1914
2549
  //#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
2550
+ //#region src/tool-data.ts
2551
+ const target$1 = z.strictObject({
2552
+ delegationId: z.string(),
2553
+ taskId: z.string().optional()
1943
2554
  });
1944
2555
  const coordinates = z.strictObject({
1945
2556
  seq: z.number().int().nonnegative(),
1946
2557
  byte: z.number().int().nonnegative()
1947
2558
  });
1948
- const resultValue = z.strictObject({
2559
+ const AcpOriginalSchema = z.strictObject({
1949
2560
  taskId: z.string(),
1950
- text: z.string(),
2561
+ body: LocalBodyRefSchema,
2562
+ startByte: z.number().int().nonnegative(),
2563
+ endByte: z.number().int().nonnegative(),
1951
2564
  start: coordinates,
1952
2565
  end: coordinates,
1953
2566
  totalBytes: z.number().int().nonnegative(),
@@ -1957,31 +2570,33 @@ const resultValue = z.strictObject({
1957
2570
  taskId: z.string()
1958
2571
  }),
1959
2572
  revision: z.number(),
1960
- originalComplete: z.boolean()
2573
+ originalComplete: z.boolean(),
2574
+ complete: z.boolean(),
2575
+ deliveryKey: z.string().optional()
1961
2576
  });
1962
- const getMember = z.strictObject({
2577
+ const AcpGetMemberSchema = z.strictObject({
1963
2578
  index: z.number().int().nonnegative(),
1964
- target,
2579
+ target: target$1,
1965
2580
  value: z.union([z.strictObject({
1966
2581
  delegation: AcpDelegationSummarySchema,
1967
2582
  task: AcpTaskSummarySchema.nullable()
1968
- }), resultValue]).optional(),
2583
+ }), AcpOriginalSchema]).optional(),
1969
2584
  error: z.object({
1970
2585
  code: z.string(),
1971
2586
  message: z.string()
1972
2587
  }).optional()
1973
2588
  });
1974
- const listMember = z.strictObject({
2589
+ const AcpListMemberSchema = z.strictObject({
1975
2590
  delegation: AcpDelegationSummarySchema,
1976
2591
  latest: AcpTaskSummarySchema.nullable()
1977
2592
  });
1978
- const instanceMember = z.strictObject({
2593
+ const AcpInstanceMemberSchema = z.strictObject({
1979
2594
  instanceId: z.string(),
1980
2595
  label: z.string(),
1981
2596
  adapter: z.string().optional(),
1982
2597
  executionMode: z.enum(["sandbox", "trusted"])
1983
2598
  });
1984
- const failure = z.strictObject({
2599
+ const AcpFailureSchema = z.strictObject({
1985
2600
  ok: z.literal(false),
1986
2601
  error: z.object({
1987
2602
  code: z.string(),
@@ -1990,7 +2605,7 @@ const failure = z.strictObject({
1990
2605
  }),
1991
2606
  next: z.unknown()
1992
2607
  });
1993
- const output = (items) => z.union([z.strictObject({
2608
+ const acpReadOutputSchema = (items) => z.union([z.strictObject({
1994
2609
  ok: z.literal(true),
1995
2610
  complete: z.boolean(),
1996
2611
  items,
@@ -1999,42 +2614,343 @@ const output = (items) => z.union([z.strictObject({
1999
2614
  limit: z.number(),
2000
2615
  outputTokens: z.number()
2001
2616
  })
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) {
2617
+ }), AcpFailureSchema]);
2618
+ acpReadOutputSchema(z.array(z.union([
2619
+ AcpGetMemberSchema,
2620
+ AcpListMemberSchema,
2621
+ AcpInstanceMemberSchema
2622
+ ])));
2623
+ const AcpTaskReceiptSchema = z.strictObject({
2624
+ id: z.string(),
2625
+ delegationId: z.string(),
2626
+ state: z.string(),
2627
+ targetGeneration: z.number(),
2628
+ createdAt: z.number(),
2629
+ revision: z.number()
2630
+ });
2631
+ const AcpSendDataSchema = z.union([AcpTaskReceiptSchema, AcpFailureSchema]);
2632
+ function acpCollectionSchema(value) {
2633
+ return z.strictObject({ results: z.array(z.discriminatedUnion("ok", [z.strictObject({
2634
+ index: z.number().int().nonnegative(),
2635
+ target: z.string(),
2636
+ ok: z.literal(true),
2637
+ value
2638
+ }), z.strictObject({
2639
+ index: z.number().int().nonnegative(),
2640
+ target: z.string(),
2641
+ ok: z.literal(false),
2642
+ error: z.strictObject({
2643
+ code: z.string().max(64),
2644
+ message: z.string().max(512)
2645
+ })
2646
+ })])).max(64) });
2647
+ }
2648
+ const AcpDelegateDataSchema = z.union([acpCollectionSchema(AcpTaskReceiptSchema), AcpFailureSchema]);
2649
+ const AcpStopDataSchema = acpCollectionSchema(z.strictObject({
2650
+ stopped: z.boolean(),
2651
+ closed: z.boolean()
2652
+ }));
2653
+ //#endregion
2654
+ //#region src/responsibility.ts
2655
+ const LAUNCH_KIND = "launch";
2656
+ const ROOT_PREFIX = "yaoguang-acp-";
2657
+ const LaunchDescriptorSchema = z.strictObject({
2658
+ roots: z.array(z.string().min(1).max(4096)).max(8),
2659
+ connected: z.boolean()
2660
+ });
2661
+ const outcome = (managed, remote) => ({
2662
+ managedCleanup: managed,
2663
+ descendantCoverage: "not-applicable",
2664
+ residual: "none",
2665
+ remote,
2666
+ ...managed === "retry" ? { code: "acp_cleanup_failed" } : {}
2667
+ });
2668
+ async function removeRoot(path) {
2669
+ if (dirname(path) !== realpathSync(tmpdir()) || !basename(path).startsWith(ROOT_PREFIX)) return;
2670
+ await rm(path, {
2671
+ recursive: true,
2672
+ force: true
2673
+ });
2674
+ }
2675
+ async function removeRoots(roots) {
2676
+ return (await Promise.allSettled(roots.map(removeRoot))).every((row) => row.status === "fulfilled");
2677
+ }
2678
+ const launchCleanup = {
2679
+ descriptorSchema: LaunchDescriptorSchema,
2680
+ async recover(_context, descriptor) {
2681
+ const { roots, connected } = LaunchDescriptorSchema.parse(descriptor);
2682
+ const remote = connected ? "unknown" : "not-applicable";
2683
+ return outcome(await removeRoots(roots) ? "complete" : "retry", remote);
2684
+ }
2685
+ };
2686
+ function registerLaunchRecovery(ctx) {
2687
+ ctx.register(LAUNCH_KIND, launchCleanup);
2688
+ }
2689
+ function createLaunchHolds(lifecycle) {
2690
+ lifecycle.register(LAUNCH_KIND, launchCleanup);
2691
+ return {
2692
+ enter: (sessionId) => lifecycle.enter(sessionId),
2693
+ hold(lease) {
2694
+ const receipt = lifecycle.reserve(lease, {
2695
+ kind: LAUNCH_KIND,
2696
+ descriptor: {
2697
+ roots: [],
2698
+ connected: false
2699
+ }
2700
+ });
2701
+ const roots = [];
2702
+ let connected = false;
2703
+ let start;
2704
+ let child;
2705
+ let close;
2706
+ let release;
2707
+ let remote = "not-applicable";
2708
+ let inflight;
2709
+ let closing = false;
2710
+ let stopped = false;
2711
+ let sealed = false;
2712
+ let attempt;
2713
+ const describe = () => receipt.acquired({
2714
+ roots: [...roots],
2715
+ connected
2716
+ });
2717
+ const seal = () => {
2718
+ if (sealed) return;
2719
+ sealed = true;
2720
+ receipt.finishAcquisition();
2721
+ };
2722
+ const run = async () => {
2723
+ closing = true;
2724
+ await inflight?.catch(() => {});
2725
+ const business = close;
2726
+ close = void 0;
2727
+ if (business) try {
2728
+ remote = await business();
2729
+ } catch {
2730
+ remote = connected ? "unknown" : remote;
2731
+ }
2732
+ let failed = false;
2733
+ if (!stopped) try {
2734
+ if (start) await start.stop();
2735
+ else await child?.stop();
2736
+ stopped = true;
2737
+ } catch {
2738
+ failed = true;
2739
+ }
2740
+ try {
2741
+ await release?.();
2742
+ release = void 0;
2743
+ } catch {
2744
+ failed = true;
2745
+ }
2746
+ if (!failed && !await removeRoots(roots)) failed = true;
2747
+ seal();
2748
+ return outcome(failed ? "retry" : "complete", remote);
2749
+ };
2750
+ receipt.retain({ cleanup: () => {
2751
+ attempt ??= run().finally(() => {
2752
+ attempt = void 0;
2753
+ });
2754
+ return attempt;
2755
+ } });
2756
+ return {
2757
+ signal: lease.signal,
2758
+ assertCurrent: () => lease.assertCurrent(),
2759
+ root(path) {
2760
+ roots.push(path);
2761
+ describe();
2762
+ },
2763
+ started(value) {
2764
+ start = value;
2765
+ },
2766
+ process(value) {
2767
+ child = value;
2768
+ },
2769
+ connected() {
2770
+ if (connected) return;
2771
+ connected = true;
2772
+ describe();
2773
+ },
2774
+ onClose(value) {
2775
+ close = value;
2776
+ },
2777
+ onRelease(value) {
2778
+ release = value;
2779
+ },
2780
+ async acquire(work) {
2781
+ if (closing) throw new Error("stopping");
2782
+ const running = work();
2783
+ inflight = running;
2784
+ try {
2785
+ return await running;
2786
+ } finally {
2787
+ seal();
2788
+ }
2789
+ },
2790
+ retire(input) {
2791
+ close = void 0;
2792
+ if (input?.remote) remote = input.remote;
2793
+ if (input?.cleaned) {
2794
+ if (child || !start) stopped = true;
2795
+ release = void 0;
2796
+ }
2797
+ receipt.retire();
2798
+ }
2799
+ };
2800
+ }
2801
+ };
2802
+ }
2803
+ //#endregion
2804
+ //#region src/tool-names.ts
2805
+ const TOOL_NAMES = [
2806
+ "acp_instances",
2807
+ "acp_delegate",
2808
+ "acp_send",
2809
+ "acp_get",
2810
+ "acp_list",
2811
+ "acp_stop"
2812
+ ];
2813
+ //#endregion
2814
+ //#region src/pages.ts
2815
+ const tokens = z.number().int().positive().optional().describe("Desired output tokens; the host may allocate less.");
2816
+ const limit = z.number().int().min(1).max(100).default(50).describe("Maximum summaries per page, default 50 and hard maximum 100.");
2817
+ const target = z.strictObject({
2818
+ delegationId: z.string().min(1).max(512).describe("Owned external delegation ID."),
2819
+ taskId: z.string().min(1).max(512).optional().describe("Named task; omit to page the delegation task summaries.")
2820
+ });
2821
+ const getInitial = z.strictObject({
2822
+ 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."),
2823
+ view: z.enum(["status", "result"]).default("status").describe("status returns metadata without prompts/output bodies; result pages original final agent text from retained updates."),
2824
+ waitMs: z.number().int().min(0).max(6e4).optional().describe("One shared deadline in milliseconds; returns early when any target awaits permission. Positive waits require taskId for every member; cancellation leaves tasks running."),
2825
+ limit,
2826
+ outputTokens: tokens
2827
+ }).superRefine((input, issues) => {
2828
+ if (((input.waitMs ?? 0) > 0 || input.view === "result") && input.items.some((item) => !item.taskId)) issues.addIssue({
2829
+ code: "custom",
2830
+ path: ["items"],
2831
+ message: "Every result or positive wait target requires taskId"
2832
+ });
2833
+ });
2834
+ const listInitial = z.strictObject({
2835
+ limit,
2836
+ outputTokens: tokens
2837
+ });
2838
+ const continuation = z.strictObject({
2839
+ cursor: z.string().min(1).max(512).describe("Opaque cursor copied unchanged from next.arguments; status and result cursors are distinct."),
2840
+ outputTokens: tokens
2841
+ });
2842
+ const sourceHash = (text) => createHash("sha256").update(text).digest("hex");
2843
+ function originalPosition(part, bytes) {
2844
+ let before = 0;
2845
+ for (const [index, segment] of part.segments.entries()) {
2846
+ const last = index === part.segments.length - 1;
2847
+ if (bytes < before + segment.bytes || last) {
2848
+ const byte = segment.offset + (bytes - before);
2849
+ const following = part.segments[index + 1];
2850
+ return {
2851
+ end: {
2852
+ seq: segment.seq,
2853
+ byte
2854
+ },
2855
+ next: byte < segment.total ? {
2856
+ seq: segment.seq,
2857
+ offset: byte
2858
+ } : following ? {
2859
+ seq: following.seq,
2860
+ offset: 0
2861
+ } : part.next
2862
+ };
2863
+ }
2864
+ before += segment.bytes;
2865
+ }
2866
+ return {
2867
+ end: {
2868
+ seq: part.start.seq,
2869
+ byte: part.start.offset
2870
+ },
2871
+ next: part.next
2872
+ };
2873
+ }
2874
+ function acpReadTools(store, manager, resources, signal, observer) {
2875
+ const track = (ctx, result) => {
2876
+ if (!result.data.ok) return;
2877
+ const completeResults = result.data.items.flatMap((row) => {
2878
+ if (!("index" in row) || !row.value || !("body" in row.value)) return [];
2879
+ const value = row.value;
2880
+ return value.complete && value.deliveryKey && value.startByte === 0 && value.endByte === value.body.byteLength ? [{
2881
+ key: value.deliveryKey,
2882
+ body: value.body,
2883
+ nodeIds: [acpResultNodeId(row.index)]
2884
+ }] : [];
2885
+ });
2886
+ if (completeResults.length) observer?.track(ctx, result, { completeResults });
2887
+ };
2888
+ const documents = createTextDocuments(acpReadDocument);
2005
2889
  const cursors = /* @__PURE__ */ new Map();
2006
2890
  let queue = Promise.resolve();
2891
+ const waited = /* @__PURE__ */ new WeakSet();
2892
+ const waitForTargets = async (items, waitMs, ctx) => {
2893
+ const deadline = performance.now() + waitMs;
2894
+ for (;;) {
2895
+ ctx.signal.throwIfAborted();
2896
+ signal.throwIfAborted();
2897
+ const states = items.map((item) => {
2898
+ try {
2899
+ return manager.summary(ctx.sessionId, item.delegationId, item.taskId).task?.state;
2900
+ } catch (failure) {
2901
+ if (resources.isAdmissionFailure(failure)) throw failure;
2902
+ return;
2903
+ }
2904
+ });
2905
+ const remaining = deadline - performance.now();
2906
+ if (states.includes("awaiting-permission") || states.every((state) => state === void 0 || state === "finished") || remaining <= 0) return;
2907
+ await new Promise((resolve) => {
2908
+ const complete = () => {
2909
+ clearTimeout(timer);
2910
+ ctx.signal.removeEventListener("abort", complete);
2911
+ signal.removeEventListener("abort", complete);
2912
+ resolve();
2913
+ };
2914
+ const timer = setTimeout(complete, Math.min(50, remaining));
2915
+ ctx.signal.addEventListener("abort", complete, { once: true });
2916
+ signal.addEventListener("abort", complete, { once: true });
2917
+ });
2918
+ }
2919
+ };
2007
2920
  const cleanupQuery = (query) => {
2008
2921
  if (query.closed) return;
2009
2922
  query.closed = true;
2010
2923
  query.sources.clear();
2011
2924
  query.revisions.clear();
2012
2925
  for (const [id, cursor] of cursors) if (cursor.query === query) {
2013
- cursor.result = void 0;
2926
+ cursor.selection = void 0;
2014
2927
  cursors.delete(id);
2015
2928
  }
2016
2929
  };
2017
2930
  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
2931
  const tool = (kind) => ({
2031
2932
  name: kind,
2032
2933
  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.",
2934
+ 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, returns early when any target awaits permission, 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
2935
  inputSchema: z.union([kind === "acp_get" ? getInitial : listInitial, continuation]),
2035
- outputSchema: output(z.array(kind === "acp_get" ? getMember : kind === "acp_list" ? listMember : instanceMember)),
2936
+ outputSchema: acpReadOutputSchema(z.array(kind === "acp_get" ? AcpGetMemberSchema : kind === "acp_list" ? AcpListMemberSchema : AcpInstanceMemberSchema)),
2937
+ formatModel: documents.formatModel,
2036
2938
  deliveryKind: "exact-page",
2037
2939
  async execute(raw, ctx) {
2940
+ const error = async (code, message, next = null) => {
2941
+ const result = acpReadBusiness({
2942
+ ok: false,
2943
+ error: {
2944
+ code,
2945
+ message: [...message].slice(0, 256).join(""),
2946
+ retryable: next !== null
2947
+ },
2948
+ next
2949
+ });
2950
+ await ctx.output.acceptExact(result, await documents.prepare(result.data, ctx), ctx.signal);
2951
+ return result;
2952
+ };
2953
+ const measure = async (result) => ctx.output.measure(result, await documents.prepare(result.data, ctx), ctx.signal);
2038
2954
  ctx.signal.throwIfAborted();
2039
2955
  signal.throwIfAborted();
2040
2956
  const input = z.union([kind === "acp_get" ? getInitial : listInitial, continuation]).parse(raw), now = performance.now();
@@ -2091,31 +3007,7 @@ function acpReadTools(store, manager, resources, signal) {
2091
3007
  offset: 0
2092
3008
  };
2093
3009
  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
- });
3010
+ if ("items" in input && (input.waitMs ?? 0) > 0 && !waited.has(ctx)) await query.lease.withUse(ctx, () => waitForTargets(input.items, input.waitMs, ctx));
2119
3011
  }
2120
3012
  const query = selected.query;
2121
3013
  try {
@@ -2128,23 +3020,8 @@ function acpReadTools(store, manager, resources, signal) {
2128
3020
  arguments: source
2129
3021
  });
2130
3022
  };
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
- }
3023
+ if (selected.selection) {
3024
+ const cached = selected.selection, items = [];
2148
3025
  try {
2149
3026
  if ("items" in source) for (const item of source.items) manager.summary(ctx.sessionId, item.delegationId, item.taskId);
2150
3027
  else if (kind === "acp_instances") store.instanceSummaryPage({
@@ -2158,10 +3035,57 @@ function acpReadTools(store, manager, resources, signal) {
2158
3035
  source: query.source,
2159
3036
  limit: 1
2160
3037
  });
3038
+ for (const row of cached.items) {
3039
+ if (!("index" in row)) {
3040
+ items.push(structuredClone(row));
3041
+ continue;
3042
+ }
3043
+ if (!row.value) {
3044
+ items.push({
3045
+ index: row.index,
3046
+ target: row.target,
3047
+ ...row.error ? { error: row.error } : {}
3048
+ });
3049
+ continue;
3050
+ }
3051
+ if (!("sourceBody" in row.value)) {
3052
+ items.push({
3053
+ ...row,
3054
+ value: structuredClone(row.value)
3055
+ });
3056
+ continue;
3057
+ }
3058
+ const { sourceBody, ...metadata } = row.value;
3059
+ const original = await manager.readResult(ctx.sessionId, row.target.delegationId, row.target.taskId, {
3060
+ seq: metadata.start.seq,
3061
+ offset: metadata.start.byte,
3062
+ limit: 4096
3063
+ });
3064
+ ctx.signal.throwIfAborted();
3065
+ signal.throwIfAborted();
3066
+ if (original.revision !== metadata.revision || JSON.stringify(original.source) !== JSON.stringify(metadata.source) || sourceHash(original.text) !== sourceBody.sha256 || Buffer.byteLength(original.text) !== sourceBody.byteLength) return restart("ACP original result changed; restart the query.");
3067
+ const body = await captureTextBody(original.text, ctx);
3068
+ ctx.signal.throwIfAborted();
3069
+ signal.throwIfAborted();
3070
+ manager.summary(ctx.sessionId, row.target.delegationId, row.target.taskId);
3071
+ items.push({
3072
+ ...row,
3073
+ value: {
3074
+ ...metadata,
3075
+ body
3076
+ }
3077
+ });
3078
+ }
2161
3079
  } catch (cause) {
2162
- return restart(cause instanceof Error ? cause.message : "ACP source unavailable");
3080
+ ctx.signal.throwIfAborted();
3081
+ signal.throwIfAborted();
3082
+ return restart(cause instanceof Error ? cause.message : "ACP original source unavailable");
2163
3083
  }
2164
- const needed = ctx.output.measure(selected.result);
3084
+ const result = acpReadBusiness({
3085
+ ...cached,
3086
+ items
3087
+ });
3088
+ const needed = await measure(result);
2165
3089
  if (needed > ctx.output.outputTokens) return error("page_too_small", "The fixed ACP page requires more allowance.", needed <= ctx.output.maximumTokens ? {
2166
3090
  tool: kind,
2167
3091
  arguments: {
@@ -2169,12 +3093,13 @@ function acpReadTools(store, manager, resources, signal) {
2169
3093
  outputTokens: needed
2170
3094
  }
2171
3095
  } : null);
2172
- ctx.output.acceptExact(selected.result);
2173
- return selected.result;
3096
+ await ctx.output.acceptExact(result, await documents.prepare(result.data, ctx), ctx.signal);
3097
+ track(ctx, result);
3098
+ return result;
2174
3099
  }
2175
3100
  const nextId = randomUUID(), items = [];
2176
3101
  let at = selected.member, after = selected.after, instanceAfter = selected.instanceAfter, seq = selected.seq, offset = selected.offset, complete = false;
2177
- const page = () => ({ content: JSON.stringify({
3102
+ const page = () => acpReadBusiness({
2178
3103
  ok: true,
2179
3104
  complete,
2180
3105
  items,
@@ -2186,7 +3111,7 @@ function acpReadTools(store, manager, resources, signal) {
2186
3111
  limit: source.limit,
2187
3112
  outputTokens: ctx.output.outputTokens
2188
3113
  }
2189
- }) });
3114
+ });
2190
3115
  if ("items" in source) {
2191
3116
  while (at < source.items.length && items.length < source.limit) {
2192
3117
  const priorAfter = after;
@@ -2195,31 +3120,38 @@ function acpReadTools(store, manager, resources, signal) {
2195
3120
  try {
2196
3121
  const status = manager.summary(ctx.sessionId, item.delegationId, item.taskId);
2197
3122
  if (source.view === "result") {
2198
- const part = manager.readResult(ctx.sessionId, item.delegationId, item.taskId, {
3123
+ const part = await manager.readResult(ctx.sessionId, item.delegationId, item.taskId, {
2199
3124
  seq,
2200
3125
  offset,
2201
3126
  limit: 4096
2202
3127
  });
3128
+ ctx.signal.throwIfAborted();
3129
+ signal.throwIfAborted();
2203
3130
  const prior = query.revisions.get(at);
2204
3131
  if (prior !== void 0 && prior !== part.revision) return restart("ACP original result changed; restart the query.");
2205
3132
  query.revisions.set(at, part.revision);
3133
+ const body = await captureTextBody(part.text, ctx);
3134
+ ctx.signal.throwIfAborted();
3135
+ signal.throwIfAborted();
3136
+ manager.summary(ctx.sessionId, item.delegationId, item.taskId);
2206
3137
  let points = [...part.text];
2207
3138
  const value = () => ({
2208
3139
  taskId: item.taskId,
2209
- text: points.join(""),
3140
+ body,
3141
+ startByte: 0,
3142
+ endByte: Buffer.byteLength(points.join("")),
2210
3143
  start: {
2211
3144
  seq: part.start.seq,
2212
3145
  byte: part.start.offset
2213
3146
  },
2214
- end: {
2215
- seq: part.start.seq,
2216
- byte: part.start.offset + Buffer.byteLength(points.join(""))
2217
- },
3147
+ end: originalPosition(part, Buffer.byteLength(points.join(""))).end,
2218
3148
  totalBytes: part.total,
2219
3149
  unit: "utf8-bytes",
2220
3150
  source: part.source,
2221
3151
  revision: part.revision,
2222
- originalComplete: part.originalComplete
3152
+ originalComplete: part.originalComplete,
3153
+ complete: seq === 0 && offset === 0 && part.complete && part.next === null && part.originalComplete && Buffer.byteLength(points.join("")) === part.total,
3154
+ ...seq === 0 && offset === 0 && part.complete && part.next === null && part.originalComplete && Buffer.byteLength(points.join("")) === part.total ? { deliveryKey: item.taskId } : {}
2223
3155
  });
2224
3156
  row = {
2225
3157
  index: at,
@@ -2227,17 +3159,13 @@ function acpReadTools(store, manager, resources, signal) {
2227
3159
  value: value()
2228
3160
  };
2229
3161
  items.push(row);
2230
- while (points.length && ctx.output.measure(page()) > ctx.output.outputTokens) {
3162
+ while (points.length && await measure(page()) > ctx.output.outputTokens) {
2231
3163
  points = points.slice(0, Math.floor(points.length / 2));
2232
3164
  row.value = value();
2233
3165
  }
2234
3166
  items.pop();
2235
3167
  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;
3168
+ nextPosition = originalPosition(part, row.value.endByte).next;
2241
3169
  memberComplete = nextPosition === null;
2242
3170
  } else if (item.taskId) row = {
2243
3171
  index: at,
@@ -2279,7 +3207,7 @@ function acpReadTools(store, manager, resources, signal) {
2279
3207
  };
2280
3208
  }
2281
3209
  items.push(row);
2282
- if (ctx.output.measure(page()) > ctx.output.outputTokens) {
3210
+ if (await measure(page()) > ctx.output.outputTokens) {
2283
3211
  items.pop();
2284
3212
  after = priorAfter;
2285
3213
  break;
@@ -2315,7 +3243,7 @@ function acpReadTools(store, manager, resources, signal) {
2315
3243
  query.source = found.source;
2316
3244
  for (const row of found.items) {
2317
3245
  items.push(row);
2318
- if (ctx.output.measure(page()) > ctx.output.outputTokens) {
3246
+ if (await measure(page()) > ctx.output.outputTokens) {
2319
3247
  items.pop();
2320
3248
  break;
2321
3249
  }
@@ -2342,7 +3270,7 @@ function acpReadTools(store, manager, resources, signal) {
2342
3270
  latest: store.summary(item.value.delegationId) ?? null
2343
3271
  };
2344
3272
  items.push(row);
2345
- if (ctx.output.measure(page()) > ctx.output.outputTokens) {
3273
+ if (await measure(page()) > ctx.output.outputTokens) {
2346
3274
  items.pop();
2347
3275
  break;
2348
3276
  }
@@ -2351,7 +3279,7 @@ function acpReadTools(store, manager, resources, signal) {
2351
3279
  if (items.length === found.items.length) after = found.after;
2352
3280
  complete = found.complete && items.length === found.items.length;
2353
3281
  }
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 ? {
3282
+ if (!items.length && !complete && kind !== "acp_list" || await measure(page()) > ctx.output.outputTokens) return error("page_too_small", "No complete ACP member fits this allowance.", ctx.output.outputTokens < ctx.output.maximumTokens ? {
2355
3283
  tool: kind,
2356
3284
  arguments: {
2357
3285
  cursor: id,
@@ -2359,7 +3287,7 @@ function acpReadTools(store, manager, resources, signal) {
2359
3287
  }
2360
3288
  } : null);
2361
3289
  const result = page();
2362
- const growth = Buffer.byteLength(result.content) + 512;
3290
+ const growth = Buffer.byteLength(JSON.stringify(result.data)) + 512;
2363
3291
  try {
2364
3292
  await query.lease.grow(ctx, {
2365
3293
  bytes: growth,
@@ -2371,13 +3299,38 @@ function acpReadTools(store, manager, resources, signal) {
2371
3299
  close(query);
2372
3300
  return error("query_capacity_exceeded", "ACP cursor cache exceeds temporary capacity.");
2373
3301
  }
2374
- ctx.output.acceptExact(result);
3302
+ await ctx.output.acceptExact(result, await documents.prepare(result.data, ctx), ctx.signal);
2375
3303
  query.lease.retain({
2376
3304
  reason: "public-cursor",
2377
3305
  idleMs: 6e5,
2378
3306
  maxAgeMs: 36e5
2379
3307
  });
2380
- selected.result = result;
3308
+ if (result.data.ok) selected.selection = {
3309
+ ...result.data,
3310
+ items: result.data.items.map((row) => {
3311
+ if (!("index" in row)) return structuredClone(row);
3312
+ if (!row.value) return {
3313
+ index: row.index,
3314
+ target: row.target,
3315
+ ...row.error ? { error: row.error } : {}
3316
+ };
3317
+ if (!("body" in row.value)) return {
3318
+ ...row,
3319
+ value: structuredClone(row.value)
3320
+ };
3321
+ const { body, ...metadata } = row.value;
3322
+ return {
3323
+ ...row,
3324
+ value: {
3325
+ ...metadata,
3326
+ sourceBody: {
3327
+ sha256: body.sha256,
3328
+ byteLength: body.byteLength
3329
+ }
3330
+ }
3331
+ };
3332
+ })
3333
+ };
2381
3334
  if (!complete) cursors.set(nextId, {
2382
3335
  query,
2383
3336
  member: at,
@@ -2386,6 +3339,7 @@ function acpReadTools(store, manager, resources, signal) {
2386
3339
  seq,
2387
3340
  offset
2388
3341
  });
3342
+ track(ctx, result);
2389
3343
  return result;
2390
3344
  });
2391
3345
  } catch (cause) {
@@ -2396,7 +3350,12 @@ function acpReadTools(store, manager, resources, signal) {
2396
3350
  });
2397
3351
  const wrap = (definition) => ({
2398
3352
  ...definition,
2399
- execute(input, ctx) {
3353
+ async execute(input, ctx) {
3354
+ const initial = definition.name === "acp_get" ? getInitial.safeParse(input) : void 0;
3355
+ if (initial?.success && (initial.data.waitMs ?? 0) > 0) {
3356
+ await waitForTargets(initial.data.items, initial.data.waitMs, ctx);
3357
+ waited.add(ctx);
3358
+ }
2400
3359
  const pending = queue.then(() => definition.execute(input, ctx));
2401
3360
  queue = pending.catch(() => {});
2402
3361
  return pending;
@@ -2414,8 +3373,6 @@ function acpReadTools(store, manager, resources, signal) {
2414
3373
  }
2415
3374
  //#endregion
2416
3375
  //#region src/tools.ts
2417
- /** Array tool intents, one launch approval and bounded paginated reads. */
2418
- /** One immutable external task proposal. */
2419
3376
  const Start = z.strictObject({
2420
3377
  instanceId: z.string().min(1).describe("Enabled adapter identity from acp_instances."),
2421
3378
  cwd: z.string().min(1).describe("Absolute working directory for the external task."),
@@ -2423,27 +3380,31 @@ const Start = z.strictObject({
2423
3380
  model: z.string().optional().describe("Remote adapter model identity; omit to retain its default."),
2424
3381
  config: z.record(z.string(), z.string()).optional().describe("Remote model or thought-level settings accepted by the adapter; permission modes are forbidden.")
2425
3382
  });
2426
- /** Positive safe page sizes are normalized by the owner rather than refused at the cap. */
2427
3383
  const Page = z.strictObject({
2428
3384
  offset: z.number().int().nonnegative().default(0),
2429
3385
  limit: z.number().int().min(1).default(50)
2430
3386
  });
2431
- /** The browser management list page, independent of model cursor pagination. */
2432
- function listPage(manager, sessionId, offset, requested) {
3387
+ function callLease(call) {
3388
+ if (!call.session) throw new Error("session_lease_unavailable: this host issues no call lease");
3389
+ return call.session;
3390
+ }
3391
+ function listPage(manager, sessionId, offset, requested, retainedOnly = false) {
2433
3392
  const limit = Math.min(200, requested);
2434
- const entries = manager.list(sessionId, offset, limit);
3393
+ const progress = manager.progress(sessionId, retainedOnly);
3394
+ const entries = manager.list(sessionId, offset, limit, retainedOnly);
2435
3395
  return {
2436
3396
  entries,
3397
+ progress,
2437
3398
  offset,
2438
3399
  limit,
2439
- nextOffset: entries.length === limit && manager.list(sessionId, offset + entries.length, 1).length > 0 ? offset + entries.length : null,
3400
+ nextOffset: entries.length === limit && manager.list(sessionId, offset + entries.length, 1, retainedOnly).length > 0 ? offset + entries.length : null,
2440
3401
  ...requested > limit ? { notice: `limit clamped from ${requested} to ${limit}` } : {}
2441
3402
  };
2442
3403
  }
2443
- /** Registers all collection tools while retaining approved physical process factories. */
2444
3404
  function registerCollectionTools(deps) {
2445
3405
  const { register, store, manager, services } = deps;
2446
- const pages = acpReadTools(store, manager, deps.resources, deps.signal);
3406
+ const documents = createTextDocuments(acpControlDocument);
3407
+ const pages = acpReadTools(store, manager, deps.resources, deps.signal, deps.observer);
2447
3408
  deps.onDispose(() => pages.close());
2448
3409
  register(pages.get);
2449
3410
  register(pages.list);
@@ -2451,10 +3412,8 @@ function registerCollectionTools(deps) {
2451
3412
  register({
2452
3413
  name: "acp_stop",
2453
3414
  preload: false,
2454
- outputSchema: collectionResult(z.strictObject({
2455
- stopped: z.boolean(),
2456
- closed: z.boolean()
2457
- })),
3415
+ outputSchema: AcpStopDataSchema,
3416
+ formatModel: documents.formatModel,
2458
3417
  deliveryKind: "receipt",
2459
3418
  description: "Stop or close independent external tasks, returning actual per-member cleanup results.",
2460
3419
  inputSchema: collectionInput({ items: z.array(z.strictObject({
@@ -2463,7 +3422,7 @@ function registerCollectionTools(deps) {
2463
3422
  })).min(1).max(64).describe("Ordered stop targets; one to 64 members, with duplicate resources settled once.") }, "items"),
2464
3423
  async execute(input, call) {
2465
3424
  const ids = input.items.map((item) => item.delegationId);
2466
- const batch = await manager.collection(ids, () => settleCollection(ids, async (id, index) => {
3425
+ return acpControlBusiness(await manager.collection(ids, () => settleCollection(ids, async (id, index) => {
2467
3426
  const before = manager.get(call.sessionId, id, 0, 200);
2468
3427
  if (input.items[index].close) await manager.close(call.sessionId, id);
2469
3428
  else await manager.stop(call.sessionId, id);
@@ -2471,28 +3430,14 @@ function registerCollectionTools(deps) {
2471
3430
  stopped: before.tasks.some((task) => task.state !== "finished" && task.state !== "queued"),
2472
3431
  closed: input.items[index].close
2473
3432
  };
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
- };
3433
+ })), "acp-stop");
2483
3434
  }
2484
3435
  });
2485
3436
  register({
2486
3437
  name: "acp_delegate",
2487
3438
  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()]),
3439
+ outputSchema: AcpDelegateDataSchema,
3440
+ formatModel: documents.formatModel,
2496
3441
  deliveryKind: "receipt",
2497
3442
  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
3443
  inputSchema: collectionInput({ items: z.array(Start).min(1).max(8).describe("One to eight independent external tasks covered by one launch approval.") }, "items"),
@@ -2503,25 +3448,37 @@ function registerCollectionTools(deps) {
2503
3448
  for (const [index, item] of input.items.entries()) try {
2504
3449
  const instance = store.instances().find((row) => row.id === item.instanceId && row.enabled);
2505
3450
  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
3451
+ await manager.prepareStart({
3452
+ ...item,
3453
+ sessionId: call.sessionId,
3454
+ requestKey: `${call.turn}:${call.toolCallId}:${index}`
2524
3455
  });
3456
+ const hold = deps.holds.hold(callLease(call));
3457
+ try {
3458
+ const launch = await prepareLaunch(call, instance, item.cwd, {
3459
+ ...services,
3460
+ approval: {
3461
+ ...services.approval,
3462
+ questionId: (id) => services.approval.questionId(id),
3463
+ decide(_authority, request) {
3464
+ requests.push(request);
3465
+ return {
3466
+ kind: "result",
3467
+ result: { kind: "allowed-once" }
3468
+ };
3469
+ }
3470
+ }
3471
+ }, hold);
3472
+ if ("result" in launch) throw new Error("launch-refused");
3473
+ prepared.set(index, {
3474
+ instance,
3475
+ launch,
3476
+ hold
3477
+ });
3478
+ } catch (error) {
3479
+ hold.retire();
3480
+ throw error;
3481
+ }
2525
3482
  } catch (error) {
2526
3483
  failures.set(index, error instanceof Error ? error : /* @__PURE__ */ new Error("launch-refused"));
2527
3484
  }
@@ -2547,12 +3504,9 @@ function registerCollectionTools(deps) {
2547
3504
  }
2548
3505
  });
2549
3506
  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
- };
3507
+ if (!decision.result.kind.startsWith("allowed-")) return acpFailure(decision.result.kind === "record-failed" ? "approval_record_failed" : "approval_rejected", decision.result.kind === "record-failed" ? `ACP approval recording failed: ${decision.result.message}` : "ACP launch was not authorized.");
2554
3508
  }
2555
- const batch = await manager.collection([], () => settleCollection(input.items.map((item) => item.instanceId), async (_id, index) => {
3509
+ return acpControlBusiness(await manager.collection([], () => settleCollection(input.items.map((item) => item.instanceId), async (_id, index) => {
2556
3510
  const failed = failures.get(index);
2557
3511
  if (failed) throw failed;
2558
3512
  const plan = prepared.get(index);
@@ -2566,7 +3520,7 @@ function registerCollectionTools(deps) {
2566
3520
  const current = store.instances().find((row) => row.id === plan.instance.id && row.enabled);
2567
3521
  if (!current || current.revision !== plan.instance.revision) throw new Error("configuration-changed: request launch again");
2568
3522
  return plan.launch.launch();
2569
- }, plan.launch.execution, plan.launch.release);
3523
+ }, plan.launch.execution, plan.launch.release, plan.hold);
2570
3524
  prepared.delete(index);
2571
3525
  return {
2572
3526
  id: task.id,
@@ -2579,18 +3533,16 @@ function registerCollectionTools(deps) {
2579
3533
  }), {
2580
3534
  sessionId: call.sessionId,
2581
3535
  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
- };
3536
+ }), "acp-delegate");
2591
3537
  };
2592
3538
  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);
3539
+ const cleanupFailures = (await Promise.allSettled([...prepared.values()].map(async (plan) => {
3540
+ try {
3541
+ await plan.launch.release();
3542
+ } finally {
3543
+ plan.hold.retire();
3544
+ }
3545
+ }))).filter((item) => item.status === "rejected").map((item) => item.reason);
2594
3546
  if (cleanupFailures.length) throw new AggregateError([...outcome.status === "rejected" ? [outcome.reason] : [], ...cleanupFailures], "ACP preparation cleanup failed");
2595
3547
  if (outcome.status === "rejected") throw outcome.reason;
2596
3548
  return outcome.value;
@@ -2602,7 +3554,7 @@ function registerCollectionTools(deps) {
2602
3554
  const Session = z.object({ sessionId: z.string().min(1) }).strict();
2603
3555
  const Target = Session.extend({ delegationId: z.string().min(1) }).strict();
2604
3556
  const Send = z.object({
2605
- delegationId: z.string().describe("Owned retained delegation to continue."),
3557
+ delegationId: z.string().describe("Owned delegation to continue; closed connections resume the saved remote session after launch approval."),
2606
3558
  task: z.string().min(1).describe("Self-contained follow-up task; an accepted task is queued and must not be resubmitted.")
2607
3559
  }).strict();
2608
3560
  const Result = z.unknown();
@@ -2614,6 +3566,7 @@ const acpPlugin = {
2614
3566
  name: "@eum-agent/integration-acp",
2615
3567
  configSchema: z.object({ disabled: z.array(z.enum(TOOL_NAMES)).default([]) }).strict().optional(),
2616
3568
  requires: [
3569
+ "delegation-policies",
2617
3570
  "sandbox",
2618
3571
  "host-commands",
2619
3572
  "network",
@@ -2621,14 +3574,25 @@ const acpPlugin = {
2621
3574
  "protocol-processes",
2622
3575
  "session-context",
2623
3576
  "session-delivery",
3577
+ "session-activity",
3578
+ "unit-of-work",
2624
3579
  "work-lifecycle",
2625
3580
  "owner-operations",
2626
- "query-resources"
3581
+ "query-resources",
3582
+ "session-lifecycle"
2627
3583
  ],
3584
+ provides: ["acp-delegation-observer"],
3585
+ recoverSessionResources: registerLaunchRecovery,
2628
3586
  async apply(ctx, config) {
2629
3587
  const register = (definition) => config?.disabled.includes(definition.name) ? () => {} : ctx.tools.register(definition);
2630
3588
  ctx.tools.guide(ACP_GUIDANCE);
2631
3589
  const store = createAcpStore(ctx.storage.open());
3590
+ ctx.retention.register(createAcpRetention(ctx.storage.open(), ctx.retention));
3591
+ const { publish: publishObservation, ...taskObserver } = createAcpDelegationObserver(store, () => ctx.log.emit({
3592
+ level: "error",
3593
+ event: "delegation.observer-failed"
3594
+ }));
3595
+ ctx.services.provide("acp-delegation-observer", taskObserver);
2632
3596
  const sessions = ctx.services.get("session-context");
2633
3597
  const commands = ctx.services.get("host-commands");
2634
3598
  const services = {
@@ -2638,16 +3602,26 @@ const acpPlugin = {
2638
3602
  approval: ctx.services.get("approval"),
2639
3603
  processes: ctx.services.get("protocol-processes")
2640
3604
  };
3605
+ const holds = createLaunchHolds(ctx.services.get("session-lifecycle"));
2641
3606
  const changed = ctx.client.registerFrame({
2642
3607
  name: "changed",
2643
3608
  delivery: "session",
2644
3609
  payload: Changed
2645
3610
  });
2646
3611
  const manager = createAcpManager({
3612
+ policies: ctx.services.get("delegation-policies"),
3613
+ holds,
3614
+ performance: ctx.performance,
2647
3615
  store,
3616
+ approval: services.approval,
2648
3617
  sessions,
2649
3618
  delivery: ctx.services.get("session-delivery"),
2650
- changed: (id, value) => changed.emit(id, Changed.parse(value)),
3619
+ activity: ctx.services.get("session-activity"),
3620
+ unitOfWork: ctx.services.get("unit-of-work"),
3621
+ observed: publishObservation,
3622
+ changed: (id, value) => {
3623
+ changed.emit(id, Changed.parse(value));
3624
+ },
2651
3625
  ask: (sessionId, request, options) => ctx.sessions.ask(sessionId, request, options)
2652
3626
  });
2653
3627
  await services.processes.recover();
@@ -2675,56 +3649,64 @@ const acpPlugin = {
2675
3649
  const find = (caller, id) => {
2676
3650
  return manager.get(caller, id);
2677
3651
  };
3652
+ const observer = ctx.toolDelivery?.observe({
3653
+ delivered() {},
3654
+ released() {}
3655
+ });
3656
+ if (observer) ctx.onDispose(() => observer.dispose());
2678
3657
  registerCollectionTools({
3658
+ observer,
2679
3659
  register,
2680
3660
  store,
2681
3661
  manager,
3662
+ holds,
2682
3663
  services,
2683
3664
  resources: ctx.services.get("query-resources"),
2684
3665
  signal: ctx.signal,
2685
3666
  onDispose: (cleanup) => ctx.onDispose(cleanup)
2686
3667
  });
3668
+ const sendDocuments = createTextDocuments(acpControlDocument);
2687
3669
  register({
2688
3670
  name: "acp_send",
2689
3671
  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
- }),
3672
+ outputSchema: AcpSendDataSchema,
3673
+ formatModel: sendDocuments.formatModel,
2698
3674
  deliveryKind: "receipt",
2699
3675
  description: "Continue an external delegation. Tasks queue FIFO; reconnecting requires renewed launch authorization.",
2700
3676
  inputSchema: Send,
2701
3677
  async execute(input, call) {
2702
3678
  const row = find(call.sessionId, input.delegationId).delegation;
3679
+ await manager.prepareSend(call.sessionId, row.id, input.task, `${call.turn}:${call.toolCallId}`);
2703
3680
  let admitted;
2704
3681
  if (!manager.hasConnection(row.id)) {
2705
3682
  const configured = store.instances().find((instance) => instance.id === row.instance.id && instance.enabled);
2706
3683
  if (!configured) throw new Error("instance-missing");
2707
3684
  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;
3685
+ const hold = holds.hold(holds.enter(row.parentSessionId));
3686
+ try {
3687
+ const prepared = await prepareLaunch(call, row.instance, row.cwd, services, hold);
3688
+ if ("result" in prepared) {
3689
+ hold.retire();
3690
+ return prepared.result;
3691
+ }
3692
+ admitted = {
3693
+ ...prepared,
3694
+ hold
3695
+ };
3696
+ } catch (error) {
3697
+ hold.retire();
3698
+ throw error;
3699
+ }
2711
3700
  }
2712
3701
  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
- };
3702
+ return acpControlBusiness({
3703
+ id: task.id,
3704
+ delegationId: task.delegationId,
3705
+ state: task.state,
3706
+ targetGeneration: task.targetGeneration,
3707
+ createdAt: task.createdAt,
3708
+ revision: task.revision
3709
+ }, "acp-send");
2728
3710
  }
2729
3711
  });
2730
3712
  const tickets = /* @__PURE__ */ new Map();
@@ -2735,11 +3717,26 @@ const acpPlugin = {
2735
3717
  const configured = store.instances().find((row) => row.id === instance.id && row.enabled);
2736
3718
  if (!configured) throw new Error("instance-missing");
2737
3719
  if (configured.revision !== instance.revision) throw new Error("configuration-changed: create a new delegation");
3720
+ if (!input.probe) {
3721
+ if (input.delegationId) await manager.prepareSend(input.sessionId, input.delegationId, input.task, input.requestKey);
3722
+ else await manager.prepareStart(input);
3723
+ }
3724
+ const hold = holds.hold(holds.enter(input.sessionId));
3725
+ let handed = false;
3726
+ try {
3727
+ return await launchManaged(input, instance, hold, answer, () => {
3728
+ handed = true;
3729
+ });
3730
+ } finally {
3731
+ if (!handed) hold.retire();
3732
+ }
3733
+ };
3734
+ const launchManaged = async (input, instance, hold, answer, handOver) => {
2738
3735
  const prepared = await prepareLaunch({
2739
3736
  sessionId: input.sessionId,
2740
3737
  address: sessions.resolve(input.sessionId).address,
2741
3738
  ...answer ? { answer } : {}
2742
- }, instance, input.cwd, services);
3739
+ }, instance, input.cwd, services, hold);
2743
3740
  if ("result" in prepared) {
2744
3741
  if (!("awaitHuman" in prepared.result)) throw new Error("launch-refused");
2745
3742
  for (const [id, ticket] of tickets) if (ticket.expires < Date.now()) tickets.delete(id);
@@ -2763,13 +3760,17 @@ const acpPlugin = {
2763
3760
  await prepared.release();
2764
3761
  throw new Error("preflight-in-progress");
2765
3762
  }
3763
+ hold.onRelease(prepared.release);
2766
3764
  const work = (async () => {
2767
- const process = await prepared.launch();
3765
+ const process = await hold.acquire(() => prepared.launch());
3766
+ hold.process(process);
2768
3767
  try {
3768
+ const { connectAcp } = await import("./client-B0Rlfsrk.js");
2769
3769
  const connection = await connectAcp(process, {
2770
3770
  update() {},
2771
3771
  permission: async () => ({ outcome: { outcome: "cancelled" } })
2772
3772
  });
3773
+ hold.connected();
2773
3774
  return { preflight: {
2774
3775
  execution: prepared.execution,
2775
3776
  protocolVersion: connection.initialized.protocolVersion,
@@ -2788,10 +3789,18 @@ const acpPlugin = {
2788
3789
  probes.delete(root);
2789
3790
  }
2790
3791
  }
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) };
3792
+ handOver();
3793
+ return { task: input.delegationId ? await manager.send(input.sessionId, input.delegationId, input.task, input.requestKey, {
3794
+ ...prepared,
3795
+ hold
3796
+ }) : await manager.start(input, prepared.launch, prepared.execution, prepared.release, hold) };
2792
3797
  };
2793
3798
  ctx.client.registerMethod({
2794
3799
  name: "preflight",
3800
+ session: {
3801
+ kind: "execution",
3802
+ sessionId: ({ sessionId }) => sessionId
3803
+ },
2795
3804
  params: Session.extend({
2796
3805
  instanceId: z.string(),
2797
3806
  cwd: z.string()
@@ -2806,6 +3815,10 @@ const acpPlugin = {
2806
3815
  });
2807
3816
  ctx.client.registerMethod({
2808
3817
  name: "start",
3818
+ session: {
3819
+ kind: "execution",
3820
+ sessionId: ({ sessionId }) => sessionId
3821
+ },
2809
3822
  params: Start.extend({
2810
3823
  sessionId: z.string(),
2811
3824
  requestKey: z.string()
@@ -2815,6 +3828,10 @@ const acpPlugin = {
2815
3828
  });
2816
3829
  ctx.client.registerMethod({
2817
3830
  name: "resume",
3831
+ session: {
3832
+ kind: "execution",
3833
+ sessionId: ({ sessionId }) => sessionId
3834
+ },
2818
3835
  params: Target.extend({
2819
3836
  task: z.string().min(1),
2820
3837
  requestKey: z.string()
@@ -2833,6 +3850,7 @@ const acpPlugin = {
2833
3850
  });
2834
3851
  ctx.client.registerMethod({
2835
3852
  name: "launchApprovals",
3853
+ session: { kind: "read" },
2836
3854
  params: Session,
2837
3855
  result: Result,
2838
3856
  handle: (input) => [...tickets.entries()].filter(([, ticket]) => ticket.input.sessionId === input.sessionId && ticket.expires > Date.now()).map(([id, ticket]) => ({
@@ -2842,6 +3860,7 @@ const acpPlugin = {
2842
3860
  });
2843
3861
  ctx.client.registerMethod({
2844
3862
  name: "usage",
3863
+ session: { kind: "read" },
2845
3864
  params: Session,
2846
3865
  result: Result,
2847
3866
  handle: (input) => manager.usage(input.sessionId)
@@ -2857,6 +3876,7 @@ const acpPlugin = {
2857
3876
  const ticket = tickets.get(input.id);
2858
3877
  tickets.delete(input.id);
2859
3878
  if (!ticket || ticket.expires < Date.now()) throw new Error("request-expired");
3879
+ holds.enter(ticket.input.sessionId);
2860
3880
  if (!input.allow) return { rejected: true };
2861
3881
  const configured = store.instances().find((row) => row.id === ticket.instance.id);
2862
3882
  if (!configured || !configured.enabled || configured.revision !== ticket.instance.revision) throw new Error("configuration-changed: request launch again");
@@ -2871,18 +3891,37 @@ const acpPlugin = {
2871
3891
  });
2872
3892
  ctx.client.registerMethod({
2873
3893
  name: "list",
2874
- params: Session.extend(Page.shape),
3894
+ session: { kind: "read" },
3895
+ params: Session.extend({
3896
+ ...Page.shape,
3897
+ retainedOnly: z.boolean().default(false)
3898
+ }),
2875
3899
  result: Result,
2876
- handle: (input) => listPage(manager, input.sessionId, input.offset, input.limit)
3900
+ handle: (input) => listPage(manager, input.sessionId, input.offset, input.limit, input.retainedOnly)
3901
+ });
3902
+ ctx.client.registerMethod({
3903
+ name: "statusByTasks",
3904
+ session: { kind: "read" },
3905
+ params: StatusByTasksParams,
3906
+ result: StatusByTasksResult,
3907
+ handle: (input) => manager.statusByTasks(input.sessionId, input.taskIds)
2877
3908
  });
2878
3909
  ctx.client.registerMethod({
2879
3910
  name: "get",
2880
- params: Target.extend(Page.shape),
3911
+ session: { kind: "read" },
3912
+ params: Target.extend({
3913
+ ...Page.shape,
3914
+ taskId: z.string().min(1).optional()
3915
+ }),
2881
3916
  result: Result,
2882
- handle: (input) => manager.get(input.sessionId, input.delegationId, input.offset, input.limit)
3917
+ handle: (input) => manager.get(input.sessionId, input.delegationId, input.offset, input.limit, void 0, input.taskId)
2883
3918
  });
2884
3919
  ctx.client.registerMethod({
2885
3920
  name: "send",
3921
+ session: {
3922
+ kind: "execution",
3923
+ sessionId: ({ sessionId }) => sessionId
3924
+ },
2886
3925
  params: Target.extend({
2887
3926
  task: z.string().min(1),
2888
3927
  requestKey: z.string()
@@ -2893,6 +3932,7 @@ const acpPlugin = {
2893
3932
  registerDelegationCollections(ctx, manager);
2894
3933
  ctx.client.registerMethod({
2895
3934
  name: "updates",
3935
+ session: { kind: "read" },
2896
3936
  params: Target.extend({
2897
3937
  taskId: z.string(),
2898
3938
  after: z.number().int().nonnegative().default(0)
@@ -2950,7 +3990,10 @@ const acpPlugin = {
2950
3990
  }
2951
3991
  });
2952
3992
  const ui = fileURLToPath(new URL("../ui/ui.js", import.meta.url));
2953
- if (existsSync(ui)) ctx.client.registerUi({ module: ui });
3993
+ if (existsSync(ui)) ctx.client.registerPackageFiles({
3994
+ root: dirname(ui),
3995
+ entry: "ui.js"
3996
+ });
2954
3997
  }
2955
3998
  };
2956
3999
  //#endregion