@causyne/agent 1.20.11 → 1.20.13
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.
- package/LICENSE +1 -1
- package/docs/ARCHITECTURE.md +24 -1
- package/package.json +1 -1
- package/src/acp/client.js +9 -2
- package/src/acp/client.ts +11 -2
- package/src/acp/protocol.ts +9 -0
- package/src/agentLoop.js +504 -119
- package/src/agentLoop.ts +477 -121
- package/src/browser/browserRuntime.js +47 -0
- package/src/browser/browserRuntime.ts +45 -0
- package/src/browser/causyneBrowser.js +60 -31
- package/src/browser/causyneBrowser.ts +37 -12
- package/src/browser/workspacePreview.js +52 -0
- package/src/browser/workspacePreview.ts +49 -0
- package/src/core/planCache.js +5 -0
- package/src/core/planCache.ts +5 -0
- package/src/decisionPolicy.js +9 -0
- package/src/decisionPolicy.ts +8 -0
- package/src/historyPruner.js +251 -0
- package/src/historyPruner.ts +263 -0
- package/src/infra/atomicWriter.js +49 -0
- package/src/infra/atomicWriter.ts +63 -0
- package/src/infra/telemetry.js +38 -0
- package/src/infra/telemetry.ts +68 -0
- package/src/observer/coldObserver.js +12 -7
- package/src/observer/coldObserver.ts +12 -7
- package/src/observer/evidence.js +8 -2
- package/src/observer/evidence.ts +9 -2
- package/src/outputRecovery.js +36 -0
- package/src/outputRecovery.ts +33 -0
- package/src/providers/acp.js +114 -46
- package/src/providers/acp.ts +129 -46
- package/src/providers/antigravity.js +264 -82
- package/src/providers/antigravity.ts +273 -87
- package/src/providers/antigravityBridge.js +58 -0
- package/src/providers/antigravityBridge.ts +51 -0
- package/src/providers/base.d.ts +9 -0
- package/src/providers/budgetEnforcer.js +110 -0
- package/src/providers/budgetEnforcer.ts +122 -0
- package/src/providers/collaborationPolicy.js +6 -0
- package/src/providers/collaborationPolicy.ts +7 -0
- package/src/providers/loopGuard.js +84 -0
- package/src/providers/loopGuard.ts +105 -0
- package/src/providers/pi.js +19 -6
- package/src/providers/pi.ts +19 -7
- package/src/providers/toolContracts.js +36 -0
- package/src/providers/toolContracts.ts +48 -0
- package/src/session/sidechainEvents.js +49 -0
- package/src/session/sidechainEvents.ts +98 -0
- package/src/skillsManager.d.ts +1 -0
- package/src/smartToolsUse.js +123 -4
- package/src/smartToolsUse.ts +136 -4
- package/src/subagent/sidechainHarness.js +66 -0
- package/src/subagent/sidechainHarness.ts +91 -0
- package/src/taskContinuation.js +12 -0
- package/src/taskContinuation.ts +13 -0
- package/src/tokenTracker.js +406 -539
- package/src/tokenTracker.ts +569 -0
- package/src/toolPacks.d.ts +2 -0
- package/src/toolPacks.js +1 -1
- package/src/tools/argumentValidation.js +56 -0
- package/src/tools/argumentValidation.ts +50 -0
- package/src/tools/browserAutomator.js +2 -2
- package/src/tools/browserAutomator.ts +3 -2
- package/src/tools/deferredMcpSearch.js +188 -201
- package/src/tools/deferredMcpSearch.ts +250 -0
- package/src/tools/generateMediaViaApi.js +305 -331
- package/src/tools/generateMediaViaApi.ts +330 -0
- package/src/tools/historyPruner.js +5 -0
- package/src/tools/historyPruner.ts +5 -0
- package/src/tools/payloadSanitizer.js +92 -0
- package/src/tools/payloadSanitizer.ts +113 -0
- package/src/tools/registry.d.ts +1 -0
- package/src/tools/sysRun.js +47 -18
- package/src/tools/sysRun.ts +52 -20
- package/src/tools/toolOutputStore.js +180 -0
- package/src/tools/toolOutputStore.ts +209 -0
- package/src/tools/toolSelfRepair.js +26 -1
- package/src/tools/toolSelfRepair.ts +25 -1
- package/src/tui/chatRenderer.d.ts +1 -0
- package/src/tui/chatRenderer.js +4 -2
- package/src/tui/codeStreamRenderer.js +36 -8
- package/src/tui/codeStreamRenderer.ts +38 -8
- package/src/tui/stageSurface.js +1 -0
- package/src/tui/text.js +4 -1
- package/src/tokenTracker.d.ts +0 -1
package/src/agentLoop.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { clearSysRunCache } from './tools/sysRun.js';
|
|
2
|
+
import { PEER_COLLABORATION_POLICY } from './providers/collaborationPolicy.js';
|
|
3
|
+
import { createHash, randomUUID } from 'crypto';
|
|
2
4
|
import { execFileSync } from 'node:child_process';
|
|
3
5
|
import { processApprovalScope, createApprovalScope } from './approvalGrants.js';
|
|
4
6
|
import { pruneSessions as pruneEmbodimentSessions, describeSession } from './embodimentSession.js';
|
|
@@ -7,6 +9,7 @@ import { audioFormatForMimeType } from './providers/base.js';
|
|
|
7
9
|
import { TaskBuffer } from './taskBuffer.js';
|
|
8
10
|
import { TOOL_DEFINITIONS, getDynamicTools, resolveTool, canonicalToolName } from './tools/registry.js';
|
|
9
11
|
import { selfRepairToolCall, generateSelfRepairDiagnostic } from './tools/toolSelfRepair.js';
|
|
12
|
+
import { validateToolArguments } from './tools/argumentValidation.js';
|
|
10
13
|
import { Sandbox } from './sandbox.js';
|
|
11
14
|
import { auditLog } from './auditLog.js';
|
|
12
15
|
import { hasMatchingHook, runConfiguredHooks } from './hooks.js';
|
|
@@ -28,11 +31,12 @@ import { VFETracker } from './vfeTracker.js';
|
|
|
28
31
|
import { coldObserver } from './observer/coldObserver.js';
|
|
29
32
|
import { TimeMachine, recoveryUserMessage } from './timeMachine.js';
|
|
30
33
|
import { routePacks, packForTool, isCoreTool, isGameIntent, isWebIntent, getPackCatalogue, PACK_PLAYBOOKS, PACKS } from './toolPacks.js';
|
|
31
|
-
import { determineToolScope, filterSuppressedPacks, resolveLazyPlaybooks } from './smartToolsUse.js';
|
|
34
|
+
import { determineToolScope, filterSuppressedPacks, resolveLazyPlaybooks, SmartToolsGovernor } from './smartToolsUse.js';
|
|
32
35
|
import { resolveCharPool, measureMessages, resultCapFor, decayToolResults, buildWindow, compactInPlace, describeDroppedMessages, sanitizeSequences, applyProgressiveCompaction, snipOversizedToolOutputs } from './contextManager.js';
|
|
33
36
|
// Provider imports
|
|
34
37
|
import { detectWorkspaceDomains, ensureSkillRepo, getSkillDomainHeader } from './skillsManager.js';
|
|
35
|
-
import { spillToolResult,
|
|
38
|
+
import { spillToolResult, buildDecayPointer, pruneOutputStore } from './outputStore.js';
|
|
39
|
+
import { defaultToolOutputStore, processToolOutputWithStore, renderSpillDocument } from './tools/toolOutputStore.js';
|
|
36
40
|
import { beginTask as beginCheckpointTask, captureBeforeMutation, pruneStore as pruneCheckpointStore, resolveProjectRoot } from './checkpoints.js';
|
|
37
41
|
import fsSync from 'fs';
|
|
38
42
|
import os from 'os';
|
|
@@ -44,6 +48,10 @@ import { resolveMentionedContext } from './promptMentions.js';
|
|
|
44
48
|
import { isLaunchOnlyPrompt, launchScopeError } from './launchIntent.js';
|
|
45
49
|
import { StreamingCodePreview, NativeCodeObserver, codeProgressFromAction } from './tui/codeProgress.js';
|
|
46
50
|
import { StallGuardController } from './stallGuard.js';
|
|
51
|
+
import { buildRecoverableDroppedSummary, pruneStaleToolObservations, shortenOversizedToolObservations, pruneExecutedToolArguments } from './historyPruner.js';
|
|
52
|
+
import { isOutputRecoveryRead } from './outputRecovery.js';
|
|
53
|
+
import { isPlanReviewHandoff, isPlanningOnlyRequest } from './taskContinuation.js';
|
|
54
|
+
import { UnifiedBudgetEnforcer, EfficiencyCheckpoint, actionLimitFor, tokenLimitFor, turnTokenLimitFor, noncachedTokens } from './providers/budgetEnforcer.js';
|
|
47
55
|
export function isActionableTaskPrompt(text) {
|
|
48
56
|
const t = (text || '').trim();
|
|
49
57
|
if (!t)
|
|
@@ -169,6 +177,8 @@ export function isMidTaskProgressText(text) {
|
|
|
169
177
|
}
|
|
170
178
|
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.
|
|
171
179
|
|
|
180
|
+
${PEER_COLLABORATION_POLICY}
|
|
181
|
+
|
|
172
182
|
# Your Capabilities
|
|
173
183
|
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.
|
|
174
184
|
|
|
@@ -177,6 +187,11 @@ ${AGENT_USER_POLICY}
|
|
|
177
187
|
# Project Conventions
|
|
178
188
|
Follow the selected project's existing style and architecture. Check dependencies and tool schemas before use. Preserve unrelated behavior.
|
|
179
189
|
|
|
190
|
+
# Greenfield Application Scaffolding vs. Legacy Codebase Exploration
|
|
191
|
+
- 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.
|
|
192
|
+
- DO NOT perform exploratory directory listings of the root repository or inspect unrelated legacy projects in the workspace.
|
|
193
|
+
- Immediately initialize the target directory and author the required implementation files (e.g. index.html, style.css, app.js).
|
|
194
|
+
|
|
180
195
|
# Operational Guidelines & Communication
|
|
181
196
|
- **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.
|
|
182
197
|
- **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.
|
|
@@ -188,6 +203,7 @@ Follow the selected project's existing style and architecture. Check dependencie
|
|
|
188
203
|
|
|
189
204
|
# Task Management & Planning
|
|
190
205
|
- 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.
|
|
206
|
+
- 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.
|
|
191
207
|
- Check off completed TODOs immediately before reporting progress. Do not batch up multiple task completions.
|
|
192
208
|
- 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.
|
|
193
209
|
|
|
@@ -200,11 +216,11 @@ Follow the selected project's existing style and architecture. Check dependencie
|
|
|
200
216
|
|
|
201
217
|
# Context Understanding & Searching
|
|
202
218
|
- Semantic search (or grep) is your MAIN exploration tool. Start with a broad, high-level query.
|
|
203
|
-
-
|
|
204
|
-
-
|
|
219
|
+
- Batch independent searches when the task needs them. Gather enough evidence to choose the next useful action; avoid repeating unchanged probes.
|
|
220
|
+
- Expand research when uncertainty or a failed check justifies it. Keep exploration proportional to the user's goal.
|
|
205
221
|
|
|
206
222
|
# Making Code Changes & Execution
|
|
207
|
-
- **No Blind Patching**:
|
|
223
|
+
- **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.
|
|
208
224
|
- **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'.
|
|
209
225
|
- **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.
|
|
210
226
|
- **No TODOs/Comments**: Do not add comments for trivial code. NEVER use inline comments. Avoid TODO comments—implement the logic instead.
|
|
@@ -240,8 +256,8 @@ If asked to perform ANY harmful task, politely decline, state that Causyne exist
|
|
|
240
256
|
- **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.
|
|
241
257
|
|
|
242
258
|
# Direct API & Automation Policy
|
|
243
|
-
- **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.
|
|
244
|
-
- **
|
|
259
|
+
- **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.
|
|
260
|
+
- **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.
|
|
245
261
|
|
|
246
262
|
# Universal Tool Calling & Registry Discipline
|
|
247
263
|
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.
|
|
@@ -426,12 +442,13 @@ export class AgentLoop {
|
|
|
426
442
|
? options.approvalScope
|
|
427
443
|
: processApprovalScope;
|
|
428
444
|
this.config = loadConfig();
|
|
429
|
-
this.sandbox = new Sandbox();
|
|
445
|
+
this.sandbox = new Sandbox({ workspaceRoot: this.workspaceRoot });
|
|
430
446
|
// Retire spilled tool outputs past their retention window. Fire-and-forget
|
|
431
447
|
// at task start rather than on a timer: nothing may run in the background
|
|
432
448
|
// (rule ZM-01), and a task boundary is often enough for a 7-day window.
|
|
433
449
|
try {
|
|
434
450
|
pruneOutputStore();
|
|
451
|
+
defaultToolOutputStore.pruneOldOutputs();
|
|
435
452
|
}
|
|
436
453
|
catch (e) { /* never block a task on housekeeping */ }
|
|
437
454
|
try {
|
|
@@ -477,6 +494,8 @@ export class AgentLoop {
|
|
|
477
494
|
this.recentActionSignatures = [];
|
|
478
495
|
this.consecutiveReadOnlySteps = 0;
|
|
479
496
|
this.stallGuard = new StallGuardController();
|
|
497
|
+
this.smartToolsGovernor = new SmartToolsGovernor();
|
|
498
|
+
this._smartToolsNudge = null;
|
|
480
499
|
// Sovereign Progressive Disclosure: which capability packs have entered the
|
|
481
500
|
// context window for this task. Nothing is disabled — see src/toolPacks.js.
|
|
482
501
|
this.unlockedPacks = new Set();
|
|
@@ -505,13 +524,14 @@ export class AgentLoop {
|
|
|
505
524
|
// entire 300-step budget on a task that was already done.
|
|
506
525
|
this.gameGuardFired = false;
|
|
507
526
|
this.webGuardFired = false;
|
|
527
|
+
this.webVerificationScheduled = false;
|
|
508
528
|
// P6: rendered surfaces this task wrote, for the anti-slop gate to read back.
|
|
509
529
|
this.webArtifacts = new Set();
|
|
510
530
|
this.slopReviewAttempts = 0;
|
|
511
531
|
this.slopLastAuditHash = '';
|
|
512
532
|
this.gameCascadeState = { active: true, currentStage: 1, stageHistory: [], verificationPassed: false };
|
|
513
533
|
this.gameToolStats = { godot_act: 0, game_asset_fetch: 0, game_build_html5: 0, last_godot_action: null };
|
|
514
|
-
this.webVerificationState = { screenshotTaken: false, browserActUsed: false }; // V8 Transcendence: Anti-Slop Guard
|
|
534
|
+
this.webVerificationState = { screenshotTaken: false, browserActUsed: false, htmlInspected: false }; // V8 Transcendence: Anti-Slop Guard
|
|
515
535
|
this.abortController = new AbortController();
|
|
516
536
|
// V5: Context compaction tracking
|
|
517
537
|
this._lastCompactionIndex = null;
|
|
@@ -583,6 +603,9 @@ export class AgentLoop {
|
|
|
583
603
|
? path.join(os.homedir(), candidate.slice(2))
|
|
584
604
|
: candidate;
|
|
585
605
|
this.webArtifacts.add(path.resolve(this.workspaceRoot, expanded));
|
|
606
|
+
this.webVerificationScheduled = false;
|
|
607
|
+
this.webVerificationState.browserActUsed = false;
|
|
608
|
+
this.webVerificationState.screenshotTaken = false;
|
|
586
609
|
}
|
|
587
610
|
/**
|
|
588
611
|
* Build the parts of the system context that are constant for a whole task.
|
|
@@ -766,9 +789,14 @@ export class AgentLoop {
|
|
|
766
789
|
return prefetched;
|
|
767
790
|
const eligible = [];
|
|
768
791
|
for (const toolCall of toolCalls) {
|
|
792
|
+
const capacity = Math.min(this.smartToolsGovernor?.inspectionCapacity ?? 2, this.efficiencyBudget?.getRemainingActions() ?? 35);
|
|
793
|
+
if (eligible.length >= capacity)
|
|
794
|
+
break;
|
|
769
795
|
const functionName = canonicalToolName(toolCall.function.name);
|
|
796
|
+
// A later read may verify an earlier write. Never prefetch it across
|
|
797
|
+
// that mutation barrier and accidentally return the pre-edit contents.
|
|
770
798
|
if (!AgentLoop.READ_ONLY_TOOLS.has(functionName))
|
|
771
|
-
|
|
799
|
+
break;
|
|
772
800
|
// Prefetch begins before the serial dispatch path. If this tool has a
|
|
773
801
|
// PreToolUse hook, running it here would create a temporal pre-trust
|
|
774
802
|
// window where the read happens before the hook can deny it.
|
|
@@ -783,6 +811,9 @@ export class AgentLoop {
|
|
|
783
811
|
catch (e) {
|
|
784
812
|
continue; // malformed arguments are the serial loop's business
|
|
785
813
|
}
|
|
814
|
+
const prefetchedTool = resolveTool(functionName);
|
|
815
|
+
if (validateToolArguments(args, prefetchedTool?.schema?.parameters || prefetchedTool?.schema?.input_schema).length)
|
|
816
|
+
continue;
|
|
786
817
|
// The same guard the serial path applies, applied before anything runs.
|
|
787
818
|
let validation;
|
|
788
819
|
try {
|
|
@@ -833,6 +864,144 @@ export class AgentLoop {
|
|
|
833
864
|
worker();
|
|
834
865
|
return prefetched;
|
|
835
866
|
}
|
|
867
|
+
/** Apply host policy to an ACP operation without disabling the peer itself. */
|
|
868
|
+
resolvePeerFilePath(file) {
|
|
869
|
+
const target = path.resolve(this.workspaceRoot, file);
|
|
870
|
+
let ancestor = target;
|
|
871
|
+
while (true) {
|
|
872
|
+
try {
|
|
873
|
+
fsSync.lstatSync(ancestor);
|
|
874
|
+
break;
|
|
875
|
+
}
|
|
876
|
+
catch (error) {
|
|
877
|
+
if (error.code !== 'ENOENT')
|
|
878
|
+
throw error;
|
|
879
|
+
const parent = path.dirname(ancestor);
|
|
880
|
+
if (parent === ancestor)
|
|
881
|
+
throw new Error('ACP path was not authorized');
|
|
882
|
+
ancestor = parent;
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
const physical = path.resolve(fsSync.realpathSync(ancestor), path.relative(ancestor, target));
|
|
886
|
+
const allowed = this.sandbox.grantAllAccess || this.sandbox.workspacePaths.some((root) => {
|
|
887
|
+
try {
|
|
888
|
+
const relative = path.relative(fsSync.realpathSync(root), physical);
|
|
889
|
+
return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
|
|
890
|
+
}
|
|
891
|
+
catch {
|
|
892
|
+
return false;
|
|
893
|
+
}
|
|
894
|
+
});
|
|
895
|
+
if (!allowed)
|
|
896
|
+
throw new Error('ACP path was not authorized by the selected workspace');
|
|
897
|
+
return target;
|
|
898
|
+
}
|
|
899
|
+
async authorizePeerOperation(tool, args, id, uncertain = false) {
|
|
900
|
+
if (this.stopRequested || this.abortController.signal.aborted)
|
|
901
|
+
return false;
|
|
902
|
+
const validation = this.sandbox.validate(tool, args);
|
|
903
|
+
if (!validation.allowed)
|
|
904
|
+
return false;
|
|
905
|
+
const hook = await this.runPreToolUse(tool, args, id);
|
|
906
|
+
if (hook?.denied)
|
|
907
|
+
return false;
|
|
908
|
+
const assessment = await coldObserver.evaluateMutation(tool, args, { workspaceRoot: this.workspaceRoot });
|
|
909
|
+
if (assessment.veto)
|
|
910
|
+
return false;
|
|
911
|
+
const needsApproval = uncertain || requiresToolApproval({
|
|
912
|
+
mode: this.config.autonomyMode || 'C', tool, args,
|
|
913
|
+
risk: assessment.requiresConfirmation ? 'dangerous' : validation.risk,
|
|
914
|
+
heavyDownload: false, standingApproval: this.isAlwaysAllowed(tool)
|
|
915
|
+
});
|
|
916
|
+
if (needsApproval) {
|
|
917
|
+
this.emitEvent({ type: 'approval_request', toolCallId: id, tool, args, risk: validation.risk });
|
|
918
|
+
if (!await this.waitForApproval(id))
|
|
919
|
+
return false;
|
|
920
|
+
}
|
|
921
|
+
if (this.stopRequested || this.abortController.signal.aborted)
|
|
922
|
+
return false;
|
|
923
|
+
auditLog.log({ event: 'peer_operation_authorized', taskId: this.taskId, tool });
|
|
924
|
+
return true;
|
|
925
|
+
}
|
|
926
|
+
async requestPeerPermission(request) {
|
|
927
|
+
const call = request.toolCall;
|
|
928
|
+
const raw = call.rawInput && typeof call.rawInput === 'object' && !Array.isArray(call.rawInput)
|
|
929
|
+
? call.rawInput : {};
|
|
930
|
+
const args = { ...raw };
|
|
931
|
+
if (!args.path && call.locations?.[0]?.path)
|
|
932
|
+
args.path = call.locations[0].path;
|
|
933
|
+
for (const field of ['path', 'file_path', 'filePath', 'filepath', 'absolutePath', 'cwd', 'source', 'destination', 'directory', 'targetFile', 'outputFile', 'outputPath']) {
|
|
934
|
+
if (typeof args[field] === 'string') {
|
|
935
|
+
try {
|
|
936
|
+
args[field] = this.resolvePeerFilePath(args[field]);
|
|
937
|
+
}
|
|
938
|
+
catch {
|
|
939
|
+
return { outcome: 'cancelled' };
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
args.path ??= args.file_path ?? args.filePath ?? args.filepath ?? args.absolutePath;
|
|
944
|
+
const tool = call.kind === 'read' ? 'fs_read' : call.kind === 'edit' ? 'fs_edit'
|
|
945
|
+
: call.kind === 'delete' ? 'fs_delete' : call.kind === 'move' ? 'fs_move'
|
|
946
|
+
: call.kind === 'execute' ? 'sysRun' : 'peer_native';
|
|
947
|
+
if (tool === 'sysRun' && !args.command && typeof args.cmd === 'string')
|
|
948
|
+
args.command = args.cmd;
|
|
949
|
+
const uncertain = !['read', 'search', 'fetch', 'think'].includes(call.kind || '')
|
|
950
|
+
&& (tool === 'peer_native' || (tool === 'sysRun' ? !args.command : !args.path));
|
|
951
|
+
const option = request.options.find(item => item.kind === 'allow_once');
|
|
952
|
+
// Never propagate a standing peer grant across sessions or forks.
|
|
953
|
+
if (!option || !await this.authorizePeerOperation(tool, { ...args, peerTitle: call.title }, `peer:${call.toolCallId}`, uncertain)) {
|
|
954
|
+
return { outcome: 'cancelled' };
|
|
955
|
+
}
|
|
956
|
+
return { outcome: 'selected', optionId: option.optionId };
|
|
957
|
+
}
|
|
958
|
+
async executePeerFile(tool, file, content, options) {
|
|
959
|
+
const target = this.resolvePeerFilePath(file);
|
|
960
|
+
if (options?.line !== undefined && (!Number.isSafeInteger(options.line) || options.line < 1))
|
|
961
|
+
throw new Error('ACP line must be a positive integer');
|
|
962
|
+
if (options?.limit !== undefined && (!Number.isSafeInteger(options.limit) || options.limit < 1))
|
|
963
|
+
throw new Error('ACP limit must be a positive integer');
|
|
964
|
+
const args = { path: target, ...(tool === 'fs_write' ? { content } : {}),
|
|
965
|
+
...(options?.line !== undefined ? { startLine: options.line } : {}),
|
|
966
|
+
...(options?.limit !== undefined ? { endLine: (options.line || 1) + options.limit - 1 } : {}) };
|
|
967
|
+
const id = `peer-file:${randomUUID()}:${tool}`;
|
|
968
|
+
if (!await this.authorizePeerOperation(tool, args, id))
|
|
969
|
+
throw new Error('The requested ACP file operation was not authorized');
|
|
970
|
+
if (tool === 'fs_write')
|
|
971
|
+
captureBeforeMutation(tool, args, { taskId: this.taskId, step: this.stepsCompleted });
|
|
972
|
+
this.efficiencyBudget.recordAction();
|
|
973
|
+
let result;
|
|
974
|
+
if (tool === 'fs_read') {
|
|
975
|
+
// ACP expects the actual requested text, not the host tool's paging
|
|
976
|
+
// warning appended to a silently shortened file.
|
|
977
|
+
const stat = fsSync.statSync(target);
|
|
978
|
+
if (stat.size > 4 * 1024 * 1024)
|
|
979
|
+
throw new Error('ACP text file exceeds the 4 MiB client transfer limit');
|
|
980
|
+
const bytes = fsSync.readFileSync(target);
|
|
981
|
+
if (bytes.includes(0))
|
|
982
|
+
throw new Error('ACP read_text_file requires a text file');
|
|
983
|
+
let output = bytes.toString('utf8');
|
|
984
|
+
if (options?.line !== undefined || options?.limit !== undefined) {
|
|
985
|
+
const start = Math.max(0, (options.line || 1) - 1);
|
|
986
|
+
output = output.split('\n').slice(start, options?.limit === undefined ? undefined : start + options.limit).join('\n');
|
|
987
|
+
}
|
|
988
|
+
result = { success: true, output };
|
|
989
|
+
}
|
|
990
|
+
else {
|
|
991
|
+
result = await withToolAutonomyMode(this.config.autonomyMode || 'C', () => resolveTool(tool).execute(args, { parentLoop: this, signal: this.abortController.signal }));
|
|
992
|
+
}
|
|
993
|
+
const postHook = await this.runPostToolUse(tool, args, result);
|
|
994
|
+
const success = result.success !== false && !result.error && !postHook?.denied;
|
|
995
|
+
coldObserver.recordToolOutcome(this.taskId, tool, args, { ...result, success });
|
|
996
|
+
auditLog.log({ event: 'tool_exec', taskId: this.taskId, tool, success, source: 'acp_client' });
|
|
997
|
+
if (!success)
|
|
998
|
+
throw new Error(result.error || postHook?.reason || 'ACP file operation failed');
|
|
999
|
+
if (tool === 'fs_write') {
|
|
1000
|
+
this.recordWebArtifact(target);
|
|
1001
|
+
clearSysRunCache();
|
|
1002
|
+
}
|
|
1003
|
+
return typeof result.output === 'string' ? result.output : '';
|
|
1004
|
+
}
|
|
836
1005
|
emitEvent(messageObj) {
|
|
837
1006
|
if (this.eventSink && this.eventSink.readyState === 1) {
|
|
838
1007
|
this.eventSink.send(JSON.stringify({ taskId: this.taskId, ...messageObj }));
|
|
@@ -1036,6 +1205,8 @@ export class AgentLoop {
|
|
|
1036
1205
|
// ORDER to work in, which saves whole exploratory steps.
|
|
1037
1206
|
this.gameGuardFired = false;
|
|
1038
1207
|
this.webGuardFired = false;
|
|
1208
|
+
this.webVerificationScheduled = false;
|
|
1209
|
+
this.webVerificationState = { screenshotTaken: false, browserActUsed: false, htmlInspected: false };
|
|
1039
1210
|
this.webArtifacts = new Set();
|
|
1040
1211
|
this.slopReviewAttempts = 0;
|
|
1041
1212
|
this.slopLastAuditHash = '';
|
|
@@ -1275,8 +1446,28 @@ export class AgentLoop {
|
|
|
1275
1446
|
this.recentActionSignatures = [];
|
|
1276
1447
|
this.consecutiveReadOnlySteps = 0;
|
|
1277
1448
|
this.stallGuard.reset();
|
|
1449
|
+
this.smartToolsGovernor.reset();
|
|
1450
|
+
this._smartToolsNudge = null;
|
|
1278
1451
|
this.tokenTracker.resetTask();
|
|
1452
|
+
const turnArchetype = determineToolScope(this.currentTaskPrompt || '', this.taskShape).archetype;
|
|
1453
|
+
const efficiency = this.config.efficiency || {};
|
|
1454
|
+
const taskTokenCeiling = Number.isInteger(this.taskTokenLimit) && this.taskTokenLimit > 0
|
|
1455
|
+
? this.taskTokenLimit
|
|
1456
|
+
: this.tokenTracker.budget?.enabled && Number.isFinite(this.tokenTracker.budget?.maxTokensPerTask) && this.tokenTracker.budget.maxTokensPerTask > 0
|
|
1457
|
+
? this.tokenTracker.budget.maxTokensPerTask
|
|
1458
|
+
: Number.isFinite(efficiency.maxTaskTokens) && efficiency.maxTaskTokens > 0
|
|
1459
|
+
? efficiency.maxTaskTokens
|
|
1460
|
+
: Number.isFinite(efficiency.maxTurnTokens) && efficiency.maxTurnTokens > 0
|
|
1461
|
+
? efficiency.maxTurnTokens
|
|
1462
|
+
: tokenLimitFor(turnArchetype);
|
|
1463
|
+
this.efficiencyBudget = new UnifiedBudgetEnforcer(Number.isFinite(efficiency.maxTurnTokens) && efficiency.maxTurnTokens > 0
|
|
1464
|
+
? efficiency.maxTurnTokens
|
|
1465
|
+
: turnTokenLimitFor(turnArchetype), Number.isSafeInteger(efficiency.maxTurnActions) && efficiency.maxTurnActions > 0 ? efficiency.maxTurnActions : actionLimitFor(turnArchetype), taskTokenCeiling);
|
|
1466
|
+
const recoveryPaths = new Set();
|
|
1467
|
+
let modelCallIndex = 0;
|
|
1279
1468
|
let mediaExplorationRecoveries = 0;
|
|
1469
|
+
let reasoningOnlyRecoveries = 0;
|
|
1470
|
+
let planHandoffRecoveries = 0;
|
|
1280
1471
|
// The core loop governed by Sovereign Human-in-the-Loop Checkpoints
|
|
1281
1472
|
while (!this.stopRequested) {
|
|
1282
1473
|
if (this.stopRequested) {
|
|
@@ -1286,6 +1477,13 @@ export class AgentLoop {
|
|
|
1286
1477
|
}
|
|
1287
1478
|
this.emitEvent({ type: 'status', message: 'Thinking...' });
|
|
1288
1479
|
try {
|
|
1480
|
+
this.smartToolsGovernor.beginModelStep();
|
|
1481
|
+
// Insert at the model boundary, never between one assistant tool-call
|
|
1482
|
+
// message and the matching tool results in a multi-call batch.
|
|
1483
|
+
if (this._smartToolsNudge) {
|
|
1484
|
+
this.messages.push({ role: 'system', content: this._smartToolsNudge });
|
|
1485
|
+
this._smartToolsNudge = null;
|
|
1486
|
+
}
|
|
1289
1487
|
// --- V8 MEMORY ARCHITECTURE: DECAY → WINDOW → REAL COMPACTION ---
|
|
1290
1488
|
// The window is no longer only a view over an ever-growing array. Old
|
|
1291
1489
|
// tool payloads decay into stubs, and anything amputated is physically
|
|
@@ -1295,13 +1493,40 @@ export class AgentLoop {
|
|
|
1295
1493
|
// 5-Stage Progressive Compaction (Claude Code Architecture / Research Section E):
|
|
1296
1494
|
// Stage 0 (HLCE Ephemeral Decay) + Stage 2 (Snip >15K tokens / 60K chars) +
|
|
1297
1495
|
// Stage 1 (Budget Reduction >70%) + Stage 3 (Microcompact) + Stage 4 (Context Collapse >85%)
|
|
1496
|
+
const observationPrune = pruneStaleToolObservations(this.messages, {
|
|
1497
|
+
keepRecent: this.config.keepRecentToolResults ?? 4,
|
|
1498
|
+
minChars: 600,
|
|
1499
|
+
taskId: this.taskId
|
|
1500
|
+
});
|
|
1501
|
+
const argumentPrune = pruneExecutedToolArguments(this.messages, { taskId: this.taskId });
|
|
1502
|
+
for (const saved of argumentPrune.recoveryPaths)
|
|
1503
|
+
recoveryPaths.add(path.resolve(saved));
|
|
1504
|
+
const oversizedPrune = shortenOversizedToolObservations(this.messages, {
|
|
1505
|
+
taskId: this.taskId
|
|
1506
|
+
});
|
|
1507
|
+
for (const message of this.messages) {
|
|
1508
|
+
if (typeof message.spillPath === 'string')
|
|
1509
|
+
recoveryPaths.add(path.resolve(message.spillPath));
|
|
1510
|
+
}
|
|
1298
1511
|
const compaction = applyProgressiveCompaction(this.messages, MAX_CHAR_POOL, {
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1512
|
+
// historyPruner preserves full output before eliding it. The legacy
|
|
1513
|
+
// decay path cannot promise that recovery, so keep it disabled here.
|
|
1514
|
+
enableEphemeralDecay: false,
|
|
1515
|
+
// The legacy snipper can discard data when a disk spill fails. The
|
|
1516
|
+
// recoverable TypeScript path above owns all oversized tool output.
|
|
1517
|
+
snipOptions: { threshold: Number.MAX_SAFE_INTEGER },
|
|
1518
|
+
budgetKeepRecent: Number.MAX_SAFE_INTEGER,
|
|
1519
|
+
collapseKeepRecent: Number.MAX_SAFE_INTEGER
|
|
1304
1520
|
});
|
|
1521
|
+
compaction.totalReclaimed += observationPrune.reclaimedChars + oversizedPrune.reclaimedChars + argumentPrune.reclaimedChars;
|
|
1522
|
+
if (argumentPrune.pruned > 0)
|
|
1523
|
+
compaction.stagesFired.push(`executed_argument_archive:${argumentPrune.pruned}`);
|
|
1524
|
+
if (observationPrune.pruned > 0) {
|
|
1525
|
+
compaction.stagesFired.push(`recoverable_observation_decay:${observationPrune.pruned}`);
|
|
1526
|
+
}
|
|
1527
|
+
if (oversizedPrune.pruned > 0) {
|
|
1528
|
+
compaction.stagesFired.push(`recoverable_oversized_output:${oversizedPrune.pruned}`);
|
|
1529
|
+
}
|
|
1305
1530
|
if (compaction.totalReclaimed > 0) {
|
|
1306
1531
|
this.debugLog(`progressive compaction reclaimed ${(compaction.totalReclaimed / 1024).toFixed(1)} KB [${compaction.stagesFired.join(', ')}]`);
|
|
1307
1532
|
auditLog.log({
|
|
@@ -1332,7 +1557,7 @@ export class AgentLoop {
|
|
|
1332
1557
|
if (splitIndex >= 1) {
|
|
1333
1558
|
const dropped = this.messages.slice(1, splitIndex + 1);
|
|
1334
1559
|
if (dropped.length > 0) {
|
|
1335
|
-
const compactSummary = buildStructuralSummary(dropped) || describeDroppedMessages(dropped);
|
|
1560
|
+
const compactSummary = buildRecoverableDroppedSummary(dropped, buildStructuralSummary(dropped) || describeDroppedMessages(dropped));
|
|
1336
1561
|
const removed = compactInPlace(this.messages, splitIndex, compactSummary);
|
|
1337
1562
|
this._lastCompactionIndex = null;
|
|
1338
1563
|
this.debugLog(`compacted ${removed} messages out of the live context`);
|
|
@@ -1436,11 +1661,16 @@ export class AgentLoop {
|
|
|
1436
1661
|
// LazyPlaybook: disclose multi-page mandates only when tools from that domain
|
|
1437
1662
|
// have been actively invoked or explicitly demanded. Otherwise emit micro-indicators.
|
|
1438
1663
|
const observedTools = (this._planSteps || []).map((step) => step.tool);
|
|
1439
|
-
const lazyPlaybookResult = resolveLazyPlaybooks(this.unlockedPacks, observedTools, this.userPrompt);
|
|
1664
|
+
const lazyPlaybookResult = resolveLazyPlaybooks(this.unlockedPacks, observedTools, this.currentTaskPrompt || this.userPrompt || '');
|
|
1440
1665
|
const activePlaybooks = [
|
|
1441
1666
|
lazyPlaybookResult.fullPlaybooks,
|
|
1442
1667
|
lazyPlaybookResult.microAnnouncements
|
|
1443
1668
|
].filter(Boolean).join('\n\n');
|
|
1669
|
+
auditLog.log({ event: 'smart_tools_context', taskId: this.taskId, step: this.stepsCompleted,
|
|
1670
|
+
archetype: determineToolScope(this.currentTaskPrompt || '', this.taskShape).archetype,
|
|
1671
|
+
toolCount: dynamicTools.length, toolSchemaChars: JSON.stringify(dynamicTools).length,
|
|
1672
|
+
playbookDomains: lazyPlaybookResult.activePlaybookDomains,
|
|
1673
|
+
playbookChars: activePlaybooks.length, planCacheHit: Boolean(this._planMatch) });
|
|
1444
1674
|
// The task brief turns "here are 28 tools" into "here is the order to
|
|
1445
1675
|
// use them in", which is where whole exploratory steps get saved.
|
|
1446
1676
|
const taskBrief = this.taskShape
|
|
@@ -1583,8 +1813,9 @@ export class AgentLoop {
|
|
|
1583
1813
|
? Number(budget.maxTokensPerDay || 0) : 0;
|
|
1584
1814
|
const dailyUsed = hardBudget && dailyLimit > 0
|
|
1585
1815
|
? (await this.tokenTracker.getDailyUsage()).totalTokens : 0;
|
|
1586
|
-
const
|
|
1816
|
+
const configuredRemainingBudget = hardBudget
|
|
1587
1817
|
? Math.min(taskLimit > 0 ? taskLimit - this.tokenTracker.taskTokens : Infinity, dailyLimit > 0 ? dailyLimit - dailyUsed : Infinity) : Infinity;
|
|
1818
|
+
const remainingBudget = Math.min(configuredRemainingBudget, this.efficiencyBudget.getRemainingTokens());
|
|
1588
1819
|
if (remainingBudget <= 0) {
|
|
1589
1820
|
this.emitEvent({ type: 'budget_warning', message: 'Token budget reached before the next model call.' });
|
|
1590
1821
|
break;
|
|
@@ -1623,20 +1854,30 @@ export class AgentLoop {
|
|
|
1623
1854
|
this.emitEvent({ type: 'status', message: 'Thinking…' });
|
|
1624
1855
|
this.emitEvent({ type: 'agent_activity', activity: 'Thinking…' });
|
|
1625
1856
|
const planStepStart = performance.now();
|
|
1857
|
+
const nativeControl = new AbortController();
|
|
1858
|
+
let nativeCheckpoint = null;
|
|
1859
|
+
const invocation = ++modelCallIndex;
|
|
1626
1860
|
const response = await this.llm.chat(prunedMessages, {
|
|
1627
1861
|
taskId: this.taskId,
|
|
1628
1862
|
conversationId: this.memoryManager?.sessionId || this.taskId,
|
|
1629
1863
|
taskIntent: isLaunchOnlyPrompt(this.currentTaskPrompt || this.userPrompt || '') ? 'launch' : 'general',
|
|
1630
1864
|
taskArchetype: determineToolScope(this.currentTaskPrompt || this.userPrompt || '', this.taskShape).archetype,
|
|
1631
1865
|
maxTokensThisCall: Number.isFinite(remainingBudget) ? remainingBudget : undefined,
|
|
1632
|
-
|
|
1866
|
+
tokenBudgetBasis: Number.isFinite(configuredRemainingBudget) ? 'total' : 'noncached',
|
|
1867
|
+
tokenLimit: Number.isFinite(remainingBudget) && remainingBudget > 0
|
|
1868
|
+
? Math.min(this.efficiencyBudget.maxTurnTokens, remainingBudget) : this.efficiencyBudget.maxTurnTokens,
|
|
1869
|
+
maxNativeActions: this.efficiencyBudget.getRemainingActions(),
|
|
1633
1870
|
workspaceRoot: this.workspaceRoot,
|
|
1871
|
+
onPeerPermission: (request) => this.requestPeerPermission(request),
|
|
1872
|
+
onPeerFileRead: (file, options) => this.executePeerFile('fs_read', file, undefined, options),
|
|
1873
|
+
onPeerFileWrite: async (file, content) => { await this.executePeerFile('fs_write', file, content); },
|
|
1634
1874
|
tools: dynamicTools,
|
|
1635
1875
|
// IARS couples escalation to a wider search. Bounded so a stuck task
|
|
1636
1876
|
// cannot climb into randomness across repeated escalations.
|
|
1637
1877
|
temperature: Math.min(1, this.taskTemperature + uncertaintyTemperatureDelta),
|
|
1638
1878
|
coreToolCount: dynamicTools.filter((t) => isCoreTool(t.name)).length,
|
|
1639
|
-
signal: this.abortController?.signal
|
|
1879
|
+
signal: this.abortController?.signal
|
|
1880
|
+
? AbortSignal.any([this.abortController.signal, nativeControl.signal]) : nativeControl.signal,
|
|
1640
1881
|
onReasoningChunk: (chunk) => {
|
|
1641
1882
|
if (this.stopRequested || this.abortController?.signal?.aborted)
|
|
1642
1883
|
return;
|
|
@@ -1668,6 +1909,21 @@ export class AgentLoop {
|
|
|
1668
1909
|
return;
|
|
1669
1910
|
if (!action || typeof action.name !== 'string')
|
|
1670
1911
|
return;
|
|
1912
|
+
auditLog.log({ event: 'native_action', taskId: this.taskId,
|
|
1913
|
+
provider: this.config.provider || 'unknown', tool: action.name, status: action.status,
|
|
1914
|
+
...(action.id ? { actionId: action.id } : {}) });
|
|
1915
|
+
if (action.status === 'running') {
|
|
1916
|
+
try {
|
|
1917
|
+
this.efficiencyBudget.recordAction(`${invocation}:${action.id || `${action.name}:${action.detail || ''}`}`);
|
|
1918
|
+
}
|
|
1919
|
+
catch (error) {
|
|
1920
|
+
if (error instanceof EfficiencyCheckpoint) {
|
|
1921
|
+
nativeCheckpoint = error;
|
|
1922
|
+
nativeControl.abort();
|
|
1923
|
+
}
|
|
1924
|
+
return;
|
|
1925
|
+
}
|
|
1926
|
+
}
|
|
1671
1927
|
const nativeCode = codeProgressFromAction(action.name, { ...(action.parameters && typeof action.parameters === 'object' ? action.parameters : {}),
|
|
1672
1928
|
path: action.parameters?.path || action.parameters?.Path || action.detail || '' }, `provider:${action.name}:${action.detail || ''}`, action.status === 'completed' ? 'done' : action.status === 'failed' ? 'failed' : 'working', 'provider');
|
|
1673
1929
|
if (nativeCode) {
|
|
@@ -1683,13 +1939,19 @@ export class AgentLoop {
|
|
|
1683
1939
|
this.emitEvent({ type: 'agent_activity', activity: `Acting: ${action.name}${detail}` });
|
|
1684
1940
|
}
|
|
1685
1941
|
else if (action.status === 'completed') {
|
|
1686
|
-
this.emitEvent({ type: 'notice', tone: 'muted', nativeStep: true, message:
|
|
1942
|
+
this.emitEvent({ type: 'notice', tone: 'muted', nativeStep: true, message: `${this.config.provider || 'Provider'} ${action.name}${detail}` });
|
|
1687
1943
|
}
|
|
1688
1944
|
else if (action.status === 'failed') {
|
|
1689
|
-
this.emitEvent({ type: 'warning', message:
|
|
1945
|
+
this.emitEvent({ type: 'warning', message: `${this.config.provider || 'Provider'} could not ${action.name}${detail}` });
|
|
1690
1946
|
}
|
|
1691
1947
|
}
|
|
1692
|
-
}).
|
|
1948
|
+
}).catch((error) => {
|
|
1949
|
+
if (nativeCheckpoint && error && typeof error === 'object' && 'partialUsage' in error) {
|
|
1950
|
+
Object.assign(nativeCheckpoint, { partialUsage: error.partialUsage });
|
|
1951
|
+
}
|
|
1952
|
+
throw nativeCheckpoint || error;
|
|
1953
|
+
})
|
|
1954
|
+
.finally(() => nativeCodeObserver.dispose());
|
|
1693
1955
|
this._totalPlanMs = (this._totalPlanMs || 0) + (performance.now() - planStepStart);
|
|
1694
1956
|
if (this.stopRequested || this.abortController?.signal?.aborted) {
|
|
1695
1957
|
auditLog.log({ event: 'task_interrupted', taskId: this.taskId });
|
|
@@ -1717,12 +1979,18 @@ export class AgentLoop {
|
|
|
1717
1979
|
promptTokens: response.usage.promptTokens,
|
|
1718
1980
|
completionTokens: response.usage.completionTokens,
|
|
1719
1981
|
cachedPromptTokens: response.usage.cachedPromptTokens || 0,
|
|
1982
|
+
uncachedPromptTokens: response.usage.uncachedPromptTokens,
|
|
1983
|
+
noncachedTokens: noncachedTokens(response.usage),
|
|
1720
1984
|
measurement: response.usage.measurement || 'unspecified',
|
|
1721
1985
|
cacheMeasurement: response.usage.cacheMeasurement || 'unspecified',
|
|
1722
1986
|
costBasis: /^(acp(?:\/|$)|antigravity$|agy$)/i.test(String(this.config.provider || ''))
|
|
1723
1987
|
? 'external_subscription_unavailable' : 'rate_card_estimate',
|
|
1724
1988
|
callEstimatedCostUsd: this.tokenTracker.calculateCost(response.usage.promptTokens, response.usage.completionTokens, response.usage)
|
|
1725
1989
|
});
|
|
1990
|
+
this.efficiencyBudget.recordUsage(response.usage);
|
|
1991
|
+
for (const action of response.externalActions || []) {
|
|
1992
|
+
this.efficiencyBudget.recordAction(`${invocation}:${action.id || `${action.name}:${action.detail || ''}`}`);
|
|
1993
|
+
}
|
|
1726
1994
|
const cachedTokens = response.usage.cachedPromptTokens || 0;
|
|
1727
1995
|
if (cachedTokens > 0) {
|
|
1728
1996
|
this.debugLog(`prompt cache hit: ${cachedTokens.toLocaleString()} of ${response.usage.promptTokens.toLocaleString()} input tokens served from cache`);
|
|
@@ -1757,6 +2025,43 @@ export class AgentLoop {
|
|
|
1757
2025
|
this.emitEvent({ type: 'error', message: tracking.reason });
|
|
1758
2026
|
break;
|
|
1759
2027
|
}
|
|
2028
|
+
// The host owns verification policy. A model cannot substitute repeated
|
|
2029
|
+
// HTTP checks for rendering, and adapters must not contradict this gate.
|
|
2030
|
+
if (!response.toolCalls?.length && !this.webVerificationScheduled
|
|
2031
|
+
&& !this.webVerificationState.browserActUsed && !this.webVerificationState.screenshotTaken
|
|
2032
|
+
&& isWebIntent(this.currentTaskPrompt || this.userPrompt || '')
|
|
2033
|
+
&& !isLaunchOnlyPrompt(this.currentTaskPrompt || this.userPrompt || '')
|
|
2034
|
+
&& !isPlanningOnlyRequest(this.currentTaskPrompt || this.userPrompt || '')) {
|
|
2035
|
+
const files = [];
|
|
2036
|
+
for (const candidate of this.webArtifacts) {
|
|
2037
|
+
if (files.length >= 50)
|
|
2038
|
+
break;
|
|
2039
|
+
try {
|
|
2040
|
+
const stat = fsSync.lstatSync(candidate);
|
|
2041
|
+
if (stat.isFile() && stat.size <= 512_000)
|
|
2042
|
+
files.push({ path: candidate, content: fsSync.readFileSync(candidate, 'utf8') });
|
|
2043
|
+
}
|
|
2044
|
+
catch { /* Deleted artifacts cannot be verified. */ }
|
|
2045
|
+
}
|
|
2046
|
+
const entry = files.find(file => /\.html?$/i.test(file.path));
|
|
2047
|
+
if (entry && analyzeFiles(files).verdict !== 'slop') {
|
|
2048
|
+
const { groupStatus } = await import('./provisioning/capabilityProvisioner.js');
|
|
2049
|
+
const { isBrowserRuntimeInstalled } = await import('./browser/browserRuntime.js');
|
|
2050
|
+
if (groupStatus('browser').state === 'ready' && isBrowserRuntimeInstalled()) {
|
|
2051
|
+
this.webVerificationScheduled = true;
|
|
2052
|
+
this.webGuardFired = true;
|
|
2053
|
+
response.toolCalls = [{ id: `host-verify-${this.stepsCompleted}`, type: 'function', function: {
|
|
2054
|
+
name: 'browser_act', arguments: JSON.stringify({ actions: [
|
|
2055
|
+
{ type: 'preview', filePath: path.relative(this.workspaceRoot, entry.path) },
|
|
2056
|
+
{ type: 'snapshot' }
|
|
2057
|
+
] })
|
|
2058
|
+
} }];
|
|
2059
|
+
response.content = '';
|
|
2060
|
+
auditLog.log({ event: 'host_verification_scheduled', taskId: this.taskId, tool: 'browser_act' });
|
|
2061
|
+
this.emitEvent({ type: 'status', message: 'Inspecting the rendered page through Causyne Browser…' });
|
|
2062
|
+
}
|
|
2063
|
+
}
|
|
2064
|
+
}
|
|
1760
2065
|
// Add assistant response to history. This is the ONLY place the turn is
|
|
1761
2066
|
// recorded — the completion and guard branches below used to push it a
|
|
1762
2067
|
// second time, duplicating every finished turn in the history.
|
|
@@ -1765,7 +2070,7 @@ export class AgentLoop {
|
|
|
1765
2070
|
role: 'assistant',
|
|
1766
2071
|
// An assistant message with neither text nor tool calls is rejected by
|
|
1767
2072
|
// some providers, so a terminal turn always carries something.
|
|
1768
|
-
content:
|
|
2073
|
+
content: hasToolCalls ? '' : (response.content || 'No final response was provided.')
|
|
1769
2074
|
};
|
|
1770
2075
|
if (hasToolCalls) {
|
|
1771
2076
|
assistantMsg.tool_calls = response.toolCalls;
|
|
@@ -1793,9 +2098,8 @@ export class AgentLoop {
|
|
|
1793
2098
|
assistantMsg.thinking_blocks = response.thinkingBlocks;
|
|
1794
2099
|
}
|
|
1795
2100
|
this.messages.push(assistantMsg);
|
|
1796
|
-
|
|
1797
|
-
|
|
1798
|
-
}
|
|
2101
|
+
// Prose accompanying pending actions is not an execution result.
|
|
2102
|
+
// Tool events provide progress; terminal claims pass completion gates below.
|
|
1799
2103
|
const externalActions = Array.isArray(response.externalActions)
|
|
1800
2104
|
? response.externalActions
|
|
1801
2105
|
: [];
|
|
@@ -1814,8 +2118,12 @@ export class AgentLoop {
|
|
|
1814
2118
|
// A native action's name is not evidence that a model inspected
|
|
1815
2119
|
// pixels. Keep visual verification false unless a real image result
|
|
1816
2120
|
// has reached a vision-capable provider.
|
|
1817
|
-
|
|
1818
|
-
|
|
2121
|
+
// A native action label alone carries no rendered-page evidence.
|
|
2122
|
+
// The shared host inspection below verifies its resulting artifacts.
|
|
2123
|
+
if (['fs_read', 'read_file', 'view_file', 'viewfile', 'view_file_content'].includes(actionName) && detailPath) {
|
|
2124
|
+
if (/\.(html|htm|css|jsx|tsx|vue|svelte)$/i.test(detailPath)) {
|
|
2125
|
+
this.webVerificationState.htmlInspected = true;
|
|
2126
|
+
}
|
|
1819
2127
|
}
|
|
1820
2128
|
}
|
|
1821
2129
|
}
|
|
@@ -1825,6 +2133,25 @@ export class AgentLoop {
|
|
|
1825
2133
|
const lower = contentText.toLowerCase();
|
|
1826
2134
|
const taskPrompt = (this.currentTaskPrompt || this.userPrompt || '').trim();
|
|
1827
2135
|
const isActionable = isActionableTaskPrompt(taskPrompt);
|
|
2136
|
+
// A peer may have completed searches or a plan artifact while still
|
|
2137
|
+
// waiting for its own UI's Proceed button. Those actions do not
|
|
2138
|
+
// satisfy an implementation request in the enclosing Causyne loop.
|
|
2139
|
+
if (isActionable && !isPlanningOnlyRequest(taskPrompt) && isPlanReviewHandoff(contentText)) {
|
|
2140
|
+
if (planHandoffRecoveries++ > 0) {
|
|
2141
|
+
this.emitEvent({ type: 'error', message: 'The selected peer stopped for plan review again instead of implementing the request. Work remains unfinished.' });
|
|
2142
|
+
this.memoryManager.saveHistory(this.messages);
|
|
2143
|
+
break;
|
|
2144
|
+
}
|
|
2145
|
+
this._implementationPlanRequired = false;
|
|
2146
|
+
this.messages.push({ role: 'system', content: '[IMPLEMENTATION CONTINUATION] The user requested implementation, not a plan-only deliverable. '
|
|
2147
|
+
+ 'Continue from the useful evidence and plan already gathered. Use update_plan for the checklist and invoke the next Causyne execution tool now. '
|
|
2148
|
+
+ 'There is no peer Proceed button in this interface. Ask only through request_decision if a genuinely unresolved consequential choice blocks progress; '
|
|
2149
|
+
+ 'routine details with a safe default do not require another approval. Do not repeat completed searches or write another plan artifact.' });
|
|
2150
|
+
this.emitEvent({ type: 'status', message: 'Continuing the requested implementation from the existing plan…' });
|
|
2151
|
+
auditLog.log({ event: 'plan_handoff_recovered', taskId: this.taskId, provider: this.config.provider });
|
|
2152
|
+
this.memoryManager.saveHistory(this.messages);
|
|
2153
|
+
continue;
|
|
2154
|
+
}
|
|
1828
2155
|
if (isActionable && isGenericHandoffResponse(contentText) && (hasExternalActions || this.stepsCompleted > 0)) {
|
|
1829
2156
|
this.emitEvent({ type: 'error', message: 'The provider returned a generic handoff after tool activity. The requested outcome was not verified; no completion is recorded.' });
|
|
1830
2157
|
this.memoryManager.saveHistory(this.messages);
|
|
@@ -2021,20 +2348,13 @@ export class AgentLoop {
|
|
|
2021
2348
|
}
|
|
2022
2349
|
}
|
|
2023
2350
|
// Web Visual Validation Guard (Anti-Slop / Transcendence)
|
|
2024
|
-
const isWebTask = !isLaunchOnlyPrompt(taskPrompt) && isWebIntent(taskPrompt);
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
// to use a tool that could not run. Ask for the capability once;
|
|
2032
|
-
// if it was declined, fall through to the path that needs nothing.
|
|
2033
|
-
let visionReady = false;
|
|
2034
|
-
let visionDeclined = false;
|
|
2035
|
-
let browserReady = false;
|
|
2036
|
-
let browserDeclined = false;
|
|
2037
|
-
let browserRuntimeError = '';
|
|
2351
|
+
const isWebTask = !isLaunchOnlyPrompt(taskPrompt) && !isPlanningOnlyRequest(taskPrompt) && isWebIntent(taskPrompt);
|
|
2352
|
+
let browserReady = false;
|
|
2353
|
+
let browserDeclined = false;
|
|
2354
|
+
let browserRuntimeError = '';
|
|
2355
|
+
let visionReady = false;
|
|
2356
|
+
let visionDeclined = false;
|
|
2357
|
+
if (isWebTask) {
|
|
2038
2358
|
try {
|
|
2039
2359
|
const { groupStatus, isGroupDeclined } = await import('./provisioning/capabilityProvisioner.js');
|
|
2040
2360
|
visionReady = groupStatus('vision').state === 'ready';
|
|
@@ -2053,6 +2373,9 @@ export class AgentLoop {
|
|
|
2053
2373
|
}
|
|
2054
2374
|
}
|
|
2055
2375
|
catch (e) { /* treat as not ready */ }
|
|
2376
|
+
}
|
|
2377
|
+
if (isWebTask && !this.webGuardFired && this.stepsCompleted > 0) {
|
|
2378
|
+
const hasVision = this.llm.supportsVision !== false;
|
|
2056
2379
|
let webGuardMsg = '';
|
|
2057
2380
|
if (browserRuntimeError) {
|
|
2058
2381
|
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.]`;
|
|
@@ -2077,7 +2400,7 @@ export class AgentLoop {
|
|
|
2077
2400
|
this.emitEvent({ type: 'status', message: '⚡ Anti-Slop Check: Visual/semantic verification recommended.' });
|
|
2078
2401
|
this.messages.push({ role: 'system', content: webGuardMsg });
|
|
2079
2402
|
this.memoryManager.saveHistory(this.messages);
|
|
2080
|
-
if (browserReady || (hasVision && visionReady)) {
|
|
2403
|
+
if (!this.webVerificationState.htmlInspected || browserReady || (hasVision && visionReady)) {
|
|
2081
2404
|
continue;
|
|
2082
2405
|
}
|
|
2083
2406
|
}
|
|
@@ -2085,9 +2408,14 @@ export class AgentLoop {
|
|
|
2085
2408
|
// Tool availability and a completed plan are not evidence of visual
|
|
2086
2409
|
// inspection. A failed browser/capture attempt must not become a
|
|
2087
2410
|
// successful task merely because the provider says "verified".
|
|
2088
|
-
|
|
2089
|
-
|
|
2090
|
-
&&
|
|
2411
|
+
const isVerified = Boolean(this.webVerificationState.browserActUsed ||
|
|
2412
|
+
this.webVerificationState.screenshotTaken ||
|
|
2413
|
+
(!browserReady && this.webVerificationState.htmlInspected));
|
|
2414
|
+
if (isWebTask && !browserReady && this.webVerificationState.htmlInspected
|
|
2415
|
+
&& !this.webVerificationState.browserActUsed && !this.webVerificationState.screenshotTaken) {
|
|
2416
|
+
this.emitEvent({ type: 'notice', message: 'Source inspection completed. Rendered-page and visual verification were not performed because the browser runtime is unavailable.' });
|
|
2417
|
+
}
|
|
2418
|
+
if (isWebTask && this.stepsCompleted > 0 && !isVerified) {
|
|
2091
2419
|
this.emitEvent({
|
|
2092
2420
|
type: 'error',
|
|
2093
2421
|
message: 'The web files may have changed, but rendered-page verification did not succeed. The task remains unverified; no completion is recorded.'
|
|
@@ -2225,6 +2553,39 @@ export class AgentLoop {
|
|
|
2225
2553
|
continue;
|
|
2226
2554
|
}
|
|
2227
2555
|
let args = repair.args;
|
|
2556
|
+
const schemaErrors = validateToolArguments(args, toolSchema);
|
|
2557
|
+
if (schemaErrors.length) {
|
|
2558
|
+
const diagnostic = generateSelfRepairDiagnostic(functionName, args, schemaErrors.join('; '), toolSchema);
|
|
2559
|
+
this.messages.push({ role: 'tool', tool_call_id: toolCall.id, name: functionName,
|
|
2560
|
+
content: JSON.stringify({ ...diagnostic, code: 'INVALID_TOOL_ARGUMENTS', expectedSchema: toolSchema }) });
|
|
2561
|
+
this.emitEvent({ type: 'step_error', tool: functionName, error: schemaErrors.join('; '), toolCallId: toolCall.id });
|
|
2562
|
+
auditLog.log({ event: 'tool_argument_validation_failed', taskId: this.taskId, tool: functionName });
|
|
2563
|
+
continue;
|
|
2564
|
+
}
|
|
2565
|
+
// Introspection Attractor Loop Breaker: Protect Causyne Agent runtime files from accidental self-debugging
|
|
2566
|
+
if (['fs_read', 'fs_search', 'codebase_search', 'grep_search', 'code_searcher'].includes(functionName)) {
|
|
2567
|
+
const targetStr = String(args?.path || args?.query || args?.searchPath || '');
|
|
2568
|
+
const isAgentDevTask = /\b(causyne|agentLoop|smartToolsUse|toolSelfRepair)\b/i.test(this.currentTaskPrompt || this.userPrompt || '');
|
|
2569
|
+
if (!isAgentDevTask && (targetStr.includes('src/smartToolsUse') || targetStr.includes('src/agentLoop') || targetStr.includes('src/tools/generateMediaViaApi'))) {
|
|
2570
|
+
this.messages.push({
|
|
2571
|
+
role: 'tool',
|
|
2572
|
+
tool_call_id: toolCall.id,
|
|
2573
|
+
name: functionName,
|
|
2574
|
+
content: JSON.stringify({
|
|
2575
|
+
success: false,
|
|
2576
|
+
error: 'Introspection Blocked: Do not inspect Causyne Agent internal runtime files during application tasks. Fulfill the user request directly in the target directory.'
|
|
2577
|
+
})
|
|
2578
|
+
});
|
|
2579
|
+
continue;
|
|
2580
|
+
}
|
|
2581
|
+
}
|
|
2582
|
+
const phaseAdmission = this.smartToolsGovernor.interceptAction(functionName, args || {});
|
|
2583
|
+
if (!phaseAdmission.allowed) {
|
|
2584
|
+
this.messages.push({ role: 'tool', tool_call_id: toolCall.id, name: functionName,
|
|
2585
|
+
content: JSON.stringify({ success: false, checkpoint: 'synthesis', error: phaseAdmission.reason }) });
|
|
2586
|
+
auditLog.log({ event: 'smart_tools_checkpoint', taskId: this.taskId, tool: functionName, phase: 'synthesis' });
|
|
2587
|
+
continue;
|
|
2588
|
+
}
|
|
2228
2589
|
if (repair.repaired && repair.repairs.length > 0) {
|
|
2229
2590
|
this.debugLog(`[TOOL SELF-REPAIR] Healed tool call '${functionName}': ${repair.repairs.join(', ')}`);
|
|
2230
2591
|
}
|
|
@@ -2295,10 +2656,10 @@ export class AgentLoop {
|
|
|
2295
2656
|
this.abort();
|
|
2296
2657
|
break;
|
|
2297
2658
|
}
|
|
2298
|
-
if (isAuthoringTask && this.stallGuard.distinctInspectionCount ===
|
|
2659
|
+
if (isAuthoringTask && (this.stallGuard.distinctInspectionCount === 3 || this.stallGuard.distinctInspectionCount === 6)) {
|
|
2299
2660
|
this.messages.push({
|
|
2300
2661
|
role: 'system',
|
|
2301
|
-
content: `[CRITICAL ACTION MANDATE: You have performed
|
|
2662
|
+
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.]`
|
|
2302
2663
|
});
|
|
2303
2664
|
}
|
|
2304
2665
|
this.emitEvent({ type: 'step_start', tool: functionName, args: args, toolCallId: toolCall.id });
|
|
@@ -2355,7 +2716,11 @@ export class AgentLoop {
|
|
|
2355
2716
|
}
|
|
2356
2717
|
// 4-Layer Security Sandbox Validation
|
|
2357
2718
|
// 2. Sandbox Security Validation (CRITICAL FIX: Prevent Infinite Loop on Block)
|
|
2358
|
-
|
|
2719
|
+
let validation = this.sandbox.validate(functionName, args);
|
|
2720
|
+
if (!validation.allowed && /^Path outside allowed workspace:/.test(validation.reason || '')
|
|
2721
|
+
&& isOutputRecoveryRead(functionName, args.path, recoveryPaths)) {
|
|
2722
|
+
validation = { allowed: true, risk: 'safe', reason: 'Read exact tool output referenced by this session' };
|
|
2723
|
+
}
|
|
2359
2724
|
if (!validation.allowed) {
|
|
2360
2725
|
this.consecutiveBlockedActions++;
|
|
2361
2726
|
// Hard Circuit Breaker (Transcendence Context Consciousness)
|
|
@@ -2564,6 +2929,7 @@ export class AgentLoop {
|
|
|
2564
2929
|
// errors. It only rewinds reasoning; it never replays side effects.
|
|
2565
2930
|
let result;
|
|
2566
2931
|
let duration;
|
|
2932
|
+
this.efficiencyBudget.recordAction();
|
|
2567
2933
|
try {
|
|
2568
2934
|
const startTime = Date.now();
|
|
2569
2935
|
const actStart = performance.now();
|
|
@@ -2636,15 +3002,24 @@ export class AgentLoop {
|
|
|
2636
3002
|
if (result && result.success !== false && !result.error && ['fs_write', 'fs_edit', 'MultiEdit'].includes(functionName)) {
|
|
2637
3003
|
this.recordWebArtifact(args.path || args.file_path);
|
|
2638
3004
|
}
|
|
3005
|
+
if (result && result.success !== false && !result.error && ['fs_read', 'view_file', 'read_file'].includes(functionName)) {
|
|
3006
|
+
const filePath = String(args.path || args.file_path || args.AbsolutePath || args.target || '');
|
|
3007
|
+
if (/\.(html|htm|css|jsx|tsx|vue|svelte)$/i.test(filePath)) {
|
|
3008
|
+
this.webVerificationState.htmlInspected = true;
|
|
3009
|
+
}
|
|
3010
|
+
}
|
|
2639
3011
|
if (['screenshot', 'vision_inspect_ui'].includes(functionName) && this.llm.supportsVision !== false && result?.success === true && result?._is_image_marker === true) {
|
|
2640
3012
|
this.webVerificationState.screenshotTaken = true;
|
|
2641
3013
|
}
|
|
2642
3014
|
if (functionName === 'browser_act' && result?.success === true) {
|
|
2643
3015
|
const browserResults = Array.isArray(result.data) ? result.data : [];
|
|
2644
|
-
if (browserResults.some((item) => ['snapshot', 'scrape'].includes(item?.action)
|
|
3016
|
+
if (browserResults.some((item) => ['snapshot', 'scrape'].includes(item?.action)
|
|
3017
|
+
&& Array.isArray(item?.data?.runtimeErrors) && item.data.runtimeErrors.length === 0)) {
|
|
2645
3018
|
this.webVerificationState.browserActUsed = true;
|
|
2646
3019
|
}
|
|
2647
3020
|
}
|
|
3021
|
+
if (result?.success === true && ['fs_write', 'fs_edit', 'fs_delete', 'fs_move', 'MultiEdit'].includes(functionName))
|
|
3022
|
+
clearSysRunCache();
|
|
2648
3023
|
// The journal is the observer's own record of what actually ran. It
|
|
2649
3024
|
// is written only after post-hook review, so a formatter that rejects
|
|
2650
3025
|
// a write is remembered as a failure rather than a success.
|
|
@@ -2794,6 +3169,13 @@ export class AgentLoop {
|
|
|
2794
3169
|
this.emitEvent({ type: 'status', message: `⚡ Tier budget extended (+${extensionBatch} steps unlocked, new limit: ${this.maxSteps}). Resuming task...` });
|
|
2795
3170
|
}
|
|
2796
3171
|
}
|
|
3172
|
+
// SmartToolsUse tracks actual local tool calls, without denying
|
|
3173
|
+
// useful inspection during long research or code tasks.
|
|
3174
|
+
const phaseNudge = this.smartToolsGovernor.observe(functionName, args || {}, result);
|
|
3175
|
+
if (phaseNudge)
|
|
3176
|
+
this._smartToolsNudge = phaseNudge;
|
|
3177
|
+
else if (this.smartToolsGovernor.snapshot().phase === 'execution')
|
|
3178
|
+
this._smartToolsNudge = null;
|
|
2797
3179
|
// Feed result back to LLM (4. OBSERVE)
|
|
2798
3180
|
if (result && result._is_image_marker) {
|
|
2799
3181
|
if (!this.llm.supportsVision) {
|
|
@@ -2854,78 +3236,45 @@ export class AgentLoop {
|
|
|
2854
3236
|
// Per tool, not one number for all of them. A build log and a
|
|
2855
3237
|
// source file are not equally worth their space in the window.
|
|
2856
3238
|
const MAX_RESULT_CHARS = resultCapFor(functionName);
|
|
3239
|
+
const originalFingerprint = createHash('sha256').update(resultString).digest('hex');
|
|
2857
3240
|
let spill = null;
|
|
2858
|
-
if (resultString.length > MAX_RESULT_CHARS) {
|
|
2859
|
-
|
|
2860
|
-
|
|
2861
|
-
|
|
2862
|
-
|
|
2863
|
-
|
|
2864
|
-
|
|
2865
|
-
|
|
2866
|
-
|
|
2867
|
-
|
|
2868
|
-
|
|
2869
|
-
|
|
2870
|
-
|
|
2871
|
-
|
|
2872
|
-
|
|
2873
|
-
|
|
2874
|
-
|
|
2875
|
-
|
|
2876
|
-
|
|
2877
|
-
|
|
2878
|
-
|
|
2879
|
-
budget -= allowance;
|
|
2880
|
-
truncatedResult[key] = allowance < value.length
|
|
2881
|
-
? value.substring(0, allowance) + TRUNCATION_NOTICE
|
|
2882
|
-
: value;
|
|
2883
|
-
}
|
|
2884
|
-
else if (value !== null && typeof value === 'object') {
|
|
2885
|
-
const serialized = JSON.stringify(value);
|
|
2886
|
-
if (serialized.length > budget) {
|
|
2887
|
-
truncatedResult[key] = spill
|
|
2888
|
-
? `[${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.]`
|
|
2889
|
-
: `[${key} omitted: ${(serialized.length / 1024).toFixed(1)} KB. Re-run with narrower arguments if you need it.]`;
|
|
2890
|
-
}
|
|
2891
|
-
else {
|
|
2892
|
-
budget -= serialized.length;
|
|
2893
|
-
truncatedResult[key] = value;
|
|
2894
|
-
}
|
|
2895
|
-
}
|
|
2896
|
-
else {
|
|
2897
|
-
truncatedResult[key] = value;
|
|
3241
|
+
if (resultString.length > Math.min(MAX_RESULT_CHARS, 2500)) {
|
|
3242
|
+
const document = renderSpillDocument(result, { taskId: this.taskId, step: this.stepsCompleted, tool: functionName });
|
|
3243
|
+
const stored = processToolOutputWithStore(this.taskId, toolCall.id, document);
|
|
3244
|
+
if (stored.isTruncated && stored.diskPath) {
|
|
3245
|
+
spill = { path: stored.diskPath };
|
|
3246
|
+
resultString = JSON.stringify({
|
|
3247
|
+
...(typeof result?.success === 'boolean' ? { success: result.success } : {}),
|
|
3248
|
+
...(typeof result?.error === 'string' ? { error: result.error.slice(0, 500) } : {}),
|
|
3249
|
+
output: stored.contentForModel
|
|
3250
|
+
});
|
|
3251
|
+
}
|
|
3252
|
+
else if (document.length > 2500) {
|
|
3253
|
+
// Compatibility recovery store if the primary store is unavailable.
|
|
3254
|
+
// spillToolResult preserves the full document; never truncate on failure.
|
|
3255
|
+
const fallback = spillToolResult(result, { taskId: this.taskId, step: this.stepsCompleted, tool: functionName });
|
|
3256
|
+
if (fallback) {
|
|
3257
|
+
spill = fallback;
|
|
3258
|
+
resultString = JSON.stringify({
|
|
3259
|
+
...(typeof result?.success === 'boolean' ? { success: result.success } : {}),
|
|
3260
|
+
output: document.slice(0, 1000) + buildDecayPointer(fallback) + document.slice(-500)
|
|
3261
|
+
});
|
|
2898
3262
|
}
|
|
2899
3263
|
}
|
|
2900
|
-
|
|
2901
|
-
|
|
2902
|
-
// B5 — OBSERVATION COMPACTION.
|
|
2903
|
-
//
|
|
2904
|
-
// ARC Prize measured the same GPT-6 Astra weights at 62.7% under a
|
|
2905
|
-
// note-passing harness and 99.9% under one that compacts and reuses
|
|
2906
|
-
// prior work — with 49% FEWER tokens. Re-reading a file the agent
|
|
2907
|
-
// already read, or re-listing an unchanged directory, pays full
|
|
2908
|
-
// price for bytes that are verbatim identical to bytes already in
|
|
2909
|
-
// the window.
|
|
2910
|
-
//
|
|
2911
|
-
// Replacing the repeat with a pointer is not a loss of information:
|
|
2912
|
-
// "identical to step N" is strictly MORE informative than the bytes
|
|
2913
|
-
// alone, because it tells the model the thing did not change —
|
|
2914
|
-
// which after an edit is exactly the question it is asking.
|
|
2915
|
-
//
|
|
2916
|
-
// Only payloads worth the trade are folded. A small `{"success":true}`
|
|
2917
|
-
// ack costs less than the pointer that would replace it, and every
|
|
2918
|
-
// Plan updates would otherwise collide with unrelated plan updates.
|
|
3264
|
+
}
|
|
3265
|
+
// Fold identical bytes without treating them as proof of external state.
|
|
2919
3266
|
const OBSERVATION_FOLD_FLOOR = 600;
|
|
2920
3267
|
if (resultString.length >= OBSERVATION_FOLD_FLOOR) {
|
|
2921
|
-
const digest =
|
|
3268
|
+
const digest = originalFingerprint;
|
|
2922
3269
|
const seenAt = this._observationDigests.get(digest);
|
|
2923
3270
|
if (seenAt !== undefined) {
|
|
2924
3271
|
resultString = JSON.stringify({
|
|
2925
|
-
success:
|
|
2926
|
-
|
|
2927
|
-
output: `
|
|
2928
|
-
+
|
|
3272
|
+
...(result && typeof result.success === 'boolean' ? { success: result.success } : {}),
|
|
3273
|
+
identicalResult: true,
|
|
3274
|
+
output: `The serialized tool response matches step ${seenAt}. This does not prove external state is unchanged. `
|
|
3275
|
+
+ (spill
|
|
3276
|
+
? `Full output is saved at ${spill.path}; read a relevant range if needed.`
|
|
3277
|
+
: 'The earlier response may have left the active context; make a targeted read if its details are needed.')
|
|
2929
3278
|
});
|
|
2930
3279
|
}
|
|
2931
3280
|
else {
|
|
@@ -2982,14 +3331,48 @@ export class AgentLoop {
|
|
|
2982
3331
|
cachedPromptTokens: usage.cachedPromptTokens || 0,
|
|
2983
3332
|
measurement: 'provider_reported_partial', costBasis: 'external_subscription_unavailable'
|
|
2984
3333
|
});
|
|
3334
|
+
try {
|
|
3335
|
+
this.efficiencyBudget.recordUsage(usage);
|
|
3336
|
+
}
|
|
3337
|
+
catch (checkpoint) {
|
|
3338
|
+
if (checkpoint instanceof EfficiencyCheckpoint)
|
|
3339
|
+
e = checkpoint;
|
|
3340
|
+
else
|
|
3341
|
+
throw checkpoint;
|
|
3342
|
+
}
|
|
2985
3343
|
}
|
|
2986
3344
|
}
|
|
2987
|
-
if (e
|
|
3345
|
+
if (e instanceof EfficiencyCheckpoint) {
|
|
3346
|
+
this.messages.push({ role: 'system', content: `[Unfinished task checkpoint] ${e.message}` });
|
|
3347
|
+
this.memoryManager.saveHistory(this.messages);
|
|
3348
|
+
this.emitEvent({ type: 'budget_warning', message: e.message });
|
|
3349
|
+
auditLog.log({ event: 'efficiency_checkpoint', taskId: this.taskId, reason: e.reason,
|
|
3350
|
+
...this.efficiencyBudget.snapshot() });
|
|
3351
|
+
break;
|
|
3352
|
+
}
|
|
3353
|
+
if (e?.code === 'AGY_TOKEN_BUDGET' || e?.code === 'TASK_TOKEN_BUDGET' || e?.code === 'PROVIDER_TOKEN_BUDGET'
|
|
3354
|
+
|| e?.code === 'AGY_NATIVE_ACTION_BUDGET' || e?.code === 'AGY_DESKTOP_TASK_LIMIT') {
|
|
3355
|
+
this.messages.push({ role: 'system', content: `[Unfinished task checkpoint] ${e.message}` });
|
|
3356
|
+
this.memoryManager.saveHistory(this.messages);
|
|
2988
3357
|
this.emitEvent({ type: 'budget_warning', message: e.message });
|
|
2989
3358
|
auditLog.log({ event: 'task_stopped_on_budget', taskId: this.taskId,
|
|
2990
3359
|
used: this.tokenTracker.taskTokens, limit: e.tokenLimit || this.tokenTracker.budget?.maxTokensPerTask || 0 });
|
|
2991
3360
|
break;
|
|
2992
3361
|
}
|
|
3362
|
+
if (e?.code === 'PROVIDER_REASONING_ONLY' && e.continuationSafe === true && reasoningOnlyRecoveries++ === 0) {
|
|
3363
|
+
this.messages.push({ role: 'system', content: '[Response recovery] The previous turn contained reasoning but no executable tool call or user response. '
|
|
3364
|
+
+ 'Continue from the existing draft in this session. Emit the next actual Causyne tool call with all required arguments. '
|
|
3365
|
+
+ 'Do not repeat searches, dependency probes, or prior actions. Do not claim completion until a tool result verifies it. '
|
|
3366
|
+
+ 'If a provider key, balance, or user decision is required, report that precise blocker.' });
|
|
3367
|
+
this.memoryManager.saveHistory(this.messages);
|
|
3368
|
+
this.emitEvent({ type: 'notice', message: 'The peer returned reasoning without an action; continuing once from its existing session.' });
|
|
3369
|
+
auditLog.log({ event: 'reasoning_only_recovery', taskId: this.taskId, recovery: reasoningOnlyRecoveries });
|
|
3370
|
+
continue;
|
|
3371
|
+
}
|
|
3372
|
+
if (e?.code === 'PROVIDER_REASONING_ONLY') {
|
|
3373
|
+
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.' });
|
|
3374
|
+
break;
|
|
3375
|
+
}
|
|
2993
3376
|
if (e?.code === 'AGY_EXPLORATION_LOOP' || e?.code === 'AGENT_EXPLORATION_LOOP' || e?.code === 'STALL_EXPLORATION_LOOP') {
|
|
2994
3377
|
auditLog.log({ event: 'media_exploration_checkpoint', taskId: this.taskId,
|
|
2995
3378
|
inspectionCount: e.inspectionCount, recovery: mediaExplorationRecoveries });
|
|
@@ -3109,6 +3492,8 @@ export class AgentLoop {
|
|
|
3109
3492
|
}
|
|
3110
3493
|
// V5: Classify errors for intelligent retry decisions
|
|
3111
3494
|
classifyError(error) {
|
|
3495
|
+
if (error?.code === 'PROVIDER_NO_PROGRESS')
|
|
3496
|
+
return 'fatal';
|
|
3112
3497
|
if (error?.code === 'AGY_NATIVE_ACTION_DENIED'
|
|
3113
3498
|
|| error?.code === 'AGY_NATIVE_ACTION_BUDGET'
|
|
3114
3499
|
|| error?.code === 'AGY_DESKTOP_TASK_LIMIT')
|
|
@@ -3196,8 +3581,8 @@ export class AgentLoop {
|
|
|
3196
3581
|
if (val.startsWith('~')) {
|
|
3197
3582
|
args[field] = val.replace(/^~(?=$|[\\/])/, os.homedir());
|
|
3198
3583
|
}
|
|
3199
|
-
else if (!
|
|
3200
|
-
args[field] =
|
|
3584
|
+
else if (!path.isAbsolute(val)) {
|
|
3585
|
+
args[field] = path.resolve(this.workspaceRoot || process.cwd(), val);
|
|
3201
3586
|
}
|
|
3202
3587
|
}
|
|
3203
3588
|
}
|