@1agents/acp-service 0.1.4 → 0.3.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/README.md +89 -114
- package/dist/bin/acp-service.js +1 -1
- package/dist/src/acp-connection.d.ts +26 -0
- package/dist/src/acp-connection.js +512 -0
- package/dist/src/acp-state.d.ts +19 -0
- package/dist/src/acp-state.js +44 -0
- package/dist/src/bridge.d.ts +12 -3
- package/dist/src/bridge.js +986 -888
- package/dist/src/catalog-descriptors.d.ts +11 -0
- package/dist/src/catalog-descriptors.js +163 -0
- package/dist/src/catalog.d.ts +30 -0
- package/dist/src/catalog.js +132 -0
- package/dist/src/index.d.ts +2 -0
- package/dist/src/index.js +1 -0
- package/dist/src/manifest.d.ts +0 -6
- package/dist/src/manifest.js +4 -0
- package/dist/src/server.d.ts +1 -0
- package/dist/src/server.js +12 -0
- package/package.json +13 -12
|
@@ -0,0 +1,512 @@
|
|
|
1
|
+
/** ACP v1 JSON-RPC over WebSocket. Runtime commands remain process-local. */
|
|
2
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { isAbsolute } from 'node:path';
|
|
5
|
+
import { realpathSync } from 'node:fs';
|
|
6
|
+
import { agent, RequestError, PROTOCOL_VERSION } from '@agentclientprotocol/sdk';
|
|
7
|
+
import { AcpState } from './acp-state.js';
|
|
8
|
+
import { dispatchCommand, activeSessions, runtime, loadSessionHistory, readRuntimeRecord } from './bridge.js';
|
|
9
|
+
const calls = new AsyncLocalStorage();
|
|
10
|
+
const NS = '1agents';
|
|
11
|
+
const EXT = '_1agents/';
|
|
12
|
+
const production = {
|
|
13
|
+
dispatch: dispatchCommand,
|
|
14
|
+
get sessions() { return activeSessions; },
|
|
15
|
+
record: id => readRuntimeRecord(id),
|
|
16
|
+
status: id => runtime.getStatus({ handle: activeSessions.get(id).handle }),
|
|
17
|
+
history: loadSessionHistory,
|
|
18
|
+
};
|
|
19
|
+
/** Restore ACP select tags omitted by the runtime's display projection. */
|
|
20
|
+
function configOptions(status) {
|
|
21
|
+
return status.details?.configOptions ?? (status.configOptions ?? []).map((option) => ({ type: 'select', ...option }));
|
|
22
|
+
}
|
|
23
|
+
/** Transport framing only; SDK owns method validation and RPC correlation. */
|
|
24
|
+
export function webSocketStream(ws) {
|
|
25
|
+
let readableClosed = false;
|
|
26
|
+
return {
|
|
27
|
+
readable: new ReadableStream({
|
|
28
|
+
start(controller) {
|
|
29
|
+
ws.on('message', data => {
|
|
30
|
+
if (readableClosed)
|
|
31
|
+
return;
|
|
32
|
+
let value;
|
|
33
|
+
try {
|
|
34
|
+
value = JSON.parse(data.toString());
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
ws.send(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } }));
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
if (!value || typeof value !== 'object' || Array.isArray(value) || value.jsonrpc !== '2.0') {
|
|
41
|
+
ws.send(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32600, message: 'Invalid Request' } }));
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
controller.enqueue(value);
|
|
45
|
+
});
|
|
46
|
+
ws.once('close', () => {
|
|
47
|
+
if (readableClosed)
|
|
48
|
+
return;
|
|
49
|
+
readableClosed = true;
|
|
50
|
+
controller.close();
|
|
51
|
+
});
|
|
52
|
+
ws.once('error', () => ws.close());
|
|
53
|
+
},
|
|
54
|
+
cancel() {
|
|
55
|
+
readableClosed = true;
|
|
56
|
+
ws.close();
|
|
57
|
+
},
|
|
58
|
+
}),
|
|
59
|
+
writable: new WritableStream({
|
|
60
|
+
write(value) {
|
|
61
|
+
return new Promise((resolve, reject) => {
|
|
62
|
+
if (ws.readyState !== 1) {
|
|
63
|
+
reject(new Error('WebSocket disconnected'));
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
ws.send(JSON.stringify(value), error => error ? reject(error) : resolve());
|
|
67
|
+
});
|
|
68
|
+
},
|
|
69
|
+
}),
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
/** A runtime subscriber owned by exactly one live ACP connection. */
|
|
73
|
+
export class RuntimePeer {
|
|
74
|
+
receive;
|
|
75
|
+
readyState = 1;
|
|
76
|
+
_acpxReqHost;
|
|
77
|
+
constructor(receive) {
|
|
78
|
+
this.receive = receive;
|
|
79
|
+
}
|
|
80
|
+
send(raw) {
|
|
81
|
+
const event = JSON.parse(raw);
|
|
82
|
+
const call = calls.getStore();
|
|
83
|
+
if (call?.active)
|
|
84
|
+
call.events.push(event);
|
|
85
|
+
this.receive(event);
|
|
86
|
+
}
|
|
87
|
+
async command(backend, payload) {
|
|
88
|
+
const events = [];
|
|
89
|
+
const call = { events, active: true };
|
|
90
|
+
try {
|
|
91
|
+
await calls.run(call, () => backend.dispatch(this, payload));
|
|
92
|
+
}
|
|
93
|
+
finally {
|
|
94
|
+
call.active = false;
|
|
95
|
+
}
|
|
96
|
+
const failure = events.find(e => (e.event === 'error' || e.type === 'error' || e.event === 'protocol_error') && e.scope !== 'turn');
|
|
97
|
+
if (failure)
|
|
98
|
+
throw new RequestError(-32000, failure.message || 'Runtime command failed', { code: failure.code });
|
|
99
|
+
return events;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
function metadata(value) { return value._meta?.[NS] || {}; }
|
|
103
|
+
function envelope(value) {
|
|
104
|
+
const { event: _event, ...fields } = value;
|
|
105
|
+
return { [NS]: fields };
|
|
106
|
+
}
|
|
107
|
+
function updateFor(event) {
|
|
108
|
+
const common = { _meta: envelope(event) };
|
|
109
|
+
switch (event.event) {
|
|
110
|
+
case 'text_delta': return { ...common, sessionUpdate: event.type === 'thought' ? 'agent_thought_chunk' : 'agent_message_chunk', content: { type: 'text', text: event.text || '' } };
|
|
111
|
+
case 'tool_call': return { ...common, sessionUpdate: 'tool_call', toolCallId: event.toolCallId, title: event.toolName || 'Tool', status: event.status || 'pending', kind: event.kind, rawInput: event.arguments, content: event.content, locations: event.locations };
|
|
112
|
+
case 'tool_result': return { ...common, sessionUpdate: 'tool_call_update', toolCallId: event.toolCallId, status: event.isError ? 'failed' : 'completed', rawOutput: event.text, content: [{ type: 'content', content: { type: 'text', text: event.text || '' } }] };
|
|
113
|
+
case 'mode_changed': return { ...common, sessionUpdate: 'current_mode_update', currentModeId: event.payload.currentModeId };
|
|
114
|
+
case 'available_commands_update': return { ...common, sessionUpdate: 'available_commands_update', availableCommands: event.payload.availableCommands.map((c) => ({ name: c.name, description: c.description || '', ...(c.hasInput ? { input: { hint: c.inputHint || 'Arguments' } } : {}) })) };
|
|
115
|
+
case 'plan': return { ...common, sessionUpdate: 'plan', entries: event.entries || event.payload?.entries || [] };
|
|
116
|
+
default: return undefined;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
/** Each endpoint binds the connection to one Agent, including session reloads. */
|
|
120
|
+
export function attachAcpConnection(ws, req, backend = production, state = new AcpState()) {
|
|
121
|
+
const endpoint = new URL(req?.url || '/', 'http://localhost');
|
|
122
|
+
let agentName = 'codex';
|
|
123
|
+
try {
|
|
124
|
+
if (endpoint.pathname !== '/') {
|
|
125
|
+
if (!endpoint.pathname.startsWith('/agents/'))
|
|
126
|
+
throw new Error('Unknown ACP endpoint');
|
|
127
|
+
agentName = decodeURIComponent(endpoint.pathname.slice(8));
|
|
128
|
+
if (!/^[a-zA-Z0-9_-]+$/.test(agentName))
|
|
129
|
+
throw new Error('Invalid Agent name');
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
ws.close(1008, 'Use /agents/<agent>');
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
let initialized = false;
|
|
137
|
+
let connected = true;
|
|
138
|
+
let extensions = false;
|
|
139
|
+
let client;
|
|
140
|
+
let output = Promise.resolve();
|
|
141
|
+
const held = new Map();
|
|
142
|
+
const attached = new Set();
|
|
143
|
+
const prompts = new Map();
|
|
144
|
+
const interactive = new Map();
|
|
145
|
+
const answers = new Map();
|
|
146
|
+
const toolsSeen = new Set();
|
|
147
|
+
const peer = new RuntimePeer(receive);
|
|
148
|
+
peer._acpxReqHost = req?.headers.host?.split(':')[0];
|
|
149
|
+
function notify(method, params) {
|
|
150
|
+
if (!connected)
|
|
151
|
+
return;
|
|
152
|
+
output = output.then(() => client.notify(method, params)).catch(error => {
|
|
153
|
+
if (!connected)
|
|
154
|
+
return;
|
|
155
|
+
for (const pending of prompts.values())
|
|
156
|
+
pending.reject(error);
|
|
157
|
+
prompts.clear();
|
|
158
|
+
ws.close(1011, 'ACP update delivery failed');
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
function requireInitialized() { if (!initialized)
|
|
162
|
+
throw new RequestError(-32002, 'Call initialize first'); }
|
|
163
|
+
function requireSession(id) {
|
|
164
|
+
requireInitialized();
|
|
165
|
+
if (!attached.has(id) || backend.sessions.get(id)?.ws !== peer)
|
|
166
|
+
throw new RequestError(-32001, 'Session is not attached to this connection');
|
|
167
|
+
}
|
|
168
|
+
async function interaction(event) {
|
|
169
|
+
const { sessionId, requestId } = event;
|
|
170
|
+
if (interactive.has(requestId))
|
|
171
|
+
return;
|
|
172
|
+
const abort = new AbortController();
|
|
173
|
+
interactive.set(requestId, { abort, sessionId });
|
|
174
|
+
try {
|
|
175
|
+
let response;
|
|
176
|
+
let action;
|
|
177
|
+
if (event.event === 'permission_request') {
|
|
178
|
+
const options = event.options || [
|
|
179
|
+
{ optionId: 'allow_once', kind: 'allow_once', name: 'Allow once' },
|
|
180
|
+
{ optionId: 'reject_once', kind: 'reject_once', name: 'Reject' },
|
|
181
|
+
];
|
|
182
|
+
const result = await client.request('session/request_permission', {
|
|
183
|
+
sessionId, toolCall: event.toolCall || { toolCallId: event.toolCallId, title: event.toolName, rawInput: event.arguments }, options,
|
|
184
|
+
_meta: envelope(event),
|
|
185
|
+
}, { cancellationSignal: abort.signal });
|
|
186
|
+
const selected = result.outcome.outcome === 'selected' ? options.find((o) => o.optionId === result.outcome.optionId) : undefined;
|
|
187
|
+
response = { behavior: selected?.kind || 'cancel' };
|
|
188
|
+
action = 'respond_permission';
|
|
189
|
+
}
|
|
190
|
+
else {
|
|
191
|
+
action = `respond_${event.event}`;
|
|
192
|
+
if (!extensions)
|
|
193
|
+
response = { outcome: event.event === 'exit_plan_mode' ? 'abandoned' : 'cancelled' };
|
|
194
|
+
else
|
|
195
|
+
response = await client.request(`_x.ai/${event.event}`, { ...event, event: undefined }, { cancellationSignal: abort.signal });
|
|
196
|
+
}
|
|
197
|
+
if (!abort.signal.aborted && connected && backend.sessions.get(sessionId)?.ws === peer) {
|
|
198
|
+
await peer.command(backend, { ...response, action, sessionId, requestId });
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
catch {
|
|
202
|
+
// Disconnection leaves the session-owned interaction pending for replay.
|
|
203
|
+
// A connected client rejecting an unsupported method cancels that interaction.
|
|
204
|
+
if (connected && !abort.signal.aborted && backend.sessions.get(sessionId)?.ws === peer) {
|
|
205
|
+
await peer.command(backend, { action: `respond_${event.event === 'permission_request' ? 'permission' : event.event}`, sessionId, requestId, behavior: 'cancel', outcome: event.event === 'exit_plan_mode' ? 'abandoned' : 'cancelled' }).catch(() => { });
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
finally {
|
|
209
|
+
if (interactive.get(requestId)?.abort === abort)
|
|
210
|
+
interactive.delete(requestId);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
function receive(event) {
|
|
214
|
+
const sessionId = event.sessionId;
|
|
215
|
+
const buffer = held.get(sessionId);
|
|
216
|
+
if (buffer) {
|
|
217
|
+
buffer.push(event);
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
if (event.event === 'session_taken_over' || event.event === 'session_closed') {
|
|
221
|
+
attached.delete(sessionId);
|
|
222
|
+
for (const item of interactive.values())
|
|
223
|
+
if (item.sessionId === sessionId)
|
|
224
|
+
item.abort.abort();
|
|
225
|
+
for (const [key, pending] of prompts)
|
|
226
|
+
if (pending.sessionId === sessionId) {
|
|
227
|
+
prompts.delete(key);
|
|
228
|
+
if (event.event === 'session_closed')
|
|
229
|
+
pending.resolve({ stopReason: 'cancelled' });
|
|
230
|
+
else
|
|
231
|
+
pending.reject(new RequestError(-32000, 'Session taken over by another connection'));
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
if (['permission_request', 'ask_user_question', 'exit_plan_mode'].includes(event.event)) {
|
|
235
|
+
if (connected)
|
|
236
|
+
void interaction(event);
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
if (event.event?.endsWith('_timeout'))
|
|
240
|
+
interactive.get(event.requestId)?.abort.abort();
|
|
241
|
+
const summary = backend.sessions.get(sessionId)?.acpResponsePolicy === 'summary';
|
|
242
|
+
if (event.event === 'text_delta' && event.type !== 'thought')
|
|
243
|
+
answers.set(sessionId, (answers.get(sessionId) || '') + (event.text || ''));
|
|
244
|
+
let update = updateFor(event);
|
|
245
|
+
if (update?.sessionUpdate === 'tool_call') {
|
|
246
|
+
const key = `${sessionId}:${update.toolCallId}`;
|
|
247
|
+
if (toolsSeen.has(key))
|
|
248
|
+
update = { ...update, sessionUpdate: 'tool_call_update' };
|
|
249
|
+
toolsSeen.add(key);
|
|
250
|
+
}
|
|
251
|
+
if (update) {
|
|
252
|
+
state.append(sessionId, update);
|
|
253
|
+
if (!summary)
|
|
254
|
+
notify('session/update', { sessionId, update });
|
|
255
|
+
}
|
|
256
|
+
else if (event.event === 'session_meta') {
|
|
257
|
+
if (event.payload.configOptions)
|
|
258
|
+
notify('session/update', { sessionId, update: { sessionUpdate: 'config_option_update', configOptions: configOptions(event.payload) } });
|
|
259
|
+
if (extensions)
|
|
260
|
+
notify(`${EXT}session/meta`, { ...event, event: undefined });
|
|
261
|
+
}
|
|
262
|
+
else if (extensions && event.type !== 'sessions_list' && !['session_ready', 'done'].includes(event.event) && (!summary || !['turn_state', 'turn_sync', 'background_task', 'usage'].includes(event.event))) {
|
|
263
|
+
const { event: name, type, ...params } = event;
|
|
264
|
+
notify(`${EXT}events/${name || type}`, { ...params, ...(name ? { type } : { _meta: { [NS]: { viewType: true } } }) });
|
|
265
|
+
}
|
|
266
|
+
const terminal = (event.event === 'turn_state' && ['completed', 'failed', 'cancelled'].includes(event.status)) || event.event === 'done' || event.event === 'turn_terminal' || (event.event === 'error' && event.terminal !== false && event.scope === 'turn');
|
|
267
|
+
if (terminal) {
|
|
268
|
+
if (summary && event.event !== 'turn_state') {
|
|
269
|
+
event = { ...event, responsePolicy: 'summary', resultText: event.finalAnswer || answers.get(sessionId) || '', summary: event.finalAnswer || answers.get(sessionId) || event.summary, sessionRef: { sessionId, turnId: event.turnId } };
|
|
270
|
+
if (extensions)
|
|
271
|
+
notify(`${EXT}events/turn_complete`, { ...event, event: undefined });
|
|
272
|
+
}
|
|
273
|
+
answers.delete(sessionId);
|
|
274
|
+
const entry = [...prompts.entries()].find(([, p]) => p.sessionId === sessionId && ((event.turnId && event.turnId === p.turnId) || ((event.runtimeRequestId || event.requestId) && (event.runtimeRequestId || event.requestId) === p.requestId) || (!event.turnId && !event.runtimeRequestId && !event.requestId)));
|
|
275
|
+
if (!entry)
|
|
276
|
+
return;
|
|
277
|
+
const [key, pending] = entry;
|
|
278
|
+
prompts.delete(key);
|
|
279
|
+
void output.then(() => {
|
|
280
|
+
if (event.status === 'failed' || event.event === 'error')
|
|
281
|
+
pending.reject(new RequestError(-32000, event.error?.message || event.message || 'Turn failed', { code: event.error?.code }));
|
|
282
|
+
else
|
|
283
|
+
pending.resolve({ stopReason: event.stopped || event.status === 'cancelled' ? 'cancelled' : ['end_turn', 'max_tokens', 'max_turn_requests', 'refusal', 'cancelled'].includes(event.stopReason) ? event.stopReason : 'end_turn', _meta: envelope(event) });
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
async function ensure(params, fresh, replay) {
|
|
288
|
+
requireInitialized();
|
|
289
|
+
if (typeof params.cwd !== 'string' || !isAbsolute(params.cwd))
|
|
290
|
+
throw RequestError.invalidParams('cwd must be absolute');
|
|
291
|
+
try {
|
|
292
|
+
params = { ...params, cwd: realpathSync(params.cwd) };
|
|
293
|
+
}
|
|
294
|
+
catch {
|
|
295
|
+
throw RequestError.invalidParams('cwd must name an existing directory');
|
|
296
|
+
}
|
|
297
|
+
const id = fresh ? randomUUID() : params.sessionId;
|
|
298
|
+
const custom = extensions ? metadata(params) : {};
|
|
299
|
+
const stored = state.get(id);
|
|
300
|
+
const record = fresh ? undefined : await backend.record(stored?.runtimeRecordId || id);
|
|
301
|
+
if (!fresh) {
|
|
302
|
+
const live = backend.sessions.get(id);
|
|
303
|
+
const binding = state.get(id);
|
|
304
|
+
if (binding?.deleted)
|
|
305
|
+
throw new RequestError(-32003, 'Session was deleted');
|
|
306
|
+
if (!live && !record)
|
|
307
|
+
throw new RequestError(-32001, 'Session not found');
|
|
308
|
+
if ((live?.handle?.cwd || record?.cwd) !== params.cwd)
|
|
309
|
+
throw RequestError.invalidParams('Session workspace cannot change');
|
|
310
|
+
if (binding && binding.agentType !== agentName)
|
|
311
|
+
throw RequestError.invalidParams('Session Agent cannot change');
|
|
312
|
+
if (replay && !binding?.completeHistory)
|
|
313
|
+
throw new RequestError(-32000, 'Imported session has no complete ACP replay log; use session/resume');
|
|
314
|
+
if (live && live.agentType !== agentName)
|
|
315
|
+
throw RequestError.invalidParams('Session Agent cannot change');
|
|
316
|
+
if (record?._meta?.[NS]?.agentType && record._meta[NS].agentType !== agentName)
|
|
317
|
+
throw RequestError.invalidParams('Session Agent cannot change');
|
|
318
|
+
}
|
|
319
|
+
if (held.has(id))
|
|
320
|
+
throw new RequestError(-32000, 'Session attachment is already in progress');
|
|
321
|
+
held.set(id, []);
|
|
322
|
+
try {
|
|
323
|
+
const events = await peer.command(backend, { ...custom, action: 'ensure_session', sessionId: id, workspacePath: params.cwd, agentType: agentName, mcpServers: params.mcpServers, runtimeSessionKey: stored?.runtimeRecordId, resumeSessionId: fresh ? custom.resumeSessionId : record?.acpSessionId, responsePolicy: 'stream' });
|
|
324
|
+
state.create({ sessionId: id, agentType: agentName, cwd: params.cwd, completeHistory: fresh ? !custom.resumeSessionId : stored?.completeHistory === true, runtimeRecordId: backend.sessions.get(id)?.handle?.acpxRecordId });
|
|
325
|
+
attached.add(id);
|
|
326
|
+
const session = backend.sessions.get(id);
|
|
327
|
+
if (session)
|
|
328
|
+
session.acpResponsePolicy = custom.responsePolicy || session.acpResponsePolicy || 'stream';
|
|
329
|
+
for (const update of state.history(id))
|
|
330
|
+
if (update.sessionUpdate === 'tool_call')
|
|
331
|
+
toolsSeen.add(`${id}:${update.toolCallId}`);
|
|
332
|
+
if (replay) {
|
|
333
|
+
for (const update of state.history(id)) {
|
|
334
|
+
notify('session/update', { sessionId: id, update });
|
|
335
|
+
}
|
|
336
|
+
await output;
|
|
337
|
+
}
|
|
338
|
+
const status = await backend.status(id);
|
|
339
|
+
if (backend.sessions.get(id)?.ws !== peer)
|
|
340
|
+
throw new RequestError(-32000, 'Session taken over during attachment');
|
|
341
|
+
if (status.availableCommands) {
|
|
342
|
+
notify('session/update', { sessionId: id, update: {
|
|
343
|
+
sessionUpdate: 'available_commands_update',
|
|
344
|
+
availableCommands: status.availableCommands.map((c) => ({ name: c.name, description: c.description || '', ...(c.hasInput ? { input: { hint: c.inputHint || 'Arguments' } } : {}) })),
|
|
345
|
+
} });
|
|
346
|
+
await output;
|
|
347
|
+
}
|
|
348
|
+
const ready = events.find(e => e.event === 'session_ready') || {};
|
|
349
|
+
return { ...(fresh ? { sessionId: id } : {}), ...(status.modes ? { modes: status.modes } : {}), configOptions: configOptions(status), _meta: { [NS]: { agentSessionId: ready.agentSessionId, turnProtocolVersion: 3, agentType: agentName } } };
|
|
350
|
+
}
|
|
351
|
+
finally {
|
|
352
|
+
const buffered = held.get(id) || [];
|
|
353
|
+
held.delete(id);
|
|
354
|
+
for (const event of buffered) {
|
|
355
|
+
// The explicit load replay is the standard transcript; runtime history
|
|
356
|
+
// snapshots are emitted only as negotiated application extensions.
|
|
357
|
+
receive(event);
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
const app = agent({ name: '1agents-acp-service' })
|
|
362
|
+
.onRequest('initialize', ({ params }) => {
|
|
363
|
+
if (initialized)
|
|
364
|
+
throw RequestError.invalidRequest('Already initialized');
|
|
365
|
+
initialized = true;
|
|
366
|
+
extensions = params.clientCapabilities?._meta?.[NS] !== undefined;
|
|
367
|
+
return { protocolVersion: PROTOCOL_VERSION, agentInfo: { name: '1agents-acp-service', version: '0.2.0' }, authMethods: [], agentCapabilities: { promptCapabilities: { image: true, audio: true }, loadSession: true, sessionCapabilities: { resume: {}, close: {}, list: {}, delete: {} }, _meta: { [NS]: { version: 1, agentType: agentName, interactions: true, turnSync: true } } } };
|
|
368
|
+
})
|
|
369
|
+
.onRequest('authenticate', () => { requireInitialized(); throw RequestError.invalidParams('No connection authentication methods are configured'); })
|
|
370
|
+
.onRequest('session/new', async ({ params }) => await ensure(params, true, false))
|
|
371
|
+
.onRequest('session/load', ({ params }) => ensure(params, false, true))
|
|
372
|
+
.onRequest('session/resume', ({ params }) => ensure(params, false, false))
|
|
373
|
+
.onRequest('session/prompt', async ({ params, signal }) => {
|
|
374
|
+
requireSession(params.sessionId);
|
|
375
|
+
const custom = extensions ? metadata(params) : {};
|
|
376
|
+
if (!custom.turnManaged && ([...prompts.values()].some(p => p.sessionId === params.sessionId) || backend.sessions.get(params.sessionId)?.activeTurn))
|
|
377
|
+
throw new RequestError(-32000, 'Session is busy');
|
|
378
|
+
const requestId = typeof custom.requestId === 'string' ? custom.requestId : randomUUID();
|
|
379
|
+
const key = `${params.sessionId}:${requestId}`;
|
|
380
|
+
if (prompts.has(key))
|
|
381
|
+
throw new RequestError(-32000, 'Prompt request is already in flight');
|
|
382
|
+
if (params.prompt.some(block => !['text', 'image', 'audio'].includes(block.type)))
|
|
383
|
+
throw RequestError.invalidParams('Unsupported prompt content');
|
|
384
|
+
const attachments = params.prompt.filter(b => b.type === 'image' || b.type === 'audio').map(b => ({ mediaType: b.mimeType, data: b.data }));
|
|
385
|
+
// The installed runtime accepts text followed by attachments; reject orders
|
|
386
|
+
// it cannot preserve instead of silently rewriting model-visible content.
|
|
387
|
+
let mediaSeen = false;
|
|
388
|
+
for (const block of params.prompt) {
|
|
389
|
+
if (block.type !== 'text')
|
|
390
|
+
mediaSeen = true;
|
|
391
|
+
else if (mediaSeen)
|
|
392
|
+
throw RequestError.invalidParams('Text must precede attachments');
|
|
393
|
+
}
|
|
394
|
+
const result = new Promise((resolve, reject) => prompts.set(key, { sessionId: params.sessionId, requestId, turnId: custom.turnId, resolve, reject }));
|
|
395
|
+
// Connection loss preserves the turn. Explicit request cancellation while
|
|
396
|
+
// connected follows the same path as session/cancel.
|
|
397
|
+
signal.addEventListener('abort', () => { if (connected)
|
|
398
|
+
void peer.command(backend, { action: 'cancel_turn', sessionId: params.sessionId, turnId: custom.turnId }).catch(() => { }); }, { once: true });
|
|
399
|
+
try {
|
|
400
|
+
for (const content of params.prompt)
|
|
401
|
+
state.append(params.sessionId, { sessionUpdate: 'user_message_chunk', content });
|
|
402
|
+
const session = backend.sessions.get(params.sessionId);
|
|
403
|
+
if (session && custom.responsePolicy)
|
|
404
|
+
session.acpResponsePolicy = custom.responsePolicy;
|
|
405
|
+
await peer.command(backend, { ...custom, responsePolicy: 'stream', requestId, attachments, action: 'prompt', sessionId: params.sessionId, text: params.prompt.map(b => b.type === 'text' ? b.text : '').join('') });
|
|
406
|
+
}
|
|
407
|
+
catch (error) {
|
|
408
|
+
prompts.delete(key);
|
|
409
|
+
throw error;
|
|
410
|
+
}
|
|
411
|
+
return result;
|
|
412
|
+
})
|
|
413
|
+
.onNotification('session/cancel', async ({ params }) => { requireSession(params.sessionId); await peer.command(backend, { action: 'cancel_turn', sessionId: params.sessionId }); })
|
|
414
|
+
.onRequest('session/close', async ({ params }) => {
|
|
415
|
+
requireSession(params.sessionId);
|
|
416
|
+
await peer.command(backend, { action: 'close_session', sessionId: params.sessionId });
|
|
417
|
+
attached.delete(params.sessionId);
|
|
418
|
+
for (const [key, pending] of prompts)
|
|
419
|
+
if (pending.sessionId === params.sessionId) {
|
|
420
|
+
prompts.delete(key);
|
|
421
|
+
pending.resolve({ stopReason: 'cancelled' });
|
|
422
|
+
}
|
|
423
|
+
return {};
|
|
424
|
+
})
|
|
425
|
+
.onRequest('session/set_mode', async ({ params }) => { requireSession(params.sessionId); await peer.command(backend, { action: 'set_session_mode', sessionId: params.sessionId, payload: { modeId: params.modeId } }); return {}; })
|
|
426
|
+
.onRequest('session/set_config_option', async ({ params }) => { requireSession(params.sessionId); await peer.command(backend, { action: 'set_config_option', sessionId: params.sessionId, payload: { key: params.configId, value: params.value } }); return { configOptions: configOptions(await backend.status(params.sessionId)) }; })
|
|
427
|
+
.onRequest('session/list', async ({ params }) => {
|
|
428
|
+
requireInitialized();
|
|
429
|
+
if (params.cursor)
|
|
430
|
+
throw RequestError.invalidParams('Unknown session list cursor');
|
|
431
|
+
const bindings = state.list().filter(s => !s.deleted && s.agentType === agentName && (!params.cwd || s.cwd === params.cwd));
|
|
432
|
+
const sessions = [];
|
|
433
|
+
for (const binding of bindings) {
|
|
434
|
+
const record = await backend.record(binding.runtimeRecordId || binding.sessionId);
|
|
435
|
+
if (!record)
|
|
436
|
+
continue;
|
|
437
|
+
const live = backend.sessions.get(binding.sessionId);
|
|
438
|
+
sessions.push({ sessionId: binding.sessionId, cwd: binding.cwd, title: record.name, updatedAt: record.lastUsedAt || record.createdAt,
|
|
439
|
+
_meta: { [NS]: { agentCommand: record.agentCommand, createdAt: record.createdAt, lastUsedAt: record.lastUsedAt, status: live?.activeTurn ? 'running' : 'idle', closed: false } } });
|
|
440
|
+
}
|
|
441
|
+
return { sessions };
|
|
442
|
+
});
|
|
443
|
+
app.onRequest('session/delete', async ({ params }) => {
|
|
444
|
+
requireInitialized();
|
|
445
|
+
const binding = state.get(params.sessionId);
|
|
446
|
+
if (!binding || binding.deleted || binding.agentType !== agentName)
|
|
447
|
+
throw new RequestError(-32001, 'Session not found');
|
|
448
|
+
const owner = backend.sessions.get(params.sessionId)?.ws;
|
|
449
|
+
await peer.command(backend, { action: 'close_session', sessionId: params.sessionId });
|
|
450
|
+
owner?.send(JSON.stringify({ event: 'session_closed', sessionId: params.sessionId }));
|
|
451
|
+
await peer.command(backend, { action: 'delete_session', sessionId: params.sessionId, runtimeRecordId: binding.runtimeRecordId });
|
|
452
|
+
state.create({ ...binding, deleted: true });
|
|
453
|
+
attached.delete(params.sessionId);
|
|
454
|
+
return {};
|
|
455
|
+
});
|
|
456
|
+
app.onRequest(`${EXT}sessions/close_all`, (value) => value, async () => {
|
|
457
|
+
requireInitialized();
|
|
458
|
+
if (!extensions)
|
|
459
|
+
throw RequestError.methodNotFound(`${EXT}sessions/close_all`);
|
|
460
|
+
const owners = [...backend.sessions].map(([sessionId, session]) => ({ sessionId, peer: session.ws }));
|
|
461
|
+
await peer.command(backend, { action: 'close_all_sessions' });
|
|
462
|
+
for (const owner of owners)
|
|
463
|
+
owner.peer?.send(JSON.stringify({ event: 'session_closed', sessionId: owner.sessionId }));
|
|
464
|
+
return {};
|
|
465
|
+
});
|
|
466
|
+
app.onRequest(`${EXT}session/import`, (value) => {
|
|
467
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
468
|
+
throw RequestError.invalidParams('Expected object');
|
|
469
|
+
return value;
|
|
470
|
+
}, async ({ params }) => {
|
|
471
|
+
requireInitialized();
|
|
472
|
+
if (!extensions || typeof params.sessionId !== 'string' || !params.sessionId)
|
|
473
|
+
throw RequestError.invalidParams('Native session ID required');
|
|
474
|
+
return ensure({ ...params, _meta: { [NS]: { ...metadata(params), resumeSessionId: params.sessionId } } }, true, false);
|
|
475
|
+
});
|
|
476
|
+
const controls = { 'session/history': 'get_history', 'session/permission_mode': 'set_permission_mode', 'session/cancel_queued': 'cancel_queued', 'session/fork': 'fork_session', 'session/authenticate': 'authenticate', 'session/logout': 'logout' };
|
|
477
|
+
for (const [method, action] of Object.entries(controls)) {
|
|
478
|
+
app.onRequest(`${EXT}${method}`, (value) => {
|
|
479
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
480
|
+
throw RequestError.invalidParams('Expected object');
|
|
481
|
+
return value;
|
|
482
|
+
}, async ({ params }) => {
|
|
483
|
+
requireSession(params.sessionId);
|
|
484
|
+
if (!extensions)
|
|
485
|
+
throw RequestError.methodNotFound(method);
|
|
486
|
+
const events = await peer.command(backend, { ...params, action });
|
|
487
|
+
if (action === 'fork_session') {
|
|
488
|
+
const fork = events.find(e => e.type === 'session_forked')?.payload?.session;
|
|
489
|
+
if (fork)
|
|
490
|
+
state.create({ sessionId: fork.id, agentType: agentName, cwd: fork.cwd, completeHistory: false });
|
|
491
|
+
}
|
|
492
|
+
if (action === 'get_history')
|
|
493
|
+
return { items: events.find(e => e.event === 'history_response')?.items || [] };
|
|
494
|
+
if (action === 'fork_session')
|
|
495
|
+
return events.find(e => e.type === 'session_forked')?.payload || {};
|
|
496
|
+
if (action === 'set_permission_mode')
|
|
497
|
+
return { permissionMode: params.permissionMode };
|
|
498
|
+
return {};
|
|
499
|
+
});
|
|
500
|
+
}
|
|
501
|
+
ws.once('close', () => {
|
|
502
|
+
connected = false;
|
|
503
|
+
for (const item of interactive.values())
|
|
504
|
+
item.abort.abort();
|
|
505
|
+
for (const pending of prompts.values())
|
|
506
|
+
pending.reject(new Error('Connection closed; resume the session to observe the retained turn'));
|
|
507
|
+
prompts.clear();
|
|
508
|
+
});
|
|
509
|
+
const connection = app.connect(webSocketStream(ws));
|
|
510
|
+
client = connection.client;
|
|
511
|
+
return connection;
|
|
512
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { SessionUpdate } from '@agentclientprotocol/sdk';
|
|
2
|
+
export interface SessionBinding {
|
|
3
|
+
sessionId: string;
|
|
4
|
+
agentType: string;
|
|
5
|
+
cwd: string;
|
|
6
|
+
completeHistory: boolean;
|
|
7
|
+
runtimeRecordId?: string;
|
|
8
|
+
deleted?: boolean;
|
|
9
|
+
}
|
|
10
|
+
export declare class AcpState {
|
|
11
|
+
private readonly directory;
|
|
12
|
+
constructor(directory?: string);
|
|
13
|
+
private file;
|
|
14
|
+
get(id: string): SessionBinding | undefined;
|
|
15
|
+
list(): SessionBinding[];
|
|
16
|
+
create(binding: SessionBinding): void;
|
|
17
|
+
append(id: string, update: SessionUpdate): void;
|
|
18
|
+
history(id: string): SessionUpdate[];
|
|
19
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/** Durable ACP endpoint identity and replayable standard updates. */
|
|
2
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
3
|
+
import { mkdirSync, readFileSync, writeFileSync, appendFileSync, renameSync, existsSync, readdirSync } from 'node:fs';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { homedir } from 'node:os';
|
|
6
|
+
export class AcpState {
|
|
7
|
+
directory;
|
|
8
|
+
constructor(directory = join(process.env.ACP_STATE_DIR || join(homedir(), '.1agents', 'acpx-state'), 'acp')) {
|
|
9
|
+
this.directory = directory;
|
|
10
|
+
}
|
|
11
|
+
file(id, suffix) { return join(this.directory, `${createHash('sha256').update(id).digest('hex')}.${suffix}`); }
|
|
12
|
+
get(id) {
|
|
13
|
+
const file = this.file(id, 'json');
|
|
14
|
+
if (!existsSync(file))
|
|
15
|
+
return undefined;
|
|
16
|
+
return JSON.parse(readFileSync(file, 'utf8'));
|
|
17
|
+
}
|
|
18
|
+
list() {
|
|
19
|
+
if (!existsSync(this.directory))
|
|
20
|
+
return [];
|
|
21
|
+
return readdirSync(this.directory).filter(file => file.endsWith('.json')).map(file => JSON.parse(readFileSync(join(this.directory, file), 'utf8')));
|
|
22
|
+
}
|
|
23
|
+
create(binding) {
|
|
24
|
+
mkdirSync(this.directory, { recursive: true });
|
|
25
|
+
const file = this.file(binding.sessionId, 'json');
|
|
26
|
+
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
27
|
+
writeFileSync(temporary, JSON.stringify(binding) + '\n', { mode: 0o600, flag: 'wx' });
|
|
28
|
+
renameSync(temporary, file);
|
|
29
|
+
}
|
|
30
|
+
append(id, update) {
|
|
31
|
+
mkdirSync(this.directory, { recursive: true });
|
|
32
|
+
appendFileSync(this.file(id, 'jsonl'), JSON.stringify(update) + '\n', { mode: 0o600 });
|
|
33
|
+
}
|
|
34
|
+
history(id) {
|
|
35
|
+
const file = this.file(id, 'jsonl');
|
|
36
|
+
if (!existsSync(file))
|
|
37
|
+
return [];
|
|
38
|
+
const text = readFileSync(file, 'utf8');
|
|
39
|
+
// A torn final append after a process crash cannot be claimed as replayable.
|
|
40
|
+
if (text && !text.endsWith('\n'))
|
|
41
|
+
throw new Error('ACP history has an incomplete final record');
|
|
42
|
+
return text.trim() ? text.trimEnd().split('\n').map(line => JSON.parse(line)) : [];
|
|
43
|
+
}
|
|
44
|
+
}
|
package/dist/src/bridge.d.ts
CHANGED
|
@@ -1,15 +1,24 @@
|
|
|
1
1
|
export function resolveResponsePolicy(explicitPolicy: any, sessionPolicy: any): any;
|
|
2
2
|
export function attachBridgeServer(serverOrOptions?: {}): {
|
|
3
|
-
wss:
|
|
3
|
+
wss: WebSocketServer;
|
|
4
4
|
runtime: import("@scottzx/1acp/runtime").AcpxRuntime;
|
|
5
5
|
activeSessions: Map<any, any>;
|
|
6
6
|
close: typeof killAllManagedAgents;
|
|
7
7
|
};
|
|
8
|
-
|
|
8
|
+
/** Internal runtime command dispatch; the network entry point is ACP JSON-RPC. */
|
|
9
|
+
export function dispatchCommand(ws: any, payload: any): Promise<void>;
|
|
10
|
+
/** The standalone HTTP/WebSocket service stops on signals, independently of stdin. */
|
|
9
11
|
export function attachProcessSignalHandlers(): void;
|
|
10
|
-
export
|
|
12
|
+
export function readRuntimeRecord(id: any): Promise<any>;
|
|
13
|
+
/** @type {import("ws").WebSocketServer | null} */
|
|
14
|
+
export let wss: import("ws").WebSocketServer | null;
|
|
15
|
+
import { WebSocketServer } from "ws";
|
|
11
16
|
export function killAllManagedAgents(): Promise<void>;
|
|
12
17
|
export const runtime: import("@scottzx/1acp/runtime").AcpxRuntime;
|
|
13
18
|
export const activeSessions: Map<any, any>;
|
|
14
19
|
export const sessionBackgroundTasks: Map<any, any>;
|
|
15
20
|
export function gracefulExit(source: any): Promise<void>;
|
|
21
|
+
export const pendingPermissions: Map<any, any>;
|
|
22
|
+
export const pendingAskUserQuestions: Map<any, any>;
|
|
23
|
+
export const pendingExitPlanModes: Map<any, any>;
|
|
24
|
+
export function loadSessionHistory(sessionId: any, payload?: {}): Promise<any>;
|