@causyne/agent 1.20.8 → 1.20.10

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.
Files changed (74) hide show
  1. package/package.json +2 -1
  2. package/src/agentLoop.js +291 -103
  3. package/src/agentLoop.ts +322 -109
  4. package/src/browser/causyneBrowser.js +36 -0
  5. package/src/browser/causyneBrowser.ts +36 -1
  6. package/src/commands.js +25 -0
  7. package/src/compiledSkills.js +7330 -319
  8. package/src/computerUse/types.js +8 -0
  9. package/src/computerUse/types.ts +121 -0
  10. package/src/computerUse/visionGrounding.js +87 -29
  11. package/src/computerUse/visionGrounding.ts +108 -36
  12. package/src/contextManager.js +16 -0
  13. package/src/decisionPolicy.js +7 -9
  14. package/src/decisionPolicy.ts +7 -9
  15. package/src/documentEngine/antiSlopAuditor.js +13 -43
  16. package/src/documentEngine/antiSlopAuditor.ts +15 -47
  17. package/src/documentEngine/documentForge.js +3 -3
  18. package/src/documentEngine/documentForge.ts +3 -3
  19. package/src/launchIntent.js +3 -3
  20. package/src/launchIntent.ts +3 -3
  21. package/src/planCache.js +4 -14
  22. package/src/planCache.ts +4 -14
  23. package/src/providers/acp.js +4 -2
  24. package/src/providers/acp.ts +4 -2
  25. package/src/providers/antigravity.js +191 -28
  26. package/src/providers/antigravity.ts +192 -27
  27. package/src/providers/base.d.ts +2 -0
  28. package/src/providers/pi.js +3 -1
  29. package/src/providers/pi.ts +4 -2
  30. package/src/provisioning/capabilityProvisioner.js +2 -7
  31. package/src/provisioning/npmInstall.js +19 -0
  32. package/src/provisioning/npmInstall.ts +19 -0
  33. package/src/sandbox.js +7 -10
  34. package/src/smartToolsUse.js +223 -0
  35. package/src/smartToolsUse.ts +284 -0
  36. package/src/stallGuard.js +356 -0
  37. package/src/stallGuard.ts +432 -0
  38. package/src/taskShape.js +7 -7
  39. package/src/taskShape.ts +7 -7
  40. package/src/toolPacks.js +5 -5
  41. package/src/tools/blenderAutomator.js +198 -11
  42. package/src/tools/browserAutomator.js +3 -3
  43. package/src/tools/browserAutomator.ts +3 -3
  44. package/src/tools/documentForge.js +1 -1
  45. package/src/tools/documentForge.ts +1 -1
  46. package/src/tools/fsRead.js +91 -80
  47. package/src/tools/fsRead.ts +125 -0
  48. package/src/tools/peerAgent.js +1 -1
  49. package/src/tools/peerAgent.ts +1 -1
  50. package/src/tools/screenshot.js +5 -1
  51. package/src/tools/screenshot.ts +5 -1
  52. package/src/tools/toolScanner.js +19 -0
  53. package/src/tools/toolScanner.ts +17 -0
  54. package/src/tools/toolSelfRepair.js +63 -1
  55. package/src/tools/toolSelfRepair.ts +61 -1
  56. package/src/tools/visionInspector.js +80 -142
  57. package/src/tools/visionInspector.ts +110 -0
  58. package/src/tui/chatboxClipboard.js +152 -0
  59. package/src/tui/chatboxClipboard.ts +201 -0
  60. package/src/tui/clipboardSync.js +38 -7
  61. package/src/tui/clipboardSync.ts +39 -7
  62. package/src/tui/codeProgress.js +89 -18
  63. package/src/tui/codeProgress.ts +102 -17
  64. package/src/tui/codeStreamRenderer.js +7 -2
  65. package/src/tui/codeStreamRenderer.ts +7 -2
  66. package/src/tui/composerControls.js +9 -0
  67. package/src/tui/composerControls.ts +9 -0
  68. package/src/tui/dialogs.js +8 -3
  69. package/src/tui/diff.d.ts +1 -0
  70. package/src/tui/lineEditor.js +166 -14
  71. package/src/tui/mouseHover.js +6 -2
  72. package/src/tui/mouseHover.ts +7 -2
  73. package/src/tui/prompt.js +96 -19
  74. package/src/tui/stageSurface.js +3 -1
@@ -2,7 +2,8 @@ import { spawn } from 'node:child_process';
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { isLaunchOnlyPrompt } from '../launchIntent.js';
5
- import { LLMProvider, type ProviderConfig, type ChatOptions, type ChatResponse, type ChatResponseAction, type ChatResponseToolCall } from './base.js';
5
+ import { scanAndAdaptToolsForProvider } from '../tools/toolScanner.js';
6
+ import { LLMProvider, type ProviderConfig, type ChatOptions, type ChatResponse, type ChatResponseAction, type ChatResponseToolCall, type ChatResponseUsage } from './base.js';
6
7
 
7
8
  /**
8
9
  * Baseline fallback models for instant offline availability.
@@ -275,6 +276,19 @@ function describeNativeAction(toolInfo: any): string | undefined {
275
276
  return undefined;
276
277
  }
277
278
 
279
+ export function isReadOnlyNativeInspection(name: string, parameters: Record<string, unknown>): boolean {
280
+ const action = name.toLowerCase().replace(/[_\s-]/g, '');
281
+ if (/^(readfile|listdirectory|listfiles|search|searchweb|grep|findfiles)$/.test(action)) return true;
282
+ if (!/^(runcommand|command|sysrun|terminal|bash|shell)$/.test(action)) return false;
283
+ const command = String(parameters.CommandLine ?? parameters.command ?? parameters.cmd ?? '').trim();
284
+ // A compound shell command can inspect and then mutate; do not count it as
285
+ // read-only merely because its first command is a probe.
286
+ if (!/[;&|]/.test(command) && /^(?:ls|rg|grep|head|tail|cat|ps|pgrep|which|file|sips|mdls)\b/.test(command)) return true;
287
+ return /\bblender\b.*--python-expr\b/is.test(command)
288
+ && /\bprint\s*\(/.test(command)
289
+ && !/\b(?:save_as_mainfile|save|render|write|unlink|remove|delete)\b/.test(command);
290
+ }
291
+
278
292
  export function mapNativeToolToCausyne(
279
293
  name: string,
280
294
  rawParams: Record<string, any>,
@@ -507,6 +521,7 @@ export class AntigravityProvider extends LLMProvider {
507
521
  printTimeout: string;
508
522
  currentConversationId: string | null = null;
509
523
  lastTaskId: string | null = null;
524
+ private lastCumulativeUsage: { conversationId: string; input: number; output: number; thinking: number; cacheRead: number } | null = null;
510
525
 
511
526
  constructor(config: ProviderConfig = {}) {
512
527
  super(config);
@@ -515,7 +530,10 @@ export class AntigravityProvider extends LLMProvider {
515
530
  this.printTimeout = typeof config.printTimeout === 'string' && config.printTimeout.trim()
516
531
  ? config.printTimeout.trim()
517
532
  : '1800s';
518
- this.visionModels = ['*'];
533
+ // This ACP bridge currently sends text-only stream-json messages. Image
534
+ // blocks are reduced to labels in formatDelta/formatConversation, so do
535
+ // not advertise vision or ask for desktop capture as proof of inspection.
536
+ this.visionModels = [];
519
537
  this.audioModels = [];
520
538
  }
521
539
 
@@ -582,18 +600,23 @@ export class AntigravityProvider extends LLMProvider {
582
600
  ' - Immediately open the URL or project in the user\'s browser using desktop.open with {"target": "http://localhost:<port>"} or run the native open command.\n' +
583
601
  ' - Confirm the application is accessible only after a readiness check succeeds.\n' +
584
602
  '3. NEVER reply with conversational pleasantries, canned greetings (e.g. "How can I help you today?"), or ask what the user wants when an instruction has already been provided.\n' +
585
- '4. Create or edit files only when the current user request authorizes it.\n\n' +
603
+ '4. Create or edit files only when the current user request authorizes it.\n' +
604
+ '5. TOKEN CONSERVATION & MEDIA DIRECTIVE:\n' +
605
+ ' - NEVER attempt to read binary or media files (.png, .jpg, .blend, .glb, .wasm, .zip, etc.) using text reading tools like read_file or cat. This blows up the token context.\n' +
606
+ ' - For 3D modeling, Blender, or media tasks: write a single self-contained generator script and execute it in one batch. Avoid dozens of speculative CLI exploration commands.\n' +
607
+ ' - Use a model-readable image channel for visual verification when available. This text-only bridge does not deliver screenshot pixels to you; a saved image or file metadata proves the file exists, not how it looks. Report visual verification as unavailable when no image channel is present.\n\n' +
586
608
  '[Environment State & Idempotency Directive]\n' +
587
609
  'Reuse relevant verified tool results from this session, and check uncertain prerequisites before relying on them.\n\n' +
588
610
  '[Language & Communication Directive]\n' +
589
- 'Dynamically reflect and match the exact language used by the user in their prompt. If the user writes in English, you must respond strictly in English. Default to English for all responses and reasoning. Never default to Indonesian or send canned greetings in Indonesian.'
611
+ 'Dynamically reflect and match the exact language used by the user in their prompt. Respond naturally in that same language. Never send conversational pleasantries or canned greetings.'
590
612
  );
591
613
 
592
614
  if (tools && tools.length > 0) {
593
- const toolSummaries = tools.map(t => {
594
- const name = t.name || t.function?.name || 'unknown';
595
- const desc = t.description || t.function?.description || '';
596
- const params = t.parameters || t.input_schema || t.function?.parameters || {};
615
+ const scanReport = scanAndAdaptToolsForProvider(tools, 'antigravity');
616
+ const toolSummaries = scanReport.adaptedTools.map((t: any) => {
617
+ const name = t.name || 'unknown';
618
+ const desc = t.description || '';
619
+ const params = t.parameters || {};
597
620
  const paramKeys = Object.keys(params.properties || {}).join(', ');
598
621
  return `- ${name}(${paramKeys}): ${desc}`;
599
622
  }).join('\n');
@@ -763,16 +786,20 @@ export class AntigravityProvider extends LLMProvider {
763
786
  const currentSessionKey = (options as any).conversationId || (options as any).taskId || null;
764
787
  if (currentSessionKey && currentSessionKey !== this.lastTaskId) {
765
788
  this.currentConversationId = null;
789
+ this.lastCumulativeUsage = null;
766
790
  this.lastTaskId = currentSessionKey;
767
791
  }
768
792
  if (messages.length <= 1) {
769
793
  this.currentConversationId = null;
794
+ this.lastCumulativeUsage = null;
770
795
  }
771
796
 
772
797
  const useConversation = Boolean(this.currentConversationId);
798
+ const resumedConversationId = this.currentConversationId;
773
799
  const latestUserMessage = [...messages].reverse().find(message => message.role === 'user');
774
800
  const latestPrompt = typeof latestUserMessage?.content === 'string' ? latestUserMessage.content : '';
775
801
  const launchOnly = (options as any).taskIntent === 'launch' || isLaunchOnlyPrompt(latestPrompt);
802
+ const desktopTask = (options as any).taskArchetype === 'desktop_personalization';
776
803
  let promptText: string;
777
804
 
778
805
  if (useConversation) {
@@ -797,6 +824,13 @@ export class AntigravityProvider extends LLMProvider {
797
824
  'Do not create, edit, delete, install, or regenerate files. Do not claim the app opened unless a tool confirmed it. ' +
798
825
  'Use Causyne tool calls for commands and desktop opening.\n\n' + promptText;
799
826
  }
827
+ if (desktopTask) {
828
+ promptText = '[Current desktop task: finish and verify the requested change]\n' +
829
+ 'Use only the tools needed. Search and download alone are not completion. ' +
830
+ 'After setting the desktop picture, read back the actual system wallpaper and compare it with the intended image. ' +
831
+ 'If a command is denied or the readback does not confirm the change, report the blocker honestly. ' +
832
+ 'Keep native tool actions within 12; use Causyne tool calls when a native action is blocked.\n\n' + promptText;
833
+ }
800
834
 
801
835
  const modelSlug = resolveAgyModelId(this.model);
802
836
  const effort = resolveAgyEffort(this.model);
@@ -859,8 +893,47 @@ export class AntigravityProvider extends LLMProvider {
859
893
  detail?: string | undefined;
860
894
  }[] = [];
861
895
  let childClosed = false;
896
+ const terminateChild = () => {
897
+ try {
898
+ child.kill('SIGTERM');
899
+ setTimeout(() => {
900
+ if (!childClosed) child.kill('SIGKILL');
901
+ }, 1000).unref();
902
+ } catch {
903
+ // A process that already exited needs no further action.
904
+ }
905
+ };
906
+ const maxNativeActions = desktopTask ? 12 : Infinity;
907
+ let nativeActionStarts = 0;
908
+ let consecutiveInspections = 0;
909
+ const seenNativeActionSteps = new Set<number>();
910
+ // Antigravity's result usage is cumulative across the conversation, but
911
+ // DONE step updates carry usage for that step. Keep a turn-local subtotal
912
+ // so a single headless run cannot consume an entire task budget unseen.
913
+ const completedUsageSteps = new Set<number>();
914
+ const partialUsage: ChatResponseUsage = {
915
+ promptTokens: 0, completionTokens: 0, cachedPromptTokens: 0,
916
+ thinkingTokens: 0, measurement: 'provider_reported', cacheMeasurement: 'provider_reported'
917
+ };
918
+ // A headless peer can run many paid model steps before chat() returns.
919
+ // Keep a finite per-call ceiling even when the optional task budget is
920
+ // disabled. Users can set a lower task budget through the existing UI.
921
+ const remainingTaskBudget = Number(options.maxTokensThisCall);
922
+ const tokenLimit = Number.isFinite(remainingTaskBudget) && remainingTaskBudget > 0
923
+ ? remainingTaskBudget
924
+ : (typeof (options as any).tokenLimit === 'number' && (options as any).tokenLimit > 0
925
+ ? (options as any).tokenLimit
926
+ : 100_000);
927
+ const wallTimer = desktopTask ? setTimeout(() => {
928
+ const error = new Error('Antigravity exceeded the 180-second desktop task limit. Outcome is unverified.') as Error & { code: string };
929
+ error.code = 'AGY_DESKTOP_TASK_LIMIT';
930
+ safeReject(error);
931
+ terminateChild();
932
+ }, 180_000) : null;
933
+ wallTimer?.unref();
862
934
 
863
935
  const cleanup = () => {
936
+ if (wallTimer) clearTimeout(wallTimer);
864
937
  if (options.signal) {
865
938
  options.signal.removeEventListener('abort', onAbort);
866
939
  }
@@ -869,6 +942,24 @@ export class AntigravityProvider extends LLMProvider {
869
942
  const safeReject = (err: Error) => {
870
943
  if (isSettled) return;
871
944
  isSettled = true;
945
+ // Failed native turns can have already consumed several model steps.
946
+ // Preserve their reported usage for the outer task ledger and prevent
947
+ // the provider from silently replaying a paid turn.
948
+ if (partialUsage.promptTokens + partialUsage.completionTokens > 0) {
949
+ Object.assign(err, { partialUsage: { ...partialUsage } });
950
+ if (((err as Error & { code?: string }).code === 'AGY_EXPLORATION_LOOP'
951
+ || (err as Error & { code?: string }).code === 'AGY_TOKEN_BUDGET') && this.currentConversationId) {
952
+ const prior = resumedConversationId === this.lastCumulativeUsage?.conversationId
953
+ ? this.lastCumulativeUsage : null;
954
+ this.lastCumulativeUsage = {
955
+ conversationId: this.currentConversationId,
956
+ input: (prior?.input || 0) + partialUsage.promptTokens,
957
+ output: (prior?.output || 0) + partialUsage.completionTokens,
958
+ thinking: (prior?.thinking || 0) + (partialUsage.thinkingTokens || 0),
959
+ cacheRead: (prior?.cacheRead || 0) + (partialUsage.cachedPromptTokens || 0)
960
+ };
961
+ }
962
+ }
872
963
  cleanup();
873
964
  reject(err);
874
965
  };
@@ -881,14 +972,7 @@ export class AntigravityProvider extends LLMProvider {
881
972
  };
882
973
 
883
974
  const onAbort = () => {
884
- try {
885
- child.kill('SIGTERM');
886
- setTimeout(() => {
887
- if (!childClosed) child.kill('SIGKILL');
888
- }, 1000).unref();
889
- } catch {
890
- // ignore kill errors
891
- }
975
+ terminateChild();
892
976
  const abortErr = new Error('Turn aborted by user or timeout.');
893
977
  abortErr.name = 'AbortError';
894
978
  safeReject(abortErr);
@@ -931,20 +1015,71 @@ export class AntigravityProvider extends LLMProvider {
931
1015
  }
932
1016
  } else if (event.event === 'step_update') {
933
1017
  const stepUpdate = event.step_update;
1018
+ const usage = stepUpdate?.usage;
1019
+ const usageStepIndex = Number(stepUpdate?.step_index ?? event?.step_index);
1020
+ if (stepUpdate?.state === 'DONE' && usage && Number.isFinite(usageStepIndex)
1021
+ && !completedUsageSteps.has(usageStepIndex)) {
1022
+ const input = Number(usage.input_tokens);
1023
+ const output = Number(usage.output_tokens);
1024
+ if (Number.isFinite(input) && input >= 0 && Number.isFinite(output) && output >= 0) {
1025
+ completedUsageSteps.add(usageStepIndex);
1026
+ partialUsage.promptTokens += input;
1027
+ partialUsage.completionTokens += output;
1028
+ partialUsage.cachedPromptTokens = (partialUsage.cachedPromptTokens || 0)
1029
+ + (Number(usage.cache_read_tokens) || 0);
1030
+ partialUsage.thinkingTokens = (partialUsage.thinkingTokens || 0)
1031
+ + (Number(usage.thinking_tokens) || 0);
1032
+ if (Number.isFinite(tokenLimit) && tokenLimit > 0
1033
+ && partialUsage.promptTokens + partialUsage.completionTokens >= tokenLimit) {
1034
+ const error = Object.assign(
1035
+ new Error(`Antigravity reported at least ${partialUsage.promptTokens + partialUsage.completionTokens} noncached tokens against a ${tokenLimit}-token per-call ceiling. This turn stopped and its outcome is unverified.`),
1036
+ { code: 'AGY_TOKEN_BUDGET', tokenLimit, partialUsage: { ...partialUsage } }
1037
+ );
1038
+ safeReject(error);
1039
+ terminateChild();
1040
+ return;
1041
+ }
1042
+ }
1043
+ }
934
1044
  const delta = stepUpdate?.text_delta;
935
1045
  const stepType = stepUpdate?.step_type;
936
1046
  if (stepType === 'tool') {
937
1047
  const state = stepUpdate?.state;
1048
+ const stepIndex = Number(stepUpdate?.step_index ?? event?.step_index);
1049
+ const newNativeAction = (state === 'ACTIVE' || (state === 'DONE' && Number.isFinite(stepIndex)))
1050
+ && (!Number.isFinite(stepIndex) || !seenNativeActionSteps.has(stepIndex));
1051
+ if (newNativeAction && Number.isFinite(stepIndex)) seenNativeActionSteps.add(stepIndex);
1052
+ if (desktopTask && newNativeAction && ++nativeActionStarts > maxNativeActions) {
1053
+ const error = new Error(`Antigravity exceeded ${maxNativeActions} native actions for this desktop task. Outcome is unverified.`) as Error & { code: string };
1054
+ error.code = 'AGY_NATIVE_ACTION_BUDGET';
1055
+ safeReject(error);
1056
+ terminateChild();
1057
+ return;
1058
+ }
938
1059
  const toolInfo = stepUpdate?.tool_info || {};
939
1060
  const name = stepUpdate?.tool_name || toolInfo?.name;
940
- const status = state === 'DONE'
941
- ? 'completed'
942
- : (state === 'ERROR' ? 'failed' : 'running');
1061
+ const status = state === 'DONE' || state === 'ERROR'
1062
+ ? (state === 'ERROR' || toolInfo?.error ? 'failed' : 'completed')
1063
+ : 'running';
943
1064
  const rawParams = (toolInfo && typeof toolInfo === 'object' && toolInfo.parameters) ||
944
1065
  (stepUpdate && typeof stepUpdate === 'object' && stepUpdate.parameters) ||
945
1066
  (toolInfo && typeof toolInfo === 'object' && toolInfo.input) ||
946
1067
  {};
947
1068
 
1069
+ if ((options as any).taskArchetype === 'media_3d_generation' && newNativeAction && name) {
1070
+ consecutiveInspections = isReadOnlyNativeInspection(String(name), rawParams)
1071
+ ? consecutiveInspections + 1 : 0;
1072
+ if (consecutiveInspections >= 10) {
1073
+ const error = Object.assign(
1074
+ new Error('Antigravity made 10 consecutive read-only media inspections without a change. Pausing to redirect the task before further token use.'),
1075
+ { code: 'AGY_EXPLORATION_LOOP', inspectionCount: consecutiveInspections }
1076
+ );
1077
+ safeReject(error);
1078
+ terminateChild();
1079
+ return;
1080
+ }
1081
+ }
1082
+
948
1083
  if (name) {
949
1084
  const existingAttempt = attemptedNativeTools.find(a => a.name === name && a.status === 'running');
950
1085
  if (existingAttempt) {
@@ -1036,6 +1171,9 @@ export class AntigravityProvider extends LLMProvider {
1036
1171
 
1037
1172
  child.on('close', (code: number | null) => {
1038
1173
  childClosed = true;
1174
+ // A budget or user abort has already settled this call. Do not accept
1175
+ // a late result from the terminated process as a resumable session.
1176
+ if (isSettled) return;
1039
1177
  // Process any remaining bytes in stdoutBuffer
1040
1178
  if (stdoutBuffer.trim()) {
1041
1179
  try {
@@ -1055,9 +1193,10 @@ export class AntigravityProvider extends LLMProvider {
1055
1193
  }
1056
1194
  }
1057
1195
 
1058
- if (code !== 0 || finalResultObj?.status === 'ERROR') {
1196
+ if (code !== 0 || (finalResultObj?.status && finalResultObj.status !== 'SUCCESS')) {
1059
1197
  if (useConversation) this.currentConversationId = null;
1060
- const errDetail = finalResultObj?.error || stderrBuffer.trim() || `exit code ${code}`;
1198
+ const errDetail = finalResultObj?.error || stderrBuffer.trim() ||
1199
+ `terminal status ${finalResultObj?.status || 'unknown'}, exit code ${code}`;
1061
1200
  safeReject(new Error(`Antigravity Agent (agy) failed: ${errDetail}`));
1062
1201
  return;
1063
1202
  }
@@ -1148,16 +1287,34 @@ export class AntigravityProvider extends LLMProvider {
1148
1287
  const missingResultEvent =
1149
1288
  finalResultObj === null && deniedActions.length === 0 && toolCalls.length === 0;
1150
1289
 
1151
- const promptTokens = Number(finalResultObj?.usage?.input_tokens) || Math.ceil(promptText.length / 4);
1152
- const completionTokens = Number(finalResultObj?.usage?.output_tokens) || Math.ceil(rawContent.length / 4);
1153
- const thinkingTokens = Number(finalResultObj?.usage?.thinking_tokens) || 0;
1290
+ const usageIsReported = finalResultObj?.usage?.input_tokens != null
1291
+ && finalResultObj?.usage?.output_tokens != null
1292
+ && Number.isFinite(Number(finalResultObj.usage.input_tokens))
1293
+ && Number.isFinite(Number(finalResultObj.usage.output_tokens));
1294
+ const cumulative = {
1295
+ input: usageIsReported ? Number(finalResultObj.usage.input_tokens) : Math.ceil(promptText.length / 4),
1296
+ output: usageIsReported ? Number(finalResultObj.usage.output_tokens) : Math.ceil(rawContent.length / 4),
1297
+ thinking: Number(finalResultObj?.usage?.thinking_tokens) || 0,
1298
+ cacheRead: Number(finalResultObj?.usage?.cache_read_tokens) || 0
1299
+ };
1300
+ const prior = useConversation && resumedConversationId === this.lastCumulativeUsage?.conversationId
1301
+ ? this.lastCumulativeUsage : null;
1302
+ const delta = (current: number, previous: number): number => current >= previous ? current - previous : current;
1303
+ const promptTokens = prior && usageIsReported ? delta(cumulative.input, prior.input) : cumulative.input;
1304
+ const completionTokens = prior && usageIsReported ? delta(cumulative.output, prior.output) : cumulative.output;
1305
+ const thinkingTokens = prior && usageIsReported ? delta(cumulative.thinking, prior.thinking) : cumulative.thinking;
1306
+ const cachedPromptTokens = prior && usageIsReported ? delta(cumulative.cacheRead, prior.cacheRead) : cumulative.cacheRead;
1154
1307
 
1155
1308
  const response: ChatResponse = {
1156
1309
  content,
1157
1310
  usage: {
1158
1311
  promptTokens,
1159
- completionTokens: completionTokens + thinkingTokens,
1160
- cachedPromptTokens: Number(finalResultObj?.usage?.cache_read_tokens) || 0
1312
+ completionTokens,
1313
+ thinkingTokens,
1314
+ cachedPromptTokens,
1315
+ measurement: usageIsReported ? 'provider_reported' : 'text_estimate',
1316
+ cacheMeasurement: finalResultObj?.usage?.cache_read_tokens != null
1317
+ ? 'provider_reported' : 'unavailable'
1161
1318
  }
1162
1319
  };
1163
1320
 
@@ -1177,6 +1334,9 @@ export class AntigravityProvider extends LLMProvider {
1177
1334
  response.incompleteTurn = true;
1178
1335
  }
1179
1336
 
1337
+ if (usageIsReported && this.currentConversationId) {
1338
+ this.lastCumulativeUsage = { conversationId: this.currentConversationId, ...cumulative };
1339
+ }
1180
1340
  safeResolve(response);
1181
1341
  });
1182
1342
  });
@@ -1193,8 +1353,13 @@ export class AntigravityProvider extends LLMProvider {
1193
1353
  if (options.signal?.aborted || err?.name === 'AbortError') {
1194
1354
  throw err;
1195
1355
  }
1356
+ if (err?.partialUsage?.promptTokens + err?.partialUsage?.completionTokens > 0) {
1357
+ throw err;
1358
+ }
1196
1359
  const canRetryResetConversation =
1197
- hadConversation && !this.currentConversationId && (err as any)?.code !== 'AGY_NATIVE_ACTION_DENIED';
1360
+ hadConversation && !this.currentConversationId
1361
+ && (err as any)?.code !== 'AGY_NATIVE_ACTION_DENIED'
1362
+ && (err as any)?.code !== 'AGY_TOKEN_BUDGET';
1198
1363
  if (attempt < maxRetries && (this._isTransientError(err.message) || canRetryResetConversation)) {
1199
1364
  attempt++;
1200
1365
  const delay = attempt * 1200;
@@ -14,6 +14,8 @@ export interface ChatResponseUsage {
14
14
  promptTokens: number;
15
15
  completionTokens: number;
16
16
  cachedPromptTokens?: number | undefined;
17
+ measurement?: 'provider_reported' | 'text_estimate' | undefined;
18
+ cacheMeasurement?: 'provider_reported' | 'unavailable' | undefined;
17
19
  totalTokens?: number | undefined;
18
20
  thinkingTokens?: number | undefined;
19
21
  }
@@ -119,7 +119,9 @@ export class PiProvider extends LLMProvider {
119
119
  usage = {
120
120
  promptTokens: Number(data.input) || 0,
121
121
  completionTokens: Number(data.output) || 0,
122
- cachedPromptTokens: Number(data.cacheRead) || 0
122
+ cachedPromptTokens: Number(data.cacheRead) || 0,
123
+ measurement: data.input != null && data.output != null ? 'provider_reported' : 'text_estimate',
124
+ cacheMeasurement: data.cacheRead != null ? 'provider_reported' : 'unavailable'
123
125
  };
124
126
  }
125
127
  else if (record.type === 'agent_settled') {
@@ -45,7 +45,7 @@ export class PiProvider extends LLMProvider {
45
45
  let acknowledged = false;
46
46
  let settled = false;
47
47
  let finished = false;
48
- let usage = { promptTokens: 0, completionTokens: 0, cachedPromptTokens: 0 };
48
+ let usage: ChatResponse['usage'] = { promptTokens: 0, completionTokens: 0, cachedPromptTokens: 0 };
49
49
 
50
50
  const cleanup = (): void => {
51
51
  options.signal?.removeEventListener('abort', abort);
@@ -115,7 +115,9 @@ export class PiProvider extends LLMProvider {
115
115
  usage = {
116
116
  promptTokens: Number(data.input) || 0,
117
117
  completionTokens: Number(data.output) || 0,
118
- cachedPromptTokens: Number(data.cacheRead) || 0
118
+ cachedPromptTokens: Number(data.cacheRead) || 0,
119
+ measurement: data.input != null && data.output != null ? 'provider_reported' : 'text_estimate',
120
+ cacheMeasurement: data.cacheRead != null ? 'provider_reported' : 'unavailable'
119
121
  };
120
122
  } else if (record.type === 'agent_settled') {
121
123
  if (record.aborted) stopReason = 'aborted';
@@ -3,7 +3,7 @@
3
3
  import fs from 'fs';
4
4
  import path from 'path';
5
5
  import { createRequire } from 'module';
6
- import { execFileSync } from 'node:child_process';
6
+ import { installCapabilityManifest } from './npmInstall.js';
7
7
  import { pathToFileURL } from 'url';
8
8
  import { loadConfig, saveConfig } from '../config.js';
9
9
  import { isGroupGranted, isGroupDeclined } from './capabilityConsent.js';
@@ -169,12 +169,7 @@ export async function provisionCapabilities(groups = []) {
169
169
 
170
170
  if (!needsInstall) return { installed: target, skipped: true };
171
171
 
172
- const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';
173
- execFileSync(
174
- npm,
175
- ['install', '--ignore-scripts', '--no-fund'],
176
- { cwd: CAPABILITY_DIR, stdio: 'inherit' }
177
- );
172
+ installCapabilityManifest(CAPABILITY_DIR);
178
173
  return { installed: target, skipped: false };
179
174
  }
180
175
 
@@ -0,0 +1,19 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ /** Install optional capabilities without writing over the active terminal UI. */
3
+ export function installCapabilityManifest(directory) {
4
+ const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';
5
+ try {
6
+ execFileSync(npm, ['install', '--ignore-scripts', '--no-fund'], {
7
+ cwd: directory,
8
+ stdio: 'pipe',
9
+ encoding: 'utf8',
10
+ maxBuffer: 2 * 1024 * 1024,
11
+ timeout: 120_000,
12
+ windowsHide: true
13
+ });
14
+ }
15
+ catch (error) {
16
+ const reason = error instanceof Error ? error.message : String(error);
17
+ throw new Error(`Capability installation failed: ${reason.slice(0, 600)}`, { cause: error });
18
+ }
19
+ }
@@ -0,0 +1,19 @@
1
+ import { execFileSync } from 'node:child_process';
2
+
3
+ /** Install optional capabilities without writing over the active terminal UI. */
4
+ export function installCapabilityManifest(directory: string): void {
5
+ const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';
6
+ try {
7
+ execFileSync(npm, ['install', '--ignore-scripts', '--no-fund'], {
8
+ cwd: directory,
9
+ stdio: 'pipe',
10
+ encoding: 'utf8',
11
+ maxBuffer: 2 * 1024 * 1024,
12
+ timeout: 120_000,
13
+ windowsHide: true
14
+ });
15
+ } catch (error: unknown) {
16
+ const reason = error instanceof Error ? error.message : String(error);
17
+ throw new Error(`Capability installation failed: ${reason.slice(0, 600)}`, { cause: error });
18
+ }
19
+ }
package/src/sandbox.js CHANGED
@@ -127,7 +127,7 @@ const SENSITIVE_WRITE_TARGETS = [
127
127
  // Shell startup files: an appended line runs on the user's next shell.
128
128
  /(^|\/)\.(bashrc|bash_profile|bash_login|profile|zshrc|zprofile|zshenv|zlogin)$/,
129
129
  /(^|\/)\.config\/fish\/config\.fish$/,
130
- // SSH: authorized_keys grants login; config can silently reroute connections.
130
+ // Remote session routing profiles and authentication credentials.
131
131
  /(^|\/)\.ssh\//,
132
132
  // Scheduled execution.
133
133
  /(^|\/)(crontab|cron\.d)(\/|$)/,
@@ -477,15 +477,12 @@ export class Sandbox {
477
477
  const masked = maskQuotedSpans(normalized);
478
478
 
479
479
 
480
- // L3 (local-path audit): classify the REDIRECTION TARGET, not just the verb.
481
- //
482
- // sandbox.validate() path-scopes tool ARGUMENTS, but a shell redirection
483
- // target is invisible to it, and the classifier only ever looked at the
484
- // command word. So `echo evil >> ~/.bashrc` and
485
- // `cat payload >> ~/.ssh/authorized_keys` both classified as SAFE and
486
- // auto-executed in every autonomy mode — persistence and remote access with
487
- // no approval prompt. Writing to these files is escalated regardless of
488
- // which harmless-looking command does the writing.
480
+ // L3 (local-path audit): classify the redirection target, not just the verb.
481
+ // Tool argument validation enforces boundaries on named arguments, but
482
+ // shell redirection targets appended via operators (>> or >) require independent
483
+ // audit. Writing into sensitive paths (such as user startup profiles, remote
484
+ // authentication directories, or agent configuration stores) must always escalate
485
+ // to extreme classification regardless of which command performs the redirection.
489
486
  if (redirectsIntoSensitiveTarget(masked)) return 'extreme';
490
487
  const executesQuotedText = INTERPRETER_INVOCATION.test(masked);
491
488
  const destructiveScanTarget = executesQuotedText ? normalized : masked;