@noetic-tools/acp 1.3.1-next.2 → 1.4.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.
Files changed (51) hide show
  1. package/dist/agents.d.ts +72 -8
  2. package/dist/agents.js +162 -58
  3. package/dist/bin.d.ts +19 -0
  4. package/dist/bin.js +99 -0
  5. package/dist/client.d.ts +14 -0
  6. package/dist/client.js +49 -0
  7. package/dist/connection.d.ts +3 -0
  8. package/dist/connection.js +26 -4
  9. package/dist/define.d.ts +21 -7
  10. package/dist/define.js +139 -15
  11. package/dist/index.d.ts +13 -3
  12. package/dist/index.js +10 -2
  13. package/dist/mcp/node.d.ts +24 -0
  14. package/dist/mcp/node.js +146 -0
  15. package/dist/mcp/server.d.ts +16 -0
  16. package/dist/mcp/server.js +104 -0
  17. package/dist/pi/extension.d.ts +31 -0
  18. package/dist/pi/extension.js +223 -0
  19. package/dist/pi/launch.d.ts +11 -0
  20. package/dist/pi/launch.js +35 -0
  21. package/dist/remote.d.ts +52 -0
  22. package/dist/remote.js +108 -0
  23. package/dist/runner/grants.d.ts +47 -0
  24. package/dist/runner/grants.js +127 -0
  25. package/dist/runner/host.d.ts +21 -0
  26. package/dist/runner/host.js +318 -0
  27. package/dist/runner/options.d.ts +21 -0
  28. package/dist/runner/options.js +82 -0
  29. package/dist/runner/protocol.d.ts +101 -0
  30. package/dist/runner/protocol.js +218 -0
  31. package/dist/runner/serve.d.ts +60 -0
  32. package/dist/runner/serve.js +285 -0
  33. package/dist/runner/ws-link.d.ts +6 -0
  34. package/dist/runner/ws-link.js +47 -0
  35. package/dist/server-env.d.ts +10 -0
  36. package/dist/server-env.js +47 -0
  37. package/dist/spawn.d.ts +12 -0
  38. package/dist/spawn.js +37 -0
  39. package/dist/stdio.d.ts +9 -1
  40. package/dist/stdio.js +97 -55
  41. package/dist/tool-bridge.d.ts +67 -0
  42. package/dist/tool-bridge.js +62 -0
  43. package/dist/tool-permissions.d.ts +46 -0
  44. package/dist/tool-permissions.js +70 -0
  45. package/dist/tool-wiring.d.ts +46 -0
  46. package/dist/tool-wiring.js +203 -0
  47. package/dist/transport-loopback.d.ts +8 -1
  48. package/dist/transport-loopback.js +22 -1
  49. package/dist/turn.d.ts +11 -5
  50. package/dist/turn.js +39 -16
  51. package/package.json +17 -4
@@ -0,0 +1,318 @@
1
+ /**
2
+ * The host's end of a remote runner: an {@link AcpMachine} whose processes run
3
+ * on the runner's machine and whose tool bridge is reached through it.
4
+ *
5
+ * Runtime-neutral: it needs only `fetch` and a {@link FrameLink}, so the
6
+ * WebSocket and stdio links that open one live in the node entry.
7
+ */
8
+ import { AcpConnectError } from '@noetic-tools/types';
9
+ import { chunksOf, fromBase64, RunnerFrameSchema, toBase64 } from './protocol.js';
10
+ /** Request headers that belong to one hop, which `fetch` sets for itself. */
11
+ const HOP_HEADERS = new Set([
12
+ 'host',
13
+ 'connection',
14
+ 'content-length',
15
+ 'transfer-encoding',
16
+ 'keep-alive',
17
+ ]);
18
+ //#endregion
19
+ //#region Public API
20
+ /**
21
+ * A machine reached through a remote runner over `openLink`.
22
+ * @public
23
+ */
24
+ export function runnerMachine(openLink) {
25
+ return async ({ signal }) => new RunnerPeer(await openLink(signal), signal).machine();
26
+ }
27
+ //#endregion
28
+ //#region Peer
29
+ class RunnerPeer {
30
+ link;
31
+ next = 0;
32
+ waiters = new Map();
33
+ streams = new Map();
34
+ /** Reached bridge paths, to the host origin each forwards to. */
35
+ bridges = new Map();
36
+ requests = new Map();
37
+ lost;
38
+ constructor(link, signal) {
39
+ this.link = link;
40
+ link.onFrame((raw) => this.receive(raw));
41
+ link.onClose((reason) => this.drop(reason ?? new Error('The runner closed the connection.')));
42
+ signal?.addEventListener('abort', () => {
43
+ void link.close();
44
+ }, {
45
+ once: true,
46
+ });
47
+ }
48
+ machine() {
49
+ return {
50
+ reach: (bridge) => this.reach(bridge),
51
+ launch: (command) => this.start(command, 'launch'),
52
+ spawn: (command) => this.start(command, 'spawn'),
53
+ close: () => this.link.close(),
54
+ };
55
+ }
56
+ async reach(bridge) {
57
+ const local = new URL(bridge.url);
58
+ this.bridges.set(local.pathname, local.origin);
59
+ const reply = await this.ask({
60
+ t: 'reach',
61
+ path: local.pathname,
62
+ });
63
+ if (reply.t !== 'reached') {
64
+ throw unexpected(reply);
65
+ }
66
+ return {
67
+ ...bridge,
68
+ url: reply.url,
69
+ };
70
+ }
71
+ async start(command, kind) {
72
+ const id = this.id();
73
+ let exit = () => undefined;
74
+ const exited = new Promise((resolve) => {
75
+ exit = resolve;
76
+ });
77
+ const readable = new ReadableStream({
78
+ start: (controller) => {
79
+ this.streams.set(id, {
80
+ controller,
81
+ exited,
82
+ exit,
83
+ });
84
+ },
85
+ });
86
+ const reply = await this.ask({
87
+ t: 'start',
88
+ kind,
89
+ command: command.command,
90
+ args: [
91
+ ...(command.args ?? []),
92
+ ],
93
+ env: definedEnv(command.env),
94
+ cwd: command.cwd,
95
+ }, id).catch((e) => {
96
+ this.streams.delete(id);
97
+ throw e;
98
+ });
99
+ if (reply.t !== 'started') {
100
+ throw unexpected(reply);
101
+ }
102
+ const writable = new WritableStream({
103
+ write: (chunk) => {
104
+ this.link.send({
105
+ t: 'stdin',
106
+ id,
107
+ data: toBase64(chunk),
108
+ });
109
+ },
110
+ });
111
+ let closed = false;
112
+ return {
113
+ readable,
114
+ writable,
115
+ close: async () => {
116
+ if (closed) {
117
+ return;
118
+ }
119
+ closed = true;
120
+ this.link.send({
121
+ t: 'kill',
122
+ id,
123
+ });
124
+ await Promise.race([
125
+ exited,
126
+ new Promise((resolve) => setTimeout(resolve, 2e3)),
127
+ ]);
128
+ },
129
+ };
130
+ }
131
+ ask(frame, id = this.id()) {
132
+ if (this.lost) {
133
+ return Promise.reject(this.lost);
134
+ }
135
+ return new Promise((resolve, reject) => {
136
+ this.waiters.set(id, {
137
+ resolve,
138
+ reject,
139
+ });
140
+ this.link.send({
141
+ ...frame,
142
+ id,
143
+ });
144
+ });
145
+ }
146
+ id() {
147
+ this.next += 1;
148
+ return `h${this.next}`;
149
+ }
150
+ //#region Incoming
151
+ receive(raw) {
152
+ const parsed = RunnerFrameSchema.safeParse(raw);
153
+ if (!parsed.success) {
154
+ return;
155
+ }
156
+ const frame = parsed.data;
157
+ if (frame.t === 'stdout') {
158
+ this.streams.get(frame.id)?.controller.enqueue(fromBase64(frame.data));
159
+ return;
160
+ }
161
+ if (frame.t === 'exit') {
162
+ this.ended(frame.id);
163
+ return;
164
+ }
165
+ if (frame.t === 'request') {
166
+ void this.forward(frame);
167
+ return;
168
+ }
169
+ if (frame.t === 'abort') {
170
+ this.requests.get(frame.id)?.abort();
171
+ return;
172
+ }
173
+ this.answer(frame);
174
+ }
175
+ answer(frame) {
176
+ const waiter = this.waiters.get(frame.id);
177
+ if (!waiter) {
178
+ return;
179
+ }
180
+ this.waiters.delete(frame.id);
181
+ if (frame.t === 'error') {
182
+ waiter.reject(new AcpConnectError({
183
+ agentId: 'runner',
184
+ message: `The remote runner refused: ${frame.message}`,
185
+ }));
186
+ return;
187
+ }
188
+ waiter.resolve(frame);
189
+ }
190
+ ended(id) {
191
+ const stream = this.streams.get(id);
192
+ if (!stream) {
193
+ return;
194
+ }
195
+ this.streams.delete(id);
196
+ try {
197
+ stream.controller.close();
198
+ }
199
+ catch {
200
+ // Already errored or closed.
201
+ }
202
+ stream.exit();
203
+ }
204
+ /** Answer a request the agent sent to a reached port from the host's bridge. */
205
+ async forward(frame) {
206
+ const target = bridgeTarget(this.bridges, frame.path);
207
+ if (!target) {
208
+ this.respond(frame.id, 404, []);
209
+ return;
210
+ }
211
+ const abort = new AbortController();
212
+ this.requests.set(frame.id, abort);
213
+ try {
214
+ const body = frame.body === '' ? undefined : fromBase64(frame.body);
215
+ const response = await fetch(target, {
216
+ method: frame.method,
217
+ headers: frame.headers.filter(([name]) => !HOP_HEADERS.has(name.toLowerCase())),
218
+ body,
219
+ signal: abort.signal,
220
+ });
221
+ this.link.send({
222
+ t: 'response',
223
+ id: frame.id,
224
+ status: response.status,
225
+ headers: headerPairs(response.headers),
226
+ });
227
+ if (response.body) {
228
+ for await (const chunk of chunksOf(response.body)) {
229
+ this.link.send({
230
+ t: 'body',
231
+ id: frame.id,
232
+ data: toBase64(chunk),
233
+ });
234
+ }
235
+ }
236
+ this.link.send({
237
+ t: 'end',
238
+ id: frame.id,
239
+ });
240
+ }
241
+ catch {
242
+ this.respond(frame.id, 502, []);
243
+ }
244
+ finally {
245
+ this.requests.delete(frame.id);
246
+ }
247
+ }
248
+ respond(id, status, headers) {
249
+ this.link.send({
250
+ t: 'response',
251
+ id,
252
+ status,
253
+ headers,
254
+ });
255
+ this.link.send({
256
+ t: 'end',
257
+ id,
258
+ });
259
+ }
260
+ drop(reason) {
261
+ this.lost = reason;
262
+ for (const waiter of this.waiters.values()) {
263
+ waiter.reject(reason);
264
+ }
265
+ this.waiters.clear();
266
+ for (const id of [
267
+ ...this.streams.keys(),
268
+ ]) {
269
+ this.ended(id);
270
+ }
271
+ for (const request of this.requests.values()) {
272
+ request.abort();
273
+ }
274
+ }
275
+ }
276
+ //#endregion
277
+ //#region Helpers
278
+ /**
279
+ * The bridge URL a request path forwards to, or none. The URL is built from
280
+ * the parsed path, the one that was checked: a raw path such as
281
+ * `0/../mcp/x` parses to a bridge path but, appended to the origin, would
282
+ * name another port.
283
+ */
284
+ export function bridgeTarget(bridges, path) {
285
+ const parsed = new URL(path, 'http://runner');
286
+ const origin = bridges.get(parsed.pathname);
287
+ if (!origin) {
288
+ return undefined;
289
+ }
290
+ const target = new URL(parsed.pathname + parsed.search, origin);
291
+ return target.origin === origin ? target : undefined;
292
+ }
293
+ function headerPairs(headers) {
294
+ const pairs = [];
295
+ headers.forEach((value, name) => {
296
+ pairs.push([
297
+ name,
298
+ value,
299
+ ]);
300
+ });
301
+ return pairs;
302
+ }
303
+ function definedEnv(env) {
304
+ const out = {};
305
+ for (const [name, value] of Object.entries(env ?? {})) {
306
+ if (value !== undefined) {
307
+ out[name] = value;
308
+ }
309
+ }
310
+ return out;
311
+ }
312
+ function unexpected(frame) {
313
+ return new AcpConnectError({
314
+ agentId: 'runner',
315
+ message: `The remote runner answered with an unexpected '${frame.t}' frame.`,
316
+ });
317
+ }
318
+ //#endregion
@@ -0,0 +1,21 @@
1
+ /**
2
+ * What `noetic-acp serve`'s flags grant, and what a runner says about the
3
+ * trust it places in whoever holds its token.
4
+ */
5
+ import type { AcpRunnerOptions } from './serve.js';
6
+ /**
7
+ * The runner options `noetic-acp serve`'s flags stand for: `--agent` grants
8
+ * a preset's command with its environment names, `--spawn` a command line
9
+ * (split on spaces), and `--env` a name every grant may set. Without either
10
+ * grant the runner starts anything.
11
+ *
12
+ * @throws Error for an unknown `--agent` or an empty `--spawn`.
13
+ */
14
+ export declare function runnerOptions(values: {
15
+ agent?: string;
16
+ spawn?: string[];
17
+ env?: string[];
18
+ cwd?: string;
19
+ }): AcpRunnerOptions;
20
+ /** A runner does what whoever holds its token, or its stdio, asks of it. */
21
+ export declare function trustWarning(options: AcpRunnerOptions): string;
@@ -0,0 +1,82 @@
1
+ /**
2
+ * What `noetic-acp serve`'s flags grant, and what a runner says about the
3
+ * trust it places in whoever holds its token.
4
+ */
5
+ import { PRESET_COMMANDS, PRESET_ENV } from '../agents.js';
6
+ import { piLauncherPath } from '../tool-wiring.js';
7
+ /**
8
+ * The runner options `noetic-acp serve`'s flags stand for: `--agent` grants
9
+ * a preset's command with its environment names, `--spawn` a command line
10
+ * (split on spaces), and `--env` a name every grant may set. Without either
11
+ * grant the runner starts anything.
12
+ *
13
+ * @throws Error for an unknown `--agent` or an empty `--spawn`.
14
+ */
15
+ export function runnerOptions(values) {
16
+ const grants = [
17
+ ...(values.agent === undefined
18
+ ? []
19
+ : [
20
+ presetGrant(values.agent),
21
+ ]),
22
+ ...(values.spawn ?? []).map(commandGrant),
23
+ ];
24
+ if (grants.length === 0) {
25
+ return {
26
+ cwd: values.cwd,
27
+ };
28
+ }
29
+ const extra = values.env ?? [];
30
+ return {
31
+ cwd: values.cwd,
32
+ allow: grants.map((grant) => ({
33
+ ...grant,
34
+ env: [
35
+ ...(grant.env ?? []),
36
+ ...extra,
37
+ ],
38
+ })),
39
+ };
40
+ }
41
+ function presetGrant(agent) {
42
+ if (!isPreset(agent)) {
43
+ throw new Error(`Unknown agent '${agent}'. Known: ${Object.keys(PRESET_COMMANDS).join(', ')}.`);
44
+ }
45
+ const fixedEnv = agent === 'pi' ? piCommands() : {};
46
+ return {
47
+ ...PRESET_COMMANDS[agent],
48
+ env: PRESET_ENV[agent].filter((name) => !Object.hasOwn(fixedEnv, name)),
49
+ fixedEnv,
50
+ };
51
+ }
52
+ /**
53
+ * pi-acp starts whatever `PI_ACP_PI_COMMAND` names, and the launcher whatever
54
+ * `NOETIC_PI_COMMAND` does, so the runner names both itself: its own
55
+ * launcher, and its own pi.
56
+ */
57
+ function piCommands() {
58
+ return {
59
+ PI_ACP_PI_COMMAND: piLauncherPath(),
60
+ NOETIC_PI_COMMAND: process.env.NOETIC_PI_COMMAND ?? 'pi',
61
+ };
62
+ }
63
+ function isPreset(id) {
64
+ return Object.hasOwn(PRESET_COMMANDS, id);
65
+ }
66
+ function commandGrant(line) {
67
+ const [command, ...args] = line.split(' ').filter((word) => word !== '');
68
+ if (command === undefined) {
69
+ throw new Error('--spawn needs a command.');
70
+ }
71
+ return {
72
+ command,
73
+ args,
74
+ };
75
+ }
76
+ /** A runner does what whoever holds its token, or its stdio, asks of it. */
77
+ export function trustWarning(options) {
78
+ const what = options.allow
79
+ ? 'start the granted commands, with the granted environment names,'
80
+ : 'start any command';
81
+ return `noetic-acp: whoever holds this runner's token (or its stdio) can ${what} as this user, and reach what they can reach. Give it only to hosts you trust.`;
82
+ }
@@ -0,0 +1,101 @@
1
+ /**
2
+ * The frames between a host and a remote runner (`noetic-acp serve`), carried
3
+ * as JSON over one WebSocket or one stdio pipe.
4
+ *
5
+ * The one channel carries everything a connection needs on the agent's
6
+ * machine: processes the host starts there (the agent, and MCP servers beside
7
+ * it), their stdio, and the tool bridge — HTTP requests the agent sends to a
8
+ * loopback port on its machine, answered by the host's bridge.
9
+ */
10
+ import { z } from 'zod';
11
+ /** @public Host → runner. */
12
+ export declare const HostFrameSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
13
+ t: z.ZodLiteral<"reach">;
14
+ id: z.ZodString;
15
+ path: z.ZodString;
16
+ }, z.core.$strip>, z.ZodObject<{
17
+ t: z.ZodLiteral<"start">;
18
+ id: z.ZodString;
19
+ kind: z.ZodEnum<{
20
+ launch: "launch";
21
+ spawn: "spawn";
22
+ }>;
23
+ command: z.ZodString;
24
+ args: z.ZodArray<z.ZodString>;
25
+ env: z.ZodRecord<z.ZodString, z.ZodString>;
26
+ cwd: z.ZodOptional<z.ZodString>;
27
+ }, z.core.$strip>, z.ZodObject<{
28
+ t: z.ZodLiteral<"stdin">;
29
+ id: z.ZodString;
30
+ data: z.ZodString;
31
+ }, z.core.$strip>, z.ZodObject<{
32
+ t: z.ZodLiteral<"kill">;
33
+ id: z.ZodString;
34
+ }, z.core.$strip>, z.ZodObject<{
35
+ t: z.ZodLiteral<"response">;
36
+ id: z.ZodString;
37
+ status: z.ZodNumber;
38
+ headers: z.ZodArray<z.ZodTuple<[z.ZodString, z.ZodString], null>>;
39
+ }, z.core.$strip>, z.ZodObject<{
40
+ t: z.ZodLiteral<"body">;
41
+ id: z.ZodString;
42
+ data: z.ZodString;
43
+ }, z.core.$strip>, z.ZodObject<{
44
+ t: z.ZodLiteral<"end">;
45
+ id: z.ZodString;
46
+ }, z.core.$strip>], "t">;
47
+ /** @public Runner → host. */
48
+ export declare const RunnerFrameSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
49
+ t: z.ZodLiteral<"reached">;
50
+ id: z.ZodString;
51
+ url: z.ZodString;
52
+ }, z.core.$strip>, z.ZodObject<{
53
+ t: z.ZodLiteral<"started">;
54
+ id: z.ZodString;
55
+ }, z.core.$strip>, z.ZodObject<{
56
+ t: z.ZodLiteral<"stdout">;
57
+ id: z.ZodString;
58
+ data: z.ZodString;
59
+ }, z.core.$strip>, z.ZodObject<{
60
+ t: z.ZodLiteral<"exit">;
61
+ id: z.ZodString;
62
+ code: z.ZodNullable<z.ZodNumber>;
63
+ }, z.core.$strip>, z.ZodObject<{
64
+ t: z.ZodLiteral<"error">;
65
+ id: z.ZodString;
66
+ message: z.ZodString;
67
+ }, z.core.$strip>, z.ZodObject<{
68
+ t: z.ZodLiteral<"request">;
69
+ id: z.ZodString;
70
+ method: z.ZodString;
71
+ path: z.ZodString;
72
+ headers: z.ZodArray<z.ZodTuple<[z.ZodString, z.ZodString], null>>;
73
+ body: z.ZodString;
74
+ }, z.core.$strip>, z.ZodObject<{
75
+ t: z.ZodLiteral<"abort">;
76
+ id: z.ZodString;
77
+ }, z.core.$strip>], "t">;
78
+ /** @public */
79
+ export type HostFrame = z.infer<typeof HostFrameSchema>;
80
+ /** @public */
81
+ export type RunnerFrame = z.infer<typeof RunnerFrameSchema>;
82
+ /**
83
+ * One duplex channel of JSON frames: a WebSocket, or newline-delimited JSON
84
+ * over a pipe.
85
+ * @public
86
+ */
87
+ export interface FrameLink {
88
+ send(frame: unknown): void;
89
+ /** Each frame as it arrives, parsed but not yet checked. */
90
+ onFrame(listener: (frame: unknown) => void): void;
91
+ onClose(listener: (reason?: Error) => void): void;
92
+ close(): Promise<void>;
93
+ }
94
+ /** Frames over a byte stream, one JSON object per line. */
95
+ export declare function lineFrameLink(readable: ReadableStream<Uint8Array>, writable: WritableStream<Uint8Array>, close: () => Promise<void>): FrameLink;
96
+ /** The chunks of a byte stream, without relying on its async iterator. */
97
+ export declare function chunksOf(readable: ReadableStream<Uint8Array>): AsyncGenerator<Uint8Array>;
98
+ export declare function toBase64(bytes: Uint8Array): string;
99
+ export declare function fromBase64(text: string): Uint8Array<ArrayBuffer>;
100
+ /** Hosts that never leave the machine, so a hop to them needs no TLS. */
101
+ export declare function isLoopbackHost(hostname: string): boolean;