@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.js
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';
|
|
@@ -27,6 +28,7 @@ import { VFETracker } from './vfeTracker.js';
|
|
|
27
28
|
import { coldObserver } from './observer/coldObserver.js';
|
|
28
29
|
import { TimeMachine, recoveryUserMessage } from './timeMachine.js';
|
|
29
30
|
import { routePacks, packForTool, isCoreTool, isGameIntent, isWebIntent, getPackCatalogue, PACK_PLAYBOOKS, PACKS } from './toolPacks.js';
|
|
31
|
+
import { determineToolScope, filterSuppressedPacks, resolveLazyPlaybooks } from './smartToolsUse.js';
|
|
30
32
|
import { resolveCharPool, measureMessages, resultCapFor, decayToolResults, buildWindow, compactInPlace, describeDroppedMessages, sanitizeSequences, applyProgressiveCompaction, snipOversizedToolOutputs } from './contextManager.js';
|
|
31
33
|
// Provider imports
|
|
32
34
|
import { detectWorkspaceDomains, ensureSkillRepo, getSkillDomainHeader } from './skillsManager.js';
|
|
@@ -41,6 +43,7 @@ import { createProvider } from './providers/factory.js';
|
|
|
41
43
|
import { resolveMentionedContext } from './promptMentions.js';
|
|
42
44
|
import { isLaunchOnlyPrompt, launchScopeError } from './launchIntent.js';
|
|
43
45
|
import { StreamingCodePreview, NativeCodeObserver, codeProgressFromAction } from './tui/codeProgress.js';
|
|
46
|
+
import { StallGuardController } from './stallGuard.js';
|
|
44
47
|
export function isActionableTaskPrompt(text) {
|
|
45
48
|
const t = (text || '').trim();
|
|
46
49
|
if (!t)
|
|
@@ -48,9 +51,31 @@ export function isActionableTaskPrompt(text) {
|
|
|
48
51
|
const pureGreeting = /^(hi|hello|hey|yo|good\s+(morning|afternoon|evening))[.!?, ]*$/i.test(t);
|
|
49
52
|
if (pureGreeting)
|
|
50
53
|
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;
|
|
54
|
+
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;
|
|
52
55
|
return actionKeywords.test(t);
|
|
53
56
|
}
|
|
57
|
+
export function isGenericHandoffResponse(text) {
|
|
58
|
+
const answer = (text || '').trim();
|
|
59
|
+
if (!answer || answer.length > 500)
|
|
60
|
+
return false;
|
|
61
|
+
const lower = answer.toLowerCase();
|
|
62
|
+
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);
|
|
63
|
+
const verifiedOutcome = /\b(completed|changed|set the (desktop|wallpaper)|saved|created|installed|verified|downloaded|finished)\b/i.test(lower);
|
|
64
|
+
return handoff && !verifiedOutcome;
|
|
65
|
+
}
|
|
66
|
+
export function isDesktopWallpaperChangePrompt(text) {
|
|
67
|
+
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 || '');
|
|
68
|
+
}
|
|
69
|
+
function readMacDesktopPictures() {
|
|
70
|
+
try {
|
|
71
|
+
return execFileSync('osascript', ['-e', 'tell application "System Events" to get picture of every desktop'], {
|
|
72
|
+
encoding: 'utf8', timeout: 4000, stdio: ['ignore', 'pipe', 'ignore']
|
|
73
|
+
}).trim() || null;
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
54
79
|
export function isExecutionOrLaunchTaskPrompt(text) {
|
|
55
80
|
const t = (text || '').trim();
|
|
56
81
|
if (!t)
|
|
@@ -153,7 +178,7 @@ ${AGENT_USER_POLICY}
|
|
|
153
178
|
Follow the selected project's existing style and architecture. Check dependencies and tool schemas before use. Preserve unrelated behavior.
|
|
154
179
|
|
|
155
180
|
# Operational Guidelines & Communication
|
|
156
|
-
- **Language Reflection**: Dynamically reflect and match the exact language used by the user in their prompt.
|
|
181
|
+
- **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.
|
|
157
182
|
- **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.
|
|
158
183
|
- **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
184
|
- **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.
|
|
@@ -451,6 +476,7 @@ export class AgentLoop {
|
|
|
451
476
|
this.consecutiveBlockedActions = 0; // V8 Transcendence: Circuit Breaker
|
|
452
477
|
this.recentActionSignatures = [];
|
|
453
478
|
this.consecutiveReadOnlySteps = 0;
|
|
479
|
+
this.stallGuard = new StallGuardController();
|
|
454
480
|
// Sovereign Progressive Disclosure: which capability packs have entered the
|
|
455
481
|
// context window for this task. Nothing is disabled — see src/toolPacks.js.
|
|
456
482
|
this.unlockedPacks = new Set();
|
|
@@ -481,7 +507,8 @@ export class AgentLoop {
|
|
|
481
507
|
this.webGuardFired = false;
|
|
482
508
|
// P6: rendered surfaces this task wrote, for the anti-slop gate to read back.
|
|
483
509
|
this.webArtifacts = new Set();
|
|
484
|
-
this.
|
|
510
|
+
this.slopReviewAttempts = 0;
|
|
511
|
+
this.slopLastAuditHash = '';
|
|
485
512
|
this.gameCascadeState = { active: true, currentStage: 1, stageHistory: [], verificationPassed: false };
|
|
486
513
|
this.gameToolStats = { godot_act: 0, game_asset_fetch: 0, game_build_html5: 0, last_godot_action: null };
|
|
487
514
|
this.webVerificationState = { screenshotTaken: false, browserActUsed: false }; // V8 Transcendence: Anti-Slop Guard
|
|
@@ -549,6 +576,14 @@ export class AgentLoop {
|
|
|
549
576
|
this.unlockOrder.push(packName);
|
|
550
577
|
return true;
|
|
551
578
|
}
|
|
579
|
+
recordWebArtifact(candidate) {
|
|
580
|
+
if (typeof candidate !== 'string' || !isScannableFile(candidate))
|
|
581
|
+
return;
|
|
582
|
+
const expanded = candidate.startsWith('~/')
|
|
583
|
+
? path.join(os.homedir(), candidate.slice(2))
|
|
584
|
+
: candidate;
|
|
585
|
+
this.webArtifacts.add(path.resolve(this.workspaceRoot, expanded));
|
|
586
|
+
}
|
|
552
587
|
/**
|
|
553
588
|
* Build the parts of the system context that are constant for a whole task.
|
|
554
589
|
* Called once per task rather than once per step.
|
|
@@ -941,6 +976,8 @@ export class AgentLoop {
|
|
|
941
976
|
// awareness instead of burning steps rediscovering it. The result used to be
|
|
942
977
|
// assigned to a local variable and thrown away.
|
|
943
978
|
auditLog.log({ event: 'task_start', taskId: this.taskId, request: this.userPrompt });
|
|
979
|
+
this.initialDesktopPictures = process.platform === 'darwin' && isDesktopWallpaperChangePrompt(this.userPrompt || '')
|
|
980
|
+
? readMacDesktopPictures() : null;
|
|
944
981
|
// Preserve an explicit workspace selected by the caller (for example ACP).
|
|
945
982
|
// The constructor already defaults to process.cwd() when none was supplied.
|
|
946
983
|
coldObserver.beginTask(this.taskId);
|
|
@@ -1000,7 +1037,8 @@ export class AgentLoop {
|
|
|
1000
1037
|
this.gameGuardFired = false;
|
|
1001
1038
|
this.webGuardFired = false;
|
|
1002
1039
|
this.webArtifacts = new Set();
|
|
1003
|
-
this.
|
|
1040
|
+
this.slopReviewAttempts = 0;
|
|
1041
|
+
this.slopLastAuditHash = '';
|
|
1004
1042
|
this.staticContext = null;
|
|
1005
1043
|
// Plan cache: the procedure THIS task follows, and the template (if any)
|
|
1006
1044
|
// that was offered to it. Both reset per task — a plan is a property of one
|
|
@@ -1031,11 +1069,20 @@ export class AgentLoop {
|
|
|
1031
1069
|
// measured budget without making the checkpoint undiscoverable.
|
|
1032
1070
|
if (this._decisionRequirement.required)
|
|
1033
1071
|
this.unlockedTools.add('request_decision');
|
|
1034
|
-
//
|
|
1035
|
-
//
|
|
1072
|
+
// SmartToolsUse preloads likely tools but never changes a delegated
|
|
1073
|
+
// subagent's permission scope. A task's intent is a routing hint, not an
|
|
1074
|
+
// authorization boundary: later tool_search results must remain usable.
|
|
1075
|
+
const smartScope = determineToolScope(this.userPrompt, this.taskShape);
|
|
1076
|
+
if (smartScope.toolScope) {
|
|
1077
|
+
for (const tool of smartScope.toolScope)
|
|
1078
|
+
this.unlockedTools.add(tool);
|
|
1079
|
+
this.debugLog(`[SmartToolsUse] preloaded ${smartScope.toolScope.size} tools (${smartScope.archetype})`);
|
|
1080
|
+
}
|
|
1081
|
+
// Scored routing, with the regex router as a safety net, filtered by SmartToolsUse suppression
|
|
1036
1082
|
const scored = packsFromShape(this.taskShape);
|
|
1037
1083
|
const fallback = routePacks(this.userPrompt, this.workspaceContext);
|
|
1038
|
-
|
|
1084
|
+
const candidatePacks = filterSuppressedPacks([...scored, ...fallback], this.userPrompt);
|
|
1085
|
+
for (const pack of candidatePacks) {
|
|
1039
1086
|
if (pack === 'game' && isDirectGameTask(this.userPrompt))
|
|
1040
1087
|
continue;
|
|
1041
1088
|
this.unlockPack(pack);
|
|
@@ -1227,7 +1274,9 @@ export class AgentLoop {
|
|
|
1227
1274
|
this.circuitBreakerUnlocked = false;
|
|
1228
1275
|
this.recentActionSignatures = [];
|
|
1229
1276
|
this.consecutiveReadOnlySteps = 0;
|
|
1277
|
+
this.stallGuard.reset();
|
|
1230
1278
|
this.tokenTracker.resetTask();
|
|
1279
|
+
let mediaExplorationRecoveries = 0;
|
|
1231
1280
|
// The core loop governed by Sovereign Human-in-the-Loop Checkpoints
|
|
1232
1281
|
while (!this.stopRequested) {
|
|
1233
1282
|
if (this.stopRequested) {
|
|
@@ -1244,9 +1293,12 @@ export class AgentLoop {
|
|
|
1244
1293
|
const activeTier = isDevEmulator(this.config) ? 'super_max' : (this.config.tier || 'premium');
|
|
1245
1294
|
const MAX_CHAR_POOL = resolveCharPool(activeTier, this.config.maxCharPool);
|
|
1246
1295
|
// 5-Stage Progressive Compaction (Claude Code Architecture / Research Section E):
|
|
1247
|
-
// Stage 2 (Snip >15K tokens / 60K chars) +
|
|
1248
|
-
// Stage 3 (Microcompact) + Stage 4 (Context Collapse >85%)
|
|
1296
|
+
// Stage 0 (HLCE Ephemeral Decay) + Stage 2 (Snip >15K tokens / 60K chars) +
|
|
1297
|
+
// Stage 1 (Budget Reduction >70%) + Stage 3 (Microcompact) + Stage 4 (Context Collapse >85%)
|
|
1249
1298
|
const compaction = applyProgressiveCompaction(this.messages, MAX_CHAR_POOL, {
|
|
1299
|
+
enableEphemeralDecay: true,
|
|
1300
|
+
ephemeralKeepRecent: 3,
|
|
1301
|
+
ephemeralMinChars: 1200,
|
|
1250
1302
|
budgetKeepRecent: this.config.keepRecentToolResults ?? 8,
|
|
1251
1303
|
collapseKeepRecent: 2
|
|
1252
1304
|
});
|
|
@@ -1381,10 +1433,14 @@ export class AgentLoop {
|
|
|
1381
1433
|
// volatile block kept dead last. Previously just [1] was anchored, so the
|
|
1382
1434
|
// pack catalogue and the whole workspace/memory/skills context were
|
|
1383
1435
|
// re-billed on every step even though they never changed mid-task.
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1436
|
+
// LazyPlaybook: disclose multi-page mandates only when tools from that domain
|
|
1437
|
+
// have been actively invoked or explicitly demanded. Otherwise emit micro-indicators.
|
|
1438
|
+
const observedTools = (this._planSteps || []).map((step) => step.tool);
|
|
1439
|
+
const lazyPlaybookResult = resolveLazyPlaybooks(this.unlockedPacks, observedTools, this.userPrompt);
|
|
1440
|
+
const activePlaybooks = [
|
|
1441
|
+
lazyPlaybookResult.fullPlaybooks,
|
|
1442
|
+
lazyPlaybookResult.microAnnouncements
|
|
1443
|
+
].filter(Boolean).join('\n\n');
|
|
1388
1444
|
// The task brief turns "here are 28 tools" into "here is the order to
|
|
1389
1445
|
// use them in", which is where whole exploratory steps get saved.
|
|
1390
1446
|
const taskBrief = this.taskShape
|
|
@@ -1516,6 +1572,28 @@ export class AgentLoop {
|
|
|
1516
1572
|
// passed, so a run always overshot by one step — with ~9,000-token
|
|
1517
1573
|
// steps a 299,000 ceiling landed near 308,000. Asking first is what
|
|
1518
1574
|
// makes a ceiling mean the number the user typed.
|
|
1575
|
+
// A peer CLI may execute many model steps inside one chat() call.
|
|
1576
|
+
// Pass the remaining hard budget into peers that expose per-step usage.
|
|
1577
|
+
const budget = this.tokenTracker.budget || {};
|
|
1578
|
+
const hardBudget = (budget.enabled && budget.hardStop) ||
|
|
1579
|
+
(Number.isInteger(this.taskTokenLimit) && this.taskTokenLimit > 0);
|
|
1580
|
+
const taskLimit = Number.isInteger(this.taskTokenLimit) && this.taskTokenLimit > 0
|
|
1581
|
+
? this.taskTokenLimit : Number(budget.maxTokensPerTask || 0);
|
|
1582
|
+
const dailyLimit = budget.enabled && budget.hardStop
|
|
1583
|
+
? Number(budget.maxTokensPerDay || 0) : 0;
|
|
1584
|
+
const dailyUsed = hardBudget && dailyLimit > 0
|
|
1585
|
+
? (await this.tokenTracker.getDailyUsage()).totalTokens : 0;
|
|
1586
|
+
const remainingBudget = hardBudget
|
|
1587
|
+
? Math.min(taskLimit > 0 ? taskLimit - this.tokenTracker.taskTokens : Infinity, dailyLimit > 0 ? dailyLimit - dailyUsed : Infinity) : Infinity;
|
|
1588
|
+
if (remainingBudget <= 0) {
|
|
1589
|
+
this.emitEvent({ type: 'budget_warning', message: 'Token budget reached before the next model call.' });
|
|
1590
|
+
break;
|
|
1591
|
+
}
|
|
1592
|
+
// trackUsage reloads persisted settings; restore the per-task profile
|
|
1593
|
+
// limit before the predictive check on each iteration.
|
|
1594
|
+
if (Number.isInteger(this.taskTokenLimit) && this.taskTokenLimit > 0) {
|
|
1595
|
+
this.tokenTracker.budget = { ...budget, enabled: true, hardStop: true, maxTokensPerTask: this.taskTokenLimit };
|
|
1596
|
+
}
|
|
1519
1597
|
const affordability = this.tokenTracker.canAffordAnotherStep();
|
|
1520
1598
|
if (!affordability.allowed) {
|
|
1521
1599
|
this.emitEvent({ type: 'budget_warning', message: affordability.reason });
|
|
@@ -1549,6 +1627,9 @@ export class AgentLoop {
|
|
|
1549
1627
|
taskId: this.taskId,
|
|
1550
1628
|
conversationId: this.memoryManager?.sessionId || this.taskId,
|
|
1551
1629
|
taskIntent: isLaunchOnlyPrompt(this.currentTaskPrompt || this.userPrompt || '') ? 'launch' : 'general',
|
|
1630
|
+
taskArchetype: determineToolScope(this.currentTaskPrompt || this.userPrompt || '', this.taskShape).archetype,
|
|
1631
|
+
maxTokensThisCall: Number.isFinite(remainingBudget) ? remainingBudget : undefined,
|
|
1632
|
+
tokenLimit: Number.isFinite(remainingBudget) ? remainingBudget : Infinity,
|
|
1552
1633
|
workspaceRoot: this.workspaceRoot,
|
|
1553
1634
|
tools: dynamicTools,
|
|
1554
1635
|
// IARS couples escalation to a wider search. Bounded so a stuck task
|
|
@@ -1592,6 +1673,9 @@ export class AgentLoop {
|
|
|
1592
1673
|
if (nativeCode) {
|
|
1593
1674
|
this.emitEvent(nativeCode);
|
|
1594
1675
|
nativeCodeObserver.handle(nativeCode);
|
|
1676
|
+
if (nativeCode.phase === 'done' && ['Creating', 'Editing'].includes(nativeCode.operation)) {
|
|
1677
|
+
this.recordWebArtifact(nativeCode.path);
|
|
1678
|
+
}
|
|
1595
1679
|
}
|
|
1596
1680
|
const detail = action.detail ? ` ${action.detail}` : '';
|
|
1597
1681
|
if (action.status === 'running') {
|
|
@@ -1623,6 +1707,22 @@ export class AgentLoop {
|
|
|
1623
1707
|
// Track tokens. usage carries cachedPromptTokens / cacheWriteTokens so
|
|
1624
1708
|
// the cost estimate reflects the real cache-discounted bill.
|
|
1625
1709
|
const tracking = await this.tokenTracker.trackUsage(response.usage.promptTokens, response.usage.completionTokens, (msg) => this.emitEvent({ type: 'budget_warning', message: msg }), response.usage);
|
|
1710
|
+
// Private numeric telemetry only. The daily ledger aggregates calls,
|
|
1711
|
+
// so it cannot attribute usage to a task or distinguish provider data
|
|
1712
|
+
// from the character-count fallback used by some ACP peers.
|
|
1713
|
+
auditLog.log({
|
|
1714
|
+
event: 'model_usage', scope: 'agent_loop_primary',
|
|
1715
|
+
taskId: this.taskId, step: this.stepsCompleted,
|
|
1716
|
+
provider: this.config.provider || 'unknown',
|
|
1717
|
+
promptTokens: response.usage.promptTokens,
|
|
1718
|
+
completionTokens: response.usage.completionTokens,
|
|
1719
|
+
cachedPromptTokens: response.usage.cachedPromptTokens || 0,
|
|
1720
|
+
measurement: response.usage.measurement || 'unspecified',
|
|
1721
|
+
cacheMeasurement: response.usage.cacheMeasurement || 'unspecified',
|
|
1722
|
+
costBasis: /^(acp(?:\/|$)|antigravity$|agy$)/i.test(String(this.config.provider || ''))
|
|
1723
|
+
? 'external_subscription_unavailable' : 'rate_card_estimate',
|
|
1724
|
+
callEstimatedCostUsd: this.tokenTracker.calculateCost(response.usage.promptTokens, response.usage.completionTokens, response.usage)
|
|
1725
|
+
});
|
|
1626
1726
|
const cachedTokens = response.usage.cachedPromptTokens || 0;
|
|
1627
1727
|
if (cachedTokens > 0) {
|
|
1628
1728
|
this.debugLog(`prompt cache hit: ${cachedTokens.toLocaleString()} of ${response.usage.promptTokens.toLocaleString()} input tokens served from cache`);
|
|
@@ -1709,16 +1809,13 @@ export class AgentLoop {
|
|
|
1709
1809
|
const actionName = String(extAction.name || '').toLowerCase();
|
|
1710
1810
|
const detailPath = typeof extAction.detail === 'string' ? extAction.detail.trim() : '';
|
|
1711
1811
|
if (['write_file', 'write_to_file', 'edit_file', 'replace_file_content', 'multi_replace_file_content', 'fs_write', 'fs_edit', 'multiedit'].includes(actionName) && detailPath) {
|
|
1712
|
-
|
|
1713
|
-
? detailPath
|
|
1714
|
-
: path.resolve(this.workspaceRoot, detailPath.replace(/^~\//, os.homedir() + '/'));
|
|
1715
|
-
if (isScannableFile(resolvedPath)) {
|
|
1716
|
-
this.webArtifacts.add(resolvedPath);
|
|
1717
|
-
}
|
|
1812
|
+
this.recordWebArtifact(detailPath);
|
|
1718
1813
|
}
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
|
|
1814
|
+
// A native action's name is not evidence that a model inspected
|
|
1815
|
+
// pixels. Keep visual verification false unless a real image result
|
|
1816
|
+
// has reached a vision-capable provider.
|
|
1817
|
+
if (['browser_get_dom', 'read_browser_page'].includes(actionName)) {
|
|
1818
|
+
this.webVerificationState.browserActUsed = true;
|
|
1722
1819
|
}
|
|
1723
1820
|
}
|
|
1724
1821
|
}
|
|
@@ -1728,6 +1825,11 @@ export class AgentLoop {
|
|
|
1728
1825
|
const lower = contentText.toLowerCase();
|
|
1729
1826
|
const taskPrompt = (this.currentTaskPrompt || this.userPrompt || '').trim();
|
|
1730
1827
|
const isActionable = isActionableTaskPrompt(taskPrompt);
|
|
1828
|
+
if (isActionable && isGenericHandoffResponse(contentText) && (hasExternalActions || this.stepsCompleted > 0)) {
|
|
1829
|
+
this.emitEvent({ type: 'error', message: 'The provider returned a generic handoff after tool activity. The requested outcome was not verified; no completion is recorded.' });
|
|
1830
|
+
this.memoryManager.saveHistory(this.messages);
|
|
1831
|
+
break;
|
|
1832
|
+
}
|
|
1731
1833
|
// A native workspace action already changed the workspace. Do not
|
|
1732
1834
|
// demand a Causyne tool call for the same work, and do not treat the
|
|
1733
1835
|
// turn as a no-op.
|
|
@@ -1840,9 +1942,6 @@ export class AgentLoop {
|
|
|
1840
1942
|
// consecutiveThinkingSteps, which resets on every tool call, so
|
|
1841
1943
|
// a guard could block completion indefinitely and burn the whole
|
|
1842
1944
|
// step budget on an already-finished task.
|
|
1843
|
-
if (response.content) {
|
|
1844
|
-
this.emitEvent({ type: 'agent_message', content: response.content });
|
|
1845
|
-
}
|
|
1846
1945
|
const isGameTask = !isLaunchOnlyPrompt(taskPrompt) && isGameIntent(taskPrompt);
|
|
1847
1946
|
this.gameToolStats = this.gameToolStats || { godot_act: 0, game_asset_fetch: 0, game_build_html5: 0, last_godot_action: null };
|
|
1848
1947
|
if (isGameTask && !this.gameGuardFired) {
|
|
@@ -1864,18 +1963,30 @@ export class AgentLoop {
|
|
|
1864
1963
|
// This reads the HTML/CSS actually written and scores it. Weighted and
|
|
1865
1964
|
// threshold-based, never a single tripwire: a guard with false
|
|
1866
1965
|
// positives gets switched off (the ZM-09 lesson).
|
|
1867
|
-
if (!
|
|
1868
|
-
this.slopGateFired = true; // fires at most once per task, like the others
|
|
1966
|
+
if (!isLaunchOnlyPrompt(taskPrompt) && isWebIntent(taskPrompt) && this.webArtifacts.size > 0) {
|
|
1869
1967
|
try {
|
|
1870
1968
|
const files = [];
|
|
1871
1969
|
for (const artifactPath of this.webArtifacts) {
|
|
1970
|
+
if (files.length >= 50)
|
|
1971
|
+
break;
|
|
1872
1972
|
try {
|
|
1973
|
+
const stat = fsSync.lstatSync(artifactPath);
|
|
1974
|
+
if (!stat.isFile() || stat.size > 512_000)
|
|
1975
|
+
continue;
|
|
1873
1976
|
files.push({ path: artifactPath, content: fsSync.readFileSync(artifactPath, 'utf8') });
|
|
1874
1977
|
}
|
|
1875
|
-
catch (
|
|
1978
|
+
catch (_error) { /* deleted or moved since: nothing to judge */ }
|
|
1979
|
+
}
|
|
1980
|
+
if (files.length === 0) {
|
|
1981
|
+
this.emitEvent({ type: 'error', message: 'Web design audit could not read the generated files; the result was not verified as complete.' });
|
|
1982
|
+
this.memoryManager.saveHistory(this.messages);
|
|
1983
|
+
break;
|
|
1876
1984
|
}
|
|
1877
1985
|
const result = analyzeFiles(files);
|
|
1878
1986
|
if (result.verdict === 'slop') {
|
|
1987
|
+
const auditHash = createHash('sha256')
|
|
1988
|
+
.update(files.map(file => `${file.path}\0${file.content}`).join('\0'))
|
|
1989
|
+
.digest('hex');
|
|
1879
1990
|
const recent = Array.isArray(this.staticContext?.recentMovements) ? this.staticContext.recentMovements : [];
|
|
1880
1991
|
const brief = formatMovementBrief(suggestMovements(recent, 3));
|
|
1881
1992
|
auditLog.log({
|
|
@@ -1883,8 +1994,16 @@ export class AgentLoop {
|
|
|
1883
1994
|
score: result.score, signals: result.findings.map((f) => f.id)
|
|
1884
1995
|
});
|
|
1885
1996
|
this.emitEvent({ type: 'status', message: `⚡ Anti-Slop Audit: design scored ${result.score}` });
|
|
1997
|
+
if (this.slopReviewAttempts >= 2 || auditHash === this.slopLastAuditHash) {
|
|
1998
|
+
this.emitEvent({ type: 'error', message: `Web design audit still found generic patterns (score ${result.score}); the result was not verified as complete.` });
|
|
1999
|
+
this.memoryManager.saveHistory(this.messages);
|
|
2000
|
+
break;
|
|
2001
|
+
}
|
|
2002
|
+
this.slopReviewAttempts++;
|
|
2003
|
+
this.slopLastAuditHash = auditHash;
|
|
1886
2004
|
this.messages.push({ role: 'system', content: formatFindings(result, brief) });
|
|
1887
2005
|
this.memoryManager.saveHistory(this.messages);
|
|
2006
|
+
continue;
|
|
1888
2007
|
}
|
|
1889
2008
|
if (result.findings.length > 0) {
|
|
1890
2009
|
auditLog.log({
|
|
@@ -1895,8 +2014,10 @@ export class AgentLoop {
|
|
|
1895
2014
|
}
|
|
1896
2015
|
}
|
|
1897
2016
|
catch (e) {
|
|
1898
|
-
|
|
1899
|
-
this.
|
|
2017
|
+
this.debugLog(`anti-slop gate failed: ${e.message}`);
|
|
2018
|
+
this.emitEvent({ type: 'error', message: 'Web design audit failed; the result was not verified as complete.' });
|
|
2019
|
+
this.memoryManager.saveHistory(this.messages);
|
|
2020
|
+
break;
|
|
1900
2021
|
}
|
|
1901
2022
|
}
|
|
1902
2023
|
// Web Visual Validation Guard (Anti-Slop / Transcendence)
|
|
@@ -1913,26 +2034,40 @@ export class AgentLoop {
|
|
|
1913
2034
|
let visionDeclined = false;
|
|
1914
2035
|
let browserReady = false;
|
|
1915
2036
|
let browserDeclined = false;
|
|
2037
|
+
let browserRuntimeError = '';
|
|
1916
2038
|
try {
|
|
1917
2039
|
const { groupStatus, isGroupDeclined } = await import('./provisioning/capabilityProvisioner.js');
|
|
1918
2040
|
visionReady = groupStatus('vision').state === 'ready';
|
|
1919
2041
|
visionDeclined = isGroupDeclined('vision');
|
|
1920
2042
|
browserReady = groupStatus('browser').state === 'ready';
|
|
1921
2043
|
browserDeclined = isGroupDeclined('browser');
|
|
2044
|
+
if (browserReady) {
|
|
2045
|
+
const { resolveBrowserRuntime } = await import('./browser/browserRuntime.js');
|
|
2046
|
+
try {
|
|
2047
|
+
resolveBrowserRuntime();
|
|
2048
|
+
}
|
|
2049
|
+
catch (error) {
|
|
2050
|
+
browserReady = false;
|
|
2051
|
+
browserRuntimeError = error instanceof Error ? error.message : String(error);
|
|
2052
|
+
}
|
|
2053
|
+
}
|
|
1922
2054
|
}
|
|
1923
2055
|
catch (e) { /* treat as not ready */ }
|
|
1924
2056
|
let webGuardMsg = '';
|
|
1925
|
-
if (
|
|
2057
|
+
if (browserRuntimeError) {
|
|
2058
|
+
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.]`;
|
|
2059
|
+
}
|
|
2060
|
+
else if (!browserReady && !browserDeclined) {
|
|
1926
2061
|
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.]`;
|
|
1927
2062
|
}
|
|
1928
2063
|
else if (hasVision && !visionReady && !visionDeclined) {
|
|
1929
2064
|
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.]`;
|
|
1930
2065
|
}
|
|
1931
2066
|
else if (hasVision && visionReady && !this.webVerificationState.screenshotTaken) {
|
|
1932
|
-
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
|
|
2067
|
+
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.]`;
|
|
1933
2068
|
}
|
|
1934
2069
|
else if ((!hasVision || visionDeclined) && browserReady && !this.webVerificationState.browserActUsed && !this.webVerificationState.screenshotTaken) {
|
|
1935
|
-
webGuardMsg = `[
|
|
2070
|
+
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.]`;
|
|
1936
2071
|
}
|
|
1937
2072
|
if (webGuardMsg) {
|
|
1938
2073
|
this.webGuardFired = true;
|
|
@@ -1947,6 +2082,20 @@ export class AgentLoop {
|
|
|
1947
2082
|
}
|
|
1948
2083
|
}
|
|
1949
2084
|
}
|
|
2085
|
+
// Tool availability and a completed plan are not evidence of visual
|
|
2086
|
+
// inspection. A failed browser/capture attempt must not become a
|
|
2087
|
+
// successful task merely because the provider says "verified".
|
|
2088
|
+
if (isWebTask && this.stepsCompleted > 0
|
|
2089
|
+
&& !this.webVerificationState.browserActUsed
|
|
2090
|
+
&& !this.webVerificationState.screenshotTaken) {
|
|
2091
|
+
this.emitEvent({
|
|
2092
|
+
type: 'error',
|
|
2093
|
+
message: 'The web files may have changed, but rendered-page verification did not succeed. The task remains unverified; no completion is recorded.'
|
|
2094
|
+
});
|
|
2095
|
+
auditLog.log({ event: 'task_unverified', taskId: this.taskId, reason: 'web_render_not_inspected' });
|
|
2096
|
+
this.memoryManager.saveHistory(this.messages);
|
|
2097
|
+
break;
|
|
2098
|
+
}
|
|
1950
2099
|
// Cold Observer: Overconfidence & Loop Verification Check
|
|
1951
2100
|
{
|
|
1952
2101
|
try {
|
|
@@ -1979,6 +2128,17 @@ export class AgentLoop {
|
|
|
1979
2128
|
// Cold observer fail-open
|
|
1980
2129
|
}
|
|
1981
2130
|
}
|
|
2131
|
+
if (process.platform === 'darwin' && isDesktopWallpaperChangePrompt(taskPrompt)) {
|
|
2132
|
+
const currentDesktopPictures = readMacDesktopPictures();
|
|
2133
|
+
if (!this.initialDesktopPictures || !currentDesktopPictures || currentDesktopPictures === this.initialDesktopPictures) {
|
|
2134
|
+
this.emitEvent({ type: 'error', message: 'The desktop wallpaper change was not confirmed by macOS readback. The task remains incomplete.' });
|
|
2135
|
+
this.memoryManager.saveHistory(this.messages);
|
|
2136
|
+
break;
|
|
2137
|
+
}
|
|
2138
|
+
}
|
|
2139
|
+
if (response.content) {
|
|
2140
|
+
this.emitEvent({ type: 'agent_message', content: response.content });
|
|
2141
|
+
}
|
|
1982
2142
|
this.emitEvent({ type: 'status', message: 'Task completed.' });
|
|
1983
2143
|
this.memoryManager.saveHistory(this.messages); // Save final state
|
|
1984
2144
|
// The task worked. Keep the route so the next one like it does not
|
|
@@ -2108,69 +2268,39 @@ export class AgentLoop {
|
|
|
2108
2268
|
if (this.recentActionSignatures.length > 20) {
|
|
2109
2269
|
this.recentActionSignatures.shift();
|
|
2110
2270
|
}
|
|
2111
|
-
|
|
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
|
-
}
|
|
2271
|
+
// Universal Intelligent Loop Guard & Stall Breaker (Hermes / Claude Code architecture)
|
|
2159
2272
|
const isExecTask = isExecutionOrLaunchTaskPrompt(this.currentTaskPrompt || this.userPrompt || '');
|
|
2160
2273
|
const isAuthoringTask = !isExecTask && isCodeAuthoringTaskPrompt(this.currentTaskPrompt || this.userPrompt || '');
|
|
2161
|
-
|
|
2274
|
+
const guardDecision = this.stallGuard.beforeCall(functionName, args || {}, {
|
|
2275
|
+
isAuthoringTask
|
|
2276
|
+
});
|
|
2277
|
+
if (guardDecision.action === 'block') {
|
|
2278
|
+
this.emitEvent({ type: 'step_error', tool: functionName, error: guardDecision.message, toolCallId: toolCall.id });
|
|
2279
|
+
auditLog.log({ event: 'tool_blocked', taskId: this.taskId, tool: functionName, args, reason: guardDecision.message });
|
|
2162
2280
|
this.messages.push({
|
|
2163
|
-
role: '
|
|
2164
|
-
|
|
2281
|
+
role: 'tool',
|
|
2282
|
+
tool_call_id: toolCall.id,
|
|
2283
|
+
name: functionName,
|
|
2284
|
+
content: JSON.stringify({
|
|
2285
|
+
success: false,
|
|
2286
|
+
error: guardDecision.code,
|
|
2287
|
+
CRITICAL_INSTRUCTION: guardDecision.message
|
|
2288
|
+
})
|
|
2165
2289
|
});
|
|
2290
|
+
continue;
|
|
2166
2291
|
}
|
|
2167
|
-
if (
|
|
2168
|
-
|
|
2169
|
-
|
|
2170
|
-
auditLog.log({ event: 'task_killed_circuit_breaker', taskId: this.taskId, reason: fatalMsg });
|
|
2292
|
+
if (guardDecision.action === 'halt') {
|
|
2293
|
+
this.emitEvent({ type: 'step_error', tool: functionName, error: guardDecision.message, toolCallId: toolCall.id });
|
|
2294
|
+
auditLog.log({ event: 'task_killed_circuit_breaker', taskId: this.taskId, reason: guardDecision.message });
|
|
2171
2295
|
this.abort();
|
|
2172
2296
|
break;
|
|
2173
2297
|
}
|
|
2298
|
+
if (isAuthoringTask && this.stallGuard.distinctInspectionCount === 12) {
|
|
2299
|
+
this.messages.push({
|
|
2300
|
+
role: 'system',
|
|
2301
|
+
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.]`
|
|
2302
|
+
});
|
|
2303
|
+
}
|
|
2174
2304
|
this.emitEvent({ type: 'step_start', tool: functionName, args: args, toolCallId: toolCall.id });
|
|
2175
2305
|
const codeAction = codeProgressFromAction(functionName, args || {}, toolCall.id);
|
|
2176
2306
|
if (codeAction)
|
|
@@ -2430,15 +2560,6 @@ export class AgentLoop {
|
|
|
2430
2560
|
step: this.stepsCompleted
|
|
2431
2561
|
});
|
|
2432
2562
|
}
|
|
2433
|
-
// P6: remember which rendered surfaces this task touched, so the
|
|
2434
|
-
// anti-slop gate can read the finished result back off disk rather
|
|
2435
|
-
// than trusting the model's own account of what it built.
|
|
2436
|
-
if (['fs_write', 'fs_edit', 'MultiEdit'].includes(functionName)) {
|
|
2437
|
-
const written = args.path || args.file_path;
|
|
2438
|
-
if (typeof written === 'string' && isScannableFile(written)) {
|
|
2439
|
-
this.webArtifacts.add(written.replace(/^~\//, os.homedir() + '/'));
|
|
2440
|
-
}
|
|
2441
|
-
}
|
|
2442
2563
|
// TimeMachine tracks actual failures across tool results and thrown
|
|
2443
2564
|
// errors. It only rewinds reasoning; it never replays side effects.
|
|
2444
2565
|
let result;
|
|
@@ -2484,6 +2605,7 @@ export class AgentLoop {
|
|
|
2484
2605
|
name: functionName, content: JSON.stringify({ ...failure,
|
|
2485
2606
|
errorType, timeMachine: recovery.guidance,
|
|
2486
2607
|
...(alternativeRoute ? { apcReplanAlternative: alternativeRoute.suggestedTool, apcReplanReason: alternativeRoute.reason } : {}) }) });
|
|
2608
|
+
this.stallGuard.observeCall(functionName, args || {}, failure, toolCall.id, true);
|
|
2487
2609
|
this.memoryManager.saveHistory(this.messages);
|
|
2488
2610
|
if (errorType === 'fatal' || recovery.kind === 'stop' || recovery.kind === 'human') {
|
|
2489
2611
|
this.stopRequested = true;
|
|
@@ -2511,13 +2633,16 @@ export class AgentLoop {
|
|
|
2511
2633
|
hookFeedback: (postHook.messages || []).join('\n') || undefined
|
|
2512
2634
|
};
|
|
2513
2635
|
}
|
|
2514
|
-
if (
|
|
2636
|
+
if (result && result.success !== false && !result.error && ['fs_write', 'fs_edit', 'MultiEdit'].includes(functionName)) {
|
|
2637
|
+
this.recordWebArtifact(args.path || args.file_path);
|
|
2638
|
+
}
|
|
2639
|
+
if (['screenshot', 'vision_inspect_ui'].includes(functionName) && this.llm.supportsVision !== false && result?.success === true && result?._is_image_marker === true) {
|
|
2515
2640
|
this.webVerificationState.screenshotTaken = true;
|
|
2516
2641
|
}
|
|
2517
2642
|
if (functionName === 'browser_act' && result?.success === true) {
|
|
2518
|
-
|
|
2519
|
-
if (
|
|
2520
|
-
this.webVerificationState.
|
|
2643
|
+
const browserResults = Array.isArray(result.data) ? result.data : [];
|
|
2644
|
+
if (browserResults.some((item) => ['snapshot', 'scrape'].includes(item?.action))) {
|
|
2645
|
+
this.webVerificationState.browserActUsed = true;
|
|
2521
2646
|
}
|
|
2522
2647
|
}
|
|
2523
2648
|
// The journal is the observer's own record of what actually ran. It
|
|
@@ -2677,7 +2802,7 @@ export class AgentLoop {
|
|
|
2677
2802
|
role: 'tool',
|
|
2678
2803
|
tool_call_id: toolCall.id,
|
|
2679
2804
|
name: functionName,
|
|
2680
|
-
content: `[Image
|
|
2805
|
+
content: `[Image captured: ${result.filename || 'image'} (${result.mimeType || 'image/png'}). This provider cannot receive image pixels; visual inspection was not completed.]`
|
|
2681
2806
|
});
|
|
2682
2807
|
}
|
|
2683
2808
|
else {
|
|
@@ -2807,6 +2932,11 @@ export class AgentLoop {
|
|
|
2807
2932
|
this._observationDigests.set(digest, this.stepsCompleted + 1);
|
|
2808
2933
|
}
|
|
2809
2934
|
}
|
|
2935
|
+
const isCallFailed = Boolean(result && (result.success === false || typeof result.error === 'string'));
|
|
2936
|
+
const stallObservation = this.stallGuard.observeCall(functionName, args || {}, result, toolCall.id, isCallFailed);
|
|
2937
|
+
if (stallObservation.stub && resultString.length >= 256) {
|
|
2938
|
+
resultString = stallObservation.stub;
|
|
2939
|
+
}
|
|
2810
2940
|
this.messages.push({
|
|
2811
2941
|
role: 'tool',
|
|
2812
2942
|
tool_call_id: toolCall.id,
|
|
@@ -2817,6 +2947,19 @@ export class AgentLoop {
|
|
|
2817
2947
|
// stub keep pointing at the spill after the payload is gone.
|
|
2818
2948
|
...(spill ? { spillPath: spill.path } : {})
|
|
2819
2949
|
});
|
|
2950
|
+
if (stallObservation.notice) {
|
|
2951
|
+
this.messages.push({
|
|
2952
|
+
role: 'system',
|
|
2953
|
+
content: stallObservation.notice
|
|
2954
|
+
});
|
|
2955
|
+
}
|
|
2956
|
+
if (stallObservation.decision?.action === 'halt') {
|
|
2957
|
+
const fatalMsg = stallObservation.decision.message;
|
|
2958
|
+
this.emitEvent({ type: 'step_error', tool: functionName, error: fatalMsg, toolCallId: toolCall.id });
|
|
2959
|
+
auditLog.log({ event: 'task_killed_circuit_breaker', taskId: this.taskId, reason: fatalMsg });
|
|
2960
|
+
this.abort();
|
|
2961
|
+
break;
|
|
2962
|
+
}
|
|
2820
2963
|
}
|
|
2821
2964
|
// Save state continuously after each tool loop
|
|
2822
2965
|
this.memoryManager.saveHistory(this.messages);
|
|
@@ -2825,6 +2968,43 @@ export class AgentLoop {
|
|
|
2825
2968
|
}
|
|
2826
2969
|
}
|
|
2827
2970
|
catch (e) {
|
|
2971
|
+
// A peer can fail after completing billable steps. Charge those steps
|
|
2972
|
+
// once even when no final result was returned, including action and
|
|
2973
|
+
// wall-clock limits, before deciding whether recovery is possible.
|
|
2974
|
+
if (e?.partialUsage) {
|
|
2975
|
+
const usage = e.partialUsage;
|
|
2976
|
+
if (usage.promptTokens + usage.completionTokens > 0) {
|
|
2977
|
+
await this.tokenTracker.trackUsage(usage.promptTokens, usage.completionTokens, (message) => this.emitEvent({ type: 'budget_warning', message }), usage);
|
|
2978
|
+
auditLog.log({
|
|
2979
|
+
event: 'model_usage', scope: 'agent_loop_primary', taskId: this.taskId,
|
|
2980
|
+
step: this.stepsCompleted, provider: this.config.provider || 'unknown',
|
|
2981
|
+
promptTokens: usage.promptTokens, completionTokens: usage.completionTokens,
|
|
2982
|
+
cachedPromptTokens: usage.cachedPromptTokens || 0,
|
|
2983
|
+
measurement: 'provider_reported_partial', costBasis: 'external_subscription_unavailable'
|
|
2984
|
+
});
|
|
2985
|
+
}
|
|
2986
|
+
}
|
|
2987
|
+
if (e?.code === 'AGY_TOKEN_BUDGET' || e?.code === 'TASK_TOKEN_BUDGET' || e?.code === 'PROVIDER_TOKEN_BUDGET') {
|
|
2988
|
+
this.emitEvent({ type: 'budget_warning', message: e.message });
|
|
2989
|
+
auditLog.log({ event: 'task_stopped_on_budget', taskId: this.taskId,
|
|
2990
|
+
used: this.tokenTracker.taskTokens, limit: e.tokenLimit || this.tokenTracker.budget?.maxTokensPerTask || 0 });
|
|
2991
|
+
break;
|
|
2992
|
+
}
|
|
2993
|
+
if (e?.code === 'AGY_EXPLORATION_LOOP' || e?.code === 'AGENT_EXPLORATION_LOOP' || e?.code === 'STALL_EXPLORATION_LOOP') {
|
|
2994
|
+
auditLog.log({ event: 'media_exploration_checkpoint', taskId: this.taskId,
|
|
2995
|
+
inspectionCount: e.inspectionCount, recovery: mediaExplorationRecoveries });
|
|
2996
|
+
if (mediaExplorationRecoveries++ === 0) {
|
|
2997
|
+
this.messages.push({ role: 'system', content: '[TASK RECOVERY] Consecutive read-only inspections without workspace changes were paused. ' +
|
|
2998
|
+
'The user requested a concrete change. Reuse the observations already gathered; do not repeat probes. ' +
|
|
2999
|
+
'Make one targeted workspace edit now, then run one focused verification. ' +
|
|
3000
|
+
'If editing is blocked, report the exact blocker. Do not claim completion from inspection alone.' });
|
|
3001
|
+
this.memoryManager.saveHistory(this.messages);
|
|
3002
|
+
this.emitEvent({ type: 'notice', message: 'Repeated inspection paused; continuing once with a direct edit instruction.' });
|
|
3003
|
+
continue;
|
|
3004
|
+
}
|
|
3005
|
+
this.emitEvent({ type: 'error', message: 'The provider continued read-only inspection after a corrective checkpoint. The task remains unfinished; no edit was verified.' });
|
|
3006
|
+
break;
|
|
3007
|
+
}
|
|
2828
3008
|
if (this.stopRequested || this.abortController?.signal?.aborted || e?.name === 'AbortError') {
|
|
2829
3009
|
this.debugLog(`agent loop interrupted: ${e?.message || 'aborted'}`);
|
|
2830
3010
|
auditLog.log({ event: 'task_interrupted', taskId: this.taskId });
|
|
@@ -2929,7 +3109,15 @@ export class AgentLoop {
|
|
|
2929
3109
|
}
|
|
2930
3110
|
// V5: Classify errors for intelligent retry decisions
|
|
2931
3111
|
classifyError(error) {
|
|
2932
|
-
if (error?.code === 'AGY_NATIVE_ACTION_DENIED'
|
|
3112
|
+
if (error?.code === 'AGY_NATIVE_ACTION_DENIED'
|
|
3113
|
+
|| error?.code === 'AGY_NATIVE_ACTION_BUDGET'
|
|
3114
|
+
|| error?.code === 'AGY_DESKTOP_TASK_LIMIT')
|
|
3115
|
+
return 'fatal';
|
|
3116
|
+
// A provider may have charged for completed steps before the turn failed.
|
|
3117
|
+
// Replaying that turn can repeat actions and spend the same tokens again.
|
|
3118
|
+
const spent = Number(error?.partialUsage?.promptTokens || 0)
|
|
3119
|
+
+ Number(error?.partialUsage?.completionTokens || 0);
|
|
3120
|
+
if (spent > 0)
|
|
2933
3121
|
return 'fatal';
|
|
2934
3122
|
const msg = (error.message || '').toLowerCase();
|
|
2935
3123
|
if (msg.includes('syntax') || msg.includes('unexpected token') || msg.includes('invalid json')) {
|