kodorun-cli 0.0.0-stage → 0.1.123

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,36 @@
1
+ import { ChildProcess, StdioOptions } from "child_process";
2
+ import type { AiBackend, MessageInfo, SessionInfo } from "./interface.js";
3
+ export declare function spawnCliBinary(executablePath: string, args: string[], options: {
4
+ cwd: string;
5
+ env: NodeJS.ProcessEnv;
6
+ stdio: StdioOptions;
7
+ }): ChildProcess;
8
+ export interface StoredSessionRecord {
9
+ id: string;
10
+ remoteSessionId?: string;
11
+ title: string;
12
+ createdAt: number;
13
+ updatedAt: number;
14
+ cwd: string;
15
+ messages: MessageInfo[];
16
+ }
17
+ export declare function getKodoRunDataDir(): string;
18
+ export declare function resolveExecutable(candidates: string[], extraPaths?: string[]): string | null;
19
+ export declare function loadAuthSecrets(): Record<string, string>;
20
+ export declare function saveAuthSecret(envKey: string, value: string): void;
21
+ export declare class LocalAiSessionStore {
22
+ private readonly filePath;
23
+ private readonly cwdKey;
24
+ private sessions;
25
+ constructor(backend: AiBackend, cwd?: string);
26
+ private loadFromDisk;
27
+ private saveToDisk;
28
+ listForWorkspace(): StoredSessionRecord[];
29
+ get(id: string): StoredSessionRecord | undefined;
30
+ upsert(record: StoredSessionRecord): StoredSessionRecord;
31
+ delete(id: string): boolean;
32
+ touch(id: string): void;
33
+ appendMessage(sessionId: string, message: MessageInfo): void;
34
+ upsertPart(sessionId: string, messageId: string, role: "user" | "assistant", part: Record<string, unknown>): void;
35
+ toSessionInfo(rec: StoredSessionRecord): SessionInfo;
36
+ }
@@ -0,0 +1,252 @@
1
+ import { spawn, spawnSync } from "child_process";
2
+ import * as fs from "fs";
3
+ import * as os from "os";
4
+ import * as path from "path";
5
+ function quoteWindowsCmdArg(arg) {
6
+ if (!arg)
7
+ return '""';
8
+ const sanitized = arg.replace(/\0/g, "").replace(/\r?\n/g, " ");
9
+ if (!/[\s"&|^<>()%]/.test(sanitized))
10
+ return sanitized;
11
+ return `"${sanitized.replace(/"/g, '""').replace(/%/g, "^%")}"`;
12
+ }
13
+ function resolveNpmCmdJsEntry(cmdPath) {
14
+ try {
15
+ const content = fs.readFileSync(cmdPath, "utf8");
16
+ const match = content.match(/"%dp0%\\([^"\r\n]+\.(?:mjs|cjs|js))"/i);
17
+ if (!match?.[1])
18
+ return null;
19
+ const candidate = path.resolve(path.dirname(cmdPath), match[1]);
20
+ return fs.existsSync(candidate) ? candidate : null;
21
+ }
22
+ catch {
23
+ return null;
24
+ }
25
+ }
26
+ export function spawnCliBinary(executablePath, args, options) {
27
+ if (process.platform === "win32" && /\.(cmd|bat)$/i.test(executablePath)) {
28
+ const jsEntry = resolveNpmCmdJsEntry(executablePath);
29
+ if (jsEntry) {
30
+ return spawn(process.execPath, [jsEntry, ...args], {
31
+ ...options,
32
+ shell: false,
33
+ });
34
+ }
35
+ const comspec = process.env.COMSPEC || "cmd.exe";
36
+ const commandLine = `"${[executablePath, ...args].map(quoteWindowsCmdArg).join(" ")}"`;
37
+ return spawn(comspec, ["/d", "/s", "/c", commandLine], {
38
+ ...options,
39
+ shell: false,
40
+ windowsVerbatimArguments: true,
41
+ });
42
+ }
43
+ return spawn(executablePath, args, {
44
+ ...options,
45
+ shell: false,
46
+ });
47
+ }
48
+ export function getKodoRunDataDir() {
49
+ if (process.platform === "win32") {
50
+ const appData = process.env.APPDATA || path.join(os.homedir(), "AppData", "Roaming");
51
+ return path.join(appData, "kodorun");
52
+ }
53
+ if (process.platform === "darwin") {
54
+ return path.join(os.homedir(), "Library", "Application Support", "kodorun");
55
+ }
56
+ const xdg = process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config");
57
+ return path.join(xdg, "kodorun");
58
+ }
59
+ function normalizePathKey(dirPath) {
60
+ try {
61
+ const resolved = fs.realpathSync(dirPath);
62
+ return process.platform === "win32" ? resolved.toLowerCase() : resolved;
63
+ }
64
+ catch {
65
+ const resolved = path.resolve(dirPath);
66
+ return process.platform === "win32" ? resolved.toLowerCase() : resolved;
67
+ }
68
+ }
69
+ export function resolveExecutable(candidates, extraPaths = []) {
70
+ for (const extra of extraPaths) {
71
+ if (extra && fs.existsSync(extra)) {
72
+ return extra;
73
+ }
74
+ }
75
+ for (const candidate of candidates) {
76
+ const checker = process.platform === "win32" ? "where" : "which";
77
+ const probe = spawnSync(checker, [candidate], {
78
+ stdio: ["ignore", "pipe", "ignore"],
79
+ encoding: "utf8",
80
+ shell: false,
81
+ });
82
+ if (!probe.error && probe.status === 0 && probe.stdout) {
83
+ const lines = probe.stdout
84
+ .split(/\r?\n/)
85
+ .map((line) => line.trim())
86
+ .filter(Boolean);
87
+ if (process.platform === "win32") {
88
+ const preferred = lines.find((line) => /\.(exe|cmd|bat|com)$/i.test(line)) ??
89
+ lines.find((line) => fs.existsSync(`${line}.exe`)) ??
90
+ lines.find((line) => fs.existsSync(`${line}.cmd`)) ??
91
+ lines[0];
92
+ if (preferred) {
93
+ if (!path.extname(preferred)) {
94
+ if (fs.existsSync(`${preferred}.exe`))
95
+ return `${preferred}.exe`;
96
+ if (fs.existsSync(`${preferred}.cmd`))
97
+ return `${preferred}.cmd`;
98
+ }
99
+ if (!/\.ps1$/i.test(preferred))
100
+ return preferred;
101
+ const base = preferred.replace(/\.ps1$/i, "");
102
+ if (fs.existsSync(`${base}.cmd`))
103
+ return `${base}.cmd`;
104
+ if (fs.existsSync(`${base}.exe`))
105
+ return `${base}.exe`;
106
+ return preferred;
107
+ }
108
+ }
109
+ else if (lines[0]) {
110
+ return lines[0];
111
+ }
112
+ }
113
+ }
114
+ return null;
115
+ }
116
+ export function loadAuthSecrets() {
117
+ const filePath = path.join(getKodoRunDataDir(), "ai-auth.json");
118
+ try {
119
+ if (!fs.existsSync(filePath))
120
+ return {};
121
+ const parsed = JSON.parse(fs.readFileSync(filePath, "utf8"));
122
+ return parsed && typeof parsed === "object" ? parsed : {};
123
+ }
124
+ catch {
125
+ return {};
126
+ }
127
+ }
128
+ export function saveAuthSecret(envKey, value) {
129
+ const dir = getKodoRunDataDir();
130
+ const filePath = path.join(dir, "ai-auth.json");
131
+ fs.mkdirSync(dir, { recursive: true });
132
+ const existing = loadAuthSecrets();
133
+ existing[envKey] = value;
134
+ fs.writeFileSync(filePath, JSON.stringify(existing, null, 2), { encoding: "utf8", mode: 0o600 });
135
+ }
136
+ export class LocalAiSessionStore {
137
+ filePath;
138
+ cwdKey;
139
+ sessions = new Map();
140
+ constructor(backend, cwd = process.cwd()) {
141
+ this.cwdKey = normalizePathKey(cwd);
142
+ const dir = path.join(getKodoRunDataDir(), "ai-sessions");
143
+ this.filePath = path.join(dir, `${backend}.json`);
144
+ this.loadFromDisk();
145
+ }
146
+ loadFromDisk() {
147
+ try {
148
+ if (!fs.existsSync(this.filePath))
149
+ return;
150
+ const parsed = JSON.parse(fs.readFileSync(this.filePath, "utf8"));
151
+ if (!Array.isArray(parsed))
152
+ return;
153
+ for (const item of parsed) {
154
+ if (!item || typeof item !== "object")
155
+ continue;
156
+ const rec = item;
157
+ if (typeof rec.id !== "string" || typeof rec.cwd !== "string")
158
+ continue;
159
+ this.sessions.set(rec.id, {
160
+ id: rec.id,
161
+ remoteSessionId: typeof rec.remoteSessionId === "string" ? rec.remoteSessionId : undefined,
162
+ title: typeof rec.title === "string" && rec.title.trim() ? rec.title : "Conversation",
163
+ createdAt: typeof rec.createdAt === "number" ? rec.createdAt : Date.now(),
164
+ updatedAt: typeof rec.updatedAt === "number" ? rec.updatedAt : Date.now(),
165
+ cwd: rec.cwd,
166
+ messages: Array.isArray(rec.messages) ? rec.messages : [],
167
+ });
168
+ }
169
+ }
170
+ catch {
171
+ // Ignore corrupt session store and start cleanly
172
+ }
173
+ }
174
+ saveToDisk() {
175
+ try {
176
+ fs.mkdirSync(path.dirname(this.filePath), { recursive: true, mode: 0o700 });
177
+ const payload = JSON.stringify(Array.from(this.sessions.values()), null, 2);
178
+ fs.writeFileSync(this.filePath, payload, { encoding: "utf8", mode: 0o600 });
179
+ }
180
+ catch {
181
+ // Best-effort persistence only
182
+ }
183
+ }
184
+ listForWorkspace() {
185
+ return Array.from(this.sessions.values())
186
+ .filter((s) => normalizePathKey(s.cwd) === this.cwdKey)
187
+ .sort((a, b) => a.updatedAt - b.updatedAt);
188
+ }
189
+ get(id) {
190
+ return this.sessions.get(id);
191
+ }
192
+ upsert(record) {
193
+ this.sessions.set(record.id, record);
194
+ this.saveToDisk();
195
+ return record;
196
+ }
197
+ delete(id) {
198
+ const deleted = this.sessions.delete(id);
199
+ if (deleted)
200
+ this.saveToDisk();
201
+ return deleted;
202
+ }
203
+ touch(id) {
204
+ const rec = this.sessions.get(id);
205
+ if (!rec)
206
+ return;
207
+ rec.updatedAt = Date.now();
208
+ this.saveToDisk();
209
+ }
210
+ appendMessage(sessionId, message) {
211
+ const rec = this.sessions.get(sessionId);
212
+ if (!rec)
213
+ return;
214
+ const idx = rec.messages.findIndex((m) => m.id === message.id);
215
+ if (idx >= 0) {
216
+ rec.messages[idx] = message;
217
+ }
218
+ else {
219
+ rec.messages.push(message);
220
+ }
221
+ rec.updatedAt = Date.now();
222
+ this.saveToDisk();
223
+ }
224
+ upsertPart(sessionId, messageId, role, part) {
225
+ const rec = this.sessions.get(sessionId);
226
+ if (!rec)
227
+ return;
228
+ let msg = rec.messages.find((m) => m.id === messageId);
229
+ if (!msg) {
230
+ msg = { id: messageId, role, parts: [], time: Date.now() };
231
+ rec.messages.push(msg);
232
+ }
233
+ const partId = typeof part.id === "string" ? part.id : undefined;
234
+ const parts = msg.parts;
235
+ const existingIdx = partId ? parts.findIndex((p) => p.id === partId) : -1;
236
+ if (existingIdx >= 0) {
237
+ parts[existingIdx] = part;
238
+ }
239
+ else {
240
+ parts.push(part);
241
+ }
242
+ rec.updatedAt = Date.now();
243
+ this.saveToDisk();
244
+ }
245
+ toSessionInfo(rec) {
246
+ return {
247
+ id: rec.id,
248
+ title: rec.title,
249
+ time: { created: rec.createdAt, updated: rec.updatedAt },
250
+ };
251
+ }
252
+ }
@@ -0,0 +1,80 @@
1
+ import type { AIProvider, AiBackend, AiEventEmitter, CodexPromptOptions, FileAttachment, MessageInfo, ModelSelector, ProviderInfo, SessionInfo, ShareInfo } from "./interface.js";
2
+ export interface StreamJsonModelSeed {
3
+ id: string;
4
+ name: string;
5
+ isDefault?: boolean;
6
+ reasoning?: boolean;
7
+ attachment?: boolean;
8
+ }
9
+ export interface StreamJsonProviderConfig {
10
+ backend: AiBackend;
11
+ displayName: string;
12
+ binaryCandidates: string[];
13
+ extraBinaryPaths?: string[];
14
+ authEnvKey: string;
15
+ defaultModels: StreamJsonModelSeed[];
16
+ buildArgs: (opts: {
17
+ prompt: string;
18
+ remoteSessionId?: string;
19
+ localSessionId: string;
20
+ isFirstTurn: boolean;
21
+ modelId?: string;
22
+ agent?: string;
23
+ }) => string[];
24
+ }
25
+ export declare class StreamJsonProvider implements AIProvider {
26
+ private readonly config;
27
+ private readonly store;
28
+ private executablePath;
29
+ private emitter;
30
+ private activeProcs;
31
+ private abortedSessions;
32
+ private activeStatus;
33
+ private apiKeyOverride;
34
+ constructor(config: StreamJsonProviderConfig);
35
+ private debugLog;
36
+ init(): Promise<void>;
37
+ destroy(): Promise<void>;
38
+ subscribe(emitter: AiEventEmitter): () => void;
39
+ createSession(title?: string): Promise<{
40
+ session: SessionInfo;
41
+ }>;
42
+ listSessions(): Promise<{
43
+ sessions: unknown;
44
+ }>;
45
+ getSession(id: string): Promise<{
46
+ session: SessionInfo;
47
+ }>;
48
+ deleteSession(id: string): Promise<{
49
+ deleted: boolean;
50
+ }>;
51
+ renameSession(id: string, title: string): Promise<{
52
+ session: SessionInfo;
53
+ }>;
54
+ getMessages(sessionId: string): Promise<{
55
+ messages: MessageInfo[];
56
+ }>;
57
+ statuses(): Promise<{
58
+ statuses: Record<string, unknown>;
59
+ }>;
60
+ private emitPart;
61
+ prompt(sessionId: string, text: string, model?: ModelSelector, agent?: string, _files?: FileAttachment[], _codexOptions?: CodexPromptOptions): Promise<{
62
+ ack: true;
63
+ }>;
64
+ private runTurn;
65
+ abort(sessionId: string): Promise<Record<string, never>>;
66
+ agents(): Promise<{
67
+ agents: unknown;
68
+ }>;
69
+ providers(): Promise<ProviderInfo>;
70
+ setAuth(_providerId: string, key: string): Promise<Record<string, never>>;
71
+ command(): Promise<{
72
+ result: unknown;
73
+ }>;
74
+ revert(): Promise<Record<string, never>>;
75
+ unrevert(): Promise<Record<string, never>>;
76
+ share(): Promise<{
77
+ share: ShareInfo;
78
+ }>;
79
+ permissionReply(): Promise<Record<string, never>>;
80
+ }