@causyne/agent 1.20.93 → 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.
@@ -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
+ }
@@ -46,6 +46,8 @@ export const RESULT_CAPS = {
46
46
  fs_read: 32000,
47
47
  code_search_ast: 32000,
48
48
  MultiEdit: 32000,
49
+ fs_read_skill: 16000,
50
+ tool_search: 8000,
49
51
 
50
52
  // Command output. Low information density, high volume, and the conclusion is
51
53
  // almost always in the first and last few lines.
@@ -59,7 +59,16 @@ export function pruneExecutedToolArguments(messages, options = {}) {
59
59
  * not make a 60 KB result safe to resend in full on every model call.
60
60
  */
61
61
  export function shortenOversizedToolObservations(messages, options = {}) {
62
- const threshold = Math.max(1, options.threshold ?? 2500);
62
+ const explicitThreshold = options.threshold !== undefined ? Math.max(1, options.threshold) : undefined;
63
+ const thresholdFor = (toolName) => {
64
+ if (explicitThreshold !== undefined)
65
+ return explicitThreshold;
66
+ if (toolName === 'fs_read_skill')
67
+ return 16000;
68
+ if (toolName === 'tool_search')
69
+ return 8000;
70
+ return 2500;
71
+ };
63
72
  let pruned = 0;
64
73
  let reclaimedChars = 0;
65
74
  let spillFailures = 0;
@@ -68,8 +77,14 @@ export function shortenOversizedToolObservations(messages, options = {}) {
68
77
  if (!message || message.role !== 'tool' || typeof message.content !== 'string')
69
78
  continue;
70
79
  const original = message.content;
80
+ const threshold = thresholdFor(message.name);
71
81
  if (original.length <= threshold || original.startsWith(MARKER))
72
82
  continue;
83
+ // Do not truncate an observation a second time when ToolOutputStore has
84
+ // already persisted the complete payload and added its recovery notice.
85
+ if (message.spillPath && original.includes('Causyne ToolOutputStore:') && original.length <= Math.max(threshold + 1000, 4000)) {
86
+ continue;
87
+ }
73
88
  let spillPath = message.spillPath;
74
89
  if (!spillPath) {
75
90
  const spill = spillToolResult(original, {
@@ -70,7 +70,13 @@ export function shortenOversizedToolObservations(
70
70
  messages: ToolObservation[],
71
71
  options: { threshold?: number; taskId?: string } = {}
72
72
  ): ObservationPruneResult {
73
- const threshold = Math.max(1, options.threshold ?? 2500);
73
+ const explicitThreshold = options.threshold !== undefined ? Math.max(1, options.threshold) : undefined;
74
+ const thresholdFor = (toolName?: string): number => {
75
+ if (explicitThreshold !== undefined) return explicitThreshold;
76
+ if (toolName === 'fs_read_skill') return 16000;
77
+ if (toolName === 'tool_search') return 8000;
78
+ return 2500;
79
+ };
74
80
  let pruned = 0;
75
81
  let reclaimedChars = 0;
76
82
  let spillFailures = 0;
@@ -78,7 +84,13 @@ export function shortenOversizedToolObservations(
78
84
  const message = messages[index];
79
85
  if (!message || message.role !== 'tool' || typeof message.content !== 'string') continue;
80
86
  const original = message.content;
87
+ const threshold = thresholdFor(message.name);
81
88
  if (original.length <= threshold || original.startsWith(MARKER)) continue;
89
+ // Do not truncate an observation a second time when ToolOutputStore has
90
+ // already persisted the complete payload and added its recovery notice.
91
+ if (message.spillPath && original.includes('Causyne ToolOutputStore:') && original.length <= Math.max(threshold + 1000, 4000)) {
92
+ continue;
93
+ }
82
94
  let spillPath = message.spillPath;
83
95
  if (!spillPath) {
84
96
  const spill = spillToolResult(original, {
@@ -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();
package/src/sandbox.js CHANGED
@@ -221,7 +221,8 @@ export class Sandbox {
221
221
 
222
222
  validate(toolName, args) {
223
223
  // 1. Tool availability check
224
- if (this.deniedTools.has(String(toolName).replace(/\./g, '_'))) {
224
+ const canonicalToolName = String(toolName || '').replace(/\./g, '_');
225
+ if (this.deniedTools.has(canonicalToolName)) {
225
226
  return { allowed: false, reason: `Tool ${toolName} is denied by local policy`, risk: 'forbidden' };
226
227
  }
227
228
  if (!this.allowedTools.includes('*') && !this.allowedTools.includes(toolName)) {
@@ -233,19 +234,24 @@ export class Sandbox {
233
234
  // file_path, the Blender/Godot automators use filepath and directory, the
234
235
  // media tools use outputPath. Checking only `path` let all of those write
235
236
  // outside the workspace unchallenged.
237
+ // fs_read_skill parameters (`skill_id`, `file_path`) identify bundled or
238
+ // user-skill resources bounded strictly by skillResourceSafety.ts rather
239
+ // than workspace filesystem paths.
236
240
  const safeArgs = args && typeof args === 'object' ? args : {};
237
- const PATH_ARGUMENTS = [
238
- 'path', 'searchPath', 'cwd', 'source', 'destination',
239
- 'file_path', 'filePath', 'filepath', 'directory',
240
- 'targetFile', 'outputFile', 'outputPath'
241
- ];
242
241
  const pathsToCheck = [];
243
- for (const field of PATH_ARGUMENTS) {
244
- if (safeArgs[field]) pathsToCheck.push(safeArgs[field]);
245
- }
246
- if (Array.isArray(safeArgs.target_directories)) {
247
- for (const dir of safeArgs.target_directories) {
248
- if (typeof dir === 'string' && dir.trim()) pathsToCheck.push(dir);
242
+ if (canonicalToolName !== 'fs_read_skill') {
243
+ const PATH_ARGUMENTS = [
244
+ 'path', 'searchPath', 'cwd', 'source', 'destination',
245
+ 'file_path', 'filePath', 'filepath', 'directory',
246
+ 'targetFile', 'outputFile', 'outputPath'
247
+ ];
248
+ for (const field of PATH_ARGUMENTS) {
249
+ if (safeArgs[field]) pathsToCheck.push(safeArgs[field]);
250
+ }
251
+ if (Array.isArray(safeArgs.target_directories)) {
252
+ for (const dir of safeArgs.target_directories) {
253
+ if (typeof dir === 'string' && dir.trim()) pathsToCheck.push(dir);
254
+ }
249
255
  }
250
256
  }
251
257
 
@@ -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);