@causyne/agent 1.20.97 → 1.20.98

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.97",
3
+ "version": "1.20.98",
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,7 +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
+ import { resolveTaskTokenCeiling, peerCallTokenCeiling, isAntigravityPeer, isTerminalBudgetFailure, desktopDeadline, remainingDesktopTime, DEFAULT_AGY_TASK_TOKENS } from './budget/budgetPolicy.js';
10
10
  import { PEER_COLLABORATION_POLICY } from './providers/collaborationPolicy.js';
11
11
  import { createHash, randomUUID } from 'crypto';
12
12
  import { execFileSync } from 'node:child_process';
@@ -1725,7 +1725,10 @@ export class AgentLoop {
1725
1725
  });
1726
1726
  this.tokenTracker.setEnforcedTaskLimit(guardLimit);
1727
1727
  const taskArchetype = determineToolScope(this.currentTaskPrompt || this.userPrompt || '', this.taskShape).archetype;
1728
- this._taskWallDeadlineAt = desktopDeadline(Date.now(), taskArchetype);
1728
+ // A workspace category must not create an unrequested 180-second kill switch.
1729
+ const strictDesktopWallMs = this.tokenTracker.budget?.enabled && this.tokenTracker.budget?.hardStop
1730
+ ? this.tokenTracker.budget.maxWallTimeMs : undefined;
1731
+ this._taskWallDeadlineAt = desktopDeadline(Date.now(), taskArchetype, strictDesktopWallMs);
1729
1732
  if (!this.llm) {
1730
1733
  throw new Error("API Key Required. Causyne is a 100% Sovereign BYOK Engine. Please configure your API Provider and Key in Settings.");
1731
1734
  }
@@ -2056,6 +2059,7 @@ export class AgentLoop {
2056
2059
  const isAutonomousMode = (this.config.autonomyMode || 'C') === 'C';
2057
2060
  const recoveryPaths = new Set();
2058
2061
  let modelCallIndex = 0;
2062
+ let softUsageNoticeIssued = false;
2059
2063
  let mediaExplorationRecoveries = 0;
2060
2064
  let taskMutationCount = 0;
2061
2065
  let reasoningOnlyRecoveries = 0;
@@ -2515,9 +2519,13 @@ You are operating in a text-and-code modality without direct image pixel renderi
2515
2519
  hardBudget: hardBudget,
2516
2520
  // The peer can perform multiple billable model steps inside one
2517
2521
  // chat() call. The per-call bound is independent of autonomy mode.
2522
+ // Only explicit hard budgets constrain the peer. No synthetic 32k sub-limit.
2518
2523
  maxTokensThisCall: isAntigravityPeer(this.config.provider)
2519
- ? peerCallTokenCeiling(configuredRemainingBudget)
2524
+ ? (hardBudget ? peerCallTokenCeiling(configuredRemainingBudget) ?? undefined : undefined)
2520
2525
  : Number.isFinite(configuredRemainingBudget) && hardBudget ? configuredRemainingBudget : undefined,
2526
+ onBudgetAdvisory: (details) => {
2527
+ this.emitEvent({ type: 'notice', message: `Usage advisory: ${details.usedTokens.toLocaleString()} fresh tokens during this ${details.scope}; no implicit hard stop. /stop cancels; configure a hard budget to enforce a ceiling.` });
2528
+ },
2521
2529
  tokenBudgetBasis: isAntigravityPeer(this.config.provider) ? 'noncached'
2522
2530
  : Number.isFinite(configuredRemainingBudget) ? 'total' : 'noncached',
2523
2531
  tokenLimit: hardBudget && Number.isFinite(remainingBudget) && remainingBudget > 0
@@ -2814,6 +2822,13 @@ You are operating in a text-and-code modality without direct image pixel renderi
2814
2822
  ? 'external_subscription_unavailable' : 'rate_card_estimate',
2815
2823
  callEstimatedCostUsd: this.tokenTracker.calculateCost(response.usage.promptTokens, response.usage.completionTokens, response.usage)
2816
2824
  });
2825
+ // Soft advisory only; repeated status frames must not consume tokens or stop work.
2826
+ if (isAntigravityPeer(this.config.provider) && !hardBudget && !softUsageNoticeIssued
2827
+ && this.tokenTracker.taskTokens >= DEFAULT_AGY_TASK_TOKENS) {
2828
+ softUsageNoticeIssued = true;
2829
+ this.emitEvent({ type: 'notice', message: `Task usage passed ${DEFAULT_AGY_TASK_TOKENS.toLocaleString()} fresh tokens. This is an advisory, not a stop. Use /stop or set a user hard budget to limit further calls.` });
2830
+ auditLog.log({ event: 'task_usage_advisory', taskId: this.taskId, freshTokens: this.tokenTracker.taskTokens });
2831
+ }
2817
2832
  const cachedTokens = response.usage.cachedPromptTokens || 0;
2818
2833
  if (cachedTokens > 0) {
2819
2834
  this.debugLog(`prompt cache hit: ${cachedTokens.toLocaleString()} of ${response.usage.promptTokens.toLocaleString()} input tokens served from cache`);
package/src/agentLoop.ts CHANGED
@@ -6,7 +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
+ import { resolveTaskTokenCeiling, peerCallTokenCeiling, isAntigravityPeer, isTerminalBudgetFailure, desktopDeadline, remainingDesktopTime, DEFAULT_AGY_TASK_TOKENS } from './budget/budgetPolicy.js';
10
10
  import { PEER_COLLABORATION_POLICY } from './providers/collaborationPolicy.js';
11
11
  import type { RequestPermissionRequest, RequestPermissionResponse } from './acp/protocol.js';
12
12
  import { createHash, randomUUID } from 'crypto';
@@ -1787,7 +1787,10 @@ export class AgentLoop {
1787
1787
  const taskArchetype = determineToolScope(
1788
1788
  this.currentTaskPrompt || this.userPrompt || '', this.taskShape
1789
1789
  ).archetype;
1790
- this._taskWallDeadlineAt = desktopDeadline(Date.now(), taskArchetype);
1790
+ // A workspace category must not create an unrequested 180-second kill switch.
1791
+ const strictDesktopWallMs = this.tokenTracker.budget?.enabled && this.tokenTracker.budget?.hardStop
1792
+ ? this.tokenTracker.budget.maxWallTimeMs : undefined;
1793
+ this._taskWallDeadlineAt = desktopDeadline(Date.now(), taskArchetype, strictDesktopWallMs);
1791
1794
  if (!this.llm) {
1792
1795
  throw new Error("API Key Required. Causyne is a 100% Sovereign BYOK Engine. Please configure your API Provider and Key in Settings.");
1793
1796
  }
@@ -2137,6 +2140,7 @@ export class AgentLoop {
2137
2140
  const isAutonomousMode = (this.config.autonomyMode || 'C') === 'C';
2138
2141
  const recoveryPaths = new Set<string>();
2139
2142
  let modelCallIndex = 0;
2143
+ let softUsageNoticeIssued = false;
2140
2144
  let mediaExplorationRecoveries = 0;
2141
2145
  let taskMutationCount = 0;
2142
2146
  let reasoningOnlyRecoveries = 0;
@@ -2625,9 +2629,14 @@ You are operating in a text-and-code modality without direct image pixel renderi
2625
2629
  hardBudget: hardBudget,
2626
2630
  // The peer can perform multiple billable model steps inside one
2627
2631
  // chat() call. The per-call bound is independent of autonomy mode.
2632
+ // Only explicit hard budgets constrain the peer. No synthetic 32k sub-limit.
2628
2633
  maxTokensThisCall: isAntigravityPeer(this.config.provider)
2629
- ? peerCallTokenCeiling(configuredRemainingBudget)
2634
+ ? (hardBudget ? peerCallTokenCeiling(configuredRemainingBudget) ?? undefined : undefined)
2630
2635
  : Number.isFinite(configuredRemainingBudget) && hardBudget ? configuredRemainingBudget : undefined,
2636
+ onBudgetAdvisory: (details: { scope: string; usedTokens: number; threshold: number }) => {
2637
+ this.emitEvent({ type: 'notice', message:
2638
+ `Usage advisory: ${details.usedTokens.toLocaleString()} fresh tokens during this ${details.scope}; no implicit hard stop. /stop cancels; configure a hard budget to enforce a ceiling.` });
2639
+ },
2631
2640
  tokenBudgetBasis: isAntigravityPeer(this.config.provider) ? 'noncached'
2632
2641
  : Number.isFinite(configuredRemainingBudget) ? 'total' : 'noncached',
2633
2642
  tokenLimit: hardBudget && Number.isFinite(remainingBudget) && remainingBudget > 0
@@ -2924,6 +2933,15 @@ You are operating in a text-and-code modality without direct image pixel renderi
2924
2933
  )
2925
2934
  });
2926
2935
 
2936
+ // Soft advisory only; repeated status frames must not consume tokens or stop work.
2937
+ if (isAntigravityPeer(this.config.provider) && !hardBudget && !softUsageNoticeIssued
2938
+ && this.tokenTracker.taskTokens >= DEFAULT_AGY_TASK_TOKENS) {
2939
+ softUsageNoticeIssued = true;
2940
+ this.emitEvent({ type: 'notice', message:
2941
+ `Task usage passed ${DEFAULT_AGY_TASK_TOKENS.toLocaleString()} fresh tokens. This is an advisory, not a stop. Use /stop or set a user hard budget to limit further calls.` });
2942
+ auditLog.log({ event: 'task_usage_advisory', taskId: this.taskId, freshTokens: this.tokenTracker.taskTokens });
2943
+ }
2944
+
2927
2945
  const cachedTokens = response.usage.cachedPromptTokens || 0;
2928
2946
  if (cachedTokens > 0) {
2929
2947
  this.debugLog(`prompt cache hit: ${cachedTokens.toLocaleString()} of ${response.usage.promptTokens.toLocaleString()} input tokens served from cache`);
@@ -1,22 +1,22 @@
1
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.
2
+ * Causyne resource policy, version 2.
3
+ *
4
+ * Design invariant: an inferred task category, autonomy mode or provider name
5
+ * must NEVER fabricate a hard resource ceiling. Explicit user/worker ceilings
6
+ * remain hard. Default thresholds are advisory telemetry only.
7
+ *
8
+ * Native tool-stall protections and provider operation timeouts are separate
9
+ * safety controls and remain active outside this policy.
6
10
  */
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;
11
+ export const DEFAULT_AGY_TASK_TOKENS = 80_000; // non-blocking advisory only
12
+ export const DEFAULT_AGY_CALL_TOKENS = 32_000; // non-blocking advisory only
13
+ export const DEFAULT_AGY_NATIVE_ACTIONS = 128; // retained for UI guidance only
14
+ export const DEFAULT_DESKTOP_NATIVE_ACTIONS = 12; // retained for UI guidance only
15
+ export const DESKTOP_TASK_WALL_MS = 180_000; // legacy hint, not a default deadline
12
16
  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'
17
+ 'TASK_TOKEN_BUDGET', 'PROVIDER_TOKEN_BUDGET',
18
+ 'AGY_DESKTOP_TASK_LIMIT', 'AGY_TOKEN_BUDGET',
19
+ 'AGY_NATIVE_ACTION_BUDGET', 'AGY_TASK_DEADLINE', 'TASK_WALL_BUDGET'
20
20
  ]);
21
21
  export function positiveSafeInteger(value) {
22
22
  if (typeof value !== 'number' && typeof value !== 'string')
@@ -29,36 +29,37 @@ export function positiveSafeInteger(value) {
29
29
  export function isAntigravityPeer(provider) {
30
30
  return /^(?:antigravity|agy)(?:$|[/:\s])/i.test(String(provider ?? '').trim());
31
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
- */
32
+ /** Only an explicit worker limit or enabled, HARD user budget can stop a task. */
38
33
  export function resolveTaskTokenCeiling(options) {
39
34
  const worker = positiveSafeInteger(options.workerLimit);
40
- const configured = options.configured?.enabled === true
35
+ const configured = options.configured?.enabled === true && options.configured.hardStop === true
41
36
  ? positiveSafeInteger(options.configured.maxTokensPerTask)
42
37
  : 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;
38
+ if (worker === null)
39
+ return configured;
40
+ if (configured === null)
41
+ return worker;
42
+ return Math.min(worker, configured);
47
43
  }
48
- /** A finite peer call bound even when the caller passes hardBudget:false. */
44
+ /**
45
+ * The entire remaining explicitly authorized ceiling is usable in one call.
46
+ * No silent 32k sub-ceiling: doing so discards successful peer output.
47
+ * Missing/unbounded input means no token checkpoint, not a hidden default.
48
+ * Zero is an explicit exhausted limit.
49
+ */
49
50
  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);
51
+ if (remaining === 0 || remaining === '0')
52
+ return 0;
53
+ return positiveSafeInteger(remaining);
55
54
  }
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);
55
+ /**
56
+ * Native action count becomes a hard stop only when an explicit option is set.
57
+ * Independently, the peer's repetition / no-progress circuit breakers remain.
58
+ */
59
+ export function peerNativeActionCeiling(configured, _desktopTask) {
60
+ if (configured === 0 || configured === '0')
61
+ return 0;
62
+ return positiveSafeInteger(configured);
62
63
  }
63
64
  export function isTerminalBudgetFailure(error) {
64
65
  if (!error || typeof error !== 'object')
@@ -78,9 +79,13 @@ export function hasBillablePartialUsage(error) {
78
79
  export function shouldRetryPeerError(error, aborted = false) {
79
80
  return !aborted && !isTerminalBudgetFailure(error) && !hasBillablePartialUsage(error);
80
81
  }
81
- export function desktopDeadline(startMs, archetype) {
82
- return archetype === 'desktop_personalization' && Number.isFinite(startMs)
83
- ? startMs + DESKTOP_TASK_WALL_MS : null;
82
+ /** User opt-in only: the old 180-second desktop hard stop was task-breaking. */
83
+ export function desktopDeadline(startMs, archetype, hardWallMs) {
84
+ const limit = positiveSafeInteger(hardWallMs);
85
+ if (archetype !== 'desktop_personalization' || !Number.isFinite(startMs) || limit === null)
86
+ return null;
87
+ const deadline = startMs + limit;
88
+ return Number.isSafeInteger(deadline) ? deadline : null;
84
89
  }
85
90
  export function remainingDesktopTime(deadlineMs, nowMs = Date.now()) {
86
91
  if (typeof deadlineMs !== 'number' || !Number.isFinite(deadlineMs))
@@ -1,23 +1,23 @@
1
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.
2
+ * Causyne resource policy, version 2.
3
+ *
4
+ * Design invariant: an inferred task category, autonomy mode or provider name
5
+ * must NEVER fabricate a hard resource ceiling. Explicit user/worker ceilings
6
+ * remain hard. Default thresholds are advisory telemetry only.
7
+ *
8
+ * Native tool-stall protections and provider operation timeouts are separate
9
+ * safety controls and remain active outside this policy.
6
10
  */
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;
11
+ export const DEFAULT_AGY_TASK_TOKENS = 80_000; // non-blocking advisory only
12
+ export const DEFAULT_AGY_CALL_TOKENS = 32_000; // non-blocking advisory only
13
+ export const DEFAULT_AGY_NATIVE_ACTIONS = 128; // retained for UI guidance only
14
+ export const DEFAULT_DESKTOP_NATIVE_ACTIONS = 12; // retained for UI guidance only
15
+ export const DESKTOP_TASK_WALL_MS = 180_000; // legacy hint, not a default deadline
12
16
 
13
17
  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'
18
+ 'TASK_TOKEN_BUDGET', 'PROVIDER_TOKEN_BUDGET',
19
+ 'AGY_DESKTOP_TASK_LIMIT', 'AGY_TOKEN_BUDGET',
20
+ 'AGY_NATIVE_ACTION_BUDGET', 'AGY_TASK_DEADLINE', 'TASK_WALL_BUDGET'
21
21
  ]);
22
22
 
23
23
  export interface TaskBudgetOptions {
@@ -25,6 +25,7 @@ export interface TaskBudgetOptions {
25
25
  workerLimit?: unknown;
26
26
  configured?: {
27
27
  enabled?: boolean | undefined;
28
+ hardStop?: boolean | undefined;
28
29
  maxTokensPerTask?: unknown;
29
30
  } | null | undefined;
30
31
  }
@@ -40,37 +41,35 @@ export function isAntigravityPeer(provider: unknown): boolean {
40
41
  return /^(?:antigravity|agy)(?:$|[/:\s])/i.test(String(provider ?? '').trim());
41
42
  }
42
43
 
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
- */
44
+ /** Only an explicit worker limit or enabled, HARD user budget can stop a task. */
49
45
  export function resolveTaskTokenCeiling(options: TaskBudgetOptions): number | null {
50
46
  const worker = positiveSafeInteger(options.workerLimit);
51
- const configured = options.configured?.enabled === true
47
+ const configured = options.configured?.enabled === true && options.configured.hardStop === true
52
48
  ? positiveSafeInteger(options.configured.maxTokensPerTask)
53
49
  : 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;
50
+ if (worker === null) return configured;
51
+ if (configured === null) return worker;
52
+ return Math.min(worker, configured);
57
53
  }
58
54
 
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);
55
+ /**
56
+ * The entire remaining explicitly authorized ceiling is usable in one call.
57
+ * No silent 32k sub-ceiling: doing so discards successful peer output.
58
+ * Missing/unbounded input means no token checkpoint, not a hidden default.
59
+ * Zero is an explicit exhausted limit.
60
+ */
61
+ export function peerCallTokenCeiling(remaining: unknown): number | null {
62
+ if (remaining === 0 || remaining === '0') return 0;
63
+ return positiveSafeInteger(remaining);
66
64
  }
67
65
 
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);
66
+ /**
67
+ * Native action count becomes a hard stop only when an explicit option is set.
68
+ * Independently, the peer's repetition / no-progress circuit breakers remain.
69
+ */
70
+ export function peerNativeActionCeiling(configured: unknown, _desktopTask: boolean): number | null {
71
+ if (configured === 0 || configured === '0') return 0;
72
+ return positiveSafeInteger(configured);
74
73
  }
75
74
 
76
75
  export function isTerminalBudgetFailure(error: unknown): boolean {
@@ -92,9 +91,12 @@ export function shouldRetryPeerError(error: unknown, aborted = false): boolean {
92
91
  return !aborted && !isTerminalBudgetFailure(error) && !hasBillablePartialUsage(error);
93
92
  }
94
93
 
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;
94
+ /** User opt-in only: the old 180-second desktop hard stop was task-breaking. */
95
+ export function desktopDeadline(startMs: number, archetype: string, hardWallMs?: unknown): number | null {
96
+ const limit = positiveSafeInteger(hardWallMs);
97
+ if (archetype !== 'desktop_personalization' || !Number.isFinite(startMs) || limit === null) return null;
98
+ const deadline = startMs + limit;
99
+ return Number.isSafeInteger(deadline) ? deadline : null;
98
100
  }
99
101
 
100
102
  export function remainingDesktopTime(deadlineMs: unknown, nowMs = Date.now()): number | null {
@@ -17,7 +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
+ import { peerCallTokenCeiling, peerNativeActionCeiling, shouldRetryPeerError, remainingDesktopTime, createBudgetError, DEFAULT_AGY_CALL_TOKENS } from '../budget/budgetPolicy.js';
21
21
  import { extractToolCallJsonObjects, stripToolCallMarkup, stripThinkBlocks, resolveToolCallEnvelopeArguments } from '../implementationPlan.js';
22
22
  /**
23
23
  * Baseline fallback models for instant offline availability.
@@ -955,7 +955,7 @@ export class AntigravityProvider extends LLMProvider {
955
955
  'Use only the tools needed. Search and download alone are not completion. ' +
956
956
  'After setting the desktop picture, read back the actual system wallpaper and compare it with the intended image. ' +
957
957
  'If a command is denied or the readback does not confirm the change, report the blocker honestly. ' +
958
- 'Keep native tool actions within 12; use Causyne tool calls when a native action is blocked.\n\n' + promptText;
958
+ 'Avoid repeated or unnecessary actions; use Causyne tools when a native action is blocked.\n\n' + promptText;
959
959
  }
960
960
  const taskArchetype = options.taskArchetype || determineToolScope(latestPrompt).archetype;
961
961
  const webOrGameTask = taskArchetype === 'web_engineering' || taskArchetype === 'game_development';
@@ -1021,7 +1021,7 @@ export class AntigravityProvider extends LLMProvider {
1021
1021
  // A process that already exited needs no further action.
1022
1022
  }
1023
1023
  };
1024
- const configuredActions = Number(options.maxNativeActions);
1024
+ const configuredActions = options.maxNativeActions;
1025
1025
  const maxNativeActions = peerNativeActionCeiling(configuredActions, desktopTask);
1026
1026
  let nativeActionStarts = 0;
1027
1027
  let lastMutationActionIndex = 0;
@@ -1042,19 +1042,24 @@ export class AntigravityProvider extends LLMProvider {
1042
1042
  promptTokens: 0, completionTokens: 0, cachedPromptTokens: 0,
1043
1043
  thinkingTokens: 0, measurement: 'provider_reported', cacheMeasurement: 'provider_reported'
1044
1044
  };
1045
- // A headless peer can run many paid model steps before chat() returns.
1046
- // Keep a finite per-call ceiling even when the optional task budget is
1047
- // disabled. Users can set a lower task budget through the existing UI.
1048
- const remainingTaskBudget = Number(options.maxTokensThisCall);
1049
- const rawTokenLimit = Number(options.tokenLimit);
1045
+ // Never invent a 32k token limit or 180s task deadline for a user.
1046
+ // Explicit user hard caps are still enforced on streamed steps.
1050
1047
  const countReportedTotal = options.tokenBudgetBasis !== 'noncached';
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;
1048
+ const tokenLimit = peerCallTokenCeiling(options.maxTokensThisCall)
1049
+ ?? peerCallTokenCeiling(options.tokenLimit);
1050
+ const wallMs = desktopTask ? remainingWall : null;
1051
+ let softCallNoticeIssued = false;
1052
+ const noteSoftUsage = (usedTokens) => {
1053
+ if (tokenLimit !== null || softCallNoticeIssued || usedTokens < DEFAULT_AGY_CALL_TOKENS)
1054
+ return;
1055
+ softCallNoticeIssued = true;
1056
+ if (typeof options.onBudgetAdvisory === 'function') {
1057
+ try {
1058
+ options.onBudgetAdvisory({ scope: 'provider call', usedTokens, threshold: DEFAULT_AGY_CALL_TOKENS });
1059
+ }
1060
+ catch { /* UI callbacks must not break the peer's stream. */ }
1061
+ }
1062
+ };
1058
1063
  const wallTimer = wallMs !== null ? setTimeout(() => {
1059
1064
  const error = createBudgetError('AGY_DESKTOP_TASK_LIMIT', 'Antigravity exceeded the remaining desktop task wall-clock allowance. Outcome is unverified.');
1060
1065
  safeReject(error);
@@ -1116,6 +1121,11 @@ export class AntigravityProvider extends LLMProvider {
1116
1121
  }
1117
1122
  options.signal.addEventListener('abort', onAbort, { once: true });
1118
1123
  }
1124
+ if (tokenLimit === 0) {
1125
+ safeReject(createBudgetError('AGY_TOKEN_BUDGET', 'Explicit per-call token allowance is exhausted.'));
1126
+ terminateChild();
1127
+ return;
1128
+ }
1119
1129
  // Feed prompt directly into child process stdin, then close stdin
1120
1130
  try {
1121
1131
  child.stdin.on('error', () => { });
@@ -1170,7 +1180,8 @@ export class AntigravityProvider extends LLMProvider {
1170
1180
  const reportedTotal = partialUsage.promptTokens + partialUsage.completionTokens;
1171
1181
  const uncachedTotal = noncachedTokens(partialUsage);
1172
1182
  const spentAgainstLimit = countReportedTotal ? reportedTotal : uncachedTotal;
1173
- if (spentAgainstLimit >= tokenLimit) {
1183
+ noteSoftUsage(spentAgainstLimit);
1184
+ if (tokenLimit !== null && spentAgainstLimit >= tokenLimit) {
1174
1185
  const error = Object.assign(createBudgetError('AGY_TOKEN_BUDGET', `Antigravity reached the ${tokenLimit}-token per-call ceiling. Outcome is unverified.`), { tokenLimit, partialUsage: { ...partialUsage } });
1175
1186
  safeReject(error);
1176
1187
  terminateChild();
@@ -1268,7 +1279,7 @@ export class AntigravityProvider extends LLMProvider {
1268
1279
  }
1269
1280
  if (newNativeAction) {
1270
1281
  nativeActionStarts++;
1271
- if (nativeActionStarts > maxNativeActions) {
1282
+ if (maxNativeActions !== null && nativeActionStarts > maxNativeActions) {
1272
1283
  const error = new Error(`Antigravity reached the ${maxNativeActions} native-action turn checkpoint. Work remains unfinished; continue from the saved session.`);
1273
1284
  error.code = 'AGY_NATIVE_ACTION_BUDGET';
1274
1285
  safeReject(error);
@@ -1636,7 +1647,8 @@ export class AntigravityProvider extends LLMProvider {
1636
1647
  const reportedTotal = promptTokens + completionTokens;
1637
1648
  const uncachedTotal = noncachedTokens(response.usage);
1638
1649
  const spentAgainstLimit = countReportedTotal ? reportedTotal : uncachedTotal;
1639
- if (spentAgainstLimit >= tokenLimit) {
1650
+ noteSoftUsage(spentAgainstLimit);
1651
+ if (tokenLimit !== null && spentAgainstLimit >= tokenLimit) {
1640
1652
  Object.assign(partialUsage, response.usage);
1641
1653
  safeReject(Object.assign(createBudgetError('AGY_TOKEN_BUDGET', `Antigravity reached its ${tokenLimit}-token checkpoint. Work remains unverified.`), { tokenLimit, partialUsage: { ...partialUsage } }));
1642
1654
  return;
@@ -16,7 +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
+ import { peerCallTokenCeiling, peerNativeActionCeiling, shouldRetryPeerError, remainingDesktopTime, createBudgetError, DEFAULT_AGY_CALL_TOKENS } from '../budget/budgetPolicy.js';
20
20
  import { extractToolCallJsonObjects, stripToolCallMarkup, stripThinkBlocks, resolveToolCallEnvelopeArguments } from '../implementationPlan.js';
21
21
 
22
22
  /**
@@ -984,7 +984,7 @@ export class AntigravityProvider extends LLMProvider {
984
984
  'Use only the tools needed. Search and download alone are not completion. ' +
985
985
  'After setting the desktop picture, read back the actual system wallpaper and compare it with the intended image. ' +
986
986
  'If a command is denied or the readback does not confirm the change, report the blocker honestly. ' +
987
- 'Keep native tool actions within 12; use Causyne tool calls when a native action is blocked.\n\n' + promptText;
987
+ 'Avoid repeated or unnecessary actions; use Causyne tools when a native action is blocked.\n\n' + promptText;
988
988
  }
989
989
 
990
990
  const taskArchetype = (options as any).taskArchetype || determineToolScope(latestPrompt).archetype;
@@ -1062,7 +1062,7 @@ export class AntigravityProvider extends LLMProvider {
1062
1062
  // A process that already exited needs no further action.
1063
1063
  }
1064
1064
  };
1065
- const configuredActions = Number(options.maxNativeActions);
1065
+ const configuredActions = options.maxNativeActions;
1066
1066
  const maxNativeActions = peerNativeActionCeiling(configuredActions, desktopTask);
1067
1067
  let nativeActionStarts = 0;
1068
1068
  let lastMutationActionIndex = 0;
@@ -1083,20 +1083,21 @@ export class AntigravityProvider extends LLMProvider {
1083
1083
  promptTokens: 0, completionTokens: 0, cachedPromptTokens: 0,
1084
1084
  thinkingTokens: 0, measurement: 'provider_reported', cacheMeasurement: 'provider_reported'
1085
1085
  };
1086
- // A headless peer can run many paid model steps before chat() returns.
1087
- // Keep a finite per-call ceiling even when the optional task budget is
1088
- // disabled. Users can set a lower task budget through the existing UI.
1089
- const remainingTaskBudget = Number(options.maxTokensThisCall);
1090
- const rawTokenLimit = Number((options as any).tokenLimit);
1086
+ // Never invent a 32k token limit or 180s task deadline for a user.
1087
+ // Explicit user hard caps are still enforced on streamed steps.
1091
1088
  const countReportedTotal = options.tokenBudgetBasis !== 'noncached';
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;
1089
+ const tokenLimit = peerCallTokenCeiling(options.maxTokensThisCall)
1090
+ ?? peerCallTokenCeiling((options as any).tokenLimit);
1091
+ const wallMs = desktopTask ? remainingWall : null;
1092
+ let softCallNoticeIssued = false;
1093
+ const noteSoftUsage = (usedTokens: number): void => {
1094
+ if (tokenLimit !== null || softCallNoticeIssued || usedTokens < DEFAULT_AGY_CALL_TOKENS) return;
1095
+ softCallNoticeIssued = true;
1096
+ if (typeof (options as any).onBudgetAdvisory === 'function') {
1097
+ try { (options as any).onBudgetAdvisory({ scope: 'provider call', usedTokens, threshold: DEFAULT_AGY_CALL_TOKENS }); }
1098
+ catch { /* UI callbacks must not break the peer's stream. */ }
1099
+ }
1100
+ };
1100
1101
  const wallTimer = wallMs !== null ? setTimeout(() => {
1101
1102
  const error = createBudgetError('AGY_DESKTOP_TASK_LIMIT',
1102
1103
  'Antigravity exceeded the remaining desktop task wall-clock allowance. Outcome is unverified.');
@@ -1160,6 +1161,11 @@ export class AntigravityProvider extends LLMProvider {
1160
1161
  }
1161
1162
  options.signal.addEventListener('abort', onAbort, { once: true });
1162
1163
  }
1164
+ if (tokenLimit === 0) {
1165
+ safeReject(createBudgetError('AGY_TOKEN_BUDGET', 'Explicit per-call token allowance is exhausted.'));
1166
+ terminateChild();
1167
+ return;
1168
+ }
1163
1169
 
1164
1170
  // Feed prompt directly into child process stdin, then close stdin
1165
1171
  try {
@@ -1213,7 +1219,8 @@ export class AntigravityProvider extends LLMProvider {
1213
1219
  const reportedTotal = partialUsage.promptTokens + partialUsage.completionTokens;
1214
1220
  const uncachedTotal = noncachedTokens(partialUsage);
1215
1221
  const spentAgainstLimit = countReportedTotal ? reportedTotal : uncachedTotal;
1216
- if (spentAgainstLimit >= tokenLimit) {
1222
+ noteSoftUsage(spentAgainstLimit);
1223
+ if (tokenLimit !== null && spentAgainstLimit >= tokenLimit) {
1217
1224
  const error = Object.assign(
1218
1225
  createBudgetError('AGY_TOKEN_BUDGET',
1219
1226
  `Antigravity reached the ${tokenLimit}-token per-call ceiling. Outcome is unverified.`),
@@ -1318,7 +1325,7 @@ export class AntigravityProvider extends LLMProvider {
1318
1325
 
1319
1326
  if (newNativeAction) {
1320
1327
  nativeActionStarts++;
1321
- if (nativeActionStarts > maxNativeActions) {
1328
+ if (maxNativeActions !== null && nativeActionStarts > maxNativeActions) {
1322
1329
  const error = new Error(`Antigravity reached the ${maxNativeActions} native-action turn checkpoint. Work remains unfinished; continue from the saved session.`) as Error & { code: string };
1323
1330
  error.code = 'AGY_NATIVE_ACTION_BUDGET';
1324
1331
  safeReject(error);
@@ -1695,7 +1702,8 @@ export class AntigravityProvider extends LLMProvider {
1695
1702
  const reportedTotal = promptTokens + completionTokens;
1696
1703
  const uncachedTotal = noncachedTokens(response.usage);
1697
1704
  const spentAgainstLimit = countReportedTotal ? reportedTotal : uncachedTotal;
1698
- if (spentAgainstLimit >= tokenLimit) {
1705
+ noteSoftUsage(spentAgainstLimit);
1706
+ if (tokenLimit !== null && spentAgainstLimit >= tokenLimit) {
1699
1707
  Object.assign(partialUsage, response.usage);
1700
1708
  safeReject(Object.assign(createBudgetError('AGY_TOKEN_BUDGET',
1701
1709
  `Antigravity reached its ${tokenLimit}-token checkpoint. Work remains unverified.`),
@@ -30,6 +30,8 @@ export interface TokenBudgetConfig {
30
30
  hardStop?: boolean;
31
31
  maxTokensPerDay?: number;
32
32
  maxTokensPerTask?: number;
33
+ /** Optional HARD wall-clock ceiling for desktop-personalization tasks only. */
34
+ maxWallTimeMs?: number;
33
35
  maxCostUsd?: number;
34
36
  alertThresholdTokens?: number;
35
37
  warningThreshold?: number;