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,782 @@
1
+ "use strict";
2
+
3
+ const fs = require("node:fs");
4
+ const path = require("node:path");
5
+ const {
6
+ loadGlobalMemory,
7
+ saveGlobalMemory,
8
+ addGlobalMemory,
9
+ classifyMemoryIntent,
10
+ saveSession,
11
+ renameSession,
12
+ suggestSessionIdFromPrompt,
13
+ evaluatePermission,
14
+ buildSuggestedRules,
15
+ addPermissionRule,
16
+ loadProviders,
17
+ } = require("../../store");
18
+ const { TOOL_DEFINITIONS, executeTool, capOutput } = require("../../tools");
19
+ const { streamProviderTurn, completeProviderFast } = require("../../providers");
20
+ const { estimateMessagesTokens, sliceValidHistory } = require("./history");
21
+ const { gatherEnvironmentSummary, loadProjectInstructions } = require("./project_context");
22
+ const { repairToolArguments, LoopDetector } = require("./resilience");
23
+ const { summarizeArgsShort, getEnvFallback } = require("../commands/handlers");
24
+
25
+ function createAbortError(message = "Task cancelled by user") {
26
+ const err = new Error(message);
27
+ err.name = "AbortError";
28
+ err.aborted = true;
29
+ return err;
30
+ }
31
+
32
+ function expandFileMentions(text, workspaceRoot = process.cwd()) {
33
+ const matches = [...String(text || "").matchAll(/(?:^|\s)@([^\s]+)/g)];
34
+ if (!matches.length) return text;
35
+ const attached = [];
36
+ const seen = new Set();
37
+ for (const m of matches) {
38
+ const rawSpec = m[1].replace(/[.,;:!?]+$/, "");
39
+ if (!rawSpec || seen.has(rawSpec)) continue;
40
+ seen.add(rawSpec);
41
+ let rel = rawSpec;
42
+ let lineStart = null;
43
+ let lineEnd = null;
44
+ const rangeMatch = rawSpec.match(/^(.+?):L?(\d+)(?:-L?(\d+))?$/i);
45
+ if (rangeMatch) {
46
+ rel = rangeMatch[1];
47
+ lineStart = Math.max(1, Number.parseInt(rangeMatch[2], 10));
48
+ lineEnd = rangeMatch[3] ? Math.max(lineStart, Number.parseInt(rangeMatch[3], 10)) : lineStart;
49
+ }
50
+ const abs = path.resolve(workspaceRoot, rel);
51
+ try {
52
+ if (fs.statSync(abs).isFile()) {
53
+ const rawText = fs.readFileSync(abs, "utf8");
54
+ if (lineStart !== null) {
55
+ const lines = rawText.split(/\r?\n/);
56
+ const slice = lines
57
+ .slice(lineStart - 1, lineEnd)
58
+ .map((ln, idx) => `${lineStart + idx}: ${ln}`)
59
+ .join("\n");
60
+ attached.push(
61
+ `--- File: ${rel} (Lines ${lineStart}-${Math.min(lineEnd, lines.length)}) ---\n${capOutput(slice)}`
62
+ );
63
+ } else {
64
+ attached.push(`--- File: ${rel} ---\n${capOutput(rawText)}`);
65
+ }
66
+ }
67
+ } catch {}
68
+ }
69
+ return attached.length ? `${text}\n\n${attached.join("\n\n")}` : text;
70
+ }
71
+
72
+ function buildRequestMessages(state) {
73
+ const root = state.workspaceRoot || process.cwd();
74
+ const sysParts = [
75
+ state.settings.systemPrompt,
76
+ `Workspace Root: ${root}\nEnvironment: ${gatherEnvironmentSummary(root)}`,
77
+ ];
78
+ const projectDocs = loadProjectInstructions(root);
79
+ if (projectDocs) sysParts.push(projectDocs);
80
+ if (state.settings.language) {
81
+ const langMap = {
82
+ banglish: "Language Preference: Respond in Banglish (Bengali written cleanly in Latin/Roman alphabet).",
83
+ bangla: "Language Preference: Respond in Bengali.",
84
+ english: "Language Preference: Respond in clear English.",
85
+ };
86
+ if (langMap[state.settings.language]) sysParts.push(langMap[state.settings.language]);
87
+ }
88
+ if (state.settings.agentMode === "plan") {
89
+ sysParts.push(
90
+ [
91
+ "AGENT MODE = PLAN (STRICT READ-ONLY RESEARCH):",
92
+ "1. Investigate the codebase/task using read-only tools only. Do NOT modify files or run mutating commands.",
93
+ "2. Output a clear, structured implementation plan containing: Goal, Files to Change, Steps, Risks, and How to Verify.",
94
+ "3. Stop and ask the user to approve the plan before any edits.",
95
+ ].join("\n")
96
+ );
97
+ }
98
+
99
+ const msgs = [{ role: "system", content: sysParts.join("\n\n") }];
100
+
101
+ const globalMem = loadGlobalMemory(state.paths);
102
+ if (globalMem.length) {
103
+ msgs.push({
104
+ role: "system",
105
+ content: `[Global Default Memory (shared)]\n${globalMem.map((x, i) => `${i + 1}. ${x}`).join("\n")}`,
106
+ });
107
+ }
108
+
109
+ const sessionBlocks = [];
110
+ if (state.session.summaryMemory) {
111
+ sessionBlocks.push(`[Session '${state.session.id}' Memory Summary]\n${state.session.summaryMemory}`);
112
+ }
113
+ if (state.session.pinnedMemory.length) {
114
+ sessionBlocks.push(
115
+ `[Session '${state.session.id}' Pinned Local Facts]\n${state.session.pinnedMemory.map((x) => `- ${x}`).join("\n")}`
116
+ );
117
+ }
118
+ if (state.session.todos.length) {
119
+ const todoLines = state.session.todos.map((t, i) => `${i + 1}. [${t.status}] ${t.task}`).join("\n");
120
+ sessionBlocks.push(`[Session '${state.session.id}' Multi-Step Todos]\n${todoLines}`);
121
+ }
122
+ if (sessionBlocks.length) {
123
+ msgs.push({ role: "system", content: sessionBlocks.join("\n\n") });
124
+ }
125
+
126
+ const win = Number(state.settings.contextWindow) || 128000;
127
+ const overhead = estimateMessagesTokens(msgs);
128
+ const histBudget = Math.max(2048, Math.floor(win * 0.78) - overhead);
129
+ const recent = sliceValidHistory(state.session.history, state.settings.maxHistoryMessages, histBudget);
130
+ return [...msgs, ...recent];
131
+ }
132
+
133
+ function formatEditDiffPreview(target = "", replacement = "") {
134
+ const tLines = String(target)
135
+ .split("\n")
136
+ .slice(0, 6)
137
+ .map((l) => ` - ${l}`);
138
+ const rLines = String(replacement)
139
+ .split("\n")
140
+ .slice(0, 6)
141
+ .map((l) => ` + ${l}`);
142
+ const moreT = String(target).split("\n").length > 6 ? [" - ..."] : [];
143
+ const moreR = String(replacement).split("\n").length > 6 ? [" + ..."] : [];
144
+ return [...tLines, ...moreT, ...rLines, ...moreR].join("\n");
145
+ }
146
+
147
+ /**
148
+ * Render detailed, non-truncated permission preview with risk label, full command, edit diff, or write preview (A3).
149
+ */
150
+ function formatApprovalPreview(toolName, rawArgs, evalResult) {
151
+ let args = {};
152
+ try {
153
+ args = typeof rawArgs === "string" ? JSON.parse(rawArgs || "{}") : rawArgs || {};
154
+ } catch {}
155
+
156
+ const risk = evalResult?.risk || "MEDIUM";
157
+ const lines = [`[Permission Required · Risk: ${risk}] Tool: ${toolName}`];
158
+ if (evalResult?.reason) lines.push(`Reason: ${evalResult.reason}`);
159
+
160
+ if (toolName === "run_command") {
161
+ lines.push(`Command:\n ${String(args.command || "")}`);
162
+ } else if (toolName === "write_file") {
163
+ const content = String(args.content || "");
164
+ const preview = content.split("\n").slice(0, 8).join("\n");
165
+ lines.push(`File: ${args.path} (${Buffer.byteLength(content, "utf8")} bytes)`);
166
+ lines.push(`Preview:\n${preview.slice(0, 500)}${content.length > 500 ? "\n ..." : ""}`);
167
+ } else if (toolName === "edit_file") {
168
+ lines.push(`File: ${args.path}`);
169
+ lines.push(`Diff:\n${formatEditDiffPreview(args.target, args.replacement)}`);
170
+ } else if (toolName === "multi_edit") {
171
+ lines.push(`File: ${args.path} (${Array.isArray(args.edits) ? args.edits.length : 0} edits)`);
172
+ if (Array.isArray(args.edits) && args.edits[0]) {
173
+ lines.push(`First edit diff:\n${formatEditDiffPreview(args.edits[0].target, args.edits[0].replacement)}`);
174
+ }
175
+ } else if (toolName === "delete_file") {
176
+ lines.push(`Delete file: ${args.path}`);
177
+ } else if (toolName === "download_file" || toolName === "web_fetch") {
178
+ lines.push(`URL: ${args.url}`);
179
+ } else {
180
+ lines.push(`Args: ${JSON.stringify(args)}`);
181
+ }
182
+ return lines.join("\n");
183
+ }
184
+
185
+ function getProviderSecretEnvKeys(state) {
186
+ try {
187
+ const store = loadProviders(getEnvFallback(), state.paths);
188
+ return Object.values(store.providers || {})
189
+ .map((p) => p.apiKeyEnv)
190
+ .filter(Boolean);
191
+ } catch {
192
+ return [];
193
+ }
194
+ }
195
+
196
+ async function waitForMemorySync(state) {
197
+ if (state.memorySyncPromise) {
198
+ try {
199
+ await state.memorySyncPromise;
200
+ } catch {}
201
+ }
202
+ }
203
+
204
+ async function updateSessionMemory(state, userText, assistantText, toolsUsed, sink, options = {}) {
205
+ if (!state.settings.autoSummarize && !options.force) return;
206
+ if (state.headless || state.noSession) return;
207
+
208
+ const prev = state.session.summaryMemory || "(none)";
209
+ const toolNote = toolsUsed.length ? `\nTools used: ${toolsUsed.join(", ")}` : "";
210
+ const digestPrompt = [
211
+ {
212
+ role: "system",
213
+ content:
214
+ "Maintain a concise rolling memory summary for THIS session only (max 180 words). Merge the previous summary with the new exchange, keeping goals, decisions, file paths, facts, and outcomes. Output ONLY the updated summary.",
215
+ },
216
+ {
217
+ role: "user",
218
+ content: `Previous summary:\n${prev}\n\nNew User message:\n${userText.slice(0, 1500)}${toolNote}\n\nAssistant response:\n${assistantText.slice(0, 2000)}`,
219
+ },
220
+ ];
221
+
222
+ const abortCtrl = new AbortController();
223
+ state.memoryAbort = abortCtrl;
224
+
225
+ const job = (async () => {
226
+ try {
227
+ const summary = await completeProviderFast({
228
+ provider: state.provider,
229
+ model: state.model,
230
+ messages: digestPrompt,
231
+ maxTokens: 300,
232
+ temperature: 0.2,
233
+ signal: abortCtrl.signal,
234
+ capabilities: state.capabilities,
235
+ toolDefinitions: TOOL_DEFINITIONS,
236
+ timeoutMs: 25000,
237
+ });
238
+ if (abortCtrl.signal.aborted) return;
239
+ if (summary) {
240
+ state.session.summaryMemory = summary;
241
+ saveSession(state.session, state.paths);
242
+ sink.syncStatus();
243
+ sink.log("meta", `🧠 Session '${state.session.id}' memory updated`);
244
+ return;
245
+ }
246
+ } catch (err) {
247
+ if (abortCtrl.signal.aborted || err?.name === "AbortError") return;
248
+ }
249
+
250
+ const snippet = `- User: ${userText.replace(/\s+/g, " ").slice(0, 120)} -> AI: ${assistantText.replace(/\s+/g, " ").slice(0, 160)}`;
251
+ const merged = state.session.summaryMemory ? `${state.session.summaryMemory}\n${snippet}` : snippet;
252
+ state.session.summaryMemory = merged.slice(-2000);
253
+ saveSession(state.session, state.paths);
254
+ sink.syncStatus();
255
+ if (options.verbose !== false) {
256
+ sink.log("meta", `🧠 Session '${state.session.id}' memory saved (local fallback)`);
257
+ }
258
+ })().finally(() => {
259
+ if (state.memorySyncPromise === job) state.memorySyncPromise = null;
260
+ if (state.memoryAbort === abortCtrl) state.memoryAbort = null;
261
+ });
262
+
263
+ state.memorySyncPromise = job;
264
+ if (options.blocking) await job;
265
+ }
266
+
267
+ async function runToolCalls(state, toolCalls, sink) {
268
+ const results = new Array(toolCalls.length);
269
+ const parallelBatch = [];
270
+ const workspaceRoot = state.workspaceRoot || process.cwd();
271
+ const extraSecretEnvKeys = getProviderSecretEnvKeys(state);
272
+
273
+ const isAutoMode = () => state.settings.agentMode === "auto" || state.settings.toolPermission === "always-proceed";
274
+
275
+ const makeCtx = (approvedByUser = false, skipDownloadDestPrompt = false, onToolOutput = null) => ({
276
+ cwd: workspaceRoot,
277
+ workspaceRoot,
278
+ paths: state.paths,
279
+ extraDirs: state.extraDirs || [],
280
+ extraSecretEnvKeys,
281
+ settings: state.settings,
282
+ session: state.session,
283
+ autoApprove: isAutoMode(),
284
+ approvedByUser: approvedByUser || isAutoMode(),
285
+ skipDownloadDestPrompt: skipDownloadDestPrompt || isAutoMode(),
286
+ onToolOutput,
287
+ openChoicePicker: sink.openChoicePicker,
288
+ bgTasks: state.bgTasks || null,
289
+ _permissionChecked: true,
290
+ signal: state.activeAbort?.signal || null,
291
+ saveSession: (s) => {
292
+ if (!state.noSession) saveSession(s, state.paths);
293
+ },
294
+ loadGlobalMemory: () => loadGlobalMemory(state.paths),
295
+ saveGlobalMemory: (items) => saveGlobalMemory(items, state.paths),
296
+ addGlobalMemory: (fact, src) => addGlobalMemory(fact, src, state.paths),
297
+ getSudoPassword: () => state.sudoPasswords.get(state.session.id) || "",
298
+ setSudoPassword: (pw) => {
299
+ if (pw) state.sudoPasswords.set(state.session.id, pw);
300
+ else state.sudoPasswords.delete(state.session.id);
301
+ },
302
+ askPrompt: sink.askPrompt,
303
+ askPassword: sink.askPassword,
304
+ startProgress: sink.startProgress,
305
+ setBusy: sink.setBusy,
306
+ log: sink.log,
307
+ });
308
+
309
+ let downloadFailedOrCancelled = false;
310
+
311
+ const flushParallel = async () => {
312
+ if (!parallelBatch.length) return;
313
+ const batch = parallelBatch.splice(0, parallelBatch.length);
314
+ await Promise.all(batch);
315
+ };
316
+
317
+ for (let i = 0; i < toolCalls.length; i++) {
318
+ if (state.activeAbort?.signal?.aborted) {
319
+ await flushParallel();
320
+ throw createAbortError();
321
+ }
322
+ const tc = toolCalls[i];
323
+ const name = tc.function.name;
324
+ const summary = summarizeArgsShort(tc.function.arguments);
325
+
326
+ // If an earlier download in the same turn was cancelled or failed, never execute follow-up commands on missing files.
327
+ if (downloadFailedOrCancelled && name === "run_command") {
328
+ const msg = "Skipped command because the preceding download did not complete.";
329
+ results[i] = { role: "tool", tool_call_id: tc.id, name, content: msg };
330
+ sink.log("tool", `⏸ ${name}(${summary}) skipped (download incomplete)`);
331
+ continue;
332
+ }
333
+ let parsedArgs = {};
334
+ try {
335
+ parsedArgs =
336
+ typeof tc.function.arguments === "string"
337
+ ? repairToolArguments(tc.function.arguments || "{}")
338
+ : tc.function.arguments || {};
339
+ } catch {}
340
+
341
+ const evalRes = evaluatePermission({
342
+ toolName: name,
343
+ args: parsedArgs,
344
+ settings: state.settings,
345
+ workspaceRoot,
346
+ extraDirs: state.extraDirs || [],
347
+ sessionRules: state.sessionRules,
348
+ paths: state.paths,
349
+ });
350
+
351
+ if (evalRes.decision === "block") {
352
+ results[i] = {
353
+ role: "tool",
354
+ tool_call_id: tc.id,
355
+ name,
356
+ content: evalRes.reason,
357
+ };
358
+ sink.log("tool", `⛔ ${name}(${summary}) blocked: ${evalRes.reason}`);
359
+ continue;
360
+ }
361
+
362
+ let approvedByUser = false;
363
+ let skipDownloadDestPrompt = Boolean(evalRes.matchedRule);
364
+
365
+ if (evalRes.decision === "ask") {
366
+ if (!sink.interactive || !sink.confirm) {
367
+ results[i] = {
368
+ role: "tool",
369
+ tool_call_id: tc.id,
370
+ name,
371
+ content: `Denied: '${name}' requires interactive approval (${evalRes.reason}).`,
372
+ };
373
+ sink.log("tool", `✗ ${name}(${summary}) requires approval`);
374
+ continue;
375
+ }
376
+
377
+ const preview = formatApprovalPreview(name, parsedArgs, evalRes);
378
+ sink.log("permission", preview);
379
+ sink.notify?.();
380
+ const rawChoice = (await sink.confirm(`Allow ${name}? [y=once / n=deny / s=session / A=always]: `)).trim();
381
+ if (state.activeAbort?.signal?.aborted) {
382
+ throw createAbortError();
383
+ }
384
+ const lowerChoice = rawChoice.toLowerCase();
385
+
386
+ if (lowerChoice === "y" || lowerChoice === "yes") {
387
+ approvedByUser = true;
388
+ } else if ((lowerChoice === "s" || rawChoice === "A") && !evalRes.hardDenied && !evalRes.requiresSudo) {
389
+ approvedByUser = true;
390
+ const suggestions = buildSuggestedRules(name, parsedArgs, workspaceRoot);
391
+ const defRule = suggestions[0];
392
+ const altHint = suggestions.length > 1 ? ` or type 'tool' for all ${name}` : "";
393
+ const scopeAns = (
394
+ await sink.confirm(
395
+ `Save ${lowerChoice === "s" ? "session" : "always (project)"} allow rule for ${defRule.label}${altHint}? [Enter=yes / n=once only]: `
396
+ )
397
+ )
398
+ .trim()
399
+ .toLowerCase();
400
+
401
+ if (scopeAns !== "n" && scopeAns !== "no") {
402
+ const picked =
403
+ scopeAns === "tool" && suggestions[suggestions.length - 1]
404
+ ? suggestions[suggestions.length - 1].rule
405
+ : defRule.rule;
406
+ if (lowerChoice === "s") {
407
+ state.sessionRules.push(picked);
408
+ sink.log(
409
+ "meta",
410
+ `✓ session rule added: ${picked.tool} (${picked.scope}: ${picked.pattern || "*"})`
411
+ );
412
+ } else {
413
+ addPermissionRule(picked, "project", state.paths);
414
+ sink.log(
415
+ "meta",
416
+ `✓ project rule saved: ${picked.tool} (${picked.scope}: ${picked.pattern || "*"})`
417
+ );
418
+ }
419
+ skipDownloadDestPrompt = true;
420
+ }
421
+ } else if ((lowerChoice === "s" || rawChoice === "A") && (evalRes.hardDenied || evalRes.requiresSudo)) {
422
+ approvedByUser = true;
423
+ sink.log(
424
+ "meta",
425
+ "Note: hard-denylist/sudo commands are allowed once (cannot be permanently auto-allowed)."
426
+ );
427
+ } else {
428
+ results[i] = { role: "tool", tool_call_id: tc.id, name, content: "Denied by user." };
429
+ sink.log("tool", `✗ ${name}(${summary}) denied`);
430
+ continue;
431
+ }
432
+ } else if (evalRes.matchedRule && evalRes.ruleLabel) {
433
+ sink.log("meta", `✓ auto-allowed by rule: ${evalRes.ruleLabel}`);
434
+ }
435
+
436
+ const isSequential =
437
+ evalRes.decision === "ask" ||
438
+ name === "run_command" ||
439
+ name === "download_file" ||
440
+ name === "write_file" ||
441
+ name === "edit_file" ||
442
+ name === "multi_edit" ||
443
+ name === "delete_file";
444
+
445
+ const runOne = async () => {
446
+ const toolUi =
447
+ name !== "download_file" && sink.startToolCall
448
+ ? sink.startToolCall(`⚙ ${name}(${summary})`, { collapsible: true })
449
+ : null;
450
+ if (!toolUi && name !== "download_file") {
451
+ sink.log("tool", `⚙ ${name}(${summary})`);
452
+ }
453
+ if (name === "download_file") {
454
+ state.isDownloading = true;
455
+ sink.setBusy("Downloading (commands paused)...");
456
+ }
457
+ try {
458
+ const out = await executeTool(
459
+ name,
460
+ parsedArgs,
461
+ makeCtx(approvedByUser, skipDownloadDestPrompt, (chunk) => toolUi?.pushOutput(chunk))
462
+ );
463
+ const outStr = String(out);
464
+ results[i] = { role: "tool", tool_call_id: tc.id, name, content: outStr };
465
+ toolUi?.finish(outStr, /^Exit |^Command timed out/i.test(outStr));
466
+ if (name === "download_file" && /^Download cancelled/i.test(outStr)) {
467
+ downloadFailedOrCancelled = true;
468
+ }
469
+ } catch (err) {
470
+ if (state.activeAbort?.signal?.aborted || err?.aborted || err?.name === "AbortError") {
471
+ toolUi?.finish("Aborted by user", true);
472
+ throw createAbortError(err?.message || "Task cancelled by user");
473
+ }
474
+ if (name === "download_file") downloadFailedOrCancelled = true;
475
+ results[i] = { role: "tool", tool_call_id: tc.id, name, content: `Error: ${err.message}` };
476
+ toolUi?.finish(`Error: ${err.message}`, true);
477
+ sink.log("error", `✗ ${name}: ${err.message}`);
478
+ } finally {
479
+ if (name === "download_file") {
480
+ state.isDownloading = false;
481
+ sink.syncStatus();
482
+ }
483
+ }
484
+ };
485
+
486
+ if (isSequential) {
487
+ // Ensure no background parallel tool writes to screen while sequential download/command executes.
488
+ await flushParallel();
489
+ await runOne();
490
+ } else {
491
+ parallelBatch.push(runOne());
492
+ }
493
+ }
494
+
495
+ await flushParallel();
496
+ return results;
497
+ }
498
+
499
+ function repairTranscriptTail(history, dropTrailingUser = false) {
500
+ // Keep completed steps intact; trim trailing unfulfilled tool_calls or orphan tool messages so /retry & resume work cleanly.
501
+ while (history.length > 0) {
502
+ const last = history[history.length - 1];
503
+ if (last.role === "assistant" && Array.isArray(last.tool_calls) && last.tool_calls.length > 0) {
504
+ history.pop();
505
+ continue;
506
+ }
507
+ break;
508
+ }
509
+ if (dropTrailingUser && history.length > 0 && history[history.length - 1].role === "user") {
510
+ history.pop();
511
+ }
512
+ }
513
+
514
+ async function runAgentTurn(state, userText, sink, options = {}) {
515
+ state.lastFailedPrompt = "";
516
+ const workspaceRoot = state.workspaceRoot || process.cwd();
517
+
518
+ // B4: Explicit memory intent ONLY, with user confirmation
519
+ if (!options.isRetry) {
520
+ const memIntent = classifyMemoryIntent(userText);
521
+ if (memIntent) {
522
+ const autoMode = state.settings.agentMode === "auto" || state.settings.toolPermission === "always-proceed";
523
+ let allowSave = true;
524
+ if (!memIntent.explicitCommand && !autoMode && sink.interactive && sink.confirm) {
525
+ const ans = (await sink.confirm(`Save to ${memIntent.scope} memory: "${memIntent.fact}"? [y/n]: `))
526
+ .trim()
527
+ .toLowerCase();
528
+ allowSave = ans === "y" || ans === "yes";
529
+ }
530
+ if (allowSave) {
531
+ if (memIntent.scope === "global" && addGlobalMemory(memIntent.fact, "user", state.paths)) {
532
+ sink.log("meta", `🌐 Saved to Global Shared Memory`);
533
+ } else if (memIntent.scope === "session" && !state.session.pinnedMemory.includes(memIntent.fact)) {
534
+ state.session.pinnedMemory.push(memIntent.fact);
535
+ if (!state.noSession) saveSession(state.session, state.paths);
536
+ sink.log("meta", `📌 Saved to Session '${state.session.id}' local memory`);
537
+ }
538
+ }
539
+ }
540
+ }
541
+
542
+ const expanded = expandFileMentions(userText, workspaceRoot);
543
+ if (!state.session.title && !options.isRetry) {
544
+ const cleanTitle = String(userText || "")
545
+ .replace(/\s+/g, " ")
546
+ .trim()
547
+ .slice(0, 60);
548
+ if (cleanTitle) {
549
+ state.session.title = cleanTitle;
550
+ if (/^session-\d{8}-\d{6}-[a-z0-9]+$/i.test(state.session.id) && state.paths) {
551
+ const nextId = suggestSessionIdFromPrompt(userText, state.paths);
552
+ if (state.noSession) {
553
+ state.session.id = nextId;
554
+ } else {
555
+ renameSession(state.session, nextId, state.paths);
556
+ }
557
+ sink.syncStatus();
558
+ }
559
+ }
560
+ }
561
+ if (state.debug) {
562
+ sink.log(
563
+ "meta",
564
+ `[debug] turn start · model=${state.model} · mode=${state.settings.agentMode} · history=${state.session.history.length}`
565
+ );
566
+ }
567
+ state.session.history.push({ role: "user", content: expanded });
568
+ const toolsUsed = [];
569
+ let finalAssistantText = "";
570
+ let lastUsage = null;
571
+ let totalTurnMs = 0;
572
+ let emptyRetried = false;
573
+
574
+ // Keep one AbortController alive across BOTH LLM streaming and all tool executions (download_file, run_command, etc.)
575
+ const turnAbort = new AbortController();
576
+ state.activeAbort = turnAbort;
577
+
578
+ try {
579
+ const maxSteps = Math.max(1, Number(state.settings.maxToolSteps) || 25);
580
+ const loopDetector = new LoopDetector(3);
581
+ for (let step = 0; step < maxSteps; step++) {
582
+ if (turnAbort.signal.aborted) throw createAbortError();
583
+ sink.setBusy(step ? `Step ${step + 1}...` : "Thinking...");
584
+ const reqMessages = buildRequestMessages(state);
585
+ const ctxEst = estimateMessagesTokens(reqMessages);
586
+ const ctxWin = state.settings.contextWindow || 128000;
587
+ if (state.settings.verbosity === "high" && step > 0) {
588
+ sink.log("meta", `[verbose] Step ${step + 1}/${maxSteps} · ~${ctxEst} tokens`);
589
+ }
590
+
591
+ const turn = await streamProviderTurn({
592
+ provider: state.provider,
593
+ model: state.model,
594
+ settings: state.settings,
595
+ messages: reqMessages,
596
+ signal: turnAbort.signal,
597
+ sink,
598
+ capabilities: state.capabilities,
599
+ toolDefinitions: TOOL_DEFINITIONS,
600
+ });
601
+ if (turnAbort.signal.aborted) throw createAbortError();
602
+
603
+ totalTurnMs += turn.elapsedMs;
604
+ lastUsage = turn.usage;
605
+ state.session.stats.requests += 1;
606
+ state.session.stats.totalMs += turn.elapsedMs;
607
+ state.session.stats.lastTtftMs = turn.ttftMs;
608
+ state.session.stats.lastTokPerSec = turn.tokPerSec;
609
+ if (turn.usage) {
610
+ state.session.stats.promptTokens += turn.usage.prompt_tokens || 0;
611
+ state.session.stats.completionTokens += turn.usage.completion_tokens || 0;
612
+ }
613
+
614
+ // B14: Guard against empty silent assistant response
615
+ if (!turn.toolCalls.length && !turn.content) {
616
+ if (!emptyRetried) {
617
+ emptyRetried = true;
618
+ state.session.history.push({
619
+ role: "user",
620
+ content:
621
+ "You returned an empty response. Provide a helpful final answer or call an appropriate tool.",
622
+ });
623
+ continue;
624
+ }
625
+ throw new Error("Model returned an empty response.");
626
+ }
627
+
628
+ const assistantMsg = { role: "assistant", content: turn.content || "" };
629
+ if (turn.toolCalls.length) assistantMsg.tool_calls = turn.toolCalls;
630
+ state.session.history.push(assistantMsg);
631
+
632
+ if (!turn.toolCalls.length) {
633
+ finalAssistantText = turn.content;
634
+ const sec = (turn.elapsedMs / 1000).toFixed(2);
635
+ const ttftStr = turn.ttftMs >= 1000 ? `${(turn.ttftMs / 1000).toFixed(2)}s` : `${turn.ttftMs}ms`;
636
+ const speedStr = turn.tokPerSec ? ` · ${turn.tokPerSec} tok/s` : "";
637
+ const ctxStr = ` · Context: ~${turn.usage?.prompt_tokens || ctxEst} / ${ctxWin}`;
638
+ const usageStr = turn.usage
639
+ ? ` · Tokens: ${turn.usage.prompt_tokens ?? 0} in, ${turn.usage.completion_tokens ?? 0} out`
640
+ : ` · Output: ~${turn.outTokens} tok`;
641
+ if (state.settings.verbosity !== "low") {
642
+ sink.log("meta", `Response: ${sec}s · TTFT: ${ttftStr}${speedStr}${ctxStr}${usageStr}`);
643
+ }
644
+ if (turn.elapsedMs >= 5000) sink.notify?.();
645
+
646
+ // A2: Structured Plan Approval Workflow when finishing in 'plan' mode
647
+ if (state.settings.agentMode === "plan" && sink.interactive && sink.confirm) {
648
+ const ans = (
649
+ await sink.confirm(
650
+ "Approve plan? [1=accept-edits / 2=auto / 3=default / 4=keep planning / 5=cancel]: "
651
+ )
652
+ )
653
+ .trim()
654
+ .toLowerCase();
655
+ if (ans === "1" || ans === "accept-edits" || ans === "y") {
656
+ state.settings.agentMode = "accept-edits";
657
+ state.session.agentMode = "accept-edits";
658
+ sink.syncStatus();
659
+ sink.log("meta", "✓ Plan approved — switched to 'accept-edits' mode. Continuing...");
660
+ state.session.history.push({
661
+ role: "user",
662
+ content:
663
+ "Plan approved. Switched to accept-edits mode. Proceed with implementing the plan now.",
664
+ });
665
+ continue;
666
+ }
667
+ if (ans === "2" || ans === "auto") {
668
+ state.settings.agentMode = "auto";
669
+ state.session.agentMode = "auto";
670
+ sink.syncStatus();
671
+ sink.log("meta", "✓ Plan approved — switched to 'auto' mode. Continuing...");
672
+ state.session.history.push({
673
+ role: "user",
674
+ content: "Plan approved. Switched to auto mode. Proceed with implementing the plan now.",
675
+ });
676
+ continue;
677
+ }
678
+ if (ans === "3" || ans === "default") {
679
+ state.settings.agentMode = "default";
680
+ state.session.agentMode = "default";
681
+ sink.syncStatus();
682
+ sink.log("meta", "✓ Plan approved — switched to 'default' mode. Continuing...");
683
+ state.session.history.push({
684
+ role: "user",
685
+ content: "Plan approved. Switched to default mode. Proceed step-by-step now.",
686
+ });
687
+ continue;
688
+ }
689
+ if (ans === "4") {
690
+ sink.log("meta", "Staying in 'plan' mode. Ask follow-up refinements in your next message.");
691
+ }
692
+ }
693
+
694
+ if (!state.noSession) saveSession(state.session, state.paths);
695
+ sink.syncStatus();
696
+ // B20: Trigger non-blocking background session memory update
697
+ void updateSessionMemory(state, userText, turn.content, toolsUsed, sink, {
698
+ blocking: false,
699
+ verbose: state.settings.verbosity === "high",
700
+ });
701
+ return {
702
+ ok: true,
703
+ answer: finalAssistantText,
704
+ toolsUsed,
705
+ usage: lastUsage,
706
+ elapsedMs: totalTurnMs,
707
+ };
708
+ }
709
+
710
+ for (const tc of turn.toolCalls) toolsUsed.push(tc.function.name);
711
+ const loopCheck = loopDetector.record(turn.toolCalls);
712
+ if (loopCheck.repeated) {
713
+ sink.log(
714
+ "system",
715
+ `⚠ Detected repeated identical tool calls (${loopCheck.count}x). Asking model to try a different approach or summarize.`
716
+ );
717
+ state.session.history.push({
718
+ role: "user",
719
+ content:
720
+ "You have repeated the exact same tool call multiple times without making progress. Do NOT repeat it again — either try a different approach/arguments or explain the blocker to the user.",
721
+ });
722
+ if (!state.noSession) saveSession(state.session, state.paths);
723
+ continue;
724
+ }
725
+ sink.setBusy("Running tools...");
726
+ const toolResults = await runToolCalls(state, turn.toolCalls, sink);
727
+ if (turnAbort.signal.aborted) throw createAbortError();
728
+ state.session.history.push(...toolResults);
729
+ if (!state.noSession) saveSession(state.session, state.paths);
730
+ sink.syncStatus();
731
+ }
732
+
733
+ sink.log("system", `Reached maxToolSteps (${state.settings.maxToolSteps}).`);
734
+ if (!state.noSession) saveSession(state.session, state.paths);
735
+ return { ok: true, answer: finalAssistantText, toolsUsed, usage: lastUsage, elapsedMs: totalTurnMs };
736
+ } catch (err) {
737
+ const isAbort = Boolean(turnAbort.signal.aborted || err?.name === "AbortError" || err?.aborted);
738
+ // When user cancels, drop unanswered trailing user turn because the prompt is restored directly into the input box
739
+ repairTranscriptTail(state.session.history, isAbort);
740
+ state.lastFailedPrompt = userText;
741
+ if (!state.noSession) saveSession(state.session, state.paths);
742
+ sink.syncStatus();
743
+ if (isAbort && err?.name !== "AbortError") {
744
+ throw createAbortError(err?.message || "Task cancelled by user");
745
+ }
746
+ throw err;
747
+ } finally {
748
+ if (state.activeAbort === turnAbort) state.activeAbort = null;
749
+ }
750
+ }
751
+
752
+ async function compactSession(state, sink) {
753
+ if (state.session.history.length <= 2) {
754
+ sink.log("system", "Session history already compact.");
755
+ return;
756
+ }
757
+ const lastUserIdx = state.session.history.findLastIndex((m) => m.role === "user");
758
+ const keepFrom = lastUserIdx > 0 ? lastUserIdx : state.session.history.length;
759
+ const toSummarize = state.session.history.slice(0, keepFrom);
760
+ const tail = state.session.history.slice(keepFrom);
761
+ const textDump = toSummarize.map((m) => `${m.role}: ${m.content || JSON.stringify(m.tool_calls || "")}`).join("\n");
762
+ await updateSessionMemory(state, textDump.slice(0, 3000), "(manual compaction)", [], sink, {
763
+ force: true,
764
+ blocking: true,
765
+ verbose: true,
766
+ });
767
+ state.session.history = tail;
768
+ if (!state.noSession) saveSession(state.session, state.paths);
769
+ sink.syncStatus();
770
+ sink.log("system", `Compacted ${toSummarize.length} messages into session memory summary.`);
771
+ }
772
+
773
+ module.exports = {
774
+ expandFileMentions,
775
+ buildRequestMessages,
776
+ formatApprovalPreview,
777
+ waitForMemorySync,
778
+ updateSessionMemory,
779
+ runToolCalls,
780
+ runAgentTurn,
781
+ compactSession,
782
+ };