@causyne/agent 1.20.112 → 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
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';
@@ -114,7 +114,7 @@ import { isPlanReviewHandoff, isPlanningOnlyRequest } from './taskContinuation.j
114
114
  export function noncachedTokens(usage: any): number {
115
115
  if (!usage) return 0;
116
116
  const finite = (value: number | undefined): number => Number.isFinite(value) ? Math.max(0, value ?? 0) : 0;
117
- const input = usage.uncachedPromptTokens !== undefined
117
+ const input = typeof usage.uncachedPromptTokens === 'number' && Number.isFinite(usage.uncachedPromptTokens)
118
118
  ? finite(usage.uncachedPromptTokens)
119
119
  : finite(usage.cachedPromptTokens) > finite(usage.promptTokens)
120
120
  ? finite(usage.promptTokens)
@@ -122,6 +122,24 @@ export function noncachedTokens(usage: any): number {
122
122
  return input + finite(usage.completionTokens);
123
123
  }
124
124
 
125
+ function nonEmptyErrorText(result: any): string | undefined {
126
+ return typeof result?.error === 'string' && result.error.trim().length > 0
127
+ ? result.error
128
+ : undefined;
129
+ }
130
+
131
+ export function isToolErrorResult(result: any): boolean {
132
+ if (!result || typeof result !== 'object') return false;
133
+ return result.success === false
134
+ || nonEmptyErrorText(result) !== undefined
135
+ || (typeof result.exitCode === 'number' && (!Number.isFinite(result.exitCode) || result.exitCode !== 0));
136
+ }
137
+
138
+ function spillErrorField(result: any): { error?: string } {
139
+ const error = nonEmptyErrorText(result);
140
+ return error !== undefined ? { error: error.slice(0, 500) } : {};
141
+ }
142
+
125
143
  export interface AgentLoopEvent {
126
144
  type: string;
127
145
  [key: string]: unknown;
@@ -1104,7 +1122,7 @@ export class AgentLoop {
1104
1122
  let universalSkillsContext = '';
1105
1123
  try {
1106
1124
  const detectedDomains = detectWorkspaceDomains(this.workspaceRoot);
1107
- const promptText = (this.taskPrompt || '').toLowerCase();
1125
+ const promptText = (this.taskIntentPrompt || this.currentTaskPrompt || this.userPrompt || '').toLowerCase();
1108
1126
  if (!detectedDomains.includes('android') && /\b(android|apk|adb|emulator|gradle|gradlew|compose|kotlin)\b/i.test(promptText)) {
1109
1127
  detectedDomains.push('android');
1110
1128
  }
@@ -1642,6 +1660,7 @@ export class AgentLoop {
1642
1660
  }
1643
1661
 
1644
1662
  async requestDecision(request: any) {
1663
+ if (this.stopRequested || this.abortController?.signal?.aborted) return null;
1645
1664
  const fingerprint = createHash('sha256')
1646
1665
  .update(JSON.stringify({ kind: request.kind, question: request.question, options: request.options.map((option: any) => option.id) }))
1647
1666
  .digest('hex');
@@ -1658,6 +1677,7 @@ export class AgentLoop {
1658
1677
  } finally {
1659
1678
  this._entitlementGate?.resume();
1660
1679
  }
1680
+ if (this.stopRequested || this.abortController?.signal?.aborted) return null;
1661
1681
  if (!answer || typeof answer.label !== 'string' || !answer.label.trim()) {
1662
1682
  this.emitEvent({ type: 'decision_result', request, answer: null });
1663
1683
  return null;
@@ -2154,6 +2174,8 @@ export class AgentLoop {
2154
2174
  this._observationDigests = new Map();
2155
2175
  this.consecutiveThinkingSteps = 0;
2156
2176
  this.consecutiveBlockedActions = 0;
2177
+ this.consecutiveFailures = 0;
2178
+ this.lastFailureType = null;
2157
2179
  this.consecutiveCommands = 0;
2158
2180
  this.circuitBreakerUnlocked = false;
2159
2181
  this.recentActionSignatures = [];
@@ -2163,6 +2185,7 @@ export class AgentLoop {
2163
2185
  this._pendingConsent = null;
2164
2186
  this._recoveryNote = null;
2165
2187
  this._verificationNudges = 0;
2188
+ this._nonMutationNudges = 0;
2166
2189
  this._verificationPlanFired = false;
2167
2190
  const effectivePrompt = (this.currentTaskPrompt || this.userPrompt || '').trim();
2168
2191
  if (!this.currentTaskPrompt && this.userPrompt) {
@@ -2181,7 +2204,7 @@ export class AgentLoop {
2181
2204
  let emptyResponseRecoveries = 0;
2182
2205
 
2183
2206
  // The core loop governed by Sovereign Human-in-the-Loop Checkpoints
2184
- while (!this.stopRequested) {
2207
+ while (!this.stopRequested && !this.abortController?.signal?.aborted) {
2185
2208
  const desktopTimeLeft = remainingDesktopTime(this._taskWallDeadlineAt);
2186
2209
  if (desktopTimeLeft !== null && desktopTimeLeft <= 0) {
2187
2210
  this.emitEvent({ type: 'budget_warning', message:
@@ -2830,7 +2853,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2830
2853
  } else if (nativeMutationCount % 2 === 0) {
2831
2854
  this.advanceImplementationPlanProgress('mutation');
2832
2855
  }
2833
- } else if (['browse', 'browser_act', 'preview', 'snapshot', 'scrape', 'web_fetch'].includes(lowerName)) {
2856
+ } else if (isRenderedNativeBrowserAction(lowerName)) {
2834
2857
  this.webVerificationState.browserActUsed = true;
2835
2858
  this.advanceImplementationPlanProgress('verification');
2836
2859
  } else if (lowerName === 'fs_read' && /\.(png|jpg|jpeg|webp)$/i.test(lowerDetail)) {
@@ -2852,12 +2875,9 @@ You are operating in a text-and-code modality without direct image pixel renderi
2852
2875
  this.llm.supportsVision) {
2853
2876
  this.webVerificationState.screenshotTaken = true;
2854
2877
  }
2855
- if (['browse', 'browser_act', 'preview', 'snapshot', 'scrape', 'web_fetch'].includes(lowerName)) {
2878
+ if (isRenderedNativeBrowserAction(lowerName)) {
2856
2879
  this.webVerificationState.browserActUsed = true;
2857
2880
  }
2858
- if (/\.(html?|css|jsx|tsx|vue|svelte)\b/i.test(rawDetail)) {
2859
- this.webVerificationState.htmlInspected = true;
2860
- }
2861
2881
  }
2862
2882
  const nativeCode = codeProgressFromAction(
2863
2883
  action.name,
@@ -2897,7 +2917,6 @@ You are operating in a text-and-code modality without direct image pixel renderi
2897
2917
  }
2898
2918
  }).catch((error: unknown) => {
2899
2919
  if (this._pendingConsent) {
2900
- this.stepsCompleted += completedNativeActionIds.size;
2901
2920
  const checkpoint = new RetryConsentCheckpoint();
2902
2921
  if (error && typeof error === 'object' && 'partialUsage' in error) {
2903
2922
  Object.assign(checkpoint, { partialUsage: error.partialUsage });
@@ -2922,7 +2941,6 @@ You are operating in a text-and-code modality without direct image pixel renderi
2922
2941
  if (finalCodePreview) this.emitEvent(finalCodePreview);
2923
2942
 
2924
2943
  if (this._pendingConsent) {
2925
- this.stepsCompleted += completedNativeActionIds.size;
2926
2944
  throw Object.assign(new RetryConsentCheckpoint(), { partialUsage: response.usage });
2927
2945
  }
2928
2946
 
@@ -4012,6 +4030,10 @@ You are operating in a text-and-code modality without direct image pixel renderi
4012
4030
  const prefetched = this.prefetchReadOnlyCalls(response.toolCalls);
4013
4031
 
4014
4032
  // 3. ACT (Execute tool calls)
4033
+ // Non-tool messages (system nudges, runtime diagnostics, image user turns)
4034
+ // must follow every role:'tool' result of the assistant batch; inserting
4035
+ // them mid-batch triggers sanitizeSequences() to strip remaining tool_calls.
4036
+ const deferredPostBatchMessages: Array<{ role: 'system' | 'user'; content: any }> = [];
4015
4037
  for (const toolCall of response.toolCalls) {
4016
4038
  if (this.stopRequested || this.abortController?.signal?.aborted) break;
4017
4039
  // Canonicalise once, here. Every downstream comparison — the sandbox's
@@ -4165,7 +4187,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4165
4187
  }
4166
4188
 
4167
4189
  if (isAuthoringTask && (this.stallGuard.distinctInspectionCount === 3 || this.stallGuard.distinctInspectionCount === 6)) {
4168
- this.messages.push({
4190
+ deferredPostBatchMessages.push({
4169
4191
  role: 'system',
4170
4192
  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
4193
  });
@@ -4502,7 +4524,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4502
4524
  duration = Date.now() - startTime;
4503
4525
  this._totalActMs = (this._totalActMs || 0) + (performance.now() - actStart);
4504
4526
  } catch (toolError: any) {
4505
- if (this.stopRequested || this.abortController?.signal?.aborted || toolError?.name === 'AbortError') {
4527
+ if (this.stopRequested || this.abortController?.signal?.aborted) {
4506
4528
  auditLog.log({ event: 'task_interrupted', taskId: this.taskId, tool: functionName });
4507
4529
  break;
4508
4530
  }
@@ -4604,7 +4626,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4604
4626
  type: 'status',
4605
4627
  message: `△ Browser runtime error(s) detected: ${allRuntimeErrors[0]}`
4606
4628
  });
4607
- this.messages.push({
4629
+ deferredPostBatchMessages.push({
4608
4630
  role: 'system',
4609
4631
  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
4632
  });
@@ -4634,12 +4656,15 @@ You are operating in a text-and-code modality without direct image pixel renderi
4634
4656
  functionName, args, observedResult, coldObserver.getToolOutcomes(this.taskId)
4635
4657
  );
4636
4658
  const verdict = await this.handleRecovery(recovery, functionName);
4637
- if (result && (result.success === false || typeof result.error === 'string')) {
4659
+ if (isToolErrorResult(result)) {
4638
4660
  result = { ...result, timeMachine: verdict.guidance };
4639
4661
  }
4640
4662
  if (this.stopRequested) {
4663
+ const stoppedContent = result?._is_image_marker
4664
+ ? `Image captured: ${result.filename || 'image'} (${result.mimeType || 'image/png'}).`
4665
+ : JSON.stringify(result);
4641
4666
  this.messages.push({ role: 'tool', tool_call_id: toolCall.id,
4642
- name: functionName, content: JSON.stringify(result) });
4667
+ name: functionName, content: stoppedContent });
4643
4668
  this.memoryManager.saveHistory(this.messages);
4644
4669
  break;
4645
4670
  }
@@ -4660,23 +4685,23 @@ You are operating in a text-and-code modality without direct image pixel renderi
4660
4685
  // Buffer output for disconnect resilience
4661
4686
  await this.taskBuffer.appendOutput(this.taskId, { tool: functionName, result: observedResult });
4662
4687
 
4688
+ const isErrorOutcome = isToolErrorResult(result);
4663
4689
  if (codeAction) this.emitEvent({ ...codeAction,
4664
- phase: result?.success === false || typeof result?.error === 'string' ? 'failed' : 'done' });
4690
+ phase: isErrorOutcome ? 'failed' : 'done' });
4665
4691
 
4666
4692
  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'})` }
4693
+ ? { success: !isErrorOutcome, output: result.output || `Image captured: ${result.filename || 'image'} (${result.mimeType || 'image/png'})` }
4668
4694
  : result;
4669
- const isErrorOutcome = result?.success === false || typeof result?.error === 'string';
4670
- const errorMsg = eventResult?.error || (typeof result?.error === 'string' ? result.error : undefined);
4695
+ const rawErrorMsg = nonEmptyErrorText(eventResult) ?? nonEmptyErrorText(result);
4671
4696
  this.emitEvent({
4672
4697
  type: isErrorOutcome ? 'step_error' : 'step_complete',
4673
4698
  tool: functionName,
4674
- ...(isErrorOutcome && errorMsg ? { error: errorMsg } : {}),
4699
+ ...(isErrorOutcome && rawErrorMsg ? { error: rawErrorMsg } : {}),
4675
4700
  result: eventResult,
4676
4701
  toolCallId: toolCall.id
4677
4702
  });
4678
4703
  this.stepsCompleted++;
4679
- if (this._implementationPlanSeeded && result?.success !== false && !result?.error && functionName !== 'update_plan') {
4704
+ if (this._implementationPlanSeeded && !isErrorOutcome && functionName !== 'update_plan') {
4680
4705
  this.advanceImplementationPlanProgress('mutation');
4681
4706
  }
4682
4707
 
@@ -4754,15 +4779,15 @@ You are operating in a text-and-code modality without direct image pixel renderi
4754
4779
  if (!approved) {
4755
4780
  this.stopRequested = true;
4756
4781
  this.emitEvent({ type: 'status', message: 'Task stopped at 100-step circuit breaker checkpoint by user.' });
4757
- break;
4782
+ } else {
4783
+ this.circuitBreakerUnlocked = true;
4784
+ this.emitEvent({ type: 'status', message: `✓ Circuit breaker unlocked! Resuming execution up to ${this.maxSteps} tier budget...` });
4758
4785
  }
4759
- this.circuitBreakerUnlocked = true;
4760
- this.emitEvent({ type: 'status', message: `✓ Circuit breaker unlocked! Resuming execution up to ${this.maxSteps} tier budget...` });
4761
4786
  }
4762
4787
  }
4763
4788
 
4764
4789
  // Sovereign Tier Budget Extension Checkpoint Gate
4765
- if (this.stepsCompleted >= this.maxSteps) {
4790
+ if (this.stepsCompleted >= this.maxSteps && !this.stopRequested) {
4766
4791
  if (this.config.autonomyMode === 'C') {
4767
4792
  this.stopRequested = true;
4768
4793
  this.emitEvent({ type: 'error', message: `Task reached the configured ${this.maxSteps}-step limit without verified completion.` });
@@ -4785,11 +4810,11 @@ You are operating in a text-and-code modality without direct image pixel renderi
4785
4810
  if (!approved) {
4786
4811
  this.stopRequested = true;
4787
4812
  this.emitEvent({ type: 'status', message: `Task stopped at ${this.maxSteps}-step tier limit by user.` });
4788
- break;
4813
+ } else {
4814
+ this.maxSteps += extensionBatch;
4815
+ this.maxCircuitBreaker = this.maxSteps;
4816
+ this.emitEvent({ type: 'status', message: `✓ Tier budget extended (+${extensionBatch} steps unlocked, new limit: ${this.maxSteps}). Resuming task...` });
4789
4817
  }
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
4818
  }
4794
4819
  }
4795
4820
 
@@ -4839,9 +4864,9 @@ You are operating in a text-and-code modality without direct image pixel renderi
4839
4864
  content: `Image successfully captured: ${result.filename || 'image'}. Passing to vision observation.`
4840
4865
  });
4841
4866
 
4842
- // Then push the user observation message containing the image data block
4843
- this.messages.push({
4844
- role: 'user',
4867
+ // Defer user image observation until after every role:'tool' result in this batch.
4868
+ deferredPostBatchMessages.push({
4869
+ role: 'user',
4845
4870
  content: [
4846
4871
  imageContent,
4847
4872
  {
@@ -4874,7 +4899,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4874
4899
  spill = { path: stored.diskPath };
4875
4900
  resultString = JSON.stringify({
4876
4901
  ...(typeof result?.success === 'boolean' ? { success: result.success } : {}),
4877
- ...(typeof result?.error === 'string' ? { error: result.error.slice(0, 500) } : {}),
4902
+ ...spillErrorField(result),
4878
4903
  output: stored.contentForModel
4879
4904
  });
4880
4905
  } else if (document.length > inlineLimit) {
@@ -4908,7 +4933,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4908
4933
  }
4909
4934
  }
4910
4935
 
4911
- const isCallFailed = Boolean(result && (result.success === false || typeof result.error === 'string'));
4936
+ const isCallFailed = isToolErrorResult(result);
4912
4937
  const stallObservation = this.stallGuard.observeCall(
4913
4938
  functionName,
4914
4939
  args || {},
@@ -4933,7 +4958,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4933
4958
  });
4934
4959
 
4935
4960
  if (stallObservation.notice) {
4936
- this.messages.push({
4961
+ deferredPostBatchMessages.push({
4937
4962
  role: 'system',
4938
4963
  content: stallObservation.notice
4939
4964
  });
@@ -4950,8 +4975,15 @@ You are operating in a text-and-code modality without direct image pixel renderi
4950
4975
 
4951
4976
  // Save state continuously after each tool loop
4952
4977
  this.memoryManager.saveHistory(this.messages);
4953
- if (this.stopRequested) break;
4978
+ if (this.stopRequested || this.abortController?.signal?.aborted) break;
4979
+ }
4980
+ if (deferredPostBatchMessages.length > 0) {
4981
+ for (const deferredMsg of deferredPostBatchMessages) {
4982
+ this.messages.push(deferredMsg);
4983
+ }
4984
+ this.memoryManager.saveHistory(this.messages);
4954
4985
  }
4986
+ if (this.stopRequested || this.abortController?.signal?.aborted) break;
4955
4987
 
4956
4988
  } catch (e: any) {
4957
4989
  // Providers sometimes throw strings or plain objects. Normalize once
@@ -5192,7 +5224,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
5192
5224
  const spent = Number(error?.partialUsage?.promptTokens || 0)
5193
5225
  + Number(error?.partialUsage?.completionTokens || 0);
5194
5226
  if (spent > 0) return 'fatal';
5195
- const msg = (error.message || '').toLowerCase();
5227
+ const msg = (typeof error === 'string' ? error : error?.message || '').toLowerCase();
5196
5228
 
5197
5229
  if (error?.name === 'OpenRouterPrivacyConstraintError'
5198
5230
  || msg.includes('matching the privacy policy')
@@ -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 {
@@ -296,6 +296,12 @@ function ensureLaunchShim(resolvedExecutable: string, resourceDirectory: string)
296
296
  return shimExecutable;
297
297
  }
298
298
 
299
+ function isChromiumExecutablePath(filePath: string): boolean {
300
+ return /^(?:google-chrome|google chrome|chrome|chromium-browser|chromium|msedge|microsoft-edge|microsoft edge)(?:-(?:stable|beta|dev|canary))?(?:\.exe)?$/i.test(
301
+ path.basename(filePath)
302
+ );
303
+ }
304
+
299
305
  /** Discover existing installations only. Never downloads or uses a personal profile. */
300
306
  export function resolveChromiumRuntime(configured?: string): PreparedBrowserRuntime | null {
301
307
  const candidates = configured ? [configured] : process.platform === 'darwin'
@@ -315,12 +321,13 @@ export function resolveChromiumRuntime(configured?: string): PreparedBrowserRunt
315
321
  export function resolveBrowserRuntime(): PreparedBrowserRuntime {
316
322
  const configured = process.env.CAUSYNE_BROWSER_EXECUTABLE?.trim()
317
323
  || process.env.CAMOUFOX_EXECUTABLE_PATH?.trim();
318
- const candidates = configured
319
- ? [resolveCandidateExecutablePath(path.resolve(configured))]
324
+ const resolvedConfigured = configured ? path.resolve(configured) : undefined;
325
+ const candidates = resolvedConfigured
326
+ ? [resolveCandidateExecutablePath(resolvedConfigured)]
320
327
  : candidateExecutables().map(resolveCandidateExecutablePath);
321
328
  const executablePath = candidates.find(existsSync);
322
- if (configured && /(?:chrome|chromium|msedge)(?:\.exe)?$/i.test(path.basename(configured))) {
323
- const chromium = resolveChromiumRuntime(configured);
329
+ if (resolvedConfigured && isChromiumExecutablePath(resolvedConfigured)) {
330
+ const chromium = resolveChromiumRuntime(resolvedConfigured);
324
331
  if (chromium) return chromium;
325
332
  }
326
333
  if (!executablePath) {
@@ -377,14 +384,15 @@ export function isBrowserRuntimeInstalled(): boolean {
377
384
  try {
378
385
  const configured = process.env.CAUSYNE_BROWSER_EXECUTABLE?.trim()
379
386
  || process.env.CAMOUFOX_EXECUTABLE_PATH?.trim();
380
- const candidates = configured
381
- ? [resolveCandidateExecutablePath(path.resolve(configured))]
387
+ const resolvedConfigured = configured ? path.resolve(configured) : undefined;
388
+ const candidates = resolvedConfigured
389
+ ? [resolveCandidateExecutablePath(resolvedConfigured)]
382
390
  : candidateExecutables().map(resolveCandidateExecutablePath);
383
391
  // Match launch-time discovery: Chromium is a supported installed runtime
384
392
  // too. The former Camoufox-only check suppressed host verification even
385
393
  // when resolveBrowserRuntime could launch the installed Chrome browser.
386
- if (configured && /(?:chrome|chromium|msedge)(?:\.exe)?$/i.test(path.basename(configured))) {
387
- return resolveChromiumRuntime(path.resolve(configured)) !== null;
394
+ if (resolvedConfigured && isChromiumExecutablePath(resolvedConfigured)) {
395
+ return resolveChromiumRuntime(resolvedConfigured) !== null;
388
396
  }
389
397
  const hasCamoufox = candidates.some(candidate => {
390
398
  try {
@@ -155,6 +155,11 @@ export function validateExtractSchema(schema) {
155
155
  }
156
156
  return { ok: true };
157
157
  }
158
+ function boundedFiniteInteger(value, fallback, min, max) {
159
+ const numeric = typeof value === 'string' && !value.trim() ? Number.NaN : Number(value ?? fallback);
160
+ const base = Number.isFinite(numeric) ? Math.floor(numeric) : fallback;
161
+ return Math.max(min, Math.min(max, base));
162
+ }
158
163
  function coerceSchemaValue(raw, type) {
159
164
  if (raw == null)
160
165
  return null;
@@ -1553,7 +1558,7 @@ export class CausyneBrowser {
1553
1558
  return { action: action.type, tabId: state.id, url: state.page.url(), output: `Pressed ${normalizedKey}` };
1554
1559
  }
1555
1560
  if (action.type === 'scroll') {
1556
- const amount = Math.max(1, Math.min(10_000, Math.floor(action.amount ?? 700)));
1561
+ const amount = boundedFiniteInteger(action.amount, 700, 1, 10_000);
1557
1562
  const direction = action.direction ?? 'down';
1558
1563
  const x = direction === 'left' ? -amount : direction === 'right' ? amount : 0;
1559
1564
  const y = direction === 'up' ? -amount : direction === 'down' ? amount : 0;
@@ -1561,7 +1566,7 @@ export class CausyneBrowser {
1561
1566
  return { action: action.type, tabId: state.id, url: state.page.url(), output: `Scrolled ${direction} ${amount}px` };
1562
1567
  }
1563
1568
  if (action.type === 'wait') {
1564
- const waitTimeout = Math.max(50, Math.min(30_000, Number(action.timeout ?? action.amount ?? 1_000)));
1569
+ const waitTimeout = boundedFiniteInteger(action.timeout ?? action.amount, 1_000, 50, 30_000);
1565
1570
  if (action.selector) {
1566
1571
  const validationErr = selectorValidationError(action.selector);
1567
1572
  if (validationErr)
@@ -177,6 +177,12 @@ export function validateExtractSchema(schema: unknown): { ok: boolean; error?: s
177
177
  return { ok: true };
178
178
  }
179
179
 
180
+ function boundedFiniteInteger(value: unknown, fallback: number, min: number, max: number): number {
181
+ const numeric = typeof value === 'string' && !value.trim() ? Number.NaN : Number(value ?? fallback);
182
+ const base = Number.isFinite(numeric) ? Math.floor(numeric) : fallback;
183
+ return Math.max(min, Math.min(max, base));
184
+ }
185
+
180
186
  function coerceSchemaValue(raw: string | null, type?: string): unknown {
181
187
  if (raw == null) return null;
182
188
  if (type === 'string' || !type) return String(raw).trim();
@@ -1770,7 +1776,7 @@ export class CausyneBrowser {
1770
1776
  return { action: action.type, tabId: state.id, url: state.page.url(), output: `Pressed ${normalizedKey}` };
1771
1777
  }
1772
1778
  if (action.type === 'scroll') {
1773
- const amount = Math.max(1, Math.min(10_000, Math.floor(action.amount ?? 700)));
1779
+ const amount = boundedFiniteInteger(action.amount, 700, 1, 10_000);
1774
1780
  const direction = action.direction ?? 'down';
1775
1781
  const x = direction === 'left' ? -amount : direction === 'right' ? amount : 0;
1776
1782
  const y = direction === 'up' ? -amount : direction === 'down' ? amount : 0;
@@ -1778,7 +1784,7 @@ export class CausyneBrowser {
1778
1784
  return { action: action.type, tabId: state.id, url: state.page.url(), output: `Scrolled ${direction} ${amount}px` };
1779
1785
  }
1780
1786
  if (action.type === 'wait') {
1781
- const waitTimeout = Math.max(50, Math.min(30_000, Number(action.timeout ?? action.amount ?? 1_000)));
1787
+ const waitTimeout = boundedFiniteInteger(action.timeout ?? action.amount, 1_000, 50, 30_000);
1782
1788
  if (action.selector) {
1783
1789
  const validationErr = selectorValidationError(action.selector);
1784
1790
  if (validationErr) throw new Error(validationErr);
@@ -1,14 +1,20 @@
1
+ import { isIP } from 'node:net';
2
+ import { isPrivateAddress } from './urlPolicy.js';
1
3
  const MAX_PROVIDER_BYTES = 2 * 1024 * 1024;
2
4
  const MAX_RESULTS = 10;
3
5
  const SEARCH_TIMEOUT_MS = 15_000;
4
6
  function decodeEntities(value) {
5
7
  const named = { amp: '&', apos: "'", gt: '>', lt: '<', nbsp: ' ', quot: '"' };
6
8
  return value.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (full, entity) => {
7
- if (entity.startsWith('#x'))
8
- return String.fromCodePoint(Number.parseInt(entity.slice(2), 16));
9
- if (entity.startsWith('#'))
10
- return String.fromCodePoint(Number.parseInt(entity.slice(1), 10));
11
- return named[entity.toLowerCase()] ?? full;
9
+ const normalized = entity.toLowerCase();
10
+ if (normalized.startsWith('#')) {
11
+ const point = normalized.startsWith('#x')
12
+ ? Number.parseInt(normalized.slice(2), 16)
13
+ : Number.parseInt(normalized.slice(1), 10);
14
+ return Number.isInteger(point) && point > 0 && point <= 0x10ffff && !(point >= 0xd800 && point <= 0xdfff)
15
+ ? String.fromCodePoint(point) : full;
16
+ }
17
+ return named[normalized] ?? full;
12
18
  });
13
19
  }
14
20
  function cleanMarkup(value) {
@@ -21,6 +27,11 @@ function publicResultUrl(value) {
21
27
  const parsed = new URL(decodeEntities(value));
22
28
  if (!['http:', 'https:'].includes(parsed.protocol))
23
29
  return null;
30
+ const host = parsed.hostname.toLowerCase().replace(/^\[|\]$/g, '').replace(/\.$/, '');
31
+ if (parsed.username || parsed.password || host === 'localhost' ||
32
+ host.endsWith('.localhost') || host.endsWith('.local') || host.endsWith('.internal') ||
33
+ (isIP(host) !== 0 && isPrivateAddress(host)))
34
+ return null;
24
35
  if (/(^|\.)(bing|duckduckgo)\.com$/i.test(parsed.hostname))
25
36
  return null;
26
37
  return parsed.href;
@@ -49,7 +60,7 @@ export function parseBingRss(xml) {
49
60
  export function parseDuckDuckGoHtml(html) {
50
61
  const results = [];
51
62
  const seen = new Set();
52
- const anchors = [...html.matchAll(/<a\b[^>]*class=["'][^"']*result__a[^"']*["'][^>]*href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi)];
63
+ const anchors = [...html.matchAll(/<a\b(?=[^>]*\bclass=["'][^"']*\bresult__a\b[^"']*["'])[^>]*\bhref=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi)];
53
64
  for (const [index, anchor] of anchors.entries()) {
54
65
  let href = decodeEntities(anchor[1] ?? '');
55
66
  try {
@@ -108,7 +119,7 @@ export async function searchPublicWeb(query, options = {}) {
108
119
  const fetchImpl = options.fetchImpl ?? fetch;
109
120
  const controller = new AbortController();
110
121
  const timeout = setTimeout(() => controller.abort(), SEARCH_TIMEOUT_MS);
111
- const signal = options.signal ?? controller.signal;
122
+ const signal = options.signal ? AbortSignal.any([controller.signal, options.signal]) : controller.signal;
112
123
  const providers = [
113
124
  {
114
125
  engine: 'duckduckgo-html',
@@ -1,3 +1,5 @@
1
+ import { isIP } from 'node:net';
2
+ import { isPrivateAddress } from './urlPolicy.js';
1
3
  const MAX_PROVIDER_BYTES = 2 * 1024 * 1024;
2
4
  const MAX_RESULTS = 10;
3
5
  const SEARCH_TIMEOUT_MS = 15_000;
@@ -17,9 +19,15 @@ interface SearchOptions {
17
19
  function decodeEntities(value: string): string {
18
20
  const named: Record<string, string> = { amp: '&', apos: "'", gt: '>', lt: '<', nbsp: ' ', quot: '"' };
19
21
  return value.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (full, entity: string) => {
20
- if (entity.startsWith('#x')) return String.fromCodePoint(Number.parseInt(entity.slice(2), 16));
21
- if (entity.startsWith('#')) return String.fromCodePoint(Number.parseInt(entity.slice(1), 10));
22
- return named[entity.toLowerCase()] ?? full;
22
+ const normalized = entity.toLowerCase();
23
+ if (normalized.startsWith('#')) {
24
+ const point = normalized.startsWith('#x')
25
+ ? Number.parseInt(normalized.slice(2), 16)
26
+ : Number.parseInt(normalized.slice(1), 10);
27
+ return Number.isInteger(point) && point > 0 && point <= 0x10ffff && !(point >= 0xd800 && point <= 0xdfff)
28
+ ? String.fromCodePoint(point) : full;
29
+ }
30
+ return named[normalized] ?? full;
23
31
  });
24
32
  }
25
33
 
@@ -33,6 +41,10 @@ function publicResultUrl(value: string): string | null {
33
41
  try {
34
42
  const parsed = new URL(decodeEntities(value));
35
43
  if (!['http:', 'https:'].includes(parsed.protocol)) return null;
44
+ const host = parsed.hostname.toLowerCase().replace(/^\[|\]$/g, '').replace(/\.$/, '');
45
+ if (parsed.username || parsed.password || host === 'localhost' ||
46
+ host.endsWith('.localhost') || host.endsWith('.local') || host.endsWith('.internal') ||
47
+ (isIP(host) !== 0 && isPrivateAddress(host))) return null;
36
48
  if (/(^|\.)(bing|duckduckgo)\.com$/i.test(parsed.hostname)) return null;
37
49
  return parsed.href;
38
50
  } catch {
@@ -59,7 +71,7 @@ export function parseBingRss(xml: string): SearchResult[] {
59
71
  export function parseDuckDuckGoHtml(html: string): SearchResult[] {
60
72
  const results: SearchResult[] = [];
61
73
  const seen = new Set<string>();
62
- const anchors = [...html.matchAll(/<a\b[^>]*class=["'][^"']*result__a[^"']*["'][^>]*href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi)];
74
+ const anchors = [...html.matchAll(/<a\b(?=[^>]*\bclass=["'][^"']*\bresult__a\b[^"']*["'])[^>]*\bhref=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi)];
63
75
  for (const [index, anchor] of anchors.entries()) {
64
76
  let href = decodeEntities(anchor[1] ?? '');
65
77
  try {
@@ -112,7 +124,7 @@ export async function searchPublicWeb(query: string, options: SearchOptions = {}
112
124
  const fetchImpl = options.fetchImpl ?? fetch;
113
125
  const controller = new AbortController();
114
126
  const timeout = setTimeout(() => controller.abort(), SEARCH_TIMEOUT_MS);
115
- const signal = options.signal ?? controller.signal;
127
+ const signal = options.signal ? AbortSignal.any([controller.signal, options.signal]) : controller.signal;
116
128
  const providers = [
117
129
  {
118
130
  engine: 'duckduckgo-html',
@@ -10,7 +10,7 @@ export function windowSnapshot(snapshot, requestedOffset = 0) {
10
10
  }
11
11
  const contentBudget = MAX_SNAPSHOT_CHARS - SNAPSHOT_TAIL_CHARS - 240;
12
12
  const maximumOffset = Math.max(0, totalChars - SNAPSHOT_TAIL_CHARS);
13
- const offset = Math.min(Math.max(0, Math.floor(requestedOffset)), maximumOffset);
13
+ const offset = Math.min(Math.max(0, Number.isFinite(requestedOffset) ? Math.floor(requestedOffset) : 0), maximumOffset);
14
14
  const chunkEnd = Math.min(offset + contentBudget, maximumOffset);
15
15
  const hasMore = chunkEnd < maximumOffset;
16
16
  const tail = text.slice(-SNAPSHOT_TAIL_CHARS);
@@ -22,7 +22,7 @@ export function windowSnapshot(snapshot: string, requestedOffset = 0): SnapshotW
22
22
 
23
23
  const contentBudget = MAX_SNAPSHOT_CHARS - SNAPSHOT_TAIL_CHARS - 240;
24
24
  const maximumOffset = Math.max(0, totalChars - SNAPSHOT_TAIL_CHARS);
25
- const offset = Math.min(Math.max(0, Math.floor(requestedOffset)), maximumOffset);
25
+ const offset = Math.min(Math.max(0, Number.isFinite(requestedOffset) ? Math.floor(requestedOffset) : 0), maximumOffset);
26
26
  const chunkEnd = Math.min(offset + contentBudget, maximumOffset);
27
27
  const hasMore = chunkEnd < maximumOffset;
28
28
  const tail = text.slice(-SNAPSHOT_TAIL_CHARS);