@causyne/agent 1.20.112 → 1.20.117

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.
Files changed (169) hide show
  1. package/docs/ARCHITECTURE.md +29 -0
  2. package/package.json +1 -1
  3. package/src/agentLoop.js +153 -68
  4. package/src/agentLoop.ts +152 -71
  5. package/src/browser/browserRuntime.js +13 -8
  6. package/src/browser/browserRuntime.ts +16 -8
  7. package/src/browser/causyneBrowser.js +37 -9
  8. package/src/browser/causyneBrowser.ts +37 -9
  9. package/src/browser/searchProviders.js +18 -7
  10. package/src/browser/searchProviders.ts +17 -5
  11. package/src/browser/snapshotWindow.js +1 -1
  12. package/src/browser/snapshotWindow.ts +1 -1
  13. package/src/browser/urlPolicy.js +21 -10
  14. package/src/browser/urlPolicy.ts +19 -10
  15. package/src/browser/workspacePreview.js +13 -1
  16. package/src/browser/workspacePreview.ts +11 -1
  17. package/src/cliMode.js +5 -1
  18. package/src/computerUse/visionGrounding.js +31 -27
  19. package/src/computerUse/visionGrounding.ts +27 -27
  20. package/src/continuum/ui/continuumPicker.js +14 -6
  21. package/src/continuum/ui/continuumPicker.ts +13 -6
  22. package/src/continuum/ui/continuumPickerView.js +24 -15
  23. package/src/continuum/ui/continuumPickerView.ts +24 -16
  24. package/src/memory/scopedFacts.js +171 -0
  25. package/src/memory/scopedFacts.ts +214 -0
  26. package/src/memory.d.ts +13 -1
  27. package/src/memory.js +9 -12
  28. package/src/observer/advisory.js +32 -22
  29. package/src/observer/advisory.ts +30 -18
  30. package/src/observer/coldObserver.js +21 -33
  31. package/src/observer/coldObserver.ts +20 -33
  32. package/src/observer/evidence.js +20 -13
  33. package/src/observer/evidence.ts +21 -13
  34. package/src/observer.js +47 -12
  35. package/src/observer.ts +50 -18
  36. package/src/perception.js +124 -3
  37. package/src/perception.ts +128 -4
  38. package/src/planCache.js +17 -3
  39. package/src/planCache.ts +17 -3
  40. package/src/pluginsFactory/discovery.js +28 -16
  41. package/src/pluginsFactory/discovery.ts +29 -16
  42. package/src/pluginsFactory/pluginsFactory.js +213 -38
  43. package/src/pluginsFactory/pluginsFactory.ts +218 -39
  44. package/src/pluginsFactory/strategy.js +26 -16
  45. package/src/pluginsFactory/strategy.ts +34 -19
  46. package/src/pluginsFactory/templates.js +183 -62
  47. package/src/pluginsFactory/templates.ts +174 -54
  48. package/src/smartToolsUse.js +4 -5
  49. package/src/smartToolsUse.ts +4 -6
  50. package/src/taskShape.js +49 -7
  51. package/src/taskShape.ts +55 -7
  52. package/src/timeMachine.js +43 -22
  53. package/src/timeMachine.ts +44 -22
  54. package/src/tool-scripts/desktop_act.applescript +1 -0
  55. package/src/toolPacks.js +27 -5
  56. package/src/toolPacks.ts +32 -5
  57. package/src/tools/computerUse.js +23 -10
  58. package/src/tools/computerUse.ts +19 -8
  59. package/src/tools/desktopAct.js +12 -1
  60. package/src/tools/memoryWrite.js +8 -10
  61. package/src/tools/memoryWrite.ts +13 -11
  62. package/src/tools/pluginsFactory.js +108 -5
  63. package/src/tools/pluginsFactory.ts +115 -5
  64. package/src/tui/CausyneRotor.js +24 -10
  65. package/src/tui/CausyneRotor.ts +25 -10
  66. package/src/tui/activityLayout.js +9 -5
  67. package/src/tui/activityLayout.ts +9 -5
  68. package/src/tui/ask.js +34 -14
  69. package/src/tui/banner.js +55 -18
  70. package/src/tui/banner.ts +52 -17
  71. package/src/tui/block.js +47 -20
  72. package/src/tui/block.ts +54 -27
  73. package/src/tui/chatRenderer.js +139 -84
  74. package/src/tui/chatboxClipboard.js +12 -5
  75. package/src/tui/chatboxClipboard.ts +10 -4
  76. package/src/tui/clipboardImage.js +52 -42
  77. package/src/tui/clipboardImage.ts +50 -39
  78. package/src/tui/clipboardSync.js +12 -1
  79. package/src/tui/clipboardSync.ts +9 -1
  80. package/src/tui/codeProgress.js +60 -28
  81. package/src/tui/codeProgress.ts +60 -27
  82. package/src/tui/codeStreamRenderer.js +94 -23
  83. package/src/tui/codeStreamRenderer.ts +92 -23
  84. package/src/tui/commandPresentation.js +9 -2
  85. package/src/tui/commandPresentation.ts +9 -2
  86. package/src/tui/completion.js +45 -23
  87. package/src/tui/composerControls.js +21 -10
  88. package/src/tui/composerControls.ts +18 -10
  89. package/src/tui/composerGeometry.js +6 -4
  90. package/src/tui/composerGeometry.ts +6 -4
  91. package/src/tui/consoleGuard.js +29 -7
  92. package/src/tui/consoleGuard.ts +28 -7
  93. package/src/tui/dialogs.js +134 -71
  94. package/src/tui/diff.js +8 -4
  95. package/src/tui/history.js +6 -5
  96. package/src/tui/home.js +25 -13
  97. package/src/tui/homeView.js +37 -18
  98. package/src/tui/homeView.ts +38 -18
  99. package/src/tui/inlineSlash.js +6 -5
  100. package/src/tui/inlineSlash.ts +6 -5
  101. package/src/tui/keys.js +36 -18
  102. package/src/tui/layout.js +27 -9
  103. package/src/tui/layout.ts +26 -9
  104. package/src/tui/lineEditor.js +49 -23
  105. package/src/tui/markdownMath.js +64 -14
  106. package/src/tui/markdownMath.ts +69 -13
  107. package/src/tui/messageActionPlacement.js +28 -13
  108. package/src/tui/messageActionPlacement.ts +28 -13
  109. package/src/tui/messageInteraction.js +111 -46
  110. package/src/tui/messageInteraction.ts +115 -47
  111. package/src/tui/modelPicker.js +44 -15
  112. package/src/tui/modelPicker.ts +48 -15
  113. package/src/tui/observerPicker.js +56 -13
  114. package/src/tui/observerPicker.ts +73 -30
  115. package/src/tui/overlay.js +79 -35
  116. package/src/tui/overlay.ts +81 -34
  117. package/src/tui/prompt.js +186 -94
  118. package/src/tui/runningLight.js +1 -1
  119. package/src/tui/runningLight.ts +1 -1
  120. package/src/tui/scrollInteraction.js +64 -36
  121. package/src/tui/scrollInteraction.ts +70 -37
  122. package/src/tui/selectList.js +60 -32
  123. package/src/tui/sessionLayout.js +11 -3
  124. package/src/tui/sessionLayout.ts +10 -3
  125. package/src/tui/sessionPicker.js +74 -46
  126. package/src/tui/sessionPicker.ts +73 -48
  127. package/src/tui/sessionPickerView.js +32 -19
  128. package/src/tui/sessionPickerView.ts +31 -18
  129. package/src/tui/sessionSidebar.js +87 -57
  130. package/src/tui/sessionSidebar.ts +90 -54
  131. package/src/tui/setup.js +28 -3
  132. package/src/tui/setup.ts +27 -3
  133. package/src/tui/skillAuthoring.js +11 -5
  134. package/src/tui/skillAuthoring.ts +11 -5
  135. package/src/tui/smartLinkClick.js +75 -23
  136. package/src/tui/smartLinkClick.ts +86 -26
  137. package/src/tui/stage.js +47 -16
  138. package/src/tui/stage.ts +53 -18
  139. package/src/tui/stageSurface.js +232 -51
  140. package/src/tui/statusLine.js +85 -53
  141. package/src/tui/statusLine.ts +82 -46
  142. package/src/tui/terminalInputFramer.js +5 -2
  143. package/src/tui/text.js +117 -46
  144. package/src/tui/text.ts +113 -43
  145. package/src/tui/textLayout.js +6 -4
  146. package/src/tui/textLayout.ts +11 -5
  147. package/src/tui/theme.js +17 -8
  148. package/src/tui/thinkingBox.js +95 -95
  149. package/src/tui/thinkingBox.ts +105 -80
  150. package/src/tui/toolActivityPolicy.js +8 -1
  151. package/src/tui/toolActivityPolicy.ts +7 -1
  152. package/src/tui/toolDisplay.js +15 -6
  153. package/src/tui/toolDisplay.ts +16 -6
  154. package/src/tui/toolOutputNormalizer.js +16 -3
  155. package/src/tui/toolOutputNormalizer.ts +13 -3
  156. package/src/tui/transcript.js +15 -9
  157. package/src/tui/turnRail.js +176 -80
  158. package/src/tui/turnRail.ts +173 -71
  159. package/src/tui/usageCard.js +136 -80
  160. package/src/tui/usageCard.ts +145 -103
  161. package/src/tui/viewport.js +48 -23
  162. package/src/tui/viewport.ts +48 -27
  163. package/src/tui/viewportAnchor.js +2 -2
  164. package/src/tui/viewportAnchor.ts +2 -2
  165. package/src/tui/workspaceFileIndex.js +8 -6
  166. package/src/tui/workspaceFileIndex.ts +8 -6
  167. package/src/tui/workspaceSwitch.js +13 -10
  168. package/src/tui/workspaceSwitch.ts +11 -7
  169. package/src/types/contracts.ts +3 -0
@@ -79,6 +79,35 @@ Runtime validation is still required at model, filesystem, subprocess and
79
79
  extension boundaries. Rust is reserved for a measured, narrow native worker;
80
80
  no Rust rewrite is underway.
81
81
 
82
+ ### Terminal mode and scroll isolation
83
+
84
+ Interactive TUI chat runs inside the normal terminal buffer via `StageSurface`
85
+ (`src/tui/stageSurface.js`) rather than switching to the alternate screen
86
+ (`\x1b[?1049h`). While any `Stage` on `process.stdout` is reserved,
87
+ `consoleGuard` (`src/tui/consoleGuard.ts`) suppresses unmanaged writes containing
88
+ `\n`, `\r`, or `\x1b` on `process.stdout.write` so stray logs cannot scroll or
89
+ corrupt the live region.
90
+
91
+ Every Stage-authorized terminal escape write MUST execute inside
92
+ `runWithStageWrite()` (`src/tui/consoleGuard.ts`):
93
+
94
+ - `Stage.write()` (`src/tui/stage.ts`) for band reservation, painting, and
95
+ collapse/print-through.
96
+ - `ClipboardSync` (`src/tui/clipboardSync.ts`) for OSC 52 clipboard payloads.
97
+ - `StageSurface` (`src/tui/stageSurface.js`) mouse mode transitions (`?1000h`/`l`,
98
+ `?1006h`/`l`, optional `?1003h`/`l`) in `enableMouse()`, `disableMouse()`,
99
+ `releaseMouse()`, and `captureMouse()`.
100
+ - `ChatPrompt` (`src/tui/prompt.js`) bracketed paste toggles (`?2004h`/`l`) and
101
+ explicit `Ctrl+L` clears.
102
+
103
+ If any mouse-reporting toggle omits `runWithStageWrite()` while a Stage is
104
+ reserved on `process.stdout`, `?1000h\x1b[?1006h` is silently dropped, causing
105
+ terminals such as macOS Terminal to scroll their own scrollback buffer instead
106
+ of sending SGR wheel events to the chat viewport. Unit tests using mock streams
107
+ (`out !== process.stdout`) do not exercise `consoleGuard`; tests covering TUI
108
+ mode transitions must assert real `process.stdout` (`isTTY: true`) byte output
109
+ with `consoleGuard` active.
110
+
82
111
  ## Planning and durable decisions
83
112
 
84
113
  Complex implementation uses `update_plan` to maintain a validated checklist in
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@causyne/agent",
3
- "version": "1.20.112",
3
+ "version": "1.20.117",
4
4
  "description": "Agentic AI for software, tools, and computer workflows",
5
5
  "main": "bin/causyne.js",
6
6
  "type": "module",
package/src/agentLoop.js CHANGED
@@ -40,7 +40,7 @@ import { requiresToolApproval, withToolAutonomyMode } from './approvalPolicy.js'
40
40
  import { AGENT_USER_POLICY } from './agentPolicy.js';
41
41
  import { VFETracker } from './vfeTracker.js';
42
42
  import { coldObserver } from './observer/coldObserver.js';
43
- import { isVerificationCommand } from './observer/evidence.js';
43
+ import { isRenderedNativeBrowserAction, isVerificationCommand } from './observer/evidence.js';
44
44
  import { CausyneObserver, defaultObserver, extractClaimedLocalUrls } from './observer.js';
45
45
  import { TimeMachine, recoveryUserMessage, TIME_MACHINE_MAX_ATTEMPTS } from './timeMachine.js';
46
46
  import { packForTool, isCoreTool, isGameIntent, isWebIntent, PACK_PLAYBOOKS, PACKS } from './toolPacks.js';
@@ -50,7 +50,7 @@ import { assessVerification } from './verificationPlan.js';
50
50
  import { SmartTools } from './SmartTools.js';
51
51
  import { decideTools, isDirectGameTask as isDirectGameTaskDecision } from './decideTools.js';
52
52
  import { SavedTools, readSavedTools, writeSavedTools } from './saveTools.js';
53
- import { resolveCharPool, measureMessages, resultCapFor, decayToolResults, buildWindow, compactInPlace, describeDroppedMessages, sanitizeSequences, applyProgressiveCompaction, snipOversizedToolOutputs } from './contextManager.js';
53
+ import { CHARS_PER_TOKEN, resolveCharPool, measureMessages, resultCapFor, decayToolResults, buildWindow, compactInPlace, describeDroppedMessages, sanitizeSequences, applyProgressiveCompaction, snipOversizedToolOutputs } from './contextManager.js';
54
54
  // Provider imports
55
55
  import { detectWorkspaceDomains, ensureSkillRepo, getSkillDomainHeader } from './skillsManager.js';
56
56
  import { spillToolResult, buildDecayPointer, pruneOutputStore } from './outputStore.js';
@@ -74,13 +74,29 @@ export function noncachedTokens(usage) {
74
74
  if (!usage)
75
75
  return 0;
76
76
  const finite = (value) => Number.isFinite(value) ? Math.max(0, value ?? 0) : 0;
77
- const input = usage.uncachedPromptTokens !== undefined
77
+ const input = typeof usage.uncachedPromptTokens === 'number' && Number.isFinite(usage.uncachedPromptTokens)
78
78
  ? finite(usage.uncachedPromptTokens)
79
79
  : finite(usage.cachedPromptTokens) > finite(usage.promptTokens)
80
80
  ? finite(usage.promptTokens)
81
81
  : Math.max(0, finite(usage.promptTokens) - finite(usage.cachedPromptTokens));
82
82
  return input + finite(usage.completionTokens);
83
83
  }
84
+ function nonEmptyErrorText(result) {
85
+ return typeof result?.error === 'string' && result.error.trim().length > 0
86
+ ? result.error
87
+ : undefined;
88
+ }
89
+ export function isToolErrorResult(result) {
90
+ if (!result || typeof result !== 'object')
91
+ return false;
92
+ return result.success === false
93
+ || nonEmptyErrorText(result) !== undefined
94
+ || (typeof result.exitCode === 'number' && (!Number.isFinite(result.exitCode) || result.exitCode !== 0));
95
+ }
96
+ function spillErrorField(result) {
97
+ const error = nonEmptyErrorText(result);
98
+ return error !== undefined ? { error: error.slice(0, 500) } : {};
99
+ }
84
100
  export function isActionableTaskPrompt(text) {
85
101
  const t = (text || '').trim();
86
102
  if (!t)
@@ -297,10 +313,10 @@ ${AGENT_USER_POLICY}
297
313
  # Project Conventions
298
314
  Follow the selected project's existing style and architecture. Check dependencies and tool schemas before use. Preserve unrelated behavior.
299
315
 
300
- # Greenfield Application Scaffolding vs. Legacy Codebase Exploration
301
- - When the user asks to CREATE or BUILD a new application, web page, 3D model, game, or tool from scratch (e.g., "buatkan", "create", "build", "make", "generate"), focus DIRECTLY on authoring the project in its designated project directory.
302
- - DO NOT perform exploratory directory listings of the root repository or inspect unrelated legacy projects in the workspace.
303
- - Immediately initialize the target directory and author the required implementation files (e.g. index.html, style.css, app.js).
316
+ # Repository Structure, Project Docs & Existing Codebases First
317
+ - When working inside an existing repository or project (indicated by Workspace Context key files, docs, build scripts, or subprojects), ALWAYS inspect the relevant project documentation (docs/, README.md), build scripts (scripts/, Makefile, package.json), and actual directory structure BEFORE modifying files or choosing a build/release command.
318
+ - Do NOT blindly initialize template web files (index.html, style.css, app.js) or assume a task is a greenfield web app unless the user explicitly requested a new web project from scratch AND the target directory has no matching existing build/architecture.
319
+ - Only skip root exploration when creating an explicitly requested brand-new greenfield project inside a dedicated new/empty directory.
304
320
 
305
321
  # Operational Guidelines & Communication
306
322
  - **Strict Mandatory English Only Directive**: Operate, reason, plan, and communicate STRICTLY and EXCLUSIVELY in the English language across all thoughts, plan steps, and responses, regardless of the language used in the user's prompt. The use of non-English languages (including Indonesian) is strictly and permanently forbidden anywhere in agent responses, plans, or thoughts.
@@ -688,6 +704,8 @@ export class AgentLoop {
688
704
  this.webVerificationScheduled = false;
689
705
  // P6: rendered surfaces this task wrote, for the anti-slop gate to read back.
690
706
  this.webArtifacts = new Set();
707
+ // Web files only read/grepped during exploration — never treated as written surfaces.
708
+ this.inspectedWebFiles = new Set();
691
709
  this.claimedLocalUrls = new Set();
692
710
  this.slopReviewAttempts = 0;
693
711
  this.slopLastAuditHash = '';
@@ -903,7 +921,7 @@ export class AgentLoop {
903
921
  const resolved = path.resolve(this.workspaceRoot, expanded);
904
922
  try {
905
923
  if (fsSync.existsSync(resolved) && fsSync.statSync(resolved).isFile()) {
906
- this.webArtifacts.add(resolved);
924
+ this.inspectedWebFiles.add(resolved);
907
925
  this.webVerificationState.htmlInspected = true;
908
926
  }
909
927
  }
@@ -994,7 +1012,7 @@ export class AgentLoop {
994
1012
  let universalSkillsContext = '';
995
1013
  try {
996
1014
  const detectedDomains = detectWorkspaceDomains(this.workspaceRoot);
997
- const promptText = (this.taskPrompt || '').toLowerCase();
1015
+ const promptText = (this.taskIntentPrompt || this.currentTaskPrompt || this.userPrompt || '').toLowerCase();
998
1016
  if (!detectedDomains.includes('android') && /\b(android|apk|adb|emulator|gradle|gradlew|compose|kotlin)\b/i.test(promptText)) {
999
1017
  detectedDomains.push('android');
1000
1018
  }
@@ -1405,6 +1423,10 @@ export class AgentLoop {
1405
1423
  }
1406
1424
  }
1407
1425
  updateImplementationPlan(update, options = {}) {
1426
+ // A malformed provider plan is not permission to replace a valid plan or
1427
+ // crash an active run. Empty arrays remain valid and can clear the plan.
1428
+ if (!update || !Array.isArray(update.plan))
1429
+ return;
1408
1430
  const nextPlan = update.plan.map((item) => ({ ...item }));
1409
1431
  const prevText = this._implementationPlan.map((item) => item.step).join('\n');
1410
1432
  const prevKey = JSON.stringify(this._implementationPlan.map((item) => ({ id: item.id, step: item.step, status: item.status })));
@@ -1575,6 +1597,8 @@ export class AgentLoop {
1575
1597
  }
1576
1598
  }
1577
1599
  async requestDecision(request) {
1600
+ if (this.stopRequested || this.abortController?.signal?.aborted)
1601
+ return null;
1578
1602
  const fingerprint = createHash('sha256')
1579
1603
  .update(JSON.stringify({ kind: request.kind, question: request.question, options: request.options.map((option) => option.id) }))
1580
1604
  .digest('hex');
@@ -1592,6 +1616,8 @@ export class AgentLoop {
1592
1616
  finally {
1593
1617
  this._entitlementGate?.resume();
1594
1618
  }
1619
+ if (this.stopRequested || this.abortController?.signal?.aborted)
1620
+ return null;
1595
1621
  if (!answer || typeof answer.label !== 'string' || !answer.label.trim()) {
1596
1622
  this.emitEvent({ type: 'decision_result', request, answer: null });
1597
1623
  return null;
@@ -1837,6 +1863,7 @@ export class AgentLoop {
1837
1863
  this._verificationPlanFired = false;
1838
1864
  this.webVerificationState = { screenshotTaken: false, browserActUsed: false, htmlInspected: false };
1839
1865
  this.webArtifacts = new Set();
1866
+ this.inspectedWebFiles = new Set();
1840
1867
  this.claimedLocalUrls = new Set();
1841
1868
  this.slopReviewAttempts = 0;
1842
1869
  this.slopLastAuditHash = '';
@@ -1920,7 +1947,11 @@ export class AgentLoop {
1920
1947
  this.seedTaskPhasePlanIfEmpty();
1921
1948
  if (!this.isInitialized) {
1922
1949
  const activeTier = this.activeTier;
1923
- const charPoolLimit = resolveCharPool(activeTier, this.config.maxCharPool);
1950
+ const charPoolLimit = resolveCharPool(activeTier, this.config.maxCharPool, {
1951
+ provider: this.config.provider,
1952
+ model: this.config.model,
1953
+ overrideTokens: this.config.contextTokens || this.config.maxContextTokens
1954
+ });
1924
1955
  const devTag = isDevEmulator(this.config) ? ' (dev emulator)' : '';
1925
1956
  // Was a console.log carrying a hardcoded \x1b[1m\x1b[36m, which ignored
1926
1957
  // NO_COLOR outright. The renderer paints this through the theme.
@@ -2081,6 +2112,8 @@ export class AgentLoop {
2081
2112
  this._observationDigests = new Map();
2082
2113
  this.consecutiveThinkingSteps = 0;
2083
2114
  this.consecutiveBlockedActions = 0;
2115
+ this.consecutiveFailures = 0;
2116
+ this.lastFailureType = null;
2084
2117
  this.consecutiveCommands = 0;
2085
2118
  this.circuitBreakerUnlocked = false;
2086
2119
  this.recentActionSignatures = [];
@@ -2090,6 +2123,7 @@ export class AgentLoop {
2090
2123
  this._pendingConsent = null;
2091
2124
  this._recoveryNote = null;
2092
2125
  this._verificationNudges = 0;
2126
+ this._nonMutationNudges = 0;
2093
2127
  this._verificationPlanFired = false;
2094
2128
  const effectivePrompt = (this.currentTaskPrompt || this.userPrompt || '').trim();
2095
2129
  if (!this.currentTaskPrompt && this.userPrompt) {
@@ -2107,7 +2141,7 @@ export class AgentLoop {
2107
2141
  let toolRoutingRecoveries = 0;
2108
2142
  let emptyResponseRecoveries = 0;
2109
2143
  // The core loop governed by Sovereign Human-in-the-Loop Checkpoints
2110
- while (!this.stopRequested) {
2144
+ while (!this.stopRequested && !this.abortController?.signal?.aborted) {
2111
2145
  const desktopTimeLeft = remainingDesktopTime(this._taskWallDeadlineAt);
2112
2146
  if (desktopTimeLeft !== null && desktopTimeLeft <= 0) {
2113
2147
  this.emitEvent({ type: 'budget_warning', message: 'Desktop task stopped at its 180-second wall-clock ceiling. Progress is preserved; outcome is unverified.' });
@@ -2147,7 +2181,11 @@ export class AgentLoop {
2147
2181
  // tool payloads decay into stubs, and anything amputated is physically
2148
2182
  // replaced by a summary, so memory, disk and CPU all stay bounded.
2149
2183
  const activeTier = isDevEmulator(this.config) ? 'super_max' : (this.config.tier || 'premium');
2150
- const MAX_CHAR_POOL = resolveCharPool(activeTier, this.config.maxCharPool);
2184
+ const MAX_CHAR_POOL = resolveCharPool(activeTier, this.config.maxCharPool, {
2185
+ provider: this.config.provider,
2186
+ model: this.config.model,
2187
+ overrideTokens: this.config.contextTokens || this.config.maxContextTokens
2188
+ });
2151
2189
  // 5-Stage Progressive Compaction (Claude Code Architecture / Research Section E):
2152
2190
  // Stage 0 (HLCE Ephemeral Decay) + Stage 2 (Snip >15K tokens / 60K chars) +
2153
2191
  // Stage 1 (Budget Reduction >70%) + Stage 3 (Microcompact) + Stage 4 (Context Collapse >85%)
@@ -2277,7 +2315,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2277
2315
  4. Perform thorough code inspection of generated math, physics, and canvas render loops to ensure zero defects.
2278
2316
  - For non-visual tasks (backend, CLI, algorithms): Verify using standard test suites and execution logs.`;
2279
2317
  const providerPrompt = `${baseProviderPrompt}${sensoryAwareness}`;
2280
- const memoryContext = getMemoryContextString();
2318
+ const memoryContext = getMemoryContextString({ workspaceRoot: this.workspaceRoot });
2281
2319
  // --- PER-TASK STATIC CONTEXT (computed once, not once per step) ---
2282
2320
  // Cortex retrieval, design detection, creative-pattern lookup and the
2283
2321
  // workspace domain scan are all constant for the duration of a task, but
@@ -2305,11 +2343,15 @@ You are operating in a text-and-code modality without direct image pixel renderi
2305
2343
  ctx.packageManager && `Package manager: ${ctx.packageManager}`,
2306
2344
  ctx.gitBranch && `Git branch: ${ctx.gitBranch}`,
2307
2345
  ctx.gitStatus && `Git status: ${ctx.gitStatus}`,
2346
+ Array.isArray(ctx.topEntries) && ctx.topEntries.length > 0 && `Top-level layout: ${ctx.topEntries.slice(0, 20).join(', ')}`,
2347
+ Array.isArray(ctx.subprojectStacks) && ctx.subprojectStacks.length > 0 && `Detected stacks: ${ctx.subprojectStacks.join(', ')}`,
2308
2348
  Array.isArray(ctx.subprojects) && ctx.subprojects.length > 0 && `Subprojects in workspace: ${ctx.subprojects.join(', ')}`,
2349
+ Array.isArray(ctx.docFiles) && ctx.docFiles.length > 0 && `Project docs (read relevant docs before guessing conventions): ${ctx.docFiles.slice(0, 15).join(', ')}`,
2350
+ Array.isArray(ctx.buildFiles) && ctx.buildFiles.length > 0 && `Build & config files: ${ctx.buildFiles.slice(0, 15).join(', ')}`,
2309
2351
  Array.isArray(ctx.keyFiles) && ctx.keyFiles.length > 0 && `Key files: ${ctx.keyFiles.slice(0, 25).join(', ')}`
2310
2352
  ].filter(Boolean);
2311
2353
  if (facts.length > 0) {
2312
- workspaceSummary = `\n\n◆ WORKSPACE CONTEXT (already scanned for you — do NOT waste steps rediscovering this):\n${facts.join('\n')}`;
2354
+ workspaceSummary = `\n\n◆ WORKSPACE CONTEXT (scanned on disk — verify docs/build scripts directly and treat repository files as authoritative):\n${facts.join('\n')}`;
2313
2355
  }
2314
2356
  }
2315
2357
  // --- PROMPT ASSEMBLY, ORDERED STABLE → VOLATILE ---
@@ -2415,7 +2457,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2415
2457
  // here never invalidates the cached prefix in [1]-[3].
2416
2458
  {
2417
2459
  role: 'system',
2418
- content: `${uncertaintyDirective ? uncertaintyDirective + '\n\n' : ''}${describeSession(this.taskId)}CURRENT AUTONOMY MODE: ${autonomyMode}\nALLOWED WORKSPACE PATHS: ${allowedPaths}\n(You MUST NOT write files outside these paths!)\n\n◆ PERSISTENT MEMORY (FACTS LEARNED ABOUT THE USER):\n${memoryContext}`
2460
+ content: `${uncertaintyDirective ? uncertaintyDirective + '\n\n' : ''}${describeSession(this.taskId)}CURRENT AUTONOMY MODE: ${autonomyMode}\nALLOWED WORKSPACE PATHS: ${allowedPaths}\n(You MUST NOT write files outside these paths!)${memoryContext ? `\n\n◆ PERSISTENT MEMORY (workspace-relevant notes — actual repository files and docs on disk always override memory if anything conflicts):\n${memoryContext}` : ''}`
2419
2461
  }
2420
2462
  ];
2421
2463
  // Dev-only visibility into what fills each step's prompt. Set
@@ -2522,6 +2564,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2522
2564
  let nativeMutationCount = 0;
2523
2565
  let nativeExplorationCount = 0;
2524
2566
  const completedNativeActionIds = new Set();
2567
+ const seenNativePlanActionIds = new Set();
2525
2568
  const observedNativeTerminalIds = new Set();
2526
2569
  const finalizeReasoningSegment = () => {
2527
2570
  if (!segmentReasoning)
@@ -2654,6 +2697,9 @@ You are operating in a text-and-code modality without direct image pixel renderi
2654
2697
  const actionPlan = normalizePeerPlanEntries(action.parameters);
2655
2698
  if (actionPlan) {
2656
2699
  hasStructuredToolPlan = true;
2700
+ if (action.id)
2701
+ seenNativePlanActionIds.add(String(action.id));
2702
+ seenNativePlanActionIds.add(JSON.stringify(actionPlan));
2657
2703
  this.updateImplementationPlan(actionPlan);
2658
2704
  }
2659
2705
  const isChecklistTool = Boolean(actionPlan) || ['todowrite', 'todo_write', 'update_plan'].includes(action.name.toLowerCase());
@@ -2730,7 +2776,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2730
2776
  const lowerName = action.name.toLowerCase();
2731
2777
  const rawDetail = String(action.detail || '');
2732
2778
  const lowerDetail = rawDetail.toLowerCase();
2733
- if (['fs_write', 'fs_edit', 'write_file', 'edit_file', 'write', 'edit', 'replace_file_content'].includes(lowerName)
2779
+ if (['fs_write', 'fs_edit', 'write_file', 'edit_file', 'write', 'edit', 'multiedit', 'multi_edit', 'write_to_file', 'replace_file_content', 'multi_replace_file_content'].includes(lowerName)
2734
2780
  || isNativeMutation(action.name, actionArgs)) {
2735
2781
  nativeMutationCount++;
2736
2782
  taskMutationCount++;
@@ -2742,7 +2788,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2742
2788
  this.advanceImplementationPlanProgress('mutation');
2743
2789
  }
2744
2790
  }
2745
- else if (['browse', 'browser_act', 'preview', 'snapshot', 'scrape', 'web_fetch'].includes(lowerName)) {
2791
+ else if (isRenderedNativeBrowserAction(lowerName)) {
2746
2792
  this.webVerificationState.browserActUsed = true;
2747
2793
  this.advanceImplementationPlanProgress('verification');
2748
2794
  }
@@ -2766,12 +2812,9 @@ You are operating in a text-and-code modality without direct image pixel renderi
2766
2812
  this.llm.supportsVision) {
2767
2813
  this.webVerificationState.screenshotTaken = true;
2768
2814
  }
2769
- if (['browse', 'browser_act', 'preview', 'snapshot', 'scrape', 'web_fetch'].includes(lowerName)) {
2815
+ if (isRenderedNativeBrowserAction(lowerName)) {
2770
2816
  this.webVerificationState.browserActUsed = true;
2771
2817
  }
2772
- if (/\.(html?|css|jsx|tsx|vue|svelte)\b/i.test(rawDetail)) {
2773
- this.webVerificationState.htmlInspected = true;
2774
- }
2775
2818
  }
2776
2819
  const nativeCode = codeProgressFromAction(action.name, { ...(action.parameters && typeof action.parameters === 'object' ? action.parameters : {}),
2777
2820
  path: action.parameters?.path || action.parameters?.Path || action.detail || '' }, `provider:${action.name}:${action.detail || ''}`, action.status === 'completed' ? 'done' : action.status === 'failed' ? 'failed' : 'working', 'provider');
@@ -2807,7 +2850,6 @@ You are operating in a text-and-code modality without direct image pixel renderi
2807
2850
  }
2808
2851
  }).catch((error) => {
2809
2852
  if (this._pendingConsent) {
2810
- this.stepsCompleted += completedNativeActionIds.size;
2811
2853
  const checkpoint = new RetryConsentCheckpoint();
2812
2854
  if (error && typeof error === 'object' && 'partialUsage' in error) {
2813
2855
  Object.assign(checkpoint, { partialUsage: error.partialUsage });
@@ -2830,18 +2872,20 @@ You are operating in a text-and-code modality without direct image pixel renderi
2830
2872
  if (finalCodePreview)
2831
2873
  this.emitEvent(finalCodePreview);
2832
2874
  if (this._pendingConsent) {
2833
- this.stepsCompleted += completedNativeActionIds.size;
2834
2875
  throw Object.assign(new RetryConsentCheckpoint(), { partialUsage: response.usage });
2835
2876
  }
2836
- // The call came back. Whatever went wrong before is no longer
2837
- // consecutive — without this reset, one failure at step 2 and another
2838
- // at step 200 would count toward the same ceiling and stop a task that
2839
- // was working perfectly well.
2840
- this.consecutiveFailures = 0;
2841
- this.lastFailureType = null;
2842
2877
  // Track tokens. usage carries cachedPromptTokens / cacheWriteTokens so
2843
2878
  // the cost estimate reflects the real cache-discounted bill.
2844
- const tracking = await this.tokenTracker.trackUsage(response.usage.promptTokens, response.usage.completionTokens, (msg) => this.emitEvent({ type: 'budget_warning', message: msg }), response.usage);
2879
+ const rawUsage = response?.usage && typeof response.usage === 'object' ? response.usage : undefined;
2880
+ const normalizedUsage = rawUsage
2881
+ ? {
2882
+ ...rawUsage,
2883
+ promptTokens: Number.isFinite(Number(rawUsage.promptTokens)) ? Math.max(0, Number(rawUsage.promptTokens)) : 0,
2884
+ completionTokens: Number.isFinite(Number(rawUsage.completionTokens)) ? Math.max(0, Number(rawUsage.completionTokens)) : 0,
2885
+ cachedPromptTokens: Number.isFinite(Number(rawUsage.cachedPromptTokens)) ? Math.max(0, Number(rawUsage.cachedPromptTokens)) : 0
2886
+ }
2887
+ : { promptTokens: 0, completionTokens: 0, cachedPromptTokens: 0 };
2888
+ const tracking = await this.tokenTracker.trackUsage(normalizedUsage.promptTokens, normalizedUsage.completionTokens, (msg) => this.emitEvent({ type: 'budget_warning', message: msg }), normalizedUsage);
2845
2889
  // Private numeric telemetry only. The daily ledger aggregates calls,
2846
2890
  // so it cannot attribute usage to a task or distinguish provider data
2847
2891
  // from the character-count fallback used by some ACP peers.
@@ -2849,17 +2893,17 @@ You are operating in a text-and-code modality without direct image pixel renderi
2849
2893
  event: 'model_usage', scope: 'agent_loop_primary',
2850
2894
  taskId: this.taskId, step: this.stepsCompleted,
2851
2895
  provider: this.config.provider || 'unknown',
2852
- promptTokens: response.usage.promptTokens,
2853
- completionTokens: response.usage.completionTokens,
2854
- cachedPromptTokens: response.usage.cachedPromptTokens || 0,
2855
- uncachedPromptTokens: response.usage.uncachedPromptTokens,
2856
- noncachedTokens: noncachedTokens(response.usage),
2857
- measurement: response.usage.measurement || 'unspecified',
2858
- measurementScope: response.usage.measurementScope || 'unspecified',
2859
- cacheMeasurement: response.usage.cacheMeasurement || 'unspecified',
2896
+ promptTokens: normalizedUsage.promptTokens,
2897
+ completionTokens: normalizedUsage.completionTokens,
2898
+ cachedPromptTokens: normalizedUsage.cachedPromptTokens,
2899
+ uncachedPromptTokens: rawUsage?.uncachedPromptTokens,
2900
+ noncachedTokens: noncachedTokens(normalizedUsage),
2901
+ measurement: rawUsage?.measurement || 'unspecified',
2902
+ measurementScope: rawUsage?.measurementScope || 'unspecified',
2903
+ cacheMeasurement: rawUsage?.cacheMeasurement || 'unspecified',
2860
2904
  costBasis: /^(acp(?:\/|$)|antigravity$|agy$)/i.test(String(this.config.provider || ''))
2861
2905
  ? 'external_subscription_unavailable' : 'rate_card_estimate',
2862
- callEstimatedCostUsd: this.tokenTracker.calculateCost(response.usage.promptTokens, response.usage.completionTokens, response.usage)
2906
+ callEstimatedCostUsd: this.tokenTracker.calculateCost(normalizedUsage.promptTokens, normalizedUsage.completionTokens, normalizedUsage)
2863
2907
  });
2864
2908
  // Soft advisory only; repeated status frames must not consume tokens or stop work.
2865
2909
  if (isAntigravityPeer(this.config.provider) && !hardBudget && !softUsageNoticeIssued
@@ -2868,10 +2912,14 @@ You are operating in a text-and-code modality without direct image pixel renderi
2868
2912
  this.emitEvent({ type: 'notice', message: `Task usage passed ${DEFAULT_AGY_TASK_TOKENS.toLocaleString()} fresh tokens. This is an advisory, not a stop. Use /stop or set a user hard budget to limit further calls.` });
2869
2913
  auditLog.log({ event: 'task_usage_advisory', taskId: this.taskId, freshTokens: this.tokenTracker.taskTokens });
2870
2914
  }
2871
- const cachedTokens = response.usage.cachedPromptTokens || 0;
2915
+ const cachedTokens = normalizedUsage.cachedPromptTokens;
2872
2916
  if (cachedTokens > 0) {
2873
- this.debugLog(`prompt cache hit: ${cachedTokens.toLocaleString()} of ${response.usage.promptTokens.toLocaleString()} input tokens served from cache`);
2917
+ this.debugLog(`prompt cache hit: ${cachedTokens.toLocaleString()} of ${normalizedUsage.promptTokens.toLocaleString()} input tokens served from cache`);
2874
2918
  }
2919
+ // Reset retry state only after response metadata and token accounting succeed
2920
+ // so an internal post-response exception cannot spin infinitely on retry 1 of 3.
2921
+ this.consecutiveFailures = 0;
2922
+ this.lastFailureType = null;
2875
2923
  //
2876
2924
  // ALWAYS read (AgentViewModel: `optInt("dailyTokens", optInt("usedTokens",
2877
2925
  // — which this frame set to the TASK total. The card therefore drew task
@@ -2882,6 +2930,16 @@ You are operating in a text-and-code modality without direct image pixel renderi
2882
2930
  // the window is actually budgeted in. The renderer converts once, using
2883
2931
  // the project's own CHAR_POOLS convention, instead of comparing a token
2884
2932
  // count to a character limit.
2933
+ const reportedPromptTokens = Number(response.usage?.promptTokens || 0);
2934
+ if (response.usage?.measurement === 'provider_reported'
2935
+ && response.usage?.measurementScope !== 'cumulative'
2936
+ && Number.isFinite(reportedPromptTokens)
2937
+ && reportedPromptTokens > 0) {
2938
+ const reportedContextChars = Math.round(reportedPromptTokens * CHARS_PER_TOKEN);
2939
+ if (reportedContextChars > (this._contextChars || 0)) {
2940
+ this._contextChars = reportedContextChars;
2941
+ }
2942
+ }
2885
2943
  this.emitEvent({
2886
2944
  type: 'usage_update',
2887
2945
  usedTokens: tracking.dailyTokens || 0,
@@ -3106,7 +3164,14 @@ You are operating in a text-and-code modality without direct image pixel renderi
3106
3164
  const extPlan = normalizePeerPlanEntries(extAction.parameters);
3107
3165
  if (extPlan) {
3108
3166
  hasStructuredToolPlan = true;
3109
- this.updateImplementationPlan(extPlan);
3167
+ const extActionId = extAction.id ? String(extAction.id) : '';
3168
+ const extPlanKey = JSON.stringify(extPlan);
3169
+ if (!(extActionId && seenNativePlanActionIds.has(extActionId)) && !seenNativePlanActionIds.has(extPlanKey)) {
3170
+ seenNativePlanActionIds.add(extPlanKey);
3171
+ if (extActionId)
3172
+ seenNativePlanActionIds.add(extActionId);
3173
+ this.updateImplementationPlan(extPlan);
3174
+ }
3110
3175
  }
3111
3176
  const actionName = String(extAction.name || '').toLowerCase();
3112
3177
  const detailPath = typeof extAction.detail === 'string' ? extAction.detail.trim() : '';
@@ -3844,6 +3909,10 @@ You are operating in a text-and-code modality without direct image pixel renderi
3844
3909
  this.smartToolsGovernor.beginModelStep();
3845
3910
  const prefetched = this.prefetchReadOnlyCalls(response.toolCalls);
3846
3911
  // 3. ACT (Execute tool calls)
3912
+ // Non-tool messages (system nudges, runtime diagnostics, image user turns)
3913
+ // must follow every role:'tool' result of the assistant batch; inserting
3914
+ // them mid-batch triggers sanitizeSequences() to strip remaining tool_calls.
3915
+ const deferredPostBatchMessages = [];
3847
3916
  for (const toolCall of response.toolCalls) {
3848
3917
  if (this.stopRequested || this.abortController?.signal?.aborted)
3849
3918
  break;
@@ -3988,7 +4057,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
3988
4057
  break;
3989
4058
  }
3990
4059
  if (isAuthoringTask && (this.stallGuard.distinctInspectionCount === 3 || this.stallGuard.distinctInspectionCount === 6)) {
3991
- this.messages.push({
4060
+ deferredPostBatchMessages.push({
3992
4061
  role: 'system',
3993
4062
  content: `[CRITICAL ACTION MANDATE: You have performed ${this.stallGuard.distinctInspectionCount} inspection steps without writing code. This is an authoring task. Proceed immediately to creating or editing implementation files using fs_write/fs_edit in the target directory.]`
3994
4063
  });
@@ -4292,7 +4361,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4292
4361
  this._totalActMs = (this._totalActMs || 0) + (performance.now() - actStart);
4293
4362
  }
4294
4363
  catch (toolError) {
4295
- if (this.stopRequested || this.abortController?.signal?.aborted || toolError?.name === 'AbortError') {
4364
+ if (this.stopRequested || this.abortController?.signal?.aborted) {
4296
4365
  auditLog.log({ event: 'task_interrupted', taskId: this.taskId, tool: functionName });
4297
4366
  break;
4298
4367
  }
@@ -4385,7 +4454,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4385
4454
  type: 'status',
4386
4455
  message: `△ Browser runtime error(s) detected: ${allRuntimeErrors[0]}`
4387
4456
  });
4388
- this.messages.push({
4457
+ deferredPostBatchMessages.push({
4389
4458
  role: 'system',
4390
4459
  content: `[BROWSER RUNTIME ERRORS DETECTED: The page encountered runtime error(s) during preview:\n${allRuntimeErrors.slice(0, 5).join('\n')}\nYou MUST inspect your code, fix these runtime bugs, and re-verify before the task can be completed.]`
4391
4460
  });
@@ -4414,12 +4483,15 @@ You are operating in a text-and-code modality without direct image pixel renderi
4414
4483
  catch { /* never block tool execution on episodic recording */ }
4415
4484
  const recovery = this.timeMachine.observe(functionName, args, observedResult, coldObserver.getToolOutcomes(this.taskId));
4416
4485
  const verdict = await this.handleRecovery(recovery, functionName);
4417
- if (result && (result.success === false || typeof result.error === 'string')) {
4486
+ if (isToolErrorResult(result)) {
4418
4487
  result = { ...result, timeMachine: verdict.guidance };
4419
4488
  }
4420
4489
  if (this.stopRequested) {
4490
+ const stoppedContent = result?._is_image_marker
4491
+ ? `Image captured: ${result.filename || 'image'} (${result.mimeType || 'image/png'}).`
4492
+ : JSON.stringify(result);
4421
4493
  this.messages.push({ role: 'tool', tool_call_id: toolCall.id,
4422
- name: functionName, content: JSON.stringify(result) });
4494
+ name: functionName, content: stoppedContent });
4423
4495
  this.memoryManager.saveHistory(this.messages);
4424
4496
  break;
4425
4497
  }
@@ -4437,23 +4509,23 @@ You are operating in a text-and-code modality without direct image pixel renderi
4437
4509
  }
4438
4510
  // Buffer output for disconnect resilience
4439
4511
  await this.taskBuffer.appendOutput(this.taskId, { tool: functionName, result: observedResult });
4512
+ const isErrorOutcome = isToolErrorResult(result);
4440
4513
  if (codeAction)
4441
4514
  this.emitEvent({ ...codeAction,
4442
- phase: result?.success === false || typeof result?.error === 'string' ? 'failed' : 'done' });
4515
+ phase: isErrorOutcome ? 'failed' : 'done' });
4443
4516
  const eventResult = result?._is_image_marker
4444
- ? { success: result.success !== false && !result.error, output: result.output || `Image captured: ${result.filename || 'image'} (${result.mimeType || 'image/png'})` }
4517
+ ? { success: !isErrorOutcome, output: result.output || `Image captured: ${result.filename || 'image'} (${result.mimeType || 'image/png'})` }
4445
4518
  : result;
4446
- const isErrorOutcome = result?.success === false || typeof result?.error === 'string';
4447
- const errorMsg = eventResult?.error || (typeof result?.error === 'string' ? result.error : undefined);
4519
+ const rawErrorMsg = nonEmptyErrorText(eventResult) ?? nonEmptyErrorText(result);
4448
4520
  this.emitEvent({
4449
4521
  type: isErrorOutcome ? 'step_error' : 'step_complete',
4450
4522
  tool: functionName,
4451
- ...(isErrorOutcome && errorMsg ? { error: errorMsg } : {}),
4523
+ ...(isErrorOutcome && rawErrorMsg ? { error: rawErrorMsg } : {}),
4452
4524
  result: eventResult,
4453
4525
  toolCallId: toolCall.id
4454
4526
  });
4455
4527
  this.stepsCompleted++;
4456
- if (this._implementationPlanSeeded && result?.success !== false && !result?.error && functionName !== 'update_plan') {
4528
+ if (this._implementationPlanSeeded && !isErrorOutcome && functionName !== 'update_plan') {
4457
4529
  this.advanceImplementationPlanProgress('mutation');
4458
4530
  }
4459
4531
  // The procedure, as it actually ran. Tool name plus a whitelisted
@@ -4523,14 +4595,15 @@ You are operating in a text-and-code modality without direct image pixel renderi
4523
4595
  if (!approved) {
4524
4596
  this.stopRequested = true;
4525
4597
  this.emitEvent({ type: 'status', message: 'Task stopped at 100-step circuit breaker checkpoint by user.' });
4526
- break;
4527
4598
  }
4528
- this.circuitBreakerUnlocked = true;
4529
- this.emitEvent({ type: 'status', message: `✓ Circuit breaker unlocked! Resuming execution up to ${this.maxSteps} tier budget...` });
4599
+ else {
4600
+ this.circuitBreakerUnlocked = true;
4601
+ this.emitEvent({ type: 'status', message: `✓ Circuit breaker unlocked! Resuming execution up to ${this.maxSteps} tier budget...` });
4602
+ }
4530
4603
  }
4531
4604
  }
4532
4605
  // Sovereign Tier Budget Extension Checkpoint Gate
4533
- if (this.stepsCompleted >= this.maxSteps) {
4606
+ if (this.stepsCompleted >= this.maxSteps && !this.stopRequested) {
4534
4607
  if (this.config.autonomyMode === 'C') {
4535
4608
  this.stopRequested = true;
4536
4609
  this.emitEvent({ type: 'error', message: `Task reached the configured ${this.maxSteps}-step limit without verified completion.` });
@@ -4553,11 +4626,12 @@ You are operating in a text-and-code modality without direct image pixel renderi
4553
4626
  if (!approved) {
4554
4627
  this.stopRequested = true;
4555
4628
  this.emitEvent({ type: 'status', message: `Task stopped at ${this.maxSteps}-step tier limit by user.` });
4556
- break;
4557
4629
  }
4558
- this.maxSteps += extensionBatch;
4559
- this.maxCircuitBreaker = this.maxSteps;
4560
- this.emitEvent({ type: 'status', message: `✓ Tier budget extended (+${extensionBatch} steps unlocked, new limit: ${this.maxSteps}). Resuming task...` });
4630
+ else {
4631
+ this.maxSteps += extensionBatch;
4632
+ this.maxCircuitBreaker = this.maxSteps;
4633
+ this.emitEvent({ type: 'status', message: `✓ Tier budget extended (+${extensionBatch} steps unlocked, new limit: ${this.maxSteps}). Resuming task...` });
4634
+ }
4561
4635
  }
4562
4636
  }
4563
4637
  // SmartToolsUse tracks actual local tool calls, without denying
@@ -4606,8 +4680,8 @@ You are operating in a text-and-code modality without direct image pixel renderi
4606
4680
  name: functionName,
4607
4681
  content: `Image successfully captured: ${result.filename || 'image'}. Passing to vision observation.`
4608
4682
  });
4609
- // Then push the user observation message containing the image data block
4610
- this.messages.push({
4683
+ // Defer user image observation until after every role:'tool' result in this batch.
4684
+ deferredPostBatchMessages.push({
4611
4685
  role: 'user',
4612
4686
  content: [
4613
4687
  imageContent,
@@ -4642,7 +4716,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4642
4716
  spill = { path: stored.diskPath };
4643
4717
  resultString = JSON.stringify({
4644
4718
  ...(typeof result?.success === 'boolean' ? { success: result.success } : {}),
4645
- ...(typeof result?.error === 'string' ? { error: result.error.slice(0, 500) } : {}),
4719
+ ...spillErrorField(result),
4646
4720
  output: stored.contentForModel
4647
4721
  });
4648
4722
  }
@@ -4676,7 +4750,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4676
4750
  this._observationDigests.set(digest, this.stepsCompleted + 1);
4677
4751
  }
4678
4752
  }
4679
- const isCallFailed = Boolean(result && (result.success === false || typeof result.error === 'string'));
4753
+ const isCallFailed = isToolErrorResult(result);
4680
4754
  const stallObservation = this.stallGuard.observeCall(functionName, args || {}, result, toolCall.id, isCallFailed);
4681
4755
  if (stallObservation.stub && resultString.length >= 256) {
4682
4756
  resultString = stallObservation.stub;
@@ -4692,7 +4766,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4692
4766
  ...(spill ? { spillPath: spill.path } : {})
4693
4767
  });
4694
4768
  if (stallObservation.notice) {
4695
- this.messages.push({
4769
+ deferredPostBatchMessages.push({
4696
4770
  role: 'system',
4697
4771
  content: stallObservation.notice
4698
4772
  });
@@ -4707,9 +4781,17 @@ You are operating in a text-and-code modality without direct image pixel renderi
4707
4781
  }
4708
4782
  // Save state continuously after each tool loop
4709
4783
  this.memoryManager.saveHistory(this.messages);
4710
- if (this.stopRequested)
4784
+ if (this.stopRequested || this.abortController?.signal?.aborted)
4711
4785
  break;
4712
4786
  }
4787
+ if (deferredPostBatchMessages.length > 0) {
4788
+ for (const deferredMsg of deferredPostBatchMessages) {
4789
+ this.messages.push(deferredMsg);
4790
+ }
4791
+ this.memoryManager.saveHistory(this.messages);
4792
+ }
4793
+ if (this.stopRequested || this.abortController?.signal?.aborted)
4794
+ break;
4713
4795
  }
4714
4796
  catch (e) {
4715
4797
  // Providers sometimes throw strings or plain objects. Normalize once
@@ -4938,7 +5020,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4938
5020
  + Number(error?.partialUsage?.completionTokens || 0);
4939
5021
  if (spent > 0)
4940
5022
  return 'fatal';
4941
- const msg = (error.message || '').toLowerCase();
5023
+ const msg = (typeof error === 'string' ? error : error?.message || '').toLowerCase();
4942
5024
  if (error?.name === 'OpenRouterPrivacyConstraintError'
4943
5025
  || msg.includes('matching the privacy policy')
4944
5026
  || msg.includes('data_collection=')) {
@@ -4971,6 +5053,9 @@ You are operating in a text-and-code modality without direct image pixel renderi
4971
5053
  if (msg.includes('kill') || msg.includes('abort') || msg.includes('signal') || msg.includes('fatal')) {
4972
5054
  return 'fatal';
4973
5055
  }
5056
+ if (error instanceof TypeError || error instanceof ReferenceError || error instanceof RangeError) {
5057
+ return 'fatal';
5058
+ }
4974
5059
  return 'unknown_error';
4975
5060
  }
4976
5061
  // V5: Provide actionable retry hints per error type