@noetic-tools/acp 1.0.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/client.js ADDED
@@ -0,0 +1,288 @@
1
+ /**
2
+ * Noetic's implementation of the ACP **Client** side.
3
+ *
4
+ * ACP inverts the usual control flow: rather than reaching for the machine
5
+ * itself, the agent asks the client to read files, write files, and run
6
+ * terminals. Serving those requests here means every file and
7
+ * shell operation a sub-agent performs flows through Noetic's own
8
+ * {@link FsAdapter} and {@link ShellAdapter} — the same sandboxing, virtual
9
+ * filesystem, and audit path as first-party steps.
10
+ *
11
+ * Capabilities are advertised from what the host can actually back, narrowed by
12
+ * the step's config. A withdrawn capability is answered with a JSON-RPC
13
+ * method-not-found rather than silently doing the work anyway.
14
+ */
15
+ import { RequestError } from '@zed-industries/agent-client-protocol';
16
+ import { isAbsolutePath, isWithinRoots } from './paths.js';
17
+ import { resolvePermission, selectPermissionOption } from './permissions.js';
18
+ import { buildCommandLine, TerminalRegistry } from './terminals.js';
19
+ //#region Capability advertisement
20
+ /** Build the `ClientCapabilities` sent during `initialize`. */
21
+ export function clientCapabilitiesFor(host) {
22
+ const config = host.capabilities;
23
+ return {
24
+ fs: {
25
+ readTextFile: config?.readTextFile !== false,
26
+ writeTextFile: config?.writeTextFile !== false,
27
+ },
28
+ terminal: config?.terminal !== false,
29
+ };
30
+ }
31
+ //#endregion
32
+ //#region Helpers
33
+ /**
34
+ * Apply ACP's `line` / `limit` window. Line numbers are 1-indexed per the
35
+ * specification; `limit` counts lines, not bytes.
36
+ */
37
+ export function sliceLines(content, line, limit) {
38
+ const start = typeof line === 'number' && line > 1 ? line - 1 : 0;
39
+ // A negative `limit` is out of schema, but passing it through would become a
40
+ // negative slice bound and quietly mean "all but the last N lines" — a
41
+ // plausible-looking answer to a malformed request. Read it as zero lines.
42
+ const count = typeof limit === 'number' ? Math.max(0, limit) : undefined;
43
+ if (start === 0 && count === undefined) {
44
+ return content;
45
+ }
46
+ const lines = content.split('\n');
47
+ const end = count === undefined ? lines.length : start + count;
48
+ return lines.slice(start, end).join('\n');
49
+ }
50
+ /** Directory portion of an absolute POSIX path, or `undefined` at the root. */
51
+ function parentDir(path) {
52
+ const index = path.lastIndexOf('/');
53
+ if (index <= 0) {
54
+ return undefined;
55
+ }
56
+ return path.slice(0, index);
57
+ }
58
+ /**
59
+ * The `Client` handed to the ACP connection. One instance per connection; it
60
+ * owns the terminal registry, so closing the connection kills every command the
61
+ * agent started.
62
+ * @public
63
+ */
64
+ export class NoeticAcpClient {
65
+ host;
66
+ onNotify;
67
+ terminals;
68
+ constructor(opts) {
69
+ this.host = opts.host;
70
+ this.onNotify = opts.onNotify;
71
+ this.terminals = new TerminalRegistry(opts.host.shell, opts.host.cwd);
72
+ }
73
+ /**
74
+ * Read the permission tiers off the host at CALL time, never snapshot them.
75
+ * A connection outlives the step that opened it, and the host is rebound
76
+ * per turn — snapshotting would answer every later step with the first
77
+ * step's policy.
78
+ */
79
+ get permissions() {
80
+ return {
81
+ policy: this.host.permissions,
82
+ steer: this.host.steerPermission,
83
+ handler: this.host.onPermissionRequest,
84
+ };
85
+ }
86
+ /** Release every terminal this connection created. */
87
+ async dispose() {
88
+ await this.terminals.releaseAll();
89
+ }
90
+ //#region Baseline
91
+ async requestPermission(params) {
92
+ const outcome = await resolvePermission(params, this.permissions);
93
+ const selected = selectPermissionOption(outcome, params.options, this.permissions.policy?.persist === true);
94
+ if (!selected) {
95
+ // Answering `cancelled` here would tell a conforming agent the whole turn
96
+ // was cancelled, killing the step over one tool. Fail loudly on our side
97
+ // instead of lying on the wire.
98
+ throw RequestError.invalidParams({
99
+ reason: `no permission option matches the '${outcome.decision}' decision`,
100
+ offered: params.options.map((option) => option.kind),
101
+ });
102
+ }
103
+ return {
104
+ outcome: selected,
105
+ };
106
+ }
107
+ async sessionUpdate(params) {
108
+ this.onNotify(params);
109
+ }
110
+ //#endregion
111
+ //#region File system
112
+ async readTextFile(params) {
113
+ return this.audited({
114
+ method: 'fs/read_text_file',
115
+ path: params.path,
116
+ }, async () => {
117
+ this.assertCapability(this.host.capabilities?.readTextFile !== false, 'fs/read_text_file');
118
+ this.assertPathAllowed(params.path);
119
+ const content = await this.host.fs.readFileText(params.path);
120
+ return {
121
+ content: sliceLines(content, params.line, params.limit),
122
+ };
123
+ });
124
+ }
125
+ async writeTextFile(params) {
126
+ return this.audited({
127
+ method: 'fs/write_text_file',
128
+ path: params.path,
129
+ }, async () => {
130
+ this.assertCapability(this.host.capabilities?.writeTextFile !== false, 'fs/write_text_file');
131
+ this.assertPathAllowed(params.path);
132
+ const dir = parentDir(params.path);
133
+ if (dir) {
134
+ await this.host.fs.mkdir(dir);
135
+ }
136
+ await this.host.fs.writeFile(params.path, params.content);
137
+ return {};
138
+ });
139
+ }
140
+ //#endregion
141
+ //#region Terminals
142
+ async createTerminal(params) {
143
+ return this.audited({
144
+ method: 'terminal/create',
145
+ command: buildCommandLine(params.command, params.args),
146
+ path: params.cwd ?? undefined,
147
+ }, async () => {
148
+ this.assertTerminalCapability('terminal/create');
149
+ // Confines where a command STARTS, not where it can go — a shell can
150
+ // `cd` anywhere the host user can. Withdrawing the terminal capability
151
+ // is the only hard boundary; this just stops the obvious case.
152
+ if (typeof params.cwd === 'string') {
153
+ this.assertPathAllowed(params.cwd);
154
+ }
155
+ return {
156
+ terminalId: this.terminals.create({
157
+ command: params.command,
158
+ args: params.args,
159
+ cwd: params.cwd,
160
+ env: params.env,
161
+ outputByteLimit: params.outputByteLimit,
162
+ }),
163
+ };
164
+ });
165
+ }
166
+ async terminalOutput(params) {
167
+ this.assertTerminalCapability('terminal/output');
168
+ const snapshot = this.terminals.output(params.terminalId);
169
+ if (!snapshot) {
170
+ throw unknownTerminal(params.terminalId);
171
+ }
172
+ return {
173
+ output: snapshot.output,
174
+ truncated: snapshot.truncated,
175
+ exitStatus: snapshot.exitStatus,
176
+ };
177
+ }
178
+ async waitForTerminalExit(params) {
179
+ this.assertTerminalCapability('terminal/wait_for_exit');
180
+ const status = await this.terminals.waitForExit(params.terminalId);
181
+ if (!status) {
182
+ throw unknownTerminal(params.terminalId);
183
+ }
184
+ return {
185
+ exitCode: status.exitCode,
186
+ signal: status.signal,
187
+ };
188
+ }
189
+ async killTerminal(params) {
190
+ this.assertTerminalCapability('terminal/kill');
191
+ const killed = await this.terminals.kill(params.terminalId);
192
+ if (!killed) {
193
+ throw unknownTerminal(params.terminalId);
194
+ }
195
+ return {};
196
+ }
197
+ async releaseTerminal(params) {
198
+ this.assertTerminalCapability('terminal/release');
199
+ await this.terminals.release(params.terminalId);
200
+ return {};
201
+ }
202
+ //#endregion
203
+ //#region internals
204
+ /**
205
+ * Run a client method, reporting it either way. A refusal is the more
206
+ * interesting record of the two — it is the moment an agent reached for
207
+ * something it was not allowed to have.
208
+ *
209
+ * Read the observer at call time, never snapshot it: the host is rebound per
210
+ * turn, so a session shared across steps must report to the CURRENT step.
211
+ */
212
+ async audited(activity, run) {
213
+ const observer = this.host.onClientActivity;
214
+ // The caller has already built the descriptor by the time we get here, so
215
+ // this only skips the two spreads below — not the descriptor itself. It
216
+ // matters for embedders that drive the client directly; the interpreter
217
+ // always installs an observer, so in-harness this branch never fires.
218
+ if (!observer) {
219
+ return await run();
220
+ }
221
+ try {
222
+ const result = await run();
223
+ observer({
224
+ ...activity,
225
+ allowed: true,
226
+ });
227
+ return result;
228
+ }
229
+ catch (e) {
230
+ observer({
231
+ ...activity,
232
+ allowed: false,
233
+ reason: e instanceof Error ? e.message : String(e),
234
+ });
235
+ throw e;
236
+ }
237
+ }
238
+ /**
239
+ * The roots an agent may reach: the session working directory plus whatever
240
+ * the step explicitly added.
241
+ */
242
+ get allowedRoots() {
243
+ return [
244
+ this.host.cwd,
245
+ ...(this.host.capabilities?.additionalDirectories ?? []),
246
+ ];
247
+ }
248
+ /**
249
+ * Reject a path outside the workspace before it reaches the adapter.
250
+ *
251
+ * The specification requires absolute paths, so a relative one is malformed
252
+ * input rather than something to resolve against a guessed base.
253
+ */
254
+ assertPathAllowed(path) {
255
+ if (!isAbsolutePath(path)) {
256
+ throw RequestError.invalidParams({
257
+ path,
258
+ reason: 'the Agent Client Protocol requires absolute paths',
259
+ });
260
+ }
261
+ if (this.host.capabilities?.allowAnyPath === true) {
262
+ return;
263
+ }
264
+ if (!isWithinRoots(path, this.allowedRoots)) {
265
+ throw RequestError.invalidParams({
266
+ path,
267
+ reason: 'path is outside the session working directory',
268
+ allowedRoots: this.allowedRoots,
269
+ });
270
+ }
271
+ }
272
+ assertTerminalCapability(method) {
273
+ this.assertCapability(this.host.capabilities?.terminal !== false, method);
274
+ }
275
+ /** A withdrawn capability must fail loudly, not quietly do the work anyway. */
276
+ assertCapability(enabled, method) {
277
+ if (!enabled) {
278
+ throw RequestError.methodNotFound(method);
279
+ }
280
+ }
281
+ }
282
+ function unknownTerminal(terminalId) {
283
+ return RequestError.invalidParams({
284
+ terminalId,
285
+ reason: 'unknown terminal id',
286
+ });
287
+ }
288
+ //#endregion
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Drives the ACP agent side of a connection.
3
+ *
4
+ * Wraps the protocol library's `ClientSideConnection` in the Noetic
5
+ * {@link AcpAgentConnection} / {@link AcpSession} contract, so `@noetic-tools/core`
6
+ * can execute an ACP step without ever importing the protocol package.
7
+ *
8
+ * Responsibilities beyond plumbing:
9
+ * - negotiate `initialize` and hold the agent's advertised capabilities,
10
+ * - refuse, before anything hits the wire, requests the agent cannot serve
11
+ * (loading a session, switching mode, sending image/audio content),
12
+ * - route `session/update` notifications to the turn accumulator *and* the
13
+ * host, so both the result and the live event stream see every update,
14
+ * - translate an aborted turn into `session/cancel` plus the `cancelled`
15
+ * stop reason the specification requires.
16
+ */
17
+ import type { AcpAgentConnection, AcpClientHost, AcpContentBlock, AcpTransport } from '@noetic-tools/types';
18
+ import type * as acp from '@zed-industries/agent-client-protocol';
19
+ /** @public Options for {@link openAcpConnection}. */
20
+ export interface OpenAcpConnectionOptions {
21
+ agentId: string;
22
+ transport: AcpTransport;
23
+ host: AcpClientHost;
24
+ signal?: AbortSignal;
25
+ }
26
+ /**
27
+ * The spec requires clients to restrict prompt content to what the agent
28
+ * advertised, so an unsupported block is a configuration error raised here
29
+ * rather than an opaque failure on the wire.
30
+ */
31
+ export declare function assertPromptContentSupported(agentId: string, content: ReadonlyArray<AcpContentBlock>, capabilities: acp.PromptCapabilities | undefined): void;
32
+ /**
33
+ * Open a transport, run the `initialize` handshake, and return the negotiated
34
+ * connection.
35
+ * @public
36
+ */
37
+ export declare function openAcpConnection(opts: OpenAcpConnectionOptions): Promise<AcpAgentConnection>;
@@ -0,0 +1,337 @@
1
+ /**
2
+ * Drives the ACP agent side of a connection.
3
+ *
4
+ * Wraps the protocol library's `ClientSideConnection` in the Noetic
5
+ * {@link AcpAgentConnection} / {@link AcpSession} contract, so `@noetic-tools/core`
6
+ * can execute an ACP step without ever importing the protocol package.
7
+ *
8
+ * Responsibilities beyond plumbing:
9
+ * - negotiate `initialize` and hold the agent's advertised capabilities,
10
+ * - refuse, before anything hits the wire, requests the agent cannot serve
11
+ * (loading a session, switching mode, sending image/audio content),
12
+ * - route `session/update` notifications to the turn accumulator *and* the
13
+ * host, so both the result and the live event stream see every update,
14
+ * - translate an aborted turn into `session/cancel` plus the `cancelled`
15
+ * stop reason the specification requires.
16
+ */
17
+ import { AcpCapabilityError, AcpConnectError } from '@noetic-tools/types';
18
+ import { ClientSideConnection, ndJsonStream, PROTOCOL_VERSION, } from '@zed-industries/agent-client-protocol';
19
+ import { clientCapabilitiesFor, NoeticAcpClient } from './client.js';
20
+ import { watchTransport } from './liveness.js';
21
+ import { AcpTurnAccumulator } from './turn.js';
22
+ //#endregion
23
+ //#region Content capability gating
24
+ /**
25
+ * The spec requires clients to restrict prompt content to what the agent
26
+ * advertised, so an unsupported block is a configuration error raised here
27
+ * rather than an opaque failure on the wire.
28
+ */
29
+ export function assertPromptContentSupported(agentId, content, capabilities) {
30
+ for (const block of content) {
31
+ if (block.type === 'image' && capabilities?.image !== true) {
32
+ throw new AcpCapabilityError({
33
+ agentId,
34
+ capability: 'promptCapabilities.image',
35
+ });
36
+ }
37
+ if (block.type === 'audio' && capabilities?.audio !== true) {
38
+ throw new AcpCapabilityError({
39
+ agentId,
40
+ capability: 'promptCapabilities.audio',
41
+ });
42
+ }
43
+ const embedded = block.type === 'resource' || block.type === 'resource_link';
44
+ if (embedded && capabilities?.embeddedContext !== true) {
45
+ throw new AcpCapabilityError({
46
+ agentId,
47
+ capability: 'promptCapabilities.embeddedContext',
48
+ });
49
+ }
50
+ }
51
+ }
52
+ //#endregion
53
+ //#region Session
54
+ class AcpSessionImpl {
55
+ agentId;
56
+ agent;
57
+ sessionId;
58
+ modes;
59
+ models;
60
+ commands;
61
+ death;
62
+ promptCapabilities;
63
+ /** Set for the duration of a turn; notifications fan out to it. */
64
+ activeTurn;
65
+ /**
66
+ * Tail of the turn queue. An ACP session is one conversation, and its
67
+ * notifications carry no turn id — so two turns in flight at once fan into
68
+ * whichever accumulator was installed last, silently truncating one and
69
+ * corrupting the other. Turns are therefore serialised rather than rejected:
70
+ * a model can emit parallel `acpAgentTool` calls sharing a session, and both
71
+ * deserve a correct answer, just not simultaneously.
72
+ */
73
+ queue = Promise.resolve();
74
+ constructor(agentId, agent, sessionId, modes, models, commands,
75
+ /** Rejects if the agent dies, so a request cannot outlive it. */
76
+ death,
77
+ /** What the agent said it accepts, enforced before a turn goes on the wire. */
78
+ promptCapabilities) {
79
+ this.agentId = agentId;
80
+ this.agent = agent;
81
+ this.sessionId = sessionId;
82
+ this.modes = modes;
83
+ this.models = models;
84
+ this.commands = commands;
85
+ this.death = death;
86
+ this.promptCapabilities = promptCapabilities;
87
+ }
88
+ get availableCommands() {
89
+ return this.commands;
90
+ }
91
+ /** Feed a notification to the running turn, if any. */
92
+ receive(notification) {
93
+ const update = notification.update;
94
+ if (update.sessionUpdate === 'available_commands_update') {
95
+ this.commands = [
96
+ ...update.availableCommands,
97
+ ];
98
+ }
99
+ this.activeTurn?.push(notification);
100
+ }
101
+ async prompt(opts) {
102
+ // The specification requires clients to restrict prompt content to what the
103
+ // agent advertised, so an unsupported block is refused here rather than
104
+ // failing opaquely inside the agent. Checked before queueing, so a bad
105
+ // request fails immediately instead of after an unrelated turn.
106
+ assertPromptContentSupported(this.agentId, opts.content, this.promptCapabilities);
107
+ // Wait for any turn already running on this session, then take our place at
108
+ // the tail. A failed predecessor must not poison the queue.
109
+ const ours = this.queue.then(() => this.runTurn(opts), () => this.runTurn(opts));
110
+ this.queue = ours.catch(() => undefined);
111
+ return await ours;
112
+ }
113
+ async runTurn(opts) {
114
+ const accumulator = new AcpTurnAccumulator();
115
+ this.activeTurn = accumulator;
116
+ const onAbort = () => {
117
+ // Fire-and-forget: the specification says the agent still answers the
118
+ // original `session/prompt` with the `cancelled` stop reason.
119
+ void this.cancel();
120
+ };
121
+ opts.signal?.addEventListener('abort', onAbort, {
122
+ once: true,
123
+ });
124
+ try {
125
+ const response = await Promise.race([
126
+ this.agent.prompt({
127
+ sessionId: this.sessionId,
128
+ prompt: [
129
+ ...opts.content,
130
+ ],
131
+ }),
132
+ this.death,
133
+ ]);
134
+ return accumulator.result({
135
+ stopReason: response.stopReason,
136
+ });
137
+ }
138
+ finally {
139
+ opts.signal?.removeEventListener('abort', onAbort);
140
+ this.activeTurn = undefined;
141
+ }
142
+ }
143
+ async cancel() {
144
+ await this.agent.cancel({
145
+ sessionId: this.sessionId,
146
+ });
147
+ }
148
+ async setMode(modeId) {
149
+ if (!this.modes || !this.agent.setSessionMode) {
150
+ throw new AcpCapabilityError({
151
+ agentId: this.agentId,
152
+ capability: 'session/set_mode',
153
+ });
154
+ }
155
+ await Promise.race([
156
+ this.agent.setSessionMode({
157
+ sessionId: this.sessionId,
158
+ modeId,
159
+ }),
160
+ this.death,
161
+ ]);
162
+ }
163
+ async setModel(modelId) {
164
+ if (!this.models || !this.agent.setSessionModel) {
165
+ throw new AcpCapabilityError({
166
+ agentId: this.agentId,
167
+ capability: 'session/set_model',
168
+ });
169
+ }
170
+ await Promise.race([
171
+ this.agent.setSessionModel({
172
+ sessionId: this.sessionId,
173
+ modelId,
174
+ }),
175
+ this.death,
176
+ ]);
177
+ }
178
+ }
179
+ //#endregion
180
+ //#region Connection
181
+ class AcpAgentConnectionImpl {
182
+ agentId;
183
+ agent;
184
+ transport;
185
+ client;
186
+ agentCapabilities;
187
+ authMethods;
188
+ protocolVersion;
189
+ watch;
190
+ sessions = new Map();
191
+ constructor(agentId, agent, transport, client, agentCapabilities, authMethods, protocolVersion, watch) {
192
+ this.agentId = agentId;
193
+ this.agent = agent;
194
+ this.transport = transport;
195
+ this.client = client;
196
+ this.agentCapabilities = agentCapabilities;
197
+ this.authMethods = authMethods;
198
+ this.protocolVersion = protocolVersion;
199
+ this.watch = watch;
200
+ }
201
+ /** The sink the client hands every `session/update` notification. */
202
+ get sink() {
203
+ return (notification) => {
204
+ this.sessions.get(notification.sessionId)?.receive(notification);
205
+ };
206
+ }
207
+ async authenticate(methodId) {
208
+ await Promise.race([
209
+ this.agent.authenticate({
210
+ methodId,
211
+ }),
212
+ this.watch.death,
213
+ ]);
214
+ }
215
+ async newSession(opts) {
216
+ const response = await Promise.race([
217
+ this.agent.newSession({
218
+ cwd: opts.cwd,
219
+ mcpServers: this.checkedMcpServers(opts.mcpServers),
220
+ }),
221
+ this.watch.death,
222
+ ]);
223
+ return this.track(new AcpSessionImpl(this.agentId, this.agent, response.sessionId, response.modes ?? undefined, response.models ?? undefined, [], this.watch.death, this.agentCapabilities.promptCapabilities));
224
+ }
225
+ async loadSession(opts) {
226
+ if (this.agentCapabilities.loadSession !== true || !this.agent.loadSession) {
227
+ throw new AcpCapabilityError({
228
+ agentId: this.agentId,
229
+ capability: 'loadSession',
230
+ });
231
+ }
232
+ // Register before the call: `session/load` replays the conversation through
233
+ // `session/update` notifications, which must not be dropped on the floor.
234
+ const session = this.track(new AcpSessionImpl(this.agentId, this.agent, opts.sessionId, undefined, undefined, [], this.watch.death, this.agentCapabilities.promptCapabilities));
235
+ await Promise.race([
236
+ this.agent.loadSession({
237
+ sessionId: opts.sessionId,
238
+ cwd: opts.cwd,
239
+ mcpServers: this.checkedMcpServers(opts.mcpServers),
240
+ }),
241
+ this.watch.death,
242
+ ]);
243
+ return session;
244
+ }
245
+ async close() {
246
+ this.sessions.clear();
247
+ // Reject anything still in flight first. Once the transport is down
248
+ // nothing can answer it, so a pending request would hang forever.
249
+ this.watch.shutdown();
250
+ // Close the transport BEFORE releasing terminals, so the agent cannot ask
251
+ // for another one during teardown.
252
+ await this.transport.close().catch(() => undefined);
253
+ await this.client.dispose();
254
+ }
255
+ //#region internals
256
+ track(session) {
257
+ this.sessions.set(session.sessionId, session);
258
+ return session;
259
+ }
260
+ /** Reject HTTP/SSE MCP transports the agent never advertised support for. */
261
+ checkedMcpServers(servers) {
262
+ if (!servers || servers.length === 0) {
263
+ return [];
264
+ }
265
+ const mcp = this.agentCapabilities.mcpCapabilities;
266
+ for (const server of servers) {
267
+ if (!('type' in server)) {
268
+ continue;
269
+ }
270
+ if (server.type === 'http' && mcp?.http !== true) {
271
+ throw new AcpCapabilityError({
272
+ agentId: this.agentId,
273
+ capability: 'mcpCapabilities.http',
274
+ });
275
+ }
276
+ if (server.type === 'sse' && mcp?.sse !== true) {
277
+ throw new AcpCapabilityError({
278
+ agentId: this.agentId,
279
+ capability: 'mcpCapabilities.sse',
280
+ });
281
+ }
282
+ }
283
+ return [
284
+ ...servers,
285
+ ];
286
+ }
287
+ }
288
+ //#endregion
289
+ //#region Public API
290
+ /**
291
+ * Open a transport, run the `initialize` handshake, and return the negotiated
292
+ * connection.
293
+ * @public
294
+ */
295
+ export async function openAcpConnection(opts) {
296
+ // The sink is late-bound: the client needs it at construction, but it can
297
+ // only dispatch once the connection exists to hold the session map. The host
298
+ // is passed through BY REFERENCE — copying it here would freeze the per-turn
299
+ // policy and event sink to whichever step opened the connection, silently
300
+ // ignoring the configuration of every step that later reuses the session.
301
+ let sink;
302
+ const host = opts.host;
303
+ const client = new NoeticAcpClient({
304
+ host,
305
+ onNotify: (notification) => {
306
+ sink?.(notification);
307
+ host.onSessionUpdate(notification);
308
+ },
309
+ });
310
+ // The protocol library never rejects pending responses when the stream ends,
311
+ // so without this a dead agent leaves every request hanging forever.
312
+ const watch = watchTransport(opts.agentId, opts.transport, opts.signal);
313
+ const agent = new ClientSideConnection(() => client, ndJsonStream(opts.transport.writable, watch.readable));
314
+ let initialized;
315
+ try {
316
+ initialized = await Promise.race([
317
+ agent.initialize({
318
+ protocolVersion: PROTOCOL_VERSION,
319
+ clientCapabilities: clientCapabilitiesFor(host),
320
+ }),
321
+ watch.death,
322
+ ]);
323
+ }
324
+ catch (error) {
325
+ watch.shutdown('failed the initialize handshake');
326
+ await opts.transport.close().catch(() => undefined);
327
+ throw new AcpConnectError({
328
+ agentId: opts.agentId,
329
+ message: `ACP agent '${opts.agentId}' failed the initialize handshake.`,
330
+ cause: error,
331
+ });
332
+ }
333
+ const connection = new AcpAgentConnectionImpl(opts.agentId, agent, opts.transport, client, initialized.agentCapabilities ?? {}, initialized.authMethods ?? [], initialized.protocolVersion, watch);
334
+ sink = connection.sink;
335
+ return connection;
336
+ }
337
+ //#endregion
@@ -0,0 +1,23 @@
1
+ /**
2
+ * `defineAcpAgent` — the one-call constructor behind every agent preset.
3
+ *
4
+ * Under ACP an "adapter" is just a way to reach a JSON-RPC peer, so an agent is
5
+ * fully described by its id plus a transport factory. Everything else — the
6
+ * handshake, sessions, prompts, permissions, terminals — is protocol-generic
7
+ * and lives in {@link openAcpConnection}.
8
+ */
9
+ import type { AcpAgent, AcpTransportFactory } from '@noetic-tools/types';
10
+ /** @public Options for {@link defineAcpAgent}. */
11
+ export interface DefineAcpAgentOptions {
12
+ /**
13
+ * Stable identifier used for registry lookup, observability, and error
14
+ * messages. Free-form — the set of agents is open.
15
+ */
16
+ agentId: string;
17
+ /** Opens the duplex byte stream to the agent. */
18
+ transport: AcpTransportFactory;
19
+ /** Environment layered onto every connection this agent opens. */
20
+ env?: Record<string, string | undefined>;
21
+ }
22
+ /** @public Build an {@link AcpAgent} from a transport factory. */
23
+ export declare function defineAcpAgent(def: DefineAcpAgentOptions): AcpAgent;