kovence-cli 0.0.0-stage → 1.0.1

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,1280 @@
1
+ "use strict";
2
+
3
+ const fs = require("node:fs");
4
+ const path = require("node:path");
5
+ const {
6
+ AGENT_MODES,
7
+ loadGlobalMemory,
8
+ saveGlobalMemory,
9
+ addGlobalMemory,
10
+ redactSecret,
11
+ loadProviders,
12
+ upsertProvider,
13
+ addProviderModels,
14
+ setActiveProvider,
15
+ removeProvider,
16
+ loadSession,
17
+ saveSession,
18
+ renameSession,
19
+ forkSession,
20
+ listSessions,
21
+ groupSessionsByDate,
22
+ deleteSession,
23
+ safeId,
24
+ updatePersistedSetting,
25
+ resolveEffectiveModel,
26
+ loadPermissionRules,
27
+ addPermissionRule,
28
+ listCombinedRules,
29
+ removePermissionRuleByIndex,
30
+ resetPermissionRules,
31
+ } = require("../../store");
32
+ const { listProviderModels } = require("../../providers");
33
+ const { TOOL_DEFINITIONS } = require("../../tools");
34
+ const { estimateMessagesTokens } = require("../agent/history");
35
+ const { estimateTokenCostUsd } = require("../config/model_registry");
36
+ const { generateProjectInitDoc } = require("../agent/project_context");
37
+ const { undoLastCheckpoint } = require("../tools/checkpoints");
38
+ const { getHelpText } = require("../cli/args");
39
+
40
+ function getEnvFallback() {
41
+ return {
42
+ baseUrl: String(process.env.LITELLM_BASE_URL || "").replace(/\/+$/, ""),
43
+ apiKey: process.env.LITELLM_VIRTUAL_KEY || process.env.LITELLM_API_KEY || "",
44
+ defaultModel: process.env.LITELLM_MODEL || "",
45
+ };
46
+ }
47
+
48
+ function summarizeArgsShort(rawArgs) {
49
+ try {
50
+ const obj = JSON.parse(rawArgs || "{}");
51
+ const first = obj.path || obj.command || obj.query || obj.pattern || obj.url || obj.fact || "";
52
+ return first ? String(first).slice(0, 60) : "";
53
+ } catch {
54
+ return "";
55
+ }
56
+ }
57
+
58
+ function formatContextMessages(state) {
59
+ const msgs = [{ role: "system", content: state.settings.systemPrompt }];
60
+ const g = loadGlobalMemory(state.paths);
61
+ if (g.length) {
62
+ msgs.push({ role: "system", content: g.join("\n") });
63
+ }
64
+ return [...msgs, ...state.session.history.slice(-state.settings.maxHistoryMessages)];
65
+ }
66
+
67
+ function getContextLabel(state) {
68
+ const est = estimateMessagesTokens(formatContextMessages(state));
69
+ const win = state.settings.contextWindow || 128000;
70
+ return `Context: ~${est} / ${win} tokens`;
71
+ }
72
+
73
+ function persistAndApplySetting(state, key, value, sink) {
74
+ const res = updatePersistedSetting(key, value, state.paths);
75
+ if (!res.ok) {
76
+ sink.log("error", res.error);
77
+ return false;
78
+ }
79
+ // Apply changed key onto persisted & active runtime settings without leaking unrelated runtime flags
80
+ state.persistedSettings = res.settings;
81
+ state.settings[res.key] = res.value;
82
+ if (res.key === "agentMode") {
83
+ if (state.runtimeOverrides) {
84
+ delete state.runtimeOverrides.cliAuto;
85
+ delete state.runtimeOverrides.cliMode;
86
+ delete state.runtimeOverrides.sessionAgentMode;
87
+ }
88
+ if (state.session) {
89
+ state.session.agentMode = res.value;
90
+ if (!state.noSession) saveSession(state.session, state.paths);
91
+ }
92
+ }
93
+ if (res.key === "model") {
94
+ state.model = res.value || state.provider?.defaultModel || state.model;
95
+ if (state.cliModel) state.cliModel = state.model;
96
+ if (state.session) {
97
+ state.session.model = state.model;
98
+ if (!state.noSession) saveSession(state.session, state.paths);
99
+ }
100
+ }
101
+ if (res.key === "provider") {
102
+ const store = loadProviders(getEnvFallback(), state.paths);
103
+ if (store.providers[res.value]) {
104
+ setActiveProvider(getEnvFallback(), res.value, state.paths);
105
+ state.provider = store.providers[res.value];
106
+ state.cliModel = "";
107
+ const provModels = Array.isArray(state.provider.models) ? state.provider.models : [];
108
+ const currentValid = state.model && provModels.includes(state.model);
109
+ const nextModel = currentValid ? state.model : state.provider.defaultModel || provModels[0] || state.model;
110
+ if (nextModel) {
111
+ state.model = nextModel;
112
+ if (state.session) {
113
+ state.session.model = nextModel;
114
+ if (!state.noSession) saveSession(state.session, state.paths);
115
+ }
116
+ updatePersistedSetting("model", nextModel, state.paths);
117
+ state.persistedSettings.model = nextModel;
118
+ }
119
+ }
120
+ }
121
+ sink.syncStatus();
122
+ return true;
123
+ }
124
+
125
+ function handleSetCommand(state, arg, sink) {
126
+ const [key, ...rest] = arg.split(/\s+/);
127
+ const val = rest.join(" ").trim();
128
+ if (!key) {
129
+ const safeSettings = { ...state.persistedSettings };
130
+ sink.log("system", JSON.stringify(safeSettings, null, 2));
131
+ return;
132
+ }
133
+ if (!val) {
134
+ sink.log("error", `Usage: /set ${key} <value>`);
135
+ return;
136
+ }
137
+ if (persistAndApplySetting(state, key, val, sink)) {
138
+ sink.log("system", `Updated ${key}: ${JSON.stringify(state.settings[key])}`);
139
+ }
140
+ }
141
+
142
+ async function handleModeCommand(state, arg, sink) {
143
+ let clean = arg.trim().toLowerCase();
144
+ if (!clean) {
145
+ if (sink.openModePicker) {
146
+ const chosen = await sink.openModePicker(state.settings.agentMode);
147
+ if (!chosen) return;
148
+ clean = chosen;
149
+ } else {
150
+ sink.log("system", `Current agentMode: ${state.settings.agentMode} (valid: ${AGENT_MODES.join(", ")})`);
151
+ return;
152
+ }
153
+ }
154
+ if (!AGENT_MODES.includes(clean)) {
155
+ sink.log("error", `Invalid mode '${clean}'. Choose one of: ${AGENT_MODES.join(", ")}`);
156
+ return;
157
+ }
158
+ if (persistAndApplySetting(state, "agentMode", clean, sink)) {
159
+ state.session.agentMode = clean;
160
+ if (!state.noSession) saveSession(state.session, state.paths);
161
+ sink.syncStatus();
162
+ sink.log("system", `Agent mode switched to '${clean}'.`);
163
+ }
164
+ }
165
+
166
+ function inferPermissionScope(tool, pattern) {
167
+ if (!pattern || pattern === "*") return { scope: "tool", pattern: "" };
168
+ if (tool === "run_command") return { scope: "commandPrefix", pattern };
169
+ if (tool === "web_fetch" || tool === "download_file") return { scope: "domain", pattern };
170
+ return { scope: "path", pattern };
171
+ }
172
+
173
+ function handlePermissionsCommand(state, arg, sink) {
174
+ if (!arg.trim() && sink.openPermissions) {
175
+ sink.openPermissions();
176
+ return;
177
+ }
178
+ const parts = arg.split(/\s+/).filter(Boolean);
179
+ const isGlobal = parts.includes("--global");
180
+ const cleanParts = parts.filter((p) => p !== "--global");
181
+ const sub = (cleanParts[0] || "list").toLowerCase();
182
+
183
+ if (sub === "list") {
184
+ const all = listCombinedRules(state.sessionRules, state.paths);
185
+ if (!all.length) {
186
+ sink.log(
187
+ "system",
188
+ "(No permission rules configured. Use /permissions allow|deny or approve with [s]/[A].)"
189
+ );
190
+ return;
191
+ }
192
+ const lines = all.map(
193
+ (r, i) => `${i + 1}. [${r.origin}] ${r.action.toUpperCase()} ${r.tool} (${r.scope}: ${r.pattern || "*"})`
194
+ );
195
+ sink.log("system", `Permission Rules:\n${lines.join("\n")}`);
196
+ return;
197
+ }
198
+
199
+ if ((sub === "allow" || sub === "deny") && cleanParts[1]) {
200
+ const tool = cleanParts[1];
201
+ const rawPattern = cleanParts.slice(2).join(" ").trim();
202
+ const { scope, pattern } = inferPermissionScope(tool, rawPattern);
203
+ const target = isGlobal ? "global" : "project";
204
+ const saved = addPermissionRule({ action: sub, tool, scope, pattern }, target, state.paths);
205
+ sink.log(
206
+ "system",
207
+ `Added ${target} ${saved.action} rule: ${saved.tool} (${saved.scope}: ${saved.pattern || "*"})`
208
+ );
209
+ return;
210
+ }
211
+
212
+ if (sub === "rm" && cleanParts[1]) {
213
+ const n = Number(cleanParts[1]);
214
+ if (!Number.isInteger(n) || n < 1) {
215
+ sink.log("error", "Usage: /permissions rm <rule-number>");
216
+ return;
217
+ }
218
+ const sessionLen = state.sessionRules.length;
219
+ if (n <= sessionLen) {
220
+ const [removed] = state.sessionRules.splice(n - 1, 1);
221
+ sink.log("system", `Removed session rule: ${removed.tool} (${removed.pattern || "*"})`);
222
+ return;
223
+ }
224
+ const removed = removePermissionRuleByIndex(n - sessionLen, state.paths);
225
+ sink.log(
226
+ removed ? "system" : "error",
227
+ removed
228
+ ? `Removed ${removed.origin} rule: ${removed.tool} (${removed.pattern || "*"})`
229
+ : `Rule #${n} not found.`
230
+ );
231
+ return;
232
+ }
233
+
234
+ if (sub === "reset") {
235
+ state.sessionRules = [];
236
+ const scope = cleanParts[1] === "global" || cleanParts[1] === "project" ? cleanParts[1] : "all";
237
+ resetPermissionRules(scope, state.paths);
238
+ sink.log("system", `Reset permission rules (${scope}).`);
239
+ return;
240
+ }
241
+
242
+ sink.log(
243
+ "system",
244
+ "Usage: /permissions [list | allow <tool> [pattern] [--global] | deny <tool> [pattern] [--global] | rm <n> | reset]"
245
+ );
246
+ }
247
+
248
+ async function promptMoreModels(initialModels, providerName, sink) {
249
+ const models = [...initialModels.filter(Boolean)];
250
+ if (!sink.askPrompt) return models;
251
+
252
+ if (models.length === 0) {
253
+ const first = (await sink.askPrompt(`Model #1 name for '${providerName}' (required): `)).trim();
254
+ if (first) models.push(first);
255
+ }
256
+ while (models.length > 0) {
257
+ const latest = models[models.length - 1];
258
+ const ans = (
259
+ await sink.askPrompt(
260
+ `Added '${latest}' (total ${models.length}). Add more model? [y=add more / Enter or n=finish]: `
261
+ )
262
+ ).trim();
263
+ const low = ans.toLowerCase();
264
+ if (!ans || low === "n" || low === "no") break;
265
+ if (low === "y" || low === "yes") {
266
+ const nextModel = (await sink.askPrompt(`Model #${models.length + 1} name: `)).trim();
267
+ if (nextModel && !models.includes(nextModel)) models.push(nextModel);
268
+ continue;
269
+ }
270
+ // User typed a model name directly at the prompt
271
+ if (!models.includes(ans)) models.push(ans);
272
+ }
273
+ return models;
274
+ }
275
+
276
+ async function runAddModelWizard(state, targetProviderName, initialModels, sink, envFallback) {
277
+ const store = loadProviders(envFallback, state.paths);
278
+ let provName = targetProviderName;
279
+ if (!provName) {
280
+ const customProvs = Object.values(store.providers).filter((p) => !p.fromEnv);
281
+ if (!customProvs.length) {
282
+ sink.log("error", "No custom provider found. Use /api -> + Add Custom Provider first.");
283
+ return;
284
+ }
285
+ if (customProvs.length === 1) {
286
+ provName = customProvs[0].name;
287
+ } else if (sink.openChoicePicker) {
288
+ const items = customProvs.map((p) => ({
289
+ type: "provider",
290
+ id: p.name,
291
+ label: `${p.name === store.active ? "● " : " "}${p.name}`,
292
+ desc: `${(p.models || []).length} model(s) · ${p.baseUrl}`,
293
+ }));
294
+ provName = await sink.openChoicePicker("Add Models to Which Provider?", items, store.active);
295
+ if (!provName) return;
296
+ } else if (sink.askPrompt) {
297
+ provName = (await sink.askPrompt("Custom provider name: ")).trim();
298
+ }
299
+ }
300
+ if (!provName) return;
301
+
302
+ const toAdd = initialModels.length ? initialModels : await promptMoreModels([], provName, sink);
303
+ if (!toAdd.length) {
304
+ sink.log("system", "No models added.");
305
+ return;
306
+ }
307
+ const updated = addProviderModels(envFallback, provName, toAdd, state.paths);
308
+ if (state.provider?.name === updated.name) {
309
+ state.provider = updated;
310
+ if (!state.model && updated.defaultModel) {
311
+ state.model = updated.defaultModel;
312
+ state.session.model = updated.defaultModel;
313
+ }
314
+ }
315
+ sink.syncStatus();
316
+ sink.log("system", `Updated '${updated.name}' models (${updated.models.length}): ${updated.models.join(", ")}`);
317
+ }
318
+
319
+ async function handleApiCommand(state, arg, sink) {
320
+ const parts = arg.split(/\s+/).filter(Boolean);
321
+ const sub = parts[0] || "";
322
+ const envFallback = getEnvFallback();
323
+
324
+ if (!sub) {
325
+ const store = loadProviders(envFallback, state.paths);
326
+ if (sink.openChoicePicker) {
327
+ const customCount = Object.values(store.providers).filter((p) => !p.fromEnv).length;
328
+ const items = [
329
+ {
330
+ type: "new",
331
+ id: "__add_provider__",
332
+ label: "+ Add Custom Provider",
333
+ desc: "Add any OpenAI/Anthropic API + multiple individual models",
334
+ },
335
+ ...(customCount > 0
336
+ ? [
337
+ {
338
+ type: "new",
339
+ id: "__add_models__",
340
+ label: "+ Add More Model",
341
+ desc: "Add more model names to an existing custom provider",
342
+ },
343
+ ]
344
+ : []),
345
+ ...Object.values(store.providers).map((p) => {
346
+ const mCount = Array.isArray(p.models) ? p.models.length : p.defaultModel ? 1 : 0;
347
+ return {
348
+ type: "provider",
349
+ id: p.name,
350
+ label: `${p.name === store.active ? "● " : " "}${p.name}`,
351
+ desc: `[${p.type}] ${p.baseUrl}${mCount ? ` · ${mCount} model(s)` : ""}`,
352
+ };
353
+ }),
354
+ ];
355
+ const chosen = await sink.openChoicePicker("API Providers (/api)", items, store.active);
356
+ if (!chosen) return;
357
+ if (chosen === "__add_provider__") {
358
+ parts[0] = "add";
359
+ } else if (chosen === "__add_models__") {
360
+ await runAddModelWizard(
361
+ state,
362
+ !state.provider.fromEnv ? state.provider.name : "",
363
+ [],
364
+ sink,
365
+ envFallback
366
+ );
367
+ return;
368
+ } else {
369
+ parts[0] = "use";
370
+ parts[1] = chosen;
371
+ }
372
+ } else {
373
+ const lines = Object.values(store.providers).map((p) => {
374
+ const mark = p.name === store.active ? "* " : " ";
375
+ const keyInfo = p.apiKeyEnv ? `env:${p.apiKeyEnv}` : `key:${redactSecret(p.apiKey)}`;
376
+ const mods =
377
+ Array.isArray(p.models) && p.models.length ? p.models.join(", ") : p.defaultModel || "auto";
378
+ return `${mark}${p.name} [${p.type}] -> ${p.baseUrl} (${keyInfo}) · models: ${mods}`;
379
+ });
380
+ sink.log("system", `Configured API Providers:\n${lines.join("\n")}`);
381
+ return;
382
+ }
383
+ }
384
+
385
+ const action = parts[0] || "list";
386
+
387
+ if (action === "list") {
388
+ const store = loadProviders(envFallback, state.paths);
389
+ const lines = Object.values(store.providers).map((p) => {
390
+ const mark = p.name === store.active ? "* " : " ";
391
+ const keyInfo = p.apiKeyEnv ? `env:${p.apiKeyEnv}` : `key:${redactSecret(p.apiKey)}`;
392
+ const mods = Array.isArray(p.models) && p.models.length ? p.models.join(", ") : p.defaultModel || "auto";
393
+ return `${mark}${p.name} [${p.type}] -> ${p.baseUrl} (${keyInfo}) · models: ${mods}`;
394
+ });
395
+ sink.log("system", `Configured API Providers:\n${lines.join("\n")}`);
396
+ return;
397
+ }
398
+
399
+ if (action === "add-model") {
400
+ const provTarget = parts[1] || (!state.provider.fromEnv ? state.provider.name : "");
401
+ const cliModels = parts
402
+ .slice(2)
403
+ .join(" ")
404
+ .split(",")
405
+ .map((s) => s.trim())
406
+ .filter(Boolean);
407
+ await runAddModelWizard(state, provTarget, cliModels, sink, envFallback);
408
+ return;
409
+ }
410
+
411
+ if (action === "add") {
412
+ let [, name, type, baseUrl, apiKey, defaultModelArg] = parts;
413
+ let models = defaultModelArg
414
+ ? defaultModelArg
415
+ .split(",")
416
+ .map((s) => s.trim())
417
+ .filter(Boolean)
418
+ : [];
419
+ const interactiveAdd = !name || !type || !baseUrl || !apiKey;
420
+
421
+ if (interactiveAdd) {
422
+ if (!sink.askPrompt) {
423
+ sink.log("error", "Usage: /api add <name> <openai|anthropic> <base_url> <api_key> <model1,model2,...>");
424
+ return;
425
+ }
426
+ name = name || (await sink.askPrompt("Custom provider name (e.g. openrouter, groq, claude): ")).trim();
427
+ if (!name) {
428
+ sink.log("system", "Cancelled adding provider.");
429
+ return;
430
+ }
431
+ const rawType = type || (await sink.askPrompt("API Type [openai / anthropic] (default: openai): ")).trim();
432
+ type = rawType || "openai";
433
+ baseUrl = baseUrl || (await sink.askPrompt("Base URL (e.g. https://api.openai.com/v1): ")).trim();
434
+ apiKey = apiKey || (await (sink.askPassword || sink.askPrompt)("API Key (or ENV:VAR_NAME): ")).trim();
435
+ models = await promptMoreModels(models, name, sink);
436
+ }
437
+
438
+ if (!name || !baseUrl || !apiKey) {
439
+ sink.log("error", "Cancelled: name, base_url, and api_key are required.");
440
+ return;
441
+ }
442
+ if (!models.length && sink.askPrompt) {
443
+ models = await promptMoreModels([], name, sink);
444
+ }
445
+ if (!models.length) {
446
+ sink.log("error", "Cancelled: at least one model name is required.");
447
+ return;
448
+ }
449
+
450
+ const apiKeyEnv = apiKey.startsWith("ENV:") ? apiKey.slice(4).trim() : "";
451
+ const saved = upsertProvider(
452
+ envFallback,
453
+ {
454
+ name,
455
+ type: String(type || "openai").toLowerCase(),
456
+ baseUrl,
457
+ apiKey: apiKeyEnv ? "" : apiKey,
458
+ apiKeyEnv,
459
+ defaultModel: models[0] || "",
460
+ models,
461
+ },
462
+ state.paths
463
+ );
464
+ setActiveProvider(envFallback, saved.name, state.paths);
465
+ state.provider = saved;
466
+ persistAndApplySetting(state, "provider", saved.name, sink);
467
+ if (saved.defaultModel) {
468
+ state.model = saved.defaultModel;
469
+ state.session.model = saved.defaultModel;
470
+ updatePersistedSetting("model", saved.defaultModel, state.paths);
471
+ if (!state.noSession) saveSession(state.session, state.paths);
472
+ }
473
+ sink.syncStatus();
474
+ sink.log(
475
+ "system",
476
+ `Added & switched to '${saved.name}' (${saved.type}: ${saved.baseUrl}) with ${saved.models.length} model(s): ${saved.models.join(", ")}`
477
+ );
478
+ return;
479
+ }
480
+
481
+ if (action === "use") {
482
+ let targetName = parts[1] || "";
483
+ if (!targetName && sink.openChoicePicker) {
484
+ const store = loadProviders(envFallback, state.paths);
485
+ const items = Object.values(store.providers).map((p) => ({
486
+ type: "provider",
487
+ id: p.name,
488
+ label: `${p.name === store.active ? "● " : " "}${p.name}`,
489
+ desc: `[${p.type}] ${p.baseUrl}`,
490
+ }));
491
+ targetName = await sink.openChoicePicker("Switch API Provider", items, store.active);
492
+ if (!targetName) return;
493
+ }
494
+ if (!targetName) {
495
+ sink.log("error", "Usage: /api use <provider-name>");
496
+ return;
497
+ }
498
+ const active = setActiveProvider(envFallback, targetName, state.paths);
499
+ state.provider = active;
500
+ updatePersistedSetting("provider", active.name, state.paths);
501
+ if (active.defaultModel) {
502
+ state.model = active.defaultModel;
503
+ state.session.model = active.defaultModel;
504
+ updatePersistedSetting("model", active.defaultModel, state.paths);
505
+ } else {
506
+ state.model = resolveEffectiveModel({
507
+ cliModel: state.cliModel,
508
+ sessionModel: state.session.model,
509
+ persistedModel: state.persistedSettings.model,
510
+ providerDefaultModel: active.defaultModel,
511
+ });
512
+ }
513
+ if (!state.noSession) saveSession(state.session, state.paths);
514
+ sink.syncStatus();
515
+ sink.log(
516
+ "system",
517
+ `Switched active API to '${active.name}' (${active.type}: ${active.baseUrl}, model: ${state.model || "auto"})`
518
+ );
519
+ return;
520
+ }
521
+
522
+ if (action === "rm" && parts[1]) {
523
+ const removed = removeProvider(envFallback, parts[1], state.paths);
524
+ const store = loadProviders(envFallback, state.paths);
525
+ state.provider = store.providers[store.active];
526
+ sink.syncStatus();
527
+ sink.log(
528
+ "system",
529
+ removed
530
+ ? `Removed provider '${parts[1]}'. Active: '${state.provider.name}'`
531
+ : `Provider '${parts[1]}' not found.`
532
+ );
533
+ return;
534
+ }
535
+
536
+ sink.log(
537
+ "system",
538
+ "Usage: /api [list | add <name> <openai|anthropic> <url> <key> [model] | use <name> | rm <name>]"
539
+ );
540
+ }
541
+
542
+ function replaySessionHistory(sink, state) {
543
+ if (!sink.isTui) return;
544
+ if (state.session.summaryMemory) {
545
+ sink.log("meta", `Memory Summary: ${state.session.summaryMemory.replace(/\s+/g, " ").slice(0, 140)}`);
546
+ }
547
+ for (const m of state.session.history.slice(-20)) {
548
+ if (m.role === "user") sink.log("user", m.content || "");
549
+ else if (m.role === "assistant" && m.content) sink.log("assistant", m.content);
550
+ else if (m.role === "assistant" && Array.isArray(m.tool_calls) && m.tool_calls.length) {
551
+ for (const tc of m.tool_calls) {
552
+ sink.log("tool", `⚙ ${tc.function?.name || "tool"}(${summarizeArgsShort(tc.function?.arguments)})`);
553
+ }
554
+ }
555
+ }
556
+ }
557
+
558
+ async function switchToSession(state, targetId, isNew, sink, waitForMemorySync) {
559
+ state.activePrompt = "";
560
+ if (Array.isArray(state.queue)) state.queue.length = 0;
561
+ state.activeAbort?.abort();
562
+ state.memoryAbort?.abort();
563
+ await waitForMemorySync?.(state);
564
+ if (!state.noSession) saveSession(state.session, state.paths);
565
+ const cleanId = safeId(targetId || (isNew ? `session-${Date.now()}` : "default"));
566
+ state.session = loadSession(cleanId, state.model, state.paths);
567
+ if (isNew) {
568
+ state.session.summaryMemory = "";
569
+ state.session.pinnedMemory = [];
570
+ state.session.todos = [];
571
+ state.session.history = [];
572
+ state.session.agentMode = null;
573
+ state.sudoPasswords.delete(state.session.id);
574
+ if (!state.noSession) saveSession(state.session, state.paths);
575
+ }
576
+ if (!state.runtimeOverrides?.cliMode && !state.runtimeOverrides?.cliAuto) {
577
+ state.settings.agentMode = state.session.agentMode || state.persistedSettings.agentMode;
578
+ }
579
+ state.model = resolveEffectiveModel({
580
+ cliModel: state.cliModel,
581
+ sessionModel: state.session.model,
582
+ persistedModel: state.persistedSettings.model,
583
+ providerDefaultModel: state.provider.defaultModel,
584
+ });
585
+ sink.clear();
586
+ sink.syncStatus();
587
+ replaySessionHistory(sink, state);
588
+ if (!sink.isTui) {
589
+ sink.log(
590
+ "system",
591
+ `Active session: ${state.session.id} (${state.session.history.length} msgs, summary: ${state.session.summaryMemory ? "yes" : "no"})`
592
+ );
593
+ }
594
+ }
595
+
596
+ async function openSessionPicker(state, tui, sink, waitForMemorySync) {
597
+ while (true) {
598
+ const list = listSessions(state.paths);
599
+ const groups = groupSessionsByDate(list);
600
+ const items = [{ type: "new", id: "", label: "+ New Session", desc: "Start a fresh isolated session" }];
601
+ for (const g of groups) {
602
+ items.push({
603
+ type: "header",
604
+ id: `__date_${g.dateKey}`,
605
+ label: g.dateLabel,
606
+ desc: `${g.sessions.length} session(s)`,
607
+ });
608
+ for (const s of g.sessions) {
609
+ const activeMark = s.id === state.session.id ? "● " : " ";
610
+ const prev = s.preview ? ` · "${s.preview}"` : "";
611
+ items.push({
612
+ type: "session",
613
+ id: s.id,
614
+ label: `${activeMark}${s.id}`,
615
+ desc: `${s.messages} msgs${s.hasSummary ? " · mem" : ""}${prev}`,
616
+ });
617
+ }
618
+ }
619
+ const res = await tui.openPicker("Sessions (Ctrl+S)", items);
620
+ if (!res) return;
621
+ if (res.action === "delete" && res.item?.type === "session") {
622
+ if (res.item.id === state.session.id) {
623
+ sink.log("error", "Cannot delete active session. Switch first.");
624
+ return;
625
+ }
626
+ state.sudoPasswords.delete(res.item.id);
627
+ deleteSession(res.item.id, state.paths);
628
+ continue;
629
+ }
630
+ if (res.action === "select") {
631
+ if (res.item.type === "new") {
632
+ const rawName = (await tui.askModal("New session name (blank = auto): ", false)).trim();
633
+ const id = rawName || `session-${new Date().toISOString().slice(11, 19).replace(/:/g, "")}`;
634
+ await switchToSession(state, id, true, sink, waitForMemorySync);
635
+ return;
636
+ }
637
+ await switchToSession(state, res.item.id, false, sink, waitForMemorySync);
638
+ return;
639
+ }
640
+ return;
641
+ }
642
+ }
643
+
644
+ async function handleMemoryCommand(state, arg, sink) {
645
+ const parts = arg.split(/\s+/).filter(Boolean);
646
+ const sub = parts[0] || "show";
647
+
648
+ if (sub === "global") {
649
+ const gsub = parts[1] || "show";
650
+ const gtext = parts.slice(2).join(" ");
651
+ const items = loadGlobalMemory(state.paths);
652
+ if (gsub === "add" && gtext) {
653
+ addGlobalMemory(gtext, "user", state.paths);
654
+ sink.log("system", "Added to Default Global Memory.");
655
+ } else if (gsub === "rm" && parts[2]) {
656
+ const idx = Number(parts[2]) - 1;
657
+ if (!Number.isInteger(idx) || idx < 0 || idx >= items.length) {
658
+ sink.log("error", `Invalid global memory index '${parts[2]}'.`);
659
+ return;
660
+ }
661
+ const next = items.filter((_, i) => i !== idx);
662
+ saveGlobalMemory(next, state.paths);
663
+ sink.log("system", `Global memory now has ${next.length} items.`);
664
+ } else if (gsub === "clear") {
665
+ saveGlobalMemory([], state.paths);
666
+ sink.log("system", "Global memory cleared.");
667
+ } else {
668
+ sink.log(
669
+ "system",
670
+ items.length ? items.map((x, i) => `${i + 1}. ${x}`).join("\n") : "(empty global memory)"
671
+ );
672
+ }
673
+ return;
674
+ }
675
+
676
+ if (sub === "add" && parts.length > 1) {
677
+ state.session.pinnedMemory.push(parts.slice(1).join(" "));
678
+ if (!state.noSession) saveSession(state.session, state.paths);
679
+ sink.log("system", `Added to session '${state.session.id}' local memory.`);
680
+ return;
681
+ }
682
+ if (sub === "clear") {
683
+ state.session.summaryMemory = "";
684
+ state.session.pinnedMemory = [];
685
+ if (!state.noSession) saveSession(state.session, state.paths);
686
+ sink.log("system", `Session '${state.session.id}' memory cleared.`);
687
+ return;
688
+ }
689
+
690
+ const gItems = loadGlobalMemory(state.paths);
691
+ sink.log(
692
+ "system",
693
+ `Session '${state.session.id}' Summary Memory:\n${state.session.summaryMemory || "(none yet)"}\n\n` +
694
+ `Session Local Pinned Memory:\n${state.session.pinnedMemory.length ? state.session.pinnedMemory.map((x) => `- ${x}`).join("\n") : "(none)"}\n\n` +
695
+ `Global Default Memory (ALL sessions):\n${gItems.length ? gItems.map((x, i) => `${i + 1}. ${x}`).join("\n") : "(none)"}`
696
+ );
697
+ }
698
+
699
+ async function runModelProviderBrowser(state, sink) {
700
+ const envFallback = getEnvFallback();
701
+ while (true) {
702
+ const store = loadProviders(envFallback, state.paths);
703
+ const customProvs = Object.values(store.providers).filter((p) => !p.fromEnv);
704
+
705
+ const provItems = [
706
+ ...Object.values(store.providers).map((p) => {
707
+ const mCount = Array.isArray(p.models) ? p.models.length : p.defaultModel ? 1 : 0;
708
+ return {
709
+ type: "provider",
710
+ id: p.name,
711
+ label: `${p.name === store.active ? "● " : " "}${p.name}`,
712
+ desc: `[${p.type}] ${p.baseUrl}${mCount ? ` · ${mCount} saved model(s)` : ""}`,
713
+ };
714
+ }),
715
+ {
716
+ type: "new",
717
+ id: "__add_provider__",
718
+ label: "+ Add Custom Provider",
719
+ desc: "Add new OpenAI/Anthropic API + individual models",
720
+ },
721
+ ...(customProvs.length > 0
722
+ ? [
723
+ {
724
+ type: "action",
725
+ id: "__remove_provider__",
726
+ label: "✖ Remove Provider",
727
+ desc: "Delete a saved custom API provider",
728
+ },
729
+ ]
730
+ : []),
731
+ ];
732
+
733
+ const chosenProvId = await sink.openChoicePicker("Select Provider -> Models", provItems, store.active);
734
+ if (!chosenProvId) return;
735
+
736
+ if (chosenProvId === "__add_provider__") {
737
+ await handleApiCommand(state, "add", sink);
738
+ continue;
739
+ }
740
+
741
+ if (chosenProvId === "__remove_provider__") {
742
+ const rmItems = customProvs.map((p) => ({
743
+ type: "provider",
744
+ id: p.name,
745
+ label: ` ${p.name}`,
746
+ desc: `[${p.type}] ${p.baseUrl}`,
747
+ }));
748
+ const rmTarget = await sink.openChoicePicker("Remove Custom Provider", rmItems, "");
749
+ if (rmTarget) {
750
+ removeProvider(envFallback, rmTarget, state.paths);
751
+ const afterStore = loadProviders(envFallback, state.paths);
752
+ state.provider = afterStore.providers[afterStore.active];
753
+ state.model = resolveEffectiveModel({
754
+ cliModel: state.cliModel,
755
+ sessionModel: state.session.model,
756
+ persistedModel: state.persistedSettings.model,
757
+ providerDefaultModel: state.provider.defaultModel,
758
+ });
759
+ sink.syncStatus();
760
+ sink.log("system", `Removed provider '${rmTarget}'. Active: '${state.provider.name}'`);
761
+ }
762
+ continue;
763
+ }
764
+
765
+ const selectedProv = store.providers[chosenProvId];
766
+ if (!selectedProv) continue;
767
+
768
+ // Level 2: Show models for selected provider (+ Add More Model at bottom)
769
+ while (true) {
770
+ const freshStore = loadProviders(envFallback, state.paths);
771
+ const prov = freshStore.providers[chosenProvId] || selectedProv;
772
+ let remoteIds = [];
773
+ try {
774
+ remoteIds = await listProviderModels(prov);
775
+ } catch {}
776
+
777
+ const merged = Array.from(
778
+ new Set([...(Array.isArray(prov.models) ? prov.models : []), ...remoteIds])
779
+ ).filter(Boolean);
780
+
781
+ const modelItems = [
782
+ ...merged.map((id) => {
783
+ const isCurrent = prov.name === state.provider.name && id === state.model;
784
+ return {
785
+ type: "model",
786
+ id,
787
+ label: `${isCurrent ? "● " : " "}${id}`,
788
+ desc: isCurrent ? "active" : "",
789
+ };
790
+ }),
791
+ ...(!prov.fromEnv
792
+ ? [
793
+ {
794
+ type: "new",
795
+ id: "__add_more_model__",
796
+ label: "+ Add More Model",
797
+ desc: `Add model(s) to '${prov.name}'`,
798
+ },
799
+ ]
800
+ : []),
801
+ {
802
+ type: "action",
803
+ id: "__back__",
804
+ label: "← Back to Providers",
805
+ desc: "Choose another provider",
806
+ },
807
+ ];
808
+
809
+ const activeHint = prov.name === state.provider.name ? state.model : prov.defaultModel || "";
810
+ const chosenModel = await sink.openChoicePicker(`Models (${prov.name})`, modelItems, activeHint);
811
+ if (!chosenModel) return;
812
+ if (chosenModel === "__back__") break;
813
+ if (chosenModel === "__add_more_model__") {
814
+ await runAddModelWizard(state, prov.name, [], sink, envFallback);
815
+ continue;
816
+ }
817
+
818
+ // Apply chosen provider + model cleanly
819
+ if (prov.name !== state.provider.name) {
820
+ const active = setActiveProvider(envFallback, prov.name, state.paths);
821
+ state.provider = active;
822
+ updatePersistedSetting("provider", active.name, state.paths);
823
+ }
824
+ state.model = chosenModel;
825
+ state.session.model = chosenModel;
826
+ updatePersistedSetting("model", chosenModel, state.paths);
827
+ state.persistedSettings.model = chosenModel;
828
+ if (!state.noSession) saveSession(state.session, state.paths);
829
+ sink.syncStatus();
830
+ sink.log("system", `Switched to ${state.provider.name} · model: ${state.model}`);
831
+ return;
832
+ }
833
+ }
834
+ }
835
+
836
+ async function handleSlash(state, input, sink, deps) {
837
+ const [cmd, ...rest] = input.split(/\s+/);
838
+ const arg = rest.join(" ").trim();
839
+ switch (cmd) {
840
+ case "/help":
841
+ sink.log("system", getHelpText());
842
+ return;
843
+ case "/mode":
844
+ await handleModeCommand(state, arg, sink);
845
+ return;
846
+ case "/api":
847
+ await handleApiCommand(state, arg, sink);
848
+ return;
849
+ case "/settings":
850
+ if (sink.openSettings) sink.openSettings();
851
+ else sink.log("system", JSON.stringify(state.persistedSettings, null, 2));
852
+ return;
853
+ case "/set":
854
+ handleSetCommand(state, arg, sink);
855
+ return;
856
+ case "/session":
857
+ case "/sessions": {
858
+ const parts = arg.split(/\s+/).filter(Boolean);
859
+ const sub = parts[0] || "";
860
+ const name = parts.slice(1).join(" ").trim();
861
+ if (!sub && sink.openSessions) {
862
+ await sink.openSessions();
863
+ return;
864
+ }
865
+ if (!sub || sub === "list") {
866
+ const list = listSessions(state.paths);
867
+ if (!list.length) {
868
+ sink.log("system", "No saved sessions.");
869
+ return;
870
+ }
871
+ const groups = groupSessionsByDate(list);
872
+ const lines = [];
873
+ for (const g of groups) {
874
+ lines.push(`${g.dateLabel} (${g.sessions.length})`);
875
+ for (const s of g.sessions) {
876
+ lines.push(
877
+ ` ${s.id === state.session.id ? "* " : " "}${s.id} (${s.messages} msgs${s.hasSummary ? ", mem" : ""})${s.preview ? ` - "${s.preview}"` : ""}`
878
+ );
879
+ }
880
+ }
881
+ sink.log("system", lines.join("\n"));
882
+ return;
883
+ }
884
+ if (sub === "new" || sub === "switch" || sub === "load") {
885
+ const isNew = sub === "new";
886
+ const targetId = isNew ? name || `session-${Date.now()}` : name || "default";
887
+ await switchToSession(state, targetId, isNew, sink, deps.waitForMemorySync);
888
+ return;
889
+ }
890
+ if (sub === "delete" && name) {
891
+ const clean = safeId(name);
892
+ if (clean === state.session.id) {
893
+ sink.log("error", "Cannot delete currently active session. Switch first.");
894
+ return;
895
+ }
896
+ state.sudoPasswords.delete(clean);
897
+ sink.log(
898
+ "system",
899
+ deleteSession(clean, state.paths) ? `Deleted session '${clean}'.` : `Session '${clean}' not found.`
900
+ );
901
+ return;
902
+ }
903
+ sink.log("system", "Usage: /session [list|new <name>|switch <name>|delete <name>]");
904
+ return;
905
+ }
906
+ case "/new": {
907
+ const stamp = new Date().toISOString().slice(0, 19).replace(/[:T]/g, "-");
908
+ const nextId = arg || `session-${stamp}-${Math.random().toString(36).slice(2, 5)}`;
909
+ await switchToSession(state, nextId, true, sink, deps.waitForMemorySync);
910
+ return;
911
+ }
912
+ case "/rename": {
913
+ if (!arg) {
914
+ sink.log("error", "Usage: /rename <session-name>");
915
+ return;
916
+ }
917
+ const nextId = renameSession(state.session, arg, state.paths);
918
+ state.noSession = false;
919
+ sink.syncStatus();
920
+ sink.log("system", `Session renamed & saved as '${nextId}'.`);
921
+ return;
922
+ }
923
+ case "/fork": {
924
+ const stamp = new Date().toISOString().slice(11, 19).replace(/:/g, "");
925
+ const forkId = arg || `${state.session.id}-fork-${stamp}`;
926
+ const forked = forkSession(state.session, forkId, state.paths);
927
+ state.session = forked;
928
+ state.noSession = false;
929
+ sink.syncStatus();
930
+ sink.log("system", `Forked into new session '${forked.id}' (${forked.history.length} msgs).`);
931
+ return;
932
+ }
933
+ case "/export": {
934
+ const parts = arg.split(/\s+/).filter(Boolean);
935
+ let fmt = "md";
936
+ let outArg = "";
937
+ if (parts[0] === "json" || parts[0] === "md") {
938
+ fmt = parts[0];
939
+ outArg = parts[1] || "";
940
+ } else if (parts[0]) {
941
+ outArg = parts[0];
942
+ if (outArg.endsWith(".json")) fmt = "json";
943
+ }
944
+ const root = state.workspaceRoot || process.cwd();
945
+ const defaultName = `${safeId(state.session.id)}.${fmt}`;
946
+ const targetPath = path.resolve(root, outArg || defaultName);
947
+ let content = "";
948
+ if (fmt === "json") {
949
+ content = JSON.stringify(state.session, null, 2);
950
+ } else {
951
+ const lines = [
952
+ `# Kovence Session: ${state.session.id}`,
953
+ `- Model: ${state.model} · Mode: ${state.settings?.agentMode || "default"}`,
954
+ state.session.title ? `- Title: ${state.session.title}` : "",
955
+ "",
956
+ ...state.session.history.map((m) => {
957
+ const hdr = `## ${String(m.role || "unknown").toUpperCase()}`;
958
+ const body = m.content
959
+ ? String(m.content)
960
+ : `[tool_calls: ${JSON.stringify(m.tool_calls || [])}]`;
961
+ return `${hdr}\n\n${body}\n`;
962
+ }),
963
+ ].filter((l) => l !== "");
964
+ content = lines.join("\n");
965
+ }
966
+ fs.mkdirSync(path.dirname(targetPath), { recursive: true });
967
+ fs.writeFileSync(targetPath, content, "utf8");
968
+ sink.log("system", `Exported session (${fmt}) -> ${path.relative(root, targetPath) || targetPath}`);
969
+ return;
970
+ }
971
+ case "/edit-last": {
972
+ const hist = state.session.history || [];
973
+ const lastUserIdx = hist.findLastIndex((m) => m.role === "user");
974
+ if (lastUserIdx < 0) {
975
+ sink.log("system", "No user turn found to edit.");
976
+ return;
977
+ }
978
+ const rawContent = String(hist[lastUserIdx].content || "");
979
+ const promptOnly = rawContent.split(/\n\n--- File: /)[0];
980
+ state.session.history = hist.slice(0, lastUserIdx);
981
+ if (!state.noSession) saveSession(state.session, state.paths);
982
+ sink.syncStatus();
983
+ if (sink.setInput) {
984
+ sink.setInput(promptOnly);
985
+ sink.log("system", "Removed last turn and restored prompt to input box for editing.");
986
+ } else {
987
+ sink.log("system", `Removed last turn. Prompt was:\n${promptOnly}`);
988
+ }
989
+ return;
990
+ }
991
+ case "/cost": {
992
+ const pTok = state.session?.stats?.promptTokens || 0;
993
+ const cTok = state.session?.stats?.completionTokens || 0;
994
+ const est = estimateTokenCostUsd(state.model, pTok, cTok);
995
+ const costLine = est.knownPricing
996
+ ? `Estimated Cost: $${est.totalUsd.toFixed(6)} (in: $${est.inCost.toFixed(6)}, out: $${est.outCost.toFixed(6)})`
997
+ : `Estimated Cost: unknown pricing for '${state.model}' (tokens: ${pTok} in, ${cTok} out)`;
998
+ sink.log(
999
+ "system",
1000
+ `${costLine}\nRequests: ${state.session?.stats?.requests || 0} · Tokens: ${pTok} in, ${cTok} out`
1001
+ );
1002
+ return;
1003
+ }
1004
+ case "/save": {
1005
+ if (arg) {
1006
+ const nextId = renameSession(state.session, arg, state.paths);
1007
+ state.noSession = false;
1008
+ sink.syncStatus();
1009
+ sink.log("system", `Session renamed & saved as '${nextId}'.`);
1010
+ } else if (state.noSession) {
1011
+ sink.log("system", "Running in --no-session mode. Use /save <name> to save this session.");
1012
+ } else {
1013
+ saveSession(state.session, state.paths);
1014
+ sink.syncStatus();
1015
+ sink.log("system", `Saved session: ${state.session.id}`);
1016
+ }
1017
+ return;
1018
+ }
1019
+ case "/undo": {
1020
+ const res = undoLastCheckpoint(state.session.id, state.paths, state.workspaceRoot);
1021
+ sink.log(res.ok ? "system" : "meta", res.message);
1022
+ return;
1023
+ }
1024
+ case "/init": {
1025
+ const fs = require("node:fs");
1026
+ const path = require("node:path");
1027
+ const root = state.workspaceRoot || process.cwd();
1028
+ const target = path.join(root, "KOVENCE.md");
1029
+ if (fs.existsSync(target) && sink.confirm) {
1030
+ const ans = (await sink.confirm("KOVENCE.md already exists. Overwrite? [y/n]: ")).trim().toLowerCase();
1031
+ if (ans !== "y" && ans !== "yes") {
1032
+ sink.log("system", "Skipped /init (kept existing KOVENCE.md).");
1033
+ return;
1034
+ }
1035
+ }
1036
+ const doc = generateProjectInitDoc(root);
1037
+ fs.writeFileSync(target, doc, "utf8");
1038
+ sink.log("system", `Generated ${path.relative(root, target) || target} (${doc.length} chars).`);
1039
+ return;
1040
+ }
1041
+ case "/load":
1042
+ await switchToSession(state, arg || "default", false, sink, deps.waitForMemorySync);
1043
+ return;
1044
+ case "/retry":
1045
+ if (!state.lastFailedPrompt) {
1046
+ sink.log("system", "Nothing to retry.");
1047
+ return;
1048
+ }
1049
+ sink.log("user", state.lastFailedPrompt);
1050
+ await deps.runAgentTurn(state, state.lastFailedPrompt, sink, { isRetry: true });
1051
+ return;
1052
+ case "/memory":
1053
+ await handleMemoryCommand(state, arg, sink);
1054
+ return;
1055
+ case "/remember": {
1056
+ if (!arg) {
1057
+ sink.log("system", "Usage: /remember <fact or preference>");
1058
+ return;
1059
+ }
1060
+ const scope = /\b(this session|local)\b/i.test(arg) ? "session" : "global";
1061
+ const ans = sink.confirm
1062
+ ? (await sink.confirm(`Save to ${scope} memory: "${arg}"? [y/n]: `)).trim().toLowerCase()
1063
+ : "y";
1064
+ if (ans !== "y" && ans !== "yes") {
1065
+ sink.log("system", "Memory save cancelled.");
1066
+ return;
1067
+ }
1068
+ if (scope === "session") {
1069
+ state.session.pinnedMemory.push(arg);
1070
+ if (!state.noSession) saveSession(state.session, state.paths);
1071
+ sink.log("system", `Pinned to session '${state.session.id}' memory.`);
1072
+ } else {
1073
+ addGlobalMemory(arg, "user", state.paths);
1074
+ sink.log("system", "Saved to Global Shared Memory.");
1075
+ }
1076
+ return;
1077
+ }
1078
+ case "/history": {
1079
+ if (arg && (!/^\d+$/.test(arg) || Number(arg) < 1)) {
1080
+ sink.log("error", "Usage: /history [positive-number]");
1081
+ return;
1082
+ }
1083
+ const limit = arg ? Number.parseInt(arg, 10) : 10;
1084
+ const slice = state.session.history.slice(-limit);
1085
+ if (!slice.length) {
1086
+ sink.log("system", "(empty chat history)");
1087
+ return;
1088
+ }
1089
+ sink.log(
1090
+ "system",
1091
+ slice
1092
+ .map(
1093
+ (m) =>
1094
+ `${m.role}: ${
1095
+ m.content
1096
+ ? String(m.content).slice(0, 140).replace(/\n/g, " ")
1097
+ : `[tool_calls: ${m.tool_calls?.length || 0}]`
1098
+ }`
1099
+ )
1100
+ .join("\n")
1101
+ );
1102
+ return;
1103
+ }
1104
+ case "/todos":
1105
+ sink.log(
1106
+ "system",
1107
+ state.session.todos.length
1108
+ ? state.session.todos.map((t, i) => `${i + 1}. [${t.status}] ${t.task}`).join("\n")
1109
+ : "(no todos in current session)"
1110
+ );
1111
+ return;
1112
+ case "/tasks": {
1113
+ const mgr = state.bgTasks;
1114
+ if (!mgr) {
1115
+ sink.log("system", "Background task manager unavailable.");
1116
+ return;
1117
+ }
1118
+ const parts = arg.split(/\s+/).filter(Boolean);
1119
+ const sub = (parts[0] || "").toLowerCase();
1120
+ if (sub === "kill" && parts[1]) {
1121
+ const ok = mgr.killTask(parts[1]);
1122
+ sink.log(
1123
+ ok ? "system" : "error",
1124
+ ok ? `Killed background task ${parts[1]}.` : `Task not running or not found: ${parts[1]}`
1125
+ );
1126
+ return;
1127
+ }
1128
+ if (sub === "log" && parts[1]) {
1129
+ const t = mgr.getTask(parts[1]);
1130
+ if (!t) {
1131
+ sink.log("error", `Task not found: ${parts[1]}`);
1132
+ return;
1133
+ }
1134
+ const tail = t.logs.slice(-40).join("").trim() || "(no output yet)";
1135
+ sink.log("system", `Task ${t.id} [${t.status}] (${t.command}):\n${tail}`);
1136
+ return;
1137
+ }
1138
+ const tasks = mgr.listTasks();
1139
+ if (!tasks.length) {
1140
+ sink.log("system", "No background tasks yet. Use run_command with background=true.");
1141
+ return;
1142
+ }
1143
+ if (!arg && sink.openChoicePicker) {
1144
+ const items = tasks.map((t) => ({
1145
+ type: "task",
1146
+ id: t.id,
1147
+ label: `${t.id} [${t.status}] pid=${t.pid ?? "?"}`,
1148
+ desc: t.command.slice(0, 60),
1149
+ }));
1150
+ const picked = await sink.openChoicePicker("Background Tasks (Enter to view log)", items, "");
1151
+ if (!picked) return;
1152
+ const t = mgr.getTask(picked);
1153
+ if (!t) return;
1154
+ const tail = t.logs.slice(-40).join("").trim() || "(no output yet)";
1155
+ sink.log("system", `Task ${t.id} [${t.status}] (${t.command}):\n${tail}`);
1156
+ if (t.status === "running" && sink.confirm) {
1157
+ const ans = (await sink.confirm(`Kill task ${t.id}? [y/N]: `)).trim().toLowerCase();
1158
+ if (ans === "y" || ans === "yes") {
1159
+ mgr.killTask(t.id);
1160
+ sink.log("system", `Killed task ${t.id}.`);
1161
+ }
1162
+ }
1163
+ return;
1164
+ }
1165
+ sink.log(
1166
+ "system",
1167
+ tasks.map((t) => ` ${t.id} · [${t.status}] pid=${t.pid ?? "?"} · ${t.command}`).join("\n") +
1168
+ "\nTip: /tasks log <id> · /tasks kill <id>"
1169
+ );
1170
+ return;
1171
+ }
1172
+ case "/models":
1173
+ case "/model": {
1174
+ if (!arg) {
1175
+ if (sink.openChoicePicker) {
1176
+ await runModelProviderBrowser(state, sink);
1177
+ return;
1178
+ }
1179
+ sink.log("system", `Provider: ${state.provider.name} · Current model: ${state.model}`);
1180
+ return;
1181
+ }
1182
+ state.model = arg;
1183
+ state.session.model = arg;
1184
+ updatePersistedSetting("model", arg, state.paths);
1185
+ state.persistedSettings.model = arg;
1186
+ if (!state.noSession) saveSession(state.session, state.paths);
1187
+ sink.syncStatus();
1188
+ sink.log("system", `Model switched & saved: ${state.model}`);
1189
+ return;
1190
+ }
1191
+ case "/tools": {
1192
+ const next = arg
1193
+ ? arg.toLowerCase() === "on" || arg.toLowerCase() === "true"
1194
+ : !state.settings.toolsEnabled;
1195
+ persistAndApplySetting(state, "toolsEnabled", next, sink);
1196
+ sink.log("system", `Tools: ${state.settings.toolsEnabled ? "ON" : "OFF"}`);
1197
+ return;
1198
+ }
1199
+ case "/auto": {
1200
+ const wantAuto = arg
1201
+ ? arg.toLowerCase() === "on" || arg.toLowerCase() === "true"
1202
+ : state.settings.agentMode !== "auto";
1203
+ await handleModeCommand(state, wantAuto ? "auto" : "default", sink);
1204
+ return;
1205
+ }
1206
+ case "/system":
1207
+ if (!arg) sink.log("system", `System prompt:\n${state.settings.systemPrompt}`);
1208
+ else {
1209
+ persistAndApplySetting(state, "systemPrompt", arg, sink);
1210
+ sink.log("system", "System prompt updated & saved.");
1211
+ }
1212
+ return;
1213
+ case "/compact":
1214
+ await deps.compactSession(state, sink);
1215
+ return;
1216
+ case "/stats": {
1217
+ const est = estimateMessagesTokens(formatContextMessages(state));
1218
+ const win = state.settings.contextWindow || 128000;
1219
+ const pct = ((est / win) * 100).toFixed(1);
1220
+ const avgSec = state.session.stats.requests
1221
+ ? (state.session.stats.totalMs / state.session.stats.requests / 1000).toFixed(2)
1222
+ : "0.00";
1223
+ const ttft = state.session.stats.lastTtftMs ?? 0;
1224
+ const tps = state.session.stats.lastTokPerSec ?? 0;
1225
+ sink.log(
1226
+ "system",
1227
+ `Session: ${state.session.id} (${state.session.history.length} messages) · Mode: ${state.settings.agentMode}\n` +
1228
+ `Provider: ${state.provider.name} [${state.provider.type}] · Model: ${state.model}\n` +
1229
+ `Context Size: ~${est} / ${win} tokens (${pct}%)\n` +
1230
+ `Average Response Time: ${avgSec}s · Last Time to First Token: ${ttft} ms · Last Generation Speed: ${tps} tok/s\n` +
1231
+ `Total Tokens Used: ${state.session.stats.promptTokens} input, ${state.session.stats.completionTokens} output`
1232
+ );
1233
+ return;
1234
+ }
1235
+ case "/copy":
1236
+ if (sink.copyLast) sink.copyLast();
1237
+ else sink.log("system", "Copy shortcut is available in TUI mode.");
1238
+ return;
1239
+ case "/select":
1240
+ if (sink.toggleSelect) sink.toggleSelect();
1241
+ else sink.log("system", "Native terminal selection is already active in plain mode.");
1242
+ return;
1243
+ case "/clear":
1244
+ state.activePrompt = "";
1245
+ if (Array.isArray(state.queue)) state.queue.length = 0;
1246
+ state.activeAbort?.abort();
1247
+ state.memoryAbort?.abort();
1248
+ await deps.waitForMemorySync?.(state);
1249
+ state.session.history = [];
1250
+ state.session.summaryMemory = "";
1251
+ state.session.pinnedMemory = [];
1252
+ state.session.todos = [];
1253
+ state.lastFailedPrompt = "";
1254
+ state.sudoPasswords.delete(state.session.id);
1255
+ if (!state.noSession) saveSession(state.session, state.paths);
1256
+ sink.clear();
1257
+ sink.syncStatus();
1258
+ sink.log("system", `Session '${state.session.id}' history & session memory cleared.`);
1259
+ return;
1260
+ case "/exit":
1261
+ case "/quit":
1262
+ if (sink.exit) sink.exit();
1263
+ else process.exit(0);
1264
+ return;
1265
+ default:
1266
+ sink.log("error", `Unknown command: ${cmd}. Type /help`);
1267
+ }
1268
+ }
1269
+
1270
+ module.exports = {
1271
+ getEnvFallback,
1272
+ summarizeArgsShort,
1273
+ getContextLabel,
1274
+ persistAndApplySetting,
1275
+ handleSlash,
1276
+ switchToSession,
1277
+ openSessionPicker,
1278
+ replaySessionHistory,
1279
+ TOOL_DEFINITIONS,
1280
+ };