kovence-cli 1.2.0 → 1.3.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.
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
+ }
125
184
 
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];
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);
334
+
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,36 +639,49 @@ 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
659
  streamCheckpointed: state.streamCheckpointed,
291
- signal: state.activeAbort?.signal || null,
660
+ streamActiveWriteFiles: state.streamActiveWriteFiles || null,
661
+ signal: activeSignal,
292
662
  saveSession: (s) => {
293
- if (!state.noSession) saveSession(s, state.paths);
663
+ if (!state.noSession && state.paths && s) saveSession(s, state.paths);
664
+ },
665
+ loadGlobalMemory: () => (state.paths ? loadGlobalMemory(state.paths) : []),
666
+ saveGlobalMemory: (items) => {
667
+ if (state.paths) saveGlobalMemory(items, state.paths);
294
668
  },
295
- loadGlobalMemory: () => loadGlobalMemory(state.paths),
296
- saveGlobalMemory: (items) => saveGlobalMemory(items, state.paths),
297
- addGlobalMemory: (fact, src) => addGlobalMemory(fact, src, state.paths),
298
- getSudoPassword: () => state.sudoPasswords.get(state.session.id) || "",
669
+ addGlobalMemory: (fact, src) => (state.paths ? addGlobalMemory(fact, src, state.paths) : false),
670
+ getSudoPassword: () => sudoPasswords.get(sessionId) || "",
299
671
  setSudoPassword: (pw) => {
300
- if (pw) state.sudoPasswords.set(state.session.id, pw);
301
- else state.sudoPasswords.delete(state.session.id);
672
+ if (pw) sudoPasswords.set(sessionId, pw);
673
+ else sudoPasswords.delete(sessionId);
302
674
  },
303
- askPrompt: sink.askPrompt,
304
- askPassword: sink.askPassword,
305
- startProgress: sink.startProgress,
306
- setBusy: sink.setBusy,
307
- log: sink.log,
675
+ askPrompt: safeSink.askPrompt,
676
+ askPassword: safeSink.askPassword,
677
+ startProgress: safeSink.startProgress,
678
+ setBusy: safeSink.setBusy,
679
+ log: safeSink.log,
308
680
  });
309
681
 
310
682
  let downloadFailedOrCancelled = false;
683
+ const editedFilesInBatch = [];
684
+ let lastSuccessfulEditIdx = -1;
311
685
 
312
686
  const flushParallel = async () => {
313
687
  if (!parallelBatch.length) return;
@@ -316,7 +690,7 @@ async function runToolCalls(state, toolCalls, sink) {
316
690
  };
317
691
 
318
692
  for (let i = 0; i < toolCalls.length; i++) {
319
- if (state.activeAbort?.signal?.aborted) {
693
+ if (activeSignal?.aborted) {
320
694
  await flushParallel();
321
695
  throw createAbortError();
322
696
  }
@@ -328,24 +702,87 @@ async function runToolCalls(state, toolCalls, sink) {
328
702
  if (downloadFailedOrCancelled && name === "run_command") {
329
703
  const msg = "Skipped command because the preceding download did not complete.";
330
704
  results[i] = { role: "tool", tool_call_id: tc.id, name, content: msg };
331
- sink.log("tool", `⏸ ${name}(${summary}) skipped (download incomplete)`);
705
+ safeSink.log("tool", `⏸ ${name}(${summary}) skipped (download incomplete)`);
332
706
  continue;
333
707
  }
334
- let parsedArgs = {};
708
+ let parsedArgs;
335
709
  try {
336
710
  parsedArgs =
337
711
  typeof tc.function.arguments === "string"
338
- ? repairToolArguments(tc.function.arguments || "{}")
712
+ ? repairToolArguments(tc.function.arguments || "", { strict: strictNoRepair })
339
713
  : tc.function.arguments || {};
340
- } catch {}
714
+ } catch (parseErr) {
715
+ safeSink.cleanupStreamWrite?.(i, true);
716
+ results[i] = {
717
+ role: "tool",
718
+ tool_call_id: tc.id,
719
+ name,
720
+ 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.`,
721
+ isError: true,
722
+ };
723
+ safeSink.log("tool", `✗ ${name}(${summary}) invalid JSON arguments`);
724
+ continue;
725
+ }
726
+
727
+ const schema = TOOL_SCHEMA_BY_NAME.get(name);
728
+ if (schema) {
729
+ try {
730
+ validateToolArgs(parsedArgs, schema);
731
+ } catch (valErr) {
732
+ safeSink.cleanupStreamWrite?.(i, true);
733
+ results[i] = {
734
+ role: "tool",
735
+ tool_call_id: tc.id,
736
+ name,
737
+ 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.`,
738
+ isError: true,
739
+ };
740
+ safeSink.log("tool", `✗ ${name}(${summary}) invalid arguments: ${valErr.message}`);
741
+ continue;
742
+ }
743
+ }
744
+
745
+ if (state.allowedToolNames && !state.allowedToolNames.has(name)) {
746
+ results[i] = {
747
+ role: "tool",
748
+ tool_call_id: tc.id,
749
+ name,
750
+ content: `Error: Tool '${name}' is not allowed for this sub-agent.`,
751
+ isError: true,
752
+ };
753
+ safeSink.log("tool", `⛔ ${name}(${summary}) not allowed for sub-agent`);
754
+ continue;
755
+ }
756
+ if (state.blockedToolNames && state.blockedToolNames.has(name)) {
757
+ results[i] = {
758
+ role: "tool",
759
+ tool_call_id: tc.id,
760
+ name,
761
+ content: `Error: Tool '${name}' is blocked for this sub-agent.`,
762
+ isError: true,
763
+ };
764
+ safeSink.log("tool", `⛔ ${name}(${summary}) blocked for sub-agent`);
765
+ continue;
766
+ }
767
+ if (state.forceReadOnly && !EXPLORE_ALLOWED_TOOLS.has(name)) {
768
+ results[i] = {
769
+ role: "tool",
770
+ tool_call_id: tc.id,
771
+ name,
772
+ content: `Error: Tool '${name}' is blocked in read-only explore sub-agent.`,
773
+ isError: true,
774
+ };
775
+ safeSink.log("tool", `⛔ ${name}(${summary}) blocked in read-only mode`);
776
+ continue;
777
+ }
341
778
 
342
779
  const evalRes = evaluatePermission({
343
780
  toolName: name,
344
781
  args: parsedArgs,
345
- settings: state.settings,
782
+ settings: state.settings || {},
346
783
  workspaceRoot,
347
784
  extraDirs: state.extraDirs || [],
348
- sessionRules: state.sessionRules,
785
+ sessionRules,
349
786
  paths: state.paths,
350
787
  });
351
788
 
@@ -355,8 +792,9 @@ async function runToolCalls(state, toolCalls, sink) {
355
792
  tool_call_id: tc.id,
356
793
  name,
357
794
  content: evalRes.reason,
795
+ isError: true,
358
796
  };
359
- sink.log("tool", `⛔ ${name}(${summary}) blocked: ${evalRes.reason}`);
797
+ safeSink.log("tool", `⛔ ${name}(${summary}) blocked: ${evalRes.reason}`);
360
798
  continue;
361
799
  }
362
800
 
@@ -364,75 +802,87 @@ async function runToolCalls(state, toolCalls, sink) {
364
802
  let skipDownloadDestPrompt = Boolean(evalRes.matchedRule);
365
803
 
366
804
  if (evalRes.decision === "ask") {
367
- if (!sink.interactive || !sink.confirm) {
805
+ if (!safeSink.interactive || !safeSink.confirm) {
368
806
  results[i] = {
369
807
  role: "tool",
370
808
  tool_call_id: tc.id,
371
809
  name,
372
810
  content: `Denied: '${name}' requires interactive approval (${evalRes.reason}).`,
811
+ isError: true,
373
812
  };
374
- sink.log("tool", `✗ ${name}(${summary}) requires approval`);
813
+ safeSink.log("tool", `✗ ${name}(${summary}) requires approval`);
375
814
  continue;
376
815
  }
377
816
 
378
- const preview = formatApprovalPreview(name, parsedArgs, evalRes);
379
- sink.log("permission", preview);
380
- sink.notify?.();
381
- const rawChoice = (await sink.confirm(`Allow ${name}? [y=once / n=deny / s=session / A=always]: `)).trim();
382
- if (state.activeAbort?.signal?.aborted) {
383
- throw createAbortError();
384
- }
385
- const lowerChoice = rawChoice.toLowerCase();
386
-
387
- if (lowerChoice === "y" || lowerChoice === "yes") {
388
- approvedByUser = true;
389
- } else if ((lowerChoice === "s" || rawChoice === "A") && !evalRes.hardDenied && !evalRes.requiresSudo) {
390
- approvedByUser = true;
391
- const suggestions = buildSuggestedRules(name, parsedArgs, workspaceRoot);
392
- const defRule = suggestions[0];
393
- const altHint = suggestions.length > 1 ? ` or type 'tool' for all ${name}` : "";
394
- const scopeAns = (
395
- await sink.confirm(
396
- `Save ${lowerChoice === "s" ? "session" : "always (project)"} allow rule for ${defRule.label}${altHint}? [Enter=yes / n=once only]: `
817
+ const runAskFlow = async () => {
818
+ const labelPrefix = state.approvalLabel ? `${state.approvalLabel} ` : "";
819
+ const preview = formatApprovalPreview(name, parsedArgs, evalRes);
820
+ safeSink.log("permission", `${labelPrefix}${preview}`);
821
+ safeSink.notify?.();
822
+ const rawChoice = (
823
+ await safeSink.confirm(`${labelPrefix}Allow ${name}? [y=once / n=deny / s=session / A=always]: `)
824
+ ).trim();
825
+ if (activeSignal?.aborted) {
826
+ throw createAbortError();
827
+ }
828
+ const lowerChoice = rawChoice.toLowerCase();
829
+
830
+ if (lowerChoice === "y" || lowerChoice === "yes") {
831
+ approvedByUser = true;
832
+ } else if ((lowerChoice === "s" || rawChoice === "A") && !evalRes.hardDenied && !evalRes.requiresSudo) {
833
+ approvedByUser = true;
834
+ const suggestions = buildSuggestedRules(name, parsedArgs, workspaceRoot);
835
+ const defRule = suggestions[0];
836
+ const altHint = suggestions.length > 1 ? ` or type 'tool' for all ${name}` : "";
837
+ const scopeAns = (
838
+ await safeSink.confirm(
839
+ `${labelPrefix}Save ${lowerChoice === "s" ? "session" : "always (project)"} allow rule for ${defRule.label}${altHint}? [Enter=yes / n=once only]: `
840
+ )
397
841
  )
398
- )
399
- .trim()
400
- .toLowerCase();
842
+ .trim()
843
+ .toLowerCase();
401
844
 
402
- if (scopeAns !== "n" && scopeAns !== "no") {
403
- const picked =
404
- scopeAns === "tool" && suggestions[suggestions.length - 1]
405
- ? suggestions[suggestions.length - 1].rule
406
- : defRule.rule;
407
- if (lowerChoice === "s") {
408
- state.sessionRules.push(picked);
409
- sink.log(
410
- "meta",
411
- `✓ session rule added: ${picked.tool} (${picked.scope}: ${picked.pattern || "*"})`
412
- );
413
- } else {
414
- addPermissionRule(picked, "project", state.paths);
415
- sink.log(
416
- "meta",
417
- `✓ project rule saved: ${picked.tool} (${picked.scope}: ${picked.pattern || "*"})`
418
- );
845
+ if (scopeAns !== "n" && scopeAns !== "no") {
846
+ const picked =
847
+ scopeAns === "tool" && suggestions[suggestions.length - 1]
848
+ ? suggestions[suggestions.length - 1].rule
849
+ : defRule.rule;
850
+ if (lowerChoice === "s") {
851
+ sessionRules.push(picked);
852
+ safeSink.log(
853
+ "meta",
854
+ `✓ session rule added: ${picked.tool} (${picked.scope}: ${picked.pattern || "*"})`
855
+ );
856
+ } else if (state.paths) {
857
+ addPermissionRule(picked, "project", state.paths);
858
+ safeSink.log(
859
+ "meta",
860
+ `✓ project rule saved: ${picked.tool} (${picked.scope}: ${picked.pattern || "*"})`
861
+ );
862
+ }
863
+ skipDownloadDestPrompt = true;
419
864
  }
420
- skipDownloadDestPrompt = true;
865
+ } else if ((lowerChoice === "s" || rawChoice === "A") && (evalRes.hardDenied || evalRes.requiresSudo)) {
866
+ approvedByUser = true;
867
+ safeSink.log(
868
+ "meta",
869
+ "Note: hard-denylist/sudo commands are allowed once (cannot be permanently auto-allowed)."
870
+ );
871
+ } else {
872
+ return "denied";
421
873
  }
422
- } else if ((lowerChoice === "s" || rawChoice === "A") && (evalRes.hardDenied || evalRes.requiresSudo)) {
423
- approvedByUser = true;
424
- sink.log(
425
- "meta",
426
- "Note: hard-denylist/sudo commands are allowed once (cannot be permanently auto-allowed)."
427
- );
428
- } else {
429
- results[i] = { role: "tool", tool_call_id: tc.id, name, content: "Denied by user." };
430
- sink.log("tool", `✗ ${name}(${summary}) denied`);
431
- sink.cleanupStreamWrite?.(i, true);
874
+ return "approved";
875
+ };
876
+
877
+ const askOutcome = approvalMutex ? await approvalMutex.run(runAskFlow) : await runAskFlow();
878
+ if (askOutcome === "denied") {
879
+ results[i] = { role: "tool", tool_call_id: tc.id, name, content: "Denied by user.", isError: true };
880
+ safeSink.log("tool", `✗ ${name}(${summary}) denied`);
881
+ safeSink.cleanupStreamWrite?.(i, true);
432
882
  continue;
433
883
  }
434
884
  } else if (evalRes.matchedRule && evalRes.ruleLabel) {
435
- sink.log("meta", `✓ auto-allowed by rule: ${evalRes.ruleLabel}`);
885
+ safeSink.log("meta", `✓ auto-allowed by rule: ${evalRes.ruleLabel}`);
436
886
  }
437
887
 
438
888
  const isSequential =
@@ -446,18 +896,20 @@ async function runToolCalls(state, toolCalls, sink) {
446
896
 
447
897
  const runOne = async () => {
448
898
  const toolUi =
449
- name !== "download_file" && sink.startToolCall
450
- ? sink.startToolCall(`⚙ ${name}(${summary})`, { collapsible: true, toolIdx: i })
899
+ name !== "download_file" && name !== "task" && safeSink.startToolCall
900
+ ? safeSink.startToolCall(`⚙ ${name}(${summary})`, { collapsible: true, toolIdx: i })
451
901
  : null;
452
- if (!toolUi && name !== "download_file") {
453
- sink.log("tool", `⚙ ${name}(${summary})`);
902
+ if (!toolUi && name !== "download_file" && name !== "task") {
903
+ safeSink.log("tool", `⚙ ${name}(${summary})`);
454
904
  }
455
- if (name === "download_file") {
905
+ if (name === "task") {
906
+ safeSink.setBusy("Running sub-agent...");
907
+ } else if (name === "download_file") {
456
908
  state.isDownloading = true;
457
- sink.setBusy("Downloading (commands paused)...");
909
+ safeSink.setBusy("Downloading (commands paused)...");
458
910
  } else if (name === "write_file" || name === "edit_file" || name === "multi_edit") {
459
911
  const target = parsedArgs.path ? parsedArgs.path.split("/").pop() : "";
460
- sink.setBusy(`Writing ${target || "file"}...`);
912
+ safeSink.setBusy(`Writing ${target || "file"}...`);
461
913
  // Populate write stats for the live TUI write indicator.
462
914
  if (toolUi && toolUi.startWrite) {
463
915
  const writeContent =
@@ -470,35 +922,56 @@ async function runToolCalls(state, toolCalls, sink) {
470
922
  }
471
923
  } else if (name === "read_file" || name === "glob_files" || name === "grep_files") {
472
924
  const target = parsedArgs.path ? parsedArgs.path.split("/").pop() : "";
473
- sink.setBusy(`Reading ${target || "code"}...`);
925
+ safeSink.setBusy(`Reading ${target || "code"}...`);
474
926
  } else {
475
- sink.setBusy(`Running ${name}...`);
927
+ safeSink.setBusy(`Running ${name}...`);
476
928
  }
477
929
  try {
478
- const out = await executeTool(
479
- name,
480
- parsedArgs,
481
- makeCtx(approvedByUser, skipDownloadDestPrompt, (chunk) => toolUi?.pushOutput(chunk))
482
- );
930
+ const capturedImages = [];
931
+ const execCtx = makeCtx(approvedByUser, skipDownloadDestPrompt, (chunk) => toolUi?.pushOutput(chunk));
932
+ execCtx.attachToolImage = (img) => {
933
+ if (img && typeof img.data === "string" && img.data) {
934
+ capturedImages.push(img);
935
+ }
936
+ };
937
+ const out = await executeTool(name, parsedArgs, execCtx);
483
938
  const outStr = String(out);
484
- results[i] = { role: "tool", tool_call_id: tc.id, name, content: outStr };
485
- toolUi?.finish(outStr, /^Exit |^Command timed out/i.test(outStr));
939
+ const failed = isToolFailure(outStr) || /^Command timed out/i.test(outStr);
940
+ results[i] = {
941
+ role: "tool",
942
+ tool_call_id: tc.id,
943
+ name,
944
+ content: outStr,
945
+ ...(capturedImages.length ? { images: capturedImages } : {}),
946
+ ...(failed ? { isError: true } : {}),
947
+ };
948
+ if (!failed && POST_EDIT_CHECK_TOOLS.has(name)) {
949
+ editedFilesInBatch.push(...extractEditedFilesFromCall(name, parsedArgs));
950
+ lastSuccessfulEditIdx = i;
951
+ }
952
+ toolUi?.finish(outStr, failed);
486
953
  if (name === "download_file" && /^Download cancelled/i.test(outStr)) {
487
954
  downloadFailedOrCancelled = true;
488
955
  }
489
956
  } catch (err) {
490
- if (state.activeAbort?.signal?.aborted || err?.aborted || err?.name === "AbortError") {
957
+ if (activeSignal?.aborted || err?.aborted || err?.name === "AbortError") {
491
958
  toolUi?.finish("Aborted by user", true);
492
959
  throw createAbortError(err?.message || "Task cancelled by user");
493
960
  }
494
961
  if (name === "download_file") downloadFailedOrCancelled = true;
495
- results[i] = { role: "tool", tool_call_id: tc.id, name, content: `Error: ${err.message}` };
962
+ results[i] = {
963
+ role: "tool",
964
+ tool_call_id: tc.id,
965
+ name,
966
+ content: `Error: ${err.message}`,
967
+ isError: true,
968
+ };
496
969
  toolUi?.finish(`Error: ${err.message}`, true);
497
- sink.log("error", `✗ ${name}: ${err.message}`);
970
+ safeSink.log("error", `✗ ${name}: ${err.message}`);
498
971
  } finally {
499
972
  if (name === "download_file") {
500
973
  state.isDownloading = false;
501
- sink.syncStatus();
974
+ safeSink.syncStatus();
502
975
  }
503
976
  }
504
977
  };
@@ -513,17 +986,53 @@ async function runToolCalls(state, toolCalls, sink) {
513
986
  }
514
987
 
515
988
  await flushParallel();
989
+ if (lastSuccessfulEditIdx >= 0 && results[lastSuccessfulEditIdx]) {
990
+ const checkCtx = makeCtx(false, false);
991
+ checkCtx.skipPostEditCheck = false;
992
+ const checkRes = await runPostEditCheck({
993
+ files: editedFilesInBatch,
994
+ ctx: checkCtx,
995
+ signal: activeSignal,
996
+ });
997
+ if (checkRes.ran && checkRes.text) {
998
+ results[lastSuccessfulEditIdx].content = `${results[lastSuccessfulEditIdx].content}${checkRes.text}`;
999
+ safeSink.log("meta", checkRes.text.trim());
1000
+ }
1001
+ }
516
1002
  return results;
517
1003
  }
518
1004
 
519
1005
  function repairTranscriptTail(history, dropTrailingUser = false) {
520
- // Keep completed steps intact; trim trailing unfulfilled tool_calls or orphan tool messages so /retry & resume work cleanly.
1006
+ // Keep completed steps intact; trim trailing unfulfilled tool_calls, partial tool groups, or orphan tool messages so /retry & resume work cleanly.
521
1007
  while (history.length > 0) {
522
1008
  const last = history[history.length - 1];
523
1009
  if (last.role === "assistant" && Array.isArray(last.tool_calls) && last.tool_calls.length > 0) {
524
1010
  history.pop();
525
1011
  continue;
526
1012
  }
1013
+ if (last.role === "tool") {
1014
+ let firstToolIdx = history.length - 1;
1015
+ while (firstToolIdx > 0 && history[firstToolIdx - 1].role === "tool") {
1016
+ firstToolIdx -= 1;
1017
+ }
1018
+ const prev = firstToolIdx > 0 ? history[firstToolIdx - 1] : null;
1019
+ if (!prev || prev.role !== "assistant" || !Array.isArray(prev.tool_calls) || !prev.tool_calls.length) {
1020
+ history.splice(firstToolIdx);
1021
+ continue;
1022
+ }
1023
+ const expectedIds = prev.tool_calls.map((tc) => tc.id).filter(Boolean);
1024
+ const actualIds = new Set(
1025
+ history
1026
+ .slice(firstToolIdx)
1027
+ .map((m) => m.tool_call_id)
1028
+ .filter(Boolean)
1029
+ );
1030
+ const allMatched = expectedIds.every((id) => actualIds.has(id));
1031
+ if (!allMatched) {
1032
+ history.splice(firstToolIdx - 1);
1033
+ continue;
1034
+ }
1035
+ }
527
1036
  break;
528
1037
  }
529
1038
  if (dropTrailingUser && history.length > 0 && history[history.length - 1].role === "user") {
@@ -531,6 +1040,509 @@ function repairTranscriptTail(history, dropTrailingUser = false) {
531
1040
  }
532
1041
  }
533
1042
 
1043
+ function resolveLoopSystemMessages({ systemPrompt, settings, model, provider, permissions }) {
1044
+ if (typeof systemPrompt === "function") return systemPrompt();
1045
+ if (Array.isArray(systemPrompt)) return systemPrompt;
1046
+ if (typeof systemPrompt === "string" && systemPrompt.length > 0) {
1047
+ return [{ role: "system", content: systemPrompt }];
1048
+ }
1049
+ const workspaceRoot = permissions?.workspaceRoot || process.cwd();
1050
+ const stablePrompt = buildStableSystemPrompt({
1051
+ systemPrompt: settings?.systemPrompt,
1052
+ model,
1053
+ providerType: provider?.type,
1054
+ language: settings?.language,
1055
+ includeDelegation: false,
1056
+ });
1057
+ const sysParts = [
1058
+ stablePrompt,
1059
+ `Workspace Root: ${workspaceRoot}\nEnvironment: ${gatherEnvironmentSummary(workspaceRoot)}`,
1060
+ ];
1061
+ return [{ role: "system", content: sysParts.join("\n\n") }];
1062
+ }
1063
+
1064
+ function resolveLoopTools({ tools, settings, model, provider }) {
1065
+ if (typeof tools === "function") return tools();
1066
+ if (Array.isArray(tools)) return tools;
1067
+ if (settings?.toolsEnabled === false) return [];
1068
+ return getToolsForRequest({
1069
+ model,
1070
+ providerType: provider?.type,
1071
+ toolset: settings?.toolset || "core",
1072
+ includeTask: false,
1073
+ });
1074
+ }
1075
+
1076
+ /**
1077
+ * Stateless multi-step LLM + tool loop operating solely on the supplied `history` array.
1078
+ * Does not touch any global session store unless caller-supplied hooks choose to.
1079
+ */
1080
+ async function runAgentLoop({
1081
+ history,
1082
+ tools = null,
1083
+ systemPrompt = null,
1084
+ provider,
1085
+ model,
1086
+ settings = {},
1087
+ maxSteps = null,
1088
+ signal = null,
1089
+ sink = null,
1090
+ permissions = {},
1091
+ capabilities = {},
1092
+ tokenCalibration = null,
1093
+ prepareContextFn = null,
1094
+ onTurnStats = null,
1095
+ onCheckpoint = null,
1096
+ onBeforeComplete = null,
1097
+ dropTrailingUserOnAbort = false,
1098
+ }) {
1099
+ if (!Array.isArray(history)) {
1100
+ throw new Error("runAgentLoop requires a history array");
1101
+ }
1102
+ const safeSink = sink || createNoopSink();
1103
+ const calibration = tokenCalibration || createTokenCalibration();
1104
+ const loopSettings = permissions?.settings || settings || {};
1105
+ const stepLimit = Math.max(1, Number(maxSteps ?? loopSettings.maxToolSteps) || 100);
1106
+ const loopStats = {
1107
+ requests: 0,
1108
+ totalMs: 0,
1109
+ promptTokens: 0,
1110
+ completionTokens: 0,
1111
+ cacheReadTokens: 0,
1112
+ cacheWriteTokens: 0,
1113
+ steps: 0,
1114
+ toolCalls: 0,
1115
+ };
1116
+
1117
+ const runnerState = permissions?._state || {
1118
+ workspaceRoot: permissions?.workspaceRoot || process.cwd(),
1119
+ paths: permissions?.paths || null,
1120
+ extraDirs: permissions?.extraDirs || [],
1121
+ settings: {
1122
+ ...loopSettings,
1123
+ ...(permissions?.agentMode ? { agentMode: permissions.agentMode } : {}),
1124
+ ...(permissions?.toolPermission ? { toolPermission: permissions.toolPermission } : {}),
1125
+ ...(permissions?.nonWorkspaceAccess ? { nonWorkspaceAccess: permissions.nonWorkspaceAccess } : {}),
1126
+ },
1127
+ sessionRules: permissions?.sessionRules || [],
1128
+ session: permissions?.session || null,
1129
+ noSession: permissions?.noSession !== undefined ? Boolean(permissions.noSession) : true,
1130
+ readTracker: permissions?.readTracker || new ReadTracker(),
1131
+ readTrackerSessionId: permissions?.session?.id || "loop",
1132
+ sudoPasswords: permissions?.sudoPasswords || new Map(),
1133
+ bgTasks: permissions?.bgTasks || null,
1134
+ streamCheckpointed: permissions?.streamCheckpointed || null,
1135
+ provider,
1136
+ model,
1137
+ capabilities,
1138
+ allowedToolNames: permissions?.allowedToolNames || null,
1139
+ blockedToolNames: permissions?.blockedToolNames || null,
1140
+ forceReadOnly: Boolean(permissions?.forceReadOnly),
1141
+ approvalMutex: permissions?.approvalMutex || null,
1142
+ approvalLabel: permissions?.approvalLabel || "",
1143
+ activeAbort: signal ? { signal } : null,
1144
+ };
1145
+
1146
+ const warnState = { warnedUnknownContextWindow: false };
1147
+ const getStepContext = async () => {
1148
+ if (typeof prepareContextFn === "function") {
1149
+ return prepareContextFn(calibration, signal);
1150
+ }
1151
+ const sysMsgs = resolveLoopSystemMessages({
1152
+ systemPrompt,
1153
+ settings: loopSettings,
1154
+ model,
1155
+ provider,
1156
+ permissions,
1157
+ });
1158
+ const activeTools = resolveLoopTools({ tools, settings: loopSettings, model, provider });
1159
+ return prepareLoopContext({
1160
+ history,
1161
+ sysMsgs,
1162
+ activeTools,
1163
+ provider,
1164
+ model,
1165
+ settings: loopSettings,
1166
+ capabilities,
1167
+ readTracker: runnerState.readTracker,
1168
+ calibration,
1169
+ sink: safeSink,
1170
+ signal,
1171
+ warnState,
1172
+ });
1173
+ };
1174
+
1175
+ const toolsUsed = [];
1176
+ let finalAssistantText = "";
1177
+ let lastUsage = null;
1178
+ let emptyRetried = false;
1179
+ let consecutiveTruncations = 0;
1180
+ let raisedOutputLimit = false;
1181
+ let maxTokensOverride = null;
1182
+
1183
+ try {
1184
+ const loopDetector = new LoopDetector(3);
1185
+
1186
+ for (let step = 0; step < stepLimit; step++) {
1187
+ if (signal?.aborted) throw createAbortError();
1188
+ safeSink.setBusy(step ? `Step ${step + 1}...` : "Thinking...");
1189
+
1190
+ let stepCtx = await getStepContext();
1191
+ const ctxEst = stepCtx.calibratedEstimate;
1192
+ const ctxWin = stepCtx.budget.contextWindow;
1193
+ if (loopSettings.verbosity === "high" && step > 0) {
1194
+ safeSink.log("meta", `[verbose] Step ${step + 1}/${stepLimit} · ~${ctxEst} tokens`);
1195
+ }
1196
+
1197
+ let turn;
1198
+ try {
1199
+ turn = await streamProviderTurn({
1200
+ provider,
1201
+ model,
1202
+ settings: loopSettings,
1203
+ messages: stepCtx.reqMessages,
1204
+ signal,
1205
+ sink: safeSink,
1206
+ capabilities,
1207
+ toolDefinitions: stepCtx.activeTools,
1208
+ maxTokensOverride,
1209
+ });
1210
+ } catch (streamErr) {
1211
+ if (!signal?.aborted && isContextLengthError(streamErr)) {
1212
+ safeSink.log(
1213
+ "system",
1214
+ "⚠ Provider reported context length exceeded; compacting history and retrying once..."
1215
+ );
1216
+ await compactHistoryArray({
1217
+ history,
1218
+ provider,
1219
+ model,
1220
+ settings: loopSettings,
1221
+ capabilities,
1222
+ readTracker: runnerState.readTracker,
1223
+ sink: safeSink,
1224
+ usableTokens: stepCtx.budget.usable,
1225
+ signal,
1226
+ onPruned: () => onCheckpoint?.(),
1227
+ onCompacted: () => onCheckpoint?.(),
1228
+ });
1229
+ stepCtx = await getStepContext();
1230
+ try {
1231
+ turn = await streamProviderTurn({
1232
+ provider,
1233
+ model,
1234
+ settings: loopSettings,
1235
+ messages: stepCtx.reqMessages,
1236
+ signal,
1237
+ sink: safeSink,
1238
+ capabilities,
1239
+ toolDefinitions: stepCtx.activeTools,
1240
+ maxTokensOverride,
1241
+ });
1242
+ } catch (retryErr) {
1243
+ throw new Error(`Context length exceeded even after compaction: ${retryErr.message}`);
1244
+ }
1245
+ } else {
1246
+ throw streamErr;
1247
+ }
1248
+ }
1249
+ if (signal?.aborted) throw createAbortError();
1250
+
1251
+ if (turn.usage?.prompt_tokens) {
1252
+ updateTokenCalibration(calibration, stepCtx.rawEstimate, turn.usage.prompt_tokens);
1253
+ }
1254
+
1255
+ lastUsage = turn.usage;
1256
+ loopStats.requests += 1;
1257
+ loopStats.steps += 1;
1258
+ loopStats.totalMs += turn.elapsedMs;
1259
+ if (turn.usage) {
1260
+ loopStats.promptTokens += turn.usage.prompt_tokens || 0;
1261
+ loopStats.completionTokens += turn.usage.completion_tokens || 0;
1262
+ loopStats.cacheReadTokens += turn.usage.cache_read_input_tokens || 0;
1263
+ loopStats.cacheWriteTokens += turn.usage.cache_creation_input_tokens || 0;
1264
+ }
1265
+ onTurnStats?.(turn);
1266
+
1267
+ // B14: Guard against empty silent assistant response
1268
+ if (!turn.toolCalls.length && !turn.content) {
1269
+ if (!emptyRetried) {
1270
+ emptyRetried = true;
1271
+ history.push({
1272
+ role: "user",
1273
+ content:
1274
+ "You returned an empty response. Provide a helpful final answer or call an appropriate tool.",
1275
+ });
1276
+ continue;
1277
+ }
1278
+ throw new Error("Model returned an empty response.");
1279
+ }
1280
+
1281
+ const assistantMsg = { role: "assistant", content: turn.content || "" };
1282
+ if (turn.toolCalls.length) assistantMsg.tool_calls = turn.toolCalls;
1283
+ if (Array.isArray(turn.thinkingBlocks) && turn.thinkingBlocks.length) {
1284
+ assistantMsg.thinkingBlocks = turn.thinkingBlocks;
1285
+ }
1286
+ if (turn.reasoning) assistantMsg.reasoningContent = turn.reasoning;
1287
+ history.push(assistantMsg);
1288
+
1289
+ const finishLower = String(turn.finishReason || "").toLowerCase();
1290
+ const isTruncated = TRUNCATED_FINISH_REASONS.has(finishLower);
1291
+ if (isTruncated) {
1292
+ consecutiveTruncations += 1;
1293
+ if (turn.toolCalls.length > 0) {
1294
+ if (safeSink.cleanupAllStreamWrites) {
1295
+ safeSink.cleanupAllStreamWrites(true);
1296
+ } else {
1297
+ for (let i = 0; i < turn.toolCalls.length; i++) {
1298
+ safeSink.cleanupStreamWrite?.(i, true);
1299
+ }
1300
+ }
1301
+ for (const tc of turn.toolCalls) {
1302
+ history.push({
1303
+ role: "tool",
1304
+ tool_call_id: tc.id,
1305
+ name: tc.function?.name || "unknown",
1306
+ content: TRUNCATION_TOOL_RETRY_MSG,
1307
+ isError: true,
1308
+ });
1309
+ }
1310
+ onCheckpoint?.();
1311
+
1312
+ if (consecutiveTruncations >= 3) {
1313
+ const regCaps = lookupModelCapabilities(model);
1314
+ const modelMax = regCaps.maxOutputTokens || DEFAULT_MAX_OUTPUT_TOKENS;
1315
+ const currentMax =
1316
+ maxTokensOverride ??
1317
+ (Number.isFinite(loopSettings?.maxTokens) ? loopSettings.maxTokens : null) ??
1318
+ Math.min(DEFAULT_MAX_OUTPUT_TOKENS, modelMax);
1319
+ if (!raisedOutputLimit && currentMax < modelMax) {
1320
+ raisedOutputLimit = true;
1321
+ maxTokensOverride = modelMax;
1322
+ safeSink.log(
1323
+ "system",
1324
+ `⚠ Output truncated ${consecutiveTruncations} times (${turn.finishReason}). Raised output token limit to ${modelMax}; asking model to retry.`
1325
+ );
1326
+ safeSink.syncStatus();
1327
+ continue;
1328
+ }
1329
+ const stopMsg = `Stopped turn after ${consecutiveTruncations} consecutive truncated tool responses (${turn.finishReason}). Break the task into smaller steps or raise maxTokens.`;
1330
+ safeSink.log("system", `⚠ ${stopMsg}`);
1331
+ safeSink.syncStatus();
1332
+ return {
1333
+ ok: false,
1334
+ answer: stopMsg,
1335
+ truncated: true,
1336
+ toolsUsed,
1337
+ usage: lastUsage,
1338
+ stats: loopStats,
1339
+ elapsedMs: loopStats.totalMs,
1340
+ };
1341
+ }
1342
+
1343
+ safeSink.log(
1344
+ "system",
1345
+ `⚠ Model output was truncated (${turn.finishReason}); none of ${turn.toolCalls.length} tool call(s) were executed. Asking model to retry in smaller pieces.`
1346
+ );
1347
+ safeSink.syncStatus();
1348
+ continue;
1349
+ }
1350
+ safeSink.log("system", `⚠ Model output was truncated (${turn.finishReason}).`);
1351
+ } else {
1352
+ consecutiveTruncations = 0;
1353
+ }
1354
+
1355
+ if (!turn.toolCalls.length) {
1356
+ finalAssistantText = turn.content;
1357
+ const sec = (turn.elapsedMs / 1000).toFixed(2);
1358
+ const ttftStr = turn.ttftMs >= 1000 ? `${(turn.ttftMs / 1000).toFixed(2)}s` : `${turn.ttftMs}ms`;
1359
+ const speedStr = turn.tokPerSec ? ` · ${turn.tokPerSec} tok/s` : "";
1360
+ const ctxStr = ` · Context: ~${turn.usage?.prompt_tokens || ctxEst} / ${ctxWin}`;
1361
+ const usageStr = turn.usage
1362
+ ? ` · Tokens: ${turn.usage.prompt_tokens ?? 0} in, ${turn.usage.completion_tokens ?? 0} out`
1363
+ : ` · Output: ~${turn.outTokens} tok`;
1364
+ if (loopSettings.verbosity !== "low") {
1365
+ safeSink.log("meta", `Response: ${sec}s · TTFT: ${ttftStr}${speedStr}${ctxStr}${usageStr}`);
1366
+ }
1367
+ if (turn.elapsedMs >= 5000) safeSink.notify?.();
1368
+
1369
+ if (onBeforeComplete) {
1370
+ const hookAction = await onBeforeComplete({ answer: finalAssistantText, turn, step, history });
1371
+ if (hookAction === "continue") continue;
1372
+ }
1373
+
1374
+ onCheckpoint?.();
1375
+ safeSink.syncStatus();
1376
+ return {
1377
+ ok: true,
1378
+ answer: finalAssistantText,
1379
+ toolsUsed,
1380
+ usage: lastUsage,
1381
+ stats: loopStats,
1382
+ elapsedMs: loopStats.totalMs,
1383
+ };
1384
+ }
1385
+
1386
+ for (const tc of turn.toolCalls) toolsUsed.push(tc.function.name);
1387
+ loopStats.toolCalls += turn.toolCalls.length;
1388
+ safeSink.setBusy("Running tools...");
1389
+ const strictNoRepair = !turn.finishReason;
1390
+ const toolResults = await runToolCalls(runnerState, turn.toolCalls, safeSink, { strictNoRepair, signal });
1391
+ if (signal?.aborted) throw createAbortError();
1392
+
1393
+ const loopCheck = loopDetector.record(turn.toolCalls, toolResults);
1394
+ if (loopCheck.repeated) {
1395
+ if (loopCheck.shouldStop) {
1396
+ history.push(...toolResults);
1397
+ onCheckpoint?.();
1398
+ safeSink.syncStatus();
1399
+ const stopMsg = `Stopped turn after ${loopCheck.detections} loop detections (${loopCheck.pattern}). Change approach or clarify what is blocking progress.`;
1400
+ safeSink.log("system", `⚠ ${stopMsg}`);
1401
+ return {
1402
+ ok: false,
1403
+ answer: stopMsg,
1404
+ loopDetected: true,
1405
+ toolsUsed,
1406
+ usage: lastUsage,
1407
+ stats: loopStats,
1408
+ elapsedMs: loopStats.totalMs,
1409
+ };
1410
+ }
1411
+ const lastRes = toolResults[toolResults.length - 1];
1412
+ if (lastRes && typeof lastRes.content === "string") {
1413
+ lastRes.content = `${lastRes.content}\n\n${loopCheck.hint}`;
1414
+ }
1415
+ safeSink.log("meta", `⚠ Loop pattern detected (${loopCheck.pattern}); hint added to tool result.`);
1416
+ }
1417
+
1418
+ history.push(...toolResults);
1419
+ onCheckpoint?.();
1420
+ safeSink.syncStatus();
1421
+ }
1422
+
1423
+ // 4.6 Last-step wrap-up: keep tool definitions (for Anthropic validity) with toolChoice="none"
1424
+ safeSink.log("system", `⚠ Reached maxToolSteps (${stepLimit}). Requesting final wrap-up without tools.`);
1425
+ history.push({ role: "user", content: STEP_LIMIT_WRAPUP_MSG });
1426
+ const wrapCtx = await getStepContext();
1427
+ try {
1428
+ const wrapTurn = await streamProviderTurn({
1429
+ provider,
1430
+ model,
1431
+ settings: loopSettings,
1432
+ messages: wrapCtx.reqMessages,
1433
+ signal,
1434
+ sink: safeSink,
1435
+ capabilities,
1436
+ toolDefinitions: wrapCtx.activeTools,
1437
+ toolChoice: "none",
1438
+ maxTokensOverride,
1439
+ });
1440
+ lastUsage = wrapTurn.usage || lastUsage;
1441
+ loopStats.requests += 1;
1442
+ loopStats.totalMs += wrapTurn.elapsedMs;
1443
+ if (wrapTurn.usage) {
1444
+ loopStats.promptTokens += wrapTurn.usage.prompt_tokens || 0;
1445
+ loopStats.completionTokens += wrapTurn.usage.completion_tokens || 0;
1446
+ loopStats.cacheReadTokens += wrapTurn.usage.cache_read_input_tokens || 0;
1447
+ loopStats.cacheWriteTokens += wrapTurn.usage.cache_creation_input_tokens || 0;
1448
+ }
1449
+ onTurnStats?.(wrapTurn);
1450
+ if (wrapTurn.content) {
1451
+ finalAssistantText = wrapTurn.content;
1452
+ history.push({ role: "assistant", content: wrapTurn.content });
1453
+ }
1454
+ } catch (wrapErr) {
1455
+ if (signal?.aborted || wrapErr?.name === "AbortError") throw wrapErr;
1456
+ safeSink.log("error", `Wrap-up request failed: ${wrapErr.message}`);
1457
+ }
1458
+ onCheckpoint?.();
1459
+ safeSink.syncStatus();
1460
+ return {
1461
+ ok: true,
1462
+ answer: finalAssistantText,
1463
+ stepLimitReached: true,
1464
+ toolsUsed,
1465
+ usage: lastUsage,
1466
+ stats: loopStats,
1467
+ elapsedMs: loopStats.totalMs,
1468
+ };
1469
+ } catch (err) {
1470
+ const isAbort = Boolean(signal?.aborted || err?.name === "AbortError" || err?.aborted);
1471
+ repairTranscriptTail(history, isAbort && Boolean(dropTrailingUserOnAbort));
1472
+ onCheckpoint?.();
1473
+ safeSink.syncStatus();
1474
+ if (isAbort && err?.name !== "AbortError") {
1475
+ throw createAbortError(err?.message || "Task cancelled by user");
1476
+ }
1477
+ throw err;
1478
+ }
1479
+ }
1480
+
1481
+ function isSkillManagementRequest(userText) {
1482
+ const raw = String(userText || "").trim();
1483
+ if (!raw) return false;
1484
+ if (raw.startsWith("/skill")) return true;
1485
+ const hasSkillNoun = /\bskills?\b/i.test(raw);
1486
+ if (!hasSkillNoun) return false;
1487
+ // If user asks to add/save/store/import/create/remove/list a skill (especially with a markdown file), let the skill tool handle it.
1488
+ return /\b(?:add|save|store|import|register|create|make|update|remove|delete|list|show)\b|\.(?:md|markdown)\b|\b(?:hisebe|hisabe)\b/i.test(
1489
+ raw
1490
+ );
1491
+ }
1492
+
1493
+ async function promptForRelevantSkills(state, userText, sink) {
1494
+ if (!sink || !sink.interactive) return [];
1495
+ if (isSkillManagementRequest(userText)) return [];
1496
+ const paths = state.paths || { projectDir: path.join(state.workspaceRoot || process.cwd(), ".kovence") };
1497
+ const allSkills = loadAllSkills(paths);
1498
+ if (!allSkills.length) return [];
1499
+ const matches = matchRelevantSkills(userText, allSkills);
1500
+ if (!matches.length) return [];
1501
+
1502
+ const items = [
1503
+ ...matches.map((s) => ({
1504
+ type: "skill",
1505
+ id: s.slug,
1506
+ label: `${s.title} [${s.slug}]`,
1507
+ desc: s.description || (s.tags?.length ? `tags: ${s.tags.join(", ")}` : `${s.scope} skill`),
1508
+ })),
1509
+ {
1510
+ type: "skip",
1511
+ id: "__skip__",
1512
+ label: "Skip (run without applying skills)",
1513
+ desc: "Proceed normally without injecting skill guidelines",
1514
+ },
1515
+ ];
1516
+
1517
+ let chosenIds = [];
1518
+ if (typeof sink.openMultiChoicePicker === "function") {
1519
+ chosenIds =
1520
+ (await sink.openMultiChoicePicker(`Select Skill(s) to Apply (${matches.length} matched)`, items)) || [];
1521
+ } else if (typeof sink.askPrompt === "function") {
1522
+ sink.log(
1523
+ "system",
1524
+ `Matching skills:\n${matches.map((s, i) => ` ${i + 1}. ${s.title} — ${s.description}`).join("\n")}`
1525
+ );
1526
+ const ans = (await sink.askPrompt("Select skill number(s) (e.g. 1,2 or 'all', Enter to skip): "))
1527
+ .trim()
1528
+ .toLowerCase();
1529
+ if (ans === "all" || ans === "*") {
1530
+ chosenIds = matches.map((s) => s.slug);
1531
+ } else if (ans && ans !== "0" && ans !== "skip" && ans !== "none") {
1532
+ for (const part of ans.split(/[\s,]+/)) {
1533
+ const n = Number.parseInt(part, 10);
1534
+ if (Number.isInteger(n) && n >= 1 && n <= matches.length) {
1535
+ const slug = matches[n - 1].slug;
1536
+ if (!chosenIds.includes(slug)) chosenIds.push(slug);
1537
+ }
1538
+ }
1539
+ }
1540
+ }
1541
+
1542
+ const pickedSet = new Set((Array.isArray(chosenIds) ? chosenIds : []).filter((id) => id && id !== "__skip__"));
1543
+ return matches.filter((s) => pickedSet.has(s.slug));
1544
+ }
1545
+
534
1546
  async function runAgentTurn(state, userText, sink, options = {}) {
535
1547
  state.lastFailedPrompt = "";
536
1548
  const workspaceRoot = state.workspaceRoot || process.cwd();
@@ -560,6 +1572,14 @@ async function runAgentTurn(state, userText, sink, options = {}) {
560
1572
  }
561
1573
 
562
1574
  const expanded = expandFileMentions(userText, workspaceRoot);
1575
+ let userContentForModel = expanded;
1576
+ if (!options.isRetry && !options.skipSkillPrompt) {
1577
+ const selectedSkills = await promptForRelevantSkills(state, userText, sink);
1578
+ if (selectedSkills.length > 0) {
1579
+ userContentForModel = `${expanded}\n\n${formatSelectedSkillsBlock(selectedSkills)}`;
1580
+ sink.log("meta", `✨ Applied skill(s): ${selectedSkills.map((s) => s.title).join(", ")}`);
1581
+ }
1582
+ }
563
1583
  if (!state.session.title && !options.isRetry) {
564
1584
  const cleanTitle = String(userText || "")
565
1585
  .replace(/\s+/g, " ")
@@ -588,85 +1608,45 @@ async function runAgentTurn(state, userText, sink, options = {}) {
588
1608
  `[debug] turn start · model=${state.model} · mode=${state.settings.agentMode} · history=${state.session.history.length}`
589
1609
  );
590
1610
  }
591
- state.session.history.push({ role: "user", content: expanded });
592
- const toolsUsed = [];
593
- let finalAssistantText = "";
594
- let lastUsage = null;
595
- let totalTurnMs = 0;
596
- let emptyRetried = false;
1611
+ state.session.history.push({ role: "user", content: userContentForModel });
597
1612
 
598
1613
  // Keep one AbortController alive across BOTH LLM streaming and all tool executions (download_file, run_command, etc.)
599
1614
  const turnAbort = new AbortController();
600
1615
  state.activeAbort = turnAbort;
1616
+ if (!state.tokenCalibration) state.tokenCalibration = createTokenCalibration();
601
1617
 
602
1618
  try {
603
- const maxSteps = Math.max(1, Number(state.settings.maxToolSteps) || 100);
604
- const loopDetector = new LoopDetector(3);
605
- for (let step = 0; step < maxSteps; step++) {
606
- if (turnAbort.signal.aborted) throw createAbortError();
607
- sink.setBusy(step ? `Step ${step + 1}...` : "Thinking...");
608
- const reqMessages = buildRequestMessages(state);
609
- const ctxEst = estimateMessagesTokens(reqMessages);
610
- const ctxWin = state.settings.contextWindow || 128000;
611
- if (state.settings.verbosity === "high" && step > 0) {
612
- sink.log("meta", `[verbose] Step ${step + 1}/${maxSteps} · ~${ctxEst} tokens`);
613
- }
614
-
615
- const turn = await streamProviderTurn({
616
- provider: state.provider,
617
- model: state.model,
618
- settings: state.settings,
619
- messages: reqMessages,
620
- signal: turnAbort.signal,
621
- sink,
622
- capabilities: state.capabilities,
623
- toolDefinitions: TOOL_DEFINITIONS,
624
- });
625
- if (turnAbort.signal.aborted) throw createAbortError();
626
-
627
- totalTurnMs += turn.elapsedMs;
628
- lastUsage = turn.usage;
629
- state.session.stats.requests += 1;
630
- state.session.stats.totalMs += turn.elapsedMs;
631
- state.session.stats.lastTtftMs = turn.ttftMs;
632
- state.session.stats.lastTokPerSec = turn.tokPerSec;
633
- if (turn.usage) {
634
- state.session.stats.promptTokens += turn.usage.prompt_tokens || 0;
635
- state.session.stats.completionTokens += turn.usage.completion_tokens || 0;
636
- }
637
-
638
- // B14: Guard against empty silent assistant response
639
- if (!turn.toolCalls.length && !turn.content) {
640
- if (!emptyRetried) {
641
- emptyRetried = true;
642
- state.session.history.push({
643
- role: "user",
644
- content:
645
- "You returned an empty response. Provide a helpful final answer or call an appropriate tool.",
646
- });
647
- continue;
648
- }
649
- throw new Error("Model returned an empty response.");
650
- }
651
-
652
- const assistantMsg = { role: "assistant", content: turn.content || "" };
653
- if (turn.toolCalls.length) assistantMsg.tool_calls = turn.toolCalls;
654
- state.session.history.push(assistantMsg);
655
-
656
- if (!turn.toolCalls.length) {
657
- finalAssistantText = turn.content;
658
- const sec = (turn.elapsedMs / 1000).toFixed(2);
659
- const ttftStr = turn.ttftMs >= 1000 ? `${(turn.ttftMs / 1000).toFixed(2)}s` : `${turn.ttftMs}ms`;
660
- const speedStr = turn.tokPerSec ? ` · ${turn.tokPerSec} tok/s` : "";
661
- const ctxStr = ` · Context: ~${turn.usage?.prompt_tokens || ctxEst} / ${ctxWin}`;
662
- const usageStr = turn.usage
663
- ? ` · Tokens: ${turn.usage.prompt_tokens ?? 0} in, ${turn.usage.completion_tokens ?? 0} out`
664
- : ` · Output: ~${turn.outTokens} tok`;
665
- if (state.settings.verbosity !== "low") {
666
- sink.log("meta", `Response: ${sec}s · TTFT: ${ttftStr}${speedStr}${ctxStr}${usageStr}`);
1619
+ const result = await runAgentLoop({
1620
+ history: state.session.history,
1621
+ provider: state.provider,
1622
+ model: state.model,
1623
+ settings: state.settings,
1624
+ maxSteps: Math.max(1, Number(state.settings.maxToolSteps) || 100),
1625
+ signal: turnAbort.signal,
1626
+ sink,
1627
+ permissions: { _state: state },
1628
+ capabilities: state.capabilities,
1629
+ tokenCalibration: state.tokenCalibration,
1630
+ prepareContextFn: (cal, sig) => prepareContextForStep(state, sink, cal, sig),
1631
+ dropTrailingUserOnAbort: true,
1632
+ onTurnStats: (turn) => {
1633
+ state.session.stats.requests += 1;
1634
+ state.session.stats.totalMs += turn.elapsedMs;
1635
+ state.session.stats.lastTtftMs = turn.ttftMs;
1636
+ state.session.stats.lastTokPerSec = turn.tokPerSec;
1637
+ if (turn.usage) {
1638
+ state.session.stats.promptTokens += turn.usage.prompt_tokens || 0;
1639
+ state.session.stats.completionTokens += turn.usage.completion_tokens || 0;
1640
+ state.session.stats.cacheReadTokens =
1641
+ (state.session.stats.cacheReadTokens || 0) + (turn.usage.cache_read_input_tokens || 0);
1642
+ state.session.stats.cacheWriteTokens =
1643
+ (state.session.stats.cacheWriteTokens || 0) + (turn.usage.cache_creation_input_tokens || 0);
667
1644
  }
668
- if (turn.elapsedMs >= 5000) sink.notify?.();
669
-
1645
+ },
1646
+ onCheckpoint: () => {
1647
+ if (!state.noSession) saveSession(state.session, state.paths);
1648
+ },
1649
+ onBeforeComplete: async () => {
670
1650
  // A2: Structured Plan Approval Workflow when finishing in 'plan' mode
671
1651
  if (state.settings.agentMode === "plan" && sink.interactive && sink.confirm) {
672
1652
  const ans = (
@@ -686,7 +1666,7 @@ async function runAgentTurn(state, userText, sink, options = {}) {
686
1666
  content:
687
1667
  "Plan approved. Switched to accept-edits mode. Proceed with implementing the plan now.",
688
1668
  });
689
- continue;
1669
+ return "continue";
690
1670
  }
691
1671
  if (ans === "2" || ans === "auto") {
692
1672
  state.settings.agentMode = "auto";
@@ -697,7 +1677,7 @@ async function runAgentTurn(state, userText, sink, options = {}) {
697
1677
  role: "user",
698
1678
  content: "Plan approved. Switched to auto mode. Proceed with implementing the plan now.",
699
1679
  });
700
- continue;
1680
+ return "continue";
701
1681
  }
702
1682
  if (ans === "3" || ans === "default") {
703
1683
  state.settings.agentMode = "default";
@@ -708,65 +1688,36 @@ async function runAgentTurn(state, userText, sink, options = {}) {
708
1688
  role: "user",
709
1689
  content: "Plan approved. Switched to default mode. Proceed step-by-step now.",
710
1690
  });
711
- continue;
1691
+ return "continue";
712
1692
  }
713
1693
  if (ans === "4") {
714
1694
  sink.log("meta", "Staying in 'plan' mode. Ask follow-up refinements in your next message.");
715
1695
  }
716
1696
  }
1697
+ return null;
1698
+ },
1699
+ });
717
1700
 
718
- if (!state.noSession) saveSession(state.session, state.paths);
719
- sink.syncStatus();
720
- // B20: Trigger non-blocking background session memory update
721
- void updateSessionMemory(state, userText, turn.content, toolsUsed, sink, {
722
- blocking: false,
723
- verbose: state.settings.verbosity === "high",
724
- });
725
- return {
726
- ok: true,
727
- answer: finalAssistantText,
728
- toolsUsed,
729
- usage: lastUsage,
730
- elapsedMs: totalTurnMs,
731
- };
732
- }
733
-
734
- for (const tc of turn.toolCalls) toolsUsed.push(tc.function.name);
735
- const loopCheck = loopDetector.record(turn.toolCalls);
736
- if (loopCheck.repeated) {
737
- sink.log(
738
- "system",
739
- `⚠ Detected repeated identical tool calls (${loopCheck.count}x). Asking model to try a different approach or summarize.`
740
- );
741
- state.session.history.push({
742
- role: "user",
743
- content:
744
- "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.",
745
- });
746
- if (!state.noSession) saveSession(state.session, state.paths);
747
- continue;
748
- }
749
- sink.setBusy("Running tools...");
750
- const toolResults = await runToolCalls(state, turn.toolCalls, sink);
751
- if (turnAbort.signal.aborted) throw createAbortError();
752
- state.session.history.push(...toolResults);
753
- if (!state.noSession) saveSession(state.session, state.paths);
754
- sink.syncStatus();
1701
+ if (result.ok && !result.stepLimitReached) {
1702
+ // B20: Trigger non-blocking background session memory update
1703
+ void updateSessionMemory(state, userText, result.answer, result.toolsUsed, sink, {
1704
+ blocking: false,
1705
+ verbose: state.settings.verbosity === "high",
1706
+ });
755
1707
  }
756
1708
 
757
- sink.log("system", `Reached maxToolSteps (${state.settings.maxToolSteps}).`);
758
- if (!state.noSession) saveSession(state.session, state.paths);
759
- return { ok: true, answer: finalAssistantText, toolsUsed, usage: lastUsage, elapsedMs: totalTurnMs };
1709
+ return {
1710
+ ok: result.ok,
1711
+ answer: result.answer,
1712
+ ...(result.truncated ? { truncated: true } : {}),
1713
+ ...(result.loopDetected ? { loopDetected: true } : {}),
1714
+ ...(result.stepLimitReached ? { stepLimitReached: true } : {}),
1715
+ toolsUsed: result.toolsUsed,
1716
+ usage: result.usage,
1717
+ elapsedMs: result.elapsedMs,
1718
+ };
760
1719
  } catch (err) {
761
- const isAbort = Boolean(turnAbort.signal.aborted || err?.name === "AbortError" || err?.aborted);
762
- // When user cancels, drop unanswered trailing user turn because the prompt is restored directly into the input box
763
- repairTranscriptTail(state.session.history, isAbort);
764
1720
  state.lastFailedPrompt = userText;
765
- if (!state.noSession) saveSession(state.session, state.paths);
766
- sink.syncStatus();
767
- if (isAbort && err?.name !== "AbortError") {
768
- throw createAbortError(err?.message || "Task cancelled by user");
769
- }
770
1721
  throw err;
771
1722
  } finally {
772
1723
  if (state.activeAbort === turnAbort) state.activeAbort = null;
@@ -774,33 +1725,24 @@ async function runAgentTurn(state, userText, sink, options = {}) {
774
1725
  }
775
1726
 
776
1727
  async function compactSession(state, sink) {
777
- if (state.session.history.length <= 2) {
778
- sink.log("system", "Session history already compact.");
779
- return;
780
- }
781
- const lastUserIdx = state.session.history.findLastIndex((m) => m.role === "user");
782
- const keepFrom = lastUserIdx > 0 ? lastUserIdx : state.session.history.length;
783
- const toSummarize = state.session.history.slice(0, keepFrom);
784
- const tail = state.session.history.slice(keepFrom);
785
- const textDump = toSummarize.map((m) => `${m.role}: ${m.content || JSON.stringify(m.tool_calls || "")}`).join("\n");
786
- await updateSessionMemory(state, textDump.slice(0, 3000), "(manual compaction)", [], sink, {
787
- force: true,
788
- blocking: true,
789
- verbose: true,
790
- });
791
- state.session.history = tail;
792
- if (!state.noSession) saveSession(state.session, state.paths);
793
- sink.syncStatus();
794
- sink.log("system", `Compacted ${toSummarize.length} messages into session memory summary.`);
1728
+ return compactHistoryWithZoneC(state, sink, { manual: true });
795
1729
  }
796
1730
 
797
1731
  module.exports = {
798
1732
  expandFileMentions,
1733
+ buildSystemMessages,
799
1734
  buildRequestMessages,
1735
+ prepareContextForStep,
1736
+ prepareLoopContext,
1737
+ compactHistoryWithZoneC,
1738
+ compactHistoryArray,
800
1739
  formatApprovalPreview,
801
1740
  waitForMemorySync,
802
1741
  updateSessionMemory,
1742
+ repairTranscriptTail,
1743
+ createAbortError,
803
1744
  runToolCalls,
1745
+ runAgentLoop,
804
1746
  runAgentTurn,
805
1747
  compactSession,
806
1748
  };