@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.
- package/dist/agents.d.ts +5 -0
- package/dist/agents.js +13 -1
- package/dist/bin.js +19 -2
- package/dist/client-adapters.d.ts +2 -2
- package/dist/client.d.ts +9 -2
- package/dist/client.js +40 -1
- package/dist/connection.d.ts +25 -2
- package/dist/connection.js +455 -36
- package/dist/define.d.ts +13 -0
- package/dist/define.js +122 -4
- package/dist/index.d.ts +1 -1
- package/dist/items.d.ts +1 -1
- package/dist/keeper/client.d.ts +93 -0
- package/dist/keeper/client.js +468 -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 +425 -0
- package/dist/keeper/protocol.d.ts +74 -0
- package/dist/keeper/protocol.js +108 -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-events.d.ts +2 -0
- package/dist/serve-events.js +1 -0
- package/dist/serve-questions.d.ts +26 -0
- package/dist/serve-questions.js +105 -0
- package/dist/serve-types.d.ts +1 -1
- package/dist/serve.d.ts +2 -2
- package/dist/serve.js +10 -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 +50 -7
- package/dist/stdio.js +192 -52
- 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 +38 -0
- package/dist/update-filter.js +193 -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-events.d.ts
CHANGED
|
@@ -39,6 +39,8 @@ export interface PumpTurnParams {
|
|
|
39
39
|
present(toolName: string, callId: string, args: unknown): ServeToolCallPresentation;
|
|
40
40
|
/** Whether `session/cancel` was received for this session. */
|
|
41
41
|
cancelRequested(): boolean;
|
|
42
|
+
/** Sees every event of the turn as it is pumped. */
|
|
43
|
+
observe?: (event: StreamEvent) => void;
|
|
42
44
|
}
|
|
43
45
|
/**
|
|
44
46
|
* Consume the harness event stream for one prompt turn, translating to
|
package/dist/serve-events.js
CHANGED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Questions a served run holds for a person (spec 31, spec 27 § Questions the
|
|
3
|
+
* agent asks): the editor driving the run is the person's side of the wire, so
|
|
4
|
+
* each held question is put to it as `elicitation/create` when it can show
|
|
5
|
+
* forms, and declined at once when it cannot — a served turn never waits on
|
|
6
|
+
* nobody.
|
|
7
|
+
*/
|
|
8
|
+
import type * as acp from '@agentclientprotocol/sdk';
|
|
9
|
+
import type { AgentSideConnection } from '@agentclientprotocol/sdk';
|
|
10
|
+
import type { StreamEvent } from '@noetic-tools/types';
|
|
11
|
+
import type { AcpServeHarness } from './serve-types.js';
|
|
12
|
+
/** What forwarding a served session's questions needs. */
|
|
13
|
+
export interface ServedQuestionsOptions {
|
|
14
|
+
conn: AgentSideConnection;
|
|
15
|
+
harness: AcpServeHarness;
|
|
16
|
+
sessionId: string;
|
|
17
|
+
/** What the editor advertised in `initialize`. */
|
|
18
|
+
capabilities: acp.ClientCapabilities | undefined;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Answer each question a served turn holds, as its events are pumped: through
|
|
22
|
+
* the editor when it advertised form elicitation, else by declining it. A
|
|
23
|
+
* question the editor's answer no longer fits stays held, as any refused
|
|
24
|
+
* answer does.
|
|
25
|
+
*/
|
|
26
|
+
export declare function servedQuestionAnswerer(opts: ServedQuestionsOptions): (event: StreamEvent) => void;
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Questions a served run holds for a person (spec 31, spec 27 § Questions the
|
|
3
|
+
* agent asks): the editor driving the run is the person's side of the wire, so
|
|
4
|
+
* each held question is put to it as `elicitation/create` when it can show
|
|
5
|
+
* forms, and declined at once when it cannot — a served turn never waits on
|
|
6
|
+
* nobody.
|
|
7
|
+
*/
|
|
8
|
+
import { DECISION_ITEM_TYPE, readHeldCallEvent } from '@noetic-tools/types';
|
|
9
|
+
//#endregion
|
|
10
|
+
//#region Helpers
|
|
11
|
+
function isRecord(value) {
|
|
12
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
13
|
+
}
|
|
14
|
+
function decline(call) {
|
|
15
|
+
return {
|
|
16
|
+
type: DECISION_ITEM_TYPE,
|
|
17
|
+
callId: call.callId,
|
|
18
|
+
argsHash: call.argsHash,
|
|
19
|
+
action: 'deny',
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
/** The editor's answer as a decision, or undefined when it cancelled. */
|
|
23
|
+
function decisionOf(call, answer) {
|
|
24
|
+
if (answer.action === 'accept') {
|
|
25
|
+
return {
|
|
26
|
+
type: DECISION_ITEM_TYPE,
|
|
27
|
+
callId: call.callId,
|
|
28
|
+
argsHash: call.argsHash,
|
|
29
|
+
output: answer.content ?? {},
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
if (answer.action === 'decline') {
|
|
33
|
+
return decline(call);
|
|
34
|
+
}
|
|
35
|
+
return undefined;
|
|
36
|
+
}
|
|
37
|
+
/** Put one held question to the editor, or decline it when the editor cannot show it. */
|
|
38
|
+
async function answerQuestion(opts, call) {
|
|
39
|
+
const question = call.question;
|
|
40
|
+
const schema = question?.schema;
|
|
41
|
+
const canAsk = opts.capabilities?.elicitation?.form !== undefined &&
|
|
42
|
+
opts.capabilities?.elicitation?.form !== null;
|
|
43
|
+
if (!question || !isRecord(schema) || !canAsk) {
|
|
44
|
+
await settle(opts, decline(call));
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
// An editor that fails the request (method not found, a dropped wire) has
|
|
48
|
+
// not answered: decline, so the turn never waits on it.
|
|
49
|
+
const answer = await opts.conn
|
|
50
|
+
.createElicitation({
|
|
51
|
+
mode: 'form',
|
|
52
|
+
sessionId: opts.sessionId,
|
|
53
|
+
message: question.message,
|
|
54
|
+
requestedSchema: {
|
|
55
|
+
type: 'object',
|
|
56
|
+
properties: isRecord(schema.properties) ? schema.properties : {},
|
|
57
|
+
...(Array.isArray(schema.required)
|
|
58
|
+
? {
|
|
59
|
+
required: schema.required.filter((name) => typeof name === 'string'),
|
|
60
|
+
}
|
|
61
|
+
: {}),
|
|
62
|
+
},
|
|
63
|
+
})
|
|
64
|
+
.catch(() => undefined);
|
|
65
|
+
if (!answer) {
|
|
66
|
+
await settle(opts, decline(call));
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
const decision = decisionOf(call, answer);
|
|
70
|
+
if (!decision) {
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
// An answer the question refuses (it does not fit the form) declines it.
|
|
74
|
+
await opts.harness
|
|
75
|
+
.execute(decision, {
|
|
76
|
+
threadId: opts.sessionId,
|
|
77
|
+
})
|
|
78
|
+
.catch(() => settle(opts, decline(call)));
|
|
79
|
+
}
|
|
80
|
+
/** Give a decision; one the run no longer takes (the turn moved on) is dropped. */
|
|
81
|
+
async function settle(opts, decision) {
|
|
82
|
+
await opts.harness
|
|
83
|
+
.execute(decision, {
|
|
84
|
+
threadId: opts.sessionId,
|
|
85
|
+
})
|
|
86
|
+
.catch(() => undefined);
|
|
87
|
+
}
|
|
88
|
+
//#endregion
|
|
89
|
+
//#region Public API
|
|
90
|
+
/**
|
|
91
|
+
* Answer each question a served turn holds, as its events are pumped: through
|
|
92
|
+
* the editor when it advertised form elicitation, else by declining it. A
|
|
93
|
+
* question the editor's answer no longer fits stays held, as any refused
|
|
94
|
+
* answer does.
|
|
95
|
+
*/
|
|
96
|
+
export function servedQuestionAnswerer(opts) {
|
|
97
|
+
return (event) => {
|
|
98
|
+
const read = readHeldCallEvent(event);
|
|
99
|
+
if (read?.type !== 'held' || read.call.reason !== 'question') {
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
void answerQuestion(opts, read.call).catch(() => undefined);
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
//#endregion
|
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,13 +9,14 @@
|
|
|
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';
|
|
17
17
|
import { pumpTurnEvents } from './serve-events.js';
|
|
18
18
|
import { createServePermissionLayer, evaluateServePolicy, ServePermissionBroker, } from './serve-permissions.js';
|
|
19
|
+
import { servedQuestionAnswerer } from './serve-questions.js';
|
|
19
20
|
/**
|
|
20
21
|
* A kind-based permission rule resolves kinds through `options.tools`; with
|
|
21
22
|
* no tools declared it silently matches nothing and the policy default
|
|
@@ -314,6 +315,13 @@ class ServeAgent {
|
|
|
314
315
|
// execute(), and the session broadcaster discards events whenever a
|
|
315
316
|
// previously-consumed stream has no live consumer.
|
|
316
317
|
const events = attachEvents(session.harness, session.sessionId);
|
|
318
|
+
// A question the run holds for a person goes to the editor, or is declined.
|
|
319
|
+
const answerQuestions = servedQuestionAnswerer({
|
|
320
|
+
conn: this.conn,
|
|
321
|
+
harness: session.harness,
|
|
322
|
+
sessionId: session.sessionId,
|
|
323
|
+
capabilities: this.clientCapabilities,
|
|
324
|
+
});
|
|
317
325
|
const messageId = crypto.randomUUID();
|
|
318
326
|
try {
|
|
319
327
|
await session.harness.execute(input, {
|
|
@@ -336,6 +344,7 @@ class ServeAgent {
|
|
|
336
344
|
}),
|
|
337
345
|
present: this.presenter.present,
|
|
338
346
|
cancelRequested: () => session.cancelRequested,
|
|
347
|
+
observe: answerQuestions,
|
|
339
348
|
});
|
|
340
349
|
if (outcome.kind === 'error') {
|
|
341
350
|
throw RequestError.internalError({
|
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
|