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.
package/src/agent/turn.js CHANGED
@@ -15,12 +15,50 @@ const {
15
15
  addPermissionRule,
16
16
  loadProviders,
17
17
  } = require("../../store");
18
- const { TOOL_DEFINITIONS, executeTool, capOutput } = require("../../tools");
18
+ const {
19
+ TOOL_DEFINITIONS,
20
+ TOOL_SCHEMA_BY_NAME,
21
+ POST_EDIT_CHECK_TOOLS,
22
+ extractEditedFilesFromCall,
23
+ ReadTracker,
24
+ getToolsForRequest,
25
+ executeTool,
26
+ capOutput,
27
+ } = require("../../tools");
28
+ const { runPostEditCheck } = require("../tools/exec");
19
29
  const { streamProviderTurn, completeProviderFast } = require("../../providers");
20
- const { estimateMessagesTokens, sliceValidHistory } = require("./history");
21
- const { gatherEnvironmentSummary, loadProjectInstructions } = require("./project_context");
22
- const { repairToolArguments, LoopDetector } = require("./resilience");
30
+ const {
31
+ COMPACTION_MARKER_PREFIX,
32
+ estimateMessagesTokens,
33
+ estimateToolsTokens,
34
+ resolveContextBudget,
35
+ createTokenCalibration,
36
+ updateTokenCalibration,
37
+ estimateCalibratedTokens,
38
+ pruneToolOutputs,
39
+ splitHistoryForCompaction,
40
+ buildCompactionChunks,
41
+ buildCompactionMessages,
42
+ sliceValidHistory,
43
+ isContextLengthError,
44
+ } = require("./history");
45
+ const {
46
+ buildStableSystemPrompt,
47
+ gatherEnvironmentSummary,
48
+ loadProjectInstructionsDetailed,
49
+ } = require("./project_context");
50
+ const { isCustomSystemPrompt } = require("../settings/store");
51
+ const { repairToolArguments, validateToolArgs, isToolFailure, LoopDetector } = require("./resilience");
52
+ const { lookupModelCapabilities, DEFAULT_MAX_OUTPUT_TOKENS } = require("../config/model_registry");
23
53
  const { summarizeArgsShort, getEnvFallback } = require("../commands/handlers");
54
+ const { EXPLORE_ALLOWED_TOOLS, createSubagentCoordinator } = require("./subagent");
55
+ const { loadAllSkills, matchRelevantSkills, formatSelectedSkillsBlock } = require("../config/skills");
56
+
57
+ const TRUNCATED_FINISH_REASONS = new Set(["length", "max_tokens", "content_filter", "error"]);
58
+ const TRUNCATION_TOOL_RETRY_MSG = [
59
+ "Your output was cut off by the token limit; this tool call was NOT executed.",
60
+ "Retry with smaller pieces: write a short skeleton first, then use edit_file/multi_edit, or split the file into parts.",
61
+ ].join("\n");
24
62
 
25
63
  function createAbortError(message = "Task cancelled by user") {
26
64
  const err = new Error(message);
@@ -69,22 +107,41 @@ function expandFileMentions(text, workspaceRoot = process.cwd()) {
69
107
  return attached.length ? `${text}\n\n${attached.join("\n\n")}` : text;
70
108
  }
71
109
 
72
- function buildRequestMessages(state) {
110
+ const STEP_LIMIT_WRAPUP_MSG = [
111
+ "The tool budget for this turn is used up. Do not call tools.",
112
+ "Reply with a short wrap-up: what is done, what is verified, and what remains.",
113
+ ].join("\n");
114
+
115
+ function buildSystemMessages(state, sink = null) {
73
116
  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]);
117
+ const includeDelegation = state._includeDelegation !== undefined ? Boolean(state._includeDelegation) : true;
118
+ const stablePrompt = buildStableSystemPrompt({
119
+ systemPrompt: state.settings.systemPrompt,
120
+ model: state.model,
121
+ providerType: state.provider?.type,
122
+ language: state.settings.language,
123
+ includeDelegation,
124
+ });
125
+
126
+ if (sink && isCustomSystemPrompt(state.settings) && !state._warnedCustomPrompt) {
127
+ state._warnedCustomPrompt = true;
128
+ sink.log(
129
+ "system",
130
+ "ℹ Using custom systemPrompt (default prompt rules skipped). Reset to default anytime in /settings or '/set systemPrompt default'."
131
+ );
87
132
  }
133
+
134
+ const sysParts = [stablePrompt, `Workspace Root: ${root}\nEnvironment: ${gatherEnvironmentSummary(root)}`];
135
+ const proj = loadProjectInstructionsDetailed(root);
136
+ if (proj.dropped.length && sink && !state._warnedInstructionDrop) {
137
+ state._warnedInstructionDrop = true;
138
+ sink.log(
139
+ "system",
140
+ `ℹ Project instructions exceeded 12k char cap; dropped farther file(s): ${proj.dropped.join(", ")}.`
141
+ );
142
+ }
143
+ if (proj.text) sysParts.push(proj.text);
144
+
88
145
  if (state.settings.agentMode === "plan") {
89
146
  sysParts.push(
90
147
  [
@@ -122,12 +179,288 @@ function buildRequestMessages(state) {
122
179
  if (sessionBlocks.length) {
123
180
  msgs.push({ role: "system", content: sessionBlocks.join("\n\n") });
124
181
  }
182
+ return msgs;
183
+ }
184
+
185
+ function buildRequestMessages(state) {
186
+ const sysMsgs = buildSystemMessages(state);
187
+ const recent = sliceValidHistory(state.session.history, state.settings.maxHistoryMessages, 0);
188
+ return [...sysMsgs, ...recent];
189
+ }
190
+
191
+ async function compactHistoryArray({
192
+ history,
193
+ provider,
194
+ model,
195
+ settings,
196
+ capabilities = {},
197
+ readTracker = null,
198
+ sink = null,
199
+ manual = false,
200
+ usableTokens = null,
201
+ signal = null,
202
+ onCompacted = null,
203
+ onPruned = null,
204
+ }) {
205
+ const budget = resolveContextBudget({ model, settings });
206
+ const usable = usableTokens || budget.usable;
207
+ const { earlierSummary, older, tail, latestUserRequest } = splitHistoryForCompaction(history, {
208
+ keepUserTurns: 2,
209
+ manual,
210
+ });
211
+
212
+ if (older.length === 0) {
213
+ if (manual) {
214
+ sink?.log?.("system", "Session history already compact.");
215
+ }
216
+ return { compacted: false, prunedFallback: false, history };
217
+ }
218
+
219
+ const chunkBudgetTokens = Math.max(4000, Math.floor(usable * 0.55));
220
+ const chunks = buildCompactionChunks(older, chunkBudgetTokens);
221
+
222
+ let runningSummary = earlierSummary || "";
223
+ let failed = false;
224
+ try {
225
+ for (const chunkText of chunks) {
226
+ const messages = buildCompactionMessages({
227
+ earlierSummary: runningSummary,
228
+ chunkText,
229
+ latestUserRequest,
230
+ });
231
+ const out = await completeProviderFast({
232
+ provider,
233
+ model,
234
+ messages,
235
+ maxTokens: 2000,
236
+ temperature: 0.2,
237
+ signal,
238
+ capabilities,
239
+ toolDefinitions: TOOL_DEFINITIONS,
240
+ timeoutMs: 45000,
241
+ });
242
+ if (!out || !out.trim()) {
243
+ failed = true;
244
+ break;
245
+ }
246
+ runningSummary = out.trim();
247
+ }
248
+ } catch (err) {
249
+ if (signal?.aborted || err?.name === "AbortError") throw err;
250
+ failed = true;
251
+ }
252
+
253
+ if (failed || !runningSummary) {
254
+ const pruned = pruneToolOutputs(history, {
255
+ protectTokens: budget.pruneProtectTokens,
256
+ minSavings: 0,
257
+ aggressive: true,
258
+ });
259
+ if (pruned.applied) {
260
+ history.splice(0, history.length, ...pruned.history);
261
+ onPruned?.(history);
262
+ }
263
+ sink?.log?.(
264
+ "system",
265
+ "⚠ Compaction summary failed or returned empty; fell back to pruning old tool outputs without dropping history."
266
+ );
267
+ sink?.syncStatus?.();
268
+ return { compacted: false, prunedFallback: true, prunedCount: pruned.prunedCount, history };
269
+ }
270
+
271
+ const summaryMsg = {
272
+ role: "user",
273
+ content: `${COMPACTION_MARKER_PREFIX}\n\n${runningSummary}`,
274
+ isCompactionSummary: true,
275
+ };
276
+ history.splice(0, history.length, summaryMsg, ...tail);
277
+ readTracker?.markAllStale();
278
+ onCompacted?.(runningSummary, history);
279
+ sink?.syncStatus?.();
280
+ sink?.log?.("system", `Compacted ${older.length} older messages into structured summary.`);
281
+ return { compacted: true, summary: runningSummary, compactedCount: older.length, history };
282
+ }
283
+
284
+ async function compactHistoryWithZoneC(state, sink, { manual = false, usableTokens = null, signal = null } = {}) {
285
+ return compactHistoryArray({
286
+ history: state.session.history,
287
+ provider: state.provider,
288
+ model: state.model,
289
+ settings: state.settings,
290
+ capabilities: state.capabilities,
291
+ readTracker: state.readTracker,
292
+ sink,
293
+ manual,
294
+ usableTokens,
295
+ signal,
296
+ onPruned: () => {
297
+ if (!state.noSession) saveSession(state.session, state.paths);
298
+ },
299
+ onCompacted: (runningSummary) => {
300
+ state.session.compactionSummary = runningSummary;
301
+ if (!state.noSession) saveSession(state.session, state.paths);
302
+ },
303
+ });
304
+ }
305
+
306
+ async function prepareLoopContext({
307
+ history,
308
+ sysMsgs,
309
+ activeTools,
310
+ provider,
311
+ model,
312
+ settings,
313
+ capabilities = {},
314
+ readTracker = null,
315
+ calibration,
316
+ sink = null,
317
+ signal = null,
318
+ warnState = null,
319
+ onHistoryMutated = null,
320
+ onCompacted = null,
321
+ }) {
322
+ const budget = resolveContextBudget({ model, settings });
323
+
324
+ if (budget.isUnknownModelWindow && warnState && !warnState.warnedUnknownContextWindow) {
325
+ warnState.warnedUnknownContextWindow = true;
326
+ sink?.log?.(
327
+ "system",
328
+ `ℹ Unknown model '${model || "default"}' — using conservative 32k context window. Set contextWindow (/set contextWindow <tokens>) if your model supports more.`
329
+ );
330
+ }
331
+
332
+ const toolsOverhead = estimateToolsTokens(activeTools);
333
+ const sysOverhead = estimateMessagesTokens(sysMsgs);
125
334
 
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];
335
+ // Keep base64 screenshot payloads only on the most recent tool message to prevent context bloat
336
+ if (Array.isArray(history) && history.length > 0) {
337
+ const imageIndices = [];
338
+ for (let i = 0; i < history.length; i++) {
339
+ const m = history[i];
340
+ if (m && Array.isArray(m.images) && m.images.length > 0 && !m.imagesPruned) {
341
+ imageIndices.push(i);
342
+ }
343
+ }
344
+ if (imageIndices.length > 1) {
345
+ let prunedImgs = false;
346
+ for (let k = 0; k < imageIndices.length - 1; k++) {
347
+ const msg = history[imageIndices[k]];
348
+ if (msg) {
349
+ delete msg.images;
350
+ msg.imagesPruned = true;
351
+ prunedImgs = true;
352
+ }
353
+ }
354
+ if (prunedImgs) onHistoryMutated?.(history);
355
+ }
356
+ }
357
+
358
+ const measureRaw = () => {
359
+ const valid = sliceValidHistory(history, settings?.maxHistoryMessages, 0);
360
+ return {
361
+ valid,
362
+ rawEstimate: sysOverhead + toolsOverhead + estimateMessagesTokens(valid),
363
+ };
364
+ };
365
+
366
+ let { valid, rawEstimate } = measureRaw();
367
+ let calibratedEstimate = estimateCalibratedTokens(calibration, rawEstimate);
368
+
369
+ // Zone B: Prune old tool outputs when above pruneThreshold (default 75% of usable)
370
+ if (calibratedEstimate > budget.usable * budget.pruneThreshold) {
371
+ const targetSaved = Math.max(
372
+ budget.pruneMinSavings,
373
+ calibratedEstimate - Math.floor(budget.usable * budget.pruneThreshold * 0.9)
374
+ );
375
+ const pruned = pruneToolOutputs(history, {
376
+ protectTokens: budget.pruneProtectTokens,
377
+ minSavings: budget.pruneMinSavings,
378
+ targetSavedTokens: targetSaved,
379
+ });
380
+ if (pruned.applied) {
381
+ history.splice(0, history.length, ...pruned.history);
382
+ onHistoryMutated?.(history);
383
+ ({ valid, rawEstimate } = measureRaw());
384
+ calibratedEstimate = estimateCalibratedTokens(calibration, rawEstimate);
385
+ sink?.log?.(
386
+ "meta",
387
+ `✂ Pruned ${pruned.prunedCount} old tool output(s) (~${pruned.savedTokens} tokens freed)`
388
+ );
389
+ }
390
+ }
391
+
392
+ // Zone C: Structured compaction when STILL above compactThreshold (default 85% of usable)
393
+ if (calibratedEstimate > budget.usable * budget.compactThreshold) {
394
+ await compactHistoryArray({
395
+ history,
396
+ provider,
397
+ model,
398
+ settings,
399
+ capabilities,
400
+ readTracker,
401
+ sink,
402
+ usableTokens: budget.usable,
403
+ signal,
404
+ onPruned: onHistoryMutated,
405
+ onCompacted: (runningSummary, h) => {
406
+ onCompacted?.(runningSummary);
407
+ onHistoryMutated?.(h);
408
+ },
409
+ });
410
+ ({ valid, rawEstimate } = measureRaw());
411
+ calibratedEstimate = estimateCalibratedTokens(calibration, rawEstimate);
412
+ }
413
+
414
+ return {
415
+ reqMessages: [...sysMsgs, ...valid],
416
+ activeTools,
417
+ budget,
418
+ rawEstimate,
419
+ calibratedEstimate,
420
+ };
421
+ }
422
+
423
+ async function prepareContextForStep(state, sink, calibration, signal = null) {
424
+ const sysMsgs = buildSystemMessages(state, sink);
425
+ const activeTools =
426
+ state.settings?.toolsEnabled === false
427
+ ? []
428
+ : getToolsForRequest({
429
+ model: state.model,
430
+ providerType: state.provider?.type,
431
+ toolset: state.settings?.toolset || "core",
432
+ includeTask: state._includeDelegation !== undefined ? Boolean(state._includeDelegation) : true,
433
+ includeSkill: state._includeSkill !== undefined ? Boolean(state._includeSkill) : true,
434
+ includeBrowser: state._includeBrowser !== undefined ? Boolean(state._includeBrowser) : true,
435
+ });
436
+ const warnState = {
437
+ get warnedUnknownContextWindow() {
438
+ return Boolean(state._warnedUnknownContextWindow);
439
+ },
440
+ set warnedUnknownContextWindow(val) {
441
+ state._warnedUnknownContextWindow = Boolean(val);
442
+ },
443
+ };
444
+ return prepareLoopContext({
445
+ history: state.session.history,
446
+ sysMsgs,
447
+ activeTools,
448
+ provider: state.provider,
449
+ model: state.model,
450
+ settings: state.settings,
451
+ capabilities: state.capabilities,
452
+ readTracker: state.readTracker,
453
+ calibration,
454
+ sink,
455
+ signal,
456
+ warnState,
457
+ onHistoryMutated: () => {
458
+ if (!state.noSession) saveSession(state.session, state.paths);
459
+ },
460
+ onCompacted: (runningSummary) => {
461
+ state.session.compactionSummary = runningSummary;
462
+ },
463
+ });
131
464
  }
132
465
 
133
466
  function formatEditDiffPreview(target = "", replacement = "") {
@@ -211,11 +544,11 @@ async function updateSessionMemory(state, userText, assistantText, toolsUsed, si
211
544
  {
212
545
  role: "system",
213
546
  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.",
547
+ "Maintain a rolling memory summary for THIS session only (up to ~800 words). Merge the previous summary with the new exchange, keeping goals, decisions, file paths, facts, and outcomes. Output ONLY the updated summary.",
215
548
  },
216
549
  {
217
550
  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)}`,
551
+ content: `Previous summary:\n${prev}\n\nNew User message:\n${userText}${toolNote}\n\nAssistant response:\n${assistantText}`,
219
552
  },
220
553
  ];
221
554
 
@@ -228,7 +561,7 @@ async function updateSessionMemory(state, userText, assistantText, toolsUsed, si
228
561
  provider: state.provider,
229
562
  model: state.model,
230
563
  messages: digestPrompt,
231
- maxTokens: 300,
564
+ maxTokens: 1200,
232
565
  temperature: 0.2,
233
566
  signal: abortCtrl.signal,
234
567
  capabilities: state.capabilities,
@@ -247,9 +580,9 @@ async function updateSessionMemory(state, userText, assistantText, toolsUsed, si
247
580
  if (abortCtrl.signal.aborted || err?.name === "AbortError") return;
248
581
  }
249
582
 
250
- const snippet = `- User: ${userText.replace(/\s+/g, " ").slice(0, 120)} -> AI: ${assistantText.replace(/\s+/g, " ").slice(0, 160)}`;
583
+ const snippet = `- User: ${userText.replace(/\s+/g, " ").slice(0, 300)} -> AI: ${assistantText.replace(/\s+/g, " ").slice(0, 400)}`;
251
584
  const merged = state.session.summaryMemory ? `${state.session.summaryMemory}\n${snippet}` : snippet;
252
- state.session.summaryMemory = merged.slice(-2000);
585
+ state.session.summaryMemory = merged.slice(-8000);
253
586
  saveSession(state.session, state.paths);
254
587
  sink.syncStatus();
255
588
  if (options.verbose !== false) {
@@ -264,13 +597,41 @@ async function updateSessionMemory(state, userText, assistantText, toolsUsed, si
264
597
  if (options.blocking) await job;
265
598
  }
266
599
 
267
- async function runToolCalls(state, toolCalls, sink) {
600
+ function createNoopSink() {
601
+ return {
602
+ interactive: false,
603
+ log() {},
604
+ setBusy() {},
605
+ syncStatus() {},
606
+ startThinking() {
607
+ return { stop() {}, write() {}, end() {}, setLabel() {} };
608
+ },
609
+ notify() {},
610
+ };
611
+ }
612
+
613
+ async function runToolCalls(state, toolCalls, sink, options = {}) {
614
+ const safeSink = sink || createNoopSink();
268
615
  const results = new Array(toolCalls.length);
269
616
  const parallelBatch = [];
270
617
  const workspaceRoot = state.workspaceRoot || process.cwd();
271
618
  const extraSecretEnvKeys = getProviderSecretEnvKeys(state);
619
+ const strictNoRepair = Boolean(options.strictNoRepair);
620
+ const activeSignal = options.signal || state.activeAbort?.signal || null;
621
+ const sessionId = state.session?.id || "loop";
622
+ const sudoPasswords = state.sudoPasswords || (state.sudoPasswords = new Map());
623
+ const sessionRules = state.sessionRules || (state.sessionRules = []);
624
+ const subagentCoordinator =
625
+ options.subagentCoordinator || state.subagentCoordinator || createSubagentCoordinator(state.settings);
626
+ const approvalMutex = state.approvalMutex || subagentCoordinator.approvalMutex;
627
+
628
+ if (!state.readTracker || (state.session?.id && state.readTrackerSessionId !== state.session.id)) {
629
+ state.readTracker = new ReadTracker();
630
+ state.readTrackerSessionId = sessionId;
631
+ }
272
632
 
273
- const isAutoMode = () => state.settings.agentMode === "auto" || state.settings.toolPermission === "always-proceed";
633
+ const isAutoMode = () =>
634
+ state.settings?.agentMode === "auto" || state.settings?.toolPermission === "always-proceed";
274
635
 
275
636
  const makeCtx = (approvedByUser = false, skipDownloadDestPrompt = false, onToolOutput = null) => ({
276
637
  cwd: workspaceRoot,
@@ -278,35 +639,48 @@ async function runToolCalls(state, toolCalls, sink) {
278
639
  paths: state.paths,
279
640
  extraDirs: state.extraDirs || [],
280
641
  extraSecretEnvKeys,
281
- settings: state.settings,
282
- session: state.session,
642
+ settings: state.settings || {},
643
+ session: state.session || null,
644
+ readTracker: state.readTracker,
283
645
  autoApprove: isAutoMode(),
284
646
  approvedByUser: approvedByUser || isAutoMode(),
285
647
  skipDownloadDestPrompt: skipDownloadDestPrompt || isAutoMode(),
286
648
  onToolOutput,
287
- openChoicePicker: sink.openChoicePicker,
649
+ openChoicePicker: safeSink.openChoicePicker,
288
650
  bgTasks: state.bgTasks || null,
651
+ provider: state.provider || null,
652
+ model: state.model || "",
653
+ capabilities: state.capabilities || {},
654
+ parentSink: safeSink,
655
+ startSubagent: safeSink.startSubagent,
656
+ subagentCoordinator,
657
+ skipPostEditCheck: true,
289
658
  _permissionChecked: true,
290
- signal: state.activeAbort?.signal || null,
659
+ streamCheckpointed: state.streamCheckpointed,
660
+ signal: activeSignal,
291
661
  saveSession: (s) => {
292
- if (!state.noSession) saveSession(s, state.paths);
662
+ if (!state.noSession && state.paths && s) saveSession(s, state.paths);
663
+ },
664
+ loadGlobalMemory: () => (state.paths ? loadGlobalMemory(state.paths) : []),
665
+ saveGlobalMemory: (items) => {
666
+ if (state.paths) saveGlobalMemory(items, state.paths);
293
667
  },
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) || "",
668
+ addGlobalMemory: (fact, src) => (state.paths ? addGlobalMemory(fact, src, state.paths) : false),
669
+ getSudoPassword: () => sudoPasswords.get(sessionId) || "",
298
670
  setSudoPassword: (pw) => {
299
- if (pw) state.sudoPasswords.set(state.session.id, pw);
300
- else state.sudoPasswords.delete(state.session.id);
671
+ if (pw) sudoPasswords.set(sessionId, pw);
672
+ else sudoPasswords.delete(sessionId);
301
673
  },
302
- askPrompt: sink.askPrompt,
303
- askPassword: sink.askPassword,
304
- startProgress: sink.startProgress,
305
- setBusy: sink.setBusy,
306
- log: sink.log,
674
+ askPrompt: safeSink.askPrompt,
675
+ askPassword: safeSink.askPassword,
676
+ startProgress: safeSink.startProgress,
677
+ setBusy: safeSink.setBusy,
678
+ log: safeSink.log,
307
679
  });
308
680
 
309
681
  let downloadFailedOrCancelled = false;
682
+ const editedFilesInBatch = [];
683
+ let lastSuccessfulEditIdx = -1;
310
684
 
311
685
  const flushParallel = async () => {
312
686
  if (!parallelBatch.length) return;
@@ -315,7 +689,7 @@ async function runToolCalls(state, toolCalls, sink) {
315
689
  };
316
690
 
317
691
  for (let i = 0; i < toolCalls.length; i++) {
318
- if (state.activeAbort?.signal?.aborted) {
692
+ if (activeSignal?.aborted) {
319
693
  await flushParallel();
320
694
  throw createAbortError();
321
695
  }
@@ -327,24 +701,87 @@ async function runToolCalls(state, toolCalls, sink) {
327
701
  if (downloadFailedOrCancelled && name === "run_command") {
328
702
  const msg = "Skipped command because the preceding download did not complete.";
329
703
  results[i] = { role: "tool", tool_call_id: tc.id, name, content: msg };
330
- sink.log("tool", `⏸ ${name}(${summary}) skipped (download incomplete)`);
704
+ safeSink.log("tool", `⏸ ${name}(${summary}) skipped (download incomplete)`);
331
705
  continue;
332
706
  }
333
- let parsedArgs = {};
707
+ let parsedArgs;
334
708
  try {
335
709
  parsedArgs =
336
710
  typeof tc.function.arguments === "string"
337
- ? repairToolArguments(tc.function.arguments || "{}")
711
+ ? repairToolArguments(tc.function.arguments || "", { strict: strictNoRepair })
338
712
  : tc.function.arguments || {};
339
- } catch {}
713
+ } catch (parseErr) {
714
+ safeSink.cleanupStreamWrite?.(i, true);
715
+ results[i] = {
716
+ role: "tool",
717
+ tool_call_id: tc.id,
718
+ name,
719
+ content: `Error: the arguments of this tool call are not valid JSON (${parseErr.message}). The tool was NOT executed.\nResend the call with valid JSON arguments that match the tool schema.`,
720
+ isError: true,
721
+ };
722
+ safeSink.log("tool", `✗ ${name}(${summary}) invalid JSON arguments`);
723
+ continue;
724
+ }
725
+
726
+ const schema = TOOL_SCHEMA_BY_NAME.get(name);
727
+ if (schema) {
728
+ try {
729
+ validateToolArgs(parsedArgs, schema);
730
+ } catch (valErr) {
731
+ safeSink.cleanupStreamWrite?.(i, true);
732
+ results[i] = {
733
+ role: "tool",
734
+ tool_call_id: tc.id,
735
+ name,
736
+ content: `Error: invalid arguments for '${name}' (${valErr.message}). The tool was NOT executed.\nResend the call with valid JSON arguments that match the tool schema.`,
737
+ isError: true,
738
+ };
739
+ safeSink.log("tool", `✗ ${name}(${summary}) invalid arguments: ${valErr.message}`);
740
+ continue;
741
+ }
742
+ }
743
+
744
+ if (state.allowedToolNames && !state.allowedToolNames.has(name)) {
745
+ results[i] = {
746
+ role: "tool",
747
+ tool_call_id: tc.id,
748
+ name,
749
+ content: `Error: Tool '${name}' is not allowed for this sub-agent.`,
750
+ isError: true,
751
+ };
752
+ safeSink.log("tool", `⛔ ${name}(${summary}) not allowed for sub-agent`);
753
+ continue;
754
+ }
755
+ if (state.blockedToolNames && state.blockedToolNames.has(name)) {
756
+ results[i] = {
757
+ role: "tool",
758
+ tool_call_id: tc.id,
759
+ name,
760
+ content: `Error: Tool '${name}' is blocked for this sub-agent.`,
761
+ isError: true,
762
+ };
763
+ safeSink.log("tool", `⛔ ${name}(${summary}) blocked for sub-agent`);
764
+ continue;
765
+ }
766
+ if (state.forceReadOnly && !EXPLORE_ALLOWED_TOOLS.has(name)) {
767
+ results[i] = {
768
+ role: "tool",
769
+ tool_call_id: tc.id,
770
+ name,
771
+ content: `Error: Tool '${name}' is blocked in read-only explore sub-agent.`,
772
+ isError: true,
773
+ };
774
+ safeSink.log("tool", `⛔ ${name}(${summary}) blocked in read-only mode`);
775
+ continue;
776
+ }
340
777
 
341
778
  const evalRes = evaluatePermission({
342
779
  toolName: name,
343
780
  args: parsedArgs,
344
- settings: state.settings,
781
+ settings: state.settings || {},
345
782
  workspaceRoot,
346
783
  extraDirs: state.extraDirs || [],
347
- sessionRules: state.sessionRules,
784
+ sessionRules,
348
785
  paths: state.paths,
349
786
  });
350
787
 
@@ -354,8 +791,9 @@ async function runToolCalls(state, toolCalls, sink) {
354
791
  tool_call_id: tc.id,
355
792
  name,
356
793
  content: evalRes.reason,
794
+ isError: true,
357
795
  };
358
- sink.log("tool", `⛔ ${name}(${summary}) blocked: ${evalRes.reason}`);
796
+ safeSink.log("tool", `⛔ ${name}(${summary}) blocked: ${evalRes.reason}`);
359
797
  continue;
360
798
  }
361
799
 
@@ -363,74 +801,87 @@ async function runToolCalls(state, toolCalls, sink) {
363
801
  let skipDownloadDestPrompt = Boolean(evalRes.matchedRule);
364
802
 
365
803
  if (evalRes.decision === "ask") {
366
- if (!sink.interactive || !sink.confirm) {
804
+ if (!safeSink.interactive || !safeSink.confirm) {
367
805
  results[i] = {
368
806
  role: "tool",
369
807
  tool_call_id: tc.id,
370
808
  name,
371
809
  content: `Denied: '${name}' requires interactive approval (${evalRes.reason}).`,
810
+ isError: true,
372
811
  };
373
- sink.log("tool", `✗ ${name}(${summary}) requires approval`);
812
+ safeSink.log("tool", `✗ ${name}(${summary}) requires approval`);
374
813
  continue;
375
814
  }
376
815
 
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]: `
816
+ const runAskFlow = async () => {
817
+ const labelPrefix = state.approvalLabel ? `${state.approvalLabel} ` : "";
818
+ const preview = formatApprovalPreview(name, parsedArgs, evalRes);
819
+ safeSink.log("permission", `${labelPrefix}${preview}`);
820
+ safeSink.notify?.();
821
+ const rawChoice = (
822
+ await safeSink.confirm(`${labelPrefix}Allow ${name}? [y=once / n=deny / s=session / A=always]: `)
823
+ ).trim();
824
+ if (activeSignal?.aborted) {
825
+ throw createAbortError();
826
+ }
827
+ const lowerChoice = rawChoice.toLowerCase();
828
+
829
+ if (lowerChoice === "y" || lowerChoice === "yes") {
830
+ approvedByUser = true;
831
+ } else if ((lowerChoice === "s" || rawChoice === "A") && !evalRes.hardDenied && !evalRes.requiresSudo) {
832
+ approvedByUser = true;
833
+ const suggestions = buildSuggestedRules(name, parsedArgs, workspaceRoot);
834
+ const defRule = suggestions[0];
835
+ const altHint = suggestions.length > 1 ? ` or type 'tool' for all ${name}` : "";
836
+ const scopeAns = (
837
+ await safeSink.confirm(
838
+ `${labelPrefix}Save ${lowerChoice === "s" ? "session" : "always (project)"} allow rule for ${defRule.label}${altHint}? [Enter=yes / n=once only]: `
839
+ )
396
840
  )
397
- )
398
- .trim()
399
- .toLowerCase();
841
+ .trim()
842
+ .toLowerCase();
400
843
 
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
- );
844
+ if (scopeAns !== "n" && scopeAns !== "no") {
845
+ const picked =
846
+ scopeAns === "tool" && suggestions[suggestions.length - 1]
847
+ ? suggestions[suggestions.length - 1].rule
848
+ : defRule.rule;
849
+ if (lowerChoice === "s") {
850
+ sessionRules.push(picked);
851
+ safeSink.log(
852
+ "meta",
853
+ `✓ session rule added: ${picked.tool} (${picked.scope}: ${picked.pattern || "*"})`
854
+ );
855
+ } else if (state.paths) {
856
+ addPermissionRule(picked, "project", state.paths);
857
+ safeSink.log(
858
+ "meta",
859
+ `✓ project rule saved: ${picked.tool} (${picked.scope}: ${picked.pattern || "*"})`
860
+ );
861
+ }
862
+ skipDownloadDestPrompt = true;
418
863
  }
419
- skipDownloadDestPrompt = true;
864
+ } else if ((lowerChoice === "s" || rawChoice === "A") && (evalRes.hardDenied || evalRes.requiresSudo)) {
865
+ approvedByUser = true;
866
+ safeSink.log(
867
+ "meta",
868
+ "Note: hard-denylist/sudo commands are allowed once (cannot be permanently auto-allowed)."
869
+ );
870
+ } else {
871
+ return "denied";
420
872
  }
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`);
873
+ return "approved";
874
+ };
875
+
876
+ const askOutcome = approvalMutex ? await approvalMutex.run(runAskFlow) : await runAskFlow();
877
+ if (askOutcome === "denied") {
878
+ results[i] = { role: "tool", tool_call_id: tc.id, name, content: "Denied by user.", isError: true };
879
+ safeSink.log("tool", `✗ ${name}(${summary}) denied`);
880
+ safeSink.cleanupStreamWrite?.(i, true);
430
881
  continue;
431
882
  }
432
883
  } else if (evalRes.matchedRule && evalRes.ruleLabel) {
433
- sink.log("meta", `✓ auto-allowed by rule: ${evalRes.ruleLabel}`);
884
+ safeSink.log("meta", `✓ auto-allowed by rule: ${evalRes.ruleLabel}`);
434
885
  }
435
886
 
436
887
  const isSequential =
@@ -444,49 +895,82 @@ async function runToolCalls(state, toolCalls, sink) {
444
895
 
445
896
  const runOne = async () => {
446
897
  const toolUi =
447
- name !== "download_file" && sink.startToolCall
448
- ? sink.startToolCall(`⚙ ${name}(${summary})`, { collapsible: true })
898
+ name !== "download_file" && name !== "task" && safeSink.startToolCall
899
+ ? safeSink.startToolCall(`⚙ ${name}(${summary})`, { collapsible: true, toolIdx: i })
449
900
  : null;
450
- if (!toolUi && name !== "download_file") {
451
- sink.log("tool", `⚙ ${name}(${summary})`);
901
+ if (!toolUi && name !== "download_file" && name !== "task") {
902
+ safeSink.log("tool", `⚙ ${name}(${summary})`);
452
903
  }
453
- if (name === "download_file") {
904
+ if (name === "task") {
905
+ safeSink.setBusy("Running sub-agent...");
906
+ } else if (name === "download_file") {
454
907
  state.isDownloading = true;
455
- sink.setBusy("Downloading (commands paused)...");
908
+ safeSink.setBusy("Downloading (commands paused)...");
456
909
  } else if (name === "write_file" || name === "edit_file" || name === "multi_edit") {
457
910
  const target = parsedArgs.path ? parsedArgs.path.split("/").pop() : "";
458
- sink.setBusy(`Writing ${target || "file"}...`);
911
+ safeSink.setBusy(`Writing ${target || "file"}...`);
912
+ // Populate write stats for the live TUI write indicator.
913
+ if (toolUi && toolUi.startWrite) {
914
+ const writeContent =
915
+ typeof parsedArgs.content === "string"
916
+ ? parsedArgs.content
917
+ : typeof parsedArgs.replacement === "string"
918
+ ? parsedArgs.replacement
919
+ : "";
920
+ toolUi.startWrite({ filePath: parsedArgs.path || "", content: writeContent });
921
+ }
459
922
  } else if (name === "read_file" || name === "glob_files" || name === "grep_files") {
460
923
  const target = parsedArgs.path ? parsedArgs.path.split("/").pop() : "";
461
- sink.setBusy(`Reading ${target || "code"}...`);
924
+ safeSink.setBusy(`Reading ${target || "code"}...`);
462
925
  } else {
463
- sink.setBusy(`Running ${name}...`);
926
+ safeSink.setBusy(`Running ${name}...`);
464
927
  }
465
928
  try {
466
- const out = await executeTool(
467
- name,
468
- parsedArgs,
469
- makeCtx(approvedByUser, skipDownloadDestPrompt, (chunk) => toolUi?.pushOutput(chunk))
470
- );
929
+ const capturedImages = [];
930
+ const execCtx = makeCtx(approvedByUser, skipDownloadDestPrompt, (chunk) => toolUi?.pushOutput(chunk));
931
+ execCtx.attachToolImage = (img) => {
932
+ if (img && typeof img.data === "string" && img.data) {
933
+ capturedImages.push(img);
934
+ }
935
+ };
936
+ const out = await executeTool(name, parsedArgs, execCtx);
471
937
  const outStr = String(out);
472
- results[i] = { role: "tool", tool_call_id: tc.id, name, content: outStr };
473
- toolUi?.finish(outStr, /^Exit |^Command timed out/i.test(outStr));
938
+ const failed = isToolFailure(outStr) || /^Command timed out/i.test(outStr);
939
+ results[i] = {
940
+ role: "tool",
941
+ tool_call_id: tc.id,
942
+ name,
943
+ content: outStr,
944
+ ...(capturedImages.length ? { images: capturedImages } : {}),
945
+ ...(failed ? { isError: true } : {}),
946
+ };
947
+ if (!failed && POST_EDIT_CHECK_TOOLS.has(name)) {
948
+ editedFilesInBatch.push(...extractEditedFilesFromCall(name, parsedArgs));
949
+ lastSuccessfulEditIdx = i;
950
+ }
951
+ toolUi?.finish(outStr, failed);
474
952
  if (name === "download_file" && /^Download cancelled/i.test(outStr)) {
475
953
  downloadFailedOrCancelled = true;
476
954
  }
477
955
  } catch (err) {
478
- if (state.activeAbort?.signal?.aborted || err?.aborted || err?.name === "AbortError") {
956
+ if (activeSignal?.aborted || err?.aborted || err?.name === "AbortError") {
479
957
  toolUi?.finish("Aborted by user", true);
480
958
  throw createAbortError(err?.message || "Task cancelled by user");
481
959
  }
482
960
  if (name === "download_file") downloadFailedOrCancelled = true;
483
- results[i] = { role: "tool", tool_call_id: tc.id, name, content: `Error: ${err.message}` };
961
+ results[i] = {
962
+ role: "tool",
963
+ tool_call_id: tc.id,
964
+ name,
965
+ content: `Error: ${err.message}`,
966
+ isError: true,
967
+ };
484
968
  toolUi?.finish(`Error: ${err.message}`, true);
485
- sink.log("error", `✗ ${name}: ${err.message}`);
969
+ safeSink.log("error", `✗ ${name}: ${err.message}`);
486
970
  } finally {
487
971
  if (name === "download_file") {
488
972
  state.isDownloading = false;
489
- sink.syncStatus();
973
+ safeSink.syncStatus();
490
974
  }
491
975
  }
492
976
  };
@@ -501,17 +985,53 @@ async function runToolCalls(state, toolCalls, sink) {
501
985
  }
502
986
 
503
987
  await flushParallel();
988
+ if (lastSuccessfulEditIdx >= 0 && results[lastSuccessfulEditIdx]) {
989
+ const checkCtx = makeCtx(false, false);
990
+ checkCtx.skipPostEditCheck = false;
991
+ const checkRes = await runPostEditCheck({
992
+ files: editedFilesInBatch,
993
+ ctx: checkCtx,
994
+ signal: activeSignal,
995
+ });
996
+ if (checkRes.ran && checkRes.text) {
997
+ results[lastSuccessfulEditIdx].content = `${results[lastSuccessfulEditIdx].content}${checkRes.text}`;
998
+ safeSink.log("meta", checkRes.text.trim());
999
+ }
1000
+ }
504
1001
  return results;
505
1002
  }
506
1003
 
507
1004
  function repairTranscriptTail(history, dropTrailingUser = false) {
508
- // Keep completed steps intact; trim trailing unfulfilled tool_calls or orphan tool messages so /retry & resume work cleanly.
1005
+ // Keep completed steps intact; trim trailing unfulfilled tool_calls, partial tool groups, or orphan tool messages so /retry & resume work cleanly.
509
1006
  while (history.length > 0) {
510
1007
  const last = history[history.length - 1];
511
1008
  if (last.role === "assistant" && Array.isArray(last.tool_calls) && last.tool_calls.length > 0) {
512
1009
  history.pop();
513
1010
  continue;
514
1011
  }
1012
+ if (last.role === "tool") {
1013
+ let firstToolIdx = history.length - 1;
1014
+ while (firstToolIdx > 0 && history[firstToolIdx - 1].role === "tool") {
1015
+ firstToolIdx -= 1;
1016
+ }
1017
+ const prev = firstToolIdx > 0 ? history[firstToolIdx - 1] : null;
1018
+ if (!prev || prev.role !== "assistant" || !Array.isArray(prev.tool_calls) || !prev.tool_calls.length) {
1019
+ history.splice(firstToolIdx);
1020
+ continue;
1021
+ }
1022
+ const expectedIds = prev.tool_calls.map((tc) => tc.id).filter(Boolean);
1023
+ const actualIds = new Set(
1024
+ history
1025
+ .slice(firstToolIdx)
1026
+ .map((m) => m.tool_call_id)
1027
+ .filter(Boolean)
1028
+ );
1029
+ const allMatched = expectedIds.every((id) => actualIds.has(id));
1030
+ if (!allMatched) {
1031
+ history.splice(firstToolIdx - 1);
1032
+ continue;
1033
+ }
1034
+ }
515
1035
  break;
516
1036
  }
517
1037
  if (dropTrailingUser && history.length > 0 && history[history.length - 1].role === "user") {
@@ -519,6 +1039,509 @@ function repairTranscriptTail(history, dropTrailingUser = false) {
519
1039
  }
520
1040
  }
521
1041
 
1042
+ function resolveLoopSystemMessages({ systemPrompt, settings, model, provider, permissions }) {
1043
+ if (typeof systemPrompt === "function") return systemPrompt();
1044
+ if (Array.isArray(systemPrompt)) return systemPrompt;
1045
+ if (typeof systemPrompt === "string" && systemPrompt.length > 0) {
1046
+ return [{ role: "system", content: systemPrompt }];
1047
+ }
1048
+ const workspaceRoot = permissions?.workspaceRoot || process.cwd();
1049
+ const stablePrompt = buildStableSystemPrompt({
1050
+ systemPrompt: settings?.systemPrompt,
1051
+ model,
1052
+ providerType: provider?.type,
1053
+ language: settings?.language,
1054
+ includeDelegation: false,
1055
+ });
1056
+ const sysParts = [
1057
+ stablePrompt,
1058
+ `Workspace Root: ${workspaceRoot}\nEnvironment: ${gatherEnvironmentSummary(workspaceRoot)}`,
1059
+ ];
1060
+ return [{ role: "system", content: sysParts.join("\n\n") }];
1061
+ }
1062
+
1063
+ function resolveLoopTools({ tools, settings, model, provider }) {
1064
+ if (typeof tools === "function") return tools();
1065
+ if (Array.isArray(tools)) return tools;
1066
+ if (settings?.toolsEnabled === false) return [];
1067
+ return getToolsForRequest({
1068
+ model,
1069
+ providerType: provider?.type,
1070
+ toolset: settings?.toolset || "core",
1071
+ includeTask: false,
1072
+ });
1073
+ }
1074
+
1075
+ /**
1076
+ * Stateless multi-step LLM + tool loop operating solely on the supplied `history` array.
1077
+ * Does not touch any global session store unless caller-supplied hooks choose to.
1078
+ */
1079
+ async function runAgentLoop({
1080
+ history,
1081
+ tools = null,
1082
+ systemPrompt = null,
1083
+ provider,
1084
+ model,
1085
+ settings = {},
1086
+ maxSteps = null,
1087
+ signal = null,
1088
+ sink = null,
1089
+ permissions = {},
1090
+ capabilities = {},
1091
+ tokenCalibration = null,
1092
+ prepareContextFn = null,
1093
+ onTurnStats = null,
1094
+ onCheckpoint = null,
1095
+ onBeforeComplete = null,
1096
+ dropTrailingUserOnAbort = false,
1097
+ }) {
1098
+ if (!Array.isArray(history)) {
1099
+ throw new Error("runAgentLoop requires a history array");
1100
+ }
1101
+ const safeSink = sink || createNoopSink();
1102
+ const calibration = tokenCalibration || createTokenCalibration();
1103
+ const loopSettings = permissions?.settings || settings || {};
1104
+ const stepLimit = Math.max(1, Number(maxSteps ?? loopSettings.maxToolSteps) || 100);
1105
+ const loopStats = {
1106
+ requests: 0,
1107
+ totalMs: 0,
1108
+ promptTokens: 0,
1109
+ completionTokens: 0,
1110
+ cacheReadTokens: 0,
1111
+ cacheWriteTokens: 0,
1112
+ steps: 0,
1113
+ toolCalls: 0,
1114
+ };
1115
+
1116
+ const runnerState = permissions?._state || {
1117
+ workspaceRoot: permissions?.workspaceRoot || process.cwd(),
1118
+ paths: permissions?.paths || null,
1119
+ extraDirs: permissions?.extraDirs || [],
1120
+ settings: {
1121
+ ...loopSettings,
1122
+ ...(permissions?.agentMode ? { agentMode: permissions.agentMode } : {}),
1123
+ ...(permissions?.toolPermission ? { toolPermission: permissions.toolPermission } : {}),
1124
+ ...(permissions?.nonWorkspaceAccess ? { nonWorkspaceAccess: permissions.nonWorkspaceAccess } : {}),
1125
+ },
1126
+ sessionRules: permissions?.sessionRules || [],
1127
+ session: permissions?.session || null,
1128
+ noSession: permissions?.noSession !== undefined ? Boolean(permissions.noSession) : true,
1129
+ readTracker: permissions?.readTracker || new ReadTracker(),
1130
+ readTrackerSessionId: permissions?.session?.id || "loop",
1131
+ sudoPasswords: permissions?.sudoPasswords || new Map(),
1132
+ bgTasks: permissions?.bgTasks || null,
1133
+ streamCheckpointed: permissions?.streamCheckpointed || null,
1134
+ provider,
1135
+ model,
1136
+ capabilities,
1137
+ allowedToolNames: permissions?.allowedToolNames || null,
1138
+ blockedToolNames: permissions?.blockedToolNames || null,
1139
+ forceReadOnly: Boolean(permissions?.forceReadOnly),
1140
+ approvalMutex: permissions?.approvalMutex || null,
1141
+ approvalLabel: permissions?.approvalLabel || "",
1142
+ activeAbort: signal ? { signal } : null,
1143
+ };
1144
+
1145
+ const warnState = { warnedUnknownContextWindow: false };
1146
+ const getStepContext = async () => {
1147
+ if (typeof prepareContextFn === "function") {
1148
+ return prepareContextFn(calibration, signal);
1149
+ }
1150
+ const sysMsgs = resolveLoopSystemMessages({
1151
+ systemPrompt,
1152
+ settings: loopSettings,
1153
+ model,
1154
+ provider,
1155
+ permissions,
1156
+ });
1157
+ const activeTools = resolveLoopTools({ tools, settings: loopSettings, model, provider });
1158
+ return prepareLoopContext({
1159
+ history,
1160
+ sysMsgs,
1161
+ activeTools,
1162
+ provider,
1163
+ model,
1164
+ settings: loopSettings,
1165
+ capabilities,
1166
+ readTracker: runnerState.readTracker,
1167
+ calibration,
1168
+ sink: safeSink,
1169
+ signal,
1170
+ warnState,
1171
+ });
1172
+ };
1173
+
1174
+ const toolsUsed = [];
1175
+ let finalAssistantText = "";
1176
+ let lastUsage = null;
1177
+ let emptyRetried = false;
1178
+ let consecutiveTruncations = 0;
1179
+ let raisedOutputLimit = false;
1180
+ let maxTokensOverride = null;
1181
+
1182
+ try {
1183
+ const loopDetector = new LoopDetector(3);
1184
+
1185
+ for (let step = 0; step < stepLimit; step++) {
1186
+ if (signal?.aborted) throw createAbortError();
1187
+ safeSink.setBusy(step ? `Step ${step + 1}...` : "Thinking...");
1188
+
1189
+ let stepCtx = await getStepContext();
1190
+ const ctxEst = stepCtx.calibratedEstimate;
1191
+ const ctxWin = stepCtx.budget.contextWindow;
1192
+ if (loopSettings.verbosity === "high" && step > 0) {
1193
+ safeSink.log("meta", `[verbose] Step ${step + 1}/${stepLimit} · ~${ctxEst} tokens`);
1194
+ }
1195
+
1196
+ let turn;
1197
+ try {
1198
+ turn = await streamProviderTurn({
1199
+ provider,
1200
+ model,
1201
+ settings: loopSettings,
1202
+ messages: stepCtx.reqMessages,
1203
+ signal,
1204
+ sink: safeSink,
1205
+ capabilities,
1206
+ toolDefinitions: stepCtx.activeTools,
1207
+ maxTokensOverride,
1208
+ });
1209
+ } catch (streamErr) {
1210
+ if (!signal?.aborted && isContextLengthError(streamErr)) {
1211
+ safeSink.log(
1212
+ "system",
1213
+ "⚠ Provider reported context length exceeded; compacting history and retrying once..."
1214
+ );
1215
+ await compactHistoryArray({
1216
+ history,
1217
+ provider,
1218
+ model,
1219
+ settings: loopSettings,
1220
+ capabilities,
1221
+ readTracker: runnerState.readTracker,
1222
+ sink: safeSink,
1223
+ usableTokens: stepCtx.budget.usable,
1224
+ signal,
1225
+ onPruned: () => onCheckpoint?.(),
1226
+ onCompacted: () => onCheckpoint?.(),
1227
+ });
1228
+ stepCtx = await getStepContext();
1229
+ try {
1230
+ turn = await streamProviderTurn({
1231
+ provider,
1232
+ model,
1233
+ settings: loopSettings,
1234
+ messages: stepCtx.reqMessages,
1235
+ signal,
1236
+ sink: safeSink,
1237
+ capabilities,
1238
+ toolDefinitions: stepCtx.activeTools,
1239
+ maxTokensOverride,
1240
+ });
1241
+ } catch (retryErr) {
1242
+ throw new Error(`Context length exceeded even after compaction: ${retryErr.message}`);
1243
+ }
1244
+ } else {
1245
+ throw streamErr;
1246
+ }
1247
+ }
1248
+ if (signal?.aborted) throw createAbortError();
1249
+
1250
+ if (turn.usage?.prompt_tokens) {
1251
+ updateTokenCalibration(calibration, stepCtx.rawEstimate, turn.usage.prompt_tokens);
1252
+ }
1253
+
1254
+ lastUsage = turn.usage;
1255
+ loopStats.requests += 1;
1256
+ loopStats.steps += 1;
1257
+ loopStats.totalMs += turn.elapsedMs;
1258
+ if (turn.usage) {
1259
+ loopStats.promptTokens += turn.usage.prompt_tokens || 0;
1260
+ loopStats.completionTokens += turn.usage.completion_tokens || 0;
1261
+ loopStats.cacheReadTokens += turn.usage.cache_read_input_tokens || 0;
1262
+ loopStats.cacheWriteTokens += turn.usage.cache_creation_input_tokens || 0;
1263
+ }
1264
+ onTurnStats?.(turn);
1265
+
1266
+ // B14: Guard against empty silent assistant response
1267
+ if (!turn.toolCalls.length && !turn.content) {
1268
+ if (!emptyRetried) {
1269
+ emptyRetried = true;
1270
+ history.push({
1271
+ role: "user",
1272
+ content:
1273
+ "You returned an empty response. Provide a helpful final answer or call an appropriate tool.",
1274
+ });
1275
+ continue;
1276
+ }
1277
+ throw new Error("Model returned an empty response.");
1278
+ }
1279
+
1280
+ const assistantMsg = { role: "assistant", content: turn.content || "" };
1281
+ if (turn.toolCalls.length) assistantMsg.tool_calls = turn.toolCalls;
1282
+ if (Array.isArray(turn.thinkingBlocks) && turn.thinkingBlocks.length) {
1283
+ assistantMsg.thinkingBlocks = turn.thinkingBlocks;
1284
+ }
1285
+ if (turn.reasoning) assistantMsg.reasoningContent = turn.reasoning;
1286
+ history.push(assistantMsg);
1287
+
1288
+ const finishLower = String(turn.finishReason || "").toLowerCase();
1289
+ const isTruncated = TRUNCATED_FINISH_REASONS.has(finishLower);
1290
+ if (isTruncated) {
1291
+ consecutiveTruncations += 1;
1292
+ if (turn.toolCalls.length > 0) {
1293
+ if (safeSink.cleanupAllStreamWrites) {
1294
+ safeSink.cleanupAllStreamWrites(true);
1295
+ } else {
1296
+ for (let i = 0; i < turn.toolCalls.length; i++) {
1297
+ safeSink.cleanupStreamWrite?.(i, true);
1298
+ }
1299
+ }
1300
+ for (const tc of turn.toolCalls) {
1301
+ history.push({
1302
+ role: "tool",
1303
+ tool_call_id: tc.id,
1304
+ name: tc.function?.name || "unknown",
1305
+ content: TRUNCATION_TOOL_RETRY_MSG,
1306
+ isError: true,
1307
+ });
1308
+ }
1309
+ onCheckpoint?.();
1310
+
1311
+ if (consecutiveTruncations >= 3) {
1312
+ const regCaps = lookupModelCapabilities(model);
1313
+ const modelMax = regCaps.maxOutputTokens || DEFAULT_MAX_OUTPUT_TOKENS;
1314
+ const currentMax =
1315
+ maxTokensOverride ??
1316
+ (Number.isFinite(loopSettings?.maxTokens) ? loopSettings.maxTokens : null) ??
1317
+ Math.min(DEFAULT_MAX_OUTPUT_TOKENS, modelMax);
1318
+ if (!raisedOutputLimit && currentMax < modelMax) {
1319
+ raisedOutputLimit = true;
1320
+ maxTokensOverride = modelMax;
1321
+ safeSink.log(
1322
+ "system",
1323
+ `⚠ Output truncated ${consecutiveTruncations} times (${turn.finishReason}). Raised output token limit to ${modelMax}; asking model to retry.`
1324
+ );
1325
+ safeSink.syncStatus();
1326
+ continue;
1327
+ }
1328
+ const stopMsg = `Stopped turn after ${consecutiveTruncations} consecutive truncated tool responses (${turn.finishReason}). Break the task into smaller steps or raise maxTokens.`;
1329
+ safeSink.log("system", `⚠ ${stopMsg}`);
1330
+ safeSink.syncStatus();
1331
+ return {
1332
+ ok: false,
1333
+ answer: stopMsg,
1334
+ truncated: true,
1335
+ toolsUsed,
1336
+ usage: lastUsage,
1337
+ stats: loopStats,
1338
+ elapsedMs: loopStats.totalMs,
1339
+ };
1340
+ }
1341
+
1342
+ safeSink.log(
1343
+ "system",
1344
+ `⚠ Model output was truncated (${turn.finishReason}); none of ${turn.toolCalls.length} tool call(s) were executed. Asking model to retry in smaller pieces.`
1345
+ );
1346
+ safeSink.syncStatus();
1347
+ continue;
1348
+ }
1349
+ safeSink.log("system", `⚠ Model output was truncated (${turn.finishReason}).`);
1350
+ } else {
1351
+ consecutiveTruncations = 0;
1352
+ }
1353
+
1354
+ if (!turn.toolCalls.length) {
1355
+ finalAssistantText = turn.content;
1356
+ const sec = (turn.elapsedMs / 1000).toFixed(2);
1357
+ const ttftStr = turn.ttftMs >= 1000 ? `${(turn.ttftMs / 1000).toFixed(2)}s` : `${turn.ttftMs}ms`;
1358
+ const speedStr = turn.tokPerSec ? ` · ${turn.tokPerSec} tok/s` : "";
1359
+ const ctxStr = ` · Context: ~${turn.usage?.prompt_tokens || ctxEst} / ${ctxWin}`;
1360
+ const usageStr = turn.usage
1361
+ ? ` · Tokens: ${turn.usage.prompt_tokens ?? 0} in, ${turn.usage.completion_tokens ?? 0} out`
1362
+ : ` · Output: ~${turn.outTokens} tok`;
1363
+ if (loopSettings.verbosity !== "low") {
1364
+ safeSink.log("meta", `Response: ${sec}s · TTFT: ${ttftStr}${speedStr}${ctxStr}${usageStr}`);
1365
+ }
1366
+ if (turn.elapsedMs >= 5000) safeSink.notify?.();
1367
+
1368
+ if (onBeforeComplete) {
1369
+ const hookAction = await onBeforeComplete({ answer: finalAssistantText, turn, step, history });
1370
+ if (hookAction === "continue") continue;
1371
+ }
1372
+
1373
+ onCheckpoint?.();
1374
+ safeSink.syncStatus();
1375
+ return {
1376
+ ok: true,
1377
+ answer: finalAssistantText,
1378
+ toolsUsed,
1379
+ usage: lastUsage,
1380
+ stats: loopStats,
1381
+ elapsedMs: loopStats.totalMs,
1382
+ };
1383
+ }
1384
+
1385
+ for (const tc of turn.toolCalls) toolsUsed.push(tc.function.name);
1386
+ loopStats.toolCalls += turn.toolCalls.length;
1387
+ safeSink.setBusy("Running tools...");
1388
+ const strictNoRepair = !turn.finishReason;
1389
+ const toolResults = await runToolCalls(runnerState, turn.toolCalls, safeSink, { strictNoRepair, signal });
1390
+ if (signal?.aborted) throw createAbortError();
1391
+
1392
+ const loopCheck = loopDetector.record(turn.toolCalls, toolResults);
1393
+ if (loopCheck.repeated) {
1394
+ if (loopCheck.shouldStop) {
1395
+ history.push(...toolResults);
1396
+ onCheckpoint?.();
1397
+ safeSink.syncStatus();
1398
+ const stopMsg = `Stopped turn after ${loopCheck.detections} loop detections (${loopCheck.pattern}). Change approach or clarify what is blocking progress.`;
1399
+ safeSink.log("system", `⚠ ${stopMsg}`);
1400
+ return {
1401
+ ok: false,
1402
+ answer: stopMsg,
1403
+ loopDetected: true,
1404
+ toolsUsed,
1405
+ usage: lastUsage,
1406
+ stats: loopStats,
1407
+ elapsedMs: loopStats.totalMs,
1408
+ };
1409
+ }
1410
+ const lastRes = toolResults[toolResults.length - 1];
1411
+ if (lastRes && typeof lastRes.content === "string") {
1412
+ lastRes.content = `${lastRes.content}\n\n${loopCheck.hint}`;
1413
+ }
1414
+ safeSink.log("meta", `⚠ Loop pattern detected (${loopCheck.pattern}); hint added to tool result.`);
1415
+ }
1416
+
1417
+ history.push(...toolResults);
1418
+ onCheckpoint?.();
1419
+ safeSink.syncStatus();
1420
+ }
1421
+
1422
+ // 4.6 Last-step wrap-up: keep tool definitions (for Anthropic validity) with toolChoice="none"
1423
+ safeSink.log("system", `⚠ Reached maxToolSteps (${stepLimit}). Requesting final wrap-up without tools.`);
1424
+ history.push({ role: "user", content: STEP_LIMIT_WRAPUP_MSG });
1425
+ const wrapCtx = await getStepContext();
1426
+ try {
1427
+ const wrapTurn = await streamProviderTurn({
1428
+ provider,
1429
+ model,
1430
+ settings: loopSettings,
1431
+ messages: wrapCtx.reqMessages,
1432
+ signal,
1433
+ sink: safeSink,
1434
+ capabilities,
1435
+ toolDefinitions: wrapCtx.activeTools,
1436
+ toolChoice: "none",
1437
+ maxTokensOverride,
1438
+ });
1439
+ lastUsage = wrapTurn.usage || lastUsage;
1440
+ loopStats.requests += 1;
1441
+ loopStats.totalMs += wrapTurn.elapsedMs;
1442
+ if (wrapTurn.usage) {
1443
+ loopStats.promptTokens += wrapTurn.usage.prompt_tokens || 0;
1444
+ loopStats.completionTokens += wrapTurn.usage.completion_tokens || 0;
1445
+ loopStats.cacheReadTokens += wrapTurn.usage.cache_read_input_tokens || 0;
1446
+ loopStats.cacheWriteTokens += wrapTurn.usage.cache_creation_input_tokens || 0;
1447
+ }
1448
+ onTurnStats?.(wrapTurn);
1449
+ if (wrapTurn.content) {
1450
+ finalAssistantText = wrapTurn.content;
1451
+ history.push({ role: "assistant", content: wrapTurn.content });
1452
+ }
1453
+ } catch (wrapErr) {
1454
+ if (signal?.aborted || wrapErr?.name === "AbortError") throw wrapErr;
1455
+ safeSink.log("error", `Wrap-up request failed: ${wrapErr.message}`);
1456
+ }
1457
+ onCheckpoint?.();
1458
+ safeSink.syncStatus();
1459
+ return {
1460
+ ok: true,
1461
+ answer: finalAssistantText,
1462
+ stepLimitReached: true,
1463
+ toolsUsed,
1464
+ usage: lastUsage,
1465
+ stats: loopStats,
1466
+ elapsedMs: loopStats.totalMs,
1467
+ };
1468
+ } catch (err) {
1469
+ const isAbort = Boolean(signal?.aborted || err?.name === "AbortError" || err?.aborted);
1470
+ repairTranscriptTail(history, isAbort && Boolean(dropTrailingUserOnAbort));
1471
+ onCheckpoint?.();
1472
+ safeSink.syncStatus();
1473
+ if (isAbort && err?.name !== "AbortError") {
1474
+ throw createAbortError(err?.message || "Task cancelled by user");
1475
+ }
1476
+ throw err;
1477
+ }
1478
+ }
1479
+
1480
+ function isSkillManagementRequest(userText) {
1481
+ const raw = String(userText || "").trim();
1482
+ if (!raw) return false;
1483
+ if (raw.startsWith("/skill")) return true;
1484
+ const hasSkillNoun = /\bskills?\b/i.test(raw);
1485
+ if (!hasSkillNoun) return false;
1486
+ // If user asks to add/save/store/import/create/remove/list a skill (especially with a markdown file), let the skill tool handle it.
1487
+ return /\b(?:add|save|store|import|register|create|make|update|remove|delete|list|show)\b|\.(?:md|markdown)\b|\b(?:hisebe|hisabe)\b/i.test(
1488
+ raw
1489
+ );
1490
+ }
1491
+
1492
+ async function promptForRelevantSkills(state, userText, sink) {
1493
+ if (!sink || !sink.interactive) return [];
1494
+ if (isSkillManagementRequest(userText)) return [];
1495
+ const paths = state.paths || { projectDir: path.join(state.workspaceRoot || process.cwd(), ".kovence") };
1496
+ const allSkills = loadAllSkills(paths);
1497
+ if (!allSkills.length) return [];
1498
+ const matches = matchRelevantSkills(userText, allSkills);
1499
+ if (!matches.length) return [];
1500
+
1501
+ const items = [
1502
+ ...matches.map((s) => ({
1503
+ type: "skill",
1504
+ id: s.slug,
1505
+ label: `${s.title} [${s.slug}]`,
1506
+ desc: s.description || (s.tags?.length ? `tags: ${s.tags.join(", ")}` : `${s.scope} skill`),
1507
+ })),
1508
+ {
1509
+ type: "skip",
1510
+ id: "__skip__",
1511
+ label: "Skip (run without applying skills)",
1512
+ desc: "Proceed normally without injecting skill guidelines",
1513
+ },
1514
+ ];
1515
+
1516
+ let chosenIds = [];
1517
+ if (typeof sink.openMultiChoicePicker === "function") {
1518
+ chosenIds =
1519
+ (await sink.openMultiChoicePicker(`Select Skill(s) to Apply (${matches.length} matched)`, items)) || [];
1520
+ } else if (typeof sink.askPrompt === "function") {
1521
+ sink.log(
1522
+ "system",
1523
+ `Matching skills:\n${matches.map((s, i) => ` ${i + 1}. ${s.title} — ${s.description}`).join("\n")}`
1524
+ );
1525
+ const ans = (await sink.askPrompt("Select skill number(s) (e.g. 1,2 or 'all', Enter to skip): "))
1526
+ .trim()
1527
+ .toLowerCase();
1528
+ if (ans === "all" || ans === "*") {
1529
+ chosenIds = matches.map((s) => s.slug);
1530
+ } else if (ans && ans !== "0" && ans !== "skip" && ans !== "none") {
1531
+ for (const part of ans.split(/[\s,]+/)) {
1532
+ const n = Number.parseInt(part, 10);
1533
+ if (Number.isInteger(n) && n >= 1 && n <= matches.length) {
1534
+ const slug = matches[n - 1].slug;
1535
+ if (!chosenIds.includes(slug)) chosenIds.push(slug);
1536
+ }
1537
+ }
1538
+ }
1539
+ }
1540
+
1541
+ const pickedSet = new Set((Array.isArray(chosenIds) ? chosenIds : []).filter((id) => id && id !== "__skip__"));
1542
+ return matches.filter((s) => pickedSet.has(s.slug));
1543
+ }
1544
+
522
1545
  async function runAgentTurn(state, userText, sink, options = {}) {
523
1546
  state.lastFailedPrompt = "";
524
1547
  const workspaceRoot = state.workspaceRoot || process.cwd();
@@ -548,6 +1571,14 @@ async function runAgentTurn(state, userText, sink, options = {}) {
548
1571
  }
549
1572
 
550
1573
  const expanded = expandFileMentions(userText, workspaceRoot);
1574
+ let userContentForModel = expanded;
1575
+ if (!options.isRetry && !options.skipSkillPrompt) {
1576
+ const selectedSkills = await promptForRelevantSkills(state, userText, sink);
1577
+ if (selectedSkills.length > 0) {
1578
+ userContentForModel = `${expanded}\n\n${formatSelectedSkillsBlock(selectedSkills)}`;
1579
+ sink.log("meta", `✨ Applied skill(s): ${selectedSkills.map((s) => s.title).join(", ")}`);
1580
+ }
1581
+ }
551
1582
  if (!state.session.title && !options.isRetry) {
552
1583
  const cleanTitle = String(userText || "")
553
1584
  .replace(/\s+/g, " ")
@@ -555,7 +1586,11 @@ async function runAgentTurn(state, userText, sink, options = {}) {
555
1586
  .slice(0, 60);
556
1587
  if (cleanTitle) {
557
1588
  state.session.title = cleanTitle;
558
- if (/^session-\d{8}-\d{6}-[a-z0-9]+$/i.test(state.session.id) && state.paths) {
1589
+ // Match any auto-generated session ID pattern:
1590
+ // compact: session-20261119-102809-6a3
1591
+ // iso-like: session-2026-11-19-10-28-09-6a3
1592
+ const isAutoId = /^session-[\d][\d-]{6,}-[a-z0-9]{2,8}$/i.test(state.session.id);
1593
+ if (isAutoId && state.paths) {
559
1594
  const nextId = suggestSessionIdFromPrompt(userText, state.paths);
560
1595
  if (state.noSession) {
561
1596
  state.session.id = nextId;
@@ -572,85 +1607,45 @@ async function runAgentTurn(state, userText, sink, options = {}) {
572
1607
  `[debug] turn start · model=${state.model} · mode=${state.settings.agentMode} · history=${state.session.history.length}`
573
1608
  );
574
1609
  }
575
- state.session.history.push({ role: "user", content: expanded });
576
- const toolsUsed = [];
577
- let finalAssistantText = "";
578
- let lastUsage = null;
579
- let totalTurnMs = 0;
580
- let emptyRetried = false;
1610
+ state.session.history.push({ role: "user", content: userContentForModel });
581
1611
 
582
1612
  // Keep one AbortController alive across BOTH LLM streaming and all tool executions (download_file, run_command, etc.)
583
1613
  const turnAbort = new AbortController();
584
1614
  state.activeAbort = turnAbort;
1615
+ if (!state.tokenCalibration) state.tokenCalibration = createTokenCalibration();
585
1616
 
586
1617
  try {
587
- const maxSteps = Math.max(1, Number(state.settings.maxToolSteps) || 25);
588
- const loopDetector = new LoopDetector(3);
589
- for (let step = 0; step < maxSteps; step++) {
590
- if (turnAbort.signal.aborted) throw createAbortError();
591
- sink.setBusy(step ? `Step ${step + 1}...` : "Thinking...");
592
- const reqMessages = buildRequestMessages(state);
593
- const ctxEst = estimateMessagesTokens(reqMessages);
594
- const ctxWin = state.settings.contextWindow || 128000;
595
- if (state.settings.verbosity === "high" && step > 0) {
596
- sink.log("meta", `[verbose] Step ${step + 1}/${maxSteps} · ~${ctxEst} tokens`);
597
- }
598
-
599
- const turn = await streamProviderTurn({
600
- provider: state.provider,
601
- model: state.model,
602
- settings: state.settings,
603
- messages: reqMessages,
604
- signal: turnAbort.signal,
605
- sink,
606
- capabilities: state.capabilities,
607
- toolDefinitions: TOOL_DEFINITIONS,
608
- });
609
- if (turnAbort.signal.aborted) throw createAbortError();
610
-
611
- totalTurnMs += turn.elapsedMs;
612
- lastUsage = turn.usage;
613
- state.session.stats.requests += 1;
614
- state.session.stats.totalMs += turn.elapsedMs;
615
- state.session.stats.lastTtftMs = turn.ttftMs;
616
- state.session.stats.lastTokPerSec = turn.tokPerSec;
617
- if (turn.usage) {
618
- state.session.stats.promptTokens += turn.usage.prompt_tokens || 0;
619
- state.session.stats.completionTokens += turn.usage.completion_tokens || 0;
620
- }
621
-
622
- // B14: Guard against empty silent assistant response
623
- if (!turn.toolCalls.length && !turn.content) {
624
- if (!emptyRetried) {
625
- emptyRetried = true;
626
- state.session.history.push({
627
- role: "user",
628
- content:
629
- "You returned an empty response. Provide a helpful final answer or call an appropriate tool.",
630
- });
631
- continue;
632
- }
633
- throw new Error("Model returned an empty response.");
634
- }
635
-
636
- const assistantMsg = { role: "assistant", content: turn.content || "" };
637
- if (turn.toolCalls.length) assistantMsg.tool_calls = turn.toolCalls;
638
- state.session.history.push(assistantMsg);
639
-
640
- if (!turn.toolCalls.length) {
641
- finalAssistantText = turn.content;
642
- const sec = (turn.elapsedMs / 1000).toFixed(2);
643
- const ttftStr = turn.ttftMs >= 1000 ? `${(turn.ttftMs / 1000).toFixed(2)}s` : `${turn.ttftMs}ms`;
644
- const speedStr = turn.tokPerSec ? ` · ${turn.tokPerSec} tok/s` : "";
645
- const ctxStr = ` · Context: ~${turn.usage?.prompt_tokens || ctxEst} / ${ctxWin}`;
646
- const usageStr = turn.usage
647
- ? ` · Tokens: ${turn.usage.prompt_tokens ?? 0} in, ${turn.usage.completion_tokens ?? 0} out`
648
- : ` · Output: ~${turn.outTokens} tok`;
649
- if (state.settings.verbosity !== "low") {
650
- sink.log("meta", `Response: ${sec}s · TTFT: ${ttftStr}${speedStr}${ctxStr}${usageStr}`);
1618
+ const result = await runAgentLoop({
1619
+ history: state.session.history,
1620
+ provider: state.provider,
1621
+ model: state.model,
1622
+ settings: state.settings,
1623
+ maxSteps: Math.max(1, Number(state.settings.maxToolSteps) || 100),
1624
+ signal: turnAbort.signal,
1625
+ sink,
1626
+ permissions: { _state: state },
1627
+ capabilities: state.capabilities,
1628
+ tokenCalibration: state.tokenCalibration,
1629
+ prepareContextFn: (cal, sig) => prepareContextForStep(state, sink, cal, sig),
1630
+ dropTrailingUserOnAbort: true,
1631
+ onTurnStats: (turn) => {
1632
+ state.session.stats.requests += 1;
1633
+ state.session.stats.totalMs += turn.elapsedMs;
1634
+ state.session.stats.lastTtftMs = turn.ttftMs;
1635
+ state.session.stats.lastTokPerSec = turn.tokPerSec;
1636
+ if (turn.usage) {
1637
+ state.session.stats.promptTokens += turn.usage.prompt_tokens || 0;
1638
+ state.session.stats.completionTokens += turn.usage.completion_tokens || 0;
1639
+ state.session.stats.cacheReadTokens =
1640
+ (state.session.stats.cacheReadTokens || 0) + (turn.usage.cache_read_input_tokens || 0);
1641
+ state.session.stats.cacheWriteTokens =
1642
+ (state.session.stats.cacheWriteTokens || 0) + (turn.usage.cache_creation_input_tokens || 0);
651
1643
  }
652
- if (turn.elapsedMs >= 5000) sink.notify?.();
653
-
1644
+ },
1645
+ onCheckpoint: () => {
1646
+ if (!state.noSession) saveSession(state.session, state.paths);
1647
+ },
1648
+ onBeforeComplete: async () => {
654
1649
  // A2: Structured Plan Approval Workflow when finishing in 'plan' mode
655
1650
  if (state.settings.agentMode === "plan" && sink.interactive && sink.confirm) {
656
1651
  const ans = (
@@ -670,7 +1665,7 @@ async function runAgentTurn(state, userText, sink, options = {}) {
670
1665
  content:
671
1666
  "Plan approved. Switched to accept-edits mode. Proceed with implementing the plan now.",
672
1667
  });
673
- continue;
1668
+ return "continue";
674
1669
  }
675
1670
  if (ans === "2" || ans === "auto") {
676
1671
  state.settings.agentMode = "auto";
@@ -681,7 +1676,7 @@ async function runAgentTurn(state, userText, sink, options = {}) {
681
1676
  role: "user",
682
1677
  content: "Plan approved. Switched to auto mode. Proceed with implementing the plan now.",
683
1678
  });
684
- continue;
1679
+ return "continue";
685
1680
  }
686
1681
  if (ans === "3" || ans === "default") {
687
1682
  state.settings.agentMode = "default";
@@ -692,65 +1687,36 @@ async function runAgentTurn(state, userText, sink, options = {}) {
692
1687
  role: "user",
693
1688
  content: "Plan approved. Switched to default mode. Proceed step-by-step now.",
694
1689
  });
695
- continue;
1690
+ return "continue";
696
1691
  }
697
1692
  if (ans === "4") {
698
1693
  sink.log("meta", "Staying in 'plan' mode. Ask follow-up refinements in your next message.");
699
1694
  }
700
1695
  }
1696
+ return null;
1697
+ },
1698
+ });
701
1699
 
702
- if (!state.noSession) saveSession(state.session, state.paths);
703
- sink.syncStatus();
704
- // B20: Trigger non-blocking background session memory update
705
- void updateSessionMemory(state, userText, turn.content, toolsUsed, sink, {
706
- blocking: false,
707
- verbose: state.settings.verbosity === "high",
708
- });
709
- return {
710
- ok: true,
711
- answer: finalAssistantText,
712
- toolsUsed,
713
- usage: lastUsage,
714
- elapsedMs: totalTurnMs,
715
- };
716
- }
717
-
718
- for (const tc of turn.toolCalls) toolsUsed.push(tc.function.name);
719
- const loopCheck = loopDetector.record(turn.toolCalls);
720
- if (loopCheck.repeated) {
721
- sink.log(
722
- "system",
723
- `⚠ Detected repeated identical tool calls (${loopCheck.count}x). Asking model to try a different approach or summarize.`
724
- );
725
- state.session.history.push({
726
- role: "user",
727
- content:
728
- "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.",
729
- });
730
- if (!state.noSession) saveSession(state.session, state.paths);
731
- continue;
732
- }
733
- sink.setBusy("Running tools...");
734
- const toolResults = await runToolCalls(state, turn.toolCalls, sink);
735
- if (turnAbort.signal.aborted) throw createAbortError();
736
- state.session.history.push(...toolResults);
737
- if (!state.noSession) saveSession(state.session, state.paths);
738
- sink.syncStatus();
1700
+ if (result.ok && !result.stepLimitReached) {
1701
+ // B20: Trigger non-blocking background session memory update
1702
+ void updateSessionMemory(state, userText, result.answer, result.toolsUsed, sink, {
1703
+ blocking: false,
1704
+ verbose: state.settings.verbosity === "high",
1705
+ });
739
1706
  }
740
1707
 
741
- sink.log("system", `Reached maxToolSteps (${state.settings.maxToolSteps}).`);
742
- if (!state.noSession) saveSession(state.session, state.paths);
743
- return { ok: true, answer: finalAssistantText, toolsUsed, usage: lastUsage, elapsedMs: totalTurnMs };
1708
+ return {
1709
+ ok: result.ok,
1710
+ answer: result.answer,
1711
+ ...(result.truncated ? { truncated: true } : {}),
1712
+ ...(result.loopDetected ? { loopDetected: true } : {}),
1713
+ ...(result.stepLimitReached ? { stepLimitReached: true } : {}),
1714
+ toolsUsed: result.toolsUsed,
1715
+ usage: result.usage,
1716
+ elapsedMs: result.elapsedMs,
1717
+ };
744
1718
  } catch (err) {
745
- const isAbort = Boolean(turnAbort.signal.aborted || err?.name === "AbortError" || err?.aborted);
746
- // When user cancels, drop unanswered trailing user turn because the prompt is restored directly into the input box
747
- repairTranscriptTail(state.session.history, isAbort);
748
1719
  state.lastFailedPrompt = userText;
749
- if (!state.noSession) saveSession(state.session, state.paths);
750
- sink.syncStatus();
751
- if (isAbort && err?.name !== "AbortError") {
752
- throw createAbortError(err?.message || "Task cancelled by user");
753
- }
754
1720
  throw err;
755
1721
  } finally {
756
1722
  if (state.activeAbort === turnAbort) state.activeAbort = null;
@@ -758,33 +1724,24 @@ async function runAgentTurn(state, userText, sink, options = {}) {
758
1724
  }
759
1725
 
760
1726
  async function compactSession(state, sink) {
761
- if (state.session.history.length <= 2) {
762
- sink.log("system", "Session history already compact.");
763
- return;
764
- }
765
- const lastUserIdx = state.session.history.findLastIndex((m) => m.role === "user");
766
- const keepFrom = lastUserIdx > 0 ? lastUserIdx : state.session.history.length;
767
- const toSummarize = state.session.history.slice(0, keepFrom);
768
- const tail = state.session.history.slice(keepFrom);
769
- const textDump = toSummarize.map((m) => `${m.role}: ${m.content || JSON.stringify(m.tool_calls || "")}`).join("\n");
770
- await updateSessionMemory(state, textDump.slice(0, 3000), "(manual compaction)", [], sink, {
771
- force: true,
772
- blocking: true,
773
- verbose: true,
774
- });
775
- state.session.history = tail;
776
- if (!state.noSession) saveSession(state.session, state.paths);
777
- sink.syncStatus();
778
- sink.log("system", `Compacted ${toSummarize.length} messages into session memory summary.`);
1727
+ return compactHistoryWithZoneC(state, sink, { manual: true });
779
1728
  }
780
1729
 
781
1730
  module.exports = {
782
1731
  expandFileMentions,
1732
+ buildSystemMessages,
783
1733
  buildRequestMessages,
1734
+ prepareContextForStep,
1735
+ prepareLoopContext,
1736
+ compactHistoryWithZoneC,
1737
+ compactHistoryArray,
784
1738
  formatApprovalPreview,
785
1739
  waitForMemorySync,
786
1740
  updateSessionMemory,
1741
+ repairTranscriptTail,
1742
+ createAbortError,
787
1743
  runToolCalls,
1744
+ runAgentLoop,
788
1745
  runAgentTurn,
789
1746
  compactSession,
790
1747
  };