@causyne/agent 1.20.11 → 1.20.13

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 (86) hide show
  1. package/LICENSE +1 -1
  2. package/docs/ARCHITECTURE.md +24 -1
  3. package/package.json +1 -1
  4. package/src/acp/client.js +9 -2
  5. package/src/acp/client.ts +11 -2
  6. package/src/acp/protocol.ts +9 -0
  7. package/src/agentLoop.js +504 -119
  8. package/src/agentLoop.ts +477 -121
  9. package/src/browser/browserRuntime.js +47 -0
  10. package/src/browser/browserRuntime.ts +45 -0
  11. package/src/browser/causyneBrowser.js +60 -31
  12. package/src/browser/causyneBrowser.ts +37 -12
  13. package/src/browser/workspacePreview.js +52 -0
  14. package/src/browser/workspacePreview.ts +49 -0
  15. package/src/core/planCache.js +5 -0
  16. package/src/core/planCache.ts +5 -0
  17. package/src/decisionPolicy.js +9 -0
  18. package/src/decisionPolicy.ts +8 -0
  19. package/src/historyPruner.js +251 -0
  20. package/src/historyPruner.ts +263 -0
  21. package/src/infra/atomicWriter.js +49 -0
  22. package/src/infra/atomicWriter.ts +63 -0
  23. package/src/infra/telemetry.js +38 -0
  24. package/src/infra/telemetry.ts +68 -0
  25. package/src/observer/coldObserver.js +12 -7
  26. package/src/observer/coldObserver.ts +12 -7
  27. package/src/observer/evidence.js +8 -2
  28. package/src/observer/evidence.ts +9 -2
  29. package/src/outputRecovery.js +36 -0
  30. package/src/outputRecovery.ts +33 -0
  31. package/src/providers/acp.js +114 -46
  32. package/src/providers/acp.ts +129 -46
  33. package/src/providers/antigravity.js +264 -82
  34. package/src/providers/antigravity.ts +273 -87
  35. package/src/providers/antigravityBridge.js +58 -0
  36. package/src/providers/antigravityBridge.ts +51 -0
  37. package/src/providers/base.d.ts +9 -0
  38. package/src/providers/budgetEnforcer.js +110 -0
  39. package/src/providers/budgetEnforcer.ts +122 -0
  40. package/src/providers/collaborationPolicy.js +6 -0
  41. package/src/providers/collaborationPolicy.ts +7 -0
  42. package/src/providers/loopGuard.js +84 -0
  43. package/src/providers/loopGuard.ts +105 -0
  44. package/src/providers/pi.js +19 -6
  45. package/src/providers/pi.ts +19 -7
  46. package/src/providers/toolContracts.js +36 -0
  47. package/src/providers/toolContracts.ts +48 -0
  48. package/src/session/sidechainEvents.js +49 -0
  49. package/src/session/sidechainEvents.ts +98 -0
  50. package/src/skillsManager.d.ts +1 -0
  51. package/src/smartToolsUse.js +123 -4
  52. package/src/smartToolsUse.ts +136 -4
  53. package/src/subagent/sidechainHarness.js +66 -0
  54. package/src/subagent/sidechainHarness.ts +91 -0
  55. package/src/taskContinuation.js +12 -0
  56. package/src/taskContinuation.ts +13 -0
  57. package/src/tokenTracker.js +406 -539
  58. package/src/tokenTracker.ts +569 -0
  59. package/src/toolPacks.d.ts +2 -0
  60. package/src/toolPacks.js +1 -1
  61. package/src/tools/argumentValidation.js +56 -0
  62. package/src/tools/argumentValidation.ts +50 -0
  63. package/src/tools/browserAutomator.js +2 -2
  64. package/src/tools/browserAutomator.ts +3 -2
  65. package/src/tools/deferredMcpSearch.js +188 -201
  66. package/src/tools/deferredMcpSearch.ts +250 -0
  67. package/src/tools/generateMediaViaApi.js +305 -331
  68. package/src/tools/generateMediaViaApi.ts +330 -0
  69. package/src/tools/historyPruner.js +5 -0
  70. package/src/tools/historyPruner.ts +5 -0
  71. package/src/tools/payloadSanitizer.js +92 -0
  72. package/src/tools/payloadSanitizer.ts +113 -0
  73. package/src/tools/registry.d.ts +1 -0
  74. package/src/tools/sysRun.js +47 -18
  75. package/src/tools/sysRun.ts +52 -20
  76. package/src/tools/toolOutputStore.js +180 -0
  77. package/src/tools/toolOutputStore.ts +209 -0
  78. package/src/tools/toolSelfRepair.js +26 -1
  79. package/src/tools/toolSelfRepair.ts +25 -1
  80. package/src/tui/chatRenderer.d.ts +1 -0
  81. package/src/tui/chatRenderer.js +4 -2
  82. package/src/tui/codeStreamRenderer.js +36 -8
  83. package/src/tui/codeStreamRenderer.ts +38 -8
  84. package/src/tui/stageSurface.js +1 -0
  85. package/src/tui/text.js +4 -1
  86. package/src/tokenTracker.d.ts +0 -1
@@ -1,8 +1,10 @@
1
+ import { formatToolContracts, toolContractUpdate, contractFingerprint } from './toolContracts.js';
2
+ import { noncachedTokens } from './budgetEnforcer.js';
3
+ import { PEER_COLLABORATION_POLICY } from './collaborationPolicy.js';
1
4
  import { spawn } from 'node:child_process';
2
5
  import fs from 'node:fs';
3
6
  import path from 'node:path';
4
7
  import { isLaunchOnlyPrompt } from '../launchIntent.js';
5
- import { scanAndAdaptToolsForProvider } from '../tools/toolScanner.js';
6
8
  import { LLMProvider } from './base.js';
7
9
  /**
8
10
  * Baseline fallback models for instant offline availability.
@@ -273,20 +275,97 @@ function describeNativeAction(toolInfo) {
273
275
  }
274
276
  return undefined;
275
277
  }
278
+ function cleanCommandString(raw) {
279
+ if (typeof raw !== 'string')
280
+ return '';
281
+ let cmd = raw.trim();
282
+ if ((cmd.startsWith('"') && cmd.endsWith('"')) || (cmd.startsWith("'") && cmd.endsWith("'"))) {
283
+ cmd = cmd.slice(1, -1).trim();
284
+ }
285
+ return cmd.replace(/\\"/g, '"').replace(/\\'/g, "'").replace(/\\\\/g, '\\').trim();
286
+ }
276
287
  export function isReadOnlyNativeInspection(name, parameters) {
277
288
  const action = name.toLowerCase().replace(/[_\s-]/g, '');
278
- if (/^(readfile|listdirectory|listfiles|search|searchweb|grep|findfiles)$/.test(action))
289
+ if (/^(readfile|viewfile|listdirectory|listfiles|search|searchweb|grep|findfiles)$/.test(action))
279
290
  return true;
280
291
  if (!/^(runcommand|command|sysrun|terminal|bash|shell)$/.test(action))
281
292
  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))
293
+ const command = cleanCommandString(parameters.CommandLine ?? parameters.command ?? parameters.cmd ?? '');
294
+ if (!command)
295
+ return false;
296
+ // Single or compound read-only shell commands (e.g. ps aux | grep -i blender)
297
+ if (/^(?:ls|rg|grep|head|tail|cat|sed|ps|pgrep|which|file|sips|mdls|git\s+status|git\s+diff|git\s+log)\b/i.test(command)) {
298
+ if (/[;&|]/.test(command)) {
299
+ const parts = command.split(/[;&|]/).map(p => p.trim()).filter(Boolean);
300
+ return parts.every(p => /^(?:ls|rg|grep|head|tail|cat|sed|ps|pgrep|which|file|sips|mdls|awk|cut|sort|uniq|wc)\b/i.test(p));
301
+ }
286
302
  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);
303
+ }
304
+ // Python image / PIL pixel inspection probes without mutation
305
+ if (/^python[23]?\s+-c\b/i.test(command) && /Image\.open/i.test(command) && !/\b(?:save|write|remove|unlink)\b/i.test(command)) {
306
+ return true;
307
+ }
308
+ // Blender inspection expressions (printing objects, collections, render engine)
309
+ if (/\bblender\b.*--python-expr\b/is.test(command)) {
310
+ const exprMatch = /--python-expr\s+["']([\s\S]*?)["'](?:\s|$)/i.exec(command)
311
+ || /--python-expr\s+([\s\S]+)$/i.exec(command);
312
+ const expr = (exprMatch ? exprMatch[1] : null) || command;
313
+ return !/\b(?:save_as_mainfile|save_mainfile|write_still\s*=\s*True|write_text|write_bytes|os\.remove|os\.unlink)\b/i.test(expr);
314
+ }
315
+ return false;
316
+ }
317
+ function nativeInspectionTarget(name, parameters) {
318
+ const normName = name.toLowerCase().replace(/[_\s-]/g, '');
319
+ if (!/^(runcommand|command|sysrun|terminal|bash|shell)$/.test(normName)) {
320
+ if (/^(readfile|viewfile)$/.test(normName)) {
321
+ const p = String(parameters.AbsolutePath ?? parameters.filePath ?? parameters.path ?? parameters.file ?? '');
322
+ if (p)
323
+ return p.trim().toLowerCase();
324
+ }
325
+ return null;
326
+ }
327
+ const command = cleanCommandString(parameters.CommandLine ?? parameters.command ?? parameters.cmd ?? '');
328
+ if (!command)
329
+ return null;
330
+ // 1. Blender scene probes (handles escaped quotes and spaces in filepath)
331
+ if (/\bblender\b/i.test(command)) {
332
+ if (/\b(?:save_as_mainfile|save_mainfile)\b/.test(command))
333
+ return null;
334
+ if (/--python-expr\b/i.test(command) || /-b\b|--background\b/i.test(command)) {
335
+ const blendMatch = /--background\s+["']?([^"'\n]+?\.blend\d*)["']?(?:\s|$)/i.exec(command)
336
+ || /["']?([^"'\n]+?\.blend\d*)["']?/i.exec(command);
337
+ if (blendMatch && blendMatch[1]) {
338
+ return blendMatch[1].trim().toLowerCase();
339
+ }
340
+ }
341
+ }
342
+ // 2. Python image inspections: from PIL import Image; Image.open(...)
343
+ if (/Image\.open\s*\(\s*["']([^"'\n]+)["']\s*\)/i.test(command)) {
344
+ const imgMatch = /Image\.open\s*\(\s*["']([^"'\n]+)["']\s*\)/i.exec(command);
345
+ if (imgMatch && imgMatch[1]) {
346
+ return imgMatch[1].trim().toLowerCase();
347
+ }
348
+ }
349
+ // 3. Repetitive CLI file reads on workspace files
350
+ const fileProbeMatch = /^(?:head|tail|sed|cat|grep)\b.*?["']([^"'\n]+\.(?:py|blend\d*|json|ts|js|png|jpg))["']/i.exec(command)
351
+ || /^(?:head|tail|sed|cat|grep)\b.*?(\S+\.(?:py|blend\d*|json|ts|js|png|jpg))/i.exec(command);
352
+ const rawFile = fileProbeMatch ? (fileProbeMatch[1] || fileProbeMatch[2]) : null;
353
+ if (rawFile) {
354
+ return rawFile.trim().toLowerCase();
355
+ }
356
+ return null;
357
+ }
358
+ function isNativeMutation(name, parameters) {
359
+ const action = name.toLowerCase().replace(/[_\s-]/g, '');
360
+ if (/^(writefile|editfile|deletefile|applypatch|createfile|replaceinfile)$/.test(action))
361
+ return true;
362
+ if (!/^(runcommand|command|sysrun|terminal|bash|shell)$/.test(action))
363
+ return false;
364
+ const command = cleanCommandString(parameters.CommandLine ?? parameters.command ?? parameters.cmd ?? '');
365
+ if (!command)
366
+ return false;
367
+ return /\b(?:save_as_mainfile|save_mainfile|write_text|write_bytes|tee)\b/.test(command)
368
+ || /(?:^|[;&|]\s*)(?:cp|mv|rm|install|patch)\s/.test(command);
290
369
  }
291
370
  export function mapNativeToolToCausyne(name, rawParams, index) {
292
371
  if (!name || typeof name !== 'string')
@@ -368,9 +447,11 @@ export function mapNativeToolToCausyne(name, rawParams, index) {
368
447
  };
369
448
  }
370
449
  }
371
- if (lowerName === 'writetofile' || lowerName === 'fswrite') {
450
+ if (['writetofile', 'writefile', 'createfile', 'fswrite'].includes(lowerName)) {
372
451
  const filePath = params.TargetFile ?? params.path ?? params.file_path ?? '';
373
- const content = params.CodeContent ?? params.content ?? '';
452
+ const content = params.CodeContent ?? params.content ?? params.fileContent ?? params.file_content ?? params.text;
453
+ if (typeof content !== 'string')
454
+ return null;
374
455
  if (typeof filePath === 'string' && filePath.trim()) {
375
456
  return {
376
457
  id: `agy_native_${Date.now()}_${index}`,
@@ -382,10 +463,12 @@ export function mapNativeToolToCausyne(name, rawParams, index) {
382
463
  };
383
464
  }
384
465
  }
385
- if (lowerName === 'replacefilecontent' || lowerName === 'fsedit') {
466
+ if (['replacefilecontent', 'editfile', 'replaceinfile', 'fsedit'].includes(lowerName)) {
386
467
  const filePath = params.TargetFile ?? params.path ?? params.file_path ?? '';
387
- const oldText = params.TargetContent ?? params.oldText ?? '';
388
- const newText = params.ReplacementContent ?? params.newText ?? '';
468
+ const oldText = params.TargetContent ?? params.oldText ?? params.old_text ?? params.old_string;
469
+ const newText = params.ReplacementContent ?? params.newText ?? params.new_text ?? params.new_string;
470
+ if (typeof oldText !== 'string' || typeof newText !== 'string')
471
+ return null;
389
472
  if (typeof filePath === 'string' && filePath.trim()) {
390
473
  return {
391
474
  id: `agy_native_${Date.now()}_${index}`,
@@ -499,6 +582,34 @@ export function mapNativeToolToCausyne(name, rawParams, index) {
499
582
  }
500
583
  }
501
584
  }
585
+ if (['screenshot', 'takescreenshot', 'capturescreenshot', 'take_screenshot'].includes(lowerName)) {
586
+ return {
587
+ id: `agy_native_${Date.now()}_${index}`,
588
+ type: 'function',
589
+ function: {
590
+ name: 'screenshot',
591
+ arguments: JSON.stringify({
592
+ path: params.path ?? params.target ?? params.TargetFile ?? '',
593
+ crop: params.crop
594
+ })
595
+ }
596
+ };
597
+ }
598
+ if (['browseract', 'browser_act', 'browser'].includes(lowerName)) {
599
+ return {
600
+ id: `agy_native_${Date.now()}_${index}`,
601
+ type: 'function',
602
+ function: {
603
+ name: 'browser_act',
604
+ arguments: JSON.stringify({
605
+ action: params.action ?? 'snapshot',
606
+ filePath: params.filePath ?? params.path ?? params.TargetFile,
607
+ url: params.url ?? params.Url,
608
+ selector: params.selector
609
+ })
610
+ }
611
+ };
612
+ }
502
613
  return null;
503
614
  }
504
615
  export class AntigravityProvider extends LLMProvider {
@@ -506,6 +617,7 @@ export class AntigravityProvider extends LLMProvider {
506
617
  printTimeout;
507
618
  currentConversationId = null;
508
619
  lastTaskId = null;
620
+ contextSnapshot = null;
509
621
  lastCumulativeUsage = null;
510
622
  constructor(config = {}) {
511
623
  super(config);
@@ -568,36 +680,20 @@ export class AntigravityProvider extends LLMProvider {
568
680
  // Host capabilities must be learned from real tool results in this session.
569
681
  lines.push('[System Instructions]\n' +
570
682
  'You are the execution engine for Causyne Agent, operating inside the user\'s workspace. ' +
571
- 'Do not claim a tool action succeeded without evidence. Use Causyne tools for file changes, terminal commands, and browser actions. ' +
572
- 'When a command, browser action, or other external action is required, output an explicit tool call in this exact format:\n' +
683
+ PEER_COLLABORATION_POLICY + '\n' +
684
+ 'Do not claim a tool action succeeded without evidence. When requesting a Causyne host tool, output an explicit tool call in this exact format:\n' +
573
685
  '<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>\n' +
574
686
  'Causyne Agent will execute the tool in its secure environment and return the results back to you.\n\n' +
575
687
  '[Action Directive]\n' +
576
- '1. When the user requests to create, build, code, fix, write, optimize, or implement anything, invoke the relevant file or command tools immediately.\n' +
577
- '2. When the user requests to OPEN, LAUNCH, RUN, SERVE, or PLAY an application, project, or game:\n' +
578
- ' - If a background server is required (e.g. server.py, python -m http.server, npm run dev), start it using sysRunBg or a background command.\n' +
579
- ' - If the default port (e.g. 8080 or 3000) is already occupied or in use by another process, immediately use the next available port (e.g. 8081, 8082, 3001) rather than getting stuck in process-checking loops.\n' +
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' +
581
- ' - Confirm the application is accessible only after a readiness check succeeds.\n' +
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' +
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' +
588
- '[Environment State & Idempotency Directive]\n' +
589
- 'Reuse relevant verified tool results from this session, and check uncertain prerequisites before relying on them.\n\n' +
688
+ 'Follow the host task scope and verification requirements. Invoke only tools needed for that task. ' +
689
+ 'Put file contents in executable tool-call arguments rather than repeating whole drafts in reasoning or summaries. ' +
690
+ 'Do not add unrequested subsystems or keep editing completed work to appear productive. ' +
691
+ 'NEVER reply with conversational pleasantries when the user has supplied a task. ' +
692
+ 'Do not present pending tool calls as completed work. Use actual results, and report blockers precisely.\n\n' +
590
693
  '[Language & Communication Directive]\n' +
591
694
  '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.');
592
695
  if (tools && tools.length > 0) {
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 || {};
598
- const paramKeys = Object.keys(params.properties || {}).join(', ');
599
- return `- ${name}(${paramKeys}): ${desc}`;
600
- }).join('\n');
696
+ const toolSummaries = formatToolContracts(tools);
601
697
  lines.push(`[Available Tools]\nYou may invoke tools when needed by outputting:\n<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>\n\n${toolSummaries}`);
602
698
  }
603
699
  const seenToolOutputs = new Set();
@@ -632,13 +728,16 @@ export class AntigravityProvider extends LLMProvider {
632
728
  return '';
633
729
  }).filter(Boolean).join('\n');
634
730
  }
635
- // Compact duplicate identical tool outputs to prevent token ballooning
731
+ // Compact duplicate identical tool outputs and elide older observations (SWE-agent / OpenCode pattern)
636
732
  if (msg.role === 'tool' && text.trim()) {
637
733
  const normalized = text.trim();
638
734
  if (seenToolOutputs.has(normalized)) {
639
735
  continue;
640
736
  }
641
737
  seenToolOutputs.add(normalized);
738
+ if (!isRecent && text.length > 300) {
739
+ text = `[Tool result: ${msg.name || 'tool'} completed successfully. Full log archived in toolOutputStore.]`;
740
+ }
642
741
  }
643
742
  if (msg.tool_calls && Array.isArray(msg.tool_calls)) {
644
743
  for (const tc of msg.tool_calls) {
@@ -768,6 +867,9 @@ export class AntigravityProvider extends LLMProvider {
768
867
  }
769
868
  const useConversation = Boolean(this.currentConversationId);
770
869
  const resumedConversationId = this.currentConversationId;
870
+ const previousContext = this.contextSnapshot?.conversationId === resumedConversationId ? this.contextSnapshot : null;
871
+ const systemMessages = messages.filter(message => message.role === 'system');
872
+ const systemHashes = systemMessages.map(message => contractFingerprint(message));
771
873
  const latestUserMessage = [...messages].reverse().find(message => message.role === 'user');
772
874
  const latestPrompt = typeof latestUserMessage?.content === 'string' ? latestUserMessage.content : '';
773
875
  const launchOnly = options.taskIntent === 'launch' || isLaunchOnlyPrompt(latestPrompt);
@@ -782,7 +884,13 @@ export class AntigravityProvider extends LLMProvider {
782
884
  }
783
885
  }
784
886
  const deltaMessages = lastAssistantIndex >= 0 ? messages.slice(lastAssistantIndex + 1) : messages;
785
- promptText = this.formatDelta(deltaMessages.length > 0 ? deltaMessages : [messages[messages.length - 1]]);
887
+ const changedSystems = systemMessages.filter((_, index) => systemHashes[index] !== previousContext?.systemHashes[index]);
888
+ const contractUpdates = toolContractUpdate(options.tools || [], previousContext?.tools || []);
889
+ promptText = [
890
+ ...changedSystems.map(message => `[Current system context — replaces the prior version of this section]\n${message.content}`),
891
+ contractUpdates,
892
+ this.formatDelta((deltaMessages.length > 0 ? deltaMessages : [messages[messages.length - 1]]).filter(message => message?.role !== 'system'))
893
+ ].filter(Boolean).join('\n\n');
786
894
  }
787
895
  else {
788
896
  promptText = this.formatConversation(messages, options.tools);
@@ -793,7 +901,7 @@ export class AntigravityProvider extends LLMProvider {
793
901
  promptText = '[Current request: open existing project only]\n' +
794
902
  'Inspect the selected project, start an existing server in the background if needed, verify readiness, and open it. ' +
795
903
  'Do not create, edit, delete, install, or regenerate files. Do not claim the app opened unless a tool confirmed it. ' +
796
- 'Use Causyne tool calls for commands and desktop opening.\n\n' + promptText;
904
+ 'Use the available native or Causyne tools for commands and desktop opening.\n\n' + promptText;
797
905
  }
798
906
  if (desktopTask) {
799
907
  promptText = '[Current desktop task: finish and verify the requested change]\n' +
@@ -804,29 +912,15 @@ export class AntigravityProvider extends LLMProvider {
804
912
  }
805
913
  const modelSlug = resolveAgyModelId(this.model);
806
914
  const effort = resolveAgyEffort(this.model);
807
- // Standard high-performance non-blocking CLI invocation:
808
- // 1. stream-json output for real-time responsiveness and non-buffering progress.
809
- // 2. --disable-slash-commands prevents sluggish filesystem and customization scans.
810
- // 3. agy only treats stdin as a prompt in stream-json input mode. Plain text
811
- // stdin without --print starts an interactive session and loses the task.
812
- // Keep the prompt off the process command line by sending one user event.
813
- // 4. --mode accept-edits lets agy create and edit workspace files in
814
- // headless mode, where the default request-review policy cannot prompt
815
- // and would auto-deny every write. --dangerously-skip-permissions must
816
- // stay off: it would also grant shell commands and other host tools,
817
- // bypassing Causyne. Native terminal/browser tools remain denied; those
818
- // must go through Causyne XML tool calls.
819
- // 5. Launch-only turns use a shorter limit because they should not spend
820
- // several minutes generating code or holding a foreground server open.
821
- // 6. --conversation links multi-turn steps to agy's local session memory to prevent re-reading files.
915
+ // Run the user's normal peer in the selected project. Do not substitute a
916
+ // managed inference profile or hide project MCPs, skills, and instructions.
917
+ const workspaceRoot = path.resolve(options.workspaceRoot || process.cwd());
918
+ promptText = `[Causyne host workspace]\n${JSON.stringify({ workspaceRoot })}\n\n` + promptText;
822
919
  const args = [
823
- '--mode',
824
- launchOnly ? 'plan' : 'accept-edits',
825
920
  '--input-format',
826
921
  'stream-json',
827
922
  '--output-format',
828
923
  'stream-json',
829
- '--disable-slash-commands',
830
924
  '--print-timeout',
831
925
  launchOnly ? '90s' : this.printTimeout,
832
926
  '--model',
@@ -840,7 +934,7 @@ export class AntigravityProvider extends LLMProvider {
840
934
  return new Promise((resolve, reject) => {
841
935
  let isSettled = false;
842
936
  const child = spawn(this.command, args, {
843
- cwd: typeof options.workspaceRoot === 'string' ? options.workspaceRoot : process.cwd(),
937
+ cwd: workspaceRoot,
844
938
  env: process.env,
845
939
  stdio: ['pipe', 'pipe', 'pipe'],
846
940
  windowsHide: true
@@ -850,6 +944,9 @@ export class AntigravityProvider extends LLMProvider {
850
944
  let streamedResponse = '';
851
945
  let finalResultObj = null;
852
946
  let sawToolAfterLastText = false;
947
+ let sawProviderProgress = false;
948
+ let reasoningChars = 0;
949
+ let usageBaselineCommitted = false;
853
950
  const nativeActions = [];
854
951
  const attemptedNativeTools = [];
855
952
  let childClosed = false;
@@ -865,9 +962,13 @@ export class AntigravityProvider extends LLMProvider {
865
962
  // A process that already exited needs no further action.
866
963
  }
867
964
  };
868
- const maxNativeActions = desktopTask ? 12 : Infinity;
965
+ const configuredActions = Number(options.maxNativeActions);
966
+ const maxNativeActions = Number.isSafeInteger(configuredActions) && configuredActions >= 0
967
+ ? configuredActions : desktopTask ? 12 : 35;
869
968
  let nativeActionStarts = 0;
870
969
  const seenNativeActionSteps = new Set();
970
+ const mediaInspectionCounts = new Map();
971
+ const pendingMediaMutations = new Set();
871
972
  // Antigravity's result usage is cumulative across the conversation, but
872
973
  // DONE step updates carry usage for that step. Keep a turn-local subtotal
873
974
  // so a single headless run cannot consume an entire task budget unseen.
@@ -880,10 +981,14 @@ export class AntigravityProvider extends LLMProvider {
880
981
  // Keep a finite per-call ceiling even when the optional task budget is
881
982
  // disabled. Users can set a lower task budget through the existing UI.
882
983
  const remainingTaskBudget = Number(options.maxTokensThisCall);
984
+ const rawTokenLimit = Number(options.tokenLimit);
985
+ const hasExplicitLimit = (Number.isFinite(remainingTaskBudget) && remainingTaskBudget > 0)
986
+ || (Number.isFinite(rawTokenLimit) && rawTokenLimit > 0);
987
+ const countReportedTotal = options.tokenBudgetBasis !== 'noncached';
883
988
  const tokenLimit = Number.isFinite(remainingTaskBudget) && remainingTaskBudget > 0
884
989
  ? remainingTaskBudget
885
- : (typeof options.tokenLimit === 'number' && options.tokenLimit > 0
886
- ? options.tokenLimit
990
+ : (Number.isFinite(rawTokenLimit) && rawTokenLimit > 0
991
+ ? rawTokenLimit
887
992
  : 100_000);
888
993
  const wallTimer = desktopTask ? setTimeout(() => {
889
994
  const error = new Error('Antigravity exceeded the 180-second desktop task limit. Outcome is unverified.');
@@ -908,8 +1013,7 @@ export class AntigravityProvider extends LLMProvider {
908
1013
  // the provider from silently replaying a paid turn.
909
1014
  if (partialUsage.promptTokens + partialUsage.completionTokens > 0) {
910
1015
  Object.assign(err, { partialUsage: { ...partialUsage } });
911
- if ((err.code === 'AGY_EXPLORATION_LOOP'
912
- || err.code === 'AGY_TOKEN_BUDGET') && this.currentConversationId) {
1016
+ if (!usageBaselineCommitted && this.currentConversationId) {
913
1017
  const prior = resumedConversationId === this.lastCumulativeUsage?.conversationId
914
1018
  ? this.lastCumulativeUsage : null;
915
1019
  this.lastCumulativeUsage = {
@@ -928,6 +1032,10 @@ export class AntigravityProvider extends LLMProvider {
928
1032
  if (isSettled)
929
1033
  return;
930
1034
  isSettled = true;
1035
+ if (this.currentConversationId)
1036
+ this.contextSnapshot = {
1037
+ conversationId: this.currentConversationId, tools: structuredClone(options.tools || []), systemHashes
1038
+ };
931
1039
  cleanup();
932
1040
  resolve(res);
933
1041
  };
@@ -973,6 +1081,10 @@ export class AntigravityProvider extends LLMProvider {
973
1081
  }
974
1082
  else if (event.event === 'step_update') {
975
1083
  const stepUpdate = event.step_update;
1084
+ if (typeof stepUpdate?.text_delta === 'string' && stepUpdate.text_delta.trim())
1085
+ sawProviderProgress = true;
1086
+ if (stepUpdate?.step_type === 'tool' && stepUpdate?.state === 'ACTIVE')
1087
+ sawProviderProgress = true;
976
1088
  const usage = stepUpdate?.usage;
977
1089
  const usageStepIndex = Number(stepUpdate?.step_index ?? event?.step_index);
978
1090
  if (stepUpdate?.state === 'DONE' && usage && Number.isFinite(usageStepIndex)
@@ -982,14 +1094,21 @@ export class AntigravityProvider extends LLMProvider {
982
1094
  if (Number.isFinite(input) && input >= 0 && Number.isFinite(output) && output >= 0) {
983
1095
  completedUsageSteps.add(usageStepIndex);
984
1096
  partialUsage.promptTokens += input;
1097
+ partialUsage.uncachedPromptTokens = (partialUsage.uncachedPromptTokens || 0) + input;
985
1098
  partialUsage.completionTokens += output;
986
1099
  partialUsage.cachedPromptTokens = (partialUsage.cachedPromptTokens || 0)
987
1100
  + (Number(usage.cache_read_tokens) || 0);
988
1101
  partialUsage.thinkingTokens = (partialUsage.thinkingTokens || 0)
989
1102
  + (Number(usage.thinking_tokens) || 0);
1103
+ // User task budgets can track all provider-reported tokens.
1104
+ // The automatic safety floor counts uncached input plus
1105
+ // output, so a cache hit does not masquerade as fresh spend.
1106
+ const reportedTotal = partialUsage.promptTokens + partialUsage.completionTokens;
1107
+ const uncachedTotal = noncachedTokens(partialUsage);
1108
+ const spentAgainstLimit = countReportedTotal ? reportedTotal : uncachedTotal;
990
1109
  if (Number.isFinite(tokenLimit) && tokenLimit > 0
991
- && partialUsage.promptTokens + partialUsage.completionTokens >= tokenLimit) {
992
- 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 } });
1110
+ && spentAgainstLimit >= tokenLimit) {
1111
+ 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 } });
993
1112
  safeReject(error);
994
1113
  terminateChild();
995
1114
  return;
@@ -1005,8 +1124,8 @@ export class AntigravityProvider extends LLMProvider {
1005
1124
  && (!Number.isFinite(stepIndex) || !seenNativeActionSteps.has(stepIndex));
1006
1125
  if (newNativeAction && Number.isFinite(stepIndex))
1007
1126
  seenNativeActionSteps.add(stepIndex);
1008
- if (desktopTask && newNativeAction && ++nativeActionStarts > maxNativeActions) {
1009
- const error = new Error(`Antigravity exceeded ${maxNativeActions} native actions for this desktop task. Outcome is unverified.`);
1127
+ if (newNativeAction && ++nativeActionStarts > maxNativeActions) {
1128
+ const error = new Error(`Antigravity reached the ${maxNativeActions} native-action turn checkpoint. Work remains unfinished; continue from the saved session.`);
1010
1129
  error.code = 'AGY_NATIVE_ACTION_BUDGET';
1011
1130
  safeReject(error);
1012
1131
  terminateChild();
@@ -1021,8 +1140,35 @@ export class AntigravityProvider extends LLMProvider {
1021
1140
  (stepUpdate && typeof stepUpdate === 'object' && stepUpdate.parameters) ||
1022
1141
  (toolInfo && typeof toolInfo === 'object' && toolInfo.input) ||
1023
1142
  {};
1143
+ if (options.taskArchetype === 'media_3d_generation' && name) {
1144
+ if (newNativeAction) {
1145
+ const target = isReadOnlyNativeInspection(name, rawParams)
1146
+ ? nativeInspectionTarget(name, rawParams) : null;
1147
+ if (target) {
1148
+ const inspectionCount = (mediaInspectionCounts.get(target) || 0) + 1;
1149
+ mediaInspectionCounts.set(target, inspectionCount);
1150
+ if (inspectionCount >= 8) {
1151
+ const error = Object.assign(new Error('Antigravity repeated read-only inspection of the same Blender scene without an edit. The task remains unfinished.'), { code: 'AGY_EXPLORATION_LOOP', inspectionCount, inspectionTarget: target });
1152
+ safeReject(error);
1153
+ terminateChild();
1154
+ return;
1155
+ }
1156
+ }
1157
+ else if (isNativeMutation(name, rawParams) && Number.isFinite(stepIndex)) {
1158
+ pendingMediaMutations.add(stepIndex);
1159
+ }
1160
+ }
1161
+ if (Number.isFinite(stepIndex) && pendingMediaMutations.has(stepIndex)
1162
+ && (state === 'DONE' || state === 'ERROR')) {
1163
+ pendingMediaMutations.delete(stepIndex);
1164
+ if (state === 'DONE' && !toolInfo?.error)
1165
+ mediaInspectionCounts.clear();
1166
+ }
1167
+ }
1024
1168
  if (name) {
1025
- const existingAttempt = attemptedNativeTools.find(a => a.name === name && a.status === 'running');
1169
+ const actionId = Number.isFinite(stepIndex) ? `agy:${stepIndex}` : undefined;
1170
+ const existingAttempt = attemptedNativeTools.find(a => actionId
1171
+ ? a.id === actionId : a.name === name && a.status === 'running');
1026
1172
  if (existingAttempt) {
1027
1173
  existingAttempt.status = status;
1028
1174
  if (rawParams && Object.keys(rawParams).length > 0) {
@@ -1033,6 +1179,7 @@ export class AntigravityProvider extends LLMProvider {
1033
1179
  }
1034
1180
  else {
1035
1181
  attemptedNativeTools.push({
1182
+ ...(actionId ? { id: actionId } : {}),
1036
1183
  name,
1037
1184
  parameters: { ...rawParams },
1038
1185
  status,
@@ -1045,6 +1192,7 @@ export class AntigravityProvider extends LLMProvider {
1045
1192
  sawToolAfterLastText = true;
1046
1193
  const detail = describeNativeAction(toolInfo) || describeNativeAction({ parameters: rawParams });
1047
1194
  const action = {
1195
+ ...(Number.isFinite(stepIndex) ? { id: `agy:${stepIndex}` } : {}),
1048
1196
  name,
1049
1197
  status,
1050
1198
  ...(detail ? { detail } : {})
@@ -1068,6 +1216,7 @@ export class AntigravityProvider extends LLMProvider {
1068
1216
  }
1069
1217
  if (delta && typeof delta === 'string') {
1070
1218
  if (stepType === 'thought' || stepType === 'agent_thought') {
1219
+ reasoningChars += delta.length;
1071
1220
  if (typeof options.onReasoningChunk === 'function') {
1072
1221
  options.onReasoningChunk(delta);
1073
1222
  }
@@ -1170,7 +1319,9 @@ export class AntigravityProvider extends LLMProvider {
1170
1319
  if (deniedNames.has(normalizeAction(action.name)))
1171
1320
  action.status = 'failed';
1172
1321
  if (typeof options.onNativeAction === 'function') {
1173
- const attempt = [...attemptedNativeTools].reverse().find(candidate => normalizeAction(candidate.name) === normalizeAction(action.name));
1322
+ const attempt = [...attemptedNativeTools].reverse().find(candidate => action.id
1323
+ ? candidate.id === action.id
1324
+ : normalizeAction(candidate.name) === normalizeAction(action.name) && candidate.detail === action.detail);
1174
1325
  options.onNativeAction({ ...action, parameters: attempt?.parameters || {} });
1175
1326
  }
1176
1327
  }
@@ -1211,17 +1362,6 @@ export class AntigravityProvider extends LLMProvider {
1211
1362
  .map((a) => `${a.name}${a.detail ? ` (${a.detail})` : ''}`)
1212
1363
  .join(', ')}`;
1213
1364
  }
1214
- if (!content && toolCalls.length === 0) {
1215
- const detail = stderrBuffer.trim();
1216
- safeReject(new Error(detail
1217
- ? `Antigravity returned no response: ${detail}`
1218
- : 'Antigravity returned no response.'));
1219
- return;
1220
- }
1221
- const timedOutMidTurn = /print timeout after .* with turn in progress|returning partial output/i.test(stderrBuffer);
1222
- const finalResponseText = typeof finalResultObj?.response === 'string' ? finalResultObj.response.trim() : '';
1223
- const endedAfterToolWithoutFinalResponse = sawToolAfterLastText && !finalResponseText && deniedActions.length === 0 && toolCalls.length === 0;
1224
- const missingResultEvent = finalResultObj === null && deniedActions.length === 0 && toolCalls.length === 0;
1225
1365
  const usageIsReported = finalResultObj?.usage?.input_tokens != null
1226
1366
  && finalResultObj?.usage?.output_tokens != null
1227
1367
  && Number.isFinite(Number(finalResultObj.usage.input_tokens))
@@ -1239,10 +1379,41 @@ export class AntigravityProvider extends LLMProvider {
1239
1379
  const completionTokens = prior && usageIsReported ? delta(cumulative.output, prior.output) : cumulative.output;
1240
1380
  const thinkingTokens = prior && usageIsReported ? delta(cumulative.thinking, prior.thinking) : cumulative.thinking;
1241
1381
  const cachedPromptTokens = prior && usageIsReported ? delta(cumulative.cacheRead, prior.cacheRead) : cumulative.cacheRead;
1382
+ // AGY reports cache reads separately (they can exceed input_tokens).
1383
+ // Keep the same accounting on terminal and streamed/error paths; do
1384
+ // not conditionally subtract cache reads from an unrelated counter.
1385
+ const uncachedPromptTokens = promptTokens;
1386
+ if (usageIsReported)
1387
+ Object.assign(partialUsage, { promptTokens, uncachedPromptTokens, completionTokens, thinkingTokens, cachedPromptTokens });
1388
+ if (usageIsReported && this.currentConversationId) {
1389
+ this.lastCumulativeUsage = { conversationId: this.currentConversationId, ...cumulative };
1390
+ usageBaselineCommitted = true;
1391
+ }
1392
+ if (!content && toolCalls.length === 0) {
1393
+ const detail = stderrBuffer.trim();
1394
+ if (!sawProviderProgress && /print timeout after .* with turn in progress|returning partial output/i.test(detail)) {
1395
+ safeReject(Object.assign(new Error('The selected peer produced no model output or tool activity before its timeout. The task remains unfinished; retry after the peer is responsive.'), { code: 'PROVIDER_NO_PROGRESS' }));
1396
+ return;
1397
+ }
1398
+ const reasoningOnly = (reasoningChars > 0 || Boolean(extractedReasoning)) && attemptedNativeTools.length === 0;
1399
+ safeReject(Object.assign(new Error(detail
1400
+ ? `Antigravity returned no response: ${detail}`
1401
+ : 'Antigravity returned no response.'), {
1402
+ code: reasoningOnly ? 'PROVIDER_REASONING_ONLY' : 'PROVIDER_EMPTY_RESPONSE',
1403
+ continuationSafe: reasoningOnly && Boolean(this.currentConversationId),
1404
+ reasoningChars, responseChars: rawContent.length
1405
+ }));
1406
+ return;
1407
+ }
1408
+ const timedOutMidTurn = /print timeout after .* with turn in progress|returning partial output/i.test(stderrBuffer);
1409
+ const finalResponseText = typeof finalResultObj?.response === 'string' ? finalResultObj.response.trim() : '';
1410
+ const endedAfterToolWithoutFinalResponse = sawToolAfterLastText && !finalResponseText && deniedActions.length === 0 && toolCalls.length === 0;
1411
+ const missingResultEvent = finalResultObj === null && deniedActions.length === 0 && toolCalls.length === 0;
1242
1412
  const response = {
1243
1413
  content,
1244
1414
  usage: {
1245
1415
  promptTokens,
1416
+ uncachedPromptTokens,
1246
1417
  completionTokens,
1247
1418
  thinkingTokens,
1248
1419
  cachedPromptTokens,
@@ -1266,6 +1437,15 @@ export class AntigravityProvider extends LLMProvider {
1266
1437
  if (usageIsReported && this.currentConversationId) {
1267
1438
  this.lastCumulativeUsage = { conversationId: this.currentConversationId, ...cumulative };
1268
1439
  }
1440
+ // A peer may report usage only in its final result.
1441
+ const reportedTotal = promptTokens + completionTokens;
1442
+ const uncachedTotal = noncachedTokens(response.usage);
1443
+ const spentAgainstLimit = countReportedTotal ? reportedTotal : uncachedTotal;
1444
+ if (spentAgainstLimit >= tokenLimit) {
1445
+ Object.assign(partialUsage, response.usage);
1446
+ safeReject(Object.assign(new Error(`Antigravity reached its ${tokenLimit}-token checkpoint. Work remains unverified.`), { code: 'AGY_TOKEN_BUDGET', tokenLimit, partialUsage: { ...partialUsage } }));
1447
+ return;
1448
+ }
1269
1449
  safeResolve(response);
1270
1450
  });
1271
1451
  });
@@ -1282,6 +1462,8 @@ export class AntigravityProvider extends LLMProvider {
1282
1462
  if (options.signal?.aborted || err?.name === 'AbortError') {
1283
1463
  throw err;
1284
1464
  }
1465
+ if (err?.code === 'PROVIDER_NO_PROGRESS')
1466
+ throw err;
1285
1467
  if (err?.partialUsage?.promptTokens + err?.partialUsage?.completionTokens > 0) {
1286
1468
  throw err;
1287
1469
  }