@causyne/agent 1.10.21 → 1.12.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.
Files changed (82) hide show
  1. package/docs/THIRD_PARTY_NOTICES.md +12 -0
  2. package/native-skills/media/professional-document-publishing/SKILL.md +44 -0
  3. package/native-skills/media/screenplay-and-shotlist-forge/SKILL.md +42 -0
  4. package/package.json +1 -1
  5. package/src/acp/client.js +235 -0
  6. package/src/acp/client.ts +282 -0
  7. package/src/acp/peerProfiles.js +122 -0
  8. package/src/acp/peerProfiles.ts +128 -0
  9. package/src/acp/protocol.js +55 -0
  10. package/src/acp/protocol.ts +456 -0
  11. package/src/acp/server.js +746 -0
  12. package/src/acp/server.ts +822 -0
  13. package/src/agentLoop.d.ts +64 -0
  14. package/src/agentLoop.js +156 -12
  15. package/src/approvalGrants.js +33 -0
  16. package/src/approvalGrants.ts +50 -0
  17. package/src/commands.js +203 -0
  18. package/src/compiledSkills.js +10 -0
  19. package/src/decisionPolicy.js +2 -0
  20. package/src/decisionPolicy.ts +1 -0
  21. package/src/documentEngine/antiSlopAuditor.js +156 -0
  22. package/src/documentEngine/antiSlopAuditor.ts +221 -0
  23. package/src/documentEngine/documentForge.js +443 -0
  24. package/src/documentEngine/documentForge.ts +519 -0
  25. package/src/documentEngine/screenplayFormatter.js +336 -0
  26. package/src/documentEngine/screenplayFormatter.ts +407 -0
  27. package/src/engines/cad.js +113 -0
  28. package/src/engines/cad.ts +128 -0
  29. package/src/engines/film.js +108 -0
  30. package/src/engines/film.ts +104 -0
  31. package/src/engines/installer.js +226 -0
  32. package/src/engines/installer.ts +248 -0
  33. package/src/engines/photo.js +126 -0
  34. package/src/engines/photo.ts +137 -0
  35. package/src/engines/registry.js +186 -0
  36. package/src/engines/registry.ts +185 -0
  37. package/src/engines/sound.js +117 -0
  38. package/src/engines/sound.ts +130 -0
  39. package/src/engines/types.js +1 -0
  40. package/src/engines/types.ts +73 -0
  41. package/src/entrypoint.js +13 -0
  42. package/src/execSafe.js +10 -13
  43. package/src/execSafe.ts +25 -0
  44. package/src/memoryManager.js +9 -3
  45. package/src/modelRouter.js +56 -123
  46. package/src/modelRouter.ts +134 -0
  47. package/src/observer/advisory.js +164 -0
  48. package/src/observer/advisory.ts +171 -0
  49. package/src/observer/coldObserver.js +462 -0
  50. package/src/observer/coldObserver.ts +540 -0
  51. package/src/observer/evidence.js +435 -0
  52. package/src/observer/evidence.ts +499 -0
  53. package/src/perception.js +303 -118
  54. package/src/perception.ts +387 -0
  55. package/src/procSignal.js +15 -16
  56. package/src/procSignal.ts +31 -0
  57. package/src/promptMentions.js +170 -0
  58. package/src/promptMentions.ts +212 -0
  59. package/src/sandbox.js +9 -1
  60. package/src/sessionJournal.js +12 -2
  61. package/src/sessionJournal.ts +12 -2
  62. package/src/textDiff.js +117 -109
  63. package/src/textDiff.ts +169 -0
  64. package/src/toolPacks.js +19 -8
  65. package/src/tools/documentForge.js +215 -0
  66. package/src/tools/documentForge.ts +265 -0
  67. package/src/tools/generateMediaViaApi.js +1 -1
  68. package/src/tools/nativeEngine.js +464 -0
  69. package/src/tools/nativeEngine.ts +433 -0
  70. package/src/tools/openSourceToolProvisioner.js +510 -0
  71. package/src/tools/openSourceToolProvisioner.ts +590 -0
  72. package/src/tools/peerAgent.js +102 -0
  73. package/src/tools/peerAgent.ts +116 -0
  74. package/src/tools/registry.js +6 -1
  75. package/src/tui/completion.js +98 -42
  76. package/src/tui/prompt.js +17 -17
  77. package/src/uncertainty.js +93 -205
  78. package/src/uncertainty.ts +255 -0
  79. package/src/utils/paths.js +15 -18
  80. package/src/utils/paths.ts +36 -0
  81. package/src/vfeTracker.js +122 -181
  82. package/src/vfeTracker.ts +242 -0
@@ -0,0 +1,746 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { AgentLoop } from '../agentLoop.js';
5
+ import { createApprovalScope } from '../approvalGrants.js';
6
+ import { createSession, getSession, saveSessionMessages } from '../sessionJournal.js';
7
+ import { ACP_ERROR_CODES, ACP_METHODS, ACP_PROTOCOL_VERSION, isJsonRpcNotification, isJsonRpcRequest, isJsonRpcResponse } from './protocol.js';
8
+ const MODE_TO_AUTONOMY = {
9
+ autonomous: 'A',
10
+ standard: 'B',
11
+ supervised: 'C'
12
+ };
13
+ const MODES = {
14
+ currentModeId: 'standard',
15
+ availableModes: [
16
+ { id: 'autonomous', name: 'Autonomous', description: 'Runs without pausing for routine approvals' },
17
+ { id: 'standard', name: 'Standard', description: 'Asks before dangerous actions' },
18
+ { id: 'supervised', name: 'Supervised', description: 'Asks before most mutating actions' }
19
+ ]
20
+ };
21
+ const MAX_PROMPT_CHARS = 200_000;
22
+ const MAX_RAW_CHARS = 4000;
23
+ function textFromPrompt(prompt) {
24
+ const parts = [];
25
+ for (const block of prompt) {
26
+ if (block.type !== 'text')
27
+ return null;
28
+ parts.push(block.text);
29
+ }
30
+ return parts.join('\n').slice(0, MAX_PROMPT_CHARS);
31
+ }
32
+ function textFromContent(content) {
33
+ if (typeof content === 'string')
34
+ return content;
35
+ if (!Array.isArray(content))
36
+ return '';
37
+ const parts = [];
38
+ for (const block of content) {
39
+ if (block !== null && typeof block === 'object' && !Array.isArray(block)) {
40
+ const item = block;
41
+ if (item.type === 'text' && typeof item.text === 'string')
42
+ parts.push(item.text);
43
+ }
44
+ }
45
+ return parts.join('\n');
46
+ }
47
+ function toolKind(name) {
48
+ if (/^(fs_read|read_file|read|fs_list|list_dir|view_file)$/.test(name))
49
+ return 'read';
50
+ if (/^(fs_write|fs_edit|MultiEdit|write_file|edit_file)$/.test(name))
51
+ return 'edit';
52
+ if (/^(fs_delete|delete_file)$/.test(name))
53
+ return 'delete';
54
+ if (/^(fs_move|move_file)$/.test(name))
55
+ return 'move';
56
+ if (/^(grep|glob|search|find|code_search)$/.test(name))
57
+ return 'search';
58
+ if (/^(sysRun|sysRunBg|shell|terminal|terminal_persistent_shell|gitOp|proc_term)$/.test(name))
59
+ return 'execute';
60
+ if (/^(webFetch|webSearch|web_fetch|web_search)$/.test(name))
61
+ return 'fetch';
62
+ if (/^(request_decision|update_plan|think)$/.test(name))
63
+ return 'think';
64
+ return 'other';
65
+ }
66
+ function bounded(value, limit = MAX_RAW_CHARS) {
67
+ let text;
68
+ try {
69
+ text = typeof value === 'string' ? value : JSON.stringify(value ?? null);
70
+ }
71
+ catch {
72
+ text = '[unserializable]';
73
+ }
74
+ return text.length > limit ? `${text.slice(0, limit)}…[truncated]` : text;
75
+ }
76
+ function toolTitle(name, args) {
77
+ const detail = args.path || args.file_path || args.command || args.cmd || args.query || args.url || args.action;
78
+ const suffix = typeof detail === 'string' && detail.trim() ? ` ${detail.trim()}` : '';
79
+ const title = `${name}${suffix}`;
80
+ return title.length > 200 ? `${title.slice(0, 200)}…` : title;
81
+ }
82
+ export class AcpServer {
83
+ input;
84
+ output;
85
+ loopFactory;
86
+ agentName;
87
+ agentVersion;
88
+ permissionTimeoutMs;
89
+ sessions = new Map();
90
+ pending = new Map();
91
+ nextClientRequestId = 1;
92
+ buffer = '';
93
+ closed = false;
94
+ workspaceRoot = null;
95
+ dataListener = null;
96
+ endListener = null;
97
+ errorListener = null;
98
+ constructor(options = {}) {
99
+ this.input = options.input ?? null;
100
+ this.output = options.output ?? null;
101
+ this.loopFactory = options.loopFactory ?? null;
102
+ this.agentName = options.agentName ?? 'Causyne Agent';
103
+ this.agentVersion = options.agentVersion ?? '0.0.0';
104
+ this.permissionTimeoutMs = options.permissionTimeoutMs ?? 10 * 60 * 1000;
105
+ }
106
+ start() {
107
+ if (!this.input || this.dataListener)
108
+ return;
109
+ this.dataListener = (chunk) => {
110
+ this.buffer += typeof chunk === 'string' ? chunk : chunk.toString('utf8');
111
+ void this.drainBuffer();
112
+ };
113
+ this.endListener = () => { void this.stop(); };
114
+ this.errorListener = () => { void this.stop(); };
115
+ this.input.on('data', this.dataListener);
116
+ this.input.on('end', this.endListener);
117
+ this.input.on('error', this.errorListener);
118
+ }
119
+ async stop() {
120
+ if (this.closed)
121
+ return;
122
+ this.closed = true;
123
+ if (this.input && this.dataListener)
124
+ this.input.off('data', this.dataListener);
125
+ if (this.input && this.endListener)
126
+ this.input.off('end', this.endListener);
127
+ if (this.input && this.errorListener)
128
+ this.input.off('error', this.errorListener);
129
+ for (const session of this.sessions.values()) {
130
+ try {
131
+ session.loop?.abort();
132
+ }
133
+ catch {
134
+ // Shutdown never blocks on a misbehaving tool.
135
+ }
136
+ }
137
+ for (const [id, pending] of this.pending) {
138
+ clearTimeout(pending.timer);
139
+ pending.reject(new Error('server stopped'));
140
+ this.pending.delete(id);
141
+ }
142
+ }
143
+ async drainBuffer() {
144
+ let index = this.buffer.indexOf('\n');
145
+ while (index >= 0) {
146
+ const line = this.buffer.slice(0, index).trim();
147
+ this.buffer = this.buffer.slice(index + 1);
148
+ if (line)
149
+ await this.handleLine(line);
150
+ index = this.buffer.indexOf('\n');
151
+ }
152
+ }
153
+ async handleLine(line) {
154
+ let parsed;
155
+ try {
156
+ parsed = JSON.parse(line);
157
+ }
158
+ catch {
159
+ this.write({ jsonrpc: '2.0', id: null, error: { code: ACP_ERROR_CODES.PARSE_ERROR, message: 'Parse error' } });
160
+ return;
161
+ }
162
+ if (isJsonRpcResponse(parsed)) {
163
+ this.resolveClientRequest(parsed);
164
+ return;
165
+ }
166
+ if (isJsonRpcRequest(parsed)) {
167
+ await this.handleRequest(parsed);
168
+ return;
169
+ }
170
+ if (isJsonRpcNotification(parsed)) {
171
+ await this.handleNotification(parsed);
172
+ return;
173
+ }
174
+ this.write({ jsonrpc: '2.0', id: null, error: { code: ACP_ERROR_CODES.INVALID_REQUEST, message: 'Invalid request' } });
175
+ }
176
+ async handleNotification(notification) {
177
+ if (notification.method === ACP_METHODS.CANCEL) {
178
+ const params = notification.params;
179
+ const session = params && typeof params.sessionId === 'string' ? this.sessions.get(params.sessionId) : undefined;
180
+ if (session) {
181
+ session.cancelled = true;
182
+ try {
183
+ session.loop?.abort();
184
+ }
185
+ catch {
186
+ // Cancellation is best effort.
187
+ }
188
+ }
189
+ }
190
+ }
191
+ async handleRequest(request) {
192
+ try {
193
+ switch (request.method) {
194
+ case ACP_METHODS.INITIALIZE:
195
+ this.writeResult(request.id, this.initialize(request.params));
196
+ return;
197
+ case ACP_METHODS.NEW_SESSION:
198
+ this.writeResult(request.id, this.newSession(request.params));
199
+ return;
200
+ case ACP_METHODS.PROMPT:
201
+ this.writeResult(request.id, await this.prompt(request.params));
202
+ return;
203
+ case ACP_METHODS.SET_MODE:
204
+ this.writeResult(request.id, this.setMode(request.params));
205
+ return;
206
+ case ACP_METHODS.LIST:
207
+ this.writeResult(request.id, this.listSessions(request.params));
208
+ return;
209
+ case ACP_METHODS.CLOSE:
210
+ this.writeResult(request.id, this.closeSession(request.params));
211
+ return;
212
+ case ACP_METHODS.LOAD:
213
+ this.writeResult(request.id, this.loadSession(request.params));
214
+ return;
215
+ case ACP_METHODS.FORK:
216
+ this.writeResult(request.id, this.forkSession(request.params));
217
+ return;
218
+ default:
219
+ this.writeError(request.id, ACP_ERROR_CODES.METHOD_NOT_FOUND, `Unknown method: ${request.method}`);
220
+ }
221
+ }
222
+ catch (error) {
223
+ const code = error.acpCode ?? ACP_ERROR_CODES.INTERNAL_ERROR;
224
+ this.writeError(request.id, code, error instanceof Error ? error.message : String(error));
225
+ }
226
+ }
227
+ initialize(params) {
228
+ if (!params || typeof params.protocolVersion !== 'number') {
229
+ throw this.paramsError('initialize requires protocolVersion');
230
+ }
231
+ const capabilities = {
232
+ loadSession: true,
233
+ promptCapabilities: { image: false, audio: false, embeddedContext: false },
234
+ mcpCapabilities: { http: false, sse: false },
235
+ sessionCapabilities: { list: {}, close: {}, fork: {} }
236
+ };
237
+ return {
238
+ protocolVersion: ACP_PROTOCOL_VERSION,
239
+ agentCapabilities: capabilities,
240
+ agentInfo: { name: this.agentName, version: this.agentVersion }
241
+ };
242
+ }
243
+ paramsError(message) {
244
+ const error = new Error(message);
245
+ error.acpCode = ACP_ERROR_CODES.INVALID_PARAMS;
246
+ return error;
247
+ }
248
+ newSession(params) {
249
+ if (!params || typeof params.cwd !== 'string' || !params.cwd.trim()) {
250
+ throw this.paramsError('session/new requires cwd');
251
+ }
252
+ if (Array.isArray(params.mcpServers) && params.mcpServers.length > 0) {
253
+ throw this.paramsError('MCP servers are not supported by this agent');
254
+ }
255
+ if (Array.isArray(params.additionalDirectories) && params.additionalDirectories.length > 0) {
256
+ throw this.paramsError('additionalDirectories is not supported by this agent');
257
+ }
258
+ const cwd = this.resolveWorkspace(params.cwd);
259
+ this.bindWorkspace(cwd);
260
+ const record = createSession(cwd, 'Untitled', false);
261
+ const session = this.addSession(record.id, cwd, record.title, MODES.currentModeId);
262
+ return this.sessionResponse(session);
263
+ }
264
+ resolveWorkspace(cwd) {
265
+ if (typeof cwd !== 'string' || !cwd.trim())
266
+ throw this.paramsError('cwd is required');
267
+ try {
268
+ const resolved = fs.realpathSync(path.resolve(cwd));
269
+ if (!fs.statSync(resolved).isDirectory())
270
+ throw new Error('not a directory');
271
+ return resolved;
272
+ }
273
+ catch {
274
+ throw this.paramsError(`cwd is not an accessible directory: ${cwd}`);
275
+ }
276
+ }
277
+ bindWorkspace(cwd) {
278
+ if (this.workspaceRoot === null) {
279
+ this.workspaceRoot = cwd;
280
+ process.chdir(cwd);
281
+ }
282
+ else if (this.workspaceRoot !== cwd) {
283
+ throw this.paramsError(`server is bound to ${this.workspaceRoot}; one workspace per server`);
284
+ }
285
+ }
286
+ addSession(id, cwd, title, modeId) {
287
+ const session = {
288
+ id,
289
+ memorySessionId: id,
290
+ title,
291
+ cwd,
292
+ modeId,
293
+ loop: null,
294
+ busy: false,
295
+ cancelled: false,
296
+ updatedAt: Date.now(),
297
+ queue: Promise.resolve(),
298
+ approvalScope: createApprovalScope()
299
+ };
300
+ this.sessions.set(id, session);
301
+ return session;
302
+ }
303
+ modesFor(session) {
304
+ return {
305
+ currentModeId: session.modeId,
306
+ availableModes: MODES.availableModes.map((mode) => ({ ...mode }))
307
+ };
308
+ }
309
+ sessionResponse(session) {
310
+ return {
311
+ sessionId: session.id,
312
+ modes: this.modesFor(session)
313
+ };
314
+ }
315
+ requireSession(sessionId) {
316
+ if (typeof sessionId !== 'string' || !sessionId)
317
+ throw this.paramsError('sessionId is required');
318
+ const session = this.sessions.get(sessionId);
319
+ if (!session) {
320
+ const error = new Error(`Unknown session: ${sessionId}`);
321
+ error.acpCode = ACP_ERROR_CODES.RESOURCE_NOT_FOUND;
322
+ throw error;
323
+ }
324
+ return session;
325
+ }
326
+ async prompt(params) {
327
+ if (!params || !Array.isArray(params.prompt)) {
328
+ throw this.paramsError('session/prompt requires a prompt array');
329
+ }
330
+ const session = this.requireSession(params.sessionId);
331
+ const text = textFromPrompt(params.prompt);
332
+ if (text === null || !text.trim()) {
333
+ return { stopReason: 'refusal' };
334
+ }
335
+ session.queue = session.queue.then(() => this.runTurn(session, text), () => this.runTurn(session, text));
336
+ const stopReason = await session.queue;
337
+ return { stopReason };
338
+ }
339
+ async runTurn(session, text) {
340
+ session.updatedAt = Date.now();
341
+ session.cancelled = false;
342
+ session.busy = true;
343
+ const taskId = `acp-${crypto.randomUUID()}`;
344
+ const sink = {
345
+ readyState: 1,
346
+ send: (payload) => this.onLoopPayload(session, payload)
347
+ };
348
+ const loopOptions = {
349
+ workspaceRoot: session.cwd,
350
+ memorySessionId: session.memorySessionId,
351
+ approvalScope: session.approvalScope
352
+ };
353
+ const loop = this.loopFactory
354
+ ? this.loopFactory({
355
+ sessionId: session.id,
356
+ memorySessionId: session.memorySessionId,
357
+ taskId,
358
+ userPrompt: text,
359
+ cwd: session.cwd,
360
+ sink,
361
+ approvalScope: session.approvalScope
362
+ })
363
+ : new AgentLoop(sink, taskId, text, loopOptions);
364
+ const autonomy = MODE_TO_AUTONOMY[session.modeId];
365
+ if (autonomy) {
366
+ try {
367
+ loop.setAutonomyMode(autonomy);
368
+ }
369
+ catch {
370
+ // A loop without autonomy control simply keeps its configured mode.
371
+ }
372
+ }
373
+ loop.waitForDecision = async (request) => this.requestDecision(session, loop, request);
374
+ session.loop = loop;
375
+ let stopReason = 'end_turn';
376
+ try {
377
+ await loop.run();
378
+ }
379
+ catch {
380
+ stopReason = 'refusal';
381
+ }
382
+ finally {
383
+ session.loop = null;
384
+ session.busy = false;
385
+ const record = getSession(session.memorySessionId);
386
+ if (record)
387
+ session.title = record.title;
388
+ if (session.cancelled)
389
+ stopReason = 'cancelled';
390
+ }
391
+ return stopReason;
392
+ }
393
+ requestDecision(session, loop, request) {
394
+ if (request === null || typeof request !== 'object' || Array.isArray(request))
395
+ return Promise.resolve(null);
396
+ const record = request;
397
+ const options = Array.isArray(record.options) ? record.options : [];
398
+ const permissionOptions = [];
399
+ const labels = new Map();
400
+ for (const option of options) {
401
+ if (option === null || typeof option !== 'object' || Array.isArray(option))
402
+ continue;
403
+ const item = option;
404
+ const id = typeof item.id === 'string' ? item.id : '';
405
+ const label = typeof item.label === 'string' ? item.label : id;
406
+ if (!id)
407
+ continue;
408
+ labels.set(id, label);
409
+ permissionOptions.push({ optionId: id, name: label, kind: 'allow_once' });
410
+ }
411
+ if (permissionOptions.length === 0)
412
+ return Promise.resolve(null);
413
+ const toolCall = {
414
+ toolCallId: typeof record.id === 'string' ? record.id : crypto.randomUUID(),
415
+ title: typeof record.question === 'string' ? record.question.slice(0, 300) : 'Decision required',
416
+ kind: 'other',
417
+ status: 'pending'
418
+ };
419
+ return this.sendClientRequest(session, ACP_METHODS.REQUEST_PERMISSION, {
420
+ sessionId: session.id,
421
+ toolCall,
422
+ options: permissionOptions
423
+ }).then((response) => {
424
+ if (!response || response.outcome.outcome !== 'selected')
425
+ return null;
426
+ const optionId = response.outcome.optionId;
427
+ const label = labels.get(optionId);
428
+ if (!label)
429
+ return null;
430
+ return { optionId, label };
431
+ }).catch(() => null);
432
+ }
433
+ onLoopPayload(session, payload) {
434
+ let event;
435
+ try {
436
+ event = JSON.parse(payload);
437
+ }
438
+ catch {
439
+ return;
440
+ }
441
+ this.onLoopEvent(session, event);
442
+ }
443
+ onLoopEvent(session, event) {
444
+ switch (event.type) {
445
+ case 'agent_message': {
446
+ this.notify(session.id, { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: String(event.content ?? '') } });
447
+ return;
448
+ }
449
+ case 'agent_reasoning': {
450
+ const text = String(event.content ?? '');
451
+ if (text)
452
+ this.notify(session.id, { sessionUpdate: 'agent_thought_chunk', content: { type: 'text', text } });
453
+ return;
454
+ }
455
+ case 'status':
456
+ case 'notice': {
457
+ const text = String(event.message ?? '');
458
+ if (text)
459
+ this.notify(session.id, { sessionUpdate: 'agent_thought_chunk', content: { type: 'text', text } });
460
+ return;
461
+ }
462
+ case 'warning':
463
+ case 'budget_warning':
464
+ case 'error': {
465
+ const text = String(event.message ?? 'Task error');
466
+ this.notify(session.id, { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text } });
467
+ return;
468
+ }
469
+ case 'step_start': {
470
+ const tool = String(event.tool ?? 'tool');
471
+ const args = event.args !== null && typeof event.args === 'object' && !Array.isArray(event.args)
472
+ ? event.args
473
+ : {};
474
+ const toolCallId = typeof event.toolCallId === 'string' ? event.toolCallId : crypto.randomUUID();
475
+ this.notify(session.id, {
476
+ sessionUpdate: 'tool_call',
477
+ toolCallId,
478
+ title: toolTitle(tool, args),
479
+ kind: toolKind(tool),
480
+ status: 'in_progress',
481
+ rawInput: args
482
+ });
483
+ return;
484
+ }
485
+ case 'step_complete': {
486
+ const toolCallId = typeof event.toolCallId === 'string' ? event.toolCallId : null;
487
+ if (!toolCallId)
488
+ return;
489
+ const result = event.result;
490
+ const status = result && result.success === false ? 'failed' : 'completed';
491
+ this.notify(session.id, {
492
+ sessionUpdate: 'tool_call_update',
493
+ toolCallId,
494
+ status,
495
+ content: [{ type: 'content', content: { type: 'text', text: bounded(event.result) } }]
496
+ });
497
+ return;
498
+ }
499
+ case 'step_error': {
500
+ const toolCallId = typeof event.toolCallId === 'string' ? event.toolCallId : null;
501
+ if (!toolCallId)
502
+ return;
503
+ this.notify(session.id, {
504
+ sessionUpdate: 'tool_call_update',
505
+ toolCallId,
506
+ status: 'failed',
507
+ content: [{ type: 'content', content: { type: 'text', text: bounded(event.error ?? 'tool failed') } }]
508
+ });
509
+ return;
510
+ }
511
+ case 'agent_plan': {
512
+ const plan = Array.isArray(event.plan) ? event.plan : [];
513
+ this.notify(session.id, {
514
+ sessionUpdate: 'plan',
515
+ entries: plan.map((entry) => {
516
+ const item = entry !== null && typeof entry === 'object' && !Array.isArray(entry)
517
+ ? entry
518
+ : {};
519
+ const status = item.status === 'completed' || item.status === 'in_progress' ? item.status : 'pending';
520
+ return {
521
+ content: String(item.text ?? item.content ?? 'step'),
522
+ priority: 'medium',
523
+ status
524
+ };
525
+ })
526
+ });
527
+ return;
528
+ }
529
+ case 'approval_request': {
530
+ const toolCallId = String(event.toolCallId ?? '');
531
+ if (!toolCallId)
532
+ return;
533
+ const args = event.args !== null && typeof event.args === 'object' && !Array.isArray(event.args)
534
+ ? event.args
535
+ : {};
536
+ const tool = String(event.tool ?? 'tool');
537
+ const toolCall = {
538
+ toolCallId,
539
+ title: toolTitle(tool, args),
540
+ kind: toolKind(tool),
541
+ status: 'pending',
542
+ rawInput: args
543
+ };
544
+ const options = [
545
+ { optionId: 'allow_once', name: 'Allow this action', kind: 'allow_once' },
546
+ { optionId: 'allow_always', name: 'Always allow this tool in this conversation', kind: 'allow_always' },
547
+ { optionId: 'reject_once', name: 'Reject this action', kind: 'reject_once' }
548
+ ];
549
+ void this.sendClientRequest(session, ACP_METHODS.REQUEST_PERMISSION, {
550
+ sessionId: session.id,
551
+ toolCall,
552
+ options
553
+ }).then((response) => {
554
+ const selected = response?.outcome.outcome === 'selected' ? response.outcome.optionId : '';
555
+ if (selected === 'allow_always')
556
+ session.approvalScope.grantAlways(tool);
557
+ const approved = selected === 'allow_once' || selected === 'allow_always';
558
+ session.loop?.handleApprovalResponse(toolCallId, approved);
559
+ }).catch(() => {
560
+ session.loop?.handleApprovalResponse(toolCallId, false);
561
+ });
562
+ return;
563
+ }
564
+ default:
565
+ return;
566
+ }
567
+ }
568
+ notify(sessionId, update) {
569
+ const notification = {
570
+ jsonrpc: '2.0',
571
+ method: ACP_METHODS.UPDATE,
572
+ params: { sessionId, update }
573
+ };
574
+ this.write(notification);
575
+ }
576
+ setMode(params) {
577
+ if (!params || typeof params.modeId !== 'string')
578
+ throw this.paramsError('session/set_mode requires modeId');
579
+ const session = this.requireSession(params.sessionId);
580
+ if (!MODES.availableModes.some((mode) => mode.id === params.modeId)) {
581
+ throw this.paramsError(`Unknown mode: ${params.modeId}`);
582
+ }
583
+ session.modeId = params.modeId;
584
+ session.updatedAt = Date.now();
585
+ const autonomy = MODE_TO_AUTONOMY[session.modeId];
586
+ if (autonomy && session.loop) {
587
+ try {
588
+ session.loop.setAutonomyMode(autonomy);
589
+ }
590
+ catch {
591
+ // The running loop keeps its mode; the next turn picks the new one.
592
+ }
593
+ }
594
+ this.notify(session.id, { sessionUpdate: 'current_mode_update', currentModeId: session.modeId });
595
+ return {};
596
+ }
597
+ listSessions(params) {
598
+ const filter = params && typeof params.cwd === 'string' ? path.resolve(params.cwd) : null;
599
+ const sessions = [];
600
+ for (const session of this.sessions.values()) {
601
+ if (filter && session.cwd !== filter)
602
+ continue;
603
+ sessions.push({
604
+ sessionId: session.id,
605
+ cwd: session.cwd,
606
+ title: session.title,
607
+ updatedAt: new Date(session.updatedAt).toISOString()
608
+ });
609
+ }
610
+ sessions.sort((a, b) => (b.updatedAt ?? '').localeCompare(a.updatedAt ?? ''));
611
+ return { sessions };
612
+ }
613
+ closeSession(params) {
614
+ const session = this.requireSession(params?.sessionId);
615
+ session.cancelled = true;
616
+ try {
617
+ session.loop?.abort();
618
+ }
619
+ catch {
620
+ // Closing never blocks on cancellation.
621
+ }
622
+ this.sessions.delete(session.id);
623
+ return {};
624
+ }
625
+ /** Resume a persisted conversation, replaying its transcript to the client. */
626
+ loadSession(params) {
627
+ if (!params || typeof params.sessionId !== 'string' || !params.sessionId) {
628
+ throw this.paramsError('session/load requires sessionId');
629
+ }
630
+ const live = this.sessions.get(params.sessionId);
631
+ if (live) {
632
+ this.bindWorkspace(live.cwd);
633
+ this.replayTranscript(live, getSession(live.memorySessionId)?.messages ?? []);
634
+ return { modes: this.modesFor(live) };
635
+ }
636
+ const record = getSession(params.sessionId);
637
+ if (!record)
638
+ throw this.notFound(`Unknown session: ${params.sessionId}`);
639
+ const requested = params.cwd ?? record.workspace;
640
+ const cwd = this.resolveWorkspace(requested);
641
+ if (record.workspace && path.resolve(record.workspace) !== cwd) {
642
+ throw this.paramsError('session workspace does not match cwd');
643
+ }
644
+ this.bindWorkspace(cwd);
645
+ const session = this.addSession(record.id, cwd, record.title, MODES.currentModeId);
646
+ this.replayTranscript(session, record.messages);
647
+ return { modes: this.modesFor(session) };
648
+ }
649
+ /**
650
+ * Copy the conversation into a new session and deliberately start with a
651
+ * fresh approval scope. Permissions are granted to a conversation, never to
652
+ * the transcript, so a fork must ask again for anything dangerous.
653
+ */
654
+ forkSession(params) {
655
+ if (!params || typeof params.sessionId !== 'string' || !params.sessionId) {
656
+ throw this.paramsError('session/fork requires sessionId');
657
+ }
658
+ const source = this.sessions.get(params.sessionId);
659
+ const sourceRecord = getSession(params.sessionId);
660
+ if (!source && !sourceRecord)
661
+ throw this.notFound(`Unknown session: ${params.sessionId}`);
662
+ if (source?.busy)
663
+ throw this.paramsError('session is busy; cancel it before forking');
664
+ const requested = params.cwd ?? source?.cwd ?? sourceRecord?.workspace;
665
+ const cwd = this.resolveWorkspace(requested);
666
+ if (source && source.cwd !== cwd)
667
+ throw this.paramsError('fork must stay in the source workspace');
668
+ if (sourceRecord?.workspace && path.resolve(sourceRecord.workspace) !== cwd) {
669
+ throw this.paramsError('fork must stay in the source workspace');
670
+ }
671
+ this.bindWorkspace(cwd);
672
+ const title = `Fork of ${source?.title || sourceRecord?.title || 'Untitled'}`;
673
+ const created = createSession(cwd, title, false);
674
+ if (sourceRecord && sourceRecord.messages.length > 0) {
675
+ saveSessionMessages(created.id, sourceRecord.messages);
676
+ }
677
+ const session = this.addSession(created.id, cwd, title, source?.modeId ?? MODES.currentModeId);
678
+ return this.sessionResponse(session);
679
+ }
680
+ replayTranscript(session, messages) {
681
+ for (const message of messages) {
682
+ const role = typeof message.role === 'string' ? message.role : '';
683
+ const text = textFromContent(message.content);
684
+ if (!text)
685
+ continue;
686
+ if (role === 'user') {
687
+ this.notify(session.id, { sessionUpdate: 'user_message_chunk', content: { type: 'text', text } });
688
+ }
689
+ else if (role === 'assistant') {
690
+ this.notify(session.id, { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text } });
691
+ }
692
+ }
693
+ }
694
+ notFound(message) {
695
+ const error = new Error(message);
696
+ error.acpCode = ACP_ERROR_CODES.RESOURCE_NOT_FOUND;
697
+ return error;
698
+ }
699
+ sendClientRequest(session, method, params) {
700
+ const id = `server-${this.nextClientRequestId++}`;
701
+ return new Promise((resolve, reject) => {
702
+ const timer = setTimeout(() => {
703
+ this.pending.delete(id);
704
+ reject(new Error(`${method} timed out`));
705
+ }, this.permissionTimeoutMs);
706
+ this.pending.set(id, {
707
+ resolve: (value) => resolve(value),
708
+ reject,
709
+ timer
710
+ });
711
+ this.write({ jsonrpc: '2.0', id, method, params });
712
+ });
713
+ }
714
+ resolveClientRequest(response) {
715
+ if (response.id === null || response.id === undefined)
716
+ return;
717
+ const pending = this.pending.get(response.id);
718
+ if (!pending)
719
+ return;
720
+ clearTimeout(pending.timer);
721
+ this.pending.delete(response.id);
722
+ if (response.error) {
723
+ pending.reject(new Error(response.error.message));
724
+ return;
725
+ }
726
+ pending.resolve(response.result);
727
+ }
728
+ writeResult(id, result) {
729
+ this.write({ jsonrpc: '2.0', id, result });
730
+ }
731
+ writeError(id, code, message) {
732
+ const error = { code, message };
733
+ this.write({ jsonrpc: '2.0', id, error });
734
+ }
735
+ write(message) {
736
+ if (!this.output || this.closed)
737
+ return;
738
+ try {
739
+ this.output.write(`${JSON.stringify(message)}\n`);
740
+ }
741
+ catch {
742
+ // A closed pipe must not crash the agent process.
743
+ }
744
+ }
745
+ }
746
+ export { MODES as ACP_SESSION_MODES };