@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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@causyne/agent",
3
- "version": "1.20.93",
3
+ "version": "1.20.95",
4
4
  "description": "Agentic AI for software, tools, and computer workflows",
5
5
  "main": "bin/causyne.js",
6
6
  "type": "module",
package/src/agentLoop.js CHANGED
@@ -6,6 +6,7 @@ import { getProcessEntitlementGate, EntitlementAccessError } from './licensing/e
6
6
  import { repairUnansweredToolCalls, validateToolCallBatch } from './agent/toolTurnIntegrity.js';
7
7
  import { waitForAbortableDelay } from './agent/abortableDelay.js';
8
8
  import { normalizeAgentFailure } from './agent/providerFailure.js';
9
+ import { resolveTaskTokenCeiling, peerCallTokenCeiling, isAntigravityPeer, isTerminalBudgetFailure, desktopDeadline, remainingDesktopTime } from './budget/budgetPolicy.js';
9
10
  import { PEER_COLLABORATION_POLICY } from './providers/collaborationPolicy.js';
10
11
  import { createHash, randomUUID } from 'crypto';
11
12
  import { execFileSync } from 'node:child_process';
@@ -53,7 +54,7 @@ import { resolveCharPool, measureMessages, resultCapFor, decayToolResults, build
53
54
  // Provider imports
54
55
  import { detectWorkspaceDomains, ensureSkillRepo, getSkillDomainHeader } from './skillsManager.js';
55
56
  import { spillToolResult, buildDecayPointer, pruneOutputStore } from './outputStore.js';
56
- import { defaultToolOutputStore, processToolOutputWithStore, renderSpillDocument } from './tools/toolOutputStore.js';
57
+ import { ToolOutputStore, defaultToolOutputStore, processToolOutputWithStore, renderSpillDocument } from './tools/toolOutputStore.js';
57
58
  import { beginTask as beginCheckpointTask, captureBeforeMutation, pruneStore as pruneCheckpointStore, resolveProjectRoot } from './checkpoints.js';
58
59
  import fsSync from 'fs';
59
60
  import os from 'os';
@@ -1712,8 +1713,19 @@ export class AgentLoop {
1712
1713
  // entitlements. A second reset here could resurrect an aborted task.
1713
1714
  if (this.stopRequested || this.abortController?.signal?.aborted)
1714
1715
  return;
1715
- // Refresh tier limits on every task run
1716
+ // Refresh tier limits on every task run.
1716
1717
  this.updateTierLimits();
1718
+ // The CLI reuses AgentLoop between messages. Task consumption must not
1719
+ // leak into the next turn, but session/daily consumption is retained.
1720
+ this.tokenTracker.resetTask();
1721
+ const guardLimit = resolveTaskTokenCeiling({
1722
+ provider: this.config.provider,
1723
+ workerLimit: this.taskTokenLimit,
1724
+ configured: this.tokenTracker.budget
1725
+ });
1726
+ this.tokenTracker.setEnforcedTaskLimit(guardLimit);
1727
+ const taskArchetype = determineToolScope(this.currentTaskPrompt || this.userPrompt || '', this.taskShape).archetype;
1728
+ this._taskWallDeadlineAt = desktopDeadline(Date.now(), taskArchetype);
1717
1729
  if (!this.llm) {
1718
1730
  throw new Error("API Key Required. Causyne is a 100% Sovereign BYOK Engine. Please configure your API Provider and Key in Settings.");
1719
1731
  }
@@ -2053,6 +2065,12 @@ export class AgentLoop {
2053
2065
  let emptyResponseRecoveries = 0;
2054
2066
  // The core loop governed by Sovereign Human-in-the-Loop Checkpoints
2055
2067
  while (!this.stopRequested) {
2068
+ const desktopTimeLeft = remainingDesktopTime(this._taskWallDeadlineAt);
2069
+ if (desktopTimeLeft !== null && desktopTimeLeft <= 0) {
2070
+ this.emitEvent({ type: 'budget_warning', message: 'Desktop task stopped at its 180-second wall-clock ceiling. Progress is preserved; outcome is unverified.' });
2071
+ auditLog.log({ event: 'task_stopped_on_wall_budget', taskId: this.taskId });
2072
+ break;
2073
+ }
2056
2074
  // CAUSYNE_ENTITLEMENT_V1: verify an authorized lease before each model step.
2057
2075
  try {
2058
2076
  await this._entitlementGate?.beforeStep();
@@ -2434,30 +2452,19 @@ You are operating in a text-and-code modality without direct image pixel renderi
2434
2452
  }
2435
2453
  const affordability = this.tokenTracker.canAffordAnotherStep();
2436
2454
  if (!affordability.allowed) {
2437
- if (hardBudget) {
2438
- this.emitEvent({ type: 'budget_warning', message: affordability.reason });
2439
- this.emitEvent({ type: 'notice', message: 'Stopped before the token ceiling. Nothing was truncated mid-step.' });
2440
- if (this._offeredPlanId) {
2441
- try {
2442
- recordMiss(this._offeredPlanId);
2443
- }
2444
- catch (e) { /* never block a stop */ }
2455
+ this.emitEvent({ type: 'budget_warning', message: affordability.reason });
2456
+ this.emitEvent({ type: 'notice', message: 'Task stopped at its token ceiling before the next model call.' });
2457
+ if (this._offeredPlanId) {
2458
+ try {
2459
+ recordMiss(this._offeredPlanId);
2445
2460
  }
2446
- auditLog.log({
2447
- event: 'task_stopped_on_budget', taskId: this.taskId,
2448
- used: affordability.used, limit: affordability.limit, projected: affordability.projected
2449
- });
2450
- break;
2451
- }
2452
- else {
2453
- // Proactive history compaction rather than artificial abort (OpenCode / SWE-agent pattern)
2454
- pruneStaleToolObservations(this.messages, { keepRecent: 3, minChars: 300, taskId: this.taskId });
2455
- shortenOversizedToolObservations(this.messages, { threshold: 1500, taskId: this.taskId });
2456
- pruneExecutedToolArguments(this.messages, { threshold: 1500, taskId: this.taskId });
2457
- const stepScale = Math.max(this.tokenTracker.largestStepTokens || 50_000, 100_000);
2458
- const extraTokens = Math.max(stepScale * 10, 1_000_000);
2459
- this.tokenTracker.extendBudget(extraTokens);
2461
+ catch { /* never block a stop */ }
2460
2462
  }
2463
+ auditLog.log({
2464
+ event: 'task_stopped_on_budget', taskId: this.taskId,
2465
+ used: affordability.used, limit: affordability.limit, projected: affordability.projected
2466
+ });
2467
+ break;
2461
2468
  }
2462
2469
  // 2. PLAN (Call LLM). dynamicTools was resolved above so the task brief
2463
2470
  // could reference the tools actually in context.
@@ -2506,10 +2513,16 @@ You are operating in a text-and-code modality without direct image pixel renderi
2506
2513
  taskIntent: isLaunchOnlyPrompt(this.currentTaskPrompt || this.userPrompt || '') ? 'launch' : 'general',
2507
2514
  taskArchetype: determineToolScope(this.currentTaskPrompt || this.userPrompt || '', this.taskShape).archetype,
2508
2515
  hardBudget: hardBudget,
2509
- maxTokensThisCall: Number.isFinite(configuredRemainingBudget) && hardBudget ? configuredRemainingBudget : undefined,
2510
- tokenBudgetBasis: Number.isFinite(configuredRemainingBudget) ? 'total' : 'noncached',
2516
+ // The peer can perform multiple billable model steps inside one
2517
+ // chat() call. The per-call bound is independent of autonomy mode.
2518
+ maxTokensThisCall: isAntigravityPeer(this.config.provider)
2519
+ ? peerCallTokenCeiling(configuredRemainingBudget)
2520
+ : Number.isFinite(configuredRemainingBudget) && hardBudget ? configuredRemainingBudget : undefined,
2521
+ tokenBudgetBasis: isAntigravityPeer(this.config.provider) ? 'noncached'
2522
+ : Number.isFinite(configuredRemainingBudget) ? 'total' : 'noncached',
2511
2523
  tokenLimit: hardBudget && Number.isFinite(remainingBudget) && remainingBudget > 0
2512
2524
  ? remainingBudget : undefined,
2525
+ taskDeadlineMs: this._taskWallDeadlineAt ?? undefined,
2513
2526
  workspaceRoot: this.workspaceRoot,
2514
2527
  onPeerPermission: (request) => this.requestPeerPermission(request),
2515
2528
  onPeerFileRead: (file, options) => this.executePeerFile('fs_read', file, undefined, options),
@@ -4536,12 +4549,15 @@ You are operating in a text-and-code modality without direct image pixel renderi
4536
4549
  let resultString = JSON.stringify(result);
4537
4550
  // Per tool, not one number for all of them. A build log and a
4538
4551
  // source file are not equally worth their space in the window.
4552
+ // Compatibility fallback preserves complete output when primary store is unavailable.
4539
4553
  const MAX_RESULT_CHARS = resultCapFor(functionName);
4554
+ const inlineLimit = Math.min(MAX_RESULT_CHARS, functionName === 'fs_read_skill' ? 16000 : functionName === 'tool_search' ? 8000 : 2500);
4540
4555
  const originalFingerprint = createHash('sha256').update(resultString).digest('hex');
4541
4556
  let spill = null;
4542
- if (resultString.length > Math.min(MAX_RESULT_CHARS, 2500)) {
4557
+ if (resultString.length > inlineLimit) {
4543
4558
  const document = renderSpillDocument(result, { taskId: this.taskId, step: this.stepsCompleted, tool: functionName });
4544
- const stored = processToolOutputWithStore(this.taskId, toolCall.id, document);
4559
+ const store = inlineLimit > 2500 ? new ToolOutputStore({ maxChars: inlineLimit, maxLines: 400, maxBytes: Math.max(50 * 1024, inlineLimit * 4) }) : defaultToolOutputStore;
4560
+ const stored = processToolOutputWithStore(this.taskId, toolCall.id, document, store);
4545
4561
  if (stored.isTruncated && stored.diskPath) {
4546
4562
  spill = { path: stored.diskPath };
4547
4563
  resultString = JSON.stringify({
@@ -4550,9 +4566,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4550
4566
  output: stored.contentForModel
4551
4567
  });
4552
4568
  }
4553
- else if (document.length > 2500) {
4554
- // Compatibility recovery store if the primary store is unavailable.
4555
- // spillToolResult preserves the full document; never truncate on failure.
4569
+ else if (document.length > inlineLimit) {
4556
4570
  const fallback = spillToolResult(result, { taskId: this.taskId, step: this.stepsCompleted, tool: functionName });
4557
4571
  if (fallback) {
4558
4572
  spill = fallback;
@@ -4649,34 +4663,16 @@ You are operating in a text-and-code modality without direct image pixel renderi
4649
4663
  this.memoryManager.saveHistory(this.messages);
4650
4664
  continue;
4651
4665
  }
4652
- if (e?.code === 'TASK_TOKEN_BUDGET' || e?.code === 'PROVIDER_TOKEN_BUDGET'
4653
- || e?.code === 'AGY_DESKTOP_TASK_LIMIT' || e?.code === 'AGY_TOKEN_BUDGET' || e?.code === 'AGY_NATIVE_ACTION_BUDGET') {
4654
- const isExplicitHardBudget = (Number.isInteger(this.taskTokenLimit) && this.taskTokenLimit > 0)
4655
- || (this.tokenTracker.budget?.enabled === true && this.tokenTracker.budget?.hardStop === true);
4656
- if (this.config.autonomyMode === 'C' && !isExplicitHardBudget) {
4657
- this.emitEvent({ type: 'budget_warning', message: e.message });
4658
- pruneStaleToolObservations(this.messages, { keepRecent: 3, minChars: 300, taskId: this.taskId });
4659
- shortenOversizedToolObservations(this.messages, { threshold: 1500, taskId: this.taskId });
4660
- pruneExecutedToolArguments(this.messages, { threshold: 1500, taskId: this.taskId });
4661
- const stepScale = Math.max(this.tokenTracker.largestStepTokens || 50_000, 100_000);
4662
- const extraTokens = Math.max(stepScale * 10, 1_000_000);
4663
- this.tokenTracker.extendBudget(extraTokens);
4664
- this.emitEvent({ type: 'status', message: 'Continuing autonomous task execution without artificial interruption…' });
4665
- this.messages.push({
4666
- role: 'system',
4667
- content: '[Autonomous task continuation: Do not repeat prior actions. Proceed with executing next concrete steps.]'
4668
- });
4669
- this.memoryManager.saveHistory(this.messages);
4670
- continue;
4671
- }
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.
4672
4669
  this.messages.push({ role: 'system', content: `[Unfinished task checkpoint] ${e.message}` });
4673
4670
  this.memoryManager.saveHistory(this.messages);
4674
4671
  this.emitEvent({ type: 'budget_warning', message: e.message });
4675
4672
  auditLog.log({
4676
- event: 'efficiency_checkpoint',
4677
- taskId: this.taskId,
4678
- reason: e?.reason || e?.code,
4679
- tokenUsage: this.tokenTracker.taskTokens
4673
+ event: 'efficiency_checkpoint', taskId: this.taskId,
4674
+ reason: e.code, tokenUsage: this.tokenTracker.taskTokens,
4675
+ outcome: 'unverified'
4680
4676
  });
4681
4677
  break;
4682
4678
  }
@@ -4952,28 +4948,30 @@ You are operating in a text-and-code modality without direct image pixel renderi
4952
4948
  }
4953
4949
  return val;
4954
4950
  };
4955
- // 1. File operations must have absolute paths
4951
+ // 1. File operations must have absolute paths (fs_read_skill uses skill-relative file_path)
4956
4952
  const nonPathTargetTools = new Set(['vision_inspect_ui', 'astryx_oracle', 'desktop_act']);
4957
- const pathFields = [
4958
- 'path', 'searchPath', 'cwd', 'directory',
4959
- 'source', 'destination', 'file_path', 'filePath', 'filepath',
4960
- 'targetFile', 'outputFile', 'outputPath',
4961
- ...(nonPathTargetTools.has(toolName) ? [] : ['target'])
4962
- ];
4963
- for (const field of pathFields) {
4964
- if (args[field] && typeof args[field] === 'string') {
4965
- const resolved = resolveOne(args[field]);
4966
- if (resolved !== null) {
4967
- args[field] = resolved;
4953
+ if (toolName !== 'fs_read_skill') {
4954
+ const pathFields = [
4955
+ 'path', 'searchPath', 'cwd', 'directory',
4956
+ 'source', 'destination', 'file_path', 'filePath', 'filepath',
4957
+ 'targetFile', 'outputFile', 'outputPath',
4958
+ ...(nonPathTargetTools.has(toolName) ? [] : ['target'])
4959
+ ];
4960
+ for (const field of pathFields) {
4961
+ if (args[field] && typeof args[field] === 'string') {
4962
+ const resolved = resolveOne(args[field]);
4963
+ if (resolved !== null) {
4964
+ args[field] = resolved;
4965
+ }
4968
4966
  }
4969
4967
  }
4970
- }
4971
- if (Array.isArray(args.target_directories)) {
4972
- args.target_directories = args.target_directories.map((entry) => {
4973
- if (typeof entry !== 'string')
4974
- return entry;
4975
- return resolveOne(entry) ?? entry;
4976
- });
4968
+ if (Array.isArray(args.target_directories)) {
4969
+ args.target_directories = args.target_directories.map((entry) => {
4970
+ if (typeof entry !== 'string')
4971
+ return entry;
4972
+ return resolveOne(entry) ?? entry;
4973
+ });
4974
+ }
4977
4975
  }
4978
4976
  // 2. Terminal commands must have a command string
4979
4977
  if ((toolName === 'sysRun' || toolName === 'sysRunBg') && !args.command) {
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';
@@ -94,7 +95,7 @@ import {
94
95
  // Provider imports
95
96
  import { detectWorkspaceDomains, ensureSkillRepo, getSkillDomainHeader } from './skillsManager.js';
96
97
  import { spillToolResult, buildDecayPointer, pruneOutputStore } from './outputStore.js';
97
- import { defaultToolOutputStore, processToolOutputWithStore, renderSpillDocument } from './tools/toolOutputStore.js';
98
+ import { ToolOutputStore, defaultToolOutputStore, processToolOutputWithStore, renderSpillDocument } from './tools/toolOutputStore.js';
98
99
  import { beginTask as beginCheckpointTask, captureBeforeMutation, pruneStore as pruneCheckpointStore, resolveProjectRoot } from './checkpoints.js';
99
100
  import fsSync from 'fs';
100
101
  import os from 'os';
@@ -1772,8 +1773,21 @@ export class AgentLoop {
1772
1773
  // run() owns cancellation and rearms it exactly once, before awaiting
1773
1774
  // entitlements. A second reset here could resurrect an aborted task.
1774
1775
  if (this.stopRequested || this.abortController?.signal?.aborted) return;
1775
- // Refresh tier limits on every task run
1776
+ // Refresh tier limits on every task run.
1776
1777
  this.updateTierLimits();
1778
+ // The CLI reuses AgentLoop between messages. Task consumption must not
1779
+ // leak into the next turn, but session/daily consumption is retained.
1780
+ this.tokenTracker.resetTask();
1781
+ const guardLimit = resolveTaskTokenCeiling({
1782
+ provider: this.config.provider,
1783
+ workerLimit: this.taskTokenLimit,
1784
+ configured: this.tokenTracker.budget
1785
+ });
1786
+ this.tokenTracker.setEnforcedTaskLimit(guardLimit);
1787
+ const taskArchetype = determineToolScope(
1788
+ this.currentTaskPrompt || this.userPrompt || '', this.taskShape
1789
+ ).archetype;
1790
+ this._taskWallDeadlineAt = desktopDeadline(Date.now(), taskArchetype);
1777
1791
  if (!this.llm) {
1778
1792
  throw new Error("API Key Required. Causyne is a 100% Sovereign BYOK Engine. Please configure your API Provider and Key in Settings.");
1779
1793
  }
@@ -2133,6 +2147,13 @@ export class AgentLoop {
2133
2147
 
2134
2148
  // The core loop governed by Sovereign Human-in-the-Loop Checkpoints
2135
2149
  while (!this.stopRequested) {
2150
+ const desktopTimeLeft = remainingDesktopTime(this._taskWallDeadlineAt);
2151
+ if (desktopTimeLeft !== null && desktopTimeLeft <= 0) {
2152
+ this.emitEvent({ type: 'budget_warning', message:
2153
+ 'Desktop task stopped at its 180-second wall-clock ceiling. Progress is preserved; outcome is unverified.' });
2154
+ auditLog.log({ event: 'task_stopped_on_wall_budget', taskId: this.taskId });
2155
+ break;
2156
+ }
2136
2157
  // CAUSYNE_ENTITLEMENT_V1: verify an authorized lease before each model step.
2137
2158
  try {
2138
2159
  await this._entitlementGate?.beforeStep();
@@ -2542,26 +2563,16 @@ You are operating in a text-and-code modality without direct image pixel renderi
2542
2563
  }
2543
2564
  const affordability = this.tokenTracker.canAffordAnotherStep();
2544
2565
  if (!affordability.allowed) {
2545
- if (hardBudget) {
2546
- this.emitEvent({ type: 'budget_warning', message: affordability.reason });
2547
- this.emitEvent({ type: 'notice', message: 'Stopped before the token ceiling. Nothing was truncated mid-step.' });
2548
- if (this._offeredPlanId) {
2549
- try { recordMiss(this._offeredPlanId); } catch (e: any) { /* never block a stop */ }
2550
- }
2551
- auditLog.log({
2552
- event: 'task_stopped_on_budget', taskId: this.taskId,
2553
- used: affordability.used, limit: affordability.limit, projected: affordability.projected
2554
- });
2555
- break;
2556
- } else {
2557
- // Proactive history compaction rather than artificial abort (OpenCode / SWE-agent pattern)
2558
- pruneStaleToolObservations(this.messages, { keepRecent: 3, minChars: 300, taskId: this.taskId });
2559
- shortenOversizedToolObservations(this.messages, { threshold: 1500, taskId: this.taskId });
2560
- pruneExecutedToolArguments(this.messages, { threshold: 1500, taskId: this.taskId });
2561
- const stepScale = Math.max(this.tokenTracker.largestStepTokens || 50_000, 100_000);
2562
- const extraTokens = Math.max(stepScale * 10, 1_000_000);
2563
- this.tokenTracker.extendBudget(extraTokens);
2566
+ this.emitEvent({ type: 'budget_warning', message: affordability.reason });
2567
+ this.emitEvent({ type: 'notice', message: 'Task stopped at its token ceiling before the next model call.' });
2568
+ if (this._offeredPlanId) {
2569
+ try { recordMiss(this._offeredPlanId); } catch { /* never block a stop */ }
2564
2570
  }
2571
+ auditLog.log({
2572
+ event: 'task_stopped_on_budget', taskId: this.taskId,
2573
+ used: affordability.used, limit: affordability.limit, projected: affordability.projected
2574
+ });
2575
+ break;
2565
2576
  }
2566
2577
 
2567
2578
  // 2. PLAN (Call LLM). dynamicTools was resolved above so the task brief
@@ -2612,10 +2623,16 @@ You are operating in a text-and-code modality without direct image pixel renderi
2612
2623
  taskIntent: isLaunchOnlyPrompt(this.currentTaskPrompt || this.userPrompt || '') ? 'launch' : 'general',
2613
2624
  taskArchetype: determineToolScope(this.currentTaskPrompt || this.userPrompt || '', this.taskShape).archetype,
2614
2625
  hardBudget: hardBudget,
2615
- maxTokensThisCall: Number.isFinite(configuredRemainingBudget) && hardBudget ? configuredRemainingBudget : undefined,
2616
- tokenBudgetBasis: Number.isFinite(configuredRemainingBudget) ? 'total' : 'noncached',
2626
+ // The peer can perform multiple billable model steps inside one
2627
+ // chat() call. The per-call bound is independent of autonomy mode.
2628
+ maxTokensThisCall: isAntigravityPeer(this.config.provider)
2629
+ ? peerCallTokenCeiling(configuredRemainingBudget)
2630
+ : Number.isFinite(configuredRemainingBudget) && hardBudget ? configuredRemainingBudget : undefined,
2631
+ tokenBudgetBasis: isAntigravityPeer(this.config.provider) ? 'noncached'
2632
+ : Number.isFinite(configuredRemainingBudget) ? 'total' : 'noncached',
2617
2633
  tokenLimit: hardBudget && Number.isFinite(remainingBudget) && remainingBudget > 0
2618
2634
  ? remainingBudget : undefined,
2635
+ taskDeadlineMs: this._taskWallDeadlineAt ?? undefined,
2619
2636
  workspaceRoot: this.workspaceRoot,
2620
2637
  onPeerPermission: (request: RequestPermissionRequest) => this.requestPeerPermission(request),
2621
2638
  onPeerFileRead: (file: string, options?: { line?: number; limit?: number }) => this.executePeerFile('fs_read', file, undefined, options),
@@ -4767,12 +4784,15 @@ You are operating in a text-and-code modality without direct image pixel renderi
4767
4784
  let resultString = JSON.stringify(result);
4768
4785
  // Per tool, not one number for all of them. A build log and a
4769
4786
  // source file are not equally worth their space in the window.
4787
+ // Compatibility fallback preserves complete output when primary store is unavailable.
4770
4788
  const MAX_RESULT_CHARS = resultCapFor(functionName);
4789
+ const inlineLimit = Math.min(MAX_RESULT_CHARS, functionName === 'fs_read_skill' ? 16000 : functionName === 'tool_search' ? 8000 : 2500);
4771
4790
  const originalFingerprint = createHash('sha256').update(resultString).digest('hex');
4772
4791
  let spill = null;
4773
- if (resultString.length > Math.min(MAX_RESULT_CHARS, 2500)) {
4792
+ if (resultString.length > inlineLimit) {
4774
4793
  const document = renderSpillDocument(result, { taskId: this.taskId, step: this.stepsCompleted, tool: functionName });
4775
- const stored = processToolOutputWithStore(this.taskId, toolCall.id, document);
4794
+ const store = inlineLimit > 2500 ? new ToolOutputStore({ maxChars: inlineLimit, maxLines: 400, maxBytes: Math.max(50 * 1024, inlineLimit * 4) }) : defaultToolOutputStore;
4795
+ const stored = processToolOutputWithStore(this.taskId, toolCall.id, document, store);
4776
4796
  if (stored.isTruncated && stored.diskPath) {
4777
4797
  spill = { path: stored.diskPath };
4778
4798
  resultString = JSON.stringify({
@@ -4780,9 +4800,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4780
4800
  ...(typeof result?.error === 'string' ? { error: result.error.slice(0, 500) } : {}),
4781
4801
  output: stored.contentForModel
4782
4802
  });
4783
- } else if (document.length > 2500) {
4784
- // Compatibility recovery store if the primary store is unavailable.
4785
- // spillToolResult preserves the full document; never truncate on failure.
4803
+ } else if (document.length > inlineLimit) {
4786
4804
  const fallback = spillToolResult(result, { taskId: this.taskId, step: this.stepsCompleted, tool: functionName });
4787
4805
  if (fallback) {
4788
4806
  spill = fallback;
@@ -4893,34 +4911,16 @@ You are operating in a text-and-code modality without direct image pixel renderi
4893
4911
  this.memoryManager.saveHistory(this.messages);
4894
4912
  continue;
4895
4913
  }
4896
- if (e?.code === 'TASK_TOKEN_BUDGET' || e?.code === 'PROVIDER_TOKEN_BUDGET'
4897
- || e?.code === 'AGY_DESKTOP_TASK_LIMIT' || e?.code === 'AGY_TOKEN_BUDGET' || e?.code === 'AGY_NATIVE_ACTION_BUDGET') {
4898
- const isExplicitHardBudget = (Number.isInteger(this.taskTokenLimit) && (this.taskTokenLimit as number) > 0)
4899
- || (this.tokenTracker.budget?.enabled === true && this.tokenTracker.budget?.hardStop === true);
4900
- if (this.config.autonomyMode === 'C' && !isExplicitHardBudget) {
4901
- this.emitEvent({ type: 'budget_warning', message: e.message });
4902
- pruneStaleToolObservations(this.messages, { keepRecent: 3, minChars: 300, taskId: this.taskId });
4903
- shortenOversizedToolObservations(this.messages, { threshold: 1500, taskId: this.taskId });
4904
- pruneExecutedToolArguments(this.messages, { threshold: 1500, taskId: this.taskId });
4905
- const stepScale = Math.max(this.tokenTracker.largestStepTokens || 50_000, 100_000);
4906
- const extraTokens = Math.max(stepScale * 10, 1_000_000);
4907
- this.tokenTracker.extendBudget(extraTokens);
4908
- this.emitEvent({ type: 'status', message: 'Continuing autonomous task execution without artificial interruption…' });
4909
- this.messages.push({
4910
- role: 'system',
4911
- content: '[Autonomous task continuation: Do not repeat prior actions. Proceed with executing next concrete steps.]'
4912
- });
4913
- this.memoryManager.saveHistory(this.messages);
4914
- continue;
4915
- }
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.
4916
4917
  this.messages.push({ role: 'system', content: `[Unfinished task checkpoint] ${e.message}` });
4917
4918
  this.memoryManager.saveHistory(this.messages);
4918
4919
  this.emitEvent({ type: 'budget_warning', message: e.message });
4919
4920
  auditLog.log({
4920
- event: 'efficiency_checkpoint',
4921
- taskId: this.taskId,
4922
- reason: (e as any)?.reason || (e as any)?.code,
4923
- tokenUsage: this.tokenTracker.taskTokens
4921
+ event: 'efficiency_checkpoint', taskId: this.taskId,
4922
+ reason: e.code, tokenUsage: this.tokenTracker.taskTokens,
4923
+ outcome: 'unverified'
4924
4924
  });
4925
4925
  break;
4926
4926
  }
@@ -5214,27 +5214,29 @@ You are operating in a text-and-code modality without direct image pixel renderi
5214
5214
  return val;
5215
5215
  };
5216
5216
 
5217
- // 1. File operations must have absolute paths
5217
+ // 1. File operations must have absolute paths (fs_read_skill uses skill-relative file_path)
5218
5218
  const nonPathTargetTools = new Set(['vision_inspect_ui', 'astryx_oracle', 'desktop_act']);
5219
- const pathFields = [
5220
- 'path', 'searchPath', 'cwd', 'directory',
5221
- 'source', 'destination', 'file_path', 'filePath', 'filepath',
5222
- 'targetFile', 'outputFile', 'outputPath',
5223
- ...(nonPathTargetTools.has(toolName) ? [] : ['target'])
5224
- ];
5225
- for (const field of pathFields) {
5226
- if (args[field] && typeof args[field] === 'string') {
5227
- const resolved = resolveOne(args[field]);
5228
- if (resolved !== null) {
5229
- args[field] = resolved;
5219
+ if (toolName !== 'fs_read_skill') {
5220
+ const pathFields = [
5221
+ 'path', 'searchPath', 'cwd', 'directory',
5222
+ 'source', 'destination', 'file_path', 'filePath', 'filepath',
5223
+ 'targetFile', 'outputFile', 'outputPath',
5224
+ ...(nonPathTargetTools.has(toolName) ? [] : ['target'])
5225
+ ];
5226
+ for (const field of pathFields) {
5227
+ if (args[field] && typeof args[field] === 'string') {
5228
+ const resolved = resolveOne(args[field]);
5229
+ if (resolved !== null) {
5230
+ args[field] = resolved;
5231
+ }
5230
5232
  }
5231
5233
  }
5232
- }
5233
- if (Array.isArray(args.target_directories)) {
5234
- args.target_directories = args.target_directories.map((entry: unknown) => {
5235
- if (typeof entry !== 'string') return entry;
5236
- return resolveOne(entry) ?? entry;
5237
- });
5234
+ if (Array.isArray(args.target_directories)) {
5235
+ args.target_directories = args.target_directories.map((entry: unknown) => {
5236
+ if (typeof entry !== 'string') return entry;
5237
+ return resolveOne(entry) ?? entry;
5238
+ });
5239
+ }
5238
5240
  }
5239
5241
 
5240
5242
  // 2. Terminal commands must have a command string
@@ -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
+ }