@causyne/agent 1.20.9 → 1.20.11

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 (47) hide show
  1. package/package.json +2 -1
  2. package/src/agentLoop.js +127 -72
  3. package/src/agentLoop.ts +137 -75
  4. package/src/browser/causyneBrowser.js +36 -0
  5. package/src/browser/causyneBrowser.ts +36 -1
  6. package/src/commands.js +25 -0
  7. package/src/contextManager.js +16 -0
  8. package/src/providers/antigravity.js +63 -11
  9. package/src/providers/antigravity.ts +62 -12
  10. package/src/provisioning/capabilityProvisioner.js +2 -7
  11. package/src/provisioning/npmInstall.js +19 -0
  12. package/src/provisioning/npmInstall.ts +19 -0
  13. package/src/smartToolsUse.js +20 -0
  14. package/src/smartToolsUse.ts +21 -0
  15. package/src/stallGuard.js +347 -0
  16. package/src/stallGuard.ts +423 -0
  17. package/src/tools/browserAutomator.js +3 -3
  18. package/src/tools/browserAutomator.ts +3 -3
  19. package/src/tools/fsRead.js +91 -80
  20. package/src/tools/fsRead.ts +125 -0
  21. package/src/tools/peerAgent.js +1 -1
  22. package/src/tools/peerAgent.ts +1 -1
  23. package/src/tools/screenshot.js +5 -1
  24. package/src/tools/screenshot.ts +5 -1
  25. package/src/tools/toolScanner.js +19 -0
  26. package/src/tools/toolScanner.ts +17 -0
  27. package/src/tools/toolSelfRepair.js +63 -1
  28. package/src/tools/toolSelfRepair.ts +61 -1
  29. package/src/tools/visionInspector.js +80 -142
  30. package/src/tools/visionInspector.ts +110 -0
  31. package/src/tui/chatboxClipboard.js +152 -0
  32. package/src/tui/chatboxClipboard.ts +201 -0
  33. package/src/tui/clipboardSync.js +38 -7
  34. package/src/tui/clipboardSync.ts +39 -7
  35. package/src/tui/codeProgress.js +89 -18
  36. package/src/tui/codeProgress.ts +102 -17
  37. package/src/tui/codeStreamRenderer.js +7 -2
  38. package/src/tui/codeStreamRenderer.ts +7 -2
  39. package/src/tui/composerControls.js +9 -0
  40. package/src/tui/composerControls.ts +9 -0
  41. package/src/tui/dialogs.js +8 -3
  42. package/src/tui/diff.d.ts +1 -0
  43. package/src/tui/lineEditor.js +166 -14
  44. package/src/tui/mouseHover.js +6 -2
  45. package/src/tui/mouseHover.ts +7 -2
  46. package/src/tui/prompt.js +96 -19
  47. package/src/tui/stageSurface.js +3 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@causyne/agent",
3
- "version": "1.20.9",
3
+ "version": "1.20.11",
4
4
  "description": "Agentic AI for software, tools, and computer workflows",
5
5
  "main": "bin/causyne.js",
6
6
  "type": "module",
@@ -21,6 +21,7 @@
21
21
  "docs/THIRD_PARTY_NOTICES.md"
22
22
  ],
23
23
  "scripts": {
24
+ "prestart": "npm run build",
24
25
  "start": "node ./bin/causyne.js",
25
26
  "test": "node --test --import ./tests/helpers/isolateState.js \"tests/**/*.test.{js,ts}\"",
26
27
  "build": "node scripts/compile_skills.js && tsc -p tsconfig.runtime.json",
package/src/agentLoop.js CHANGED
@@ -43,6 +43,7 @@ import { createProvider } from './providers/factory.js';
43
43
  import { resolveMentionedContext } from './promptMentions.js';
44
44
  import { isLaunchOnlyPrompt, launchScopeError } from './launchIntent.js';
45
45
  import { StreamingCodePreview, NativeCodeObserver, codeProgressFromAction } from './tui/codeProgress.js';
46
+ import { StallGuardController } from './stallGuard.js';
46
47
  export function isActionableTaskPrompt(text) {
47
48
  const t = (text || '').trim();
48
49
  if (!t)
@@ -475,6 +476,7 @@ export class AgentLoop {
475
476
  this.consecutiveBlockedActions = 0; // V8 Transcendence: Circuit Breaker
476
477
  this.recentActionSignatures = [];
477
478
  this.consecutiveReadOnlySteps = 0;
479
+ this.stallGuard = new StallGuardController();
478
480
  // Sovereign Progressive Disclosure: which capability packs have entered the
479
481
  // context window for this task. Nothing is disabled — see src/toolPacks.js.
480
482
  this.unlockedPacks = new Set();
@@ -1272,7 +1274,9 @@ export class AgentLoop {
1272
1274
  this.circuitBreakerUnlocked = false;
1273
1275
  this.recentActionSignatures = [];
1274
1276
  this.consecutiveReadOnlySteps = 0;
1277
+ this.stallGuard.reset();
1275
1278
  this.tokenTracker.resetTask();
1279
+ let mediaExplorationRecoveries = 0;
1276
1280
  // The core loop governed by Sovereign Human-in-the-Loop Checkpoints
1277
1281
  while (!this.stopRequested) {
1278
1282
  if (this.stopRequested) {
@@ -1289,9 +1293,12 @@ export class AgentLoop {
1289
1293
  const activeTier = isDevEmulator(this.config) ? 'super_max' : (this.config.tier || 'premium');
1290
1294
  const MAX_CHAR_POOL = resolveCharPool(activeTier, this.config.maxCharPool);
1291
1295
  // 5-Stage Progressive Compaction (Claude Code Architecture / Research Section E):
1292
- // Stage 2 (Snip >15K tokens / 60K chars) + Stage 1 (Budget Reduction >70%) +
1293
- // Stage 3 (Microcompact) + Stage 4 (Context Collapse >85%)
1296
+ // Stage 0 (HLCE Ephemeral Decay) + Stage 2 (Snip >15K tokens / 60K chars) +
1297
+ // Stage 1 (Budget Reduction >70%) + Stage 3 (Microcompact) + Stage 4 (Context Collapse >85%)
1294
1298
  const compaction = applyProgressiveCompaction(this.messages, MAX_CHAR_POOL, {
1299
+ enableEphemeralDecay: true,
1300
+ ephemeralKeepRecent: 3,
1301
+ ephemeralMinChars: 1200,
1295
1302
  budgetKeepRecent: this.config.keepRecentToolResults ?? 8,
1296
1303
  collapseKeepRecent: 2
1297
1304
  });
@@ -1622,6 +1629,7 @@ export class AgentLoop {
1622
1629
  taskIntent: isLaunchOnlyPrompt(this.currentTaskPrompt || this.userPrompt || '') ? 'launch' : 'general',
1623
1630
  taskArchetype: determineToolScope(this.currentTaskPrompt || this.userPrompt || '', this.taskShape).archetype,
1624
1631
  maxTokensThisCall: Number.isFinite(remainingBudget) ? remainingBudget : undefined,
1632
+ tokenLimit: Number.isFinite(remainingBudget) ? remainingBudget : Infinity,
1625
1633
  workspaceRoot: this.workspaceRoot,
1626
1634
  tools: dynamicTools,
1627
1635
  // IARS couples escalation to a wider search. Bounded so a stuck task
@@ -1803,9 +1811,11 @@ export class AgentLoop {
1803
1811
  if (['write_file', 'write_to_file', 'edit_file', 'replace_file_content', 'multi_replace_file_content', 'fs_write', 'fs_edit', 'multiedit'].includes(actionName) && detailPath) {
1804
1812
  this.recordWebArtifact(detailPath);
1805
1813
  }
1806
- if (['capture_browser_screenshot', 'browser_subagent', 'open_browser_url', 'browser_get_dom', 'read_browser_page'].includes(actionName) ||
1807
- ((actionName === 'read_file' || actionName === 'view_file') && /\.(png|jpe?g|webp|gif|svg)$/i.test(detailPath))) {
1808
- this.webVerificationState.screenshotTaken = true;
1814
+ // A native action's name is not evidence that a model inspected
1815
+ // pixels. Keep visual verification false unless a real image result
1816
+ // has reached a vision-capable provider.
1817
+ if (['browser_get_dom', 'read_browser_page'].includes(actionName)) {
1818
+ this.webVerificationState.browserActUsed = true;
1809
1819
  }
1810
1820
  }
1811
1821
  }
@@ -2024,26 +2034,40 @@ export class AgentLoop {
2024
2034
  let visionDeclined = false;
2025
2035
  let browserReady = false;
2026
2036
  let browserDeclined = false;
2037
+ let browserRuntimeError = '';
2027
2038
  try {
2028
2039
  const { groupStatus, isGroupDeclined } = await import('./provisioning/capabilityProvisioner.js');
2029
2040
  visionReady = groupStatus('vision').state === 'ready';
2030
2041
  visionDeclined = isGroupDeclined('vision');
2031
2042
  browserReady = groupStatus('browser').state === 'ready';
2032
2043
  browserDeclined = isGroupDeclined('browser');
2044
+ if (browserReady) {
2045
+ const { resolveBrowserRuntime } = await import('./browser/browserRuntime.js');
2046
+ try {
2047
+ resolveBrowserRuntime();
2048
+ }
2049
+ catch (error) {
2050
+ browserReady = false;
2051
+ browserRuntimeError = error instanceof Error ? error.message : String(error);
2052
+ }
2053
+ }
2033
2054
  }
2034
2055
  catch (e) { /* treat as not ready */ }
2035
2056
  let webGuardMsg = '';
2036
- if (!browserReady && !browserDeclined) {
2057
+ if (browserRuntimeError) {
2058
+ webGuardMsg = `[WEB CHECK: The browser capability is granted, but its runtime cannot launch: ${browserRuntimeError} Do not request the same grant again or claim a rendered-page check. Inspect the source and report the runtime blocker. This check fires once.]`;
2059
+ }
2060
+ else if (!browserReady && !browserDeclined) {
2037
2061
  webGuardMsg = `[ANTI-SLOP CHECK: You are building a Web/UI project and must inspect it before finishing, but the dedicated browser capability is not enabled yet. Call \`manage_local_dependencies\` with action "grant_capability" and group "browser" to request the Causyne Browser runtime. If the user declines, read the final compiled HTML/CSS instead. This check fires once.]`;
2038
2062
  }
2039
2063
  else if (hasVision && !visionReady && !visionDeclined) {
2040
2064
  webGuardMsg = `[ANTI-SLOP CHECK: The browser is available, but desktop screen capture is not enabled. Call \`manage_local_dependencies\` with action "grant_capability" and group "vision" to request it, or use \`browser_act\` snapshots and its workspace-scoped screenshot action. This check fires once.]`;
2041
2065
  }
2042
2066
  else if (hasVision && visionReady && !this.webVerificationState.screenshotTaken) {
2043
- webGuardMsg = `[ANTI-SLOP CHECK: You are building a Web/UI project but attempted to finish without VISUALLY verifying your work. Use \`screenshot\` or \`vision_inspect_ui\` to look at the UI in a browser. A human looks at their work to avoid slop. This check fires once — if there is genuinely nothing visual to inspect, say so plainly and finish.]`;
2067
+ webGuardMsg = `[ANTI-SLOP CHECK: You are building a Web/UI project but attempted to finish without VISUALLY verifying your work. Use \`screenshot\` or \`vision_inspect_ui\` to look at the UI in a browser. A saved file is not evidence that the model saw the image. If capture fails, report that visual verification was not completed. This check fires once.]`;
2044
2068
  }
2045
2069
  else if ((!hasVision || visionDeclined) && browserReady && !this.webVerificationState.browserActUsed && !this.webVerificationState.screenshotTaken) {
2046
- webGuardMsg = `[TRANSCENDENCE CHECK: You are building a Web/UI project. As a vision-disabled model you cannot screenshot, but you MUST use \`browser_act\` to inspect the DOM, or read the final compiled HTML/CSS, to verify semantic correctness before finishing. This check fires once.]`;
2070
+ webGuardMsg = `[WEB CHECK: You are building a Web/UI project. Use \`browser_act\` with preview and a workspace-relative HTML filePath, then snapshot to inspect the rendered DOM. A screenshot file by itself is not visual inspection. If browser access fails, read the final HTML/CSS and report that visual verification was not completed. This check fires once.]`;
2047
2071
  }
2048
2072
  if (webGuardMsg) {
2049
2073
  this.webGuardFired = true;
@@ -2058,6 +2082,20 @@ export class AgentLoop {
2058
2082
  }
2059
2083
  }
2060
2084
  }
2085
+ // Tool availability and a completed plan are not evidence of visual
2086
+ // inspection. A failed browser/capture attempt must not become a
2087
+ // successful task merely because the provider says "verified".
2088
+ if (isWebTask && this.stepsCompleted > 0
2089
+ && !this.webVerificationState.browserActUsed
2090
+ && !this.webVerificationState.screenshotTaken) {
2091
+ this.emitEvent({
2092
+ type: 'error',
2093
+ message: 'The web files may have changed, but rendered-page verification did not succeed. The task remains unverified; no completion is recorded.'
2094
+ });
2095
+ auditLog.log({ event: 'task_unverified', taskId: this.taskId, reason: 'web_render_not_inspected' });
2096
+ this.memoryManager.saveHistory(this.messages);
2097
+ break;
2098
+ }
2061
2099
  // Cold Observer: Overconfidence & Loop Verification Check
2062
2100
  {
2063
2101
  try {
@@ -2230,69 +2268,39 @@ export class AgentLoop {
2230
2268
  if (this.recentActionSignatures.length > 20) {
2231
2269
  this.recentActionSignatures.shift();
2232
2270
  }
2233
- const isCommandTool = ['sysRun', 'sysRunBg', 'terminal_persistent_shell'].includes(functionName);
2234
- if (isCommandTool) {
2235
- const duplicateCount = this.recentActionSignatures.filter((sig) => sig === actionSig).length;
2236
- // 1. Hard Circuit Breaker on Duplicate Command Thrashing (same command attempted 4 times total)
2237
- if (duplicateCount >= 4) {
2238
- const fatalMsg = `FATAL ERROR: Infinite Token Drain Detected. Agent repeatedly attempted identical command '${functionName}' (${actionSig}) 4 times without making progress. Forcibly aborting task to save tokens.`;
2239
- this.emitEvent({ type: 'step_error', tool: functionName, error: fatalMsg, toolCallId: toolCall.id });
2240
- auditLog.log({ event: 'task_killed_circuit_breaker', taskId: this.taskId, reason: fatalMsg });
2241
- this.abort();
2242
- break;
2243
- }
2244
- // 2. Block 3rd attempt of identical command and inject a non-negotiable recovery mandate
2245
- if (duplicateCount === 3) {
2246
- const isExec = isExecutionOrLaunchTaskPrompt(this.currentTaskPrompt || this.userPrompt || '');
2247
- const isAuthoring = !isExec && isCodeAuthoringTaskPrompt(this.currentTaskPrompt || this.userPrompt || '');
2248
- let blockMsg;
2249
- if (actionSig === 'sysRun:probe:process_or_port' || isExec) {
2250
- blockMsg = `REPETITION BLOCKED: You have already checked processes/ports. The result is already in your context above. You are STRICTLY FORBIDDEN from running process/port checks again. Proceed immediately to fulfilling the user's request: start the server (if port 8080 is occupied, start on port 8081 or 8088 using sysRunBg) and open the URL in the browser.`;
2251
- }
2252
- else if (isAuthoring) {
2253
- blockMsg = `REPETITION BLOCKED: You have already executed this identical command '${functionName}' 2 times. The result is already in your context above. You are STRICTLY FORBIDDEN from running this action again. You must immediately proceed to creating or editing the solution files using fs_write.`;
2254
- }
2255
- else {
2256
- blockMsg = `REPETITION BLOCKED: You have already executed this identical command '${functionName}' 2 times. The result is already in your context above. You are STRICTLY FORBIDDEN from running this action again. Proceed immediately to fulfilling the user's request: if starting a service or server, launch it (if a port is occupied, use an alternate open port); if launching an app, open it in the browser; if done, summarize and finish.`;
2257
- }
2258
- this.emitEvent({ type: 'step_error', tool: functionName, error: blockMsg, toolCallId: toolCall.id });
2259
- this.messages.push({
2260
- role: 'tool',
2261
- tool_call_id: toolCall.id,
2262
- name: functionName,
2263
- content: JSON.stringify({
2264
- success: false,
2265
- error: 'DUPLICATE_ACTION_BLOCKED',
2266
- CRITICAL_INSTRUCTION: blockMsg
2267
- })
2268
- });
2269
- continue;
2270
- }
2271
- }
2272
- // 3. Track Read-Only Inspection Chains on Code Authoring Tasks (Max 6 inspection steps)
2273
- const isMutatingAction = ['fs_write', 'fs_edit', 'MultiEdit', 'game_build_html5'].includes(functionName)
2274
- || (functionName === 'sysRun' && /(npm\s+(i|install|add)|pnpm\s+add|yarn\s+add|pip\s+install|git\s+commit)\b/.test(args?.command || ''));
2275
- if (isMutatingAction) {
2276
- this.consecutiveReadOnlySteps = 0;
2277
- }
2278
- else if (['sysRun', 'sysRunBg', 'fs_read', 'fs_list', 'dir_list', 'grep_search'].includes(functionName)) {
2279
- this.consecutiveReadOnlySteps = (Number(this.consecutiveReadOnlySteps) || 0) + 1;
2280
- }
2271
+ // Universal Intelligent Loop Guard & Stall Breaker (Hermes / Claude Code architecture)
2281
2272
  const isExecTask = isExecutionOrLaunchTaskPrompt(this.currentTaskPrompt || this.userPrompt || '');
2282
2273
  const isAuthoringTask = !isExecTask && isCodeAuthoringTaskPrompt(this.currentTaskPrompt || this.userPrompt || '');
2283
- if (isAuthoringTask && this.consecutiveReadOnlySteps === 4) {
2274
+ const guardDecision = this.stallGuard.beforeCall(functionName, args || {}, {
2275
+ isAuthoringTask
2276
+ });
2277
+ if (guardDecision.action === 'block') {
2278
+ this.emitEvent({ type: 'step_error', tool: functionName, error: guardDecision.message, toolCallId: toolCall.id });
2279
+ auditLog.log({ event: 'tool_blocked', taskId: this.taskId, tool: functionName, args, reason: guardDecision.message });
2284
2280
  this.messages.push({
2285
- role: 'system',
2286
- content: `[CRITICAL ACTION MANDATE: You have performed 4 consecutive inspection steps without writing code. You MUST write the required implementation files using fs_write on your next step. Any further read-only commands will be rejected.]`
2281
+ role: 'tool',
2282
+ tool_call_id: toolCall.id,
2283
+ name: functionName,
2284
+ content: JSON.stringify({
2285
+ success: false,
2286
+ error: guardDecision.code,
2287
+ CRITICAL_INSTRUCTION: guardDecision.message
2288
+ })
2287
2289
  });
2290
+ continue;
2288
2291
  }
2289
- if (isAuthoringTask && this.consecutiveReadOnlySteps >= 6) {
2290
- const fatalMsg = `FATAL ERROR: Read-Only Verification Loop Detected. Agent performed 6 consecutive inspection steps without writing any implementation code. Forcibly aborting task to save your token budget.`;
2291
- this.emitEvent({ type: 'step_error', tool: functionName, error: fatalMsg, toolCallId: toolCall.id });
2292
- auditLog.log({ event: 'task_killed_circuit_breaker', taskId: this.taskId, reason: fatalMsg });
2292
+ if (guardDecision.action === 'halt') {
2293
+ this.emitEvent({ type: 'step_error', tool: functionName, error: guardDecision.message, toolCallId: toolCall.id });
2294
+ auditLog.log({ event: 'task_killed_circuit_breaker', taskId: this.taskId, reason: guardDecision.message });
2293
2295
  this.abort();
2294
2296
  break;
2295
2297
  }
2298
+ if (isAuthoringTask && this.stallGuard.distinctInspectionCount === 12) {
2299
+ this.messages.push({
2300
+ role: 'system',
2301
+ content: `[CRITICAL ACTION MANDATE: You have performed 12 consecutive inspection steps without writing code. If you have gathered sufficient context, proceed to creating or editing implementation files using fs_write/fs_edit.]`
2302
+ });
2303
+ }
2296
2304
  this.emitEvent({ type: 'step_start', tool: functionName, args: args, toolCallId: toolCall.id });
2297
2305
  const codeAction = codeProgressFromAction(functionName, args || {}, toolCall.id);
2298
2306
  if (codeAction)
@@ -2597,6 +2605,7 @@ export class AgentLoop {
2597
2605
  name: functionName, content: JSON.stringify({ ...failure,
2598
2606
  errorType, timeMachine: recovery.guidance,
2599
2607
  ...(alternativeRoute ? { apcReplanAlternative: alternativeRoute.suggestedTool, apcReplanReason: alternativeRoute.reason } : {}) }) });
2608
+ this.stallGuard.observeCall(functionName, args || {}, failure, toolCall.id, true);
2600
2609
  this.memoryManager.saveHistory(this.messages);
2601
2610
  if (errorType === 'fatal' || recovery.kind === 'stop' || recovery.kind === 'human') {
2602
2611
  this.stopRequested = true;
@@ -2627,13 +2636,13 @@ export class AgentLoop {
2627
2636
  if (result && result.success !== false && !result.error && ['fs_write', 'fs_edit', 'MultiEdit'].includes(functionName)) {
2628
2637
  this.recordWebArtifact(args.path || args.file_path);
2629
2638
  }
2630
- if (functionName === 'screenshot' && result?.success === true && result?._is_image_marker === true) {
2639
+ if (['screenshot', 'vision_inspect_ui'].includes(functionName) && this.llm.supportsVision !== false && result?.success === true && result?._is_image_marker === true) {
2631
2640
  this.webVerificationState.screenshotTaken = true;
2632
2641
  }
2633
2642
  if (functionName === 'browser_act' && result?.success === true) {
2634
- this.webVerificationState.browserActUsed = true;
2635
- if (Array.isArray(args?.actions) && args.actions.some((action) => action?.type === 'screenshot')) {
2636
- this.webVerificationState.screenshotTaken = true;
2643
+ const browserResults = Array.isArray(result.data) ? result.data : [];
2644
+ if (browserResults.some((item) => ['snapshot', 'scrape'].includes(item?.action))) {
2645
+ this.webVerificationState.browserActUsed = true;
2637
2646
  }
2638
2647
  }
2639
2648
  // The journal is the observer's own record of what actually ran. It
@@ -2793,7 +2802,7 @@ export class AgentLoop {
2793
2802
  role: 'tool',
2794
2803
  tool_call_id: toolCall.id,
2795
2804
  name: functionName,
2796
- content: `[Image observed: ${result.filename || 'image'} (${result.mimeType || 'image/png'}) - verified on disk. Vision observation payload passed.]`
2805
+ content: `[Image captured: ${result.filename || 'image'} (${result.mimeType || 'image/png'}). This provider cannot receive image pixels; visual inspection was not completed.]`
2797
2806
  });
2798
2807
  }
2799
2808
  else {
@@ -2923,6 +2932,11 @@ export class AgentLoop {
2923
2932
  this._observationDigests.set(digest, this.stepsCompleted + 1);
2924
2933
  }
2925
2934
  }
2935
+ const isCallFailed = Boolean(result && (result.success === false || typeof result.error === 'string'));
2936
+ const stallObservation = this.stallGuard.observeCall(functionName, args || {}, result, toolCall.id, isCallFailed);
2937
+ if (stallObservation.stub && resultString.length >= 256) {
2938
+ resultString = stallObservation.stub;
2939
+ }
2926
2940
  this.messages.push({
2927
2941
  role: 'tool',
2928
2942
  tool_call_id: toolCall.id,
@@ -2933,6 +2947,19 @@ export class AgentLoop {
2933
2947
  // stub keep pointing at the spill after the payload is gone.
2934
2948
  ...(spill ? { spillPath: spill.path } : {})
2935
2949
  });
2950
+ if (stallObservation.notice) {
2951
+ this.messages.push({
2952
+ role: 'system',
2953
+ content: stallObservation.notice
2954
+ });
2955
+ }
2956
+ if (stallObservation.decision?.action === 'halt') {
2957
+ const fatalMsg = stallObservation.decision.message;
2958
+ this.emitEvent({ type: 'step_error', tool: functionName, error: fatalMsg, toolCallId: toolCall.id });
2959
+ auditLog.log({ event: 'task_killed_circuit_breaker', taskId: this.taskId, reason: fatalMsg });
2960
+ this.abort();
2961
+ break;
2962
+ }
2936
2963
  }
2937
2964
  // Save state continuously after each tool loop
2938
2965
  this.memoryManager.saveHistory(this.messages);
@@ -2941,9 +2968,12 @@ export class AgentLoop {
2941
2968
  }
2942
2969
  }
2943
2970
  catch (e) {
2944
- if (e?.code === 'AGY_TOKEN_BUDGET') {
2971
+ // A peer can fail after completing billable steps. Charge those steps
2972
+ // once even when no final result was returned, including action and
2973
+ // wall-clock limits, before deciding whether recovery is possible.
2974
+ if (e?.partialUsage) {
2945
2975
  const usage = e.partialUsage;
2946
- if (usage) {
2976
+ if (usage.promptTokens + usage.completionTokens > 0) {
2947
2977
  await this.tokenTracker.trackUsage(usage.promptTokens, usage.completionTokens, (message) => this.emitEvent({ type: 'budget_warning', message }), usage);
2948
2978
  auditLog.log({
2949
2979
  event: 'model_usage', scope: 'agent_loop_primary', taskId: this.taskId,
@@ -2953,9 +2983,26 @@ export class AgentLoop {
2953
2983
  measurement: 'provider_reported_partial', costBasis: 'external_subscription_unavailable'
2954
2984
  });
2955
2985
  }
2986
+ }
2987
+ if (e?.code === 'AGY_TOKEN_BUDGET' || e?.code === 'TASK_TOKEN_BUDGET' || e?.code === 'PROVIDER_TOKEN_BUDGET') {
2956
2988
  this.emitEvent({ type: 'budget_warning', message: e.message });
2957
2989
  auditLog.log({ event: 'task_stopped_on_budget', taskId: this.taskId,
2958
- used: this.tokenTracker.taskTokens, limit: this.tokenTracker.budget?.maxTokensPerTask || 0 });
2990
+ used: this.tokenTracker.taskTokens, limit: e.tokenLimit || this.tokenTracker.budget?.maxTokensPerTask || 0 });
2991
+ break;
2992
+ }
2993
+ if (e?.code === 'AGY_EXPLORATION_LOOP' || e?.code === 'AGENT_EXPLORATION_LOOP' || e?.code === 'STALL_EXPLORATION_LOOP') {
2994
+ auditLog.log({ event: 'media_exploration_checkpoint', taskId: this.taskId,
2995
+ inspectionCount: e.inspectionCount, recovery: mediaExplorationRecoveries });
2996
+ if (mediaExplorationRecoveries++ === 0) {
2997
+ this.messages.push({ role: 'system', content: '[TASK RECOVERY] Consecutive read-only inspections without workspace changes were paused. ' +
2998
+ 'The user requested a concrete change. Reuse the observations already gathered; do not repeat probes. ' +
2999
+ 'Make one targeted workspace edit now, then run one focused verification. ' +
3000
+ 'If editing is blocked, report the exact blocker. Do not claim completion from inspection alone.' });
3001
+ this.memoryManager.saveHistory(this.messages);
3002
+ this.emitEvent({ type: 'notice', message: 'Repeated inspection paused; continuing once with a direct edit instruction.' });
3003
+ continue;
3004
+ }
3005
+ this.emitEvent({ type: 'error', message: 'The provider continued read-only inspection after a corrective checkpoint. The task remains unfinished; no edit was verified.' });
2959
3006
  break;
2960
3007
  }
2961
3008
  if (this.stopRequested || this.abortController?.signal?.aborted || e?.name === 'AbortError') {
@@ -3062,7 +3109,15 @@ export class AgentLoop {
3062
3109
  }
3063
3110
  // V5: Classify errors for intelligent retry decisions
3064
3111
  classifyError(error) {
3065
- if (error?.code === 'AGY_NATIVE_ACTION_DENIED')
3112
+ if (error?.code === 'AGY_NATIVE_ACTION_DENIED'
3113
+ || error?.code === 'AGY_NATIVE_ACTION_BUDGET'
3114
+ || error?.code === 'AGY_DESKTOP_TASK_LIMIT')
3115
+ return 'fatal';
3116
+ // A provider may have charged for completed steps before the turn failed.
3117
+ // Replaying that turn can repeat actions and spend the same tokens again.
3118
+ const spent = Number(error?.partialUsage?.promptTokens || 0)
3119
+ + Number(error?.partialUsage?.completionTokens || 0);
3120
+ if (spent > 0)
3066
3121
  return 'fatal';
3067
3122
  const msg = (error.message || '').toLowerCase();
3068
3123
  if (msg.includes('syntax') || msg.includes('unexpected token') || msg.includes('invalid json')) {