@causyne/agent 1.20.111 → 1.20.116

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 (151) hide show
  1. package/docs/ARCHITECTURE.md +29 -0
  2. package/package.json +1 -1
  3. package/src/agentLoop.js +72 -37
  4. package/src/agentLoop.ts +70 -38
  5. package/src/browser/browserRuntime.js +13 -8
  6. package/src/browser/browserRuntime.ts +16 -8
  7. package/src/browser/causyneBrowser.js +7 -2
  8. package/src/browser/causyneBrowser.ts +8 -2
  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/computerUse/visionGrounding.js +31 -27
  18. package/src/computerUse/visionGrounding.ts +27 -27
  19. package/src/continuum/ui/continuumPicker.js +14 -6
  20. package/src/continuum/ui/continuumPicker.ts +13 -6
  21. package/src/continuum/ui/continuumPickerView.js +24 -15
  22. package/src/continuum/ui/continuumPickerView.ts +24 -16
  23. package/src/observer/advisory.js +32 -22
  24. package/src/observer/advisory.ts +30 -18
  25. package/src/observer/coldObserver.js +21 -33
  26. package/src/observer/coldObserver.ts +20 -33
  27. package/src/observer/evidence.js +20 -13
  28. package/src/observer/evidence.ts +21 -13
  29. package/src/observer.js +47 -12
  30. package/src/observer.ts +50 -18
  31. package/src/pluginsFactory/discovery.js +28 -16
  32. package/src/pluginsFactory/discovery.ts +29 -16
  33. package/src/pluginsFactory/pluginsFactory.js +213 -38
  34. package/src/pluginsFactory/pluginsFactory.ts +218 -39
  35. package/src/pluginsFactory/strategy.js +26 -16
  36. package/src/pluginsFactory/strategy.ts +34 -19
  37. package/src/pluginsFactory/templates.js +183 -62
  38. package/src/pluginsFactory/templates.ts +174 -54
  39. package/src/timeMachine.js +43 -22
  40. package/src/timeMachine.ts +44 -22
  41. package/src/tool-scripts/desktop_act.applescript +1 -0
  42. package/src/tools/computerUse.js +23 -10
  43. package/src/tools/computerUse.ts +19 -8
  44. package/src/tools/desktopAct.js +12 -1
  45. package/src/tools/pluginsFactory.js +108 -5
  46. package/src/tools/pluginsFactory.ts +115 -5
  47. package/src/tui/CausyneRotor.js +24 -10
  48. package/src/tui/CausyneRotor.ts +25 -10
  49. package/src/tui/activityLayout.js +9 -5
  50. package/src/tui/activityLayout.ts +9 -5
  51. package/src/tui/ask.js +34 -14
  52. package/src/tui/banner.js +55 -18
  53. package/src/tui/banner.ts +52 -17
  54. package/src/tui/block.js +47 -20
  55. package/src/tui/block.ts +54 -27
  56. package/src/tui/chatRenderer.js +135 -83
  57. package/src/tui/chatboxClipboard.js +12 -5
  58. package/src/tui/chatboxClipboard.ts +10 -4
  59. package/src/tui/clipboardImage.js +52 -42
  60. package/src/tui/clipboardImage.ts +50 -39
  61. package/src/tui/clipboardSync.js +12 -1
  62. package/src/tui/clipboardSync.ts +9 -1
  63. package/src/tui/codeProgress.js +57 -26
  64. package/src/tui/codeProgress.ts +57 -25
  65. package/src/tui/codeStreamRenderer.js +59 -14
  66. package/src/tui/codeStreamRenderer.ts +58 -14
  67. package/src/tui/commandPresentation.js +9 -2
  68. package/src/tui/commandPresentation.ts +9 -2
  69. package/src/tui/completion.js +45 -23
  70. package/src/tui/composerControls.js +21 -10
  71. package/src/tui/composerControls.ts +18 -10
  72. package/src/tui/composerGeometry.js +6 -4
  73. package/src/tui/composerGeometry.ts +6 -4
  74. package/src/tui/consoleGuard.js +29 -7
  75. package/src/tui/consoleGuard.ts +28 -7
  76. package/src/tui/dialogs.js +134 -71
  77. package/src/tui/diff.js +8 -4
  78. package/src/tui/history.js +6 -5
  79. package/src/tui/home.js +25 -13
  80. package/src/tui/homeView.js +37 -18
  81. package/src/tui/homeView.ts +38 -18
  82. package/src/tui/inlineSlash.js +6 -5
  83. package/src/tui/inlineSlash.ts +6 -5
  84. package/src/tui/keys.js +33 -17
  85. package/src/tui/layout.js +27 -9
  86. package/src/tui/layout.ts +26 -9
  87. package/src/tui/lineEditor.js +49 -23
  88. package/src/tui/markdownMath.js +64 -14
  89. package/src/tui/markdownMath.ts +69 -13
  90. package/src/tui/messageActionPlacement.js +28 -13
  91. package/src/tui/messageActionPlacement.ts +28 -13
  92. package/src/tui/messageInteraction.js +111 -46
  93. package/src/tui/messageInteraction.ts +115 -47
  94. package/src/tui/modelPicker.js +44 -15
  95. package/src/tui/modelPicker.ts +48 -15
  96. package/src/tui/observerPicker.js +56 -13
  97. package/src/tui/observerPicker.ts +73 -30
  98. package/src/tui/overlay.js +79 -35
  99. package/src/tui/overlay.ts +81 -34
  100. package/src/tui/prompt.js +162 -94
  101. package/src/tui/runningLight.js +1 -1
  102. package/src/tui/runningLight.ts +1 -1
  103. package/src/tui/scrollInteraction.js +64 -36
  104. package/src/tui/scrollInteraction.ts +70 -37
  105. package/src/tui/selectList.js +60 -32
  106. package/src/tui/sessionLayout.js +11 -3
  107. package/src/tui/sessionLayout.ts +10 -3
  108. package/src/tui/sessionPicker.js +74 -46
  109. package/src/tui/sessionPicker.ts +73 -48
  110. package/src/tui/sessionPickerView.js +32 -19
  111. package/src/tui/sessionPickerView.ts +31 -18
  112. package/src/tui/sessionSidebar.js +87 -57
  113. package/src/tui/sessionSidebar.ts +90 -54
  114. package/src/tui/setup.js +28 -3
  115. package/src/tui/setup.ts +27 -3
  116. package/src/tui/skillAuthoring.js +11 -5
  117. package/src/tui/skillAuthoring.ts +11 -5
  118. package/src/tui/smartLinkClick.js +75 -23
  119. package/src/tui/smartLinkClick.ts +86 -26
  120. package/src/tui/stage.js +47 -16
  121. package/src/tui/stage.ts +53 -18
  122. package/src/tui/stageSurface.js +120 -49
  123. package/src/tui/statusLine.js +85 -53
  124. package/src/tui/statusLine.ts +82 -46
  125. package/src/tui/terminalInputFramer.js +5 -2
  126. package/src/tui/text.js +117 -46
  127. package/src/tui/text.ts +113 -43
  128. package/src/tui/textLayout.js +6 -4
  129. package/src/tui/textLayout.ts +11 -5
  130. package/src/tui/theme.js +17 -8
  131. package/src/tui/thinkingBox.js +95 -95
  132. package/src/tui/thinkingBox.ts +105 -80
  133. package/src/tui/toolActivityPolicy.js +8 -1
  134. package/src/tui/toolActivityPolicy.ts +7 -1
  135. package/src/tui/toolDisplay.js +15 -6
  136. package/src/tui/toolDisplay.ts +16 -6
  137. package/src/tui/toolOutputNormalizer.js +16 -3
  138. package/src/tui/toolOutputNormalizer.ts +13 -3
  139. package/src/tui/transcript.js +15 -9
  140. package/src/tui/turnRail.js +156 -67
  141. package/src/tui/turnRail.ts +155 -58
  142. package/src/tui/usageCard.js +80 -45
  143. package/src/tui/usageCard.ts +81 -46
  144. package/src/tui/viewport.js +48 -23
  145. package/src/tui/viewport.ts +48 -27
  146. package/src/tui/viewportAnchor.js +2 -2
  147. package/src/tui/viewportAnchor.ts +2 -2
  148. package/src/tui/workspaceFileIndex.js +8 -6
  149. package/src/tui/workspaceFileIndex.ts +8 -6
  150. package/src/tui/workspaceSwitch.js +13 -10
  151. package/src/tui/workspaceSwitch.ts +11 -7
@@ -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.111",
3
+ "version": "1.20.116",
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';
@@ -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)
@@ -994,7 +1010,7 @@ export class AgentLoop {
994
1010
  let universalSkillsContext = '';
995
1011
  try {
996
1012
  const detectedDomains = detectWorkspaceDomains(this.workspaceRoot);
997
- const promptText = (this.taskPrompt || '').toLowerCase();
1013
+ const promptText = (this.taskIntentPrompt || this.currentTaskPrompt || this.userPrompt || '').toLowerCase();
998
1014
  if (!detectedDomains.includes('android') && /\b(android|apk|adb|emulator|gradle|gradlew|compose|kotlin)\b/i.test(promptText)) {
999
1015
  detectedDomains.push('android');
1000
1016
  }
@@ -1575,6 +1591,8 @@ export class AgentLoop {
1575
1591
  }
1576
1592
  }
1577
1593
  async requestDecision(request) {
1594
+ if (this.stopRequested || this.abortController?.signal?.aborted)
1595
+ return null;
1578
1596
  const fingerprint = createHash('sha256')
1579
1597
  .update(JSON.stringify({ kind: request.kind, question: request.question, options: request.options.map((option) => option.id) }))
1580
1598
  .digest('hex');
@@ -1592,6 +1610,8 @@ export class AgentLoop {
1592
1610
  finally {
1593
1611
  this._entitlementGate?.resume();
1594
1612
  }
1613
+ if (this.stopRequested || this.abortController?.signal?.aborted)
1614
+ return null;
1595
1615
  if (!answer || typeof answer.label !== 'string' || !answer.label.trim()) {
1596
1616
  this.emitEvent({ type: 'decision_result', request, answer: null });
1597
1617
  return null;
@@ -2081,6 +2101,8 @@ export class AgentLoop {
2081
2101
  this._observationDigests = new Map();
2082
2102
  this.consecutiveThinkingSteps = 0;
2083
2103
  this.consecutiveBlockedActions = 0;
2104
+ this.consecutiveFailures = 0;
2105
+ this.lastFailureType = null;
2084
2106
  this.consecutiveCommands = 0;
2085
2107
  this.circuitBreakerUnlocked = false;
2086
2108
  this.recentActionSignatures = [];
@@ -2090,6 +2112,7 @@ export class AgentLoop {
2090
2112
  this._pendingConsent = null;
2091
2113
  this._recoveryNote = null;
2092
2114
  this._verificationNudges = 0;
2115
+ this._nonMutationNudges = 0;
2093
2116
  this._verificationPlanFired = false;
2094
2117
  const effectivePrompt = (this.currentTaskPrompt || this.userPrompt || '').trim();
2095
2118
  if (!this.currentTaskPrompt && this.userPrompt) {
@@ -2107,7 +2130,7 @@ export class AgentLoop {
2107
2130
  let toolRoutingRecoveries = 0;
2108
2131
  let emptyResponseRecoveries = 0;
2109
2132
  // The core loop governed by Sovereign Human-in-the-Loop Checkpoints
2110
- while (!this.stopRequested) {
2133
+ while (!this.stopRequested && !this.abortController?.signal?.aborted) {
2111
2134
  const desktopTimeLeft = remainingDesktopTime(this._taskWallDeadlineAt);
2112
2135
  if (desktopTimeLeft !== null && desktopTimeLeft <= 0) {
2113
2136
  this.emitEvent({ type: 'budget_warning', message: 'Desktop task stopped at its 180-second wall-clock ceiling. Progress is preserved; outcome is unverified.' });
@@ -2742,7 +2765,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2742
2765
  this.advanceImplementationPlanProgress('mutation');
2743
2766
  }
2744
2767
  }
2745
- else if (['browse', 'browser_act', 'preview', 'snapshot', 'scrape', 'web_fetch'].includes(lowerName)) {
2768
+ else if (isRenderedNativeBrowserAction(lowerName)) {
2746
2769
  this.webVerificationState.browserActUsed = true;
2747
2770
  this.advanceImplementationPlanProgress('verification');
2748
2771
  }
@@ -2766,12 +2789,9 @@ You are operating in a text-and-code modality without direct image pixel renderi
2766
2789
  this.llm.supportsVision) {
2767
2790
  this.webVerificationState.screenshotTaken = true;
2768
2791
  }
2769
- if (['browse', 'browser_act', 'preview', 'snapshot', 'scrape', 'web_fetch'].includes(lowerName)) {
2792
+ if (isRenderedNativeBrowserAction(lowerName)) {
2770
2793
  this.webVerificationState.browserActUsed = true;
2771
2794
  }
2772
- if (/\.(html?|css|jsx|tsx|vue|svelte)\b/i.test(rawDetail)) {
2773
- this.webVerificationState.htmlInspected = true;
2774
- }
2775
2795
  }
2776
2796
  const nativeCode = codeProgressFromAction(action.name, { ...(action.parameters && typeof action.parameters === 'object' ? action.parameters : {}),
2777
2797
  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 +2827,6 @@ You are operating in a text-and-code modality without direct image pixel renderi
2807
2827
  }
2808
2828
  }).catch((error) => {
2809
2829
  if (this._pendingConsent) {
2810
- this.stepsCompleted += completedNativeActionIds.size;
2811
2830
  const checkpoint = new RetryConsentCheckpoint();
2812
2831
  if (error && typeof error === 'object' && 'partialUsage' in error) {
2813
2832
  Object.assign(checkpoint, { partialUsage: error.partialUsage });
@@ -2830,7 +2849,6 @@ You are operating in a text-and-code modality without direct image pixel renderi
2830
2849
  if (finalCodePreview)
2831
2850
  this.emitEvent(finalCodePreview);
2832
2851
  if (this._pendingConsent) {
2833
- this.stepsCompleted += completedNativeActionIds.size;
2834
2852
  throw Object.assign(new RetryConsentCheckpoint(), { partialUsage: response.usage });
2835
2853
  }
2836
2854
  // The call came back. Whatever went wrong before is no longer
@@ -3844,6 +3862,10 @@ You are operating in a text-and-code modality without direct image pixel renderi
3844
3862
  this.smartToolsGovernor.beginModelStep();
3845
3863
  const prefetched = this.prefetchReadOnlyCalls(response.toolCalls);
3846
3864
  // 3. ACT (Execute tool calls)
3865
+ // Non-tool messages (system nudges, runtime diagnostics, image user turns)
3866
+ // must follow every role:'tool' result of the assistant batch; inserting
3867
+ // them mid-batch triggers sanitizeSequences() to strip remaining tool_calls.
3868
+ const deferredPostBatchMessages = [];
3847
3869
  for (const toolCall of response.toolCalls) {
3848
3870
  if (this.stopRequested || this.abortController?.signal?.aborted)
3849
3871
  break;
@@ -3988,7 +4010,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
3988
4010
  break;
3989
4011
  }
3990
4012
  if (isAuthoringTask && (this.stallGuard.distinctInspectionCount === 3 || this.stallGuard.distinctInspectionCount === 6)) {
3991
- this.messages.push({
4013
+ deferredPostBatchMessages.push({
3992
4014
  role: 'system',
3993
4015
  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
4016
  });
@@ -4292,7 +4314,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4292
4314
  this._totalActMs = (this._totalActMs || 0) + (performance.now() - actStart);
4293
4315
  }
4294
4316
  catch (toolError) {
4295
- if (this.stopRequested || this.abortController?.signal?.aborted || toolError?.name === 'AbortError') {
4317
+ if (this.stopRequested || this.abortController?.signal?.aborted) {
4296
4318
  auditLog.log({ event: 'task_interrupted', taskId: this.taskId, tool: functionName });
4297
4319
  break;
4298
4320
  }
@@ -4385,7 +4407,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4385
4407
  type: 'status',
4386
4408
  message: `△ Browser runtime error(s) detected: ${allRuntimeErrors[0]}`
4387
4409
  });
4388
- this.messages.push({
4410
+ deferredPostBatchMessages.push({
4389
4411
  role: 'system',
4390
4412
  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
4413
  });
@@ -4414,12 +4436,15 @@ You are operating in a text-and-code modality without direct image pixel renderi
4414
4436
  catch { /* never block tool execution on episodic recording */ }
4415
4437
  const recovery = this.timeMachine.observe(functionName, args, observedResult, coldObserver.getToolOutcomes(this.taskId));
4416
4438
  const verdict = await this.handleRecovery(recovery, functionName);
4417
- if (result && (result.success === false || typeof result.error === 'string')) {
4439
+ if (isToolErrorResult(result)) {
4418
4440
  result = { ...result, timeMachine: verdict.guidance };
4419
4441
  }
4420
4442
  if (this.stopRequested) {
4443
+ const stoppedContent = result?._is_image_marker
4444
+ ? `Image captured: ${result.filename || 'image'} (${result.mimeType || 'image/png'}).`
4445
+ : JSON.stringify(result);
4421
4446
  this.messages.push({ role: 'tool', tool_call_id: toolCall.id,
4422
- name: functionName, content: JSON.stringify(result) });
4447
+ name: functionName, content: stoppedContent });
4423
4448
  this.memoryManager.saveHistory(this.messages);
4424
4449
  break;
4425
4450
  }
@@ -4437,23 +4462,23 @@ You are operating in a text-and-code modality without direct image pixel renderi
4437
4462
  }
4438
4463
  // Buffer output for disconnect resilience
4439
4464
  await this.taskBuffer.appendOutput(this.taskId, { tool: functionName, result: observedResult });
4465
+ const isErrorOutcome = isToolErrorResult(result);
4440
4466
  if (codeAction)
4441
4467
  this.emitEvent({ ...codeAction,
4442
- phase: result?.success === false || typeof result?.error === 'string' ? 'failed' : 'done' });
4468
+ phase: isErrorOutcome ? 'failed' : 'done' });
4443
4469
  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'})` }
4470
+ ? { success: !isErrorOutcome, output: result.output || `Image captured: ${result.filename || 'image'} (${result.mimeType || 'image/png'})` }
4445
4471
  : result;
4446
- const isErrorOutcome = result?.success === false || typeof result?.error === 'string';
4447
- const errorMsg = eventResult?.error || (typeof result?.error === 'string' ? result.error : undefined);
4472
+ const rawErrorMsg = nonEmptyErrorText(eventResult) ?? nonEmptyErrorText(result);
4448
4473
  this.emitEvent({
4449
4474
  type: isErrorOutcome ? 'step_error' : 'step_complete',
4450
4475
  tool: functionName,
4451
- ...(isErrorOutcome && errorMsg ? { error: errorMsg } : {}),
4476
+ ...(isErrorOutcome && rawErrorMsg ? { error: rawErrorMsg } : {}),
4452
4477
  result: eventResult,
4453
4478
  toolCallId: toolCall.id
4454
4479
  });
4455
4480
  this.stepsCompleted++;
4456
- if (this._implementationPlanSeeded && result?.success !== false && !result?.error && functionName !== 'update_plan') {
4481
+ if (this._implementationPlanSeeded && !isErrorOutcome && functionName !== 'update_plan') {
4457
4482
  this.advanceImplementationPlanProgress('mutation');
4458
4483
  }
4459
4484
  // The procedure, as it actually ran. Tool name plus a whitelisted
@@ -4523,14 +4548,15 @@ You are operating in a text-and-code modality without direct image pixel renderi
4523
4548
  if (!approved) {
4524
4549
  this.stopRequested = true;
4525
4550
  this.emitEvent({ type: 'status', message: 'Task stopped at 100-step circuit breaker checkpoint by user.' });
4526
- break;
4527
4551
  }
4528
- this.circuitBreakerUnlocked = true;
4529
- this.emitEvent({ type: 'status', message: `✓ Circuit breaker unlocked! Resuming execution up to ${this.maxSteps} tier budget...` });
4552
+ else {
4553
+ this.circuitBreakerUnlocked = true;
4554
+ this.emitEvent({ type: 'status', message: `✓ Circuit breaker unlocked! Resuming execution up to ${this.maxSteps} tier budget...` });
4555
+ }
4530
4556
  }
4531
4557
  }
4532
4558
  // Sovereign Tier Budget Extension Checkpoint Gate
4533
- if (this.stepsCompleted >= this.maxSteps) {
4559
+ if (this.stepsCompleted >= this.maxSteps && !this.stopRequested) {
4534
4560
  if (this.config.autonomyMode === 'C') {
4535
4561
  this.stopRequested = true;
4536
4562
  this.emitEvent({ type: 'error', message: `Task reached the configured ${this.maxSteps}-step limit without verified completion.` });
@@ -4553,11 +4579,12 @@ You are operating in a text-and-code modality without direct image pixel renderi
4553
4579
  if (!approved) {
4554
4580
  this.stopRequested = true;
4555
4581
  this.emitEvent({ type: 'status', message: `Task stopped at ${this.maxSteps}-step tier limit by user.` });
4556
- break;
4557
4582
  }
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...` });
4583
+ else {
4584
+ this.maxSteps += extensionBatch;
4585
+ this.maxCircuitBreaker = this.maxSteps;
4586
+ this.emitEvent({ type: 'status', message: `✓ Tier budget extended (+${extensionBatch} steps unlocked, new limit: ${this.maxSteps}). Resuming task...` });
4587
+ }
4561
4588
  }
4562
4589
  }
4563
4590
  // SmartToolsUse tracks actual local tool calls, without denying
@@ -4606,8 +4633,8 @@ You are operating in a text-and-code modality without direct image pixel renderi
4606
4633
  name: functionName,
4607
4634
  content: `Image successfully captured: ${result.filename || 'image'}. Passing to vision observation.`
4608
4635
  });
4609
- // Then push the user observation message containing the image data block
4610
- this.messages.push({
4636
+ // Defer user image observation until after every role:'tool' result in this batch.
4637
+ deferredPostBatchMessages.push({
4611
4638
  role: 'user',
4612
4639
  content: [
4613
4640
  imageContent,
@@ -4642,7 +4669,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4642
4669
  spill = { path: stored.diskPath };
4643
4670
  resultString = JSON.stringify({
4644
4671
  ...(typeof result?.success === 'boolean' ? { success: result.success } : {}),
4645
- ...(typeof result?.error === 'string' ? { error: result.error.slice(0, 500) } : {}),
4672
+ ...spillErrorField(result),
4646
4673
  output: stored.contentForModel
4647
4674
  });
4648
4675
  }
@@ -4676,7 +4703,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4676
4703
  this._observationDigests.set(digest, this.stepsCompleted + 1);
4677
4704
  }
4678
4705
  }
4679
- const isCallFailed = Boolean(result && (result.success === false || typeof result.error === 'string'));
4706
+ const isCallFailed = isToolErrorResult(result);
4680
4707
  const stallObservation = this.stallGuard.observeCall(functionName, args || {}, result, toolCall.id, isCallFailed);
4681
4708
  if (stallObservation.stub && resultString.length >= 256) {
4682
4709
  resultString = stallObservation.stub;
@@ -4692,7 +4719,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4692
4719
  ...(spill ? { spillPath: spill.path } : {})
4693
4720
  });
4694
4721
  if (stallObservation.notice) {
4695
- this.messages.push({
4722
+ deferredPostBatchMessages.push({
4696
4723
  role: 'system',
4697
4724
  content: stallObservation.notice
4698
4725
  });
@@ -4707,9 +4734,17 @@ You are operating in a text-and-code modality without direct image pixel renderi
4707
4734
  }
4708
4735
  // Save state continuously after each tool loop
4709
4736
  this.memoryManager.saveHistory(this.messages);
4710
- if (this.stopRequested)
4737
+ if (this.stopRequested || this.abortController?.signal?.aborted)
4711
4738
  break;
4712
4739
  }
4740
+ if (deferredPostBatchMessages.length > 0) {
4741
+ for (const deferredMsg of deferredPostBatchMessages) {
4742
+ this.messages.push(deferredMsg);
4743
+ }
4744
+ this.memoryManager.saveHistory(this.messages);
4745
+ }
4746
+ if (this.stopRequested || this.abortController?.signal?.aborted)
4747
+ break;
4713
4748
  }
4714
4749
  catch (e) {
4715
4750
  // Providers sometimes throw strings or plain objects. Normalize once
@@ -4938,7 +4973,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4938
4973
  + Number(error?.partialUsage?.completionTokens || 0);
4939
4974
  if (spent > 0)
4940
4975
  return 'fatal';
4941
- const msg = (error.message || '').toLowerCase();
4976
+ const msg = (typeof error === 'string' ? error : error?.message || '').toLowerCase();
4942
4977
  if (error?.name === 'OpenRouterPrivacyConstraintError'
4943
4978
  || msg.includes('matching the privacy policy')
4944
4979
  || msg.includes('data_collection=')) {