@noetic-tools/acp 1.3.1 → 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.
- package/dist/agents.d.ts +72 -8
- package/dist/agents.js +162 -58
- package/dist/bin.d.ts +19 -0
- package/dist/bin.js +99 -0
- package/dist/client.d.ts +14 -0
- package/dist/client.js +49 -0
- package/dist/connection.d.ts +3 -0
- package/dist/connection.js +26 -4
- package/dist/define.d.ts +21 -7
- package/dist/define.js +139 -15
- package/dist/index.d.ts +13 -3
- package/dist/index.js +10 -2
- package/dist/mcp/node.d.ts +24 -0
- package/dist/mcp/node.js +146 -0
- package/dist/mcp/server.d.ts +16 -0
- package/dist/mcp/server.js +104 -0
- package/dist/pi/extension.d.ts +31 -0
- package/dist/pi/extension.js +223 -0
- package/dist/pi/launch.d.ts +11 -0
- package/dist/pi/launch.js +35 -0
- package/dist/remote.d.ts +52 -0
- package/dist/remote.js +108 -0
- package/dist/runner/grants.d.ts +47 -0
- package/dist/runner/grants.js +127 -0
- package/dist/runner/host.d.ts +21 -0
- package/dist/runner/host.js +318 -0
- package/dist/runner/options.d.ts +21 -0
- package/dist/runner/options.js +82 -0
- package/dist/runner/protocol.d.ts +101 -0
- package/dist/runner/protocol.js +218 -0
- package/dist/runner/serve.d.ts +60 -0
- package/dist/runner/serve.js +285 -0
- package/dist/runner/ws-link.d.ts +6 -0
- package/dist/runner/ws-link.js +47 -0
- package/dist/server-env.d.ts +10 -0
- package/dist/server-env.js +47 -0
- package/dist/spawn.d.ts +12 -0
- package/dist/spawn.js +37 -0
- package/dist/stdio.d.ts +9 -1
- package/dist/stdio.js +97 -55
- package/dist/tool-bridge.d.ts +67 -0
- package/dist/tool-bridge.js +62 -0
- package/dist/tool-permissions.d.ts +46 -0
- package/dist/tool-permissions.js +70 -0
- package/dist/tool-wiring.d.ts +46 -0
- package/dist/tool-wiring.js +203 -0
- package/dist/transport-loopback.d.ts +8 -1
- package/dist/transport-loopback.js +22 -1
- package/dist/turn.d.ts +11 -5
- package/dist/turn.js +39 -16
- package/package.json +17 -4
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `pi-noetic-tools` — a pi extension that registers each tool the Noetic
|
|
3
|
+
* bridge serves as a native pi tool, with the same name, description and
|
|
4
|
+
* JSON Schema, and forwards each call to the bridge, returning its text
|
|
5
|
+
* unchanged.
|
|
6
|
+
*
|
|
7
|
+
* pi loads this file into its own process (through jiti), so it imports
|
|
8
|
+
* nothing: it speaks just enough MCP streamable HTTP over `fetch` to list and
|
|
9
|
+
* call tools. It reads the bridge address from the environment and then
|
|
10
|
+
* removes it, so the token never reaches commands pi runs.
|
|
11
|
+
*/
|
|
12
|
+
//#endregion
|
|
13
|
+
//#region Constants
|
|
14
|
+
/** Environment the pi wiring sets: the bridge URL and its headers as JSON pairs. */
|
|
15
|
+
const URL_VAR = 'NOETIC_TOOLS_URL';
|
|
16
|
+
const HEADERS_VAR = 'NOETIC_TOOLS_HEADERS';
|
|
17
|
+
const PROTOCOL_VERSION = '2025-06-18';
|
|
18
|
+
//#endregion
|
|
19
|
+
//#region Public API
|
|
20
|
+
/** Registers the bridged tools before pi's session starts. */
|
|
21
|
+
export default async function noeticTools(pi) {
|
|
22
|
+
const url = process.env[URL_VAR];
|
|
23
|
+
if (!url) {
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
const headers = parseHeaders(process.env[HEADERS_VAR]);
|
|
27
|
+
delete process.env[URL_VAR];
|
|
28
|
+
delete process.env[HEADERS_VAR];
|
|
29
|
+
const bridge = new BridgeClient(url, headers);
|
|
30
|
+
await bridge.open();
|
|
31
|
+
for (const tool of await bridge.listTools()) {
|
|
32
|
+
pi.registerTool({
|
|
33
|
+
name: tool.name,
|
|
34
|
+
label: tool.title ?? tool.name,
|
|
35
|
+
description: tool.description ?? '',
|
|
36
|
+
parameters: tool.inputSchema,
|
|
37
|
+
// The bridge runs calls one at a time, as a `callModel` round does.
|
|
38
|
+
executionMode: 'sequential',
|
|
39
|
+
async execute(toolCallId, params, signal) {
|
|
40
|
+
const text = await bridge.callTool(tool.name, params, toolCallId, signal);
|
|
41
|
+
return {
|
|
42
|
+
content: [
|
|
43
|
+
{
|
|
44
|
+
type: 'text',
|
|
45
|
+
text,
|
|
46
|
+
},
|
|
47
|
+
],
|
|
48
|
+
details: {},
|
|
49
|
+
};
|
|
50
|
+
},
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
//#endregion
|
|
55
|
+
//#region Bridge client
|
|
56
|
+
class BridgeClient {
|
|
57
|
+
url;
|
|
58
|
+
headers;
|
|
59
|
+
session;
|
|
60
|
+
next = 0;
|
|
61
|
+
constructor(url, headers) {
|
|
62
|
+
this.url = url;
|
|
63
|
+
this.headers = headers;
|
|
64
|
+
}
|
|
65
|
+
async open() {
|
|
66
|
+
await this.request('initialize', {
|
|
67
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
68
|
+
capabilities: {},
|
|
69
|
+
clientInfo: {
|
|
70
|
+
name: 'pi-noetic-tools',
|
|
71
|
+
version: '1.0.0',
|
|
72
|
+
},
|
|
73
|
+
});
|
|
74
|
+
await this.post({
|
|
75
|
+
jsonrpc: '2.0',
|
|
76
|
+
method: 'notifications/initialized',
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
async listTools() {
|
|
80
|
+
const tools = [];
|
|
81
|
+
let cursor;
|
|
82
|
+
do {
|
|
83
|
+
const page = asRecord(await this.request('tools/list', cursor
|
|
84
|
+
? {
|
|
85
|
+
cursor,
|
|
86
|
+
}
|
|
87
|
+
: {}));
|
|
88
|
+
tools.push(...(Array.isArray(page.tools) ? page.tools.flatMap(toolOf) : []));
|
|
89
|
+
cursor = typeof page.nextCursor === 'string' ? page.nextCursor : undefined;
|
|
90
|
+
} while (cursor);
|
|
91
|
+
return tools;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* The result's text, exactly as the bridge gave it. An error result is the
|
|
95
|
+
* same text a `callModel` model would read, so it is returned, not thrown.
|
|
96
|
+
*/
|
|
97
|
+
async callTool(name, args, callId, signal) {
|
|
98
|
+
const result = asRecord(await this.request('tools/call', {
|
|
99
|
+
name,
|
|
100
|
+
arguments: args ?? {},
|
|
101
|
+
_meta: {
|
|
102
|
+
callId,
|
|
103
|
+
},
|
|
104
|
+
}, signal));
|
|
105
|
+
const content = Array.isArray(result.content) ? result.content : [];
|
|
106
|
+
return content
|
|
107
|
+
.map((part) => {
|
|
108
|
+
const text = asRecord(part).text;
|
|
109
|
+
return typeof text === 'string' ? text : '';
|
|
110
|
+
})
|
|
111
|
+
.join('');
|
|
112
|
+
}
|
|
113
|
+
async request(method, params, signal) {
|
|
114
|
+
this.next += 1;
|
|
115
|
+
const id = this.next;
|
|
116
|
+
const response = await this.post({
|
|
117
|
+
jsonrpc: '2.0',
|
|
118
|
+
id,
|
|
119
|
+
method,
|
|
120
|
+
params,
|
|
121
|
+
}, signal);
|
|
122
|
+
const reply = await readReply(response, id);
|
|
123
|
+
if (reply.error) {
|
|
124
|
+
throw new Error(`noetic tools: ${method} failed: ${reply.error.message ?? 'unknown error'}`);
|
|
125
|
+
}
|
|
126
|
+
return reply.result;
|
|
127
|
+
}
|
|
128
|
+
async post(body, signal) {
|
|
129
|
+
const response = await fetch(this.url, {
|
|
130
|
+
method: 'POST',
|
|
131
|
+
headers: {
|
|
132
|
+
...this.headers,
|
|
133
|
+
'Content-Type': 'application/json',
|
|
134
|
+
Accept: 'application/json, text/event-stream',
|
|
135
|
+
'MCP-Protocol-Version': PROTOCOL_VERSION,
|
|
136
|
+
...(this.session
|
|
137
|
+
? {
|
|
138
|
+
'Mcp-Session-Id': this.session,
|
|
139
|
+
}
|
|
140
|
+
: {}),
|
|
141
|
+
},
|
|
142
|
+
body: JSON.stringify(body),
|
|
143
|
+
signal,
|
|
144
|
+
});
|
|
145
|
+
if (!response.ok) {
|
|
146
|
+
throw new Error(`noetic tools: the bridge answered HTTP ${response.status}.`);
|
|
147
|
+
}
|
|
148
|
+
this.session = response.headers.get('mcp-session-id') ?? this.session;
|
|
149
|
+
return response;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
//#endregion
|
|
153
|
+
//#region Helpers
|
|
154
|
+
/** A JSON reply, or the matching message of an SSE stream. */
|
|
155
|
+
async function readReply(response, id) {
|
|
156
|
+
const type = response.headers.get('content-type') ?? '';
|
|
157
|
+
if (!type.includes('text/event-stream')) {
|
|
158
|
+
return replyOf(await response.json());
|
|
159
|
+
}
|
|
160
|
+
const text = await response.text();
|
|
161
|
+
for (const event of text.split(/\r?\n\r?\n/)) {
|
|
162
|
+
const data = event
|
|
163
|
+
.split(/\r?\n/)
|
|
164
|
+
.filter((line) => line.startsWith('data:'))
|
|
165
|
+
.map((line) => line.slice(5).trimStart())
|
|
166
|
+
.join('\n');
|
|
167
|
+
if (data === '') {
|
|
168
|
+
continue;
|
|
169
|
+
}
|
|
170
|
+
const message = asRecord(JSON.parse(data));
|
|
171
|
+
if (message.id === id) {
|
|
172
|
+
return replyOf(message);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
throw new Error('noetic tools: the bridge sent no reply.');
|
|
176
|
+
}
|
|
177
|
+
function parseHeaders(raw) {
|
|
178
|
+
if (!raw) {
|
|
179
|
+
return {};
|
|
180
|
+
}
|
|
181
|
+
const pairs = JSON.parse(raw);
|
|
182
|
+
if (!Array.isArray(pairs)) {
|
|
183
|
+
return {};
|
|
184
|
+
}
|
|
185
|
+
const headers = {};
|
|
186
|
+
for (const pair of pairs) {
|
|
187
|
+
const entry = asRecord(pair);
|
|
188
|
+
if (typeof entry.name === 'string' && typeof entry.value === 'string') {
|
|
189
|
+
headers[entry.name] = entry.value;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
return headers;
|
|
193
|
+
}
|
|
194
|
+
function asRecord(value) {
|
|
195
|
+
return typeof value === 'object' && value !== null
|
|
196
|
+
? Object.fromEntries(Object.entries(value))
|
|
197
|
+
: {};
|
|
198
|
+
}
|
|
199
|
+
function toolOf(value) {
|
|
200
|
+
const tool = asRecord(value);
|
|
201
|
+
if (typeof tool.name !== 'string') {
|
|
202
|
+
return [];
|
|
203
|
+
}
|
|
204
|
+
return [
|
|
205
|
+
{
|
|
206
|
+
name: tool.name,
|
|
207
|
+
title: typeof tool.title === 'string' ? tool.title : undefined,
|
|
208
|
+
description: typeof tool.description === 'string' ? tool.description : undefined,
|
|
209
|
+
inputSchema: tool.inputSchema,
|
|
210
|
+
},
|
|
211
|
+
];
|
|
212
|
+
}
|
|
213
|
+
function replyOf(value) {
|
|
214
|
+
const message = asRecord(value);
|
|
215
|
+
const error = message.error === undefined ? undefined : asRecord(message.error);
|
|
216
|
+
return {
|
|
217
|
+
result: message.result,
|
|
218
|
+
error: error && {
|
|
219
|
+
message: typeof error.message === 'string' ? error.message : undefined,
|
|
220
|
+
},
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
//#endregion
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* `noetic-pi` — what `pi-acp` starts in place of `pi` (through
|
|
4
|
+
* `PI_ACP_PI_COMMAND`) when a step gives pi tools: pi itself, with the
|
|
5
|
+
* `pi-noetic-tools` extension added. pi-acp passes no extra arguments of its
|
|
6
|
+
* own, so the extension rides in here.
|
|
7
|
+
*
|
|
8
|
+
* Node runs it as `.js` from the published package, and as `.ts` (type
|
|
9
|
+
* stripping) in the workspace; the extension beside it has the same suffix.
|
|
10
|
+
*/
|
|
11
|
+
export {};
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* `noetic-pi` — what `pi-acp` starts in place of `pi` (through
|
|
4
|
+
* `PI_ACP_PI_COMMAND`) when a step gives pi tools: pi itself, with the
|
|
5
|
+
* `pi-noetic-tools` extension added. pi-acp passes no extra arguments of its
|
|
6
|
+
* own, so the extension rides in here.
|
|
7
|
+
*
|
|
8
|
+
* Node runs it as `.js` from the published package, and as `.ts` (type
|
|
9
|
+
* stripping) in the workspace; the extension beside it has the same suffix.
|
|
10
|
+
*/
|
|
11
|
+
import { spawn } from 'node:child_process';
|
|
12
|
+
import { fileURLToPath } from 'node:url';
|
|
13
|
+
const suffix = import.meta.url.endsWith('.ts') ? 'ts' : 'js';
|
|
14
|
+
const extension = fileURLToPath(new URL(`./extension.${suffix}`, import.meta.url));
|
|
15
|
+
const pi = process.env.NOETIC_PI_COMMAND ?? 'pi';
|
|
16
|
+
const child = spawn(pi, [
|
|
17
|
+
'--extension',
|
|
18
|
+
extension,
|
|
19
|
+
...process.argv.slice(2),
|
|
20
|
+
], {
|
|
21
|
+
stdio: 'inherit',
|
|
22
|
+
});
|
|
23
|
+
child.once('error', (error) => {
|
|
24
|
+
process.stderr.write(`noetic-pi: could not start '${pi}': ${error.message}\n`);
|
|
25
|
+
process.exit(127);
|
|
26
|
+
});
|
|
27
|
+
for (const signal of [
|
|
28
|
+
'SIGINT',
|
|
29
|
+
'SIGTERM',
|
|
30
|
+
]) {
|
|
31
|
+
process.on(signal, () => child.kill(signal));
|
|
32
|
+
}
|
|
33
|
+
child.once('exit', (code, signal) => {
|
|
34
|
+
process.exit(code ?? (signal ? 1 : 0));
|
|
35
|
+
});
|
package/dist/remote.d.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Machines elsewhere, through a remote runner (`noetic-acp serve`), and the
|
|
3
|
+
* runner itself.
|
|
4
|
+
*
|
|
5
|
+
* A runner on the agent's machine starts the agent with the preset's launch
|
|
6
|
+
* settings, starts MCP servers beside it, and serves the host's tool bridge to
|
|
7
|
+
* them on its own loopback interface — all over one channel, so the agent
|
|
8
|
+
* needs no route back to the host. The channel is a WebSocket
|
|
9
|
+
* ({@link webSocketMachine}) or the stdio of a command that starts the runner
|
|
10
|
+
* there ({@link commandMachine}: `ssh host …`, `docker exec -i ctr …`).
|
|
11
|
+
*
|
|
12
|
+
* Node-only (`ws`, `node:child_process`), so it lives behind
|
|
13
|
+
* `@noetic-tools/acp/remote`.
|
|
14
|
+
*/
|
|
15
|
+
import type { AcpMachineFactory } from '@noetic-tools/types';
|
|
16
|
+
import { runnerMachine } from './runner/host.js';
|
|
17
|
+
export type { AcpRunnerGrant } from './runner/grants.js';
|
|
18
|
+
export type { FrameLink, HostFrame, RunnerFrame } from './runner/protocol.js';
|
|
19
|
+
export { HostFrameSchema, lineFrameLink, RunnerFrameSchema } from './runner/protocol.js';
|
|
20
|
+
export type { AcpRunnerListener, AcpRunnerListenOptions, AcpRunnerOptions, } from './runner/serve.js';
|
|
21
|
+
export { listenAcpRunner, serveAcpRunner, serveAcpRunnerOverStdio } from './runner/serve.js';
|
|
22
|
+
export { runnerMachine };
|
|
23
|
+
/** @public Options for {@link webSocketMachine}. */
|
|
24
|
+
export interface WebSocketMachineOptions {
|
|
25
|
+
/** The runner's `wss://` URL; `ws://` only to a loopback host. */
|
|
26
|
+
url: string;
|
|
27
|
+
/** The runner's bearer token. */
|
|
28
|
+
token: string;
|
|
29
|
+
/** PEM certificate authority to trust, for a runner with its own certificate. */
|
|
30
|
+
ca?: string;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* A runner reached over WebSocket. Every upgrade carries the bearer token, and
|
|
34
|
+
* a runner off the loopback interface is reached over TLS only.
|
|
35
|
+
* @public
|
|
36
|
+
*/
|
|
37
|
+
export declare function webSocketMachine(opts: WebSocketMachineOptions): AcpMachineFactory;
|
|
38
|
+
/** @public Options for {@link commandMachine}. */
|
|
39
|
+
export interface CommandMachineOptions {
|
|
40
|
+
/** Starts a runner over stdio, e.g. `ssh`, or `docker` with `exec -i`. */
|
|
41
|
+
command: string;
|
|
42
|
+
/** e.g. `['build-host', 'npx', '-y', '@noetic-tools/acp', 'serve', '--stdio']`. */
|
|
43
|
+
args: ReadonlyArray<string>;
|
|
44
|
+
env?: Record<string, string | undefined>;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* A runner started by a local command and spoken to over its stdio. The
|
|
48
|
+
* command's own channel (ssh, `docker exec`) carries the frames, so it adds no
|
|
49
|
+
* listener anywhere.
|
|
50
|
+
* @public
|
|
51
|
+
*/
|
|
52
|
+
export declare function commandMachine(opts: CommandMachineOptions): AcpMachineFactory;
|
package/dist/remote.js
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Machines elsewhere, through a remote runner (`noetic-acp serve`), and the
|
|
3
|
+
* runner itself.
|
|
4
|
+
*
|
|
5
|
+
* A runner on the agent's machine starts the agent with the preset's launch
|
|
6
|
+
* settings, starts MCP servers beside it, and serves the host's tool bridge to
|
|
7
|
+
* them on its own loopback interface — all over one channel, so the agent
|
|
8
|
+
* needs no route back to the host. The channel is a WebSocket
|
|
9
|
+
* ({@link webSocketMachine}) or the stdio of a command that starts the runner
|
|
10
|
+
* there ({@link commandMachine}: `ssh host …`, `docker exec -i ctr …`).
|
|
11
|
+
*
|
|
12
|
+
* Node-only (`ws`, `node:child_process`), so it lives behind
|
|
13
|
+
* `@noetic-tools/acp/remote`.
|
|
14
|
+
*/
|
|
15
|
+
import { spawn } from 'node:child_process';
|
|
16
|
+
import { Readable, Writable } from 'node:stream';
|
|
17
|
+
import { AcpConnectError, frameworkCast } from '@noetic-tools/types';
|
|
18
|
+
import { WebSocket } from 'ws';
|
|
19
|
+
import { runnerMachine } from './runner/host.js';
|
|
20
|
+
import { isLoopbackHost, lineFrameLink } from './runner/protocol.js';
|
|
21
|
+
import { webSocketFrameLink } from './runner/ws-link.js';
|
|
22
|
+
export { HostFrameSchema, lineFrameLink, RunnerFrameSchema } from './runner/protocol.js';
|
|
23
|
+
export { listenAcpRunner, serveAcpRunner, serveAcpRunnerOverStdio } from './runner/serve.js';
|
|
24
|
+
export { runnerMachine };
|
|
25
|
+
/**
|
|
26
|
+
* A runner reached over WebSocket. Every upgrade carries the bearer token, and
|
|
27
|
+
* a runner off the loopback interface is reached over TLS only.
|
|
28
|
+
* @public
|
|
29
|
+
*/
|
|
30
|
+
export function webSocketMachine(opts) {
|
|
31
|
+
const url = new URL(opts.url);
|
|
32
|
+
if (url.protocol !== 'wss:' && !(url.protocol === 'ws:' && isLoopbackHost(url.hostname))) {
|
|
33
|
+
throw new TypeError(`webSocketMachine needs a wss:// URL for ${url.host}; ws:// is allowed only to a loopback host.`);
|
|
34
|
+
}
|
|
35
|
+
return runnerMachine(async () => {
|
|
36
|
+
const socket = new WebSocket(url, {
|
|
37
|
+
headers: {
|
|
38
|
+
Authorization: `Bearer ${opts.token}`,
|
|
39
|
+
},
|
|
40
|
+
ca: opts.ca,
|
|
41
|
+
// Bun's built-in `ws` reads its TLS settings from here.
|
|
42
|
+
...{
|
|
43
|
+
tls: {
|
|
44
|
+
ca: opts.ca,
|
|
45
|
+
},
|
|
46
|
+
},
|
|
47
|
+
});
|
|
48
|
+
await new Promise((resolve, reject) => {
|
|
49
|
+
const refused = (detail, cause) => {
|
|
50
|
+
reject(new AcpConnectError({
|
|
51
|
+
agentId: 'runner',
|
|
52
|
+
message: `The runner at ${url.host} refused the connection or could not be reached (${detail}).`,
|
|
53
|
+
cause,
|
|
54
|
+
}));
|
|
55
|
+
};
|
|
56
|
+
socket.once('open', () => resolve());
|
|
57
|
+
socket.once('unexpected-response', (_req, res) => refused(`HTTP ${res.statusCode}`));
|
|
58
|
+
// Kept for the socket's life: a second error must not go unhandled.
|
|
59
|
+
socket.on('error', (cause) => refused(cause.message, cause));
|
|
60
|
+
});
|
|
61
|
+
return webSocketFrameLink(socket);
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* A runner started by a local command and spoken to over its stdio. The
|
|
66
|
+
* command's own channel (ssh, `docker exec`) carries the frames, so it adds no
|
|
67
|
+
* listener anywhere.
|
|
68
|
+
* @public
|
|
69
|
+
*/
|
|
70
|
+
export function commandMachine(opts) {
|
|
71
|
+
return runnerMachine(async (signal) => {
|
|
72
|
+
const child = spawn(opts.command, [
|
|
73
|
+
...opts.args,
|
|
74
|
+
], {
|
|
75
|
+
env: {
|
|
76
|
+
...process.env,
|
|
77
|
+
...opts.env,
|
|
78
|
+
},
|
|
79
|
+
stdio: [
|
|
80
|
+
'pipe',
|
|
81
|
+
'pipe',
|
|
82
|
+
'inherit',
|
|
83
|
+
],
|
|
84
|
+
signal,
|
|
85
|
+
});
|
|
86
|
+
await new Promise((resolve, reject) => {
|
|
87
|
+
child.once('spawn', resolve);
|
|
88
|
+
child.once('error', (cause) => reject(new AcpConnectError({
|
|
89
|
+
agentId: 'runner',
|
|
90
|
+
message: `Could not start the runner with '${opts.command}'.`,
|
|
91
|
+
cause,
|
|
92
|
+
})));
|
|
93
|
+
});
|
|
94
|
+
const { stdin, stdout } = child;
|
|
95
|
+
if (!stdin || !stdout) {
|
|
96
|
+
child.kill();
|
|
97
|
+
throw new AcpConnectError({
|
|
98
|
+
agentId: 'runner',
|
|
99
|
+
message: `The runner started with '${opts.command}' has no stdio.`,
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
stdin.on('error', () => undefined);
|
|
103
|
+
return lineFrameLink(frameworkCast(Readable.toWeb(stdout)), frameworkCast(Writable.toWeb(stdin)), async () => {
|
|
104
|
+
child.kill();
|
|
105
|
+
});
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
//#endregion
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a runner with an allowlist lets a host start: a granted command with
|
|
3
|
+
* its exact arguments, only the environment names that grant lists, in a
|
|
4
|
+
* working directory inside the runner's own.
|
|
5
|
+
*
|
|
6
|
+
* Environment names are allowed rather than refused, since a launcher name
|
|
7
|
+
* (`NODE_OPTIONS`, `LD_PRELOAD`, `PATH`, …) runs code under any command, and
|
|
8
|
+
* no list of such names is ever complete. A value that names a command the
|
|
9
|
+
* agent starts — a Codex config's MCP servers, pi's own command — is checked
|
|
10
|
+
* against the grants or set by the runner itself.
|
|
11
|
+
*/
|
|
12
|
+
/** @public A command a runner may start. */
|
|
13
|
+
export interface AcpRunnerGrant {
|
|
14
|
+
command: string;
|
|
15
|
+
args?: ReadonlyArray<string>;
|
|
16
|
+
/** Environment names a host may set for it. It may set no others. */
|
|
17
|
+
env?: ReadonlyArray<string>;
|
|
18
|
+
/**
|
|
19
|
+
* Environment the runner sets itself, over whatever a host sends under
|
|
20
|
+
* these names: what the command would otherwise start on a host's word.
|
|
21
|
+
*/
|
|
22
|
+
fixedEnv?: Readonly<Record<string, string>>;
|
|
23
|
+
}
|
|
24
|
+
/** A start a host asked for. */
|
|
25
|
+
export interface Start {
|
|
26
|
+
command: string;
|
|
27
|
+
args: ReadonlyArray<string>;
|
|
28
|
+
env: Record<string, string>;
|
|
29
|
+
cwd?: string;
|
|
30
|
+
}
|
|
31
|
+
/** What the runner starts a granted command with. */
|
|
32
|
+
export interface CheckedStart {
|
|
33
|
+
/** The real working directory. */
|
|
34
|
+
readonly cwd: string;
|
|
35
|
+
/** The host's environment, with the grant's `fixedEnv` over it. */
|
|
36
|
+
readonly env: Record<string, string>;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* What the runner starts `start` with, or a throw naming why it refuses it.
|
|
40
|
+
* Without `allow` the host may start anything, anywhere. With it, a
|
|
41
|
+
* `CODEX_CONFIG` the host sets may declare only MCP server commands `allow`
|
|
42
|
+
* grants, since Codex starts each one.
|
|
43
|
+
*/
|
|
44
|
+
export declare function checkStart(start: Start, options: {
|
|
45
|
+
allow?: ReadonlyArray<AcpRunnerGrant>;
|
|
46
|
+
cwd?: string;
|
|
47
|
+
}): CheckedStart;
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a runner with an allowlist lets a host start: a granted command with
|
|
3
|
+
* its exact arguments, only the environment names that grant lists, in a
|
|
4
|
+
* working directory inside the runner's own.
|
|
5
|
+
*
|
|
6
|
+
* Environment names are allowed rather than refused, since a launcher name
|
|
7
|
+
* (`NODE_OPTIONS`, `LD_PRELOAD`, `PATH`, …) runs code under any command, and
|
|
8
|
+
* no list of such names is ever complete. A value that names a command the
|
|
9
|
+
* agent starts — a Codex config's MCP servers, pi's own command — is checked
|
|
10
|
+
* against the grants or set by the runner itself.
|
|
11
|
+
*/
|
|
12
|
+
import { existsSync, realpathSync } from 'node:fs';
|
|
13
|
+
import { isAbsolute, relative, sep } from 'node:path';
|
|
14
|
+
import { z } from 'zod';
|
|
15
|
+
//#endregion
|
|
16
|
+
//#region Public API
|
|
17
|
+
/**
|
|
18
|
+
* What the runner starts `start` with, or a throw naming why it refuses it.
|
|
19
|
+
* Without `allow` the host may start anything, anywhere. With it, a
|
|
20
|
+
* `CODEX_CONFIG` the host sets may declare only MCP server commands `allow`
|
|
21
|
+
* grants, since Codex starts each one.
|
|
22
|
+
*/
|
|
23
|
+
export function checkStart(start, options) {
|
|
24
|
+
const root = options.cwd ?? process.cwd();
|
|
25
|
+
const allow = options.allow;
|
|
26
|
+
if (!allow) {
|
|
27
|
+
return {
|
|
28
|
+
cwd: existing(start.cwd ?? root),
|
|
29
|
+
env: start.env,
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
const grant = grantFor(allow, start.command, start.args);
|
|
33
|
+
if (!grant) {
|
|
34
|
+
throw new Error(`This runner does not start '${commandLine(start.command, start.args)}'.`);
|
|
35
|
+
}
|
|
36
|
+
const granted = new Set([
|
|
37
|
+
...(grant.env ?? []),
|
|
38
|
+
...Object.keys(grant.fixedEnv ?? {}),
|
|
39
|
+
]);
|
|
40
|
+
const refused = Object.keys(start.env).filter((name) => !granted.has(name));
|
|
41
|
+
if (refused.length > 0) {
|
|
42
|
+
throw new Error(`This runner does not let a host set ${refused.join(', ')} for '${start.command}'.`);
|
|
43
|
+
}
|
|
44
|
+
const codexConfig = start.env.CODEX_CONFIG;
|
|
45
|
+
if (codexConfig !== undefined) {
|
|
46
|
+
checkCodexConfig(codexConfig, allow);
|
|
47
|
+
}
|
|
48
|
+
return {
|
|
49
|
+
cwd: inside(existing(root), existing(start.cwd ?? root)),
|
|
50
|
+
env: {
|
|
51
|
+
...start.env,
|
|
52
|
+
...grant.fixedEnv,
|
|
53
|
+
},
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
//#endregion
|
|
57
|
+
//#region Helpers
|
|
58
|
+
const CodexServerSchema = z.object({
|
|
59
|
+
command: z.string().optional(),
|
|
60
|
+
args: z.array(z.string()).optional(),
|
|
61
|
+
env: z.record(z.string(), z.string()).optional(),
|
|
62
|
+
});
|
|
63
|
+
const CodexConfigSchema = z.object({
|
|
64
|
+
mcp_servers: z.record(z.string(), CodexServerSchema).optional(),
|
|
65
|
+
notify: z.unknown().optional(),
|
|
66
|
+
});
|
|
67
|
+
/**
|
|
68
|
+
* Codex starts every `mcp_servers` entry with a `command`, with its `env`, and
|
|
69
|
+
* runs `notify` after each turn. Each server must be a granted command line
|
|
70
|
+
* whose grant lists every name it sets; `notify` is refused outright.
|
|
71
|
+
*/
|
|
72
|
+
function checkCodexConfig(raw, allow) {
|
|
73
|
+
const parsed = CodexConfigSchema.safeParse(safeJson(raw));
|
|
74
|
+
if (!parsed.success) {
|
|
75
|
+
throw new Error('This runner does not start Codex with a CODEX_CONFIG it cannot read.');
|
|
76
|
+
}
|
|
77
|
+
if (parsed.data.notify !== undefined) {
|
|
78
|
+
throw new Error('This runner does not let a host set CODEX_CONFIG.notify, a command Codex runs.');
|
|
79
|
+
}
|
|
80
|
+
for (const [name, server] of Object.entries(parsed.data.mcp_servers ?? {})) {
|
|
81
|
+
if (server.command === undefined) {
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
const args = server.args ?? [];
|
|
85
|
+
const grant = grantFor(allow, server.command, args);
|
|
86
|
+
if (!grant) {
|
|
87
|
+
throw new Error(`This runner does not start '${commandLine(server.command, args)}', which CODEX_CONFIG declares as MCP server '${name}'.`);
|
|
88
|
+
}
|
|
89
|
+
const granted = new Set(grant.env ?? []);
|
|
90
|
+
const refused = Object.keys(server.env ?? {}).filter((variable) => !granted.has(variable));
|
|
91
|
+
if (refused.length > 0) {
|
|
92
|
+
throw new Error(`This runner does not let a host set ${refused.join(', ')} for MCP server '${name}' in CODEX_CONFIG.`);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
function grantFor(allow, command, args) {
|
|
97
|
+
return allow.find((entry) => entry.command === command && JSON.stringify(entry.args ?? []) === JSON.stringify(args));
|
|
98
|
+
}
|
|
99
|
+
function commandLine(command, args) {
|
|
100
|
+
return [
|
|
101
|
+
command,
|
|
102
|
+
...args,
|
|
103
|
+
].join(' ');
|
|
104
|
+
}
|
|
105
|
+
function safeJson(text) {
|
|
106
|
+
try {
|
|
107
|
+
return JSON.parse(text);
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
return undefined;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
/** The real path of `dir`, so a symlink cannot lead out of the runner's directory. */
|
|
114
|
+
function existing(dir) {
|
|
115
|
+
if (!existsSync(dir)) {
|
|
116
|
+
throw new Error(`The working directory '${dir}' does not exist on the runner's machine.`);
|
|
117
|
+
}
|
|
118
|
+
return realpathSync(dir);
|
|
119
|
+
}
|
|
120
|
+
function inside(root, dir) {
|
|
121
|
+
const rel = relative(root, dir);
|
|
122
|
+
if (rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {
|
|
123
|
+
throw new Error(`This runner starts nothing outside '${root}'; '${dir}' is.`);
|
|
124
|
+
}
|
|
125
|
+
return dir;
|
|
126
|
+
}
|
|
127
|
+
//#endregion
|
|
@@ -0,0 +1,21 @@
|
|
|
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 type { AcpMachineFactory } from '@noetic-tools/types';
|
|
9
|
+
import type { FrameLink } from './protocol.js';
|
|
10
|
+
/**
|
|
11
|
+
* A machine reached through a remote runner over `openLink`.
|
|
12
|
+
* @public
|
|
13
|
+
*/
|
|
14
|
+
export declare function runnerMachine(openLink: (signal?: AbortSignal) => Promise<FrameLink>): AcpMachineFactory;
|
|
15
|
+
/**
|
|
16
|
+
* The bridge URL a request path forwards to, or none. The URL is built from
|
|
17
|
+
* the parsed path, the one that was checked: a raw path such as
|
|
18
|
+
* `0/../mcp/x` parses to a bridge path but, appended to the origin, would
|
|
19
|
+
* name another port.
|
|
20
|
+
*/
|
|
21
|
+
export declare function bridgeTarget(bridges: ReadonlyMap<string, string>, path: string): URL | undefined;
|