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