kovence-cli 1.0.3 → 1.3.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.
@@ -31,11 +31,28 @@ const {
31
31
  } = require("../../store");
32
32
  const { listProviderModels } = require("../../providers");
33
33
  const { TOOL_DEFINITIONS } = require("../../tools");
34
- const { estimateMessagesTokens } = require("../agent/history");
34
+ const { estimateMessagesTokens, resolveContextBudget } = require("../agent/history");
35
35
  const { estimateTokenCostUsd } = require("../config/model_registry");
36
36
  const { generateProjectInitDoc } = require("../agent/project_context");
37
37
  const { undoLastCheckpoint } = require("../tools/checkpoints");
38
+ const { getBrowserStatus, ensurePlaywrightInstalled, closeBrowserSession } = require("../tools/browser");
38
39
  const { getHelpText } = require("../cli/args");
40
+ const { loadAllSkills, saveSkillFromMarkdown, removeSkill, slugifySkillName } = require("../config/skills");
41
+
42
+ const REASONING_LEVELS = [
43
+ { id: "off", desc: "Fastest — no extended reasoning/thinking budget" },
44
+ { id: "low", desc: "Light reasoning effort" },
45
+ { id: "medium", desc: "Balanced reasoning effort" },
46
+ { id: "high", desc: "Deep reasoning / high thinking budget" },
47
+ ];
48
+
49
+ function makeAutoSessionId() {
50
+ const d = new Date();
51
+ const pad = (n) => String(n).padStart(2, "0");
52
+ const stamp = `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
53
+ const rand = Math.random().toString(36).slice(2, 5);
54
+ return `session-${stamp}-${rand}`;
55
+ }
39
56
 
40
57
  function getEnvFallback() {
41
58
  return {
@@ -61,12 +78,15 @@ function formatContextMessages(state) {
61
78
  if (g.length) {
62
79
  msgs.push({ role: "system", content: g.join("\n") });
63
80
  }
64
- return [...msgs, ...state.session.history.slice(-state.settings.maxHistoryMessages)];
81
+ const hist = state.settings.maxHistoryMessages
82
+ ? state.session.history.slice(-state.settings.maxHistoryMessages)
83
+ : state.session.history;
84
+ return [...msgs, ...hist];
65
85
  }
66
86
 
67
87
  function getContextLabel(state) {
68
88
  const est = estimateMessagesTokens(formatContextMessages(state));
69
- const win = state.settings.contextWindow || 128000;
89
+ const win = resolveContextBudget({ model: state.model, settings: state.settings }).contextWindow;
70
90
  return `Context: ~${est} / ${win} tokens`;
71
91
  }
72
92
 
@@ -545,7 +565,14 @@ function replaySessionHistory(sink, state) {
545
565
  sink.log("meta", `Memory Summary: ${state.session.summaryMemory.replace(/\s+/g, " ").slice(0, 140)}`);
546
566
  }
547
567
  for (const m of state.session.history.slice(-20)) {
548
- if (m.role === "user") sink.log("user", m.content || "");
568
+ if (m.role === "user" && m.isCompactionSummary) {
569
+ sink.log(
570
+ "meta",
571
+ `Compaction Summary: ${String(m.content || "")
572
+ .replace(/\s+/g, " ")
573
+ .slice(0, 140)}`
574
+ );
575
+ } else if (m.role === "user") sink.log("user", m.content || "");
549
576
  else if (m.role === "assistant" && m.content) sink.log("assistant", m.content);
550
577
  else if (m.role === "assistant" && Array.isArray(m.tool_calls) && m.tool_calls.length) {
551
578
  for (const tc of m.tool_calls) {
@@ -564,6 +591,8 @@ async function switchToSession(state, targetId, isNew, sink, waitForMemorySync)
564
591
  if (!state.noSession) saveSession(state.session, state.paths);
565
592
  const cleanId = safeId(targetId || (isNew ? `session-${Date.now()}` : "default"));
566
593
  state.session = loadSession(cleanId, state.model, state.paths);
594
+ state.readTracker = null;
595
+ state.tokenCalibration = null;
567
596
  if (isNew) {
568
597
  state.session.summaryMemory = "";
569
598
  state.session.pinnedMemory = [];
@@ -630,7 +659,7 @@ async function openSessionPicker(state, tui, sink, waitForMemorySync) {
630
659
  if (res.action === "select") {
631
660
  if (res.item.type === "new") {
632
661
  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, "")}`;
662
+ const id = rawName || makeAutoSessionId();
634
663
  await switchToSession(state, id, true, sink, waitForMemorySync);
635
664
  return;
636
665
  }
@@ -828,9 +857,159 @@ async function runModelProviderBrowser(state, sink) {
828
857
  if (!state.noSession) saveSession(state.session, state.paths);
829
858
  sink.syncStatus();
830
859
  sink.log("system", `Switched to ${state.provider.name} · model: ${state.model}`);
860
+ await promptReasoningSelection(state, sink);
861
+ return;
862
+ }
863
+ }
864
+ }
865
+
866
+ async function promptReasoningSelection(state, sink) {
867
+ if (!sink || !sink.openChoicePicker) return null;
868
+ const current = String(state.settings?.reasoning || "off").toLowerCase();
869
+ const items = REASONING_LEVELS.map((r) => ({
870
+ type: "reasoning",
871
+ id: r.id,
872
+ label: `${r.id === current ? "● " : " "}${r.id}`,
873
+ desc: r.desc,
874
+ }));
875
+ const picked = await sink.openChoicePicker(`Select Reasoning Level (${state.model})`, items, current);
876
+ if (!picked) return null;
877
+ persistAndApplySetting(state, "reasoning", picked, sink);
878
+ sink.log("system", `Reasoning level set to: ${state.settings.reasoning}`);
879
+ return state.settings.reasoning;
880
+ }
881
+
882
+ async function handleSkillsCommand(state, arg, sink) {
883
+ const rawArg = String(arg || "").trim();
884
+ const tokens = rawArg.match(/"[^"]+"|'[^']+'|\S+/g) || [];
885
+ const sub = (tokens[0] || "list").toLowerCase();
886
+ const restTokens = tokens.slice(1).map((t) => t.replace(/^["']|["']$/g, ""));
887
+
888
+ if (sub === "add") {
889
+ const useProject = restTokens.includes("--project") || restTokens.includes("-p");
890
+ const pathArgs = restTokens.filter((t) => t !== "--project" && t !== "-p");
891
+ const fileArg = pathArgs.join(" ").trim();
892
+ if (!fileArg) {
893
+ sink.log("error", "Usage: /skills add <markdown-file.md> [--project]");
894
+ return;
895
+ }
896
+ const root = state.workspaceRoot || process.cwd();
897
+ const abs = path.resolve(root, fileArg);
898
+ if (!fs.existsSync(abs)) {
899
+ sink.log("error", `Skill markdown file not found: ${abs}`);
900
+ return;
901
+ }
902
+ const rawMd = fs.readFileSync(abs, "utf8");
903
+ const saved = saveSkillFromMarkdown({
904
+ markdownText: rawMd,
905
+ filePath: abs,
906
+ scope: useProject ? "project" : "global",
907
+ paths: state.paths,
908
+ });
909
+ sink.log(
910
+ "system",
911
+ `Saved skill '${saved.title}' [${saved.slug}] (${saved.scope})\n` +
912
+ `Description: ${saved.description}\n` +
913
+ `Tags: ${saved.tags.join(", ") || "(none)"}\n` +
914
+ `File: ${saved.filePath}`
915
+ );
916
+ return;
917
+ }
918
+
919
+ if (sub === "new") {
920
+ let title = restTokens.join(" ").trim();
921
+ if (!title && sink.askPrompt) {
922
+ title = (await sink.askPrompt("Skill title (e.g. React Design System): ")).trim();
923
+ }
924
+ if (!title) {
925
+ sink.log("error", "Usage: /skills new <title>");
926
+ return;
927
+ }
928
+ let desc = "";
929
+ let tagsRaw = "";
930
+ let body = "";
931
+ if (sink.askPrompt) {
932
+ desc = (await sink.askPrompt("Skill description (when should this skill apply?): ")).trim();
933
+ tagsRaw = (await sink.askPrompt("Tags (comma-separated, e.g. frontend,react,css): ")).trim();
934
+ body = (await sink.askPrompt("Core guidelines / instructions: ")).trim();
935
+ }
936
+ const tags = tagsRaw
937
+ ? tagsRaw
938
+ .split(",")
939
+ .map((s) => s.trim())
940
+ .filter(Boolean)
941
+ : [];
942
+ const saved = saveSkillFromMarkdown({
943
+ markdownText: body || `# ${title}\n\n${desc || "Add guidelines here."}`,
944
+ title,
945
+ description: desc,
946
+ tags,
947
+ scope: "global",
948
+ paths: state.paths,
949
+ });
950
+ sink.log("system", `Created skill '${saved.title}' [${saved.slug}] -> ${saved.filePath}`);
951
+ return;
952
+ }
953
+
954
+ if (sub === "show" || sub === "view") {
955
+ const target = restTokens.join(" ").trim();
956
+ if (!target) {
957
+ sink.log("error", "Usage: /skills show <slug-or-title>");
958
+ return;
959
+ }
960
+ const slug = slugifySkillName(target);
961
+ const all = loadAllSkills(state.paths);
962
+ const found = all.find(
963
+ (s) => s.slug === slug || s.title.toLowerCase() === target.toLowerCase() || s.slug.includes(slug)
964
+ );
965
+ if (!found) {
966
+ sink.log("error", `Skill not found: ${target}`);
967
+ return;
968
+ }
969
+ sink.log(
970
+ "system",
971
+ `Skill: ${found.title} [${found.slug}] (${found.scope})\n` +
972
+ `Description: ${found.description}\n` +
973
+ `Tags: ${found.tags.join(", ") || "(none)"}\n` +
974
+ `Path: ${found.filePath}\n\n${found.body}`
975
+ );
976
+ return;
977
+ }
978
+
979
+ if (sub === "rm" || sub === "remove" || sub === "delete") {
980
+ const target = restTokens.join(" ").trim();
981
+ if (!target) {
982
+ sink.log("error", "Usage: /skills rm <slug-or-title>");
831
983
  return;
832
984
  }
985
+ const removed = removeSkill(target, state.paths);
986
+ sink.log(
987
+ removed.removed ? "system" : "error",
988
+ removed.removed
989
+ ? `Removed skill '${removed.skill?.title || target}' [${removed.skill?.slug || target}].`
990
+ : removed.reason || `Skill not found: ${target}`
991
+ );
992
+ return;
993
+ }
994
+
995
+ const all = loadAllSkills(state.paths);
996
+ if (!all.length) {
997
+ sink.log(
998
+ "system",
999
+ "No skills saved yet.\n" +
1000
+ "Add one with: /skills add <path/to/skill.md> [--project]\n" +
1001
+ 'Or ask in chat: "Save @my-frontend-guide.md as a skill"'
1002
+ );
1003
+ return;
833
1004
  }
1005
+ const lines = all.map(
1006
+ (s, i) =>
1007
+ `${i + 1}. ${s.title} [${s.slug}] (${s.scope})${s.tags.length ? ` · tags: ${s.tags.join(", ")}` : ""}\n ${s.description}`
1008
+ );
1009
+ sink.log(
1010
+ "system",
1011
+ `Saved Skills (${all.length}):\n${lines.join("\n")}\n\nTip: /skills add <file.md> | /skills show <slug> | /skills rm <slug>`
1012
+ );
834
1013
  }
835
1014
 
836
1015
  async function handleSlash(state, input, sink, deps) {
@@ -991,13 +1170,16 @@ async function handleSlash(state, input, sink, deps) {
991
1170
  case "/cost": {
992
1171
  const pTok = state.session?.stats?.promptTokens || 0;
993
1172
  const cTok = state.session?.stats?.completionTokens || 0;
1173
+ const crTok = state.session?.stats?.cacheReadTokens || 0;
1174
+ const cwTok = state.session?.stats?.cacheWriteTokens || 0;
994
1175
  const est = estimateTokenCostUsd(state.model, pTok, cTok);
995
1176
  const costLine = est.knownPricing
996
1177
  ? `Estimated Cost: $${est.totalUsd.toFixed(6)} (in: $${est.inCost.toFixed(6)}, out: $${est.outCost.toFixed(6)})`
997
1178
  : `Estimated Cost: unknown pricing for '${state.model}' (tokens: ${pTok} in, ${cTok} out)`;
1179
+ const cacheStr = crTok || cwTok ? ` · Cache: ${crTok} read, ${cwTok} write` : "";
998
1180
  sink.log(
999
1181
  "system",
1000
- `${costLine}\nRequests: ${state.session?.stats?.requests || 0} · Tokens: ${pTok} in, ${cTok} out`
1182
+ `${costLine}\nRequests: ${state.session?.stats?.requests || 0} · Tokens: ${pTok} in, ${cTok} out${cacheStr}`
1001
1183
  );
1002
1184
  return;
1003
1185
  }
@@ -1186,6 +1368,66 @@ async function handleSlash(state, input, sink, deps) {
1186
1368
  if (!state.noSession) saveSession(state.session, state.paths);
1187
1369
  sink.syncStatus();
1188
1370
  sink.log("system", `Model switched & saved: ${state.model}`);
1371
+ if (sink.openChoicePicker) {
1372
+ await promptReasoningSelection(state, sink);
1373
+ }
1374
+ return;
1375
+ }
1376
+ case "/reasoning": {
1377
+ const level = arg.trim().toLowerCase();
1378
+ if (level) {
1379
+ if (!REASONING_LEVELS.some((r) => r.id === level)) {
1380
+ sink.log("error", "Invalid reasoning level. Use: off | low | medium | high");
1381
+ return;
1382
+ }
1383
+ persistAndApplySetting(state, "reasoning", level, sink);
1384
+ sink.log("system", `Reasoning level set to: ${state.settings.reasoning}`);
1385
+ return;
1386
+ }
1387
+ if (sink.openChoicePicker) {
1388
+ await promptReasoningSelection(state, sink);
1389
+ } else {
1390
+ sink.log(
1391
+ "system",
1392
+ `Current reasoning level: ${state.settings?.reasoning || "off"} (options: off, low, medium, high)`
1393
+ );
1394
+ }
1395
+ return;
1396
+ }
1397
+ case "/skill":
1398
+ case "/skills":
1399
+ await handleSkillsCommand(state, arg, sink);
1400
+ return;
1401
+ case "/browser": {
1402
+ const sub = (arg.trim().split(/\s+/)[0] || "status").toLowerCase();
1403
+ if (sub === "install") {
1404
+ sink.log("system", "Checking / installing isolated Playwright browser runtime...");
1405
+ const res = await ensurePlaywrightInstalled({
1406
+ paths: state.paths,
1407
+ ctx: { log: (k, m) => sink.log(k, m), setBusy: (l) => sink.setBusy?.(l) },
1408
+ });
1409
+ sink.setBusy?.("");
1410
+ sink.log(
1411
+ "system",
1412
+ `Playwright ready (${res.alreadyInstalled ? "already installed" : "installed now"}) in ${res.runtimeDir}\nBrowser executable: ${res.executablePath || "(Chromium)"}`
1413
+ );
1414
+ return;
1415
+ }
1416
+ if (sub === "close") {
1417
+ await closeBrowserSession();
1418
+ sink.log("system", "Closed active headless browser session.");
1419
+ return;
1420
+ }
1421
+ const st = getBrowserStatus({ paths: state.paths });
1422
+ sink.log(
1423
+ "system",
1424
+ `Browser Runtime Status:\n` +
1425
+ ` Playwright installed: ${st.playwrightInstalled ? `yes (${st.source})` : "no (will auto-install on first browser tool call)"}\n` +
1426
+ ` Browser executable: ${st.executablePath || "(none cached; will auto-detect or install Chromium on demand)"}\n` +
1427
+ ` Isolated runtime dir: ${st.runtimeDir}\n` +
1428
+ ` Active session: ${st.sessionOpen ? `open (${st.activeUrl || "blank"})` : "closed"}\n` +
1429
+ `Tip: /browser install | /browser close`
1430
+ );
1189
1431
  return;
1190
1432
  }
1191
1433
  case "/tools": {
@@ -1215,20 +1457,23 @@ async function handleSlash(state, input, sink, deps) {
1215
1457
  return;
1216
1458
  case "/stats": {
1217
1459
  const est = estimateMessagesTokens(formatContextMessages(state));
1218
- const win = state.settings.contextWindow || 128000;
1460
+ const win = resolveContextBudget({ model: state.model, settings: state.settings }).contextWindow;
1219
1461
  const pct = ((est / win) * 100).toFixed(1);
1220
1462
  const avgSec = state.session.stats.requests
1221
1463
  ? (state.session.stats.totalMs / state.session.stats.requests / 1000).toFixed(2)
1222
1464
  : "0.00";
1223
1465
  const ttft = state.session.stats.lastTtftMs ?? 0;
1224
1466
  const tps = state.session.stats.lastTokPerSec ?? 0;
1467
+ const crTok = state.session.stats.cacheReadTokens || 0;
1468
+ const cwTok = state.session.stats.cacheWriteTokens || 0;
1469
+ const cacheSuffix = crTok || cwTok ? ` (cache: ${crTok} read, ${cwTok} write)` : "";
1225
1470
  sink.log(
1226
1471
  "system",
1227
1472
  `Session: ${state.session.id} (${state.session.history.length} messages) · Mode: ${state.settings.agentMode}\n` +
1228
1473
  `Provider: ${state.provider.name} [${state.provider.type}] · Model: ${state.model}\n` +
1229
1474
  `Context Size: ~${est} / ${win} tokens (${pct}%)\n` +
1230
1475
  `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`
1476
+ `Total Tokens Used: ${state.session.stats.promptTokens} input, ${state.session.stats.completionTokens} output${cacheSuffix}`
1232
1477
  );
1233
1478
  return;
1234
1479
  }
@@ -1272,6 +1517,7 @@ module.exports = {
1272
1517
  summarizeArgsShort,
1273
1518
  getContextLabel,
1274
1519
  persistAndApplySetting,
1520
+ promptReasoningSelection,
1275
1521
  handleSlash,
1276
1522
  switchToSession,
1277
1523
  openSessionPicker,
@@ -1,93 +1,127 @@
1
1
  "use strict";
2
2
 
3
+ const DEFAULT_MAX_OUTPUT_TOKENS = 16384;
4
+
3
5
  const MODEL_PROFILES = [
4
6
  {
5
- match: /claude-(?:3-7|sonnet-4|opus-4|haiku-4|3-5)/i,
7
+ match: /claude-(?:3-7|sonnet-4|opus-4|haiku-4)/i,
6
8
  contextWindow: 200000,
9
+ maxOutputTokens: 64000,
7
10
  supportsTemperature: true,
8
11
  supportsTools: true,
9
12
  inputPer1M: 3.0,
10
13
  outputPer1M: 15.0,
14
+ known: true,
15
+ },
16
+ {
17
+ match: /claude-3-5/i,
18
+ contextWindow: 200000,
19
+ maxOutputTokens: 8192,
20
+ supportsTemperature: true,
21
+ supportsTools: true,
22
+ inputPer1M: 3.0,
23
+ outputPer1M: 15.0,
24
+ known: true,
11
25
  },
12
26
  {
13
27
  match: /claude-3/i,
14
28
  contextWindow: 200000,
29
+ maxOutputTokens: 4096,
15
30
  supportsTemperature: true,
16
31
  supportsTools: true,
17
32
  inputPer1M: 3.0,
18
33
  outputPer1M: 15.0,
34
+ known: true,
19
35
  },
20
36
  {
21
37
  match: /\b(?:o1|o3|o4)(?:-|$)/i,
22
38
  contextWindow: 200000,
39
+ maxOutputTokens: 32768,
23
40
  supportsTemperature: false,
24
41
  supportsTools: true,
25
42
  inputPer1M: 2.0,
26
43
  outputPer1M: 8.0,
44
+ known: true,
27
45
  },
28
46
  {
29
47
  match: /gpt-4\.1/i,
30
48
  contextWindow: 1000000,
49
+ maxOutputTokens: 32768,
31
50
  supportsTemperature: true,
32
51
  supportsTools: true,
33
52
  inputPer1M: 2.0,
34
53
  outputPer1M: 8.0,
54
+ known: true,
35
55
  },
36
56
  {
37
57
  match: /gpt-4o-mini/i,
38
58
  contextWindow: 128000,
59
+ maxOutputTokens: 16384,
39
60
  supportsTemperature: true,
40
61
  supportsTools: true,
41
62
  inputPer1M: 0.15,
42
63
  outputPer1M: 0.6,
64
+ known: true,
43
65
  },
44
66
  {
45
67
  match: /gpt-4o/i,
46
68
  contextWindow: 128000,
69
+ maxOutputTokens: 16384,
47
70
  supportsTemperature: true,
48
71
  supportsTools: true,
49
72
  inputPer1M: 2.5,
50
73
  outputPer1M: 10.0,
74
+ known: true,
51
75
  },
52
76
  {
53
77
  match: /gemini-(?:2|2\.5|3|4)/i,
54
78
  contextWindow: 1000000,
79
+ maxOutputTokens: 65536,
55
80
  supportsTemperature: true,
56
81
  supportsTools: true,
57
82
  inputPer1M: 1.25,
58
83
  outputPer1M: 5.0,
84
+ known: true,
59
85
  },
60
86
  {
61
87
  match: /gemma-/i,
62
88
  contextWindow: 128000,
89
+ maxOutputTokens: 8192,
63
90
  supportsTemperature: true,
64
91
  supportsTools: true,
65
92
  inputPer1M: 0.1,
66
93
  outputPer1M: 0.2,
94
+ known: true,
67
95
  },
68
96
  {
69
97
  match: /deepseek-r1|deepseek-reasoner/i,
70
98
  contextWindow: 128000,
99
+ maxOutputTokens: 16384,
71
100
  supportsTemperature: false,
72
101
  supportsTools: true,
73
102
  inputPer1M: 0.55,
74
103
  outputPer1M: 2.19,
104
+ known: true,
75
105
  },
76
106
  {
77
107
  match: /deepseek/i,
78
108
  contextWindow: 128000,
109
+ maxOutputTokens: 8192,
79
110
  supportsTemperature: true,
80
111
  supportsTools: true,
81
112
  inputPer1M: 0.27,
82
113
  outputPer1M: 1.1,
114
+ known: true,
83
115
  },
84
116
  {
85
117
  match: /qwen|llama-3/i,
86
118
  contextWindow: 128000,
119
+ maxOutputTokens: 16384,
87
120
  supportsTemperature: true,
88
121
  supportsTools: true,
89
122
  inputPer1M: 0.2,
90
123
  outputPer1M: 0.6,
124
+ known: true,
91
125
  },
92
126
  ];
93
127
 
@@ -97,11 +131,13 @@ function lookupModelCapabilities(modelId = "") {
97
131
  if (p.match.test(clean)) return { ...p };
98
132
  }
99
133
  return {
100
- contextWindow: 128000,
134
+ contextWindow: 32000,
135
+ maxOutputTokens: DEFAULT_MAX_OUTPUT_TOKENS,
101
136
  supportsTemperature: true,
102
137
  supportsTools: true,
103
138
  inputPer1M: 0,
104
139
  outputPer1M: 0,
140
+ known: false,
105
141
  };
106
142
  }
107
143
 
@@ -118,6 +154,7 @@ function estimateTokenCostUsd(modelId, promptTokens = 0, completionTokens = 0) {
118
154
  }
119
155
 
120
156
  module.exports = {
157
+ DEFAULT_MAX_OUTPUT_TOKENS,
121
158
  lookupModelCapabilities,
122
159
  estimateTokenCostUsd,
123
160
  };
@@ -29,15 +29,32 @@ function findProjectRoot(cwd = process.cwd()) {
29
29
  }
30
30
 
31
31
  /**
32
- * Resolve all global (~/.config/kovence) and per-project (<project>/.kovence) paths.
32
+ * Resolve the global config directory in a cross-platform way.
33
+ *
34
+ * Priority (highest to lowest):
35
+ * 1. KOVENCE_CONFIG_DIR env var (always wins, any OS)
36
+ * 2. XDG_CONFIG_HOME/kovence (Linux/macOS with XDG override)
37
+ * 3. %APPDATA%\kovence (Windows — C:\Users\<user>\AppData\Roaming\kovence)
38
+ * 4. ~/.config/kovence (Linux/macOS default)
39
+ */
40
+ function resolveGlobalConfigDir() {
41
+ if (process.env.XDG_CONFIG_HOME) {
42
+ return path.join(process.env.XDG_CONFIG_HOME, "kovence");
43
+ }
44
+ if (process.platform === "win32") {
45
+ const appData = process.env.APPDATA || path.join(os.homedir(), "AppData", "Roaming");
46
+ return path.join(appData, "kovence");
47
+ }
48
+ return path.join(os.homedir(), ".config", "kovence");
49
+ }
50
+
51
+ /**
52
+ * Resolve all global and per-project paths.
33
53
  */
34
54
  function resolvePaths(options = {}) {
35
55
  const cwd = path.resolve(options.cwd || process.cwd());
36
56
  const projectRoot = path.resolve(options.projectRoot || findProjectRoot(cwd));
37
- const xdgConfig = process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config");
38
- const globalDir = path.resolve(
39
- options.globalDir || process.env.KOVENCE_CONFIG_DIR || path.join(xdgConfig, "kovence")
40
- );
57
+ const globalDir = path.resolve(options.globalDir || process.env.KOVENCE_CONFIG_DIR || resolveGlobalConfigDir());
41
58
  const projectDir = path.resolve(options.projectDir || path.join(projectRoot, ".kovence"));
42
59
 
43
60
  return {
@@ -45,8 +62,10 @@ function resolvePaths(options = {}) {
45
62
  projectRoot,
46
63
  globalDir,
47
64
  projectDir,
48
- sessionsDir: path.join(projectDir, "sessions"),
49
- checkpointsDir: path.join(projectDir, "checkpoints"),
65
+ // Sessions and checkpoints are always global so data never scatters
66
+ // across different working directories.
67
+ sessionsDir: path.join(globalDir, "sessions"),
68
+ checkpointsDir: path.join(globalDir, "checkpoints"),
50
69
  commandsDir: path.join(projectDir, "commands"),
51
70
  settingsFile: path.join(globalDir, "settings.json"),
52
71
  providersFile: path.join(globalDir, "providers.json"),
@@ -55,7 +74,7 @@ function resolvePaths(options = {}) {
55
74
  inputHistoryFile: path.join(globalDir, "input_history.json"),
56
75
  projectMemoryFile: path.join(projectDir, "project_memory.json"),
57
76
  projectPermissionsFile: path.join(projectDir, "permissions.json"),
58
- migrationMarkerFile: path.join(projectDir, ".migrated_from_ai_harness"),
77
+ migrationMarkerFile: path.join(globalDir, ".migrated_from_ai_harness"),
59
78
  };
60
79
  }
61
80
 
@@ -85,8 +104,10 @@ function ensureGitInfoExclude(projectRoot) {
85
104
  */
86
105
  function ensureStorageDirs(paths) {
87
106
  fs.mkdirSync(paths.globalDir, { recursive: true, mode: 0o700 });
88
- fs.mkdirSync(paths.projectDir, { recursive: true });
89
107
  fs.mkdirSync(paths.sessionsDir, { recursive: true });
108
+ fs.mkdirSync(paths.checkpointsDir, { recursive: true });
109
+ // Only create projectDir when it already exists (avoid polluting random dirs).
110
+ // Commands dir is project-local and opt-in.
90
111
  ensureGitInfoExclude(paths.projectRoot);
91
112
  }
92
113
 
@@ -14,10 +14,18 @@ function createEmptySession(id, model = "") {
14
14
  model,
15
15
  agentMode: null,
16
16
  summaryMemory: "",
17
+ compactionSummary: "",
17
18
  pinnedMemory: [],
18
19
  todos: [],
19
20
  history: [],
20
- stats: { requests: 0, totalMs: 0, promptTokens: 0, completionTokens: 0 },
21
+ stats: {
22
+ requests: 0,
23
+ totalMs: 0,
24
+ promptTokens: 0,
25
+ completionTokens: 0,
26
+ cacheReadTokens: 0,
27
+ cacheWriteTokens: 0,
28
+ },
21
29
  };
22
30
  }
23
31
 
@@ -33,10 +41,19 @@ function loadSession(id, defaultModel = "", paths = resolvePaths()) {
33
41
  ...createEmptySession(cleanId, defaultModel),
34
42
  ...data,
35
43
  id: cleanId,
44
+ compactionSummary: typeof data.compactionSummary === "string" ? data.compactionSummary : "",
36
45
  pinnedMemory: Array.isArray(data.pinnedMemory) ? data.pinnedMemory : [],
37
46
  todos: Array.isArray(data.todos) ? data.todos : [],
38
47
  history: Array.isArray(data.history) ? data.history : [],
39
- stats: { requests: 0, totalMs: 0, promptTokens: 0, completionTokens: 0, ...(data.stats || {}) },
48
+ stats: {
49
+ requests: 0,
50
+ totalMs: 0,
51
+ promptTokens: 0,
52
+ completionTokens: 0,
53
+ cacheReadTokens: 0,
54
+ cacheWriteTokens: 0,
55
+ ...(data.stats || {}),
56
+ },
40
57
  };
41
58
  }
42
59
 
@@ -157,6 +174,40 @@ function deleteSession(id, paths = resolvePaths()) {
157
174
  return true;
158
175
  }
159
176
 
177
+ /**
178
+ * Delete session files whose `updatedAt` (or `createdAt`) timestamp is older than
179
+ * `retentionDays` days. Pass 0 (or null/undefined) to skip cleanup entirely.
180
+ * Returns the number of sessions deleted.
181
+ */
182
+ function cleanupOldSessions(retentionDays, paths = resolvePaths(), activeSessionId = "") {
183
+ const days = Number(retentionDays);
184
+ if (!Number.isFinite(days) || days <= 0) return 0;
185
+ ensureStorageDirs(paths);
186
+ if (!fs.existsSync(paths.sessionsDir)) return 0;
187
+ const cutoffMs = Date.now() - days * 24 * 60 * 60 * 1000;
188
+ let deleted = 0;
189
+ const files = fs.readdirSync(paths.sessionsDir).filter((f) => f.endsWith(".json"));
190
+ for (const f of files) {
191
+ const id = f.replace(/\.json$/, "");
192
+ if (id === activeSessionId) continue; // never delete current session
193
+ const full = path.join(paths.sessionsDir, f);
194
+ try {
195
+ const data = readJsonSafe(full, null);
196
+ const stamp = data?.updatedAt || data?.createdAt || "";
197
+ if (!stamp) continue;
198
+ const ts = new Date(stamp).getTime();
199
+ if (!Number.isFinite(ts)) continue;
200
+ if (ts < cutoffMs) {
201
+ fs.unlinkSync(full);
202
+ deleted++;
203
+ }
204
+ } catch {
205
+ // Non-fatal: skip unreadable file.
206
+ }
207
+ }
208
+ return deleted;
209
+ }
210
+
160
211
  function forkSession(sourceSession, newId, paths = resolvePaths()) {
161
212
  const cleanNewId = safeId(newId);
162
213
  if (!cleanNewId) throw new Error("Invalid fork session name.");
@@ -196,6 +247,7 @@ module.exports = {
196
247
  groupSessionsByDate,
197
248
  suggestSessionIdFromPrompt,
198
249
  deleteSession,
250
+ cleanupOldSessions,
199
251
  loadInputHistory,
200
252
  saveInputHistory,
201
253
  };