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.
@@ -0,0 +1,113 @@
1
+ "use strict";
2
+
3
+ const crypto = require("node:crypto");
4
+ const { ensureStorageDirs, readJsonSafe, atomicWriteJson, resolvePaths } = require("../config/paths");
5
+
6
+ const VALID_ACTIONS = new Set(["allow", "deny", "ask"]);
7
+ const VALID_SCOPES = new Set(["tool", "commandPrefix", "path", "domain"]);
8
+
9
+ function makeRuleId() {
10
+ return crypto.randomBytes(4).toString("hex");
11
+ }
12
+
13
+ function normalizeRule(raw) {
14
+ if (!raw || typeof raw !== "object") return null;
15
+ const action = VALID_ACTIONS.has(raw.action) ? raw.action : "allow";
16
+ const scope = VALID_SCOPES.has(raw.scope) ? raw.scope : "tool";
17
+ const tool = String(raw.tool || "").trim();
18
+ const pattern = String(raw.pattern ?? "").trim();
19
+ if (!tool) return null;
20
+ return {
21
+ id: String(raw.id || makeRuleId()),
22
+ action,
23
+ tool,
24
+ scope,
25
+ pattern,
26
+ createdAt: String(raw.createdAt || new Date().toISOString()),
27
+ };
28
+ }
29
+
30
+ function fileForTarget(target, paths = resolvePaths()) {
31
+ return target === "project" ? paths.projectPermissionsFile : paths.globalPermissionsFile;
32
+ }
33
+
34
+ function loadPermissionRules(target = "global", paths = resolvePaths()) {
35
+ const file = fileForTarget(target, paths);
36
+ const data = readJsonSafe(file, { version: 1, rules: [] });
37
+ const rawRules = Array.isArray(data?.rules) ? data.rules : [];
38
+ return rawRules.map(normalizeRule).filter(Boolean);
39
+ }
40
+
41
+ function savePermissionRules(rules, target = "global", paths = resolvePaths()) {
42
+ ensureStorageDirs(paths);
43
+ const clean = (Array.isArray(rules) ? rules : []).map(normalizeRule).filter(Boolean);
44
+ atomicWriteJson(fileForTarget(target, paths), {
45
+ version: 1,
46
+ updatedAt: new Date().toISOString(),
47
+ rules: clean,
48
+ });
49
+ return clean;
50
+ }
51
+
52
+ function addPermissionRule(ruleInput, target = "project", paths = resolvePaths()) {
53
+ const candidate = normalizeRule(ruleInput);
54
+ if (!candidate) throw new Error("Invalid permission rule.");
55
+ const existing = loadPermissionRules(target, paths);
56
+ const idx = existing.findIndex(
57
+ (r) => r.tool === candidate.tool && r.scope === candidate.scope && r.pattern === candidate.pattern
58
+ );
59
+ if (idx >= 0) {
60
+ existing[idx] = { ...candidate, id: existing[idx].id };
61
+ } else {
62
+ existing.push(candidate);
63
+ }
64
+ savePermissionRules(existing, target, paths);
65
+ return candidate;
66
+ }
67
+
68
+ function listCombinedRules(sessionRules = [], paths = resolvePaths()) {
69
+ const project = loadPermissionRules("project", paths).map((r) => ({ ...r, origin: "project" }));
70
+ const global = loadPermissionRules("global", paths).map((r) => ({ ...r, origin: "global" }));
71
+ const session = (Array.isArray(sessionRules) ? sessionRules : [])
72
+ .map(normalizeRule)
73
+ .filter(Boolean)
74
+ .map((r) => ({ ...r, origin: "session" }));
75
+ return [...session, ...project, ...global];
76
+ }
77
+
78
+ function removePermissionRuleByIndex(oneBasedIndex, paths = resolvePaths()) {
79
+ const project = loadPermissionRules("project", paths);
80
+ const global = loadPermissionRules("global", paths);
81
+ const idx = Number(oneBasedIndex) - 1;
82
+ if (!Number.isInteger(idx) || idx < 0) return null;
83
+
84
+ if (idx < project.length) {
85
+ const [removed] = project.splice(idx, 1);
86
+ savePermissionRules(project, "project", paths);
87
+ return { ...removed, origin: "project" };
88
+ }
89
+ const gIdx = idx - project.length;
90
+ if (gIdx < global.length) {
91
+ const [removed] = global.splice(gIdx, 1);
92
+ savePermissionRules(global, "global", paths);
93
+ return { ...removed, origin: "global" };
94
+ }
95
+ return null;
96
+ }
97
+
98
+ function resetPermissionRules(target = "all", paths = resolvePaths()) {
99
+ if (target === "all" || target === "project") savePermissionRules([], "project", paths);
100
+ if (target === "all" || target === "global") savePermissionRules([], "global", paths);
101
+ }
102
+
103
+ module.exports = {
104
+ VALID_ACTIONS,
105
+ VALID_SCOPES,
106
+ normalizeRule,
107
+ loadPermissionRules,
108
+ savePermissionRules,
109
+ addPermissionRule,
110
+ listCombinedRules,
111
+ removePermissionRuleByIndex,
112
+ resetPermissionRules,
113
+ };
@@ -0,0 +1,340 @@
1
+ "use strict";
2
+
3
+ const AGENT_MODES = ["default", "accept-edits", "plan", "auto"];
4
+ const TOOL_PERMISSIONS = ["ask", "allow-reads", "allow-edits", "always-proceed"];
5
+ const NON_WORKSPACE_MODES = ["ask", "allow", "deny"];
6
+ const VERBOSITY_LEVELS = ["low", "normal", "high"];
7
+ const LANGUAGES = ["banglish", "bangla", "english"];
8
+ const RENDERING_MODES = ["fullscreen", "inline"];
9
+ const QUEUED_MESSAGE_MODES = ["queue", "interrupt"];
10
+ const COLOR_SCHEMES = ["amber", "dark", "light", "terminal"];
11
+
12
+ const DEFAULT_SYSTEM_PROMPT = [
13
+ "You are Kovence CLI, an advanced multi-step CLI agent harness built by Kovence (https://kovence.com).",
14
+ "Use tools proactively to inspect files, search code, edit cleanly, run tests/commands, download files/installers with download_file and install them with run_command, search online with web_search/google_search, fetch pages with web_fetch, and track multi-step plans with todo_write.",
15
+ "When answering with online search results, synthesize the retrieved context cleanly and cite relevant sources.",
16
+ "MEMORY RULE: Save persistent user preferences ONLY when explicitly requested via save_global_memory. Save temporary current-task notes using save_session_memory.",
17
+ ].join("\n");
18
+
19
+ const DEFAULT_SETTINGS = {
20
+ agentMode: "default",
21
+ toolPermission: "ask",
22
+ nonWorkspaceAccess: "ask",
23
+ model: "",
24
+ provider: "",
25
+ toolsEnabled: true,
26
+ autoSummarize: true,
27
+ maxToolSteps: 25,
28
+ maxHistoryMessages: 24,
29
+ contextWindow: 128000,
30
+ temperature: null,
31
+ maxTokens: null,
32
+ verbosity: "normal",
33
+ language: "banglish",
34
+ renderingMode: "fullscreen",
35
+ queuedMessages: "queue",
36
+ showTips: true,
37
+ showActiveTasks: true,
38
+ notifications: true,
39
+ colorScheme: "amber",
40
+ systemPrompt: DEFAULT_SYSTEM_PROMPT,
41
+ };
42
+
43
+ /**
44
+ * Schema metadata powering both /set CLI validation and the interactive /settings UI.
45
+ */
46
+ const SETTINGS_SCHEMA = [
47
+ {
48
+ key: "agentMode",
49
+ label: "Agent Mode",
50
+ type: "enum",
51
+ options: AGENT_MODES,
52
+ description:
53
+ "'default': ask on mutations, 'accept-edits': auto-approve file edits, 'plan': read-only plan before edits, 'auto': allow all except denylist.",
54
+ },
55
+ {
56
+ key: "toolPermission",
57
+ label: "Tool Permission",
58
+ type: "enum",
59
+ options: TOOL_PERMISSIONS,
60
+ description:
61
+ "'ask': confirm per policy, 'allow-reads': never ask on reads/fetches, 'allow-edits': auto-approve edits, 'always-proceed': allow safe tools.",
62
+ },
63
+ {
64
+ key: "nonWorkspaceAccess",
65
+ label: "Non-Workspace Access",
66
+ type: "enum",
67
+ options: NON_WORKSPACE_MODES,
68
+ description:
69
+ "Access to paths outside workspace root (+ --add-dir): 'ask': prompt, 'allow': permit, 'deny': block.",
70
+ },
71
+ {
72
+ key: "model",
73
+ label: "Model",
74
+ type: "string",
75
+ description:
76
+ "Default saved model ID (precedence: CLI --model > session model > saved setting > provider default).",
77
+ },
78
+ {
79
+ key: "provider",
80
+ label: "Provider",
81
+ type: "string",
82
+ description: "Active configured API provider profile name (cycle or press Enter to edit/switch).",
83
+ },
84
+ {
85
+ key: "toolsEnabled",
86
+ label: "Tools Enabled",
87
+ type: "boolean",
88
+ description: "'on': agent can invoke filesystem, shell, search and memory tools; 'off': chat-only mode.",
89
+ },
90
+ {
91
+ key: "autoSummarize",
92
+ label: "Auto Summarize",
93
+ type: "boolean",
94
+ description: "'on': compact older turns in background when history grows large; 'off': manual /compact only.",
95
+ },
96
+ {
97
+ key: "maxToolSteps",
98
+ label: "Max Tool Steps",
99
+ type: "integer",
100
+ min: 1,
101
+ max: 100,
102
+ description: "Maximum consecutive tool-calling loop iterations per user turn (1-100).",
103
+ },
104
+ {
105
+ key: "maxHistoryMessages",
106
+ label: "Max History Messages",
107
+ type: "integer",
108
+ min: 2,
109
+ max: 500,
110
+ description: "Target turn-aware message budget retained verbatim before pruning/summarizing (2-500).",
111
+ },
112
+ {
113
+ key: "contextWindow",
114
+ label: "Context Window",
115
+ type: "integer",
116
+ min: 1024,
117
+ max: 2000000,
118
+ description: "Model context window size in tokens used for budget tracking and auto-compaction (>= 1024).",
119
+ },
120
+ {
121
+ key: "temperature",
122
+ label: "Temperature",
123
+ type: "nullableFloat",
124
+ min: 0,
125
+ max: 2,
126
+ description: "Sampling temperature (0.0-2.0) or 'null' to use the model provider's default.",
127
+ },
128
+ {
129
+ key: "maxTokens",
130
+ label: "Max Tokens",
131
+ type: "nullableInteger",
132
+ min: 1,
133
+ max: 1000000,
134
+ description: "Maximum completion tokens per request or 'null' for provider default.",
135
+ },
136
+ {
137
+ key: "verbosity",
138
+ label: "Verbosity",
139
+ type: "enum",
140
+ options: VERBOSITY_LEVELS,
141
+ description:
142
+ "'low': minimal tool/status logs, 'normal': standard output, 'high': detailed diagnostics & audit trail.",
143
+ },
144
+ {
145
+ key: "language",
146
+ label: "Language",
147
+ type: "enum",
148
+ options: LANGUAGES,
149
+ description: "Preferred assistant response language hint: 'banglish' (Latin script), 'bangla', or 'english'.",
150
+ },
151
+ {
152
+ key: "renderingMode",
153
+ label: "Rendering Mode",
154
+ type: "enum",
155
+ options: RENDERING_MODES,
156
+ description: "'fullscreen': alt-screen Kovence TUI; 'inline': plain scrollback REPL on next launch.",
157
+ },
158
+ {
159
+ key: "queuedMessages",
160
+ label: "Queued Messages",
161
+ type: "enum",
162
+ options: QUEUED_MESSAGE_MODES,
163
+ description:
164
+ "When sending a prompt mid-turn: 'queue' runs after active turn; 'interrupt' aborts current turn first.",
165
+ },
166
+ {
167
+ key: "showTips",
168
+ label: "Show Tips",
169
+ type: "boolean",
170
+ description: "'on': show helpful shortcut and slash-command tips in welcome/status area; 'off': hide tips.",
171
+ },
172
+ {
173
+ key: "showActiveTasks",
174
+ label: "Show Active Tasks",
175
+ type: "boolean",
176
+ description: "'on': display live todo/background task status in the TUI; 'off': hide task banner.",
177
+ },
178
+ {
179
+ key: "notifications",
180
+ label: "Notifications",
181
+ type: "boolean",
182
+ description: "'on': emit terminal bell/notice when long turns finish or approval is needed; 'off': silent.",
183
+ },
184
+ {
185
+ key: "colorScheme",
186
+ label: "Color Scheme",
187
+ type: "enum",
188
+ options: COLOR_SCHEMES,
189
+ description: "UI palette: 'amber' (Kovence orange/amber), 'dark', 'light', or 'terminal' (minimal ANSI).",
190
+ },
191
+ {
192
+ key: "systemPrompt",
193
+ label: "Edit System Prompt",
194
+ type: "multilineString",
195
+ description: "Base system instructions injected at the start of every request (press Enter to edit).",
196
+ },
197
+ {
198
+ key: "managePermissions",
199
+ label: "Manage Permissions",
200
+ type: "action",
201
+ description: "Open saved global & project permission rules (list, search, and delete rules).",
202
+ },
203
+ ];
204
+
205
+ const SCHEMA_BY_KEY = new Map(SETTINGS_SCHEMA.map((item) => [item.key, item]));
206
+
207
+ const KEY_ALIASES = {
208
+ mode: "agentMode",
209
+ agent_mode: "agentMode",
210
+ tool_permission: "toolPermission",
211
+ non_workspace_access: "nonWorkspaceAccess",
212
+ tools: "toolsEnabled",
213
+ tools_enabled: "toolsEnabled",
214
+ auto_summarize: "autoSummarize",
215
+ max_steps: "maxToolSteps",
216
+ max_tool_steps: "maxToolSteps",
217
+ max_history: "maxHistoryMessages",
218
+ max_history_messages: "maxHistoryMessages",
219
+ context: "contextWindow",
220
+ context_window: "contextWindow",
221
+ temp: "temperature",
222
+ max_tokens: "maxTokens",
223
+ rendering: "renderingMode",
224
+ rendering_mode: "renderingMode",
225
+ queued_messages: "queuedMessages",
226
+ show_tips: "showTips",
227
+ show_active_tasks: "showActiveTasks",
228
+ color_scheme: "colorScheme",
229
+ system_prompt: "systemPrompt",
230
+ };
231
+
232
+ const PERSISTABLE_KEYS = new Set(Object.keys(DEFAULT_SETTINGS));
233
+
234
+ /**
235
+ * Resolve a user-facing key or alias to a canonical setting key.
236
+ */
237
+ function canonicalSettingKey(rawKey) {
238
+ const clean = String(rawKey || "").trim();
239
+ if (SCHEMA_BY_KEY.has(clean)) return clean;
240
+ const lower = clean.toLowerCase();
241
+ if (KEY_ALIASES[lower]) return KEY_ALIASES[lower];
242
+ for (const key of PERSISTABLE_KEYS) {
243
+ if (key.toLowerCase() === lower) return key;
244
+ }
245
+ return null;
246
+ }
247
+
248
+ /**
249
+ * Parse and strictly validate a raw input value for a setting key.
250
+ */
251
+ function parseSettingValue(rawKey, rawValue) {
252
+ const key = canonicalSettingKey(rawKey);
253
+ if (!key) {
254
+ return { ok: false, error: `Unknown setting '${rawKey}'.` };
255
+ }
256
+ const meta = SCHEMA_BY_KEY.get(key);
257
+ if (!meta || meta.type === "action") {
258
+ return { ok: false, error: `'${key}' cannot be set directly.` };
259
+ }
260
+
261
+ if (typeof rawValue === "boolean" && meta.type === "boolean") {
262
+ return { ok: true, key, value: rawValue };
263
+ }
264
+
265
+ const str = String(rawValue ?? "").trim();
266
+
267
+ if (meta.type === "boolean") {
268
+ if (/^(true|on|1|yes)$/i.test(str)) return { ok: true, key, value: true };
269
+ if (/^(false|off|0|no)$/i.test(str)) return { ok: true, key, value: false };
270
+ return { ok: false, error: `${meta.label} expects on/off or true/false (got '${str}').` };
271
+ }
272
+
273
+ if (meta.type === "enum") {
274
+ const match = meta.options.find((opt) => opt.toLowerCase() === str.toLowerCase());
275
+ if (!match) {
276
+ return {
277
+ ok: false,
278
+ error: `${meta.label} must be one of: ${meta.options.join(", ")}.`,
279
+ };
280
+ }
281
+ return { ok: true, key, value: match };
282
+ }
283
+
284
+ if (meta.type === "integer" || meta.type === "nullableInteger") {
285
+ if (meta.type === "nullableInteger" && (!str || /^(null|none|default|unset)$/i.test(str))) {
286
+ return { ok: true, key, value: null };
287
+ }
288
+ if (!/^-?\d+$/.test(str)) {
289
+ return { ok: false, error: `${meta.label} must be a whole number.` };
290
+ }
291
+ const n = Number.parseInt(str, 10);
292
+ if (!Number.isSafeInteger(n) || Number.isNaN(n)) {
293
+ return { ok: false, error: `${meta.label} is not a valid integer.` };
294
+ }
295
+ if (meta.min !== undefined && n < meta.min) {
296
+ return { ok: false, error: `${meta.label} must be >= ${meta.min}.` };
297
+ }
298
+ if (meta.max !== undefined && n > meta.max) {
299
+ return { ok: false, error: `${meta.label} must be <= ${meta.max}.` };
300
+ }
301
+ return { ok: true, key, value: n };
302
+ }
303
+
304
+ if (meta.type === "nullableFloat") {
305
+ if (!str || /^(null|none|default|unset)$/i.test(str)) {
306
+ return { ok: true, key, value: null };
307
+ }
308
+ const n = Number(str);
309
+ if (!Number.isFinite(n) || Number.isNaN(n)) {
310
+ return { ok: false, error: `${meta.label} must be a number or 'null'.` };
311
+ }
312
+ if (meta.min !== undefined && n < meta.min) {
313
+ return { ok: false, error: `${meta.label} must be >= ${meta.min}.` };
314
+ }
315
+ if (meta.max !== undefined && n > meta.max) {
316
+ return { ok: false, error: `${meta.label} must be <= ${meta.max}.` };
317
+ }
318
+ return { ok: true, key, value: n };
319
+ }
320
+
321
+ return { ok: true, key, value: typeof rawValue === "string" ? rawValue : str };
322
+ }
323
+
324
+ module.exports = {
325
+ AGENT_MODES,
326
+ TOOL_PERMISSIONS,
327
+ NON_WORKSPACE_MODES,
328
+ VERBOSITY_LEVELS,
329
+ LANGUAGES,
330
+ RENDERING_MODES,
331
+ QUEUED_MESSAGE_MODES,
332
+ COLOR_SCHEMES,
333
+ DEFAULT_SYSTEM_PROMPT,
334
+ DEFAULT_SETTINGS,
335
+ SETTINGS_SCHEMA,
336
+ SCHEMA_BY_KEY,
337
+ PERSISTABLE_KEYS,
338
+ canonicalSettingKey,
339
+ parseSettingValue,
340
+ };
@@ -0,0 +1,136 @@
1
+ "use strict";
2
+
3
+ const { ensureStorageDirs, readJsonSafe, atomicWriteJson, resolvePaths } = require("../config/paths");
4
+ const { DEFAULT_SETTINGS, PERSISTABLE_KEYS, SCHEMA_BY_KEY, parseSettingValue } = require("./schema");
5
+
6
+ /**
7
+ * Normalize loaded settings object against schema defaults without introducing runtime-only keys.
8
+ */
9
+ function sanitizePersistedObject(raw) {
10
+ const out = { ...DEFAULT_SETTINGS };
11
+ if (!raw || typeof raw !== "object") return out;
12
+
13
+ // Legacy compatibility: read old autoApprove=true only when agentMode was not explicitly stored.
14
+ if (raw.autoApprove === true && raw.agentMode === undefined) {
15
+ out.agentMode = "auto";
16
+ }
17
+
18
+ for (const key of PERSISTABLE_KEYS) {
19
+ if (raw[key] === undefined) continue;
20
+ const parsed = parseSettingValue(key, raw[key]);
21
+ if (parsed.ok) {
22
+ out[key] = parsed.value;
23
+ }
24
+ }
25
+ return out;
26
+ }
27
+
28
+ /**
29
+ * Load persisted settings strictly from settings.json (never includes CLI/session overrides).
30
+ */
31
+ function loadPersistedSettings(paths = resolvePaths()) {
32
+ const raw = readJsonSafe(paths.settingsFile, {});
33
+ return sanitizePersistedObject(raw);
34
+ }
35
+
36
+ /**
37
+ * Save strictly persistable fields to settings.json, stripping any runtime overrides or virtual keys.
38
+ */
39
+ function savePersistedSettings(settings, paths = resolvePaths()) {
40
+ ensureStorageDirs(paths);
41
+ const clean = sanitizePersistedObject(settings);
42
+ // Explicitly strip legacy autoApprove from disk whenever settings are written.
43
+ const toWrite = {};
44
+ for (const key of PERSISTABLE_KEYS) {
45
+ toWrite[key] = clean[key];
46
+ }
47
+ atomicWriteJson(paths.settingsFile, toWrite);
48
+ return clean;
49
+ }
50
+
51
+ /**
52
+ * Update a single persisted setting cleanly without touching or leaking active runtime overrides.
53
+ */
54
+ function updatePersistedSetting(key, rawValue, paths = resolvePaths()) {
55
+ const parsed = parseSettingValue(key, rawValue);
56
+ if (!parsed.ok) return parsed;
57
+ const currentPersisted = loadPersistedSettings(paths);
58
+ currentPersisted[parsed.key] = parsed.value;
59
+ const saved = savePersistedSettings(currentPersisted, paths);
60
+ return {
61
+ ok: true,
62
+ key: parsed.key,
63
+ value: saved[parsed.key],
64
+ settings: saved,
65
+ };
66
+ }
67
+
68
+ /**
69
+ * Cycle an enum or boolean setting to its next/previous value (used by Settings UI Left/Right keys).
70
+ */
71
+ function stepSettingValue(key, currentValue, direction = 1) {
72
+ const meta = SCHEMA_BY_KEY.get(key);
73
+ if (!meta) return null;
74
+ if (meta.type === "boolean") return !Boolean(currentValue);
75
+ if (meta.type === "enum" && Array.isArray(meta.options) && meta.options.length > 0) {
76
+ const idx = Math.max(0, meta.options.indexOf(currentValue));
77
+ const nextIdx = (idx + direction + meta.options.length) % meta.options.length;
78
+ return meta.options[nextIdx];
79
+ }
80
+ return null;
81
+ }
82
+
83
+ /**
84
+ * Resolve effective runtime settings by layering CLI flags and session overrides over persisted settings.
85
+ */
86
+ function resolveEffectiveSettings(persisted, runtimeOverrides = {}) {
87
+ const base = sanitizePersistedObject(persisted);
88
+ const effective = { ...base };
89
+
90
+ if (runtimeOverrides.cliAuto === true) {
91
+ effective.agentMode = "auto";
92
+ }
93
+ if (runtimeOverrides.cliMode) {
94
+ const parsed = parseSettingValue("agentMode", runtimeOverrides.cliMode);
95
+ if (parsed.ok) effective.agentMode = String(parsed.value);
96
+ }
97
+ if (runtimeOverrides.sessionAgentMode) {
98
+ const parsed = parseSettingValue("agentMode", runtimeOverrides.sessionAgentMode);
99
+ if (parsed.ok) effective.agentMode = String(parsed.value);
100
+ }
101
+ if (runtimeOverrides.sessionToolPermission) {
102
+ const parsed = parseSettingValue("toolPermission", runtimeOverrides.sessionToolPermission);
103
+ if (parsed.ok) effective.toolPermission = String(parsed.value);
104
+ }
105
+ if (runtimeOverrides.cliProvider) {
106
+ effective.provider = String(runtimeOverrides.cliProvider).trim();
107
+ }
108
+ return effective;
109
+ }
110
+
111
+ /**
112
+ * Resolve effective model using strict precedence:
113
+ * CLI flag > session model > saved setting > provider default.
114
+ */
115
+ function resolveEffectiveModel({
116
+ cliModel = "",
117
+ sessionModel = "",
118
+ persistedModel = "",
119
+ providerDefaultModel = "",
120
+ } = {}) {
121
+ for (const candidate of [cliModel, sessionModel, persistedModel, providerDefaultModel]) {
122
+ const clean = String(candidate || "").trim();
123
+ if (clean) return clean;
124
+ }
125
+ return "";
126
+ }
127
+
128
+ module.exports = {
129
+ sanitizePersistedObject,
130
+ loadPersistedSettings,
131
+ savePersistedSettings,
132
+ updatePersistedSetting,
133
+ stepSettingValue,
134
+ resolveEffectiveSettings,
135
+ resolveEffectiveModel,
136
+ };
@@ -0,0 +1,108 @@
1
+ "use strict";
2
+
3
+ const fs = require("node:fs");
4
+ const path = require("node:path");
5
+ const { safeId, readJsonSafe, atomicWriteJson, resolvePaths } = require("../config/paths");
6
+
7
+ const MAX_CHECKPOINTS_PER_SESSION = 25;
8
+
9
+ function checkpointFilePath(sessionId, paths = resolvePaths()) {
10
+ return path.join(paths.checkpointsDir, `${safeId(sessionId)}.json`);
11
+ }
12
+
13
+ function loadCheckpoints(sessionId, paths = resolvePaths()) {
14
+ const data = readJsonSafe(checkpointFilePath(sessionId, paths), { items: [] });
15
+ return Array.isArray(data?.items) ? data.items : [];
16
+ }
17
+
18
+ function saveCheckpoints(sessionId, items, paths = resolvePaths()) {
19
+ fs.mkdirSync(paths.checkpointsDir, { recursive: true });
20
+ atomicWriteJson(checkpointFilePath(sessionId, paths), {
21
+ sessionId: safeId(sessionId),
22
+ updatedAt: new Date().toISOString(),
23
+ items: items.slice(-MAX_CHECKPOINTS_PER_SESSION),
24
+ });
25
+ }
26
+
27
+ /**
28
+ * Snapshot the pre-mutation state of one or more target file paths before modifying/deleting them.
29
+ */
30
+ function recordCheckpoint({ sessionId = "default", toolName, filePaths = [], paths = resolvePaths() }) {
31
+ const snapshots = [];
32
+ const seen = new Set();
33
+
34
+ for (const raw of filePaths) {
35
+ if (!raw) continue;
36
+ const absPath = path.resolve(raw);
37
+ if (seen.has(absPath)) continue;
38
+ seen.add(absPath);
39
+
40
+ if (fs.existsSync(absPath)) {
41
+ const st = fs.statSync(absPath);
42
+ if (!st.isFile() || st.size > 5 * 1024 * 1024) continue;
43
+ snapshots.push({
44
+ absPath,
45
+ existed: true,
46
+ contentBase64: fs.readFileSync(absPath).toString("base64"),
47
+ });
48
+ } else {
49
+ snapshots.push({
50
+ absPath,
51
+ existed: false,
52
+ contentBase64: "",
53
+ });
54
+ }
55
+ }
56
+
57
+ if (!snapshots.length) return null;
58
+ const list = loadCheckpoints(sessionId, paths);
59
+ const entry = {
60
+ id: `${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
61
+ createdAt: new Date().toISOString(),
62
+ toolName,
63
+ snapshots,
64
+ };
65
+ list.push(entry);
66
+ saveCheckpoints(sessionId, list, paths);
67
+ return entry;
68
+ }
69
+
70
+ /**
71
+ * Restore the latest recorded file checkpoint for the active session (/undo).
72
+ */
73
+ function undoLastCheckpoint(sessionId = "default", paths = resolvePaths(), workspaceRoot = process.cwd()) {
74
+ const list = loadCheckpoints(sessionId, paths);
75
+ if (!list.length) return { ok: false, message: "Nothing to undo in this session." };
76
+
77
+ const latest = list.pop();
78
+ const restored = [];
79
+
80
+ for (const snap of latest.snapshots || []) {
81
+ const rel = path.relative(workspaceRoot, snap.absPath) || snap.absPath;
82
+ if (snap.existed) {
83
+ fs.mkdirSync(path.dirname(snap.absPath), { recursive: true });
84
+ fs.writeFileSync(snap.absPath, Buffer.from(snap.contentBase64, "base64"));
85
+ restored.push(`restored ${rel}`);
86
+ } else {
87
+ if (fs.existsSync(snap.absPath)) {
88
+ fs.rmSync(snap.absPath, { force: true });
89
+ }
90
+ restored.push(`removed created ${rel}`);
91
+ }
92
+ }
93
+
94
+ saveCheckpoints(sessionId, list, paths);
95
+ return {
96
+ ok: true,
97
+ toolName: latest.toolName,
98
+ restored,
99
+ remaining: list.length,
100
+ message: `Undid ${latest.toolName}: ${restored.join(", ")} (${list.length} checkpoint(s) remaining)`,
101
+ };
102
+ }
103
+
104
+ module.exports = {
105
+ loadCheckpoints,
106
+ recordCheckpoint,
107
+ undoLastCheckpoint,
108
+ };