kodorun-cli 0.0.0-stage → 0.1.122
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 +99 -2
- package/dist/ai/acp.d.ts +95 -0
- package/dist/ai/acp.js +771 -0
- package/dist/ai/antigravity.d.ts +4 -0
- package/dist/ai/antigravity.js +29 -0
- package/dist/ai/claude.d.ts +4 -0
- package/dist/ai/claude.js +45 -0
- package/dist/ai/codex.d.ts +154 -0
- package/dist/ai/codex.js +2241 -0
- package/dist/ai/cursor.d.ts +4 -0
- package/dist/ai/cursor.js +56 -0
- package/dist/ai/gemini.d.ts +4 -0
- package/dist/ai/gemini.js +26 -0
- package/dist/ai/index.d.ts +58 -0
- package/dist/ai/index.js +137 -0
- package/dist/ai/interface.d.ts +95 -0
- package/dist/ai/interface.js +10 -0
- package/dist/ai/opencode.d.ts +72 -0
- package/dist/ai/opencode.js +906 -0
- package/dist/ai/session-store.d.ts +36 -0
- package/dist/ai/session-store.js +252 -0
- package/dist/ai/stream-json.d.ts +80 -0
- package/dist/ai/stream-json.js +555 -0
- package/dist/cli.test.d.ts +1 -0
- package/dist/cli.test.js +167 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +3736 -0
- package/dist/transport/protocol.d.ts +77 -0
- package/dist/transport/protocol.js +80 -0
- package/dist/transport/v2.d.ts +49 -0
- package/dist/transport/v2.js +362 -0
- package/package.json +59 -4
package/dist/ai/acp.js
ADDED
|
@@ -0,0 +1,771 @@
|
|
|
1
|
+
import * as crypto from "crypto";
|
|
2
|
+
import { createInterface } from "readline";
|
|
3
|
+
import { LocalAiSessionStore, loadAuthSecrets, resolveExecutable, saveAuthSecret, spawnCliBinary, } from "./session-store.js";
|
|
4
|
+
const DEFAULT_AGENTS = [
|
|
5
|
+
{ name: "Build", mode: "build", description: "Default coding and execution mode." },
|
|
6
|
+
{ name: "Plan", mode: "plan", description: "Read-only planning mode." },
|
|
7
|
+
];
|
|
8
|
+
function asRecord(value) {
|
|
9
|
+
return value && typeof value === "object" ? value : {};
|
|
10
|
+
}
|
|
11
|
+
function readString(value) {
|
|
12
|
+
return typeof value === "string" && value.trim().length > 0 ? value : undefined;
|
|
13
|
+
}
|
|
14
|
+
export class AcpProvider {
|
|
15
|
+
config;
|
|
16
|
+
store;
|
|
17
|
+
executablePath = null;
|
|
18
|
+
proc = null;
|
|
19
|
+
initPromise = null;
|
|
20
|
+
shuttingDown = false;
|
|
21
|
+
emitter = null;
|
|
22
|
+
nextId = 1;
|
|
23
|
+
pending = new Map();
|
|
24
|
+
loadedRemoteSessions = new Set();
|
|
25
|
+
discoveredModels = [];
|
|
26
|
+
discoveredDefaultModel;
|
|
27
|
+
availableModes = new Map();
|
|
28
|
+
activeTurnBySession = new Map();
|
|
29
|
+
activeStatusBySession = new Map();
|
|
30
|
+
pendingPermissions = new Map();
|
|
31
|
+
apiKeyOverride = null;
|
|
32
|
+
constructor(config) {
|
|
33
|
+
this.config = config;
|
|
34
|
+
this.store = new LocalAiSessionStore(config.backend, process.cwd());
|
|
35
|
+
const saved = loadAuthSecrets();
|
|
36
|
+
if (saved[config.authEnvKey]) {
|
|
37
|
+
this.apiKeyOverride = saved[config.authEnvKey];
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
debugLog(message, ...args) {
|
|
41
|
+
if (process.env.KODORUN_DEBUG === "1" || process.env.KODORUN_DEBUG_AI === "1") {
|
|
42
|
+
console.log(`[${this.config.backend}] ${message}`, ...args);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
async init() {
|
|
46
|
+
const resolved = resolveExecutable(this.config.binaryCandidates, this.config.extraBinaryPaths ?? []);
|
|
47
|
+
if (!resolved) {
|
|
48
|
+
throw new Error(`${this.config.displayName} CLI is not installed`);
|
|
49
|
+
}
|
|
50
|
+
this.executablePath = resolved;
|
|
51
|
+
}
|
|
52
|
+
async destroy() {
|
|
53
|
+
this.shuttingDown = true;
|
|
54
|
+
for (const [id, entry] of this.pending) {
|
|
55
|
+
clearTimeout(entry.timer);
|
|
56
|
+
entry.reject(new Error(`${this.config.displayName} provider shut down`));
|
|
57
|
+
this.pending.delete(id);
|
|
58
|
+
}
|
|
59
|
+
if (this.proc) {
|
|
60
|
+
try {
|
|
61
|
+
this.proc.stdin?.end();
|
|
62
|
+
}
|
|
63
|
+
catch { }
|
|
64
|
+
this.proc.kill();
|
|
65
|
+
this.proc = null;
|
|
66
|
+
}
|
|
67
|
+
this.initPromise = null;
|
|
68
|
+
this.loadedRemoteSessions.clear();
|
|
69
|
+
}
|
|
70
|
+
subscribe(emitter) {
|
|
71
|
+
this.emitter = emitter;
|
|
72
|
+
return () => {
|
|
73
|
+
this.emitter = null;
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
async ensureProcessReady() {
|
|
77
|
+
if (this.proc && this.proc.exitCode === null)
|
|
78
|
+
return;
|
|
79
|
+
if (this.initPromise)
|
|
80
|
+
return this.initPromise;
|
|
81
|
+
this.initPromise = (async () => {
|
|
82
|
+
if (!this.executablePath) {
|
|
83
|
+
await this.init();
|
|
84
|
+
}
|
|
85
|
+
const cmdPath = this.executablePath;
|
|
86
|
+
const env = { ...process.env };
|
|
87
|
+
if (this.apiKeyOverride) {
|
|
88
|
+
env[this.config.authEnvKey] = this.apiKeyOverride;
|
|
89
|
+
}
|
|
90
|
+
this.shuttingDown = false;
|
|
91
|
+
this.loadedRemoteSessions.clear();
|
|
92
|
+
this.proc = spawnCliBinary(cmdPath, this.config.acpArgs, {
|
|
93
|
+
cwd: process.cwd(),
|
|
94
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
95
|
+
env,
|
|
96
|
+
});
|
|
97
|
+
this.proc.stdin?.on("error", (err) => {
|
|
98
|
+
this.debugLog("stdin error:", err.message);
|
|
99
|
+
});
|
|
100
|
+
const rl = createInterface({ input: this.proc.stdout });
|
|
101
|
+
rl.on("line", (line) => this.handleLine(line));
|
|
102
|
+
let lastStderr = "";
|
|
103
|
+
this.proc.stderr?.on("data", (chunk) => {
|
|
104
|
+
const text = chunk.toString().trim();
|
|
105
|
+
if (text) {
|
|
106
|
+
lastStderr = text.split(/\r?\n/).filter(Boolean).pop() ?? lastStderr;
|
|
107
|
+
this.debugLog("stderr:", text.slice(0, 400));
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
this.proc.on("error", (err) => {
|
|
111
|
+
this.debugLog("process error:", err.message);
|
|
112
|
+
});
|
|
113
|
+
this.proc.on("exit", (code) => {
|
|
114
|
+
const wasShuttingDown = this.shuttingDown;
|
|
115
|
+
this.proc = null;
|
|
116
|
+
this.initPromise = null;
|
|
117
|
+
this.loadedRemoteSessions.clear();
|
|
118
|
+
const exitDetail = lastStderr ? `${this.config.displayName} exited (${code}): ${lastStderr.slice(0, 200)}` : `${this.config.displayName} exited (${code})`;
|
|
119
|
+
for (const [key, req] of this.pending) {
|
|
120
|
+
clearTimeout(req.timer);
|
|
121
|
+
req.reject(new Error(exitDetail));
|
|
122
|
+
this.pending.delete(key);
|
|
123
|
+
}
|
|
124
|
+
if (!wasShuttingDown) {
|
|
125
|
+
for (const [sid, status] of this.activeStatusBySession) {
|
|
126
|
+
if (status === "running") {
|
|
127
|
+
this.activeStatusBySession.set(sid, "idle");
|
|
128
|
+
this.emitter?.({ type: "session.idle", properties: { sessionID: sid } });
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
});
|
|
133
|
+
try {
|
|
134
|
+
await this.call("initialize", {
|
|
135
|
+
protocolVersion: 1,
|
|
136
|
+
clientInfo: { name: "kodorun", version: "1.0" },
|
|
137
|
+
clientCapabilities: {},
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
catch (err) {
|
|
141
|
+
const orphan = this.proc;
|
|
142
|
+
this.proc = null;
|
|
143
|
+
try {
|
|
144
|
+
orphan?.kill();
|
|
145
|
+
}
|
|
146
|
+
catch { /* ignore */ }
|
|
147
|
+
throw err;
|
|
148
|
+
}
|
|
149
|
+
if (this.apiKeyOverride && this.config.authMethodId) {
|
|
150
|
+
await this.call("authenticate", { methodId: this.config.authMethodId }).catch(() => {
|
|
151
|
+
// Best effort for backends that inspect env directly
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
})();
|
|
155
|
+
try {
|
|
156
|
+
await this.initPromise;
|
|
157
|
+
}
|
|
158
|
+
catch (err) {
|
|
159
|
+
this.initPromise = null;
|
|
160
|
+
throw err;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
sendJson(payload) {
|
|
164
|
+
if (!this.proc?.stdin?.writable) {
|
|
165
|
+
throw new Error(`${this.config.displayName} stdin is not writable`);
|
|
166
|
+
}
|
|
167
|
+
this.proc.stdin.write(JSON.stringify(payload) + "\n");
|
|
168
|
+
}
|
|
169
|
+
call(method, params, timeoutMs = 180_000) {
|
|
170
|
+
return new Promise((resolve, reject) => {
|
|
171
|
+
const id = this.nextId++;
|
|
172
|
+
const key = String(id);
|
|
173
|
+
const timer = setTimeout(() => {
|
|
174
|
+
if (this.pending.has(key)) {
|
|
175
|
+
this.pending.delete(key);
|
|
176
|
+
reject(new Error(`${this.config.displayName} RPC timeout: ${method}`));
|
|
177
|
+
}
|
|
178
|
+
}, timeoutMs);
|
|
179
|
+
this.pending.set(key, { resolve, reject, timer });
|
|
180
|
+
try {
|
|
181
|
+
this.sendJson({ jsonrpc: "2.0", id, method, params });
|
|
182
|
+
}
|
|
183
|
+
catch (err) {
|
|
184
|
+
clearTimeout(timer);
|
|
185
|
+
this.pending.delete(key);
|
|
186
|
+
reject(err);
|
|
187
|
+
}
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
notify(method, params) {
|
|
191
|
+
this.sendJson({ jsonrpc: "2.0", method, params });
|
|
192
|
+
}
|
|
193
|
+
handleLine(line) {
|
|
194
|
+
const trimmed = line.trim();
|
|
195
|
+
if (!trimmed)
|
|
196
|
+
return;
|
|
197
|
+
let msg;
|
|
198
|
+
try {
|
|
199
|
+
msg = JSON.parse(trimmed);
|
|
200
|
+
}
|
|
201
|
+
catch {
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
if (typeof msg.method === "string") {
|
|
205
|
+
const params = asRecord(msg.params);
|
|
206
|
+
if (msg.id != null) {
|
|
207
|
+
this.handleServerRequest(msg.method, msg.id, params);
|
|
208
|
+
}
|
|
209
|
+
else {
|
|
210
|
+
this.handleNotification(msg.method, params);
|
|
211
|
+
}
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
if (msg.id != null) {
|
|
215
|
+
const key = String(msg.id);
|
|
216
|
+
const pending = this.pending.get(key);
|
|
217
|
+
if (!pending)
|
|
218
|
+
return;
|
|
219
|
+
clearTimeout(pending.timer);
|
|
220
|
+
this.pending.delete(key);
|
|
221
|
+
if (msg.error && typeof msg.error === "object") {
|
|
222
|
+
const errObj = asRecord(msg.error);
|
|
223
|
+
const message = readString(errObj.message) ?? JSON.stringify(msg.error);
|
|
224
|
+
pending.reject(new Error(message));
|
|
225
|
+
}
|
|
226
|
+
else {
|
|
227
|
+
pending.resolve(msg.result ?? null);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
handleServerRequest(method, requestId, params) {
|
|
232
|
+
if (method === "session/request_permission") {
|
|
233
|
+
const sessionId = this.resolveLocalSessionId(readString(params.sessionId)) ?? "";
|
|
234
|
+
const toolCall = asRecord(params.toolCall);
|
|
235
|
+
const rawOptions = Array.isArray(params.options) ? params.options : [];
|
|
236
|
+
const options = rawOptions
|
|
237
|
+
.map((opt) => {
|
|
238
|
+
const rec = asRecord(opt);
|
|
239
|
+
const optionId = readString(rec.optionId);
|
|
240
|
+
if (!optionId)
|
|
241
|
+
return null;
|
|
242
|
+
return {
|
|
243
|
+
optionId,
|
|
244
|
+
kind: readString(rec.kind),
|
|
245
|
+
name: readString(rec.name),
|
|
246
|
+
};
|
|
247
|
+
})
|
|
248
|
+
.filter((o) => Boolean(o));
|
|
249
|
+
const permissionId = String(requestId);
|
|
250
|
+
const turn = sessionId ? this.activeTurnBySession.get(sessionId) : undefined;
|
|
251
|
+
const callId = readString(toolCall.toolCallId);
|
|
252
|
+
this.pendingPermissions.set(permissionId, {
|
|
253
|
+
requestId,
|
|
254
|
+
sessionId,
|
|
255
|
+
options,
|
|
256
|
+
});
|
|
257
|
+
this.emitter?.({
|
|
258
|
+
type: "permission.updated",
|
|
259
|
+
properties: {
|
|
260
|
+
id: permissionId,
|
|
261
|
+
sessionID: sessionId,
|
|
262
|
+
messageID: turn?.messageId,
|
|
263
|
+
callID: callId,
|
|
264
|
+
type: readString(toolCall.kind) ?? "permission",
|
|
265
|
+
title: readString(toolCall.title) ?? "Permission requested",
|
|
266
|
+
metadata: toolCall,
|
|
267
|
+
},
|
|
268
|
+
});
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
this.sendJson({
|
|
272
|
+
jsonrpc: "2.0",
|
|
273
|
+
id: requestId,
|
|
274
|
+
error: { code: -32601, message: `Unsupported ACP client method: ${method}` },
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
resolveLocalSessionId(remoteOrLocalId) {
|
|
278
|
+
if (!remoteOrLocalId)
|
|
279
|
+
return undefined;
|
|
280
|
+
if (this.store.get(remoteOrLocalId))
|
|
281
|
+
return remoteOrLocalId;
|
|
282
|
+
for (const rec of this.store.listForWorkspace()) {
|
|
283
|
+
if (rec.remoteSessionId === remoteOrLocalId)
|
|
284
|
+
return rec.id;
|
|
285
|
+
}
|
|
286
|
+
return remoteOrLocalId;
|
|
287
|
+
}
|
|
288
|
+
handleNotification(method, params) {
|
|
289
|
+
if (method !== "session/update")
|
|
290
|
+
return;
|
|
291
|
+
const sessionId = this.resolveLocalSessionId(readString(params.sessionId));
|
|
292
|
+
if (!sessionId)
|
|
293
|
+
return;
|
|
294
|
+
const update = asRecord(params.update);
|
|
295
|
+
const kind = readString(update.sessionUpdate);
|
|
296
|
+
if (!kind)
|
|
297
|
+
return;
|
|
298
|
+
if (kind === "session_info_update") {
|
|
299
|
+
const title = readString(update.title);
|
|
300
|
+
const rec = this.store.get(sessionId);
|
|
301
|
+
if (rec && title) {
|
|
302
|
+
rec.title = title;
|
|
303
|
+
rec.updatedAt = Date.now();
|
|
304
|
+
this.store.upsert(rec);
|
|
305
|
+
this.emitter?.({ type: "session.updated", properties: { info: this.store.toSessionInfo(rec) } });
|
|
306
|
+
}
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
if (kind === "config_option_update") {
|
|
310
|
+
const opts = Array.isArray(update.configOptions) ? update.configOptions : [];
|
|
311
|
+
for (const opt of opts) {
|
|
312
|
+
const rec = asRecord(opt);
|
|
313
|
+
if (rec.id === "model" && Array.isArray(rec.options)) {
|
|
314
|
+
const mapped = [];
|
|
315
|
+
for (const entry of rec.options) {
|
|
316
|
+
const o = asRecord(entry);
|
|
317
|
+
const id = readString(o.value);
|
|
318
|
+
const name = readString(o.name) ?? id;
|
|
319
|
+
if (id && name)
|
|
320
|
+
mapped.push({ id, name, reasoning: true, attachment: true });
|
|
321
|
+
}
|
|
322
|
+
if (mapped.length > 0)
|
|
323
|
+
this.discoveredModels = mapped;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
if (kind === "usage_update") {
|
|
329
|
+
this.emitter?.({
|
|
330
|
+
type: "session.usage",
|
|
331
|
+
properties: { sessionID: sessionId, tokenUsage: update },
|
|
332
|
+
});
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
const turn = this.activeTurnBySession.get(sessionId);
|
|
336
|
+
if (!turn)
|
|
337
|
+
return;
|
|
338
|
+
if (kind === "agent_message_chunk") {
|
|
339
|
+
const content = asRecord(update.content);
|
|
340
|
+
const chunk = readString(content.text) ?? (typeof content.text === "string" ? content.text : "");
|
|
341
|
+
if (!chunk)
|
|
342
|
+
return;
|
|
343
|
+
if (!turn.textPartId) {
|
|
344
|
+
turn.textPartId = `${turn.messageId}:text:${crypto.randomUUID()}`;
|
|
345
|
+
}
|
|
346
|
+
turn.textContent += chunk;
|
|
347
|
+
const part = {
|
|
348
|
+
id: turn.textPartId,
|
|
349
|
+
sessionID: sessionId,
|
|
350
|
+
messageID: turn.messageId,
|
|
351
|
+
type: "text",
|
|
352
|
+
text: turn.textContent,
|
|
353
|
+
};
|
|
354
|
+
this.store.upsertPart(sessionId, turn.messageId, "assistant", part);
|
|
355
|
+
this.emitPart(sessionId, turn.messageId, part);
|
|
356
|
+
return;
|
|
357
|
+
}
|
|
358
|
+
if (kind === "agent_thought_chunk") {
|
|
359
|
+
const content = asRecord(update.content);
|
|
360
|
+
const chunk = readString(content.text) ?? (typeof content.text === "string" ? content.text : "");
|
|
361
|
+
if (!chunk)
|
|
362
|
+
return;
|
|
363
|
+
if (!turn.reasoningPartId) {
|
|
364
|
+
turn.reasoningPartId = `${turn.messageId}:reasoning:${crypto.randomUUID()}`;
|
|
365
|
+
}
|
|
366
|
+
turn.reasoningContent += chunk;
|
|
367
|
+
const part = {
|
|
368
|
+
id: turn.reasoningPartId,
|
|
369
|
+
sessionID: sessionId,
|
|
370
|
+
messageID: turn.messageId,
|
|
371
|
+
type: "reasoning",
|
|
372
|
+
text: turn.reasoningContent,
|
|
373
|
+
};
|
|
374
|
+
this.store.upsertPart(sessionId, turn.messageId, "assistant", part);
|
|
375
|
+
this.emitPart(sessionId, turn.messageId, part);
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
if (kind === "tool_call" || kind === "tool_call_update") {
|
|
379
|
+
const callId = readString(update.toolCallId) ?? crypto.randomUUID();
|
|
380
|
+
const partId = turn.toolPartIds.get(callId) ?? `${turn.messageId}:tool:${callId}`;
|
|
381
|
+
turn.toolPartIds.set(callId, partId);
|
|
382
|
+
const rawStatus = readString(update.status) ?? "running";
|
|
383
|
+
const mappedState = rawStatus === "completed" ? "completed"
|
|
384
|
+
: rawStatus === "failed" || rawStatus === "error" ? "error"
|
|
385
|
+
: "running";
|
|
386
|
+
const existingMsg = this.store.get(sessionId)?.messages.find((m) => m.id === turn.messageId);
|
|
387
|
+
const existingPart = existingMsg?.parts?.find((p) => p.id === partId);
|
|
388
|
+
const outputChunks = Array.isArray(update.content)
|
|
389
|
+
? update.content
|
|
390
|
+
.map((entry) => readString(asRecord(asRecord(entry).content).text) ?? readString(asRecord(entry).text))
|
|
391
|
+
.filter(Boolean)
|
|
392
|
+
.join("\n")
|
|
393
|
+
: undefined;
|
|
394
|
+
const toolName = readString(update.title)
|
|
395
|
+
?? readString(update.kind)
|
|
396
|
+
?? readString(existingPart?.toolName)
|
|
397
|
+
?? "tool";
|
|
398
|
+
const part = {
|
|
399
|
+
...(existingPart ?? {}),
|
|
400
|
+
id: partId,
|
|
401
|
+
sessionID: sessionId,
|
|
402
|
+
messageID: turn.messageId,
|
|
403
|
+
type: "tool",
|
|
404
|
+
toolName,
|
|
405
|
+
name: toolName,
|
|
406
|
+
title: readString(update.title) ?? existingPart?.title,
|
|
407
|
+
state: mappedState,
|
|
408
|
+
...(update.rawInput !== undefined ? { input: update.rawInput } : {}),
|
|
409
|
+
...(outputChunks ? { output: outputChunks } : update.rawOutput !== undefined ? { output: update.rawOutput } : {}),
|
|
410
|
+
};
|
|
411
|
+
this.store.upsertPart(sessionId, turn.messageId, "assistant", part);
|
|
412
|
+
this.emitPart(sessionId, turn.messageId, part);
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
415
|
+
if (kind === "plan") {
|
|
416
|
+
const entries = Array.isArray(update.entries) ? update.entries : [];
|
|
417
|
+
const text = entries
|
|
418
|
+
.map((e) => {
|
|
419
|
+
const rec = asRecord(e);
|
|
420
|
+
const status = readString(rec.status) ?? "pending";
|
|
421
|
+
const content = readString(rec.content) ?? "";
|
|
422
|
+
return content ? `- [${status}] ${content}` : "";
|
|
423
|
+
})
|
|
424
|
+
.filter(Boolean)
|
|
425
|
+
.join("\n");
|
|
426
|
+
if (!text)
|
|
427
|
+
return;
|
|
428
|
+
const part = {
|
|
429
|
+
id: `${turn.messageId}:plan`,
|
|
430
|
+
sessionID: sessionId,
|
|
431
|
+
messageID: turn.messageId,
|
|
432
|
+
type: "plan",
|
|
433
|
+
text,
|
|
434
|
+
};
|
|
435
|
+
this.store.upsertPart(sessionId, turn.messageId, "assistant", part);
|
|
436
|
+
this.emitPart(sessionId, turn.messageId, part);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
emitPart(sessionId, messageId, part) {
|
|
440
|
+
this.emitter?.({
|
|
441
|
+
type: "message.updated",
|
|
442
|
+
properties: { info: { sessionID: sessionId, id: messageId, role: "assistant" } },
|
|
443
|
+
});
|
|
444
|
+
this.emitter?.({
|
|
445
|
+
type: "message.part.updated",
|
|
446
|
+
properties: {
|
|
447
|
+
part,
|
|
448
|
+
message: { sessionID: sessionId, id: messageId, role: "assistant" },
|
|
449
|
+
},
|
|
450
|
+
});
|
|
451
|
+
}
|
|
452
|
+
ingestSessionMetadata(result) {
|
|
453
|
+
const modelsObj = asRecord(result.models);
|
|
454
|
+
const availableModels = Array.isArray(modelsObj.availableModels) ? modelsObj.availableModels : [];
|
|
455
|
+
if (availableModels.length > 0) {
|
|
456
|
+
this.discoveredModels = availableModels
|
|
457
|
+
.map((entry) => {
|
|
458
|
+
const rec = asRecord(entry);
|
|
459
|
+
const id = readString(rec.modelId);
|
|
460
|
+
const name = readString(rec.name) ?? id;
|
|
461
|
+
if (!id || !name)
|
|
462
|
+
return null;
|
|
463
|
+
return { id, name, reasoning: true, attachment: true };
|
|
464
|
+
})
|
|
465
|
+
.filter((item) => Boolean(item));
|
|
466
|
+
const cur = readString(modelsObj.currentModelId);
|
|
467
|
+
if (cur)
|
|
468
|
+
this.discoveredDefaultModel = cur;
|
|
469
|
+
}
|
|
470
|
+
const modesObj = asRecord(result.modes);
|
|
471
|
+
const availableModes = Array.isArray(modesObj.availableModes) ? modesObj.availableModes : [];
|
|
472
|
+
for (const mode of availableModes) {
|
|
473
|
+
const rec = asRecord(mode);
|
|
474
|
+
const id = readString(rec.id);
|
|
475
|
+
const name = readString(rec.name)?.toLowerCase();
|
|
476
|
+
if (id && name) {
|
|
477
|
+
if (name.includes("plan"))
|
|
478
|
+
this.availableModes.set("plan", id);
|
|
479
|
+
if (name.includes("code") || name.includes("agent") || name.includes("build") || name.includes("default") || name.includes("edit")) {
|
|
480
|
+
if (!this.availableModes.has("build"))
|
|
481
|
+
this.availableModes.set("build", id);
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
async createSession(title) {
|
|
487
|
+
await this.ensureProcessReady();
|
|
488
|
+
const res = asRecord(await this.call("session/new", { cwd: process.cwd(), mcpServers: [] }));
|
|
489
|
+
const remoteSessionId = readString(res.sessionId);
|
|
490
|
+
if (!remoteSessionId) {
|
|
491
|
+
throw new Error(`${this.config.displayName} session/new missing sessionId`);
|
|
492
|
+
}
|
|
493
|
+
this.ingestSessionMetadata(res);
|
|
494
|
+
this.loadedRemoteSessions.add(remoteSessionId);
|
|
495
|
+
const now = Date.now();
|
|
496
|
+
const rec = this.store.upsert({
|
|
497
|
+
id: remoteSessionId,
|
|
498
|
+
remoteSessionId,
|
|
499
|
+
title: title?.trim() || "Conversation",
|
|
500
|
+
createdAt: now,
|
|
501
|
+
updatedAt: now,
|
|
502
|
+
cwd: process.cwd(),
|
|
503
|
+
messages: [],
|
|
504
|
+
});
|
|
505
|
+
return { session: this.store.toSessionInfo(rec) };
|
|
506
|
+
}
|
|
507
|
+
async listSessions() {
|
|
508
|
+
return {
|
|
509
|
+
sessions: this.store.listForWorkspace().map((rec) => this.store.toSessionInfo(rec)),
|
|
510
|
+
};
|
|
511
|
+
}
|
|
512
|
+
async getSession(id) {
|
|
513
|
+
const rec = this.store.get(id);
|
|
514
|
+
if (!rec) {
|
|
515
|
+
throw Object.assign(new Error(`Session ${id} not found`), { code: "NotFoundError" });
|
|
516
|
+
}
|
|
517
|
+
return { session: this.store.toSessionInfo(rec) };
|
|
518
|
+
}
|
|
519
|
+
async deleteSession(id) {
|
|
520
|
+
const rec = this.store.get(id);
|
|
521
|
+
if (rec?.remoteSessionId && this.proc && this.proc.exitCode === null) {
|
|
522
|
+
await this.call("session/close", { sessionId: rec.remoteSessionId }).catch(() => { });
|
|
523
|
+
}
|
|
524
|
+
const deleted = this.store.delete(id);
|
|
525
|
+
if (deleted) {
|
|
526
|
+
this.emitter?.({ type: "session.deleted", properties: { info: { id } } });
|
|
527
|
+
}
|
|
528
|
+
return { deleted };
|
|
529
|
+
}
|
|
530
|
+
async renameSession(id, title) {
|
|
531
|
+
const rec = this.store.get(id);
|
|
532
|
+
if (!rec)
|
|
533
|
+
throw new Error(`Session ${id} not found`);
|
|
534
|
+
rec.title = title;
|
|
535
|
+
rec.updatedAt = Date.now();
|
|
536
|
+
this.store.upsert(rec);
|
|
537
|
+
return { session: this.store.toSessionInfo(rec) };
|
|
538
|
+
}
|
|
539
|
+
async getMessages(sessionId) {
|
|
540
|
+
const rec = this.store.get(sessionId);
|
|
541
|
+
if (!rec)
|
|
542
|
+
throw Object.assign(new Error(`Session ${sessionId} not found`), { code: "NotFoundError" });
|
|
543
|
+
return { messages: rec.messages };
|
|
544
|
+
}
|
|
545
|
+
async statuses() {
|
|
546
|
+
const out = {};
|
|
547
|
+
for (const [sid, status] of this.activeStatusBySession) {
|
|
548
|
+
out[sid] = { type: status };
|
|
549
|
+
}
|
|
550
|
+
return { statuses: out };
|
|
551
|
+
}
|
|
552
|
+
async prompt(sessionId, text, model, agent, files = [], _codexOptions) {
|
|
553
|
+
let rec = this.store.get(sessionId);
|
|
554
|
+
if (!rec) {
|
|
555
|
+
throw new Error(`Session ${sessionId} not found`);
|
|
556
|
+
}
|
|
557
|
+
const userMessageId = crypto.randomUUID();
|
|
558
|
+
const now = Date.now();
|
|
559
|
+
const userMsg = {
|
|
560
|
+
id: userMessageId,
|
|
561
|
+
role: "user",
|
|
562
|
+
parts: [{ id: `${userMessageId}:text`, type: "text", text }],
|
|
563
|
+
time: { created: now, updated: now },
|
|
564
|
+
};
|
|
565
|
+
this.store.appendMessage(sessionId, userMsg);
|
|
566
|
+
this.emitter?.({
|
|
567
|
+
type: "message.updated",
|
|
568
|
+
properties: { info: { sessionID: sessionId, id: userMessageId, role: "user", time: { created: now, updated: now } } },
|
|
569
|
+
});
|
|
570
|
+
this.emitter?.({
|
|
571
|
+
type: "message.part.updated",
|
|
572
|
+
properties: {
|
|
573
|
+
part: { id: `${userMessageId}:text`, sessionID: sessionId, messageID: userMessageId, type: "text", text },
|
|
574
|
+
message: { sessionID: sessionId, id: userMessageId, role: "user" },
|
|
575
|
+
},
|
|
576
|
+
});
|
|
577
|
+
if (rec.title === "Conversation" && text.trim()) {
|
|
578
|
+
rec.title = text.replace(/\s+/g, " ").trim().slice(0, 48);
|
|
579
|
+
this.store.upsert(rec);
|
|
580
|
+
this.emitter?.({ type: "session.updated", properties: { info: this.store.toSessionInfo(rec) } });
|
|
581
|
+
}
|
|
582
|
+
this.activeStatusBySession.set(sessionId, "running");
|
|
583
|
+
this.emitter?.({
|
|
584
|
+
type: "session.status",
|
|
585
|
+
properties: { sessionID: sessionId, status: { type: "running" } },
|
|
586
|
+
});
|
|
587
|
+
void (async () => {
|
|
588
|
+
try {
|
|
589
|
+
await this.ensureProcessReady();
|
|
590
|
+
let remoteId = rec.remoteSessionId ?? rec.id;
|
|
591
|
+
if (!this.loadedRemoteSessions.has(remoteId)) {
|
|
592
|
+
try {
|
|
593
|
+
const loaded = asRecord(await this.call("session/load", { sessionId: remoteId, cwd: rec.cwd, mcpServers: [] }));
|
|
594
|
+
this.ingestSessionMetadata(loaded);
|
|
595
|
+
this.loadedRemoteSessions.add(remoteId);
|
|
596
|
+
}
|
|
597
|
+
catch {
|
|
598
|
+
// If load is unavailable or stale, create a fresh remote ACP session and link it
|
|
599
|
+
const fresh = asRecord(await this.call("session/new", { cwd: rec.cwd, mcpServers: [] }));
|
|
600
|
+
const newRemoteId = readString(fresh.sessionId);
|
|
601
|
+
if (!newRemoteId)
|
|
602
|
+
throw new Error(`${this.config.displayName} failed to initialize remote session`);
|
|
603
|
+
this.ingestSessionMetadata(fresh);
|
|
604
|
+
this.loadedRemoteSessions.add(newRemoteId);
|
|
605
|
+
rec.remoteSessionId = newRemoteId;
|
|
606
|
+
this.store.upsert(rec);
|
|
607
|
+
remoteId = newRemoteId;
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
if (model?.modelID) {
|
|
611
|
+
await this.call("session/set_model", { sessionId: remoteId, modelId: model.modelID }).catch(() => { });
|
|
612
|
+
}
|
|
613
|
+
if (agent) {
|
|
614
|
+
const targetMode = this.availableModes.get(agent.toLowerCase()) ?? agent;
|
|
615
|
+
await this.call("session/set_mode", { sessionId: remoteId, modeId: targetMode }).catch(() => { });
|
|
616
|
+
}
|
|
617
|
+
const assistantMsgId = crypto.randomUUID();
|
|
618
|
+
const turn = {
|
|
619
|
+
messageId: assistantMsgId,
|
|
620
|
+
startedAt: Date.now(),
|
|
621
|
+
textContent: "",
|
|
622
|
+
reasoningContent: "",
|
|
623
|
+
toolPartIds: new Map(),
|
|
624
|
+
};
|
|
625
|
+
this.activeTurnBySession.set(sessionId, turn);
|
|
626
|
+
const startPart = {
|
|
627
|
+
id: `${assistantMsgId}:start`,
|
|
628
|
+
sessionID: sessionId,
|
|
629
|
+
messageID: assistantMsgId,
|
|
630
|
+
type: "step-start",
|
|
631
|
+
title: "Working",
|
|
632
|
+
time: { start: turn.startedAt },
|
|
633
|
+
};
|
|
634
|
+
this.store.upsertPart(sessionId, assistantMsgId, "assistant", startPart);
|
|
635
|
+
this.emitPart(sessionId, assistantMsgId, startPart);
|
|
636
|
+
const promptBlocks = [{ type: "text", text }];
|
|
637
|
+
for (const file of files) {
|
|
638
|
+
if (file.url.startsWith("data:") && file.mime.startsWith("image/")) {
|
|
639
|
+
const [, base64Data] = file.url.split(",", 2);
|
|
640
|
+
if (base64Data) {
|
|
641
|
+
promptBlocks.push({ type: "image", mimeType: file.mime, data: base64Data });
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
await this.call("session/prompt", { sessionId: remoteId, prompt: promptBlocks }, 300_000);
|
|
646
|
+
const finishPart = {
|
|
647
|
+
id: `${assistantMsgId}:finish`,
|
|
648
|
+
sessionID: sessionId,
|
|
649
|
+
messageID: assistantMsgId,
|
|
650
|
+
type: "step-finish",
|
|
651
|
+
title: "Completed",
|
|
652
|
+
time: { end: Date.now() },
|
|
653
|
+
};
|
|
654
|
+
this.store.upsertPart(sessionId, assistantMsgId, "assistant", finishPart);
|
|
655
|
+
this.emitPart(sessionId, assistantMsgId, finishPart);
|
|
656
|
+
this.activeTurnBySession.delete(sessionId);
|
|
657
|
+
this.activeStatusBySession.set(sessionId, "idle");
|
|
658
|
+
this.emitter?.({ type: "session.idle", properties: { sessionID: sessionId } });
|
|
659
|
+
}
|
|
660
|
+
catch (err) {
|
|
661
|
+
const message = err.message;
|
|
662
|
+
this.activeTurnBySession.delete(sessionId);
|
|
663
|
+
this.activeStatusBySession.set(sessionId, "idle");
|
|
664
|
+
this.emitter?.({ type: "session.error", properties: { sessionID: sessionId, error: message } });
|
|
665
|
+
}
|
|
666
|
+
})();
|
|
667
|
+
return { ack: true };
|
|
668
|
+
}
|
|
669
|
+
async abort(sessionId) {
|
|
670
|
+
const rec = this.store.get(sessionId);
|
|
671
|
+
const remoteId = rec?.remoteSessionId ?? sessionId;
|
|
672
|
+
if (this.proc && this.proc.exitCode === null) {
|
|
673
|
+
this.notify("session/cancel", { sessionId: remoteId });
|
|
674
|
+
}
|
|
675
|
+
this.activeStatusBySession.set(sessionId, "idle");
|
|
676
|
+
return {};
|
|
677
|
+
}
|
|
678
|
+
async agents() {
|
|
679
|
+
return { agents: [...DEFAULT_AGENTS] };
|
|
680
|
+
}
|
|
681
|
+
async providers() {
|
|
682
|
+
const seeds = this.discoveredModels.length > 0 ? this.discoveredModels : this.config.defaultModels;
|
|
683
|
+
const providerId = this.config.backend;
|
|
684
|
+
const models = Object.fromEntries(seeds.map((m) => [
|
|
685
|
+
m.id,
|
|
686
|
+
{
|
|
687
|
+
id: m.id,
|
|
688
|
+
name: m.name,
|
|
689
|
+
provider: providerId,
|
|
690
|
+
capabilities: {
|
|
691
|
+
reasoning: m.reasoning ?? true,
|
|
692
|
+
attachment: m.attachment ?? true,
|
|
693
|
+
toolcall: true,
|
|
694
|
+
},
|
|
695
|
+
},
|
|
696
|
+
]));
|
|
697
|
+
const configuredDefaultId = this.config.defaultModels.find((m) => m.isDefault)?.id;
|
|
698
|
+
const hasConfiguredDefault = configuredDefaultId && seeds.some((m) => m.id === configuredDefaultId);
|
|
699
|
+
const defaultModel = (hasConfiguredDefault ? configuredDefaultId : undefined)
|
|
700
|
+
?? this.discoveredDefaultModel
|
|
701
|
+
?? seeds.find((m) => m.isDefault)?.id
|
|
702
|
+
?? seeds[0]?.id;
|
|
703
|
+
return {
|
|
704
|
+
providers: [
|
|
705
|
+
{
|
|
706
|
+
id: providerId,
|
|
707
|
+
name: this.config.displayName,
|
|
708
|
+
source: this.apiKeyOverride || process.env[this.config.authEnvKey] ? "env" : "oauth",
|
|
709
|
+
models,
|
|
710
|
+
},
|
|
711
|
+
],
|
|
712
|
+
default: defaultModel ? { [providerId]: defaultModel } : {},
|
|
713
|
+
};
|
|
714
|
+
}
|
|
715
|
+
async setAuth(_providerId, key) {
|
|
716
|
+
const trimmed = key.trim();
|
|
717
|
+
if (!trimmed)
|
|
718
|
+
throw new Error("API key is required");
|
|
719
|
+
this.apiKeyOverride = trimmed;
|
|
720
|
+
saveAuthSecret(this.config.authEnvKey, trimmed);
|
|
721
|
+
await this.destroy();
|
|
722
|
+
await this.ensureProcessReady();
|
|
723
|
+
return {};
|
|
724
|
+
}
|
|
725
|
+
async command() {
|
|
726
|
+
throw new Error(`Slash commands are not supported by ${this.config.displayName} via RPC`);
|
|
727
|
+
}
|
|
728
|
+
async revert() {
|
|
729
|
+
throw new Error(`Revert is not supported by ${this.config.displayName} yet`);
|
|
730
|
+
}
|
|
731
|
+
async unrevert() {
|
|
732
|
+
throw new Error(`Unrevert is not supported by ${this.config.displayName} yet`);
|
|
733
|
+
}
|
|
734
|
+
async share() {
|
|
735
|
+
return { share: { url: null } };
|
|
736
|
+
}
|
|
737
|
+
async permissionReply(sessionId, permissionId, response) {
|
|
738
|
+
const pending = this.pendingPermissions.get(permissionId);
|
|
739
|
+
if (!pending) {
|
|
740
|
+
throw new Error(`Pending permission ${permissionId} not found`);
|
|
741
|
+
}
|
|
742
|
+
this.pendingPermissions.delete(permissionId);
|
|
743
|
+
if (response === "reject") {
|
|
744
|
+
const rejectOpt = pending.options.find((o) => o.kind?.includes("reject"));
|
|
745
|
+
this.sendJson({
|
|
746
|
+
jsonrpc: "2.0",
|
|
747
|
+
id: pending.requestId,
|
|
748
|
+
result: rejectOpt
|
|
749
|
+
? { outcome: { outcome: "selected", optionId: rejectOpt.optionId } }
|
|
750
|
+
: { outcome: { outcome: "cancelled" } },
|
|
751
|
+
});
|
|
752
|
+
}
|
|
753
|
+
else {
|
|
754
|
+
const allowOpt = response === "always"
|
|
755
|
+
? (pending.options.find((o) => o.kind === "allow_always") ?? pending.options.find((o) => o.kind?.includes("allow")) ?? pending.options[0])
|
|
756
|
+
: (pending.options.find((o) => o.kind === "allow_once") ?? pending.options.find((o) => o.kind?.includes("allow")) ?? pending.options[0]);
|
|
757
|
+
this.sendJson({
|
|
758
|
+
jsonrpc: "2.0",
|
|
759
|
+
id: pending.requestId,
|
|
760
|
+
result: allowOpt
|
|
761
|
+
? { outcome: { outcome: "selected", optionId: allowOpt.optionId } }
|
|
762
|
+
: { outcome: { outcome: "cancelled" } },
|
|
763
|
+
});
|
|
764
|
+
}
|
|
765
|
+
this.emitter?.({
|
|
766
|
+
type: "permission.replied",
|
|
767
|
+
properties: { sessionID: sessionId || pending.sessionId, permissionId, response },
|
|
768
|
+
});
|
|
769
|
+
return {};
|
|
770
|
+
}
|
|
771
|
+
}
|