@causyne/agent 1.20.10 → 1.20.12

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 (88) hide show
  1. package/LICENSE +1 -1
  2. package/docs/ARCHITECTURE.md +24 -1
  3. package/package.json +1 -1
  4. package/src/acp/client.js +9 -2
  5. package/src/acp/client.ts +11 -2
  6. package/src/acp/protocol.ts +9 -0
  7. package/src/agentLoop.js +504 -119
  8. package/src/agentLoop.ts +477 -121
  9. package/src/browser/browserRuntime.js +47 -0
  10. package/src/browser/browserRuntime.ts +45 -0
  11. package/src/browser/causyneBrowser.js +60 -31
  12. package/src/browser/causyneBrowser.ts +37 -12
  13. package/src/browser/workspacePreview.js +52 -0
  14. package/src/browser/workspacePreview.ts +49 -0
  15. package/src/core/planCache.js +5 -0
  16. package/src/core/planCache.ts +5 -0
  17. package/src/decisionPolicy.js +9 -0
  18. package/src/decisionPolicy.ts +8 -0
  19. package/src/historyPruner.js +251 -0
  20. package/src/historyPruner.ts +263 -0
  21. package/src/infra/atomicWriter.js +49 -0
  22. package/src/infra/atomicWriter.ts +63 -0
  23. package/src/infra/telemetry.js +38 -0
  24. package/src/infra/telemetry.ts +68 -0
  25. package/src/observer/coldObserver.js +12 -7
  26. package/src/observer/coldObserver.ts +12 -7
  27. package/src/observer/evidence.js +8 -2
  28. package/src/observer/evidence.ts +9 -2
  29. package/src/outputRecovery.js +36 -0
  30. package/src/outputRecovery.ts +33 -0
  31. package/src/providers/acp.js +114 -46
  32. package/src/providers/acp.ts +129 -46
  33. package/src/providers/antigravity.js +262 -91
  34. package/src/providers/antigravity.ts +270 -99
  35. package/src/providers/antigravityBridge.js +58 -0
  36. package/src/providers/antigravityBridge.ts +51 -0
  37. package/src/providers/base.d.ts +9 -0
  38. package/src/providers/budgetEnforcer.js +110 -0
  39. package/src/providers/budgetEnforcer.ts +122 -0
  40. package/src/providers/collaborationPolicy.js +6 -0
  41. package/src/providers/collaborationPolicy.ts +7 -0
  42. package/src/providers/loopGuard.js +84 -0
  43. package/src/providers/loopGuard.ts +105 -0
  44. package/src/providers/pi.js +19 -6
  45. package/src/providers/pi.ts +19 -7
  46. package/src/providers/toolContracts.js +36 -0
  47. package/src/providers/toolContracts.ts +48 -0
  48. package/src/session/sidechainEvents.js +49 -0
  49. package/src/session/sidechainEvents.ts +98 -0
  50. package/src/skillsManager.d.ts +1 -0
  51. package/src/smartToolsUse.js +123 -4
  52. package/src/smartToolsUse.ts +136 -4
  53. package/src/stallGuard.js +3 -12
  54. package/src/stallGuard.ts +3 -12
  55. package/src/subagent/sidechainHarness.js +66 -0
  56. package/src/subagent/sidechainHarness.ts +91 -0
  57. package/src/taskContinuation.js +12 -0
  58. package/src/taskContinuation.ts +13 -0
  59. package/src/tokenTracker.js +406 -539
  60. package/src/tokenTracker.ts +569 -0
  61. package/src/toolPacks.d.ts +2 -0
  62. package/src/toolPacks.js +1 -1
  63. package/src/tools/argumentValidation.js +56 -0
  64. package/src/tools/argumentValidation.ts +50 -0
  65. package/src/tools/browserAutomator.js +2 -2
  66. package/src/tools/browserAutomator.ts +3 -2
  67. package/src/tools/deferredMcpSearch.js +188 -201
  68. package/src/tools/deferredMcpSearch.ts +250 -0
  69. package/src/tools/generateMediaViaApi.js +305 -331
  70. package/src/tools/generateMediaViaApi.ts +330 -0
  71. package/src/tools/historyPruner.js +5 -0
  72. package/src/tools/historyPruner.ts +5 -0
  73. package/src/tools/payloadSanitizer.js +92 -0
  74. package/src/tools/payloadSanitizer.ts +113 -0
  75. package/src/tools/registry.d.ts +1 -0
  76. package/src/tools/sysRun.js +47 -18
  77. package/src/tools/sysRun.ts +52 -20
  78. package/src/tools/toolOutputStore.js +180 -0
  79. package/src/tools/toolOutputStore.ts +209 -0
  80. package/src/tools/toolSelfRepair.js +26 -1
  81. package/src/tools/toolSelfRepair.ts +25 -1
  82. package/src/tui/chatRenderer.d.ts +1 -0
  83. package/src/tui/chatRenderer.js +4 -2
  84. package/src/tui/codeStreamRenderer.js +36 -8
  85. package/src/tui/codeStreamRenderer.ts +38 -8
  86. package/src/tui/stageSurface.js +1 -0
  87. package/src/tui/text.js +4 -1
  88. package/src/tokenTracker.d.ts +0 -1
package/src/agentLoop.ts CHANGED
@@ -1,4 +1,7 @@
1
- import { createHash } from 'crypto';
1
+ import { clearSysRunCache } from './tools/sysRun.js';
2
+ import { PEER_COLLABORATION_POLICY } from './providers/collaborationPolicy.js';
3
+ import type { RequestPermissionRequest, RequestPermissionResponse } from './acp/protocol.js';
4
+ import { createHash, randomUUID } from 'crypto';
2
5
  import { execFileSync } from 'node:child_process';
3
6
  import { processApprovalScope, createApprovalScope } from './approvalGrants.js';
4
7
  import { pruneSessions as pruneEmbodimentSessions, describeSession } from './embodimentSession.js';
@@ -7,6 +10,7 @@ import { audioFormatForMimeType } from './providers/base.js';
7
10
  import { TaskBuffer } from './taskBuffer.js';
8
11
  import { TOOL_DEFINITIONS, getDynamicTools, resolveTool, canonicalToolName } from './tools/registry.js';
9
12
  import { selfRepairToolCall, generateSelfRepairDiagnostic } from './tools/toolSelfRepair.js';
13
+ import { validateToolArguments } from './tools/argumentValidation.js';
10
14
  import { Sandbox } from './sandbox.js';
11
15
  import { auditLog } from './auditLog.js';
12
16
  import { hasMatchingHook, runConfiguredHooks } from './hooks.js';
@@ -51,7 +55,8 @@ import {
51
55
  import {
52
56
  determineToolScope,
53
57
  filterSuppressedPacks,
54
- resolveLazyPlaybooks
58
+ resolveLazyPlaybooks,
59
+ SmartToolsGovernor
55
60
  } from './smartToolsUse.js';
56
61
  import {
57
62
  resolveCharPool,
@@ -68,7 +73,8 @@ import {
68
73
 
69
74
  // Provider imports
70
75
  import { detectWorkspaceDomains, ensureSkillRepo, getSkillDomainHeader } from './skillsManager.js';
71
- import { spillToolResult, buildSpillNotice, buildDecayPointer, pruneOutputStore } from './outputStore.js';
76
+ import { spillToolResult, buildDecayPointer, pruneOutputStore } from './outputStore.js';
77
+ import { defaultToolOutputStore, processToolOutputWithStore, renderSpillDocument } from './tools/toolOutputStore.js';
72
78
  import { beginTask as beginCheckpointTask, captureBeforeMutation, pruneStore as pruneCheckpointStore, resolveProjectRoot } from './checkpoints.js';
73
79
  import fsSync from 'fs';
74
80
  import os from 'os';
@@ -80,6 +86,10 @@ import { resolveMentionedContext } from './promptMentions.js';
80
86
  import { isLaunchOnlyPrompt, launchScopeError } from './launchIntent.js';
81
87
  import { StreamingCodePreview, NativeCodeObserver, codeProgressFromAction } from './tui/codeProgress.js';
82
88
  import { StallGuardController, type StallGuardDecision, type IdenticalCallObservation } from './stallGuard.js';
89
+ import { buildRecoverableDroppedSummary, pruneStaleToolObservations, shortenOversizedToolObservations, pruneExecutedToolArguments } from './historyPruner.js';
90
+ import { isOutputRecoveryRead } from './outputRecovery.js';
91
+ import { isPlanReviewHandoff, isPlanningOnlyRequest } from './taskContinuation.js';
92
+ import { UnifiedBudgetEnforcer, EfficiencyCheckpoint, actionLimitFor, tokenLimitFor, turnTokenLimitFor, noncachedTokens } from './providers/budgetEnforcer.js';
83
93
 
84
94
  export interface AgentLoopEvent {
85
95
  type: string;
@@ -250,6 +260,8 @@ export function isMidTaskProgressText(text: string): boolean {
250
260
 
251
261
  const SYSTEM_PROMPT = `You are Causyne Agent, an autonomous local AI agent. Your capabilities are the tools actually available in this session. Never invent a capability or claim an action occurred without evidence.
252
262
 
263
+ ${PEER_COLLABORATION_POLICY}
264
+
253
265
  # Your Capabilities
254
266
  Use only tools actually present and permitted in this session. Read each tool result before reporting an outcome. A user message that only asks a question or greets you may be answered directly without calling a tool.
255
267
 
@@ -258,6 +270,11 @@ ${AGENT_USER_POLICY}
258
270
  # Project Conventions
259
271
  Follow the selected project's existing style and architecture. Check dependencies and tool schemas before use. Preserve unrelated behavior.
260
272
 
273
+ # Greenfield Application Scaffolding vs. Legacy Codebase Exploration
274
+ - When the user asks to CREATE or BUILD a new application, web page, 3D model, game, or tool from scratch (e.g., "buatkan", "create", "build", "make", "generate"), focus DIRECTLY on authoring the project in its designated project directory.
275
+ - DO NOT perform exploratory directory listings of the root repository or inspect unrelated legacy projects in the workspace.
276
+ - Immediately initialize the target directory and author the required implementation files (e.g. index.html, style.css, app.js).
277
+
261
278
  # Operational Guidelines & Communication
262
279
  - **Language Reflection**: Dynamically reflect and match the exact language used by the user in their prompt. Respond naturally in that same language without mentioning language policies.
263
280
  - **Ruthless Conciseness**: Answer concisely with fewer than 4 lines unless detail is requested. No preambles ("Okay, I will now...") or postambles ("I have finished..."). One-word answers are best for simple questions.
@@ -269,6 +286,7 @@ Follow the selected project's existing style and architecture. Check dependencie
269
286
 
270
287
  # Task Management & Planning
271
288
  - Use update_plan to create a visible implementation checklist before complex implementation. Create atomic, verb-led, verifiable steps and keep exactly one step in progress.
289
+ - Return known tool calls together when their arguments are already available. Calls execute in order: a checklist update, file write, and readback of that path can share one response. Wait for results before choosing arguments that depend on their contents.
272
290
  - Check off completed TODOs immediately before reporting progress. Do not batch up multiple task completions.
273
291
  - Reconcile and close the todo list when all goal tasks are done. If the user asks you to implement, do not output a separate text-based plan. Just build and display the todo list.
274
292
 
@@ -281,11 +299,11 @@ Follow the selected project's existing style and architecture. Check dependencie
281
299
 
282
300
  # Context Understanding & Searching
283
301
  - Semantic search (or grep) is your MAIN exploration tool. Start with a broad, high-level query.
284
- - MANDATORY: Run multiple searches with different wording in parallel; first-pass results often miss key details.
285
- - Keep searching new areas until you're CONFIDENT nothing important remains. Bias towards not asking the user for help if you can find the answer yourself.
302
+ - Batch independent searches when the task needs them. Gather enough evidence to choose the next useful action; avoid repeating unchanged probes.
303
+ - Expand research when uncertainty or a failed check justifies it. Keep exploration proportional to the user's goal.
286
304
 
287
305
  # Making Code Changes & Execution
288
- - **No Blind Patching**: NEVER edit a file using a patch/edit tool if you have not opened it with the read tool within your last 5 messages. Read the file again to confirm its contents before patching.
306
+ - **No Blind Patching**: Base edits on observed current file contents. Read again when the file changed or the observation is stale; reuse an unchanged verified observation across loop steps.
289
307
  - **Verification Loop**: NEVER assume code works. After making code changes, execute the project-specific build, linting, and type-checking commands (e.g., 'tsc', 'npm run lint', 'pytest'). Identify these commands by examining 'README' files or 'package.json'.
290
308
  - **Code Quality**: Write HIGH-VERBOSITY code. Optimize for clarity. Use meaningful variable names (no 1-letter names like 'n'). Use guard clauses/early returns. Avoid deep nesting.
291
309
  - **No TODOs/Comments**: Do not add comments for trivial code. NEVER use inline comments. Avoid TODO comments—implement the logic instead.
@@ -321,8 +339,8 @@ If asked to perform ANY harmful task, politely decline, state that Causyne exist
321
339
  - **Mode C (Autonomous)**: Work independently within the user's task and selected workspace. Ordinary in-scope actions do not require an approval dialog. Whole-file or directory deletion requires approval. Hard policy blocks, workspace boundaries, and explicit user limits still apply.
322
340
 
323
341
  # Direct API & Automation Policy
324
- - **Prefer REST APIs (curl)**: When interacting with external services (like web, email, chat), prioritize finding and using official REST APIs via \`curl\` or simple scripts.
325
- - **Avoid UI/Browser Automation**: Automating a browser (e.g., Puppeteer/Playwright) is noisy, expensive, and fragile. ONLY use browser automation if a site genuinely has no API. Reading JSON is always better than reading DOM.
342
+ - **Prefer REST APIs (curl) for External Services**: When interacting with external services (like web, email, chat), prioritize finding and using official REST APIs via \`curl\` or simple scripts over browser scraping.
343
+ - **Web/UI Verification Requirement**: Prefer \`browser_act\` preview for static workspace HTML and ES modules; it does not need a separate HTTP server. Use \`sysRunBg\` only when a real application server is required. Do not kill unrelated processes to claim a port. For web development, UI components, and frontend applications, ALWAYS verify your rendered output before concluding. Use \`browser_act\` (preview and snapshot) or \`screenshot\`/\`vision_inspect_ui\` to inspect the visual/DOM state of your web pages. Report DOM inspection separately from visual inspection; only claim visual inspection when you actually receive and inspect image pixels.
326
344
 
327
345
  # Universal Tool Calling & Registry Discipline
328
346
  1. **Strict Registry Adherence**: Use ONLY the tools declared in the catalogue. Invoke tools using exact parameter names specified in the schema. Do not invent or rename parameters.
@@ -528,12 +546,12 @@ export class AgentLoop {
528
546
  : processApprovalScope;
529
547
 
530
548
  this.config = loadConfig();
531
- this.sandbox = new Sandbox();
549
+ this.sandbox = new Sandbox({ workspaceRoot: this.workspaceRoot });
532
550
 
533
551
  // Retire spilled tool outputs past their retention window. Fire-and-forget
534
552
  // at task start rather than on a timer: nothing may run in the background
535
553
  // (rule ZM-01), and a task boundary is often enough for a 7-day window.
536
- try { pruneOutputStore(); } catch (e: any) { /* never block a task on housekeeping */ }
554
+ try { pruneOutputStore(); defaultToolOutputStore.pruneOldOutputs(); } catch (e: any) { /* never block a task on housekeeping */ }
537
555
  try { pruneCheckpointStore(); } catch (e: any) { /* never block a task on housekeeping */ }
538
556
  try { pruneEmbodimentSessions(); } catch (e: any) { /* never block a task on housekeeping */ }
539
557
  // Set by the caller when the user invokes a skill by name. Its body becomes
@@ -574,6 +592,8 @@ export class AgentLoop {
574
592
  this.recentActionSignatures = [];
575
593
  this.consecutiveReadOnlySteps = 0;
576
594
  this.stallGuard = new StallGuardController();
595
+ this.smartToolsGovernor = new SmartToolsGovernor();
596
+ this._smartToolsNudge = null;
577
597
 
578
598
  // Sovereign Progressive Disclosure: which capability packs have entered the
579
599
  // context window for this task. Nothing is disabled — see src/toolPacks.js.
@@ -604,6 +624,7 @@ export class AgentLoop {
604
624
  // entire 300-step budget on a task that was already done.
605
625
  this.gameGuardFired = false;
606
626
  this.webGuardFired = false;
627
+ this.webVerificationScheduled = false;
607
628
  // P6: rendered surfaces this task wrote, for the anti-slop gate to read back.
608
629
  this.webArtifacts = new Set();
609
630
  this.slopReviewAttempts = 0;
@@ -611,7 +632,7 @@ export class AgentLoop {
611
632
 
612
633
  this.gameCascadeState = { active: true, currentStage: 1, stageHistory: [], verificationPassed: false };
613
634
  this.gameToolStats = { godot_act: 0, game_asset_fetch: 0, game_build_html5: 0, last_godot_action: null };
614
- this.webVerificationState = { screenshotTaken: false, browserActUsed: false }; // V8 Transcendence: Anti-Slop Guard
635
+ this.webVerificationState = { screenshotTaken: false, browserActUsed: false, htmlInspected: false }; // V8 Transcendence: Anti-Slop Guard
615
636
 
616
637
  this.abortController = new AbortController();
617
638
 
@@ -688,6 +709,9 @@ export class AgentLoop {
688
709
  ? path.join(os.homedir(), candidate.slice(2))
689
710
  : candidate;
690
711
  this.webArtifacts.add(path.resolve(this.workspaceRoot, expanded));
712
+ this.webVerificationScheduled = false;
713
+ this.webVerificationState.browserActUsed = false;
714
+ this.webVerificationState.screenshotTaken = false;
691
715
  }
692
716
 
693
717
  /**
@@ -874,8 +898,13 @@ export class AgentLoop {
874
898
 
875
899
  const eligible: any[] = [];
876
900
  for (const toolCall of toolCalls) {
901
+ const capacity = Math.min(this.smartToolsGovernor?.inspectionCapacity ?? 2,
902
+ this.efficiencyBudget?.getRemainingActions() ?? 35);
903
+ if (eligible.length >= capacity) break;
877
904
  const functionName = canonicalToolName(toolCall.function.name);
878
- if (!AgentLoop.READ_ONLY_TOOLS.has(functionName)) continue;
905
+ // A later read may verify an earlier write. Never prefetch it across
906
+ // that mutation barrier and accidentally return the pre-edit contents.
907
+ if (!AgentLoop.READ_ONLY_TOOLS.has(functionName)) break;
879
908
  // Prefetch begins before the serial dispatch path. If this tool has a
880
909
  // PreToolUse hook, running it here would create a temporal pre-trust
881
910
  // window where the read happens before the hook can deny it.
@@ -890,6 +919,9 @@ export class AgentLoop {
890
919
  continue; // malformed arguments are the serial loop's business
891
920
  }
892
921
 
922
+ const prefetchedTool = resolveTool(functionName);
923
+ if (validateToolArguments(args, prefetchedTool?.schema?.parameters || prefetchedTool?.schema?.input_schema).length) continue;
924
+
893
925
  // The same guard the serial path applies, applied before anything runs.
894
926
  let validation;
895
927
  try {
@@ -939,6 +971,115 @@ export class AgentLoop {
939
971
  return prefetched;
940
972
  }
941
973
 
974
+ /** Apply host policy to an ACP operation without disabling the peer itself. */
975
+ private resolvePeerFilePath(file: string): string {
976
+ const target = path.resolve(this.workspaceRoot, file);
977
+ let ancestor = target;
978
+ while (true) {
979
+ try { fsSync.lstatSync(ancestor); break; }
980
+ catch (error: unknown) {
981
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
982
+ const parent = path.dirname(ancestor);
983
+ if (parent === ancestor) throw new Error('ACP path was not authorized');
984
+ ancestor = parent;
985
+ }
986
+ }
987
+ const physical = path.resolve(fsSync.realpathSync(ancestor), path.relative(ancestor, target));
988
+ const allowed = this.sandbox.grantAllAccess || this.sandbox.workspacePaths.some((root: string) => {
989
+ try {
990
+ const relative = path.relative(fsSync.realpathSync(root), physical);
991
+ return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
992
+ } catch { return false; }
993
+ });
994
+ if (!allowed) throw new Error('ACP path was not authorized by the selected workspace');
995
+ return target;
996
+ }
997
+
998
+ async authorizePeerOperation(tool: string, args: Record<string, unknown>, id: string, uncertain = false): Promise<boolean> {
999
+ if (this.stopRequested || this.abortController.signal.aborted) return false;
1000
+ const validation = this.sandbox.validate(tool, args);
1001
+ if (!validation.allowed) return false;
1002
+ const hook = await this.runPreToolUse(tool, args, id);
1003
+ if (hook?.denied) return false;
1004
+ const assessment = await coldObserver.evaluateMutation(tool, args, { workspaceRoot: this.workspaceRoot });
1005
+ if (assessment.veto) return false;
1006
+ const needsApproval = uncertain || requiresToolApproval({
1007
+ mode: this.config.autonomyMode || 'C', tool, args,
1008
+ risk: assessment.requiresConfirmation ? 'dangerous' : validation.risk,
1009
+ heavyDownload: false, standingApproval: this.isAlwaysAllowed(tool)
1010
+ });
1011
+ if (needsApproval) {
1012
+ this.emitEvent({ type: 'approval_request', toolCallId: id, tool, args, risk: validation.risk });
1013
+ if (!await this.waitForApproval(id)) return false;
1014
+ }
1015
+ if (this.stopRequested || this.abortController.signal.aborted) return false;
1016
+ auditLog.log({ event: 'peer_operation_authorized', taskId: this.taskId, tool });
1017
+ return true;
1018
+ }
1019
+
1020
+ async requestPeerPermission(request: RequestPermissionRequest): Promise<RequestPermissionResponse['outcome']> {
1021
+ const call = request.toolCall;
1022
+ const raw = call.rawInput && typeof call.rawInput === 'object' && !Array.isArray(call.rawInput)
1023
+ ? call.rawInput as Record<string, unknown> : {};
1024
+ const args = { ...raw };
1025
+ if (!args.path && call.locations?.[0]?.path) args.path = call.locations[0].path;
1026
+ for (const field of ['path', 'file_path', 'filePath', 'filepath', 'absolutePath', 'cwd', 'source', 'destination', 'directory', 'targetFile', 'outputFile', 'outputPath']) {
1027
+ if (typeof args[field] === 'string') {
1028
+ try { args[field] = this.resolvePeerFilePath(args[field] as string); } catch { return { outcome: 'cancelled' }; }
1029
+ }
1030
+ }
1031
+ args.path ??= args.file_path ?? args.filePath ?? args.filepath ?? args.absolutePath;
1032
+ const tool = call.kind === 'read' ? 'fs_read' : call.kind === 'edit' ? 'fs_edit'
1033
+ : call.kind === 'delete' ? 'fs_delete' : call.kind === 'move' ? 'fs_move'
1034
+ : call.kind === 'execute' ? 'sysRun' : 'peer_native';
1035
+ if (tool === 'sysRun' && !args.command && typeof args.cmd === 'string') args.command = args.cmd;
1036
+ const uncertain = !['read', 'search', 'fetch', 'think'].includes(call.kind || '')
1037
+ && (tool === 'peer_native' || (tool === 'sysRun' ? !args.command : !args.path));
1038
+ const option = request.options.find(item => item.kind === 'allow_once');
1039
+ // Never propagate a standing peer grant across sessions or forks.
1040
+ if (!option || !await this.authorizePeerOperation(tool, { ...args, peerTitle: call.title }, `peer:${call.toolCallId}`, uncertain)) {
1041
+ return { outcome: 'cancelled' };
1042
+ }
1043
+ return { outcome: 'selected', optionId: option.optionId };
1044
+ }
1045
+
1046
+ async executePeerFile(tool: 'fs_read' | 'fs_write', file: string, content?: string, options?: { line?: number; limit?: number }): Promise<string> {
1047
+ const target = this.resolvePeerFilePath(file);
1048
+ if (options?.line !== undefined && (!Number.isSafeInteger(options.line) || options.line < 1)) throw new Error('ACP line must be a positive integer');
1049
+ if (options?.limit !== undefined && (!Number.isSafeInteger(options.limit) || options.limit < 1)) throw new Error('ACP limit must be a positive integer');
1050
+ const args = { path: target, ...(tool === 'fs_write' ? { content } : {}),
1051
+ ...(options?.line !== undefined ? { startLine: options.line } : {}),
1052
+ ...(options?.limit !== undefined ? { endLine: (options.line || 1) + options.limit - 1 } : {}) };
1053
+ const id = `peer-file:${randomUUID()}:${tool}`;
1054
+ if (!await this.authorizePeerOperation(tool, args, id)) throw new Error('The requested ACP file operation was not authorized');
1055
+ if (tool === 'fs_write') captureBeforeMutation(tool, args, { taskId: this.taskId, step: this.stepsCompleted });
1056
+ this.efficiencyBudget.recordAction();
1057
+ let result: { success: boolean; error?: string; output?: string };
1058
+ if (tool === 'fs_read') {
1059
+ // ACP expects the actual requested text, not the host tool's paging
1060
+ // warning appended to a silently shortened file.
1061
+ const stat = fsSync.statSync(target);
1062
+ if (stat.size > 4 * 1024 * 1024) throw new Error('ACP text file exceeds the 4 MiB client transfer limit');
1063
+ const bytes = fsSync.readFileSync(target);
1064
+ if (bytes.includes(0)) throw new Error('ACP read_text_file requires a text file');
1065
+ let output = bytes.toString('utf8');
1066
+ if (options?.line !== undefined || options?.limit !== undefined) {
1067
+ const start = Math.max(0, (options.line || 1) - 1);
1068
+ output = output.split('\n').slice(start, options?.limit === undefined ? undefined : start + options.limit).join('\n');
1069
+ }
1070
+ result = { success: true, output };
1071
+ } else {
1072
+ result = await withToolAutonomyMode(this.config.autonomyMode || 'C', () => resolveTool(tool).execute(args, { parentLoop: this, signal: this.abortController.signal })) as typeof result;
1073
+ }
1074
+ const postHook = await this.runPostToolUse(tool, args, result);
1075
+ const success = result.success !== false && !result.error && !postHook?.denied;
1076
+ coldObserver.recordToolOutcome(this.taskId, tool, args, { ...result, success });
1077
+ auditLog.log({ event: 'tool_exec', taskId: this.taskId, tool, success, source: 'acp_client' });
1078
+ if (!success) throw new Error(result.error || postHook?.reason || 'ACP file operation failed');
1079
+ if (tool === 'fs_write') { this.recordWebArtifact(target); clearSysRunCache(); }
1080
+ return typeof result.output === 'string' ? result.output : '';
1081
+ }
1082
+
942
1083
  emitEvent(messageObj: AgentLoopEvent) {
943
1084
  if (this.eventSink && this.eventSink.readyState === 1) {
944
1085
  this.eventSink.send(JSON.stringify({ taskId: this.taskId, ...messageObj }));
@@ -1150,6 +1291,8 @@ export class AgentLoop {
1150
1291
  // ORDER to work in, which saves whole exploratory steps.
1151
1292
  this.gameGuardFired = false;
1152
1293
  this.webGuardFired = false;
1294
+ this.webVerificationScheduled = false;
1295
+ this.webVerificationState = { screenshotTaken: false, browserActUsed: false, htmlInspected: false };
1153
1296
  this.webArtifacts = new Set();
1154
1297
  this.slopReviewAttempts = 0;
1155
1298
  this.slopLastAuditHash = '';
@@ -1402,8 +1545,32 @@ export class AgentLoop {
1402
1545
  this.recentActionSignatures = [];
1403
1546
  this.consecutiveReadOnlySteps = 0;
1404
1547
  this.stallGuard.reset();
1548
+ this.smartToolsGovernor.reset();
1549
+ this._smartToolsNudge = null;
1405
1550
  this.tokenTracker.resetTask();
1551
+ const turnArchetype = determineToolScope(this.currentTaskPrompt || '', this.taskShape).archetype;
1552
+ const efficiency = this.config.efficiency || {};
1553
+ const taskTokenCeiling = Number.isInteger(this.taskTokenLimit) && (this.taskTokenLimit as number) > 0
1554
+ ? (this.taskTokenLimit as number)
1555
+ : this.tokenTracker.budget?.enabled && Number.isFinite(this.tokenTracker.budget?.maxTokensPerTask) && (this.tokenTracker.budget.maxTokensPerTask as number) > 0
1556
+ ? (this.tokenTracker.budget.maxTokensPerTask as number)
1557
+ : Number.isFinite(efficiency.maxTaskTokens) && efficiency.maxTaskTokens > 0
1558
+ ? efficiency.maxTaskTokens
1559
+ : Number.isFinite(efficiency.maxTurnTokens) && efficiency.maxTurnTokens > 0
1560
+ ? efficiency.maxTurnTokens
1561
+ : tokenLimitFor(turnArchetype);
1562
+ this.efficiencyBudget = new UnifiedBudgetEnforcer(
1563
+ Number.isFinite(efficiency.maxTurnTokens) && efficiency.maxTurnTokens > 0
1564
+ ? efficiency.maxTurnTokens
1565
+ : turnTokenLimitFor(turnArchetype),
1566
+ Number.isSafeInteger(efficiency.maxTurnActions) && efficiency.maxTurnActions > 0 ? efficiency.maxTurnActions : actionLimitFor(turnArchetype),
1567
+ taskTokenCeiling
1568
+ );
1569
+ const recoveryPaths = new Set<string>();
1570
+ let modelCallIndex = 0;
1406
1571
  let mediaExplorationRecoveries = 0;
1572
+ let reasoningOnlyRecoveries = 0;
1573
+ let planHandoffRecoveries = 0;
1407
1574
 
1408
1575
  // The core loop governed by Sovereign Human-in-the-Loop Checkpoints
1409
1576
  while (!this.stopRequested) {
@@ -1415,6 +1582,13 @@ export class AgentLoop {
1415
1582
  this.emitEvent({ type: 'status', message: 'Thinking...' });
1416
1583
 
1417
1584
  try {
1585
+ this.smartToolsGovernor.beginModelStep();
1586
+ // Insert at the model boundary, never between one assistant tool-call
1587
+ // message and the matching tool results in a multi-call batch.
1588
+ if (this._smartToolsNudge) {
1589
+ this.messages.push({ role: 'system', content: this._smartToolsNudge });
1590
+ this._smartToolsNudge = null;
1591
+ }
1418
1592
  // --- V8 MEMORY ARCHITECTURE: DECAY → WINDOW → REAL COMPACTION ---
1419
1593
  // The window is no longer only a view over an ever-growing array. Old
1420
1594
  // tool payloads decay into stubs, and anything amputated is physically
@@ -1426,13 +1600,37 @@ export class AgentLoop {
1426
1600
  // 5-Stage Progressive Compaction (Claude Code Architecture / Research Section E):
1427
1601
  // Stage 0 (HLCE Ephemeral Decay) + Stage 2 (Snip >15K tokens / 60K chars) +
1428
1602
  // Stage 1 (Budget Reduction >70%) + Stage 3 (Microcompact) + Stage 4 (Context Collapse >85%)
1603
+ const observationPrune = pruneStaleToolObservations(this.messages, {
1604
+ keepRecent: this.config.keepRecentToolResults ?? 4,
1605
+ minChars: 600,
1606
+ taskId: this.taskId
1607
+ });
1608
+ const argumentPrune = pruneExecutedToolArguments(this.messages, { taskId: this.taskId });
1609
+ for (const saved of argumentPrune.recoveryPaths) recoveryPaths.add(path.resolve(saved));
1610
+ const oversizedPrune = shortenOversizedToolObservations(this.messages, {
1611
+ taskId: this.taskId
1612
+ });
1613
+ for (const message of this.messages) {
1614
+ if (typeof message.spillPath === 'string') recoveryPaths.add(path.resolve(message.spillPath));
1615
+ }
1429
1616
  const compaction = applyProgressiveCompaction(this.messages, MAX_CHAR_POOL, {
1430
- enableEphemeralDecay: true,
1431
- ephemeralKeepRecent: 3,
1432
- ephemeralMinChars: 1200,
1433
- budgetKeepRecent: this.config.keepRecentToolResults ?? 8,
1434
- collapseKeepRecent: 2
1617
+ // historyPruner preserves full output before eliding it. The legacy
1618
+ // decay path cannot promise that recovery, so keep it disabled here.
1619
+ enableEphemeralDecay: false,
1620
+ // The legacy snipper can discard data when a disk spill fails. The
1621
+ // recoverable TypeScript path above owns all oversized tool output.
1622
+ snipOptions: { threshold: Number.MAX_SAFE_INTEGER },
1623
+ budgetKeepRecent: Number.MAX_SAFE_INTEGER,
1624
+ collapseKeepRecent: Number.MAX_SAFE_INTEGER
1435
1625
  });
1626
+ compaction.totalReclaimed += observationPrune.reclaimedChars + oversizedPrune.reclaimedChars + argumentPrune.reclaimedChars;
1627
+ if (argumentPrune.pruned > 0) compaction.stagesFired.push(`executed_argument_archive:${argumentPrune.pruned}`);
1628
+ if (observationPrune.pruned > 0) {
1629
+ compaction.stagesFired.push(`recoverable_observation_decay:${observationPrune.pruned}`);
1630
+ }
1631
+ if (oversizedPrune.pruned > 0) {
1632
+ compaction.stagesFired.push(`recoverable_oversized_output:${oversizedPrune.pruned}`);
1633
+ }
1436
1634
  if (compaction.totalReclaimed > 0) {
1437
1635
  this.debugLog(`progressive compaction reclaimed ${(compaction.totalReclaimed / 1024).toFixed(1)} KB [${compaction.stagesFired.join(', ')}]`);
1438
1636
  auditLog.log({
@@ -1466,7 +1664,10 @@ export class AgentLoop {
1466
1664
  if (splitIndex >= 1) {
1467
1665
  const dropped = this.messages.slice(1, splitIndex + 1);
1468
1666
  if (dropped.length > 0) {
1469
- const compactSummary = buildStructuralSummary(dropped) || describeDroppedMessages(dropped);
1667
+ const compactSummary = buildRecoverableDroppedSummary(
1668
+ dropped,
1669
+ buildStructuralSummary(dropped) || describeDroppedMessages(dropped)
1670
+ );
1470
1671
  const removed = compactInPlace(this.messages, splitIndex, compactSummary);
1471
1672
  this._lastCompactionIndex = null;
1472
1673
  this.debugLog(`compacted ${removed} messages out of the live context`);
@@ -1578,12 +1779,17 @@ export class AgentLoop {
1578
1779
  const lazyPlaybookResult = resolveLazyPlaybooks(
1579
1780
  this.unlockedPacks,
1580
1781
  observedTools,
1581
- this.userPrompt
1782
+ this.currentTaskPrompt || this.userPrompt || ''
1582
1783
  );
1583
1784
  const activePlaybooks = [
1584
1785
  lazyPlaybookResult.fullPlaybooks,
1585
1786
  lazyPlaybookResult.microAnnouncements
1586
1787
  ].filter(Boolean).join('\n\n');
1788
+ auditLog.log({ event: 'smart_tools_context', taskId: this.taskId, step: this.stepsCompleted,
1789
+ archetype: determineToolScope(this.currentTaskPrompt || '', this.taskShape).archetype,
1790
+ toolCount: dynamicTools.length, toolSchemaChars: JSON.stringify(dynamicTools).length,
1791
+ playbookDomains: lazyPlaybookResult.activePlaybookDomains,
1792
+ playbookChars: activePlaybooks.length, planCacheHit: Boolean(this._planMatch) });
1587
1793
 
1588
1794
  // The task brief turns "here are 28 tools" into "here is the order to
1589
1795
  // use them in", which is where whole exploratory steps get saved.
@@ -1736,11 +1942,12 @@ export class AgentLoop {
1736
1942
  ? Number(budget.maxTokensPerDay || 0) : 0;
1737
1943
  const dailyUsed = hardBudget && dailyLimit > 0
1738
1944
  ? (await this.tokenTracker.getDailyUsage()).totalTokens : 0;
1739
- const remainingBudget = hardBudget
1945
+ const configuredRemainingBudget = hardBudget
1740
1946
  ? Math.min(
1741
1947
  taskLimit > 0 ? taskLimit - this.tokenTracker.taskTokens : Infinity,
1742
1948
  dailyLimit > 0 ? dailyLimit - dailyUsed : Infinity
1743
1949
  ) : Infinity;
1950
+ const remainingBudget = Math.min(configuredRemainingBudget, this.efficiencyBudget.getRemainingTokens());
1744
1951
  if (remainingBudget <= 0) {
1745
1952
  this.emitEvent({ type: 'budget_warning', message: 'Token budget reached before the next model call.' });
1746
1953
  break;
@@ -1779,20 +1986,30 @@ export class AgentLoop {
1779
1986
  this.emitEvent({ type: 'agent_activity', activity: 'Thinking…' });
1780
1987
 
1781
1988
  const planStepStart = performance.now();
1989
+ const nativeControl = new AbortController();
1990
+ let nativeCheckpoint: EfficiencyCheckpoint | null = null;
1991
+ const invocation = ++modelCallIndex;
1782
1992
  const response = await this.llm.chat(prunedMessages, {
1783
1993
  taskId: this.taskId,
1784
1994
  conversationId: this.memoryManager?.sessionId || this.taskId,
1785
1995
  taskIntent: isLaunchOnlyPrompt(this.currentTaskPrompt || this.userPrompt || '') ? 'launch' : 'general',
1786
1996
  taskArchetype: determineToolScope(this.currentTaskPrompt || this.userPrompt || '', this.taskShape).archetype,
1787
1997
  maxTokensThisCall: Number.isFinite(remainingBudget) ? remainingBudget : undefined,
1788
- tokenLimit: Number.isFinite(remainingBudget) ? remainingBudget : Infinity,
1998
+ tokenBudgetBasis: Number.isFinite(configuredRemainingBudget) ? 'total' : 'noncached',
1999
+ tokenLimit: Number.isFinite(remainingBudget) && remainingBudget > 0
2000
+ ? Math.min(this.efficiencyBudget.maxTurnTokens, remainingBudget) : this.efficiencyBudget.maxTurnTokens,
2001
+ maxNativeActions: this.efficiencyBudget.getRemainingActions(),
1789
2002
  workspaceRoot: this.workspaceRoot,
2003
+ onPeerPermission: (request: RequestPermissionRequest) => this.requestPeerPermission(request),
2004
+ onPeerFileRead: (file: string, options?: { line?: number; limit?: number }) => this.executePeerFile('fs_read', file, undefined, options),
2005
+ onPeerFileWrite: async (file: string, content: string) => { await this.executePeerFile('fs_write', file, content); },
1790
2006
  tools: dynamicTools,
1791
2007
  // IARS couples escalation to a wider search. Bounded so a stuck task
1792
2008
  // cannot climb into randomness across repeated escalations.
1793
2009
  temperature: Math.min(1, this.taskTemperature + uncertaintyTemperatureDelta),
1794
2010
  coreToolCount: dynamicTools.filter((t: any) => isCoreTool(t.name)).length,
1795
- signal: this.abortController?.signal,
2011
+ signal: this.abortController?.signal
2012
+ ? AbortSignal.any([this.abortController.signal, nativeControl.signal]) : nativeControl.signal,
1796
2013
  onReasoningChunk: (chunk: string) => {
1797
2014
  if (this.stopRequested || this.abortController?.signal?.aborted) return;
1798
2015
  if (!thoughtStartedAt) thoughtStartedAt = Date.now();
@@ -1818,6 +2035,17 @@ export class AgentLoop {
1818
2035
  onNativeAction: (action: any) => {
1819
2036
  if (this.stopRequested || this.abortController?.signal?.aborted) return;
1820
2037
  if (!action || typeof action.name !== 'string') return;
2038
+ auditLog.log({ event: 'native_action', taskId: this.taskId,
2039
+ provider: this.config.provider || 'unknown', tool: action.name, status: action.status,
2040
+ ...(action.id ? { actionId: action.id } : {}) });
2041
+ if (action.status === 'running') {
2042
+ try {
2043
+ this.efficiencyBudget.recordAction(`${invocation}:${action.id || `${action.name}:${action.detail || ''}`}`);
2044
+ } catch (error: unknown) {
2045
+ if (error instanceof EfficiencyCheckpoint) { nativeCheckpoint = error; nativeControl.abort(); }
2046
+ return;
2047
+ }
2048
+ }
1821
2049
  const nativeCode = codeProgressFromAction(
1822
2050
  action.name,
1823
2051
  { ...(action.parameters && typeof action.parameters === 'object' ? action.parameters : {}),
@@ -1838,12 +2066,18 @@ export class AgentLoop {
1838
2066
  this.emitEvent({ type: 'status', message: `Acting: ${action.name}${detail}` });
1839
2067
  this.emitEvent({ type: 'agent_activity', activity: `Acting: ${action.name}${detail}` });
1840
2068
  } else if (action.status === 'completed') {
1841
- this.emitEvent({ type: 'notice', tone: 'muted', nativeStep: true, message: `Antigravity ${action.name}${detail}` });
2069
+ this.emitEvent({ type: 'notice', tone: 'muted', nativeStep: true, message: `${this.config.provider || 'Provider'} ${action.name}${detail}` });
1842
2070
  } else if (action.status === 'failed') {
1843
- this.emitEvent({ type: 'warning', message: `Antigravity could not ${action.name}${detail}` });
2071
+ this.emitEvent({ type: 'warning', message: `${this.config.provider || 'Provider'} could not ${action.name}${detail}` });
1844
2072
  }
1845
2073
  }
1846
- }).finally(() => nativeCodeObserver.dispose());
2074
+ }).catch((error: unknown) => {
2075
+ if (nativeCheckpoint && error && typeof error === 'object' && 'partialUsage' in error) {
2076
+ Object.assign(nativeCheckpoint, { partialUsage: error.partialUsage });
2077
+ }
2078
+ throw nativeCheckpoint || error;
2079
+ })
2080
+ .finally(() => nativeCodeObserver.dispose());
1847
2081
  this._totalPlanMs = (this._totalPlanMs || 0) + (performance.now() - planStepStart);
1848
2082
 
1849
2083
  if (this.stopRequested || this.abortController?.signal?.aborted) {
@@ -1880,6 +2114,8 @@ export class AgentLoop {
1880
2114
  promptTokens: response.usage.promptTokens,
1881
2115
  completionTokens: response.usage.completionTokens,
1882
2116
  cachedPromptTokens: response.usage.cachedPromptTokens || 0,
2117
+ uncachedPromptTokens: response.usage.uncachedPromptTokens,
2118
+ noncachedTokens: noncachedTokens(response.usage),
1883
2119
  measurement: response.usage.measurement || 'unspecified',
1884
2120
  cacheMeasurement: response.usage.cacheMeasurement || 'unspecified',
1885
2121
  costBasis: /^(acp(?:\/|$)|antigravity$|agy$)/i.test(String(this.config.provider || ''))
@@ -1888,6 +2124,10 @@ export class AgentLoop {
1888
2124
  response.usage.promptTokens, response.usage.completionTokens, response.usage
1889
2125
  )
1890
2126
  });
2127
+ this.efficiencyBudget.recordUsage(response.usage);
2128
+ for (const action of response.externalActions || []) {
2129
+ this.efficiencyBudget.recordAction(`${invocation}:${action.id || `${action.name}:${action.detail || ''}`}`);
2130
+ }
1891
2131
 
1892
2132
  const cachedTokens = response.usage.cachedPromptTokens || 0;
1893
2133
  if (cachedTokens > 0) {
@@ -1930,6 +2170,41 @@ export class AgentLoop {
1930
2170
  break;
1931
2171
  }
1932
2172
 
2173
+ // The host owns verification policy. A model cannot substitute repeated
2174
+ // HTTP checks for rendering, and adapters must not contradict this gate.
2175
+ if (!response.toolCalls?.length && !this.webVerificationScheduled
2176
+ && !this.webVerificationState.browserActUsed && !this.webVerificationState.screenshotTaken
2177
+ && isWebIntent(this.currentTaskPrompt || this.userPrompt || '')
2178
+ && !isLaunchOnlyPrompt(this.currentTaskPrompt || this.userPrompt || '')
2179
+ && !isPlanningOnlyRequest(this.currentTaskPrompt || this.userPrompt || '')) {
2180
+ const files: Array<{ path: string; content: string }> = [];
2181
+ for (const candidate of this.webArtifacts) {
2182
+ if (files.length >= 50) break;
2183
+ try {
2184
+ const stat = fsSync.lstatSync(candidate);
2185
+ if (stat.isFile() && stat.size <= 512_000) files.push({ path: candidate, content: fsSync.readFileSync(candidate, 'utf8') });
2186
+ } catch { /* Deleted artifacts cannot be verified. */ }
2187
+ }
2188
+ const entry = files.find(file => /\.html?$/i.test(file.path));
2189
+ if (entry && analyzeFiles(files).verdict !== 'slop') {
2190
+ const { groupStatus } = await import('./provisioning/capabilityProvisioner.js');
2191
+ const { isBrowserRuntimeInstalled } = await import('./browser/browserRuntime.js');
2192
+ if (groupStatus('browser').state === 'ready' && isBrowserRuntimeInstalled()) {
2193
+ this.webVerificationScheduled = true;
2194
+ this.webGuardFired = true;
2195
+ response.toolCalls = [{ id: `host-verify-${this.stepsCompleted}`, type: 'function', function: {
2196
+ name: 'browser_act', arguments: JSON.stringify({ actions: [
2197
+ { type: 'preview', filePath: path.relative(this.workspaceRoot, entry.path) },
2198
+ { type: 'snapshot' }
2199
+ ] })
2200
+ } }];
2201
+ response.content = '';
2202
+ auditLog.log({ event: 'host_verification_scheduled', taskId: this.taskId, tool: 'browser_act' });
2203
+ this.emitEvent({ type: 'status', message: 'Inspecting the rendered page through Causyne Browser…' });
2204
+ }
2205
+ }
2206
+ }
2207
+
1933
2208
  // Add assistant response to history. This is the ONLY place the turn is
1934
2209
  // recorded — the completion and guard branches below used to push it a
1935
2210
  // second time, duplicating every finished turn in the history.
@@ -1938,7 +2213,7 @@ export class AgentLoop {
1938
2213
  role: 'assistant',
1939
2214
  // An assistant message with neither text nor tool calls is rejected by
1940
2215
  // some providers, so a terminal turn always carries something.
1941
- content: response.content || (hasToolCalls ? '' : 'Task completed.')
2216
+ content: hasToolCalls ? '' : (response.content || 'No final response was provided.')
1942
2217
  };
1943
2218
  if (hasToolCalls) {
1944
2219
  assistantMsg.tool_calls = response.toolCalls;
@@ -1966,9 +2241,8 @@ export class AgentLoop {
1966
2241
  }
1967
2242
  this.messages.push(assistantMsg);
1968
2243
 
1969
- if (response.content && hasToolCalls) {
1970
- this.emitEvent({ type: 'agent_message', content: response.content });
1971
- }
2244
+ // Prose accompanying pending actions is not an execution result.
2245
+ // Tool events provide progress; terminal claims pass completion gates below.
1972
2246
 
1973
2247
  const externalActions = Array.isArray((response as any).externalActions)
1974
2248
  ? (response as any).externalActions
@@ -1989,8 +2263,12 @@ export class AgentLoop {
1989
2263
  // A native action's name is not evidence that a model inspected
1990
2264
  // pixels. Keep visual verification false unless a real image result
1991
2265
  // has reached a vision-capable provider.
1992
- if (['browser_get_dom', 'read_browser_page'].includes(actionName)) {
1993
- this.webVerificationState.browserActUsed = true;
2266
+ // A native action label alone carries no rendered-page evidence.
2267
+ // The shared host inspection below verifies its resulting artifacts.
2268
+ if (['fs_read', 'read_file', 'view_file', 'viewfile', 'view_file_content'].includes(actionName) && detailPath) {
2269
+ if (/\.(html|htm|css|jsx|tsx|vue|svelte)$/i.test(detailPath)) {
2270
+ this.webVerificationState.htmlInspected = true;
2271
+ }
1994
2272
  }
1995
2273
  }
1996
2274
  }
@@ -2002,6 +2280,27 @@ export class AgentLoop {
2002
2280
  const taskPrompt = (this.currentTaskPrompt || this.userPrompt || '').trim();
2003
2281
  const isActionable = isActionableTaskPrompt(taskPrompt);
2004
2282
 
2283
+ // A peer may have completed searches or a plan artifact while still
2284
+ // waiting for its own UI's Proceed button. Those actions do not
2285
+ // satisfy an implementation request in the enclosing Causyne loop.
2286
+ if (isActionable && !isPlanningOnlyRequest(taskPrompt) && isPlanReviewHandoff(contentText)) {
2287
+ if (planHandoffRecoveries++ > 0) {
2288
+ this.emitEvent({ type: 'error', message: 'The selected peer stopped for plan review again instead of implementing the request. Work remains unfinished.' });
2289
+ this.memoryManager.saveHistory(this.messages);
2290
+ break;
2291
+ }
2292
+ this._implementationPlanRequired = false;
2293
+ this.messages.push({ role: 'system', content:
2294
+ '[IMPLEMENTATION CONTINUATION] The user requested implementation, not a plan-only deliverable. '
2295
+ + 'Continue from the useful evidence and plan already gathered. Use update_plan for the checklist and invoke the next Causyne execution tool now. '
2296
+ + 'There is no peer Proceed button in this interface. Ask only through request_decision if a genuinely unresolved consequential choice blocks progress; '
2297
+ + 'routine details with a safe default do not require another approval. Do not repeat completed searches or write another plan artifact.' });
2298
+ this.emitEvent({ type: 'status', message: 'Continuing the requested implementation from the existing plan…' });
2299
+ auditLog.log({ event: 'plan_handoff_recovered', taskId: this.taskId, provider: this.config.provider });
2300
+ this.memoryManager.saveHistory(this.messages);
2301
+ continue;
2302
+ }
2303
+
2005
2304
  if (isActionable && isGenericHandoffResponse(contentText) && (hasExternalActions || this.stepsCompleted > 0)) {
2006
2305
  this.emitEvent({ type: 'error', message: 'The provider returned a generic handoff after tool activity. The requested outcome was not verified; no completion is recorded.' });
2007
2306
  this.memoryManager.saveHistory(this.messages);
@@ -2215,21 +2514,14 @@ export class AgentLoop {
2215
2514
  }
2216
2515
 
2217
2516
  // Web Visual Validation Guard (Anti-Slop / Transcendence)
2218
- const isWebTask = !isLaunchOnlyPrompt(taskPrompt) && isWebIntent(taskPrompt);
2219
-
2220
- if (isWebTask && !this.webGuardFired && this.stepsCompleted > 0) {
2221
- const hasVision = this.llm.supportsVision !== false;
2222
- // Finding D-6: this guard used to demand `screenshot` /
2223
- // `vision_inspect_ui` unconditionally. Both need the browser and
2224
- // capture packages, which are provisioned only after the user
2225
- // consents — so on a fresh install the guard was ordering the agent
2226
- // to use a tool that could not run. Ask for the capability once;
2227
- // if it was declined, fall through to the path that needs nothing.
2228
- let visionReady = false;
2229
- let visionDeclined = false;
2230
- let browserReady = false;
2231
- let browserDeclined = false;
2232
- let browserRuntimeError = '';
2517
+ const isWebTask = !isLaunchOnlyPrompt(taskPrompt) && !isPlanningOnlyRequest(taskPrompt) && isWebIntent(taskPrompt);
2518
+ let browserReady = false;
2519
+ let browserDeclined = false;
2520
+ let browserRuntimeError = '';
2521
+ let visionReady = false;
2522
+ let visionDeclined = false;
2523
+
2524
+ if (isWebTask) {
2233
2525
  try {
2234
2526
  const { groupStatus, isGroupDeclined } = await import('./provisioning/capabilityProvisioner.js');
2235
2527
  visionReady = groupStatus('vision').state === 'ready';
@@ -2244,6 +2536,10 @@ export class AgentLoop {
2244
2536
  }
2245
2537
  }
2246
2538
  } catch (e: any) { /* treat as not ready */ }
2539
+ }
2540
+
2541
+ if (isWebTask && !this.webGuardFired && this.stepsCompleted > 0) {
2542
+ const hasVision = this.llm.supportsVision !== false;
2247
2543
  let webGuardMsg = '';
2248
2544
 
2249
2545
  if (browserRuntimeError) {
@@ -2266,7 +2562,7 @@ export class AgentLoop {
2266
2562
  this.emitEvent({ type: 'status', message: '⚡ Anti-Slop Check: Visual/semantic verification recommended.' });
2267
2563
  this.messages.push({ role: 'system', content: webGuardMsg });
2268
2564
  this.memoryManager.saveHistory(this.messages);
2269
- if (browserReady || (hasVision && visionReady)) {
2565
+ if (!this.webVerificationState.htmlInspected || browserReady || (hasVision && visionReady)) {
2270
2566
  continue;
2271
2567
  }
2272
2568
  }
@@ -2275,9 +2571,16 @@ export class AgentLoop {
2275
2571
  // Tool availability and a completed plan are not evidence of visual
2276
2572
  // inspection. A failed browser/capture attempt must not become a
2277
2573
  // successful task merely because the provider says "verified".
2278
- if (isWebTask && this.stepsCompleted > 0
2279
- && !this.webVerificationState.browserActUsed
2280
- && !this.webVerificationState.screenshotTaken) {
2574
+ const isVerified = Boolean(
2575
+ this.webVerificationState.browserActUsed ||
2576
+ this.webVerificationState.screenshotTaken ||
2577
+ (!browserReady && this.webVerificationState.htmlInspected)
2578
+ );
2579
+ if (isWebTask && !browserReady && this.webVerificationState.htmlInspected
2580
+ && !this.webVerificationState.browserActUsed && !this.webVerificationState.screenshotTaken) {
2581
+ this.emitEvent({ type: 'notice', message: 'Source inspection completed. Rendered-page and visual verification were not performed because the browser runtime is unavailable.' });
2582
+ }
2583
+ if (isWebTask && this.stepsCompleted > 0 && !isVerified) {
2281
2584
  this.emitEvent({
2282
2585
  type: 'error',
2283
2586
  message: 'The web files may have changed, but rendered-page verification did not succeed. The task remains unverified; no completion is recorded.'
@@ -2424,6 +2727,41 @@ export class AgentLoop {
2424
2727
  }
2425
2728
 
2426
2729
  let args: any = repair.args;
2730
+ const schemaErrors = validateToolArguments(args, toolSchema);
2731
+ if (schemaErrors.length) {
2732
+ const diagnostic = generateSelfRepairDiagnostic(functionName, args, schemaErrors.join('; '), toolSchema);
2733
+ this.messages.push({ role: 'tool', tool_call_id: toolCall.id, name: functionName,
2734
+ content: JSON.stringify({ ...diagnostic, code: 'INVALID_TOOL_ARGUMENTS', expectedSchema: toolSchema }) });
2735
+ this.emitEvent({ type: 'step_error', tool: functionName, error: schemaErrors.join('; '), toolCallId: toolCall.id });
2736
+ auditLog.log({ event: 'tool_argument_validation_failed', taskId: this.taskId, tool: functionName });
2737
+ continue;
2738
+ }
2739
+
2740
+ // Introspection Attractor Loop Breaker: Protect Causyne Agent runtime files from accidental self-debugging
2741
+ if (['fs_read', 'fs_search', 'codebase_search', 'grep_search', 'code_searcher'].includes(functionName)) {
2742
+ const targetStr = String(args?.path || args?.query || args?.searchPath || '');
2743
+ const isAgentDevTask = /\b(causyne|agentLoop|smartToolsUse|toolSelfRepair)\b/i.test(this.currentTaskPrompt || this.userPrompt || '');
2744
+ if (!isAgentDevTask && (targetStr.includes('src/smartToolsUse') || targetStr.includes('src/agentLoop') || targetStr.includes('src/tools/generateMediaViaApi'))) {
2745
+ this.messages.push({
2746
+ role: 'tool',
2747
+ tool_call_id: toolCall.id,
2748
+ name: functionName,
2749
+ content: JSON.stringify({
2750
+ success: false,
2751
+ error: 'Introspection Blocked: Do not inspect Causyne Agent internal runtime files during application tasks. Fulfill the user request directly in the target directory.'
2752
+ })
2753
+ });
2754
+ continue;
2755
+ }
2756
+ }
2757
+
2758
+ const phaseAdmission = this.smartToolsGovernor.interceptAction(functionName, args || {});
2759
+ if (!phaseAdmission.allowed) {
2760
+ this.messages.push({ role: 'tool', tool_call_id: toolCall.id, name: functionName,
2761
+ content: JSON.stringify({ success: false, checkpoint: 'synthesis', error: phaseAdmission.reason }) });
2762
+ auditLog.log({ event: 'smart_tools_checkpoint', taskId: this.taskId, tool: functionName, phase: 'synthesis' });
2763
+ continue;
2764
+ }
2427
2765
  if (repair.repaired && repair.repairs.length > 0) {
2428
2766
  this.debugLog(`[TOOL SELF-REPAIR] Healed tool call '${functionName}': ${repair.repairs.join(', ')}`);
2429
2767
  }
@@ -2499,10 +2837,10 @@ export class AgentLoop {
2499
2837
  break;
2500
2838
  }
2501
2839
 
2502
- if (isAuthoringTask && this.stallGuard.distinctInspectionCount === 12) {
2840
+ if (isAuthoringTask && (this.stallGuard.distinctInspectionCount === 3 || this.stallGuard.distinctInspectionCount === 6)) {
2503
2841
  this.messages.push({
2504
2842
  role: 'system',
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.]`
2843
+ 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.]`
2506
2844
  });
2507
2845
  }
2508
2846
 
@@ -2561,7 +2899,11 @@ export class AgentLoop {
2561
2899
 
2562
2900
  // 4-Layer Security Sandbox Validation
2563
2901
  // 2. Sandbox Security Validation (CRITICAL FIX: Prevent Infinite Loop on Block)
2564
- const validation = this.sandbox.validate(functionName, args);
2902
+ let validation = this.sandbox.validate(functionName, args);
2903
+ if (!validation.allowed && /^Path outside allowed workspace:/.test(validation.reason || '')
2904
+ && isOutputRecoveryRead(functionName, args.path, recoveryPaths)) {
2905
+ validation = { allowed: true, risk: 'safe', reason: 'Read exact tool output referenced by this session' };
2906
+ }
2565
2907
  if (!validation.allowed) {
2566
2908
  this.consecutiveBlockedActions++;
2567
2909
 
@@ -2798,6 +3140,7 @@ export class AgentLoop {
2798
3140
  // errors. It only rewinds reasoning; it never replays side effects.
2799
3141
  let result;
2800
3142
  let duration;
3143
+ this.efficiencyBudget.recordAction();
2801
3144
 
2802
3145
  try {
2803
3146
  const startTime = Date.now();
@@ -2876,16 +3219,26 @@ export class AgentLoop {
2876
3219
  this.recordWebArtifact(args.path || args.file_path);
2877
3220
  }
2878
3221
 
3222
+ if (result && result.success !== false && !result.error && ['fs_read', 'view_file', 'read_file'].includes(functionName)) {
3223
+ const filePath = String(args.path || args.file_path || args.AbsolutePath || args.target || '');
3224
+ if (/\.(html|htm|css|jsx|tsx|vue|svelte)$/i.test(filePath)) {
3225
+ this.webVerificationState.htmlInspected = true;
3226
+ }
3227
+ }
3228
+
2879
3229
  if (['screenshot', 'vision_inspect_ui'].includes(functionName) && this.llm.supportsVision !== false && result?.success === true && result?._is_image_marker === true) {
2880
3230
  this.webVerificationState.screenshotTaken = true;
2881
3231
  }
2882
3232
  if (functionName === 'browser_act' && result?.success === true) {
2883
3233
  const browserResults = Array.isArray(result.data) ? result.data : [];
2884
- if (browserResults.some((item: any) => ['snapshot', 'scrape'].includes(item?.action))) {
3234
+ if (browserResults.some((item: any) => ['snapshot', 'scrape'].includes(item?.action)
3235
+ && Array.isArray(item?.data?.runtimeErrors) && item.data.runtimeErrors.length === 0)) {
2885
3236
  this.webVerificationState.browserActUsed = true;
2886
3237
  }
2887
3238
  }
2888
3239
 
3240
+ if (result?.success === true && ['fs_write', 'fs_edit', 'fs_delete', 'fs_move', 'MultiEdit'].includes(functionName)) clearSysRunCache();
3241
+
2889
3242
  // The journal is the observer's own record of what actually ran. It
2890
3243
  // is written only after post-hook review, so a formatter that rejects
2891
3244
  // a write is remembered as a failure rather than a success.
@@ -3050,6 +3403,12 @@ export class AgentLoop {
3050
3403
  }
3051
3404
  }
3052
3405
 
3406
+ // SmartToolsUse tracks actual local tool calls, without denying
3407
+ // useful inspection during long research or code tasks.
3408
+ const phaseNudge = this.smartToolsGovernor.observe(functionName, args || {}, result);
3409
+ if (phaseNudge) this._smartToolsNudge = phaseNudge;
3410
+ else if (this.smartToolsGovernor.snapshot().phase === 'execution') this._smartToolsNudge = null;
3411
+
3053
3412
  // Feed result back to LLM (4. OBSERVE)
3054
3413
  if (result && result._is_image_marker) {
3055
3414
  if (!this.llm.supportsVision) {
@@ -3110,80 +3469,45 @@ export class AgentLoop {
3110
3469
  // Per tool, not one number for all of them. A build log and a
3111
3470
  // source file are not equally worth their space in the window.
3112
3471
  const MAX_RESULT_CHARS = resultCapFor(functionName);
3472
+ const originalFingerprint = createHash('sha256').update(resultString).digest('hex');
3113
3473
  let spill = null;
3114
-
3115
- if (resultString.length > MAX_RESULT_CHARS) {
3116
- // A1: spill the WHOLE result to disk before shortening it. The
3117
- // previous code threw the overflow away, so the only way back to
3118
- // it was re-running the tool — a second full execution and a
3119
- // second full-size result in the window. Now the bytes survive
3120
- // behind a path and recovery is one bounded read.
3121
- // The raw result, not JSON.stringify(result): JSON escapes every
3122
- // newline, which would land a large payload on a single line and
3123
- // make the fs_read/ripgrep recovery route we advertise useless.
3124
- spill = spillToolResult(result, {
3125
- taskId: this.taskId,
3126
- step: this.stepsCompleted,
3127
- tool: functionName
3128
- });
3129
- const TRUNCATION_NOTICE = buildSpillNotice(spill);
3130
-
3131
- const truncatedResult: any = {};
3132
- // Budget shared across every oversized string field on the result.
3133
- let budget = MAX_RESULT_CHARS - 2000;
3134
-
3135
- for (const [key, value] of Object.entries(result)) {
3136
- if (typeof value === 'string' && value.length > 500) {
3137
- const allowance = Math.max(0, Math.min(value.length, budget));
3138
- budget -= allowance;
3139
- truncatedResult[key] = allowance < value.length
3140
- ? value.substring(0, allowance) + TRUNCATION_NOTICE
3141
- : value;
3142
- } else if (value !== null && typeof value === 'object') {
3143
- const serialized = JSON.stringify(value);
3144
- if (serialized.length > budget) {
3145
- truncatedResult[key] = spill
3146
- ? `[${key} omitted here: ${(serialized.length / 1024).toFixed(1)} KB. The complete result is saved at ${spill.path} — read or search that file rather than re-running.]`
3147
- : `[${key} omitted: ${(serialized.length / 1024).toFixed(1)} KB. Re-run with narrower arguments if you need it.]`;
3148
- } else {
3149
- budget -= serialized.length;
3150
- truncatedResult[key] = value;
3151
- }
3152
- } else {
3153
- truncatedResult[key] = value;
3474
+ if (resultString.length > Math.min(MAX_RESULT_CHARS, 2500)) {
3475
+ const document = renderSpillDocument(result, { taskId: this.taskId, step: this.stepsCompleted, tool: functionName });
3476
+ const stored = processToolOutputWithStore(this.taskId, toolCall.id, document);
3477
+ if (stored.isTruncated && stored.diskPath) {
3478
+ spill = { path: stored.diskPath };
3479
+ resultString = JSON.stringify({
3480
+ ...(typeof result?.success === 'boolean' ? { success: result.success } : {}),
3481
+ ...(typeof result?.error === 'string' ? { error: result.error.slice(0, 500) } : {}),
3482
+ output: stored.contentForModel
3483
+ });
3484
+ } else if (document.length > 2500) {
3485
+ // Compatibility recovery store if the primary store is unavailable.
3486
+ // spillToolResult preserves the full document; never truncate on failure.
3487
+ const fallback = spillToolResult(result, { taskId: this.taskId, step: this.stepsCompleted, tool: functionName });
3488
+ if (fallback) {
3489
+ spill = fallback;
3490
+ resultString = JSON.stringify({
3491
+ ...(typeof result?.success === 'boolean' ? { success: result.success } : {}),
3492
+ output: document.slice(0, 1000) + buildDecayPointer(fallback) + document.slice(-500)
3493
+ });
3154
3494
  }
3155
3495
  }
3156
-
3157
- resultString = JSON.stringify(truncatedResult);
3158
3496
  }
3159
3497
 
3160
- // B5 — OBSERVATION COMPACTION.
3161
- //
3162
- // ARC Prize measured the same GPT-6 Astra weights at 62.7% under a
3163
- // note-passing harness and 99.9% under one that compacts and reuses
3164
- // prior work — with 49% FEWER tokens. Re-reading a file the agent
3165
- // already read, or re-listing an unchanged directory, pays full
3166
- // price for bytes that are verbatim identical to bytes already in
3167
- // the window.
3168
- //
3169
- // Replacing the repeat with a pointer is not a loss of information:
3170
- // "identical to step N" is strictly MORE informative than the bytes
3171
- // alone, because it tells the model the thing did not change —
3172
- // which after an edit is exactly the question it is asking.
3173
- //
3174
- // Only payloads worth the trade are folded. A small `{"success":true}`
3175
- // ack costs less than the pointer that would replace it, and every
3176
- // Plan updates would otherwise collide with unrelated plan updates.
3498
+ // Fold identical bytes without treating them as proof of external state.
3177
3499
  const OBSERVATION_FOLD_FLOOR = 600;
3178
3500
  if (resultString.length >= OBSERVATION_FOLD_FLOOR) {
3179
- const digest = createHash('sha256').update(resultString).digest('hex');
3501
+ const digest = originalFingerprint;
3180
3502
  const seenAt = this._observationDigests.get(digest);
3181
3503
  if (seenAt !== undefined) {
3182
3504
  resultString = JSON.stringify({
3183
- success: true,
3184
- unchanged: true,
3185
- output: `Identical to the result of step ${seenAt} — nothing has changed since. `
3186
- + `That earlier result is still in your context; re-read it there rather than asking again.`
3505
+ ...(result && typeof result.success === 'boolean' ? { success: result.success } : {}),
3506
+ identicalResult: true,
3507
+ output: `The serialized tool response matches step ${seenAt}. This does not prove external state is unchanged. `
3508
+ + (spill
3509
+ ? `Full output is saved at ${spill.path}; read a relevant range if needed.`
3510
+ : 'The earlier response may have left the active context; make a targeted read if its details are needed.')
3187
3511
  });
3188
3512
  } else {
3189
3513
  this._observationDigests.set(digest, this.stepsCompleted + 1);
@@ -3253,14 +3577,45 @@ export class AgentLoop {
3253
3577
  cachedPromptTokens: usage.cachedPromptTokens || 0,
3254
3578
  measurement: 'provider_reported_partial', costBasis: 'external_subscription_unavailable'
3255
3579
  });
3580
+ try { this.efficiencyBudget.recordUsage(usage); }
3581
+ catch (checkpoint: unknown) {
3582
+ if (checkpoint instanceof EfficiencyCheckpoint) e = checkpoint;
3583
+ else throw checkpoint;
3584
+ }
3256
3585
  }
3257
3586
  }
3258
- if (e?.code === 'AGY_TOKEN_BUDGET' || e?.code === 'TASK_TOKEN_BUDGET' || e?.code === 'PROVIDER_TOKEN_BUDGET') {
3587
+ if (e instanceof EfficiencyCheckpoint) {
3588
+ this.messages.push({ role: 'system', content: `[Unfinished task checkpoint] ${e.message}` });
3589
+ this.memoryManager.saveHistory(this.messages);
3590
+ this.emitEvent({ type: 'budget_warning', message: e.message });
3591
+ auditLog.log({ event: 'efficiency_checkpoint', taskId: this.taskId, reason: e.reason,
3592
+ ...this.efficiencyBudget.snapshot() });
3593
+ break;
3594
+ }
3595
+ if (e?.code === 'AGY_TOKEN_BUDGET' || e?.code === 'TASK_TOKEN_BUDGET' || e?.code === 'PROVIDER_TOKEN_BUDGET'
3596
+ || e?.code === 'AGY_NATIVE_ACTION_BUDGET' || e?.code === 'AGY_DESKTOP_TASK_LIMIT') {
3597
+ this.messages.push({ role: 'system', content: `[Unfinished task checkpoint] ${e.message}` });
3598
+ this.memoryManager.saveHistory(this.messages);
3259
3599
  this.emitEvent({ type: 'budget_warning', message: e.message });
3260
3600
  auditLog.log({ event: 'task_stopped_on_budget', taskId: this.taskId,
3261
3601
  used: this.tokenTracker.taskTokens, limit: e.tokenLimit || this.tokenTracker.budget?.maxTokensPerTask || 0 });
3262
3602
  break;
3263
3603
  }
3604
+ if (e?.code === 'PROVIDER_REASONING_ONLY' && e.continuationSafe === true && reasoningOnlyRecoveries++ === 0) {
3605
+ this.messages.push({ role: 'system', content:
3606
+ '[Response recovery] The previous turn contained reasoning but no executable tool call or user response. '
3607
+ + 'Continue from the existing draft in this session. Emit the next actual Causyne tool call with all required arguments. '
3608
+ + 'Do not repeat searches, dependency probes, or prior actions. Do not claim completion until a tool result verifies it. '
3609
+ + 'If a provider key, balance, or user decision is required, report that precise blocker.' });
3610
+ this.memoryManager.saveHistory(this.messages);
3611
+ this.emitEvent({ type: 'notice', message: 'The peer returned reasoning without an action; continuing once from its existing session.' });
3612
+ auditLog.log({ event: 'reasoning_only_recovery', taskId: this.taskId, recovery: reasoningOnlyRecoveries });
3613
+ continue;
3614
+ }
3615
+ if (e?.code === 'PROVIDER_REASONING_ONLY') {
3616
+ this.emitEvent({ type: 'error', message: 'The peer returned reasoning without an executable action or final answer. The task remains unfinished. The saved session is available; no further automatic retry will spend your budget.' });
3617
+ break;
3618
+ }
3264
3619
  if (e?.code === 'AGY_EXPLORATION_LOOP' || e?.code === 'AGENT_EXPLORATION_LOOP' || e?.code === 'STALL_EXPLORATION_LOOP') {
3265
3620
  auditLog.log({ event: 'media_exploration_checkpoint', taskId: this.taskId,
3266
3621
  inspectionCount: e.inspectionCount, recovery: mediaExplorationRecoveries });
@@ -3395,6 +3750,7 @@ export class AgentLoop {
3395
3750
 
3396
3751
  // V5: Classify errors for intelligent retry decisions
3397
3752
  classifyError(error: any) {
3753
+ if (error?.code === 'PROVIDER_NO_PROGRESS') return 'fatal';
3398
3754
  if (error?.code === 'AGY_NATIVE_ACTION_DENIED'
3399
3755
  || error?.code === 'AGY_NATIVE_ACTION_BUDGET'
3400
3756
  || error?.code === 'AGY_DESKTOP_TASK_LIMIT') return 'fatal';
@@ -3487,8 +3843,8 @@ export class AgentLoop {
3487
3843
  }
3488
3844
  if (val.startsWith('~')) {
3489
3845
  args[field] = val.replace(/^~(?=$|[\\/])/, os.homedir());
3490
- } else if (!val.startsWith('/')) {
3491
- args[field] = `${this.workspaceRoot || process.cwd()}/${val}`;
3846
+ } else if (!path.isAbsolute(val)) {
3847
+ args[field] = path.resolve(this.workspaceRoot || process.cwd(), val);
3492
3848
  }
3493
3849
  }
3494
3850
  }