@noetic-tools/acp 2.0.0-next.1 → 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.
Files changed (54) hide show
  1. package/dist/agents.d.ts +5 -0
  2. package/dist/agents.js +13 -1
  3. package/dist/bin.js +19 -2
  4. package/dist/client-adapters.d.ts +2 -2
  5. package/dist/client.d.ts +9 -2
  6. package/dist/client.js +40 -1
  7. package/dist/connection.d.ts +25 -2
  8. package/dist/connection.js +455 -36
  9. package/dist/define.d.ts +13 -0
  10. package/dist/define.js +122 -4
  11. package/dist/index.d.ts +1 -1
  12. package/dist/items.d.ts +1 -1
  13. package/dist/keeper/client.d.ts +93 -0
  14. package/dist/keeper/client.js +468 -0
  15. package/dist/keeper/main.d.ts +6 -0
  16. package/dist/keeper/main.js +31 -0
  17. package/dist/keeper/process.d.ts +24 -0
  18. package/dist/keeper/process.js +425 -0
  19. package/dist/keeper/protocol.d.ts +74 -0
  20. package/dist/keeper/protocol.js +108 -0
  21. package/dist/keeper/relay.d.ts +88 -0
  22. package/dist/keeper/relay.js +420 -0
  23. package/dist/mcp/node.d.ts +6 -1
  24. package/dist/mcp/node.js +4 -4
  25. package/dist/permission-channel.d.ts +5 -0
  26. package/dist/permission-channel.js +16 -1
  27. package/dist/runner/host.js +74 -16
  28. package/dist/runner/options.d.ts +2 -0
  29. package/dist/runner/options.js +2 -0
  30. package/dist/runner/protocol.d.ts +12 -0
  31. package/dist/runner/protocol.js +24 -0
  32. package/dist/runner/serve.d.ts +5 -0
  33. package/dist/runner/serve.js +93 -3
  34. package/dist/serve-events.d.ts +2 -0
  35. package/dist/serve-events.js +1 -0
  36. package/dist/serve-questions.d.ts +26 -0
  37. package/dist/serve-questions.js +105 -0
  38. package/dist/serve-types.d.ts +1 -1
  39. package/dist/serve.d.ts +2 -2
  40. package/dist/serve.js +10 -1
  41. package/dist/server.js +1 -1
  42. package/dist/stdio-process.d.ts +38 -0
  43. package/dist/stdio-process.js +214 -0
  44. package/dist/stdio.d.ts +50 -7
  45. package/dist/stdio.js +192 -52
  46. package/dist/tool-bridge.d.ts +9 -0
  47. package/dist/tool-bridge.js +5 -1
  48. package/dist/transport-loopback.d.ts +2 -2
  49. package/dist/transport-loopback.js +1 -1
  50. package/dist/turn.d.ts +3 -2
  51. package/dist/turn.js +22 -2
  52. package/dist/update-filter.d.ts +38 -0
  53. package/dist/update-filter.js +193 -0
  54. package/package.json +3 -3
@@ -0,0 +1,468 @@
1
+ /**
2
+ * The host's side of a keeper (`process.ts`): start one for a new agent, or
3
+ * attach to the one an earlier host left running, and carry the agent's ACP
4
+ * stream and the bridge port over its socket.
5
+ */
6
+ import { spawn } from 'node:child_process';
7
+ import { randomBytes, randomUUID } from 'node:crypto';
8
+ import { chmodSync, existsSync, mkdirSync } from 'node:fs';
9
+ import * as net from 'node:net';
10
+ import { tmpdir } from 'node:os';
11
+ import { join } from 'node:path';
12
+ import { fileURLToPath } from 'node:url';
13
+ import { AcpConnectError } from '@noetic-tools/types';
14
+ import { z } from 'zod';
15
+ import { isControlLine, KeeperLineSchema, LineSplitter } from './protocol.js';
16
+ //#endregion
17
+ //#region Handle
18
+ const KeeperHandleSchema = z.object({
19
+ kind: z.literal('noetic-acp-keeper'),
20
+ version: z.literal(1),
21
+ address: z.string(),
22
+ token: z.string(),
23
+ });
24
+ /** The keeper part of a reattach handle, or undefined when it names no keeper. */
25
+ export function keeperHandleOf(handle) {
26
+ const parsed = KeeperHandleSchema.safeParse(handle);
27
+ return parsed.success ? parsed.data : undefined;
28
+ }
29
+ //#endregion
30
+ //#region Constants
31
+ /** How long a keeper may take to start listening. */
32
+ const START_TIMEOUT_MS = 1e4;
33
+ /** How long `stop` waits for the keeper to close its end. */
34
+ const STOP_WAIT_MS = 5e3;
35
+ //#endregion
36
+ //#region Helpers
37
+ /**
38
+ * The keeper's entry script beside this module, or undefined when there is
39
+ * none on disk (a bundled single-file build), in which case agents are
40
+ * started directly and do not outlive their host.
41
+ */
42
+ export function keeperScript() {
43
+ for (const name of [
44
+ './main.js',
45
+ './main.ts',
46
+ ]) {
47
+ const url = new URL(name, import.meta.url);
48
+ if (url.protocol !== 'file:') {
49
+ continue;
50
+ }
51
+ const path = fileURLToPath(url);
52
+ if (existsSync(path)) {
53
+ return path;
54
+ }
55
+ }
56
+ return undefined;
57
+ }
58
+ /** Where this user's keepers listen and log (POSIX). */
59
+ function keeperDirectory() {
60
+ return join(tmpdir(), `noetic-acp-${process.getuid?.() ?? 'user'}`);
61
+ }
62
+ /** The prefix of every keeper's named pipe (Windows). */
63
+ const PIPE_PREFIX = '\\\\.\\pipe\\noetic-acp-';
64
+ /**
65
+ * Whether `handle` names a keeper this user's keepers would listen on — so a
66
+ * runner never connects to an arbitrary socket a host names.
67
+ */
68
+ export function isKeeperAddress(address) {
69
+ if (process.platform === 'win32') {
70
+ return address.startsWith(PIPE_PREFIX);
71
+ }
72
+ return (address.startsWith(`${keeperDirectory()}/`) &&
73
+ !address.includes('..') &&
74
+ address.endsWith('.sock'));
75
+ }
76
+ /** A fresh private address for a keeper, and its log file. */
77
+ function newAddress() {
78
+ const id = randomBytes(6).toString('hex');
79
+ if (process.platform === 'win32') {
80
+ return {
81
+ address: `${PIPE_PREFIX}${id}-${randomUUID()}`,
82
+ log: join(tmpdir(), `noetic-acp-${id}.log`),
83
+ };
84
+ }
85
+ // Only this user may open the directory, so only this user reaches the socket.
86
+ const dir = keeperDirectory();
87
+ mkdirSync(dir, {
88
+ recursive: true,
89
+ mode: 0o700,
90
+ });
91
+ chmodSync(dir, 0o700);
92
+ return {
93
+ address: join(dir, `${id}.sock`),
94
+ log: join(dir, `${id}.log`),
95
+ };
96
+ }
97
+ async function readFirstLine(stream, ms) {
98
+ const splitter = new LineSplitter();
99
+ return await new Promise((resolve, reject) => {
100
+ const timer = setTimeout(() => reject(new Error('The keeper did not start in time.')), ms);
101
+ stream.on('data', (chunk) => {
102
+ const [first] = splitter.push(chunk);
103
+ if (first !== undefined) {
104
+ clearTimeout(timer);
105
+ resolve(first);
106
+ }
107
+ });
108
+ stream.once('end', () => {
109
+ clearTimeout(timer);
110
+ reject(new Error('The keeper exited before it was ready.'));
111
+ });
112
+ });
113
+ }
114
+ function connectSocket(address) {
115
+ return new Promise((resolve, reject) => {
116
+ const socket = net.createConnection(address);
117
+ socket.once('connect', () => {
118
+ socket.off('error', reject);
119
+ resolve(socket);
120
+ });
121
+ socket.once('error', reject);
122
+ });
123
+ }
124
+ function definedEnv(env) {
125
+ const out = {};
126
+ for (const [name, value] of Object.entries(env)) {
127
+ if (value !== undefined) {
128
+ out[name] = value;
129
+ }
130
+ }
131
+ return out;
132
+ }
133
+ //#endregion
134
+ //#region Keeper link
135
+ /**
136
+ * One host's connection to a keeper. Control lines are answered here; every
137
+ * other line is the agent's ACP stream.
138
+ * @public
139
+ */
140
+ export class KeeperLink {
141
+ socket;
142
+ handle;
143
+ agentId;
144
+ next = 0;
145
+ waiters = new Map();
146
+ welcomed;
147
+ acp;
148
+ /** ACP lines that arrived before the stream was taken. */
149
+ early = [];
150
+ encoder = new TextEncoder();
151
+ closed = false;
152
+ stopping;
153
+ /** Where the agent's stderr goes. Default: this process's stderr. */
154
+ onStderr = (chunk) => {
155
+ process.stderr.write(chunk);
156
+ };
157
+ constructor(socket, handle, agentId) {
158
+ this.socket = socket;
159
+ this.handle = handle;
160
+ this.agentId = agentId;
161
+ let welcome = () => undefined;
162
+ let refuse = () => undefined;
163
+ this.welcomed = new Promise((resolve, reject) => {
164
+ welcome = resolve;
165
+ refuse = reject;
166
+ });
167
+ const splitter = new LineSplitter();
168
+ socket.on('data', (chunk) => {
169
+ for (const line of splitter.push(chunk)) {
170
+ this.receive(line, welcome);
171
+ }
172
+ });
173
+ socket.on('error', () => undefined);
174
+ socket.on('close', () => {
175
+ this.closed = true;
176
+ refuse(this.lost('closed the connection before welcoming this host'));
177
+ for (const waiter of this.waiters.values()) {
178
+ waiter.reject(this.lost('closed the connection'));
179
+ }
180
+ this.waiters.clear();
181
+ try {
182
+ this.acp?.close();
183
+ }
184
+ catch {
185
+ // Already closed.
186
+ }
187
+ });
188
+ }
189
+ /** Say hello; resolves with whether the keeper runs an agent. */
190
+ async hello(whenHostExits) {
191
+ this.write({
192
+ keeper: 'hello',
193
+ token: this.handle.token,
194
+ whenHostExits,
195
+ });
196
+ return await this.welcomed;
197
+ }
198
+ /** Serve the bridge at `target` on the keeper's port for `path`. */
199
+ async reach(path, target) {
200
+ const reply = await this.ask({
201
+ keeper: 'reach',
202
+ id: this.id(),
203
+ path,
204
+ target,
205
+ });
206
+ if (reply.keeper !== 'reached') {
207
+ throw this.lost(`answered a reach with '${reply.keeper}'`);
208
+ }
209
+ return reply.url;
210
+ }
211
+ /** Start the agent and return its stream. */
212
+ async launch(command) {
213
+ const reply = await this.ask({
214
+ keeper: 'launch',
215
+ id: this.id(),
216
+ command: command.command,
217
+ args: [
218
+ ...(command.args ?? []),
219
+ ],
220
+ env: definedEnv(command.env ?? {}),
221
+ cwd: command.cwd,
222
+ });
223
+ if (reply.keeper !== 'launched') {
224
+ throw this.lost(`answered a launch with '${reply.keeper}'`);
225
+ }
226
+ return this.transport();
227
+ }
228
+ /** The stream of the agent the keeper already runs. */
229
+ transport() {
230
+ const readable = new ReadableStream({
231
+ start: (controller) => {
232
+ this.acp = controller;
233
+ for (const chunk of this.early.splice(0)) {
234
+ controller.enqueue(chunk);
235
+ }
236
+ if (this.closed) {
237
+ controller.close();
238
+ }
239
+ },
240
+ });
241
+ const writable = new WritableStream({
242
+ write: (chunk) => {
243
+ if (!this.closed) {
244
+ this.socket.write(chunk);
245
+ }
246
+ },
247
+ });
248
+ return {
249
+ readable,
250
+ writable,
251
+ reattach: this.handle,
252
+ close: () => this.stop(),
253
+ detach: () => this.release(),
254
+ };
255
+ }
256
+ /** Stop the agent's tree and the keeper. Shared by every caller. */
257
+ stop() {
258
+ this.stopping ??= this.shutdown();
259
+ return this.stopping;
260
+ }
261
+ /** Let go of the keeper without stopping it, as a host that goes away does. */
262
+ detach() {
263
+ this.socket.destroy();
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
+ }
280
+ async shutdown() {
281
+ if (this.closed) {
282
+ return;
283
+ }
284
+ this.write({
285
+ keeper: 'stop',
286
+ });
287
+ await new Promise((resolve) => {
288
+ const timer = setTimeout(resolve, STOP_WAIT_MS);
289
+ timer.unref?.();
290
+ this.socket.once('close', () => {
291
+ clearTimeout(timer);
292
+ resolve();
293
+ });
294
+ });
295
+ this.socket.destroy();
296
+ }
297
+ receive(line, welcome) {
298
+ if (!isControlLine(line)) {
299
+ const bytes = this.encoder.encode(`${line}\n`);
300
+ if (this.acp) {
301
+ this.acp.enqueue(bytes);
302
+ }
303
+ else {
304
+ this.early.push(bytes);
305
+ }
306
+ return;
307
+ }
308
+ let parsedJson;
309
+ try {
310
+ parsedJson = JSON.parse(line);
311
+ }
312
+ catch {
313
+ return;
314
+ }
315
+ const parsed = KeeperLineSchema.safeParse(parsedJson);
316
+ if (!parsed.success) {
317
+ return;
318
+ }
319
+ const message = parsed.data;
320
+ if (message.keeper === 'welcome') {
321
+ welcome(message.agent);
322
+ return;
323
+ }
324
+ if (message.keeper === 'stderr') {
325
+ this.onStderr(message.data);
326
+ return;
327
+ }
328
+ const waiter = this.waiters.get(message.id);
329
+ if (!waiter) {
330
+ return;
331
+ }
332
+ this.waiters.delete(message.id);
333
+ if (message.keeper === 'error') {
334
+ waiter.reject(this.lost(`refused: ${message.message}`));
335
+ return;
336
+ }
337
+ waiter.resolve(message);
338
+ }
339
+ ask(line) {
340
+ if (this.closed) {
341
+ return Promise.reject(this.lost('closed the connection'));
342
+ }
343
+ return new Promise((resolve, reject) => {
344
+ this.waiters.set(line.id, {
345
+ resolve,
346
+ reject,
347
+ });
348
+ this.write(line);
349
+ });
350
+ }
351
+ write(line) {
352
+ if (!this.closed) {
353
+ this.socket.write(`${JSON.stringify(line)}\n`);
354
+ }
355
+ }
356
+ id() {
357
+ this.next += 1;
358
+ return `k${this.next}`;
359
+ }
360
+ lost(what) {
361
+ return new AcpConnectError({
362
+ agentId: this.agentId,
363
+ message: `The keeper of ACP agent '${this.agentId}' ${what}.`,
364
+ });
365
+ }
366
+ }
367
+ //#endregion
368
+ //#region Public API
369
+ /**
370
+ * Start a keeper and connect to it, or return undefined when there is no
371
+ * keeper script to run.
372
+ */
373
+ export async function startKeeper(agentId, opts) {
374
+ const script = keeperScript();
375
+ if (!script) {
376
+ return undefined;
377
+ }
378
+ const { address, log } = newAddress();
379
+ const handle = {
380
+ kind: 'noetic-acp-keeper',
381
+ version: 1,
382
+ address,
383
+ token: `${randomUUID()}${randomUUID()}`,
384
+ };
385
+ const config = {
386
+ address,
387
+ token: handle.token,
388
+ log,
389
+ detachedTimeoutMs: opts.detachedTimeoutMs,
390
+ };
391
+ // Its own process group and session: the host's Ctrl-C or crash does not
392
+ // reach it, so it can keep the agent for the next host.
393
+ const child = spawn(process.execPath, [
394
+ script,
395
+ ], {
396
+ detached: true,
397
+ stdio: [
398
+ 'pipe',
399
+ 'pipe',
400
+ 'ignore',
401
+ ],
402
+ windowsHide: true,
403
+ });
404
+ try {
405
+ await new Promise((resolve, reject) => {
406
+ child.once('spawn', resolve);
407
+ child.once('error', reject);
408
+ });
409
+ child.stdin?.end(`${JSON.stringify(config)}\n`);
410
+ const ready = child.stdout ? await readFirstLine(child.stdout, START_TIMEOUT_MS) : '';
411
+ if (!ready.includes('"ready"')) {
412
+ throw new Error('The keeper did not say it was ready.');
413
+ }
414
+ }
415
+ catch (cause) {
416
+ child.kill();
417
+ throw new AcpConnectError({
418
+ agentId,
419
+ message: `The keeper for ACP agent '${agentId}' failed to start.`,
420
+ cause,
421
+ });
422
+ }
423
+ child.stdout?.destroy();
424
+ child.unref();
425
+ const link = new KeeperLink(await connectSocket(address), handle, agentId);
426
+ await link.hello(opts.whenHostExits);
427
+ return link;
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
+ }
437
+ /**
438
+ * Connect to the keeper `handle` names. Rejects with AcpConnectError when it
439
+ * is gone or no longer runs its agent.
440
+ */
441
+ export async function attachKeeper(agentId, handle, whenHostExits) {
442
+ let socket;
443
+ try {
444
+ socket = await connectSocket(handle.address);
445
+ }
446
+ catch (cause) {
447
+ throw new AcpConnectError({
448
+ agentId,
449
+ message: `ACP agent '${agentId}' is no longer running: its keeper cannot be reached.`,
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),
454
+ });
455
+ }
456
+ const link = new KeeperLink(socket, handle, agentId);
457
+ const agent = await link.hello(whenHostExits);
458
+ if (agent !== 'running') {
459
+ await link.stop();
460
+ throw new AcpConnectError({
461
+ agentId,
462
+ message: `ACP agent '${agentId}' is no longer running.`,
463
+ gone: true,
464
+ });
465
+ }
466
+ return link;
467
+ }
468
+ //#endregion
@@ -0,0 +1,6 @@
1
+ /**
2
+ * The keeper's entry point: read its config from stdin, listen, say `ready`
3
+ * on stdout, then let go of both — the host that started it may go away
4
+ * while the keeper runs on.
5
+ */
6
+ export {};
@@ -0,0 +1,31 @@
1
+ /**
2
+ * The keeper's entry point: read its config from stdin, listen, say `ready`
3
+ * on stdout, then let go of both — the host that started it may go away
4
+ * while the keeper runs on.
5
+ */
6
+ import { stdin, stdout } from 'node:process';
7
+ import { runKeeper } from './process.js';
8
+ import { KeeperConfigSchema, LineSplitter } from './protocol.js';
9
+ async function readConfig() {
10
+ const splitter = new LineSplitter();
11
+ for await (const chunk of stdin) {
12
+ const [first] = splitter.push(chunk);
13
+ if (first !== undefined) {
14
+ return JSON.parse(first);
15
+ }
16
+ }
17
+ throw new Error('The keeper got no config.');
18
+ }
19
+ async function main() {
20
+ const config = KeeperConfigSchema.parse(await readConfig());
21
+ const { stopped } = await runKeeper(config);
22
+ stdout.write('{"ready":true}\n');
23
+ stdin.destroy();
24
+ stdout.end();
25
+ await stopped;
26
+ process.exit(0);
27
+ }
28
+ main().catch((error) => {
29
+ process.stderr.write(`noetic acp keeper: ${error instanceof Error ? error.message : String(error)}\n`);
30
+ process.exit(1);
31
+ });
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The keeper: a small detached process that runs one local agent for its
3
+ * host and keeps it running when the host goes away.
4
+ *
5
+ * It owns the agent's stdio and relays its ACP stream (`relay.ts`) to whichever
6
+ * host is attached over a private local socket — a Unix socket in a directory
7
+ * only its user can open, or a named pipe on Windows — that every connection
8
+ * must open with the keeper's token. It also owns the loopback port the agent
9
+ * reaches the host's tool bridge on, so the agent's MCP settings stay valid
10
+ * when a later host serves the bridge.
11
+ *
12
+ * When the attached host's connection drops without a `stop`, the keeper
13
+ * either stops the agent (`whenHostExits: 'stop'`) or keeps it working and
14
+ * holds what it sends until a host attaches again, for at most
15
+ * `detachedTimeoutMs`. It exits when the agent does.
16
+ */
17
+ import type { KeeperConfig } from './protocol.js';
18
+ /**
19
+ * Run a keeper until its agent exits or it is stopped. Resolves once it
20
+ * listens on `config.address`.
21
+ */
22
+ export declare function runKeeper(config: KeeperConfig): Promise<{
23
+ stopped: Promise<void>;
24
+ }>;