@causyne/agent 1.20.94 → 1.20.95

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.94",
3
+ "version": "1.20.95",
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
@@ -6,6 +6,7 @@ import { getProcessEntitlementGate, EntitlementAccessError } from './licensing/e
6
6
  import { repairUnansweredToolCalls, validateToolCallBatch } from './agent/toolTurnIntegrity.js';
7
7
  import { waitForAbortableDelay } from './agent/abortableDelay.js';
8
8
  import { normalizeAgentFailure } from './agent/providerFailure.js';
9
+ import { resolveTaskTokenCeiling, peerCallTokenCeiling, isAntigravityPeer, isTerminalBudgetFailure, desktopDeadline, remainingDesktopTime } from './budget/budgetPolicy.js';
9
10
  import { PEER_COLLABORATION_POLICY } from './providers/collaborationPolicy.js';
10
11
  import { createHash, randomUUID } from 'crypto';
11
12
  import { execFileSync } from 'node:child_process';
@@ -1712,8 +1713,19 @@ export class AgentLoop {
1712
1713
  // entitlements. A second reset here could resurrect an aborted task.
1713
1714
  if (this.stopRequested || this.abortController?.signal?.aborted)
1714
1715
  return;
1715
- // Refresh tier limits on every task run
1716
+ // Refresh tier limits on every task run.
1716
1717
  this.updateTierLimits();
1718
+ // The CLI reuses AgentLoop between messages. Task consumption must not
1719
+ // leak into the next turn, but session/daily consumption is retained.
1720
+ this.tokenTracker.resetTask();
1721
+ const guardLimit = resolveTaskTokenCeiling({
1722
+ provider: this.config.provider,
1723
+ workerLimit: this.taskTokenLimit,
1724
+ configured: this.tokenTracker.budget
1725
+ });
1726
+ this.tokenTracker.setEnforcedTaskLimit(guardLimit);
1727
+ const taskArchetype = determineToolScope(this.currentTaskPrompt || this.userPrompt || '', this.taskShape).archetype;
1728
+ this._taskWallDeadlineAt = desktopDeadline(Date.now(), taskArchetype);
1717
1729
  if (!this.llm) {
1718
1730
  throw new Error("API Key Required. Causyne is a 100% Sovereign BYOK Engine. Please configure your API Provider and Key in Settings.");
1719
1731
  }
@@ -2053,6 +2065,12 @@ export class AgentLoop {
2053
2065
  let emptyResponseRecoveries = 0;
2054
2066
  // The core loop governed by Sovereign Human-in-the-Loop Checkpoints
2055
2067
  while (!this.stopRequested) {
2068
+ const desktopTimeLeft = remainingDesktopTime(this._taskWallDeadlineAt);
2069
+ if (desktopTimeLeft !== null && desktopTimeLeft <= 0) {
2070
+ this.emitEvent({ type: 'budget_warning', message: 'Desktop task stopped at its 180-second wall-clock ceiling. Progress is preserved; outcome is unverified.' });
2071
+ auditLog.log({ event: 'task_stopped_on_wall_budget', taskId: this.taskId });
2072
+ break;
2073
+ }
2056
2074
  // CAUSYNE_ENTITLEMENT_V1: verify an authorized lease before each model step.
2057
2075
  try {
2058
2076
  await this._entitlementGate?.beforeStep();
@@ -2434,30 +2452,19 @@ You are operating in a text-and-code modality without direct image pixel renderi
2434
2452
  }
2435
2453
  const affordability = this.tokenTracker.canAffordAnotherStep();
2436
2454
  if (!affordability.allowed) {
2437
- if (hardBudget) {
2438
- this.emitEvent({ type: 'budget_warning', message: affordability.reason });
2439
- this.emitEvent({ type: 'notice', message: 'Stopped before the token ceiling. Nothing was truncated mid-step.' });
2440
- if (this._offeredPlanId) {
2441
- try {
2442
- recordMiss(this._offeredPlanId);
2443
- }
2444
- catch (e) { /* never block a stop */ }
2455
+ this.emitEvent({ type: 'budget_warning', message: affordability.reason });
2456
+ this.emitEvent({ type: 'notice', message: 'Task stopped at its token ceiling before the next model call.' });
2457
+ if (this._offeredPlanId) {
2458
+ try {
2459
+ recordMiss(this._offeredPlanId);
2445
2460
  }
2446
- auditLog.log({
2447
- event: 'task_stopped_on_budget', taskId: this.taskId,
2448
- used: affordability.used, limit: affordability.limit, projected: affordability.projected
2449
- });
2450
- break;
2451
- }
2452
- else {
2453
- // Proactive history compaction rather than artificial abort (OpenCode / SWE-agent pattern)
2454
- pruneStaleToolObservations(this.messages, { keepRecent: 3, minChars: 300, taskId: this.taskId });
2455
- shortenOversizedToolObservations(this.messages, { threshold: 1500, taskId: this.taskId });
2456
- pruneExecutedToolArguments(this.messages, { threshold: 1500, taskId: this.taskId });
2457
- const stepScale = Math.max(this.tokenTracker.largestStepTokens || 50_000, 100_000);
2458
- const extraTokens = Math.max(stepScale * 10, 1_000_000);
2459
- this.tokenTracker.extendBudget(extraTokens);
2461
+ catch { /* never block a stop */ }
2460
2462
  }
2463
+ auditLog.log({
2464
+ event: 'task_stopped_on_budget', taskId: this.taskId,
2465
+ used: affordability.used, limit: affordability.limit, projected: affordability.projected
2466
+ });
2467
+ break;
2461
2468
  }
2462
2469
  // 2. PLAN (Call LLM). dynamicTools was resolved above so the task brief
2463
2470
  // could reference the tools actually in context.
@@ -2506,10 +2513,16 @@ You are operating in a text-and-code modality without direct image pixel renderi
2506
2513
  taskIntent: isLaunchOnlyPrompt(this.currentTaskPrompt || this.userPrompt || '') ? 'launch' : 'general',
2507
2514
  taskArchetype: determineToolScope(this.currentTaskPrompt || this.userPrompt || '', this.taskShape).archetype,
2508
2515
  hardBudget: hardBudget,
2509
- maxTokensThisCall: Number.isFinite(configuredRemainingBudget) && hardBudget ? configuredRemainingBudget : undefined,
2510
- tokenBudgetBasis: Number.isFinite(configuredRemainingBudget) ? 'total' : 'noncached',
2516
+ // The peer can perform multiple billable model steps inside one
2517
+ // chat() call. The per-call bound is independent of autonomy mode.
2518
+ maxTokensThisCall: isAntigravityPeer(this.config.provider)
2519
+ ? peerCallTokenCeiling(configuredRemainingBudget)
2520
+ : Number.isFinite(configuredRemainingBudget) && hardBudget ? configuredRemainingBudget : undefined,
2521
+ tokenBudgetBasis: isAntigravityPeer(this.config.provider) ? 'noncached'
2522
+ : Number.isFinite(configuredRemainingBudget) ? 'total' : 'noncached',
2511
2523
  tokenLimit: hardBudget && Number.isFinite(remainingBudget) && remainingBudget > 0
2512
2524
  ? remainingBudget : undefined,
2525
+ taskDeadlineMs: this._taskWallDeadlineAt ?? undefined,
2513
2526
  workspaceRoot: this.workspaceRoot,
2514
2527
  onPeerPermission: (request) => this.requestPeerPermission(request),
2515
2528
  onPeerFileRead: (file, options) => this.executePeerFile('fs_read', file, undefined, options),
@@ -4650,34 +4663,16 @@ You are operating in a text-and-code modality without direct image pixel renderi
4650
4663
  this.memoryManager.saveHistory(this.messages);
4651
4664
  continue;
4652
4665
  }
4653
- if (e?.code === 'TASK_TOKEN_BUDGET' || e?.code === 'PROVIDER_TOKEN_BUDGET'
4654
- || e?.code === 'AGY_DESKTOP_TASK_LIMIT' || e?.code === 'AGY_TOKEN_BUDGET' || e?.code === 'AGY_NATIVE_ACTION_BUDGET') {
4655
- const isExplicitHardBudget = (Number.isInteger(this.taskTokenLimit) && this.taskTokenLimit > 0)
4656
- || (this.tokenTracker.budget?.enabled === true && this.tokenTracker.budget?.hardStop === true);
4657
- if (this.config.autonomyMode === 'C' && !isExplicitHardBudget) {
4658
- this.emitEvent({ type: 'budget_warning', message: e.message });
4659
- pruneStaleToolObservations(this.messages, { keepRecent: 3, minChars: 300, taskId: this.taskId });
4660
- shortenOversizedToolObservations(this.messages, { threshold: 1500, taskId: this.taskId });
4661
- pruneExecutedToolArguments(this.messages, { threshold: 1500, taskId: this.taskId });
4662
- const stepScale = Math.max(this.tokenTracker.largestStepTokens || 50_000, 100_000);
4663
- const extraTokens = Math.max(stepScale * 10, 1_000_000);
4664
- this.tokenTracker.extendBudget(extraTokens);
4665
- this.emitEvent({ type: 'status', message: 'Continuing autonomous task execution without artificial interruption…' });
4666
- this.messages.push({
4667
- role: 'system',
4668
- content: '[Autonomous task continuation: Do not repeat prior actions. Proceed with executing next concrete steps.]'
4669
- });
4670
- this.memoryManager.saveHistory(this.messages);
4671
- continue;
4672
- }
4666
+ if (isTerminalBudgetFailure(e)) {
4667
+ // Budget checkpoints always stop this task. Mode C is autonomous
4668
+ // about tools, not about spending user resources without approval.
4673
4669
  this.messages.push({ role: 'system', content: `[Unfinished task checkpoint] ${e.message}` });
4674
4670
  this.memoryManager.saveHistory(this.messages);
4675
4671
  this.emitEvent({ type: 'budget_warning', message: e.message });
4676
4672
  auditLog.log({
4677
- event: 'efficiency_checkpoint',
4678
- taskId: this.taskId,
4679
- reason: e?.reason || e?.code,
4680
- tokenUsage: this.tokenTracker.taskTokens
4673
+ event: 'efficiency_checkpoint', taskId: this.taskId,
4674
+ reason: e.code, tokenUsage: this.tokenTracker.taskTokens,
4675
+ outcome: 'unverified'
4681
4676
  });
4682
4677
  break;
4683
4678
  }
package/src/agentLoop.ts CHANGED
@@ -6,6 +6,7 @@ import { getProcessEntitlementGate, EntitlementAccessError } from './licensing/e
6
6
  import { repairUnansweredToolCalls, validateToolCallBatch } from './agent/toolTurnIntegrity.js';
7
7
  import { waitForAbortableDelay } from './agent/abortableDelay.js';
8
8
  import { normalizeAgentFailure } from './agent/providerFailure.js';
9
+ import { resolveTaskTokenCeiling, peerCallTokenCeiling, isAntigravityPeer, isTerminalBudgetFailure, desktopDeadline, remainingDesktopTime } from './budget/budgetPolicy.js';
9
10
  import { PEER_COLLABORATION_POLICY } from './providers/collaborationPolicy.js';
10
11
  import type { RequestPermissionRequest, RequestPermissionResponse } from './acp/protocol.js';
11
12
  import { createHash, randomUUID } from 'crypto';
@@ -1772,8 +1773,21 @@ export class AgentLoop {
1772
1773
  // run() owns cancellation and rearms it exactly once, before awaiting
1773
1774
  // entitlements. A second reset here could resurrect an aborted task.
1774
1775
  if (this.stopRequested || this.abortController?.signal?.aborted) return;
1775
- // Refresh tier limits on every task run
1776
+ // Refresh tier limits on every task run.
1776
1777
  this.updateTierLimits();
1778
+ // The CLI reuses AgentLoop between messages. Task consumption must not
1779
+ // leak into the next turn, but session/daily consumption is retained.
1780
+ this.tokenTracker.resetTask();
1781
+ const guardLimit = resolveTaskTokenCeiling({
1782
+ provider: this.config.provider,
1783
+ workerLimit: this.taskTokenLimit,
1784
+ configured: this.tokenTracker.budget
1785
+ });
1786
+ this.tokenTracker.setEnforcedTaskLimit(guardLimit);
1787
+ const taskArchetype = determineToolScope(
1788
+ this.currentTaskPrompt || this.userPrompt || '', this.taskShape
1789
+ ).archetype;
1790
+ this._taskWallDeadlineAt = desktopDeadline(Date.now(), taskArchetype);
1777
1791
  if (!this.llm) {
1778
1792
  throw new Error("API Key Required. Causyne is a 100% Sovereign BYOK Engine. Please configure your API Provider and Key in Settings.");
1779
1793
  }
@@ -2133,6 +2147,13 @@ export class AgentLoop {
2133
2147
 
2134
2148
  // The core loop governed by Sovereign Human-in-the-Loop Checkpoints
2135
2149
  while (!this.stopRequested) {
2150
+ const desktopTimeLeft = remainingDesktopTime(this._taskWallDeadlineAt);
2151
+ if (desktopTimeLeft !== null && desktopTimeLeft <= 0) {
2152
+ this.emitEvent({ type: 'budget_warning', message:
2153
+ 'Desktop task stopped at its 180-second wall-clock ceiling. Progress is preserved; outcome is unverified.' });
2154
+ auditLog.log({ event: 'task_stopped_on_wall_budget', taskId: this.taskId });
2155
+ break;
2156
+ }
2136
2157
  // CAUSYNE_ENTITLEMENT_V1: verify an authorized lease before each model step.
2137
2158
  try {
2138
2159
  await this._entitlementGate?.beforeStep();
@@ -2542,26 +2563,16 @@ You are operating in a text-and-code modality without direct image pixel renderi
2542
2563
  }
2543
2564
  const affordability = this.tokenTracker.canAffordAnotherStep();
2544
2565
  if (!affordability.allowed) {
2545
- if (hardBudget) {
2546
- this.emitEvent({ type: 'budget_warning', message: affordability.reason });
2547
- this.emitEvent({ type: 'notice', message: 'Stopped before the token ceiling. Nothing was truncated mid-step.' });
2548
- if (this._offeredPlanId) {
2549
- try { recordMiss(this._offeredPlanId); } catch (e: any) { /* never block a stop */ }
2550
- }
2551
- auditLog.log({
2552
- event: 'task_stopped_on_budget', taskId: this.taskId,
2553
- used: affordability.used, limit: affordability.limit, projected: affordability.projected
2554
- });
2555
- break;
2556
- } else {
2557
- // Proactive history compaction rather than artificial abort (OpenCode / SWE-agent pattern)
2558
- pruneStaleToolObservations(this.messages, { keepRecent: 3, minChars: 300, taskId: this.taskId });
2559
- shortenOversizedToolObservations(this.messages, { threshold: 1500, taskId: this.taskId });
2560
- pruneExecutedToolArguments(this.messages, { threshold: 1500, taskId: this.taskId });
2561
- const stepScale = Math.max(this.tokenTracker.largestStepTokens || 50_000, 100_000);
2562
- const extraTokens = Math.max(stepScale * 10, 1_000_000);
2563
- this.tokenTracker.extendBudget(extraTokens);
2566
+ this.emitEvent({ type: 'budget_warning', message: affordability.reason });
2567
+ this.emitEvent({ type: 'notice', message: 'Task stopped at its token ceiling before the next model call.' });
2568
+ if (this._offeredPlanId) {
2569
+ try { recordMiss(this._offeredPlanId); } catch { /* never block a stop */ }
2564
2570
  }
2571
+ auditLog.log({
2572
+ event: 'task_stopped_on_budget', taskId: this.taskId,
2573
+ used: affordability.used, limit: affordability.limit, projected: affordability.projected
2574
+ });
2575
+ break;
2565
2576
  }
2566
2577
 
2567
2578
  // 2. PLAN (Call LLM). dynamicTools was resolved above so the task brief
@@ -2612,10 +2623,16 @@ You are operating in a text-and-code modality without direct image pixel renderi
2612
2623
  taskIntent: isLaunchOnlyPrompt(this.currentTaskPrompt || this.userPrompt || '') ? 'launch' : 'general',
2613
2624
  taskArchetype: determineToolScope(this.currentTaskPrompt || this.userPrompt || '', this.taskShape).archetype,
2614
2625
  hardBudget: hardBudget,
2615
- maxTokensThisCall: Number.isFinite(configuredRemainingBudget) && hardBudget ? configuredRemainingBudget : undefined,
2616
- tokenBudgetBasis: Number.isFinite(configuredRemainingBudget) ? 'total' : 'noncached',
2626
+ // The peer can perform multiple billable model steps inside one
2627
+ // chat() call. The per-call bound is independent of autonomy mode.
2628
+ maxTokensThisCall: isAntigravityPeer(this.config.provider)
2629
+ ? peerCallTokenCeiling(configuredRemainingBudget)
2630
+ : Number.isFinite(configuredRemainingBudget) && hardBudget ? configuredRemainingBudget : undefined,
2631
+ tokenBudgetBasis: isAntigravityPeer(this.config.provider) ? 'noncached'
2632
+ : Number.isFinite(configuredRemainingBudget) ? 'total' : 'noncached',
2617
2633
  tokenLimit: hardBudget && Number.isFinite(remainingBudget) && remainingBudget > 0
2618
2634
  ? remainingBudget : undefined,
2635
+ taskDeadlineMs: this._taskWallDeadlineAt ?? undefined,
2619
2636
  workspaceRoot: this.workspaceRoot,
2620
2637
  onPeerPermission: (request: RequestPermissionRequest) => this.requestPeerPermission(request),
2621
2638
  onPeerFileRead: (file: string, options?: { line?: number; limit?: number }) => this.executePeerFile('fs_read', file, undefined, options),
@@ -4894,34 +4911,16 @@ You are operating in a text-and-code modality without direct image pixel renderi
4894
4911
  this.memoryManager.saveHistory(this.messages);
4895
4912
  continue;
4896
4913
  }
4897
- if (e?.code === 'TASK_TOKEN_BUDGET' || e?.code === 'PROVIDER_TOKEN_BUDGET'
4898
- || e?.code === 'AGY_DESKTOP_TASK_LIMIT' || e?.code === 'AGY_TOKEN_BUDGET' || e?.code === 'AGY_NATIVE_ACTION_BUDGET') {
4899
- const isExplicitHardBudget = (Number.isInteger(this.taskTokenLimit) && (this.taskTokenLimit as number) > 0)
4900
- || (this.tokenTracker.budget?.enabled === true && this.tokenTracker.budget?.hardStop === true);
4901
- if (this.config.autonomyMode === 'C' && !isExplicitHardBudget) {
4902
- this.emitEvent({ type: 'budget_warning', message: e.message });
4903
- pruneStaleToolObservations(this.messages, { keepRecent: 3, minChars: 300, taskId: this.taskId });
4904
- shortenOversizedToolObservations(this.messages, { threshold: 1500, taskId: this.taskId });
4905
- pruneExecutedToolArguments(this.messages, { threshold: 1500, taskId: this.taskId });
4906
- const stepScale = Math.max(this.tokenTracker.largestStepTokens || 50_000, 100_000);
4907
- const extraTokens = Math.max(stepScale * 10, 1_000_000);
4908
- this.tokenTracker.extendBudget(extraTokens);
4909
- this.emitEvent({ type: 'status', message: 'Continuing autonomous task execution without artificial interruption…' });
4910
- this.messages.push({
4911
- role: 'system',
4912
- content: '[Autonomous task continuation: Do not repeat prior actions. Proceed with executing next concrete steps.]'
4913
- });
4914
- this.memoryManager.saveHistory(this.messages);
4915
- continue;
4916
- }
4914
+ if (isTerminalBudgetFailure(e)) {
4915
+ // Budget checkpoints always stop this task. Mode C is autonomous
4916
+ // about tools, not about spending user resources without approval.
4917
4917
  this.messages.push({ role: 'system', content: `[Unfinished task checkpoint] ${e.message}` });
4918
4918
  this.memoryManager.saveHistory(this.messages);
4919
4919
  this.emitEvent({ type: 'budget_warning', message: e.message });
4920
4920
  auditLog.log({
4921
- event: 'efficiency_checkpoint',
4922
- taskId: this.taskId,
4923
- reason: (e as any)?.reason || (e as any)?.code,
4924
- tokenUsage: this.tokenTracker.taskTokens
4921
+ event: 'efficiency_checkpoint', taskId: this.taskId,
4922
+ reason: e.code, tokenUsage: this.tokenTracker.taskTokens,
4923
+ outcome: 'unverified'
4925
4924
  });
4926
4925
  break;
4927
4926
  }
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Causyne peer budget policy. No model calls, filesystem writes, or global state.
3
+ * One task token ceiling is shared by the AgentLoop and TokenTracker.
4
+ * Provider-local ceilings stop a headless peer before it can consume an entire
5
+ * task budget in one internal multi-step CLI invocation.
6
+ */
7
+ export const DEFAULT_AGY_TASK_TOKENS = 80_000;
8
+ export const DEFAULT_AGY_CALL_TOKENS = 32_000;
9
+ export const DEFAULT_AGY_NATIVE_ACTIONS = 128;
10
+ export const DEFAULT_DESKTOP_NATIVE_ACTIONS = 12;
11
+ export const DESKTOP_TASK_WALL_MS = 180_000;
12
+ const TERMINAL_BUDGET_CODES = new Set([
13
+ 'TASK_TOKEN_BUDGET',
14
+ 'PROVIDER_TOKEN_BUDGET',
15
+ 'AGY_DESKTOP_TASK_LIMIT',
16
+ 'AGY_TOKEN_BUDGET',
17
+ 'AGY_NATIVE_ACTION_BUDGET',
18
+ 'AGY_TASK_DEADLINE',
19
+ 'TASK_WALL_BUDGET'
20
+ ]);
21
+ export function positiveSafeInteger(value) {
22
+ if (typeof value !== 'number' && typeof value !== 'string')
23
+ return null;
24
+ if (typeof value === 'string' && !/^\d+$/.test(value.trim()))
25
+ return null;
26
+ const n = Number(value);
27
+ return Number.isSafeInteger(n) && n > 0 ? n : null;
28
+ }
29
+ export function isAntigravityPeer(provider) {
30
+ return /^(?:antigravity|agy)(?:$|[/:\s])/i.test(String(provider ?? '').trim());
31
+ }
32
+ /**
33
+ * Explicit worker ceiling remains strict. An enabled user task limit is
34
+ * authoritative even if its previous 'hardStop' flag was false. In the absence
35
+ * of explicit limits, only Antigravity peers get the conservative default.
36
+ * Other BYOK providers retain their existing policy.
37
+ */
38
+ export function resolveTaskTokenCeiling(options) {
39
+ const worker = positiveSafeInteger(options.workerLimit);
40
+ const configured = options.configured?.enabled === true
41
+ ? positiveSafeInteger(options.configured.maxTokensPerTask)
42
+ : null;
43
+ const explicit = [worker, configured].filter((v) => v !== null);
44
+ if (explicit.length > 0)
45
+ return Math.min(...explicit);
46
+ return isAntigravityPeer(options.provider) ? DEFAULT_AGY_TASK_TOKENS : null;
47
+ }
48
+ /** A finite peer call bound even when the caller passes hardBudget:false. */
49
+ export function peerCallTokenCeiling(remaining) {
50
+ const configuredRemaining = typeof remaining === 'number' && Number.isFinite(remaining)
51
+ ? Math.max(0, Math.floor(remaining)) : null;
52
+ return configuredRemaining === null
53
+ ? DEFAULT_AGY_CALL_TOKENS
54
+ : Math.min(DEFAULT_AGY_CALL_TOKENS, configuredRemaining);
55
+ }
56
+ export function peerNativeActionCeiling(configured, desktopTask) {
57
+ const fallback = desktopTask ? DEFAULT_DESKTOP_NATIVE_ACTIONS : DEFAULT_AGY_NATIVE_ACTIONS;
58
+ // Zero explicitly disables native peer actions; it is not 'missing'.
59
+ const explicit = typeof configured === 'number' && Number.isSafeInteger(configured)
60
+ && configured >= 0 ? configured : positiveSafeInteger(configured);
61
+ return explicit === null ? fallback : Math.min(explicit, fallback);
62
+ }
63
+ export function isTerminalBudgetFailure(error) {
64
+ if (!error || typeof error !== 'object')
65
+ return false;
66
+ const code = error.code;
67
+ return typeof code === 'string' && TERMINAL_BUDGET_CODES.has(code);
68
+ }
69
+ export function hasBillablePartialUsage(error) {
70
+ if (!error || typeof error !== 'object')
71
+ return false;
72
+ const usage = error.partialUsage;
73
+ if (!usage || typeof usage !== 'object')
74
+ return false;
75
+ const record = usage;
76
+ return [record.promptTokens, record.completionTokens].some(value => typeof value === 'number' && Number.isFinite(value) && value > 0);
77
+ }
78
+ export function shouldRetryPeerError(error, aborted = false) {
79
+ return !aborted && !isTerminalBudgetFailure(error) && !hasBillablePartialUsage(error);
80
+ }
81
+ export function desktopDeadline(startMs, archetype) {
82
+ return archetype === 'desktop_personalization' && Number.isFinite(startMs)
83
+ ? startMs + DESKTOP_TASK_WALL_MS : null;
84
+ }
85
+ export function remainingDesktopTime(deadlineMs, nowMs = Date.now()) {
86
+ if (typeof deadlineMs !== 'number' || !Number.isFinite(deadlineMs))
87
+ return null;
88
+ return Math.max(0, Math.floor(deadlineMs - nowMs));
89
+ }
90
+ export function createBudgetError(code, message) {
91
+ return Object.assign(new Error(message), { code });
92
+ }
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Causyne peer budget policy. No model calls, filesystem writes, or global state.
3
+ * One task token ceiling is shared by the AgentLoop and TokenTracker.
4
+ * Provider-local ceilings stop a headless peer before it can consume an entire
5
+ * task budget in one internal multi-step CLI invocation.
6
+ */
7
+ export const DEFAULT_AGY_TASK_TOKENS = 80_000;
8
+ export const DEFAULT_AGY_CALL_TOKENS = 32_000;
9
+ export const DEFAULT_AGY_NATIVE_ACTIONS = 128;
10
+ export const DEFAULT_DESKTOP_NATIVE_ACTIONS = 12;
11
+ export const DESKTOP_TASK_WALL_MS = 180_000;
12
+
13
+ const TERMINAL_BUDGET_CODES = new Set([
14
+ 'TASK_TOKEN_BUDGET',
15
+ 'PROVIDER_TOKEN_BUDGET',
16
+ 'AGY_DESKTOP_TASK_LIMIT',
17
+ 'AGY_TOKEN_BUDGET',
18
+ 'AGY_NATIVE_ACTION_BUDGET',
19
+ 'AGY_TASK_DEADLINE',
20
+ 'TASK_WALL_BUDGET'
21
+ ]);
22
+
23
+ export interface TaskBudgetOptions {
24
+ provider?: string | undefined;
25
+ workerLimit?: unknown;
26
+ configured?: {
27
+ enabled?: boolean | undefined;
28
+ maxTokensPerTask?: unknown;
29
+ } | null | undefined;
30
+ }
31
+
32
+ export function positiveSafeInteger(value: unknown): number | null {
33
+ if (typeof value !== 'number' && typeof value !== 'string') return null;
34
+ if (typeof value === 'string' && !/^\d+$/.test(value.trim())) return null;
35
+ const n = Number(value);
36
+ return Number.isSafeInteger(n) && n > 0 ? n : null;
37
+ }
38
+
39
+ export function isAntigravityPeer(provider: unknown): boolean {
40
+ return /^(?:antigravity|agy)(?:$|[/:\s])/i.test(String(provider ?? '').trim());
41
+ }
42
+
43
+ /**
44
+ * Explicit worker ceiling remains strict. An enabled user task limit is
45
+ * authoritative even if its previous 'hardStop' flag was false. In the absence
46
+ * of explicit limits, only Antigravity peers get the conservative default.
47
+ * Other BYOK providers retain their existing policy.
48
+ */
49
+ export function resolveTaskTokenCeiling(options: TaskBudgetOptions): number | null {
50
+ const worker = positiveSafeInteger(options.workerLimit);
51
+ const configured = options.configured?.enabled === true
52
+ ? positiveSafeInteger(options.configured.maxTokensPerTask)
53
+ : null;
54
+ const explicit = [worker, configured].filter((v): v is number => v !== null);
55
+ if (explicit.length > 0) return Math.min(...explicit);
56
+ return isAntigravityPeer(options.provider) ? DEFAULT_AGY_TASK_TOKENS : null;
57
+ }
58
+
59
+ /** A finite peer call bound even when the caller passes hardBudget:false. */
60
+ export function peerCallTokenCeiling(remaining: unknown): number {
61
+ const configuredRemaining = typeof remaining === 'number' && Number.isFinite(remaining)
62
+ ? Math.max(0, Math.floor(remaining)) : null;
63
+ return configuredRemaining === null
64
+ ? DEFAULT_AGY_CALL_TOKENS
65
+ : Math.min(DEFAULT_AGY_CALL_TOKENS, configuredRemaining);
66
+ }
67
+
68
+ export function peerNativeActionCeiling(configured: unknown, desktopTask: boolean): number {
69
+ const fallback = desktopTask ? DEFAULT_DESKTOP_NATIVE_ACTIONS : DEFAULT_AGY_NATIVE_ACTIONS;
70
+ // Zero explicitly disables native peer actions; it is not 'missing'.
71
+ const explicit = typeof configured === 'number' && Number.isSafeInteger(configured)
72
+ && configured >= 0 ? configured : positiveSafeInteger(configured);
73
+ return explicit === null ? fallback : Math.min(explicit, fallback);
74
+ }
75
+
76
+ export function isTerminalBudgetFailure(error: unknown): boolean {
77
+ if (!error || typeof error !== 'object') return false;
78
+ const code = (error as { code?: unknown }).code;
79
+ return typeof code === 'string' && TERMINAL_BUDGET_CODES.has(code);
80
+ }
81
+
82
+ export function hasBillablePartialUsage(error: unknown): boolean {
83
+ if (!error || typeof error !== 'object') return false;
84
+ const usage = (error as { partialUsage?: unknown }).partialUsage;
85
+ if (!usage || typeof usage !== 'object') return false;
86
+ const record = usage as { promptTokens?: unknown; completionTokens?: unknown };
87
+ return [record.promptTokens, record.completionTokens].some(value =>
88
+ typeof value === 'number' && Number.isFinite(value) && value > 0);
89
+ }
90
+
91
+ export function shouldRetryPeerError(error: unknown, aborted = false): boolean {
92
+ return !aborted && !isTerminalBudgetFailure(error) && !hasBillablePartialUsage(error);
93
+ }
94
+
95
+ export function desktopDeadline(startMs: number, archetype: string): number | null {
96
+ return archetype === 'desktop_personalization' && Number.isFinite(startMs)
97
+ ? startMs + DESKTOP_TASK_WALL_MS : null;
98
+ }
99
+
100
+ export function remainingDesktopTime(deadlineMs: unknown, nowMs = Date.now()): number | null {
101
+ if (typeof deadlineMs !== 'number' || !Number.isFinite(deadlineMs)) return null;
102
+ return Math.max(0, Math.floor(deadlineMs - nowMs));
103
+ }
104
+
105
+ export function createBudgetError(code: string, message: string): Error & { code: string } {
106
+ return Object.assign(new Error(message), { code });
107
+ }
@@ -17,6 +17,7 @@ import fs from 'node:fs';
17
17
  import path from 'node:path';
18
18
  import { isLaunchOnlyPrompt } from '../launchIntent.js';
19
19
  import { LLMProvider } from './base.js';
20
+ import { peerCallTokenCeiling, peerNativeActionCeiling, shouldRetryPeerError, remainingDesktopTime, createBudgetError, DESKTOP_TASK_WALL_MS } from '../budget/budgetPolicy.js';
20
21
  import { extractToolCallJsonObjects, stripToolCallMarkup, stripThinkBlocks, resolveToolCallEnvelopeArguments } from '../implementationPlan.js';
21
22
  /**
22
23
  * Baseline fallback models for instant offline availability.
@@ -916,6 +917,10 @@ export class AntigravityProvider extends LLMProvider {
916
917
  const latestPrompt = typeof latestUserMessage?.content === 'string' ? latestUserMessage.content : '';
917
918
  const launchOnly = options.taskIntent === 'launch' || isLaunchOnlyPrompt(latestPrompt);
918
919
  const desktopTask = options.taskArchetype === 'desktop_personalization';
920
+ const remainingWall = desktopTask ? remainingDesktopTime(options.taskDeadlineMs) : null;
921
+ if (remainingWall !== null && remainingWall <= 0) {
922
+ throw createBudgetError('AGY_TASK_DEADLINE', 'Desktop task wall-clock budget reached before the next peer invocation.');
923
+ }
919
924
  let promptText;
920
925
  if (useConversation) {
921
926
  let lastAssistantIndex = -1;
@@ -1017,9 +1022,7 @@ export class AntigravityProvider extends LLMProvider {
1017
1022
  }
1018
1023
  };
1019
1024
  const configuredActions = Number(options.maxNativeActions);
1020
- const isAutonomous = options.hardBudget === false;
1021
- let maxNativeActions = Number.isSafeInteger(configuredActions) && configuredActions >= 0
1022
- ? configuredActions : desktopTask ? 12 : isAutonomous ? Infinity : 35;
1025
+ const maxNativeActions = peerNativeActionCeiling(configuredActions, desktopTask);
1023
1026
  let nativeActionStarts = 0;
1024
1027
  let lastMutationActionIndex = 0;
1025
1028
  let progressiveActionsCount = 0;
@@ -1044,21 +1047,19 @@ export class AntigravityProvider extends LLMProvider {
1044
1047
  // disabled. Users can set a lower task budget through the existing UI.
1045
1048
  const remainingTaskBudget = Number(options.maxTokensThisCall);
1046
1049
  const rawTokenLimit = Number(options.tokenLimit);
1047
- const hasExplicitLimit = (Number.isFinite(remainingTaskBudget) && remainingTaskBudget > 0)
1048
- || (Number.isFinite(rawTokenLimit) && rawTokenLimit > 0);
1049
1050
  const countReportedTotal = options.tokenBudgetBasis !== 'noncached';
1050
- const defaultTokenLimit = 100_000;
1051
- const tokenLimit = Number.isFinite(remainingTaskBudget) && remainingTaskBudget > 0
1052
- ? remainingTaskBudget
1053
- : (Number.isFinite(rawTokenLimit) && rawTokenLimit > 0
1054
- ? rawTokenLimit
1055
- : defaultTokenLimit);
1056
- const wallTimer = desktopTask ? setTimeout(() => {
1057
- const error = new Error('Antigravity exceeded the 180-second desktop task limit. Outcome is unverified.');
1058
- error.code = 'AGY_DESKTOP_TASK_LIMIT';
1051
+ // A peer may execute many model steps without returning to AgentLoop.
1052
+ // Count uncached input + output for the conservative default ceiling.
1053
+ const requestedLimit = Number.isFinite(remainingTaskBudget) && remainingTaskBudget > 0
1054
+ ? remainingTaskBudget : Number.isFinite(rawTokenLimit) && rawTokenLimit > 0
1055
+ ? rawTokenLimit : Infinity;
1056
+ const tokenLimit = peerCallTokenCeiling(requestedLimit);
1057
+ const wallMs = desktopTask ? Math.min(DESKTOP_TASK_WALL_MS, remainingWall === null ? DESKTOP_TASK_WALL_MS : remainingWall) : null;
1058
+ const wallTimer = wallMs !== null ? setTimeout(() => {
1059
+ const error = createBudgetError('AGY_DESKTOP_TASK_LIMIT', 'Antigravity exceeded the remaining desktop task wall-clock allowance. Outcome is unverified.');
1059
1060
  safeReject(error);
1060
1061
  terminateChild();
1061
- }, 180_000) : null;
1062
+ }, wallMs) : null;
1062
1063
  wallTimer?.unref();
1063
1064
  const cleanup = () => {
1064
1065
  if (wallTimer)
@@ -1169,19 +1170,11 @@ export class AntigravityProvider extends LLMProvider {
1169
1170
  const reportedTotal = partialUsage.promptTokens + partialUsage.completionTokens;
1170
1171
  const uncachedTotal = noncachedTokens(partialUsage);
1171
1172
  const spentAgainstLimit = countReportedTotal ? reportedTotal : uncachedTotal;
1172
- if (Number.isFinite(tokenLimit) && tokenLimit > 0
1173
- && spentAgainstLimit >= tokenLimit) {
1174
- if (options.hardBudget === false) {
1175
- if (process.env.CAUSYNE_DEBUG === '1') {
1176
- console.log(`[BUDGET] Turn spent ${spentAgainstLimit} tokens against soft checkpoint ${tokenLimit}. Continuing execution.`);
1177
- }
1178
- }
1179
- else {
1180
- const error = Object.assign(new Error(`Antigravity reported ${spentAgainstLimit} tokens against a ${tokenLimit}-token per-call ceiling. This turn stopped and its outcome is unverified.`), { code: 'AGY_TOKEN_BUDGET', tokenLimit, partialUsage: { ...partialUsage } });
1181
- safeReject(error);
1182
- terminateChild();
1183
- return;
1184
- }
1173
+ if (spentAgainstLimit >= tokenLimit) {
1174
+ const error = Object.assign(createBudgetError('AGY_TOKEN_BUDGET', `Antigravity reached the ${tokenLimit}-token per-call ceiling. Outcome is unverified.`), { tokenLimit, partialUsage: { ...partialUsage } });
1175
+ safeReject(error);
1176
+ terminateChild();
1177
+ return;
1185
1178
  }
1186
1179
  }
1187
1180
  }
@@ -1275,7 +1268,7 @@ export class AntigravityProvider extends LLMProvider {
1275
1268
  }
1276
1269
  if (newNativeAction) {
1277
1270
  nativeActionStarts++;
1278
- if (!isAutonomous && Number.isFinite(maxNativeActions) && nativeActionStarts > maxNativeActions) {
1271
+ if (nativeActionStarts > maxNativeActions) {
1279
1272
  const error = new Error(`Antigravity reached the ${maxNativeActions} native-action turn checkpoint. Work remains unfinished; continue from the saved session.`);
1280
1273
  error.code = 'AGY_NATIVE_ACTION_BUDGET';
1281
1274
  safeReject(error);
@@ -1644,16 +1637,9 @@ export class AntigravityProvider extends LLMProvider {
1644
1637
  const uncachedTotal = noncachedTokens(response.usage);
1645
1638
  const spentAgainstLimit = countReportedTotal ? reportedTotal : uncachedTotal;
1646
1639
  if (spentAgainstLimit >= tokenLimit) {
1647
- if (options.hardBudget === false) {
1648
- if (process.env.CAUSYNE_DEBUG === '1') {
1649
- console.log(`[BUDGET] Turn finished with ${spentAgainstLimit} tokens against soft checkpoint ${tokenLimit}. Preserving result.`);
1650
- }
1651
- }
1652
- else {
1653
- Object.assign(partialUsage, response.usage);
1654
- safeReject(Object.assign(new Error(`Antigravity reached its ${tokenLimit}-token checkpoint. Work remains unverified.`), { code: 'AGY_TOKEN_BUDGET', tokenLimit, partialUsage: { ...partialUsage } }));
1655
- return;
1656
- }
1640
+ Object.assign(partialUsage, response.usage);
1641
+ safeReject(Object.assign(createBudgetError('AGY_TOKEN_BUDGET', `Antigravity reached its ${tokenLimit}-token checkpoint. Work remains unverified.`), { tokenLimit, partialUsage: { ...partialUsage } }));
1642
+ return;
1657
1643
  }
1658
1644
  safeResolve(response);
1659
1645
  });
@@ -1668,10 +1654,8 @@ export class AntigravityProvider extends LLMProvider {
1668
1654
  return await this._executeOnce(messages, options);
1669
1655
  }
1670
1656
  catch (err) {
1671
- if (options.signal?.aborted || err?.name === 'AbortError') {
1672
- throw err;
1673
- }
1674
- if (err?.code === 'AGY_NATIVE_ACTION_DENIED' || err?.code === 'AGY_TOKEN_BUDGET' || err?.code === 'PROVIDER_NO_PROGRESS') {
1657
+ if (!shouldRetryPeerError(err, options.signal?.aborted === true || err?.name === 'AbortError')
1658
+ || err?.code === 'AGY_NATIVE_ACTION_DENIED' || err?.code === 'PROVIDER_NO_PROGRESS') {
1675
1659
  throw err;
1676
1660
  }
1677
1661
  const msg = String(err?.message || '').toLowerCase();
@@ -16,6 +16,7 @@ import fs from 'node:fs';
16
16
  import path from 'node:path';
17
17
  import { isLaunchOnlyPrompt } from '../launchIntent.js';
18
18
  import { LLMProvider, type ProviderConfig, type ChatOptions, type ChatResponse, type ChatResponseAction, type ChatResponseToolCall, type ChatResponseUsage } from './base.js';
19
+ import { peerCallTokenCeiling, peerNativeActionCeiling, shouldRetryPeerError, remainingDesktopTime, createBudgetError, DESKTOP_TASK_WALL_MS } from '../budget/budgetPolicy.js';
19
20
  import { extractToolCallJsonObjects, stripToolCallMarkup, stripThinkBlocks, resolveToolCallEnvelopeArguments } from '../implementationPlan.js';
20
21
 
21
22
  /**
@@ -944,6 +945,10 @@ export class AntigravityProvider extends LLMProvider {
944
945
  const latestPrompt = typeof latestUserMessage?.content === 'string' ? latestUserMessage.content : '';
945
946
  const launchOnly = (options as any).taskIntent === 'launch' || isLaunchOnlyPrompt(latestPrompt);
946
947
  const desktopTask = (options as any).taskArchetype === 'desktop_personalization';
948
+ const remainingWall = desktopTask ? remainingDesktopTime((options as any).taskDeadlineMs) : null;
949
+ if (remainingWall !== null && remainingWall <= 0) {
950
+ throw createBudgetError('AGY_TASK_DEADLINE', 'Desktop task wall-clock budget reached before the next peer invocation.');
951
+ }
947
952
  let promptText: string;
948
953
 
949
954
  if (useConversation) {
@@ -1058,9 +1063,7 @@ export class AntigravityProvider extends LLMProvider {
1058
1063
  }
1059
1064
  };
1060
1065
  const configuredActions = Number(options.maxNativeActions);
1061
- const isAutonomous = (options as any).hardBudget === false;
1062
- let maxNativeActions = Number.isSafeInteger(configuredActions) && configuredActions >= 0
1063
- ? configuredActions : desktopTask ? 12 : isAutonomous ? Infinity : 35;
1066
+ const maxNativeActions = peerNativeActionCeiling(configuredActions, desktopTask);
1064
1067
  let nativeActionStarts = 0;
1065
1068
  let lastMutationActionIndex = 0;
1066
1069
  let progressiveActionsCount = 0;
@@ -1085,21 +1088,21 @@ export class AntigravityProvider extends LLMProvider {
1085
1088
  // disabled. Users can set a lower task budget through the existing UI.
1086
1089
  const remainingTaskBudget = Number(options.maxTokensThisCall);
1087
1090
  const rawTokenLimit = Number((options as any).tokenLimit);
1088
- const hasExplicitLimit = (Number.isFinite(remainingTaskBudget) && remainingTaskBudget > 0)
1089
- || (Number.isFinite(rawTokenLimit) && rawTokenLimit > 0);
1090
1091
  const countReportedTotal = options.tokenBudgetBasis !== 'noncached';
1091
- const defaultTokenLimit = 100_000;
1092
- const tokenLimit = Number.isFinite(remainingTaskBudget) && remainingTaskBudget > 0
1093
- ? remainingTaskBudget
1094
- : (Number.isFinite(rawTokenLimit) && rawTokenLimit > 0
1095
- ? rawTokenLimit
1096
- : defaultTokenLimit);
1097
- const wallTimer = desktopTask ? setTimeout(() => {
1098
- const error = new Error('Antigravity exceeded the 180-second desktop task limit. Outcome is unverified.') as Error & { code: string };
1099
- error.code = 'AGY_DESKTOP_TASK_LIMIT';
1092
+ // A peer may execute many model steps without returning to AgentLoop.
1093
+ // Count uncached input + output for the conservative default ceiling.
1094
+ const requestedLimit = Number.isFinite(remainingTaskBudget) && remainingTaskBudget > 0
1095
+ ? remainingTaskBudget : Number.isFinite(rawTokenLimit) && rawTokenLimit > 0
1096
+ ? rawTokenLimit : Infinity;
1097
+ const tokenLimit = peerCallTokenCeiling(requestedLimit);
1098
+ const wallMs = desktopTask ? Math.min(DESKTOP_TASK_WALL_MS,
1099
+ remainingWall === null ? DESKTOP_TASK_WALL_MS : remainingWall) : null;
1100
+ const wallTimer = wallMs !== null ? setTimeout(() => {
1101
+ const error = createBudgetError('AGY_DESKTOP_TASK_LIMIT',
1102
+ 'Antigravity exceeded the remaining desktop task wall-clock allowance. Outcome is unverified.');
1100
1103
  safeReject(error);
1101
1104
  terminateChild();
1102
- }, 180_000) : null;
1105
+ }, wallMs) : null;
1103
1106
  wallTimer?.unref();
1104
1107
 
1105
1108
  const cleanup = () => {
@@ -1210,21 +1213,15 @@ export class AntigravityProvider extends LLMProvider {
1210
1213
  const reportedTotal = partialUsage.promptTokens + partialUsage.completionTokens;
1211
1214
  const uncachedTotal = noncachedTokens(partialUsage);
1212
1215
  const spentAgainstLimit = countReportedTotal ? reportedTotal : uncachedTotal;
1213
- if (Number.isFinite(tokenLimit) && tokenLimit > 0
1214
- && spentAgainstLimit >= tokenLimit) {
1215
- if ((options as any).hardBudget === false) {
1216
- if (process.env.CAUSYNE_DEBUG === '1') {
1217
- console.log(`[BUDGET] Turn spent ${spentAgainstLimit} tokens against soft checkpoint ${tokenLimit}. Continuing execution.`);
1218
- }
1219
- } else {
1220
- const error = Object.assign(
1221
- new Error(`Antigravity reported ${spentAgainstLimit} tokens against a ${tokenLimit}-token per-call ceiling. This turn stopped and its outcome is unverified.`),
1222
- { code: 'AGY_TOKEN_BUDGET', tokenLimit, partialUsage: { ...partialUsage } }
1223
- );
1224
- safeReject(error);
1225
- terminateChild();
1226
- return;
1227
- }
1216
+ if (spentAgainstLimit >= tokenLimit) {
1217
+ const error = Object.assign(
1218
+ createBudgetError('AGY_TOKEN_BUDGET',
1219
+ `Antigravity reached the ${tokenLimit}-token per-call ceiling. Outcome is unverified.`),
1220
+ { tokenLimit, partialUsage: { ...partialUsage } }
1221
+ );
1222
+ safeReject(error);
1223
+ terminateChild();
1224
+ return;
1228
1225
  }
1229
1226
  }
1230
1227
  }
@@ -1321,7 +1318,7 @@ export class AntigravityProvider extends LLMProvider {
1321
1318
 
1322
1319
  if (newNativeAction) {
1323
1320
  nativeActionStarts++;
1324
- if (!isAutonomous && Number.isFinite(maxNativeActions) && nativeActionStarts > maxNativeActions) {
1321
+ if (nativeActionStarts > maxNativeActions) {
1325
1322
  const error = new Error(`Antigravity reached the ${maxNativeActions} native-action turn checkpoint. Work remains unfinished; continue from the saved session.`) as Error & { code: string };
1326
1323
  error.code = 'AGY_NATIVE_ACTION_BUDGET';
1327
1324
  safeReject(error);
@@ -1699,16 +1696,11 @@ export class AntigravityProvider extends LLMProvider {
1699
1696
  const uncachedTotal = noncachedTokens(response.usage);
1700
1697
  const spentAgainstLimit = countReportedTotal ? reportedTotal : uncachedTotal;
1701
1698
  if (spentAgainstLimit >= tokenLimit) {
1702
- if ((options as any).hardBudget === false) {
1703
- if (process.env.CAUSYNE_DEBUG === '1') {
1704
- console.log(`[BUDGET] Turn finished with ${spentAgainstLimit} tokens against soft checkpoint ${tokenLimit}. Preserving result.`);
1705
- }
1706
- } else {
1707
- Object.assign(partialUsage, response.usage);
1708
- safeReject(Object.assign(new Error(`Antigravity reached its ${tokenLimit}-token checkpoint. Work remains unverified.`),
1709
- { code: 'AGY_TOKEN_BUDGET', tokenLimit, partialUsage: { ...partialUsage } }));
1710
- return;
1711
- }
1699
+ Object.assign(partialUsage, response.usage);
1700
+ safeReject(Object.assign(createBudgetError('AGY_TOKEN_BUDGET',
1701
+ `Antigravity reached its ${tokenLimit}-token checkpoint. Work remains unverified.`),
1702
+ { tokenLimit, partialUsage: { ...partialUsage } }));
1703
+ return;
1712
1704
  }
1713
1705
  safeResolve(response);
1714
1706
  });
@@ -1723,10 +1715,8 @@ export class AntigravityProvider extends LLMProvider {
1723
1715
  try {
1724
1716
  return await this._executeOnce(messages, options);
1725
1717
  } catch (err: any) {
1726
- if (options.signal?.aborted || err?.name === 'AbortError') {
1727
- throw err;
1728
- }
1729
- if (err?.code === 'AGY_NATIVE_ACTION_DENIED' || err?.code === 'AGY_TOKEN_BUDGET' || err?.code === 'PROVIDER_NO_PROGRESS') {
1718
+ if (!shouldRetryPeerError(err, options.signal?.aborted === true || err?.name === 'AbortError')
1719
+ || err?.code === 'AGY_NATIVE_ACTION_DENIED' || err?.code === 'PROVIDER_NO_PROGRESS') {
1730
1720
  throw err;
1731
1721
  }
1732
1722
  const msg = String(err?.message || '').toLowerCase();
@@ -27,6 +27,9 @@ export class TokenTracker {
27
27
  sessionTokens;
28
28
  sessionCostUsd;
29
29
  largestStepTokens;
30
+ // Applied after every settings reload; prevents trackUsage() from silently
31
+ // dropping the limit selected at the beginning of this run.
32
+ enforcedTaskTokenLimit;
30
33
  constructor() {
31
34
  this.config = loadConfig();
32
35
  this.budget = this.config.tokenBudget || { enabled: false };
@@ -35,6 +38,7 @@ export class TokenTracker {
35
38
  this.sessionTokens = 0;
36
39
  this.sessionCostUsd = 0;
37
40
  this.largestStepTokens = 0;
41
+ this.enforcedTaskTokenLimit = null;
38
42
  this.ensureUsageDir();
39
43
  }
40
44
  getPricing(promptTokens = 0) {
@@ -178,6 +182,7 @@ export class TokenTracker {
178
182
  async trackMediaUsage(provider, mediaType, model, quantityUnits = 1, onWarning = null) {
179
183
  this.config = loadConfig();
180
184
  this.budget = this.config.tokenBudget || { enabled: false };
185
+ this.applyEnforcedTaskLimit();
181
186
  const unitPrice = this.getMediaPricing(provider, model, mediaType);
182
187
  const cost = unitPrice * (quantityUnits || 1);
183
188
  const equivalentTokens = Math.round(cost / 0.000002);
@@ -354,12 +359,30 @@ export class TokenTracker {
354
359
  }
355
360
  }
356
361
  }
362
+ setEnforcedTaskLimit(limit) {
363
+ this.enforcedTaskTokenLimit = Number.isSafeInteger(limit) && Number(limit) > 0
364
+ ? Number(limit) : null;
365
+ this.applyEnforcedTaskLimit();
366
+ }
367
+ applyEnforcedTaskLimit() {
368
+ const limit = this.enforcedTaskTokenLimit;
369
+ if (limit === null)
370
+ return;
371
+ this.budget = {
372
+ ...this.budget,
373
+ enabled: true,
374
+ hardStop: true,
375
+ maxTokensPerTask: limit
376
+ };
377
+ }
357
378
  resetTask() {
379
+ this.enforcedTaskTokenLimit = null;
358
380
  this.taskTokens = 0;
359
381
  this.taskCostUsd = 0;
360
382
  this.largestStepTokens = 0;
361
383
  }
362
384
  resetSession() {
385
+ this.enforcedTaskTokenLimit = null;
363
386
  this.sessionTokens = 0;
364
387
  this.sessionCostUsd = 0;
365
388
  this.taskTokens = 0;
@@ -391,6 +414,7 @@ export class TokenTracker {
391
414
  async trackUsage(promptTokens, completionTokens, onWarning = null, usageDetail = null) {
392
415
  this.config = loadConfig();
393
416
  this.budget = this.config.tokenBudget || { enabled: false };
417
+ this.applyEnforcedTaskLimit();
394
418
  const finite = (v) => (Number.isFinite(v) ? Math.max(0, Number(v)) : 0);
395
419
  const pTokens = finite(promptTokens);
396
420
  const cTokens = finite(completionTokens);
@@ -107,6 +107,9 @@ export class TokenTracker {
107
107
  sessionTokens: number;
108
108
  sessionCostUsd: number;
109
109
  largestStepTokens: number;
110
+ // Applied after every settings reload; prevents trackUsage() from silently
111
+ // dropping the limit selected at the beginning of this run.
112
+ enforcedTaskTokenLimit: number | null;
110
113
 
111
114
  constructor() {
112
115
  this.config = loadConfig() as TrackerConfig;
@@ -116,6 +119,7 @@ export class TokenTracker {
116
119
  this.sessionTokens = 0;
117
120
  this.sessionCostUsd = 0;
118
121
  this.largestStepTokens = 0;
122
+ this.enforcedTaskTokenLimit = null;
119
123
  this.ensureUsageDir();
120
124
  }
121
125
 
@@ -260,6 +264,7 @@ export class TokenTracker {
260
264
  ): Promise<{ allowed: boolean; used: number; costUsd: number; taskCostUsd: number; equivalentTokens: number; reason?: string }> {
261
265
  this.config = loadConfig() as TrackerConfig;
262
266
  this.budget = this.config.tokenBudget || { enabled: false };
267
+ this.applyEnforcedTaskLimit();
263
268
 
264
269
  const unitPrice = this.getMediaPricing(provider, model, mediaType);
265
270
  const cost = unitPrice * (quantityUnits || 1);
@@ -468,13 +473,32 @@ export class TokenTracker {
468
473
  }
469
474
  }
470
475
 
476
+ setEnforcedTaskLimit(limit: number | null): void {
477
+ this.enforcedTaskTokenLimit = Number.isSafeInteger(limit) && Number(limit) > 0
478
+ ? Number(limit) : null;
479
+ this.applyEnforcedTaskLimit();
480
+ }
481
+
482
+ private applyEnforcedTaskLimit(): void {
483
+ const limit = this.enforcedTaskTokenLimit;
484
+ if (limit === null) return;
485
+ this.budget = {
486
+ ...this.budget,
487
+ enabled: true,
488
+ hardStop: true,
489
+ maxTokensPerTask: limit
490
+ };
491
+ }
492
+
471
493
  resetTask(): void {
494
+ this.enforcedTaskTokenLimit = null;
472
495
  this.taskTokens = 0;
473
496
  this.taskCostUsd = 0;
474
497
  this.largestStepTokens = 0;
475
498
  }
476
499
 
477
500
  resetSession(): void {
501
+ this.enforcedTaskTokenLimit = null;
478
502
  this.sessionTokens = 0;
479
503
  this.sessionCostUsd = 0;
480
504
  this.taskTokens = 0;
@@ -514,6 +538,7 @@ export class TokenTracker {
514
538
  ): Promise<SettledUsage> {
515
539
  this.config = loadConfig() as TrackerConfig;
516
540
  this.budget = this.config.tokenBudget || { enabled: false };
541
+ this.applyEnforcedTaskLimit();
517
542
 
518
543
  const finite = (v: number | undefined | null): number => (Number.isFinite(v) ? Math.max(0, Number(v)) : 0);
519
544
  const pTokens = finite(promptTokens);