@causyne/agent 1.18.0 → 1.20.0

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 (76) hide show
  1. package/package.json +1 -1
  2. package/src/agentLoop.js +2348 -2531
  3. package/src/agentLoop.ts +2865 -0
  4. package/src/checkpoints.d.ts +4 -0
  5. package/src/cliMode.js +30 -17
  6. package/src/commands.js +307 -57
  7. package/src/config.js +22 -0
  8. package/src/contextManager.d.ts +10 -0
  9. package/src/continuum/adapters/antigravity.js +193 -0
  10. package/src/continuum/adapters/antigravity.ts +204 -0
  11. package/src/continuum/adapters/base.js +48 -0
  12. package/src/continuum/adapters/base.ts +57 -0
  13. package/src/continuum/adapters/causyne.js +66 -0
  14. package/src/continuum/adapters/causyne.ts +72 -0
  15. package/src/continuum/adapters/claudeCode.js +171 -0
  16. package/src/continuum/adapters/claudeCode.ts +179 -0
  17. package/src/continuum/adapters/codex.js +181 -0
  18. package/src/continuum/adapters/codex.ts +193 -0
  19. package/src/continuum/adapters/opencode.js +134 -0
  20. package/src/continuum/adapters/opencode.ts +153 -0
  21. package/src/continuum/compactor.js +54 -0
  22. package/src/continuum/compactor.ts +83 -0
  23. package/src/continuum/index.js +8 -0
  24. package/src/continuum/index.ts +9 -0
  25. package/src/continuum/ingest.js +63 -0
  26. package/src/continuum/ingest.ts +89 -0
  27. package/src/continuum/sanitizer.js +55 -0
  28. package/src/continuum/sanitizer.ts +59 -0
  29. package/src/continuum/scanner.js +86 -0
  30. package/src/continuum/scanner.ts +106 -0
  31. package/src/continuum/types.js +3 -0
  32. package/src/continuum/types.ts +51 -0
  33. package/src/continuum/ui/continuumPicker.js +111 -0
  34. package/src/continuum/ui/continuumPicker.ts +145 -0
  35. package/src/cortex/autoCondenser.d.ts +2 -0
  36. package/src/cortex/vectorDb.d.ts +1 -0
  37. package/src/designPalettes.d.ts +2 -0
  38. package/src/devMode.d.ts +1 -0
  39. package/src/dynamicCatalogue.js +5 -3
  40. package/src/dynamicCatalogue.ts +7 -4
  41. package/src/embodimentSession.d.ts +2 -0
  42. package/src/entrypoint.js +12 -0
  43. package/src/memory.d.ts +1 -0
  44. package/src/memoryManager.d.ts +1 -0
  45. package/src/memoryManager.js +10 -6
  46. package/src/modelIds.d.ts +2 -0
  47. package/src/outputStore.d.ts +4 -0
  48. package/src/providers/acp.js +320 -299
  49. package/src/providers/acp.ts +360 -0
  50. package/src/providers/antigravity.js +387 -278
  51. package/src/providers/antigravity.ts +450 -0
  52. package/src/providers/base.d.ts +68 -0
  53. package/src/providers/factory.d.ts +1 -0
  54. package/src/provisioning/capabilityProvisioner.d.ts +2 -0
  55. package/src/sandbox.d.ts +1 -0
  56. package/src/sessionJournal.js +14 -1
  57. package/src/sessionJournal.ts +21 -1
  58. package/src/skillsManager.d.ts +3 -0
  59. package/src/slopDetector.d.ts +3 -0
  60. package/src/taskBuffer.d.ts +1 -0
  61. package/src/tokenTracker.d.ts +1 -0
  62. package/src/toolPacks.d.ts +8 -0
  63. package/src/tools/registry.d.ts +4 -0
  64. package/src/tui/chatRenderer.js +148 -8
  65. package/src/tui/clipboardSync.js +36 -0
  66. package/src/tui/clipboardSync.ts +36 -0
  67. package/src/tui/dialogs.js +15 -2
  68. package/src/tui/home.js +2 -1
  69. package/src/tui/modelPicker.js +254 -0
  70. package/src/tui/modelPicker.ts +318 -0
  71. package/src/tui/prompt.js +90 -8
  72. package/src/tui/selectList.js +20 -0
  73. package/src/tui/sessionPicker.js +185 -0
  74. package/src/tui/sessionPicker.ts +259 -0
  75. package/src/tui/stageSurface.js +9 -0
  76. package/src/tui/statusLine.js +5 -5
@@ -2,7 +2,6 @@ import { spawn } from 'node:child_process';
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { LLMProvider } from './base.js';
5
-
6
5
  /**
7
6
  * Display label → the id `agy --model` actually accepts, exactly as reported
8
7
  * by `agy models`. The CLI exposes slugs; the picker shows the readable label.
@@ -10,304 +9,414 @@ import { LLMProvider } from './base.js';
10
9
  * resolve here rather than failing at the provider.
11
10
  */
12
11
  export const ANTIGRAVITY_MODEL_IDS = {
13
- 'Gemini 3.8 Flash (Low)': 'gemini-3.8-flash-low',
14
- 'Gemini 3.8 Flash (Medium)': 'gemini-3.8-flash-medium',
15
- 'Gemini 3.8 Flash (High)': 'gemini-3.8-flash-high',
16
- 'Gemini 4 Argon (Low)': 'gemini-4-argon-low',
17
- 'Gemini 4 Argon (Medium)': 'gemini-4-argon-medium',
18
- 'Gemini 4 Argon (High)': 'gemini-4-argon-high',
19
- 'Claude Sonnet 5.5 (Low)': 'claude-sonnet-5-5-low',
20
- 'Claude Sonnet 5.5 (Medium)': 'claude-sonnet-5-5-medium',
21
- 'Claude Sonnet 5.5 (High)': 'claude-sonnet-5-5-high',
22
- 'Claude Opus 5.5 (Low)': 'claude-opus-5-5-low',
23
- 'Claude Opus 5.5 (Medium)': 'claude-opus-5-5-medium',
24
- 'Claude Opus 5.5 (High)': 'claude-opus-5-5-high',
25
- 'GPT-OSS 120B (Medium)': 'gpt-oss-120b-medium'
12
+ 'Gemini 3.8 Flash (Low)': 'gemini-3.8-flash-low',
13
+ 'Gemini 3.8 Flash (Medium)': 'gemini-3.8-flash-medium',
14
+ 'Gemini 3.8 Flash (High)': 'gemini-3.8-flash-high',
15
+ 'Gemini 4 Argon (Low)': 'gemini-4-argon-low',
16
+ 'Gemini 4 Argon (Medium)': 'gemini-4-argon-medium',
17
+ 'Gemini 4 Argon (High)': 'gemini-4-argon-high',
18
+ 'Claude Sonnet 5.5 (Low)': 'claude-sonnet-5-5-low',
19
+ 'Claude Sonnet 5.5 (Medium)': 'claude-sonnet-5-5-medium',
20
+ 'Claude Sonnet 5.5 (High)': 'claude-sonnet-5-5-high',
21
+ 'Claude Opus 5.5 (Low)': 'claude-opus-5-5-low',
22
+ 'Claude Opus 5.5 (Medium)': 'claude-opus-5-5-medium',
23
+ 'Claude Opus 5.5 (High)': 'claude-opus-5-5-high',
24
+ 'GPT-OSS 120B (Medium)': 'gpt-oss-120b-medium'
26
25
  };
27
-
28
- export const ANTIGRAVITY_LABEL_BY_ID = Object.fromEntries(
29
- Object.entries(ANTIGRAVITY_MODEL_IDS).map(([label, id]) => [id, label])
30
- );
31
-
26
+ export const ANTIGRAVITY_LABEL_BY_ID = Object.fromEntries(Object.entries(ANTIGRAVITY_MODEL_IDS).map(([label, id]) => [id, label]));
32
27
  export const ANTIGRAVITY_MODELS = Object.keys(ANTIGRAVITY_MODEL_IDS);
33
-
34
28
  export function resolveAgyModelId(model) {
35
- if (typeof model !== 'string') return '';
36
- const trimmed = model.trim();
37
- return ANTIGRAVITY_MODEL_IDS[trimmed] || trimmed;
29
+ if (typeof model !== 'string')
30
+ return '';
31
+ const trimmed = model.trim();
32
+ return ANTIGRAVITY_MODEL_IDS[trimmed] || trimmed;
33
+ }
34
+ export function resolveAgyEffort(model) {
35
+ if (typeof model !== 'string')
36
+ return 'low';
37
+ const m = model.toLowerCase();
38
+ if (m.includes('(low)') || m.includes('-low'))
39
+ return 'low';
40
+ if (m.includes('(medium)') || m.includes('-medium'))
41
+ return 'medium';
42
+ if (m.includes('(high)') || m.includes('-high'))
43
+ return 'high';
44
+ if (m.includes('(xhigh)') || m.includes('-xhigh'))
45
+ return 'xhigh';
46
+ if (m.includes('(max)') || m.includes('-max'))
47
+ return 'max';
48
+ return 'low';
38
49
  }
39
-
40
50
  export function isAntigravityProvider(provider) {
41
- if (!provider) return false;
42
- const p = String(provider).toLowerCase();
43
- return p === 'antigravity' || p === 'agy' || p.startsWith('antigravity/') || p.startsWith('agy/');
51
+ if (!provider)
52
+ return false;
53
+ const p = String(provider).toLowerCase();
54
+ return p === 'antigravity' || p === 'agy' || p.startsWith('antigravity/') || p.startsWith('agy/');
44
55
  }
45
-
46
56
  export function resolveAgyBinary() {
47
- const envPath = process.env.PATH || '';
48
- const searchDirs = [
49
- ...envPath.split(path.delimiter),
50
- path.join(process.env.HOME || '', '.local/bin'),
51
- path.join(process.env.HOME || '', '.antigravity/antigravity/bin'),
52
- path.join(process.env.HOME || '', '.gemini/antigravity-ide/bin'),
53
- '/Applications/Antigravity.app/Contents/Resources/app/bin',
54
- '/Applications/Antigravity IDE.app/Contents/Resources/app/bin'
55
- ];
56
-
57
- const binNames = ['agy', 'antigravity'];
58
- for (const dir of searchDirs) {
59
- if (!dir) continue;
60
- for (const name of binNames) {
61
- const full = path.join(dir, name);
62
- try {
63
- if (fs.existsSync(full) && fs.statSync(full).isFile()) {
64
- return full;
57
+ const envPath = process.env.PATH || '';
58
+ const searchDirs = [
59
+ ...envPath.split(path.delimiter),
60
+ path.join(process.env.HOME || '', '.local/bin'),
61
+ path.join(process.env.HOME || '', '.antigravity/antigravity/bin'),
62
+ path.join(process.env.HOME || '', '.gemini/antigravity-ide/bin'),
63
+ '/Applications/Antigravity.app/Contents/Resources/app/bin',
64
+ '/Applications/Antigravity IDE.app/Contents/Resources/app/bin'
65
+ ];
66
+ const binNames = ['agy', 'antigravity'];
67
+ for (const dir of searchDirs) {
68
+ if (!dir)
69
+ continue;
70
+ for (const name of binNames) {
71
+ const full = path.join(dir, name);
72
+ try {
73
+ if (fs.existsSync(full) && fs.statSync(full).isFile()) {
74
+ return full;
75
+ }
76
+ }
77
+ catch {
78
+ // ignore inaccessible path
79
+ }
65
80
  }
66
- } catch {
67
- // ignore inaccessible path
68
- }
69
81
  }
70
- }
71
- return 'agy';
82
+ return 'agy';
72
83
  }
73
-
74
84
  export class AntigravityProvider extends LLMProvider {
75
- constructor(config = {}) {
76
- super(config);
77
- this.model = config.model || 'Gemini 3.8 Flash (Low)';
78
- this.command = config.command || resolveAgyBinary();
79
- // The agy print path takes text only — no image flag is documented, and the
80
- // formatter below drops image blocks. Claiming vision here would let the
81
- // agent believe a screenshot was seen when it never left the machine.
82
- this.visionModels = [];
83
- this.audioModels = [];
84
- }
85
-
86
- formatConversation(messages, tools = []) {
87
- const lines = [];
88
- lines.push(`[System Instructions]\nYou are acting as an AI reasoning engine for Causyne Agent. Do NOT invoke your own internal host CLI tools or execute commands directly. When an action or tool is required, output an explicit tool call in this exact format:\n<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>\nCausyne Agent will execute the tool in its secure environment and return the results back to you.`);
89
-
90
- if (tools && tools.length > 0) {
91
- const toolSummaries = tools.map(t => {
92
- const name = t.name || t.function?.name || 'unknown';
93
- const desc = t.description || t.function?.description || '';
94
- const params = t.parameters || t.input_schema || t.function?.parameters || {};
95
- const paramKeys = Object.keys(params.properties || {}).join(', ');
96
- return `- ${name}(${paramKeys}): ${desc}`;
97
- }).join('\n');
98
- lines.push(`[Available Tools]\nYou may invoke tools when needed by outputting:\n<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>\n\n${toolSummaries}`);
85
+ command;
86
+ constructor(config = {}) {
87
+ super(config);
88
+ this.model = config.model || 'Gemini 3.8 Flash (Low)';
89
+ this.command = config.command || resolveAgyBinary();
90
+ this.visionModels = [];
91
+ this.audioModels = [];
99
92
  }
100
- for (const msg of messages) {
101
- const role = msg.role === 'user'
102
- ? 'User'
103
- : (msg.role === 'assistant'
104
- ? 'Assistant'
105
- : (msg.role === 'system'
106
- ? 'System Instructions'
107
- : (msg.role === 'tool'
108
- ? `Tool Result (${msg.name || 'tool'})`
109
- : 'Context')));
110
-
111
- let text = '';
112
- if (typeof msg.content === 'string') {
113
- text = msg.content;
114
- } else if (Array.isArray(msg.content)) {
115
- text = msg.content.map(c => typeof c === 'string' ? c : (c?.text || '')).filter(Boolean).join('\n');
116
- }
117
-
118
- if (msg.tool_calls && Array.isArray(msg.tool_calls)) {
119
- for (const tc of msg.tool_calls) {
120
- const fn = tc.function || {};
121
- const fnArgs = typeof fn.arguments === 'string' ? fn.arguments : JSON.stringify(fn.arguments || {});
122
- text += `\n<tool_call>{"name": "${fn.name}", "arguments": ${fnArgs}}</tool_call>`;
93
+ formatConversation(messages, tools = []) {
94
+ const lines = [];
95
+ // Core System boundary instructions
96
+ lines.push('[System Instructions]\n' +
97
+ 'You are acting as an AI reasoning engine for Causyne Agent. Do NOT invoke your own internal host CLI tools or execute commands directly. ' +
98
+ 'When an action or tool is required, output an explicit tool call in this exact format:\n' +
99
+ '<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>\n' +
100
+ 'Causyne Agent will execute the tool in its secure environment and return the results back to you.');
101
+ if (tools && tools.length > 0) {
102
+ const toolSummaries = tools.map(t => {
103
+ const name = t.name || t.function?.name || 'unknown';
104
+ const desc = t.description || t.function?.description || '';
105
+ const params = t.parameters || t.input_schema || t.function?.parameters || {};
106
+ const paramKeys = Object.keys(params.properties || {}).join(', ');
107
+ return `- ${name}(${paramKeys}): ${desc}`;
108
+ }).join('\n');
109
+ lines.push(`[Available Tools]\nYou may invoke tools when needed by outputting:\n<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>\n\n${toolSummaries}`);
110
+ }
111
+ for (const msg of messages) {
112
+ const role = msg.role === 'user'
113
+ ? 'User'
114
+ : (msg.role === 'assistant'
115
+ ? 'Assistant'
116
+ : (msg.role === 'system'
117
+ ? 'System Instructions'
118
+ : (msg.role === 'tool'
119
+ ? `Tool Result (${msg.name || 'tool'})`
120
+ : 'Context')));
121
+ let text = '';
122
+ if (typeof msg.content === 'string') {
123
+ text = msg.content;
124
+ }
125
+ else if (Array.isArray(msg.content)) {
126
+ text = msg.content.map((c) => typeof c === 'string' ? c : (c?.text || '')).filter(Boolean).join('\n');
127
+ }
128
+ if (msg.tool_calls && Array.isArray(msg.tool_calls)) {
129
+ for (const tc of msg.tool_calls) {
130
+ const fn = tc.function || {};
131
+ const fnArgs = typeof fn.arguments === 'string' ? fn.arguments : JSON.stringify(fn.arguments || {});
132
+ text += `\n<tool_call>{"name": "${fn.name}", "arguments": ${fnArgs}}</tool_call>`;
133
+ }
134
+ }
135
+ if (text.trim()) {
136
+ lines.push(`[${role}]\n${text.trim()}`);
137
+ }
123
138
  }
124
- }
125
-
126
- if (text.trim()) {
127
- lines.push(`[${role}]\n${text.trim()}`);
128
- }
139
+ return lines.join('\n\n');
129
140
  }
130
- return lines.join('\n\n');
131
- }
132
-
133
- extractToolCalls(text) {
134
- const calls = [];
135
- if (!text || typeof text !== 'string') return calls;
136
- const regex = /<tool_call>([\s\S]*?)<\/tool_call>/g;
137
- let match;
138
- let index = 0;
139
- while ((match = regex.exec(text)) !== null) {
140
- try {
141
- const parsed = JSON.parse(match[1].trim());
142
- const name = parsed.name || parsed.tool || parsed.function?.name;
143
- if (name) {
144
- const rawArgs = parsed.arguments !== undefined ? parsed.arguments : (parsed.parameters !== undefined ? parsed.parameters : (parsed.input !== undefined ? parsed.input : (parsed.function?.arguments || {})));
145
- calls.push({
146
- id: `agy_call_${Date.now()}_${index++}`,
147
- type: 'function',
148
- function: {
149
- name,
150
- arguments: typeof rawArgs === 'string' ? rawArgs : JSON.stringify(rawArgs || {})
141
+ extractToolCalls(text) {
142
+ const calls = [];
143
+ if (!text || typeof text !== 'string')
144
+ return calls;
145
+ const regex = /<tool_call>([\s\S]*?)<\/tool_call>/g;
146
+ let match;
147
+ let index = 0;
148
+ while ((match = regex.exec(text)) !== null) {
149
+ try {
150
+ const raw = match[1]?.trim() || '';
151
+ const parsed = JSON.parse(raw);
152
+ const name = parsed.name || parsed.tool || parsed.function?.name;
153
+ if (name) {
154
+ const rawArgs = parsed.arguments !== undefined ? parsed.arguments : (parsed.parameters !== undefined ? parsed.parameters : (parsed.input !== undefined ? parsed.input : (parsed.function?.arguments || {})));
155
+ calls.push({
156
+ id: `agy_call_${Date.now()}_${index++}`,
157
+ type: 'function',
158
+ function: {
159
+ name,
160
+ arguments: typeof rawArgs === 'string' ? rawArgs : JSON.stringify(rawArgs || {})
161
+ }
162
+ });
163
+ }
164
+ }
165
+ catch {
166
+ // ignore malformed tool_call blocks
167
+ }
168
+ }
169
+ if (calls.length === 0) {
170
+ const fenceRegex = /```(?:tool_call|json)?\s*(\{[\s\S]*?"name"\s*:\s*[\s\S]*?\})\s*```/g;
171
+ while ((match = fenceRegex.exec(text)) !== null) {
172
+ try {
173
+ const raw = match[1]?.trim() || '';
174
+ const parsed = JSON.parse(raw);
175
+ const name = parsed.name || parsed.tool || parsed.function?.name;
176
+ if (name) {
177
+ const rawArgs = parsed.arguments !== undefined ? parsed.arguments : (parsed.parameters !== undefined ? parsed.parameters : (parsed.input !== undefined ? parsed.input : (parsed.function?.arguments || {})));
178
+ calls.push({
179
+ id: `agy_call_${Date.now()}_${index++}`,
180
+ type: 'function',
181
+ function: {
182
+ name,
183
+ arguments: typeof rawArgs === 'string' ? rawArgs : JSON.stringify(rawArgs || {})
184
+ }
185
+ });
186
+ }
187
+ }
188
+ catch {
189
+ // ignore
190
+ }
151
191
  }
152
- });
153
192
  }
154
- } catch {
155
- // ignore malformed tool_call blocks
156
- }
193
+ return calls;
157
194
  }
158
-
159
- if (calls.length === 0) {
160
- const fenceRegex = /```(?:tool_call|json)?\s*(\{[\s\S]*?"name"\s*:\s*[\s\S]*?\})\s*```/g;
161
- while ((match = fenceRegex.exec(text)) !== null) {
162
- try {
163
- const parsed = JSON.parse(match[1].trim());
164
- const name = parsed.name || parsed.tool || parsed.function?.name;
165
- if (name) {
166
- const rawArgs = parsed.arguments !== undefined ? parsed.arguments : (parsed.parameters !== undefined ? parsed.parameters : (parsed.input !== undefined ? parsed.input : (parsed.function?.arguments || {})));
167
- calls.push({
168
- id: `agy_call_${Date.now()}_${index++}`,
169
- type: 'function',
170
- function: {
171
- name,
172
- arguments: typeof rawArgs === 'string' ? rawArgs : JSON.stringify(rawArgs || {})
173
- }
195
+ _isTransientError(errMessage) {
196
+ if (!errMessage)
197
+ return false;
198
+ const msg = String(errMessage).toLowerCase();
199
+ return msg.includes('connection reset') ||
200
+ msg.includes('econnreset') ||
201
+ msg.includes('etimedout') ||
202
+ msg.includes('streamgeneratecontent') ||
203
+ msg.includes('socket hang up') ||
204
+ msg.includes('network error') ||
205
+ msg.includes('temporarily unavailable') ||
206
+ msg.includes('status 503') ||
207
+ msg.includes('status 504') ||
208
+ msg.includes('status 429');
209
+ }
210
+ async _executeOnce(messages, options = {}) {
211
+ const promptText = this.formatConversation(messages, options.tools);
212
+ const modelSlug = resolveAgyModelId(this.model);
213
+ const effort = resolveAgyEffort(this.model);
214
+ // Standard high-performance non-blocking CLI invocation:
215
+ // 1. stream-json output for real-time responsiveness and non-buffering progress.
216
+ // 2. --disable-slash-commands prevents sluggish filesystem and customization scans.
217
+ // 3. -p - pipes prompt from stdin to avoid OS argument length bottlenecks.
218
+ // 4. --print-timeout 120s protects against unhandled deadlocks.
219
+ const args = [
220
+ '--output-format',
221
+ 'stream-json',
222
+ '--disable-slash-commands',
223
+ '--print-timeout',
224
+ '120s',
225
+ '--dangerously-skip-permissions',
226
+ '--model',
227
+ modelSlug,
228
+ '--effort',
229
+ effort,
230
+ '-p',
231
+ '-'
232
+ ];
233
+ return new Promise((resolve, reject) => {
234
+ let isSettled = false;
235
+ const child = spawn(this.command, args, {
236
+ cwd: process.cwd(),
237
+ env: process.env,
238
+ stdio: ['pipe', 'pipe', 'pipe'],
239
+ windowsHide: true
174
240
  });
175
- }
176
- } catch {
177
- // ignore
178
- }
179
- }
241
+ let stdoutBuffer = '';
242
+ let stderrBuffer = '';
243
+ let streamedResponse = '';
244
+ let finalResultObj = null;
245
+ const cleanup = () => {
246
+ if (options.signal) {
247
+ options.signal.removeEventListener('abort', onAbort);
248
+ }
249
+ };
250
+ const safeReject = (err) => {
251
+ if (isSettled)
252
+ return;
253
+ isSettled = true;
254
+ cleanup();
255
+ reject(err);
256
+ };
257
+ const safeResolve = (res) => {
258
+ if (isSettled)
259
+ return;
260
+ isSettled = true;
261
+ cleanup();
262
+ resolve(res);
263
+ };
264
+ const onAbort = () => {
265
+ try {
266
+ child.kill('SIGTERM');
267
+ setTimeout(() => {
268
+ if (!child.killed)
269
+ child.kill('SIGKILL');
270
+ }, 1000).unref();
271
+ }
272
+ catch {
273
+ // ignore kill errors
274
+ }
275
+ safeReject(new Error('Turn aborted by user or timeout.'));
276
+ };
277
+ if (options.signal) {
278
+ if (options.signal.aborted) {
279
+ onAbort();
280
+ return;
281
+ }
282
+ options.signal.addEventListener('abort', onAbort, { once: true });
283
+ }
284
+ // Feed prompt directly into child process stdin, then close stdin
285
+ try {
286
+ child.stdin.write(promptText, 'utf8');
287
+ child.stdin.end();
288
+ }
289
+ catch (err) {
290
+ safeReject(new Error(`Failed to pipe prompt to Antigravity CLI: ${err.message}`));
291
+ return;
292
+ }
293
+ child.stdout.setEncoding('utf8');
294
+ child.stdout.on('data', (chunk) => {
295
+ stdoutBuffer += chunk;
296
+ // Process line-delimited stream-json events
297
+ const lines = stdoutBuffer.split('\n');
298
+ stdoutBuffer = lines.pop() || ''; // Keep incomplete trailing fragment in buffer
299
+ for (const line of lines) {
300
+ const trimmed = line.trim();
301
+ if (!trimmed)
302
+ continue;
303
+ try {
304
+ const event = JSON.parse(trimmed);
305
+ if (event.event === 'step_update') {
306
+ const stepUpdate = event.step_update;
307
+ const delta = stepUpdate?.text_delta;
308
+ const stepType = stepUpdate?.step_type;
309
+ if (delta && typeof delta === 'string') {
310
+ if (stepType === 'thought' || stepType === 'agent_thought') {
311
+ if (typeof options.onReasoningChunk === 'function') {
312
+ options.onReasoningChunk(delta);
313
+ }
314
+ }
315
+ else {
316
+ streamedResponse += delta;
317
+ if (typeof options.onChunk === 'function') {
318
+ options.onChunk(delta);
319
+ }
320
+ }
321
+ }
322
+ }
323
+ else if (event.event === 'result') {
324
+ finalResultObj = event.result;
325
+ }
326
+ else if (event.status === 'ERROR') {
327
+ safeReject(new Error(`Antigravity Agent returned error: ${event.error || 'Unknown error'}`));
328
+ return;
329
+ }
330
+ }
331
+ catch {
332
+ // Non-JSON line (fallback log)
333
+ }
334
+ }
335
+ });
336
+ child.stderr.setEncoding('utf8');
337
+ child.stderr.on('data', (chunk) => {
338
+ stderrBuffer += chunk;
339
+ });
340
+ child.on('error', (err) => {
341
+ safeReject(new Error(`Antigravity Agent (agy) spawn error: ${err.message}. Make sure Antigravity CLI is installed.`));
342
+ });
343
+ child.on('close', (code) => {
344
+ // Process any remaining bytes in stdoutBuffer
345
+ if (stdoutBuffer.trim()) {
346
+ try {
347
+ const event = JSON.parse(stdoutBuffer.trim());
348
+ if (event.event === 'result') {
349
+ finalResultObj = event.result;
350
+ }
351
+ else if (event.status === 'ERROR') {
352
+ safeReject(new Error(`Antigravity Agent returned error: ${event.error || 'Unknown error'}`));
353
+ return;
354
+ }
355
+ }
356
+ catch {
357
+ // ignore
358
+ }
359
+ }
360
+ if (code !== 0 && !streamedResponse && !finalResultObj) {
361
+ const errDetail = stderrBuffer.trim() || `exit code ${code}`;
362
+ safeReject(new Error(`Antigravity Agent (agy) failed: ${errDetail}`));
363
+ return;
364
+ }
365
+ let rawContent = (finalResultObj?.response || streamedResponse || '').trim();
366
+ let extractedReasoning = finalResultObj?.reasoning || finalResultObj?.thought || '';
367
+ // Extract <thought> or <thinking> blocks if present in rawContent
368
+ const thoughtMatch = /<(?:thought|thinking)>([\s\S]*?)<\/(?:thought|thinking)>/i.exec(rawContent);
369
+ if (thoughtMatch && thoughtMatch[1]) {
370
+ extractedReasoning = (extractedReasoning ? extractedReasoning + '\n' : '') + thoughtMatch[1].trim();
371
+ rawContent = rawContent.replace(/<(?:thought|thinking)>[\s\S]*?<\/(?:thought|thinking)>/gi, '').trim();
372
+ }
373
+ const toolCalls = this.extractToolCalls(rawContent);
374
+ // Strip tool call tags from prose so raw XML does not leak into chat display
375
+ let content = rawContent.replace(/<tool_call>[\s\S]*?<\/tool_call>/g, '').trim();
376
+ if (!content && Array.isArray(finalResultObj?.denied_actions) && finalResultObj.denied_actions.length > 0) {
377
+ content = `Antigravity attempted action: ${finalResultObj.denied_actions.map((a) => a.display_name || a.action).join(', ')}`;
378
+ }
379
+ if (!content && toolCalls.length === 0) {
380
+ content = 'Turn completed by Antigravity Agent.';
381
+ }
382
+ const promptTokens = Number(finalResultObj?.usage?.input_tokens) || Math.ceil(promptText.length / 4);
383
+ const completionTokens = Number(finalResultObj?.usage?.output_tokens) || Math.ceil(rawContent.length / 4);
384
+ const thinkingTokens = Number(finalResultObj?.usage?.thinking_tokens) || 0;
385
+ const response = {
386
+ content: content || (toolCalls.length > 0 ? '' : 'Turn completed by Antigravity Agent.'),
387
+ usage: {
388
+ promptTokens,
389
+ completionTokens: completionTokens + thinkingTokens,
390
+ cachedPromptTokens: Number(finalResultObj?.usage?.cache_read_tokens) || 0
391
+ }
392
+ };
393
+ if (extractedReasoning) {
394
+ response.reasoningContent = extractedReasoning;
395
+ }
396
+ if (toolCalls.length > 0) {
397
+ response.toolCalls = toolCalls;
398
+ }
399
+ safeResolve(response);
400
+ });
401
+ });
180
402
  }
181
-
182
- return calls;
183
- }
184
-
185
- _isTransientError(errMessage) {
186
- if (!errMessage) return false;
187
- const msg = String(errMessage).toLowerCase();
188
- return msg.includes('connection reset') ||
189
- msg.includes('econnreset') ||
190
- msg.includes('etimedout') ||
191
- msg.includes('streamgeneratecontent') ||
192
- msg.includes('socket hang up') ||
193
- msg.includes('network error') ||
194
- msg.includes('temporarily unavailable') ||
195
- msg.includes('status 503') ||
196
- msg.includes('status 504') ||
197
- msg.includes('status 429');
198
- }
199
-
200
- async _executeOnce(messages, options = {}) {
201
- const promptText = this.formatConversation(messages, options.tools);
202
-
203
- const args = [
204
- '--output-format',
205
- 'json',
206
- '--dangerously-skip-permissions',
207
- '--model',
208
- resolveAgyModelId(this.model),
209
- `-p=${promptText}`
210
- ];
211
-
212
- return new Promise((resolve, reject) => {
213
- const child = spawn(this.command, args, {
214
- cwd: process.cwd(),
215
- env: process.env,
216
- windowsHide: true
217
- });
218
-
219
- let stdout = '';
220
- let stderr = '';
221
-
222
- child.stdout.setEncoding('utf8');
223
- child.stdout.on('data', chunk => { stdout += chunk; });
224
-
225
- child.stderr.setEncoding('utf8');
226
- child.stderr.on('data', chunk => { stderr += chunk; });
227
-
228
- child.on('error', err => {
229
- reject(new Error(`Antigravity Agent (agy) spawn error: ${err.message}. Make sure Antigravity CLI is installed.`));
230
- });
231
-
232
- child.on('close', code => {
233
- const rawOut = stdout.trim();
234
- if (code !== 0 && !rawOut) {
235
- const errDetail = stderr.trim() || `exit code ${code}`;
236
- reject(new Error(`Antigravity Agent (agy) failed: ${errDetail}`));
237
- return;
238
- }
239
-
240
- try {
241
- const parsed = JSON.parse(rawOut);
242
- if (parsed.status === 'ERROR') {
243
- reject(new Error(`Antigravity Agent returned error: ${parsed.error || 'Unknown error'}`));
244
- return;
245
- }
246
-
247
- let rawContent = (parsed.response || '').trim();
248
- const toolCalls = this.extractToolCalls(rawContent);
249
-
250
- // Strip tool call tags from prose so raw XML does not leak into chat display
251
- let content = rawContent.replace(/<tool_call>[\s\S]*?<\/tool_call>/g, '').trim();
252
-
253
- // If content is empty and denied_actions is present, describe it
254
- if (!content && Array.isArray(parsed.denied_actions) && parsed.denied_actions.length > 0) {
255
- content = `Antigravity attempted action: ${parsed.denied_actions.map(a => a.display_name || a.action).join(', ')}`;
256
- }
257
-
258
- if (!content && toolCalls.length === 0) {
259
- content = 'Turn completed by Antigravity Agent.';
260
- }
261
-
262
- const promptTokens = Number(parsed.usage?.input_tokens) || Math.ceil(promptText.length / 4);
263
- const completionTokens = Number(parsed.usage?.output_tokens) || Math.ceil(rawContent.length / 4);
264
- const thinkingTokens = Number(parsed.usage?.thinking_tokens) || 0;
265
-
266
- const response = {
267
- content: content || (toolCalls.length > 0 ? '' : 'Turn completed by Antigravity Agent.'),
268
- usage: {
269
- promptTokens,
270
- completionTokens: completionTokens + thinkingTokens,
271
- cachedPromptTokens: Number(parsed.usage?.cache_read_tokens) || 0
403
+ async chat(messages, options = {}) {
404
+ const maxRetries = options.maxRetries ?? 2;
405
+ let attempt = 0;
406
+ while (attempt <= maxRetries) {
407
+ try {
408
+ return await this._executeOnce(messages, options);
272
409
  }
273
- };
274
-
275
- if (toolCalls.length > 0) {
276
- response.toolCalls = toolCalls;
277
- }
278
-
279
- resolve(response);
280
- } catch {
281
- // If non-JSON returned, wrap raw output
282
- const content = rawOut || stderr.trim();
283
- resolve({
284
- content: content || 'Turn completed by Antigravity Agent.',
285
- usage: {
286
- promptTokens: Math.ceil(promptText.length / 4),
287
- completionTokens: Math.ceil((content || '').length / 4),
288
- cachedPromptTokens: 0
410
+ catch (err) {
411
+ if (attempt < maxRetries && this._isTransientError(err.message)) {
412
+ attempt++;
413
+ const delay = attempt * 1200;
414
+ await new Promise(r => setTimeout(r, delay));
415
+ continue;
416
+ }
417
+ throw err;
289
418
  }
290
- });
291
- }
292
- });
293
- });
294
- }
295
-
296
- async chat(messages, options = {}) {
297
- const maxRetries = options.maxRetries ?? 2;
298
- let attempt = 0;
299
- while (attempt <= maxRetries) {
300
- try {
301
- return await this._executeOnce(messages, options);
302
- } catch (err) {
303
- if (attempt < maxRetries && this._isTransientError(err.message)) {
304
- attempt++;
305
- const delay = attempt * 1200;
306
- await new Promise(r => setTimeout(r, delay));
307
- continue;
308
419
  }
309
- throw err;
310
- }
420
+ throw new Error('Antigravity execution failed after maximum retries.');
311
421
  }
312
- }
313
422
  }