@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,6 +2,7 @@ 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 { scanAndAdaptToolsForProvider } from '../tools/toolScanner.js';
5
6
  import { LLMProvider } from './base.js';
6
7
  /**
7
8
  * Baseline fallback models for instant offline availability.
@@ -272,6 +273,21 @@ function describeNativeAction(toolInfo) {
272
273
  }
273
274
  return undefined;
274
275
  }
276
+ export function isReadOnlyNativeInspection(name, parameters) {
277
+ const action = name.toLowerCase().replace(/[_\s-]/g, '');
278
+ if (/^(readfile|listdirectory|listfiles|search|searchweb|grep|findfiles)$/.test(action))
279
+ return true;
280
+ if (!/^(runcommand|command|sysrun|terminal|bash|shell)$/.test(action))
281
+ return false;
282
+ const command = String(parameters.CommandLine ?? parameters.command ?? parameters.cmd ?? '').trim();
283
+ // A compound shell command can inspect and then mutate; do not count it as
284
+ // read-only merely because its first command is a probe.
285
+ if (!/[;&|]/.test(command) && /^(?:ls|rg|grep|head|tail|cat|ps|pgrep|which|file|sips|mdls)\b/.test(command))
286
+ 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
+ }
275
291
  export function mapNativeToolToCausyne(name, rawParams, index) {
276
292
  if (!name || typeof name !== 'string')
277
293
  return null;
@@ -490,6 +506,7 @@ export class AntigravityProvider extends LLMProvider {
490
506
  printTimeout;
491
507
  currentConversationId = null;
492
508
  lastTaskId = null;
509
+ lastCumulativeUsage = null;
493
510
  constructor(config = {}) {
494
511
  super(config);
495
512
  this.model = config.model || 'Gemini 3.8 Flash (Low)';
@@ -497,7 +514,10 @@ export class AntigravityProvider extends LLMProvider {
497
514
  this.printTimeout = typeof config.printTimeout === 'string' && config.printTimeout.trim()
498
515
  ? config.printTimeout.trim()
499
516
  : '1800s';
500
- this.visionModels = ['*'];
517
+ // This ACP bridge currently sends text-only stream-json messages. Image
518
+ // blocks are reduced to labels in formatDelta/formatConversation, so do
519
+ // not advertise vision or ask for desktop capture as proof of inspection.
520
+ this.visionModels = [];
501
521
  this.audioModels = [];
502
522
  }
503
523
  formatDelta(messages) {
@@ -560,16 +580,21 @@ export class AntigravityProvider extends LLMProvider {
560
580
  ' - 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' +
561
581
  ' - Confirm the application is accessible only after a readiness check succeeds.\n' +
562
582
  '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' +
563
- '4. Create or edit files only when the current user request authorizes it.\n\n' +
583
+ '4. Create or edit files only when the current user request authorizes it.\n' +
584
+ '5. TOKEN CONSERVATION & MEDIA DIRECTIVE:\n' +
585
+ ' - 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' +
586
+ ' - 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' +
587
+ ' - 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' +
564
588
  '[Environment State & Idempotency Directive]\n' +
565
589
  'Reuse relevant verified tool results from this session, and check uncertain prerequisites before relying on them.\n\n' +
566
590
  '[Language & Communication Directive]\n' +
567
- '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.');
591
+ '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.');
568
592
  if (tools && tools.length > 0) {
569
- const toolSummaries = tools.map(t => {
570
- const name = t.name || t.function?.name || 'unknown';
571
- const desc = t.description || t.function?.description || '';
572
- const params = t.parameters || t.input_schema || t.function?.parameters || {};
593
+ const scanReport = scanAndAdaptToolsForProvider(tools, 'antigravity');
594
+ const toolSummaries = scanReport.adaptedTools.map((t) => {
595
+ const name = t.name || 'unknown';
596
+ const desc = t.description || '';
597
+ const params = t.parameters || {};
573
598
  const paramKeys = Object.keys(params.properties || {}).join(', ');
574
599
  return `- ${name}(${paramKeys}): ${desc}`;
575
600
  }).join('\n');
@@ -734,15 +759,19 @@ export class AntigravityProvider extends LLMProvider {
734
759
  const currentSessionKey = options.conversationId || options.taskId || null;
735
760
  if (currentSessionKey && currentSessionKey !== this.lastTaskId) {
736
761
  this.currentConversationId = null;
762
+ this.lastCumulativeUsage = null;
737
763
  this.lastTaskId = currentSessionKey;
738
764
  }
739
765
  if (messages.length <= 1) {
740
766
  this.currentConversationId = null;
767
+ this.lastCumulativeUsage = null;
741
768
  }
742
769
  const useConversation = Boolean(this.currentConversationId);
770
+ const resumedConversationId = this.currentConversationId;
743
771
  const latestUserMessage = [...messages].reverse().find(message => message.role === 'user');
744
772
  const latestPrompt = typeof latestUserMessage?.content === 'string' ? latestUserMessage.content : '';
745
773
  const launchOnly = options.taskIntent === 'launch' || isLaunchOnlyPrompt(latestPrompt);
774
+ const desktopTask = options.taskArchetype === 'desktop_personalization';
746
775
  let promptText;
747
776
  if (useConversation) {
748
777
  let lastAssistantIndex = -1;
@@ -766,6 +795,13 @@ export class AntigravityProvider extends LLMProvider {
766
795
  'Do not create, edit, delete, install, or regenerate files. Do not claim the app opened unless a tool confirmed it. ' +
767
796
  'Use Causyne tool calls for commands and desktop opening.\n\n' + promptText;
768
797
  }
798
+ if (desktopTask) {
799
+ promptText = '[Current desktop task: finish and verify the requested change]\n' +
800
+ 'Use only the tools needed. Search and download alone are not completion. ' +
801
+ 'After setting the desktop picture, read back the actual system wallpaper and compare it with the intended image. ' +
802
+ 'If a command is denied or the readback does not confirm the change, report the blocker honestly. ' +
803
+ 'Keep native tool actions within 12; use Causyne tool calls when a native action is blocked.\n\n' + promptText;
804
+ }
769
805
  const modelSlug = resolveAgyModelId(this.model);
770
806
  const effort = resolveAgyEffort(this.model);
771
807
  // Standard high-performance non-blocking CLI invocation:
@@ -817,7 +853,49 @@ export class AntigravityProvider extends LLMProvider {
817
853
  const nativeActions = [];
818
854
  const attemptedNativeTools = [];
819
855
  let childClosed = false;
856
+ const terminateChild = () => {
857
+ try {
858
+ child.kill('SIGTERM');
859
+ setTimeout(() => {
860
+ if (!childClosed)
861
+ child.kill('SIGKILL');
862
+ }, 1000).unref();
863
+ }
864
+ catch {
865
+ // A process that already exited needs no further action.
866
+ }
867
+ };
868
+ const maxNativeActions = desktopTask ? 12 : Infinity;
869
+ let nativeActionStarts = 0;
870
+ let consecutiveInspections = 0;
871
+ const seenNativeActionSteps = new Set();
872
+ // Antigravity's result usage is cumulative across the conversation, but
873
+ // DONE step updates carry usage for that step. Keep a turn-local subtotal
874
+ // so a single headless run cannot consume an entire task budget unseen.
875
+ const completedUsageSteps = new Set();
876
+ const partialUsage = {
877
+ promptTokens: 0, completionTokens: 0, cachedPromptTokens: 0,
878
+ thinkingTokens: 0, measurement: 'provider_reported', cacheMeasurement: 'provider_reported'
879
+ };
880
+ // A headless peer can run many paid model steps before chat() returns.
881
+ // Keep a finite per-call ceiling even when the optional task budget is
882
+ // disabled. Users can set a lower task budget through the existing UI.
883
+ const remainingTaskBudget = Number(options.maxTokensThisCall);
884
+ const tokenLimit = Number.isFinite(remainingTaskBudget) && remainingTaskBudget > 0
885
+ ? remainingTaskBudget
886
+ : (typeof options.tokenLimit === 'number' && options.tokenLimit > 0
887
+ ? options.tokenLimit
888
+ : 100_000);
889
+ const wallTimer = desktopTask ? setTimeout(() => {
890
+ const error = new Error('Antigravity exceeded the 180-second desktop task limit. Outcome is unverified.');
891
+ error.code = 'AGY_DESKTOP_TASK_LIMIT';
892
+ safeReject(error);
893
+ terminateChild();
894
+ }, 180_000) : null;
895
+ wallTimer?.unref();
820
896
  const cleanup = () => {
897
+ if (wallTimer)
898
+ clearTimeout(wallTimer);
821
899
  if (options.signal) {
822
900
  options.signal.removeEventListener('abort', onAbort);
823
901
  }
@@ -826,6 +904,24 @@ export class AntigravityProvider extends LLMProvider {
826
904
  if (isSettled)
827
905
  return;
828
906
  isSettled = true;
907
+ // Failed native turns can have already consumed several model steps.
908
+ // Preserve their reported usage for the outer task ledger and prevent
909
+ // the provider from silently replaying a paid turn.
910
+ if (partialUsage.promptTokens + partialUsage.completionTokens > 0) {
911
+ Object.assign(err, { partialUsage: { ...partialUsage } });
912
+ if ((err.code === 'AGY_EXPLORATION_LOOP'
913
+ || err.code === 'AGY_TOKEN_BUDGET') && this.currentConversationId) {
914
+ const prior = resumedConversationId === this.lastCumulativeUsage?.conversationId
915
+ ? this.lastCumulativeUsage : null;
916
+ this.lastCumulativeUsage = {
917
+ conversationId: this.currentConversationId,
918
+ input: (prior?.input || 0) + partialUsage.promptTokens,
919
+ output: (prior?.output || 0) + partialUsage.completionTokens,
920
+ thinking: (prior?.thinking || 0) + (partialUsage.thinkingTokens || 0),
921
+ cacheRead: (prior?.cacheRead || 0) + (partialUsage.cachedPromptTokens || 0)
922
+ };
923
+ }
924
+ }
829
925
  cleanup();
830
926
  reject(err);
831
927
  };
@@ -837,16 +933,7 @@ export class AntigravityProvider extends LLMProvider {
837
933
  resolve(res);
838
934
  };
839
935
  const onAbort = () => {
840
- try {
841
- child.kill('SIGTERM');
842
- setTimeout(() => {
843
- if (!childClosed)
844
- child.kill('SIGKILL');
845
- }, 1000).unref();
846
- }
847
- catch {
848
- // ignore kill errors
849
- }
936
+ terminateChild();
850
937
  const abortErr = new Error('Turn aborted by user or timeout.');
851
938
  abortErr.name = 'AbortError';
852
939
  safeReject(abortErr);
@@ -887,19 +974,64 @@ export class AntigravityProvider extends LLMProvider {
887
974
  }
888
975
  else if (event.event === 'step_update') {
889
976
  const stepUpdate = event.step_update;
977
+ const usage = stepUpdate?.usage;
978
+ const usageStepIndex = Number(stepUpdate?.step_index ?? event?.step_index);
979
+ if (stepUpdate?.state === 'DONE' && usage && Number.isFinite(usageStepIndex)
980
+ && !completedUsageSteps.has(usageStepIndex)) {
981
+ const input = Number(usage.input_tokens);
982
+ const output = Number(usage.output_tokens);
983
+ if (Number.isFinite(input) && input >= 0 && Number.isFinite(output) && output >= 0) {
984
+ completedUsageSteps.add(usageStepIndex);
985
+ partialUsage.promptTokens += input;
986
+ partialUsage.completionTokens += output;
987
+ partialUsage.cachedPromptTokens = (partialUsage.cachedPromptTokens || 0)
988
+ + (Number(usage.cache_read_tokens) || 0);
989
+ partialUsage.thinkingTokens = (partialUsage.thinkingTokens || 0)
990
+ + (Number(usage.thinking_tokens) || 0);
991
+ if (Number.isFinite(tokenLimit) && tokenLimit > 0
992
+ && partialUsage.promptTokens + partialUsage.completionTokens >= tokenLimit) {
993
+ const error = Object.assign(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.`), { code: 'AGY_TOKEN_BUDGET', tokenLimit, partialUsage: { ...partialUsage } });
994
+ safeReject(error);
995
+ terminateChild();
996
+ return;
997
+ }
998
+ }
999
+ }
890
1000
  const delta = stepUpdate?.text_delta;
891
1001
  const stepType = stepUpdate?.step_type;
892
1002
  if (stepType === 'tool') {
893
1003
  const state = stepUpdate?.state;
1004
+ const stepIndex = Number(stepUpdate?.step_index ?? event?.step_index);
1005
+ const newNativeAction = (state === 'ACTIVE' || (state === 'DONE' && Number.isFinite(stepIndex)))
1006
+ && (!Number.isFinite(stepIndex) || !seenNativeActionSteps.has(stepIndex));
1007
+ if (newNativeAction && Number.isFinite(stepIndex))
1008
+ seenNativeActionSteps.add(stepIndex);
1009
+ if (desktopTask && newNativeAction && ++nativeActionStarts > maxNativeActions) {
1010
+ const error = new Error(`Antigravity exceeded ${maxNativeActions} native actions for this desktop task. Outcome is unverified.`);
1011
+ error.code = 'AGY_NATIVE_ACTION_BUDGET';
1012
+ safeReject(error);
1013
+ terminateChild();
1014
+ return;
1015
+ }
894
1016
  const toolInfo = stepUpdate?.tool_info || {};
895
1017
  const name = stepUpdate?.tool_name || toolInfo?.name;
896
- const status = state === 'DONE'
897
- ? 'completed'
898
- : (state === 'ERROR' ? 'failed' : 'running');
1018
+ const status = state === 'DONE' || state === 'ERROR'
1019
+ ? (state === 'ERROR' || toolInfo?.error ? 'failed' : 'completed')
1020
+ : 'running';
899
1021
  const rawParams = (toolInfo && typeof toolInfo === 'object' && toolInfo.parameters) ||
900
1022
  (stepUpdate && typeof stepUpdate === 'object' && stepUpdate.parameters) ||
901
1023
  (toolInfo && typeof toolInfo === 'object' && toolInfo.input) ||
902
1024
  {};
1025
+ if (options.taskArchetype === 'media_3d_generation' && newNativeAction && name) {
1026
+ consecutiveInspections = isReadOnlyNativeInspection(String(name), rawParams)
1027
+ ? consecutiveInspections + 1 : 0;
1028
+ if (consecutiveInspections >= 10) {
1029
+ const error = Object.assign(new Error('Antigravity made 10 consecutive read-only media inspections without a change. Pausing to redirect the task before further token use.'), { code: 'AGY_EXPLORATION_LOOP', inspectionCount: consecutiveInspections });
1030
+ safeReject(error);
1031
+ terminateChild();
1032
+ return;
1033
+ }
1034
+ }
903
1035
  if (name) {
904
1036
  const existingAttempt = attemptedNativeTools.find(a => a.name === name && a.status === 'running');
905
1037
  if (existingAttempt) {
@@ -997,6 +1129,10 @@ export class AntigravityProvider extends LLMProvider {
997
1129
  });
998
1130
  child.on('close', (code) => {
999
1131
  childClosed = true;
1132
+ // A budget or user abort has already settled this call. Do not accept
1133
+ // a late result from the terminated process as a resumable session.
1134
+ if (isSettled)
1135
+ return;
1000
1136
  // Process any remaining bytes in stdoutBuffer
1001
1137
  if (stdoutBuffer.trim()) {
1002
1138
  try {
@@ -1018,10 +1154,11 @@ export class AntigravityProvider extends LLMProvider {
1018
1154
  // ignore
1019
1155
  }
1020
1156
  }
1021
- if (code !== 0 || finalResultObj?.status === 'ERROR') {
1157
+ if (code !== 0 || (finalResultObj?.status && finalResultObj.status !== 'SUCCESS')) {
1022
1158
  if (useConversation)
1023
1159
  this.currentConversationId = null;
1024
- const errDetail = finalResultObj?.error || stderrBuffer.trim() || `exit code ${code}`;
1160
+ const errDetail = finalResultObj?.error || stderrBuffer.trim() ||
1161
+ `terminal status ${finalResultObj?.status || 'unknown'}, exit code ${code}`;
1025
1162
  safeReject(new Error(`Antigravity Agent (agy) failed: ${errDetail}`));
1026
1163
  return;
1027
1164
  }
@@ -1096,15 +1233,33 @@ export class AntigravityProvider extends LLMProvider {
1096
1233
  const finalResponseText = typeof finalResultObj?.response === 'string' ? finalResultObj.response.trim() : '';
1097
1234
  const endedAfterToolWithoutFinalResponse = sawToolAfterLastText && !finalResponseText && deniedActions.length === 0 && toolCalls.length === 0;
1098
1235
  const missingResultEvent = finalResultObj === null && deniedActions.length === 0 && toolCalls.length === 0;
1099
- const promptTokens = Number(finalResultObj?.usage?.input_tokens) || Math.ceil(promptText.length / 4);
1100
- const completionTokens = Number(finalResultObj?.usage?.output_tokens) || Math.ceil(rawContent.length / 4);
1101
- const thinkingTokens = Number(finalResultObj?.usage?.thinking_tokens) || 0;
1236
+ const usageIsReported = finalResultObj?.usage?.input_tokens != null
1237
+ && finalResultObj?.usage?.output_tokens != null
1238
+ && Number.isFinite(Number(finalResultObj.usage.input_tokens))
1239
+ && Number.isFinite(Number(finalResultObj.usage.output_tokens));
1240
+ const cumulative = {
1241
+ input: usageIsReported ? Number(finalResultObj.usage.input_tokens) : Math.ceil(promptText.length / 4),
1242
+ output: usageIsReported ? Number(finalResultObj.usage.output_tokens) : Math.ceil(rawContent.length / 4),
1243
+ thinking: Number(finalResultObj?.usage?.thinking_tokens) || 0,
1244
+ cacheRead: Number(finalResultObj?.usage?.cache_read_tokens) || 0
1245
+ };
1246
+ const prior = useConversation && resumedConversationId === this.lastCumulativeUsage?.conversationId
1247
+ ? this.lastCumulativeUsage : null;
1248
+ const delta = (current, previous) => current >= previous ? current - previous : current;
1249
+ const promptTokens = prior && usageIsReported ? delta(cumulative.input, prior.input) : cumulative.input;
1250
+ const completionTokens = prior && usageIsReported ? delta(cumulative.output, prior.output) : cumulative.output;
1251
+ const thinkingTokens = prior && usageIsReported ? delta(cumulative.thinking, prior.thinking) : cumulative.thinking;
1252
+ const cachedPromptTokens = prior && usageIsReported ? delta(cumulative.cacheRead, prior.cacheRead) : cumulative.cacheRead;
1102
1253
  const response = {
1103
1254
  content,
1104
1255
  usage: {
1105
1256
  promptTokens,
1106
- completionTokens: completionTokens + thinkingTokens,
1107
- cachedPromptTokens: Number(finalResultObj?.usage?.cache_read_tokens) || 0
1257
+ completionTokens,
1258
+ thinkingTokens,
1259
+ cachedPromptTokens,
1260
+ measurement: usageIsReported ? 'provider_reported' : 'text_estimate',
1261
+ cacheMeasurement: finalResultObj?.usage?.cache_read_tokens != null
1262
+ ? 'provider_reported' : 'unavailable'
1108
1263
  }
1109
1264
  };
1110
1265
  if (extractedReasoning) {
@@ -1119,6 +1274,9 @@ export class AntigravityProvider extends LLMProvider {
1119
1274
  if (timedOutMidTurn || endedAfterToolWithoutFinalResponse || missingResultEvent) {
1120
1275
  response.incompleteTurn = true;
1121
1276
  }
1277
+ if (usageIsReported && this.currentConversationId) {
1278
+ this.lastCumulativeUsage = { conversationId: this.currentConversationId, ...cumulative };
1279
+ }
1122
1280
  safeResolve(response);
1123
1281
  });
1124
1282
  });
@@ -1135,7 +1293,12 @@ export class AntigravityProvider extends LLMProvider {
1135
1293
  if (options.signal?.aborted || err?.name === 'AbortError') {
1136
1294
  throw err;
1137
1295
  }
1138
- const canRetryResetConversation = hadConversation && !this.currentConversationId && err?.code !== 'AGY_NATIVE_ACTION_DENIED';
1296
+ if (err?.partialUsage?.promptTokens + err?.partialUsage?.completionTokens > 0) {
1297
+ throw err;
1298
+ }
1299
+ const canRetryResetConversation = hadConversation && !this.currentConversationId
1300
+ && err?.code !== 'AGY_NATIVE_ACTION_DENIED'
1301
+ && err?.code !== 'AGY_TOKEN_BUDGET';
1139
1302
  if (attempt < maxRetries && (this._isTransientError(err.message) || canRetryResetConversation)) {
1140
1303
  attempt++;
1141
1304
  const delay = attempt * 1200;