@noetic-tools/acp 1.0.0 → 1.1.1
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/client-adapters.d.ts +46 -0
- package/dist/client-adapters.js +216 -0
- package/dist/index.d.ts +24 -0
- package/dist/index.js +16 -0
- package/dist/serve-events.d.ts +48 -0
- package/dist/serve-events.js +310 -0
- package/dist/serve-permissions.d.ts +55 -0
- package/dist/serve-permissions.js +180 -0
- package/dist/serve-types.d.ts +162 -0
- package/dist/serve-types.js +9 -0
- package/dist/serve.d.ts +28 -0
- package/dist/serve.js +658 -0
- package/dist/server.d.ts +33 -0
- package/dist/server.js +65 -0
- package/dist/transport-loopback.js +14 -1
- package/package.json +10 -4
package/dist/serve.js
ADDED
|
@@ -0,0 +1,658 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The server direction (spec 31): expose a Noetic harness *as* an ACP agent.
|
|
3
|
+
*
|
|
4
|
+
* `toAcpAgent(harness)` returns the `(conn) => acp.Agent` factory shape that
|
|
5
|
+
* `loopbackTransport()` accepts — so a served harness can be mounted as a
|
|
6
|
+
* sub-agent of another harness, driven by Noetic's own ACP client in tests,
|
|
7
|
+
* or bound to process stdio by `serveAcp()` (`@noetic-tools/acp/server`).
|
|
8
|
+
*
|
|
9
|
+
* The adapter maps the protocol onto the harness's existing public surface —
|
|
10
|
+
* `execute`, the streams, `seedSessionHistory`, `abort` — and nothing else.
|
|
11
|
+
*/
|
|
12
|
+
import { frameworkCast, NoeticConfigError } from '@noetic-tools/types';
|
|
13
|
+
import { PROTOCOL_VERSION, RequestError } from '@zed-industries/agent-client-protocol';
|
|
14
|
+
import { clientFsAdapter, clientShellAdapter } from './client-adapters.js';
|
|
15
|
+
import { contentBlockText } from './items.js';
|
|
16
|
+
import { isAbsolutePath } from './paths.js';
|
|
17
|
+
import { pumpTurnEvents } from './serve-events.js';
|
|
18
|
+
import { createServePermissionLayer, evaluateServePolicy, ServePermissionBroker, } from './serve-permissions.js';
|
|
19
|
+
/**
|
|
20
|
+
* A kind-based permission rule resolves kinds through `options.tools`; with
|
|
21
|
+
* no tools declared it silently matches nothing and the policy default
|
|
22
|
+
* applies — a security policy that does nothing must be a loud config error,
|
|
23
|
+
* not a quiet fallback to `allow`.
|
|
24
|
+
*/
|
|
25
|
+
function assertKindRulesResolvable(options) {
|
|
26
|
+
const rules = options.permissions?.rules ?? [];
|
|
27
|
+
const hasKindOnlyRule = rules.some((rule) => rule.kind !== undefined && rule.tool === undefined);
|
|
28
|
+
if (hasKindOnlyRule && (!options.tools || options.tools.length === 0)) {
|
|
29
|
+
throw new NoeticConfigError({
|
|
30
|
+
code: 'ACP_SERVE_KIND_RULES_WITHOUT_TOOLS',
|
|
31
|
+
message: 'A kind-based permission rule was given without `tools` to resolve kinds from.',
|
|
32
|
+
hint: "Pass the harness's tools to the serve options — serveAcp(harness, { tools, permissions }) — so rules like { kind: 'execute' } can match their tools.",
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
function buildPresenter(options) {
|
|
37
|
+
const declarations = new Map(options.tools?.map((tool) => [
|
|
38
|
+
tool.name,
|
|
39
|
+
tool.acp,
|
|
40
|
+
]));
|
|
41
|
+
const kindOf = (toolName) => declarations.get(toolName)?.kind;
|
|
42
|
+
const titleOf = (toolName, args) => {
|
|
43
|
+
const title = declarations.get(toolName)?.title;
|
|
44
|
+
if (typeof title === 'string') {
|
|
45
|
+
return title;
|
|
46
|
+
}
|
|
47
|
+
if (typeof title === 'function' && args !== undefined) {
|
|
48
|
+
try {
|
|
49
|
+
return title(args);
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
return toolName;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return toolName;
|
|
56
|
+
};
|
|
57
|
+
const locationsOf = (toolName, args) => {
|
|
58
|
+
const locations = declarations.get(toolName)?.locations;
|
|
59
|
+
if (!locations || args === undefined) {
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
62
|
+
try {
|
|
63
|
+
return locations(args).map((path) => ({
|
|
64
|
+
path,
|
|
65
|
+
}));
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
return undefined;
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
const statusOf = (toolName) => {
|
|
72
|
+
if (!options.permissions) {
|
|
73
|
+
return 'in_progress';
|
|
74
|
+
}
|
|
75
|
+
const decision = evaluateServePolicy({
|
|
76
|
+
policy: options.permissions,
|
|
77
|
+
toolName,
|
|
78
|
+
kind: kindOf(toolName),
|
|
79
|
+
});
|
|
80
|
+
return decision === 'ask' ? 'pending' : 'in_progress';
|
|
81
|
+
};
|
|
82
|
+
return {
|
|
83
|
+
kindOf,
|
|
84
|
+
titleOf,
|
|
85
|
+
present: (toolName, _callId, args) => ({
|
|
86
|
+
title: titleOf(toolName, args),
|
|
87
|
+
kind: kindOf(toolName),
|
|
88
|
+
locations: locationsOf(toolName, args),
|
|
89
|
+
status: statusOf(toolName),
|
|
90
|
+
}),
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
//#endregion
|
|
94
|
+
//#region Prompt conversion
|
|
95
|
+
function contentBlocksToItems(prompt) {
|
|
96
|
+
const parts = [];
|
|
97
|
+
for (const block of prompt) {
|
|
98
|
+
if (block.type === 'image') {
|
|
99
|
+
parts.push({
|
|
100
|
+
type: 'input_image',
|
|
101
|
+
imageUrl: block.uri ?? `data:${block.mimeType};base64,${block.data}`,
|
|
102
|
+
});
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
const text = contentBlockText(block);
|
|
106
|
+
if (text.length > 0) {
|
|
107
|
+
parts.push({
|
|
108
|
+
type: 'input_text',
|
|
109
|
+
text,
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
if (parts.length === 0) {
|
|
114
|
+
return [];
|
|
115
|
+
}
|
|
116
|
+
return [
|
|
117
|
+
userMessageItem(parts),
|
|
118
|
+
];
|
|
119
|
+
}
|
|
120
|
+
function userMessageItem(parts) {
|
|
121
|
+
return frameworkCast({
|
|
122
|
+
id: `acp-user-${crypto.randomUUID()}`,
|
|
123
|
+
type: 'message',
|
|
124
|
+
role: 'user',
|
|
125
|
+
status: 'completed',
|
|
126
|
+
content: parts,
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
function textInput(text) {
|
|
130
|
+
return [
|
|
131
|
+
userMessageItem([
|
|
132
|
+
{
|
|
133
|
+
type: 'input_text',
|
|
134
|
+
text,
|
|
135
|
+
},
|
|
136
|
+
]),
|
|
137
|
+
];
|
|
138
|
+
}
|
|
139
|
+
//#endregion
|
|
140
|
+
//#region History replay
|
|
141
|
+
/** Replay stored items to the client, the `session/load` contract. */
|
|
142
|
+
function replayUpdates(items) {
|
|
143
|
+
const updates = [];
|
|
144
|
+
for (const item of items) {
|
|
145
|
+
const record = frameworkCast(item);
|
|
146
|
+
if (record.type === 'message') {
|
|
147
|
+
const text = messageText(record);
|
|
148
|
+
if (text.length === 0) {
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
updates.push({
|
|
152
|
+
sessionUpdate: record.role === 'assistant' ? 'agent_message_chunk' : 'user_message_chunk',
|
|
153
|
+
content: {
|
|
154
|
+
type: 'text',
|
|
155
|
+
text,
|
|
156
|
+
},
|
|
157
|
+
});
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
if (record.type === 'function_call' && typeof record.callId === 'string') {
|
|
161
|
+
updates.push({
|
|
162
|
+
sessionUpdate: 'tool_call',
|
|
163
|
+
toolCallId: record.callId,
|
|
164
|
+
title: typeof record.name === 'string' ? record.name : record.callId,
|
|
165
|
+
status: 'completed',
|
|
166
|
+
});
|
|
167
|
+
continue;
|
|
168
|
+
}
|
|
169
|
+
if (record.type === 'function_call_output' && typeof record.callId === 'string') {
|
|
170
|
+
updates.push({
|
|
171
|
+
sessionUpdate: 'tool_call_update',
|
|
172
|
+
toolCallId: record.callId,
|
|
173
|
+
status: record.status === 'failed' ? 'failed' : 'completed',
|
|
174
|
+
content: [
|
|
175
|
+
{
|
|
176
|
+
type: 'content',
|
|
177
|
+
content: {
|
|
178
|
+
type: 'text',
|
|
179
|
+
text: typeof record.output === 'string' ? record.output : JSON.stringify(record.output),
|
|
180
|
+
},
|
|
181
|
+
},
|
|
182
|
+
],
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
return updates;
|
|
187
|
+
}
|
|
188
|
+
function messageText(record) {
|
|
189
|
+
if (!Array.isArray(record.content)) {
|
|
190
|
+
return '';
|
|
191
|
+
}
|
|
192
|
+
const texts = [];
|
|
193
|
+
for (const part of record.content) {
|
|
194
|
+
if (typeof part !== 'object' || part === null) {
|
|
195
|
+
continue;
|
|
196
|
+
}
|
|
197
|
+
const text = frameworkCast(part).text;
|
|
198
|
+
if (typeof text === 'string') {
|
|
199
|
+
texts.push(text);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
return texts.join('');
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Adapt a harness (or per-session factory) into an ACP `Agent` factory — the
|
|
206
|
+
* exact shape `loopbackTransport()` and `AgentSideConnection` accept.
|
|
207
|
+
* @public
|
|
208
|
+
*/
|
|
209
|
+
export function toAcpAgent(source, options = {}) {
|
|
210
|
+
return (conn) => new ServeAgent(conn, source, options);
|
|
211
|
+
}
|
|
212
|
+
class ServeAgent {
|
|
213
|
+
conn;
|
|
214
|
+
source;
|
|
215
|
+
options;
|
|
216
|
+
sessions = new Map();
|
|
217
|
+
presenter;
|
|
218
|
+
broker;
|
|
219
|
+
clientCapabilities;
|
|
220
|
+
constructor(conn, source, options) {
|
|
221
|
+
this.conn = conn;
|
|
222
|
+
this.source = source;
|
|
223
|
+
this.options = options;
|
|
224
|
+
assertKindRulesResolvable(options);
|
|
225
|
+
this.presenter = buildPresenter(options);
|
|
226
|
+
const onPermissionRequest = options.onPermissionRequest;
|
|
227
|
+
const forward = onPermissionRequest
|
|
228
|
+
? (prompt) => onPermissionRequest(prompt)
|
|
229
|
+
: this.forwardPermissionToWire.bind(this);
|
|
230
|
+
// The grant→in_progress transition belongs to the broker wrapper, not one
|
|
231
|
+
// forwarder: the gated tool_call went out as `pending`, and it must move
|
|
232
|
+
// whether the wire client or an in-process host answered the ask.
|
|
233
|
+
this.broker = new ServePermissionBroker(async (prompt) => {
|
|
234
|
+
const reply = await forward(prompt);
|
|
235
|
+
if (reply.decision === 'allow') {
|
|
236
|
+
this.sendGrantProgress(prompt);
|
|
237
|
+
}
|
|
238
|
+
return reply;
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
//#region Protocol methods
|
|
242
|
+
async initialize(params) {
|
|
243
|
+
this.clientCapabilities = params.clientCapabilities;
|
|
244
|
+
return {
|
|
245
|
+
// One supported revision: answer it whatever the client requested (the
|
|
246
|
+
// protocol says respond with the latest supported version otherwise).
|
|
247
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
248
|
+
agentCapabilities: {
|
|
249
|
+
loadSession: this.options.history !== undefined,
|
|
250
|
+
promptCapabilities: {
|
|
251
|
+
image: true,
|
|
252
|
+
embeddedContext: true,
|
|
253
|
+
},
|
|
254
|
+
},
|
|
255
|
+
authMethods: [],
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
async authenticate() {
|
|
259
|
+
return {};
|
|
260
|
+
}
|
|
261
|
+
async newSession(params) {
|
|
262
|
+
const session = await this.openSession(crypto.randomUUID(), params.cwd, params.mcpServers);
|
|
263
|
+
this.advertiseCommands(session.sessionId);
|
|
264
|
+
return {
|
|
265
|
+
sessionId: session.sessionId,
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
async loadSession(params) {
|
|
269
|
+
const history = this.options.history;
|
|
270
|
+
if (!history) {
|
|
271
|
+
throw RequestError.methodNotFound('session/load');
|
|
272
|
+
}
|
|
273
|
+
if (this.sessions.has(params.sessionId)) {
|
|
274
|
+
// Reloading a LIVE session would clobber its entry while its pumps keep
|
|
275
|
+
// running against the old one; the protocol has no reason to do this.
|
|
276
|
+
throw RequestError.invalidParams({
|
|
277
|
+
message: `session is already active: ${params.sessionId}`,
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
const items = await history.load(params.sessionId);
|
|
281
|
+
if (items === null) {
|
|
282
|
+
throw RequestError.invalidParams({
|
|
283
|
+
message: `unknown session: ${params.sessionId}`,
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
const session = await this.openSession(params.sessionId, params.cwd, params.mcpServers);
|
|
287
|
+
session.harness.seedSessionHistory(session.sessionId, items);
|
|
288
|
+
for (const item of items) {
|
|
289
|
+
const id = itemId(item);
|
|
290
|
+
if (id) {
|
|
291
|
+
session.persistedIds.add(id);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
for (const update of replayUpdates(items)) {
|
|
295
|
+
await this.conn.sessionUpdate({
|
|
296
|
+
sessionId: session.sessionId,
|
|
297
|
+
update,
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
this.advertiseCommands(session.sessionId);
|
|
301
|
+
return {};
|
|
302
|
+
}
|
|
303
|
+
async prompt(params) {
|
|
304
|
+
const session = this.requireSession(params.sessionId);
|
|
305
|
+
const input = await this.resolveInput(session, params.prompt);
|
|
306
|
+
if (input.length === 0) {
|
|
307
|
+
return {
|
|
308
|
+
stopReason: 'end_turn',
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
await this.persistItems(session, input);
|
|
312
|
+
this.startSavePump(session);
|
|
313
|
+
// Attach BEFORE execute(): `turn_started` is emitted synchronously inside
|
|
314
|
+
// execute(), and the session broadcaster discards events whenever a
|
|
315
|
+
// previously-consumed stream has no live consumer.
|
|
316
|
+
const events = attachEvents(session.harness, session.sessionId);
|
|
317
|
+
const messageId = crypto.randomUUID();
|
|
318
|
+
try {
|
|
319
|
+
await session.harness.execute(input, {
|
|
320
|
+
threadId: session.sessionId,
|
|
321
|
+
messageId,
|
|
322
|
+
// ADDITIVE: the gate joins the harness's own layers; the override
|
|
323
|
+
// option would silently delete instructions/history/steering.
|
|
324
|
+
extraContextLayers: session.gateLayer
|
|
325
|
+
? [
|
|
326
|
+
session.gateLayer,
|
|
327
|
+
]
|
|
328
|
+
: undefined,
|
|
329
|
+
});
|
|
330
|
+
const outcome = await pumpTurnEvents({
|
|
331
|
+
events,
|
|
332
|
+
messageId,
|
|
333
|
+
notify: (update) => this.conn.sessionUpdate({
|
|
334
|
+
sessionId: session.sessionId,
|
|
335
|
+
update,
|
|
336
|
+
}),
|
|
337
|
+
present: this.presenter.present,
|
|
338
|
+
cancelRequested: () => session.cancelRequested,
|
|
339
|
+
});
|
|
340
|
+
if (outcome.kind === 'error') {
|
|
341
|
+
throw RequestError.internalError({
|
|
342
|
+
message: outcome.message,
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
return {
|
|
346
|
+
stopReason: outcome.stopReason,
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
finally {
|
|
350
|
+
// Release the broadcaster consumer even when execute() rejects before
|
|
351
|
+
// the pump runs — a leaked live iterator would suppress the discard
|
|
352
|
+
// rule for every later turn on this session.
|
|
353
|
+
await events.close();
|
|
354
|
+
// The flag is NOT reset at prompt start: a fast follow-up prompt must
|
|
355
|
+
// not erase an in-flight turn's cancellation. It is turn-scoped by
|
|
356
|
+
// resetting here, once this turn's outcome is decided.
|
|
357
|
+
session.cancelRequested = false;
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
async cancel(params) {
|
|
361
|
+
const session = this.sessions.get(params.sessionId);
|
|
362
|
+
if (!session) {
|
|
363
|
+
return;
|
|
364
|
+
}
|
|
365
|
+
session.cancelRequested = true;
|
|
366
|
+
this.broker.cancelSession(session.sessionId);
|
|
367
|
+
await session.harness.abort({
|
|
368
|
+
threadId: session.sessionId,
|
|
369
|
+
reason: 'cancelled',
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
/** Cancel every live session — the transport-shutdown path (`serveAcp().close()`). */
|
|
373
|
+
async dispose() {
|
|
374
|
+
const sessions = [
|
|
375
|
+
...this.sessions.values(),
|
|
376
|
+
];
|
|
377
|
+
this.sessions.clear();
|
|
378
|
+
await Promise.all(sessions.map(async (session) => {
|
|
379
|
+
session.cancelRequested = true;
|
|
380
|
+
this.broker.cancelSession(session.sessionId);
|
|
381
|
+
session.stopSavePump?.();
|
|
382
|
+
await session.harness
|
|
383
|
+
.abort({
|
|
384
|
+
threadId: session.sessionId,
|
|
385
|
+
reason: 'connection closed',
|
|
386
|
+
})
|
|
387
|
+
.catch(() => undefined);
|
|
388
|
+
}));
|
|
389
|
+
}
|
|
390
|
+
//#endregion
|
|
391
|
+
//#region Internals
|
|
392
|
+
async openSession(sessionId, cwd, mcpServers) {
|
|
393
|
+
if (!isAbsolutePath(cwd)) {
|
|
394
|
+
throw RequestError.invalidParams({
|
|
395
|
+
message: `cwd must be an absolute path: ${cwd}`,
|
|
396
|
+
});
|
|
397
|
+
}
|
|
398
|
+
const harness = typeof this.source === 'function'
|
|
399
|
+
? await this.source({
|
|
400
|
+
sessionId,
|
|
401
|
+
cwd,
|
|
402
|
+
mcpServers,
|
|
403
|
+
client: {
|
|
404
|
+
fs: clientFsAdapter({
|
|
405
|
+
conn: this.conn,
|
|
406
|
+
sessionId,
|
|
407
|
+
capabilities: this.clientCapabilities,
|
|
408
|
+
}),
|
|
409
|
+
shell: clientShellAdapter({
|
|
410
|
+
conn: this.conn,
|
|
411
|
+
sessionId,
|
|
412
|
+
capabilities: this.clientCapabilities,
|
|
413
|
+
}),
|
|
414
|
+
capabilities: this.clientCapabilities,
|
|
415
|
+
},
|
|
416
|
+
})
|
|
417
|
+
: this.source;
|
|
418
|
+
const session = {
|
|
419
|
+
sessionId,
|
|
420
|
+
cwd,
|
|
421
|
+
harness,
|
|
422
|
+
gateLayer: this.options.permissions
|
|
423
|
+
? createServePermissionLayer({
|
|
424
|
+
sessionId,
|
|
425
|
+
policy: this.options.permissions,
|
|
426
|
+
broker: this.broker,
|
|
427
|
+
presentation: this.presenter,
|
|
428
|
+
})
|
|
429
|
+
: undefined,
|
|
430
|
+
cancelRequested: false,
|
|
431
|
+
pumping: false,
|
|
432
|
+
persistedIds: new Set(),
|
|
433
|
+
};
|
|
434
|
+
this.sessions.set(sessionId, session);
|
|
435
|
+
return session;
|
|
436
|
+
}
|
|
437
|
+
requireSession(sessionId) {
|
|
438
|
+
const session = this.sessions.get(sessionId);
|
|
439
|
+
if (!session) {
|
|
440
|
+
throw RequestError.invalidParams({
|
|
441
|
+
message: `unknown session: ${sessionId}`,
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
return session;
|
|
445
|
+
}
|
|
446
|
+
/**
|
|
447
|
+
* `NewSessionResponse` has no commands field at this protocol revision, so
|
|
448
|
+
* advertised commands follow as an `available_commands_update` notification.
|
|
449
|
+
* Deferred a tick so the notification cannot reach the wire before the
|
|
450
|
+
* response that introduces the session id.
|
|
451
|
+
*/
|
|
452
|
+
advertiseCommands(sessionId) {
|
|
453
|
+
const commands = this.options.commands;
|
|
454
|
+
if (!commands || commands.length === 0) {
|
|
455
|
+
return;
|
|
456
|
+
}
|
|
457
|
+
setTimeout(() => {
|
|
458
|
+
void this.conn
|
|
459
|
+
.sessionUpdate({
|
|
460
|
+
sessionId,
|
|
461
|
+
update: {
|
|
462
|
+
sessionUpdate: 'available_commands_update',
|
|
463
|
+
availableCommands: commands.map((command) => ({
|
|
464
|
+
name: command.name,
|
|
465
|
+
description: command.description,
|
|
466
|
+
input: command.inputHint
|
|
467
|
+
? {
|
|
468
|
+
hint: command.inputHint,
|
|
469
|
+
}
|
|
470
|
+
: undefined,
|
|
471
|
+
})),
|
|
472
|
+
},
|
|
473
|
+
})
|
|
474
|
+
.catch(() => undefined);
|
|
475
|
+
}, 0);
|
|
476
|
+
}
|
|
477
|
+
/** Route `/name args` prompts through the matching command's `run`. */
|
|
478
|
+
async resolveInput(session, prompt) {
|
|
479
|
+
const commands = this.options.commands;
|
|
480
|
+
const first = prompt[0];
|
|
481
|
+
if (commands && commands.length > 0 && first?.type === 'text' && first.text.startsWith('/')) {
|
|
482
|
+
// Only the command NAME is tokenized; the argument text is passed RAW
|
|
483
|
+
// (minus one separator character) so newlines, code blocks, and runs of
|
|
484
|
+
// whitespace survive the rewrite.
|
|
485
|
+
const match = /^\/(\S+)([\s\S]*)$/.exec(first.text);
|
|
486
|
+
const command = match ? commands.find((c) => c.name === match[1]) : undefined;
|
|
487
|
+
if (command?.run && match) {
|
|
488
|
+
const argsText = (match[2] ?? '').replace(/^\s/, '');
|
|
489
|
+
const result = await command.run(argsText, {
|
|
490
|
+
sessionId: session.sessionId,
|
|
491
|
+
cwd: session.cwd,
|
|
492
|
+
});
|
|
493
|
+
// Blocks after the command block (images, embedded context) still
|
|
494
|
+
// reach the turn — a command rewrite must not discard client content.
|
|
495
|
+
const rest = contentBlocksToItems(prompt.slice(1));
|
|
496
|
+
return typeof result === 'string'
|
|
497
|
+
? [
|
|
498
|
+
...textInput(result),
|
|
499
|
+
...rest,
|
|
500
|
+
]
|
|
501
|
+
: [
|
|
502
|
+
...result,
|
|
503
|
+
...rest,
|
|
504
|
+
];
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
return contentBlocksToItems(prompt);
|
|
508
|
+
}
|
|
509
|
+
/** Forward an `ask` to the client as `session/request_permission`. */
|
|
510
|
+
async forwardPermissionToWire(prompt) {
|
|
511
|
+
const toolCallId = prompt.callId ?? prompt.requestId;
|
|
512
|
+
const response = await this.conn.requestPermission({
|
|
513
|
+
sessionId: prompt.sessionId,
|
|
514
|
+
toolCall: {
|
|
515
|
+
toolCallId,
|
|
516
|
+
title: prompt.title,
|
|
517
|
+
kind: prompt.kind,
|
|
518
|
+
rawInput: asRecord(prompt.args),
|
|
519
|
+
status: 'pending',
|
|
520
|
+
},
|
|
521
|
+
options: [
|
|
522
|
+
{
|
|
523
|
+
optionId: 'allow',
|
|
524
|
+
name: 'Allow',
|
|
525
|
+
kind: 'allow_once',
|
|
526
|
+
},
|
|
527
|
+
{
|
|
528
|
+
optionId: 'reject',
|
|
529
|
+
name: 'Reject',
|
|
530
|
+
kind: 'reject_once',
|
|
531
|
+
},
|
|
532
|
+
],
|
|
533
|
+
});
|
|
534
|
+
if (response.outcome.outcome === 'cancelled') {
|
|
535
|
+
return {
|
|
536
|
+
decision: 'cancel',
|
|
537
|
+
};
|
|
538
|
+
}
|
|
539
|
+
if (response.outcome.optionId === 'allow') {
|
|
540
|
+
return {
|
|
541
|
+
decision: 'allow',
|
|
542
|
+
};
|
|
543
|
+
}
|
|
544
|
+
return {
|
|
545
|
+
decision: 'deny',
|
|
546
|
+
reason: 'the user rejected the tool call',
|
|
547
|
+
};
|
|
548
|
+
}
|
|
549
|
+
/** Move the pending gated `tool_call` to `in_progress` after a grant, whoever answered. */
|
|
550
|
+
sendGrantProgress(prompt) {
|
|
551
|
+
void this.conn
|
|
552
|
+
.sessionUpdate({
|
|
553
|
+
sessionId: prompt.sessionId,
|
|
554
|
+
update: {
|
|
555
|
+
sessionUpdate: 'tool_call_update',
|
|
556
|
+
toolCallId: prompt.callId ?? prompt.requestId,
|
|
557
|
+
status: 'in_progress',
|
|
558
|
+
},
|
|
559
|
+
})
|
|
560
|
+
.catch(() => undefined);
|
|
561
|
+
}
|
|
562
|
+
/** Append completed items to the history seam as they stream, deduplicated by id. */
|
|
563
|
+
startSavePump(session) {
|
|
564
|
+
const history = this.options.history;
|
|
565
|
+
if (!history || session.pumping) {
|
|
566
|
+
return;
|
|
567
|
+
}
|
|
568
|
+
session.pumping = true;
|
|
569
|
+
void pumpItems(session, history.save.bind(history)).catch(() => {
|
|
570
|
+
// A dead pump only pauses persistence; the next prompt restarts it, and
|
|
571
|
+
// the persisted-id set keeps the replay from duplicating history.
|
|
572
|
+
session.pumping = false;
|
|
573
|
+
});
|
|
574
|
+
}
|
|
575
|
+
async persistItems(session, items) {
|
|
576
|
+
const history = this.options.history;
|
|
577
|
+
if (!history) {
|
|
578
|
+
return;
|
|
579
|
+
}
|
|
580
|
+
for (const item of items) {
|
|
581
|
+
const id = itemId(item);
|
|
582
|
+
if (id) {
|
|
583
|
+
if (session.persistedIds.has(id)) {
|
|
584
|
+
continue;
|
|
585
|
+
}
|
|
586
|
+
session.persistedIds.add(id);
|
|
587
|
+
}
|
|
588
|
+
await history.save(session.sessionId, item);
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
async function pumpItems(session, save) {
|
|
593
|
+
const iterator = session.harness
|
|
594
|
+
.getItemStream({
|
|
595
|
+
threadId: session.sessionId,
|
|
596
|
+
})[Symbol.asyncIterator]();
|
|
597
|
+
// The item stream spans turns and never completes on its own; dispose()
|
|
598
|
+
// ends the pump through this handle instead of leaving a consumer parked
|
|
599
|
+
// on the broadcaster for the life of the process.
|
|
600
|
+
session.stopSavePump = () => {
|
|
601
|
+
void iterator.return?.().catch(() => undefined);
|
|
602
|
+
};
|
|
603
|
+
while (true) {
|
|
604
|
+
const next = await iterator.next();
|
|
605
|
+
if (next.done) {
|
|
606
|
+
return;
|
|
607
|
+
}
|
|
608
|
+
const item = next.value;
|
|
609
|
+
if (!item.isComplete) {
|
|
610
|
+
continue;
|
|
611
|
+
}
|
|
612
|
+
// The stream re-emits an assistant message once at text-done (status
|
|
613
|
+
// still in_progress) and again finalized; registering the first copy's id
|
|
614
|
+
// would make the dedupe DISCARD the corrected one, persisting messages
|
|
615
|
+
// permanently marked in_progress.
|
|
616
|
+
if (itemStatus(item) === 'in_progress') {
|
|
617
|
+
continue;
|
|
618
|
+
}
|
|
619
|
+
const id = itemId(item);
|
|
620
|
+
if (id) {
|
|
621
|
+
if (session.persistedIds.has(id)) {
|
|
622
|
+
continue;
|
|
623
|
+
}
|
|
624
|
+
session.persistedIds.add(id);
|
|
625
|
+
}
|
|
626
|
+
await save(session.sessionId, stripIsComplete(item));
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
function itemStatus(item) {
|
|
630
|
+
return 'status' in item && typeof item.status === 'string' ? item.status : undefined;
|
|
631
|
+
}
|
|
632
|
+
/** Eagerly bind an iterator so the broadcaster registers the consumer now, not at first read. */
|
|
633
|
+
function attachEvents(harness, threadId) {
|
|
634
|
+
const iterator = harness
|
|
635
|
+
.getFullStream({
|
|
636
|
+
threadId,
|
|
637
|
+
})[Symbol.asyncIterator]();
|
|
638
|
+
return {
|
|
639
|
+
[Symbol.asyncIterator]: () => iterator,
|
|
640
|
+
async close() {
|
|
641
|
+
await iterator.return?.().catch(() => undefined);
|
|
642
|
+
},
|
|
643
|
+
};
|
|
644
|
+
}
|
|
645
|
+
function itemId(item) {
|
|
646
|
+
return 'id' in item && typeof item.id === 'string' ? item.id : null;
|
|
647
|
+
}
|
|
648
|
+
function stripIsComplete(streamingItem) {
|
|
649
|
+
const { isComplete: _isComplete, ...item } = streamingItem;
|
|
650
|
+
return item;
|
|
651
|
+
}
|
|
652
|
+
function asRecord(value) {
|
|
653
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
654
|
+
return undefined;
|
|
655
|
+
}
|
|
656
|
+
return frameworkCast(value);
|
|
657
|
+
}
|
|
658
|
+
//#endregion
|
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Node stdio entry for the server direction — the inverse of `./stdio`,
|
|
3
|
+
* which spawns a child and binds to *its* stdio: `serveAcp` binds a served
|
|
4
|
+
* harness to the **current process's** stdin/stdout, so an ACP client (Zed,
|
|
5
|
+
* another editor, a Noetic step) that launched this process as its agent can
|
|
6
|
+
* drive the harness.
|
|
7
|
+
*
|
|
8
|
+
* Lives behind the `@noetic-tools/acp/server` subpath so the package's main
|
|
9
|
+
* entry stays runtime-neutral.
|
|
10
|
+
*
|
|
11
|
+
* ```ts
|
|
12
|
+
* import { AgentHarness } from '@noetic-tools/core';
|
|
13
|
+
* import { serveAcp } from '@noetic-tools/acp/server';
|
|
14
|
+
*
|
|
15
|
+
* const harness = new AgentHarness({ name: 'my-agent', agentGraph, tools, params: {} });
|
|
16
|
+
* await serveAcp(harness).closed;
|
|
17
|
+
* ```
|
|
18
|
+
*/
|
|
19
|
+
import type { AcpServeHarnessSource, AcpServeOptions } from './serve-types.js';
|
|
20
|
+
/** @public Handle over a running stdio ACP server. */
|
|
21
|
+
export interface AcpServerHandle {
|
|
22
|
+
/** Resolves when the client disconnects (stdin ends) or `close()` runs. */
|
|
23
|
+
closed: Promise<void>;
|
|
24
|
+
/** Cancel live sessions and stop serving. */
|
|
25
|
+
close(): Promise<void>;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Serve a harness as an ACP agent over the current process's stdio. `await`
|
|
29
|
+
* the returned handle's `closed` to keep the process alive until the client
|
|
30
|
+
* disconnects.
|
|
31
|
+
* @public
|
|
32
|
+
*/
|
|
33
|
+
export declare function serveAcp(source: AcpServeHarnessSource, options?: AcpServeOptions): AcpServerHandle;
|