@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/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,
@@ -115,10 +121,33 @@ export function isActionableTaskPrompt(text: string): boolean {
115
121
  if (!t) return false;
116
122
  const pureGreeting = /^(hi|hello|hey|yo|good\s+(morning|afternoon|evening))[.!?, ]*$/i.test(t);
117
123
  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;
124
+ 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
125
  return actionKeywords.test(t);
120
126
  }
121
127
 
128
+ export function isGenericHandoffResponse(text: string): boolean {
129
+ const answer = (text || '').trim();
130
+ if (!answer || answer.length > 500) return false;
131
+ const lower = answer.toLowerCase();
132
+ 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);
133
+ const verifiedOutcome = /\b(completed|changed|set the (desktop|wallpaper)|saved|created|installed|verified|downloaded|finished)\b/i.test(lower);
134
+ return handoff && !verifiedOutcome;
135
+ }
136
+
137
+ export function isDesktopWallpaperChangePrompt(text: string): boolean {
138
+ 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 || '');
139
+ }
140
+
141
+ function readMacDesktopPictures(): string | null {
142
+ try {
143
+ return execFileSync('osascript', ['-e', 'tell application "System Events" to get picture of every desktop'], {
144
+ encoding: 'utf8', timeout: 4000, stdio: ['ignore', 'pipe', 'ignore']
145
+ }).trim() || null;
146
+ } catch {
147
+ return null;
148
+ }
149
+ }
150
+
122
151
  export function isExecutionOrLaunchTaskPrompt(text: string): boolean {
123
152
  const t = (text || '').trim();
124
153
  if (!t) return false;
@@ -229,7 +258,7 @@ ${AGENT_USER_POLICY}
229
258
  Follow the selected project's existing style and architecture. Check dependencies and tool schemas before use. Preserve unrelated behavior.
230
259
 
231
260
  # Operational Guidelines & Communication
232
- - **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.
261
+ - **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
262
  - **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
263
  - **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
264
  - **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.
@@ -575,7 +604,8 @@ export class AgentLoop {
575
604
  this.webGuardFired = false;
576
605
  // P6: rendered surfaces this task wrote, for the anti-slop gate to read back.
577
606
  this.webArtifacts = new Set();
578
- this.slopGateFired = false;
607
+ this.slopReviewAttempts = 0;
608
+ this.slopLastAuditHash = '';
579
609
 
580
610
  this.gameCascadeState = { active: true, currentStage: 1, stageHistory: [], verificationPassed: false };
581
611
  this.gameToolStats = { godot_act: 0, game_asset_fetch: 0, game_build_html5: 0, last_godot_action: null };
@@ -650,6 +680,14 @@ export class AgentLoop {
650
680
  return true;
651
681
  }
652
682
 
683
+ recordWebArtifact(candidate: unknown): void {
684
+ if (typeof candidate !== 'string' || !isScannableFile(candidate)) return;
685
+ const expanded = candidate.startsWith('~/')
686
+ ? path.join(os.homedir(), candidate.slice(2))
687
+ : candidate;
688
+ this.webArtifacts.add(path.resolve(this.workspaceRoot, expanded));
689
+ }
690
+
653
691
  /**
654
692
  * Build the parts of the system context that are constant for a whole task.
655
693
  * Called once per task rather than once per step.
@@ -1047,6 +1085,8 @@ export class AgentLoop {
1047
1085
  // awareness instead of burning steps rediscovering it. The result used to be
1048
1086
  // assigned to a local variable and thrown away.
1049
1087
  auditLog.log({ event: 'task_start', taskId: this.taskId, request: this.userPrompt });
1088
+ this.initialDesktopPictures = process.platform === 'darwin' && isDesktopWallpaperChangePrompt(this.userPrompt || '')
1089
+ ? readMacDesktopPictures() : null;
1050
1090
  // Preserve an explicit workspace selected by the caller (for example ACP).
1051
1091
  // The constructor already defaults to process.cwd() when none was supplied.
1052
1092
  coldObserver.beginTask(this.taskId);
@@ -1109,7 +1149,8 @@ export class AgentLoop {
1109
1149
  this.gameGuardFired = false;
1110
1150
  this.webGuardFired = false;
1111
1151
  this.webArtifacts = new Set();
1112
- this.slopGateFired = false;
1152
+ this.slopReviewAttempts = 0;
1153
+ this.slopLastAuditHash = '';
1113
1154
  this.staticContext = null;
1114
1155
  // Plan cache: the procedure THIS task follows, and the template (if any)
1115
1156
  // that was offered to it. Both reset per task — a plan is a property of one
@@ -1144,11 +1185,20 @@ export class AgentLoop {
1144
1185
  // measured budget without making the checkpoint undiscoverable.
1145
1186
  if (this._decisionRequirement.required) this.unlockedTools.add('request_decision');
1146
1187
 
1147
- // Scored routing, with the regex router as a safety net so a pack can
1148
- // never be missed just because it scored below threshold.
1188
+ // SmartToolsUse preloads likely tools but never changes a delegated
1189
+ // subagent's permission scope. A task's intent is a routing hint, not an
1190
+ // authorization boundary: later tool_search results must remain usable.
1191
+ const smartScope = determineToolScope(this.userPrompt, this.taskShape);
1192
+ if (smartScope.toolScope) {
1193
+ for (const tool of smartScope.toolScope) this.unlockedTools.add(tool);
1194
+ this.debugLog(`[SmartToolsUse] preloaded ${smartScope.toolScope.size} tools (${smartScope.archetype})`);
1195
+ }
1196
+
1197
+ // Scored routing, with the regex router as a safety net, filtered by SmartToolsUse suppression
1149
1198
  const scored = packsFromShape(this.taskShape);
1150
1199
  const fallback = routePacks(this.userPrompt, this.workspaceContext);
1151
- for (const pack of [...scored, ...fallback]) {
1200
+ const candidatePacks = filterSuppressedPacks([...scored, ...fallback], this.userPrompt);
1201
+ for (const pack of candidatePacks) {
1152
1202
  if (pack === 'game' && isDirectGameTask(this.userPrompt)) continue;
1153
1203
  this.unlockPack(pack);
1154
1204
  }
@@ -1515,10 +1565,18 @@ export class AgentLoop {
1515
1565
  // volatile block kept dead last. Previously just [1] was anchored, so the
1516
1566
  // pack catalogue and the whole workspace/memory/skills context were
1517
1567
  // re-billed on every step even though they never changed mid-task.
1518
- const activePlaybooks = [...this.unlockedPacks]
1519
- .map(pack => PACK_PLAYBOOKS[pack])
1520
- .filter(Boolean)
1521
- .join('\n\n');
1568
+ // LazyPlaybook: disclose multi-page mandates only when tools from that domain
1569
+ // have been actively invoked or explicitly demanded. Otherwise emit micro-indicators.
1570
+ const observedTools = (this._planSteps || []).map((step: any) => step.tool);
1571
+ const lazyPlaybookResult = resolveLazyPlaybooks(
1572
+ this.unlockedPacks,
1573
+ observedTools,
1574
+ this.userPrompt
1575
+ );
1576
+ const activePlaybooks = [
1577
+ lazyPlaybookResult.fullPlaybooks,
1578
+ lazyPlaybookResult.microAnnouncements
1579
+ ].filter(Boolean).join('\n\n');
1522
1580
 
1523
1581
  // The task brief turns "here are 28 tools" into "here is the order to
1524
1582
  // use them in", which is where whole exploratory steps get saved.
@@ -1660,6 +1718,31 @@ export class AgentLoop {
1660
1718
  // passed, so a run always overshot by one step — with ~9,000-token
1661
1719
  // steps a 299,000 ceiling landed near 308,000. Asking first is what
1662
1720
  // makes a ceiling mean the number the user typed.
1721
+ // A peer CLI may execute many model steps inside one chat() call.
1722
+ // Pass the remaining hard budget into peers that expose per-step usage.
1723
+ const budget = this.tokenTracker.budget || {};
1724
+ const hardBudget = (budget.enabled && budget.hardStop) ||
1725
+ (Number.isInteger(this.taskTokenLimit) && this.taskTokenLimit > 0);
1726
+ const taskLimit = Number.isInteger(this.taskTokenLimit) && this.taskTokenLimit > 0
1727
+ ? this.taskTokenLimit : Number(budget.maxTokensPerTask || 0);
1728
+ const dailyLimit = budget.enabled && budget.hardStop
1729
+ ? Number(budget.maxTokensPerDay || 0) : 0;
1730
+ const dailyUsed = hardBudget && dailyLimit > 0
1731
+ ? (await this.tokenTracker.getDailyUsage()).totalTokens : 0;
1732
+ const remainingBudget = hardBudget
1733
+ ? Math.min(
1734
+ taskLimit > 0 ? taskLimit - this.tokenTracker.taskTokens : Infinity,
1735
+ dailyLimit > 0 ? dailyLimit - dailyUsed : Infinity
1736
+ ) : Infinity;
1737
+ if (remainingBudget <= 0) {
1738
+ this.emitEvent({ type: 'budget_warning', message: 'Token budget reached before the next model call.' });
1739
+ break;
1740
+ }
1741
+ // trackUsage reloads persisted settings; restore the per-task profile
1742
+ // limit before the predictive check on each iteration.
1743
+ if (Number.isInteger(this.taskTokenLimit) && this.taskTokenLimit > 0) {
1744
+ this.tokenTracker.budget = { ...budget, enabled: true, hardStop: true, maxTokensPerTask: this.taskTokenLimit };
1745
+ }
1663
1746
  const affordability = this.tokenTracker.canAffordAnotherStep();
1664
1747
  if (!affordability.allowed) {
1665
1748
  this.emitEvent({ type: 'budget_warning', message: affordability.reason });
@@ -1693,6 +1776,8 @@ export class AgentLoop {
1693
1776
  taskId: this.taskId,
1694
1777
  conversationId: this.memoryManager?.sessionId || this.taskId,
1695
1778
  taskIntent: isLaunchOnlyPrompt(this.currentTaskPrompt || this.userPrompt || '') ? 'launch' : 'general',
1779
+ taskArchetype: determineToolScope(this.currentTaskPrompt || this.userPrompt || '', this.taskShape).archetype,
1780
+ maxTokensThisCall: Number.isFinite(remainingBudget) ? remainingBudget : undefined,
1696
1781
  workspaceRoot: this.workspaceRoot,
1697
1782
  tools: dynamicTools,
1698
1783
  // IARS couples escalation to a wider search. Bounded so a stuck task
@@ -1736,6 +1821,9 @@ export class AgentLoop {
1736
1821
  if (nativeCode) {
1737
1822
  this.emitEvent(nativeCode);
1738
1823
  nativeCodeObserver.handle(nativeCode);
1824
+ if (nativeCode.phase === 'done' && ['Creating', 'Editing'].includes(nativeCode.operation)) {
1825
+ this.recordWebArtifact(nativeCode.path);
1826
+ }
1739
1827
  }
1740
1828
  const detail = action.detail ? ` ${action.detail}` : '';
1741
1829
  if (action.status === 'running') {
@@ -1774,6 +1862,25 @@ export class AgentLoop {
1774
1862
  response.usage
1775
1863
  );
1776
1864
 
1865
+ // Private numeric telemetry only. The daily ledger aggregates calls,
1866
+ // so it cannot attribute usage to a task or distinguish provider data
1867
+ // from the character-count fallback used by some ACP peers.
1868
+ auditLog.log({
1869
+ event: 'model_usage', scope: 'agent_loop_primary',
1870
+ taskId: this.taskId, step: this.stepsCompleted,
1871
+ provider: this.config.provider || 'unknown',
1872
+ promptTokens: response.usage.promptTokens,
1873
+ completionTokens: response.usage.completionTokens,
1874
+ cachedPromptTokens: response.usage.cachedPromptTokens || 0,
1875
+ measurement: response.usage.measurement || 'unspecified',
1876
+ cacheMeasurement: response.usage.cacheMeasurement || 'unspecified',
1877
+ costBasis: /^(acp(?:\/|$)|antigravity$|agy$)/i.test(String(this.config.provider || ''))
1878
+ ? 'external_subscription_unavailable' : 'rate_card_estimate',
1879
+ callEstimatedCostUsd: this.tokenTracker.calculateCost(
1880
+ response.usage.promptTokens, response.usage.completionTokens, response.usage
1881
+ )
1882
+ });
1883
+
1777
1884
  const cachedTokens = response.usage.cachedPromptTokens || 0;
1778
1885
  if (cachedTokens > 0) {
1779
1886
  this.debugLog(`prompt cache hit: ${cachedTokens.toLocaleString()} of ${response.usage.promptTokens.toLocaleString()} input tokens served from cache`);
@@ -1869,12 +1976,7 @@ export class AgentLoop {
1869
1976
  const actionName = String(extAction.name || '').toLowerCase();
1870
1977
  const detailPath = typeof extAction.detail === 'string' ? extAction.detail.trim() : '';
1871
1978
  if (['write_file', 'write_to_file', 'edit_file', 'replace_file_content', 'multi_replace_file_content', 'fs_write', 'fs_edit', 'multiedit'].includes(actionName) && detailPath) {
1872
- const resolvedPath = path.isAbsolute(detailPath)
1873
- ? detailPath
1874
- : path.resolve(this.workspaceRoot, detailPath.replace(/^~\//, os.homedir() + '/'));
1875
- if (isScannableFile(resolvedPath)) {
1876
- this.webArtifacts.add(resolvedPath);
1877
- }
1979
+ this.recordWebArtifact(detailPath);
1878
1980
  }
1879
1981
  if (
1880
1982
  ['capture_browser_screenshot', 'browser_subagent', 'open_browser_url', 'browser_get_dom', 'read_browser_page'].includes(actionName) ||
@@ -1892,6 +1994,12 @@ export class AgentLoop {
1892
1994
  const taskPrompt = (this.currentTaskPrompt || this.userPrompt || '').trim();
1893
1995
  const isActionable = isActionableTaskPrompt(taskPrompt);
1894
1996
 
1997
+ if (isActionable && isGenericHandoffResponse(contentText) && (hasExternalActions || this.stepsCompleted > 0)) {
1998
+ this.emitEvent({ type: 'error', message: 'The provider returned a generic handoff after tool activity. The requested outcome was not verified; no completion is recorded.' });
1999
+ this.memoryManager.saveHistory(this.messages);
2000
+ break;
2001
+ }
2002
+
1895
2003
  // A native workspace action already changed the workspace. Do not
1896
2004
  // demand a Causyne tool call for the same work, and do not treat the
1897
2005
  // turn as a no-op.
@@ -2013,10 +2121,6 @@ export class AgentLoop {
2013
2121
  // consecutiveThinkingSteps, which resets on every tool call, so
2014
2122
  // a guard could block completion indefinitely and burn the whole
2015
2123
  // step budget on an already-finished task.
2016
- if (response.content) {
2017
- this.emitEvent({ type: 'agent_message', content: response.content });
2018
- }
2019
-
2020
2124
  const isGameTask = !isLaunchOnlyPrompt(taskPrompt) && isGameIntent(taskPrompt);
2021
2125
 
2022
2126
  this.gameToolStats = this.gameToolStats || { godot_act: 0, game_asset_fetch: 0, game_build_html5: 0, last_godot_action: null };
@@ -2044,18 +2148,29 @@ export class AgentLoop {
2044
2148
  // This reads the HTML/CSS actually written and scores it. Weighted and
2045
2149
  // threshold-based, never a single tripwire: a guard with false
2046
2150
  // positives gets switched off (the ZM-09 lesson).
2047
- if (!this.slopGateFired && this.webArtifacts.size > 0) {
2048
- this.slopGateFired = true; // fires at most once per task, like the others
2151
+ if (!isLaunchOnlyPrompt(taskPrompt) && isWebIntent(taskPrompt) && this.webArtifacts.size > 0) {
2049
2152
  try {
2050
- const files = [];
2153
+ const files: Array<{ path: string; content: string }> = [];
2051
2154
  for (const artifactPath of this.webArtifacts) {
2155
+ if (files.length >= 50) break;
2052
2156
  try {
2157
+ const stat = fsSync.lstatSync(artifactPath);
2158
+ if (!stat.isFile() || stat.size > 512_000) continue;
2053
2159
  files.push({ path: artifactPath, content: fsSync.readFileSync(artifactPath, 'utf8') });
2054
- } catch (e: any) { /* deleted or moved since: nothing to judge */ }
2160
+ } catch (_error: unknown) { /* deleted or moved since: nothing to judge */ }
2161
+ }
2162
+
2163
+ if (files.length === 0) {
2164
+ this.emitEvent({ type: 'error', message: 'Web design audit could not read the generated files; the result was not verified as complete.' });
2165
+ this.memoryManager.saveHistory(this.messages);
2166
+ break;
2055
2167
  }
2056
2168
 
2057
2169
  const result = analyzeFiles(files);
2058
2170
  if (result.verdict === 'slop') {
2171
+ const auditHash = createHash('sha256')
2172
+ .update(files.map(file => `${file.path}\0${file.content}`).join('\0'))
2173
+ .digest('hex');
2059
2174
  const recent = Array.isArray(this.staticContext?.recentMovements) ? this.staticContext.recentMovements : [];
2060
2175
  const brief = formatMovementBrief(suggestMovements(recent, 3));
2061
2176
 
@@ -2064,8 +2179,16 @@ export class AgentLoop {
2064
2179
  score: result.score, signals: result.findings.map((f: any) => f.id)
2065
2180
  });
2066
2181
  this.emitEvent({ type: 'status', message: `⚡ Anti-Slop Audit: design scored ${result.score}` });
2182
+ if (this.slopReviewAttempts >= 2 || auditHash === this.slopLastAuditHash) {
2183
+ this.emitEvent({ type: 'error', message: `Web design audit still found generic patterns (score ${result.score}); the result was not verified as complete.` });
2184
+ this.memoryManager.saveHistory(this.messages);
2185
+ break;
2186
+ }
2187
+ this.slopReviewAttempts++;
2188
+ this.slopLastAuditHash = auditHash;
2067
2189
  this.messages.push({ role: 'system', content: formatFindings(result, brief) });
2068
2190
  this.memoryManager.saveHistory(this.messages);
2191
+ continue;
2069
2192
  }
2070
2193
 
2071
2194
  if (result.findings.length > 0) {
@@ -2076,8 +2199,10 @@ export class AgentLoop {
2076
2199
  });
2077
2200
  }
2078
2201
  } catch (e: any) {
2079
- // A quality gate must never be the reason a task fails.
2080
- this.debugLog(`anti-slop gate skipped: ${e.message}`);
2202
+ this.debugLog(`anti-slop gate failed: ${e.message}`);
2203
+ this.emitEvent({ type: 'error', message: 'Web design audit failed; the result was not verified as complete.' });
2204
+ this.memoryManager.saveHistory(this.messages);
2205
+ break;
2081
2206
  }
2082
2207
  }
2083
2208
 
@@ -2162,6 +2287,18 @@ export class AgentLoop {
2162
2287
  }
2163
2288
  }
2164
2289
 
2290
+ if (process.platform === 'darwin' && isDesktopWallpaperChangePrompt(taskPrompt)) {
2291
+ const currentDesktopPictures = readMacDesktopPictures();
2292
+ if (!this.initialDesktopPictures || !currentDesktopPictures || currentDesktopPictures === this.initialDesktopPictures) {
2293
+ this.emitEvent({ type: 'error', message: 'The desktop wallpaper change was not confirmed by macOS readback. The task remains incomplete.' });
2294
+ this.memoryManager.saveHistory(this.messages);
2295
+ break;
2296
+ }
2297
+ }
2298
+
2299
+ if (response.content) {
2300
+ this.emitEvent({ type: 'agent_message', content: response.content });
2301
+ }
2165
2302
  this.emitEvent({ type: 'status', message: 'Task completed.' });
2166
2303
  this.memoryManager.saveHistory(this.messages); // Save final state
2167
2304
 
@@ -2653,16 +2790,6 @@ export class AgentLoop {
2653
2790
  });
2654
2791
  }
2655
2792
 
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
2793
  // TimeMachine tracks actual failures across tool results and thrown
2667
2794
  // errors. It only rewinds reasoning; it never replays side effects.
2668
2795
  let result;
@@ -2740,6 +2867,10 @@ export class AgentLoop {
2740
2867
  };
2741
2868
  }
2742
2869
 
2870
+ if (result && result.success !== false && !result.error && ['fs_write', 'fs_edit', 'MultiEdit'].includes(functionName)) {
2871
+ this.recordWebArtifact(args.path || args.file_path);
2872
+ }
2873
+
2743
2874
  if (functionName === 'screenshot' && result?.success === true && result?._is_image_marker === true) {
2744
2875
  this.webVerificationState.screenshotTaken = true;
2745
2876
  }
@@ -3072,6 +3203,26 @@ export class AgentLoop {
3072
3203
  }
3073
3204
 
3074
3205
  } catch (e: any) {
3206
+ if (e?.code === 'AGY_TOKEN_BUDGET') {
3207
+ const usage = e.partialUsage;
3208
+ if (usage) {
3209
+ await this.tokenTracker.trackUsage(
3210
+ usage.promptTokens, usage.completionTokens,
3211
+ (message: string) => this.emitEvent({ type: 'budget_warning', message }), usage
3212
+ );
3213
+ auditLog.log({
3214
+ event: 'model_usage', scope: 'agent_loop_primary', taskId: this.taskId,
3215
+ step: this.stepsCompleted, provider: this.config.provider || 'unknown',
3216
+ promptTokens: usage.promptTokens, completionTokens: usage.completionTokens,
3217
+ cachedPromptTokens: usage.cachedPromptTokens || 0,
3218
+ measurement: 'provider_reported_partial', costBasis: 'external_subscription_unavailable'
3219
+ });
3220
+ }
3221
+ this.emitEvent({ type: 'budget_warning', message: e.message });
3222
+ auditLog.log({ event: 'task_stopped_on_budget', taskId: this.taskId,
3223
+ used: this.tokenTracker.taskTokens, limit: this.tokenTracker.budget?.maxTokensPerTask || 0 });
3224
+ break;
3225
+ }
3075
3226
  if (this.stopRequested || this.abortController?.signal?.aborted || e?.name === 'AbortError') {
3076
3227
  this.debugLog(`agent loop interrupted: ${e?.message || 'aborted'}`);
3077
3228
  auditLog.log({ event: 'task_interrupted', taskId: this.taskId });