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

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.d.ts CHANGED
@@ -86,6 +86,6 @@ export { NoeticAcpClient } from './client.js';
86
86
  * pieces underneath it.
87
87
  * @public
88
88
  */
89
- export type { OpenAcpConnectionOptions } from './connection.js';
89
+ export type { InstructionsMeta, OpenAcpConnectionOptions } from './connection.js';
90
90
  /** @public */
91
91
  export { openAcpConnection } from './connection.js';
@@ -51,6 +51,8 @@ export declare class KeeperLink {
51
51
  private readonly encoder;
52
52
  private closed;
53
53
  private stopping?;
54
+ /** Where the agent's stderr goes. Default: this process's stderr. */
55
+ onStderr: (chunk: string) => void;
54
56
  constructor(socket: net.Socket, handle: KeeperHandle, agentId: string);
55
57
  /** Say hello; resolves with whether the keeper runs an agent. */
56
58
  hello(whenHostExits: AcpWhenHostExits): Promise<'running' | 'none'>;
@@ -64,6 +66,11 @@ export declare class KeeperLink {
64
66
  stop(): Promise<void>;
65
67
  /** Let go of the keeper without stopping it, as a host that goes away does. */
66
68
  detach(): void;
69
+ /**
70
+ * Let go of an agent this host did not adopt: the keeper keeps it running
71
+ * whatever exit policy this host's hello set, then the connection drops.
72
+ */
73
+ release(): Promise<void>;
67
74
  private shutdown;
68
75
  private receive;
69
76
  private ask;
@@ -76,6 +83,8 @@ export declare class KeeperLink {
76
83
  * keeper script to run.
77
84
  */
78
85
  export declare function startKeeper(agentId: string, opts: KeeperStartOptions): Promise<KeeperLink | undefined>;
86
+ /** Whether a failed connect means no keeper is there: its socket is missing or refuses. */
87
+ export declare function keeperIsGone(cause: unknown): boolean;
79
88
  /**
80
89
  * Connect to the keeper `handle` names. Rejects with AcpConnectError when it
81
90
  * is gone or no longer runs its agent.
@@ -150,6 +150,10 @@ export class KeeperLink {
150
150
  encoder = new TextEncoder();
151
151
  closed = false;
152
152
  stopping;
153
+ /** Where the agent's stderr goes. Default: this process's stderr. */
154
+ onStderr = (chunk) => {
155
+ process.stderr.write(chunk);
156
+ };
153
157
  constructor(socket, handle, agentId) {
154
158
  this.socket = socket;
155
159
  this.handle = handle;
@@ -246,6 +250,7 @@ export class KeeperLink {
246
250
  writable,
247
251
  reattach: this.handle,
248
252
  close: () => this.stop(),
253
+ detach: () => this.release(),
249
254
  };
250
255
  }
251
256
  /** Stop the agent's tree and the keeper. Shared by every caller. */
@@ -257,6 +262,21 @@ export class KeeperLink {
257
262
  detach() {
258
263
  this.socket.destroy();
259
264
  }
265
+ /**
266
+ * Let go of an agent this host did not adopt: the keeper keeps it running
267
+ * whatever exit policy this host's hello set, then the connection drops.
268
+ */
269
+ async release() {
270
+ if (this.closed) {
271
+ return;
272
+ }
273
+ await new Promise((resolve) => {
274
+ this.socket.write(`${JSON.stringify({
275
+ keeper: 'release',
276
+ })}\n`, () => resolve());
277
+ });
278
+ this.socket.destroy();
279
+ }
260
280
  async shutdown() {
261
281
  if (this.closed) {
262
282
  return;
@@ -302,7 +322,7 @@ export class KeeperLink {
302
322
  return;
303
323
  }
304
324
  if (message.keeper === 'stderr') {
305
- process.stderr.write(message.data);
325
+ this.onStderr(message.data);
306
326
  return;
307
327
  }
308
328
  const waiter = this.waiters.get(message.id);
@@ -406,6 +426,14 @@ export async function startKeeper(agentId, opts) {
406
426
  await link.hello(opts.whenHostExits);
407
427
  return link;
408
428
  }
429
+ /** Whether a failed connect means no keeper is there: its socket is missing or refuses. */
430
+ export function keeperIsGone(cause) {
431
+ if (typeof cause !== 'object' || cause === null) {
432
+ return false;
433
+ }
434
+ const code = Reflect.get(cause, 'code');
435
+ return code === 'ENOENT' || code === 'ECONNREFUSED';
436
+ }
409
437
  /**
410
438
  * Connect to the keeper `handle` names. Rejects with AcpConnectError when it
411
439
  * is gone or no longer runs its agent.
@@ -420,6 +448,9 @@ export async function attachKeeper(agentId, handle, whenHostExits) {
420
448
  agentId,
421
449
  message: `ACP agent '${agentId}' is no longer running: its keeper cannot be reached.`,
422
450
  cause,
451
+ // No socket, or nobody listening on it: the keeper is gone. Any other
452
+ // failure (permissions, a full table) says nothing about the agent.
453
+ gone: keeperIsGone(cause),
423
454
  });
424
455
  }
425
456
  const link = new KeeperLink(socket, handle, agentId);
@@ -429,6 +460,7 @@ export async function attachKeeper(agentId, handle, whenHostExits) {
429
460
  throw new AcpConnectError({
430
461
  agentId,
431
462
  message: `ACP agent '${agentId}' is no longer running.`,
463
+ gone: true,
432
464
  });
433
465
  }
434
466
  return link;
@@ -83,6 +83,9 @@ class Keeper {
83
83
  this.keepLog = false;
84
84
  void this.stop();
85
85
  },
86
+ release: () => {
87
+ this.whenHostExits = 'keep';
88
+ },
86
89
  };
87
90
  }
88
91
  log(message) {
@@ -26,6 +26,8 @@ export declare const KeeperHostLineSchema: z.ZodDiscriminatedUnion<[z.ZodObject<
26
26
  cwd: z.ZodOptional<z.ZodString>;
27
27
  }, z.core.$strip>, z.ZodObject<{
28
28
  keeper: z.ZodLiteral<"stop">;
29
+ }, z.core.$strip>, z.ZodObject<{
30
+ keeper: z.ZodLiteral<"release">;
29
31
  }, z.core.$strip>], "keeper">;
30
32
  /** @public Keeper → host. */
31
33
  export declare const KeeperLineSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
@@ -39,6 +39,13 @@ export const KeeperHostLineSchema = z.discriminatedUnion('keeper', [
39
39
  z.object({
40
40
  keeper: z.literal('stop'),
41
41
  }),
42
+ /**
43
+ * This host lets go without adopting the agent: whatever exit policy its
44
+ * hello set, the agent keeps running for a later host.
45
+ */
46
+ z.object({
47
+ keeper: z.literal('release'),
48
+ }),
42
49
  ]);
43
50
  /** @public Keeper → host. */
44
51
  export const KeeperLineSchema = z.discriminatedUnion('keeper', [
@@ -39,6 +39,8 @@ export interface PumpTurnParams {
39
39
  present(toolName: string, callId: string, args: unknown): ServeToolCallPresentation;
40
40
  /** Whether `session/cancel` was received for this session. */
41
41
  cancelRequested(): boolean;
42
+ /** Sees every event of the turn as it is pumped. */
43
+ observe?: (event: StreamEvent) => void;
42
44
  }
43
45
  /**
44
46
  * Consume the harness event stream for one prompt turn, translating to
@@ -142,6 +142,7 @@ export async function pumpTurnEvents(params) {
142
142
  }
143
143
  continue;
144
144
  }
145
+ params.observe?.(event);
145
146
  if (event.source === 'sdk') {
146
147
  await handleSdkEvent(state, event);
147
148
  continue;
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Questions a served run holds for a person (spec 31, spec 27 § Questions the
3
+ * agent asks): the editor driving the run is the person's side of the wire, so
4
+ * each held question is put to it as `elicitation/create` when it can show
5
+ * forms, and declined at once when it cannot — a served turn never waits on
6
+ * nobody.
7
+ */
8
+ import type * as acp from '@agentclientprotocol/sdk';
9
+ import type { AgentSideConnection } from '@agentclientprotocol/sdk';
10
+ import type { StreamEvent } from '@noetic-tools/types';
11
+ import type { AcpServeHarness } from './serve-types.js';
12
+ /** What forwarding a served session's questions needs. */
13
+ export interface ServedQuestionsOptions {
14
+ conn: AgentSideConnection;
15
+ harness: AcpServeHarness;
16
+ sessionId: string;
17
+ /** What the editor advertised in `initialize`. */
18
+ capabilities: acp.ClientCapabilities | undefined;
19
+ }
20
+ /**
21
+ * Answer each question a served turn holds, as its events are pumped: through
22
+ * the editor when it advertised form elicitation, else by declining it. A
23
+ * question the editor's answer no longer fits stays held, as any refused
24
+ * answer does.
25
+ */
26
+ export declare function servedQuestionAnswerer(opts: ServedQuestionsOptions): (event: StreamEvent) => void;
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Questions a served run holds for a person (spec 31, spec 27 § Questions the
3
+ * agent asks): the editor driving the run is the person's side of the wire, so
4
+ * each held question is put to it as `elicitation/create` when it can show
5
+ * forms, and declined at once when it cannot — a served turn never waits on
6
+ * nobody.
7
+ */
8
+ import { DECISION_ITEM_TYPE, readHeldCallEvent } from '@noetic-tools/types';
9
+ //#endregion
10
+ //#region Helpers
11
+ function isRecord(value) {
12
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
13
+ }
14
+ function decline(call) {
15
+ return {
16
+ type: DECISION_ITEM_TYPE,
17
+ callId: call.callId,
18
+ argsHash: call.argsHash,
19
+ action: 'deny',
20
+ };
21
+ }
22
+ /** The editor's answer as a decision, or undefined when it cancelled. */
23
+ function decisionOf(call, answer) {
24
+ if (answer.action === 'accept') {
25
+ return {
26
+ type: DECISION_ITEM_TYPE,
27
+ callId: call.callId,
28
+ argsHash: call.argsHash,
29
+ output: answer.content ?? {},
30
+ };
31
+ }
32
+ if (answer.action === 'decline') {
33
+ return decline(call);
34
+ }
35
+ return undefined;
36
+ }
37
+ /** Put one held question to the editor, or decline it when the editor cannot show it. */
38
+ async function answerQuestion(opts, call) {
39
+ const question = call.question;
40
+ const schema = question?.schema;
41
+ const canAsk = opts.capabilities?.elicitation?.form !== undefined &&
42
+ opts.capabilities?.elicitation?.form !== null;
43
+ if (!question || !isRecord(schema) || !canAsk) {
44
+ await settle(opts, decline(call));
45
+ return;
46
+ }
47
+ // An editor that fails the request (method not found, a dropped wire) has
48
+ // not answered: decline, so the turn never waits on it.
49
+ const answer = await opts.conn
50
+ .createElicitation({
51
+ mode: 'form',
52
+ sessionId: opts.sessionId,
53
+ message: question.message,
54
+ requestedSchema: {
55
+ type: 'object',
56
+ properties: isRecord(schema.properties) ? schema.properties : {},
57
+ ...(Array.isArray(schema.required)
58
+ ? {
59
+ required: schema.required.filter((name) => typeof name === 'string'),
60
+ }
61
+ : {}),
62
+ },
63
+ })
64
+ .catch(() => undefined);
65
+ if (!answer) {
66
+ await settle(opts, decline(call));
67
+ return;
68
+ }
69
+ const decision = decisionOf(call, answer);
70
+ if (!decision) {
71
+ return;
72
+ }
73
+ // An answer the question refuses (it does not fit the form) declines it.
74
+ await opts.harness
75
+ .execute(decision, {
76
+ threadId: opts.sessionId,
77
+ })
78
+ .catch(() => settle(opts, decline(call)));
79
+ }
80
+ /** Give a decision; one the run no longer takes (the turn moved on) is dropped. */
81
+ async function settle(opts, decision) {
82
+ await opts.harness
83
+ .execute(decision, {
84
+ threadId: opts.sessionId,
85
+ })
86
+ .catch(() => undefined);
87
+ }
88
+ //#endregion
89
+ //#region Public API
90
+ /**
91
+ * Answer each question a served turn holds, as its events are pumped: through
92
+ * the editor when it advertised form elicitation, else by declining it. A
93
+ * question the editor's answer no longer fits stays held, as any refused
94
+ * answer does.
95
+ */
96
+ export function servedQuestionAnswerer(opts) {
97
+ return (event) => {
98
+ const read = readHeldCallEvent(event);
99
+ if (read?.type !== 'held' || read.call.reason !== 'question') {
100
+ return;
101
+ }
102
+ void answerQuestion(opts, read.call).catch(() => undefined);
103
+ };
104
+ }
105
+ //#endregion
package/dist/serve.js CHANGED
@@ -16,6 +16,7 @@ import { contentBlockText } from './items.js';
16
16
  import { isAbsolutePath } from './paths.js';
17
17
  import { pumpTurnEvents } from './serve-events.js';
18
18
  import { createServePermissionLayer, evaluateServePolicy, ServePermissionBroker, } from './serve-permissions.js';
19
+ import { servedQuestionAnswerer } from './serve-questions.js';
19
20
  /**
20
21
  * A kind-based permission rule resolves kinds through `options.tools`; with
21
22
  * no tools declared it silently matches nothing and the policy default
@@ -314,6 +315,13 @@ class ServeAgent {
314
315
  // execute(), and the session broadcaster discards events whenever a
315
316
  // previously-consumed stream has no live consumer.
316
317
  const events = attachEvents(session.harness, session.sessionId);
318
+ // A question the run holds for a person goes to the editor, or is declined.
319
+ const answerQuestions = servedQuestionAnswerer({
320
+ conn: this.conn,
321
+ harness: session.harness,
322
+ sessionId: session.sessionId,
323
+ capabilities: this.clientCapabilities,
324
+ });
317
325
  const messageId = crypto.randomUUID();
318
326
  try {
319
327
  await session.harness.execute(input, {
@@ -336,6 +344,7 @@ class ServeAgent {
336
344
  }),
337
345
  present: this.presenter.present,
338
346
  cancelRequested: () => session.cancelRequested,
347
+ observe: answerQuestions,
339
348
  });
340
349
  if (outcome.kind === 'error') {
341
350
  throw RequestError.internalError({
package/dist/stdio.d.ts CHANGED
@@ -7,7 +7,7 @@
7
7
  * lazy dynamic import, so `claudeCode()` works with no extra wiring while
8
8
  * keeping the dependency off the main graph.
9
9
  */
10
- import type { AcpMachineFactory, AcpTransportFactory } from '@noetic-tools/types';
10
+ import type { AcpMachineFactory, AcpTransportFactory, SpawnCommand, ToolBridgeAddress } from '@noetic-tools/types';
11
11
  export type { StopProcessTreeOptions } from './stdio-process.js';
12
12
  export { stopProcessTree, TERM_GRACE_MS } from './stdio-process.js';
13
13
  /** @public How to launch an ACP agent as a child process. */
@@ -45,6 +45,27 @@ export interface LocalMachineOptions {
45
45
  * closes it, or it exits.
46
46
  */
47
47
  detachedTimeoutMs?: number;
48
+ /**
49
+ * Rewrite the agent's command just before it starts — wrap it in a sandbox
50
+ * (`sandbox-exec`, `bwrap`), swap in a binary the host ships. `command.env`
51
+ * is the complete environment the agent would get; `bridges` are the tool
52
+ * bridge addresses this machine handed out, so a sandbox can let their
53
+ * ports through. The returned command runs with exactly its own `args`,
54
+ * `env` (the given one when it names none) and `cwd`, as the leader of its
55
+ * own process group, with or without a keeper.
56
+ */
57
+ wrap?: (command: LocalAgentCommand, info: LocalWrapInfo) => SpawnCommand | Promise<SpawnCommand>;
58
+ /** The agent's stderr. Default: this process's stderr. */
59
+ onStderr?: (chunk: string) => void;
60
+ }
61
+ /** @public The command {@link LocalMachineOptions.wrap} receives: `env` is complete. */
62
+ export interface LocalAgentCommand extends SpawnCommand {
63
+ readonly env: Readonly<Record<string, string>>;
64
+ }
65
+ /** @public What {@link LocalMachineOptions.wrap} is told besides the command. */
66
+ export interface LocalWrapInfo {
67
+ /** Every tool bridge address `reach` handed out on this machine, in order. */
68
+ readonly bridges: ReadonlyArray<ToolBridgeAddress>;
48
69
  }
49
70
  /**
50
71
  * This machine: the agent runs through a keeper (see
package/dist/stdio.js CHANGED
@@ -38,6 +38,16 @@ export function stdioAcpTransport(spec) {
38
38
  whenHostExits: opts.whenHostExits,
39
39
  });
40
40
  }
41
+ /** The variables that are set, so a wrapper sees plain strings. */
42
+ function definedEnv(env) {
43
+ const out = {};
44
+ for (const [name, value] of Object.entries(env)) {
45
+ if (value !== undefined) {
46
+ out[name] = value;
47
+ }
48
+ }
49
+ return out;
50
+ }
41
51
  /**
42
52
  * This machine: the agent runs through a keeper (see
43
53
  * {@link LocalMachineOptions.keeper}), which also serves the tool bridge to it
@@ -49,16 +59,50 @@ export function stdioAcpTransport(spec) {
49
59
  export function localMachine(agentId = 'local', options = {}) {
50
60
  return async ({ signal, whenHostExits = 'keep' }) => {
51
61
  const started = new Set();
62
+ const bridges = [];
52
63
  const useKeeper = options.keeper !== false;
53
64
  let keeper;
54
65
  const keeperOptions = {
55
66
  whenHostExits,
56
67
  detachedTimeoutMs: options.detachedTimeoutMs ?? 0,
57
68
  };
69
+ const withStderr = (link) => {
70
+ if (link && options.onStderr) {
71
+ link.onStderr = options.onStderr;
72
+ }
73
+ return link;
74
+ };
58
75
  const openKeeper = () => {
59
- keeper ??= useKeeper ? startKeeper(agentId, keeperOptions) : Promise.resolve(undefined);
76
+ keeper ??= useKeeper
77
+ ? startKeeper(agentId, keeperOptions).then(withStderr)
78
+ : Promise.resolve(undefined);
60
79
  return keeper;
61
80
  };
81
+ /** The command as it will run: the host's wrapper applied, env complete. */
82
+ const prepare = async (command) => {
83
+ const env = definedEnv({
84
+ ...process.env,
85
+ ...command.env,
86
+ });
87
+ if (!options.wrap) {
88
+ return {
89
+ ...command,
90
+ env,
91
+ };
92
+ }
93
+ const wrapped = await options.wrap({
94
+ ...command,
95
+ env,
96
+ }, {
97
+ bridges: [
98
+ ...bridges,
99
+ ],
100
+ });
101
+ return {
102
+ ...wrapped,
103
+ env: wrapped.env ?? env,
104
+ };
105
+ };
62
106
  signal?.addEventListener('abort', () => {
63
107
  void keeper?.then((link) => link?.stop());
64
108
  }, {
@@ -71,6 +115,7 @@ export function localMachine(agentId = 'local', options = {}) {
71
115
  }, {
72
116
  signal,
73
117
  whenHostExits,
118
+ onStderr: options.onStderr,
74
119
  });
75
120
  started.add(transport);
76
121
  return transport;
@@ -79,27 +124,24 @@ export function localMachine(agentId = 'local', options = {}) {
79
124
  reach: async (bridge) => {
80
125
  const link = await openKeeper();
81
126
  if (!link) {
127
+ bridges.push(bridge);
82
128
  return bridge;
83
129
  }
84
130
  const url = await link.reach(new URL(bridge.url).pathname, bridge.url);
85
- return {
131
+ const reached = {
86
132
  ...bridge,
87
133
  url,
88
134
  };
135
+ bridges.push(reached);
136
+ return reached;
89
137
  },
90
138
  launch: async (command) => {
91
- const env = {
92
- ...process.env,
93
- ...command.env,
94
- };
139
+ const prepared = await prepare(command);
95
140
  const link = await openKeeper();
96
141
  if (!link) {
97
- return await start(command, env);
142
+ return await start(prepared, prepared.env ?? {});
98
143
  }
99
- const transport = await link.launch({
100
- ...command,
101
- env,
102
- });
144
+ const transport = await link.launch(prepared);
103
145
  started.add(transport);
104
146
  return transport;
105
147
  },
@@ -112,7 +154,7 @@ export function localMachine(agentId = 'local', options = {}) {
112
154
  });
113
155
  }
114
156
  const link = attachKeeper(agentId, named, whenHostExits);
115
- keeper = link;
157
+ keeper = link.then(withStderr);
116
158
  const transport = (await link).transport();
117
159
  started.add(transport);
118
160
  return transport;
@@ -139,7 +181,7 @@ export function localMachine(agentId = 'local', options = {}) {
139
181
  * included — and releases the pipes; see `stopProcessTree`. A missing binary
140
182
  * or a signal that is already aborted rejects here, not at `close()`.
141
183
  */
142
- async function spawnStdio(agentId, command, { signal, whenHostExits = 'keep', }) {
184
+ async function spawnStdio(agentId, command, { signal, whenHostExits = 'keep', onStderr, }) {
143
185
  const fail = (message, cause) => new AcpConnectError({
144
186
  agentId,
145
187
  message: `ACP agent '${agentId}' (${command.command}) ${message}.`,
@@ -156,7 +198,7 @@ async function spawnStdio(agentId, command, { signal, whenHostExits = 'keep', })
156
198
  stdio: [
157
199
  'pipe',
158
200
  'pipe',
159
- 'inherit',
201
+ onStderr ? 'pipe' : 'inherit',
160
202
  ],
161
203
  // Its own process group, so shutdown can signal the whole tree without
162
204
  // ever signalling the host's group. Windows stops the tree by pid.
@@ -197,6 +239,10 @@ async function spawnStdio(agentId, command, { signal, whenHostExits = 'keep', })
197
239
  // streams report that to their reader, so the Node-side error is handled.
198
240
  child.stdin?.on('error', () => undefined);
199
241
  child.stdout?.on('error', () => undefined);
242
+ if (onStderr) {
243
+ child.stderr?.on('error', () => undefined);
244
+ child.stderr?.on('data', (chunk) => onStderr(chunk.toString('utf8')));
245
+ }
200
246
  if (signal?.aborted) {
201
247
  await close().catch(() => undefined);
202
248
  throw fail('was aborted while starting', signal.reason);
@@ -15,8 +15,24 @@ import type { AcpSessionNotification } from '@noetic-tools/types';
15
15
  * does not know; otherwise undefined.
16
16
  */
17
17
  export declare function newerSessionUpdate(line: string): AcpSessionNotification | undefined;
18
+ /**
19
+ * An agent's `elicitation/create` line with its JSON-RPC id copied into the
20
+ * params' `_meta`, or undefined for any other line. The SDK hands the client a
21
+ * request's params only; the id is what identifies the request across hosts,
22
+ * since a keeper asks a reattached host again with the agent's own id. Riding
23
+ * in the request itself, it cannot drift onto another request.
24
+ */
25
+ export declare function tagElicitationRequest(line: string): string | undefined;
26
+ /** A request's params as the agent sent them, and the JSON-RPC id the stream tagged them with. */
27
+ export declare function untagElicitation<T extends {
28
+ _meta?: Record<string, unknown> | null;
29
+ }>(params: T): {
30
+ request: T;
31
+ requestId?: string | number;
32
+ };
18
33
  /**
19
34
  * Pass the agent's stream through, handing `deliver` each `session/update`
20
- * the SDK would reject for its variant instead of passing it on.
35
+ * the SDK would reject for its variant instead of passing it on, and tagging
36
+ * each `elicitation/create` with its JSON-RPC id.
21
37
  */
22
38
  export declare function divertNewerUpdates(readable: ReadableStream<Uint8Array>, deliver: (notification: AcpSessionNotification) => void): ReadableStream<Uint8Array>;
@@ -74,16 +74,85 @@ export function newerSessionUpdate(line) {
74
74
  return frameworkCast(params);
75
75
  }
76
76
  //#endregion
77
+ /** Where an `elicitation/create`'s JSON-RPC id rides in its params, for the client. */
78
+ const REQUEST_ID_META = 'noetic.tools/requestId';
79
+ /**
80
+ * An agent's `elicitation/create` line with its JSON-RPC id copied into the
81
+ * params' `_meta`, or undefined for any other line. The SDK hands the client a
82
+ * request's params only; the id is what identifies the request across hosts,
83
+ * since a keeper asks a reattached host again with the agent's own id. Riding
84
+ * in the request itself, it cannot drift onto another request.
85
+ */
86
+ export function tagElicitationRequest(line) {
87
+ if (!line.includes('"elicitation/create"')) {
88
+ return undefined;
89
+ }
90
+ let message;
91
+ try {
92
+ message = JSON.parse(line);
93
+ }
94
+ catch {
95
+ return undefined;
96
+ }
97
+ if (!isRecord(message) || message.method !== 'elicitation/create' || !isRecord(message.params)) {
98
+ return undefined;
99
+ }
100
+ const id = message.id;
101
+ if (typeof id !== 'string' && typeof id !== 'number') {
102
+ return undefined;
103
+ }
104
+ const meta = isRecord(message.params._meta) ? message.params._meta : {};
105
+ return JSON.stringify({
106
+ ...message,
107
+ params: {
108
+ ...message.params,
109
+ _meta: {
110
+ ...meta,
111
+ [REQUEST_ID_META]: id,
112
+ },
113
+ },
114
+ });
115
+ }
116
+ /** A request's params as the agent sent them, and the JSON-RPC id the stream tagged them with. */
117
+ export function untagElicitation(params) {
118
+ const meta = params._meta;
119
+ if (!meta || !Object.hasOwn(meta, REQUEST_ID_META)) {
120
+ return {
121
+ request: params,
122
+ };
123
+ }
124
+ const { [REQUEST_ID_META]: tagged, ...rest } = meta;
125
+ const requestId = typeof tagged === 'string' || typeof tagged === 'number' ? tagged : undefined;
126
+ const request = {
127
+ ...params,
128
+ _meta: Object.keys(rest).length > 0 ? rest : undefined,
129
+ };
130
+ return {
131
+ request,
132
+ ...(requestId === undefined
133
+ ? {}
134
+ : {
135
+ requestId,
136
+ }),
137
+ };
138
+ }
139
+ //#endregion
77
140
  //#region Public API
78
141
  /**
79
142
  * Pass the agent's stream through, handing `deliver` each `session/update`
80
- * the SDK would reject for its variant instead of passing it on.
143
+ * the SDK would reject for its variant instead of passing it on, and tagging
144
+ * each `elicitation/create` with its JSON-RPC id.
81
145
  */
82
146
  export function divertNewerUpdates(readable, deliver) {
83
147
  const decoder = new TextDecoder();
84
148
  const encoder = new TextEncoder();
85
149
  let carry = '';
86
150
  const pass = (line, controller) => {
151
+ const tagged = tagElicitationRequest(line);
152
+ if (tagged !== undefined) {
153
+ controller.enqueue(encoder.encode(`${tagged}\n`));
154
+ return;
155
+ }
87
156
  const newer = newerSessionUpdate(line);
88
157
  if (newer) {
89
158
  deliver(newer);
@@ -106,6 +175,11 @@ export function divertNewerUpdates(readable, deliver) {
106
175
  flush(controller) {
107
176
  const tail = carry + decoder.decode();
108
177
  if (tail.length > 0) {
178
+ const tagged = tagElicitationRequest(tail);
179
+ if (tagged !== undefined) {
180
+ controller.enqueue(encoder.encode(tagged));
181
+ return;
182
+ }
109
183
  const newer = newerSessionUpdate(tail);
110
184
  if (newer) {
111
185
  deliver(newer);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noetic-tools/acp",
3
- "version": "2.0.0-next.2",
3
+ "version": "2.0.0-next.3",
4
4
  "type": "module",
5
5
  "description": "Both directions of the Agent Client Protocol for Noetic. Drives any ACP-speaking coding agent (Claude Code, Codex, Gemini CLI, …) as a step, and serves a Noetic harness as an ACP agent for editors like Zed (toAcpAgent / serveAcp).",
6
6
  "license": "Apache-2.0",
@@ -64,7 +64,7 @@
64
64
  "dependencies": {
65
65
  "@modelcontextprotocol/node": "2.1.2",
66
66
  "@modelcontextprotocol/server": "2.4.0",
67
- "@noetic-tools/types": "^3.19.0-next.4",
67
+ "@noetic-tools/types": "^3.19.0-next.6",
68
68
  "@agentclientprotocol/sdk": "1.9.0",
69
69
  "ws": "8.22.1",
70
70
  "zod": "^4.0.0"