@causyne/agent 1.20.0 → 1.20.7
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 +13 -9
- package/SECURITY.md +1 -4
- package/package.json +1 -1
- package/src/acp/client.js +176 -26
- package/src/acp/client.ts +167 -25
- package/src/acp/protocol.js +116 -0
- package/src/acp/protocol.ts +163 -0
- 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 +681 -245
- package/src/agentLoop.ts +708 -262
- 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 +52 -29
- package/src/commands.js +141 -17
- package/src/config.js +22 -12
- 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 +26 -2
- package/src/modelCatalogue.js +2 -0
- package/src/planCache.js +320 -11
- package/src/planCache.ts +402 -13
- package/src/providers/acp.js +173 -18
- package/src/providers/acp.ts +169 -19
- package/src/providers/antigravity.d.ts +5 -1
- package/src/providers/antigravity.js +674 -34
- package/src/providers/antigravity.ts +707 -35
- package/src/providers/base.d.ts +10 -0
- package/src/providers/factory.js +2 -0
- package/src/providers/pi.js +161 -0
- package/src/providers/pi.ts +148 -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 +53 -10
- package/src/sessionJournal.ts +64 -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/activityLayout.js +9 -0
- package/src/tui/activityLayout.ts +10 -0
- package/src/tui/block.d.ts +1 -0
- package/src/tui/chatRenderer.d.ts +23 -0
- package/src/tui/chatRenderer.js +49 -49
- 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 +132 -0
- package/src/tui/codeStreamRenderer.ts +141 -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 +131 -0
- package/src/tui/composerControls.ts +184 -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 +4 -24
- package/src/tui/modelPicker.ts +4 -20
- package/src/tui/mouseHover.js +6 -0
- package/src/tui/mouseHover.ts +5 -0
- package/src/tui/prompt.js +175 -101
- 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 +111 -16
- package/src/tui/sessionPicker.ts +121 -16
- 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 +120 -58
- package/src/tui/text.d.ts +6 -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
|
|
@@ -31,28 +34,130 @@ import { spillToolResult, buildSpillNotice, buildDecayPointer, pruneOutputStore
|
|
|
31
34
|
import { beginTask as beginCheckpointTask, captureBeforeMutation, pruneStore as pruneCheckpointStore, resolveProjectRoot } from './checkpoints.js';
|
|
32
35
|
import fsSync from 'fs';
|
|
33
36
|
import os from 'os';
|
|
37
|
+
import path from 'path';
|
|
34
38
|
import { analyzeFiles, formatFindings, isScannableFile } from './slopDetector.js';
|
|
35
39
|
import { suggestMovements, formatMovementBrief } from './designPalettes.js';
|
|
36
40
|
import { createProvider } from './providers/factory.js';
|
|
37
41
|
import { resolveMentionedContext } from './promptMentions.js';
|
|
38
|
-
|
|
42
|
+
import { isLaunchOnlyPrompt, launchScopeError } from './launchIntent.js';
|
|
43
|
+
import { StreamingCodePreview, NativeCodeObserver, codeProgressFromAction } from './tui/codeProgress.js';
|
|
44
|
+
export function isActionableTaskPrompt(text) {
|
|
45
|
+
const t = (text || '').trim();
|
|
46
|
+
if (!t)
|
|
47
|
+
return false;
|
|
48
|
+
const pureGreeting = /^(hi|hello|hey|yo|good\s+(morning|afternoon|evening))[.!?, ]*$/i.test(t);
|
|
49
|
+
if (pureGreeting)
|
|
50
|
+
return false;
|
|
51
|
+
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;
|
|
52
|
+
return actionKeywords.test(t);
|
|
53
|
+
}
|
|
54
|
+
export function isExecutionOrLaunchTaskPrompt(text) {
|
|
55
|
+
const t = (text || '').trim();
|
|
56
|
+
if (!t)
|
|
57
|
+
return false;
|
|
58
|
+
return /\b(open|launch|start|run|play|serve|preview)\b/i.test(t)
|
|
59
|
+
&& !/\b(create|build|make|write|code|implement|generate|refactor)\b/i.test(t);
|
|
60
|
+
}
|
|
61
|
+
export function isCodeAuthoringTaskPrompt(text) {
|
|
62
|
+
const t = (text || '').trim();
|
|
63
|
+
if (!t)
|
|
64
|
+
return false;
|
|
65
|
+
if (isExecutionOrLaunchTaskPrompt(t))
|
|
66
|
+
return false;
|
|
67
|
+
return /\b(create|build|make|write|code|implement|generate|game|3js|threejs|three\.js|app)\b/i.test(t);
|
|
68
|
+
}
|
|
69
|
+
export function isDirectGameTask(text) {
|
|
70
|
+
return /\b(three\.?js|3js|webgl|canvas|html5|pygame)\b/i.test(text)
|
|
71
|
+
&& !/\b(godot|unity|unreal|full engine)\b/i.test(text);
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Detects when an agent response is an intermediate mid-task progress note or
|
|
75
|
+
* transition announcement (e.g. "Real assets verified. Writing the Tesla-style
|
|
76
|
+
* redesign now." or "Let me look at the newer assets... Pulling their real
|
|
77
|
+
* stills and confirming embeddability.") rather than a finished answer.
|
|
78
|
+
*/
|
|
79
|
+
export function isMidTaskProgressText(text) {
|
|
80
|
+
if (!text || typeof text !== 'string')
|
|
81
|
+
return false;
|
|
82
|
+
const trimmed = text.trim();
|
|
83
|
+
if (!trimmed || trimmed.length > 480)
|
|
84
|
+
return false;
|
|
85
|
+
const lower = trimmed.toLowerCase();
|
|
86
|
+
if (lower.includes('?') ||
|
|
87
|
+
lower.includes('let me know') ||
|
|
88
|
+
lower.includes('how can i help') ||
|
|
89
|
+
lower.includes('how may i help') ||
|
|
90
|
+
lower.includes('how can i assist') ||
|
|
91
|
+
lower.includes('what would you like') ||
|
|
92
|
+
lower.includes('what can i help') ||
|
|
93
|
+
lower.includes('feel free to')) {
|
|
94
|
+
return false;
|
|
95
|
+
}
|
|
96
|
+
if (trimmed.includes('```'))
|
|
97
|
+
return false;
|
|
98
|
+
const sentences = trimmed
|
|
99
|
+
.split(/(?:(?<=[.!])\s+|\n+)/)
|
|
100
|
+
.map(s => s.trim())
|
|
101
|
+
.filter(Boolean);
|
|
102
|
+
const lastSentence = (sentences[sentences.length - 1] || trimmed).trim();
|
|
103
|
+
const lastLower = lastSentence.toLowerCase();
|
|
104
|
+
if (trimmed.length <= 280 && (trimmed.endsWith(':') || trimmed.endsWith('...') || trimmed.endsWith('…'))) {
|
|
105
|
+
return true;
|
|
106
|
+
}
|
|
107
|
+
const intentPrefixes = [
|
|
108
|
+
'let me ',
|
|
109
|
+
"i'll ",
|
|
110
|
+
'i will ',
|
|
111
|
+
'now i ',
|
|
112
|
+
'now let me ',
|
|
113
|
+
"now i'll ",
|
|
114
|
+
'now i will ',
|
|
115
|
+
'next, i ',
|
|
116
|
+
'next i ',
|
|
117
|
+
"next, i'll ",
|
|
118
|
+
"next i'll ",
|
|
119
|
+
'first, i ',
|
|
120
|
+
'first i ',
|
|
121
|
+
'let us ',
|
|
122
|
+
"let's ",
|
|
123
|
+
'i shall ',
|
|
124
|
+
'we will ',
|
|
125
|
+
"we'll ",
|
|
126
|
+
'i am going to ',
|
|
127
|
+
"i'm going to ",
|
|
128
|
+
'going to '
|
|
129
|
+
];
|
|
130
|
+
if (intentPrefixes.some(prefix => lastLower.startsWith(prefix) || lower.startsWith(prefix))) {
|
|
131
|
+
if (!/\b(?:task completed|all done|everything is ready|finished|complete\.)\b/i.test(lastSentence)) {
|
|
132
|
+
return true;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
const gerundStart = /^(?:now\s+|next,?\s+|currently\s+|still\s+)?(?:writing|pulling|checking|inspecting|building|creating|updating|applying|implementing|generating|fetching|downloading|testing|running|fixing|setting up|configuring|refactoring|adding|modifying|replacing|launching|starting|verifying|confirming|reading|searching|analyzing|preparing|compiling|rendering|extracting|installing|opening|switching|retrying|continuing)\b/i;
|
|
136
|
+
if (gerundStart.test(lastSentence) && lastSentence.length <= 220) {
|
|
137
|
+
return true;
|
|
138
|
+
}
|
|
139
|
+
const actionNowSuffix = /\b(?:writing|pulling|checking|inspecting|building|creating|updating|applying|implementing|generating|fetching|downloading|testing|running|fixing|configuring|refactoring|adding|modifying|replacing|launching|starting|verifying|confirming|reading|searching|analyzing|preparing|compiling|rendering|extracting)\b[^.!?\n]{1,120}\b(?:now|next)\.?$/i;
|
|
140
|
+
if (actionNowSuffix.test(lastSentence)) {
|
|
141
|
+
return true;
|
|
142
|
+
}
|
|
143
|
+
return false;
|
|
144
|
+
}
|
|
145
|
+
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
146
|
|
|
40
147
|
# 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).
|
|
148
|
+
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.
|
|
149
|
+
|
|
150
|
+
${AGENT_USER_POLICY}
|
|
46
151
|
|
|
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.
|
|
152
|
+
# Project Conventions
|
|
153
|
+
Follow the selected project's existing style and architecture. Check dependencies and tool schemas before use. Preserve unrelated behavior.
|
|
51
154
|
|
|
52
155
|
# Operational Guidelines & Communication
|
|
156
|
+
- **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
157
|
- **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
|
-
- **
|
|
158
|
+
- **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.
|
|
159
|
+
- **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.
|
|
160
|
+
- **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
161
|
- **No Chitchat**: Tools are for actions, text output is *only* for communication. Do not add explanatory comments within tool calls or code blocks.
|
|
57
162
|
- **File Paths**: ALWAYS output the absolute path of any file you create, modify, or generate so the user knows exactly where it is.
|
|
58
163
|
|
|
@@ -65,10 +170,8 @@ Specifically, you excel at:
|
|
|
65
170
|
- 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
171
|
- 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
172
|
|
|
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.
|
|
173
|
+
# Efficient Tool Use
|
|
174
|
+
- Batch independent searches and reads when useful. Keep edits, dependent operations, approvals, and verification in a safe order. Never run conflicting writes concurrently.
|
|
72
175
|
|
|
73
176
|
# Context Understanding & Searching
|
|
74
177
|
- Semantic search (or grep) is your MAIN exploration tool. Start with a broad, high-level query.
|
|
@@ -90,7 +193,7 @@ Specifically, you excel at:
|
|
|
90
193
|
- **Token Budgeting**: You must respect the user's BYOK (Bring Your Own Key) limits. Be highly token-efficient.
|
|
91
194
|
- **Explain Critical Commands**: Before executing destructive shell commands, provide a brief explanation of the impact.
|
|
92
195
|
- **Interactive Commands**: Avoid shell commands that require user interaction (e.g., \`git rebase -i\`). Use non-interactive flags (e.g., \`-y\`).
|
|
93
|
-
- **Sandboxing**:
|
|
196
|
+
- **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
197
|
- **SSRF Protection**: Do not fetch internal IPs (127.0.0.1, 169.254.x.x, 10.x.x.x).
|
|
95
198
|
|
|
96
199
|
# ABSOLUTE ETHICAL SAFETY NET (NON-NEGOTIABLE)
|
|
@@ -109,7 +212,7 @@ If asked to perform ANY harmful task, politely decline, state that Causyne exist
|
|
|
109
212
|
# Dependency Management & Autonomy Modes
|
|
110
213
|
- **Mode A (Passive)**: You MUST explicitly ask the user for permission (by ending your turn and asking a question) before installing any dependencies.
|
|
111
214
|
- **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)**:
|
|
215
|
+
- **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
216
|
|
|
114
217
|
# Direct API & Automation Policy
|
|
115
218
|
- **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 +223,8 @@ If asked to perform ANY harmful task, politely decline, state that Causyne exist
|
|
|
120
223
|
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
224
|
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
225
|
|
|
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!
|
|
226
|
+
# Completion
|
|
227
|
+
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
228
|
`;
|
|
127
229
|
function getProviderSpecificPrompt(provider = '') {
|
|
128
230
|
const p = provider.toLowerCase();
|
|
@@ -347,6 +449,8 @@ export class AgentLoop {
|
|
|
347
449
|
this.updateTierLimits();
|
|
348
450
|
this.consecutiveThinkingSteps = 0;
|
|
349
451
|
this.consecutiveBlockedActions = 0; // V8 Transcendence: Circuit Breaker
|
|
452
|
+
this.recentActionSignatures = [];
|
|
453
|
+
this.consecutiveReadOnlySteps = 0;
|
|
350
454
|
// Sovereign Progressive Disclosure: which capability packs have entered the
|
|
351
455
|
// context window for this task. Nothing is disabled — see src/toolPacks.js.
|
|
352
456
|
this.unlockedPacks = new Set();
|
|
@@ -378,16 +482,13 @@ export class AgentLoop {
|
|
|
378
482
|
// P6: rendered surfaces this task wrote, for the anti-slop gate to read back.
|
|
379
483
|
this.webArtifacts = new Set();
|
|
380
484
|
this.slopGateFired = false;
|
|
381
|
-
this.coldObserverGuardFired = false;
|
|
382
485
|
this.gameCascadeState = { active: true, currentStage: 1, stageHistory: [], verificationPassed: false };
|
|
383
486
|
this.gameToolStats = { godot_act: 0, game_asset_fetch: 0, game_build_html5: 0, last_godot_action: null };
|
|
384
487
|
this.webVerificationState = { screenshotTaken: false, browserActUsed: false }; // V8 Transcendence: Anti-Slop Guard
|
|
385
488
|
this.abortController = new AbortController();
|
|
386
489
|
// V5: Context compaction tracking
|
|
387
490
|
this._lastCompactionIndex = null;
|
|
388
|
-
|
|
389
|
-
// V5: Error recovery tracking (per tool call)
|
|
390
|
-
this._toolRetryCount = new Map();
|
|
491
|
+
this.timeMachine = new TimeMachine();
|
|
391
492
|
this.isInitialized = false;
|
|
392
493
|
this.taskTemperature = 0.1; // Default
|
|
393
494
|
// Set only on a delegated subagent loop; null means "the full catalogue".
|
|
@@ -397,6 +498,23 @@ export class AgentLoop {
|
|
|
397
498
|
isAlwaysAllowed(toolName) {
|
|
398
499
|
return this.approvalScope.isAlwaysAllowed(toolName);
|
|
399
500
|
}
|
|
501
|
+
/**
|
|
502
|
+
* Reset all standing tool approvals, allowlists, and autonomy overrides.
|
|
503
|
+
*
|
|
504
|
+
* Critical security invariant (Claude Code Architecture, p. 24):
|
|
505
|
+
* When a session is forked or reset, permissions and standing approvals
|
|
506
|
+
* must NEVER carry over into the new branch. A forked session starts with
|
|
507
|
+
* fresh, ungranted permissions so that user authorization must be re-verified.
|
|
508
|
+
*/
|
|
509
|
+
resetApprovalScope() {
|
|
510
|
+
if (this.approvalScope && typeof this.approvalScope.revokeAllAlways === 'function') {
|
|
511
|
+
this.approvalScope.revokeAllAlways();
|
|
512
|
+
}
|
|
513
|
+
this.approvalScope = createApprovalScope();
|
|
514
|
+
this.autonomyOverride = null;
|
|
515
|
+
this.circuitBreakerUnlocked = false;
|
|
516
|
+
this.pendingApprovals.clear();
|
|
517
|
+
}
|
|
400
518
|
// V6: Adaptive Temperature based on task intent
|
|
401
519
|
determineTemperature(prompt) {
|
|
402
520
|
if (!prompt)
|
|
@@ -454,7 +572,7 @@ export class AgentLoop {
|
|
|
454
572
|
// Anti-Slop: Design Context Awareness (what design system is already installed)
|
|
455
573
|
let designContext = '';
|
|
456
574
|
try {
|
|
457
|
-
const detectedDesign = await this.perception.detectDesignContext(
|
|
575
|
+
const detectedDesign = await this.perception.detectDesignContext(this.workspaceRoot);
|
|
458
576
|
if (detectedDesign && detectedDesign.length > 0) {
|
|
459
577
|
designContext = `\nDETECTED DESIGN SYSTEM IN WORKSPACE: ${detectedDesign.join(', ')} — USE THIS. Do NOT install a conflicting system.`;
|
|
460
578
|
}
|
|
@@ -476,7 +594,7 @@ export class AgentLoop {
|
|
|
476
594
|
// Universal skills awareness
|
|
477
595
|
let universalSkillsContext = '';
|
|
478
596
|
try {
|
|
479
|
-
const detectedDomains = detectWorkspaceDomains(
|
|
597
|
+
const detectedDomains = detectWorkspaceDomains(this.workspaceRoot);
|
|
480
598
|
if (detectedDomains.length > 0) {
|
|
481
599
|
this.debugLog(`detected workspace domains: ${detectedDomains.join(', ')}`);
|
|
482
600
|
for (const domain of detectedDomains) {
|
|
@@ -509,6 +627,27 @@ export class AgentLoop {
|
|
|
509
627
|
if (this.abortController) {
|
|
510
628
|
this.abortController.abort();
|
|
511
629
|
}
|
|
630
|
+
if (this.llm && typeof this.llm.abort === 'function') {
|
|
631
|
+
try {
|
|
632
|
+
this.llm.abort();
|
|
633
|
+
}
|
|
634
|
+
catch {
|
|
635
|
+
// ignore provider abort errors
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
else if (this.llm && typeof this.llm.close === 'function') {
|
|
639
|
+
try {
|
|
640
|
+
void this.llm.close();
|
|
641
|
+
}
|
|
642
|
+
catch {
|
|
643
|
+
// ignore provider close errors
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
if (this.pendingApprovals && this.pendingApprovals.size > 0) {
|
|
647
|
+
for (const toolCallId of [...this.pendingApprovals.keys()]) {
|
|
648
|
+
this.handleApprovalResponse(toolCallId, false);
|
|
649
|
+
}
|
|
650
|
+
}
|
|
512
651
|
}
|
|
513
652
|
setAutonomyMode(mode) {
|
|
514
653
|
const normalized = String(mode || '').trim().toUpperCase();
|
|
@@ -643,11 +782,11 @@ export class AgentLoop {
|
|
|
643
782
|
continue;
|
|
644
783
|
}
|
|
645
784
|
try {
|
|
646
|
-
resolve(await item.tool.execute(item.args, {
|
|
785
|
+
resolve(await withToolAutonomyMode(this.config.autonomyMode || 'C', () => item.tool.execute(item.args, {
|
|
647
786
|
signal: this.abortController.signal,
|
|
648
787
|
parentLoop: this,
|
|
649
788
|
...this.sandbox
|
|
650
|
-
}));
|
|
789
|
+
})));
|
|
651
790
|
}
|
|
652
791
|
catch (e) {
|
|
653
792
|
resolve(null); // let the serial path fail it, with its own retries
|
|
@@ -749,8 +888,11 @@ export class AgentLoop {
|
|
|
749
888
|
if (this.autonomyOverride)
|
|
750
889
|
this.config.autonomyMode = this.autonomyOverride;
|
|
751
890
|
if (typeof this.initializeProvider === 'function') {
|
|
752
|
-
|
|
753
|
-
|
|
891
|
+
const nextProvider = this.initializeProvider();
|
|
892
|
+
if (nextProvider) {
|
|
893
|
+
this.llm = nextProvider;
|
|
894
|
+
this._utilityLlm = null; // the route is derived from the model; re-derive it
|
|
895
|
+
}
|
|
754
896
|
}
|
|
755
897
|
if (this.tokenTracker) {
|
|
756
898
|
this.tokenTracker.config = this.config;
|
|
@@ -799,8 +941,10 @@ export class AgentLoop {
|
|
|
799
941
|
// awareness instead of burning steps rediscovering it. The result used to be
|
|
800
942
|
// assigned to a local variable and thrown away.
|
|
801
943
|
auditLog.log({ event: 'task_start', taskId: this.taskId, request: this.userPrompt });
|
|
802
|
-
|
|
944
|
+
// Preserve an explicit workspace selected by the caller (for example ACP).
|
|
945
|
+
// The constructor already defaults to process.cwd() when none was supplied.
|
|
803
946
|
coldObserver.beginTask(this.taskId);
|
|
947
|
+
this.timeMachine.reset();
|
|
804
948
|
this.emitEvent({ type: 'status', message: 'Analyzing workspace...' });
|
|
805
949
|
// P2: open the undo group for this task. This snapshots the CONVERSATION as
|
|
806
950
|
// well as the workspace tree, because restoring files while chat_history
|
|
@@ -832,18 +976,22 @@ export class AgentLoop {
|
|
|
832
976
|
// return $HOME or a system root, so the checkpoint covers the code being
|
|
833
977
|
// worked on or honestly covers nothing at all.
|
|
834
978
|
workspaceRoots: [
|
|
835
|
-
resolveProjectRoot(
|
|
836
|
-
|
|
979
|
+
resolveProjectRoot(this.workspaceRoot),
|
|
980
|
+
this.workspaceRoot,
|
|
837
981
|
...(this.sandbox.grantAllAccess ? [] : (this.sandbox.workspacePaths || []))
|
|
838
982
|
].filter(Boolean)
|
|
839
983
|
});
|
|
840
984
|
try {
|
|
841
|
-
this.workspaceContext = await this.perception.buildContext(
|
|
985
|
+
this.workspaceContext = await this.perception.buildContext(this.workspaceRoot);
|
|
842
986
|
}
|
|
843
987
|
catch (perceptionError) {
|
|
844
988
|
this.debugLog(`workspace scan failed: ${perceptionError.message}`);
|
|
845
989
|
this.workspaceContext = null;
|
|
846
990
|
}
|
|
991
|
+
if (this.stopRequested || this.abortController?.signal?.aborted) {
|
|
992
|
+
auditLog.log({ event: 'task_interrupted', taskId: this.taskId });
|
|
993
|
+
return;
|
|
994
|
+
}
|
|
847
995
|
// 2. ANALYSE TASK SHAPE & PRE-WARM CAPABILITY PACKS.
|
|
848
996
|
// A game request gets the full game toolset from step one with no discovery
|
|
849
997
|
// round trip, while a "rename my files" request never pays the 7,282 tokens
|
|
@@ -853,7 +1001,6 @@ export class AgentLoop {
|
|
|
853
1001
|
this.webGuardFired = false;
|
|
854
1002
|
this.webArtifacts = new Set();
|
|
855
1003
|
this.slopGateFired = false;
|
|
856
|
-
this.coldObserverGuardFired = false;
|
|
857
1004
|
this.staticContext = null;
|
|
858
1005
|
// Plan cache: the procedure THIS task follows, and the template (if any)
|
|
859
1006
|
// that was offered to it. Both reset per task — a plan is a property of one
|
|
@@ -869,7 +1016,9 @@ export class AgentLoop {
|
|
|
869
1016
|
this._decisionAnswers = new Map();
|
|
870
1017
|
this._decisionRequirement = assessDecisionRequirement(this.userPrompt || '');
|
|
871
1018
|
this._decisionResolved = !this._decisionRequirement.required;
|
|
872
|
-
this.
|
|
1019
|
+
this._taskStartedAt = performance.now();
|
|
1020
|
+
this._totalPlanMs = 0;
|
|
1021
|
+
this._totalActMs = 0;
|
|
873
1022
|
if (this.vfeTracker)
|
|
874
1023
|
this.vfeTracker.reset();
|
|
875
1024
|
if (this.userPrompt) {
|
|
@@ -887,6 +1036,8 @@ export class AgentLoop {
|
|
|
887
1036
|
const scored = packsFromShape(this.taskShape);
|
|
888
1037
|
const fallback = routePacks(this.userPrompt, this.workspaceContext);
|
|
889
1038
|
for (const pack of [...scored, ...fallback]) {
|
|
1039
|
+
if (pack === 'game' && isDirectGameTask(this.userPrompt))
|
|
1040
|
+
continue;
|
|
890
1041
|
this.unlockPack(pack);
|
|
891
1042
|
}
|
|
892
1043
|
// Reuse a known route before the first model call. Exact keyword-set
|
|
@@ -940,7 +1091,7 @@ export class AgentLoop {
|
|
|
940
1091
|
try {
|
|
941
1092
|
const subprojects = this.workspaceContext?.subprojects || [];
|
|
942
1093
|
const mentionResult = await resolveMentionedContext(this.userPrompt, {
|
|
943
|
-
cwd:
|
|
1094
|
+
cwd: this.workspaceRoot,
|
|
944
1095
|
subprojects
|
|
945
1096
|
});
|
|
946
1097
|
if (mentionResult.detectedSubproject) {
|
|
@@ -948,12 +1099,14 @@ export class AgentLoop {
|
|
|
948
1099
|
this.notice(`Focused on subproject '${mentionResult.detectedSubproject}'`);
|
|
949
1100
|
}
|
|
950
1101
|
else if (subprojects.length > 0) {
|
|
951
|
-
const lowerPrompt = this.userPrompt.toLowerCase();
|
|
952
1102
|
for (const sp of subprojects) {
|
|
953
|
-
if (
|
|
954
|
-
|
|
955
|
-
this.
|
|
956
|
-
|
|
1103
|
+
if (sp.length >= 2) {
|
|
1104
|
+
const boundaryRegex = new RegExp(`(?:^|\\s|["'\`(@/\\\\])${sp.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\$&')}(?:$|\\s|["'\`):,/\\\\])`, 'i');
|
|
1105
|
+
if (boundaryRegex.test(this.userPrompt)) {
|
|
1106
|
+
this.activeSubproject = sp;
|
|
1107
|
+
this.notice(`Focused on subproject '${sp}'`);
|
|
1108
|
+
break;
|
|
1109
|
+
}
|
|
957
1110
|
}
|
|
958
1111
|
}
|
|
959
1112
|
}
|
|
@@ -1046,7 +1199,7 @@ export class AgentLoop {
|
|
|
1046
1199
|
const path = await import('path');
|
|
1047
1200
|
// Ensure unique name to prevent overwriting
|
|
1048
1201
|
const safeName = att.name.replace(/[^a-zA-Z0-9.\-_]/g, '_');
|
|
1049
|
-
const writePath = path.join(
|
|
1202
|
+
const writePath = path.join(this.workspaceRoot, safeName);
|
|
1050
1203
|
fs.writeFileSync(writePath, Buffer.from(att.base64, 'base64'));
|
|
1051
1204
|
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
1205
|
this.notice(`saved attached document to ${writePath}`);
|
|
@@ -1055,7 +1208,13 @@ export class AgentLoop {
|
|
|
1055
1208
|
this.messages.push({ role: 'user', content: contentArray });
|
|
1056
1209
|
}
|
|
1057
1210
|
else {
|
|
1058
|
-
this.messages.
|
|
1211
|
+
const lastMsg = this.messages[this.messages.length - 1];
|
|
1212
|
+
if (lastMsg && lastMsg.role === 'user' && typeof lastMsg.content === 'string' && lastMsg.content.trim() === this.userPrompt.trim()) {
|
|
1213
|
+
lastMsg.content = this.userPrompt;
|
|
1214
|
+
}
|
|
1215
|
+
else {
|
|
1216
|
+
this.messages.push({ role: 'user', content: this.userPrompt });
|
|
1217
|
+
}
|
|
1059
1218
|
}
|
|
1060
1219
|
this.userPrompt = null; // Clear so we don't push it again
|
|
1061
1220
|
this.attachments = null; // Clear attachments
|
|
@@ -1066,6 +1225,8 @@ export class AgentLoop {
|
|
|
1066
1225
|
this._observationDigests = new Map();
|
|
1067
1226
|
this.consecutiveCommands = 0;
|
|
1068
1227
|
this.circuitBreakerUnlocked = false;
|
|
1228
|
+
this.recentActionSignatures = [];
|
|
1229
|
+
this.consecutiveReadOnlySteps = 0;
|
|
1069
1230
|
this.tokenTracker.resetTask();
|
|
1070
1231
|
// The core loop governed by Sovereign Human-in-the-Loop Checkpoints
|
|
1071
1232
|
while (!this.stopRequested) {
|
|
@@ -1174,7 +1335,7 @@ export class AgentLoop {
|
|
|
1174
1335
|
const autonomyMode = this.config.autonomyMode || 'C';
|
|
1175
1336
|
const allowedPaths = this.sandbox.grantAllAccess
|
|
1176
1337
|
? "/ (ALL ACCESS GRANTED - You can read/write anywhere EXCEPT system protected folders like /etc or /System)"
|
|
1177
|
-
: (this.sandbox.workspacePaths ? this.sandbox.workspacePaths.join(', ') :
|
|
1338
|
+
: (this.sandbox.workspacePaths ? this.sandbox.workspacePaths.join(', ') : this.workspaceRoot);
|
|
1178
1339
|
const providerPrompt = getProviderSpecificPrompt(this.config.provider);
|
|
1179
1340
|
const memoryContext = getMemoryContextString();
|
|
1180
1341
|
// --- PER-TASK STATIC CONTEXT (computed once, not once per step) ---
|
|
@@ -1377,11 +1538,18 @@ export class AgentLoop {
|
|
|
1377
1538
|
// 2. PLAN (Call LLM). dynamicTools was resolved above so the task brief
|
|
1378
1539
|
// could reference the tools actually in context.
|
|
1379
1540
|
let hasStreamedChunk = false;
|
|
1541
|
+
const streamingCode = new StreamingCodePreview();
|
|
1542
|
+
const nativeCodeObserver = new NativeCodeObserver(this.workspaceRoot, event => this.emitEvent(event));
|
|
1380
1543
|
let reasoningAccumulated = '';
|
|
1381
1544
|
let thoughtStartedAt = 0;
|
|
1382
1545
|
this.emitEvent({ type: 'status', message: 'Thinking…' });
|
|
1383
1546
|
this.emitEvent({ type: 'agent_activity', activity: 'Thinking…' });
|
|
1547
|
+
const planStepStart = performance.now();
|
|
1384
1548
|
const response = await this.llm.chat(prunedMessages, {
|
|
1549
|
+
taskId: this.taskId,
|
|
1550
|
+
conversationId: this.memoryManager?.sessionId || this.taskId,
|
|
1551
|
+
taskIntent: isLaunchOnlyPrompt(this.currentTaskPrompt || this.userPrompt || '') ? 'launch' : 'general',
|
|
1552
|
+
workspaceRoot: this.workspaceRoot,
|
|
1385
1553
|
tools: dynamicTools,
|
|
1386
1554
|
// IARS couples escalation to a wider search. Bounded so a stuck task
|
|
1387
1555
|
// cannot climb into randomness across repeated escalations.
|
|
@@ -1389,6 +1557,8 @@ export class AgentLoop {
|
|
|
1389
1557
|
coreToolCount: dynamicTools.filter((t) => isCoreTool(t.name)).length,
|
|
1390
1558
|
signal: this.abortController?.signal,
|
|
1391
1559
|
onReasoningChunk: (chunk) => {
|
|
1560
|
+
if (this.stopRequested || this.abortController?.signal?.aborted)
|
|
1561
|
+
return;
|
|
1392
1562
|
if (!thoughtStartedAt)
|
|
1393
1563
|
thoughtStartedAt = Date.now();
|
|
1394
1564
|
reasoningAccumulated += chunk;
|
|
@@ -1401,13 +1571,49 @@ export class AgentLoop {
|
|
|
1401
1571
|
});
|
|
1402
1572
|
},
|
|
1403
1573
|
onChunk: (_chunk) => {
|
|
1574
|
+
if (this.stopRequested || this.abortController?.signal?.aborted)
|
|
1575
|
+
return;
|
|
1404
1576
|
if (!hasStreamedChunk) {
|
|
1405
1577
|
hasStreamedChunk = true;
|
|
1406
1578
|
this.emitEvent({ type: 'status', message: 'Responding…' });
|
|
1407
1579
|
this.emitEvent({ type: 'agent_activity', activity: 'Responding…' });
|
|
1408
1580
|
}
|
|
1581
|
+
const preview = streamingCode.accept(_chunk);
|
|
1582
|
+
if (preview)
|
|
1583
|
+
this.emitEvent(preview);
|
|
1584
|
+
},
|
|
1585
|
+
onNativeAction: (action) => {
|
|
1586
|
+
if (this.stopRequested || this.abortController?.signal?.aborted)
|
|
1587
|
+
return;
|
|
1588
|
+
if (!action || typeof action.name !== 'string')
|
|
1589
|
+
return;
|
|
1590
|
+
const nativeCode = codeProgressFromAction(action.name, { ...(action.parameters && typeof action.parameters === 'object' ? action.parameters : {}),
|
|
1591
|
+
path: action.parameters?.path || action.parameters?.Path || action.detail || '' }, `provider:${action.name}:${action.detail || ''}`, action.status === 'completed' ? 'done' : action.status === 'failed' ? 'failed' : 'working', 'provider');
|
|
1592
|
+
if (nativeCode) {
|
|
1593
|
+
this.emitEvent(nativeCode);
|
|
1594
|
+
nativeCodeObserver.handle(nativeCode);
|
|
1595
|
+
}
|
|
1596
|
+
const detail = action.detail ? ` ${action.detail}` : '';
|
|
1597
|
+
if (action.status === 'running') {
|
|
1598
|
+
this.emitEvent({ type: 'status', message: `Acting: ${action.name}${detail}` });
|
|
1599
|
+
this.emitEvent({ type: 'agent_activity', activity: `Acting: ${action.name}${detail}` });
|
|
1600
|
+
}
|
|
1601
|
+
else if (action.status === 'completed') {
|
|
1602
|
+
this.emitEvent({ type: 'notice', tone: 'muted', nativeStep: true, message: `Antigravity ${action.name}${detail}` });
|
|
1603
|
+
}
|
|
1604
|
+
else if (action.status === 'failed') {
|
|
1605
|
+
this.emitEvent({ type: 'warning', message: `Antigravity could not ${action.name}${detail}` });
|
|
1606
|
+
}
|
|
1409
1607
|
}
|
|
1410
|
-
});
|
|
1608
|
+
}).finally(() => nativeCodeObserver.dispose());
|
|
1609
|
+
this._totalPlanMs = (this._totalPlanMs || 0) + (performance.now() - planStepStart);
|
|
1610
|
+
if (this.stopRequested || this.abortController?.signal?.aborted) {
|
|
1611
|
+
auditLog.log({ event: 'task_interrupted', taskId: this.taskId });
|
|
1612
|
+
break;
|
|
1613
|
+
}
|
|
1614
|
+
const finalCodePreview = streamingCode.flush();
|
|
1615
|
+
if (finalCodePreview)
|
|
1616
|
+
this.emitEvent(finalCodePreview);
|
|
1411
1617
|
// The call came back. Whatever went wrong before is no longer
|
|
1412
1618
|
// consecutive — without this reset, one failure at step 2 and another
|
|
1413
1619
|
// at step 200 would count toward the same ceiling and stop a task that
|
|
@@ -1487,16 +1693,92 @@ export class AgentLoop {
|
|
|
1487
1693
|
assistantMsg.thinking_blocks = response.thinkingBlocks;
|
|
1488
1694
|
}
|
|
1489
1695
|
this.messages.push(assistantMsg);
|
|
1490
|
-
if (response.content) {
|
|
1696
|
+
if (response.content && hasToolCalls) {
|
|
1491
1697
|
this.emitEvent({ type: 'agent_message', content: response.content });
|
|
1492
1698
|
}
|
|
1699
|
+
const externalActions = Array.isArray(response.externalActions)
|
|
1700
|
+
? response.externalActions
|
|
1701
|
+
: [];
|
|
1702
|
+
const completedExternalActions = externalActions.filter((a) => a && a.status === 'completed');
|
|
1703
|
+
const failedExternalActions = externalActions.filter((a) => a && a.status === 'failed');
|
|
1704
|
+
const hasExternalActions = completedExternalActions.length > 0;
|
|
1705
|
+
const isIncompleteTurn = Boolean(response.incompleteTurn);
|
|
1706
|
+
if (hasExternalActions) {
|
|
1707
|
+
this.stepsCompleted += completedExternalActions.length;
|
|
1708
|
+
for (const extAction of completedExternalActions) {
|
|
1709
|
+
const actionName = String(extAction.name || '').toLowerCase();
|
|
1710
|
+
const detailPath = typeof extAction.detail === 'string' ? extAction.detail.trim() : '';
|
|
1711
|
+
if (['write_file', 'write_to_file', 'edit_file', 'replace_file_content', 'multi_replace_file_content', 'fs_write', 'fs_edit', 'multiedit'].includes(actionName) && detailPath) {
|
|
1712
|
+
const resolvedPath = path.isAbsolute(detailPath)
|
|
1713
|
+
? detailPath
|
|
1714
|
+
: path.resolve(this.workspaceRoot, detailPath.replace(/^~\//, os.homedir() + '/'));
|
|
1715
|
+
if (isScannableFile(resolvedPath)) {
|
|
1716
|
+
this.webArtifacts.add(resolvedPath);
|
|
1717
|
+
}
|
|
1718
|
+
}
|
|
1719
|
+
if (['capture_browser_screenshot', 'browser_subagent', 'open_browser_url', 'browser_get_dom', 'read_browser_page'].includes(actionName) ||
|
|
1720
|
+
((actionName === 'read_file' || actionName === 'view_file') && /\.(png|jpe?g|webp|gif|svg)$/i.test(detailPath))) {
|
|
1721
|
+
this.webVerificationState.screenshotTaken = true;
|
|
1722
|
+
}
|
|
1723
|
+
}
|
|
1724
|
+
}
|
|
1493
1725
|
// If no tool calls, check if the agent is just thinking/planning or actually done
|
|
1494
1726
|
if (!response.toolCalls || response.toolCalls.length === 0) {
|
|
1495
1727
|
const contentText = response.content || '';
|
|
1496
1728
|
const lower = contentText.toLowerCase();
|
|
1497
|
-
const
|
|
1498
|
-
const
|
|
1499
|
-
|
|
1729
|
+
const taskPrompt = (this.currentTaskPrompt || this.userPrompt || '').trim();
|
|
1730
|
+
const isActionable = isActionableTaskPrompt(taskPrompt);
|
|
1731
|
+
// A native workspace action already changed the workspace. Do not
|
|
1732
|
+
// demand a Causyne tool call for the same work, and do not treat the
|
|
1733
|
+
// turn as a no-op.
|
|
1734
|
+
if (!hasExternalActions && failedExternalActions.length > 0 && this.consecutiveThinkingSteps < 2) {
|
|
1735
|
+
this.consecutiveThinkingSteps++;
|
|
1736
|
+
const blocked = failedExternalActions
|
|
1737
|
+
.map((a) => `${a.name}${a.detail ? ` (${a.detail})` : ''}`)
|
|
1738
|
+
.join(', ');
|
|
1739
|
+
this.emitEvent({ type: 'status', message: 'Native action blocked; switching to Causyne tools...' });
|
|
1740
|
+
this.emitEvent({ type: 'agent_activity', activity: 'Retrying blocked action through Causyne…' });
|
|
1741
|
+
this.messages.push({
|
|
1742
|
+
role: 'system',
|
|
1743
|
+
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>.]`
|
|
1744
|
+
});
|
|
1745
|
+
this.memoryManager.saveHistory(this.messages);
|
|
1746
|
+
continue;
|
|
1747
|
+
}
|
|
1748
|
+
const isQuestionOrGreeting = lower.includes('?') ||
|
|
1749
|
+
lower.includes('let me know') ||
|
|
1750
|
+
lower.includes('how can i help') ||
|
|
1751
|
+
lower.includes('how may i help') ||
|
|
1752
|
+
lower.includes('how can i assist') ||
|
|
1753
|
+
lower.includes('what would you like') ||
|
|
1754
|
+
lower.includes('what can i help') ||
|
|
1755
|
+
lower.includes('feel free to');
|
|
1756
|
+
// Action Enforcement on Step 0:
|
|
1757
|
+
// If the user instructed an actionable task (e.g. "create a 3js game..."), but the model
|
|
1758
|
+
// replied with a greeting, polite pleasantry, question, or refusal without calling any tools:
|
|
1759
|
+
if (!hasExternalActions && this.stepsCompleted === 0 && isActionable && (isQuestionOrGreeting || lower.includes('hello') || lower.includes('hi '))) {
|
|
1760
|
+
this.messages.pop();
|
|
1761
|
+
if (this.consecutiveThinkingSteps >= 2) {
|
|
1762
|
+
this.emitEvent({ type: 'error', message: 'The selected model did not follow the task after three attempts. No work was completed.' });
|
|
1763
|
+
this.memoryManager.saveHistory(this.messages);
|
|
1764
|
+
break;
|
|
1765
|
+
}
|
|
1766
|
+
this.consecutiveThinkingSteps++;
|
|
1767
|
+
this.emitEvent({ type: 'status', message: 'Enforcing task execution: rejecting greeting on actionable instruction...' });
|
|
1768
|
+
this.emitEvent({ type: 'agent_activity', activity: 'Enforcing tool execution…' });
|
|
1769
|
+
this.messages.push({
|
|
1770
|
+
role: 'system',
|
|
1771
|
+
content: isLaunchOnlyPrompt(taskPrompt)
|
|
1772
|
+
? `[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.]`
|
|
1773
|
+
: `[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.]`
|
|
1774
|
+
});
|
|
1775
|
+
this.memoryManager.saveHistory(this.messages);
|
|
1776
|
+
continue;
|
|
1777
|
+
}
|
|
1778
|
+
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'];
|
|
1779
|
+
const isMidTaskProgress = !isQuestionOrGreeting && isMidTaskProgressText(contentText);
|
|
1780
|
+
const isThinking = !isQuestionOrGreeting && (isMidTaskProgress || thinkingKeywords.some(kw => lower.includes(kw)));
|
|
1781
|
+
if (!hasExternalActions && (isThinking || isIncompleteTurn) && this.consecutiveThinkingSteps < 3) {
|
|
1500
1782
|
this.consecutiveThinkingSteps++;
|
|
1501
1783
|
this.emitEvent({ type: 'status', message: 'Agent planning next steps...' });
|
|
1502
1784
|
this.emitEvent({ type: 'agent_activity', activity: 'Planning next actionable steps…' });
|
|
@@ -1504,24 +1786,51 @@ export class AgentLoop {
|
|
|
1504
1786
|
// duplicated the whole turn in history on every nudge.
|
|
1505
1787
|
this.messages.push({
|
|
1506
1788
|
role: 'system',
|
|
1507
|
-
content:
|
|
1789
|
+
content: isIncompleteTurn
|
|
1790
|
+
? '[SYSTEM NOTICE: Your previous turn ended before completion. Continue immediately from where you left off and invoke the next appropriate tool to complete the task.]'
|
|
1791
|
+
: '[SYSTEM NOTICE: You provided reasoning/planning without calling any tools. Please invoke the next appropriate tool now to continue progressing on the task.]'
|
|
1792
|
+
});
|
|
1793
|
+
this.memoryManager.saveHistory(this.messages);
|
|
1794
|
+
continue;
|
|
1795
|
+
}
|
|
1796
|
+
if (hasExternalActions && (isIncompleteTurn || isMidTaskProgress) && this.consecutiveThinkingSteps < 3) {
|
|
1797
|
+
this.consecutiveThinkingSteps++;
|
|
1798
|
+
if (response.content) {
|
|
1799
|
+
this.emitEvent({ type: 'agent_message', content: response.content });
|
|
1800
|
+
}
|
|
1801
|
+
this.emitEvent({ type: 'status', message: 'Continuing task execution...' });
|
|
1802
|
+
this.emitEvent({ type: 'agent_activity', activity: 'Continuing mid-task execution…' });
|
|
1803
|
+
this.messages.push({
|
|
1804
|
+
role: 'system',
|
|
1805
|
+
content: isIncompleteTurn
|
|
1806
|
+
? '[SYSTEM NOTICE: Your previous turn ended while the task was still in progress. Continue immediately from where you left off and execute the remaining steps to complete the task.]'
|
|
1807
|
+
: '[SYSTEM NOTICE: You announced the next step without executing it. Continue immediately from where you left off and execute the remaining file edits or tool calls to complete the task.]'
|
|
1508
1808
|
});
|
|
1509
1809
|
this.memoryManager.saveHistory(this.messages);
|
|
1510
1810
|
continue;
|
|
1511
1811
|
}
|
|
1512
|
-
if (
|
|
1513
|
-
|
|
1812
|
+
if (hasExternalActions) {
|
|
1813
|
+
this.consecutiveThinkingSteps = 0;
|
|
1814
|
+
}
|
|
1815
|
+
if (!hasExternalActions && this.stepsCompleted === 0 && this.consecutiveThinkingSteps < 2) {
|
|
1816
|
+
if (isActionable || lower.includes('turn completed') || lower.includes('no output produced') || !contentText.trim()) {
|
|
1514
1817
|
this.consecutiveThinkingSteps++;
|
|
1515
1818
|
this.emitEvent({ type: 'status', message: 'Nudging agent to execute actionable steps...' });
|
|
1516
1819
|
this.emitEvent({ type: 'agent_activity', activity: 'Nudging agent to invoke tools…' });
|
|
1517
1820
|
this.messages.push({
|
|
1518
1821
|
role: 'system',
|
|
1519
|
-
content:
|
|
1822
|
+
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
1823
|
});
|
|
1521
1824
|
this.memoryManager.saveHistory(this.messages);
|
|
1522
1825
|
continue;
|
|
1523
1826
|
}
|
|
1524
1827
|
}
|
|
1828
|
+
if (!hasExternalActions && this.stepsCompleted === 0 && isActionable) {
|
|
1829
|
+
this.messages.pop();
|
|
1830
|
+
this.emitEvent({ type: 'error', message: 'The selected model returned text without taking any action. No work was completed.' });
|
|
1831
|
+
this.memoryManager.saveHistory(this.messages);
|
|
1832
|
+
break;
|
|
1833
|
+
}
|
|
1525
1834
|
// --- COMPLETION GUARDS ---
|
|
1526
1835
|
// Two hard rules learned the expensive way:
|
|
1527
1836
|
// 1. Match on word boundaries. Substring matching made 'ui' fire on
|
|
@@ -1531,24 +1840,20 @@ export class AgentLoop {
|
|
|
1531
1840
|
// consecutiveThinkingSteps, which resets on every tool call, so
|
|
1532
1841
|
// a guard could block completion indefinitely and burn the whole
|
|
1533
1842
|
// step budget on an already-finished task.
|
|
1534
|
-
|
|
1535
|
-
|
|
1843
|
+
if (response.content) {
|
|
1844
|
+
this.emitEvent({ type: 'agent_message', content: response.content });
|
|
1845
|
+
}
|
|
1846
|
+
const isGameTask = !isLaunchOnlyPrompt(taskPrompt) && isGameIntent(taskPrompt);
|
|
1536
1847
|
this.gameToolStats = this.gameToolStats || { godot_act: 0, game_asset_fetch: 0, game_build_html5: 0, last_godot_action: null };
|
|
1537
1848
|
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".
|
|
1849
|
+
// Production-depth enforcement is opt-in for full production tasks.
|
|
1542
1850
|
const needsDepth = this.config.enforceGameDepth === true && this.stepsCompleted < 50;
|
|
1543
|
-
if (
|
|
1851
|
+
if (needsDepth) {
|
|
1544
1852
|
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.]`;
|
|
1853
|
+
this.emitEvent({ type: 'status', message: '⚡ Sovereign Game Guard: Checking production depth...' });
|
|
1854
|
+
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
1855
|
this.messages.push({ role: 'system', content: guardMsg });
|
|
1550
1856
|
this.memoryManager.saveHistory(this.messages);
|
|
1551
|
-
continue;
|
|
1552
1857
|
}
|
|
1553
1858
|
}
|
|
1554
1859
|
// P6 — ANTI-SLOP GATE (Vision §7, ENFORCED)
|
|
@@ -1574,13 +1879,12 @@ export class AgentLoop {
|
|
|
1574
1879
|
const recent = Array.isArray(this.staticContext?.recentMovements) ? this.staticContext.recentMovements : [];
|
|
1575
1880
|
const brief = formatMovementBrief(suggestMovements(recent, 3));
|
|
1576
1881
|
auditLog.log({
|
|
1577
|
-
event: '
|
|
1882
|
+
event: 'anti_slop_notice', taskId: this.taskId,
|
|
1578
1883
|
score: result.score, signals: result.findings.map((f) => f.id)
|
|
1579
1884
|
});
|
|
1580
|
-
this.emitEvent({ type: 'status', message: `⚡ Anti-Slop
|
|
1885
|
+
this.emitEvent({ type: 'status', message: `⚡ Anti-Slop Audit: design scored ${result.score}` });
|
|
1581
1886
|
this.messages.push({ role: 'system', content: formatFindings(result, brief) });
|
|
1582
1887
|
this.memoryManager.saveHistory(this.messages);
|
|
1583
|
-
continue;
|
|
1584
1888
|
}
|
|
1585
1889
|
if (result.findings.length > 0) {
|
|
1586
1890
|
auditLog.log({
|
|
@@ -1596,7 +1900,7 @@ export class AgentLoop {
|
|
|
1596
1900
|
}
|
|
1597
1901
|
}
|
|
1598
1902
|
// Web Visual Validation Guard (Anti-Slop / Transcendence)
|
|
1599
|
-
const isWebTask = isWebIntent(taskPrompt);
|
|
1903
|
+
const isWebTask = !isLaunchOnlyPrompt(taskPrompt) && isWebIntent(taskPrompt);
|
|
1600
1904
|
if (isWebTask && !this.webGuardFired && this.stepsCompleted > 0) {
|
|
1601
1905
|
const hasVision = this.llm.supportsVision !== false;
|
|
1602
1906
|
// Finding D-6: this guard used to demand `screenshot` /
|
|
@@ -1635,14 +1939,16 @@ export class AgentLoop {
|
|
|
1635
1939
|
// The verification tools live in the web pack; make sure they are
|
|
1636
1940
|
// actually in context before demanding the agent use them.
|
|
1637
1941
|
this.unlockPack('web');
|
|
1638
|
-
this.emitEvent({ type: 'status', message: '⚡ Anti-Slop
|
|
1942
|
+
this.emitEvent({ type: 'status', message: '⚡ Anti-Slop Check: Visual/semantic verification recommended.' });
|
|
1639
1943
|
this.messages.push({ role: 'system', content: webGuardMsg });
|
|
1640
1944
|
this.memoryManager.saveHistory(this.messages);
|
|
1641
|
-
|
|
1945
|
+
if (browserReady || (hasVision && visionReady)) {
|
|
1946
|
+
continue;
|
|
1947
|
+
}
|
|
1642
1948
|
}
|
|
1643
1949
|
}
|
|
1644
1950
|
// Cold Observer: Overconfidence & Loop Verification Check
|
|
1645
|
-
|
|
1951
|
+
{
|
|
1646
1952
|
try {
|
|
1647
1953
|
const coldAudit = await coldObserver.auditTurnVerification({
|
|
1648
1954
|
taskId: this.taskId,
|
|
@@ -1652,11 +1958,18 @@ export class AgentLoop {
|
|
|
1652
1958
|
stepsCompleted: this.stepsCompleted
|
|
1653
1959
|
});
|
|
1654
1960
|
if (coldAudit.overconfident) {
|
|
1655
|
-
this.
|
|
1961
|
+
const recovery = this.timeMachine.observe('observer_verification', {}, {
|
|
1962
|
+
success: false, error: coldAudit.discrepancy
|
|
1963
|
+
}, coldObserver.getToolOutcomes(this.taskId));
|
|
1656
1964
|
this.emitEvent({ type: 'status', message: `Cold Observer: ${coldAudit.discrepancy}` });
|
|
1965
|
+
if (recovery.kind === 'stop') {
|
|
1966
|
+
this.stopRequested = true;
|
|
1967
|
+
this.emitEvent({ type: 'error', message: recoveryUserMessage(recovery, 'Verification') });
|
|
1968
|
+
break;
|
|
1969
|
+
}
|
|
1657
1970
|
this.messages.push({
|
|
1658
1971
|
role: 'system',
|
|
1659
|
-
content: coldAudit.coldDirective
|
|
1972
|
+
content: `${coldAudit.coldDirective} ${recovery.guidance}`
|
|
1660
1973
|
});
|
|
1661
1974
|
this.memoryManager.saveHistory(this.messages);
|
|
1662
1975
|
continue;
|
|
@@ -1673,13 +1986,21 @@ export class AgentLoop {
|
|
|
1673
1986
|
// run, so asking a model to summarise it would be paying for a worse
|
|
1674
1987
|
// copy of a fact we hold.
|
|
1675
1988
|
try {
|
|
1676
|
-
const
|
|
1989
|
+
const planPayload = {
|
|
1677
1990
|
prompt: this.currentTaskPrompt || this.userPrompt,
|
|
1678
1991
|
archetype: this.taskShape ? this.taskShape.archetype : '',
|
|
1679
1992
|
steps: this._planSteps || []
|
|
1993
|
+
};
|
|
1994
|
+
recordPlanAsync(planPayload).then((stored) => {
|
|
1995
|
+
if (stored)
|
|
1996
|
+
this.debugLog(`plan cached asynchronously: ${stored.steps.length} steps, ${stored.wins}/${stored.uses} wins`);
|
|
1997
|
+
}).catch(() => { });
|
|
1998
|
+
recordAPCPipelineLatency({
|
|
1999
|
+
planMs: this._totalPlanMs || 0,
|
|
2000
|
+
actMs: this._totalActMs || 0,
|
|
2001
|
+
cacheLookupMs: this._planMatch?.telemetry?.lookupMs || 0,
|
|
2002
|
+
totalMs: performance.now() - (this._taskStartedAt || performance.now())
|
|
1680
2003
|
});
|
|
1681
|
-
if (stored)
|
|
1682
|
-
this.debugLog(`plan cached: ${stored.steps.length} steps, ${stored.wins}/${stored.uses} wins`);
|
|
1683
2004
|
}
|
|
1684
2005
|
catch (e) {
|
|
1685
2006
|
this.debugLog(`plan cache write skipped: ${e.message}`);
|
|
@@ -1696,9 +2017,8 @@ export class AgentLoop {
|
|
|
1696
2017
|
// them strictly one after another, so six `fs_read`s cost six full
|
|
1697
2018
|
// round trips of tool latency.
|
|
1698
2019
|
//
|
|
1699
|
-
// The serial loop below
|
|
1700
|
-
//
|
|
1701
|
-
// error classification changes — the only difference is that a
|
|
2020
|
+
// The serial loop below preserves ordering and approval gates. The
|
|
2021
|
+
// only difference from prefetching is that a
|
|
1702
2022
|
// read-only result may already be sitting in this map by the time the
|
|
1703
2023
|
// loop reaches it. Restructuring the 400-line body into a batch would
|
|
1704
2024
|
// have been the obvious approach and a far worse one: it is dense with
|
|
@@ -1712,11 +2032,12 @@ export class AgentLoop {
|
|
|
1712
2032
|
// * The sandbox is consulted FIRST, with the same call the serial path
|
|
1713
2033
|
// makes, so a denied path is never read behind the guard's back.
|
|
1714
2034
|
// * 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.
|
|
2035
|
+
// the serial path executes normally, so TimeMachine sees its outcome.
|
|
1717
2036
|
const prefetched = this.prefetchReadOnlyCalls(response.toolCalls);
|
|
1718
2037
|
// 3. ACT (Execute tool calls)
|
|
1719
2038
|
for (const toolCall of response.toolCalls) {
|
|
2039
|
+
if (this.stopRequested || this.abortController?.signal?.aborted)
|
|
2040
|
+
break;
|
|
1720
2041
|
// Canonicalise once, here. Every downstream comparison — the sandbox's
|
|
1721
2042
|
// risk classification, the approval gates, the game cascade lists —
|
|
1722
2043
|
// matches on this string, so if it is not the catalogue name those
|
|
@@ -1747,16 +2068,116 @@ export class AgentLoop {
|
|
|
1747
2068
|
if (repair.repaired && repair.repairs.length > 0) {
|
|
1748
2069
|
this.debugLog(`[TOOL SELF-REPAIR] Healed tool call '${functionName}': ${repair.repairs.join(', ')}`);
|
|
1749
2070
|
}
|
|
1750
|
-
this.
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
2071
|
+
if (isLaunchOnlyPrompt(this.currentTaskPrompt || this.userPrompt || '')) {
|
|
2072
|
+
const scopeError = launchScopeError(functionName, args || {});
|
|
2073
|
+
if (scopeError) {
|
|
2074
|
+
this.emitEvent({ type: 'step_error', tool: functionName, error: scopeError, toolCallId: toolCall.id });
|
|
2075
|
+
this.messages.push({ role: 'tool', tool_call_id: toolCall.id, name: functionName,
|
|
2076
|
+
content: JSON.stringify({ success: false, error: scopeError }) });
|
|
2077
|
+
continue;
|
|
2078
|
+
}
|
|
2079
|
+
if (args && ['sysRun', 'sysRunBg', 'terminal_persistent_shell'].includes(functionName) && !args.cwd) {
|
|
2080
|
+
args.cwd = this.workspaceRoot;
|
|
2081
|
+
}
|
|
1754
2082
|
}
|
|
1755
|
-
|
|
1756
|
-
|
|
2083
|
+
// Universal Repetition & Infinite Loop Circuit Breakers (Token Hemorrhage Guard)
|
|
2084
|
+
if (!Array.isArray(this.recentActionSignatures)) {
|
|
2085
|
+
this.recentActionSignatures = [];
|
|
2086
|
+
}
|
|
2087
|
+
let actionSig = `${functionName}:${JSON.stringify(args || {})}`;
|
|
2088
|
+
if (functionName === 'sysRun' || functionName === 'sysRunBg') {
|
|
2089
|
+
const rawCmd = String(args?.command || '').trim();
|
|
2090
|
+
if (/python[0-9.]*\s+.*import\s+numpy/i.test(rawCmd)) {
|
|
2091
|
+
actionSig = 'sysRun:probe:numpy';
|
|
2092
|
+
}
|
|
2093
|
+
else if (/python[0-9.]*\s+(--version|-V|-c\s+['"]print)/i.test(rawCmd)) {
|
|
2094
|
+
actionSig = 'sysRun:probe:python';
|
|
2095
|
+
}
|
|
2096
|
+
else if (/node\s+(--version|-v)/i.test(rawCmd)) {
|
|
2097
|
+
actionSig = 'sysRun:probe:node';
|
|
2098
|
+
}
|
|
2099
|
+
else if (/(?:ps\s+aux|pgrep|lsof|netstat|ss\s+-)/i.test(rawCmd)) {
|
|
2100
|
+
actionSig = 'sysRun:probe:process_or_port';
|
|
2101
|
+
}
|
|
2102
|
+
else {
|
|
2103
|
+
actionSig = `${functionName}:${rawCmd.replace(/\s+/g, ' ')}`;
|
|
2104
|
+
}
|
|
2105
|
+
}
|
|
2106
|
+
// Always record action signature into recent history FIRST
|
|
2107
|
+
this.recentActionSignatures.push(actionSig);
|
|
2108
|
+
if (this.recentActionSignatures.length > 20) {
|
|
2109
|
+
this.recentActionSignatures.shift();
|
|
2110
|
+
}
|
|
2111
|
+
const isCommandTool = ['sysRun', 'sysRunBg', 'terminal_persistent_shell'].includes(functionName);
|
|
2112
|
+
if (isCommandTool) {
|
|
2113
|
+
const duplicateCount = this.recentActionSignatures.filter((sig) => sig === actionSig).length;
|
|
2114
|
+
// 1. Hard Circuit Breaker on Duplicate Command Thrashing (same command attempted 4 times total)
|
|
2115
|
+
if (duplicateCount >= 4) {
|
|
2116
|
+
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.`;
|
|
2117
|
+
this.emitEvent({ type: 'step_error', tool: functionName, error: fatalMsg, toolCallId: toolCall.id });
|
|
2118
|
+
auditLog.log({ event: 'task_killed_circuit_breaker', taskId: this.taskId, reason: fatalMsg });
|
|
2119
|
+
this.abort();
|
|
2120
|
+
break;
|
|
2121
|
+
}
|
|
2122
|
+
// 2. Block 3rd attempt of identical command and inject a non-negotiable recovery mandate
|
|
2123
|
+
if (duplicateCount === 3) {
|
|
2124
|
+
const isExec = isExecutionOrLaunchTaskPrompt(this.currentTaskPrompt || this.userPrompt || '');
|
|
2125
|
+
const isAuthoring = !isExec && isCodeAuthoringTaskPrompt(this.currentTaskPrompt || this.userPrompt || '');
|
|
2126
|
+
let blockMsg;
|
|
2127
|
+
if (actionSig === 'sysRun:probe:process_or_port' || isExec) {
|
|
2128
|
+
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.`;
|
|
2129
|
+
}
|
|
2130
|
+
else if (isAuthoring) {
|
|
2131
|
+
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.`;
|
|
2132
|
+
}
|
|
2133
|
+
else {
|
|
2134
|
+
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.`;
|
|
2135
|
+
}
|
|
2136
|
+
this.emitEvent({ type: 'step_error', tool: functionName, error: blockMsg, toolCallId: toolCall.id });
|
|
2137
|
+
this.messages.push({
|
|
2138
|
+
role: 'tool',
|
|
2139
|
+
tool_call_id: toolCall.id,
|
|
2140
|
+
name: functionName,
|
|
2141
|
+
content: JSON.stringify({
|
|
2142
|
+
success: false,
|
|
2143
|
+
error: 'DUPLICATE_ACTION_BLOCKED',
|
|
2144
|
+
CRITICAL_INSTRUCTION: blockMsg
|
|
2145
|
+
})
|
|
2146
|
+
});
|
|
2147
|
+
continue;
|
|
2148
|
+
}
|
|
2149
|
+
}
|
|
2150
|
+
// 3. Track Read-Only Inspection Chains on Code Authoring Tasks (Max 6 inspection steps)
|
|
2151
|
+
const isMutatingAction = ['fs_write', 'fs_edit', 'MultiEdit', 'game_build_html5'].includes(functionName)
|
|
2152
|
+
|| (functionName === 'sysRun' && /(npm\s+(i|install|add)|pnpm\s+add|yarn\s+add|pip\s+install|git\s+commit)\b/.test(args?.command || ''));
|
|
2153
|
+
if (isMutatingAction) {
|
|
2154
|
+
this.consecutiveReadOnlySteps = 0;
|
|
2155
|
+
}
|
|
2156
|
+
else if (['sysRun', 'sysRunBg', 'fs_read', 'fs_list', 'dir_list', 'grep_search'].includes(functionName)) {
|
|
2157
|
+
this.consecutiveReadOnlySteps = (Number(this.consecutiveReadOnlySteps) || 0) + 1;
|
|
2158
|
+
}
|
|
2159
|
+
const isExecTask = isExecutionOrLaunchTaskPrompt(this.currentTaskPrompt || this.userPrompt || '');
|
|
2160
|
+
const isAuthoringTask = !isExecTask && isCodeAuthoringTaskPrompt(this.currentTaskPrompt || this.userPrompt || '');
|
|
2161
|
+
if (isAuthoringTask && this.consecutiveReadOnlySteps === 4) {
|
|
2162
|
+
this.messages.push({
|
|
2163
|
+
role: 'system',
|
|
2164
|
+
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.]`
|
|
2165
|
+
});
|
|
1757
2166
|
}
|
|
2167
|
+
if (isAuthoringTask && this.consecutiveReadOnlySteps >= 6) {
|
|
2168
|
+
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.`;
|
|
2169
|
+
this.emitEvent({ type: 'step_error', tool: functionName, error: fatalMsg, toolCallId: toolCall.id });
|
|
2170
|
+
auditLog.log({ event: 'task_killed_circuit_breaker', taskId: this.taskId, reason: fatalMsg });
|
|
2171
|
+
this.abort();
|
|
2172
|
+
break;
|
|
2173
|
+
}
|
|
2174
|
+
this.emitEvent({ type: 'step_start', tool: functionName, args: args, toolCallId: toolCall.id });
|
|
2175
|
+
const codeAction = codeProgressFromAction(functionName, args || {}, toolCall.id);
|
|
2176
|
+
if (codeAction)
|
|
2177
|
+
this.emitEvent(codeAction);
|
|
2178
|
+
this.consecutiveCommands++;
|
|
1758
2179
|
// Sovereign Game Pre-Flight Interceptor (v1.3.13)
|
|
1759
|
-
const isGameTaskExec = isGameIntent(this.currentTaskPrompt || this.userPrompt || '');
|
|
2180
|
+
const isGameTaskExec = !isLaunchOnlyPrompt(this.currentTaskPrompt || this.userPrompt || '') && isGameIntent(this.currentTaskPrompt || this.userPrompt || '');
|
|
1760
2181
|
const ALL_GAME_TOOLS_LIST = [
|
|
1761
2182
|
'godot_act', 'game_asset_fetch', 'game_build_html5',
|
|
1762
2183
|
'game_lore_forge', 'game_dialogue_tree_gen', 'game_quest_arc_builder',
|
|
@@ -1784,25 +2205,7 @@ export class AgentLoop {
|
|
|
1784
2205
|
this.gameCascadeState.verificationPassed = true;
|
|
1785
2206
|
}
|
|
1786
2207
|
}
|
|
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
|
-
}
|
|
2208
|
+
// Sovereign Cascade Intercept neutralized: coding and execution tools execute freely without artificial stage enforcement.
|
|
1806
2209
|
if (functionName === 'game_build_html5' && args.template === 'custom' && args.customScript) {
|
|
1807
2210
|
const scr = args.customScript;
|
|
1808
2211
|
if (scr.includes('c.drw ?') && !scr.includes('drw(')) {
|
|
@@ -1963,29 +2366,33 @@ export class AgentLoop {
|
|
|
1963
2366
|
catch (_err) {
|
|
1964
2367
|
// Cold observer mutation assessment fail-open
|
|
1965
2368
|
}
|
|
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.
|
|
2369
|
+
// A standing grant can avoid repeat prompts in supervised modes.
|
|
2370
|
+
// Mode C is autonomous for in-scope work. Whole-file deletion asks
|
|
2371
|
+
// unless this session explicitly granted the fs_delete tool; a broad
|
|
2372
|
+
// shell grant cannot authorize deletion. Sandbox denials and observer
|
|
2373
|
+
// vetoes have already run and are never lifted by prompt policy.
|
|
1974
2374
|
const standingApproval = this.isAlwaysAllowed(functionName);
|
|
1975
|
-
|
|
2375
|
+
const needsToolApproval = requiresToolApproval({
|
|
2376
|
+
mode: this.config.autonomyMode || 'C',
|
|
2377
|
+
tool: functionName,
|
|
2378
|
+
args,
|
|
2379
|
+
risk: validation.risk,
|
|
2380
|
+
heavyDownload: isHeavyAiDownload,
|
|
2381
|
+
standingApproval
|
|
2382
|
+
});
|
|
2383
|
+
if (standingApproval && !needsToolApproval && this.config.autonomyMode !== 'C') {
|
|
1976
2384
|
auditLog.log({
|
|
1977
2385
|
event: 'approval_auto_granted', taskId: this.taskId,
|
|
1978
2386
|
tool: functionName, risk: validation.risk, reason: 'allow_always'
|
|
1979
2387
|
});
|
|
1980
2388
|
}
|
|
1981
|
-
if (
|
|
1982
|
-
isHeavyAiDownload ||
|
|
1983
|
-
(this.config.autonomyMode !== 'C' && validation.risk === 'dangerous') ||
|
|
1984
|
-
this.config.autonomyMode === 'A')) {
|
|
2389
|
+
if (needsToolApproval) {
|
|
1985
2390
|
// Wait for local approval
|
|
1986
2391
|
this.emitEvent({ type: 'approval_request', toolCallId: toolCall.id, tool: functionName, args, risk: validation.risk });
|
|
1987
2392
|
const approved = await this.waitForApproval(toolCall.id);
|
|
1988
2393
|
if (!approved) {
|
|
2394
|
+
if (this.stopRequested || this.abortController?.signal?.aborted)
|
|
2395
|
+
break;
|
|
1989
2396
|
coldObserver.recordToolOutcome(this.taskId, functionName, args, {
|
|
1990
2397
|
success: false,
|
|
1991
2398
|
error: 'User denied this action'
|
|
@@ -2032,91 +2439,58 @@ export class AgentLoop {
|
|
|
2032
2439
|
this.webArtifacts.add(written.replace(/^~\//, os.homedir() + '/'));
|
|
2033
2440
|
}
|
|
2034
2441
|
}
|
|
2035
|
-
//
|
|
2036
|
-
|
|
2442
|
+
// TimeMachine tracks actual failures across tool results and thrown
|
|
2443
|
+
// errors. It only rewinds reasoning; it never replays side effects.
|
|
2037
2444
|
let result;
|
|
2038
2445
|
let duration;
|
|
2039
|
-
const MAX_RETRIES = 3;
|
|
2040
|
-
const currentRetries = this._toolRetryCount.get(retryKey) || 0;
|
|
2041
2446
|
try {
|
|
2042
|
-
const wasRetried = currentRetries > 0;
|
|
2043
2447
|
const startTime = Date.now();
|
|
2448
|
+
const actStart = performance.now();
|
|
2044
2449
|
// A concurrent read from the prefetch pass above, if it succeeded.
|
|
2045
2450
|
const ready = prefetched.get(toolCall.id);
|
|
2046
2451
|
const early = ready ? await ready : null;
|
|
2047
2452
|
result = (early && early.success)
|
|
2048
2453
|
? early
|
|
2049
|
-
: await tool.execute(args, { signal: this.abortController.signal, parentLoop: this, ...this.sandbox });
|
|
2454
|
+
: await withToolAutonomyMode(this.config.autonomyMode || 'C', () => tool.execute(args, { signal: this.abortController.signal, parentLoop: this, ...this.sandbox }));
|
|
2050
2455
|
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
|
-
}
|
|
2456
|
+
this._totalActMs = (this._totalActMs || 0) + (performance.now() - actStart);
|
|
2057
2457
|
}
|
|
2058
2458
|
catch (toolError) {
|
|
2459
|
+
if (this.stopRequested || this.abortController?.signal?.aborted || toolError?.name === 'AbortError') {
|
|
2460
|
+
auditLog.log({ event: 'task_interrupted', taskId: this.taskId, tool: functionName });
|
|
2461
|
+
break;
|
|
2462
|
+
}
|
|
2059
2463
|
duration = 0;
|
|
2060
2464
|
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;
|
|
2465
|
+
const failure = { success: false, error: String(toolError?.message || toolError) };
|
|
2466
|
+
const alternativeRoute = lookupAlternativeStep({
|
|
2467
|
+
failedTool: functionName,
|
|
2468
|
+
why: failureClass(failure),
|
|
2469
|
+
archetype: this.taskShape?.archetype
|
|
2470
|
+
});
|
|
2471
|
+
if (alternativeRoute) {
|
|
2472
|
+
this.debugLog(`[APC RE-PLANNING] Learned alternative: ${alternativeRoute.suggestedTool} (${alternativeRoute.reason})`);
|
|
2094
2473
|
}
|
|
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;
|
|
2474
|
+
coldObserver.recordToolOutcome(this.taskId, functionName, args, failure);
|
|
2475
|
+
const recovery = this.timeMachine.observe(functionName, args, failure, coldObserver.getToolOutcomes(this.taskId));
|
|
2476
|
+
auditLog.log({ event: 'tool_failure', taskId: this.taskId,
|
|
2477
|
+
tool: functionName, attempt: recovery.attempt, errorType });
|
|
2478
|
+
if (codeAction)
|
|
2479
|
+
this.emitEvent({ ...codeAction, phase: 'failed' });
|
|
2480
|
+
this.emitEvent({ type: 'step_error', tool: functionName,
|
|
2481
|
+
error: `${errorType}: ${failure.error} (${recovery.attempt}/${recovery.maxAttempts})`,
|
|
2482
|
+
toolCallId: toolCall.id });
|
|
2483
|
+
this.messages.push({ role: 'tool', tool_call_id: toolCall.id,
|
|
2484
|
+
name: functionName, content: JSON.stringify({ ...failure,
|
|
2485
|
+
errorType, timeMachine: recovery.guidance,
|
|
2486
|
+
...(alternativeRoute ? { apcReplanAlternative: alternativeRoute.suggestedTool, apcReplanReason: alternativeRoute.reason } : {}) }) });
|
|
2487
|
+
this.memoryManager.saveHistory(this.messages);
|
|
2488
|
+
if (errorType === 'fatal' || recovery.kind === 'stop' || recovery.kind === 'human') {
|
|
2489
|
+
this.stopRequested = true;
|
|
2490
|
+
this.emitEvent({ type: 'error', message: recoveryUserMessage(recovery, functionName) });
|
|
2491
|
+
break;
|
|
2119
2492
|
}
|
|
2493
|
+
continue;
|
|
2120
2494
|
}
|
|
2121
2495
|
auditLog.log({
|
|
2122
2496
|
event: 'tool_exec',
|
|
@@ -2137,10 +2511,39 @@ export class AgentLoop {
|
|
|
2137
2511
|
hookFeedback: (postHook.messages || []).join('\n') || undefined
|
|
2138
2512
|
};
|
|
2139
2513
|
}
|
|
2514
|
+
if (functionName === 'screenshot' && result?.success === true && result?._is_image_marker === true) {
|
|
2515
|
+
this.webVerificationState.screenshotTaken = true;
|
|
2516
|
+
}
|
|
2517
|
+
if (functionName === 'browser_act' && result?.success === true) {
|
|
2518
|
+
this.webVerificationState.browserActUsed = true;
|
|
2519
|
+
if (Array.isArray(args?.actions) && args.actions.some((action) => action?.type === 'screenshot')) {
|
|
2520
|
+
this.webVerificationState.screenshotTaken = true;
|
|
2521
|
+
}
|
|
2522
|
+
}
|
|
2140
2523
|
// The journal is the observer's own record of what actually ran. It
|
|
2141
2524
|
// is written only after post-hook review, so a formatter that rejects
|
|
2142
2525
|
// a write is remembered as a failure rather than a success.
|
|
2143
|
-
|
|
2526
|
+
const observedResult = result?._is_image_marker === true
|
|
2527
|
+
? { success: true, _is_image_marker: true, filename: result.filename, mimeType: result.mimeType }
|
|
2528
|
+
: result;
|
|
2529
|
+
coldObserver.recordToolOutcome(this.taskId, functionName, args, observedResult);
|
|
2530
|
+
const recovery = this.timeMachine.observe(functionName, args, observedResult, coldObserver.getToolOutcomes(this.taskId));
|
|
2531
|
+
if (recovery.kind === 'replan') {
|
|
2532
|
+
this.emitEvent({ type: 'status', message: `TimeMachine: approach change after ${recovery.attempt} failed attempts.` });
|
|
2533
|
+
}
|
|
2534
|
+
if (recovery.kind === 'stop' || recovery.kind === 'human') {
|
|
2535
|
+
this.stopRequested = true;
|
|
2536
|
+
this.emitEvent({ type: 'error', message: recoveryUserMessage(recovery, functionName) });
|
|
2537
|
+
}
|
|
2538
|
+
if (result && (result.success === false || typeof result.error === 'string')) {
|
|
2539
|
+
result = { ...result, timeMachine: recovery.guidance };
|
|
2540
|
+
}
|
|
2541
|
+
if (this.stopRequested) {
|
|
2542
|
+
this.messages.push({ role: 'tool', tool_call_id: toolCall.id,
|
|
2543
|
+
name: functionName, content: JSON.stringify(result) });
|
|
2544
|
+
this.memoryManager.saveHistory(this.messages);
|
|
2545
|
+
break;
|
|
2546
|
+
}
|
|
2144
2547
|
// PROGRESSIVE DISCLOSURE: honour unlock signals from tool_search.
|
|
2145
2548
|
// The control fields are stripped before the result reaches the LLM.
|
|
2146
2549
|
if (result && (result._unlock_tools || result._unlock_packs)) {
|
|
@@ -2155,8 +2558,12 @@ export class AgentLoop {
|
|
|
2155
2558
|
this.debugLog(`capability packs loaded: ${[...this.unlockedPacks].join(', ') || 'core only'}`);
|
|
2156
2559
|
}
|
|
2157
2560
|
// Buffer output for disconnect resilience
|
|
2158
|
-
await this.taskBuffer.appendOutput(this.taskId, { tool: functionName, result });
|
|
2159
|
-
|
|
2561
|
+
await this.taskBuffer.appendOutput(this.taskId, { tool: functionName, result: observedResult });
|
|
2562
|
+
if (codeAction)
|
|
2563
|
+
this.emitEvent({ ...codeAction,
|
|
2564
|
+
phase: result?.success === false || typeof result?.error === 'string' ? 'failed' : 'done' });
|
|
2565
|
+
this.emitEvent({ type: result?.success === false || typeof result?.error === 'string' ? 'step_error' : 'step_complete',
|
|
2566
|
+
tool: functionName, result: result._is_image_marker ? '[IMAGE DATA]' : result, toolCallId: toolCall.id });
|
|
2160
2567
|
this.stepsCompleted++;
|
|
2161
2568
|
// The procedure, as it actually ran. Tool name plus a whitelisted
|
|
2162
2569
|
// action token only — planCache.toStep() reads no paths, arguments or
|
|
@@ -2165,7 +2572,7 @@ export class AgentLoop {
|
|
|
2165
2572
|
if (Array.isArray(this._planSteps)) {
|
|
2166
2573
|
const stepSuccess = Boolean(result && result.success !== false && !result.error);
|
|
2167
2574
|
this._planSteps.push(toStep(functionName, args, stepSuccess, result));
|
|
2168
|
-
this._lastToolResult =
|
|
2575
|
+
this._lastToolResult = observedResult;
|
|
2169
2576
|
// Active Inference: Record step prediction error into VFE rolling tracker
|
|
2170
2577
|
if (this.vfeTracker) {
|
|
2171
2578
|
const isThrash = isThrashing((this._planSteps || []).map((s) => s.tool), functionName);
|
|
@@ -2203,62 +2610,74 @@ export class AgentLoop {
|
|
|
2203
2610
|
}
|
|
2204
2611
|
// Sovereign 100-Step Circuit Breaker Checkpoint Gate
|
|
2205
2612
|
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
|
-
|
|
2613
|
+
if (this.config.autonomyMode === 'C') {
|
|
2614
|
+
this.circuitBreakerUnlocked = true;
|
|
2615
|
+
this.emitEvent({ type: 'status', message: `Continuing within the configured ${this.maxSteps}-step task limit.` });
|
|
2616
|
+
}
|
|
2617
|
+
else {
|
|
2618
|
+
this.emitEvent({
|
|
2619
|
+
type: 'approval_request',
|
|
2620
|
+
toolCallId: 'circuit_breaker_100_' + this.stepsCompleted,
|
|
2621
|
+
tool: 'circuit_breaker_checkpoint',
|
|
2622
|
+
args: {
|
|
2623
|
+
consecutiveCommands: this.consecutiveCommands,
|
|
2624
|
+
stepsCompleted: this.stepsCompleted,
|
|
2625
|
+
activeTier: this.activeTier,
|
|
2626
|
+
maxTierSteps: this.maxSteps,
|
|
2627
|
+
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)?`
|
|
2628
|
+
},
|
|
2629
|
+
risk: 'info'
|
|
2630
|
+
});
|
|
2631
|
+
const approved = await this.waitForApproval('circuit_breaker_100_' + this.stepsCompleted);
|
|
2632
|
+
if (!approved) {
|
|
2633
|
+
this.stopRequested = true;
|
|
2634
|
+
this.emitEvent({ type: 'status', message: 'Task stopped at 100-step circuit breaker checkpoint by user.' });
|
|
2635
|
+
break;
|
|
2636
|
+
}
|
|
2637
|
+
this.circuitBreakerUnlocked = true;
|
|
2638
|
+
this.emitEvent({ type: 'status', message: `⚡ Circuit breaker unlocked! Resuming execution up to ${this.maxSteps} tier budget...` });
|
|
2224
2639
|
}
|
|
2225
|
-
this.circuitBreakerUnlocked = true;
|
|
2226
|
-
this.emitEvent({ type: 'status', message: `⚡ Circuit breaker unlocked! Resuming execution up to ${this.maxSteps} tier budget...` });
|
|
2227
2640
|
}
|
|
2228
2641
|
// Sovereign Tier Budget Extension Checkpoint Gate
|
|
2229
2642
|
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) {
|
|
2643
|
+
if (this.config.autonomyMode === 'C') {
|
|
2245
2644
|
this.stopRequested = true;
|
|
2246
|
-
this.emitEvent({ type: '
|
|
2247
|
-
|
|
2645
|
+
this.emitEvent({ type: 'error', message: `Task reached the configured ${this.maxSteps}-step limit without verified completion.` });
|
|
2646
|
+
}
|
|
2647
|
+
else {
|
|
2648
|
+
const extensionBatch = (this.activeTier === 'super_max') ? 600 : ((this.activeTier === 'max') ? 400 : 300);
|
|
2649
|
+
this.emitEvent({
|
|
2650
|
+
type: 'approval_request',
|
|
2651
|
+
toolCallId: 'tier_extension_' + this.stepsCompleted,
|
|
2652
|
+
tool: 'tier_budget_extension',
|
|
2653
|
+
args: {
|
|
2654
|
+
stepsCompleted: this.stepsCompleted,
|
|
2655
|
+
activeTier: this.activeTier,
|
|
2656
|
+
currentMaxSteps: this.maxSteps,
|
|
2657
|
+
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?`
|
|
2658
|
+
},
|
|
2659
|
+
risk: 'info'
|
|
2660
|
+
});
|
|
2661
|
+
const approved = await this.waitForApproval('tier_extension_' + this.stepsCompleted);
|
|
2662
|
+
if (!approved) {
|
|
2663
|
+
this.stopRequested = true;
|
|
2664
|
+
this.emitEvent({ type: 'status', message: `Task stopped at ${this.maxSteps}-step tier limit by user.` });
|
|
2665
|
+
break;
|
|
2666
|
+
}
|
|
2667
|
+
this.maxSteps += extensionBatch;
|
|
2668
|
+
this.maxCircuitBreaker = this.maxSteps;
|
|
2669
|
+
this.emitEvent({ type: 'status', message: `⚡ Tier budget extended (+${extensionBatch} steps unlocked, new limit: ${this.maxSteps}). Resuming task...` });
|
|
2248
2670
|
}
|
|
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
2671
|
}
|
|
2253
2672
|
// Feed result back to LLM (4. OBSERVE)
|
|
2254
2673
|
if (result && result._is_image_marker) {
|
|
2255
2674
|
if (!this.llm.supportsVision) {
|
|
2256
|
-
// Fallback
|
|
2675
|
+
// Fallback when vision streaming payload is not active on model
|
|
2257
2676
|
this.messages.push({
|
|
2258
2677
|
role: 'tool',
|
|
2259
2678
|
tool_call_id: toolCall.id,
|
|
2260
2679
|
name: functionName,
|
|
2261
|
-
content:
|
|
2680
|
+
content: `[Image observed: ${result.filename || 'image'} (${result.mimeType || 'image/png'}) - verified on disk. Vision observation payload passed.]`
|
|
2262
2681
|
});
|
|
2263
2682
|
}
|
|
2264
2683
|
else {
|
|
@@ -2401,9 +2820,16 @@ export class AgentLoop {
|
|
|
2401
2820
|
}
|
|
2402
2821
|
// Save state continuously after each tool loop
|
|
2403
2822
|
this.memoryManager.saveHistory(this.messages);
|
|
2823
|
+
if (this.stopRequested)
|
|
2824
|
+
break;
|
|
2404
2825
|
}
|
|
2405
2826
|
}
|
|
2406
2827
|
catch (e) {
|
|
2828
|
+
if (this.stopRequested || this.abortController?.signal?.aborted || e?.name === 'AbortError') {
|
|
2829
|
+
this.debugLog(`agent loop interrupted: ${e?.message || 'aborted'}`);
|
|
2830
|
+
auditLog.log({ event: 'task_interrupted', taskId: this.taskId });
|
|
2831
|
+
break;
|
|
2832
|
+
}
|
|
2407
2833
|
// A real failure. It reaches the user as an `error` frame further down
|
|
2408
2834
|
// this same catch; the stack is a diagnostic and stays behind the flag.
|
|
2409
2835
|
this.debugLog(`agent loop error: ${e && e.stack ? e.stack : e}`);
|
|
@@ -2468,7 +2894,9 @@ export class AgentLoop {
|
|
|
2468
2894
|
}
|
|
2469
2895
|
}
|
|
2470
2896
|
}
|
|
2471
|
-
|
|
2897
|
+
// Successful completion is emitted only at the verified completion path
|
|
2898
|
+
// above. A provider error, rejected check, or exhausted recovery budget
|
|
2899
|
+
// must not generate a second (and misleading) success event here.
|
|
2472
2900
|
}
|
|
2473
2901
|
async waitForApproval(toolCallId) {
|
|
2474
2902
|
return new Promise((resolve) => {
|
|
@@ -2501,6 +2929,8 @@ export class AgentLoop {
|
|
|
2501
2929
|
}
|
|
2502
2930
|
// V5: Classify errors for intelligent retry decisions
|
|
2503
2931
|
classifyError(error) {
|
|
2932
|
+
if (error?.code === 'AGY_NATIVE_ACTION_DENIED')
|
|
2933
|
+
return 'fatal';
|
|
2504
2934
|
const msg = (error.message || '').toLowerCase();
|
|
2505
2935
|
if (msg.includes('syntax') || msg.includes('unexpected token') || msg.includes('invalid json')) {
|
|
2506
2936
|
return 'syntax_error';
|
|
@@ -2568,12 +2998,18 @@ export class AgentLoop {
|
|
|
2568
2998
|
validateToolArgs(toolName, args) {
|
|
2569
2999
|
// Check for common LLM mistakes
|
|
2570
3000
|
// 1. File operations must have absolute paths
|
|
2571
|
-
const pathFields = ['path', 'source', 'destination'];
|
|
3001
|
+
const pathFields = ['path', 'source', 'destination', 'target'];
|
|
2572
3002
|
for (const field of pathFields) {
|
|
2573
3003
|
if (args[field] && typeof args[field] === 'string') {
|
|
2574
|
-
|
|
2575
|
-
if (
|
|
2576
|
-
|
|
3004
|
+
const val = args[field].trim();
|
|
3005
|
+
if (/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(val)) {
|
|
3006
|
+
continue;
|
|
3007
|
+
}
|
|
3008
|
+
if (val.startsWith('~')) {
|
|
3009
|
+
args[field] = val.replace(/^~(?=$|[\\/])/, os.homedir());
|
|
3010
|
+
}
|
|
3011
|
+
else if (!val.startsWith('/')) {
|
|
3012
|
+
args[field] = `${this.workspaceRoot || process.cwd()}/${val}`;
|
|
2577
3013
|
}
|
|
2578
3014
|
}
|
|
2579
3015
|
}
|