@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
package/src/agentLoop.ts CHANGED
@@ -52,7 +52,7 @@ import { requiresToolApproval, withToolAutonomyMode } from './approvalPolicy.js'
52
52
  import { AGENT_USER_POLICY } from './agentPolicy.js';
53
53
  import { VFETracker } from './vfeTracker.js';
54
54
  import { coldObserver } from './observer/coldObserver.js';
55
- import { isVerificationCommand } from './observer/evidence.js';
55
+ import { isRenderedNativeBrowserAction, isVerificationCommand } from './observer/evidence.js';
56
56
  import { CausyneObserver, defaultObserver, extractClaimedLocalUrls } from './observer.js';
57
57
  import type { Observation } from './observer.js';
58
58
  import { TimeMachine, recoveryUserMessage, TIME_MACHINE_MAX_ATTEMPTS } from './timeMachine.js';
@@ -80,6 +80,7 @@ import type { DecideToolsInput } from './decideTools.js';
80
80
  import { SavedTools, readSavedTools, writeSavedTools } from './saveTools.js';
81
81
  import type { AdmissionResult } from './saveTools.js';
82
82
  import {
83
+ CHARS_PER_TOKEN,
83
84
  resolveCharPool,
84
85
  measureMessages,
85
86
  resultCapFor,
@@ -114,7 +115,7 @@ import { isPlanReviewHandoff, isPlanningOnlyRequest } from './taskContinuation.j
114
115
  export function noncachedTokens(usage: any): number {
115
116
  if (!usage) return 0;
116
117
  const finite = (value: number | undefined): number => Number.isFinite(value) ? Math.max(0, value ?? 0) : 0;
117
- const input = usage.uncachedPromptTokens !== undefined
118
+ const input = typeof usage.uncachedPromptTokens === 'number' && Number.isFinite(usage.uncachedPromptTokens)
118
119
  ? finite(usage.uncachedPromptTokens)
119
120
  : finite(usage.cachedPromptTokens) > finite(usage.promptTokens)
120
121
  ? finite(usage.promptTokens)
@@ -122,6 +123,24 @@ export function noncachedTokens(usage: any): number {
122
123
  return input + finite(usage.completionTokens);
123
124
  }
124
125
 
126
+ function nonEmptyErrorText(result: any): string | undefined {
127
+ return typeof result?.error === 'string' && result.error.trim().length > 0
128
+ ? result.error
129
+ : undefined;
130
+ }
131
+
132
+ export function isToolErrorResult(result: any): boolean {
133
+ if (!result || typeof result !== 'object') return false;
134
+ return result.success === false
135
+ || nonEmptyErrorText(result) !== undefined
136
+ || (typeof result.exitCode === 'number' && (!Number.isFinite(result.exitCode) || result.exitCode !== 0));
137
+ }
138
+
139
+ function spillErrorField(result: any): { error?: string } {
140
+ const error = nonEmptyErrorText(result);
141
+ return error !== undefined ? { error: error.slice(0, 500) } : {};
142
+ }
143
+
125
144
  export interface AgentLoopEvent {
126
145
  type: string;
127
146
  [key: string]: unknown;
@@ -376,10 +395,10 @@ ${AGENT_USER_POLICY}
376
395
  # Project Conventions
377
396
  Follow the selected project's existing style and architecture. Check dependencies and tool schemas before use. Preserve unrelated behavior.
378
397
 
379
- # Greenfield Application Scaffolding vs. Legacy Codebase Exploration
380
- - 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.
381
- - DO NOT perform exploratory directory listings of the root repository or inspect unrelated legacy projects in the workspace.
382
- - Immediately initialize the target directory and author the required implementation files (e.g. index.html, style.css, app.js).
398
+ # Repository Structure, Project Docs & Existing Codebases First
399
+ - 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.
400
+ - 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.
401
+ - Only skip root exploration when creating an explicitly requested brand-new greenfield project inside a dedicated new/empty directory.
383
402
 
384
403
  # Operational Guidelines & Communication
385
404
  - **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.
@@ -787,6 +806,8 @@ export class AgentLoop {
787
806
  this.webVerificationScheduled = false;
788
807
  // P6: rendered surfaces this task wrote, for the anti-slop gate to read back.
789
808
  this.webArtifacts = new Set();
809
+ // Web files only read/grepped during exploration — never treated as written surfaces.
810
+ this.inspectedWebFiles = new Set();
790
811
  this.claimedLocalUrls = new Set();
791
812
  this.slopReviewAttempts = 0;
792
813
  this.slopLastAuditHash = '';
@@ -1012,7 +1033,7 @@ export class AgentLoop {
1012
1033
  const resolved = path.resolve(this.workspaceRoot, expanded);
1013
1034
  try {
1014
1035
  if (fsSync.existsSync(resolved) && fsSync.statSync(resolved).isFile()) {
1015
- this.webArtifacts.add(resolved);
1036
+ this.inspectedWebFiles.add(resolved);
1016
1037
  this.webVerificationState.htmlInspected = true;
1017
1038
  }
1018
1039
  } catch {
@@ -1104,7 +1125,7 @@ export class AgentLoop {
1104
1125
  let universalSkillsContext = '';
1105
1126
  try {
1106
1127
  const detectedDomains = detectWorkspaceDomains(this.workspaceRoot);
1107
- const promptText = (this.taskPrompt || '').toLowerCase();
1128
+ const promptText = (this.taskIntentPrompt || this.currentTaskPrompt || this.userPrompt || '').toLowerCase();
1108
1129
  if (!detectedDomains.includes('android') && /\b(android|apk|adb|emulator|gradle|gradlew|compose|kotlin)\b/i.test(promptText)) {
1109
1130
  detectedDomains.push('android');
1110
1131
  }
@@ -1488,6 +1509,9 @@ export class AgentLoop {
1488
1509
  }
1489
1510
 
1490
1511
  updateImplementationPlan(update: any, options: { seeded?: boolean } = {}) {
1512
+ // A malformed provider plan is not permission to replace a valid plan or
1513
+ // crash an active run. Empty arrays remain valid and can clear the plan.
1514
+ if (!update || !Array.isArray(update.plan)) return;
1491
1515
  const nextPlan = update.plan.map((item: any) => ({ ...item }));
1492
1516
  const prevText = this._implementationPlan.map((item: any) => item.step).join('\n');
1493
1517
  const prevKey = JSON.stringify(this._implementationPlan.map((item: any) => ({ id: item.id, step: item.step, status: item.status })));
@@ -1642,6 +1666,7 @@ export class AgentLoop {
1642
1666
  }
1643
1667
 
1644
1668
  async requestDecision(request: any) {
1669
+ if (this.stopRequested || this.abortController?.signal?.aborted) return null;
1645
1670
  const fingerprint = createHash('sha256')
1646
1671
  .update(JSON.stringify({ kind: request.kind, question: request.question, options: request.options.map((option: any) => option.id) }))
1647
1672
  .digest('hex');
@@ -1658,6 +1683,7 @@ export class AgentLoop {
1658
1683
  } finally {
1659
1684
  this._entitlementGate?.resume();
1660
1685
  }
1686
+ if (this.stopRequested || this.abortController?.signal?.aborted) return null;
1661
1687
  if (!answer || typeof answer.label !== 'string' || !answer.label.trim()) {
1662
1688
  this.emitEvent({ type: 'decision_result', request, answer: null });
1663
1689
  return null;
@@ -1895,6 +1921,7 @@ export class AgentLoop {
1895
1921
  this._verificationPlanFired = false;
1896
1922
  this.webVerificationState = { screenshotTaken: false, browserActUsed: false, htmlInspected: false };
1897
1923
  this.webArtifacts = new Set();
1924
+ this.inspectedWebFiles = new Set();
1898
1925
  this.claimedLocalUrls = new Set();
1899
1926
  this.slopReviewAttempts = 0;
1900
1927
  this.slopLastAuditHash = '';
@@ -1986,7 +2013,11 @@ export class AgentLoop {
1986
2013
 
1987
2014
  if (!this.isInitialized) {
1988
2015
  const activeTier = this.activeTier;
1989
- const charPoolLimit = resolveCharPool(activeTier, this.config.maxCharPool);
2016
+ const charPoolLimit = resolveCharPool(activeTier, this.config.maxCharPool, {
2017
+ provider: this.config.provider,
2018
+ model: this.config.model,
2019
+ overrideTokens: this.config.contextTokens || this.config.maxContextTokens
2020
+ });
1990
2021
  const devTag = isDevEmulator(this.config) ? ' (dev emulator)' : '';
1991
2022
  // Was a console.log carrying a hardcoded \x1b[1m\x1b[36m, which ignored
1992
2023
  // NO_COLOR outright. The renderer paints this through the theme.
@@ -2154,6 +2185,8 @@ export class AgentLoop {
2154
2185
  this._observationDigests = new Map();
2155
2186
  this.consecutiveThinkingSteps = 0;
2156
2187
  this.consecutiveBlockedActions = 0;
2188
+ this.consecutiveFailures = 0;
2189
+ this.lastFailureType = null;
2157
2190
  this.consecutiveCommands = 0;
2158
2191
  this.circuitBreakerUnlocked = false;
2159
2192
  this.recentActionSignatures = [];
@@ -2163,6 +2196,7 @@ export class AgentLoop {
2163
2196
  this._pendingConsent = null;
2164
2197
  this._recoveryNote = null;
2165
2198
  this._verificationNudges = 0;
2199
+ this._nonMutationNudges = 0;
2166
2200
  this._verificationPlanFired = false;
2167
2201
  const effectivePrompt = (this.currentTaskPrompt || this.userPrompt || '').trim();
2168
2202
  if (!this.currentTaskPrompt && this.userPrompt) {
@@ -2181,7 +2215,7 @@ export class AgentLoop {
2181
2215
  let emptyResponseRecoveries = 0;
2182
2216
 
2183
2217
  // The core loop governed by Sovereign Human-in-the-Loop Checkpoints
2184
- while (!this.stopRequested) {
2218
+ while (!this.stopRequested && !this.abortController?.signal?.aborted) {
2185
2219
  const desktopTimeLeft = remainingDesktopTime(this._taskWallDeadlineAt);
2186
2220
  if (desktopTimeLeft !== null && desktopTimeLeft <= 0) {
2187
2221
  this.emitEvent({ type: 'budget_warning', message:
@@ -2223,7 +2257,11 @@ export class AgentLoop {
2223
2257
  // replaced by a summary, so memory, disk and CPU all stay bounded.
2224
2258
 
2225
2259
  const activeTier = isDevEmulator(this.config) ? 'super_max' : (this.config.tier || 'premium');
2226
- const MAX_CHAR_POOL = resolveCharPool(activeTier, this.config.maxCharPool);
2260
+ const MAX_CHAR_POOL = resolveCharPool(activeTier, this.config.maxCharPool, {
2261
+ provider: this.config.provider,
2262
+ model: this.config.model,
2263
+ overrideTokens: this.config.contextTokens || this.config.maxContextTokens
2264
+ });
2227
2265
 
2228
2266
  // 5-Stage Progressive Compaction (Claude Code Architecture / Research Section E):
2229
2267
  // Stage 0 (HLCE Ephemeral Decay) + Stage 2 (Snip >15K tokens / 60K chars) +
@@ -2360,7 +2398,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2360
2398
  4. Perform thorough code inspection of generated math, physics, and canvas render loops to ensure zero defects.
2361
2399
  - For non-visual tasks (backend, CLI, algorithms): Verify using standard test suites and execution logs.`;
2362
2400
  const providerPrompt = `${baseProviderPrompt}${sensoryAwareness}`;
2363
- const memoryContext = getMemoryContextString();
2401
+ const memoryContext = getMemoryContextString({ workspaceRoot: this.workspaceRoot });
2364
2402
 
2365
2403
  // --- PER-TASK STATIC CONTEXT (computed once, not once per step) ---
2366
2404
  // Cortex retrieval, design detection, creative-pattern lookup and the
@@ -2390,11 +2428,15 @@ You are operating in a text-and-code modality without direct image pixel renderi
2390
2428
  ctx.packageManager && `Package manager: ${ctx.packageManager}`,
2391
2429
  ctx.gitBranch && `Git branch: ${ctx.gitBranch}`,
2392
2430
  ctx.gitStatus && `Git status: ${ctx.gitStatus}`,
2431
+ Array.isArray(ctx.topEntries) && ctx.topEntries.length > 0 && `Top-level layout: ${ctx.topEntries.slice(0, 20).join(', ')}`,
2432
+ Array.isArray(ctx.subprojectStacks) && ctx.subprojectStacks.length > 0 && `Detected stacks: ${ctx.subprojectStacks.join(', ')}`,
2393
2433
  Array.isArray(ctx.subprojects) && ctx.subprojects.length > 0 && `Subprojects in workspace: ${ctx.subprojects.join(', ')}`,
2434
+ Array.isArray(ctx.docFiles) && ctx.docFiles.length > 0 && `Project docs (read relevant docs before guessing conventions): ${ctx.docFiles.slice(0, 15).join(', ')}`,
2435
+ Array.isArray(ctx.buildFiles) && ctx.buildFiles.length > 0 && `Build & config files: ${ctx.buildFiles.slice(0, 15).join(', ')}`,
2394
2436
  Array.isArray(ctx.keyFiles) && ctx.keyFiles.length > 0 && `Key files: ${ctx.keyFiles.slice(0, 25).join(', ')}`
2395
2437
  ].filter(Boolean);
2396
2438
  if (facts.length > 0) {
2397
- workspaceSummary = `\n\n◆ WORKSPACE CONTEXT (already scanned for you — do NOT waste steps rediscovering this):\n${facts.join('\n')}`;
2439
+ workspaceSummary = `\n\n◆ WORKSPACE CONTEXT (scanned on disk — verify docs/build scripts directly and treat repository files as authoritative):\n${facts.join('\n')}`;
2398
2440
  }
2399
2441
  }
2400
2442
 
@@ -2508,7 +2550,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2508
2550
  // here never invalidates the cached prefix in [1]-[3].
2509
2551
  {
2510
2552
  role: 'system',
2511
- 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}`
2553
+ 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}` : ''}`
2512
2554
  }
2513
2555
  ];
2514
2556
 
@@ -2623,6 +2665,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2623
2665
  let nativeMutationCount = 0;
2624
2666
  let nativeExplorationCount = 0;
2625
2667
  const completedNativeActionIds = new Set<string>();
2668
+ const seenNativePlanActionIds = new Set<string>();
2626
2669
  const observedNativeTerminalIds = new Set<string>();
2627
2670
  const finalizeReasoningSegment = (): void => {
2628
2671
  if (!segmentReasoning) return;
@@ -2749,6 +2792,8 @@ You are operating in a text-and-code modality without direct image pixel renderi
2749
2792
  const actionPlan = normalizePeerPlanEntries(action.parameters);
2750
2793
  if (actionPlan) {
2751
2794
  hasStructuredToolPlan = true;
2795
+ if (action.id) seenNativePlanActionIds.add(String(action.id));
2796
+ seenNativePlanActionIds.add(JSON.stringify(actionPlan));
2752
2797
  this.updateImplementationPlan(actionPlan);
2753
2798
  }
2754
2799
  const isChecklistTool = Boolean(actionPlan) || ['todowrite', 'todo_write', 'update_plan'].includes(action.name.toLowerCase());
@@ -2820,7 +2865,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2820
2865
  const lowerName = action.name.toLowerCase();
2821
2866
  const rawDetail = String(action.detail || '');
2822
2867
  const lowerDetail = rawDetail.toLowerCase();
2823
- if (['fs_write', 'fs_edit', 'write_file', 'edit_file', 'write', 'edit', 'replace_file_content'].includes(lowerName)
2868
+ 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)
2824
2869
  || isNativeMutation(action.name, actionArgs)) {
2825
2870
  nativeMutationCount++;
2826
2871
  taskMutationCount++;
@@ -2830,7 +2875,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2830
2875
  } else if (nativeMutationCount % 2 === 0) {
2831
2876
  this.advanceImplementationPlanProgress('mutation');
2832
2877
  }
2833
- } else if (['browse', 'browser_act', 'preview', 'snapshot', 'scrape', 'web_fetch'].includes(lowerName)) {
2878
+ } else if (isRenderedNativeBrowserAction(lowerName)) {
2834
2879
  this.webVerificationState.browserActUsed = true;
2835
2880
  this.advanceImplementationPlanProgress('verification');
2836
2881
  } else if (lowerName === 'fs_read' && /\.(png|jpg|jpeg|webp)$/i.test(lowerDetail)) {
@@ -2852,12 +2897,9 @@ You are operating in a text-and-code modality without direct image pixel renderi
2852
2897
  this.llm.supportsVision) {
2853
2898
  this.webVerificationState.screenshotTaken = true;
2854
2899
  }
2855
- if (['browse', 'browser_act', 'preview', 'snapshot', 'scrape', 'web_fetch'].includes(lowerName)) {
2900
+ if (isRenderedNativeBrowserAction(lowerName)) {
2856
2901
  this.webVerificationState.browserActUsed = true;
2857
2902
  }
2858
- if (/\.(html?|css|jsx|tsx|vue|svelte)\b/i.test(rawDetail)) {
2859
- this.webVerificationState.htmlInspected = true;
2860
- }
2861
2903
  }
2862
2904
  const nativeCode = codeProgressFromAction(
2863
2905
  action.name,
@@ -2897,7 +2939,6 @@ You are operating in a text-and-code modality without direct image pixel renderi
2897
2939
  }
2898
2940
  }).catch((error: unknown) => {
2899
2941
  if (this._pendingConsent) {
2900
- this.stepsCompleted += completedNativeActionIds.size;
2901
2942
  const checkpoint = new RetryConsentCheckpoint();
2902
2943
  if (error && typeof error === 'object' && 'partialUsage' in error) {
2903
2944
  Object.assign(checkpoint, { partialUsage: error.partialUsage });
@@ -2922,24 +2963,26 @@ You are operating in a text-and-code modality without direct image pixel renderi
2922
2963
  if (finalCodePreview) this.emitEvent(finalCodePreview);
2923
2964
 
2924
2965
  if (this._pendingConsent) {
2925
- this.stepsCompleted += completedNativeActionIds.size;
2926
2966
  throw Object.assign(new RetryConsentCheckpoint(), { partialUsage: response.usage });
2927
2967
  }
2928
2968
 
2929
- // The call came back. Whatever went wrong before is no longer
2930
- // consecutive — without this reset, one failure at step 2 and another
2931
- // at step 200 would count toward the same ceiling and stop a task that
2932
- // was working perfectly well.
2933
- this.consecutiveFailures = 0;
2934
- this.lastFailureType = null;
2935
-
2936
2969
  // Track tokens. usage carries cachedPromptTokens / cacheWriteTokens so
2937
2970
  // the cost estimate reflects the real cache-discounted bill.
2971
+ const rawUsage = response?.usage && typeof response.usage === 'object' ? response.usage : undefined;
2972
+ const normalizedUsage = rawUsage
2973
+ ? {
2974
+ ...rawUsage,
2975
+ promptTokens: Number.isFinite(Number(rawUsage.promptTokens)) ? Math.max(0, Number(rawUsage.promptTokens)) : 0,
2976
+ completionTokens: Number.isFinite(Number(rawUsage.completionTokens)) ? Math.max(0, Number(rawUsage.completionTokens)) : 0,
2977
+ cachedPromptTokens: Number.isFinite(Number(rawUsage.cachedPromptTokens)) ? Math.max(0, Number(rawUsage.cachedPromptTokens)) : 0
2978
+ }
2979
+ : { promptTokens: 0, completionTokens: 0, cachedPromptTokens: 0 };
2980
+
2938
2981
  const tracking = await this.tokenTracker.trackUsage(
2939
- response.usage.promptTokens,
2940
- response.usage.completionTokens,
2982
+ normalizedUsage.promptTokens,
2983
+ normalizedUsage.completionTokens,
2941
2984
  (msg: string) => this.emitEvent({ type: 'budget_warning', message: msg }),
2942
- response.usage
2985
+ normalizedUsage
2943
2986
  );
2944
2987
 
2945
2988
  // Private numeric telemetry only. The daily ledger aggregates calls,
@@ -2949,18 +2992,18 @@ You are operating in a text-and-code modality without direct image pixel renderi
2949
2992
  event: 'model_usage', scope: 'agent_loop_primary',
2950
2993
  taskId: this.taskId, step: this.stepsCompleted,
2951
2994
  provider: this.config.provider || 'unknown',
2952
- promptTokens: response.usage.promptTokens,
2953
- completionTokens: response.usage.completionTokens,
2954
- cachedPromptTokens: response.usage.cachedPromptTokens || 0,
2955
- uncachedPromptTokens: response.usage.uncachedPromptTokens,
2956
- noncachedTokens: noncachedTokens(response.usage),
2957
- measurement: response.usage.measurement || 'unspecified',
2958
- measurementScope: response.usage.measurementScope || 'unspecified',
2959
- cacheMeasurement: response.usage.cacheMeasurement || 'unspecified',
2995
+ promptTokens: normalizedUsage.promptTokens,
2996
+ completionTokens: normalizedUsage.completionTokens,
2997
+ cachedPromptTokens: normalizedUsage.cachedPromptTokens,
2998
+ uncachedPromptTokens: rawUsage?.uncachedPromptTokens,
2999
+ noncachedTokens: noncachedTokens(normalizedUsage),
3000
+ measurement: rawUsage?.measurement || 'unspecified',
3001
+ measurementScope: rawUsage?.measurementScope || 'unspecified',
3002
+ cacheMeasurement: rawUsage?.cacheMeasurement || 'unspecified',
2960
3003
  costBasis: /^(acp(?:\/|$)|antigravity$|agy$)/i.test(String(this.config.provider || ''))
2961
3004
  ? 'external_subscription_unavailable' : 'rate_card_estimate',
2962
3005
  callEstimatedCostUsd: this.tokenTracker.calculateCost(
2963
- response.usage.promptTokens, response.usage.completionTokens, response.usage
3006
+ normalizedUsage.promptTokens, normalizedUsage.completionTokens, normalizedUsage
2964
3007
  )
2965
3008
  });
2966
3009
 
@@ -2973,11 +3016,16 @@ You are operating in a text-and-code modality without direct image pixel renderi
2973
3016
  auditLog.log({ event: 'task_usage_advisory', taskId: this.taskId, freshTokens: this.tokenTracker.taskTokens });
2974
3017
  }
2975
3018
 
2976
- const cachedTokens = response.usage.cachedPromptTokens || 0;
3019
+ const cachedTokens = normalizedUsage.cachedPromptTokens;
2977
3020
  if (cachedTokens > 0) {
2978
- this.debugLog(`prompt cache hit: ${cachedTokens.toLocaleString()} of ${response.usage.promptTokens.toLocaleString()} input tokens served from cache`);
3021
+ this.debugLog(`prompt cache hit: ${cachedTokens.toLocaleString()} of ${normalizedUsage.promptTokens.toLocaleString()} input tokens served from cache`);
2979
3022
  }
2980
3023
 
3024
+ // Reset retry state only after response metadata and token accounting succeed
3025
+ // so an internal post-response exception cannot spin infinitely on retry 1 of 3.
3026
+ this.consecutiveFailures = 0;
3027
+ this.lastFailureType = null;
3028
+
2981
3029
 
2982
3030
  //
2983
3031
 
@@ -2992,6 +3040,16 @@ You are operating in a text-and-code modality without direct image pixel renderi
2992
3040
  // the window is actually budgeted in. The renderer converts once, using
2993
3041
  // the project's own CHAR_POOLS convention, instead of comparing a token
2994
3042
  // count to a character limit.
3043
+ const reportedPromptTokens = Number(response.usage?.promptTokens || 0);
3044
+ if (response.usage?.measurement === 'provider_reported'
3045
+ && response.usage?.measurementScope !== 'cumulative'
3046
+ && Number.isFinite(reportedPromptTokens)
3047
+ && reportedPromptTokens > 0) {
3048
+ const reportedContextChars = Math.round(reportedPromptTokens * CHARS_PER_TOKEN);
3049
+ if (reportedContextChars > (this._contextChars || 0)) {
3050
+ this._contextChars = reportedContextChars;
3051
+ }
3052
+ }
2995
3053
  this.emitEvent({
2996
3054
  type: 'usage_update',
2997
3055
  usedTokens: tracking.dailyTokens || 0,
@@ -3227,7 +3285,13 @@ You are operating in a text-and-code modality without direct image pixel renderi
3227
3285
  const extPlan = normalizePeerPlanEntries(extAction.parameters);
3228
3286
  if (extPlan) {
3229
3287
  hasStructuredToolPlan = true;
3230
- this.updateImplementationPlan(extPlan);
3288
+ const extActionId = extAction.id ? String(extAction.id) : '';
3289
+ const extPlanKey = JSON.stringify(extPlan);
3290
+ if (!(extActionId && seenNativePlanActionIds.has(extActionId)) && !seenNativePlanActionIds.has(extPlanKey)) {
3291
+ seenNativePlanActionIds.add(extPlanKey);
3292
+ if (extActionId) seenNativePlanActionIds.add(extActionId);
3293
+ this.updateImplementationPlan(extPlan);
3294
+ }
3231
3295
  }
3232
3296
  const actionName = String(extAction.name || '').toLowerCase();
3233
3297
  const detailPath = typeof extAction.detail === 'string' ? extAction.detail.trim() : '';
@@ -4012,6 +4076,10 @@ You are operating in a text-and-code modality without direct image pixel renderi
4012
4076
  const prefetched = this.prefetchReadOnlyCalls(response.toolCalls);
4013
4077
 
4014
4078
  // 3. ACT (Execute tool calls)
4079
+ // Non-tool messages (system nudges, runtime diagnostics, image user turns)
4080
+ // must follow every role:'tool' result of the assistant batch; inserting
4081
+ // them mid-batch triggers sanitizeSequences() to strip remaining tool_calls.
4082
+ const deferredPostBatchMessages: Array<{ role: 'system' | 'user'; content: any }> = [];
4015
4083
  for (const toolCall of response.toolCalls) {
4016
4084
  if (this.stopRequested || this.abortController?.signal?.aborted) break;
4017
4085
  // Canonicalise once, here. Every downstream comparison — the sandbox's
@@ -4165,7 +4233,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4165
4233
  }
4166
4234
 
4167
4235
  if (isAuthoringTask && (this.stallGuard.distinctInspectionCount === 3 || this.stallGuard.distinctInspectionCount === 6)) {
4168
- this.messages.push({
4236
+ deferredPostBatchMessages.push({
4169
4237
  role: 'system',
4170
4238
  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.]`
4171
4239
  });
@@ -4502,7 +4570,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4502
4570
  duration = Date.now() - startTime;
4503
4571
  this._totalActMs = (this._totalActMs || 0) + (performance.now() - actStart);
4504
4572
  } catch (toolError: any) {
4505
- if (this.stopRequested || this.abortController?.signal?.aborted || toolError?.name === 'AbortError') {
4573
+ if (this.stopRequested || this.abortController?.signal?.aborted) {
4506
4574
  auditLog.log({ event: 'task_interrupted', taskId: this.taskId, tool: functionName });
4507
4575
  break;
4508
4576
  }
@@ -4604,7 +4672,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4604
4672
  type: 'status',
4605
4673
  message: `△ Browser runtime error(s) detected: ${allRuntimeErrors[0]}`
4606
4674
  });
4607
- this.messages.push({
4675
+ deferredPostBatchMessages.push({
4608
4676
  role: 'system',
4609
4677
  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.]`
4610
4678
  });
@@ -4634,12 +4702,15 @@ You are operating in a text-and-code modality without direct image pixel renderi
4634
4702
  functionName, args, observedResult, coldObserver.getToolOutcomes(this.taskId)
4635
4703
  );
4636
4704
  const verdict = await this.handleRecovery(recovery, functionName);
4637
- if (result && (result.success === false || typeof result.error === 'string')) {
4705
+ if (isToolErrorResult(result)) {
4638
4706
  result = { ...result, timeMachine: verdict.guidance };
4639
4707
  }
4640
4708
  if (this.stopRequested) {
4709
+ const stoppedContent = result?._is_image_marker
4710
+ ? `Image captured: ${result.filename || 'image'} (${result.mimeType || 'image/png'}).`
4711
+ : JSON.stringify(result);
4641
4712
  this.messages.push({ role: 'tool', tool_call_id: toolCall.id,
4642
- name: functionName, content: JSON.stringify(result) });
4713
+ name: functionName, content: stoppedContent });
4643
4714
  this.memoryManager.saveHistory(this.messages);
4644
4715
  break;
4645
4716
  }
@@ -4660,23 +4731,23 @@ You are operating in a text-and-code modality without direct image pixel renderi
4660
4731
  // Buffer output for disconnect resilience
4661
4732
  await this.taskBuffer.appendOutput(this.taskId, { tool: functionName, result: observedResult });
4662
4733
 
4734
+ const isErrorOutcome = isToolErrorResult(result);
4663
4735
  if (codeAction) this.emitEvent({ ...codeAction,
4664
- phase: result?.success === false || typeof result?.error === 'string' ? 'failed' : 'done' });
4736
+ phase: isErrorOutcome ? 'failed' : 'done' });
4665
4737
 
4666
4738
  const eventResult = result?._is_image_marker
4667
- ? { success: result.success !== false && !result.error, output: result.output || `Image captured: ${result.filename || 'image'} (${result.mimeType || 'image/png'})` }
4739
+ ? { success: !isErrorOutcome, output: result.output || `Image captured: ${result.filename || 'image'} (${result.mimeType || 'image/png'})` }
4668
4740
  : result;
4669
- const isErrorOutcome = result?.success === false || typeof result?.error === 'string';
4670
- const errorMsg = eventResult?.error || (typeof result?.error === 'string' ? result.error : undefined);
4741
+ const rawErrorMsg = nonEmptyErrorText(eventResult) ?? nonEmptyErrorText(result);
4671
4742
  this.emitEvent({
4672
4743
  type: isErrorOutcome ? 'step_error' : 'step_complete',
4673
4744
  tool: functionName,
4674
- ...(isErrorOutcome && errorMsg ? { error: errorMsg } : {}),
4745
+ ...(isErrorOutcome && rawErrorMsg ? { error: rawErrorMsg } : {}),
4675
4746
  result: eventResult,
4676
4747
  toolCallId: toolCall.id
4677
4748
  });
4678
4749
  this.stepsCompleted++;
4679
- if (this._implementationPlanSeeded && result?.success !== false && !result?.error && functionName !== 'update_plan') {
4750
+ if (this._implementationPlanSeeded && !isErrorOutcome && functionName !== 'update_plan') {
4680
4751
  this.advanceImplementationPlanProgress('mutation');
4681
4752
  }
4682
4753
 
@@ -4754,15 +4825,15 @@ You are operating in a text-and-code modality without direct image pixel renderi
4754
4825
  if (!approved) {
4755
4826
  this.stopRequested = true;
4756
4827
  this.emitEvent({ type: 'status', message: 'Task stopped at 100-step circuit breaker checkpoint by user.' });
4757
- break;
4828
+ } else {
4829
+ this.circuitBreakerUnlocked = true;
4830
+ this.emitEvent({ type: 'status', message: `✓ Circuit breaker unlocked! Resuming execution up to ${this.maxSteps} tier budget...` });
4758
4831
  }
4759
- this.circuitBreakerUnlocked = true;
4760
- this.emitEvent({ type: 'status', message: `✓ Circuit breaker unlocked! Resuming execution up to ${this.maxSteps} tier budget...` });
4761
4832
  }
4762
4833
  }
4763
4834
 
4764
4835
  // Sovereign Tier Budget Extension Checkpoint Gate
4765
- if (this.stepsCompleted >= this.maxSteps) {
4836
+ if (this.stepsCompleted >= this.maxSteps && !this.stopRequested) {
4766
4837
  if (this.config.autonomyMode === 'C') {
4767
4838
  this.stopRequested = true;
4768
4839
  this.emitEvent({ type: 'error', message: `Task reached the configured ${this.maxSteps}-step limit without verified completion.` });
@@ -4785,11 +4856,11 @@ You are operating in a text-and-code modality without direct image pixel renderi
4785
4856
  if (!approved) {
4786
4857
  this.stopRequested = true;
4787
4858
  this.emitEvent({ type: 'status', message: `Task stopped at ${this.maxSteps}-step tier limit by user.` });
4788
- break;
4859
+ } else {
4860
+ this.maxSteps += extensionBatch;
4861
+ this.maxCircuitBreaker = this.maxSteps;
4862
+ this.emitEvent({ type: 'status', message: `✓ Tier budget extended (+${extensionBatch} steps unlocked, new limit: ${this.maxSteps}). Resuming task...` });
4789
4863
  }
4790
- this.maxSteps += extensionBatch;
4791
- this.maxCircuitBreaker = this.maxSteps;
4792
- this.emitEvent({ type: 'status', message: `✓ Tier budget extended (+${extensionBatch} steps unlocked, new limit: ${this.maxSteps}). Resuming task...` });
4793
4864
  }
4794
4865
  }
4795
4866
 
@@ -4839,9 +4910,9 @@ You are operating in a text-and-code modality without direct image pixel renderi
4839
4910
  content: `Image successfully captured: ${result.filename || 'image'}. Passing to vision observation.`
4840
4911
  });
4841
4912
 
4842
- // Then push the user observation message containing the image data block
4843
- this.messages.push({
4844
- role: 'user',
4913
+ // Defer user image observation until after every role:'tool' result in this batch.
4914
+ deferredPostBatchMessages.push({
4915
+ role: 'user',
4845
4916
  content: [
4846
4917
  imageContent,
4847
4918
  {
@@ -4874,7 +4945,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4874
4945
  spill = { path: stored.diskPath };
4875
4946
  resultString = JSON.stringify({
4876
4947
  ...(typeof result?.success === 'boolean' ? { success: result.success } : {}),
4877
- ...(typeof result?.error === 'string' ? { error: result.error.slice(0, 500) } : {}),
4948
+ ...spillErrorField(result),
4878
4949
  output: stored.contentForModel
4879
4950
  });
4880
4951
  } else if (document.length > inlineLimit) {
@@ -4908,7 +4979,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4908
4979
  }
4909
4980
  }
4910
4981
 
4911
- const isCallFailed = Boolean(result && (result.success === false || typeof result.error === 'string'));
4982
+ const isCallFailed = isToolErrorResult(result);
4912
4983
  const stallObservation = this.stallGuard.observeCall(
4913
4984
  functionName,
4914
4985
  args || {},
@@ -4933,7 +5004,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4933
5004
  });
4934
5005
 
4935
5006
  if (stallObservation.notice) {
4936
- this.messages.push({
5007
+ deferredPostBatchMessages.push({
4937
5008
  role: 'system',
4938
5009
  content: stallObservation.notice
4939
5010
  });
@@ -4950,8 +5021,15 @@ You are operating in a text-and-code modality without direct image pixel renderi
4950
5021
 
4951
5022
  // Save state continuously after each tool loop
4952
5023
  this.memoryManager.saveHistory(this.messages);
4953
- if (this.stopRequested) break;
5024
+ if (this.stopRequested || this.abortController?.signal?.aborted) break;
4954
5025
  }
5026
+ if (deferredPostBatchMessages.length > 0) {
5027
+ for (const deferredMsg of deferredPostBatchMessages) {
5028
+ this.messages.push(deferredMsg);
5029
+ }
5030
+ this.memoryManager.saveHistory(this.messages);
5031
+ }
5032
+ if (this.stopRequested || this.abortController?.signal?.aborted) break;
4955
5033
 
4956
5034
  } catch (e: any) {
4957
5035
  // Providers sometimes throw strings or plain objects. Normalize once
@@ -5192,7 +5270,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
5192
5270
  const spent = Number(error?.partialUsage?.promptTokens || 0)
5193
5271
  + Number(error?.partialUsage?.completionTokens || 0);
5194
5272
  if (spent > 0) return 'fatal';
5195
- const msg = (error.message || '').toLowerCase();
5273
+ const msg = (typeof error === 'string' ? error : error?.message || '').toLowerCase();
5196
5274
 
5197
5275
  if (error?.name === 'OpenRouterPrivacyConstraintError'
5198
5276
  || msg.includes('matching the privacy policy')
@@ -5226,6 +5304,9 @@ You are operating in a text-and-code modality without direct image pixel renderi
5226
5304
  if (msg.includes('kill') || msg.includes('abort') || msg.includes('signal') || msg.includes('fatal')) {
5227
5305
  return 'fatal';
5228
5306
  }
5307
+ if (error instanceof TypeError || error instanceof ReferenceError || error instanceof RangeError) {
5308
+ return 'fatal';
5309
+ }
5229
5310
 
5230
5311
  return 'unknown_error';
5231
5312
  }
@@ -248,6 +248,9 @@ function ensureLaunchShim(resolvedExecutable, resourceDirectory) {
248
248
  }
249
249
  return shimExecutable;
250
250
  }
251
+ function isChromiumExecutablePath(filePath) {
252
+ return /^(?:google-chrome|google chrome|chrome|chromium-browser|chromium|msedge|microsoft-edge|microsoft edge)(?:-(?:stable|beta|dev|canary))?(?:\.exe)?$/i.test(path.basename(filePath));
253
+ }
251
254
  /** Discover existing installations only. Never downloads or uses a personal profile. */
252
255
  export function resolveChromiumRuntime(configured) {
253
256
  const candidates = configured ? [configured] : process.platform === 'darwin'
@@ -267,12 +270,13 @@ export function resolveChromiumRuntime(configured) {
267
270
  export function resolveBrowserRuntime() {
268
271
  const configured = process.env.CAUSYNE_BROWSER_EXECUTABLE?.trim()
269
272
  || process.env.CAMOUFOX_EXECUTABLE_PATH?.trim();
270
- const candidates = configured
271
- ? [resolveCandidateExecutablePath(path.resolve(configured))]
273
+ const resolvedConfigured = configured ? path.resolve(configured) : undefined;
274
+ const candidates = resolvedConfigured
275
+ ? [resolveCandidateExecutablePath(resolvedConfigured)]
272
276
  : candidateExecutables().map(resolveCandidateExecutablePath);
273
277
  const executablePath = candidates.find(existsSync);
274
- if (configured && /(?:chrome|chromium|msedge)(?:\.exe)?$/i.test(path.basename(configured))) {
275
- const chromium = resolveChromiumRuntime(configured);
278
+ if (resolvedConfigured && isChromiumExecutablePath(resolvedConfigured)) {
279
+ const chromium = resolveChromiumRuntime(resolvedConfigured);
276
280
  if (chromium)
277
281
  return chromium;
278
282
  }
@@ -320,14 +324,15 @@ export function isBrowserRuntimeInstalled() {
320
324
  try {
321
325
  const configured = process.env.CAUSYNE_BROWSER_EXECUTABLE?.trim()
322
326
  || process.env.CAMOUFOX_EXECUTABLE_PATH?.trim();
323
- const candidates = configured
324
- ? [resolveCandidateExecutablePath(path.resolve(configured))]
327
+ const resolvedConfigured = configured ? path.resolve(configured) : undefined;
328
+ const candidates = resolvedConfigured
329
+ ? [resolveCandidateExecutablePath(resolvedConfigured)]
325
330
  : candidateExecutables().map(resolveCandidateExecutablePath);
326
331
  // Match launch-time discovery: Chromium is a supported installed runtime
327
332
  // too. The former Camoufox-only check suppressed host verification even
328
333
  // when resolveBrowserRuntime could launch the installed Chrome browser.
329
- if (configured && /(?:chrome|chromium|msedge)(?:\.exe)?$/i.test(path.basename(configured))) {
330
- return resolveChromiumRuntime(path.resolve(configured)) !== null;
334
+ if (resolvedConfigured && isChromiumExecutablePath(resolvedConfigured)) {
335
+ return resolveChromiumRuntime(resolvedConfigured) !== null;
331
336
  }
332
337
  const hasCamoufox = candidates.some(candidate => {
333
338
  try {