@causyne/agent 1.20.9 → 1.20.10

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 +74 -11
  9. package/src/providers/antigravity.ts +77 -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 +356 -0
  16. package/src/stallGuard.ts +432 -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/src/agentLoop.ts CHANGED
@@ -79,6 +79,7 @@ import { createProvider } from './providers/factory.js';
79
79
  import { resolveMentionedContext } from './promptMentions.js';
80
80
  import { isLaunchOnlyPrompt, launchScopeError } from './launchIntent.js';
81
81
  import { StreamingCodePreview, NativeCodeObserver, codeProgressFromAction } from './tui/codeProgress.js';
82
+ import { StallGuardController, type StallGuardDecision, type IdenticalCallObservation } from './stallGuard.js';
82
83
 
83
84
  export interface AgentLoopEvent {
84
85
  type: string;
@@ -572,6 +573,7 @@ export class AgentLoop {
572
573
  this.consecutiveBlockedActions = 0; // V8 Transcendence: Circuit Breaker
573
574
  this.recentActionSignatures = [];
574
575
  this.consecutiveReadOnlySteps = 0;
576
+ this.stallGuard = new StallGuardController();
575
577
 
576
578
  // Sovereign Progressive Disclosure: which capability packs have entered the
577
579
  // context window for this task. Nothing is disabled — see src/toolPacks.js.
@@ -1399,7 +1401,9 @@ export class AgentLoop {
1399
1401
  this.circuitBreakerUnlocked = false;
1400
1402
  this.recentActionSignatures = [];
1401
1403
  this.consecutiveReadOnlySteps = 0;
1404
+ this.stallGuard.reset();
1402
1405
  this.tokenTracker.resetTask();
1406
+ let mediaExplorationRecoveries = 0;
1403
1407
 
1404
1408
  // The core loop governed by Sovereign Human-in-the-Loop Checkpoints
1405
1409
  while (!this.stopRequested) {
@@ -1420,9 +1424,12 @@ export class AgentLoop {
1420
1424
  const MAX_CHAR_POOL = resolveCharPool(activeTier, this.config.maxCharPool);
1421
1425
 
1422
1426
  // 5-Stage Progressive Compaction (Claude Code Architecture / Research Section E):
1423
- // Stage 2 (Snip >15K tokens / 60K chars) + Stage 1 (Budget Reduction >70%) +
1424
- // Stage 3 (Microcompact) + Stage 4 (Context Collapse >85%)
1427
+ // Stage 0 (HLCE Ephemeral Decay) + Stage 2 (Snip >15K tokens / 60K chars) +
1428
+ // Stage 1 (Budget Reduction >70%) + Stage 3 (Microcompact) + Stage 4 (Context Collapse >85%)
1425
1429
  const compaction = applyProgressiveCompaction(this.messages, MAX_CHAR_POOL, {
1430
+ enableEphemeralDecay: true,
1431
+ ephemeralKeepRecent: 3,
1432
+ ephemeralMinChars: 1200,
1426
1433
  budgetKeepRecent: this.config.keepRecentToolResults ?? 8,
1427
1434
  collapseKeepRecent: 2
1428
1435
  });
@@ -1778,6 +1785,7 @@ export class AgentLoop {
1778
1785
  taskIntent: isLaunchOnlyPrompt(this.currentTaskPrompt || this.userPrompt || '') ? 'launch' : 'general',
1779
1786
  taskArchetype: determineToolScope(this.currentTaskPrompt || this.userPrompt || '', this.taskShape).archetype,
1780
1787
  maxTokensThisCall: Number.isFinite(remainingBudget) ? remainingBudget : undefined,
1788
+ tokenLimit: Number.isFinite(remainingBudget) ? remainingBudget : Infinity,
1781
1789
  workspaceRoot: this.workspaceRoot,
1782
1790
  tools: dynamicTools,
1783
1791
  // IARS couples escalation to a wider search. Bounded so a stuck task
@@ -1978,11 +1986,11 @@ export class AgentLoop {
1978
1986
  if (['write_file', 'write_to_file', 'edit_file', 'replace_file_content', 'multi_replace_file_content', 'fs_write', 'fs_edit', 'multiedit'].includes(actionName) && detailPath) {
1979
1987
  this.recordWebArtifact(detailPath);
1980
1988
  }
1981
- if (
1982
- ['capture_browser_screenshot', 'browser_subagent', 'open_browser_url', 'browser_get_dom', 'read_browser_page'].includes(actionName) ||
1983
- ((actionName === 'read_file' || actionName === 'view_file') && /\.(png|jpe?g|webp|gif|svg)$/i.test(detailPath))
1984
- ) {
1985
- this.webVerificationState.screenshotTaken = true;
1989
+ // A native action's name is not evidence that a model inspected
1990
+ // pixels. Keep visual verification false unless a real image result
1991
+ // has reached a vision-capable provider.
1992
+ if (['browser_get_dom', 'read_browser_page'].includes(actionName)) {
1993
+ this.webVerificationState.browserActUsed = true;
1986
1994
  }
1987
1995
  }
1988
1996
  }
@@ -2221,23 +2229,33 @@ export class AgentLoop {
2221
2229
  let visionDeclined = false;
2222
2230
  let browserReady = false;
2223
2231
  let browserDeclined = false;
2232
+ let browserRuntimeError = '';
2224
2233
  try {
2225
2234
  const { groupStatus, isGroupDeclined } = await import('./provisioning/capabilityProvisioner.js');
2226
2235
  visionReady = groupStatus('vision').state === 'ready';
2227
2236
  visionDeclined = isGroupDeclined('vision');
2228
2237
  browserReady = groupStatus('browser').state === 'ready';
2229
2238
  browserDeclined = isGroupDeclined('browser');
2239
+ if (browserReady) {
2240
+ const { resolveBrowserRuntime } = await import('./browser/browserRuntime.js');
2241
+ try { resolveBrowserRuntime(); } catch (error: unknown) {
2242
+ browserReady = false;
2243
+ browserRuntimeError = error instanceof Error ? error.message : String(error);
2244
+ }
2245
+ }
2230
2246
  } catch (e: any) { /* treat as not ready */ }
2231
2247
  let webGuardMsg = '';
2232
2248
 
2233
- if (!browserReady && !browserDeclined) {
2249
+ if (browserRuntimeError) {
2250
+ 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.]`;
2251
+ } else if (!browserReady && !browserDeclined) {
2234
2252
  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.]`;
2235
2253
  } else if (hasVision && !visionReady && !visionDeclined) {
2236
2254
  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.]`;
2237
2255
  } else if (hasVision && visionReady && !this.webVerificationState.screenshotTaken) {
2238
- 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.]`;
2256
+ 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.]`;
2239
2257
  } else if ((!hasVision || visionDeclined) && browserReady && !this.webVerificationState.browserActUsed && !this.webVerificationState.screenshotTaken) {
2240
- 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.]`;
2258
+ 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.]`;
2241
2259
  }
2242
2260
 
2243
2261
  if (webGuardMsg) {
@@ -2254,6 +2272,21 @@ export class AgentLoop {
2254
2272
  }
2255
2273
  }
2256
2274
 
2275
+ // Tool availability and a completed plan are not evidence of visual
2276
+ // inspection. A failed browser/capture attempt must not become a
2277
+ // successful task merely because the provider says "verified".
2278
+ if (isWebTask && this.stepsCompleted > 0
2279
+ && !this.webVerificationState.browserActUsed
2280
+ && !this.webVerificationState.screenshotTaken) {
2281
+ this.emitEvent({
2282
+ type: 'error',
2283
+ message: 'The web files may have changed, but rendered-page verification did not succeed. The task remains unverified; no completion is recorded.'
2284
+ });
2285
+ auditLog.log({ event: 'task_unverified', taskId: this.taskId, reason: 'web_render_not_inspected' });
2286
+ this.memoryManager.saveHistory(this.messages);
2287
+ break;
2288
+ }
2289
+
2257
2290
  // Cold Observer: Overconfidence & Loop Verification Check
2258
2291
  {
2259
2292
  try {
@@ -2435,72 +2468,43 @@ export class AgentLoop {
2435
2468
  this.recentActionSignatures.shift();
2436
2469
  }
2437
2470
 
2438
- const isCommandTool = ['sysRun', 'sysRunBg', 'terminal_persistent_shell'].includes(functionName);
2439
- if (isCommandTool) {
2440
- const duplicateCount = this.recentActionSignatures.filter((sig: string) => sig === actionSig).length;
2471
+ // Universal Intelligent Loop Guard & Stall Breaker (Hermes / Claude Code architecture)
2472
+ const isExecTask = isExecutionOrLaunchTaskPrompt(this.currentTaskPrompt || this.userPrompt || '');
2473
+ const isAuthoringTask = !isExecTask && isCodeAuthoringTaskPrompt(this.currentTaskPrompt || this.userPrompt || '');
2441
2474
 
2442
- // 1. Hard Circuit Breaker on Duplicate Command Thrashing (same command attempted 4 times total)
2443
- if (duplicateCount >= 4) {
2444
- 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.`;
2445
- this.emitEvent({ type: 'step_error', tool: functionName, error: fatalMsg, toolCallId: toolCall.id });
2446
- auditLog.log({ event: 'task_killed_circuit_breaker', taskId: this.taskId, reason: fatalMsg });
2447
- this.abort();
2448
- break;
2449
- }
2475
+ const guardDecision = this.stallGuard.beforeCall(functionName, args || {}, {
2476
+ isAuthoringTask
2477
+ });
2450
2478
 
2451
- // 2. Block 3rd attempt of identical command and inject a non-negotiable recovery mandate
2452
- if (duplicateCount === 3) {
2453
- const isExec = isExecutionOrLaunchTaskPrompt(this.currentTaskPrompt || this.userPrompt || '');
2454
- const isAuthoring = !isExec && isCodeAuthoringTaskPrompt(this.currentTaskPrompt || this.userPrompt || '');
2455
- let blockMsg: string;
2456
- if (actionSig === 'sysRun:probe:process_or_port' || isExec) {
2457
- 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.`;
2458
- } else if (isAuthoring) {
2459
- 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.`;
2460
- } else {
2461
- 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.`;
2462
- }
2463
- this.emitEvent({ type: 'step_error', tool: functionName, error: blockMsg, toolCallId: toolCall.id });
2464
- this.messages.push({
2465
- role: 'tool',
2466
- tool_call_id: toolCall.id,
2467
- name: functionName,
2468
- content: JSON.stringify({
2469
- success: false,
2470
- error: 'DUPLICATE_ACTION_BLOCKED',
2471
- CRITICAL_INSTRUCTION: blockMsg
2472
- })
2473
- });
2474
- continue;
2475
- }
2479
+ if (guardDecision.action === 'block') {
2480
+ this.emitEvent({ type: 'step_error', tool: functionName, error: guardDecision.message, toolCallId: toolCall.id });
2481
+ auditLog.log({ event: 'tool_blocked', taskId: this.taskId, tool: functionName, args, reason: guardDecision.message });
2482
+ this.messages.push({
2483
+ role: 'tool',
2484
+ tool_call_id: toolCall.id,
2485
+ name: functionName,
2486
+ content: JSON.stringify({
2487
+ success: false,
2488
+ error: guardDecision.code,
2489
+ CRITICAL_INSTRUCTION: guardDecision.message
2490
+ })
2491
+ });
2492
+ continue;
2476
2493
  }
2477
2494
 
2478
- // 3. Track Read-Only Inspection Chains on Code Authoring Tasks (Max 6 inspection steps)
2479
- const isMutatingAction = ['fs_write', 'fs_edit', 'MultiEdit', 'game_build_html5'].includes(functionName)
2480
- || (functionName === 'sysRun' && /(npm\s+(i|install|add)|pnpm\s+add|yarn\s+add|pip\s+install|git\s+commit)\b/.test(args?.command || ''));
2481
-
2482
- if (isMutatingAction) {
2483
- this.consecutiveReadOnlySteps = 0;
2484
- } else if (['sysRun', 'sysRunBg', 'fs_read', 'fs_list', 'dir_list', 'grep_search'].includes(functionName)) {
2485
- this.consecutiveReadOnlySteps = (Number(this.consecutiveReadOnlySteps) || 0) + 1;
2495
+ if (guardDecision.action === 'halt') {
2496
+ this.emitEvent({ type: 'step_error', tool: functionName, error: guardDecision.message, toolCallId: toolCall.id });
2497
+ auditLog.log({ event: 'task_killed_circuit_breaker', taskId: this.taskId, reason: guardDecision.message });
2498
+ this.abort();
2499
+ break;
2486
2500
  }
2487
2501
 
2488
- const isExecTask = isExecutionOrLaunchTaskPrompt(this.currentTaskPrompt || this.userPrompt || '');
2489
- const isAuthoringTask = !isExecTask && isCodeAuthoringTaskPrompt(this.currentTaskPrompt || this.userPrompt || '');
2490
- if (isAuthoringTask && this.consecutiveReadOnlySteps === 4) {
2502
+ if (isAuthoringTask && this.stallGuard.distinctInspectionCount === 12) {
2491
2503
  this.messages.push({
2492
2504
  role: 'system',
2493
- 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.]`
2505
+ 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.]`
2494
2506
  });
2495
2507
  }
2496
-
2497
- if (isAuthoringTask && this.consecutiveReadOnlySteps >= 6) {
2498
- 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.`;
2499
- this.emitEvent({ type: 'step_error', tool: functionName, error: fatalMsg, toolCallId: toolCall.id });
2500
- auditLog.log({ event: 'task_killed_circuit_breaker', taskId: this.taskId, reason: fatalMsg });
2501
- this.abort();
2502
- break;
2503
- }
2504
2508
 
2505
2509
  this.emitEvent({ type: 'step_start', tool: functionName, args: args, toolCallId: toolCall.id });
2506
2510
  const codeAction = codeProgressFromAction(functionName, args || {}, toolCall.id);
@@ -2837,6 +2841,7 @@ export class AgentLoop {
2837
2841
  name: functionName, content: JSON.stringify({ ...failure,
2838
2842
  errorType, timeMachine: recovery.guidance,
2839
2843
  ...(alternativeRoute ? { apcReplanAlternative: alternativeRoute.suggestedTool, apcReplanReason: alternativeRoute.reason } : {}) }) });
2844
+ this.stallGuard.observeCall(functionName, args || {}, failure, toolCall.id, true);
2840
2845
  this.memoryManager.saveHistory(this.messages);
2841
2846
  if (errorType === 'fatal' || recovery.kind === 'stop' || recovery.kind === 'human') {
2842
2847
  this.stopRequested = true;
@@ -2871,13 +2876,13 @@ export class AgentLoop {
2871
2876
  this.recordWebArtifact(args.path || args.file_path);
2872
2877
  }
2873
2878
 
2874
- if (functionName === 'screenshot' && result?.success === true && result?._is_image_marker === true) {
2879
+ if (['screenshot', 'vision_inspect_ui'].includes(functionName) && this.llm.supportsVision !== false && result?.success === true && result?._is_image_marker === true) {
2875
2880
  this.webVerificationState.screenshotTaken = true;
2876
2881
  }
2877
2882
  if (functionName === 'browser_act' && result?.success === true) {
2878
- this.webVerificationState.browserActUsed = true;
2879
- if (Array.isArray(args?.actions) && args.actions.some((action: any) => action?.type === 'screenshot')) {
2880
- this.webVerificationState.screenshotTaken = true;
2883
+ const browserResults = Array.isArray(result.data) ? result.data : [];
2884
+ if (browserResults.some((item: any) => ['snapshot', 'scrape'].includes(item?.action))) {
2885
+ this.webVerificationState.browserActUsed = true;
2881
2886
  }
2882
2887
  }
2883
2888
 
@@ -3053,7 +3058,7 @@ export class AgentLoop {
3053
3058
  role: 'tool',
3054
3059
  tool_call_id: toolCall.id,
3055
3060
  name: functionName,
3056
- content: `[Image observed: ${result.filename || 'image'} (${result.mimeType || 'image/png'}) - verified on disk. Vision observation payload passed.]`
3061
+ content: `[Image captured: ${result.filename || 'image'} (${result.mimeType || 'image/png'}). This provider cannot receive image pixels; visual inspection was not completed.]`
3057
3062
  });
3058
3063
  } else {
3059
3064
  // Provider-specific format.
@@ -3185,6 +3190,19 @@ export class AgentLoop {
3185
3190
  }
3186
3191
  }
3187
3192
 
3193
+ const isCallFailed = Boolean(result && (result.success === false || typeof result.error === 'string'));
3194
+ const stallObservation = this.stallGuard.observeCall(
3195
+ functionName,
3196
+ args || {},
3197
+ result,
3198
+ toolCall.id,
3199
+ isCallFailed
3200
+ );
3201
+
3202
+ if (stallObservation.stub && resultString.length >= 256) {
3203
+ resultString = stallObservation.stub;
3204
+ }
3205
+
3188
3206
  this.messages.push({
3189
3207
  role: 'tool',
3190
3208
  tool_call_id: toolCall.id,
@@ -3195,6 +3213,21 @@ export class AgentLoop {
3195
3213
  // stub keep pointing at the spill after the payload is gone.
3196
3214
  ...(spill ? { spillPath: spill.path } : {})
3197
3215
  });
3216
+
3217
+ if (stallObservation.notice) {
3218
+ this.messages.push({
3219
+ role: 'system',
3220
+ content: stallObservation.notice
3221
+ });
3222
+ }
3223
+
3224
+ if (stallObservation.decision?.action === 'halt') {
3225
+ const fatalMsg = stallObservation.decision.message;
3226
+ this.emitEvent({ type: 'step_error', tool: functionName, error: fatalMsg, toolCallId: toolCall.id });
3227
+ auditLog.log({ event: 'task_killed_circuit_breaker', taskId: this.taskId, reason: fatalMsg });
3228
+ this.abort();
3229
+ break;
3230
+ }
3198
3231
  }
3199
3232
 
3200
3233
  // Save state continuously after each tool loop
@@ -3203,9 +3236,12 @@ export class AgentLoop {
3203
3236
  }
3204
3237
 
3205
3238
  } catch (e: any) {
3206
- if (e?.code === 'AGY_TOKEN_BUDGET') {
3239
+ // A peer can fail after completing billable steps. Charge those steps
3240
+ // once even when no final result was returned, including action and
3241
+ // wall-clock limits, before deciding whether recovery is possible.
3242
+ if (e?.partialUsage) {
3207
3243
  const usage = e.partialUsage;
3208
- if (usage) {
3244
+ if (usage.promptTokens + usage.completionTokens > 0) {
3209
3245
  await this.tokenTracker.trackUsage(
3210
3246
  usage.promptTokens, usage.completionTokens,
3211
3247
  (message: string) => this.emitEvent({ type: 'budget_warning', message }), usage
@@ -3218,9 +3254,28 @@ export class AgentLoop {
3218
3254
  measurement: 'provider_reported_partial', costBasis: 'external_subscription_unavailable'
3219
3255
  });
3220
3256
  }
3257
+ }
3258
+ if (e?.code === 'AGY_TOKEN_BUDGET' || e?.code === 'TASK_TOKEN_BUDGET' || e?.code === 'PROVIDER_TOKEN_BUDGET') {
3221
3259
  this.emitEvent({ type: 'budget_warning', message: e.message });
3222
3260
  auditLog.log({ event: 'task_stopped_on_budget', taskId: this.taskId,
3223
- used: this.tokenTracker.taskTokens, limit: this.tokenTracker.budget?.maxTokensPerTask || 0 });
3261
+ used: this.tokenTracker.taskTokens, limit: e.tokenLimit || this.tokenTracker.budget?.maxTokensPerTask || 0 });
3262
+ break;
3263
+ }
3264
+ if (e?.code === 'AGY_EXPLORATION_LOOP' || e?.code === 'AGENT_EXPLORATION_LOOP' || e?.code === 'STALL_EXPLORATION_LOOP') {
3265
+ auditLog.log({ event: 'media_exploration_checkpoint', taskId: this.taskId,
3266
+ inspectionCount: e.inspectionCount, recovery: mediaExplorationRecoveries });
3267
+ if (mediaExplorationRecoveries++ === 0) {
3268
+ this.messages.push({ role: 'system', content:
3269
+ '[TASK RECOVERY] Consecutive read-only inspections without workspace changes were paused. ' +
3270
+ 'The user requested a concrete change. Reuse the observations already gathered; do not repeat probes. ' +
3271
+ 'Make one targeted workspace edit now, then run one focused verification. ' +
3272
+ 'If editing is blocked, report the exact blocker. Do not claim completion from inspection alone.' });
3273
+ this.memoryManager.saveHistory(this.messages);
3274
+ this.emitEvent({ type: 'notice', message: 'Repeated inspection paused; continuing once with a direct edit instruction.' });
3275
+ continue;
3276
+ }
3277
+ this.emitEvent({ type: 'error', message:
3278
+ 'The provider continued read-only inspection after a corrective checkpoint. The task remains unfinished; no edit was verified.' });
3224
3279
  break;
3225
3280
  }
3226
3281
  if (this.stopRequested || this.abortController?.signal?.aborted || e?.name === 'AbortError') {
@@ -3340,7 +3395,14 @@ export class AgentLoop {
3340
3395
 
3341
3396
  // V5: Classify errors for intelligent retry decisions
3342
3397
  classifyError(error: any) {
3343
- if (error?.code === 'AGY_NATIVE_ACTION_DENIED') return 'fatal';
3398
+ if (error?.code === 'AGY_NATIVE_ACTION_DENIED'
3399
+ || error?.code === 'AGY_NATIVE_ACTION_BUDGET'
3400
+ || error?.code === 'AGY_DESKTOP_TASK_LIMIT') return 'fatal';
3401
+ // A provider may have charged for completed steps before the turn failed.
3402
+ // Replaying that turn can repeat actions and spend the same tokens again.
3403
+ const spent = Number(error?.partialUsage?.promptTokens || 0)
3404
+ + Number(error?.partialUsage?.completionTokens || 0);
3405
+ if (spent > 0) return 'fatal';
3344
3406
  const msg = (error.message || '').toLowerCase();
3345
3407
 
3346
3408
  if (msg.includes('syntax') || msg.includes('unexpected token') || msg.includes('invalid json')) {
@@ -1,6 +1,7 @@
1
1
  import crypto from 'node:crypto';
2
2
  import fs from 'node:fs/promises';
3
3
  import path from 'node:path';
4
+ import { fileURLToPath, pathToFileURL } from 'node:url';
4
5
  import { capabilityDirectory, ensureCapability, loadCapabilityPackage } from '../provisioning/capabilityProvisioner.js';
5
6
  import { resolveBrowserRuntime } from './browserRuntime.js';
6
7
  import { assertPublicWebUrl } from './urlPolicy.js';
@@ -864,6 +865,14 @@ export class CausyneBrowser {
864
865
  return route.continue();
865
866
  try {
866
867
  const parsed = new URL(url);
868
+ if (parsed.protocol === 'file:') {
869
+ const workspace = await fs.realpath(this.workspace);
870
+ const file = await fs.realpath(fileURLToPath(parsed));
871
+ if (!isWithin(workspace, file))
872
+ throw new Error('File is outside the selected workspace');
873
+ await route.continue();
874
+ return;
875
+ }
867
876
  if (parsed.protocol === 'ws:' || parsed.protocol === 'wss:') {
868
877
  parsed.protocol = parsed.protocol === 'wss:' ? 'https:' : 'http:';
869
878
  await this.validateUrl(parsed.href);
@@ -1046,6 +1055,21 @@ export class CausyneBrowser {
1046
1055
  state.lastSnapshot = '';
1047
1056
  state.lastStructure = null;
1048
1057
  }
1058
+ async preview(state, filePath, workspace) {
1059
+ const root = await fs.realpath(workspace);
1060
+ const target = await fs.realpath(path.resolve(root, filePath));
1061
+ if (!isWithin(root, target) || !/\.html?$/i.test(target)) {
1062
+ throw new Error('Preview requires an HTML file inside the selected workspace');
1063
+ }
1064
+ await state.page.goto(pathToFileURL(target).href, { waitUntil: 'domcontentloaded', timeout: NAVIGATION_TIMEOUT_MS });
1065
+ await state.page.waitForLoadState('domcontentloaded', { timeout: NAVIGATION_TIMEOUT_MS });
1066
+ if (state.page.url() !== pathToFileURL(target).href) {
1067
+ throw new Error('Preview navigated away from the selected workspace file');
1068
+ }
1069
+ state.refs.clear();
1070
+ state.lastSnapshot = '';
1071
+ state.lastStructure = null;
1072
+ }
1049
1073
  async navigateWithMacroFallback(state, action) {
1050
1074
  const { targetUrl, macroName, macroQuery } = this.resolveTargetUrl(action);
1051
1075
  if (macroName === '@google_search' && macroQuery) {
@@ -1378,6 +1402,12 @@ export class CausyneBrowser {
1378
1402
  await this.navigateWithMacroFallback(state, action);
1379
1403
  return { action: action.type, tabId: state.id, url: state.page.url(), title: await state.page.title() };
1380
1404
  }
1405
+ if (action.type === 'preview') {
1406
+ if (typeof action.filePath !== 'string')
1407
+ throw new Error('preview requires filePath');
1408
+ await this.preview(state, action.filePath, workspace);
1409
+ return { action: action.type, tabId: state.id, url: state.page.url(), title: await state.page.title() };
1410
+ }
1381
1411
  if (action.type === 'snapshot' || action.type === 'scrape') {
1382
1412
  const snapshot = await this.snapshot(action.offset ?? 0);
1383
1413
  return {
@@ -1588,6 +1618,12 @@ export function validateBrowserActSandbox(args, workspaceRoot, isInternalUrl, is
1588
1618
  for (const action of actions) {
1589
1619
  if (!action || typeof action !== 'object')
1590
1620
  continue;
1621
+ if (action.type === 'preview') {
1622
+ const filePath = typeof action.filePath === 'string' ? action.filePath : '';
1623
+ if (!filePath || !/\.html?$/i.test(filePath) || !isPathAllowed(path.resolve(workspaceRoot, filePath))) {
1624
+ return { allowed: false, reason: 'Preview requires an HTML file inside the selected workspace', risk: 'forbidden' };
1625
+ }
1626
+ }
1591
1627
  const rawUrl = typeof action.url === 'string' ? action.url.trim() : '';
1592
1628
  const rawMacro = typeof action.macro === 'string' ? action.macro.trim() : '';
1593
1629
  if (rawMacro) {
@@ -1,6 +1,7 @@
1
1
  import crypto from 'node:crypto';
2
2
  import fs from 'node:fs/promises';
3
3
  import path from 'node:path';
4
+ import { fileURLToPath, pathToFileURL } from 'node:url';
4
5
 
5
6
  import {
6
7
  capabilityDirectory,
@@ -419,7 +420,7 @@ export type BrowserActionType =
419
420
  | 'listTabs' | 'list_tabs'
420
421
  | 'closeTab' | 'close_tab'
421
422
  | 'search'
422
- | 'goto' | 'open' | 'navigate'
423
+ | 'goto' | 'open' | 'navigate' | 'preview'
423
424
  | 'snapshot' | 'scrape'
424
425
  | 'click' | 'clickIndex'
425
426
  | 'type' | 'typeIndex' | 'fill'
@@ -1123,6 +1124,13 @@ export class CausyneBrowser {
1123
1124
  if (/^(about:|data:|blob:|moz-extension:)/i.test(url)) return route.continue();
1124
1125
  try {
1125
1126
  const parsed = new URL(url);
1127
+ if (parsed.protocol === 'file:') {
1128
+ const workspace = await fs.realpath(this.workspace);
1129
+ const file = await fs.realpath(fileURLToPath(parsed));
1130
+ if (!isWithin(workspace, file)) throw new Error('File is outside the selected workspace');
1131
+ await route.continue();
1132
+ return;
1133
+ }
1126
1134
  if (parsed.protocol === 'ws:' || parsed.protocol === 'wss:') {
1127
1135
  parsed.protocol = parsed.protocol === 'wss:' ? 'https:' : 'http:';
1128
1136
  await this.validateUrl(parsed.href);
@@ -1291,6 +1299,22 @@ export class CausyneBrowser {
1291
1299
  state.lastStructure = null;
1292
1300
  }
1293
1301
 
1302
+ private async preview(state: TabState, filePath: string, workspace: string): Promise<void> {
1303
+ const root = await fs.realpath(workspace);
1304
+ const target = await fs.realpath(path.resolve(root, filePath));
1305
+ if (!isWithin(root, target) || !/\.html?$/i.test(target)) {
1306
+ throw new Error('Preview requires an HTML file inside the selected workspace');
1307
+ }
1308
+ await state.page.goto(pathToFileURL(target).href, { waitUntil: 'domcontentloaded', timeout: NAVIGATION_TIMEOUT_MS });
1309
+ await state.page.waitForLoadState('domcontentloaded', { timeout: NAVIGATION_TIMEOUT_MS });
1310
+ if (state.page.url() !== pathToFileURL(target).href) {
1311
+ throw new Error('Preview navigated away from the selected workspace file');
1312
+ }
1313
+ state.refs.clear();
1314
+ state.lastSnapshot = '';
1315
+ state.lastStructure = null;
1316
+ }
1317
+
1294
1318
  private async navigateWithMacroFallback(state: TabState, action: BrowserAction): Promise<void> {
1295
1319
  const { targetUrl, macroName, macroQuery } = this.resolveTargetUrl(action);
1296
1320
  if (macroName === '@google_search' && macroQuery) {
@@ -1603,6 +1627,11 @@ export class CausyneBrowser {
1603
1627
  await this.navigateWithMacroFallback(state, action);
1604
1628
  return { action: action.type, tabId: state.id, url: state.page.url(), title: await state.page.title() };
1605
1629
  }
1630
+ if (action.type === 'preview') {
1631
+ if (typeof action.filePath !== 'string') throw new Error('preview requires filePath');
1632
+ await this.preview(state, action.filePath, workspace);
1633
+ return { action: action.type, tabId: state.id, url: state.page.url(), title: await state.page.title() };
1634
+ }
1606
1635
  if (action.type === 'snapshot' || action.type === 'scrape') {
1607
1636
  const snapshot = await this.snapshot(action.offset ?? 0);
1608
1637
  return {
@@ -1808,6 +1837,12 @@ export function validateBrowserActSandbox(
1808
1837
  let hasDownload = false;
1809
1838
  for (const action of actions) {
1810
1839
  if (!action || typeof action !== 'object') continue;
1840
+ if (action.type === 'preview') {
1841
+ const filePath = typeof action.filePath === 'string' ? action.filePath : '';
1842
+ if (!filePath || !/\.html?$/i.test(filePath) || !isPathAllowed(path.resolve(workspaceRoot, filePath))) {
1843
+ return { allowed: false, reason: 'Preview requires an HTML file inside the selected workspace', risk: 'forbidden' };
1844
+ }
1845
+ }
1811
1846
  const rawUrl = typeof action.url === 'string' ? action.url.trim() : '';
1812
1847
  const rawMacro = typeof action.macro === 'string' ? action.macro.trim() : '';
1813
1848
  if (rawMacro) {
package/src/commands.js CHANGED
@@ -45,6 +45,7 @@ import {
45
45
  import fs from 'fs';
46
46
  import os from 'os';
47
47
  import path from 'path';
48
+ import { runCopyCommand, runPasteCommand } from './tui/chatboxClipboard.js';
48
49
 
49
50
  export const SCOPES = ['local'];
50
51
 
@@ -991,6 +992,30 @@ export const COMMANDS = [
991
992
  }
992
993
  },
993
994
 
995
+ {
996
+ name: 'copy',
997
+ aliases: ['cp', 'clip'],
998
+ scope: 'local',
999
+ usage: '/copy [input | last | <text>]',
1000
+ description: 'Copy chatbox input, last assistant response, or text to system clipboard',
1001
+ run: (argv, ctx) => {
1002
+ const res = runCopyCommand(argv, ctx);
1003
+ return res.ok ? ok(res.output) : fail(res.output);
1004
+ }
1005
+ },
1006
+
1007
+ {
1008
+ name: 'paste',
1009
+ aliases: ['pasteclip'],
1010
+ scope: 'local',
1011
+ usage: '/paste [text]',
1012
+ description: 'Paste clipboard content or text into the chatbox input',
1013
+ run: (argv, ctx) => {
1014
+ const res = runPasteCommand(argv, ctx);
1015
+ return res.ok ? ok(res.output) : fail(res.output);
1016
+ }
1017
+ },
1018
+
994
1019
  {
995
1020
  name: 'stop',
996
1021
  aliases: ['abort'],
@@ -449,6 +449,22 @@ export function applyProgressiveCompaction(messages, maxCharPool, options = {})
449
449
  let totalReclaimed = 0;
450
450
  const stagesFired = [];
451
451
 
452
+ // Stage 0: Ephemeral Observation Compaction (Hyper-Lean Context Engine / HLCE)
453
+ // Decays stale tool outputs older than ephemeralKeepRecent (default 3) exceeding ephemeralMinChars (default 1200)
454
+ // to prevent turn-over-turn cumulative prompt token blowup while preserving full detail on active turns.
455
+ if (options.enableEphemeralDecay) {
456
+ const ephemeralKeepRecent = options.ephemeralKeepRecent ?? 3;
457
+ const ephemeralMinChars = options.ephemeralMinChars ?? 1200;
458
+ const ephemeralReclaimed = decayToolResults(messages, {
459
+ keepRecent: ephemeralKeepRecent,
460
+ minChars: ephemeralMinChars
461
+ });
462
+ if (ephemeralReclaimed > 0) {
463
+ totalReclaimed += ephemeralReclaimed;
464
+ stagesFired.push(`ephemeral_decay:${(ephemeralReclaimed / 1024).toFixed(1)}kb`);
465
+ }
466
+ }
467
+
452
468
  // Stage 2: Snip oversized tool outputs (>15K tokens / 60K chars)
453
469
  const snipRes = snipOversizedToolOutputs(messages, options.snipOptions);
454
470
  if (snipRes.snippedCount > 0) {