@causyne/agent 1.20.8 → 1.20.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -1
- package/src/agentLoop.js +291 -103
- package/src/agentLoop.ts +322 -109
- package/src/browser/causyneBrowser.js +36 -0
- package/src/browser/causyneBrowser.ts +36 -1
- package/src/commands.js +25 -0
- package/src/compiledSkills.js +7330 -319
- package/src/computerUse/types.js +8 -0
- package/src/computerUse/types.ts +121 -0
- package/src/computerUse/visionGrounding.js +87 -29
- package/src/computerUse/visionGrounding.ts +108 -36
- package/src/contextManager.js +16 -0
- package/src/decisionPolicy.js +7 -9
- package/src/decisionPolicy.ts +7 -9
- package/src/documentEngine/antiSlopAuditor.js +13 -43
- package/src/documentEngine/antiSlopAuditor.ts +15 -47
- package/src/documentEngine/documentForge.js +3 -3
- package/src/documentEngine/documentForge.ts +3 -3
- package/src/launchIntent.js +3 -3
- package/src/launchIntent.ts +3 -3
- package/src/planCache.js +4 -14
- package/src/planCache.ts +4 -14
- package/src/providers/acp.js +4 -2
- package/src/providers/acp.ts +4 -2
- package/src/providers/antigravity.js +191 -28
- package/src/providers/antigravity.ts +192 -27
- package/src/providers/base.d.ts +2 -0
- package/src/providers/pi.js +3 -1
- package/src/providers/pi.ts +4 -2
- package/src/provisioning/capabilityProvisioner.js +2 -7
- package/src/provisioning/npmInstall.js +19 -0
- package/src/provisioning/npmInstall.ts +19 -0
- package/src/sandbox.js +7 -10
- package/src/smartToolsUse.js +223 -0
- package/src/smartToolsUse.ts +284 -0
- package/src/stallGuard.js +356 -0
- package/src/stallGuard.ts +432 -0
- package/src/taskShape.js +7 -7
- package/src/taskShape.ts +7 -7
- package/src/toolPacks.js +5 -5
- package/src/tools/blenderAutomator.js +198 -11
- package/src/tools/browserAutomator.js +3 -3
- package/src/tools/browserAutomator.ts +3 -3
- package/src/tools/documentForge.js +1 -1
- package/src/tools/documentForge.ts +1 -1
- package/src/tools/fsRead.js +91 -80
- package/src/tools/fsRead.ts +125 -0
- package/src/tools/peerAgent.js +1 -1
- package/src/tools/peerAgent.ts +1 -1
- package/src/tools/screenshot.js +5 -1
- package/src/tools/screenshot.ts +5 -1
- package/src/tools/toolScanner.js +19 -0
- package/src/tools/toolScanner.ts +17 -0
- package/src/tools/toolSelfRepair.js +63 -1
- package/src/tools/toolSelfRepair.ts +61 -1
- package/src/tools/visionInspector.js +80 -142
- package/src/tools/visionInspector.ts +110 -0
- package/src/tui/chatboxClipboard.js +152 -0
- package/src/tui/chatboxClipboard.ts +201 -0
- package/src/tui/clipboardSync.js +38 -7
- package/src/tui/clipboardSync.ts +39 -7
- package/src/tui/codeProgress.js +89 -18
- package/src/tui/codeProgress.ts +102 -17
- package/src/tui/codeStreamRenderer.js +7 -2
- package/src/tui/codeStreamRenderer.ts +7 -2
- package/src/tui/composerControls.js +9 -0
- package/src/tui/composerControls.ts +9 -0
- package/src/tui/dialogs.js +8 -3
- package/src/tui/diff.d.ts +1 -0
- package/src/tui/lineEditor.js +166 -14
- package/src/tui/mouseHover.js +6 -2
- package/src/tui/mouseHover.ts +7 -2
- package/src/tui/prompt.js +96 -19
- package/src/tui/stageSurface.js +3 -1
package/src/agentLoop.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { createHash } from 'crypto';
|
|
2
|
+
import { execFileSync } from 'node:child_process';
|
|
2
3
|
import { processApprovalScope, createApprovalScope } from './approvalGrants.js';
|
|
3
4
|
import { pruneSessions as pruneEmbodimentSessions, describeSession } from './embodimentSession.js';
|
|
4
5
|
import { WorkspacePerception } from './perception.js';
|
|
@@ -47,6 +48,11 @@ import {
|
|
|
47
48
|
PACK_PLAYBOOKS,
|
|
48
49
|
PACKS
|
|
49
50
|
} from './toolPacks.js';
|
|
51
|
+
import {
|
|
52
|
+
determineToolScope,
|
|
53
|
+
filterSuppressedPacks,
|
|
54
|
+
resolveLazyPlaybooks
|
|
55
|
+
} from './smartToolsUse.js';
|
|
50
56
|
import {
|
|
51
57
|
resolveCharPool,
|
|
52
58
|
measureMessages,
|
|
@@ -73,6 +79,7 @@ import { createProvider } from './providers/factory.js';
|
|
|
73
79
|
import { resolveMentionedContext } from './promptMentions.js';
|
|
74
80
|
import { isLaunchOnlyPrompt, launchScopeError } from './launchIntent.js';
|
|
75
81
|
import { StreamingCodePreview, NativeCodeObserver, codeProgressFromAction } from './tui/codeProgress.js';
|
|
82
|
+
import { StallGuardController, type StallGuardDecision, type IdenticalCallObservation } from './stallGuard.js';
|
|
76
83
|
|
|
77
84
|
export interface AgentLoopEvent {
|
|
78
85
|
type: string;
|
|
@@ -115,10 +122,33 @@ export function isActionableTaskPrompt(text: string): boolean {
|
|
|
115
122
|
if (!t) return false;
|
|
116
123
|
const pureGreeting = /^(hi|hello|hey|yo|good\s+(morning|afternoon|evening))[.!?, ]*$/i.test(t);
|
|
117
124
|
if (pureGreeting) return false;
|
|
118
|
-
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;
|
|
125
|
+
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|download)\b/i;
|
|
119
126
|
return actionKeywords.test(t);
|
|
120
127
|
}
|
|
121
128
|
|
|
129
|
+
export function isGenericHandoffResponse(text: string): boolean {
|
|
130
|
+
const answer = (text || '').trim();
|
|
131
|
+
if (!answer || answer.length > 500) return false;
|
|
132
|
+
const lower = answer.toLowerCase();
|
|
133
|
+
const handoff = /\b(let me know what you would like to do next|what would you like me to do next|how (can|may) i help|what can i help you with|feel free to (ask|tell me))\b/i.test(lower);
|
|
134
|
+
const verifiedOutcome = /\b(completed|changed|set the (desktop|wallpaper)|saved|created|installed|verified|downloaded|finished)\b/i.test(lower);
|
|
135
|
+
return handoff && !verifiedOutcome;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export function isDesktopWallpaperChangePrompt(text: string): boolean {
|
|
139
|
+
return /\b(?:change|set|switch|replace)\b[\s\S]{0,100}\b(?:desktop picture|wallpaper|desktop background)\b|\b(?:desktop picture|wallpaper|desktop background)\b[\s\S]{0,100}\b(?:change|set|switch|replace)\b/i.test(text || '');
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function readMacDesktopPictures(): string | null {
|
|
143
|
+
try {
|
|
144
|
+
return execFileSync('osascript', ['-e', 'tell application "System Events" to get picture of every desktop'], {
|
|
145
|
+
encoding: 'utf8', timeout: 4000, stdio: ['ignore', 'pipe', 'ignore']
|
|
146
|
+
}).trim() || null;
|
|
147
|
+
} catch {
|
|
148
|
+
return null;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
122
152
|
export function isExecutionOrLaunchTaskPrompt(text: string): boolean {
|
|
123
153
|
const t = (text || '').trim();
|
|
124
154
|
if (!t) return false;
|
|
@@ -229,7 +259,7 @@ ${AGENT_USER_POLICY}
|
|
|
229
259
|
Follow the selected project's existing style and architecture. Check dependencies and tool schemas before use. Preserve unrelated behavior.
|
|
230
260
|
|
|
231
261
|
# Operational Guidelines & Communication
|
|
232
|
-
- **Language Reflection**: Dynamically reflect and match the exact language used by the user in their prompt.
|
|
262
|
+
- **Language Reflection**: Dynamically reflect and match the exact language used by the user in their prompt. Respond naturally in that same language without mentioning language policies.
|
|
233
263
|
- **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.
|
|
234
264
|
- **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.
|
|
235
265
|
- **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.
|
|
@@ -543,6 +573,7 @@ export class AgentLoop {
|
|
|
543
573
|
this.consecutiveBlockedActions = 0; // V8 Transcendence: Circuit Breaker
|
|
544
574
|
this.recentActionSignatures = [];
|
|
545
575
|
this.consecutiveReadOnlySteps = 0;
|
|
576
|
+
this.stallGuard = new StallGuardController();
|
|
546
577
|
|
|
547
578
|
// Sovereign Progressive Disclosure: which capability packs have entered the
|
|
548
579
|
// context window for this task. Nothing is disabled — see src/toolPacks.js.
|
|
@@ -575,7 +606,8 @@ export class AgentLoop {
|
|
|
575
606
|
this.webGuardFired = false;
|
|
576
607
|
// P6: rendered surfaces this task wrote, for the anti-slop gate to read back.
|
|
577
608
|
this.webArtifacts = new Set();
|
|
578
|
-
this.
|
|
609
|
+
this.slopReviewAttempts = 0;
|
|
610
|
+
this.slopLastAuditHash = '';
|
|
579
611
|
|
|
580
612
|
this.gameCascadeState = { active: true, currentStage: 1, stageHistory: [], verificationPassed: false };
|
|
581
613
|
this.gameToolStats = { godot_act: 0, game_asset_fetch: 0, game_build_html5: 0, last_godot_action: null };
|
|
@@ -650,6 +682,14 @@ export class AgentLoop {
|
|
|
650
682
|
return true;
|
|
651
683
|
}
|
|
652
684
|
|
|
685
|
+
recordWebArtifact(candidate: unknown): void {
|
|
686
|
+
if (typeof candidate !== 'string' || !isScannableFile(candidate)) return;
|
|
687
|
+
const expanded = candidate.startsWith('~/')
|
|
688
|
+
? path.join(os.homedir(), candidate.slice(2))
|
|
689
|
+
: candidate;
|
|
690
|
+
this.webArtifacts.add(path.resolve(this.workspaceRoot, expanded));
|
|
691
|
+
}
|
|
692
|
+
|
|
653
693
|
/**
|
|
654
694
|
* Build the parts of the system context that are constant for a whole task.
|
|
655
695
|
* Called once per task rather than once per step.
|
|
@@ -1047,6 +1087,8 @@ export class AgentLoop {
|
|
|
1047
1087
|
// awareness instead of burning steps rediscovering it. The result used to be
|
|
1048
1088
|
// assigned to a local variable and thrown away.
|
|
1049
1089
|
auditLog.log({ event: 'task_start', taskId: this.taskId, request: this.userPrompt });
|
|
1090
|
+
this.initialDesktopPictures = process.platform === 'darwin' && isDesktopWallpaperChangePrompt(this.userPrompt || '')
|
|
1091
|
+
? readMacDesktopPictures() : null;
|
|
1050
1092
|
// Preserve an explicit workspace selected by the caller (for example ACP).
|
|
1051
1093
|
// The constructor already defaults to process.cwd() when none was supplied.
|
|
1052
1094
|
coldObserver.beginTask(this.taskId);
|
|
@@ -1109,7 +1151,8 @@ export class AgentLoop {
|
|
|
1109
1151
|
this.gameGuardFired = false;
|
|
1110
1152
|
this.webGuardFired = false;
|
|
1111
1153
|
this.webArtifacts = new Set();
|
|
1112
|
-
this.
|
|
1154
|
+
this.slopReviewAttempts = 0;
|
|
1155
|
+
this.slopLastAuditHash = '';
|
|
1113
1156
|
this.staticContext = null;
|
|
1114
1157
|
// Plan cache: the procedure THIS task follows, and the template (if any)
|
|
1115
1158
|
// that was offered to it. Both reset per task — a plan is a property of one
|
|
@@ -1144,11 +1187,20 @@ export class AgentLoop {
|
|
|
1144
1187
|
// measured budget without making the checkpoint undiscoverable.
|
|
1145
1188
|
if (this._decisionRequirement.required) this.unlockedTools.add('request_decision');
|
|
1146
1189
|
|
|
1147
|
-
//
|
|
1148
|
-
//
|
|
1190
|
+
// SmartToolsUse preloads likely tools but never changes a delegated
|
|
1191
|
+
// subagent's permission scope. A task's intent is a routing hint, not an
|
|
1192
|
+
// authorization boundary: later tool_search results must remain usable.
|
|
1193
|
+
const smartScope = determineToolScope(this.userPrompt, this.taskShape);
|
|
1194
|
+
if (smartScope.toolScope) {
|
|
1195
|
+
for (const tool of smartScope.toolScope) this.unlockedTools.add(tool);
|
|
1196
|
+
this.debugLog(`[SmartToolsUse] preloaded ${smartScope.toolScope.size} tools (${smartScope.archetype})`);
|
|
1197
|
+
}
|
|
1198
|
+
|
|
1199
|
+
// Scored routing, with the regex router as a safety net, filtered by SmartToolsUse suppression
|
|
1149
1200
|
const scored = packsFromShape(this.taskShape);
|
|
1150
1201
|
const fallback = routePacks(this.userPrompt, this.workspaceContext);
|
|
1151
|
-
|
|
1202
|
+
const candidatePacks = filterSuppressedPacks([...scored, ...fallback], this.userPrompt);
|
|
1203
|
+
for (const pack of candidatePacks) {
|
|
1152
1204
|
if (pack === 'game' && isDirectGameTask(this.userPrompt)) continue;
|
|
1153
1205
|
this.unlockPack(pack);
|
|
1154
1206
|
}
|
|
@@ -1349,7 +1401,9 @@ export class AgentLoop {
|
|
|
1349
1401
|
this.circuitBreakerUnlocked = false;
|
|
1350
1402
|
this.recentActionSignatures = [];
|
|
1351
1403
|
this.consecutiveReadOnlySteps = 0;
|
|
1404
|
+
this.stallGuard.reset();
|
|
1352
1405
|
this.tokenTracker.resetTask();
|
|
1406
|
+
let mediaExplorationRecoveries = 0;
|
|
1353
1407
|
|
|
1354
1408
|
// The core loop governed by Sovereign Human-in-the-Loop Checkpoints
|
|
1355
1409
|
while (!this.stopRequested) {
|
|
@@ -1370,9 +1424,12 @@ export class AgentLoop {
|
|
|
1370
1424
|
const MAX_CHAR_POOL = resolveCharPool(activeTier, this.config.maxCharPool);
|
|
1371
1425
|
|
|
1372
1426
|
// 5-Stage Progressive Compaction (Claude Code Architecture / Research Section E):
|
|
1373
|
-
// Stage 2 (Snip >15K tokens / 60K chars) +
|
|
1374
|
-
// Stage 3 (Microcompact) + Stage 4 (Context Collapse >85%)
|
|
1427
|
+
// Stage 0 (HLCE Ephemeral Decay) + Stage 2 (Snip >15K tokens / 60K chars) +
|
|
1428
|
+
// Stage 1 (Budget Reduction >70%) + Stage 3 (Microcompact) + Stage 4 (Context Collapse >85%)
|
|
1375
1429
|
const compaction = applyProgressiveCompaction(this.messages, MAX_CHAR_POOL, {
|
|
1430
|
+
enableEphemeralDecay: true,
|
|
1431
|
+
ephemeralKeepRecent: 3,
|
|
1432
|
+
ephemeralMinChars: 1200,
|
|
1376
1433
|
budgetKeepRecent: this.config.keepRecentToolResults ?? 8,
|
|
1377
1434
|
collapseKeepRecent: 2
|
|
1378
1435
|
});
|
|
@@ -1515,10 +1572,18 @@ export class AgentLoop {
|
|
|
1515
1572
|
// volatile block kept dead last. Previously just [1] was anchored, so the
|
|
1516
1573
|
// pack catalogue and the whole workspace/memory/skills context were
|
|
1517
1574
|
// re-billed on every step even though they never changed mid-task.
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1575
|
+
// LazyPlaybook: disclose multi-page mandates only when tools from that domain
|
|
1576
|
+
// have been actively invoked or explicitly demanded. Otherwise emit micro-indicators.
|
|
1577
|
+
const observedTools = (this._planSteps || []).map((step: any) => step.tool);
|
|
1578
|
+
const lazyPlaybookResult = resolveLazyPlaybooks(
|
|
1579
|
+
this.unlockedPacks,
|
|
1580
|
+
observedTools,
|
|
1581
|
+
this.userPrompt
|
|
1582
|
+
);
|
|
1583
|
+
const activePlaybooks = [
|
|
1584
|
+
lazyPlaybookResult.fullPlaybooks,
|
|
1585
|
+
lazyPlaybookResult.microAnnouncements
|
|
1586
|
+
].filter(Boolean).join('\n\n');
|
|
1522
1587
|
|
|
1523
1588
|
// The task brief turns "here are 28 tools" into "here is the order to
|
|
1524
1589
|
// use them in", which is where whole exploratory steps get saved.
|
|
@@ -1660,6 +1725,31 @@ export class AgentLoop {
|
|
|
1660
1725
|
// passed, so a run always overshot by one step — with ~9,000-token
|
|
1661
1726
|
// steps a 299,000 ceiling landed near 308,000. Asking first is what
|
|
1662
1727
|
// makes a ceiling mean the number the user typed.
|
|
1728
|
+
// A peer CLI may execute many model steps inside one chat() call.
|
|
1729
|
+
// Pass the remaining hard budget into peers that expose per-step usage.
|
|
1730
|
+
const budget = this.tokenTracker.budget || {};
|
|
1731
|
+
const hardBudget = (budget.enabled && budget.hardStop) ||
|
|
1732
|
+
(Number.isInteger(this.taskTokenLimit) && this.taskTokenLimit > 0);
|
|
1733
|
+
const taskLimit = Number.isInteger(this.taskTokenLimit) && this.taskTokenLimit > 0
|
|
1734
|
+
? this.taskTokenLimit : Number(budget.maxTokensPerTask || 0);
|
|
1735
|
+
const dailyLimit = budget.enabled && budget.hardStop
|
|
1736
|
+
? Number(budget.maxTokensPerDay || 0) : 0;
|
|
1737
|
+
const dailyUsed = hardBudget && dailyLimit > 0
|
|
1738
|
+
? (await this.tokenTracker.getDailyUsage()).totalTokens : 0;
|
|
1739
|
+
const remainingBudget = hardBudget
|
|
1740
|
+
? Math.min(
|
|
1741
|
+
taskLimit > 0 ? taskLimit - this.tokenTracker.taskTokens : Infinity,
|
|
1742
|
+
dailyLimit > 0 ? dailyLimit - dailyUsed : Infinity
|
|
1743
|
+
) : Infinity;
|
|
1744
|
+
if (remainingBudget <= 0) {
|
|
1745
|
+
this.emitEvent({ type: 'budget_warning', message: 'Token budget reached before the next model call.' });
|
|
1746
|
+
break;
|
|
1747
|
+
}
|
|
1748
|
+
// trackUsage reloads persisted settings; restore the per-task profile
|
|
1749
|
+
// limit before the predictive check on each iteration.
|
|
1750
|
+
if (Number.isInteger(this.taskTokenLimit) && this.taskTokenLimit > 0) {
|
|
1751
|
+
this.tokenTracker.budget = { ...budget, enabled: true, hardStop: true, maxTokensPerTask: this.taskTokenLimit };
|
|
1752
|
+
}
|
|
1663
1753
|
const affordability = this.tokenTracker.canAffordAnotherStep();
|
|
1664
1754
|
if (!affordability.allowed) {
|
|
1665
1755
|
this.emitEvent({ type: 'budget_warning', message: affordability.reason });
|
|
@@ -1693,6 +1783,9 @@ export class AgentLoop {
|
|
|
1693
1783
|
taskId: this.taskId,
|
|
1694
1784
|
conversationId: this.memoryManager?.sessionId || this.taskId,
|
|
1695
1785
|
taskIntent: isLaunchOnlyPrompt(this.currentTaskPrompt || this.userPrompt || '') ? 'launch' : 'general',
|
|
1786
|
+
taskArchetype: determineToolScope(this.currentTaskPrompt || this.userPrompt || '', this.taskShape).archetype,
|
|
1787
|
+
maxTokensThisCall: Number.isFinite(remainingBudget) ? remainingBudget : undefined,
|
|
1788
|
+
tokenLimit: Number.isFinite(remainingBudget) ? remainingBudget : Infinity,
|
|
1696
1789
|
workspaceRoot: this.workspaceRoot,
|
|
1697
1790
|
tools: dynamicTools,
|
|
1698
1791
|
// IARS couples escalation to a wider search. Bounded so a stuck task
|
|
@@ -1736,6 +1829,9 @@ export class AgentLoop {
|
|
|
1736
1829
|
if (nativeCode) {
|
|
1737
1830
|
this.emitEvent(nativeCode);
|
|
1738
1831
|
nativeCodeObserver.handle(nativeCode);
|
|
1832
|
+
if (nativeCode.phase === 'done' && ['Creating', 'Editing'].includes(nativeCode.operation)) {
|
|
1833
|
+
this.recordWebArtifact(nativeCode.path);
|
|
1834
|
+
}
|
|
1739
1835
|
}
|
|
1740
1836
|
const detail = action.detail ? ` ${action.detail}` : '';
|
|
1741
1837
|
if (action.status === 'running') {
|
|
@@ -1774,6 +1870,25 @@ export class AgentLoop {
|
|
|
1774
1870
|
response.usage
|
|
1775
1871
|
);
|
|
1776
1872
|
|
|
1873
|
+
// Private numeric telemetry only. The daily ledger aggregates calls,
|
|
1874
|
+
// so it cannot attribute usage to a task or distinguish provider data
|
|
1875
|
+
// from the character-count fallback used by some ACP peers.
|
|
1876
|
+
auditLog.log({
|
|
1877
|
+
event: 'model_usage', scope: 'agent_loop_primary',
|
|
1878
|
+
taskId: this.taskId, step: this.stepsCompleted,
|
|
1879
|
+
provider: this.config.provider || 'unknown',
|
|
1880
|
+
promptTokens: response.usage.promptTokens,
|
|
1881
|
+
completionTokens: response.usage.completionTokens,
|
|
1882
|
+
cachedPromptTokens: response.usage.cachedPromptTokens || 0,
|
|
1883
|
+
measurement: response.usage.measurement || 'unspecified',
|
|
1884
|
+
cacheMeasurement: response.usage.cacheMeasurement || 'unspecified',
|
|
1885
|
+
costBasis: /^(acp(?:\/|$)|antigravity$|agy$)/i.test(String(this.config.provider || ''))
|
|
1886
|
+
? 'external_subscription_unavailable' : 'rate_card_estimate',
|
|
1887
|
+
callEstimatedCostUsd: this.tokenTracker.calculateCost(
|
|
1888
|
+
response.usage.promptTokens, response.usage.completionTokens, response.usage
|
|
1889
|
+
)
|
|
1890
|
+
});
|
|
1891
|
+
|
|
1777
1892
|
const cachedTokens = response.usage.cachedPromptTokens || 0;
|
|
1778
1893
|
if (cachedTokens > 0) {
|
|
1779
1894
|
this.debugLog(`prompt cache hit: ${cachedTokens.toLocaleString()} of ${response.usage.promptTokens.toLocaleString()} input tokens served from cache`);
|
|
@@ -1869,18 +1984,13 @@ export class AgentLoop {
|
|
|
1869
1984
|
const actionName = String(extAction.name || '').toLowerCase();
|
|
1870
1985
|
const detailPath = typeof extAction.detail === 'string' ? extAction.detail.trim() : '';
|
|
1871
1986
|
if (['write_file', 'write_to_file', 'edit_file', 'replace_file_content', 'multi_replace_file_content', 'fs_write', 'fs_edit', 'multiedit'].includes(actionName) && detailPath) {
|
|
1872
|
-
|
|
1873
|
-
? detailPath
|
|
1874
|
-
: path.resolve(this.workspaceRoot, detailPath.replace(/^~\//, os.homedir() + '/'));
|
|
1875
|
-
if (isScannableFile(resolvedPath)) {
|
|
1876
|
-
this.webArtifacts.add(resolvedPath);
|
|
1877
|
-
}
|
|
1987
|
+
this.recordWebArtifact(detailPath);
|
|
1878
1988
|
}
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
) {
|
|
1883
|
-
this.webVerificationState.
|
|
1989
|
+
// A native action's name is not evidence that a model inspected
|
|
1990
|
+
// pixels. Keep visual verification false unless a real image result
|
|
1991
|
+
// has reached a vision-capable provider.
|
|
1992
|
+
if (['browser_get_dom', 'read_browser_page'].includes(actionName)) {
|
|
1993
|
+
this.webVerificationState.browserActUsed = true;
|
|
1884
1994
|
}
|
|
1885
1995
|
}
|
|
1886
1996
|
}
|
|
@@ -1892,6 +2002,12 @@ export class AgentLoop {
|
|
|
1892
2002
|
const taskPrompt = (this.currentTaskPrompt || this.userPrompt || '').trim();
|
|
1893
2003
|
const isActionable = isActionableTaskPrompt(taskPrompt);
|
|
1894
2004
|
|
|
2005
|
+
if (isActionable && isGenericHandoffResponse(contentText) && (hasExternalActions || this.stepsCompleted > 0)) {
|
|
2006
|
+
this.emitEvent({ type: 'error', message: 'The provider returned a generic handoff after tool activity. The requested outcome was not verified; no completion is recorded.' });
|
|
2007
|
+
this.memoryManager.saveHistory(this.messages);
|
|
2008
|
+
break;
|
|
2009
|
+
}
|
|
2010
|
+
|
|
1895
2011
|
// A native workspace action already changed the workspace. Do not
|
|
1896
2012
|
// demand a Causyne tool call for the same work, and do not treat the
|
|
1897
2013
|
// turn as a no-op.
|
|
@@ -2013,10 +2129,6 @@ export class AgentLoop {
|
|
|
2013
2129
|
// consecutiveThinkingSteps, which resets on every tool call, so
|
|
2014
2130
|
// a guard could block completion indefinitely and burn the whole
|
|
2015
2131
|
// step budget on an already-finished task.
|
|
2016
|
-
if (response.content) {
|
|
2017
|
-
this.emitEvent({ type: 'agent_message', content: response.content });
|
|
2018
|
-
}
|
|
2019
|
-
|
|
2020
2132
|
const isGameTask = !isLaunchOnlyPrompt(taskPrompt) && isGameIntent(taskPrompt);
|
|
2021
2133
|
|
|
2022
2134
|
this.gameToolStats = this.gameToolStats || { godot_act: 0, game_asset_fetch: 0, game_build_html5: 0, last_godot_action: null };
|
|
@@ -2044,18 +2156,29 @@ export class AgentLoop {
|
|
|
2044
2156
|
// This reads the HTML/CSS actually written and scores it. Weighted and
|
|
2045
2157
|
// threshold-based, never a single tripwire: a guard with false
|
|
2046
2158
|
// positives gets switched off (the ZM-09 lesson).
|
|
2047
|
-
if (!
|
|
2048
|
-
this.slopGateFired = true; // fires at most once per task, like the others
|
|
2159
|
+
if (!isLaunchOnlyPrompt(taskPrompt) && isWebIntent(taskPrompt) && this.webArtifacts.size > 0) {
|
|
2049
2160
|
try {
|
|
2050
|
-
const files = [];
|
|
2161
|
+
const files: Array<{ path: string; content: string }> = [];
|
|
2051
2162
|
for (const artifactPath of this.webArtifacts) {
|
|
2163
|
+
if (files.length >= 50) break;
|
|
2052
2164
|
try {
|
|
2165
|
+
const stat = fsSync.lstatSync(artifactPath);
|
|
2166
|
+
if (!stat.isFile() || stat.size > 512_000) continue;
|
|
2053
2167
|
files.push({ path: artifactPath, content: fsSync.readFileSync(artifactPath, 'utf8') });
|
|
2054
|
-
} catch (
|
|
2168
|
+
} catch (_error: unknown) { /* deleted or moved since: nothing to judge */ }
|
|
2169
|
+
}
|
|
2170
|
+
|
|
2171
|
+
if (files.length === 0) {
|
|
2172
|
+
this.emitEvent({ type: 'error', message: 'Web design audit could not read the generated files; the result was not verified as complete.' });
|
|
2173
|
+
this.memoryManager.saveHistory(this.messages);
|
|
2174
|
+
break;
|
|
2055
2175
|
}
|
|
2056
2176
|
|
|
2057
2177
|
const result = analyzeFiles(files);
|
|
2058
2178
|
if (result.verdict === 'slop') {
|
|
2179
|
+
const auditHash = createHash('sha256')
|
|
2180
|
+
.update(files.map(file => `${file.path}\0${file.content}`).join('\0'))
|
|
2181
|
+
.digest('hex');
|
|
2059
2182
|
const recent = Array.isArray(this.staticContext?.recentMovements) ? this.staticContext.recentMovements : [];
|
|
2060
2183
|
const brief = formatMovementBrief(suggestMovements(recent, 3));
|
|
2061
2184
|
|
|
@@ -2064,8 +2187,16 @@ export class AgentLoop {
|
|
|
2064
2187
|
score: result.score, signals: result.findings.map((f: any) => f.id)
|
|
2065
2188
|
});
|
|
2066
2189
|
this.emitEvent({ type: 'status', message: `⚡ Anti-Slop Audit: design scored ${result.score}` });
|
|
2190
|
+
if (this.slopReviewAttempts >= 2 || auditHash === this.slopLastAuditHash) {
|
|
2191
|
+
this.emitEvent({ type: 'error', message: `Web design audit still found generic patterns (score ${result.score}); the result was not verified as complete.` });
|
|
2192
|
+
this.memoryManager.saveHistory(this.messages);
|
|
2193
|
+
break;
|
|
2194
|
+
}
|
|
2195
|
+
this.slopReviewAttempts++;
|
|
2196
|
+
this.slopLastAuditHash = auditHash;
|
|
2067
2197
|
this.messages.push({ role: 'system', content: formatFindings(result, brief) });
|
|
2068
2198
|
this.memoryManager.saveHistory(this.messages);
|
|
2199
|
+
continue;
|
|
2069
2200
|
}
|
|
2070
2201
|
|
|
2071
2202
|
if (result.findings.length > 0) {
|
|
@@ -2076,8 +2207,10 @@ export class AgentLoop {
|
|
|
2076
2207
|
});
|
|
2077
2208
|
}
|
|
2078
2209
|
} catch (e: any) {
|
|
2079
|
-
|
|
2080
|
-
this.
|
|
2210
|
+
this.debugLog(`anti-slop gate failed: ${e.message}`);
|
|
2211
|
+
this.emitEvent({ type: 'error', message: 'Web design audit failed; the result was not verified as complete.' });
|
|
2212
|
+
this.memoryManager.saveHistory(this.messages);
|
|
2213
|
+
break;
|
|
2081
2214
|
}
|
|
2082
2215
|
}
|
|
2083
2216
|
|
|
@@ -2096,23 +2229,33 @@ export class AgentLoop {
|
|
|
2096
2229
|
let visionDeclined = false;
|
|
2097
2230
|
let browserReady = false;
|
|
2098
2231
|
let browserDeclined = false;
|
|
2232
|
+
let browserRuntimeError = '';
|
|
2099
2233
|
try {
|
|
2100
2234
|
const { groupStatus, isGroupDeclined } = await import('./provisioning/capabilityProvisioner.js');
|
|
2101
2235
|
visionReady = groupStatus('vision').state === 'ready';
|
|
2102
2236
|
visionDeclined = isGroupDeclined('vision');
|
|
2103
2237
|
browserReady = groupStatus('browser').state === 'ready';
|
|
2104
2238
|
browserDeclined = isGroupDeclined('browser');
|
|
2239
|
+
if (browserReady) {
|
|
2240
|
+
const { resolveBrowserRuntime } = await import('./browser/browserRuntime.js');
|
|
2241
|
+
try { resolveBrowserRuntime(); } catch (error: unknown) {
|
|
2242
|
+
browserReady = false;
|
|
2243
|
+
browserRuntimeError = error instanceof Error ? error.message : String(error);
|
|
2244
|
+
}
|
|
2245
|
+
}
|
|
2105
2246
|
} catch (e: any) { /* treat as not ready */ }
|
|
2106
2247
|
let webGuardMsg = '';
|
|
2107
2248
|
|
|
2108
|
-
if (
|
|
2249
|
+
if (browserRuntimeError) {
|
|
2250
|
+
webGuardMsg = `[WEB CHECK: The browser capability is granted, but its runtime cannot launch: ${browserRuntimeError} Do not request the same grant again or claim a rendered-page check. Inspect the source and report the runtime blocker. This check fires once.]`;
|
|
2251
|
+
} else if (!browserReady && !browserDeclined) {
|
|
2109
2252
|
webGuardMsg = `[ANTI-SLOP CHECK: You are building a Web/UI project and must inspect it before finishing, but the dedicated browser capability is not enabled yet. Call \`manage_local_dependencies\` with action "grant_capability" and group "browser" to request the Causyne Browser runtime. If the user declines, read the final compiled HTML/CSS instead. This check fires once.]`;
|
|
2110
2253
|
} else if (hasVision && !visionReady && !visionDeclined) {
|
|
2111
2254
|
webGuardMsg = `[ANTI-SLOP CHECK: The browser is available, but desktop screen capture is not enabled. Call \`manage_local_dependencies\` with action "grant_capability" and group "vision" to request it, or use \`browser_act\` snapshots and its workspace-scoped screenshot action. This check fires once.]`;
|
|
2112
2255
|
} else if (hasVision && visionReady && !this.webVerificationState.screenshotTaken) {
|
|
2113
|
-
webGuardMsg = `[ANTI-SLOP CHECK: You are building a Web/UI project but attempted to finish without VISUALLY verifying your work. Use \`screenshot\` or \`vision_inspect_ui\` to look at the UI in a browser. A
|
|
2256
|
+
webGuardMsg = `[ANTI-SLOP CHECK: You are building a Web/UI project but attempted to finish without VISUALLY verifying your work. Use \`screenshot\` or \`vision_inspect_ui\` to look at the UI in a browser. A saved file is not evidence that the model saw the image. If capture fails, report that visual verification was not completed. This check fires once.]`;
|
|
2114
2257
|
} else if ((!hasVision || visionDeclined) && browserReady && !this.webVerificationState.browserActUsed && !this.webVerificationState.screenshotTaken) {
|
|
2115
|
-
webGuardMsg = `[
|
|
2258
|
+
webGuardMsg = `[WEB CHECK: You are building a Web/UI project. Use \`browser_act\` with preview and a workspace-relative HTML filePath, then snapshot to inspect the rendered DOM. A screenshot file by itself is not visual inspection. If browser access fails, read the final HTML/CSS and report that visual verification was not completed. This check fires once.]`;
|
|
2116
2259
|
}
|
|
2117
2260
|
|
|
2118
2261
|
if (webGuardMsg) {
|
|
@@ -2129,6 +2272,21 @@ export class AgentLoop {
|
|
|
2129
2272
|
}
|
|
2130
2273
|
}
|
|
2131
2274
|
|
|
2275
|
+
// Tool availability and a completed plan are not evidence of visual
|
|
2276
|
+
// inspection. A failed browser/capture attempt must not become a
|
|
2277
|
+
// successful task merely because the provider says "verified".
|
|
2278
|
+
if (isWebTask && this.stepsCompleted > 0
|
|
2279
|
+
&& !this.webVerificationState.browserActUsed
|
|
2280
|
+
&& !this.webVerificationState.screenshotTaken) {
|
|
2281
|
+
this.emitEvent({
|
|
2282
|
+
type: 'error',
|
|
2283
|
+
message: 'The web files may have changed, but rendered-page verification did not succeed. The task remains unverified; no completion is recorded.'
|
|
2284
|
+
});
|
|
2285
|
+
auditLog.log({ event: 'task_unverified', taskId: this.taskId, reason: 'web_render_not_inspected' });
|
|
2286
|
+
this.memoryManager.saveHistory(this.messages);
|
|
2287
|
+
break;
|
|
2288
|
+
}
|
|
2289
|
+
|
|
2132
2290
|
// Cold Observer: Overconfidence & Loop Verification Check
|
|
2133
2291
|
{
|
|
2134
2292
|
try {
|
|
@@ -2162,6 +2320,18 @@ export class AgentLoop {
|
|
|
2162
2320
|
}
|
|
2163
2321
|
}
|
|
2164
2322
|
|
|
2323
|
+
if (process.platform === 'darwin' && isDesktopWallpaperChangePrompt(taskPrompt)) {
|
|
2324
|
+
const currentDesktopPictures = readMacDesktopPictures();
|
|
2325
|
+
if (!this.initialDesktopPictures || !currentDesktopPictures || currentDesktopPictures === this.initialDesktopPictures) {
|
|
2326
|
+
this.emitEvent({ type: 'error', message: 'The desktop wallpaper change was not confirmed by macOS readback. The task remains incomplete.' });
|
|
2327
|
+
this.memoryManager.saveHistory(this.messages);
|
|
2328
|
+
break;
|
|
2329
|
+
}
|
|
2330
|
+
}
|
|
2331
|
+
|
|
2332
|
+
if (response.content) {
|
|
2333
|
+
this.emitEvent({ type: 'agent_message', content: response.content });
|
|
2334
|
+
}
|
|
2165
2335
|
this.emitEvent({ type: 'status', message: 'Task completed.' });
|
|
2166
2336
|
this.memoryManager.saveHistory(this.messages); // Save final state
|
|
2167
2337
|
|
|
@@ -2298,72 +2468,43 @@ export class AgentLoop {
|
|
|
2298
2468
|
this.recentActionSignatures.shift();
|
|
2299
2469
|
}
|
|
2300
2470
|
|
|
2301
|
-
|
|
2302
|
-
|
|
2303
|
-
|
|
2471
|
+
// Universal Intelligent Loop Guard & Stall Breaker (Hermes / Claude Code architecture)
|
|
2472
|
+
const isExecTask = isExecutionOrLaunchTaskPrompt(this.currentTaskPrompt || this.userPrompt || '');
|
|
2473
|
+
const isAuthoringTask = !isExecTask && isCodeAuthoringTaskPrompt(this.currentTaskPrompt || this.userPrompt || '');
|
|
2304
2474
|
|
|
2305
|
-
|
|
2306
|
-
|
|
2307
|
-
|
|
2308
|
-
this.emitEvent({ type: 'step_error', tool: functionName, error: fatalMsg, toolCallId: toolCall.id });
|
|
2309
|
-
auditLog.log({ event: 'task_killed_circuit_breaker', taskId: this.taskId, reason: fatalMsg });
|
|
2310
|
-
this.abort();
|
|
2311
|
-
break;
|
|
2312
|
-
}
|
|
2475
|
+
const guardDecision = this.stallGuard.beforeCall(functionName, args || {}, {
|
|
2476
|
+
isAuthoringTask
|
|
2477
|
+
});
|
|
2313
2478
|
|
|
2314
|
-
|
|
2315
|
-
|
|
2316
|
-
|
|
2317
|
-
|
|
2318
|
-
|
|
2319
|
-
|
|
2320
|
-
|
|
2321
|
-
|
|
2322
|
-
|
|
2323
|
-
|
|
2324
|
-
|
|
2325
|
-
}
|
|
2326
|
-
|
|
2327
|
-
|
|
2328
|
-
role: 'tool',
|
|
2329
|
-
tool_call_id: toolCall.id,
|
|
2330
|
-
name: functionName,
|
|
2331
|
-
content: JSON.stringify({
|
|
2332
|
-
success: false,
|
|
2333
|
-
error: 'DUPLICATE_ACTION_BLOCKED',
|
|
2334
|
-
CRITICAL_INSTRUCTION: blockMsg
|
|
2335
|
-
})
|
|
2336
|
-
});
|
|
2337
|
-
continue;
|
|
2338
|
-
}
|
|
2479
|
+
if (guardDecision.action === 'block') {
|
|
2480
|
+
this.emitEvent({ type: 'step_error', tool: functionName, error: guardDecision.message, toolCallId: toolCall.id });
|
|
2481
|
+
auditLog.log({ event: 'tool_blocked', taskId: this.taskId, tool: functionName, args, reason: guardDecision.message });
|
|
2482
|
+
this.messages.push({
|
|
2483
|
+
role: 'tool',
|
|
2484
|
+
tool_call_id: toolCall.id,
|
|
2485
|
+
name: functionName,
|
|
2486
|
+
content: JSON.stringify({
|
|
2487
|
+
success: false,
|
|
2488
|
+
error: guardDecision.code,
|
|
2489
|
+
CRITICAL_INSTRUCTION: guardDecision.message
|
|
2490
|
+
})
|
|
2491
|
+
});
|
|
2492
|
+
continue;
|
|
2339
2493
|
}
|
|
2340
2494
|
|
|
2341
|
-
|
|
2342
|
-
|
|
2343
|
-
|
|
2344
|
-
|
|
2345
|
-
|
|
2346
|
-
this.consecutiveReadOnlySteps = 0;
|
|
2347
|
-
} else if (['sysRun', 'sysRunBg', 'fs_read', 'fs_list', 'dir_list', 'grep_search'].includes(functionName)) {
|
|
2348
|
-
this.consecutiveReadOnlySteps = (Number(this.consecutiveReadOnlySteps) || 0) + 1;
|
|
2495
|
+
if (guardDecision.action === 'halt') {
|
|
2496
|
+
this.emitEvent({ type: 'step_error', tool: functionName, error: guardDecision.message, toolCallId: toolCall.id });
|
|
2497
|
+
auditLog.log({ event: 'task_killed_circuit_breaker', taskId: this.taskId, reason: guardDecision.message });
|
|
2498
|
+
this.abort();
|
|
2499
|
+
break;
|
|
2349
2500
|
}
|
|
2350
2501
|
|
|
2351
|
-
|
|
2352
|
-
const isAuthoringTask = !isExecTask && isCodeAuthoringTaskPrompt(this.currentTaskPrompt || this.userPrompt || '');
|
|
2353
|
-
if (isAuthoringTask && this.consecutiveReadOnlySteps === 4) {
|
|
2502
|
+
if (isAuthoringTask && this.stallGuard.distinctInspectionCount === 12) {
|
|
2354
2503
|
this.messages.push({
|
|
2355
2504
|
role: 'system',
|
|
2356
|
-
content: `[CRITICAL ACTION MANDATE: You have performed
|
|
2505
|
+
content: `[CRITICAL ACTION MANDATE: You have performed 12 consecutive inspection steps without writing code. If you have gathered sufficient context, proceed to creating or editing implementation files using fs_write/fs_edit.]`
|
|
2357
2506
|
});
|
|
2358
2507
|
}
|
|
2359
|
-
|
|
2360
|
-
if (isAuthoringTask && this.consecutiveReadOnlySteps >= 6) {
|
|
2361
|
-
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.`;
|
|
2362
|
-
this.emitEvent({ type: 'step_error', tool: functionName, error: fatalMsg, toolCallId: toolCall.id });
|
|
2363
|
-
auditLog.log({ event: 'task_killed_circuit_breaker', taskId: this.taskId, reason: fatalMsg });
|
|
2364
|
-
this.abort();
|
|
2365
|
-
break;
|
|
2366
|
-
}
|
|
2367
2508
|
|
|
2368
2509
|
this.emitEvent({ type: 'step_start', tool: functionName, args: args, toolCallId: toolCall.id });
|
|
2369
2510
|
const codeAction = codeProgressFromAction(functionName, args || {}, toolCall.id);
|
|
@@ -2653,16 +2794,6 @@ export class AgentLoop {
|
|
|
2653
2794
|
});
|
|
2654
2795
|
}
|
|
2655
2796
|
|
|
2656
|
-
// P6: remember which rendered surfaces this task touched, so the
|
|
2657
|
-
// anti-slop gate can read the finished result back off disk rather
|
|
2658
|
-
// than trusting the model's own account of what it built.
|
|
2659
|
-
if (['fs_write', 'fs_edit', 'MultiEdit'].includes(functionName)) {
|
|
2660
|
-
const written = args.path || args.file_path;
|
|
2661
|
-
if (typeof written === 'string' && isScannableFile(written)) {
|
|
2662
|
-
this.webArtifacts.add(written.replace(/^~\//, os.homedir() + '/'));
|
|
2663
|
-
}
|
|
2664
|
-
}
|
|
2665
|
-
|
|
2666
2797
|
// TimeMachine tracks actual failures across tool results and thrown
|
|
2667
2798
|
// errors. It only rewinds reasoning; it never replays side effects.
|
|
2668
2799
|
let result;
|
|
@@ -2710,6 +2841,7 @@ export class AgentLoop {
|
|
|
2710
2841
|
name: functionName, content: JSON.stringify({ ...failure,
|
|
2711
2842
|
errorType, timeMachine: recovery.guidance,
|
|
2712
2843
|
...(alternativeRoute ? { apcReplanAlternative: alternativeRoute.suggestedTool, apcReplanReason: alternativeRoute.reason } : {}) }) });
|
|
2844
|
+
this.stallGuard.observeCall(functionName, args || {}, failure, toolCall.id, true);
|
|
2713
2845
|
this.memoryManager.saveHistory(this.messages);
|
|
2714
2846
|
if (errorType === 'fatal' || recovery.kind === 'stop' || recovery.kind === 'human') {
|
|
2715
2847
|
this.stopRequested = true;
|
|
@@ -2740,13 +2872,17 @@ export class AgentLoop {
|
|
|
2740
2872
|
};
|
|
2741
2873
|
}
|
|
2742
2874
|
|
|
2743
|
-
if (
|
|
2875
|
+
if (result && result.success !== false && !result.error && ['fs_write', 'fs_edit', 'MultiEdit'].includes(functionName)) {
|
|
2876
|
+
this.recordWebArtifact(args.path || args.file_path);
|
|
2877
|
+
}
|
|
2878
|
+
|
|
2879
|
+
if (['screenshot', 'vision_inspect_ui'].includes(functionName) && this.llm.supportsVision !== false && result?.success === true && result?._is_image_marker === true) {
|
|
2744
2880
|
this.webVerificationState.screenshotTaken = true;
|
|
2745
2881
|
}
|
|
2746
2882
|
if (functionName === 'browser_act' && result?.success === true) {
|
|
2747
|
-
|
|
2748
|
-
if (
|
|
2749
|
-
this.webVerificationState.
|
|
2883
|
+
const browserResults = Array.isArray(result.data) ? result.data : [];
|
|
2884
|
+
if (browserResults.some((item: any) => ['snapshot', 'scrape'].includes(item?.action))) {
|
|
2885
|
+
this.webVerificationState.browserActUsed = true;
|
|
2750
2886
|
}
|
|
2751
2887
|
}
|
|
2752
2888
|
|
|
@@ -2922,7 +3058,7 @@ export class AgentLoop {
|
|
|
2922
3058
|
role: 'tool',
|
|
2923
3059
|
tool_call_id: toolCall.id,
|
|
2924
3060
|
name: functionName,
|
|
2925
|
-
content: `[Image
|
|
3061
|
+
content: `[Image captured: ${result.filename || 'image'} (${result.mimeType || 'image/png'}). This provider cannot receive image pixels; visual inspection was not completed.]`
|
|
2926
3062
|
});
|
|
2927
3063
|
} else {
|
|
2928
3064
|
// Provider-specific format.
|
|
@@ -3054,6 +3190,19 @@ export class AgentLoop {
|
|
|
3054
3190
|
}
|
|
3055
3191
|
}
|
|
3056
3192
|
|
|
3193
|
+
const isCallFailed = Boolean(result && (result.success === false || typeof result.error === 'string'));
|
|
3194
|
+
const stallObservation = this.stallGuard.observeCall(
|
|
3195
|
+
functionName,
|
|
3196
|
+
args || {},
|
|
3197
|
+
result,
|
|
3198
|
+
toolCall.id,
|
|
3199
|
+
isCallFailed
|
|
3200
|
+
);
|
|
3201
|
+
|
|
3202
|
+
if (stallObservation.stub && resultString.length >= 256) {
|
|
3203
|
+
resultString = stallObservation.stub;
|
|
3204
|
+
}
|
|
3205
|
+
|
|
3057
3206
|
this.messages.push({
|
|
3058
3207
|
role: 'tool',
|
|
3059
3208
|
tool_call_id: toolCall.id,
|
|
@@ -3064,6 +3213,21 @@ export class AgentLoop {
|
|
|
3064
3213
|
// stub keep pointing at the spill after the payload is gone.
|
|
3065
3214
|
...(spill ? { spillPath: spill.path } : {})
|
|
3066
3215
|
});
|
|
3216
|
+
|
|
3217
|
+
if (stallObservation.notice) {
|
|
3218
|
+
this.messages.push({
|
|
3219
|
+
role: 'system',
|
|
3220
|
+
content: stallObservation.notice
|
|
3221
|
+
});
|
|
3222
|
+
}
|
|
3223
|
+
|
|
3224
|
+
if (stallObservation.decision?.action === 'halt') {
|
|
3225
|
+
const fatalMsg = stallObservation.decision.message;
|
|
3226
|
+
this.emitEvent({ type: 'step_error', tool: functionName, error: fatalMsg, toolCallId: toolCall.id });
|
|
3227
|
+
auditLog.log({ event: 'task_killed_circuit_breaker', taskId: this.taskId, reason: fatalMsg });
|
|
3228
|
+
this.abort();
|
|
3229
|
+
break;
|
|
3230
|
+
}
|
|
3067
3231
|
}
|
|
3068
3232
|
|
|
3069
3233
|
// Save state continuously after each tool loop
|
|
@@ -3072,6 +3236,48 @@ export class AgentLoop {
|
|
|
3072
3236
|
}
|
|
3073
3237
|
|
|
3074
3238
|
} catch (e: any) {
|
|
3239
|
+
// A peer can fail after completing billable steps. Charge those steps
|
|
3240
|
+
// once even when no final result was returned, including action and
|
|
3241
|
+
// wall-clock limits, before deciding whether recovery is possible.
|
|
3242
|
+
if (e?.partialUsage) {
|
|
3243
|
+
const usage = e.partialUsage;
|
|
3244
|
+
if (usage.promptTokens + usage.completionTokens > 0) {
|
|
3245
|
+
await this.tokenTracker.trackUsage(
|
|
3246
|
+
usage.promptTokens, usage.completionTokens,
|
|
3247
|
+
(message: string) => this.emitEvent({ type: 'budget_warning', message }), usage
|
|
3248
|
+
);
|
|
3249
|
+
auditLog.log({
|
|
3250
|
+
event: 'model_usage', scope: 'agent_loop_primary', taskId: this.taskId,
|
|
3251
|
+
step: this.stepsCompleted, provider: this.config.provider || 'unknown',
|
|
3252
|
+
promptTokens: usage.promptTokens, completionTokens: usage.completionTokens,
|
|
3253
|
+
cachedPromptTokens: usage.cachedPromptTokens || 0,
|
|
3254
|
+
measurement: 'provider_reported_partial', costBasis: 'external_subscription_unavailable'
|
|
3255
|
+
});
|
|
3256
|
+
}
|
|
3257
|
+
}
|
|
3258
|
+
if (e?.code === 'AGY_TOKEN_BUDGET' || e?.code === 'TASK_TOKEN_BUDGET' || e?.code === 'PROVIDER_TOKEN_BUDGET') {
|
|
3259
|
+
this.emitEvent({ type: 'budget_warning', message: e.message });
|
|
3260
|
+
auditLog.log({ event: 'task_stopped_on_budget', taskId: this.taskId,
|
|
3261
|
+
used: this.tokenTracker.taskTokens, limit: e.tokenLimit || this.tokenTracker.budget?.maxTokensPerTask || 0 });
|
|
3262
|
+
break;
|
|
3263
|
+
}
|
|
3264
|
+
if (e?.code === 'AGY_EXPLORATION_LOOP' || e?.code === 'AGENT_EXPLORATION_LOOP' || e?.code === 'STALL_EXPLORATION_LOOP') {
|
|
3265
|
+
auditLog.log({ event: 'media_exploration_checkpoint', taskId: this.taskId,
|
|
3266
|
+
inspectionCount: e.inspectionCount, recovery: mediaExplorationRecoveries });
|
|
3267
|
+
if (mediaExplorationRecoveries++ === 0) {
|
|
3268
|
+
this.messages.push({ role: 'system', content:
|
|
3269
|
+
'[TASK RECOVERY] Consecutive read-only inspections without workspace changes were paused. ' +
|
|
3270
|
+
'The user requested a concrete change. Reuse the observations already gathered; do not repeat probes. ' +
|
|
3271
|
+
'Make one targeted workspace edit now, then run one focused verification. ' +
|
|
3272
|
+
'If editing is blocked, report the exact blocker. Do not claim completion from inspection alone.' });
|
|
3273
|
+
this.memoryManager.saveHistory(this.messages);
|
|
3274
|
+
this.emitEvent({ type: 'notice', message: 'Repeated inspection paused; continuing once with a direct edit instruction.' });
|
|
3275
|
+
continue;
|
|
3276
|
+
}
|
|
3277
|
+
this.emitEvent({ type: 'error', message:
|
|
3278
|
+
'The provider continued read-only inspection after a corrective checkpoint. The task remains unfinished; no edit was verified.' });
|
|
3279
|
+
break;
|
|
3280
|
+
}
|
|
3075
3281
|
if (this.stopRequested || this.abortController?.signal?.aborted || e?.name === 'AbortError') {
|
|
3076
3282
|
this.debugLog(`agent loop interrupted: ${e?.message || 'aborted'}`);
|
|
3077
3283
|
auditLog.log({ event: 'task_interrupted', taskId: this.taskId });
|
|
@@ -3189,7 +3395,14 @@ export class AgentLoop {
|
|
|
3189
3395
|
|
|
3190
3396
|
// V5: Classify errors for intelligent retry decisions
|
|
3191
3397
|
classifyError(error: any) {
|
|
3192
|
-
if (error?.code === 'AGY_NATIVE_ACTION_DENIED'
|
|
3398
|
+
if (error?.code === 'AGY_NATIVE_ACTION_DENIED'
|
|
3399
|
+
|| error?.code === 'AGY_NATIVE_ACTION_BUDGET'
|
|
3400
|
+
|| error?.code === 'AGY_DESKTOP_TASK_LIMIT') return 'fatal';
|
|
3401
|
+
// A provider may have charged for completed steps before the turn failed.
|
|
3402
|
+
// Replaying that turn can repeat actions and spend the same tokens again.
|
|
3403
|
+
const spent = Number(error?.partialUsage?.promptTokens || 0)
|
|
3404
|
+
+ Number(error?.partialUsage?.completionTokens || 0);
|
|
3405
|
+
if (spent > 0) return 'fatal';
|
|
3193
3406
|
const msg = (error.message || '').toLowerCase();
|
|
3194
3407
|
|
|
3195
3408
|
if (msg.includes('syntax') || msg.includes('unexpected token') || msg.includes('invalid json')) {
|