@causyne/agent 1.20.8 → 1.20.9

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@causyne/agent",
3
- "version": "1.20.8",
3
+ "version": "1.20.9",
4
4
  "description": "Agentic AI for software, tools, and computer workflows",
5
5
  "main": "bin/causyne.js",
6
6
  "type": "module",
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';
@@ -48,9 +50,31 @@ export function isActionableTaskPrompt(text) {
48
50
  const pureGreeting = /^(hi|hello|hey|yo|good\s+(morning|afternoon|evening))[.!?, ]*$/i.test(t);
49
51
  if (pureGreeting)
50
52
  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;
53
+ 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
54
  return actionKeywords.test(t);
53
55
  }
56
+ export function isGenericHandoffResponse(text) {
57
+ const answer = (text || '').trim();
58
+ if (!answer || answer.length > 500)
59
+ return false;
60
+ const lower = answer.toLowerCase();
61
+ 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);
62
+ const verifiedOutcome = /\b(completed|changed|set the (desktop|wallpaper)|saved|created|installed|verified|downloaded|finished)\b/i.test(lower);
63
+ return handoff && !verifiedOutcome;
64
+ }
65
+ export function isDesktopWallpaperChangePrompt(text) {
66
+ 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 || '');
67
+ }
68
+ function readMacDesktopPictures() {
69
+ try {
70
+ return execFileSync('osascript', ['-e', 'tell application "System Events" to get picture of every desktop'], {
71
+ encoding: 'utf8', timeout: 4000, stdio: ['ignore', 'pipe', 'ignore']
72
+ }).trim() || null;
73
+ }
74
+ catch {
75
+ return null;
76
+ }
77
+ }
54
78
  export function isExecutionOrLaunchTaskPrompt(text) {
55
79
  const t = (text || '').trim();
56
80
  if (!t)
@@ -153,7 +177,7 @@ ${AGENT_USER_POLICY}
153
177
  Follow the selected project's existing style and architecture. Check dependencies and tool schemas before use. Preserve unrelated behavior.
154
178
 
155
179
  # Operational Guidelines & Communication
156
- - **Language Reflection**: Dynamically reflect and match the exact language used by the user in their prompt. If the user communicates in English, communicate strictly in English. Default language is English. Never use or default to Indonesian unless the user explicitly speaks to you in Indonesian.
180
+ - **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
181
  - **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
182
  - **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
183
  - **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.
@@ -481,7 +505,8 @@ export class AgentLoop {
481
505
  this.webGuardFired = false;
482
506
  // P6: rendered surfaces this task wrote, for the anti-slop gate to read back.
483
507
  this.webArtifacts = new Set();
484
- this.slopGateFired = false;
508
+ this.slopReviewAttempts = 0;
509
+ this.slopLastAuditHash = '';
485
510
  this.gameCascadeState = { active: true, currentStage: 1, stageHistory: [], verificationPassed: false };
486
511
  this.gameToolStats = { godot_act: 0, game_asset_fetch: 0, game_build_html5: 0, last_godot_action: null };
487
512
  this.webVerificationState = { screenshotTaken: false, browserActUsed: false }; // V8 Transcendence: Anti-Slop Guard
@@ -549,6 +574,14 @@ export class AgentLoop {
549
574
  this.unlockOrder.push(packName);
550
575
  return true;
551
576
  }
577
+ recordWebArtifact(candidate) {
578
+ if (typeof candidate !== 'string' || !isScannableFile(candidate))
579
+ return;
580
+ const expanded = candidate.startsWith('~/')
581
+ ? path.join(os.homedir(), candidate.slice(2))
582
+ : candidate;
583
+ this.webArtifacts.add(path.resolve(this.workspaceRoot, expanded));
584
+ }
552
585
  /**
553
586
  * Build the parts of the system context that are constant for a whole task.
554
587
  * Called once per task rather than once per step.
@@ -941,6 +974,8 @@ export class AgentLoop {
941
974
  // awareness instead of burning steps rediscovering it. The result used to be
942
975
  // assigned to a local variable and thrown away.
943
976
  auditLog.log({ event: 'task_start', taskId: this.taskId, request: this.userPrompt });
977
+ this.initialDesktopPictures = process.platform === 'darwin' && isDesktopWallpaperChangePrompt(this.userPrompt || '')
978
+ ? readMacDesktopPictures() : null;
944
979
  // Preserve an explicit workspace selected by the caller (for example ACP).
945
980
  // The constructor already defaults to process.cwd() when none was supplied.
946
981
  coldObserver.beginTask(this.taskId);
@@ -1000,7 +1035,8 @@ export class AgentLoop {
1000
1035
  this.gameGuardFired = false;
1001
1036
  this.webGuardFired = false;
1002
1037
  this.webArtifacts = new Set();
1003
- this.slopGateFired = false;
1038
+ this.slopReviewAttempts = 0;
1039
+ this.slopLastAuditHash = '';
1004
1040
  this.staticContext = null;
1005
1041
  // Plan cache: the procedure THIS task follows, and the template (if any)
1006
1042
  // that was offered to it. Both reset per task — a plan is a property of one
@@ -1031,11 +1067,20 @@ export class AgentLoop {
1031
1067
  // measured budget without making the checkpoint undiscoverable.
1032
1068
  if (this._decisionRequirement.required)
1033
1069
  this.unlockedTools.add('request_decision');
1034
- // Scored routing, with the regex router as a safety net so a pack can
1035
- // never be missed just because it scored below threshold.
1070
+ // SmartToolsUse preloads likely tools but never changes a delegated
1071
+ // subagent's permission scope. A task's intent is a routing hint, not an
1072
+ // authorization boundary: later tool_search results must remain usable.
1073
+ const smartScope = determineToolScope(this.userPrompt, this.taskShape);
1074
+ if (smartScope.toolScope) {
1075
+ for (const tool of smartScope.toolScope)
1076
+ this.unlockedTools.add(tool);
1077
+ this.debugLog(`[SmartToolsUse] preloaded ${smartScope.toolScope.size} tools (${smartScope.archetype})`);
1078
+ }
1079
+ // Scored routing, with the regex router as a safety net, filtered by SmartToolsUse suppression
1036
1080
  const scored = packsFromShape(this.taskShape);
1037
1081
  const fallback = routePacks(this.userPrompt, this.workspaceContext);
1038
- for (const pack of [...scored, ...fallback]) {
1082
+ const candidatePacks = filterSuppressedPacks([...scored, ...fallback], this.userPrompt);
1083
+ for (const pack of candidatePacks) {
1039
1084
  if (pack === 'game' && isDirectGameTask(this.userPrompt))
1040
1085
  continue;
1041
1086
  this.unlockPack(pack);
@@ -1381,10 +1426,14 @@ export class AgentLoop {
1381
1426
  // volatile block kept dead last. Previously just [1] was anchored, so the
1382
1427
  // pack catalogue and the whole workspace/memory/skills context were
1383
1428
  // re-billed on every step even though they never changed mid-task.
1384
- const activePlaybooks = [...this.unlockedPacks]
1385
- .map(pack => PACK_PLAYBOOKS[pack])
1386
- .filter(Boolean)
1387
- .join('\n\n');
1429
+ // LazyPlaybook: disclose multi-page mandates only when tools from that domain
1430
+ // have been actively invoked or explicitly demanded. Otherwise emit micro-indicators.
1431
+ const observedTools = (this._planSteps || []).map((step) => step.tool);
1432
+ const lazyPlaybookResult = resolveLazyPlaybooks(this.unlockedPacks, observedTools, this.userPrompt);
1433
+ const activePlaybooks = [
1434
+ lazyPlaybookResult.fullPlaybooks,
1435
+ lazyPlaybookResult.microAnnouncements
1436
+ ].filter(Boolean).join('\n\n');
1388
1437
  // The task brief turns "here are 28 tools" into "here is the order to
1389
1438
  // use them in", which is where whole exploratory steps get saved.
1390
1439
  const taskBrief = this.taskShape
@@ -1516,6 +1565,28 @@ export class AgentLoop {
1516
1565
  // passed, so a run always overshot by one step — with ~9,000-token
1517
1566
  // steps a 299,000 ceiling landed near 308,000. Asking first is what
1518
1567
  // makes a ceiling mean the number the user typed.
1568
+ // A peer CLI may execute many model steps inside one chat() call.
1569
+ // Pass the remaining hard budget into peers that expose per-step usage.
1570
+ const budget = this.tokenTracker.budget || {};
1571
+ const hardBudget = (budget.enabled && budget.hardStop) ||
1572
+ (Number.isInteger(this.taskTokenLimit) && this.taskTokenLimit > 0);
1573
+ const taskLimit = Number.isInteger(this.taskTokenLimit) && this.taskTokenLimit > 0
1574
+ ? this.taskTokenLimit : Number(budget.maxTokensPerTask || 0);
1575
+ const dailyLimit = budget.enabled && budget.hardStop
1576
+ ? Number(budget.maxTokensPerDay || 0) : 0;
1577
+ const dailyUsed = hardBudget && dailyLimit > 0
1578
+ ? (await this.tokenTracker.getDailyUsage()).totalTokens : 0;
1579
+ const remainingBudget = hardBudget
1580
+ ? Math.min(taskLimit > 0 ? taskLimit - this.tokenTracker.taskTokens : Infinity, dailyLimit > 0 ? dailyLimit - dailyUsed : Infinity) : Infinity;
1581
+ if (remainingBudget <= 0) {
1582
+ this.emitEvent({ type: 'budget_warning', message: 'Token budget reached before the next model call.' });
1583
+ break;
1584
+ }
1585
+ // trackUsage reloads persisted settings; restore the per-task profile
1586
+ // limit before the predictive check on each iteration.
1587
+ if (Number.isInteger(this.taskTokenLimit) && this.taskTokenLimit > 0) {
1588
+ this.tokenTracker.budget = { ...budget, enabled: true, hardStop: true, maxTokensPerTask: this.taskTokenLimit };
1589
+ }
1519
1590
  const affordability = this.tokenTracker.canAffordAnotherStep();
1520
1591
  if (!affordability.allowed) {
1521
1592
  this.emitEvent({ type: 'budget_warning', message: affordability.reason });
@@ -1549,6 +1620,8 @@ export class AgentLoop {
1549
1620
  taskId: this.taskId,
1550
1621
  conversationId: this.memoryManager?.sessionId || this.taskId,
1551
1622
  taskIntent: isLaunchOnlyPrompt(this.currentTaskPrompt || this.userPrompt || '') ? 'launch' : 'general',
1623
+ taskArchetype: determineToolScope(this.currentTaskPrompt || this.userPrompt || '', this.taskShape).archetype,
1624
+ maxTokensThisCall: Number.isFinite(remainingBudget) ? remainingBudget : undefined,
1552
1625
  workspaceRoot: this.workspaceRoot,
1553
1626
  tools: dynamicTools,
1554
1627
  // IARS couples escalation to a wider search. Bounded so a stuck task
@@ -1592,6 +1665,9 @@ export class AgentLoop {
1592
1665
  if (nativeCode) {
1593
1666
  this.emitEvent(nativeCode);
1594
1667
  nativeCodeObserver.handle(nativeCode);
1668
+ if (nativeCode.phase === 'done' && ['Creating', 'Editing'].includes(nativeCode.operation)) {
1669
+ this.recordWebArtifact(nativeCode.path);
1670
+ }
1595
1671
  }
1596
1672
  const detail = action.detail ? ` ${action.detail}` : '';
1597
1673
  if (action.status === 'running') {
@@ -1623,6 +1699,22 @@ export class AgentLoop {
1623
1699
  // Track tokens. usage carries cachedPromptTokens / cacheWriteTokens so
1624
1700
  // the cost estimate reflects the real cache-discounted bill.
1625
1701
  const tracking = await this.tokenTracker.trackUsage(response.usage.promptTokens, response.usage.completionTokens, (msg) => this.emitEvent({ type: 'budget_warning', message: msg }), response.usage);
1702
+ // Private numeric telemetry only. The daily ledger aggregates calls,
1703
+ // so it cannot attribute usage to a task or distinguish provider data
1704
+ // from the character-count fallback used by some ACP peers.
1705
+ auditLog.log({
1706
+ event: 'model_usage', scope: 'agent_loop_primary',
1707
+ taskId: this.taskId, step: this.stepsCompleted,
1708
+ provider: this.config.provider || 'unknown',
1709
+ promptTokens: response.usage.promptTokens,
1710
+ completionTokens: response.usage.completionTokens,
1711
+ cachedPromptTokens: response.usage.cachedPromptTokens || 0,
1712
+ measurement: response.usage.measurement || 'unspecified',
1713
+ cacheMeasurement: response.usage.cacheMeasurement || 'unspecified',
1714
+ costBasis: /^(acp(?:\/|$)|antigravity$|agy$)/i.test(String(this.config.provider || ''))
1715
+ ? 'external_subscription_unavailable' : 'rate_card_estimate',
1716
+ callEstimatedCostUsd: this.tokenTracker.calculateCost(response.usage.promptTokens, response.usage.completionTokens, response.usage)
1717
+ });
1626
1718
  const cachedTokens = response.usage.cachedPromptTokens || 0;
1627
1719
  if (cachedTokens > 0) {
1628
1720
  this.debugLog(`prompt cache hit: ${cachedTokens.toLocaleString()} of ${response.usage.promptTokens.toLocaleString()} input tokens served from cache`);
@@ -1709,12 +1801,7 @@ export class AgentLoop {
1709
1801
  const actionName = String(extAction.name || '').toLowerCase();
1710
1802
  const detailPath = typeof extAction.detail === 'string' ? extAction.detail.trim() : '';
1711
1803
  if (['write_file', 'write_to_file', 'edit_file', 'replace_file_content', 'multi_replace_file_content', 'fs_write', 'fs_edit', 'multiedit'].includes(actionName) && detailPath) {
1712
- const resolvedPath = path.isAbsolute(detailPath)
1713
- ? detailPath
1714
- : path.resolve(this.workspaceRoot, detailPath.replace(/^~\//, os.homedir() + '/'));
1715
- if (isScannableFile(resolvedPath)) {
1716
- this.webArtifacts.add(resolvedPath);
1717
- }
1804
+ this.recordWebArtifact(detailPath);
1718
1805
  }
1719
1806
  if (['capture_browser_screenshot', 'browser_subagent', 'open_browser_url', 'browser_get_dom', 'read_browser_page'].includes(actionName) ||
1720
1807
  ((actionName === 'read_file' || actionName === 'view_file') && /\.(png|jpe?g|webp|gif|svg)$/i.test(detailPath))) {
@@ -1728,6 +1815,11 @@ export class AgentLoop {
1728
1815
  const lower = contentText.toLowerCase();
1729
1816
  const taskPrompt = (this.currentTaskPrompt || this.userPrompt || '').trim();
1730
1817
  const isActionable = isActionableTaskPrompt(taskPrompt);
1818
+ if (isActionable && isGenericHandoffResponse(contentText) && (hasExternalActions || this.stepsCompleted > 0)) {
1819
+ this.emitEvent({ type: 'error', message: 'The provider returned a generic handoff after tool activity. The requested outcome was not verified; no completion is recorded.' });
1820
+ this.memoryManager.saveHistory(this.messages);
1821
+ break;
1822
+ }
1731
1823
  // A native workspace action already changed the workspace. Do not
1732
1824
  // demand a Causyne tool call for the same work, and do not treat the
1733
1825
  // turn as a no-op.
@@ -1840,9 +1932,6 @@ export class AgentLoop {
1840
1932
  // consecutiveThinkingSteps, which resets on every tool call, so
1841
1933
  // a guard could block completion indefinitely and burn the whole
1842
1934
  // step budget on an already-finished task.
1843
- if (response.content) {
1844
- this.emitEvent({ type: 'agent_message', content: response.content });
1845
- }
1846
1935
  const isGameTask = !isLaunchOnlyPrompt(taskPrompt) && isGameIntent(taskPrompt);
1847
1936
  this.gameToolStats = this.gameToolStats || { godot_act: 0, game_asset_fetch: 0, game_build_html5: 0, last_godot_action: null };
1848
1937
  if (isGameTask && !this.gameGuardFired) {
@@ -1864,18 +1953,30 @@ export class AgentLoop {
1864
1953
  // This reads the HTML/CSS actually written and scores it. Weighted and
1865
1954
  // threshold-based, never a single tripwire: a guard with false
1866
1955
  // positives gets switched off (the ZM-09 lesson).
1867
- if (!this.slopGateFired && this.webArtifacts.size > 0) {
1868
- this.slopGateFired = true; // fires at most once per task, like the others
1956
+ if (!isLaunchOnlyPrompt(taskPrompt) && isWebIntent(taskPrompt) && this.webArtifacts.size > 0) {
1869
1957
  try {
1870
1958
  const files = [];
1871
1959
  for (const artifactPath of this.webArtifacts) {
1960
+ if (files.length >= 50)
1961
+ break;
1872
1962
  try {
1963
+ const stat = fsSync.lstatSync(artifactPath);
1964
+ if (!stat.isFile() || stat.size > 512_000)
1965
+ continue;
1873
1966
  files.push({ path: artifactPath, content: fsSync.readFileSync(artifactPath, 'utf8') });
1874
1967
  }
1875
- catch (e) { /* deleted or moved since: nothing to judge */ }
1968
+ catch (_error) { /* deleted or moved since: nothing to judge */ }
1969
+ }
1970
+ if (files.length === 0) {
1971
+ this.emitEvent({ type: 'error', message: 'Web design audit could not read the generated files; the result was not verified as complete.' });
1972
+ this.memoryManager.saveHistory(this.messages);
1973
+ break;
1876
1974
  }
1877
1975
  const result = analyzeFiles(files);
1878
1976
  if (result.verdict === 'slop') {
1977
+ const auditHash = createHash('sha256')
1978
+ .update(files.map(file => `${file.path}\0${file.content}`).join('\0'))
1979
+ .digest('hex');
1879
1980
  const recent = Array.isArray(this.staticContext?.recentMovements) ? this.staticContext.recentMovements : [];
1880
1981
  const brief = formatMovementBrief(suggestMovements(recent, 3));
1881
1982
  auditLog.log({
@@ -1883,8 +1984,16 @@ export class AgentLoop {
1883
1984
  score: result.score, signals: result.findings.map((f) => f.id)
1884
1985
  });
1885
1986
  this.emitEvent({ type: 'status', message: `⚡ Anti-Slop Audit: design scored ${result.score}` });
1987
+ if (this.slopReviewAttempts >= 2 || auditHash === this.slopLastAuditHash) {
1988
+ this.emitEvent({ type: 'error', message: `Web design audit still found generic patterns (score ${result.score}); the result was not verified as complete.` });
1989
+ this.memoryManager.saveHistory(this.messages);
1990
+ break;
1991
+ }
1992
+ this.slopReviewAttempts++;
1993
+ this.slopLastAuditHash = auditHash;
1886
1994
  this.messages.push({ role: 'system', content: formatFindings(result, brief) });
1887
1995
  this.memoryManager.saveHistory(this.messages);
1996
+ continue;
1888
1997
  }
1889
1998
  if (result.findings.length > 0) {
1890
1999
  auditLog.log({
@@ -1895,8 +2004,10 @@ export class AgentLoop {
1895
2004
  }
1896
2005
  }
1897
2006
  catch (e) {
1898
- // A quality gate must never be the reason a task fails.
1899
- this.debugLog(`anti-slop gate skipped: ${e.message}`);
2007
+ this.debugLog(`anti-slop gate failed: ${e.message}`);
2008
+ this.emitEvent({ type: 'error', message: 'Web design audit failed; the result was not verified as complete.' });
2009
+ this.memoryManager.saveHistory(this.messages);
2010
+ break;
1900
2011
  }
1901
2012
  }
1902
2013
  // Web Visual Validation Guard (Anti-Slop / Transcendence)
@@ -1979,6 +2090,17 @@ export class AgentLoop {
1979
2090
  // Cold observer fail-open
1980
2091
  }
1981
2092
  }
2093
+ if (process.platform === 'darwin' && isDesktopWallpaperChangePrompt(taskPrompt)) {
2094
+ const currentDesktopPictures = readMacDesktopPictures();
2095
+ if (!this.initialDesktopPictures || !currentDesktopPictures || currentDesktopPictures === this.initialDesktopPictures) {
2096
+ this.emitEvent({ type: 'error', message: 'The desktop wallpaper change was not confirmed by macOS readback. The task remains incomplete.' });
2097
+ this.memoryManager.saveHistory(this.messages);
2098
+ break;
2099
+ }
2100
+ }
2101
+ if (response.content) {
2102
+ this.emitEvent({ type: 'agent_message', content: response.content });
2103
+ }
1982
2104
  this.emitEvent({ type: 'status', message: 'Task completed.' });
1983
2105
  this.memoryManager.saveHistory(this.messages); // Save final state
1984
2106
  // The task worked. Keep the route so the next one like it does not
@@ -2430,15 +2552,6 @@ export class AgentLoop {
2430
2552
  step: this.stepsCompleted
2431
2553
  });
2432
2554
  }
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
2555
  // TimeMachine tracks actual failures across tool results and thrown
2443
2556
  // errors. It only rewinds reasoning; it never replays side effects.
2444
2557
  let result;
@@ -2511,6 +2624,9 @@ export class AgentLoop {
2511
2624
  hookFeedback: (postHook.messages || []).join('\n') || undefined
2512
2625
  };
2513
2626
  }
2627
+ if (result && result.success !== false && !result.error && ['fs_write', 'fs_edit', 'MultiEdit'].includes(functionName)) {
2628
+ this.recordWebArtifact(args.path || args.file_path);
2629
+ }
2514
2630
  if (functionName === 'screenshot' && result?.success === true && result?._is_image_marker === true) {
2515
2631
  this.webVerificationState.screenshotTaken = true;
2516
2632
  }
@@ -2825,6 +2941,23 @@ export class AgentLoop {
2825
2941
  }
2826
2942
  }
2827
2943
  catch (e) {
2944
+ if (e?.code === 'AGY_TOKEN_BUDGET') {
2945
+ const usage = e.partialUsage;
2946
+ if (usage) {
2947
+ await this.tokenTracker.trackUsage(usage.promptTokens, usage.completionTokens, (message) => this.emitEvent({ type: 'budget_warning', message }), usage);
2948
+ auditLog.log({
2949
+ event: 'model_usage', scope: 'agent_loop_primary', taskId: this.taskId,
2950
+ step: this.stepsCompleted, provider: this.config.provider || 'unknown',
2951
+ promptTokens: usage.promptTokens, completionTokens: usage.completionTokens,
2952
+ cachedPromptTokens: usage.cachedPromptTokens || 0,
2953
+ measurement: 'provider_reported_partial', costBasis: 'external_subscription_unavailable'
2954
+ });
2955
+ }
2956
+ this.emitEvent({ type: 'budget_warning', message: e.message });
2957
+ auditLog.log({ event: 'task_stopped_on_budget', taskId: this.taskId,
2958
+ used: this.tokenTracker.taskTokens, limit: this.tokenTracker.budget?.maxTokensPerTask || 0 });
2959
+ break;
2960
+ }
2828
2961
  if (this.stopRequested || this.abortController?.signal?.aborted || e?.name === 'AbortError') {
2829
2962
  this.debugLog(`agent loop interrupted: ${e?.message || 'aborted'}`);
2830
2963
  auditLog.log({ event: 'task_interrupted', taskId: this.taskId });