kovence-cli 0.0.0-stage → 1.0.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/nd.js ADDED
@@ -0,0 +1,700 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+
4
+ const fs = require("node:fs");
5
+ const path = require("node:path");
6
+ const util = require("node:util");
7
+ const pkg = require("./package.json");
8
+ const {
9
+ AGENT_MODES,
10
+ getDefaultPaths,
11
+ safeId,
12
+ loadSettings,
13
+ resolveEffectiveSettings,
14
+ resolveEffectiveModel,
15
+ loadGlobalMemory,
16
+ loadProviders,
17
+ createEmptySession,
18
+ loadSession,
19
+ saveSession,
20
+ listSessions,
21
+ listCombinedRules,
22
+ removePermissionRuleByIndex,
23
+ loadInputHistory,
24
+ saveInputHistory,
25
+ } = require("./store");
26
+ const { capOutput, executeTool } = require("./tools");
27
+ const { BackgroundTaskManager } = require("./src/tools/tasks");
28
+ const { C, promptLine } = require("./ui");
29
+ const { KovenceTUI } = require("./tui");
30
+ const { buildProviderUrls, listProviderModels } = require("./providers");
31
+ const { parseArgs, getHelpText } = require("./src/cli/args");
32
+ const { createPlainSink, addTuiBanner, createTuiSink, nextAgentMode } = require("./src/cli/sinks");
33
+ const {
34
+ getEnvFallback,
35
+ getContextLabel,
36
+ persistAndApplySetting,
37
+ handleSlash,
38
+ switchToSession,
39
+ openSessionPicker,
40
+ replaySessionHistory,
41
+ } = require("./src/commands/handlers");
42
+ const { runAgentTurn, compactSession, waitForMemorySync } = require("./src/agent/turn");
43
+
44
+ function makeAutoSessionId() {
45
+ const d = new Date();
46
+ const pad = (n) => String(n).padStart(2, "0");
47
+ const stamp = `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
48
+ const rand = Math.random().toString(36).slice(2, 5);
49
+ return `session-${stamp}-${rand}`;
50
+ }
51
+
52
+ async function readPipedStdin() {
53
+ if (process.stdin.isTTY) return "";
54
+ const chunks = [];
55
+ for await (const chunk of process.stdin) chunks.push(chunk);
56
+ return Buffer.concat(chunks).toString("utf8").trim();
57
+ }
58
+
59
+ function printBanner(state) {
60
+ const gCount = loadGlobalMemory(state.paths).length;
61
+ const { chatUrl } = buildProviderUrls(state.provider);
62
+ const art = [
63
+ `${C.cyan}${C.bold} ██╗ ██╗ ██████╗ ██╗ ██╗███████╗███╗ ██╗ ██████╗███████╗${C.reset}`,
64
+ `${C.cyan}${C.bold} ██║ ██╔╝██╔═══██╗██║ ██║██╔════╝████╗ ██║██╔════╝██╔════╝${C.reset}`,
65
+ `${C.cyan}${C.bold} █████╔╝ ██║ ██║██║ ██║█████╗ ██╔██╗ ██║██║ █████╗ ${C.reset}`,
66
+ `${C.magenta}${C.bold} ██╔═██╗ ██║ ██║╚██╗ ██╔╝██╔══╝ ██║╚██╗██║██║ ██╔══╝ ${C.reset}`,
67
+ `${C.magenta}${C.bold} ██║ ██╗╚██████╔╝ ╚████╔╝ ███████╗██║ ╚████║╚██████╗███████╗${C.reset}`,
68
+ `${C.magenta}${C.bold} ╚═╝ ╚═╝ ╚═════╝ ╚═══╝ ╚══════╝╚═╝ ╚═══╝ ╚═════╝╚══════╝${C.reset}`,
69
+ ];
70
+ console.log();
71
+ console.log(art.join("\n"));
72
+ console.log(
73
+ ` ${C.bold}Kovence CLI${C.reset} ${C.dim}· https://kovence.com · ${chatUrl}${C.reset}\n` +
74
+ ` ${C.dim}──────────────────────────────────────────────────────────────${C.reset}\n` +
75
+ ` API : ${C.cyan}${state.provider.name}${C.reset} [${state.provider.type}] · Model: ${C.cyan}${state.model}${C.reset}\n` +
76
+ ` Session : ${C.magenta}${state.session.id}${C.reset} (${state.session.history.length} msgs, ${getContextLabel(state)}, globalMem: ${gCount})\n` +
77
+ ` Mode : ${C.yellow}${state.settings.agentMode}${C.reset} · Tools ${state.settings.toolsEnabled ? `${C.green}ON${C.reset}` : `${C.red}OFF${C.reset}`} · Memory Sync ${state.settings.autoSummarize ? `${C.green}ON${C.reset}` : "OFF"}\n` +
78
+ ` ${C.dim}Tip: @file attaches files · /mode plan|accept-edits|auto · /settings · /help${C.reset}\n`
79
+ );
80
+ }
81
+
82
+ /**
83
+ * Install centralized terminal/child cleanup across all exit and signal paths (B11).
84
+ */
85
+ function installCleanupHandlers(state, getTui, isInteractive) {
86
+ let cleaned = false;
87
+ const cleanup = (exitCode = null, fatalErr = null) => {
88
+ if (!cleaned) {
89
+ cleaned = true;
90
+ try {
91
+ state.activeAbort?.abort();
92
+ } catch {}
93
+ try {
94
+ state.memoryAbort?.abort();
95
+ } catch {}
96
+ try {
97
+ state.bgTasks?.killAll();
98
+ } catch {}
99
+ try {
100
+ getTui?.()?.leave();
101
+ } catch {}
102
+ try {
103
+ if (!state.noSession && state.session) saveSession(state.session, state.paths);
104
+ } catch {}
105
+ if (fatalErr) {
106
+ console.error(`${C.red}Fatal:${C.reset} ${fatalErr.message || fatalErr}`);
107
+ } else if (isInteractive && state.session?.id && !state.noSession) {
108
+ console.log(`${C.dim}Resume anytime: kovence --session ${state.session.id}${C.reset}`);
109
+ }
110
+ }
111
+ if (exitCode !== null) process.exit(exitCode);
112
+ };
113
+
114
+ process.on("exit", () => cleanup(null, null));
115
+ process.on("SIGTERM", () => cleanup(0, null));
116
+ process.on("SIGHUP", () => cleanup(0, null));
117
+ process.on("uncaughtException", (err) => cleanup(1, err));
118
+ process.on("unhandledRejection", (err) => cleanup(1, err));
119
+ return cleanup;
120
+ }
121
+
122
+ async function runDirectShell(state, cmdText, sink) {
123
+ const command = String(cmdText || "").trim();
124
+ if (!command) return;
125
+ sink.log("meta", `! ${command}`);
126
+ try {
127
+ const out = await executeTool(
128
+ "run_command",
129
+ { command },
130
+ {
131
+ workspaceRoot: state.workspaceRoot || process.cwd(),
132
+ extraDirs: state.extraDirs || [],
133
+ settings: state.settings,
134
+ askPrompt: sink.askPrompt,
135
+ askPassword: sink.askPassword,
136
+ bgTasks: state.bgTasks,
137
+ approvedByUser: state.settings?.agentMode === "auto",
138
+ }
139
+ );
140
+ sink.log("tool", out);
141
+ } catch (err) {
142
+ sink.log("error", `Shell error: ${err.message}`);
143
+ }
144
+ }
145
+
146
+ async function runDoctor(paths, envFallback) {
147
+ const { execFileSync } = require("node:child_process");
148
+ const hasBin = (bin) => {
149
+ try {
150
+ execFileSync("which", [bin], { stdio: "ignore" });
151
+ return true;
152
+ } catch {
153
+ return false;
154
+ }
155
+ };
156
+ const checks = [];
157
+ const nodeParts = process.versions.node.split(".").map(Number);
158
+ const nodeOk = nodeParts[0] > 20 || (nodeParts[0] === 20 && nodeParts[1] >= 12);
159
+ checks.push({ name: "Node.js (>=20.12)", ok: nodeOk, detail: `v${process.versions.node}` });
160
+ checks.push({ name: "git", ok: hasBin("git"), detail: hasBin("git") ? "installed" : "missing (optional)" });
161
+ checks.push({
162
+ name: "ripgrep (rg)",
163
+ ok: hasBin("rg"),
164
+ detail: hasBin("rg") ? "installed" : "missing (JS fallback active)",
165
+ });
166
+ checks.push({ name: "sudo", ok: hasBin("sudo"), detail: hasBin("sudo") ? "installed" : "missing" });
167
+ checks.push({ name: "Global config dir", ok: true, detail: paths.globalDir });
168
+ checks.push({ name: "Project .kovence dir", ok: true, detail: paths.projectDir });
169
+
170
+ const provStore = loadProviders(envFallback, paths);
171
+ const active = provStore.providers[provStore.active];
172
+ if (!active || !active.apiKey || active.apiKey === "sk-your-virtual-key") {
173
+ checks.push({ name: "Active API provider", ok: false, detail: "API key not configured (.env or /api add)" });
174
+ } else {
175
+ try {
176
+ const models = await listProviderModels(active, { timeoutMs: 5000 });
177
+ checks.push({
178
+ name: `Provider '${active.name}' [${active.type}]`,
179
+ ok: true,
180
+ detail: `reachable (${models.length} models listed)`,
181
+ });
182
+ } catch (err) {
183
+ checks.push({
184
+ name: `Provider '${active.name}' [${active.type}]`,
185
+ ok: false,
186
+ detail: err.message,
187
+ });
188
+ }
189
+ }
190
+
191
+ console.log(`\n${C.bold}Kovence Doctor (v${pkg.version})${C.reset}`);
192
+ for (const c of checks) {
193
+ const icon = c.ok ? `${C.green}✓${C.reset}` : `${C.red}✗${C.reset}`;
194
+ console.log(` ${icon} ${c.name}: ${c.detail}`);
195
+ }
196
+ console.log();
197
+ }
198
+
199
+ async function runPlainRepl(state) {
200
+ const sink = createPlainSink(true);
201
+ installCleanupHandlers(state, null, true);
202
+ printBanner(state);
203
+ const inputHistory = loadInputHistory(state.paths);
204
+
205
+ let lastSigIntAt = 0;
206
+ process.on("SIGINT", () => {
207
+ const now = Date.now();
208
+ if (state.activeAbort) {
209
+ if (now - lastSigIntAt < 2500) {
210
+ process.exit(0);
211
+ }
212
+ lastSigIntAt = now;
213
+ state.activeAbort.abort();
214
+ console.log(`\n${C.yellow}Task cancelled (press Ctrl+C again to exit).${C.reset}`);
215
+ } else {
216
+ process.exit(0);
217
+ }
218
+ });
219
+
220
+ const slashDeps = { waitForMemorySync, runAgentTurn, compactSession };
221
+
222
+ while (true) {
223
+ const raw = await promptLine(
224
+ `${C.green}[${state.session.id}:${state.settings.agentMode}] You: ${C.reset}`,
225
+ inputHistory
226
+ );
227
+ if (raw === null) break;
228
+ const input = raw.trim();
229
+ if (!input) continue;
230
+ if (!input.startsWith("/") && inputHistory[inputHistory.length - 1] !== input) {
231
+ inputHistory.push(input);
232
+ saveInputHistory(inputHistory, state.paths);
233
+ }
234
+ if (input === "/exit" || input === "/quit") break;
235
+
236
+ if (input.startsWith("!")) {
237
+ await runDirectShell(state, input.slice(1), sink);
238
+ console.log();
239
+ continue;
240
+ }
241
+
242
+ if (input.startsWith("/")) {
243
+ try {
244
+ await handleSlash(state, input, sink, slashDeps);
245
+ } catch (e) {
246
+ sink.log("error", `Error: ${e.message}`);
247
+ }
248
+ console.log();
249
+ continue;
250
+ }
251
+
252
+ try {
253
+ if (!state.provider || state.provider.empty || !state.provider.baseUrl || !state.provider.apiKey) {
254
+ sink.log("system", "No AI provider configured yet. Use /api add or /models to add a custom provider.");
255
+ console.log();
256
+ continue;
257
+ }
258
+ await runAgentTurn(state, input, sink);
259
+ } catch (e) {
260
+ if (e.name !== "AbortError") sink.log("error", `Error: ${e.message}`);
261
+ }
262
+ console.log();
263
+ }
264
+ }
265
+
266
+ async function runTuiRepl(state) {
267
+ let tui = null;
268
+ let sink = null;
269
+ const cleanup = installCleanupHandlers(state, () => tui, true);
270
+ const slashDeps = { waitForMemorySync, runAgentTurn, compactSession };
271
+
272
+ process.on("SIGINT", () => cleanup(0, null));
273
+
274
+ const drainQueue = async () => {
275
+ if (state.isBusy) return;
276
+ state.isBusy = true;
277
+ try {
278
+ while (state.queue.length) {
279
+ const item = state.queue.shift();
280
+ sink.syncStatus();
281
+ if (item.startsWith("/")) {
282
+ try {
283
+ await handleSlash(state, item, sink, slashDeps);
284
+ } catch (e) {
285
+ sink.log("error", `Error: ${e.message}`);
286
+ }
287
+ continue;
288
+ }
289
+ state.activePrompt = item;
290
+ sink.log("user", item);
291
+ try {
292
+ if (!state.provider || state.provider.empty || !state.provider.baseUrl || !state.provider.apiKey) {
293
+ sink.log(
294
+ "system",
295
+ "No AI provider configured yet. Use /api add or /models to add a custom provider."
296
+ );
297
+ state.activePrompt = "";
298
+ continue;
299
+ }
300
+ await runAgentTurn(state, item, sink);
301
+ state.activePrompt = "";
302
+ } catch (e) {
303
+ state.activePrompt = "";
304
+ if (e.name === "AbortError" || e.aborted) {
305
+ sink.log("system", "Task cancelled — prompt restored to input box.");
306
+ } else {
307
+ sink.log("error", `Error: ${e.message}`);
308
+ }
309
+ }
310
+ }
311
+ } finally {
312
+ state.activePrompt = "";
313
+ state.isBusy = false;
314
+ state.isDownloading = false;
315
+ sink.setBusy("");
316
+ sink.syncStatus();
317
+ }
318
+ };
319
+
320
+ const shutdown = () => cleanup(0, null);
321
+
322
+ tui = new KovenceTUI({
323
+ onSubmit(raw) {
324
+ if (raw === "/exit" || raw === "/quit") {
325
+ shutdown();
326
+ return;
327
+ }
328
+ // Slash commands execute immediately even while an agent turn is running
329
+ if (raw.startsWith("/")) {
330
+ Promise.resolve(handleSlash(state, raw, sink, slashDeps)).catch((e) => {
331
+ sink.log("error", `Error: ${e.message}`);
332
+ });
333
+ return;
334
+ }
335
+ if (raw.startsWith("!")) {
336
+ Promise.resolve(runDirectShell(state, raw.slice(1), sink)).catch((e) => {
337
+ sink.log("error", `Error: ${e.message}`);
338
+ });
339
+ return;
340
+ }
341
+ if (state.isBusy) {
342
+ if (state.settings.queuedMessages === "interrupt" && !state.isDownloading) {
343
+ state.activePrompt = "";
344
+ state.activeAbort?.abort();
345
+ state.queue.unshift(raw);
346
+ tui.flashNotice("Interrupting current turn...", 1800);
347
+ sink.syncStatus();
348
+ return;
349
+ }
350
+ state.queue.push(raw);
351
+ tui.addBlock(
352
+ "queued",
353
+ state.isDownloading
354
+ ? `[Queued while downloading #${state.queue.length}] ${raw}`
355
+ : `[Queued #${state.queue.length}] ${raw}`
356
+ );
357
+ sink.syncStatus();
358
+ return;
359
+ }
360
+ state.queue.push(raw);
361
+ drainQueue();
362
+ },
363
+ onCancel() {
364
+ const restoreParts = [];
365
+ if (state.activePrompt) {
366
+ restoreParts.push(state.activePrompt);
367
+ state.activePrompt = "";
368
+ }
369
+ if (state.queue.length) {
370
+ restoreParts.push(...state.queue);
371
+ state.queue.length = 0;
372
+ }
373
+ if (tui.input && tui.input.trim()) {
374
+ restoreParts.push(tui.input);
375
+ }
376
+ if (restoreParts.length) {
377
+ tui.setInput(restoreParts.join("\n"));
378
+ }
379
+ tui.removeQueuedBlocks();
380
+ state.activeAbort?.abort();
381
+ state.memoryAbort?.abort();
382
+ tui.cancelModal();
383
+ sink.syncStatus();
384
+ },
385
+ onOpenSessions() {
386
+ openSessionPicker(state, tui, sink, waitForMemorySync);
387
+ },
388
+ async onNewSession() {
389
+ const rawName = (await tui.askModal("New session name (blank = auto): ", false)).trim();
390
+ const id = rawName || `session-${new Date().toISOString().slice(11, 19).replace(/:/g, "")}`;
391
+ state.activePrompt = "";
392
+ state.queue.length = 0;
393
+ state.activeAbort?.abort();
394
+ await switchToSession(state, id, true, sink, waitForMemorySync);
395
+ },
396
+ onCycleMode() {
397
+ const next = nextAgentMode(state.settings.agentMode);
398
+ persistAndApplySetting(state, "agentMode", next, sink);
399
+ tui.flashNotice(`Agent Mode: ${next}`, 1800);
400
+ },
401
+ onGetSettings() {
402
+ return {
403
+ ...state.persistedSettings,
404
+ ...state.settings,
405
+ provider: state.provider?.name || state.settings.provider,
406
+ model: state.model || state.settings.model,
407
+ };
408
+ },
409
+ onUpdateSetting(key, value) {
410
+ persistAndApplySetting(state, key, value, sink);
411
+ },
412
+ onGetProviders() {
413
+ const store = loadProviders(getEnvFallback(), state.paths);
414
+ return Object.keys(store.providers);
415
+ },
416
+ onGetModels() {
417
+ const cached = state.cachedProviderModels?.get(state.provider?.name) || [];
418
+ const saved = Array.isArray(state.provider?.models) ? state.provider.models : [];
419
+ return [...new Set([state.model, ...saved, ...cached, state.provider?.defaultModel].filter(Boolean))];
420
+ },
421
+ async onRefreshModels() {
422
+ try {
423
+ const live = await listProviderModels(state.provider, { timeoutMs: 6000 });
424
+ if (Array.isArray(live) && live.length) {
425
+ state.cachedProviderModels?.set(state.provider.name, live);
426
+ tui?.scheduleRender();
427
+ }
428
+ } catch {}
429
+ },
430
+ async onPickSettingChoice(key) {
431
+ const savedSettings = tui.settingsScreen ? { ...tui.settingsScreen } : null;
432
+ tui.settingsScreen = null;
433
+ try {
434
+ if (key === "provider") {
435
+ const store = loadProviders(getEnvFallback(), state.paths);
436
+ const items = Object.values(store.providers).map((p) => ({
437
+ type: "provider",
438
+ id: p.name,
439
+ label: `${p.name === state.provider.name ? "● " : " "}${p.name}`,
440
+ desc: `[${p.type}] ${p.baseUrl}`,
441
+ }));
442
+ const picked = await sink.openChoicePicker("Select Provider", items, state.provider.name);
443
+ if (picked) {
444
+ persistAndApplySetting(state, "provider", picked, sink);
445
+ }
446
+ } else if (key === "model") {
447
+ let live = state.cachedProviderModels?.get(state.provider.name) || [];
448
+ if (!live.length) {
449
+ try {
450
+ live = await listProviderModels(state.provider, { timeoutMs: 6000 });
451
+ if (live.length) state.cachedProviderModels?.set(state.provider.name, live);
452
+ } catch {}
453
+ }
454
+ const saved = Array.isArray(state.provider?.models) ? state.provider.models : [];
455
+ const allModels = [
456
+ ...new Set([state.model, ...saved, ...live, state.provider?.defaultModel].filter(Boolean)),
457
+ ];
458
+ const items = [
459
+ ...allModels.map((id) => ({
460
+ type: "model",
461
+ id,
462
+ label: `${id === state.model ? "● " : " "}${id}`,
463
+ desc: saved.includes(id) ? "saved" : "api",
464
+ })),
465
+ { type: "new", id: "__custom__", label: "+ Enter custom model ID", desc: "" },
466
+ ];
467
+ const picked = await sink.openChoicePicker(
468
+ `Select Model (${state.provider.name})`,
469
+ items,
470
+ state.model
471
+ );
472
+ if (picked === "__custom__") {
473
+ const custom = (await tui.askModal("Custom model ID: ", false)).trim();
474
+ if (custom) persistAndApplySetting(state, "model", custom, sink);
475
+ } else if (picked) {
476
+ persistAndApplySetting(state, "model", picked, sink);
477
+ }
478
+ }
479
+ } finally {
480
+ if (savedSettings) {
481
+ tui.settingsScreen = savedSettings;
482
+ tui.scheduleRender();
483
+ }
484
+ }
485
+ },
486
+ onGetPermissionRules() {
487
+ return listCombinedRules(state.sessionRules, state.paths);
488
+ },
489
+ onRemovePermissionRule(rule) {
490
+ if (rule.origin === "session") {
491
+ const idx = state.sessionRules.findIndex((r) => r.id === rule.id);
492
+ if (idx >= 0) return state.sessionRules.splice(idx, 1)[0];
493
+ return null;
494
+ }
495
+ const all = listCombinedRules(state.sessionRules, state.paths);
496
+ const idxOneBased = all.findIndex((r) => r.id === rule.id && r.origin === rule.origin) + 1;
497
+ const sessionLen = state.sessionRules.length;
498
+ if (idxOneBased > sessionLen) {
499
+ return removePermissionRuleByIndex(idxOneBased - sessionLen, state.paths);
500
+ }
501
+ return null;
502
+ },
503
+ workspaceRoot: state.workspaceRoot || process.cwd(),
504
+ initialInputHistory: loadInputHistory(state.paths),
505
+ onSaveInputHistory: (items) => saveInputHistory(items, state.paths),
506
+ onExit: shutdown,
507
+ });
508
+
509
+ sink = createTuiSink(tui, state);
510
+ sink.openSessions = () => openSessionPicker(state, tui, sink, waitForMemorySync);
511
+ sink.copyLast = () => tui.copyLastResponse();
512
+ sink.toggleSelect = () => tui.toggleMouseMode();
513
+ sink.exit = shutdown;
514
+ tui.enter();
515
+ sink.syncStatus();
516
+
517
+ addTuiBanner(tui, state);
518
+ replaySessionHistory(sink, state);
519
+ }
520
+
521
+ async function main() {
522
+ let opts;
523
+ try {
524
+ opts = parseArgs(process.argv.slice(2));
525
+ } catch (err) {
526
+ console.error(`Error: ${err.message}`);
527
+ process.exit(1);
528
+ }
529
+
530
+ if (opts.version) {
531
+ console.log(`kovence-cli v${pkg.version}`);
532
+ return;
533
+ }
534
+ if (opts.help) {
535
+ console.log(getHelpText());
536
+ return;
537
+ }
538
+
539
+ const paths = getDefaultPaths();
540
+ const envFallback = getEnvFallback();
541
+ if (opts.doctor) {
542
+ await runDoctor(paths, envFallback);
543
+ return;
544
+ }
545
+ const provStore = loadProviders(envFallback, paths);
546
+ const activeProvName = opts.provider ? safeId(opts.provider) : provStore.active;
547
+ let provider = activeProvName ? provStore.providers[activeProvName] : null;
548
+ if (opts.provider && !provider) {
549
+ console.error(`Provider '${activeProvName}' not found. Use /api list or /api add.`);
550
+ process.exit(1);
551
+ }
552
+ const piped = await readPipedStdin();
553
+ if (!provider || !provider.apiKey || provider.apiKey === "sk-your-virtual-key") {
554
+ if (opts.prompt || piped) {
555
+ console.error(
556
+ "No AI provider configured. Run interactively and use /api add or /models to add a provider."
557
+ );
558
+ process.exit(1);
559
+ }
560
+ provider = {
561
+ name: "(none)",
562
+ type: "openai",
563
+ baseUrl: "",
564
+ apiKey: "",
565
+ defaultModel: "",
566
+ models: [],
567
+ empty: true,
568
+ };
569
+ }
570
+
571
+ const persistedSettings = loadSettings(paths);
572
+ let sessionId = "";
573
+ let isFreshSession = false;
574
+ if (opts.newSession) {
575
+ sessionId = safeId(opts.newSession);
576
+ isFreshSession = true;
577
+ } else if (opts.session) {
578
+ sessionId = safeId(opts.session);
579
+ } else if (opts.continueLatest) {
580
+ const recent = listSessions(paths);
581
+ sessionId = recent[0]?.id || makeAutoSessionId();
582
+ isFreshSession = recent.length === 0;
583
+ } else {
584
+ sessionId = makeAutoSessionId();
585
+ isFreshSession = true;
586
+ }
587
+
588
+ const session =
589
+ opts.noSession || isFreshSession ? createEmptySession(sessionId, "") : loadSession(sessionId, "", paths);
590
+
591
+ const runtimeOverrides = {
592
+ cliAuto: opts.autoApprove === true,
593
+ cliMode: opts.mode || "",
594
+ cliProvider: opts.provider || "",
595
+ sessionAgentMode: !isFreshSession && !opts.mode && !opts.autoApprove ? session.agentMode || "" : "",
596
+ };
597
+ const settings = resolveEffectiveSettings(persistedSettings, runtimeOverrides);
598
+ if (opts.system) settings.systemPrompt = opts.system;
599
+ if (opts.toolsEnabled !== null) settings.toolsEnabled = opts.toolsEnabled;
600
+ if (opts.autoSummarize !== null) settings.autoSummarize = opts.autoSummarize;
601
+ if (opts.temperature !== null) settings.temperature = opts.temperature;
602
+ if (opts.maxTokens !== null) settings.maxTokens = opts.maxTokens;
603
+
604
+ let model = resolveEffectiveModel({
605
+ cliModel: opts.model,
606
+ sessionModel: isFreshSession ? "" : session.model,
607
+ persistedModel: persistedSettings.model,
608
+ providerDefaultModel: provider.defaultModel,
609
+ });
610
+ if (!model && !provider.empty && provider.baseUrl) {
611
+ const ids = await listProviderModels(provider);
612
+ if (!ids.length) {
613
+ console.error("Provider theke kono model pawa jay ni.");
614
+ process.exit(1);
615
+ }
616
+ model = ids[0];
617
+ }
618
+ session.model = model;
619
+ if (!opts.noSession) saveSession(session, paths);
620
+
621
+ const state = {
622
+ paths,
623
+ workspaceRoot: paths.cwd,
624
+ extraDirs: opts.addDirs || [],
625
+ noSession: opts.noSession,
626
+ cliModel: opts.model || "",
627
+ provider,
628
+ model,
629
+ persistedSettings,
630
+ runtimeOverrides,
631
+ settings,
632
+ session,
633
+ sessionRules: [],
634
+ capabilities: { _byModel: new Map() },
635
+ activeAbort: null,
636
+ memoryAbort: null,
637
+ memorySyncPromise: null,
638
+ activePrompt: "",
639
+ lastFailedPrompt: "",
640
+ sudoPasswords: new Map(),
641
+ cachedProviderModels: new Map(),
642
+ bgTasks: new BackgroundTaskManager(),
643
+ queue: [],
644
+ isBusy: false,
645
+ isDownloading: false,
646
+ debug: Boolean(opts.debug),
647
+ headless: false,
648
+ };
649
+
650
+ if (opts.prompt || piped) {
651
+ state.headless = true;
652
+ const combined = [opts.prompt, piped ? `\`\`\`\n${capOutput(piped)}\n\`\`\`` : ""].filter(Boolean).join("\n\n");
653
+ const sink = createPlainSink(false, { headless: true, jsonMode: opts.json });
654
+ try {
655
+ const result = await runAgentTurn(state, combined, sink);
656
+ if (opts.json) {
657
+ console.log(
658
+ JSON.stringify(
659
+ {
660
+ ok: true,
661
+ sessionId: state.session.id,
662
+ provider: state.provider.name,
663
+ model: state.model,
664
+ answer: result.answer,
665
+ toolsUsed: result.toolsUsed,
666
+ usage: result.usage,
667
+ elapsedMs: result.elapsedMs,
668
+ },
669
+ null,
670
+ 2
671
+ )
672
+ );
673
+ }
674
+ } catch (err) {
675
+ if (opts.json) {
676
+ console.log(JSON.stringify({ ok: false, error: err.message }, null, 2));
677
+ } else {
678
+ console.error(`Error: ${err.message}`);
679
+ }
680
+ process.exit(1);
681
+ }
682
+ return;
683
+ }
684
+
685
+ const usePlain = opts.plain || settings.renderingMode === "inline" || !process.stdin.isTTY || !process.stdout.isTTY;
686
+ if (!usePlain) {
687
+ await runTuiRepl(state);
688
+ } else {
689
+ await runPlainRepl(state);
690
+ }
691
+ }
692
+
693
+ if (require.main === module) {
694
+ main().catch((e) => {
695
+ console.error(`${C.red}Fatal:${C.reset} ${e.message}`);
696
+ process.exit(1);
697
+ });
698
+ }
699
+
700
+ module.exports = { main };