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,209 @@
1
+ "use strict";
2
+
3
+ const { safeId, ensureStorageDirs, readJsonSafe, atomicWriteJson, resolvePaths } = require("./paths");
4
+
5
+ /**
6
+ * Redact sensitive API tokens for safe terminal and log display.
7
+ */
8
+ function redactSecret(secret) {
9
+ const clean = String(secret || "").trim();
10
+ if (!clean) return "(not set)";
11
+ if (clean.length <= 8) return "***";
12
+ return `${clean.slice(0, 4)}...${clean.slice(-4)}`;
13
+ }
14
+
15
+ function normalizeModelList(modelsInput, fallbackDefault = "") {
16
+ const out = [];
17
+ const seen = new Set();
18
+ const list = Array.isArray(modelsInput)
19
+ ? modelsInput
20
+ : typeof modelsInput === "string"
21
+ ? modelsInput.split(",")
22
+ : [];
23
+ for (const raw of [...list, fallbackDefault]) {
24
+ const clean = String(raw || "").trim();
25
+ if (!clean || seen.has(clean)) continue;
26
+ seen.add(clean);
27
+ out.push(clean);
28
+ }
29
+ return out;
30
+ }
31
+
32
+ /**
33
+ * Build runtime default provider from environment variables (never persisted to providers.json).
34
+ */
35
+ function buildEnvDefaultProvider(envFallback = {}) {
36
+ const baseUrl = String(envFallback.baseUrl || "").replace(/\/+$/, "");
37
+ const apiKey = String(envFallback.apiKey || "").trim();
38
+ if (!baseUrl || !apiKey || apiKey === "sk-your-virtual-key") return null;
39
+ const models = normalizeModelList(envFallback.models, envFallback.defaultModel);
40
+ return {
41
+ name: "default",
42
+ type: envFallback.type === "anthropic" ? "anthropic" : "openai",
43
+ baseUrl,
44
+ apiKey,
45
+ apiKeyEnv: "",
46
+ defaultModel: models[0] || "",
47
+ models,
48
+ fromEnv: true,
49
+ };
50
+ }
51
+
52
+ /**
53
+ * Resolve stored provider entry into runtime view, looking up apiKeyEnv dynamically without mutating persisted keys.
54
+ */
55
+ function hydrateCustomProvider(id, raw) {
56
+ if (!raw || typeof raw !== "object" || id === "default") return null;
57
+ const cleanId = safeId(id);
58
+ const type = raw.type === "anthropic" ? "anthropic" : "openai";
59
+ const apiKeyEnv = String(raw.apiKeyEnv || "").trim();
60
+ const storedKey = String(raw.apiKey || "");
61
+ const resolvedKey = apiKeyEnv ? String(process.env[apiKeyEnv] || storedKey || "") : storedKey;
62
+ const models = normalizeModelList(raw.models, raw.defaultModel);
63
+ return {
64
+ name: cleanId,
65
+ type,
66
+ baseUrl: String(raw.baseUrl || "").replace(/\/+$/, ""),
67
+ apiKey: resolvedKey,
68
+ _storedApiKey: storedKey,
69
+ apiKeyEnv,
70
+ defaultModel: String(raw.defaultModel || models[0] || ""),
71
+ models,
72
+ fromEnv: false,
73
+ };
74
+ }
75
+
76
+ /**
77
+ * Load provider profiles, keeping env 'default' dynamic and ignoring any legacy 'default' saved on disk.
78
+ */
79
+ function loadProviders(envFallback = {}, paths = resolvePaths()) {
80
+ const envDefault = buildEnvDefaultProvider(envFallback);
81
+ const data = readJsonSafe(paths.providersFile, { active: "", providers: {} });
82
+ const customProviders = {};
83
+ if (data && data.providers && typeof data.providers === "object") {
84
+ for (const [key, val] of Object.entries(data.providers)) {
85
+ if (key === "default") continue;
86
+ const cleanId = safeId(key);
87
+ const hydrated = hydrateCustomProvider(cleanId, val);
88
+ if (hydrated && hydrated.baseUrl) {
89
+ customProviders[cleanId] = hydrated;
90
+ }
91
+ }
92
+ }
93
+ const providers = envDefault ? { default: envDefault, ...customProviders } : { ...customProviders };
94
+ const firstKey = Object.keys(providers)[0] || "";
95
+ const active = data && data.active && providers[data.active] ? data.active : firstKey;
96
+ return { active, providers };
97
+ }
98
+
99
+ /**
100
+ * Persist custom providers only (never writes 'default' or env-resolved plaintext keys when apiKeyEnv is set).
101
+ */
102
+ function saveProviders(store, paths = resolvePaths()) {
103
+ ensureStorageDirs(paths);
104
+ const customOnly = {};
105
+ for (const [key, val] of Object.entries(store.providers || {})) {
106
+ if (key === "default" || !val || val.fromEnv) continue;
107
+ const cleanId = safeId(key);
108
+ const apiKeyEnv = String(val.apiKeyEnv || "").trim();
109
+ const storedKey = apiKeyEnv
110
+ ? val._storedApiKey !== undefined
111
+ ? String(val._storedApiKey)
112
+ : ""
113
+ : String(val.apiKey || "");
114
+ const models = normalizeModelList(val.models, val.defaultModel);
115
+ customOnly[cleanId] = {
116
+ name: cleanId,
117
+ type: val.type === "anthropic" ? "anthropic" : "openai",
118
+ baseUrl: String(val.baseUrl || "").replace(/\/+$/, ""),
119
+ ...(apiKeyEnv ? { apiKeyEnv } : {}),
120
+ ...(storedKey ? { apiKey: storedKey } : {}),
121
+ defaultModel: String(val.defaultModel || models[0] || ""),
122
+ ...(models.length ? { models } : {}),
123
+ };
124
+ }
125
+ const firstCustom = Object.keys(customOnly)[0] || "";
126
+ const active =
127
+ store.active && (store.active === "default" || customOnly[store.active]) ? store.active : firstCustom;
128
+ atomicWriteJson(paths.providersFile, { active, providers: customOnly }, 0o600);
129
+ }
130
+
131
+ function upsertProvider(
132
+ envFallback,
133
+ { name, type, baseUrl, apiKey = "", apiKeyEnv = "", defaultModel = "", models = [] },
134
+ paths = resolvePaths()
135
+ ) {
136
+ const id = safeId(name);
137
+ if (id === "default") {
138
+ throw new Error("Built-in 'default' provider comes from environment/.env and cannot be overwritten.");
139
+ }
140
+ const store = loadProviders(envFallback, paths);
141
+ const cleanType = type === "anthropic" ? "anthropic" : "openai";
142
+ const cleanEnvVar = String(apiKeyEnv || "").trim();
143
+ const normalizedModels = normalizeModelList(models, defaultModel);
144
+ store.providers[id] = hydrateCustomProvider(id, {
145
+ name: id,
146
+ type: cleanType,
147
+ baseUrl: String(baseUrl || "").replace(/\/+$/, ""),
148
+ apiKey: cleanEnvVar ? "" : String(apiKey || ""),
149
+ apiKeyEnv: cleanEnvVar,
150
+ defaultModel: String(defaultModel || normalizedModels[0] || ""),
151
+ models: normalizedModels,
152
+ });
153
+ if (!store.active || !store.providers[store.active]) store.active = id;
154
+ saveProviders(store, paths);
155
+ return store.providers[id];
156
+ }
157
+
158
+ /**
159
+ * Append one or more individual model names to an existing custom provider without duplicates.
160
+ */
161
+ function addProviderModels(envFallback, name, newModels = [], paths = resolvePaths()) {
162
+ const id = safeId(name);
163
+ if (id === "default") {
164
+ throw new Error("Cannot add persisted models to built-in 'default' env provider.");
165
+ }
166
+ const store = loadProviders(envFallback, paths);
167
+ const existing = store.providers[id];
168
+ if (!existing) throw new Error(`Provider '${id}' not found.`);
169
+ const merged = normalizeModelList(
170
+ [...(existing.models || []), ...(Array.isArray(newModels) ? newModels : [newModels])],
171
+ existing.defaultModel
172
+ );
173
+ existing.models = merged;
174
+ if (!existing.defaultModel && merged.length) existing.defaultModel = merged[0];
175
+ saveProviders(store, paths);
176
+ return existing;
177
+ }
178
+
179
+ function setActiveProvider(envFallback, name, paths = resolvePaths()) {
180
+ const store = loadProviders(envFallback, paths);
181
+ const id = safeId(name);
182
+ if (!store.providers[id]) throw new Error(`Provider '${id}' not found.`);
183
+ store.active = id;
184
+ saveProviders(store, paths);
185
+ return store.providers[id];
186
+ }
187
+
188
+ function removeProvider(envFallback, name, paths = resolvePaths()) {
189
+ const store = loadProviders(envFallback, paths);
190
+ const id = safeId(name);
191
+ if (id === "default") throw new Error("Cannot remove built-in 'default' provider.");
192
+ if (!store.providers[id]) return false;
193
+ delete store.providers[id];
194
+ if (store.active === id) store.active = Object.keys(store.providers)[0] || "";
195
+ saveProviders(store, paths);
196
+ return true;
197
+ }
198
+
199
+ module.exports = {
200
+ redactSecret,
201
+ normalizeModelList,
202
+ buildEnvDefaultProvider,
203
+ loadProviders,
204
+ saveProviders,
205
+ upsertProvider,
206
+ addProviderModels,
207
+ setActiveProvider,
208
+ removeProvider,
209
+ };
@@ -0,0 +1,201 @@
1
+ "use strict";
2
+
3
+ const fs = require("node:fs");
4
+ const path = require("node:path");
5
+ const { safeId, ensureStorageDirs, readJsonSafe, atomicWriteJson, resolvePaths } = require("./paths");
6
+
7
+ function createEmptySession(id, model = "") {
8
+ const now = new Date().toISOString();
9
+ return {
10
+ id: safeId(id),
11
+ title: "",
12
+ createdAt: now,
13
+ updatedAt: now,
14
+ model,
15
+ agentMode: null,
16
+ summaryMemory: "",
17
+ pinnedMemory: [],
18
+ todos: [],
19
+ history: [],
20
+ stats: { requests: 0, totalMs: 0, promptTokens: 0, completionTokens: 0 },
21
+ };
22
+ }
23
+
24
+ function sessionPath(id, paths = resolvePaths()) {
25
+ return path.join(paths.sessionsDir, `${safeId(id)}.json`);
26
+ }
27
+
28
+ function loadSession(id, defaultModel = "", paths = resolvePaths()) {
29
+ const cleanId = safeId(id);
30
+ const data = readJsonSafe(sessionPath(cleanId, paths), null);
31
+ if (!data) return createEmptySession(cleanId, defaultModel);
32
+ return {
33
+ ...createEmptySession(cleanId, defaultModel),
34
+ ...data,
35
+ id: cleanId,
36
+ pinnedMemory: Array.isArray(data.pinnedMemory) ? data.pinnedMemory : [],
37
+ todos: Array.isArray(data.todos) ? data.todos : [],
38
+ history: Array.isArray(data.history) ? data.history : [],
39
+ stats: { requests: 0, totalMs: 0, promptTokens: 0, completionTokens: 0, ...(data.stats || {}) },
40
+ };
41
+ }
42
+
43
+ function saveSession(session, paths = resolvePaths()) {
44
+ ensureStorageDirs(paths);
45
+ session.updatedAt = new Date().toISOString();
46
+ atomicWriteJson(sessionPath(session.id, paths), session);
47
+ }
48
+
49
+ function renameSession(session, newId, paths = resolvePaths()) {
50
+ const oldId = safeId(session.id);
51
+ const cleanNewId = safeId(newId);
52
+ if (!cleanNewId) throw new Error("Invalid session name.");
53
+ const oldFile = sessionPath(oldId, paths);
54
+ session.id = cleanNewId;
55
+ saveSession(session, paths);
56
+ if (oldId !== cleanNewId && fs.existsSync(oldFile)) {
57
+ try {
58
+ fs.unlinkSync(oldFile);
59
+ } catch {
60
+ // Non-fatal if already removed.
61
+ }
62
+ }
63
+ return cleanNewId;
64
+ }
65
+
66
+ function toLocalDateKey(isoStr) {
67
+ const d = isoStr ? new Date(isoStr) : null;
68
+ if (!d || Number.isNaN(d.getTime())) return "unknown";
69
+ const pad = (n) => String(n).padStart(2, "0");
70
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
71
+ }
72
+
73
+ function formatDateGroupLabel(dateKey, now = new Date()) {
74
+ if (!dateKey || dateKey === "unknown") return "Unknown Date";
75
+ const todayKey = toLocalDateKey(now.toISOString());
76
+ const yest = new Date(now.getTime() - 86400000);
77
+ const yestKey = toLocalDateKey(yest.toISOString());
78
+ if (dateKey === todayKey) return `Today (${dateKey})`;
79
+ if (dateKey === yestKey) return `Yesterday (${dateKey})`;
80
+ return dateKey;
81
+ }
82
+
83
+ function groupSessionsByDate(sessions, now = new Date()) {
84
+ const groups = new Map();
85
+ for (const s of sessions || []) {
86
+ const key = s.dateKey || toLocalDateKey(s.updatedAt || s.createdAt);
87
+ if (!groups.has(key)) groups.set(key, []);
88
+ groups.get(key).push(s);
89
+ }
90
+ return [...groups.entries()]
91
+ .filter(([, list]) => list.length > 0)
92
+ .sort(([a], [b]) => {
93
+ if (a === "unknown") return 1;
94
+ if (b === "unknown") return -1;
95
+ return b.localeCompare(a);
96
+ })
97
+ .map(([dateKey, list]) => ({
98
+ dateKey,
99
+ dateLabel: formatDateGroupLabel(dateKey, now),
100
+ sessions: list,
101
+ }));
102
+ }
103
+
104
+ function suggestSessionIdFromPrompt(promptText, paths = resolvePaths()) {
105
+ const cleaned = String(promptText || "")
106
+ .replace(/```[\s\S]*?```/g, " ")
107
+ .replace(/\s+/g, " ")
108
+ .trim();
109
+ const rawSlug = cleaned
110
+ .toLowerCase()
111
+ .replace(/[^a-z0-9]+/g, "-")
112
+ .replace(/^-+|-+$/g, "")
113
+ .slice(0, 36)
114
+ .replace(/-+$/g, "");
115
+ const base = rawSlug || "chat";
116
+ let candidate = safeId(base);
117
+ let n = 2;
118
+ while (fs.existsSync(sessionPath(candidate, paths)) && n < 1000) {
119
+ candidate = safeId(`${base}-${n}`);
120
+ n++;
121
+ }
122
+ return candidate;
123
+ }
124
+
125
+ function listSessions(paths = resolvePaths()) {
126
+ ensureStorageDirs(paths);
127
+ if (!fs.existsSync(paths.sessionsDir)) return [];
128
+ return fs
129
+ .readdirSync(paths.sessionsDir)
130
+ .filter((f) => f.endsWith(".json"))
131
+ .map((f) => {
132
+ const id = f.replace(/\.json$/, "");
133
+ const data = readJsonSafe(path.join(paths.sessionsDir, f), {});
134
+ const hist = Array.isArray(data.history) ? data.history : [];
135
+ const lastUser = [...hist].reverse().find((m) => m.role === "user" && m.content);
136
+ const rawPreview = data.title || (lastUser ? String(lastUser.content) : "");
137
+ const preview = rawPreview.replace(/\s+/g, " ").trim().slice(0, 48);
138
+ const updatedAt = data.updatedAt || data.createdAt || "";
139
+ return {
140
+ id,
141
+ title: data.title || "",
142
+ createdAt: data.createdAt || "",
143
+ updatedAt,
144
+ dateKey: toLocalDateKey(updatedAt),
145
+ messages: hist.length,
146
+ hasSummary: Boolean(data.summaryMemory),
147
+ preview,
148
+ };
149
+ })
150
+ .sort((a, b) => (b.updatedAt || "").localeCompare(a.updatedAt || ""));
151
+ }
152
+
153
+ function deleteSession(id, paths = resolvePaths()) {
154
+ const file = sessionPath(id, paths);
155
+ if (!fs.existsSync(file)) return false;
156
+ fs.unlinkSync(file);
157
+ return true;
158
+ }
159
+
160
+ function forkSession(sourceSession, newId, paths = resolvePaths()) {
161
+ const cleanNewId = safeId(newId);
162
+ if (!cleanNewId) throw new Error("Invalid fork session name.");
163
+ const now = new Date().toISOString();
164
+ const cloned = JSON.parse(JSON.stringify(sourceSession));
165
+ cloned.id = cleanNewId;
166
+ cloned.createdAt = now;
167
+ cloned.updatedAt = now;
168
+ if (cloned.title) cloned.title = `${cloned.title} (fork)`;
169
+ saveSession(cloned, paths);
170
+ return cloned;
171
+ }
172
+
173
+ function loadInputHistory(paths = resolvePaths()) {
174
+ const data = readJsonSafe(paths.inputHistoryFile, []);
175
+ return Array.isArray(data)
176
+ ? data.filter((x) => typeof x === "string" && x.trim() && !x.trim().startsWith("/")).slice(-200)
177
+ : [];
178
+ }
179
+
180
+ function saveInputHistory(items, paths = resolvePaths()) {
181
+ ensureStorageDirs(paths);
182
+ const clean = (Array.isArray(items) ? items : [])
183
+ .filter((x) => typeof x === "string" && x.trim() && !x.trim().startsWith("/"))
184
+ .slice(-200);
185
+ atomicWriteJson(paths.inputHistoryFile, clean);
186
+ }
187
+
188
+ module.exports = {
189
+ createEmptySession,
190
+ sessionPath,
191
+ loadSession,
192
+ saveSession,
193
+ renameSession,
194
+ forkSession,
195
+ listSessions,
196
+ groupSessionsByDate,
197
+ suggestSessionIdFromPrompt,
198
+ deleteSession,
199
+ loadInputHistory,
200
+ saveInputHistory,
201
+ };