@causyne/agent 1.20.10 → 1.20.12

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 (88) 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 +262 -91
  34. package/src/providers/antigravity.ts +270 -99
  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/stallGuard.js +3 -12
  54. package/src/stallGuard.ts +3 -12
  55. package/src/subagent/sidechainHarness.js +66 -0
  56. package/src/subagent/sidechainHarness.ts +91 -0
  57. package/src/taskContinuation.js +12 -0
  58. package/src/taskContinuation.ts +13 -0
  59. package/src/tokenTracker.js +406 -539
  60. package/src/tokenTracker.ts +569 -0
  61. package/src/toolPacks.d.ts +2 -0
  62. package/src/toolPacks.js +1 -1
  63. package/src/tools/argumentValidation.js +56 -0
  64. package/src/tools/argumentValidation.ts +50 -0
  65. package/src/tools/browserAutomator.js +2 -2
  66. package/src/tools/browserAutomator.ts +3 -2
  67. package/src/tools/deferredMcpSearch.js +188 -201
  68. package/src/tools/deferredMcpSearch.ts +250 -0
  69. package/src/tools/generateMediaViaApi.js +305 -331
  70. package/src/tools/generateMediaViaApi.ts +330 -0
  71. package/src/tools/historyPruner.js +5 -0
  72. package/src/tools/historyPruner.ts +5 -0
  73. package/src/tools/payloadSanitizer.js +92 -0
  74. package/src/tools/payloadSanitizer.ts +113 -0
  75. package/src/tools/registry.d.ts +1 -0
  76. package/src/tools/sysRun.js +47 -18
  77. package/src/tools/sysRun.ts +52 -20
  78. package/src/tools/toolOutputStore.js +180 -0
  79. package/src/tools/toolOutputStore.ts +209 -0
  80. package/src/tools/toolSelfRepair.js +26 -1
  81. package/src/tools/toolSelfRepair.ts +25 -1
  82. package/src/tui/chatRenderer.d.ts +1 -0
  83. package/src/tui/chatRenderer.js +4 -2
  84. package/src/tui/codeStreamRenderer.js +36 -8
  85. package/src/tui/codeStreamRenderer.ts +38 -8
  86. package/src/tui/stageSurface.js +1 -0
  87. package/src/tui/text.js +4 -1
  88. 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, type ProviderConfig, type ChatOptions, type ChatResponse, type ChatResponseAction, type ChatResponseToolCall, type ChatResponseUsage } from './base.js';
7
9
 
8
10
  /**
@@ -276,17 +278,98 @@ function describeNativeAction(toolInfo: any): string | undefined {
276
278
  return undefined;
277
279
  }
278
280
 
281
+ function cleanCommandString(raw: unknown): string {
282
+ if (typeof raw !== 'string') return '';
283
+ let cmd = raw.trim();
284
+ if ((cmd.startsWith('"') && cmd.endsWith('"')) || (cmd.startsWith("'") && cmd.endsWith("'"))) {
285
+ cmd = cmd.slice(1, -1).trim();
286
+ }
287
+ return cmd.replace(/\\"/g, '"').replace(/\\'/g, "'").replace(/\\\\/g, '\\').trim();
288
+ }
289
+
279
290
  export function isReadOnlyNativeInspection(name: string, parameters: Record<string, unknown>): boolean {
280
291
  const action = name.toLowerCase().replace(/[_\s-]/g, '');
281
- if (/^(readfile|listdirectory|listfiles|search|searchweb|grep|findfiles)$/.test(action)) return true;
292
+ if (/^(readfile|viewfile|listdirectory|listfiles|search|searchweb|grep|findfiles)$/.test(action)) return true;
282
293
  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);
294
+ const command = cleanCommandString(parameters.CommandLine ?? parameters.command ?? parameters.cmd ?? '');
295
+ if (!command) return false;
296
+
297
+ // Single or compound read-only shell commands (e.g. ps aux | grep -i blender)
298
+ 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)) {
299
+ if (/[;&|]/.test(command)) {
300
+ const parts = command.split(/[;&|]/).map(p => p.trim()).filter(Boolean);
301
+ 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));
302
+ }
303
+ return true;
304
+ }
305
+
306
+ // Python image / PIL pixel inspection probes without mutation
307
+ if (/^python[23]?\s+-c\b/i.test(command) && /Image\.open/i.test(command) && !/\b(?:save|write|remove|unlink)\b/i.test(command)) {
308
+ return true;
309
+ }
310
+
311
+ // Blender inspection expressions (printing objects, collections, render engine)
312
+ if (/\bblender\b.*--python-expr\b/is.test(command)) {
313
+ const exprMatch = /--python-expr\s+["']([\s\S]*?)["'](?:\s|$)/i.exec(command)
314
+ || /--python-expr\s+([\s\S]+)$/i.exec(command);
315
+ const expr = (exprMatch ? exprMatch[1] : null) || command;
316
+ return !/\b(?:save_as_mainfile|save_mainfile|write_still\s*=\s*True|write_text|write_bytes|os\.remove|os\.unlink)\b/i.test(expr);
317
+ }
318
+
319
+ return false;
320
+ }
321
+
322
+ function nativeInspectionTarget(name: string, parameters: Record<string, unknown>): string | null {
323
+ const normName = name.toLowerCase().replace(/[_\s-]/g, '');
324
+ if (!/^(runcommand|command|sysrun|terminal|bash|shell)$/.test(normName)) {
325
+ if (/^(readfile|viewfile)$/.test(normName)) {
326
+ const p = String(parameters.AbsolutePath ?? parameters.filePath ?? parameters.path ?? parameters.file ?? '');
327
+ if (p) return p.trim().toLowerCase();
328
+ }
329
+ return null;
330
+ }
331
+ const command = cleanCommandString(parameters.CommandLine ?? parameters.command ?? parameters.cmd ?? '');
332
+ if (!command) return null;
333
+
334
+ // 1. Blender scene probes (handles escaped quotes and spaces in filepath)
335
+ if (/\bblender\b/i.test(command)) {
336
+ if (/\b(?:save_as_mainfile|save_mainfile)\b/.test(command)) return null;
337
+ if (/--python-expr\b/i.test(command) || /-b\b|--background\b/i.test(command)) {
338
+ const blendMatch = /--background\s+["']?([^"'\n]+?\.blend\d*)["']?(?:\s|$)/i.exec(command)
339
+ || /["']?([^"'\n]+?\.blend\d*)["']?/i.exec(command);
340
+ if (blendMatch && blendMatch[1]) {
341
+ return blendMatch[1].trim().toLowerCase();
342
+ }
343
+ }
344
+ }
345
+
346
+ // 2. Python image inspections: from PIL import Image; Image.open(...)
347
+ if (/Image\.open\s*\(\s*["']([^"'\n]+)["']\s*\)/i.test(command)) {
348
+ const imgMatch = /Image\.open\s*\(\s*["']([^"'\n]+)["']\s*\)/i.exec(command);
349
+ if (imgMatch && imgMatch[1]) {
350
+ return imgMatch[1].trim().toLowerCase();
351
+ }
352
+ }
353
+
354
+ // 3. Repetitive CLI file reads on workspace files
355
+ const fileProbeMatch = /^(?:head|tail|sed|cat|grep)\b.*?["']([^"'\n]+\.(?:py|blend\d*|json|ts|js|png|jpg))["']/i.exec(command)
356
+ || /^(?:head|tail|sed|cat|grep)\b.*?(\S+\.(?:py|blend\d*|json|ts|js|png|jpg))/i.exec(command);
357
+ const rawFile = fileProbeMatch ? (fileProbeMatch[1] || fileProbeMatch[2]) : null;
358
+ if (rawFile) {
359
+ return rawFile.trim().toLowerCase();
360
+ }
361
+
362
+ return null;
363
+ }
364
+
365
+ function isNativeMutation(name: string, parameters: Record<string, unknown>): boolean {
366
+ const action = name.toLowerCase().replace(/[_\s-]/g, '');
367
+ if (/^(writefile|editfile|deletefile|applypatch|createfile|replaceinfile)$/.test(action)) return true;
368
+ if (!/^(runcommand|command|sysrun|terminal|bash|shell)$/.test(action)) return false;
369
+ const command = cleanCommandString(parameters.CommandLine ?? parameters.command ?? parameters.cmd ?? '');
370
+ if (!command) return false;
371
+ return /\b(?:save_as_mainfile|save_mainfile|write_text|write_bytes|tee)\b/.test(command)
372
+ || /(?:^|[;&|]\s*)(?:cp|mv|rm|install|patch)\s/.test(command);
290
373
  }
291
374
 
292
375
  export function mapNativeToolToCausyne(
@@ -375,9 +458,10 @@ export function mapNativeToolToCausyne(
375
458
  }
376
459
  }
377
460
 
378
- if (lowerName === 'writetofile' || lowerName === 'fswrite') {
461
+ if (['writetofile', 'writefile', 'createfile', 'fswrite'].includes(lowerName)) {
379
462
  const filePath = params.TargetFile ?? params.path ?? params.file_path ?? '';
380
- const content = params.CodeContent ?? params.content ?? '';
463
+ const content = params.CodeContent ?? params.content ?? params.fileContent ?? params.file_content ?? params.text;
464
+ if (typeof content !== 'string') return null;
381
465
  if (typeof filePath === 'string' && filePath.trim()) {
382
466
  return {
383
467
  id: `agy_native_${Date.now()}_${index}`,
@@ -390,10 +474,11 @@ export function mapNativeToolToCausyne(
390
474
  }
391
475
  }
392
476
 
393
- if (lowerName === 'replacefilecontent' || lowerName === 'fsedit') {
477
+ if (['replacefilecontent', 'editfile', 'replaceinfile', 'fsedit'].includes(lowerName)) {
394
478
  const filePath = params.TargetFile ?? params.path ?? params.file_path ?? '';
395
- const oldText = params.TargetContent ?? params.oldText ?? '';
396
- const newText = params.ReplacementContent ?? params.newText ?? '';
479
+ const oldText = params.TargetContent ?? params.oldText ?? params.old_text ?? params.old_string;
480
+ const newText = params.ReplacementContent ?? params.newText ?? params.new_text ?? params.new_string;
481
+ if (typeof oldText !== 'string' || typeof newText !== 'string') return null;
397
482
  if (typeof filePath === 'string' && filePath.trim()) {
398
483
  return {
399
484
  id: `agy_native_${Date.now()}_${index}`,
@@ -513,6 +598,36 @@ export function mapNativeToolToCausyne(
513
598
  }
514
599
  }
515
600
 
601
+ if (['screenshot', 'takescreenshot', 'capturescreenshot', 'take_screenshot'].includes(lowerName)) {
602
+ return {
603
+ id: `agy_native_${Date.now()}_${index}`,
604
+ type: 'function',
605
+ function: {
606
+ name: 'screenshot',
607
+ arguments: JSON.stringify({
608
+ path: params.path ?? params.target ?? params.TargetFile ?? '',
609
+ crop: params.crop
610
+ })
611
+ }
612
+ };
613
+ }
614
+
615
+ if (['browseract', 'browser_act', 'browser'].includes(lowerName)) {
616
+ return {
617
+ id: `agy_native_${Date.now()}_${index}`,
618
+ type: 'function',
619
+ function: {
620
+ name: 'browser_act',
621
+ arguments: JSON.stringify({
622
+ action: params.action ?? 'snapshot',
623
+ filePath: params.filePath ?? params.path ?? params.TargetFile,
624
+ url: params.url ?? params.Url,
625
+ selector: params.selector
626
+ })
627
+ }
628
+ };
629
+ }
630
+
516
631
  return null;
517
632
  }
518
633
 
@@ -521,6 +636,7 @@ export class AntigravityProvider extends LLMProvider {
521
636
  printTimeout: string;
522
637
  currentConversationId: string | null = null;
523
638
  lastTaskId: string | null = null;
639
+ private contextSnapshot: { conversationId: string; tools: unknown[]; systemHashes: string[] } | null = null;
524
640
  private lastCumulativeUsage: { conversationId: string; input: number; output: number; thinking: number; cacheRead: number } | null = null;
525
641
 
526
642
  constructor(config: ProviderConfig = {}) {
@@ -588,38 +704,22 @@ export class AntigravityProvider extends LLMProvider {
588
704
  lines.push(
589
705
  '[System Instructions]\n' +
590
706
  'You are the execution engine for Causyne Agent, operating inside the user\'s workspace. ' +
591
- 'Do not claim a tool action succeeded without evidence. Use Causyne tools for file changes, terminal commands, and browser actions. ' +
592
- 'When a command, browser action, or other external action is required, output an explicit tool call in this exact format:\n' +
707
+ PEER_COLLABORATION_POLICY + '\n' +
708
+ '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' +
593
709
  '<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>\n' +
594
710
  'Causyne Agent will execute the tool in its secure environment and return the results back to you.\n\n' +
595
711
  '[Action Directive]\n' +
596
- '1. When the user requests to create, build, code, fix, write, optimize, or implement anything, invoke the relevant file or command tools immediately.\n' +
597
- '2. When the user requests to OPEN, LAUNCH, RUN, SERVE, or PLAY an application, project, or game:\n' +
598
- ' - 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' +
599
- ' - 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' +
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' +
601
- ' - Confirm the application is accessible only after a readiness check succeeds.\n' +
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' +
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' +
608
- '[Environment State & Idempotency Directive]\n' +
609
- 'Reuse relevant verified tool results from this session, and check uncertain prerequisites before relying on them.\n\n' +
712
+ 'Follow the host task scope and verification requirements. Invoke only tools needed for that task. ' +
713
+ 'Put file contents in executable tool-call arguments rather than repeating whole drafts in reasoning or summaries. ' +
714
+ 'Do not add unrequested subsystems or keep editing completed work to appear productive. ' +
715
+ 'NEVER reply with conversational pleasantries when the user has supplied a task. ' +
716
+ 'Do not present pending tool calls as completed work. Use actual results, and report blockers precisely.\n\n' +
610
717
  '[Language & Communication Directive]\n' +
611
718
  '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.'
612
719
  );
613
720
 
614
721
  if (tools && tools.length > 0) {
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 || {};
620
- const paramKeys = Object.keys(params.properties || {}).join(', ');
621
- return `- ${name}(${paramKeys}): ${desc}`;
622
- }).join('\n');
722
+ const toolSummaries = formatToolContracts(tools);
623
723
  lines.push(
624
724
  `[Available Tools]\nYou may invoke tools when needed by outputting:\n<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>\n\n${toolSummaries}`
625
725
  );
@@ -656,13 +756,16 @@ export class AntigravityProvider extends LLMProvider {
656
756
  }).filter(Boolean).join('\n');
657
757
  }
658
758
 
659
- // Compact duplicate identical tool outputs to prevent token ballooning
759
+ // Compact duplicate identical tool outputs and elide older observations (SWE-agent / OpenCode pattern)
660
760
  if (msg.role === 'tool' && text.trim()) {
661
761
  const normalized = text.trim();
662
762
  if (seenToolOutputs.has(normalized)) {
663
763
  continue;
664
764
  }
665
765
  seenToolOutputs.add(normalized);
766
+ if (!isRecent && text.length > 300) {
767
+ text = `[Tool result: ${msg.name || 'tool'} completed successfully. Full log archived in toolOutputStore.]`;
768
+ }
666
769
  }
667
770
 
668
771
  if (msg.tool_calls && Array.isArray(msg.tool_calls)) {
@@ -796,6 +899,9 @@ export class AntigravityProvider extends LLMProvider {
796
899
 
797
900
  const useConversation = Boolean(this.currentConversationId);
798
901
  const resumedConversationId = this.currentConversationId;
902
+ const previousContext = this.contextSnapshot?.conversationId === resumedConversationId ? this.contextSnapshot : null;
903
+ const systemMessages = messages.filter(message => message.role === 'system');
904
+ const systemHashes = systemMessages.map(message => contractFingerprint(message));
799
905
  const latestUserMessage = [...messages].reverse().find(message => message.role === 'user');
800
906
  const latestPrompt = typeof latestUserMessage?.content === 'string' ? latestUserMessage.content : '';
801
907
  const launchOnly = (options as any).taskIntent === 'launch' || isLaunchOnlyPrompt(latestPrompt);
@@ -811,7 +917,13 @@ export class AntigravityProvider extends LLMProvider {
811
917
  }
812
918
  }
813
919
  const deltaMessages = lastAssistantIndex >= 0 ? messages.slice(lastAssistantIndex + 1) : messages;
814
- promptText = this.formatDelta(deltaMessages.length > 0 ? deltaMessages : [messages[messages.length - 1]]);
920
+ const changedSystems = systemMessages.filter((_, index) => systemHashes[index] !== previousContext?.systemHashes[index]);
921
+ const contractUpdates = toolContractUpdate(options.tools || [], previousContext?.tools || []);
922
+ promptText = [
923
+ ...changedSystems.map(message => `[Current system context — replaces the prior version of this section]\n${message.content}`),
924
+ contractUpdates,
925
+ this.formatDelta((deltaMessages.length > 0 ? deltaMessages : [messages[messages.length - 1]]).filter(message => message?.role !== 'system'))
926
+ ].filter(Boolean).join('\n\n');
815
927
  } else {
816
928
  promptText = this.formatConversation(messages, options.tools);
817
929
  }
@@ -822,7 +934,7 @@ export class AntigravityProvider extends LLMProvider {
822
934
  promptText = '[Current request: open existing project only]\n' +
823
935
  'Inspect the selected project, start an existing server in the background if needed, verify readiness, and open it. ' +
824
936
  'Do not create, edit, delete, install, or regenerate files. Do not claim the app opened unless a tool confirmed it. ' +
825
- 'Use Causyne tool calls for commands and desktop opening.\n\n' + promptText;
937
+ 'Use the available native or Causyne tools for commands and desktop opening.\n\n' + promptText;
826
938
  }
827
939
  if (desktopTask) {
828
940
  promptText = '[Current desktop task: finish and verify the requested change]\n' +
@@ -835,29 +947,15 @@ export class AntigravityProvider extends LLMProvider {
835
947
  const modelSlug = resolveAgyModelId(this.model);
836
948
  const effort = resolveAgyEffort(this.model);
837
949
 
838
- // Standard high-performance non-blocking CLI invocation:
839
- // 1. stream-json output for real-time responsiveness and non-buffering progress.
840
- // 2. --disable-slash-commands prevents sluggish filesystem and customization scans.
841
- // 3. agy only treats stdin as a prompt in stream-json input mode. Plain text
842
- // stdin without --print starts an interactive session and loses the task.
843
- // Keep the prompt off the process command line by sending one user event.
844
- // 4. --mode accept-edits lets agy create and edit workspace files in
845
- // headless mode, where the default request-review policy cannot prompt
846
- // and would auto-deny every write. --dangerously-skip-permissions must
847
- // stay off: it would also grant shell commands and other host tools,
848
- // bypassing Causyne. Native terminal/browser tools remain denied; those
849
- // must go through Causyne XML tool calls.
850
- // 5. Launch-only turns use a shorter limit because they should not spend
851
- // several minutes generating code or holding a foreground server open.
852
- // 6. --conversation links multi-turn steps to agy's local session memory to prevent re-reading files.
950
+ // Run the user's normal peer in the selected project. Do not substitute a
951
+ // managed inference profile or hide project MCPs, skills, and instructions.
952
+ const workspaceRoot = path.resolve(options.workspaceRoot || process.cwd());
953
+ promptText = `[Causyne host workspace]\n${JSON.stringify({ workspaceRoot })}\n\n` + promptText;
853
954
  const args = [
854
- '--mode',
855
- launchOnly ? 'plan' : 'accept-edits',
856
955
  '--input-format',
857
956
  'stream-json',
858
957
  '--output-format',
859
958
  'stream-json',
860
- '--disable-slash-commands',
861
959
  '--print-timeout',
862
960
  launchOnly ? '90s' : this.printTimeout,
863
961
  '--model',
@@ -873,7 +971,7 @@ export class AntigravityProvider extends LLMProvider {
873
971
  return new Promise<ChatResponse>((resolve, reject) => {
874
972
  let isSettled = false;
875
973
  const child = spawn(this.command, args, {
876
- cwd: typeof (options as any).workspaceRoot === 'string' ? (options as any).workspaceRoot : process.cwd(),
974
+ cwd: workspaceRoot,
877
975
  env: process.env,
878
976
  stdio: ['pipe', 'pipe', 'pipe'],
879
977
  windowsHide: true
@@ -884,8 +982,12 @@ export class AntigravityProvider extends LLMProvider {
884
982
  let streamedResponse = '';
885
983
  let finalResultObj: any = null;
886
984
  let sawToolAfterLastText = false;
985
+ let sawProviderProgress = false;
986
+ let reasoningChars = 0;
987
+ let usageBaselineCommitted = false;
887
988
  const nativeActions: ChatResponseAction[] = [];
888
989
  const attemptedNativeTools: {
990
+ id?: string | undefined;
889
991
  name: string;
890
992
  parameters: Record<string, any>;
891
993
  status: 'running' | 'completed' | 'failed';
@@ -903,10 +1005,13 @@ export class AntigravityProvider extends LLMProvider {
903
1005
  // A process that already exited needs no further action.
904
1006
  }
905
1007
  };
906
- const maxNativeActions = desktopTask ? 12 : Infinity;
1008
+ const configuredActions = Number(options.maxNativeActions);
1009
+ const maxNativeActions = Number.isSafeInteger(configuredActions) && configuredActions >= 0
1010
+ ? configuredActions : desktopTask ? 12 : 35;
907
1011
  let nativeActionStarts = 0;
908
- let consecutiveInspections = 0;
909
1012
  const seenNativeActionSteps = new Set<number>();
1013
+ const mediaInspectionCounts = new Map<string, number>();
1014
+ const pendingMediaMutations = new Set<number>();
910
1015
  // Antigravity's result usage is cumulative across the conversation, but
911
1016
  // DONE step updates carry usage for that step. Keep a turn-local subtotal
912
1017
  // so a single headless run cannot consume an entire task budget unseen.
@@ -919,10 +1024,14 @@ export class AntigravityProvider extends LLMProvider {
919
1024
  // Keep a finite per-call ceiling even when the optional task budget is
920
1025
  // disabled. Users can set a lower task budget through the existing UI.
921
1026
  const remainingTaskBudget = Number(options.maxTokensThisCall);
1027
+ const rawTokenLimit = Number((options as any).tokenLimit);
1028
+ const hasExplicitLimit = (Number.isFinite(remainingTaskBudget) && remainingTaskBudget > 0)
1029
+ || (Number.isFinite(rawTokenLimit) && rawTokenLimit > 0);
1030
+ const countReportedTotal = options.tokenBudgetBasis !== 'noncached';
922
1031
  const tokenLimit = Number.isFinite(remainingTaskBudget) && remainingTaskBudget > 0
923
1032
  ? remainingTaskBudget
924
- : (typeof (options as any).tokenLimit === 'number' && (options as any).tokenLimit > 0
925
- ? (options as any).tokenLimit
1033
+ : (Number.isFinite(rawTokenLimit) && rawTokenLimit > 0
1034
+ ? rawTokenLimit
926
1035
  : 100_000);
927
1036
  const wallTimer = desktopTask ? setTimeout(() => {
928
1037
  const error = new Error('Antigravity exceeded the 180-second desktop task limit. Outcome is unverified.') as Error & { code: string };
@@ -947,8 +1056,7 @@ export class AntigravityProvider extends LLMProvider {
947
1056
  // the provider from silently replaying a paid turn.
948
1057
  if (partialUsage.promptTokens + partialUsage.completionTokens > 0) {
949
1058
  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) {
1059
+ if (!usageBaselineCommitted && this.currentConversationId) {
952
1060
  const prior = resumedConversationId === this.lastCumulativeUsage?.conversationId
953
1061
  ? this.lastCumulativeUsage : null;
954
1062
  this.lastCumulativeUsage = {
@@ -967,6 +1075,9 @@ export class AntigravityProvider extends LLMProvider {
967
1075
  const safeResolve = (res: ChatResponse) => {
968
1076
  if (isSettled) return;
969
1077
  isSettled = true;
1078
+ if (this.currentConversationId) this.contextSnapshot = {
1079
+ conversationId: this.currentConversationId, tools: structuredClone(options.tools || []), systemHashes
1080
+ };
970
1081
  cleanup();
971
1082
  resolve(res);
972
1083
  };
@@ -1015,6 +1126,8 @@ export class AntigravityProvider extends LLMProvider {
1015
1126
  }
1016
1127
  } else if (event.event === 'step_update') {
1017
1128
  const stepUpdate = event.step_update;
1129
+ if (typeof stepUpdate?.text_delta === 'string' && stepUpdate.text_delta.trim()) sawProviderProgress = true;
1130
+ if (stepUpdate?.step_type === 'tool' && stepUpdate?.state === 'ACTIVE') sawProviderProgress = true;
1018
1131
  const usage = stepUpdate?.usage;
1019
1132
  const usageStepIndex = Number(stepUpdate?.step_index ?? event?.step_index);
1020
1133
  if (stepUpdate?.state === 'DONE' && usage && Number.isFinite(usageStepIndex)
@@ -1024,15 +1137,22 @@ export class AntigravityProvider extends LLMProvider {
1024
1137
  if (Number.isFinite(input) && input >= 0 && Number.isFinite(output) && output >= 0) {
1025
1138
  completedUsageSteps.add(usageStepIndex);
1026
1139
  partialUsage.promptTokens += input;
1140
+ partialUsage.uncachedPromptTokens = (partialUsage.uncachedPromptTokens || 0) + input;
1027
1141
  partialUsage.completionTokens += output;
1028
1142
  partialUsage.cachedPromptTokens = (partialUsage.cachedPromptTokens || 0)
1029
1143
  + (Number(usage.cache_read_tokens) || 0);
1030
1144
  partialUsage.thinkingTokens = (partialUsage.thinkingTokens || 0)
1031
1145
  + (Number(usage.thinking_tokens) || 0);
1146
+ // User task budgets can track all provider-reported tokens.
1147
+ // The automatic safety floor counts uncached input plus
1148
+ // output, so a cache hit does not masquerade as fresh spend.
1149
+ const reportedTotal = partialUsage.promptTokens + partialUsage.completionTokens;
1150
+ const uncachedTotal = noncachedTokens(partialUsage);
1151
+ const spentAgainstLimit = countReportedTotal ? reportedTotal : uncachedTotal;
1032
1152
  if (Number.isFinite(tokenLimit) && tokenLimit > 0
1033
- && partialUsage.promptTokens + partialUsage.completionTokens >= tokenLimit) {
1153
+ && spentAgainstLimit >= tokenLimit) {
1034
1154
  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.`),
1155
+ new Error(`Antigravity reported ${spentAgainstLimit} tokens against a ${tokenLimit}-token per-call ceiling. This turn stopped and its outcome is unverified.`),
1036
1156
  { code: 'AGY_TOKEN_BUDGET', tokenLimit, partialUsage: { ...partialUsage } }
1037
1157
  );
1038
1158
  safeReject(error);
@@ -1049,8 +1169,8 @@ export class AntigravityProvider extends LLMProvider {
1049
1169
  const newNativeAction = (state === 'ACTIVE' || (state === 'DONE' && Number.isFinite(stepIndex)))
1050
1170
  && (!Number.isFinite(stepIndex) || !seenNativeActionSteps.has(stepIndex));
1051
1171
  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 };
1172
+ if (newNativeAction && ++nativeActionStarts > maxNativeActions) {
1173
+ const error = new Error(`Antigravity reached the ${maxNativeActions} native-action turn checkpoint. Work remains unfinished; continue from the saved session.`) as Error & { code: string };
1054
1174
  error.code = 'AGY_NATIVE_ACTION_BUDGET';
1055
1175
  safeReject(error);
1056
1176
  terminateChild();
@@ -1066,22 +1186,37 @@ export class AntigravityProvider extends LLMProvider {
1066
1186
  (toolInfo && typeof toolInfo === 'object' && toolInfo.input) ||
1067
1187
  {};
1068
1188
 
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;
1189
+ if ((options as any).taskArchetype === 'media_3d_generation' && name) {
1190
+ if (newNativeAction) {
1191
+ const target = isReadOnlyNativeInspection(name, rawParams)
1192
+ ? nativeInspectionTarget(name, rawParams) : null;
1193
+ if (target) {
1194
+ const inspectionCount = (mediaInspectionCounts.get(target) || 0) + 1;
1195
+ mediaInspectionCounts.set(target, inspectionCount);
1196
+ if (inspectionCount >= 8) {
1197
+ const error = Object.assign(
1198
+ new Error('Antigravity repeated read-only inspection of the same Blender scene without an edit. The task remains unfinished.'),
1199
+ { code: 'AGY_EXPLORATION_LOOP', inspectionCount, inspectionTarget: target }
1200
+ );
1201
+ safeReject(error);
1202
+ terminateChild();
1203
+ return;
1204
+ }
1205
+ } else if (isNativeMutation(name, rawParams) && Number.isFinite(stepIndex)) {
1206
+ pendingMediaMutations.add(stepIndex);
1207
+ }
1208
+ }
1209
+ if (Number.isFinite(stepIndex) && pendingMediaMutations.has(stepIndex)
1210
+ && (state === 'DONE' || state === 'ERROR')) {
1211
+ pendingMediaMutations.delete(stepIndex);
1212
+ if (state === 'DONE' && !toolInfo?.error) mediaInspectionCounts.clear();
1080
1213
  }
1081
1214
  }
1082
1215
 
1083
1216
  if (name) {
1084
- const existingAttempt = attemptedNativeTools.find(a => a.name === name && a.status === 'running');
1217
+ const actionId = Number.isFinite(stepIndex) ? `agy:${stepIndex}` : undefined;
1218
+ const existingAttempt = attemptedNativeTools.find(a => actionId
1219
+ ? a.id === actionId : a.name === name && a.status === 'running');
1085
1220
  if (existingAttempt) {
1086
1221
  existingAttempt.status = status;
1087
1222
  if (rawParams && Object.keys(rawParams).length > 0) {
@@ -1090,6 +1225,7 @@ export class AntigravityProvider extends LLMProvider {
1090
1225
  if (toolInfo?.error?.message) existingAttempt.error = toolInfo.error.message;
1091
1226
  } else {
1092
1227
  attemptedNativeTools.push({
1228
+ ...(actionId ? { id: actionId } : {}),
1093
1229
  name,
1094
1230
  parameters: { ...rawParams },
1095
1231
  status,
@@ -1103,6 +1239,7 @@ export class AntigravityProvider extends LLMProvider {
1103
1239
  sawToolAfterLastText = true;
1104
1240
  const detail = describeNativeAction(toolInfo) || describeNativeAction({ parameters: rawParams });
1105
1241
  const action: ChatResponseAction = {
1242
+ ...(Number.isFinite(stepIndex) ? { id: `agy:${stepIndex}` } : {}),
1106
1243
  name,
1107
1244
  status,
1108
1245
  ...(detail ? { detail } : {})
@@ -1124,6 +1261,7 @@ export class AntigravityProvider extends LLMProvider {
1124
1261
  }
1125
1262
  if (delta && typeof delta === 'string') {
1126
1263
  if (stepType === 'thought' || stepType === 'agent_thought') {
1264
+ reasoningChars += delta.length;
1127
1265
  if (typeof options.onReasoningChunk === 'function') {
1128
1266
  options.onReasoningChunk(delta);
1129
1267
  }
@@ -1225,8 +1363,9 @@ export class AntigravityProvider extends LLMProvider {
1225
1363
  for (const action of nativeActions) {
1226
1364
  if (deniedNames.has(normalizeAction(action.name))) action.status = 'failed';
1227
1365
  if (typeof options.onNativeAction === 'function') {
1228
- const attempt = [...attemptedNativeTools].reverse().find(candidate =>
1229
- normalizeAction(candidate.name) === normalizeAction(action.name));
1366
+ const attempt = [...attemptedNativeTools].reverse().find(candidate => action.id
1367
+ ? candidate.id === action.id
1368
+ : normalizeAction(candidate.name) === normalizeAction(action.name) && candidate.detail === action.detail);
1230
1369
  options.onNativeAction({ ...action, parameters: attempt?.parameters || {} });
1231
1370
  }
1232
1371
  }
@@ -1272,21 +1411,6 @@ export class AntigravityProvider extends LLMProvider {
1272
1411
  .join(', ')}`;
1273
1412
  }
1274
1413
 
1275
- if (!content && toolCalls.length === 0) {
1276
- const detail = stderrBuffer.trim();
1277
- safeReject(new Error(detail
1278
- ? `Antigravity returned no response: ${detail}`
1279
- : 'Antigravity returned no response.'));
1280
- return;
1281
- }
1282
-
1283
- const timedOutMidTurn = /print timeout after .* with turn in progress|returning partial output/i.test(stderrBuffer);
1284
- const finalResponseText = typeof finalResultObj?.response === 'string' ? finalResultObj.response.trim() : '';
1285
- const endedAfterToolWithoutFinalResponse =
1286
- sawToolAfterLastText && !finalResponseText && deniedActions.length === 0 && toolCalls.length === 0;
1287
- const missingResultEvent =
1288
- finalResultObj === null && deniedActions.length === 0 && toolCalls.length === 0;
1289
-
1290
1414
  const usageIsReported = finalResultObj?.usage?.input_tokens != null
1291
1415
  && finalResultObj?.usage?.output_tokens != null
1292
1416
  && Number.isFinite(Number(finalResultObj.usage.input_tokens))
@@ -1305,10 +1429,46 @@ export class AntigravityProvider extends LLMProvider {
1305
1429
  const thinkingTokens = prior && usageIsReported ? delta(cumulative.thinking, prior.thinking) : cumulative.thinking;
1306
1430
  const cachedPromptTokens = prior && usageIsReported ? delta(cumulative.cacheRead, prior.cacheRead) : cumulative.cacheRead;
1307
1431
 
1432
+ // AGY reports cache reads separately (they can exceed input_tokens).
1433
+ // Keep the same accounting on terminal and streamed/error paths; do
1434
+ // not conditionally subtract cache reads from an unrelated counter.
1435
+ const uncachedPromptTokens = promptTokens;
1436
+ if (usageIsReported) Object.assign(partialUsage, { promptTokens, uncachedPromptTokens, completionTokens, thinkingTokens, cachedPromptTokens });
1437
+ if (usageIsReported && this.currentConversationId) {
1438
+ this.lastCumulativeUsage = { conversationId: this.currentConversationId, ...cumulative };
1439
+ usageBaselineCommitted = true;
1440
+ }
1441
+ if (!content && toolCalls.length === 0) {
1442
+ const detail = stderrBuffer.trim();
1443
+ if (!sawProviderProgress && /print timeout after .* with turn in progress|returning partial output/i.test(detail)) {
1444
+ 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.'),
1445
+ { code: 'PROVIDER_NO_PROGRESS' }));
1446
+ return;
1447
+ }
1448
+ const reasoningOnly = (reasoningChars > 0 || Boolean(extractedReasoning)) && attemptedNativeTools.length === 0;
1449
+ safeReject(Object.assign(new Error(detail
1450
+ ? `Antigravity returned no response: ${detail}`
1451
+ : 'Antigravity returned no response.'), {
1452
+ code: reasoningOnly ? 'PROVIDER_REASONING_ONLY' : 'PROVIDER_EMPTY_RESPONSE',
1453
+ continuationSafe: reasoningOnly && Boolean(this.currentConversationId),
1454
+ reasoningChars, responseChars: rawContent.length
1455
+ }));
1456
+ return;
1457
+ }
1458
+
1459
+ const timedOutMidTurn = /print timeout after .* with turn in progress|returning partial output/i.test(stderrBuffer);
1460
+ const finalResponseText = typeof finalResultObj?.response === 'string' ? finalResultObj.response.trim() : '';
1461
+ const endedAfterToolWithoutFinalResponse =
1462
+ sawToolAfterLastText && !finalResponseText && deniedActions.length === 0 && toolCalls.length === 0;
1463
+ const missingResultEvent =
1464
+ finalResultObj === null && deniedActions.length === 0 && toolCalls.length === 0;
1465
+
1466
+
1308
1467
  const response: ChatResponse = {
1309
1468
  content,
1310
1469
  usage: {
1311
1470
  promptTokens,
1471
+ uncachedPromptTokens,
1312
1472
  completionTokens,
1313
1473
  thinkingTokens,
1314
1474
  cachedPromptTokens,
@@ -1337,6 +1497,16 @@ export class AntigravityProvider extends LLMProvider {
1337
1497
  if (usageIsReported && this.currentConversationId) {
1338
1498
  this.lastCumulativeUsage = { conversationId: this.currentConversationId, ...cumulative };
1339
1499
  }
1500
+ // A peer may report usage only in its final result.
1501
+ const reportedTotal = promptTokens + completionTokens;
1502
+ const uncachedTotal = noncachedTokens(response.usage);
1503
+ const spentAgainstLimit = countReportedTotal ? reportedTotal : uncachedTotal;
1504
+ if (spentAgainstLimit >= tokenLimit) {
1505
+ Object.assign(partialUsage, response.usage);
1506
+ safeReject(Object.assign(new Error(`Antigravity reached its ${tokenLimit}-token checkpoint. Work remains unverified.`),
1507
+ { code: 'AGY_TOKEN_BUDGET', tokenLimit, partialUsage: { ...partialUsage } }));
1508
+ return;
1509
+ }
1340
1510
  safeResolve(response);
1341
1511
  });
1342
1512
  });
@@ -1353,6 +1523,7 @@ export class AntigravityProvider extends LLMProvider {
1353
1523
  if (options.signal?.aborted || err?.name === 'AbortError') {
1354
1524
  throw err;
1355
1525
  }
1526
+ if (err?.code === 'PROVIDER_NO_PROGRESS') throw err;
1356
1527
  if (err?.partialUsage?.promptTokens + err?.partialUsage?.completionTokens > 0) {
1357
1528
  throw err;
1358
1529
  }