@causyne/agent 1.19.0 → 1.20.5
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/README.md +0 -18
- package/package.json +1 -1
- package/src/acp/client.js +2 -1
- package/src/acp/client.ts +2 -1
- package/src/acp/server.js +5 -6
- package/src/acp/server.ts +4 -6
- package/src/agentLoop.d.ts +1 -0
- package/src/agentLoop.js +505 -241
- package/src/agentLoop.ts +527 -258
- package/src/agentPolicy.js +9 -0
- package/src/agentPolicy.ts +9 -0
- package/src/approvalPolicy.js +55 -0
- package/src/approvalPolicy.ts +66 -0
- package/src/browser/browserRuntime.js +217 -14
- package/src/browser/browserRuntime.ts +255 -14
- package/src/browser/causyneBrowser.js +1215 -68
- package/src/browser/causyneBrowser.ts +1340 -72
- package/src/cliMode.js +66 -37
- package/src/commands.js +343 -72
- package/src/config.js +22 -12
- package/src/continuum/ingest.js +1 -1
- package/src/continuum/ingest.ts +1 -1
- package/src/continuum/ui/continuumPicker.js +18 -1
- package/src/continuum/ui/continuumPicker.ts +19 -1
- package/src/dynamicCatalogue.js +87 -20
- package/src/dynamicCatalogue.ts +85 -15
- package/src/launchIntent.js +40 -0
- package/src/launchIntent.ts +49 -0
- package/src/memoryManager.js +36 -8
- package/src/modelCatalogue.js +2 -0
- package/src/planCache.js +320 -11
- package/src/planCache.ts +402 -13
- package/src/providers/acp.js +67 -1
- package/src/providers/acp.ts +65 -2
- package/src/providers/antigravity.d.ts +5 -1
- package/src/providers/antigravity.js +643 -32
- package/src/providers/antigravity.ts +671 -33
- package/src/providers/base.d.ts +9 -0
- package/src/providers/factory.js +2 -0
- package/src/providers/pi.js +157 -0
- package/src/providers/pi.ts +144 -0
- package/src/provisioning/capabilityProvisioner.js +17 -0
- package/src/provisioning/capabilityTools.js +1 -1
- package/src/sandbox.js +30 -39
- package/src/sessionJournal.js +66 -10
- package/src/sessionJournal.ts +84 -10
- package/src/taskShape.js +9 -9
- package/src/taskShape.ts +9 -9
- package/src/timeMachine.js +124 -0
- package/src/timeMachine.ts +141 -0
- package/src/toolPacks.js +4 -10
- package/src/tools/archive.js +196 -59
- package/src/tools/archive.ts +220 -0
- package/src/tools/browserAutomator.js +78 -9
- package/src/tools/browserAutomator.ts +90 -9
- package/src/tools/desktopOpen.js +114 -31
- package/src/tools/desktopOpen.ts +144 -0
- package/src/tools/gitExec.js +5 -3
- package/src/tools/nativeEngine.js +4 -3
- package/src/tools/nativeEngine.ts +5 -3
- package/src/tools/openSourceToolProvisioner.js +5 -4
- package/src/tools/openSourceToolProvisioner.ts +5 -4
- package/src/tools/registry.js +3 -0
- package/src/tools/screenshot.js +55 -71
- package/src/tools/screenshot.ts +70 -0
- package/src/tools/sysRun.js +284 -117
- package/src/tools/sysRun.ts +347 -0
- package/src/tools/toolSelfRepair.js +109 -2
- package/src/tools/toolSelfRepair.ts +100 -2
- package/src/tools/updatePlan.js +49 -1
- package/src/tools/updatePlan.ts +43 -1
- package/src/tools/viewImage.js +93 -78
- package/src/tools/viewImage.ts +116 -0
- package/src/tools/webFetch.js +20 -6
- package/src/tools/webFetch.ts +26 -6
- package/src/tui/block.d.ts +1 -0
- package/src/tui/chatRenderer.d.ts +21 -0
- package/src/tui/chatRenderer.js +118 -45
- package/src/tui/clipboardSync.js +28 -1
- package/src/tui/clipboardSync.ts +26 -1
- package/src/tui/codeProgress.js +299 -0
- package/src/tui/codeProgress.ts +304 -0
- package/src/tui/codeStreamRenderer.js +116 -0
- package/src/tui/codeStreamRenderer.ts +124 -0
- package/src/tui/commandPresentation.js +11 -0
- package/src/tui/commandPresentation.ts +18 -0
- package/src/tui/completion.js +45 -13
- package/src/tui/composerControls.js +66 -0
- package/src/tui/composerControls.ts +78 -0
- package/src/tui/diff.d.ts +2 -0
- package/src/tui/home.js +4 -2
- package/src/tui/homeTransition.js +21 -0
- package/src/tui/homeTransition.ts +27 -0
- package/src/tui/homeView.js +62 -0
- package/src/tui/homeView.ts +91 -0
- package/src/tui/layout.js +46 -0
- package/src/tui/layout.ts +52 -0
- package/src/tui/messageActionPlacement.js +16 -0
- package/src/tui/messageActionPlacement.ts +25 -0
- package/src/tui/messageInteraction.js +221 -0
- package/src/tui/messageInteraction.ts +275 -0
- package/src/tui/modelPicker.js +13 -0
- package/src/tui/modelPicker.ts +12 -0
- package/src/tui/mouseHover.js +6 -0
- package/src/tui/mouseHover.ts +5 -0
- package/src/tui/prompt.js +199 -52
- package/src/tui/resizeRecovery.js +15 -0
- package/src/tui/resizeRecovery.ts +27 -0
- package/src/tui/scrollInteraction.js +97 -0
- package/src/tui/scrollInteraction.ts +189 -0
- package/src/tui/sessionLayout.js +12 -0
- package/src/tui/sessionLayout.ts +12 -0
- package/src/tui/sessionPicker.js +280 -0
- package/src/tui/sessionPicker.ts +364 -0
- package/src/tui/sessionSidebar.js +78 -0
- package/src/tui/sessionSidebar.ts +95 -0
- package/src/tui/setup.js +1 -1
- package/src/tui/setup.ts +1 -1
- package/src/tui/stageSurface.js +128 -57
- package/src/tui/statusLine.js +5 -5
- package/src/tui/text.d.ts +5 -0
- package/src/tui/textLayout.js +23 -0
- package/src/tui/textLayout.ts +28 -0
- package/src/tui/viewport.js +204 -279
- package/src/tui/viewport.ts +326 -0
- package/src/types/contracts.ts +54 -0
- package/src/utils/paths.js +5 -4
- package/src/utils/paths.ts +5 -5
package/src/agentLoop.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createHash } from 'crypto';
|
|
2
|
-
import { processApprovalScope } from './approvalGrants.js';
|
|
2
|
+
import { processApprovalScope, createApprovalScope } from './approvalGrants.js';
|
|
3
3
|
import { pruneSessions as pruneEmbodimentSessions, describeSession } from './embodimentSession.js';
|
|
4
4
|
import { WorkspacePerception } from './perception.js';
|
|
5
5
|
import { audioFormatForMimeType } from './providers/base.js';
|
|
@@ -17,12 +17,15 @@ import { MemoryManager } from './memoryManager.js';
|
|
|
17
17
|
import { cortexDb } from './cortex/vectorDb.js';
|
|
18
18
|
import { buildStructuralSummary, condenseAndSave } from './cortex/autoCondenser.js';
|
|
19
19
|
import { analyzeTask, buildTaskBrief, packsFromShape } from './taskShape.js';
|
|
20
|
-
import { lookupPlan, recordPlan, recordMiss, renderPlanHint, toStep } from './planCache.js';
|
|
20
|
+
import { lookupPlan, recordPlan, recordPlanAsync, recordMiss, renderPlanHint, toStep, recordAPCPipelineLatency, lookupAlternativeStep, failureClass } from './planCache.js';
|
|
21
21
|
import { routedConfig } from './modelRouter.js';
|
|
22
22
|
import { assessStep, isThrashing } from './uncertainty.js';
|
|
23
23
|
import { assessDecisionRequirement, isMutatingToolCall, requiresImplementationPlan } from './decisionPolicy.js';
|
|
24
|
+
import { requiresToolApproval, withToolAutonomyMode } from './approvalPolicy.js';
|
|
25
|
+
import { AGENT_USER_POLICY } from './agentPolicy.js';
|
|
24
26
|
import { VFETracker } from './vfeTracker.js';
|
|
25
27
|
import { coldObserver } from './observer/coldObserver.js';
|
|
28
|
+
import { TimeMachine, recoveryUserMessage } from './timeMachine.js';
|
|
26
29
|
import { routePacks, packForTool, isCoreTool, isGameIntent, isWebIntent, getPackCatalogue, PACK_PLAYBOOKS, PACKS } from './toolPacks.js';
|
|
27
30
|
import { resolveCharPool, measureMessages, resultCapFor, decayToolResults, buildWindow, compactInPlace, describeDroppedMessages, sanitizeSequences, applyProgressiveCompaction, snipOversizedToolOutputs } from './contextManager.js';
|
|
28
31
|
// Provider imports
|
|
@@ -35,24 +38,53 @@ import { analyzeFiles, formatFindings, isScannableFile } from './slopDetector.js
|
|
|
35
38
|
import { suggestMovements, formatMovementBrief } from './designPalettes.js';
|
|
36
39
|
import { createProvider } from './providers/factory.js';
|
|
37
40
|
import { resolveMentionedContext } from './promptMentions.js';
|
|
38
|
-
|
|
41
|
+
import { isLaunchOnlyPrompt, launchScopeError } from './launchIntent.js';
|
|
42
|
+
import { StreamingCodePreview, NativeCodeObserver, codeProgressFromAction } from './tui/codeProgress.js';
|
|
43
|
+
export function isActionableTaskPrompt(text) {
|
|
44
|
+
const t = (text || '').trim();
|
|
45
|
+
if (!t)
|
|
46
|
+
return false;
|
|
47
|
+
const pureGreeting = /^(hi|hello|hey|yo|good\s+(morning|afternoon|evening))[.!?, ]*$/i.test(t);
|
|
48
|
+
if (pureGreeting)
|
|
49
|
+
return false;
|
|
50
|
+
const actionKeywords = /\b(create|build|make|write|code|implement|fix|optimize|refactor|generate|add|setup|install|run|open|launch|start|play|serve|preview|deploy|delete|remove|update|change|test|review|inspect|search|find)\b/i;
|
|
51
|
+
return actionKeywords.test(t);
|
|
52
|
+
}
|
|
53
|
+
export function isExecutionOrLaunchTaskPrompt(text) {
|
|
54
|
+
const t = (text || '').trim();
|
|
55
|
+
if (!t)
|
|
56
|
+
return false;
|
|
57
|
+
return /\b(open|launch|start|run|play|serve|preview)\b/i.test(t)
|
|
58
|
+
&& !/\b(create|build|make|write|code|implement|generate|refactor)\b/i.test(t);
|
|
59
|
+
}
|
|
60
|
+
export function isCodeAuthoringTaskPrompt(text) {
|
|
61
|
+
const t = (text || '').trim();
|
|
62
|
+
if (!t)
|
|
63
|
+
return false;
|
|
64
|
+
if (isExecutionOrLaunchTaskPrompt(t))
|
|
65
|
+
return false;
|
|
66
|
+
return /\b(create|build|make|write|code|implement|generate|game|3js|threejs|three\.js|app)\b/i.test(t);
|
|
67
|
+
}
|
|
68
|
+
export function isDirectGameTask(text) {
|
|
69
|
+
return /\b(three\.?js|3js|webgl|canvas|html5|pygame)\b/i.test(text)
|
|
70
|
+
&& !/\b(godot|unity|unreal|full engine)\b/i.test(text);
|
|
71
|
+
}
|
|
72
|
+
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.
|
|
39
73
|
|
|
40
74
|
# Your Capabilities
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
- **Office & Creative Work**: Researching and writing massive 100-page theses, novels, or film scripts. Writing scripts to output Excel, Word, or PDF files from raw data.
|
|
45
|
-
- **Web & Media**: Searching the web, downloading files, and opening browsers to specific videos (YouTube, Netflix) using cross-platform terminal commands (e.g., AppleScript for macOS, PowerShell for Windows, or xdg-open for Linux).
|
|
75
|
+
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.
|
|
76
|
+
|
|
77
|
+
${AGENT_USER_POLICY}
|
|
46
78
|
|
|
47
|
-
#
|
|
48
|
-
|
|
49
|
-
2. **Ambition vs. Precision**: Be highly ambitious and creative on new tasks. Be surgically precise on existing codebases. Treat existing code with respect, never touching unrelated files or fixing unrelated bugs.
|
|
50
|
-
3. **Conventions**: Rigorously adhere to existing project conventions. Mimic the style, structure, framework choices, and architectural patterns of existing code. NEVER assume a library/framework is available; verify it first.
|
|
79
|
+
# Project Conventions
|
|
80
|
+
Follow the selected project's existing style and architecture. Check dependencies and tool schemas before use. Preserve unrelated behavior.
|
|
51
81
|
|
|
52
82
|
# Operational Guidelines & Communication
|
|
83
|
+
- **Language Reflection**: Dynamically reflect and match the exact language used by the user in their prompt. If the user communicates in English, communicate strictly in English. Default language is English. Never use or default to Indonesian unless the user explicitly speaks to you in Indonesian.
|
|
53
84
|
- **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.
|
|
54
|
-
- **
|
|
55
|
-
- **
|
|
85
|
+
- **Evidence-Based Recovery Reports**: State only observed tool results and checks. Never claim a failed task was fixed without a passing check. Keep failure reports brief; if the user requests a detailed report, write it to a Markdown file in their selected workspace and give its path instead of dumping it into chat.
|
|
86
|
+
- **Status Updates**: For substantial work, give brief progress notes while using tools. Use a tool when it contributes to the task, and report what it actually returned.
|
|
87
|
+
- **Clarify Only When Needed**: Make routine implementation choices yourself. Ask when an unresolved choice or missing user-only input genuinely blocks progress; continue independent work while waiting.
|
|
56
88
|
- **No Chitchat**: Tools are for actions, text output is *only* for communication. Do not add explanatory comments within tool calls or code blocks.
|
|
57
89
|
- **File Paths**: ALWAYS output the absolute path of any file you create, modify, or generate so the user knows exactly where it is.
|
|
58
90
|
|
|
@@ -65,10 +97,8 @@ Specifically, you excel at:
|
|
|
65
97
|
- Use request_decision when multiple materially different architecture, product, data, security, or workflow directions are valid. Give 2-4 concrete options with consequences; the UI adds a custom-answer choice.
|
|
66
98
|
- A decision is separate from permission. Do not ask for routine implementation details that can be resolved from the repository. Even in Mode C, pause for an unresolved durable architecture decision before changing the system.
|
|
67
99
|
|
|
68
|
-
#
|
|
69
|
-
-
|
|
70
|
-
- Searching for different patterns (imports, usage, definitions) MUST happen in parallel. Reading multiple files MUST happen in parallel.
|
|
71
|
-
- Sequential calls can ONLY be used when you genuinely REQUIRE the output of one tool to determine the usage of the next tool. Parallel tool execution is 3-5x faster and is the expected behavior.
|
|
100
|
+
# Efficient Tool Use
|
|
101
|
+
- Batch independent searches and reads when useful. Keep edits, dependent operations, approvals, and verification in a safe order. Never run conflicting writes concurrently.
|
|
72
102
|
|
|
73
103
|
# Context Understanding & Searching
|
|
74
104
|
- Semantic search (or grep) is your MAIN exploration tool. Start with a broad, high-level query.
|
|
@@ -90,7 +120,7 @@ Specifically, you excel at:
|
|
|
90
120
|
- **Token Budgeting**: You must respect the user's BYOK (Bring Your Own Key) limits. Be highly token-efficient.
|
|
91
121
|
- **Explain Critical Commands**: Before executing destructive shell commands, provide a brief explanation of the impact.
|
|
92
122
|
- **Interactive Commands**: Avoid shell commands that require user interaction (e.g., \`git rebase -i\`). Use non-interactive flags (e.g., \`-y\`).
|
|
93
|
-
- **Sandboxing**:
|
|
123
|
+
- **Sandboxing**: Keep workspace checks and hard safety blocks active. In Mode C, ordinary in-scope edits and tool calls do not need approval; deleting an entire file or directory does. Removing or replacing lines while editing a file is not whole-file deletion.
|
|
94
124
|
- **SSRF Protection**: Do not fetch internal IPs (127.0.0.1, 169.254.x.x, 10.x.x.x).
|
|
95
125
|
|
|
96
126
|
# ABSOLUTE ETHICAL SAFETY NET (NON-NEGOTIABLE)
|
|
@@ -109,7 +139,7 @@ If asked to perform ANY harmful task, politely decline, state that Causyne exist
|
|
|
109
139
|
# Dependency Management & Autonomy Modes
|
|
110
140
|
- **Mode A (Passive)**: You MUST explicitly ask the user for permission (by ending your turn and asking a question) before installing any dependencies.
|
|
111
141
|
- **Mode B (Supervised)**: You may install standard development dependencies automatically, but you MUST ask for permission before modifying OS-level settings or running \`sudo\`.
|
|
112
|
-
- **Mode C (Autonomous)**:
|
|
142
|
+
- **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.
|
|
113
143
|
|
|
114
144
|
# Direct API & Automation Policy
|
|
115
145
|
- **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.
|
|
@@ -120,9 +150,8 @@ If asked to perform ANY harmful task, politely decline, state that Causyne exist
|
|
|
120
150
|
2. **Valid JSON Formatting**: All tool call arguments must be valid JSON objects. Never include raw unescaped newlines or trailing commas inside argument strings.
|
|
121
151
|
3. **Automated Buffer & Self-Correction**: Causyne runs a Universal Tool Buffer with self-repair capabilities. If a tool returns a \`selfRepairGuidance\` result indicating missing or invalid parameters, immediately read the \`expectedParameters\` and re-invoke the tool with the corrected arguments.
|
|
122
152
|
|
|
123
|
-
#
|
|
124
|
-
|
|
125
|
-
If the task is not 100% finished, you MUST invoke a tool (like web_search, fs_read, sysRun, etc.) in the exact same response as your text. If you output text without a tool call, the system will assume you are completely done and immediately terminate the task!
|
|
153
|
+
# Completion
|
|
154
|
+
Answer directly when no tool is needed. For action tasks, continue until the authorized work is done or a real blocker is evidenced; then report the verified outcome or blocker concisely.
|
|
126
155
|
`;
|
|
127
156
|
function getProviderSpecificPrompt(provider = '') {
|
|
128
157
|
const p = provider.toLowerCase();
|
|
@@ -347,6 +376,8 @@ export class AgentLoop {
|
|
|
347
376
|
this.updateTierLimits();
|
|
348
377
|
this.consecutiveThinkingSteps = 0;
|
|
349
378
|
this.consecutiveBlockedActions = 0; // V8 Transcendence: Circuit Breaker
|
|
379
|
+
this.recentActionSignatures = [];
|
|
380
|
+
this.consecutiveReadOnlySteps = 0;
|
|
350
381
|
// Sovereign Progressive Disclosure: which capability packs have entered the
|
|
351
382
|
// context window for this task. Nothing is disabled — see src/toolPacks.js.
|
|
352
383
|
this.unlockedPacks = new Set();
|
|
@@ -378,16 +409,13 @@ export class AgentLoop {
|
|
|
378
409
|
// P6: rendered surfaces this task wrote, for the anti-slop gate to read back.
|
|
379
410
|
this.webArtifacts = new Set();
|
|
380
411
|
this.slopGateFired = false;
|
|
381
|
-
this.coldObserverGuardFired = false;
|
|
382
412
|
this.gameCascadeState = { active: true, currentStage: 1, stageHistory: [], verificationPassed: false };
|
|
383
413
|
this.gameToolStats = { godot_act: 0, game_asset_fetch: 0, game_build_html5: 0, last_godot_action: null };
|
|
384
414
|
this.webVerificationState = { screenshotTaken: false, browserActUsed: false }; // V8 Transcendence: Anti-Slop Guard
|
|
385
415
|
this.abortController = new AbortController();
|
|
386
416
|
// V5: Context compaction tracking
|
|
387
417
|
this._lastCompactionIndex = null;
|
|
388
|
-
|
|
389
|
-
// V5: Error recovery tracking (per tool call)
|
|
390
|
-
this._toolRetryCount = new Map();
|
|
418
|
+
this.timeMachine = new TimeMachine();
|
|
391
419
|
this.isInitialized = false;
|
|
392
420
|
this.taskTemperature = 0.1; // Default
|
|
393
421
|
// Set only on a delegated subagent loop; null means "the full catalogue".
|
|
@@ -397,6 +425,23 @@ export class AgentLoop {
|
|
|
397
425
|
isAlwaysAllowed(toolName) {
|
|
398
426
|
return this.approvalScope.isAlwaysAllowed(toolName);
|
|
399
427
|
}
|
|
428
|
+
/**
|
|
429
|
+
* Reset all standing tool approvals, allowlists, and autonomy overrides.
|
|
430
|
+
*
|
|
431
|
+
* Critical security invariant (Claude Code Architecture, p. 24):
|
|
432
|
+
* When a session is forked or reset, permissions and standing approvals
|
|
433
|
+
* must NEVER carry over into the new branch. A forked session starts with
|
|
434
|
+
* fresh, ungranted permissions so that user authorization must be re-verified.
|
|
435
|
+
*/
|
|
436
|
+
resetApprovalScope() {
|
|
437
|
+
if (this.approvalScope && typeof this.approvalScope.revokeAllAlways === 'function') {
|
|
438
|
+
this.approvalScope.revokeAllAlways();
|
|
439
|
+
}
|
|
440
|
+
this.approvalScope = createApprovalScope();
|
|
441
|
+
this.autonomyOverride = null;
|
|
442
|
+
this.circuitBreakerUnlocked = false;
|
|
443
|
+
this.pendingApprovals.clear();
|
|
444
|
+
}
|
|
400
445
|
// V6: Adaptive Temperature based on task intent
|
|
401
446
|
determineTemperature(prompt) {
|
|
402
447
|
if (!prompt)
|
|
@@ -454,7 +499,7 @@ export class AgentLoop {
|
|
|
454
499
|
// Anti-Slop: Design Context Awareness (what design system is already installed)
|
|
455
500
|
let designContext = '';
|
|
456
501
|
try {
|
|
457
|
-
const detectedDesign = await this.perception.detectDesignContext(
|
|
502
|
+
const detectedDesign = await this.perception.detectDesignContext(this.workspaceRoot);
|
|
458
503
|
if (detectedDesign && detectedDesign.length > 0) {
|
|
459
504
|
designContext = `\nDETECTED DESIGN SYSTEM IN WORKSPACE: ${detectedDesign.join(', ')} — USE THIS. Do NOT install a conflicting system.`;
|
|
460
505
|
}
|
|
@@ -476,7 +521,7 @@ export class AgentLoop {
|
|
|
476
521
|
// Universal skills awareness
|
|
477
522
|
let universalSkillsContext = '';
|
|
478
523
|
try {
|
|
479
|
-
const detectedDomains = detectWorkspaceDomains(
|
|
524
|
+
const detectedDomains = detectWorkspaceDomains(this.workspaceRoot);
|
|
480
525
|
if (detectedDomains.length > 0) {
|
|
481
526
|
this.debugLog(`detected workspace domains: ${detectedDomains.join(', ')}`);
|
|
482
527
|
for (const domain of detectedDomains) {
|
|
@@ -643,11 +688,11 @@ export class AgentLoop {
|
|
|
643
688
|
continue;
|
|
644
689
|
}
|
|
645
690
|
try {
|
|
646
|
-
resolve(await item.tool.execute(item.args, {
|
|
691
|
+
resolve(await withToolAutonomyMode(this.config.autonomyMode || 'C', () => item.tool.execute(item.args, {
|
|
647
692
|
signal: this.abortController.signal,
|
|
648
693
|
parentLoop: this,
|
|
649
694
|
...this.sandbox
|
|
650
|
-
}));
|
|
695
|
+
})));
|
|
651
696
|
}
|
|
652
697
|
catch (e) {
|
|
653
698
|
resolve(null); // let the serial path fail it, with its own retries
|
|
@@ -799,8 +844,10 @@ export class AgentLoop {
|
|
|
799
844
|
// awareness instead of burning steps rediscovering it. The result used to be
|
|
800
845
|
// assigned to a local variable and thrown away.
|
|
801
846
|
auditLog.log({ event: 'task_start', taskId: this.taskId, request: this.userPrompt });
|
|
802
|
-
|
|
847
|
+
// Preserve an explicit workspace selected by the caller (for example ACP).
|
|
848
|
+
// The constructor already defaults to process.cwd() when none was supplied.
|
|
803
849
|
coldObserver.beginTask(this.taskId);
|
|
850
|
+
this.timeMachine.reset();
|
|
804
851
|
this.emitEvent({ type: 'status', message: 'Analyzing workspace...' });
|
|
805
852
|
// P2: open the undo group for this task. This snapshots the CONVERSATION as
|
|
806
853
|
// well as the workspace tree, because restoring files while chat_history
|
|
@@ -832,13 +879,13 @@ export class AgentLoop {
|
|
|
832
879
|
// return $HOME or a system root, so the checkpoint covers the code being
|
|
833
880
|
// worked on or honestly covers nothing at all.
|
|
834
881
|
workspaceRoots: [
|
|
835
|
-
resolveProjectRoot(
|
|
836
|
-
|
|
882
|
+
resolveProjectRoot(this.workspaceRoot),
|
|
883
|
+
this.workspaceRoot,
|
|
837
884
|
...(this.sandbox.grantAllAccess ? [] : (this.sandbox.workspacePaths || []))
|
|
838
885
|
].filter(Boolean)
|
|
839
886
|
});
|
|
840
887
|
try {
|
|
841
|
-
this.workspaceContext = await this.perception.buildContext(
|
|
888
|
+
this.workspaceContext = await this.perception.buildContext(this.workspaceRoot);
|
|
842
889
|
}
|
|
843
890
|
catch (perceptionError) {
|
|
844
891
|
this.debugLog(`workspace scan failed: ${perceptionError.message}`);
|
|
@@ -853,7 +900,6 @@ export class AgentLoop {
|
|
|
853
900
|
this.webGuardFired = false;
|
|
854
901
|
this.webArtifacts = new Set();
|
|
855
902
|
this.slopGateFired = false;
|
|
856
|
-
this.coldObserverGuardFired = false;
|
|
857
903
|
this.staticContext = null;
|
|
858
904
|
// Plan cache: the procedure THIS task follows, and the template (if any)
|
|
859
905
|
// that was offered to it. Both reset per task — a plan is a property of one
|
|
@@ -869,7 +915,9 @@ export class AgentLoop {
|
|
|
869
915
|
this._decisionAnswers = new Map();
|
|
870
916
|
this._decisionRequirement = assessDecisionRequirement(this.userPrompt || '');
|
|
871
917
|
this._decisionResolved = !this._decisionRequirement.required;
|
|
872
|
-
this.
|
|
918
|
+
this._taskStartedAt = performance.now();
|
|
919
|
+
this._totalPlanMs = 0;
|
|
920
|
+
this._totalActMs = 0;
|
|
873
921
|
if (this.vfeTracker)
|
|
874
922
|
this.vfeTracker.reset();
|
|
875
923
|
if (this.userPrompt) {
|
|
@@ -887,6 +935,8 @@ export class AgentLoop {
|
|
|
887
935
|
const scored = packsFromShape(this.taskShape);
|
|
888
936
|
const fallback = routePacks(this.userPrompt, this.workspaceContext);
|
|
889
937
|
for (const pack of [...scored, ...fallback]) {
|
|
938
|
+
if (pack === 'game' && isDirectGameTask(this.userPrompt))
|
|
939
|
+
continue;
|
|
890
940
|
this.unlockPack(pack);
|
|
891
941
|
}
|
|
892
942
|
// Reuse a known route before the first model call. Exact keyword-set
|
|
@@ -940,7 +990,7 @@ export class AgentLoop {
|
|
|
940
990
|
try {
|
|
941
991
|
const subprojects = this.workspaceContext?.subprojects || [];
|
|
942
992
|
const mentionResult = await resolveMentionedContext(this.userPrompt, {
|
|
943
|
-
cwd:
|
|
993
|
+
cwd: this.workspaceRoot,
|
|
944
994
|
subprojects
|
|
945
995
|
});
|
|
946
996
|
if (mentionResult.detectedSubproject) {
|
|
@@ -948,12 +998,14 @@ export class AgentLoop {
|
|
|
948
998
|
this.notice(`Focused on subproject '${mentionResult.detectedSubproject}'`);
|
|
949
999
|
}
|
|
950
1000
|
else if (subprojects.length > 0) {
|
|
951
|
-
const lowerPrompt = this.userPrompt.toLowerCase();
|
|
952
1001
|
for (const sp of subprojects) {
|
|
953
|
-
if (
|
|
954
|
-
|
|
955
|
-
this.
|
|
956
|
-
|
|
1002
|
+
if (sp.length >= 2) {
|
|
1003
|
+
const boundaryRegex = new RegExp(`(?:^|\\s|["'\`(@/\\\\])${sp.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\$&')}(?:$|\\s|["'\`):,/\\\\])`, 'i');
|
|
1004
|
+
if (boundaryRegex.test(this.userPrompt)) {
|
|
1005
|
+
this.activeSubproject = sp;
|
|
1006
|
+
this.notice(`Focused on subproject '${sp}'`);
|
|
1007
|
+
break;
|
|
1008
|
+
}
|
|
957
1009
|
}
|
|
958
1010
|
}
|
|
959
1011
|
}
|
|
@@ -1046,7 +1098,7 @@ export class AgentLoop {
|
|
|
1046
1098
|
const path = await import('path');
|
|
1047
1099
|
// Ensure unique name to prevent overwriting
|
|
1048
1100
|
const safeName = att.name.replace(/[^a-zA-Z0-9.\-_]/g, '_');
|
|
1049
|
-
const writePath = path.join(
|
|
1101
|
+
const writePath = path.join(this.workspaceRoot, safeName);
|
|
1050
1102
|
fs.writeFileSync(writePath, Buffer.from(att.base64, 'base64'));
|
|
1051
1103
|
contentArray[0].text += `\n\n[SYSTEM NOTIFICATION: The user attached a document named '${safeName}'. It has been saved to your workspace at ./${safeName}. Please use your file reading tools to examine its contents.]`;
|
|
1052
1104
|
this.notice(`saved attached document to ${writePath}`);
|
|
@@ -1066,6 +1118,8 @@ export class AgentLoop {
|
|
|
1066
1118
|
this._observationDigests = new Map();
|
|
1067
1119
|
this.consecutiveCommands = 0;
|
|
1068
1120
|
this.circuitBreakerUnlocked = false;
|
|
1121
|
+
this.recentActionSignatures = [];
|
|
1122
|
+
this.consecutiveReadOnlySteps = 0;
|
|
1069
1123
|
this.tokenTracker.resetTask();
|
|
1070
1124
|
// The core loop governed by Sovereign Human-in-the-Loop Checkpoints
|
|
1071
1125
|
while (!this.stopRequested) {
|
|
@@ -1174,7 +1228,7 @@ export class AgentLoop {
|
|
|
1174
1228
|
const autonomyMode = this.config.autonomyMode || 'C';
|
|
1175
1229
|
const allowedPaths = this.sandbox.grantAllAccess
|
|
1176
1230
|
? "/ (ALL ACCESS GRANTED - You can read/write anywhere EXCEPT system protected folders like /etc or /System)"
|
|
1177
|
-
: (this.sandbox.workspacePaths ? this.sandbox.workspacePaths.join(', ') :
|
|
1231
|
+
: (this.sandbox.workspacePaths ? this.sandbox.workspacePaths.join(', ') : this.workspaceRoot);
|
|
1178
1232
|
const providerPrompt = getProviderSpecificPrompt(this.config.provider);
|
|
1179
1233
|
const memoryContext = getMemoryContextString();
|
|
1180
1234
|
// --- PER-TASK STATIC CONTEXT (computed once, not once per step) ---
|
|
@@ -1377,11 +1431,18 @@ export class AgentLoop {
|
|
|
1377
1431
|
// 2. PLAN (Call LLM). dynamicTools was resolved above so the task brief
|
|
1378
1432
|
// could reference the tools actually in context.
|
|
1379
1433
|
let hasStreamedChunk = false;
|
|
1434
|
+
const streamingCode = new StreamingCodePreview();
|
|
1435
|
+
const nativeCodeObserver = new NativeCodeObserver(this.workspaceRoot, event => this.emitEvent(event));
|
|
1380
1436
|
let reasoningAccumulated = '';
|
|
1381
1437
|
let thoughtStartedAt = 0;
|
|
1382
1438
|
this.emitEvent({ type: 'status', message: 'Thinking…' });
|
|
1383
1439
|
this.emitEvent({ type: 'agent_activity', activity: 'Thinking…' });
|
|
1440
|
+
const planStepStart = performance.now();
|
|
1384
1441
|
const response = await this.llm.chat(prunedMessages, {
|
|
1442
|
+
taskId: this.taskId,
|
|
1443
|
+
conversationId: this.taskId,
|
|
1444
|
+
taskIntent: isLaunchOnlyPrompt(this.currentTaskPrompt || this.userPrompt || '') ? 'launch' : 'general',
|
|
1445
|
+
workspaceRoot: this.workspaceRoot,
|
|
1385
1446
|
tools: dynamicTools,
|
|
1386
1447
|
// IARS couples escalation to a wider search. Bounded so a stuck task
|
|
1387
1448
|
// cannot climb into randomness across repeated escalations.
|
|
@@ -1406,8 +1467,36 @@ export class AgentLoop {
|
|
|
1406
1467
|
this.emitEvent({ type: 'status', message: 'Responding…' });
|
|
1407
1468
|
this.emitEvent({ type: 'agent_activity', activity: 'Responding…' });
|
|
1408
1469
|
}
|
|
1470
|
+
const preview = streamingCode.accept(_chunk);
|
|
1471
|
+
if (preview)
|
|
1472
|
+
this.emitEvent(preview);
|
|
1473
|
+
},
|
|
1474
|
+
onNativeAction: (action) => {
|
|
1475
|
+
if (!action || typeof action.name !== 'string')
|
|
1476
|
+
return;
|
|
1477
|
+
const nativeCode = codeProgressFromAction(action.name, { ...(action.parameters && typeof action.parameters === 'object' ? action.parameters : {}),
|
|
1478
|
+
path: action.parameters?.path || action.parameters?.Path || action.detail || '' }, `provider:${action.name}:${action.detail || ''}`, action.status === 'completed' ? 'done' : action.status === 'failed' ? 'failed' : 'working', 'provider');
|
|
1479
|
+
if (nativeCode) {
|
|
1480
|
+
this.emitEvent(nativeCode);
|
|
1481
|
+
nativeCodeObserver.handle(nativeCode);
|
|
1482
|
+
}
|
|
1483
|
+
const detail = action.detail ? ` ${action.detail}` : '';
|
|
1484
|
+
if (action.status === 'running') {
|
|
1485
|
+
this.emitEvent({ type: 'status', message: `Acting: ${action.name}${detail}` });
|
|
1486
|
+
this.emitEvent({ type: 'agent_activity', activity: `Acting: ${action.name}${detail}` });
|
|
1487
|
+
}
|
|
1488
|
+
else if (action.status === 'completed') {
|
|
1489
|
+
this.emitEvent({ type: 'notice', tone: 'muted', message: `Antigravity ${action.name}${detail}` });
|
|
1490
|
+
}
|
|
1491
|
+
else if (action.status === 'failed') {
|
|
1492
|
+
this.emitEvent({ type: 'warning', message: `Antigravity could not ${action.name}${detail}` });
|
|
1493
|
+
}
|
|
1409
1494
|
}
|
|
1410
|
-
});
|
|
1495
|
+
}).finally(() => nativeCodeObserver.dispose());
|
|
1496
|
+
this._totalPlanMs = (this._totalPlanMs || 0) + (performance.now() - planStepStart);
|
|
1497
|
+
const finalCodePreview = streamingCode.flush();
|
|
1498
|
+
if (finalCodePreview)
|
|
1499
|
+
this.emitEvent(finalCodePreview);
|
|
1411
1500
|
// The call came back. Whatever went wrong before is no longer
|
|
1412
1501
|
// consecutive — without this reset, one failure at step 2 and another
|
|
1413
1502
|
// at step 200 would count toward the same ceiling and stop a task that
|
|
@@ -1487,16 +1576,71 @@ export class AgentLoop {
|
|
|
1487
1576
|
assistantMsg.thinking_blocks = response.thinkingBlocks;
|
|
1488
1577
|
}
|
|
1489
1578
|
this.messages.push(assistantMsg);
|
|
1490
|
-
if (response.content) {
|
|
1579
|
+
if (response.content && hasToolCalls) {
|
|
1491
1580
|
this.emitEvent({ type: 'agent_message', content: response.content });
|
|
1492
1581
|
}
|
|
1582
|
+
const externalActions = Array.isArray(response.externalActions)
|
|
1583
|
+
? response.externalActions
|
|
1584
|
+
: [];
|
|
1585
|
+
const completedExternalActions = externalActions.filter((a) => a && a.status === 'completed');
|
|
1586
|
+
const failedExternalActions = externalActions.filter((a) => a && a.status === 'failed');
|
|
1587
|
+
const hasExternalActions = completedExternalActions.length > 0;
|
|
1493
1588
|
// If no tool calls, check if the agent is just thinking/planning or actually done
|
|
1494
1589
|
if (!response.toolCalls || response.toolCalls.length === 0) {
|
|
1495
1590
|
const contentText = response.content || '';
|
|
1496
1591
|
const lower = contentText.toLowerCase();
|
|
1497
|
-
const
|
|
1498
|
-
const
|
|
1499
|
-
|
|
1592
|
+
const taskPrompt = (this.currentTaskPrompt || this.userPrompt || '').trim();
|
|
1593
|
+
const isActionable = isActionableTaskPrompt(taskPrompt);
|
|
1594
|
+
// A native workspace action already changed the workspace. Do not
|
|
1595
|
+
// demand a Causyne tool call for the same work, and do not treat the
|
|
1596
|
+
// turn as a no-op.
|
|
1597
|
+
if (!hasExternalActions && failedExternalActions.length > 0 && this.consecutiveThinkingSteps < 2) {
|
|
1598
|
+
this.consecutiveThinkingSteps++;
|
|
1599
|
+
const blocked = failedExternalActions
|
|
1600
|
+
.map((a) => `${a.name}${a.detail ? ` (${a.detail})` : ''}`)
|
|
1601
|
+
.join(', ');
|
|
1602
|
+
this.emitEvent({ type: 'status', message: 'Native action blocked; switching to Causyne tools...' });
|
|
1603
|
+
this.emitEvent({ type: 'agent_activity', activity: 'Retrying blocked action through Causyne…' });
|
|
1604
|
+
this.messages.push({
|
|
1605
|
+
role: 'system',
|
|
1606
|
+
content: `[SYSTEM NOTICE: Your native action(s) were blocked: ${blocked}. Do not retry native terminal or browser tools. Instead use Causyne's XML tool call format, for example <tool_call>{"name": "sysRun", "arguments": {"command": "..."}}</tool_call>.]`
|
|
1607
|
+
});
|
|
1608
|
+
this.memoryManager.saveHistory(this.messages);
|
|
1609
|
+
continue;
|
|
1610
|
+
}
|
|
1611
|
+
const isQuestionOrGreeting = lower.includes('?') ||
|
|
1612
|
+
lower.includes('let me know') ||
|
|
1613
|
+
lower.includes('how can i help') ||
|
|
1614
|
+
lower.includes('how may i help') ||
|
|
1615
|
+
lower.includes('how can i assist') ||
|
|
1616
|
+
lower.includes('what would you like') ||
|
|
1617
|
+
lower.includes('what can i help') ||
|
|
1618
|
+
lower.includes('feel free to');
|
|
1619
|
+
// Action Enforcement on Step 0:
|
|
1620
|
+
// If the user instructed an actionable task (e.g. "create a 3js game..."), but the model
|
|
1621
|
+
// replied with a greeting, polite pleasantry, question, or refusal without calling any tools:
|
|
1622
|
+
if (!hasExternalActions && this.stepsCompleted === 0 && isActionable && (isQuestionOrGreeting || lower.includes('hello') || lower.includes('hi '))) {
|
|
1623
|
+
this.messages.pop();
|
|
1624
|
+
if (this.consecutiveThinkingSteps >= 2) {
|
|
1625
|
+
this.emitEvent({ type: 'error', message: 'The selected model did not follow the task after three attempts. No work was completed.' });
|
|
1626
|
+
this.memoryManager.saveHistory(this.messages);
|
|
1627
|
+
break;
|
|
1628
|
+
}
|
|
1629
|
+
this.consecutiveThinkingSteps++;
|
|
1630
|
+
this.emitEvent({ type: 'status', message: 'Enforcing task execution: rejecting greeting on actionable instruction...' });
|
|
1631
|
+
this.emitEvent({ type: 'agent_activity', activity: 'Enforcing tool execution…' });
|
|
1632
|
+
this.messages.push({
|
|
1633
|
+
role: 'system',
|
|
1634
|
+
content: isLaunchOnlyPrompt(taskPrompt)
|
|
1635
|
+
? `[CURRENT TASK: "${taskPrompt}". The user asked to open the existing project. Inspect it, start its existing server in the background if needed, verify readiness, and open it. Do not write or edit files. Use the appropriate Causyne tools now.]`
|
|
1636
|
+
: `[CRITICAL ACTION MANDATE: The user explicitly instructed: "${taskPrompt}". You responded with a greeting or inquiry without performing any actions or writing any code. Do NOT reply with greetings, pleasantries, or ask how to help. You must immediately invoke the appropriate tools (e.g., fs_write, sysRun) to implement the user's request.]`
|
|
1637
|
+
});
|
|
1638
|
+
this.memoryManager.saveHistory(this.messages);
|
|
1639
|
+
continue;
|
|
1640
|
+
}
|
|
1641
|
+
const thinkingKeywords = ['let me ', "i'll ", 'i will ', 'now i ', 'next, i ', 'first, i ', 'checking ', 'trying to ', 'let us ', 'going to ', 'i shall', 'we will', 'i am going to'];
|
|
1642
|
+
const isThinking = !isQuestionOrGreeting && thinkingKeywords.some(kw => lower.includes(kw));
|
|
1643
|
+
if (!hasExternalActions && isThinking && this.consecutiveThinkingSteps < 3) {
|
|
1500
1644
|
this.consecutiveThinkingSteps++;
|
|
1501
1645
|
this.emitEvent({ type: 'status', message: 'Agent planning next steps...' });
|
|
1502
1646
|
this.emitEvent({ type: 'agent_activity', activity: 'Planning next actionable steps…' });
|
|
@@ -1509,19 +1653,25 @@ export class AgentLoop {
|
|
|
1509
1653
|
this.memoryManager.saveHistory(this.messages);
|
|
1510
1654
|
continue;
|
|
1511
1655
|
}
|
|
1512
|
-
if (this.stepsCompleted === 0 && this.consecutiveThinkingSteps < 2) {
|
|
1513
|
-
if (lower.includes('turn completed') || lower.includes('no output produced') || !contentText.trim()) {
|
|
1656
|
+
if (!hasExternalActions && this.stepsCompleted === 0 && this.consecutiveThinkingSteps < 2) {
|
|
1657
|
+
if (isActionable || lower.includes('turn completed') || lower.includes('no output produced') || !contentText.trim()) {
|
|
1514
1658
|
this.consecutiveThinkingSteps++;
|
|
1515
1659
|
this.emitEvent({ type: 'status', message: 'Nudging agent to execute actionable steps...' });
|
|
1516
1660
|
this.emitEvent({ type: 'agent_activity', activity: 'Nudging agent to invoke tools…' });
|
|
1517
1661
|
this.messages.push({
|
|
1518
1662
|
role: 'system',
|
|
1519
|
-
content:
|
|
1663
|
+
content: `[SYSTEM NOTICE: An action or task was requested ("${taskPrompt}"), but no tools were called. Please invoke the appropriate tool by outputting: <tool_call>{"name": "tool_name", "arguments": {...}}</tool_call> to execute the task.]`
|
|
1520
1664
|
});
|
|
1521
1665
|
this.memoryManager.saveHistory(this.messages);
|
|
1522
1666
|
continue;
|
|
1523
1667
|
}
|
|
1524
1668
|
}
|
|
1669
|
+
if (!hasExternalActions && this.stepsCompleted === 0 && isActionable) {
|
|
1670
|
+
this.messages.pop();
|
|
1671
|
+
this.emitEvent({ type: 'error', message: 'The selected model returned text without taking any action. No work was completed.' });
|
|
1672
|
+
this.memoryManager.saveHistory(this.messages);
|
|
1673
|
+
break;
|
|
1674
|
+
}
|
|
1525
1675
|
// --- COMPLETION GUARDS ---
|
|
1526
1676
|
// Two hard rules learned the expensive way:
|
|
1527
1677
|
// 1. Match on word boundaries. Substring matching made 'ui' fire on
|
|
@@ -1531,24 +1681,20 @@ export class AgentLoop {
|
|
|
1531
1681
|
// consecutiveThinkingSteps, which resets on every tool call, so
|
|
1532
1682
|
// a guard could block completion indefinitely and burn the whole
|
|
1533
1683
|
// step budget on an already-finished task.
|
|
1534
|
-
|
|
1535
|
-
|
|
1684
|
+
if (response.content) {
|
|
1685
|
+
this.emitEvent({ type: 'agent_message', content: response.content });
|
|
1686
|
+
}
|
|
1687
|
+
const isGameTask = !isLaunchOnlyPrompt(taskPrompt) && isGameIntent(taskPrompt);
|
|
1536
1688
|
this.gameToolStats = this.gameToolStats || { godot_act: 0, game_asset_fetch: 0, game_build_html5: 0, last_godot_action: null };
|
|
1537
1689
|
if (isGameTask && !this.gameGuardFired) {
|
|
1538
|
-
|
|
1539
|
-
const needsVerification = buildingRealGame && !this.gameCascadeState.verificationPassed && this.gameCascadeState.currentStage >= 7;
|
|
1540
|
-
// Production-depth enforcement is opt-in. It is right for
|
|
1541
|
-
// "build me a full RPG" and wrong for "fix the jump height in my game".
|
|
1690
|
+
// Production-depth enforcement is opt-in for full production tasks.
|
|
1542
1691
|
const needsDepth = this.config.enforceGameDepth === true && this.stepsCompleted < 50;
|
|
1543
|
-
if (
|
|
1692
|
+
if (needsDepth) {
|
|
1544
1693
|
this.gameGuardFired = true;
|
|
1545
|
-
this.emitEvent({ type: 'status', message: '⚡ Sovereign Game Guard:
|
|
1546
|
-
const guardMsg =
|
|
1547
|
-
? `[SOVEREIGN DEPTH BLOCK: You are building a Full Production Game but only took ${this.stepsCompleted} steps. A full production game requires 100+ steps. Expand the game with more levels, richer UI, complex enemy AI, or more assets before finishing. This check fires once — if the task genuinely is complete, say so plainly and finish.]`
|
|
1548
|
-
: `[SOVEREIGN QUALITY GATE: You built a game but declared completion without verifying it. Run \`game_web_runtime_inspector\` and \`game_canvas_audit\` to confirm runtime stability (FPS >= 30, no missing sprites) before exiting. This check fires once — if verification is genuinely not applicable, say so plainly and finish.]`;
|
|
1694
|
+
this.emitEvent({ type: 'status', message: '⚡ Sovereign Game Guard: Checking production depth...' });
|
|
1695
|
+
const guardMsg = `[SOVEREIGN DEPTH NOTICE: You are building a Full Production Game with enforceGameDepth enabled. Current step count: ${this.stepsCompleted}. Expand the game with more levels, richer UI, complex enemy AI, or more assets before finishing. If the task is genuinely complete, state so and finish.]`;
|
|
1549
1696
|
this.messages.push({ role: 'system', content: guardMsg });
|
|
1550
1697
|
this.memoryManager.saveHistory(this.messages);
|
|
1551
|
-
continue;
|
|
1552
1698
|
}
|
|
1553
1699
|
}
|
|
1554
1700
|
// P6 — ANTI-SLOP GATE (Vision §7, ENFORCED)
|
|
@@ -1574,13 +1720,12 @@ export class AgentLoop {
|
|
|
1574
1720
|
const recent = Array.isArray(this.staticContext?.recentMovements) ? this.staticContext.recentMovements : [];
|
|
1575
1721
|
const brief = formatMovementBrief(suggestMovements(recent, 3));
|
|
1576
1722
|
auditLog.log({
|
|
1577
|
-
event: '
|
|
1723
|
+
event: 'anti_slop_notice', taskId: this.taskId,
|
|
1578
1724
|
score: result.score, signals: result.findings.map((f) => f.id)
|
|
1579
1725
|
});
|
|
1580
|
-
this.emitEvent({ type: 'status', message: `⚡ Anti-Slop
|
|
1726
|
+
this.emitEvent({ type: 'status', message: `⚡ Anti-Slop Audit: design scored ${result.score}` });
|
|
1581
1727
|
this.messages.push({ role: 'system', content: formatFindings(result, brief) });
|
|
1582
1728
|
this.memoryManager.saveHistory(this.messages);
|
|
1583
|
-
continue;
|
|
1584
1729
|
}
|
|
1585
1730
|
if (result.findings.length > 0) {
|
|
1586
1731
|
auditLog.log({
|
|
@@ -1596,7 +1741,7 @@ export class AgentLoop {
|
|
|
1596
1741
|
}
|
|
1597
1742
|
}
|
|
1598
1743
|
// Web Visual Validation Guard (Anti-Slop / Transcendence)
|
|
1599
|
-
const isWebTask = isWebIntent(taskPrompt);
|
|
1744
|
+
const isWebTask = !isLaunchOnlyPrompt(taskPrompt) && isWebIntent(taskPrompt);
|
|
1600
1745
|
if (isWebTask && !this.webGuardFired && this.stepsCompleted > 0) {
|
|
1601
1746
|
const hasVision = this.llm.supportsVision !== false;
|
|
1602
1747
|
// Finding D-6: this guard used to demand `screenshot` /
|
|
@@ -1635,14 +1780,16 @@ export class AgentLoop {
|
|
|
1635
1780
|
// The verification tools live in the web pack; make sure they are
|
|
1636
1781
|
// actually in context before demanding the agent use them.
|
|
1637
1782
|
this.unlockPack('web');
|
|
1638
|
-
this.emitEvent({ type: 'status', message: '⚡ Anti-Slop
|
|
1783
|
+
this.emitEvent({ type: 'status', message: '⚡ Anti-Slop Check: Visual/semantic verification recommended.' });
|
|
1639
1784
|
this.messages.push({ role: 'system', content: webGuardMsg });
|
|
1640
1785
|
this.memoryManager.saveHistory(this.messages);
|
|
1641
|
-
|
|
1786
|
+
if (browserReady || (hasVision && visionReady)) {
|
|
1787
|
+
continue;
|
|
1788
|
+
}
|
|
1642
1789
|
}
|
|
1643
1790
|
}
|
|
1644
1791
|
// Cold Observer: Overconfidence & Loop Verification Check
|
|
1645
|
-
|
|
1792
|
+
{
|
|
1646
1793
|
try {
|
|
1647
1794
|
const coldAudit = await coldObserver.auditTurnVerification({
|
|
1648
1795
|
taskId: this.taskId,
|
|
@@ -1652,11 +1799,18 @@ export class AgentLoop {
|
|
|
1652
1799
|
stepsCompleted: this.stepsCompleted
|
|
1653
1800
|
});
|
|
1654
1801
|
if (coldAudit.overconfident) {
|
|
1655
|
-
this.
|
|
1802
|
+
const recovery = this.timeMachine.observe('observer_verification', {}, {
|
|
1803
|
+
success: false, error: coldAudit.discrepancy
|
|
1804
|
+
}, coldObserver.getToolOutcomes(this.taskId));
|
|
1656
1805
|
this.emitEvent({ type: 'status', message: `Cold Observer: ${coldAudit.discrepancy}` });
|
|
1806
|
+
if (recovery.kind === 'stop') {
|
|
1807
|
+
this.stopRequested = true;
|
|
1808
|
+
this.emitEvent({ type: 'error', message: recoveryUserMessage(recovery, 'Verification') });
|
|
1809
|
+
break;
|
|
1810
|
+
}
|
|
1657
1811
|
this.messages.push({
|
|
1658
1812
|
role: 'system',
|
|
1659
|
-
content: coldAudit.coldDirective
|
|
1813
|
+
content: `${coldAudit.coldDirective} ${recovery.guidance}`
|
|
1660
1814
|
});
|
|
1661
1815
|
this.memoryManager.saveHistory(this.messages);
|
|
1662
1816
|
continue;
|
|
@@ -1673,13 +1827,21 @@ export class AgentLoop {
|
|
|
1673
1827
|
// run, so asking a model to summarise it would be paying for a worse
|
|
1674
1828
|
// copy of a fact we hold.
|
|
1675
1829
|
try {
|
|
1676
|
-
const
|
|
1830
|
+
const planPayload = {
|
|
1677
1831
|
prompt: this.currentTaskPrompt || this.userPrompt,
|
|
1678
1832
|
archetype: this.taskShape ? this.taskShape.archetype : '',
|
|
1679
1833
|
steps: this._planSteps || []
|
|
1834
|
+
};
|
|
1835
|
+
recordPlanAsync(planPayload).then((stored) => {
|
|
1836
|
+
if (stored)
|
|
1837
|
+
this.debugLog(`plan cached asynchronously: ${stored.steps.length} steps, ${stored.wins}/${stored.uses} wins`);
|
|
1838
|
+
}).catch(() => { });
|
|
1839
|
+
recordAPCPipelineLatency({
|
|
1840
|
+
planMs: this._totalPlanMs || 0,
|
|
1841
|
+
actMs: this._totalActMs || 0,
|
|
1842
|
+
cacheLookupMs: this._planMatch?.telemetry?.lookupMs || 0,
|
|
1843
|
+
totalMs: performance.now() - (this._taskStartedAt || performance.now())
|
|
1680
1844
|
});
|
|
1681
|
-
if (stored)
|
|
1682
|
-
this.debugLog(`plan cached: ${stored.steps.length} steps, ${stored.wins}/${stored.uses} wins`);
|
|
1683
1845
|
}
|
|
1684
1846
|
catch (e) {
|
|
1685
1847
|
this.debugLog(`plan cache write skipped: ${e.message}`);
|
|
@@ -1696,9 +1858,8 @@ export class AgentLoop {
|
|
|
1696
1858
|
// them strictly one after another, so six `fs_read`s cost six full
|
|
1697
1859
|
// round trips of tool latency.
|
|
1698
1860
|
//
|
|
1699
|
-
// The serial loop below
|
|
1700
|
-
//
|
|
1701
|
-
// error classification changes — the only difference is that a
|
|
1861
|
+
// The serial loop below preserves ordering and approval gates. The
|
|
1862
|
+
// only difference from prefetching is that a
|
|
1702
1863
|
// read-only result may already be sitting in this map by the time the
|
|
1703
1864
|
// loop reaches it. Restructuring the 400-line body into a batch would
|
|
1704
1865
|
// have been the obvious approach and a far worse one: it is dense with
|
|
@@ -1712,8 +1873,7 @@ export class AgentLoop {
|
|
|
1712
1873
|
// * The sandbox is consulted FIRST, with the same call the serial path
|
|
1713
1874
|
// makes, so a denied path is never read behind the guard's back.
|
|
1714
1875
|
// * Only a SUCCESSFUL prefetch is consumed. A failure is discarded and
|
|
1715
|
-
// the serial path executes normally, so
|
|
1716
|
-
// error-classification logic keeps its exact behaviour.
|
|
1876
|
+
// the serial path executes normally, so TimeMachine sees its outcome.
|
|
1717
1877
|
const prefetched = this.prefetchReadOnlyCalls(response.toolCalls);
|
|
1718
1878
|
// 3. ACT (Execute tool calls)
|
|
1719
1879
|
for (const toolCall of response.toolCalls) {
|
|
@@ -1747,16 +1907,116 @@ export class AgentLoop {
|
|
|
1747
1907
|
if (repair.repaired && repair.repairs.length > 0) {
|
|
1748
1908
|
this.debugLog(`[TOOL SELF-REPAIR] Healed tool call '${functionName}': ${repair.repairs.join(', ')}`);
|
|
1749
1909
|
}
|
|
1750
|
-
this.
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1910
|
+
if (isLaunchOnlyPrompt(this.currentTaskPrompt || this.userPrompt || '')) {
|
|
1911
|
+
const scopeError = launchScopeError(functionName, args || {});
|
|
1912
|
+
if (scopeError) {
|
|
1913
|
+
this.emitEvent({ type: 'step_error', tool: functionName, error: scopeError, toolCallId: toolCall.id });
|
|
1914
|
+
this.messages.push({ role: 'tool', tool_call_id: toolCall.id, name: functionName,
|
|
1915
|
+
content: JSON.stringify({ success: false, error: scopeError }) });
|
|
1916
|
+
continue;
|
|
1917
|
+
}
|
|
1918
|
+
if (args && ['sysRun', 'sysRunBg', 'terminal_persistent_shell'].includes(functionName) && !args.cwd) {
|
|
1919
|
+
args.cwd = this.workspaceRoot;
|
|
1920
|
+
}
|
|
1754
1921
|
}
|
|
1755
|
-
|
|
1756
|
-
|
|
1922
|
+
// Universal Repetition & Infinite Loop Circuit Breakers (Token Hemorrhage Guard)
|
|
1923
|
+
if (!Array.isArray(this.recentActionSignatures)) {
|
|
1924
|
+
this.recentActionSignatures = [];
|
|
1925
|
+
}
|
|
1926
|
+
let actionSig = `${functionName}:${JSON.stringify(args || {})}`;
|
|
1927
|
+
if (functionName === 'sysRun' || functionName === 'sysRunBg') {
|
|
1928
|
+
const rawCmd = String(args?.command || '').trim();
|
|
1929
|
+
if (/python[0-9.]*\s+.*import\s+numpy/i.test(rawCmd)) {
|
|
1930
|
+
actionSig = 'sysRun:probe:numpy';
|
|
1931
|
+
}
|
|
1932
|
+
else if (/python[0-9.]*\s+(--version|-V|-c\s+['"]print)/i.test(rawCmd)) {
|
|
1933
|
+
actionSig = 'sysRun:probe:python';
|
|
1934
|
+
}
|
|
1935
|
+
else if (/node\s+(--version|-v)/i.test(rawCmd)) {
|
|
1936
|
+
actionSig = 'sysRun:probe:node';
|
|
1937
|
+
}
|
|
1938
|
+
else if (/(?:ps\s+aux|pgrep|lsof|netstat|ss\s+-)/i.test(rawCmd)) {
|
|
1939
|
+
actionSig = 'sysRun:probe:process_or_port';
|
|
1940
|
+
}
|
|
1941
|
+
else {
|
|
1942
|
+
actionSig = `${functionName}:${rawCmd.replace(/\s+/g, ' ')}`;
|
|
1943
|
+
}
|
|
1944
|
+
}
|
|
1945
|
+
// Always record action signature into recent history FIRST
|
|
1946
|
+
this.recentActionSignatures.push(actionSig);
|
|
1947
|
+
if (this.recentActionSignatures.length > 20) {
|
|
1948
|
+
this.recentActionSignatures.shift();
|
|
1949
|
+
}
|
|
1950
|
+
const isCommandTool = ['sysRun', 'sysRunBg', 'terminal_persistent_shell'].includes(functionName);
|
|
1951
|
+
if (isCommandTool) {
|
|
1952
|
+
const duplicateCount = this.recentActionSignatures.filter((sig) => sig === actionSig).length;
|
|
1953
|
+
// 1. Hard Circuit Breaker on Duplicate Command Thrashing (same command attempted 4 times total)
|
|
1954
|
+
if (duplicateCount >= 4) {
|
|
1955
|
+
const fatalMsg = `FATAL ERROR: Infinite Token Drain Detected. Agent repeatedly attempted identical command '${functionName}' (${actionSig}) 4 times without making progress. Forcibly aborting task to save tokens.`;
|
|
1956
|
+
this.emitEvent({ type: 'step_error', tool: functionName, error: fatalMsg, toolCallId: toolCall.id });
|
|
1957
|
+
auditLog.log({ event: 'task_killed_circuit_breaker', taskId: this.taskId, reason: fatalMsg });
|
|
1958
|
+
this.abort();
|
|
1959
|
+
break;
|
|
1960
|
+
}
|
|
1961
|
+
// 2. Block 3rd attempt of identical command and inject a non-negotiable recovery mandate
|
|
1962
|
+
if (duplicateCount === 3) {
|
|
1963
|
+
const isExec = isExecutionOrLaunchTaskPrompt(this.currentTaskPrompt || this.userPrompt || '');
|
|
1964
|
+
const isAuthoring = !isExec && isCodeAuthoringTaskPrompt(this.currentTaskPrompt || this.userPrompt || '');
|
|
1965
|
+
let blockMsg;
|
|
1966
|
+
if (actionSig === 'sysRun:probe:process_or_port' || isExec) {
|
|
1967
|
+
blockMsg = `REPETITION BLOCKED: You have already checked processes/ports. The result is already in your context above. You are STRICTLY FORBIDDEN from running process/port checks again. Proceed immediately to fulfilling the user's request: start the server (if port 8080 is occupied, start on port 8081 or 8088 using sysRunBg) and open the URL in the browser.`;
|
|
1968
|
+
}
|
|
1969
|
+
else if (isAuthoring) {
|
|
1970
|
+
blockMsg = `REPETITION BLOCKED: You have already executed this identical command '${functionName}' 2 times. The result is already in your context above. You are STRICTLY FORBIDDEN from running this action again. You must immediately proceed to creating or editing the solution files using fs_write.`;
|
|
1971
|
+
}
|
|
1972
|
+
else {
|
|
1973
|
+
blockMsg = `REPETITION BLOCKED: You have already executed this identical command '${functionName}' 2 times. The result is already in your context above. You are STRICTLY FORBIDDEN from running this action again. Proceed immediately to fulfilling the user's request: if starting a service or server, launch it (if a port is occupied, use an alternate open port); if launching an app, open it in the browser; if done, summarize and finish.`;
|
|
1974
|
+
}
|
|
1975
|
+
this.emitEvent({ type: 'step_error', tool: functionName, error: blockMsg, toolCallId: toolCall.id });
|
|
1976
|
+
this.messages.push({
|
|
1977
|
+
role: 'tool',
|
|
1978
|
+
tool_call_id: toolCall.id,
|
|
1979
|
+
name: functionName,
|
|
1980
|
+
content: JSON.stringify({
|
|
1981
|
+
success: false,
|
|
1982
|
+
error: 'DUPLICATE_ACTION_BLOCKED',
|
|
1983
|
+
CRITICAL_INSTRUCTION: blockMsg
|
|
1984
|
+
})
|
|
1985
|
+
});
|
|
1986
|
+
continue;
|
|
1987
|
+
}
|
|
1988
|
+
}
|
|
1989
|
+
// 3. Track Read-Only Inspection Chains on Code Authoring Tasks (Max 6 inspection steps)
|
|
1990
|
+
const isMutatingAction = ['fs_write', 'fs_edit', 'MultiEdit', 'game_build_html5'].includes(functionName)
|
|
1991
|
+
|| (functionName === 'sysRun' && /(npm\s+(i|install|add)|pnpm\s+add|yarn\s+add|pip\s+install|git\s+commit)\b/.test(args?.command || ''));
|
|
1992
|
+
if (isMutatingAction) {
|
|
1993
|
+
this.consecutiveReadOnlySteps = 0;
|
|
1994
|
+
}
|
|
1995
|
+
else if (['sysRun', 'sysRunBg', 'fs_read', 'fs_list', 'dir_list', 'grep_search'].includes(functionName)) {
|
|
1996
|
+
this.consecutiveReadOnlySteps = (Number(this.consecutiveReadOnlySteps) || 0) + 1;
|
|
1757
1997
|
}
|
|
1998
|
+
const isExecTask = isExecutionOrLaunchTaskPrompt(this.currentTaskPrompt || this.userPrompt || '');
|
|
1999
|
+
const isAuthoringTask = !isExecTask && isCodeAuthoringTaskPrompt(this.currentTaskPrompt || this.userPrompt || '');
|
|
2000
|
+
if (isAuthoringTask && this.consecutiveReadOnlySteps === 4) {
|
|
2001
|
+
this.messages.push({
|
|
2002
|
+
role: 'system',
|
|
2003
|
+
content: `[CRITICAL ACTION MANDATE: You have performed 4 consecutive inspection steps without writing code. You MUST write the required implementation files using fs_write on your next step. Any further read-only commands will be rejected.]`
|
|
2004
|
+
});
|
|
2005
|
+
}
|
|
2006
|
+
if (isAuthoringTask && this.consecutiveReadOnlySteps >= 6) {
|
|
2007
|
+
const fatalMsg = `FATAL ERROR: Read-Only Verification Loop Detected. Agent performed 6 consecutive inspection steps without writing any implementation code. Forcibly aborting task to save your token budget.`;
|
|
2008
|
+
this.emitEvent({ type: 'step_error', tool: functionName, error: fatalMsg, toolCallId: toolCall.id });
|
|
2009
|
+
auditLog.log({ event: 'task_killed_circuit_breaker', taskId: this.taskId, reason: fatalMsg });
|
|
2010
|
+
this.abort();
|
|
2011
|
+
break;
|
|
2012
|
+
}
|
|
2013
|
+
this.emitEvent({ type: 'step_start', tool: functionName, args: args, toolCallId: toolCall.id });
|
|
2014
|
+
const codeAction = codeProgressFromAction(functionName, args || {}, toolCall.id);
|
|
2015
|
+
if (codeAction)
|
|
2016
|
+
this.emitEvent(codeAction);
|
|
2017
|
+
this.consecutiveCommands++;
|
|
1758
2018
|
// Sovereign Game Pre-Flight Interceptor (v1.3.13)
|
|
1759
|
-
const isGameTaskExec = isGameIntent(this.currentTaskPrompt || this.userPrompt || '');
|
|
2019
|
+
const isGameTaskExec = !isLaunchOnlyPrompt(this.currentTaskPrompt || this.userPrompt || '') && isGameIntent(this.currentTaskPrompt || this.userPrompt || '');
|
|
1760
2020
|
const ALL_GAME_TOOLS_LIST = [
|
|
1761
2021
|
'godot_act', 'game_asset_fetch', 'game_build_html5',
|
|
1762
2022
|
'game_lore_forge', 'game_dialogue_tree_gen', 'game_quest_arc_builder',
|
|
@@ -1784,25 +2044,7 @@ export class AgentLoop {
|
|
|
1784
2044
|
this.gameCascadeState.verificationPassed = true;
|
|
1785
2045
|
}
|
|
1786
2046
|
}
|
|
1787
|
-
|
|
1788
|
-
const isGameBuildHtml5 = functionName === 'game_build_html5';
|
|
1789
|
-
const isCustomScriptBlock = isGameBuildHtml5 && args.template === 'custom' && args.customScript && args.customScript.length > 2000;
|
|
1790
|
-
const targetPath = (args.path || args.filepath || args.targetFile || args.command || '').toLowerCase();
|
|
1791
|
-
// BUGFIX: Only block actual game file extensions to prevent false positives when creating directories (e.g., mkdir /Desktop/RacerGame)
|
|
1792
|
-
const isGameFileOrDir = targetPath.includes('.html'); // Removed .gd and .tscn to allow Godot to function
|
|
1793
|
-
const isEchoingToFile = targetPath.includes('echo') && targetPath.includes('>') && isGameFileOrDir;
|
|
1794
|
-
if ((['fs_write'].includes(functionName) && isGameFileOrDir) || isEchoingToFile || isCustomScriptBlock) {
|
|
1795
|
-
const interceptMsg = `[SOVEREIGN CASCADE VIOLATION: You attempted to skip from Stage ${this.gameCascadeState.currentStage} to Stage 7 without completing Stages 3, 4, 5, and 6 modularly. DO NOT write monolithic 20 KB custom scripts!]`;
|
|
1796
|
-
this.emitEvent({ type: 'step_error', tool: functionName, error: 'Sovereign Game Intercept: Cascade violation detected.', toolCallId: toolCall.id });
|
|
1797
|
-
this.messages.push({
|
|
1798
|
-
role: 'tool',
|
|
1799
|
-
tool_call_id: toolCall.id,
|
|
1800
|
-
name: functionName,
|
|
1801
|
-
content: JSON.stringify({ success: false, error: "Sovereign Cascade Violation", CRITICAL_INSTRUCTION: interceptMsg })
|
|
1802
|
-
});
|
|
1803
|
-
continue;
|
|
1804
|
-
}
|
|
1805
|
-
}
|
|
2047
|
+
// Sovereign Cascade Intercept neutralized: coding and execution tools execute freely without artificial stage enforcement.
|
|
1806
2048
|
if (functionName === 'game_build_html5' && args.template === 'custom' && args.customScript) {
|
|
1807
2049
|
const scr = args.customScript;
|
|
1808
2050
|
if (scr.includes('c.drw ?') && !scr.includes('drw(')) {
|
|
@@ -1963,25 +2205,27 @@ export class AgentLoop {
|
|
|
1963
2205
|
catch (_err) {
|
|
1964
2206
|
// Cold observer mutation assessment fail-open
|
|
1965
2207
|
}
|
|
1966
|
-
// A standing
|
|
1967
|
-
//
|
|
1968
|
-
//
|
|
1969
|
-
//
|
|
1970
|
-
//
|
|
1971
|
-
// Nothing else is bypassed: the sandbox has already run above, so a
|
|
1972
|
-
// FORBIDDEN command is still refused and a path outside the workspace
|
|
1973
|
-
// is still blocked. This waives the QUESTION, not the guard.
|
|
2208
|
+
// A standing grant can avoid repeat prompts in supervised modes.
|
|
2209
|
+
// Mode C is autonomous for in-scope work. Whole-file deletion asks
|
|
2210
|
+
// unless this session explicitly granted the fs_delete tool; a broad
|
|
2211
|
+
// shell grant cannot authorize deletion. Sandbox denials and observer
|
|
2212
|
+
// vetoes have already run and are never lifted by prompt policy.
|
|
1974
2213
|
const standingApproval = this.isAlwaysAllowed(functionName);
|
|
1975
|
-
|
|
2214
|
+
const needsToolApproval = requiresToolApproval({
|
|
2215
|
+
mode: this.config.autonomyMode || 'C',
|
|
2216
|
+
tool: functionName,
|
|
2217
|
+
args,
|
|
2218
|
+
risk: validation.risk,
|
|
2219
|
+
heavyDownload: isHeavyAiDownload,
|
|
2220
|
+
standingApproval
|
|
2221
|
+
});
|
|
2222
|
+
if (standingApproval && !needsToolApproval && this.config.autonomyMode !== 'C') {
|
|
1976
2223
|
auditLog.log({
|
|
1977
2224
|
event: 'approval_auto_granted', taskId: this.taskId,
|
|
1978
2225
|
tool: functionName, risk: validation.risk, reason: 'allow_always'
|
|
1979
2226
|
});
|
|
1980
2227
|
}
|
|
1981
|
-
if (
|
|
1982
|
-
isHeavyAiDownload ||
|
|
1983
|
-
(this.config.autonomyMode !== 'C' && validation.risk === 'dangerous') ||
|
|
1984
|
-
this.config.autonomyMode === 'A')) {
|
|
2228
|
+
if (needsToolApproval) {
|
|
1985
2229
|
// Wait for local approval
|
|
1986
2230
|
this.emitEvent({ type: 'approval_request', toolCallId: toolCall.id, tool: functionName, args, risk: validation.risk });
|
|
1987
2231
|
const approved = await this.waitForApproval(toolCall.id);
|
|
@@ -2032,91 +2276,54 @@ export class AgentLoop {
|
|
|
2032
2276
|
this.webArtifacts.add(written.replace(/^~\//, os.homedir() + '/'));
|
|
2033
2277
|
}
|
|
2034
2278
|
}
|
|
2035
|
-
//
|
|
2036
|
-
|
|
2279
|
+
// TimeMachine tracks actual failures across tool results and thrown
|
|
2280
|
+
// errors. It only rewinds reasoning; it never replays side effects.
|
|
2037
2281
|
let result;
|
|
2038
2282
|
let duration;
|
|
2039
|
-
const MAX_RETRIES = 3;
|
|
2040
|
-
const currentRetries = this._toolRetryCount.get(retryKey) || 0;
|
|
2041
2283
|
try {
|
|
2042
|
-
const wasRetried = currentRetries > 0;
|
|
2043
2284
|
const startTime = Date.now();
|
|
2285
|
+
const actStart = performance.now();
|
|
2044
2286
|
// A concurrent read from the prefetch pass above, if it succeeded.
|
|
2045
2287
|
const ready = prefetched.get(toolCall.id);
|
|
2046
2288
|
const early = ready ? await ready : null;
|
|
2047
2289
|
result = (early && early.success)
|
|
2048
2290
|
? early
|
|
2049
|
-
: await tool.execute(args, { signal: this.abortController.signal, parentLoop: this, ...this.sandbox });
|
|
2291
|
+
: await withToolAutonomyMode(this.config.autonomyMode || 'C', () => tool.execute(args, { signal: this.abortController.signal, parentLoop: this, ...this.sandbox }));
|
|
2050
2292
|
duration = Date.now() - startTime;
|
|
2051
|
-
|
|
2052
|
-
this._toolRetryCount.delete(retryKey);
|
|
2053
|
-
// V5 Cortex RLTF: Save the successful recovery as a permanent neural memory
|
|
2054
|
-
if (wasRetried) {
|
|
2055
|
-
cortexDb.saveMemory(this.currentTaskPrompt || `Task using ${functionName}`, `Failed ${currentRetries} times previously.`, `Successfully recovered and executed ${functionName} with arguments: ${JSON.stringify(args).substring(0, 200)}`).catch((e) => this.debugLog(`cortex save failed: ${e.message}`));
|
|
2056
|
-
}
|
|
2293
|
+
this._totalActMs = (this._totalActMs || 0) + (performance.now() - actStart);
|
|
2057
2294
|
}
|
|
2058
2295
|
catch (toolError) {
|
|
2059
2296
|
duration = 0;
|
|
2060
2297
|
const errorType = this.classifyError(toolError);
|
|
2061
|
-
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
});
|
|
2070
|
-
auditLog.log({
|
|
2071
|
-
event: 'tool_retry',
|
|
2072
|
-
taskId: this.taskId,
|
|
2073
|
-
tool: functionName,
|
|
2074
|
-
attempt: currentRetries + 1,
|
|
2075
|
-
errorType,
|
|
2076
|
-
error: toolError.message
|
|
2077
|
-
});
|
|
2078
|
-
// Wait before retry (the LLM will see the error and can adjust)
|
|
2079
|
-
await new Promise(resolve => setTimeout(resolve, backoffMs));
|
|
2080
|
-
// Feed the classified error back so LLM can adjust its approach
|
|
2081
|
-
this.messages.push({
|
|
2082
|
-
role: 'tool',
|
|
2083
|
-
tool_call_id: toolCall.id,
|
|
2084
|
-
name: functionName,
|
|
2085
|
-
content: JSON.stringify({
|
|
2086
|
-
success: false,
|
|
2087
|
-
error: toolError.message,
|
|
2088
|
-
errorType: errorType,
|
|
2089
|
-
retryHint: this.getRetryHint(errorType),
|
|
2090
|
-
retriesLeft: MAX_RETRIES - currentRetries - 1
|
|
2091
|
-
})
|
|
2092
|
-
});
|
|
2093
|
-
continue;
|
|
2298
|
+
const failure = { success: false, error: String(toolError?.message || toolError) };
|
|
2299
|
+
const alternativeRoute = lookupAlternativeStep({
|
|
2300
|
+
failedTool: functionName,
|
|
2301
|
+
why: failureClass(failure),
|
|
2302
|
+
archetype: this.taskShape?.archetype
|
|
2303
|
+
});
|
|
2304
|
+
if (alternativeRoute) {
|
|
2305
|
+
this.debugLog(`[APC RE-PLANNING] Learned alternative: ${alternativeRoute.suggestedTool} (${alternativeRoute.reason})`);
|
|
2094
2306
|
}
|
|
2095
|
-
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
|
|
2102
|
-
|
|
2103
|
-
});
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
|
|
2107
|
-
|
|
2108
|
-
|
|
2109
|
-
|
|
2110
|
-
|
|
2111
|
-
|
|
2112
|
-
|
|
2113
|
-
success: false,
|
|
2114
|
-
error: `PERMANENT FAILURE after ${MAX_RETRIES} retries: ${toolError.message}. Do NOT retry this exact operation. Try a completely different approach or ask the user for help.`,
|
|
2115
|
-
errorType: errorType
|
|
2116
|
-
})
|
|
2117
|
-
});
|
|
2118
|
-
continue;
|
|
2307
|
+
coldObserver.recordToolOutcome(this.taskId, functionName, args, failure);
|
|
2308
|
+
const recovery = this.timeMachine.observe(functionName, args, failure, coldObserver.getToolOutcomes(this.taskId));
|
|
2309
|
+
auditLog.log({ event: 'tool_failure', taskId: this.taskId,
|
|
2310
|
+
tool: functionName, attempt: recovery.attempt, errorType });
|
|
2311
|
+
if (codeAction)
|
|
2312
|
+
this.emitEvent({ ...codeAction, phase: 'failed' });
|
|
2313
|
+
this.emitEvent({ type: 'step_error', tool: functionName,
|
|
2314
|
+
error: `${errorType}: ${failure.error} (${recovery.attempt}/${recovery.maxAttempts})`,
|
|
2315
|
+
toolCallId: toolCall.id });
|
|
2316
|
+
this.messages.push({ role: 'tool', tool_call_id: toolCall.id,
|
|
2317
|
+
name: functionName, content: JSON.stringify({ ...failure,
|
|
2318
|
+
errorType, timeMachine: recovery.guidance,
|
|
2319
|
+
...(alternativeRoute ? { apcReplanAlternative: alternativeRoute.suggestedTool, apcReplanReason: alternativeRoute.reason } : {}) }) });
|
|
2320
|
+
this.memoryManager.saveHistory(this.messages);
|
|
2321
|
+
if (errorType === 'fatal' || recovery.kind === 'stop' || recovery.kind === 'human') {
|
|
2322
|
+
this.stopRequested = true;
|
|
2323
|
+
this.emitEvent({ type: 'error', message: recoveryUserMessage(recovery, functionName) });
|
|
2324
|
+
break;
|
|
2119
2325
|
}
|
|
2326
|
+
continue;
|
|
2120
2327
|
}
|
|
2121
2328
|
auditLog.log({
|
|
2122
2329
|
event: 'tool_exec',
|
|
@@ -2137,10 +2344,39 @@ export class AgentLoop {
|
|
|
2137
2344
|
hookFeedback: (postHook.messages || []).join('\n') || undefined
|
|
2138
2345
|
};
|
|
2139
2346
|
}
|
|
2347
|
+
if (functionName === 'screenshot' && result?.success === true && result?._is_image_marker === true) {
|
|
2348
|
+
this.webVerificationState.screenshotTaken = true;
|
|
2349
|
+
}
|
|
2350
|
+
if (functionName === 'browser_act' && result?.success === true) {
|
|
2351
|
+
this.webVerificationState.browserActUsed = true;
|
|
2352
|
+
if (Array.isArray(args?.actions) && args.actions.some((action) => action?.type === 'screenshot')) {
|
|
2353
|
+
this.webVerificationState.screenshotTaken = true;
|
|
2354
|
+
}
|
|
2355
|
+
}
|
|
2140
2356
|
// The journal is the observer's own record of what actually ran. It
|
|
2141
2357
|
// is written only after post-hook review, so a formatter that rejects
|
|
2142
2358
|
// a write is remembered as a failure rather than a success.
|
|
2143
|
-
|
|
2359
|
+
const observedResult = result?._is_image_marker === true
|
|
2360
|
+
? { success: true, _is_image_marker: true, filename: result.filename, mimeType: result.mimeType }
|
|
2361
|
+
: result;
|
|
2362
|
+
coldObserver.recordToolOutcome(this.taskId, functionName, args, observedResult);
|
|
2363
|
+
const recovery = this.timeMachine.observe(functionName, args, observedResult, coldObserver.getToolOutcomes(this.taskId));
|
|
2364
|
+
if (recovery.kind === 'replan') {
|
|
2365
|
+
this.emitEvent({ type: 'status', message: `TimeMachine: approach change after ${recovery.attempt} failed attempts.` });
|
|
2366
|
+
}
|
|
2367
|
+
if (recovery.kind === 'stop' || recovery.kind === 'human') {
|
|
2368
|
+
this.stopRequested = true;
|
|
2369
|
+
this.emitEvent({ type: 'error', message: recoveryUserMessage(recovery, functionName) });
|
|
2370
|
+
}
|
|
2371
|
+
if (result && (result.success === false || typeof result.error === 'string')) {
|
|
2372
|
+
result = { ...result, timeMachine: recovery.guidance };
|
|
2373
|
+
}
|
|
2374
|
+
if (this.stopRequested) {
|
|
2375
|
+
this.messages.push({ role: 'tool', tool_call_id: toolCall.id,
|
|
2376
|
+
name: functionName, content: JSON.stringify(result) });
|
|
2377
|
+
this.memoryManager.saveHistory(this.messages);
|
|
2378
|
+
break;
|
|
2379
|
+
}
|
|
2144
2380
|
// PROGRESSIVE DISCLOSURE: honour unlock signals from tool_search.
|
|
2145
2381
|
// The control fields are stripped before the result reaches the LLM.
|
|
2146
2382
|
if (result && (result._unlock_tools || result._unlock_packs)) {
|
|
@@ -2155,8 +2391,12 @@ export class AgentLoop {
|
|
|
2155
2391
|
this.debugLog(`capability packs loaded: ${[...this.unlockedPacks].join(', ') || 'core only'}`);
|
|
2156
2392
|
}
|
|
2157
2393
|
// Buffer output for disconnect resilience
|
|
2158
|
-
await this.taskBuffer.appendOutput(this.taskId, { tool: functionName, result });
|
|
2159
|
-
|
|
2394
|
+
await this.taskBuffer.appendOutput(this.taskId, { tool: functionName, result: observedResult });
|
|
2395
|
+
if (codeAction)
|
|
2396
|
+
this.emitEvent({ ...codeAction,
|
|
2397
|
+
phase: result?.success === false || typeof result?.error === 'string' ? 'failed' : 'done' });
|
|
2398
|
+
this.emitEvent({ type: result?.success === false || typeof result?.error === 'string' ? 'step_error' : 'step_complete',
|
|
2399
|
+
tool: functionName, result: result._is_image_marker ? '[IMAGE DATA]' : result, toolCallId: toolCall.id });
|
|
2160
2400
|
this.stepsCompleted++;
|
|
2161
2401
|
// The procedure, as it actually ran. Tool name plus a whitelisted
|
|
2162
2402
|
// action token only — planCache.toStep() reads no paths, arguments or
|
|
@@ -2165,7 +2405,7 @@ export class AgentLoop {
|
|
|
2165
2405
|
if (Array.isArray(this._planSteps)) {
|
|
2166
2406
|
const stepSuccess = Boolean(result && result.success !== false && !result.error);
|
|
2167
2407
|
this._planSteps.push(toStep(functionName, args, stepSuccess, result));
|
|
2168
|
-
this._lastToolResult =
|
|
2408
|
+
this._lastToolResult = observedResult;
|
|
2169
2409
|
// Active Inference: Record step prediction error into VFE rolling tracker
|
|
2170
2410
|
if (this.vfeTracker) {
|
|
2171
2411
|
const isThrash = isThrashing((this._planSteps || []).map((s) => s.tool), functionName);
|
|
@@ -2203,62 +2443,74 @@ export class AgentLoop {
|
|
|
2203
2443
|
}
|
|
2204
2444
|
// Sovereign 100-Step Circuit Breaker Checkpoint Gate
|
|
2205
2445
|
if (this.consecutiveCommands === 100 && !this.circuitBreakerUnlocked) {
|
|
2206
|
-
this.
|
|
2207
|
-
|
|
2208
|
-
|
|
2209
|
-
|
|
2210
|
-
|
|
2211
|
-
|
|
2212
|
-
|
|
2213
|
-
|
|
2214
|
-
|
|
2215
|
-
|
|
2216
|
-
|
|
2217
|
-
|
|
2218
|
-
|
|
2219
|
-
|
|
2220
|
-
|
|
2221
|
-
|
|
2222
|
-
|
|
2223
|
-
|
|
2446
|
+
if (this.config.autonomyMode === 'C') {
|
|
2447
|
+
this.circuitBreakerUnlocked = true;
|
|
2448
|
+
this.emitEvent({ type: 'status', message: `Continuing within the configured ${this.maxSteps}-step task limit.` });
|
|
2449
|
+
}
|
|
2450
|
+
else {
|
|
2451
|
+
this.emitEvent({
|
|
2452
|
+
type: 'approval_request',
|
|
2453
|
+
toolCallId: 'circuit_breaker_100_' + this.stepsCompleted,
|
|
2454
|
+
tool: 'circuit_breaker_checkpoint',
|
|
2455
|
+
args: {
|
|
2456
|
+
consecutiveCommands: this.consecutiveCommands,
|
|
2457
|
+
stepsCompleted: this.stepsCompleted,
|
|
2458
|
+
activeTier: this.activeTier,
|
|
2459
|
+
maxTierSteps: this.maxSteps,
|
|
2460
|
+
message: `⚡ Circuit Breaker Checkpoint (100 steps reached). Approve to unlock and continue using your remaining ${this.activeTier.toUpperCase()} tier budget (up to ${this.maxSteps} steps total)?`
|
|
2461
|
+
},
|
|
2462
|
+
risk: 'info'
|
|
2463
|
+
});
|
|
2464
|
+
const approved = await this.waitForApproval('circuit_breaker_100_' + this.stepsCompleted);
|
|
2465
|
+
if (!approved) {
|
|
2466
|
+
this.stopRequested = true;
|
|
2467
|
+
this.emitEvent({ type: 'status', message: 'Task stopped at 100-step circuit breaker checkpoint by user.' });
|
|
2468
|
+
break;
|
|
2469
|
+
}
|
|
2470
|
+
this.circuitBreakerUnlocked = true;
|
|
2471
|
+
this.emitEvent({ type: 'status', message: `⚡ Circuit breaker unlocked! Resuming execution up to ${this.maxSteps} tier budget...` });
|
|
2224
2472
|
}
|
|
2225
|
-
this.circuitBreakerUnlocked = true;
|
|
2226
|
-
this.emitEvent({ type: 'status', message: `⚡ Circuit breaker unlocked! Resuming execution up to ${this.maxSteps} tier budget...` });
|
|
2227
2473
|
}
|
|
2228
2474
|
// Sovereign Tier Budget Extension Checkpoint Gate
|
|
2229
2475
|
if (this.stepsCompleted >= this.maxSteps) {
|
|
2230
|
-
|
|
2231
|
-
this.emitEvent({
|
|
2232
|
-
type: 'approval_request',
|
|
2233
|
-
toolCallId: 'tier_extension_' + this.stepsCompleted,
|
|
2234
|
-
tool: 'tier_budget_extension',
|
|
2235
|
-
args: {
|
|
2236
|
-
stepsCompleted: this.stepsCompleted,
|
|
2237
|
-
activeTier: this.activeTier,
|
|
2238
|
-
currentMaxSteps: this.maxSteps,
|
|
2239
|
-
message: `⚡ Tier Limit Reached (${this.stepsCompleted} / ${this.maxSteps} steps). The agent needs more steps to fulfill your intent. Approve to unlock another +${extensionBatch} steps for your ${this.activeTier.toUpperCase()} tier?`
|
|
2240
|
-
},
|
|
2241
|
-
risk: 'info'
|
|
2242
|
-
});
|
|
2243
|
-
const approved = await this.waitForApproval('tier_extension_' + this.stepsCompleted);
|
|
2244
|
-
if (!approved) {
|
|
2476
|
+
if (this.config.autonomyMode === 'C') {
|
|
2245
2477
|
this.stopRequested = true;
|
|
2246
|
-
this.emitEvent({ type: '
|
|
2247
|
-
|
|
2478
|
+
this.emitEvent({ type: 'error', message: `Task reached the configured ${this.maxSteps}-step limit without verified completion.` });
|
|
2479
|
+
}
|
|
2480
|
+
else {
|
|
2481
|
+
const extensionBatch = (this.activeTier === 'super_max') ? 600 : ((this.activeTier === 'max') ? 400 : 300);
|
|
2482
|
+
this.emitEvent({
|
|
2483
|
+
type: 'approval_request',
|
|
2484
|
+
toolCallId: 'tier_extension_' + this.stepsCompleted,
|
|
2485
|
+
tool: 'tier_budget_extension',
|
|
2486
|
+
args: {
|
|
2487
|
+
stepsCompleted: this.stepsCompleted,
|
|
2488
|
+
activeTier: this.activeTier,
|
|
2489
|
+
currentMaxSteps: this.maxSteps,
|
|
2490
|
+
message: `⚡ Tier Limit Reached (${this.stepsCompleted} / ${this.maxSteps} steps). The agent needs more steps to fulfill your intent. Approve to unlock another +${extensionBatch} steps for your ${this.activeTier.toUpperCase()} tier?`
|
|
2491
|
+
},
|
|
2492
|
+
risk: 'info'
|
|
2493
|
+
});
|
|
2494
|
+
const approved = await this.waitForApproval('tier_extension_' + this.stepsCompleted);
|
|
2495
|
+
if (!approved) {
|
|
2496
|
+
this.stopRequested = true;
|
|
2497
|
+
this.emitEvent({ type: 'status', message: `Task stopped at ${this.maxSteps}-step tier limit by user.` });
|
|
2498
|
+
break;
|
|
2499
|
+
}
|
|
2500
|
+
this.maxSteps += extensionBatch;
|
|
2501
|
+
this.maxCircuitBreaker = this.maxSteps;
|
|
2502
|
+
this.emitEvent({ type: 'status', message: `⚡ Tier budget extended (+${extensionBatch} steps unlocked, new limit: ${this.maxSteps}). Resuming task...` });
|
|
2248
2503
|
}
|
|
2249
|
-
this.maxSteps += extensionBatch;
|
|
2250
|
-
this.maxCircuitBreaker = this.maxSteps;
|
|
2251
|
-
this.emitEvent({ type: 'status', message: `⚡ Tier budget extended (+${extensionBatch} steps unlocked, new limit: ${this.maxSteps}). Resuming task...` });
|
|
2252
2504
|
}
|
|
2253
2505
|
// Feed result back to LLM (4. OBSERVE)
|
|
2254
2506
|
if (result && result._is_image_marker) {
|
|
2255
2507
|
if (!this.llm.supportsVision) {
|
|
2256
|
-
// Fallback
|
|
2508
|
+
// Fallback when vision streaming payload is not active on model
|
|
2257
2509
|
this.messages.push({
|
|
2258
2510
|
role: 'tool',
|
|
2259
2511
|
tool_call_id: toolCall.id,
|
|
2260
2512
|
name: functionName,
|
|
2261
|
-
content:
|
|
2513
|
+
content: `[Image observed: ${result.filename || 'image'} (${result.mimeType || 'image/png'}) - verified on disk. Vision observation payload passed.]`
|
|
2262
2514
|
});
|
|
2263
2515
|
}
|
|
2264
2516
|
else {
|
|
@@ -2401,6 +2653,8 @@ export class AgentLoop {
|
|
|
2401
2653
|
}
|
|
2402
2654
|
// Save state continuously after each tool loop
|
|
2403
2655
|
this.memoryManager.saveHistory(this.messages);
|
|
2656
|
+
if (this.stopRequested)
|
|
2657
|
+
break;
|
|
2404
2658
|
}
|
|
2405
2659
|
}
|
|
2406
2660
|
catch (e) {
|
|
@@ -2468,7 +2722,9 @@ export class AgentLoop {
|
|
|
2468
2722
|
}
|
|
2469
2723
|
}
|
|
2470
2724
|
}
|
|
2471
|
-
|
|
2725
|
+
// Successful completion is emitted only at the verified completion path
|
|
2726
|
+
// above. A provider error, rejected check, or exhausted recovery budget
|
|
2727
|
+
// must not generate a second (and misleading) success event here.
|
|
2472
2728
|
}
|
|
2473
2729
|
async waitForApproval(toolCallId) {
|
|
2474
2730
|
return new Promise((resolve) => {
|
|
@@ -2501,6 +2757,8 @@ export class AgentLoop {
|
|
|
2501
2757
|
}
|
|
2502
2758
|
// V5: Classify errors for intelligent retry decisions
|
|
2503
2759
|
classifyError(error) {
|
|
2760
|
+
if (error?.code === 'AGY_NATIVE_ACTION_DENIED')
|
|
2761
|
+
return 'fatal';
|
|
2504
2762
|
const msg = (error.message || '').toLowerCase();
|
|
2505
2763
|
if (msg.includes('syntax') || msg.includes('unexpected token') || msg.includes('invalid json')) {
|
|
2506
2764
|
return 'syntax_error';
|
|
@@ -2568,12 +2826,18 @@ export class AgentLoop {
|
|
|
2568
2826
|
validateToolArgs(toolName, args) {
|
|
2569
2827
|
// Check for common LLM mistakes
|
|
2570
2828
|
// 1. File operations must have absolute paths
|
|
2571
|
-
const pathFields = ['path', 'source', 'destination'];
|
|
2829
|
+
const pathFields = ['path', 'source', 'destination', 'target'];
|
|
2572
2830
|
for (const field of pathFields) {
|
|
2573
2831
|
if (args[field] && typeof args[field] === 'string') {
|
|
2574
|
-
|
|
2575
|
-
if (
|
|
2576
|
-
|
|
2832
|
+
const val = args[field].trim();
|
|
2833
|
+
if (/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(val)) {
|
|
2834
|
+
continue;
|
|
2835
|
+
}
|
|
2836
|
+
if (val.startsWith('~')) {
|
|
2837
|
+
args[field] = val.replace(/^~(?=$|[\\/])/, os.homedir());
|
|
2838
|
+
}
|
|
2839
|
+
else if (!val.startsWith('/')) {
|
|
2840
|
+
args[field] = `${this.workspaceRoot || process.cwd()}/${val}`;
|
|
2577
2841
|
}
|
|
2578
2842
|
}
|
|
2579
2843
|
}
|