@causyne/agent 1.20.19 → 1.20.22

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/bin/causyne.js CHANGED
@@ -8,7 +8,13 @@ try {
8
8
  const { startUpdateChecker } = await import('../src/autoUpdate.js');
9
9
  const update = await startUpdateChecker();
10
10
  if (update && update.updated) {
11
- process.stderr.write(`Causyne updated to ${update.latest}. Starting the new version.\n`);
11
+ process.stderr.write(`Causyne Agent updated to ${update.latest}. Restarting...\n`);
12
+ const { spawnSync } = await import('node:child_process');
13
+ const child = spawnSync(process.execPath, process.argv.slice(1), {
14
+ stdio: 'inherit',
15
+ env: process.env
16
+ });
17
+ process.exit(child.status ?? 0);
12
18
  }
13
19
  await import('../src/entrypoint.js');
14
20
  } catch (error) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@causyne/agent",
3
- "version": "1.20.19",
3
+ "version": "1.20.22",
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
@@ -60,7 +60,17 @@ import { StallGuardController } from './stallGuard.js';
60
60
  import { buildRecoverableDroppedSummary, pruneStaleToolObservations, shortenOversizedToolObservations, pruneExecutedToolArguments } from './historyPruner.js';
61
61
  import { isOutputRecoveryRead } from './outputRecovery.js';
62
62
  import { isPlanReviewHandoff, isPlanningOnlyRequest } from './taskContinuation.js';
63
- import { UnifiedBudgetEnforcer, EfficiencyCheckpoint, actionLimitFor, tokenLimitFor, turnTokenLimitFor, noncachedTokens } from './providers/budgetEnforcer.js';
63
+ export function noncachedTokens(usage) {
64
+ if (!usage)
65
+ return 0;
66
+ const finite = (value) => Number.isFinite(value) ? Math.max(0, value ?? 0) : 0;
67
+ const input = usage.uncachedPromptTokens !== undefined
68
+ ? finite(usage.uncachedPromptTokens)
69
+ : finite(usage.cachedPromptTokens) > finite(usage.promptTokens)
70
+ ? finite(usage.promptTokens)
71
+ : Math.max(0, finite(usage.promptTokens) - finite(usage.cachedPromptTokens));
72
+ return input + finite(usage.completionTokens);
73
+ }
64
74
  export function isActionableTaskPrompt(text) {
65
75
  const t = (text || '').trim();
66
76
  if (!t)
@@ -982,7 +992,7 @@ export class AgentLoop {
982
992
  return prefetched;
983
993
  const eligible = [];
984
994
  for (const toolCall of toolCalls) {
985
- const capacity = Math.min(this.smartToolsGovernor?.inspectionCapacity ?? 2, this.efficiencyBudget?.getRemainingActions() ?? 35);
995
+ const capacity = this.smartToolsGovernor?.inspectionCapacity ?? 2;
986
996
  if (eligible.length >= capacity)
987
997
  break;
988
998
  const functionName = canonicalToolName(toolCall.function.name);
@@ -1162,9 +1172,6 @@ export class AgentLoop {
1162
1172
  throw new Error('The requested ACP file operation was not authorized');
1163
1173
  if (tool === 'fs_write')
1164
1174
  captureBeforeMutation(tool, args, { taskId: this.taskId, step: this.stepsCompleted });
1165
- if (!this._inModelCall) {
1166
- this.efficiencyBudget?.recordAction(`peer-file:${tool}:${target}`);
1167
- }
1168
1175
  let result;
1169
1176
  if (tool === 'fs_read') {
1170
1177
  // ACP expects the actual requested text, not the host tool's paging
@@ -1729,18 +1736,7 @@ export class AgentLoop {
1729
1736
  if (!this.currentTaskPrompt && this.userPrompt) {
1730
1737
  this.currentTaskPrompt = this.userPrompt;
1731
1738
  }
1732
- const turnArchetype = determineToolScope(effectivePrompt, this.taskShape).archetype;
1733
- const efficiency = this.config.efficiency || {};
1734
- const taskTokenCeiling = Number.isInteger(this.taskTokenLimit) && this.taskTokenLimit > 0
1735
- ? this.taskTokenLimit
1736
- : this.tokenTracker.budget?.enabled && Number.isFinite(this.tokenTracker.budget?.maxTokensPerTask) && this.tokenTracker.budget.maxTokensPerTask > 0
1737
- ? this.tokenTracker.budget.maxTokensPerTask
1738
- : Number.isFinite(efficiency.maxTaskTokens) && efficiency.maxTaskTokens > 0
1739
- ? efficiency.maxTaskTokens
1740
- : tokenLimitFor(turnArchetype);
1741
- this.efficiencyBudget = new UnifiedBudgetEnforcer(Number.isFinite(efficiency.maxTurnTokens) && efficiency.maxTurnTokens > 0
1742
- ? efficiency.maxTurnTokens
1743
- : turnTokenLimitFor(turnArchetype), Number.isSafeInteger(efficiency.maxTurnActions) && efficiency.maxTurnActions > 0 ? efficiency.maxTurnActions : actionLimitFor(turnArchetype), taskTokenCeiling);
1739
+ const isAutonomousMode = (this.config.autonomyMode || 'C') === 'C';
1744
1740
  const recoveryPaths = new Set();
1745
1741
  let modelCallIndex = 0;
1746
1742
  let mediaExplorationRecoveries = 0;
@@ -2107,7 +2103,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2107
2103
  const configuredRemainingBudget = hardBudget
2108
2104
  ? Math.min(taskLimit > 0 ? taskLimit - this.tokenTracker.taskTokens : Infinity, dailyLimit > 0 ? dailyLimit - dailyUsed : Infinity) : Infinity;
2109
2105
  const remainingBudget = hardBudget
2110
- ? Math.min(configuredRemainingBudget, this.efficiencyBudget.getRemainingTokens())
2106
+ ? configuredRemainingBudget
2111
2107
  : Infinity;
2112
2108
  if (hardBudget && remainingBudget <= 0) {
2113
2109
  this.emitEvent({ type: 'budget_warning', message: 'Token budget reached before the next model call.' });
@@ -2142,9 +2138,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2142
2138
  pruneExecutedToolArguments(this.messages, { threshold: 1500, taskId: this.taskId });
2143
2139
  const stepScale = Math.max(this.tokenTracker.largestStepTokens || 50_000, 100_000);
2144
2140
  const extraTokens = Math.max(stepScale * 10, 1_000_000);
2145
- const extraActions = Math.max(Math.ceil((this.efficiencyBudget?.getRemainingActions() ?? 50) + 100), 100);
2146
2141
  this.tokenTracker.extendBudget(extraTokens);
2147
- this.efficiencyBudget?.extendBudget?.(extraTokens, extraActions);
2148
2142
  }
2149
2143
  }
2150
2144
  // 2. PLAN (Call LLM). dynamicTools was resolved above so the task brief
@@ -2185,7 +2179,6 @@ You are operating in a text-and-code modality without direct image pixel renderi
2185
2179
  this.emitEvent({ type: 'agent_activity', activity: 'Thinking…' });
2186
2180
  const planStepStart = performance.now();
2187
2181
  const nativeControl = new AbortController();
2188
- let nativeCheckpoint = null;
2189
2182
  const invocation = ++modelCallIndex;
2190
2183
  this._inModelCall = true;
2191
2184
  const response = await this.llm.chat(prunedMessages, {
@@ -2197,8 +2190,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2197
2190
  maxTokensThisCall: Number.isFinite(configuredRemainingBudget) && hardBudget ? configuredRemainingBudget : undefined,
2198
2191
  tokenBudgetBasis: Number.isFinite(configuredRemainingBudget) ? 'total' : 'noncached',
2199
2192
  tokenLimit: hardBudget && Number.isFinite(remainingBudget) && remainingBudget > 0
2200
- ? Math.min(this.efficiencyBudget.maxTurnTokens, remainingBudget) : this.efficiencyBudget.maxTurnTokens,
2201
- maxNativeActions: this.efficiencyBudget.getRemainingActions(),
2193
+ ? remainingBudget : undefined,
2202
2194
  workspaceRoot: this.workspaceRoot,
2203
2195
  onPeerPermission: (request) => this.requestPeerPermission(request),
2204
2196
  onPeerFileRead: (file, options) => this.executePeerFile('fs_read', file, undefined, options),
@@ -2292,19 +2284,6 @@ You are operating in a text-and-code modality without direct image pixel renderi
2292
2284
  auditLog.log({ event: 'native_action', taskId: this.taskId,
2293
2285
  provider: this.config.provider || 'unknown', tool: action.name, status: action.status,
2294
2286
  ...(action.id ? { actionId: action.id } : {}) });
2295
- if (action.status === 'running' && !isChecklistTool) {
2296
- try {
2297
- this.efficiencyBudget.recordAction(`${invocation}:${action.id || `${action.name}:${action.detail || ''}`}`);
2298
- }
2299
- catch (error) {
2300
- if (error instanceof EfficiencyCheckpoint) {
2301
- finalizeReasoningSegment();
2302
- nativeCheckpoint = error;
2303
- nativeControl.abort();
2304
- }
2305
- return;
2306
- }
2307
- }
2308
2287
  if (action.status === 'completed' && action.id && !isChecklistTool) {
2309
2288
  completedNativeActionIds.add(String(action.id));
2310
2289
  }
@@ -2424,22 +2403,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2424
2403
  }
2425
2404
  throw checkpoint;
2426
2405
  }
2427
- if (nativeCheckpoint) {
2428
- if (completedNativeActionIds.size > 0) {
2429
- this.stepsCompleted += completedNativeActionIds.size;
2430
- }
2431
- if (reasoningAccumulated) {
2432
- this.messages.push({
2433
- role: 'assistant',
2434
- content: 'Turn paused at efficiency checkpoint.',
2435
- reasoning_content: reasoningAccumulated
2436
- });
2437
- }
2438
- if (error && typeof error === 'object' && 'partialUsage' in error) {
2439
- Object.assign(nativeCheckpoint, { partialUsage: error.partialUsage });
2440
- }
2441
- }
2442
- throw nativeCheckpoint || error;
2406
+ throw error;
2443
2407
  })
2444
2408
  .finally(() => {
2445
2409
  finalizeReasoningSegment();
@@ -2486,10 +2450,6 @@ You are operating in a text-and-code modality without direct image pixel renderi
2486
2450
  ? 'external_subscription_unavailable' : 'rate_card_estimate',
2487
2451
  callEstimatedCostUsd: this.tokenTracker.calculateCost(response.usage.promptTokens, response.usage.completionTokens, response.usage)
2488
2452
  });
2489
- this.efficiencyBudget.recordUsage(response.usage);
2490
- for (const action of response.externalActions || []) {
2491
- this.efficiencyBudget.recordAction(`${invocation}:${action.id || `${action.name}:${action.detail || ''}`}`);
2492
- }
2493
2453
  const cachedTokens = response.usage.cachedPromptTokens || 0;
2494
2454
  if (cachedTokens > 0) {
2495
2455
  this.debugLog(`prompt cache hit: ${cachedTokens.toLocaleString()} of ${response.usage.promptTokens.toLocaleString()} input tokens served from cache`);
@@ -3581,7 +3541,6 @@ You are operating in a text-and-code modality without direct image pixel renderi
3581
3541
  // errors. It only rewinds reasoning; it never replays side effects.
3582
3542
  let result;
3583
3543
  let duration;
3584
- this.efficiencyBudget.recordAction();
3585
3544
  try {
3586
3545
  const startTime = Date.now();
3587
3546
  const actStart = performance.now();
@@ -4000,15 +3959,6 @@ You are operating in a text-and-code modality without direct image pixel renderi
4000
3959
  cachedPromptTokens: usage.cachedPromptTokens || 0,
4001
3960
  measurement: 'provider_reported_partial', costBasis: 'external_subscription_unavailable'
4002
3961
  });
4003
- try {
4004
- this.efficiencyBudget.recordUsage(usage);
4005
- }
4006
- catch (checkpoint) {
4007
- if (checkpoint instanceof EfficiencyCheckpoint)
4008
- e = checkpoint;
4009
- else
4010
- throw checkpoint;
4011
- }
4012
3962
  }
4013
3963
  }
4014
3964
  if (e instanceof RetryConsentCheckpoint && this._pendingConsent) {
@@ -4023,40 +3973,26 @@ You are operating in a text-and-code modality without direct image pixel renderi
4023
3973
  this.memoryManager.saveHistory(this.messages);
4024
3974
  continue;
4025
3975
  }
4026
- const isTokenCheckpoint = e instanceof EfficiencyCheckpoint && e.scope === 'turn' && e.reason === 'tokens';
4027
- const isHardBudget = (Number.isInteger(this.taskTokenLimit) && this.taskTokenLimit > 0)
4028
- || (this.tokenTracker.budget?.enabled === true && this.tokenTracker.budget?.hardStop === true);
4029
- const isDesktopLimit = e?.code === 'AGY_DESKTOP_TASK_LIMIT';
4030
- if (isTokenCheckpoint && !isHardBudget && !isDesktopLimit && incompleteTurnContinuations < 5) {
4031
- incompleteTurnContinuations++;
4032
- this.emitEvent({ type: 'budget_warning', message: e.message });
4033
- auditLog.log({
4034
- event: 'efficiency_checkpoint',
4035
- taskId: this.taskId,
4036
- reason: e?.reason || e?.code || 'budget',
4037
- ...this.efficiencyBudget.snapshot()
4038
- });
4039
- const stepScale = Math.max(this.tokenTracker.largestStepTokens || 50_000, 100_000);
4040
- const extraTokens = Math.max(stepScale * 10, 1_000_000);
4041
- const extraActions = Math.max(Math.ceil((this.efficiencyBudget?.getRemainingActions() ?? 50) + 100), 100);
4042
- this.tokenTracker.extendBudget(extraTokens);
4043
- this.efficiencyBudget.extendBudget?.(extraTokens, extraActions);
4044
- compactSessionMessages(this.messages, {
4045
- keepRecentTurns: 4,
4046
- taskId: this.taskId,
4047
- originalPrompt: this.currentTaskPrompt || this.userPrompt
4048
- });
4049
- this.emitEvent({ type: 'status', message: `Continuing task execution from efficiency checkpoint (runway extended +${extraActions} actions)…` });
4050
- this.emitEvent({ type: 'agent_activity', activity: 'Continuing task from efficiency checkpoint…' });
4051
- this.messages.push({
4052
- role: 'system',
4053
- content: `[EFFICIENCY CONTINUATION: Previous turn paused at checkpoint (${e.message}). Autonomous runway extended (+${extraActions} actions). Session history and disk modifications are preserved. Do NOT replay prior actions. Continue executing the task directly.]`
4054
- });
4055
- this.memoryManager.saveHistory(this.messages);
4056
- continue;
4057
- }
4058
- if (e instanceof EfficiencyCheckpoint || e?.code === 'TASK_TOKEN_BUDGET' || e?.code === 'PROVIDER_TOKEN_BUDGET'
3976
+ if (e?.code === 'TASK_TOKEN_BUDGET' || e?.code === 'PROVIDER_TOKEN_BUDGET'
4059
3977
  || e?.code === 'AGY_DESKTOP_TASK_LIMIT' || e?.code === 'AGY_TOKEN_BUDGET' || e?.code === 'AGY_NATIVE_ACTION_BUDGET') {
3978
+ const isExplicitHardBudget = (Number.isInteger(this.taskTokenLimit) && this.taskTokenLimit > 0)
3979
+ || (this.tokenTracker.budget?.enabled === true && this.tokenTracker.budget?.hardStop === true);
3980
+ if (this.config.autonomyMode === 'C' && !isExplicitHardBudget) {
3981
+ this.emitEvent({ type: 'budget_warning', message: e.message });
3982
+ pruneStaleToolObservations(this.messages, { keepRecent: 3, minChars: 300, taskId: this.taskId });
3983
+ shortenOversizedToolObservations(this.messages, { threshold: 1500, taskId: this.taskId });
3984
+ pruneExecutedToolArguments(this.messages, { threshold: 1500, taskId: this.taskId });
3985
+ const stepScale = Math.max(this.tokenTracker.largestStepTokens || 50_000, 100_000);
3986
+ const extraTokens = Math.max(stepScale * 10, 1_000_000);
3987
+ this.tokenTracker.extendBudget(extraTokens);
3988
+ this.emitEvent({ type: 'status', message: 'Continuing autonomous task execution without artificial interruption…' });
3989
+ this.messages.push({
3990
+ role: 'system',
3991
+ content: '[Autonomous task continuation: Do not repeat prior actions. Proceed with executing next concrete steps.]'
3992
+ });
3993
+ this.memoryManager.saveHistory(this.messages);
3994
+ continue;
3995
+ }
4060
3996
  this.messages.push({ role: 'system', content: `[Unfinished task checkpoint] ${e.message}` });
4061
3997
  this.memoryManager.saveHistory(this.messages);
4062
3998
  this.emitEvent({ type: 'budget_warning', message: e.message });
@@ -4064,7 +4000,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4064
4000
  event: 'efficiency_checkpoint',
4065
4001
  taskId: this.taskId,
4066
4002
  reason: e?.reason || e?.code,
4067
- ...this.efficiencyBudget.snapshot()
4003
+ tokenUsage: this.tokenTracker.taskTokens
4068
4004
  });
4069
4005
  break;
4070
4006
  }
package/src/agentLoop.ts CHANGED
@@ -101,7 +101,16 @@ import { StallGuardController, type StallGuardDecision, type IdenticalCallObserv
101
101
  import { buildRecoverableDroppedSummary, pruneStaleToolObservations, shortenOversizedToolObservations, pruneExecutedToolArguments } from './historyPruner.js';
102
102
  import { isOutputRecoveryRead } from './outputRecovery.js';
103
103
  import { isPlanReviewHandoff, isPlanningOnlyRequest } from './taskContinuation.js';
104
- import { UnifiedBudgetEnforcer, EfficiencyCheckpoint, actionLimitFor, tokenLimitFor, turnTokenLimitFor, noncachedTokens } from './providers/budgetEnforcer.js';
104
+ export function noncachedTokens(usage: any): number {
105
+ if (!usage) return 0;
106
+ const finite = (value: number | undefined): number => Number.isFinite(value) ? Math.max(0, value ?? 0) : 0;
107
+ const input = usage.uncachedPromptTokens !== undefined
108
+ ? finite(usage.uncachedPromptTokens)
109
+ : finite(usage.cachedPromptTokens) > finite(usage.promptTokens)
110
+ ? finite(usage.promptTokens)
111
+ : Math.max(0, finite(usage.promptTokens) - finite(usage.cachedPromptTokens));
112
+ return input + finite(usage.completionTokens);
113
+ }
105
114
 
106
115
  export interface AgentLoopEvent {
107
116
  type: string;
@@ -1096,8 +1105,7 @@ export class AgentLoop {
1096
1105
 
1097
1106
  const eligible: any[] = [];
1098
1107
  for (const toolCall of toolCalls) {
1099
- const capacity = Math.min(this.smartToolsGovernor?.inspectionCapacity ?? 2,
1100
- this.efficiencyBudget?.getRemainingActions() ?? 35);
1108
+ const capacity = this.smartToolsGovernor?.inspectionCapacity ?? 2;
1101
1109
  if (eligible.length >= capacity) break;
1102
1110
  const functionName = canonicalToolName(toolCall.function.name);
1103
1111
  // A later read may verify an earlier write. Never prefetch it across
@@ -1251,9 +1259,6 @@ export class AgentLoop {
1251
1259
  const id = `peer-file:${randomUUID()}:${tool}`;
1252
1260
  if (!await this.authorizePeerOperation(tool, args, id)) throw new Error('The requested ACP file operation was not authorized');
1253
1261
  if (tool === 'fs_write') captureBeforeMutation(tool, args, { taskId: this.taskId, step: this.stepsCompleted });
1254
- if (!this._inModelCall) {
1255
- this.efficiencyBudget?.recordAction(`peer-file:${tool}:${target}`);
1256
- }
1257
1262
  let result: { success: boolean; error?: string; output?: string };
1258
1263
  if (tool === 'fs_read') {
1259
1264
  // ACP expects the actual requested text, not the host tool's paging
@@ -1828,22 +1833,7 @@ export class AgentLoop {
1828
1833
  if (!this.currentTaskPrompt && this.userPrompt) {
1829
1834
  this.currentTaskPrompt = this.userPrompt;
1830
1835
  }
1831
- const turnArchetype = determineToolScope(effectivePrompt, this.taskShape).archetype;
1832
- const efficiency = this.config.efficiency || {};
1833
- const taskTokenCeiling = Number.isInteger(this.taskTokenLimit) && (this.taskTokenLimit as number) > 0
1834
- ? (this.taskTokenLimit as number)
1835
- : this.tokenTracker.budget?.enabled && Number.isFinite(this.tokenTracker.budget?.maxTokensPerTask) && (this.tokenTracker.budget.maxTokensPerTask as number) > 0
1836
- ? (this.tokenTracker.budget.maxTokensPerTask as number)
1837
- : Number.isFinite(efficiency.maxTaskTokens) && (efficiency.maxTaskTokens as number) > 0
1838
- ? (efficiency.maxTaskTokens as number)
1839
- : tokenLimitFor(turnArchetype);
1840
- this.efficiencyBudget = new UnifiedBudgetEnforcer(
1841
- Number.isFinite(efficiency.maxTurnTokens) && efficiency.maxTurnTokens > 0
1842
- ? efficiency.maxTurnTokens
1843
- : turnTokenLimitFor(turnArchetype),
1844
- Number.isSafeInteger(efficiency.maxTurnActions) && efficiency.maxTurnActions > 0 ? efficiency.maxTurnActions : actionLimitFor(turnArchetype),
1845
- taskTokenCeiling
1846
- );
1836
+ const isAutonomousMode = (this.config.autonomyMode || 'C') === 'C';
1847
1837
  const recoveryPaths = new Set<string>();
1848
1838
  let modelCallIndex = 0;
1849
1839
  let mediaExplorationRecoveries = 0;
@@ -2240,7 +2230,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2240
2230
  dailyLimit > 0 ? dailyLimit - dailyUsed : Infinity
2241
2231
  ) : Infinity;
2242
2232
  const remainingBudget = hardBudget
2243
- ? Math.min(configuredRemainingBudget, this.efficiencyBudget.getRemainingTokens())
2233
+ ? configuredRemainingBudget
2244
2234
  : Infinity;
2245
2235
  if (hardBudget && remainingBudget <= 0) {
2246
2236
  this.emitEvent({ type: 'budget_warning', message: 'Token budget reached before the next model call.' });
@@ -2271,9 +2261,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2271
2261
  pruneExecutedToolArguments(this.messages, { threshold: 1500, taskId: this.taskId });
2272
2262
  const stepScale = Math.max(this.tokenTracker.largestStepTokens || 50_000, 100_000);
2273
2263
  const extraTokens = Math.max(stepScale * 10, 1_000_000);
2274
- const extraActions = Math.max(Math.ceil((this.efficiencyBudget?.getRemainingActions() ?? 50) + 100), 100);
2275
2264
  this.tokenTracker.extendBudget(extraTokens);
2276
- this.efficiencyBudget?.extendBudget?.(extraTokens, extraActions);
2277
2265
  }
2278
2266
  }
2279
2267
 
@@ -2316,7 +2304,6 @@ You are operating in a text-and-code modality without direct image pixel renderi
2316
2304
 
2317
2305
  const planStepStart = performance.now();
2318
2306
  const nativeControl = new AbortController();
2319
- let nativeCheckpoint: EfficiencyCheckpoint | null = null;
2320
2307
  const invocation = ++modelCallIndex;
2321
2308
  this._inModelCall = true;
2322
2309
  const response = await this.llm.chat(prunedMessages, {
@@ -2328,8 +2315,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2328
2315
  maxTokensThisCall: Number.isFinite(configuredRemainingBudget) && hardBudget ? configuredRemainingBudget : undefined,
2329
2316
  tokenBudgetBasis: Number.isFinite(configuredRemainingBudget) ? 'total' : 'noncached',
2330
2317
  tokenLimit: hardBudget && Number.isFinite(remainingBudget) && remainingBudget > 0
2331
- ? Math.min(this.efficiencyBudget.maxTurnTokens, remainingBudget) : this.efficiencyBudget.maxTurnTokens,
2332
- maxNativeActions: this.efficiencyBudget.getRemainingActions(),
2318
+ ? remainingBudget : undefined,
2333
2319
  workspaceRoot: this.workspaceRoot,
2334
2320
  onPeerPermission: (request: RequestPermissionRequest) => this.requestPeerPermission(request),
2335
2321
  onPeerFileRead: (file: string, options?: { line?: number; limit?: number }) => this.executePeerFile('fs_read', file, undefined, options),
@@ -2415,18 +2401,6 @@ You are operating in a text-and-code modality without direct image pixel renderi
2415
2401
  auditLog.log({ event: 'native_action', taskId: this.taskId,
2416
2402
  provider: this.config.provider || 'unknown', tool: action.name, status: action.status,
2417
2403
  ...(action.id ? { actionId: action.id } : {}) });
2418
- if (action.status === 'running' && !isChecklistTool) {
2419
- try {
2420
- this.efficiencyBudget.recordAction(`${invocation}:${action.id || `${action.name}:${action.detail || ''}`}`);
2421
- } catch (error: unknown) {
2422
- if (error instanceof EfficiencyCheckpoint) {
2423
- finalizeReasoningSegment();
2424
- nativeCheckpoint = error;
2425
- nativeControl.abort();
2426
- }
2427
- return;
2428
- }
2429
- }
2430
2404
  if (action.status === 'completed' && action.id && !isChecklistTool) {
2431
2405
  completedNativeActionIds.add(String(action.id));
2432
2406
  }
@@ -2543,22 +2517,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2543
2517
  }
2544
2518
  throw checkpoint;
2545
2519
  }
2546
- if (nativeCheckpoint) {
2547
- if (completedNativeActionIds.size > 0) {
2548
- this.stepsCompleted += completedNativeActionIds.size;
2549
- }
2550
- if (reasoningAccumulated) {
2551
- this.messages.push({
2552
- role: 'assistant',
2553
- content: 'Turn paused at efficiency checkpoint.',
2554
- reasoning_content: reasoningAccumulated
2555
- });
2556
- }
2557
- if (error && typeof error === 'object' && 'partialUsage' in error) {
2558
- Object.assign(nativeCheckpoint, { partialUsage: error.partialUsage });
2559
- }
2560
- }
2561
- throw nativeCheckpoint || error;
2520
+ throw error;
2562
2521
  })
2563
2522
  .finally(() => {
2564
2523
  finalizeReasoningSegment();
@@ -2617,10 +2576,6 @@ You are operating in a text-and-code modality without direct image pixel renderi
2617
2576
  response.usage.promptTokens, response.usage.completionTokens, response.usage
2618
2577
  )
2619
2578
  });
2620
- this.efficiencyBudget.recordUsage(response.usage);
2621
- for (const action of response.externalActions || []) {
2622
- this.efficiencyBudget.recordAction(`${invocation}:${action.id || `${action.name}:${action.detail || ''}`}`);
2623
- }
2624
2579
 
2625
2580
  const cachedTokens = response.usage.cachedPromptTokens || 0;
2626
2581
  if (cachedTokens > 0) {
@@ -3795,7 +3750,6 @@ You are operating in a text-and-code modality without direct image pixel renderi
3795
3750
  // errors. It only rewinds reasoning; it never replays side effects.
3796
3751
  let result;
3797
3752
  let duration;
3798
- this.efficiencyBudget.recordAction();
3799
3753
 
3800
3754
  try {
3801
3755
  const startTime = Date.now();
@@ -4251,11 +4205,6 @@ You are operating in a text-and-code modality without direct image pixel renderi
4251
4205
  cachedPromptTokens: usage.cachedPromptTokens || 0,
4252
4206
  measurement: 'provider_reported_partial', costBasis: 'external_subscription_unavailable'
4253
4207
  });
4254
- try { this.efficiencyBudget.recordUsage(usage); }
4255
- catch (checkpoint: unknown) {
4256
- if (checkpoint instanceof EfficiencyCheckpoint) e = checkpoint;
4257
- else throw checkpoint;
4258
- }
4259
4208
  }
4260
4209
  }
4261
4210
  if (e instanceof RetryConsentCheckpoint && this._pendingConsent) {
@@ -4270,41 +4219,26 @@ You are operating in a text-and-code modality without direct image pixel renderi
4270
4219
  this.memoryManager.saveHistory(this.messages);
4271
4220
  continue;
4272
4221
  }
4273
- const isTokenCheckpoint = e instanceof EfficiencyCheckpoint && e.scope === 'turn' && e.reason === 'tokens';
4274
- const isHardBudget = (Number.isInteger(this.taskTokenLimit) && (this.taskTokenLimit as number) > 0)
4275
- || (this.tokenTracker.budget?.enabled === true && this.tokenTracker.budget?.hardStop === true);
4276
- const isDesktopLimit = e?.code === 'AGY_DESKTOP_TASK_LIMIT';
4277
-
4278
- if (isTokenCheckpoint && !isHardBudget && !isDesktopLimit && incompleteTurnContinuations < 5) {
4279
- incompleteTurnContinuations++;
4280
- this.emitEvent({ type: 'budget_warning', message: e.message });
4281
- auditLog.log({
4282
- event: 'efficiency_checkpoint',
4283
- taskId: this.taskId,
4284
- reason: (e as any)?.reason || (e as any)?.code || 'budget',
4285
- ...this.efficiencyBudget.snapshot()
4286
- });
4287
- const stepScale = Math.max(this.tokenTracker.largestStepTokens || 50_000, 100_000);
4288
- const extraTokens = Math.max(stepScale * 10, 1_000_000);
4289
- const extraActions = Math.max(Math.ceil((this.efficiencyBudget?.getRemainingActions() ?? 50) + 100), 100);
4290
- this.tokenTracker.extendBudget(extraTokens);
4291
- this.efficiencyBudget.extendBudget?.(extraTokens, extraActions);
4292
- compactSessionMessages(this.messages, {
4293
- keepRecentTurns: 4,
4294
- taskId: this.taskId,
4295
- originalPrompt: this.currentTaskPrompt || this.userPrompt
4296
- });
4297
- this.emitEvent({ type: 'status', message: `Continuing task execution from efficiency checkpoint (runway extended +${extraActions} actions)…` });
4298
- this.emitEvent({ type: 'agent_activity', activity: 'Continuing task from efficiency checkpoint…' });
4299
- this.messages.push({
4300
- role: 'system',
4301
- content: `[EFFICIENCY CONTINUATION: Previous turn paused at checkpoint (${e.message}). Autonomous runway extended (+${extraActions} actions). Session history and disk modifications are preserved. Do NOT replay prior actions. Continue executing the task directly.]`
4302
- });
4303
- this.memoryManager.saveHistory(this.messages);
4304
- continue;
4305
- }
4306
- if (e instanceof EfficiencyCheckpoint || e?.code === 'TASK_TOKEN_BUDGET' || e?.code === 'PROVIDER_TOKEN_BUDGET'
4222
+ if (e?.code === 'TASK_TOKEN_BUDGET' || e?.code === 'PROVIDER_TOKEN_BUDGET'
4307
4223
  || e?.code === 'AGY_DESKTOP_TASK_LIMIT' || e?.code === 'AGY_TOKEN_BUDGET' || e?.code === 'AGY_NATIVE_ACTION_BUDGET') {
4224
+ const isExplicitHardBudget = (Number.isInteger(this.taskTokenLimit) && (this.taskTokenLimit as number) > 0)
4225
+ || (this.tokenTracker.budget?.enabled === true && this.tokenTracker.budget?.hardStop === true);
4226
+ if (this.config.autonomyMode === 'C' && !isExplicitHardBudget) {
4227
+ this.emitEvent({ type: 'budget_warning', message: e.message });
4228
+ pruneStaleToolObservations(this.messages, { keepRecent: 3, minChars: 300, taskId: this.taskId });
4229
+ shortenOversizedToolObservations(this.messages, { threshold: 1500, taskId: this.taskId });
4230
+ pruneExecutedToolArguments(this.messages, { threshold: 1500, taskId: this.taskId });
4231
+ const stepScale = Math.max(this.tokenTracker.largestStepTokens || 50_000, 100_000);
4232
+ const extraTokens = Math.max(stepScale * 10, 1_000_000);
4233
+ this.tokenTracker.extendBudget(extraTokens);
4234
+ this.emitEvent({ type: 'status', message: 'Continuing autonomous task execution without artificial interruption…' });
4235
+ this.messages.push({
4236
+ role: 'system',
4237
+ content: '[Autonomous task continuation: Do not repeat prior actions. Proceed with executing next concrete steps.]'
4238
+ });
4239
+ this.memoryManager.saveHistory(this.messages);
4240
+ continue;
4241
+ }
4308
4242
  this.messages.push({ role: 'system', content: `[Unfinished task checkpoint] ${e.message}` });
4309
4243
  this.memoryManager.saveHistory(this.messages);
4310
4244
  this.emitEvent({ type: 'budget_warning', message: e.message });
@@ -4312,7 +4246,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4312
4246
  event: 'efficiency_checkpoint',
4313
4247
  taskId: this.taskId,
4314
4248
  reason: (e as any)?.reason || (e as any)?.code,
4315
- ...this.efficiencyBudget.snapshot()
4249
+ tokenUsage: this.tokenTracker.taskTokens
4316
4250
  });
4317
4251
  break;
4318
4252
  }