kodorun-cli 0.0.0-stage → 0.1.124

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.
@@ -0,0 +1,555 @@
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 mode with workspace edits." },
6
+ { name: "Plan", mode: "plan", description: "Read-only planning and analysis mode." },
7
+ ];
8
+ function asRecord(value) {
9
+ return value && typeof value === "object" ? value : {};
10
+ }
11
+ function readString(value) {
12
+ return typeof value === "string" && value.length > 0 ? value : undefined;
13
+ }
14
+ export class StreamJsonProvider {
15
+ config;
16
+ store;
17
+ executablePath = null;
18
+ emitter = null;
19
+ activeProcs = new Map();
20
+ abortedSessions = new Set();
21
+ activeStatus = new Map();
22
+ apiKeyOverride = null;
23
+ constructor(config) {
24
+ this.config = config;
25
+ this.store = new LocalAiSessionStore(config.backend, process.cwd());
26
+ const saved = loadAuthSecrets();
27
+ if (saved[config.authEnvKey]) {
28
+ this.apiKeyOverride = saved[config.authEnvKey];
29
+ }
30
+ }
31
+ debugLog(message, ...args) {
32
+ if (process.env.KODORUN_DEBUG === "1" || process.env.KODORUN_DEBUG_AI === "1") {
33
+ console.log(`[${this.config.backend}] ${message}`, ...args);
34
+ }
35
+ }
36
+ async init() {
37
+ const resolved = resolveExecutable(this.config.binaryCandidates, this.config.extraBinaryPaths ?? []);
38
+ if (!resolved) {
39
+ throw new Error(`${this.config.displayName} CLI is not installed`);
40
+ }
41
+ this.executablePath = resolved;
42
+ }
43
+ async destroy() {
44
+ for (const [sid, proc] of this.activeProcs) {
45
+ this.abortedSessions.add(sid);
46
+ proc.kill();
47
+ }
48
+ this.activeProcs.clear();
49
+ }
50
+ subscribe(emitter) {
51
+ this.emitter = emitter;
52
+ return () => {
53
+ this.emitter = null;
54
+ };
55
+ }
56
+ async createSession(title) {
57
+ const id = crypto.randomUUID();
58
+ const now = Date.now();
59
+ const rec = this.store.upsert({
60
+ id,
61
+ title: title?.trim() || "Conversation",
62
+ createdAt: now,
63
+ updatedAt: now,
64
+ cwd: process.cwd(),
65
+ messages: [],
66
+ });
67
+ return { session: this.store.toSessionInfo(rec) };
68
+ }
69
+ async listSessions() {
70
+ return {
71
+ sessions: this.store.listForWorkspace().map((rec) => this.store.toSessionInfo(rec)),
72
+ };
73
+ }
74
+ async getSession(id) {
75
+ const rec = this.store.get(id);
76
+ if (!rec)
77
+ throw Object.assign(new Error(`Session ${id} not found`), { code: "NotFoundError" });
78
+ return { session: this.store.toSessionInfo(rec) };
79
+ }
80
+ async deleteSession(id) {
81
+ const proc = this.activeProcs.get(id);
82
+ if (proc) {
83
+ this.abortedSessions.add(id);
84
+ proc.kill();
85
+ this.activeProcs.delete(id);
86
+ }
87
+ const deleted = this.store.delete(id);
88
+ if (deleted) {
89
+ this.emitter?.({ type: "session.deleted", properties: { info: { id } } });
90
+ }
91
+ return { deleted };
92
+ }
93
+ async renameSession(id, title) {
94
+ const rec = this.store.get(id);
95
+ if (!rec)
96
+ throw new Error(`Session ${id} not found`);
97
+ rec.title = title;
98
+ rec.updatedAt = Date.now();
99
+ this.store.upsert(rec);
100
+ return { session: this.store.toSessionInfo(rec) };
101
+ }
102
+ async getMessages(sessionId) {
103
+ const rec = this.store.get(sessionId);
104
+ if (!rec)
105
+ throw Object.assign(new Error(`Session ${sessionId} not found`), { code: "NotFoundError" });
106
+ return { messages: rec.messages };
107
+ }
108
+ async statuses() {
109
+ const out = {};
110
+ for (const [sid, status] of this.activeStatus) {
111
+ out[sid] = { type: status };
112
+ }
113
+ return { statuses: out };
114
+ }
115
+ emitPart(sessionId, messageId, part) {
116
+ this.emitter?.({
117
+ type: "message.updated",
118
+ properties: { info: { sessionID: sessionId, id: messageId, role: "assistant" } },
119
+ });
120
+ this.emitter?.({
121
+ type: "message.part.updated",
122
+ properties: {
123
+ part,
124
+ message: { sessionID: sessionId, id: messageId, role: "assistant" },
125
+ },
126
+ });
127
+ }
128
+ async prompt(sessionId, text, model, agent, _files = [], _codexOptions) {
129
+ const rec = this.store.get(sessionId);
130
+ if (!rec)
131
+ throw new Error(`Session ${sessionId} not found`);
132
+ if (this.activeProcs.has(sessionId)) {
133
+ throw new Error(`Session ${sessionId} already has an active turn`);
134
+ }
135
+ const userMsgId = crypto.randomUUID();
136
+ const now = Date.now();
137
+ this.store.appendMessage(sessionId, {
138
+ id: userMsgId,
139
+ role: "user",
140
+ parts: [{ id: `${userMsgId}:text`, type: "text", text }],
141
+ time: { created: now, updated: now },
142
+ });
143
+ this.emitter?.({
144
+ type: "message.updated",
145
+ properties: { info: { sessionID: sessionId, id: userMsgId, role: "user", time: { created: now, updated: now } } },
146
+ });
147
+ this.emitter?.({
148
+ type: "message.part.updated",
149
+ properties: {
150
+ part: { id: `${userMsgId}:text`, sessionID: sessionId, messageID: userMsgId, type: "text", text },
151
+ message: { sessionID: sessionId, id: userMsgId, role: "user" },
152
+ },
153
+ });
154
+ if (rec.title === "Conversation" && text.trim()) {
155
+ rec.title = text.replace(/\s+/g, " ").trim().slice(0, 48);
156
+ this.store.upsert(rec);
157
+ this.emitter?.({ type: "session.updated", properties: { info: this.store.toSessionInfo(rec) } });
158
+ }
159
+ this.abortedSessions.delete(sessionId);
160
+ this.activeStatus.set(sessionId, "running");
161
+ this.emitter?.({
162
+ type: "session.status",
163
+ properties: { sessionID: sessionId, status: { type: "running" } },
164
+ });
165
+ void this.runTurn(sessionId, text, model?.modelID, agent).catch((err) => {
166
+ const message = err instanceof Error ? err.message : String(err);
167
+ this.activeStatus.set(sessionId, "idle");
168
+ this.emitter?.({
169
+ type: "session.status",
170
+ properties: { sessionID: sessionId, status: { type: "idle" } },
171
+ });
172
+ this.emitter?.({
173
+ type: "prompt_error",
174
+ properties: { sessionId, error: message },
175
+ });
176
+ });
177
+ return { ack: true };
178
+ }
179
+ async runTurn(sessionId, text, modelId, agent) {
180
+ const rec = this.store.get(sessionId);
181
+ if (!rec)
182
+ return;
183
+ if (!this.executablePath) {
184
+ await this.init();
185
+ }
186
+ const isFirstTurn = !rec.remoteSessionId;
187
+ const args = this.config.buildArgs({
188
+ prompt: text,
189
+ remoteSessionId: rec.remoteSessionId,
190
+ localSessionId: rec.id,
191
+ isFirstTurn,
192
+ modelId,
193
+ agent,
194
+ });
195
+ const env = { ...process.env };
196
+ if (this.apiKeyOverride) {
197
+ env[this.config.authEnvKey] = this.apiKeyOverride;
198
+ }
199
+ const cmdPath = this.executablePath;
200
+ const proc = spawnCliBinary(cmdPath, args, {
201
+ cwd: rec.cwd,
202
+ env,
203
+ stdio: ["ignore", "pipe", "pipe"],
204
+ });
205
+ this.activeProcs.set(sessionId, proc);
206
+ const assistantMsgId = crypto.randomUUID();
207
+ const startPart = {
208
+ id: `${assistantMsgId}:start`,
209
+ sessionID: sessionId,
210
+ messageID: assistantMsgId,
211
+ type: "step-start",
212
+ title: "Working",
213
+ time: { start: Date.now() },
214
+ };
215
+ this.store.upsertPart(sessionId, assistantMsgId, "assistant", startPart);
216
+ this.emitPart(sessionId, assistantMsgId, startPart);
217
+ const blocksByIndex = new Map();
218
+ let fallbackTextPartId = null;
219
+ let fallbackText = "";
220
+ let fallbackReasoningPartId = null;
221
+ let fallbackReasoning = "";
222
+ let stderrOutput = "";
223
+ let emittedError = null;
224
+ const rl = createInterface({ input: proc.stdout });
225
+ rl.on("line", (line) => {
226
+ const trimmed = line.trim();
227
+ if (!trimmed)
228
+ return;
229
+ let ev;
230
+ try {
231
+ ev = JSON.parse(trimmed);
232
+ }
233
+ catch {
234
+ return;
235
+ }
236
+ const remoteSid = readString(ev.session_id);
237
+ if (remoteSid && rec.remoteSessionId !== remoteSid) {
238
+ rec.remoteSessionId = remoteSid;
239
+ this.store.upsert(rec);
240
+ }
241
+ const evType = readString(ev.type);
242
+ // Claude token streaming (`--include-partial-messages`)
243
+ if (evType === "stream_event") {
244
+ const inner = asRecord(ev.event);
245
+ const innerType = readString(inner.type);
246
+ const index = typeof inner.index === "number" ? inner.index : 0;
247
+ if (innerType === "content_block_start") {
248
+ const cb = asRecord(inner.content_block);
249
+ const cbType = readString(cb.type);
250
+ if (cbType === "text") {
251
+ blocksByIndex.set(index, { partId: `${assistantMsgId}:text:${index}`, type: "text", content: "" });
252
+ }
253
+ else if (cbType === "thinking") {
254
+ blocksByIndex.set(index, { partId: `${assistantMsgId}:reasoning:${index}`, type: "reasoning", content: "" });
255
+ }
256
+ else if (cbType === "tool_use") {
257
+ const toolId = readString(cb.id) ?? `${index}`;
258
+ const toolName = readString(cb.name) ?? "tool";
259
+ const partId = `${assistantMsgId}:tool:${toolId}`;
260
+ blocksByIndex.set(index, { partId, type: "tool", content: "", toolName });
261
+ const part = {
262
+ id: partId,
263
+ sessionID: sessionId,
264
+ messageID: assistantMsgId,
265
+ type: "tool",
266
+ toolName,
267
+ name: toolName,
268
+ state: "running",
269
+ };
270
+ this.store.upsertPart(sessionId, assistantMsgId, "assistant", part);
271
+ this.emitPart(sessionId, assistantMsgId, part);
272
+ }
273
+ return;
274
+ }
275
+ if (innerType === "content_block_delta") {
276
+ const delta = asRecord(inner.delta);
277
+ const deltaType = readString(delta.type);
278
+ const tracker = blocksByIndex.get(index);
279
+ if (!tracker)
280
+ return;
281
+ if (deltaType === "text_delta" && typeof delta.text === "string") {
282
+ tracker.content += delta.text;
283
+ const part = {
284
+ id: tracker.partId,
285
+ sessionID: sessionId,
286
+ messageID: assistantMsgId,
287
+ type: "text",
288
+ text: tracker.content,
289
+ };
290
+ this.store.upsertPart(sessionId, assistantMsgId, "assistant", part);
291
+ this.emitPart(sessionId, assistantMsgId, part);
292
+ }
293
+ else if (deltaType === "thinking_delta" && typeof delta.thinking === "string") {
294
+ tracker.content += delta.thinking;
295
+ const part = {
296
+ id: tracker.partId,
297
+ sessionID: sessionId,
298
+ messageID: assistantMsgId,
299
+ type: "reasoning",
300
+ text: tracker.content,
301
+ };
302
+ this.store.upsertPart(sessionId, assistantMsgId, "assistant", part);
303
+ this.emitPart(sessionId, assistantMsgId, part);
304
+ }
305
+ else if (deltaType === "input_json_delta" && typeof delta.partial_json === "string") {
306
+ tracker.content += delta.partial_json;
307
+ }
308
+ return;
309
+ }
310
+ return;
311
+ }
312
+ // Cursor reasoning delta/completed
313
+ if (evType === "thinking") {
314
+ const delta = readString(ev.text);
315
+ if (delta) {
316
+ fallbackReasoningPartId = fallbackReasoningPartId ?? `${assistantMsgId}:reasoning`;
317
+ fallbackReasoning += delta;
318
+ const part = {
319
+ id: fallbackReasoningPartId,
320
+ sessionID: sessionId,
321
+ messageID: assistantMsgId,
322
+ type: "reasoning",
323
+ text: fallbackReasoning,
324
+ };
325
+ this.store.upsertPart(sessionId, assistantMsgId, "assistant", part);
326
+ this.emitPart(sessionId, assistantMsgId, part);
327
+ }
328
+ return;
329
+ }
330
+ // Claude & Cursor `assistant` message
331
+ if (evType === "assistant") {
332
+ const msgObj = asRecord(ev.message);
333
+ const content = Array.isArray(msgObj.content) ? msgObj.content : [];
334
+ const errCode = readString(ev.error);
335
+ content.forEach((rawBlock, idx) => {
336
+ const block = asRecord(rawBlock);
337
+ const bType = readString(block.type);
338
+ if (bType === "text" && typeof block.text === "string") {
339
+ const tracker = blocksByIndex.get(idx);
340
+ const partId = tracker?.partId ?? (fallbackTextPartId ??= `${assistantMsgId}:text:fallback`);
341
+ if (errCode && !emittedError) {
342
+ emittedError = block.text;
343
+ }
344
+ // Support both full-text snapshots and partial chunks cleanly
345
+ fallbackText = block.text.startsWith(fallbackText) ? block.text : fallbackText + block.text;
346
+ const part = {
347
+ id: partId,
348
+ sessionID: sessionId,
349
+ messageID: assistantMsgId,
350
+ type: "text",
351
+ text: tracker ? (block.text || tracker.content) : fallbackText,
352
+ };
353
+ this.store.upsertPart(sessionId, assistantMsgId, "assistant", part);
354
+ this.emitPart(sessionId, assistantMsgId, part);
355
+ }
356
+ else if (bType === "thinking" && typeof block.thinking === "string") {
357
+ const tracker = blocksByIndex.get(idx);
358
+ const partId = tracker?.partId ?? (fallbackReasoningPartId ??= `${assistantMsgId}:reasoning:fallback`);
359
+ const part = {
360
+ id: partId,
361
+ sessionID: sessionId,
362
+ messageID: assistantMsgId,
363
+ type: "reasoning",
364
+ text: block.thinking,
365
+ };
366
+ this.store.upsertPart(sessionId, assistantMsgId, "assistant", part);
367
+ this.emitPart(sessionId, assistantMsgId, part);
368
+ }
369
+ else if (bType === "tool_use") {
370
+ const toolId = readString(block.id) ?? String(idx);
371
+ const toolName = readString(block.name) ?? "tool";
372
+ const partId = `${assistantMsgId}:tool:${toolId}`;
373
+ const part = {
374
+ id: partId,
375
+ sessionID: sessionId,
376
+ messageID: assistantMsgId,
377
+ type: "tool",
378
+ toolName,
379
+ name: toolName,
380
+ state: "running",
381
+ input: block.input ?? {},
382
+ };
383
+ this.store.upsertPart(sessionId, assistantMsgId, "assistant", part);
384
+ this.emitPart(sessionId, assistantMsgId, part);
385
+ }
386
+ });
387
+ return;
388
+ }
389
+ // Claude `user` message carrying `tool_result`
390
+ if (evType === "user") {
391
+ const msgObj = asRecord(ev.message);
392
+ const content = Array.isArray(msgObj.content) ? msgObj.content : [];
393
+ for (const rawBlock of content) {
394
+ const block = asRecord(rawBlock);
395
+ if (block.type === "tool_result") {
396
+ const toolUseId = readString(block.tool_use_id);
397
+ if (!toolUseId)
398
+ continue;
399
+ const partId = `${assistantMsgId}:tool:${toolUseId}`;
400
+ const existingMsg = this.store.get(sessionId)?.messages.find((m) => m.id === assistantMsgId);
401
+ const existingPart = existingMsg?.parts?.find((p) => p.id === partId);
402
+ const output = typeof block.content === "string"
403
+ ? block.content
404
+ : Array.isArray(block.content)
405
+ ? block.content.map((c) => readString(asRecord(c).text) ?? JSON.stringify(c)).join("\n")
406
+ : JSON.stringify(block.content ?? "");
407
+ const part = {
408
+ ...(existingPart ?? { id: partId, sessionID: sessionId, messageID: assistantMsgId, type: "tool", toolName: "tool" }),
409
+ state: block.is_error === true ? "error" : "completed",
410
+ output,
411
+ };
412
+ this.store.upsertPart(sessionId, assistantMsgId, "assistant", part);
413
+ this.emitPart(sessionId, assistantMsgId, part);
414
+ }
415
+ }
416
+ return;
417
+ }
418
+ // Cursor `tool_call` event
419
+ if (evType === "tool_call") {
420
+ const callId = readString(ev.call_id) ?? crypto.randomUUID();
421
+ const subtype = readString(ev.subtype);
422
+ const toolObj = asRecord(ev.tool_call);
423
+ const toolKey = Object.keys(toolObj)[0] ?? "tool";
424
+ const toolPayload = asRecord(toolObj[toolKey]);
425
+ const partId = `${assistantMsgId}:tool:${callId}`;
426
+ const part = {
427
+ id: partId,
428
+ sessionID: sessionId,
429
+ messageID: assistantMsgId,
430
+ type: "tool",
431
+ toolName: toolKey.replace(/ToolCall$/, ""),
432
+ name: toolKey.replace(/ToolCall$/, ""),
433
+ state: subtype === "completed" ? "completed" : "running",
434
+ ...(toolPayload.args !== undefined ? { input: toolPayload.args } : {}),
435
+ ...(toolPayload.result !== undefined ? { output: typeof toolPayload.result === "string" ? toolPayload.result : JSON.stringify(toolPayload.result) } : {}),
436
+ };
437
+ this.store.upsertPart(sessionId, assistantMsgId, "assistant", part);
438
+ this.emitPart(sessionId, assistantMsgId, part);
439
+ return;
440
+ }
441
+ // Final turn result (Claude & Cursor)
442
+ if (evType === "result") {
443
+ if (ev.is_error === true) {
444
+ emittedError = readString(ev.result) ?? emittedError ?? `${this.config.displayName} turn failed`;
445
+ }
446
+ else if (typeof ev.result === "string" && ev.result.length > 0 && blocksByIndex.size === 0 && !fallbackText) {
447
+ const partId = `${assistantMsgId}:text:result`;
448
+ const part = {
449
+ id: partId,
450
+ sessionID: sessionId,
451
+ messageID: assistantMsgId,
452
+ type: "text",
453
+ text: ev.result,
454
+ };
455
+ this.store.upsertPart(sessionId, assistantMsgId, "assistant", part);
456
+ this.emitPart(sessionId, assistantMsgId, part);
457
+ }
458
+ }
459
+ });
460
+ proc.stderr?.on("data", (chunk) => {
461
+ const s = chunk.toString();
462
+ stderrOutput += s;
463
+ this.debugLog("stderr:", s.trim());
464
+ });
465
+ proc.on("error", (err) => {
466
+ this.activeProcs.delete(sessionId);
467
+ this.activeStatus.set(sessionId, "idle");
468
+ this.emitter?.({ type: "session.error", properties: { sessionID: sessionId, error: err.message } });
469
+ });
470
+ proc.on("exit", (code) => {
471
+ this.activeProcs.delete(sessionId);
472
+ this.activeStatus.set(sessionId, "idle");
473
+ const wasAborted = this.abortedSessions.delete(sessionId);
474
+ const finishPart = {
475
+ id: `${assistantMsgId}:finish`,
476
+ sessionID: sessionId,
477
+ messageID: assistantMsgId,
478
+ type: "step-finish",
479
+ title: wasAborted ? "Interrupted" : (emittedError ? "Failed" : "Completed"),
480
+ time: { end: Date.now() },
481
+ };
482
+ this.store.upsertPart(sessionId, assistantMsgId, "assistant", finishPart);
483
+ this.emitPart(sessionId, assistantMsgId, finishPart);
484
+ this.emitter?.({ type: "session.idle", properties: { sessionID: sessionId } });
485
+ if (!wasAborted && (emittedError || (code != null && code !== 0))) {
486
+ const errorText = emittedError ?? (stderrOutput.trim() || `${this.config.displayName} exited with code ${code}`);
487
+ this.emitter?.({ type: "session.error", properties: { sessionID: sessionId, error: errorText } });
488
+ }
489
+ });
490
+ }
491
+ async abort(sessionId) {
492
+ const proc = this.activeProcs.get(sessionId);
493
+ if (!proc) {
494
+ this.activeStatus.set(sessionId, "idle");
495
+ return {};
496
+ }
497
+ this.abortedSessions.add(sessionId);
498
+ proc.kill();
499
+ return {};
500
+ }
501
+ async agents() {
502
+ return { agents: [...DEFAULT_AGENTS] };
503
+ }
504
+ async providers() {
505
+ const providerId = this.config.backend;
506
+ const models = Object.fromEntries(this.config.defaultModels.map((m) => [
507
+ m.id,
508
+ {
509
+ id: m.id,
510
+ name: m.name,
511
+ provider: providerId,
512
+ capabilities: {
513
+ reasoning: m.reasoning ?? true,
514
+ attachment: m.attachment ?? false,
515
+ toolcall: true,
516
+ },
517
+ },
518
+ ]));
519
+ const defaultModel = this.config.defaultModels.find((m) => m.isDefault)?.id ?? this.config.defaultModels[0]?.id;
520
+ return {
521
+ providers: [
522
+ {
523
+ id: providerId,
524
+ name: this.config.displayName,
525
+ source: this.apiKeyOverride || process.env[this.config.authEnvKey] ? "env" : "oauth",
526
+ models,
527
+ },
528
+ ],
529
+ default: defaultModel ? { [providerId]: defaultModel } : {},
530
+ };
531
+ }
532
+ async setAuth(_providerId, key) {
533
+ const trimmed = key.trim();
534
+ if (!trimmed)
535
+ throw new Error("API key is required");
536
+ this.apiKeyOverride = trimmed;
537
+ saveAuthSecret(this.config.authEnvKey, trimmed);
538
+ return {};
539
+ }
540
+ async command() {
541
+ throw new Error(`Slash commands are not supported by ${this.config.displayName} via RPC`);
542
+ }
543
+ async revert() {
544
+ throw new Error(`Revert is not supported by ${this.config.displayName} yet`);
545
+ }
546
+ async unrevert() {
547
+ throw new Error(`Unrevert is not supported by ${this.config.displayName} yet`);
548
+ }
549
+ async share() {
550
+ return { share: { url: null } };
551
+ }
552
+ async permissionReply() {
553
+ return {};
554
+ }
555
+ }
@@ -0,0 +1 @@
1
+ export {};