@causyne/agent 1.20.94 → 1.20.96
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 +1 -1
- package/src/agentLoop.js +44 -49
- package/src/agentLoop.ts +45 -46
- package/src/budget/budgetPolicy.js +92 -0
- package/src/budget/budgetPolicy.ts +107 -0
- package/src/providers/antigravity.js +27 -43
- package/src/providers/antigravity.ts +35 -45
- package/src/tokenTracker.js +24 -0
- package/src/tokenTracker.ts +25 -0
- package/src/tui/completion.js +29 -88
- package/src/tui/prompt.js +23 -1
- package/src/tui/workspaceFileIndex.js +183 -0
- package/src/tui/workspaceFileIndex.ts +179 -0
package/package.json
CHANGED
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
|
-
|
|
2438
|
-
|
|
2439
|
-
|
|
2440
|
-
|
|
2441
|
-
|
|
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
|
-
|
|
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
|
-
|
|
2510
|
-
|
|
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
|
|
4654
|
-
|
|
4655
|
-
|
|
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
|
-
|
|
4679
|
-
|
|
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
|
-
|
|
2546
|
-
|
|
2547
|
-
|
|
2548
|
-
|
|
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
|
-
|
|
2616
|
-
|
|
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
|
|
4898
|
-
|
|
4899
|
-
|
|
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
|
-
|
|
4923
|
-
|
|
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
|
|
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
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
:
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
const
|
|
1057
|
-
|
|
1058
|
-
error
|
|
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
|
-
},
|
|
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 (
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
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 (
|
|
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
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
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
|
-
|
|
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();
|