@noetic-tools/acp 1.4.0 → 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 (50) 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 +2 -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 +7 -2
  22. package/dist/permission-channel.js +39 -13
  23. package/dist/permissions.d.ts +6 -0
  24. package/dist/permissions.js +7 -0
  25. package/dist/runner/host.js +74 -16
  26. package/dist/runner/options.d.ts +2 -0
  27. package/dist/runner/options.js +2 -0
  28. package/dist/runner/protocol.d.ts +12 -0
  29. package/dist/runner/protocol.js +24 -0
  30. package/dist/runner/serve.d.ts +5 -0
  31. package/dist/runner/serve.js +93 -3
  32. package/dist/serve-permissions.d.ts +8 -2
  33. package/dist/serve-permissions.js +26 -5
  34. package/dist/serve-types.d.ts +7 -6
  35. package/dist/serve.d.ts +2 -2
  36. package/dist/serve.js +1 -1
  37. package/dist/server.js +1 -1
  38. package/dist/stdio-process.d.ts +38 -0
  39. package/dist/stdio-process.js +214 -0
  40. package/dist/stdio.d.ts +28 -6
  41. package/dist/stdio.js +145 -51
  42. package/dist/tool-bridge.d.ts +9 -0
  43. package/dist/tool-bridge.js +5 -1
  44. package/dist/transport-loopback.d.ts +2 -2
  45. package/dist/transport-loopback.js +1 -1
  46. package/dist/turn.d.ts +3 -2
  47. package/dist/turn.js +22 -2
  48. package/dist/update-filter.d.ts +22 -0
  49. package/dist/update-filter.js +119 -0
  50. package/package.json +3 -3
package/dist/bin.js CHANGED
@@ -19,7 +19,18 @@
19
19
  import { parseArgs } from 'node:util';
20
20
  import { runnerOptions, trustWarning } from './runner/options.js';
21
21
  import { listenAcpRunner, newRunnerToken, readPem, serveAcpRunnerOverStdio } from './runner/serve.js';
22
- const USAGE = 'usage: noetic-acp serve [--stdio] [--host <host>] [--port <port>] [--agent <id>] [--spawn <command>]... [--env <name>]... [--cwd <dir>] [--tls-cert <pem> --tls-key <pem>]';
22
+ const USAGE = 'usage: noetic-acp serve [--stdio] [--host <host>] [--port <port>] [--agent <id>] [--spawn <command>]... [--env <name>]... [--cwd <dir>] [--detached-timeout <ms>] [--tls-cert <pem> --tls-key <pem>]';
23
+ /** `--detached-timeout <ms>`: a whole number of milliseconds, `0` for no limit. */
24
+ function detachedTimeout(value) {
25
+ if (value === undefined) {
26
+ return undefined;
27
+ }
28
+ const ms = Number(value);
29
+ if (!Number.isInteger(ms) || ms < 0) {
30
+ fail('--detached-timeout takes a whole number of milliseconds (0 for no limit).');
31
+ }
32
+ return ms;
33
+ }
23
34
  async function main(argv) {
24
35
  const [verb, ...rest] = argv;
25
36
  if (verb !== 'serve') {
@@ -53,6 +64,9 @@ async function main(argv) {
53
64
  cwd: {
54
65
  type: 'string',
55
66
  },
67
+ 'detached-timeout': {
68
+ type: 'string',
69
+ },
56
70
  'tls-cert': {
57
71
  type: 'string',
58
72
  },
@@ -61,7 +75,10 @@ async function main(argv) {
61
75
  },
62
76
  },
63
77
  });
64
- const options = runnerOptions(values);
78
+ const options = runnerOptions({
79
+ ...values,
80
+ detachedTimeoutMs: detachedTimeout(values['detached-timeout']),
81
+ });
65
82
  process.stderr.write(`${trustWarning(options)}\n`);
66
83
  if (values.stdio) {
67
84
  await serveAcpRunnerOverStdio(options);
@@ -11,9 +11,9 @@
11
11
  * {@link AcpCapabilityError} rather than pretending, and a factory author who
12
12
  * needs those falls back to a local adapter for them.
13
13
  */
14
+ import type * as acp from '@agentclientprotocol/sdk';
15
+ import type { AgentSideConnection } from '@agentclientprotocol/sdk';
14
16
  import type { FsAdapter, ShellAdapter } from '@noetic-tools/types';
15
- import type * as acp from '@zed-industries/agent-client-protocol';
16
- import type { AgentSideConnection } from '@zed-industries/agent-client-protocol';
17
17
  /** @public Options for {@link clientFsAdapter}. */
18
18
  export interface ClientFsAdapterOptions {
19
19
  conn: AgentSideConnection;
package/dist/client.d.ts CHANGED
@@ -12,8 +12,8 @@
12
12
  * the step's config. A withdrawn capability is answered with a JSON-RPC
13
13
  * method-not-found rather than silently doing the work anyway.
14
14
  */
15
+ import type * as acp from '@agentclientprotocol/sdk';
15
16
  import type { AcpClientHost } from '@noetic-tools/types';
16
- import type * as acp from '@zed-industries/agent-client-protocol';
17
17
  import type { BridgedPermissionCheck } from './tool-permissions.js';
18
18
  /** Build the `ClientCapabilities` sent during `initialize`. */
19
19
  export declare function clientCapabilitiesFor(host: AcpClientHost): acp.ClientCapabilities;
@@ -77,7 +77,7 @@ export declare class NoeticAcpClient implements acp.Client {
77
77
  createTerminal(params: acp.CreateTerminalRequest): Promise<acp.CreateTerminalResponse>;
78
78
  terminalOutput(params: acp.TerminalOutputRequest): Promise<acp.TerminalOutputResponse>;
79
79
  waitForTerminalExit(params: acp.WaitForTerminalExitRequest): Promise<acp.WaitForTerminalExitResponse>;
80
- killTerminal(params: acp.KillTerminalCommandRequest): Promise<acp.KillTerminalResponse>;
80
+ killTerminal(params: acp.KillTerminalRequest): Promise<acp.KillTerminalResponse>;
81
81
  releaseTerminal(params: acp.ReleaseTerminalRequest): Promise<acp.ReleaseTerminalResponse>;
82
82
  /**
83
83
  * Run a client method, reporting it either way. A refusal is the more
package/dist/client.js CHANGED
@@ -12,7 +12,7 @@
12
12
  * the step's config. A withdrawn capability is answered with a JSON-RPC
13
13
  * method-not-found rather than silently doing the work anyway.
14
14
  */
15
- import { RequestError } from '@zed-industries/agent-client-protocol';
15
+ import { RequestError } from '@agentclientprotocol/sdk';
16
16
  import { isAbsolutePath, isWithinRoots } from './paths.js';
17
17
  import { resolvePermission, selectPermissionOption } from './permissions.js';
18
18
  import { buildCommandLine, TerminalRegistry } from './terminals.js';
@@ -88,6 +88,7 @@ export class NoeticAcpClient {
88
88
  return {
89
89
  policy: this.host.permissions,
90
90
  steer: this.host.steerPermission,
91
+ approve: this.host.approvePermission,
91
92
  handler: this.host.onPermissionRequest,
92
93
  };
93
94
  }
@@ -14,8 +14,8 @@
14
14
  * - translate an aborted turn into `session/cancel` plus the `cancelled`
15
15
  * stop reason the specification requires.
16
16
  */
17
- import type { AcpAgentConnection, AcpClientHost, AcpContentBlock, AcpTransport } from '@noetic-tools/types';
18
- import type * as acp from '@zed-industries/agent-client-protocol';
17
+ import type * as acp from '@agentclientprotocol/sdk';
18
+ import type { AcpAgentConnection, AcpClientHost, AcpContentBlock, AcpReattachHandle, AcpTransport } from '@noetic-tools/types';
19
19
  import type { ToolBridge } from './tool-bridge.js';
20
20
  /** @public Options for {@link openAcpConnection}. */
21
21
  export interface OpenAcpConnectionOptions {
@@ -25,6 +25,10 @@ export interface OpenAcpConnectionOptions {
25
25
  signal?: AbortSignal;
26
26
  /** The tool bridge serving `host.tools`, closed with the connection. */
27
27
  tools?: ToolBridge;
28
+ /** How a later host reaches this agent, when it can outlive this one. */
29
+ reattach?: AcpReattachHandle;
30
+ /** The transport reaches an agent an earlier host started (through its keeper). */
31
+ reattached?: boolean;
28
32
  }
29
33
  /**
30
34
  * The spec requires clients to restrict prompt content to what the agent
@@ -14,11 +14,14 @@
14
14
  * - translate an aborted turn into `session/cancel` plus the `cancelled`
15
15
  * stop reason the specification requires.
16
16
  */
17
+ import { ClientSideConnection, ndJsonStream, PROTOCOL_VERSION } from '@agentclientprotocol/sdk';
17
18
  import { AcpCapabilityError, AcpConnectError } from '@noetic-tools/types';
18
- import { ClientSideConnection, ndJsonStream, PROTOCOL_VERSION, } from '@zed-industries/agent-client-protocol';
19
+ import { z } from 'zod';
19
20
  import { clientCapabilitiesFor, NoeticAcpClient } from './client.js';
21
+ import { KEEPER_METHODS } from './keeper/relay.js';
20
22
  import { watchTransport } from './liveness.js';
21
23
  import { AcpTurnAccumulator } from './turn.js';
24
+ import { divertNewerUpdates } from './update-filter.js';
22
25
  //#endregion
23
26
  //#region Content capability gating
24
27
  /**
@@ -49,14 +52,48 @@ export function assertPromptContentSupported(agentId, content, capabilities) {
49
52
  }
50
53
  }
51
54
  }
55
+ /** What the keeper says about a session (`_noetic/keeper/session`). */
56
+ const KeeperSessionSchema = z.object({
57
+ known: z.boolean(),
58
+ modes: z.custom((value) => isRecord(value)).optional(),
59
+ configOptions: z.custom((value) => Array.isArray(value)).optional(),
60
+ });
61
+ const StopReasonSchema = z.enum([
62
+ 'end_turn',
63
+ 'max_tokens',
64
+ 'max_turn_requests',
65
+ 'refusal',
66
+ 'cancelled',
67
+ ]);
68
+ /** How the keeper answers `_noetic/keeper/turn`. */
69
+ const KeeperTurnSchema = z.discriminatedUnion('state', [
70
+ z.object({
71
+ state: z.literal('idle'),
72
+ }),
73
+ z.object({
74
+ state: z.literal('finished'),
75
+ response: z.object({
76
+ stopReason: StopReasonSchema,
77
+ usage: z.custom((value) => isRecord(value)).nullish(),
78
+ }),
79
+ }),
80
+ ]);
81
+ function isRecord(value) {
82
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
83
+ }
84
+ /** JSON-RPC's "method not found". */
85
+ const METHOD_NOT_FOUND = -32601;
86
+ function isMethodNotFound(error) {
87
+ return (typeof error === 'object' && error !== null && Reflect.get(error, 'code') === METHOD_NOT_FOUND);
88
+ }
52
89
  //#endregion
53
90
  //#region Session
54
91
  class AcpSessionImpl {
55
92
  agentId;
56
93
  agent;
57
94
  sessionId;
58
- modes;
59
- models;
95
+ modeState;
96
+ options;
60
97
  commands;
61
98
  death;
62
99
  promptCapabilities;
@@ -71,7 +108,7 @@ class AcpSessionImpl {
71
108
  * deserve a correct answer, just not simultaneously.
72
109
  */
73
110
  queue = Promise.resolve();
74
- constructor(agentId, agent, sessionId, modes, models, commands,
111
+ constructor(agentId, agent, sessionId, modeState, options, commands,
75
112
  /** Rejects if the agent dies, so a request cannot outlive it. */
76
113
  death,
77
114
  /** What the agent said it accepts, enforced before a turn goes on the wire. */
@@ -79,15 +116,34 @@ class AcpSessionImpl {
79
116
  this.agentId = agentId;
80
117
  this.agent = agent;
81
118
  this.sessionId = sessionId;
82
- this.modes = modes;
83
- this.models = models;
119
+ this.modeState = modeState;
120
+ this.options = options;
84
121
  this.commands = commands;
85
122
  this.death = death;
86
123
  this.promptCapabilities = promptCapabilities;
87
124
  }
125
+ get modes() {
126
+ return this.modeState;
127
+ }
128
+ get configOptions() {
129
+ return this.options ?? [];
130
+ }
88
131
  get availableCommands() {
89
132
  return this.commands;
90
133
  }
134
+ /**
135
+ * Take the modes and config options a `session/load` answer advertises. The
136
+ * session is registered before the load (so replayed updates reach it), so
137
+ * these arrive after construction.
138
+ */
139
+ applySettings(settings) {
140
+ if (settings.modes) {
141
+ this.modeState = settings.modes;
142
+ }
143
+ if (settings.configOptions) {
144
+ this.options = settings.configOptions;
145
+ }
146
+ }
91
147
  /** Feed a notification to the running turn, if any. */
92
148
  receive(notification) {
93
149
  const update = notification.update;
@@ -96,6 +152,15 @@ class AcpSessionImpl {
96
152
  ...update.availableCommands,
97
153
  ];
98
154
  }
155
+ if (update.sessionUpdate === 'current_mode_update' && this.modeState) {
156
+ this.modeState = {
157
+ ...this.modeState,
158
+ currentModeId: update.currentModeId,
159
+ };
160
+ }
161
+ if (update.sessionUpdate === 'config_option_update') {
162
+ this.options = update.configOptions;
163
+ }
99
164
  this.activeTurn?.push(notification);
100
165
  }
101
166
  async prompt(opts) {
@@ -111,8 +176,51 @@ class AcpSessionImpl {
111
176
  return await ours;
112
177
  }
113
178
  async runTurn(opts) {
179
+ const result = await this.collectTurn(opts.signal, async () => this.agent.prompt({
180
+ sessionId: this.sessionId,
181
+ prompt: [
182
+ ...opts.content,
183
+ ],
184
+ }));
185
+ if (!result) {
186
+ throw new Error('session/prompt returned no answer.');
187
+ }
188
+ return result;
189
+ }
190
+ /**
191
+ * Make this a reattached session: {@link resumeTurn} collects the turn the
192
+ * previous host left running through the keeper.
193
+ */
194
+ enableResume() {
195
+ this.resumeTurn = async (opts) => {
196
+ const ours = this.queue.then(() => this.collectTurn(opts.signal, () => this.keeperTurn()), () => this.collectTurn(opts.signal, () => this.keeperTurn()));
197
+ this.queue = ours.catch(() => undefined);
198
+ return await ours;
199
+ };
200
+ }
201
+ /** Set on a reattached session; see `AcpSession.resumeTurn`. */
202
+ resumeTurn;
203
+ /** Ask the keeper for the turn in flight: its updates arrive, then its answer. */
204
+ async keeperTurn() {
205
+ const request = this.agent.extMethod?.bind(this.agent);
206
+ if (!request) {
207
+ return undefined;
208
+ }
209
+ const answer = KeeperTurnSchema.parse(await request(KEEPER_METHODS.turn, {
210
+ sessionId: this.sessionId,
211
+ }));
212
+ return answer.state === 'finished' ? answer.response : undefined;
213
+ }
214
+ /**
215
+ * Run one turn: updates go to a fresh accumulator while `send` waits for
216
+ * the agent's answer. Undefined when there was no turn to collect.
217
+ */
218
+ async collectTurn(signal, send) {
114
219
  const accumulator = new AcpTurnAccumulator();
115
220
  this.activeTurn = accumulator;
221
+ const opts = {
222
+ signal,
223
+ };
116
224
  const onAbort = () => {
117
225
  // Fire-and-forget: the specification says the agent still answers the
118
226
  // original `session/prompt` with the `cancelled` stop reason.
@@ -123,16 +231,15 @@ class AcpSessionImpl {
123
231
  });
124
232
  try {
125
233
  const response = await Promise.race([
126
- this.agent.prompt({
127
- sessionId: this.sessionId,
128
- prompt: [
129
- ...opts.content,
130
- ],
131
- }),
234
+ send(),
132
235
  this.death,
133
236
  ]);
237
+ if (!response) {
238
+ return undefined;
239
+ }
134
240
  return accumulator.result({
135
241
  stopReason: response.stopReason,
242
+ reportedUsage: response.usage ?? undefined,
136
243
  });
137
244
  }
138
245
  finally {
@@ -146,7 +253,7 @@ class AcpSessionImpl {
146
253
  });
147
254
  }
148
255
  async setMode(modeId) {
149
- if (!this.modes || !this.agent.setSessionMode) {
256
+ if (!this.modeState || !this.agent.setSessionMode) {
150
257
  throw new AcpCapabilityError({
151
258
  agentId: this.agentId,
152
259
  capability: 'session/set_mode',
@@ -161,19 +268,62 @@ class AcpSessionImpl {
161
268
  ]);
162
269
  }
163
270
  async setModel(modelId) {
164
- if (!this.models || !this.agent.setSessionModel) {
271
+ const model = this.modelOption();
272
+ if (model && this.agent.setSessionConfigOption) {
273
+ const response = await Promise.race([
274
+ this.agent.setSessionConfigOption({
275
+ sessionId: this.sessionId,
276
+ configId: model.id,
277
+ value: modelId,
278
+ }),
279
+ this.death,
280
+ ]);
281
+ this.options = response.configOptions;
282
+ return;
283
+ }
284
+ await this.setModelDirectly(modelId);
285
+ }
286
+ /**
287
+ * The `model` config option: by category, else by id, for an agent that
288
+ * leaves the (optional, UX-only) category off.
289
+ */
290
+ modelOption() {
291
+ const selects = (this.options ?? []).filter((option) => option.type === 'select');
292
+ return (selects.find((option) => option.category === 'model') ??
293
+ selects.find((option) => option.id === 'model'));
294
+ }
295
+ /**
296
+ * An agent that advertises no `model` config option may still take the
297
+ * draft `session/set_model` request (it predates config options). One that
298
+ * does not know it answers "method not found", which is the capability
299
+ * error a step expects.
300
+ */
301
+ async setModelDirectly(modelId) {
302
+ const request = this.agent.extMethod?.bind(this.agent);
303
+ if (!request) {
165
304
  throw new AcpCapabilityError({
166
305
  agentId: this.agentId,
167
- capability: 'session/set_model',
306
+ capability: 'session/set_config_option:model',
168
307
  });
169
308
  }
170
- await Promise.race([
171
- this.agent.setSessionModel({
172
- sessionId: this.sessionId,
173
- modelId,
174
- }),
175
- this.death,
176
- ]);
309
+ try {
310
+ await Promise.race([
311
+ request('session/set_model', {
312
+ sessionId: this.sessionId,
313
+ modelId,
314
+ }),
315
+ this.death,
316
+ ]);
317
+ }
318
+ catch (error) {
319
+ if (isMethodNotFound(error)) {
320
+ throw new AcpCapabilityError({
321
+ agentId: this.agentId,
322
+ capability: 'session/set_config_option:model',
323
+ });
324
+ }
325
+ throw error;
326
+ }
177
327
  }
178
328
  }
179
329
  //#endregion
@@ -188,8 +338,9 @@ class AcpAgentConnectionImpl {
188
338
  protocolVersion;
189
339
  watch;
190
340
  tools;
341
+ reattach;
191
342
  sessions = new Map();
192
- constructor(agentId, agent, transport, client, agentCapabilities, authMethods, protocolVersion, watch, tools) {
343
+ constructor(agentId, agent, transport, client, agentCapabilities, authMethods, protocolVersion, watch, tools, reattach, reattached) {
193
344
  this.agentId = agentId;
194
345
  this.agent = agent;
195
346
  this.transport = transport;
@@ -199,6 +350,33 @@ class AcpAgentConnectionImpl {
199
350
  this.protocolVersion = protocolVersion;
200
351
  this.watch = watch;
201
352
  this.tools = tools;
353
+ this.reattach = reattach;
354
+ if (reattached) {
355
+ this.attachSession = (sessionId) => this.attachTo(sessionId);
356
+ }
357
+ }
358
+ /** Set on a reattached connection; see `AcpAgentConnection.attachSession`. */
359
+ attachSession;
360
+ /** The live session `sessionId`, as the keeper last saw it. */
361
+ async attachTo(sessionId) {
362
+ const request = this.agent.extMethod?.bind(this.agent);
363
+ const info = request
364
+ ? KeeperSessionSchema.parse(await Promise.race([
365
+ request(KEEPER_METHODS.session, {
366
+ sessionId,
367
+ }),
368
+ this.watch.death,
369
+ ]))
370
+ : undefined;
371
+ if (!info?.known) {
372
+ throw new AcpConnectError({
373
+ agentId: this.agentId,
374
+ message: `ACP agent '${this.agentId}' no longer has session ${sessionId}.`,
375
+ });
376
+ }
377
+ const session = new AcpSessionImpl(this.agentId, this.agent, sessionId, info.modes, info.configOptions, [], this.watch.death, this.agentCapabilities.promptCapabilities);
378
+ session.enableResume();
379
+ return this.track(session);
202
380
  }
203
381
  /** The sink the client hands every `session/update` notification. */
204
382
  get sink() {
@@ -222,7 +400,7 @@ class AcpAgentConnectionImpl {
222
400
  }),
223
401
  this.watch.death,
224
402
  ]);
225
- return this.track(new AcpSessionImpl(this.agentId, this.agent, response.sessionId, response.modes ?? undefined, response.models ?? undefined, [], this.watch.death, this.agentCapabilities.promptCapabilities));
403
+ return this.track(new AcpSessionImpl(this.agentId, this.agent, response.sessionId, response.modes ?? undefined, response.configOptions ?? undefined, [], this.watch.death, this.agentCapabilities.promptCapabilities));
226
404
  }
227
405
  async loadSession(opts) {
228
406
  if (this.agentCapabilities.loadSession !== true || !this.agent.loadSession) {
@@ -234,7 +412,7 @@ class AcpAgentConnectionImpl {
234
412
  // Register before the call: `session/load` replays the conversation through
235
413
  // `session/update` notifications, which must not be dropped on the floor.
236
414
  const session = this.track(new AcpSessionImpl(this.agentId, this.agent, opts.sessionId, undefined, undefined, [], this.watch.death, this.agentCapabilities.promptCapabilities));
237
- await Promise.race([
415
+ const response = await Promise.race([
238
416
  this.agent.loadSession({
239
417
  sessionId: opts.sessionId,
240
418
  cwd: opts.cwd,
@@ -242,6 +420,9 @@ class AcpAgentConnectionImpl {
242
420
  }),
243
421
  this.watch.death,
244
422
  ]);
423
+ if (response) {
424
+ session.applySettings(response);
425
+ }
245
426
  return session;
246
427
  }
247
428
  async close() {
@@ -324,15 +505,16 @@ export async function openAcpConnection(opts) {
324
505
  const client = new NoeticAcpClient({
325
506
  host,
326
507
  permitsBridged: opts.tools?.permits,
327
- onNotify: (notification) => {
328
- sink?.(notification);
329
- host.onSessionUpdate(notification);
330
- },
508
+ onNotify: (notification) => notify(notification),
331
509
  });
332
510
  // The protocol library never rejects pending responses when the stream ends,
333
511
  // so without this a dead agent leaves every request hanging forever.
334
512
  const watch = watchTransport(opts.agentId, opts.transport, opts.signal);
335
- const agent = new ClientSideConnection(() => client, ndJsonStream(opts.transport.writable, watch.readable));
513
+ const notify = (notification) => {
514
+ sink?.(notification);
515
+ host.onSessionUpdate(notification);
516
+ };
517
+ const agent = new ClientSideConnection(() => client, ndJsonStream(opts.transport.writable, divertNewerUpdates(watch.readable, notify)));
336
518
  let initialized;
337
519
  try {
338
520
  initialized = await Promise.race([
@@ -352,7 +534,7 @@ export async function openAcpConnection(opts) {
352
534
  cause: error,
353
535
  });
354
536
  }
355
- const connection = new AcpAgentConnectionImpl(opts.agentId, agent, opts.transport, client, initialized.agentCapabilities ?? {}, initialized.authMethods ?? [], initialized.protocolVersion, watch, opts.tools);
537
+ const connection = new AcpAgentConnectionImpl(opts.agentId, agent, opts.transport, client, initialized.agentCapabilities ?? {}, initialized.authMethods ?? [], initialized.protocolVersion, watch, opts.tools, opts.reattach, opts.reattached === true);
356
538
  sink = connection.sink;
357
539
  return connection;
358
540
  }
package/dist/define.js CHANGED
@@ -7,6 +7,8 @@
7
7
  * prompts, permissions, terminals — is protocol-generic and lives in
8
8
  * {@link openAcpConnection}.
9
9
  */
10
+ import { AcpConnectError } from '@noetic-tools/types';
11
+ import { z } from 'zod';
10
12
  import { openAcpConnection } from './connection.js';
11
13
  import { spawnOn } from './spawn.js';
12
14
  import { startToolBridge } from './tool-bridge.js';
@@ -25,10 +27,20 @@ export function defineAcpAgent(def) {
25
27
  spawn: def.command ? spawnOn(def.machine ?? lazyLocalMachine(def.agentId)) : undefined,
26
28
  async connect(opts) {
27
29
  const signal = opts.signal ?? opts.host.signal;
28
- const opened = await openTarget(def, opts.host.cwd, signal);
30
+ const whenHostExits = opts.whenHostExits ?? 'keep';
31
+ if (opts.reattach) {
32
+ return await reattachTo(def, opts, opts.reattach);
33
+ }
34
+ const opened = await openTarget(def, {
35
+ cwd: opts.host.cwd,
36
+ signal,
37
+ whenHostExits,
38
+ });
29
39
  let bridge;
30
40
  try {
31
- bridge = await openBridge(def, opts, opened.reach);
41
+ bridge = await openBridge(def, opts, {
42
+ reach: opened.reach,
43
+ });
32
44
  const transport = await opened.open(bridge?.env ?? {});
33
45
  return await openAcpConnection({
34
46
  agentId: def.agentId,
@@ -36,6 +48,7 @@ export function defineAcpAgent(def) {
36
48
  host: opts.host,
37
49
  signal,
38
50
  tools: bridge,
51
+ reattach: reattachHandle(transport.reattach, bridge),
39
52
  });
40
53
  }
41
54
  catch (e) {
@@ -69,7 +82,7 @@ function attachedRefusal(wiring) {
69
82
  };
70
83
  }
71
84
  /** A command starts on its machine; a transport attaches as it is. */
72
- async function openTarget(def, cwd, signal) {
85
+ async function openTarget(def, { cwd, signal, whenHostExits, }) {
73
86
  const command = def.command;
74
87
  if (!command) {
75
88
  const transport = def.transport;
@@ -84,6 +97,7 @@ async function openTarget(def, cwd, signal) {
84
97
  ...env,
85
98
  },
86
99
  signal,
100
+ whenHostExits,
87
101
  }),
88
102
  // Unreached: a step never gives an attached agent tools (`refusesTools`).
89
103
  reach: async () => {
@@ -94,6 +108,7 @@ async function openTarget(def, cwd, signal) {
94
108
  }
95
109
  const machine = await (def.machine ?? lazyLocalMachine(def.agentId))({
96
110
  signal,
111
+ whenHostExits,
97
112
  });
98
113
  return {
99
114
  open: (env) => machine.launch({
@@ -134,8 +149,80 @@ function closingWith(transport, opened) {
134
149
  },
135
150
  };
136
151
  }
152
+ /**
153
+ * Reach the agent an earlier host started, through the machine that runs it:
154
+ * the stream from its keeper, and the bridge served again under the path and
155
+ * token the agent was given, at the address it already uses.
156
+ */
157
+ async function reattachTo(def, opts, handle) {
158
+ const signal = opts.signal ?? opts.host.signal;
159
+ const whenHostExits = opts.whenHostExits ?? 'keep';
160
+ if (!def.command) {
161
+ throw new AcpConnectError({
162
+ agentId: def.agentId,
163
+ message: `ACP agent '${def.agentId}' attaches through a transport and cannot be reattached.`,
164
+ });
165
+ }
166
+ const machine = await (def.machine ?? lazyLocalMachine(def.agentId))({
167
+ signal,
168
+ whenHostExits,
169
+ });
170
+ let bridge;
171
+ try {
172
+ if (!machine.attach) {
173
+ throw new AcpConnectError({
174
+ agentId: def.agentId,
175
+ message: `The machine ACP agent '${def.agentId}' runs on cannot reattach to an agent.`,
176
+ });
177
+ }
178
+ const transport = await machine.attach(handle);
179
+ bridge = await openBridge(def, opts, {
180
+ reach: (address) => machine.reach(address),
181
+ reuse: bridgeOf(handle),
182
+ });
183
+ return await openAcpConnection({
184
+ agentId: def.agentId,
185
+ transport: closingWith(transport, {
186
+ open: async () => transport,
187
+ reach: (address) => machine.reach(address),
188
+ close: () => machine.close(),
189
+ }),
190
+ host: opts.host,
191
+ signal,
192
+ tools: bridge,
193
+ reattach: reattachHandle(transport.reattach ?? handle, bridge),
194
+ reattached: true,
195
+ });
196
+ }
197
+ catch (e) {
198
+ await bridge?.close();
199
+ await machine.close().catch(() => undefined);
200
+ throw e;
201
+ }
202
+ }
203
+ const BridgeCredentialsSchema = z.object({
204
+ path: z.string().startsWith('/'),
205
+ token: z.string().min(1),
206
+ });
207
+ /** The bridge credentials a reattach handle carries, if any. */
208
+ function bridgeOf(handle) {
209
+ const parsed = BridgeCredentialsSchema.safeParse(handle.bridge);
210
+ return parsed.success ? parsed.data : undefined;
211
+ }
212
+ /** The handle a later host reattaches with: the machine's, plus the bridge it must serve again. */
213
+ function reattachHandle(machine, bridge) {
214
+ if (!machine) {
215
+ return undefined;
216
+ }
217
+ return bridge
218
+ ? {
219
+ ...machine,
220
+ bridge: bridge.credentials,
221
+ }
222
+ : machine;
223
+ }
137
224
  /** Start the tool bridge when the step gave tools, before the agent starts. */
138
- async function openBridge(def, opts, reach) {
225
+ async function openBridge(def, opts, { reach, reuse, }) {
139
226
  const host = opts.host.tools;
140
227
  if (!host) {
141
228
  return undefined;
@@ -148,6 +235,7 @@ async function openBridge(def, opts, reach) {
148
235
  mcpServers: opts.mcpServers ?? [],
149
236
  env: def.env,
150
237
  reach,
238
+ reuse,
151
239
  });
152
240
  }
153
241
  //#endregion
package/dist/items.d.ts CHANGED
@@ -17,7 +17,7 @@ export declare function assistantMessageItem(text: string, id?: string): Message
17
17
  export declare function functionCallItem(opts: {
18
18
  title: string;
19
19
  toolCallId: string;
20
- rawInput?: Record<string, unknown>;
20
+ rawInput?: unknown;
21
21
  kind?: string;
22
22
  }): FunctionCallItem;
23
23
  /** @public Build the tool-result Item paired with a completed ACP tool call. */