@noetic-tools/acp 2.0.0-next.1 → 2.0.0-next.2
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/bin.js +19 -2
- package/dist/client-adapters.d.ts +2 -2
- package/dist/client.d.ts +2 -2
- package/dist/client.js +1 -1
- package/dist/connection.d.ts +6 -2
- package/dist/connection.js +213 -31
- package/dist/define.js +92 -4
- package/dist/items.d.ts +1 -1
- package/dist/keeper/client.d.ts +84 -0
- package/dist/keeper/client.js +436 -0
- package/dist/keeper/main.d.ts +6 -0
- package/dist/keeper/main.js +31 -0
- package/dist/keeper/process.d.ts +24 -0
- package/dist/keeper/process.js +422 -0
- package/dist/keeper/protocol.d.ts +72 -0
- package/dist/keeper/protocol.js +101 -0
- package/dist/keeper/relay.d.ts +88 -0
- package/dist/keeper/relay.js +420 -0
- package/dist/mcp/node.d.ts +6 -1
- package/dist/mcp/node.js +4 -4
- package/dist/permission-channel.d.ts +5 -0
- package/dist/permission-channel.js +16 -1
- package/dist/runner/host.js +74 -16
- package/dist/runner/options.d.ts +2 -0
- package/dist/runner/options.js +2 -0
- package/dist/runner/protocol.d.ts +12 -0
- package/dist/runner/protocol.js +24 -0
- package/dist/runner/serve.d.ts +5 -0
- package/dist/runner/serve.js +93 -3
- package/dist/serve-types.d.ts +1 -1
- package/dist/serve.d.ts +2 -2
- package/dist/serve.js +1 -1
- package/dist/server.js +1 -1
- package/dist/stdio-process.d.ts +38 -0
- package/dist/stdio-process.js +214 -0
- package/dist/stdio.d.ts +28 -6
- package/dist/stdio.js +145 -51
- package/dist/tool-bridge.d.ts +9 -0
- package/dist/tool-bridge.js +5 -1
- package/dist/transport-loopback.d.ts +2 -2
- package/dist/transport-loopback.js +1 -1
- package/dist/turn.d.ts +3 -2
- package/dist/turn.js +22 -2
- package/dist/update-filter.d.ts +22 -0
- package/dist/update-filter.js +119 -0
- package/package.json +3 -3
package/dist/runner/protocol.js
CHANGED
|
@@ -48,6 +48,28 @@ export const HostFrameSchema = z.discriminatedUnion('t', [
|
|
|
48
48
|
t: z.literal('kill'),
|
|
49
49
|
id: Id,
|
|
50
50
|
}),
|
|
51
|
+
/**
|
|
52
|
+
* Run the agents this channel launches through a keeper on the runner's
|
|
53
|
+
* machine, so they outlive the channel; `whenHostExits` says what happens
|
|
54
|
+
* to them when it drops. Sent once, first, by hosts that keep agents.
|
|
55
|
+
*/
|
|
56
|
+
z.object({
|
|
57
|
+
t: z.literal('keep'),
|
|
58
|
+
id: Id,
|
|
59
|
+
whenHostExits: z.enum([
|
|
60
|
+
'keep',
|
|
61
|
+
'stop',
|
|
62
|
+
]),
|
|
63
|
+
}),
|
|
64
|
+
/**
|
|
65
|
+
* Carry the stream of an agent an earlier channel launched, from the
|
|
66
|
+
* reattach handle its `started` frame gave; answered with `started`.
|
|
67
|
+
*/
|
|
68
|
+
z.object({
|
|
69
|
+
t: z.literal('attach'),
|
|
70
|
+
id: Id,
|
|
71
|
+
handle: z.record(z.string(), z.unknown()),
|
|
72
|
+
}),
|
|
51
73
|
z.object({
|
|
52
74
|
t: z.literal('response'),
|
|
53
75
|
id: Id,
|
|
@@ -74,6 +96,8 @@ export const RunnerFrameSchema = z.discriminatedUnion('t', [
|
|
|
74
96
|
z.object({
|
|
75
97
|
t: z.literal('started'),
|
|
76
98
|
id: Id,
|
|
99
|
+
/** For a kept agent: how a later channel reaches it again. */
|
|
100
|
+
reattach: z.record(z.string(), z.unknown()).optional(),
|
|
77
101
|
}),
|
|
78
102
|
z.object({
|
|
79
103
|
t: z.literal('stdout'),
|
package/dist/runner/serve.d.ts
CHANGED
|
@@ -19,6 +19,11 @@ export interface AcpRunnerOptions {
|
|
|
19
19
|
allow?: ReadonlyArray<AcpRunnerGrant>;
|
|
20
20
|
/** Working directory for a start that names none. */
|
|
21
21
|
cwd?: string;
|
|
22
|
+
/**
|
|
23
|
+
* How long an agent a host keeps may run with no host attached before its
|
|
24
|
+
* keeper stops it. Default `0`: until a host reattaches or it exits.
|
|
25
|
+
*/
|
|
26
|
+
detachedTimeoutMs?: number;
|
|
22
27
|
}
|
|
23
28
|
/** @public Options for {@link listenAcpRunner}. */
|
|
24
29
|
export interface AcpRunnerListenOptions extends AcpRunnerOptions {
|
package/dist/runner/serve.js
CHANGED
|
@@ -15,9 +15,10 @@ import * as https from 'node:https';
|
|
|
15
15
|
import { Readable, Writable } from 'node:stream';
|
|
16
16
|
import { frameworkCast } from '@noetic-tools/types';
|
|
17
17
|
import { WebSocketServer } from 'ws';
|
|
18
|
+
import { attachKeeper, isKeeperAddress, keeperHandleOf, startKeeper } from '../keeper/client.js';
|
|
18
19
|
import { serverEnv } from '../server-env.js';
|
|
19
20
|
import { checkStart } from './grants.js';
|
|
20
|
-
import { fromBase64, HostFrameSchema, isLoopbackHost, lineFrameLink, toBase64 } from './protocol.js';
|
|
21
|
+
import { chunksOf, fromBase64, HostFrameSchema, isLoopbackHost, lineFrameLink, toBase64, } from './protocol.js';
|
|
21
22
|
import { webSocketFrameLink } from './ws-link.js';
|
|
22
23
|
//#endregion
|
|
23
24
|
//#region Public API
|
|
@@ -33,6 +34,7 @@ export function serveAcpRunner(link, options = {}) {
|
|
|
33
34
|
ports: [],
|
|
34
35
|
responses: new Map(),
|
|
35
36
|
next: 0,
|
|
37
|
+
kept: new Map(),
|
|
36
38
|
};
|
|
37
39
|
return new Promise((resolve) => {
|
|
38
40
|
link.onFrame((raw) => {
|
|
@@ -112,11 +114,27 @@ const handlers = {
|
|
|
112
114
|
reach: openPort,
|
|
113
115
|
start: startProcess,
|
|
114
116
|
stdin: (session, frame) => {
|
|
117
|
+
const kept = session.kept.get(frame.id);
|
|
118
|
+
if (kept) {
|
|
119
|
+
void kept.writer.write(fromBase64(frame.data)).catch(() => undefined);
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
115
122
|
session.children.get(frame.id)?.stdin?.write(fromBase64(frame.data));
|
|
116
123
|
},
|
|
117
|
-
kill: (session, frame) => {
|
|
124
|
+
kill: async (session, frame) => {
|
|
125
|
+
const kept = session.kept.get(frame.id);
|
|
126
|
+
if (kept) {
|
|
127
|
+
// The host closes its agent on purpose: stop it, keeper and all.
|
|
128
|
+
session.kept.delete(frame.id);
|
|
129
|
+
await kept.transport.close();
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
118
132
|
session.children.get(frame.id)?.kill();
|
|
119
133
|
},
|
|
134
|
+
keep: (session, frame) => {
|
|
135
|
+
session.keep = frame.whenHostExits;
|
|
136
|
+
},
|
|
137
|
+
attach: attachKept,
|
|
120
138
|
response: (session, frame) => {
|
|
121
139
|
const res = session.responses.get(frame.id);
|
|
122
140
|
if (!res || res.headersSent) {
|
|
@@ -170,10 +188,14 @@ async function openPort(session, frame) {
|
|
|
170
188
|
if (address === null || typeof address === 'string') {
|
|
171
189
|
throw new Error('The bridge port did not bind.');
|
|
172
190
|
}
|
|
191
|
+
const local = `http://127.0.0.1:${address.port}${frame.path}`;
|
|
192
|
+
// A kept agent reaches the bridge on its keeper's port, which outlives this
|
|
193
|
+
// channel; the keeper forwards to this channel's port while it is open.
|
|
194
|
+
const keeper = await openKeeper(session);
|
|
173
195
|
session.link.send({
|
|
174
196
|
t: 'reached',
|
|
175
197
|
id: frame.id,
|
|
176
|
-
url:
|
|
198
|
+
url: keeper ? await keeper.reach(frame.path, local) : local,
|
|
177
199
|
});
|
|
178
200
|
}
|
|
179
201
|
async function relay(session, req, res) {
|
|
@@ -210,6 +232,20 @@ async function relay(session, req, res) {
|
|
|
210
232
|
}
|
|
211
233
|
async function startProcess(session, frame) {
|
|
212
234
|
const checked = checkStart(frame, session.options);
|
|
235
|
+
const keeper = frame.kind === 'launch' ? await openKeeper(session) : undefined;
|
|
236
|
+
if (keeper) {
|
|
237
|
+
const transport = await keeper.launch({
|
|
238
|
+
command: frame.command,
|
|
239
|
+
args: frame.args,
|
|
240
|
+
cwd: checked.cwd,
|
|
241
|
+
env: {
|
|
242
|
+
...process.env,
|
|
243
|
+
...checked.env,
|
|
244
|
+
},
|
|
245
|
+
});
|
|
246
|
+
carryKept(session, frame.id, transport);
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
213
249
|
// An MCP server gets what the MCP SDK would give it here, the agent all of the runner's.
|
|
214
250
|
const env = frame.kind === 'spawn'
|
|
215
251
|
? serverEnv(checked.env)
|
|
@@ -253,6 +289,57 @@ async function startProcess(session, frame) {
|
|
|
253
289
|
id: frame.id,
|
|
254
290
|
});
|
|
255
291
|
}
|
|
292
|
+
/** Start this channel's keeper on first use, when the host keeps its agents. */
|
|
293
|
+
function openKeeper(session) {
|
|
294
|
+
const whenHostExits = session.keep;
|
|
295
|
+
if (!whenHostExits) {
|
|
296
|
+
return Promise.resolve(undefined);
|
|
297
|
+
}
|
|
298
|
+
session.keeper ??= startKeeper('runner', {
|
|
299
|
+
whenHostExits,
|
|
300
|
+
detachedTimeoutMs: session.options.detachedTimeoutMs ?? 0,
|
|
301
|
+
});
|
|
302
|
+
return session.keeper;
|
|
303
|
+
}
|
|
304
|
+
/** Send a kept agent's output as stream `id` until it ends. */
|
|
305
|
+
async function pumpKept(session, id, transport) {
|
|
306
|
+
for await (const chunk of chunksOf(transport.readable)) {
|
|
307
|
+
session.link.send({
|
|
308
|
+
t: 'stdout',
|
|
309
|
+
id,
|
|
310
|
+
data: toBase64(chunk),
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
session.kept.delete(id);
|
|
314
|
+
session.link.send({
|
|
315
|
+
t: 'exit',
|
|
316
|
+
id,
|
|
317
|
+
code: null,
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
/** Carry a kept agent's stream over this channel as stream `id`. */
|
|
321
|
+
function carryKept(session, id, transport) {
|
|
322
|
+
session.kept.set(id, {
|
|
323
|
+
transport,
|
|
324
|
+
writer: transport.writable.getWriter(),
|
|
325
|
+
});
|
|
326
|
+
void pumpKept(session, id, transport).catch(() => undefined);
|
|
327
|
+
session.link.send({
|
|
328
|
+
t: 'started',
|
|
329
|
+
id,
|
|
330
|
+
reattach: transport.reattach,
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
/** Take over an agent an earlier channel launched and kept. */
|
|
334
|
+
async function attachKept(session, frame) {
|
|
335
|
+
const handle = keeperHandleOf(frame.handle);
|
|
336
|
+
if (!handle || !isKeeperAddress(handle.address)) {
|
|
337
|
+
throw new Error('The handle names no keeper on this runner.');
|
|
338
|
+
}
|
|
339
|
+
const link = await attachKeeper('runner', handle, session.keep ?? 'keep');
|
|
340
|
+
session.keeper = Promise.resolve(link);
|
|
341
|
+
carryKept(session, frame.id, link.transport());
|
|
342
|
+
}
|
|
256
343
|
//#endregion
|
|
257
344
|
//#region Helpers
|
|
258
345
|
function release(session) {
|
|
@@ -268,6 +355,9 @@ function release(session) {
|
|
|
268
355
|
res.destroy();
|
|
269
356
|
}
|
|
270
357
|
session.responses.clear();
|
|
358
|
+
// A kept agent is let go, not stopped: its keeper decides (`whenHostExits`).
|
|
359
|
+
session.kept.clear();
|
|
360
|
+
void session.keeper?.then((link) => link?.detach());
|
|
271
361
|
}
|
|
272
362
|
function sameSecret(given, expected) {
|
|
273
363
|
const a = Buffer.from(given ?? '');
|
package/dist/serve-types.d.ts
CHANGED
|
@@ -5,8 +5,8 @@
|
|
|
5
5
|
* `@noetic-tools/chat-sdk` uses — so this package keeps depending only on
|
|
6
6
|
* `@noetic-tools/types`.
|
|
7
7
|
*/
|
|
8
|
+
import type * as acp from '@agentclientprotocol/sdk';
|
|
8
9
|
import type { AcpMcpServer, AcpToolKind, ExecuteArgument, ExecuteOptions, FsAdapter, Item, SessionScope, ShellAdapter, StreamEvent, StreamingItem, ToolAcpDeclaration } from '@noetic-tools/types';
|
|
9
|
-
import type * as acp from '@zed-industries/agent-client-protocol';
|
|
10
10
|
/**
|
|
11
11
|
* The slice of `AgentHarnessContract` the ACP server drives. Any harness (or
|
|
12
12
|
* structural stand-in, in tests) satisfying this can be served.
|
package/dist/serve.d.ts
CHANGED
|
@@ -9,8 +9,8 @@
|
|
|
9
9
|
* The adapter maps the protocol onto the harness's existing public surface —
|
|
10
10
|
* `execute`, the streams, `seedSessionHistory`, `abort` — and nothing else.
|
|
11
11
|
*/
|
|
12
|
-
import type * as acp from '@
|
|
13
|
-
import type { AgentSideConnection } from '@
|
|
12
|
+
import type * as acp from '@agentclientprotocol/sdk';
|
|
13
|
+
import type { AgentSideConnection } from '@agentclientprotocol/sdk';
|
|
14
14
|
import type { AcpServeHarnessSource, AcpServeOptions } from './serve-types.js';
|
|
15
15
|
/**
|
|
16
16
|
* The served agent: the protocol surface plus `dispose()`, which cancels
|
package/dist/serve.js
CHANGED
|
@@ -9,8 +9,8 @@
|
|
|
9
9
|
* The adapter maps the protocol onto the harness's existing public surface —
|
|
10
10
|
* `execute`, the streams, `seedSessionHistory`, `abort` — and nothing else.
|
|
11
11
|
*/
|
|
12
|
+
import { PROTOCOL_VERSION, RequestError } from '@agentclientprotocol/sdk';
|
|
12
13
|
import { frameworkCast, NoeticConfigError } from '@noetic-tools/types';
|
|
13
|
-
import { PROTOCOL_VERSION, RequestError } from '@zed-industries/agent-client-protocol';
|
|
14
14
|
import { clientFsAdapter, clientShellAdapter } from './client-adapters.js';
|
|
15
15
|
import { contentBlockText } from './items.js';
|
|
16
16
|
import { isAbsolutePath } from './paths.js';
|
package/dist/server.js
CHANGED
|
@@ -17,8 +17,8 @@
|
|
|
17
17
|
* ```
|
|
18
18
|
*/
|
|
19
19
|
import { Readable, Writable } from 'node:stream';
|
|
20
|
+
import { AgentSideConnection, ndJsonStream } from '@agentclientprotocol/sdk';
|
|
20
21
|
import { frameworkCast } from '@noetic-tools/types';
|
|
21
|
-
import { AgentSideConnection, ndJsonStream } from '@zed-industries/agent-client-protocol';
|
|
22
22
|
import { toAcpAgent } from './serve.js';
|
|
23
23
|
/**
|
|
24
24
|
* Serve a harness as an ACP agent over the current process's stdio. `await`
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Stopping a stdio agent's whole process tree.
|
|
3
|
+
*
|
|
4
|
+
* Agents are often launched through a wrapper (`npx`, a Node launcher that
|
|
5
|
+
* `spawnSync`s a native binary), so killing the immediate child leaves the
|
|
6
|
+
* real agent running with our pipes inherited — and the host never exits. The
|
|
7
|
+
* transport therefore starts each agent as the leader of its own process group
|
|
8
|
+
* and stops the group: SIGTERM, a grace period, then SIGKILL. On Windows the
|
|
9
|
+
* tree is stopped with `taskkill /T /F`.
|
|
10
|
+
*/
|
|
11
|
+
import type { ChildProcess } from 'node:child_process';
|
|
12
|
+
/** @public How long a group has to exit after SIGTERM before it is killed. */
|
|
13
|
+
export declare const TERM_GRACE_MS = 2000;
|
|
14
|
+
/**
|
|
15
|
+
* Kill `child`'s process group when this process exits normally (`exit`), for
|
|
16
|
+
* a host whose agents must not outlive it. A host killed by a signal cannot
|
|
17
|
+
* run this; a child it started directly then sees its stdin close. Returns a
|
|
18
|
+
* function that forgets the child.
|
|
19
|
+
*/
|
|
20
|
+
export declare function stopWithHost(child: ChildProcess): () => void;
|
|
21
|
+
/** @public Options for {@link stopProcessTree}. */
|
|
22
|
+
export interface StopProcessTreeOptions {
|
|
23
|
+
/** Grace period between SIGTERM and SIGKILL. Default {@link TERM_GRACE_MS}. */
|
|
24
|
+
graceMs?: number;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Stop the child's process group (POSIX) or process tree (Windows): end its
|
|
28
|
+
* stdin, SIGTERM, up to `graceMs` for it to exit, then SIGKILL. Then release
|
|
29
|
+
* our ends of the pipes, which a descendant that left the group (`setsid`)
|
|
30
|
+
* may still hold — such a descendant must manage its own lifetime. Bounded
|
|
31
|
+
* throughout, so an uncooperative child cannot hang the host.
|
|
32
|
+
*
|
|
33
|
+
* For a host that spawns its own agent process (a sandbox-wrapped command, a
|
|
34
|
+
* transport that rewrites lines): spawn it with `detached: true` on POSIX so it
|
|
35
|
+
* leads its own group, and call this from the transport's `close()`.
|
|
36
|
+
* @public
|
|
37
|
+
*/
|
|
38
|
+
export declare function stopProcessTree(child: ChildProcess, opts?: StopProcessTreeOptions): Promise<void>;
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Stopping a stdio agent's whole process tree.
|
|
3
|
+
*
|
|
4
|
+
* Agents are often launched through a wrapper (`npx`, a Node launcher that
|
|
5
|
+
* `spawnSync`s a native binary), so killing the immediate child leaves the
|
|
6
|
+
* real agent running with our pipes inherited — and the host never exits. The
|
|
7
|
+
* transport therefore starts each agent as the leader of its own process group
|
|
8
|
+
* and stops the group: SIGTERM, a grace period, then SIGKILL. On Windows the
|
|
9
|
+
* tree is stopped with `taskkill /T /F`.
|
|
10
|
+
*/
|
|
11
|
+
import { spawn } from 'node:child_process';
|
|
12
|
+
//#region Constants
|
|
13
|
+
/** @public How long a group has to exit after SIGTERM before it is killed. */
|
|
14
|
+
export const TERM_GRACE_MS = 2e3;
|
|
15
|
+
/** How long to wait for the group to vanish after SIGKILL, and for taskkill. */
|
|
16
|
+
const KILL_WAIT_MS = 1e3;
|
|
17
|
+
const POLL_MS = 20;
|
|
18
|
+
//#endregion
|
|
19
|
+
//#region Helpers
|
|
20
|
+
function wait(ms) {
|
|
21
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
22
|
+
}
|
|
23
|
+
function exited(child) {
|
|
24
|
+
return child.exitCode !== null || child.signalCode !== null;
|
|
25
|
+
}
|
|
26
|
+
/** Wait (bounded) for the child itself to exit and be reaped. */
|
|
27
|
+
function waitForExit(child, ms) {
|
|
28
|
+
if (exited(child)) {
|
|
29
|
+
return Promise.resolve();
|
|
30
|
+
}
|
|
31
|
+
return new Promise((resolve) => {
|
|
32
|
+
const done = () => {
|
|
33
|
+
clearTimeout(timer);
|
|
34
|
+
child.removeListener('exit', done);
|
|
35
|
+
resolve();
|
|
36
|
+
};
|
|
37
|
+
const timer = setTimeout(done, ms);
|
|
38
|
+
child.once('exit', done);
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
function signalGroup(pid, signal) {
|
|
42
|
+
try {
|
|
43
|
+
process.kill(-pid, signal);
|
|
44
|
+
return 'sent';
|
|
45
|
+
}
|
|
46
|
+
catch (error) {
|
|
47
|
+
if (!(error instanceof Error) || !('code' in error)) {
|
|
48
|
+
throw error;
|
|
49
|
+
}
|
|
50
|
+
if (error.code === 'ESRCH') {
|
|
51
|
+
return 'gone';
|
|
52
|
+
}
|
|
53
|
+
if (error.code === 'EPERM') {
|
|
54
|
+
return 'zombie';
|
|
55
|
+
}
|
|
56
|
+
throw error;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/** Poll until the group is gone or `ms` passes. True when it is gone. */
|
|
60
|
+
async function waitForGroup(pid, ms) {
|
|
61
|
+
const deadline = Date.now() + ms;
|
|
62
|
+
while (signalGroup(pid, 0) !== 'gone') {
|
|
63
|
+
if (Date.now() >= deadline) {
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
await wait(POLL_MS);
|
|
67
|
+
}
|
|
68
|
+
return true;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Signal the group, reaping an exited leader first when the group refuses
|
|
72
|
+
* signals. False when there is nothing left to signal.
|
|
73
|
+
*/
|
|
74
|
+
async function signalLiveGroup(child, pid, signal) {
|
|
75
|
+
const first = signalGroup(pid, signal);
|
|
76
|
+
if (first !== 'zombie') {
|
|
77
|
+
return first === 'sent' || signalChild(child, signal);
|
|
78
|
+
}
|
|
79
|
+
await waitForExit(child, KILL_WAIT_MS);
|
|
80
|
+
// Still refused once the leader is reaped: no member we may signal remains.
|
|
81
|
+
return signalGroup(pid, signal) === 'sent';
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* A child that was not started as a group leader has no group to signal; stop
|
|
85
|
+
* the child itself rather than leave it running.
|
|
86
|
+
*/
|
|
87
|
+
function signalChild(child, signal) {
|
|
88
|
+
if (exited(child)) {
|
|
89
|
+
return false;
|
|
90
|
+
}
|
|
91
|
+
return child.kill(signal);
|
|
92
|
+
}
|
|
93
|
+
function killWindowsTree(pid) {
|
|
94
|
+
return new Promise((resolve, reject) => {
|
|
95
|
+
const killer = spawn('taskkill', [
|
|
96
|
+
'/pid',
|
|
97
|
+
String(pid),
|
|
98
|
+
'/T',
|
|
99
|
+
'/F',
|
|
100
|
+
], {
|
|
101
|
+
windowsHide: true,
|
|
102
|
+
stdio: 'ignore',
|
|
103
|
+
});
|
|
104
|
+
const timer = setTimeout(() => {
|
|
105
|
+
killer.kill();
|
|
106
|
+
reject(new Error('Timed out stopping the ACP process tree.'));
|
|
107
|
+
}, KILL_WAIT_MS);
|
|
108
|
+
killer.once('error', (error) => {
|
|
109
|
+
clearTimeout(timer);
|
|
110
|
+
reject(error);
|
|
111
|
+
});
|
|
112
|
+
killer.once('exit', (code) => {
|
|
113
|
+
clearTimeout(timer);
|
|
114
|
+
// 128: no such process — the tree had already exited.
|
|
115
|
+
if (code !== 0 && code !== 128) {
|
|
116
|
+
reject(new Error(`taskkill failed with exit code ${code}.`));
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
resolve();
|
|
120
|
+
});
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
//#endregion
|
|
124
|
+
//#region Host exit
|
|
125
|
+
/** Children to kill when this process exits, for hosts that asked to stop them. */
|
|
126
|
+
const stopOnExit = new Set();
|
|
127
|
+
let exitHookInstalled = false;
|
|
128
|
+
function killOnExit() {
|
|
129
|
+
for (const child of stopOnExit) {
|
|
130
|
+
const pid = child.pid;
|
|
131
|
+
if (!pid || exited(child)) {
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
try {
|
|
135
|
+
// Synchronous on purpose: nothing asynchronous runs during 'exit'.
|
|
136
|
+
process.kill(process.platform === 'win32' ? pid : -pid, 'SIGKILL');
|
|
137
|
+
}
|
|
138
|
+
catch {
|
|
139
|
+
// Already gone.
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Kill `child`'s process group when this process exits normally (`exit`), for
|
|
145
|
+
* a host whose agents must not outlive it. A host killed by a signal cannot
|
|
146
|
+
* run this; a child it started directly then sees its stdin close. Returns a
|
|
147
|
+
* function that forgets the child.
|
|
148
|
+
*/
|
|
149
|
+
export function stopWithHost(child) {
|
|
150
|
+
if (!exitHookInstalled) {
|
|
151
|
+
exitHookInstalled = true;
|
|
152
|
+
process.on('exit', killOnExit);
|
|
153
|
+
}
|
|
154
|
+
stopOnExit.add(child);
|
|
155
|
+
child.once('exit', () => stopOnExit.delete(child));
|
|
156
|
+
return () => {
|
|
157
|
+
stopOnExit.delete(child);
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Stop the child's process group (POSIX) or process tree (Windows): end its
|
|
162
|
+
* stdin, SIGTERM, up to `graceMs` for it to exit, then SIGKILL. Then release
|
|
163
|
+
* our ends of the pipes, which a descendant that left the group (`setsid`)
|
|
164
|
+
* may still hold — such a descendant must manage its own lifetime. Bounded
|
|
165
|
+
* throughout, so an uncooperative child cannot hang the host.
|
|
166
|
+
*
|
|
167
|
+
* For a host that spawns its own agent process (a sandbox-wrapped command, a
|
|
168
|
+
* transport that rewrites lines): spawn it with `detached: true` on POSIX so it
|
|
169
|
+
* leads its own group, and call this from the transport's `close()`.
|
|
170
|
+
* @public
|
|
171
|
+
*/
|
|
172
|
+
export async function stopProcessTree(child, opts = {}) {
|
|
173
|
+
try {
|
|
174
|
+
await signalTree(child, opts.graceMs ?? TERM_GRACE_MS);
|
|
175
|
+
}
|
|
176
|
+
finally {
|
|
177
|
+
child.stdin?.destroy();
|
|
178
|
+
child.stdout?.destroy();
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
async function signalTree(child, graceMs) {
|
|
182
|
+
const pid = child.pid;
|
|
183
|
+
// Reap a leader whose stdout already ended before signalling its group:
|
|
184
|
+
// macOS can refuse signals to a group whose last member is a zombie.
|
|
185
|
+
if (child.stdout?.readableEnded) {
|
|
186
|
+
await waitForExit(child, POLL_MS * 10);
|
|
187
|
+
}
|
|
188
|
+
child.stdin?.end();
|
|
189
|
+
if (!pid || pid <= 0) {
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
if (process.platform === 'win32') {
|
|
193
|
+
// Even when the child itself exited, its descendants may not have:
|
|
194
|
+
// taskkill answers 128 when there is nothing left.
|
|
195
|
+
await killWindowsTree(pid);
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
if (!(await signalLiveGroup(child, pid, 'SIGTERM'))) {
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
const groupGone = await waitForGroup(pid, graceMs);
|
|
202
|
+
// A child that is not a group leader has no group to watch: it gets the
|
|
203
|
+
// kill wait as its grace period.
|
|
204
|
+
await waitForExit(child, groupGone ? KILL_WAIT_MS : 0);
|
|
205
|
+
if (groupGone && exited(child)) {
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
await signalLiveGroup(child, pid, 'SIGKILL');
|
|
209
|
+
await Promise.all([
|
|
210
|
+
waitForExit(child, KILL_WAIT_MS),
|
|
211
|
+
waitForGroup(pid, KILL_WAIT_MS),
|
|
212
|
+
]);
|
|
213
|
+
}
|
|
214
|
+
//#endregion
|
package/dist/stdio.d.ts
CHANGED
|
@@ -8,6 +8,8 @@
|
|
|
8
8
|
* keeping the dependency off the main graph.
|
|
9
9
|
*/
|
|
10
10
|
import type { AcpMachineFactory, AcpTransportFactory } from '@noetic-tools/types';
|
|
11
|
+
export type { StopProcessTreeOptions } from './stdio-process.js';
|
|
12
|
+
export { stopProcessTree, TERM_GRACE_MS } from './stdio-process.js';
|
|
11
13
|
/** @public How to launch an ACP agent as a child process. */
|
|
12
14
|
export interface StdioAgentSpec {
|
|
13
15
|
/** Identifier used in error messages. */
|
|
@@ -21,15 +23,35 @@ export interface StdioAgentSpec {
|
|
|
21
23
|
/**
|
|
22
24
|
* Build a transport factory that spawns `spec.command` and speaks ACP over its
|
|
23
25
|
* stdin/stdout. The child's stderr is inherited so agent diagnostics reach the
|
|
24
|
-
* host's logs instead of vanishing.
|
|
26
|
+
* host's logs instead of vanishing. Closing the transport (or aborting its
|
|
27
|
+
* signal) closes the pipes and stops the agent's whole process group —
|
|
28
|
+
* SIGTERM, a grace period, then SIGKILL; on Windows, its process tree. Close
|
|
29
|
+
* is idempotent: every call shares one shutdown.
|
|
25
30
|
* @public
|
|
26
31
|
*/
|
|
27
32
|
export declare function stdioAcpTransport(spec: StdioAgentSpec): AcpTransportFactory;
|
|
33
|
+
/** @public Options for {@link localMachine}. */
|
|
34
|
+
export interface LocalMachineOptions {
|
|
35
|
+
/**
|
|
36
|
+
* Run the agent through a keeper, so it can outlive this host and a later
|
|
37
|
+
* host can reattach to it (`AcpTransport.reattach`). Default `true`. Without
|
|
38
|
+
* one — or where no keeper script is on disk, as in a single-file bundle —
|
|
39
|
+
* the agent is a child process that ends with its host.
|
|
40
|
+
*/
|
|
41
|
+
keeper?: boolean;
|
|
42
|
+
/**
|
|
43
|
+
* How long a kept agent may run with no host attached before its keeper
|
|
44
|
+
* stops it. Default `0`: no limit — it runs until a host reattaches and
|
|
45
|
+
* closes it, or it exits.
|
|
46
|
+
*/
|
|
47
|
+
detachedTimeoutMs?: number;
|
|
48
|
+
}
|
|
28
49
|
/**
|
|
29
|
-
* This machine: the
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
50
|
+
* This machine: the agent runs through a keeper (see
|
|
51
|
+
* {@link LocalMachineOptions.keeper}), which also serves the tool bridge to it
|
|
52
|
+
* on a port that outlives the host; an MCP server beside it is a child
|
|
53
|
+
* process. The agent gets this process's environment; an MCP server, as the
|
|
54
|
+
* MCP SDK starts one, only `serverEnv`'s short list.
|
|
33
55
|
* @public
|
|
34
56
|
*/
|
|
35
|
-
export declare function localMachine(agentId?: string): AcpMachineFactory;
|
|
57
|
+
export declare function localMachine(agentId?: string, options?: LocalMachineOptions): AcpMachineFactory;
|