kovence-cli 1.2.0 → 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
+ }
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,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
659
  streamCheckpointed: state.streamCheckpointed,
291
- signal: state.activeAbort?.signal || null,
660
+ signal: activeSignal,
292
661
  saveSession: (s) => {
293
- 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);
294
667
  },
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) || "",
668
+ addGlobalMemory: (fact, src) => (state.paths ? addGlobalMemory(fact, src, state.paths) : false),
669
+ getSudoPassword: () => sudoPasswords.get(sessionId) || "",
299
670
  setSudoPassword: (pw) => {
300
- if (pw) state.sudoPasswords.set(state.session.id, pw);
301
- else state.sudoPasswords.delete(state.session.id);
671
+ if (pw) sudoPasswords.set(sessionId, pw);
672
+ else sudoPasswords.delete(sessionId);
302
673
  },
303
- askPrompt: sink.askPrompt,
304
- askPassword: sink.askPassword,
305
- startProgress: sink.startProgress,
306
- setBusy: sink.setBusy,
307
- log: sink.log,
674
+ askPrompt: safeSink.askPrompt,
675
+ askPassword: safeSink.askPassword,
676
+ startProgress: safeSink.startProgress,
677
+ setBusy: safeSink.setBusy,
678
+ log: safeSink.log,
308
679
  });
309
680
 
310
681
  let downloadFailedOrCancelled = false;
682
+ const editedFilesInBatch = [];
683
+ let lastSuccessfulEditIdx = -1;
311
684
 
312
685
  const flushParallel = async () => {
313
686
  if (!parallelBatch.length) return;
@@ -316,7 +689,7 @@ async function runToolCalls(state, toolCalls, sink) {
316
689
  };
317
690
 
318
691
  for (let i = 0; i < toolCalls.length; i++) {
319
- if (state.activeAbort?.signal?.aborted) {
692
+ if (activeSignal?.aborted) {
320
693
  await flushParallel();
321
694
  throw createAbortError();
322
695
  }
@@ -328,24 +701,87 @@ async function runToolCalls(state, toolCalls, sink) {
328
701
  if (downloadFailedOrCancelled && name === "run_command") {
329
702
  const msg = "Skipped command because the preceding download did not complete.";
330
703
  results[i] = { role: "tool", tool_call_id: tc.id, name, content: msg };
331
- sink.log("tool", `⏸ ${name}(${summary}) skipped (download incomplete)`);
704
+ safeSink.log("tool", `⏸ ${name}(${summary}) skipped (download incomplete)`);
332
705
  continue;
333
706
  }
334
- let parsedArgs = {};
707
+ let parsedArgs;
335
708
  try {
336
709
  parsedArgs =
337
710
  typeof tc.function.arguments === "string"
338
- ? repairToolArguments(tc.function.arguments || "{}")
711
+ ? repairToolArguments(tc.function.arguments || "", { strict: strictNoRepair })
339
712
  : tc.function.arguments || {};
340
- } 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
+ }
341
777
 
342
778
  const evalRes = evaluatePermission({
343
779
  toolName: name,
344
780
  args: parsedArgs,
345
- settings: state.settings,
781
+ settings: state.settings || {},
346
782
  workspaceRoot,
347
783
  extraDirs: state.extraDirs || [],
348
- sessionRules: state.sessionRules,
784
+ sessionRules,
349
785
  paths: state.paths,
350
786
  });
351
787
 
@@ -355,8 +791,9 @@ async function runToolCalls(state, toolCalls, sink) {
355
791
  tool_call_id: tc.id,
356
792
  name,
357
793
  content: evalRes.reason,
794
+ isError: true,
358
795
  };
359
- sink.log("tool", `⛔ ${name}(${summary}) blocked: ${evalRes.reason}`);
796
+ safeSink.log("tool", `⛔ ${name}(${summary}) blocked: ${evalRes.reason}`);
360
797
  continue;
361
798
  }
362
799
 
@@ -364,75 +801,87 @@ async function runToolCalls(state, toolCalls, sink) {
364
801
  let skipDownloadDestPrompt = Boolean(evalRes.matchedRule);
365
802
 
366
803
  if (evalRes.decision === "ask") {
367
- if (!sink.interactive || !sink.confirm) {
804
+ if (!safeSink.interactive || !safeSink.confirm) {
368
805
  results[i] = {
369
806
  role: "tool",
370
807
  tool_call_id: tc.id,
371
808
  name,
372
809
  content: `Denied: '${name}' requires interactive approval (${evalRes.reason}).`,
810
+ isError: true,
373
811
  };
374
- sink.log("tool", `✗ ${name}(${summary}) requires approval`);
812
+ safeSink.log("tool", `✗ ${name}(${summary}) requires approval`);
375
813
  continue;
376
814
  }
377
815
 
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]: `
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
+ )
397
840
  )
398
- )
399
- .trim()
400
- .toLowerCase();
841
+ .trim()
842
+ .toLowerCase();
401
843
 
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
- );
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;
419
863
  }
420
- 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";
421
872
  }
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);
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);
432
881
  continue;
433
882
  }
434
883
  } else if (evalRes.matchedRule && evalRes.ruleLabel) {
435
- sink.log("meta", `✓ auto-allowed by rule: ${evalRes.ruleLabel}`);
884
+ safeSink.log("meta", `✓ auto-allowed by rule: ${evalRes.ruleLabel}`);
436
885
  }
437
886
 
438
887
  const isSequential =
@@ -446,18 +895,20 @@ async function runToolCalls(state, toolCalls, sink) {
446
895
 
447
896
  const runOne = async () => {
448
897
  const toolUi =
449
- name !== "download_file" && sink.startToolCall
450
- ? sink.startToolCall(`⚙ ${name}(${summary})`, { collapsible: true, toolIdx: i })
898
+ name !== "download_file" && name !== "task" && safeSink.startToolCall
899
+ ? safeSink.startToolCall(`⚙ ${name}(${summary})`, { collapsible: true, toolIdx: i })
451
900
  : null;
452
- if (!toolUi && name !== "download_file") {
453
- sink.log("tool", `⚙ ${name}(${summary})`);
901
+ if (!toolUi && name !== "download_file" && name !== "task") {
902
+ safeSink.log("tool", `⚙ ${name}(${summary})`);
454
903
  }
455
- if (name === "download_file") {
904
+ if (name === "task") {
905
+ safeSink.setBusy("Running sub-agent...");
906
+ } else if (name === "download_file") {
456
907
  state.isDownloading = true;
457
- sink.setBusy("Downloading (commands paused)...");
908
+ safeSink.setBusy("Downloading (commands paused)...");
458
909
  } else if (name === "write_file" || name === "edit_file" || name === "multi_edit") {
459
910
  const target = parsedArgs.path ? parsedArgs.path.split("/").pop() : "";
460
- sink.setBusy(`Writing ${target || "file"}...`);
911
+ safeSink.setBusy(`Writing ${target || "file"}...`);
461
912
  // Populate write stats for the live TUI write indicator.
462
913
  if (toolUi && toolUi.startWrite) {
463
914
  const writeContent =
@@ -470,35 +921,56 @@ async function runToolCalls(state, toolCalls, sink) {
470
921
  }
471
922
  } else if (name === "read_file" || name === "glob_files" || name === "grep_files") {
472
923
  const target = parsedArgs.path ? parsedArgs.path.split("/").pop() : "";
473
- sink.setBusy(`Reading ${target || "code"}...`);
924
+ safeSink.setBusy(`Reading ${target || "code"}...`);
474
925
  } else {
475
- sink.setBusy(`Running ${name}...`);
926
+ safeSink.setBusy(`Running ${name}...`);
476
927
  }
477
928
  try {
478
- const out = await executeTool(
479
- name,
480
- parsedArgs,
481
- makeCtx(approvedByUser, skipDownloadDestPrompt, (chunk) => toolUi?.pushOutput(chunk))
482
- );
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);
483
937
  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));
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);
486
952
  if (name === "download_file" && /^Download cancelled/i.test(outStr)) {
487
953
  downloadFailedOrCancelled = true;
488
954
  }
489
955
  } catch (err) {
490
- if (state.activeAbort?.signal?.aborted || err?.aborted || err?.name === "AbortError") {
956
+ if (activeSignal?.aborted || err?.aborted || err?.name === "AbortError") {
491
957
  toolUi?.finish("Aborted by user", true);
492
958
  throw createAbortError(err?.message || "Task cancelled by user");
493
959
  }
494
960
  if (name === "download_file") downloadFailedOrCancelled = true;
495
- 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
+ };
496
968
  toolUi?.finish(`Error: ${err.message}`, true);
497
- sink.log("error", `✗ ${name}: ${err.message}`);
969
+ safeSink.log("error", `✗ ${name}: ${err.message}`);
498
970
  } finally {
499
971
  if (name === "download_file") {
500
972
  state.isDownloading = false;
501
- sink.syncStatus();
973
+ safeSink.syncStatus();
502
974
  }
503
975
  }
504
976
  };
@@ -513,17 +985,53 @@ async function runToolCalls(state, toolCalls, sink) {
513
985
  }
514
986
 
515
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
+ }
516
1001
  return results;
517
1002
  }
518
1003
 
519
1004
  function repairTranscriptTail(history, dropTrailingUser = false) {
520
- // 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.
521
1006
  while (history.length > 0) {
522
1007
  const last = history[history.length - 1];
523
1008
  if (last.role === "assistant" && Array.isArray(last.tool_calls) && last.tool_calls.length > 0) {
524
1009
  history.pop();
525
1010
  continue;
526
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
+ }
527
1035
  break;
528
1036
  }
529
1037
  if (dropTrailingUser && history.length > 0 && history[history.length - 1].role === "user") {
@@ -531,6 +1039,509 @@ function repairTranscriptTail(history, dropTrailingUser = false) {
531
1039
  }
532
1040
  }
533
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
+
534
1545
  async function runAgentTurn(state, userText, sink, options = {}) {
535
1546
  state.lastFailedPrompt = "";
536
1547
  const workspaceRoot = state.workspaceRoot || process.cwd();
@@ -560,6 +1571,14 @@ async function runAgentTurn(state, userText, sink, options = {}) {
560
1571
  }
561
1572
 
562
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
+ }
563
1582
  if (!state.session.title && !options.isRetry) {
564
1583
  const cleanTitle = String(userText || "")
565
1584
  .replace(/\s+/g, " ")
@@ -588,85 +1607,45 @@ async function runAgentTurn(state, userText, sink, options = {}) {
588
1607
  `[debug] turn start · model=${state.model} · mode=${state.settings.agentMode} · history=${state.session.history.length}`
589
1608
  );
590
1609
  }
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;
1610
+ state.session.history.push({ role: "user", content: userContentForModel });
597
1611
 
598
1612
  // Keep one AbortController alive across BOTH LLM streaming and all tool executions (download_file, run_command, etc.)
599
1613
  const turnAbort = new AbortController();
600
1614
  state.activeAbort = turnAbort;
1615
+ if (!state.tokenCalibration) state.tokenCalibration = createTokenCalibration();
601
1616
 
602
1617
  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}`);
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);
667
1643
  }
668
- if (turn.elapsedMs >= 5000) sink.notify?.();
669
-
1644
+ },
1645
+ onCheckpoint: () => {
1646
+ if (!state.noSession) saveSession(state.session, state.paths);
1647
+ },
1648
+ onBeforeComplete: async () => {
670
1649
  // A2: Structured Plan Approval Workflow when finishing in 'plan' mode
671
1650
  if (state.settings.agentMode === "plan" && sink.interactive && sink.confirm) {
672
1651
  const ans = (
@@ -686,7 +1665,7 @@ async function runAgentTurn(state, userText, sink, options = {}) {
686
1665
  content:
687
1666
  "Plan approved. Switched to accept-edits mode. Proceed with implementing the plan now.",
688
1667
  });
689
- continue;
1668
+ return "continue";
690
1669
  }
691
1670
  if (ans === "2" || ans === "auto") {
692
1671
  state.settings.agentMode = "auto";
@@ -697,7 +1676,7 @@ async function runAgentTurn(state, userText, sink, options = {}) {
697
1676
  role: "user",
698
1677
  content: "Plan approved. Switched to auto mode. Proceed with implementing the plan now.",
699
1678
  });
700
- continue;
1679
+ return "continue";
701
1680
  }
702
1681
  if (ans === "3" || ans === "default") {
703
1682
  state.settings.agentMode = "default";
@@ -708,65 +1687,36 @@ async function runAgentTurn(state, userText, sink, options = {}) {
708
1687
  role: "user",
709
1688
  content: "Plan approved. Switched to default mode. Proceed step-by-step now.",
710
1689
  });
711
- continue;
1690
+ return "continue";
712
1691
  }
713
1692
  if (ans === "4") {
714
1693
  sink.log("meta", "Staying in 'plan' mode. Ask follow-up refinements in your next message.");
715
1694
  }
716
1695
  }
1696
+ return null;
1697
+ },
1698
+ });
717
1699
 
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();
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
+ });
755
1706
  }
756
1707
 
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 };
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
+ };
760
1718
  } 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
1719
  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
1720
  throw err;
771
1721
  } finally {
772
1722
  if (state.activeAbort === turnAbort) state.activeAbort = null;
@@ -774,33 +1724,24 @@ async function runAgentTurn(state, userText, sink, options = {}) {
774
1724
  }
775
1725
 
776
1726
  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.`);
1727
+ return compactHistoryWithZoneC(state, sink, { manual: true });
795
1728
  }
796
1729
 
797
1730
  module.exports = {
798
1731
  expandFileMentions,
1732
+ buildSystemMessages,
799
1733
  buildRequestMessages,
1734
+ prepareContextForStep,
1735
+ prepareLoopContext,
1736
+ compactHistoryWithZoneC,
1737
+ compactHistoryArray,
800
1738
  formatApprovalPreview,
801
1739
  waitForMemorySync,
802
1740
  updateSessionMemory,
1741
+ repairTranscriptTail,
1742
+ createAbortError,
803
1743
  runToolCalls,
1744
+ runAgentLoop,
804
1745
  runAgentTurn,
805
1746
  compactSession,
806
1747
  };