@noetic-tools/acp 2.0.0-next.1 → 2.0.0-next.2

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.
Files changed (46) hide show
  1. package/dist/bin.js +19 -2
  2. package/dist/client-adapters.d.ts +2 -2
  3. package/dist/client.d.ts +2 -2
  4. package/dist/client.js +1 -1
  5. package/dist/connection.d.ts +6 -2
  6. package/dist/connection.js +213 -31
  7. package/dist/define.js +92 -4
  8. package/dist/items.d.ts +1 -1
  9. package/dist/keeper/client.d.ts +84 -0
  10. package/dist/keeper/client.js +436 -0
  11. package/dist/keeper/main.d.ts +6 -0
  12. package/dist/keeper/main.js +31 -0
  13. package/dist/keeper/process.d.ts +24 -0
  14. package/dist/keeper/process.js +422 -0
  15. package/dist/keeper/protocol.d.ts +72 -0
  16. package/dist/keeper/protocol.js +101 -0
  17. package/dist/keeper/relay.d.ts +88 -0
  18. package/dist/keeper/relay.js +420 -0
  19. package/dist/mcp/node.d.ts +6 -1
  20. package/dist/mcp/node.js +4 -4
  21. package/dist/permission-channel.d.ts +5 -0
  22. package/dist/permission-channel.js +16 -1
  23. package/dist/runner/host.js +74 -16
  24. package/dist/runner/options.d.ts +2 -0
  25. package/dist/runner/options.js +2 -0
  26. package/dist/runner/protocol.d.ts +12 -0
  27. package/dist/runner/protocol.js +24 -0
  28. package/dist/runner/serve.d.ts +5 -0
  29. package/dist/runner/serve.js +93 -3
  30. package/dist/serve-types.d.ts +1 -1
  31. package/dist/serve.d.ts +2 -2
  32. package/dist/serve.js +1 -1
  33. package/dist/server.js +1 -1
  34. package/dist/stdio-process.d.ts +38 -0
  35. package/dist/stdio-process.js +214 -0
  36. package/dist/stdio.d.ts +28 -6
  37. package/dist/stdio.js +145 -51
  38. package/dist/tool-bridge.d.ts +9 -0
  39. package/dist/tool-bridge.js +5 -1
  40. package/dist/transport-loopback.d.ts +2 -2
  41. package/dist/transport-loopback.js +1 -1
  42. package/dist/turn.d.ts +3 -2
  43. package/dist/turn.js +22 -2
  44. package/dist/update-filter.d.ts +22 -0
  45. package/dist/update-filter.js +119 -0
  46. package/package.json +3 -3
@@ -0,0 +1,420 @@
1
+ /**
2
+ * The ACP relay inside an agent's keeper: it sits between the agent's stdio
3
+ * and whichever host is attached, so the agent can outlive a host and a later
4
+ * host can take it over.
5
+ *
6
+ * Pure: it consumes JSON-RPC lines from each side and emits lines through the
7
+ * two senders it is given. The keeper process (`main.ts`) owns the I/O.
8
+ *
9
+ * What it does:
10
+ * - Rewrites every host request id to its own, so a response is routed to the
11
+ * host attachment that asked; a later host's ids never collide with
12
+ * requests an earlier host left in flight.
13
+ * - Answers `initialize` from its cache after the first, so a reattaching host
14
+ * negotiates without re-initializing the agent.
15
+ * - Keeps, per session, the modes and config options the agent advertised,
16
+ * the updates of the turn in flight, updates sent while no host held the
17
+ * session, the agent's unanswered requests, and a turn result no host was
18
+ * attached to receive.
19
+ * - Serves two keeper requests a reattaching host makes:
20
+ * `_noetic/keeper/session` (what it knows of a session) and
21
+ * `_noetic/keeper/turn` (hand the session to this host: send the turn's
22
+ * updates and the agent's waiting requests again, then the turn's result
23
+ * once there is one).
24
+ */
25
+ //#endregion
26
+ //#region Constants
27
+ /** @public The keeper's own requests, which never reach the agent. */
28
+ export const KEEPER_METHODS = {
29
+ session: '_noetic/keeper/session',
30
+ turn: '_noetic/keeper/turn',
31
+ };
32
+ /** Updates kept per session while no host holds it, beyond which the oldest go. */
33
+ const MAX_BACKLOG = 1e4;
34
+ //#endregion
35
+ //#region Helpers
36
+ function isRecord(value) {
37
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
38
+ }
39
+ function isId(value) {
40
+ return typeof value === 'string' || typeof value === 'number';
41
+ }
42
+ function parse(line) {
43
+ try {
44
+ const value = JSON.parse(line);
45
+ return isRecord(value) ? value : undefined;
46
+ }
47
+ catch {
48
+ return undefined;
49
+ }
50
+ }
51
+ function sessionIdOf(params) {
52
+ return isRecord(params) && typeof params.sessionId === 'string' ? params.sessionId : undefined;
53
+ }
54
+ function line(message) {
55
+ return JSON.stringify({
56
+ jsonrpc: '2.0',
57
+ ...message,
58
+ });
59
+ }
60
+ //#endregion
61
+ //#region Relay
62
+ /** @public See the module comment. */
63
+ export class AcpRelay {
64
+ send;
65
+ /** Bumped on every detach, so what an earlier attachment asked has no host. */
66
+ epoch = 0;
67
+ attached = false;
68
+ nextId = 1;
69
+ asked = new Map();
70
+ sessions = new Map();
71
+ /** The agent's requests that name no session. */
72
+ unscoped = new Map();
73
+ initialized;
74
+ constructor(send) {
75
+ this.send = send;
76
+ }
77
+ /** A host attached. */
78
+ attach() {
79
+ this.attached = true;
80
+ for (const pending of this.unscoped.values()) {
81
+ this.send.toHost(pending);
82
+ }
83
+ }
84
+ /** The host went away; everything it held is kept for the next one. */
85
+ detach() {
86
+ this.attached = false;
87
+ this.epoch += 1;
88
+ }
89
+ get isAttached() {
90
+ return this.attached;
91
+ }
92
+ //#region From the host
93
+ fromHost(raw) {
94
+ const message = parse(raw);
95
+ if (!message) {
96
+ return;
97
+ }
98
+ const method = typeof message.method === 'string' ? message.method : undefined;
99
+ const id = isId(message.id) ? message.id : undefined;
100
+ if (method !== undefined && id !== undefined) {
101
+ this.hostRequest(method, id, isRecord(message.params) ? message.params : {}, message);
102
+ return;
103
+ }
104
+ if (method === undefined && id !== undefined) {
105
+ // The host's answer to one of the agent's requests.
106
+ this.forget(id);
107
+ this.send.toAgent(raw);
108
+ return;
109
+ }
110
+ this.send.toAgent(raw);
111
+ }
112
+ hostRequest(method, hostId, params, message) {
113
+ if (method === KEEPER_METHODS.session) {
114
+ this.answerHost(hostId, {
115
+ result: this.sessionInfo(sessionIdOf(params)),
116
+ });
117
+ return;
118
+ }
119
+ if (method === KEEPER_METHODS.turn) {
120
+ this.resumeTurn(sessionIdOf(params), hostId);
121
+ return;
122
+ }
123
+ if (method === 'initialize' && this.initialized !== undefined) {
124
+ this.answerHost(hostId, {
125
+ result: this.initialized,
126
+ });
127
+ return;
128
+ }
129
+ const keeperId = this.nextId;
130
+ this.nextId += 1;
131
+ this.asked.set(keeperId, {
132
+ epoch: this.epoch,
133
+ hostId,
134
+ method,
135
+ params,
136
+ });
137
+ const sessionId = sessionIdOf(params);
138
+ if (sessionId && (method === 'session/prompt' || method === 'session/load')) {
139
+ const session = this.session(sessionId);
140
+ this.claim(session, false);
141
+ if (method === 'session/prompt') {
142
+ session.turn = keeperId;
143
+ session.finished = undefined;
144
+ session.journal = [];
145
+ }
146
+ }
147
+ this.send.toAgent(JSON.stringify({
148
+ ...message,
149
+ id: keeperId,
150
+ }));
151
+ }
152
+ sessionInfo(sessionId) {
153
+ const session = sessionId ? this.sessions.get(sessionId) : undefined;
154
+ if (!session) {
155
+ return {
156
+ known: false,
157
+ turn: 'idle',
158
+ };
159
+ }
160
+ return {
161
+ known: true,
162
+ modes: session.modes,
163
+ configOptions: session.configOptions,
164
+ turn: session.turn !== undefined ? 'running' : session.finished ? 'finished' : 'idle',
165
+ };
166
+ }
167
+ /**
168
+ * Hand a session to this host: its turn's updates and the agent's waiting
169
+ * requests again, then the turn's result — now, or when the agent answers.
170
+ */
171
+ resumeTurn(sessionId, hostId) {
172
+ const session = sessionId ? this.sessions.get(sessionId) : undefined;
173
+ if (!session) {
174
+ this.answerHost(hostId, {
175
+ error: {
176
+ code: -32602,
177
+ message: `The keeper has no session ${String(sessionId)}.`,
178
+ },
179
+ });
180
+ return;
181
+ }
182
+ this.claim(session, true);
183
+ if (session.finished) {
184
+ const finished = session.finished;
185
+ session.finished = undefined;
186
+ this.answerHost(hostId, turnAnswer(finished));
187
+ return;
188
+ }
189
+ if (session.turn === undefined) {
190
+ this.answerHost(hostId, {
191
+ result: {
192
+ state: 'idle',
193
+ },
194
+ });
195
+ return;
196
+ }
197
+ session.waiter = {
198
+ epoch: this.epoch,
199
+ hostId,
200
+ };
201
+ }
202
+ /**
203
+ * The current attachment takes the session: what it missed (the whole turn
204
+ * when resuming one, else the backlog) and the agent's waiting requests.
205
+ */
206
+ claim(session, replayTurn) {
207
+ if (session.claimedBy === this.epoch) {
208
+ return;
209
+ }
210
+ session.claimedBy = this.epoch;
211
+ const missed = replayTurn ? session.journal : session.backlog;
212
+ for (const update of missed) {
213
+ this.send.toHost(update);
214
+ }
215
+ session.backlog = [];
216
+ for (const pending of session.pending.values()) {
217
+ this.send.toHost(pending);
218
+ }
219
+ }
220
+ forget(agentId) {
221
+ if (this.unscoped.delete(agentId)) {
222
+ return;
223
+ }
224
+ for (const session of this.sessions.values()) {
225
+ if (session.pending.delete(agentId)) {
226
+ return;
227
+ }
228
+ }
229
+ }
230
+ answerHost(hostId, answer) {
231
+ this.send.toHost(line({
232
+ id: hostId,
233
+ ...answer,
234
+ }));
235
+ }
236
+ //#endregion
237
+ //#region From the agent
238
+ fromAgent(raw) {
239
+ const message = parse(raw);
240
+ if (!message) {
241
+ return;
242
+ }
243
+ const method = typeof message.method === 'string' ? message.method : undefined;
244
+ const id = isId(message.id) ? message.id : undefined;
245
+ if (method === undefined && typeof id === 'number') {
246
+ this.agentResponse(id, message);
247
+ return;
248
+ }
249
+ if (method !== undefined && id !== undefined) {
250
+ this.agentRequest(id, message.params, raw);
251
+ return;
252
+ }
253
+ if (method !== undefined) {
254
+ this.agentNotification(method, message.params, raw);
255
+ }
256
+ }
257
+ agentResponse(keeperId, message) {
258
+ const asked = this.asked.get(keeperId);
259
+ if (!asked) {
260
+ return;
261
+ }
262
+ this.asked.delete(keeperId);
263
+ const answer = 'error' in message
264
+ ? {
265
+ error: message.error,
266
+ }
267
+ : {
268
+ result: message.result,
269
+ };
270
+ this.remember(asked, answer);
271
+ if (asked.method === 'session/prompt') {
272
+ this.turnEnded(asked, answer);
273
+ return;
274
+ }
275
+ if (this.isLive(asked.epoch)) {
276
+ this.answerHost(asked.hostId, answer);
277
+ }
278
+ }
279
+ /** Keep what an answer says about the agent and its sessions. */
280
+ remember(asked, answer) {
281
+ if (!('result' in answer) || !isRecord(answer.result)) {
282
+ return;
283
+ }
284
+ const result = answer.result;
285
+ if (asked.method === 'initialize') {
286
+ this.initialized = result;
287
+ return;
288
+ }
289
+ const sessionId = asked.method === 'session/new' ? sessionIdOf(result) : sessionIdOf(asked.params);
290
+ if (!sessionId) {
291
+ return;
292
+ }
293
+ const session = this.session(sessionId);
294
+ if (asked.method === 'session/new') {
295
+ session.claimedBy = asked.epoch;
296
+ }
297
+ if ('modes' in result && result.modes !== null) {
298
+ session.modes = result.modes;
299
+ }
300
+ if ('configOptions' in result && result.configOptions !== null) {
301
+ session.configOptions = result.configOptions;
302
+ }
303
+ if (asked.method === 'session/set_mode' && isRecord(session.modes)) {
304
+ session.modes = {
305
+ ...session.modes,
306
+ currentModeId: asked.params.modeId,
307
+ };
308
+ }
309
+ }
310
+ turnEnded(asked, answer) {
311
+ const sessionId = sessionIdOf(asked.params);
312
+ const session = sessionId ? this.sessions.get(sessionId) : undefined;
313
+ if (session) {
314
+ session.turn = undefined;
315
+ }
316
+ if (this.isLive(asked.epoch)) {
317
+ this.answerHost(asked.hostId, answer);
318
+ return;
319
+ }
320
+ const waiter = session?.waiter;
321
+ if (session && waiter && this.isLive(waiter.epoch)) {
322
+ session.waiter = undefined;
323
+ this.answerHost(waiter.hostId, turnAnswer(answer));
324
+ return;
325
+ }
326
+ if (session) {
327
+ session.finished = answer;
328
+ }
329
+ }
330
+ agentRequest(agentId, params, raw) {
331
+ const sessionId = sessionIdOf(params);
332
+ if (!sessionId) {
333
+ this.unscoped.set(agentId, raw);
334
+ if (this.attached) {
335
+ this.send.toHost(raw);
336
+ }
337
+ return;
338
+ }
339
+ const session = this.session(sessionId);
340
+ session.pending.set(agentId, raw);
341
+ if (this.holds(session)) {
342
+ this.send.toHost(raw);
343
+ }
344
+ }
345
+ agentNotification(method, params, raw) {
346
+ const sessionId = sessionIdOf(params);
347
+ if (method !== 'session/update' || !sessionId) {
348
+ if (this.attached) {
349
+ this.send.toHost(raw);
350
+ }
351
+ return;
352
+ }
353
+ const session = this.session(sessionId);
354
+ this.track(session, params);
355
+ if (session.turn !== undefined) {
356
+ session.journal.push(raw);
357
+ }
358
+ if (this.holds(session)) {
359
+ this.send.toHost(raw);
360
+ return;
361
+ }
362
+ if (session.turn === undefined) {
363
+ session.backlog.push(raw);
364
+ if (session.backlog.length > MAX_BACKLOG) {
365
+ session.backlog.shift();
366
+ }
367
+ }
368
+ }
369
+ /** Follow the mode and config option updates a session reports. */
370
+ track(session, params) {
371
+ const update = isRecord(params) && isRecord(params.update) ? params.update : undefined;
372
+ if (!update) {
373
+ return;
374
+ }
375
+ if (update.sessionUpdate === 'current_mode_update' && isRecord(session.modes)) {
376
+ session.modes = {
377
+ ...session.modes,
378
+ currentModeId: update.currentModeId,
379
+ };
380
+ }
381
+ if (update.sessionUpdate === 'config_option_update') {
382
+ session.configOptions = update.configOptions;
383
+ }
384
+ }
385
+ //#endregion
386
+ //#region State
387
+ session(sessionId) {
388
+ let session = this.sessions.get(sessionId);
389
+ if (!session) {
390
+ session = {
391
+ claimedBy: -1,
392
+ journal: [],
393
+ backlog: [],
394
+ pending: new Map(),
395
+ };
396
+ this.sessions.set(sessionId, session);
397
+ }
398
+ return session;
399
+ }
400
+ /** Whether the attached host holds the session, so it gets it live. */
401
+ holds(session) {
402
+ return this.attached && session.claimedBy === this.epoch;
403
+ }
404
+ isLive(epoch) {
405
+ return this.attached && epoch === this.epoch;
406
+ }
407
+ }
408
+ /** A finished turn, as `_noetic/keeper/turn` answers it. */
409
+ function turnAnswer(answer) {
410
+ if ('error' in answer) {
411
+ return answer;
412
+ }
413
+ return {
414
+ result: {
415
+ state: 'finished',
416
+ response: answer.result,
417
+ },
418
+ };
419
+ }
420
+ //#endregion
@@ -17,8 +17,13 @@ export interface HttpToolServer {
17
17
  readonly token: string;
18
18
  close(): Promise<void>;
19
19
  }
20
+ /** The path and token a bridge serves under, kept so a later host can serve the same. */
21
+ export interface BridgeCredentials {
22
+ readonly path: string;
23
+ readonly token: string;
24
+ }
20
25
  /**
21
26
  * Start a tool server on `127.0.0.1` at a random port and path. Each MCP
22
27
  * session the agent opens gets its own protocol server over the same host.
23
28
  */
24
- export declare function serveToolsOverHttp(getHost: () => AcpToolHost | undefined): Promise<HttpToolServer>;
29
+ export declare function serveToolsOverHttp(getHost: () => AcpToolHost | undefined, reuse?: BridgeCredentials): Promise<HttpToolServer>;
package/dist/mcp/node.js CHANGED
@@ -44,15 +44,15 @@ function refusal(req, expect) {
44
44
  }
45
45
  return undefined;
46
46
  }
47
- //#endregion
48
47
  //#region Public API
49
48
  /**
50
49
  * Start a tool server on `127.0.0.1` at a random port and path. Each MCP
51
50
  * session the agent opens gets its own protocol server over the same host.
52
51
  */
53
- export async function serveToolsOverHttp(getHost) {
54
- const token = randomUUID();
55
- const path = `/mcp/${randomUUID()}`;
52
+ export async function serveToolsOverHttp(getHost, reuse) {
53
+ // A reattached agent keeps the path and token an earlier host gave it.
54
+ const token = reuse?.token ?? randomUUID();
55
+ const path = reuse?.path ?? `/mcp/${randomUUID()}`;
56
56
  const sessions = new Map();
57
57
  const open = async () => {
58
58
  const transport = new NodeStreamableHTTPServerTransport({
@@ -70,6 +70,11 @@ export type AcpPermissionReply = z.infer<typeof AcpPermissionReplySchema>;
70
70
  export declare const acpPermissionRequests: ExternalChannel<AcpPermissionPrompt>;
71
71
  /** @public Decisions broadcast to every parked handler; each filters by its own `requestId`. */
72
72
  export declare const acpPermissionDecisions: ExternalChannel<AcpPermissionReply>;
73
+ /**
74
+ * ACP types a tool call's `rawInput` as any JSON value; the request record
75
+ * keeps an object, so a scalar or array is carried as `{ value }`.
76
+ */
77
+ export declare function rawInputRecord(value: unknown): Record<string, unknown> | undefined;
73
78
  /** @public Options for {@link askUserForPermission}. */
74
79
  export interface AskUserForPermissionOptions {
75
80
  /**
@@ -99,6 +99,21 @@ const MAX_WAIT_MS = 2 ** 31 - 1;
99
99
  function isChannelTimeout(error) {
100
100
  return isNoeticError(error) && error.noeticError.kind === 'channel_timeout';
101
101
  }
102
+ /**
103
+ * ACP types a tool call's `rawInput` as any JSON value; the request record
104
+ * keeps an object, so a scalar or array is carried as `{ value }`.
105
+ */
106
+ export function rawInputRecord(value) {
107
+ if (value === undefined || value === null) {
108
+ return undefined;
109
+ }
110
+ if (typeof value === 'object' && !Array.isArray(value)) {
111
+ return Object.fromEntries(Object.entries(value));
112
+ }
113
+ return {
114
+ value,
115
+ };
116
+ }
102
117
  /**
103
118
  * Build an {@link AcpPermissionHandler} that asks a human over the channel pair
104
119
  * above. Pass it as a step's `onPermissionRequest`; it runs after the step's
@@ -130,7 +145,7 @@ export function askUserForPermission(opts = {}) {
130
145
  stepId: info.stepId,
131
146
  title: request.toolCall.title ?? request.toolCall.toolCallId,
132
147
  kind: request.toolCall.kind ?? undefined,
133
- rawInput: request.toolCall.rawInput,
148
+ rawInput: rawInputRecord(request.toolCall.rawInput),
134
149
  options: request.options.map((option) => ({
135
150
  optionId: option.optionId,
136
151
  name: option.name,
@@ -7,6 +7,10 @@
7
7
  */
8
8
  import { AcpConnectError } from '@noetic-tools/types';
9
9
  import { chunksOf, fromBase64, RunnerFrameSchema, toBase64 } from './protocol.js';
10
+ /** How long a runner may take to answer a reattach. */
11
+ const ATTACH_TIMEOUT_MS = 1e4;
12
+ /** How long closing a stream waits for the runner to report it stopped. */
13
+ const KILL_WAIT_MS = 5e3;
10
14
  /** Request headers that belong to one hop, which `fetch` sets for itself. */
11
15
  const HOP_HEADERS = new Set([
12
16
  'host',
@@ -22,7 +26,13 @@ const HOP_HEADERS = new Set([
22
26
  * @public
23
27
  */
24
28
  export function runnerMachine(openLink) {
25
- return async ({ signal }) => new RunnerPeer(await openLink(signal), signal).machine();
29
+ return async ({ signal, whenHostExits = 'keep' }) => {
30
+ const peer = new RunnerPeer(await openLink(signal), signal);
31
+ // Agents this channel launches run through a keeper on the runner's
32
+ // machine, so they outlive the channel and a later one can reattach.
33
+ peer.keep(whenHostExits);
34
+ return peer.machine();
35
+ };
26
36
  }
27
37
  //#endregion
28
38
  //#region Peer
@@ -50,6 +60,7 @@ class RunnerPeer {
50
60
  reach: (bridge) => this.reach(bridge),
51
61
  launch: (command) => this.start(command, 'launch'),
52
62
  spawn: (command) => this.start(command, 'spawn'),
63
+ attach: (handle) => this.attach(handle),
53
64
  close: () => this.link.close(),
54
65
  };
55
66
  }
@@ -68,21 +79,43 @@ class RunnerPeer {
68
79
  url: reply.url,
69
80
  };
70
81
  }
71
- async start(command, kind) {
82
+ keep(whenHostExits) {
83
+ this.link.send({
84
+ t: 'keep',
85
+ id: this.id(),
86
+ whenHostExits,
87
+ });
88
+ }
89
+ /** The stream of an agent an earlier channel launched and the runner kept. */
90
+ async attach(handle) {
72
91
  const id = this.id();
73
- let exit = () => undefined;
74
- const exited = new Promise((resolve) => {
75
- exit = resolve;
92
+ const stream = this.openStream(id);
93
+ // A runner that does not keep agents never answers an attach.
94
+ const timeout = new Promise((_, reject) => {
95
+ const timer = setTimeout(() => reject(new AcpConnectError({
96
+ agentId: 'runner',
97
+ message: 'The remote runner did not answer a reattach; it may not keep agents.',
98
+ })), ATTACH_TIMEOUT_MS);
99
+ timer.unref?.();
76
100
  });
77
- const readable = new ReadableStream({
78
- start: (controller) => {
79
- this.streams.set(id, {
80
- controller,
81
- exited,
82
- exit,
83
- });
84
- },
101
+ const reply = await Promise.race([
102
+ this.ask({
103
+ t: 'attach',
104
+ handle,
105
+ }, id),
106
+ timeout,
107
+ ]).catch((e) => {
108
+ this.streams.delete(id);
109
+ throw e;
85
110
  });
111
+ if (reply.t !== 'started') {
112
+ throw unexpected(reply);
113
+ }
114
+ return this.transportFor(id, stream, handle);
115
+ }
116
+ async start(command, kind) {
117
+ const id = this.id();
118
+ const stream = this.openStream(id);
86
119
  const reply = await this.ask({
87
120
  t: 'start',
88
121
  kind,
@@ -99,6 +132,30 @@ class RunnerPeer {
99
132
  if (reply.t !== 'started') {
100
133
  throw unexpected(reply);
101
134
  }
135
+ return this.transportFor(id, stream, reply.reattach);
136
+ }
137
+ /** The readable for stream `id`, registered before the runner can answer. */
138
+ openStream(id) {
139
+ let exit = () => undefined;
140
+ const exited = new Promise((resolve) => {
141
+ exit = resolve;
142
+ });
143
+ const readable = new ReadableStream({
144
+ start: (controller) => {
145
+ this.streams.set(id, {
146
+ controller,
147
+ exited,
148
+ exit,
149
+ });
150
+ },
151
+ });
152
+ return {
153
+ readable,
154
+ exited,
155
+ };
156
+ }
157
+ /** Stream `id` as a transport; closing it stops what it carries. */
158
+ transportFor(id, stream, reattach) {
102
159
  const writable = new WritableStream({
103
160
  write: (chunk) => {
104
161
  this.link.send({
@@ -110,8 +167,9 @@ class RunnerPeer {
110
167
  });
111
168
  let closed = false;
112
169
  return {
113
- readable,
170
+ readable: stream.readable,
114
171
  writable,
172
+ reattach,
115
173
  close: async () => {
116
174
  if (closed) {
117
175
  return;
@@ -122,8 +180,8 @@ class RunnerPeer {
122
180
  id,
123
181
  });
124
182
  await Promise.race([
125
- exited,
126
- new Promise((resolve) => setTimeout(resolve, 2e3)),
183
+ stream.exited,
184
+ new Promise((resolve) => setTimeout(resolve, KILL_WAIT_MS)),
127
185
  ]);
128
186
  },
129
187
  };
@@ -16,6 +16,8 @@ export declare function runnerOptions(values: {
16
16
  spawn?: string[];
17
17
  env?: string[];
18
18
  cwd?: string;
19
+ /** How long a kept agent may run with no host attached; see {@link AcpRunnerOptions.detachedTimeoutMs}. */
20
+ detachedTimeoutMs?: number;
19
21
  }): AcpRunnerOptions;
20
22
  /** A runner does what whoever holds its token, or its stdio, asks of it. */
21
23
  export declare function trustWarning(options: AcpRunnerOptions): string;
@@ -24,11 +24,13 @@ export function runnerOptions(values) {
24
24
  if (grants.length === 0) {
25
25
  return {
26
26
  cwd: values.cwd,
27
+ detachedTimeoutMs: values.detachedTimeoutMs,
27
28
  };
28
29
  }
29
30
  const extra = values.env ?? [];
30
31
  return {
31
32
  cwd: values.cwd,
33
+ detachedTimeoutMs: values.detachedTimeoutMs,
32
34
  allow: grants.map((grant) => ({
33
35
  ...grant,
34
36
  env: [
@@ -31,6 +31,17 @@ export declare const HostFrameSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
31
31
  }, z.core.$strip>, z.ZodObject<{
32
32
  t: z.ZodLiteral<"kill">;
33
33
  id: z.ZodString;
34
+ }, z.core.$strip>, z.ZodObject<{
35
+ t: z.ZodLiteral<"keep">;
36
+ id: z.ZodString;
37
+ whenHostExits: z.ZodEnum<{
38
+ stop: "stop";
39
+ keep: "keep";
40
+ }>;
41
+ }, z.core.$strip>, z.ZodObject<{
42
+ t: z.ZodLiteral<"attach">;
43
+ id: z.ZodString;
44
+ handle: z.ZodRecord<z.ZodString, z.ZodUnknown>;
34
45
  }, z.core.$strip>, z.ZodObject<{
35
46
  t: z.ZodLiteral<"response">;
36
47
  id: z.ZodString;
@@ -52,6 +63,7 @@ export declare const RunnerFrameSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
52
63
  }, z.core.$strip>, z.ZodObject<{
53
64
  t: z.ZodLiteral<"started">;
54
65
  id: z.ZodString;
66
+ reattach: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
55
67
  }, z.core.$strip>, z.ZodObject<{
56
68
  t: z.ZodLiteral<"stdout">;
57
69
  id: z.ZodString;