@causyne/agent 1.14.0 → 1.18.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.
@@ -0,0 +1,328 @@
1
+ import { canonicalModelId } from '../modelIds.js';
2
+ import { DEFAULT_MODEL_BY_PROVIDER } from '../modelCatalogue.js';
3
+ import { LLMProvider } from './base.js';
4
+ import { AcpClient } from '../acp/client.js';
5
+ import { getPeerProfile } from '../acp/peerProfiles.js';
6
+ import { BUILTIN_PEER_PRESETS } from '../acp/agentCatalog.js';
7
+
8
+ export function isAcpProvider(provider) {
9
+ if (!provider) return false;
10
+ const p = String(provider).toLowerCase();
11
+ return p === 'acp' || p.startsWith('acp/') || p.startsWith('acp:') ||
12
+ ['opencode', 'claude', 'codex', 'cursor', 'hermes', 'goose', 'copilot'].includes(p);
13
+ }
14
+
15
+ export class AcpProvider extends LLMProvider {
16
+ constructor(config = {}) {
17
+ super(config);
18
+
19
+ // Resolve the peer first: `acp/opencode` names it outright, a bare peer id
20
+ // (the legacy shape) names it too, and a generic `acp` falls back to the
21
+ // model field — which historically carried the peer id.
22
+ const providerStr = String(config.provider || '').toLowerCase().trim();
23
+ const configuredModel = typeof config.model === 'string' ? config.model.trim() : '';
24
+ let resolvedPeer = '';
25
+ if (providerStr.startsWith('acp/') || providerStr.startsWith('acp:')) {
26
+ resolvedPeer = providerStr.slice(4).split('/')[0];
27
+ } else if (providerStr && providerStr !== 'acp') {
28
+ resolvedPeer = providerStr;
29
+ } else if (config.peer) {
30
+ resolvedPeer = String(config.peer).toLowerCase();
31
+ } else if (configuredModel && configuredModel !== 'acp' && BUILTIN_PEER_PRESETS[configuredModel.toLowerCase()]) {
32
+ resolvedPeer = configuredModel.toLowerCase();
33
+ }
34
+ this.peerId = resolvedPeer || 'opencode';
35
+
36
+ // Every peer gets its own default. Without this, selecting Claude Code or
37
+ // Codex inherited OpenCode's model and asked the wrong peer for it.
38
+ const peerDefault = DEFAULT_MODEL_BY_PROVIDER[`acp/${this.peerId}`]
39
+ || DEFAULT_MODEL_BY_PROVIDER['acp']
40
+ || this.peerId;
41
+ const modelIsPeerName = !configuredModel || configuredModel === 'acp' || configuredModel === this.peerId;
42
+ this.model = canonicalModelId(modelIsPeerName ? peerDefault : configuredModel);
43
+
44
+ const profile = getPeerProfile(this.peerId);
45
+ if (profile) {
46
+ this.command = profile.command;
47
+ this.args = profile.args || [];
48
+ } else {
49
+ const preset = BUILTIN_PEER_PRESETS[this.peerId];
50
+ if (preset) {
51
+ this.command = preset.command;
52
+ this.args = preset.args || [];
53
+ } else {
54
+ this.command = config.command || this.peerId;
55
+ this.args = config.args || ['acp'];
56
+ }
57
+ }
58
+
59
+ this.visionModels = ['*'];
60
+ this.audioModels = [];
61
+ }
62
+
63
+ formatConversation(messages, tools = []) {
64
+ const lines = [];
65
+ lines.push(`[System Instructions]\nYou are acting as an AI reasoning engine for Causyne Agent over ACP. 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.`);
66
+
67
+ if (tools && tools.length > 0) {
68
+ const toolSummaries = tools.map(t => {
69
+ const name = t.name || t.function?.name || 'unknown';
70
+ const desc = t.description || t.function?.description || '';
71
+ const params = t.parameters || t.input_schema || t.function?.parameters || {};
72
+ const paramKeys = Object.keys(params.properties || {}).join(', ');
73
+ return `- ${name}(${paramKeys}): ${desc}`;
74
+ }).join('\n');
75
+ lines.push(`[Available Tools]\nYou may invoke tools when needed by outputting:\n<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>\n\n${toolSummaries}`);
76
+ }
77
+ for (const msg of messages) {
78
+ const role = msg.role === 'user'
79
+ ? 'User'
80
+ : (msg.role === 'assistant'
81
+ ? 'Assistant'
82
+ : (msg.role === 'system'
83
+ ? 'System Instructions'
84
+ : (msg.role === 'tool'
85
+ ? `Tool Result (${msg.name || 'tool'})`
86
+ : 'Context')));
87
+
88
+ let text = '';
89
+ if (typeof msg.content === 'string') {
90
+ text = msg.content;
91
+ } else if (Array.isArray(msg.content)) {
92
+ text = msg.content.map(c => typeof c === 'string' ? c : (c?.text || '')).filter(Boolean).join('\n');
93
+ }
94
+
95
+ if (msg.tool_calls && Array.isArray(msg.tool_calls)) {
96
+ for (const tc of msg.tool_calls) {
97
+ const fn = tc.function || {};
98
+ const fnArgs = typeof fn.arguments === 'string' ? fn.arguments : JSON.stringify(fn.arguments || {});
99
+ text += `\n<tool_call>{"name": "${fn.name}", "arguments": ${fnArgs}}</tool_call>`;
100
+ }
101
+ }
102
+
103
+ if (text.trim()) {
104
+ lines.push(`[${role}]\n${text.trim()}`);
105
+ }
106
+ }
107
+ return lines.join('\n\n');
108
+ }
109
+
110
+ /**
111
+ * The same transcript as formatConversation, split into ACP content blocks so
112
+ * images the agent loop attached reach a peer that can see them instead of
113
+ * being dropped by a text-only formatter. When the peer's initialize result
114
+ * does not advertise image input, the image is replaced with a plain note —
115
+ * the model must know it is blind, not guess at what it cannot see.
116
+ */
117
+ formatPromptBlocks(messages, tools = [], imageSupport = false) {
118
+ const blocks = [];
119
+ let pending = [];
120
+ const flush = () => {
121
+ if (pending.length === 0) return;
122
+ blocks.push({ type: 'text', text: pending.join('\n\n') });
123
+ pending = [];
124
+ };
125
+
126
+ pending.push(`[System Instructions]\nYou are acting as an AI reasoning engine for Causyne Agent over ACP. 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.`);
127
+
128
+ if (tools && tools.length > 0) {
129
+ const toolSummaries = tools.map(t => {
130
+ const name = t.name || t.function?.name || 'unknown';
131
+ const desc = t.description || t.function?.description || '';
132
+ const params = t.parameters || t.input_schema || t.function?.parameters || {};
133
+ const paramKeys = Object.keys(params.properties || {}).join(', ');
134
+ return `- ${name}(${paramKeys}): ${desc}`;
135
+ }).join('\n');
136
+ pending.push(`[Available Tools]\nYou may invoke tools when needed by outputting:\n<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>\n\n${toolSummaries}`);
137
+ }
138
+
139
+ for (const msg of messages) {
140
+ const role = this._roleLabel(msg);
141
+ let text = '';
142
+ if (typeof msg.content === 'string') {
143
+ text = msg.content;
144
+ } else if (Array.isArray(msg.content)) {
145
+ text = msg.content.map(c => typeof c === 'string' ? c : (c?.text || '')).filter(Boolean).join('\n');
146
+ }
147
+
148
+ if (msg.tool_calls && Array.isArray(msg.tool_calls)) {
149
+ for (const tc of msg.tool_calls) {
150
+ const fn = tc.function || {};
151
+ const fnArgs = typeof fn.arguments === 'string' ? fn.arguments : JSON.stringify(fn.arguments || {});
152
+ text += `\n<tool_call>{"name": "${fn.name}", "arguments": ${fnArgs}}</tool_call>`;
153
+ }
154
+ }
155
+
156
+ if (text.trim()) {
157
+ pending.push(`[${role}]\n${text.trim()}`);
158
+ }
159
+
160
+ if (Array.isArray(msg.content)) {
161
+ for (const part of msg.content) {
162
+ const image = this._imageBlock(part);
163
+ if (!image) continue;
164
+ flush();
165
+ if (imageSupport) {
166
+ blocks.push(image);
167
+ } else {
168
+ pending.push(`[Image omitted — ${this.peerId} does not accept image input]`);
169
+ }
170
+ }
171
+ }
172
+ }
173
+
174
+ flush();
175
+ return blocks.length > 0 ? blocks : [{ type: 'text', text: 'Continue.' }];
176
+ }
177
+
178
+ _roleLabel(msg) {
179
+ if (msg.role === 'user') return 'User';
180
+ if (msg.role === 'assistant') return 'Assistant';
181
+ if (msg.role === 'system') return 'System Instructions';
182
+ if (msg.role === 'tool') return `Tool Result (${msg.name || 'tool'})`;
183
+ return 'Context';
184
+ }
185
+
186
+ _imageBlock(part) {
187
+ if (!part || typeof part !== 'object') return null;
188
+ if (part.type === 'image' && part.source?.type === 'base64') {
189
+ return { type: 'image', mimeType: part.source.media_type, data: part.source.data };
190
+ }
191
+ if (part.type === 'image_url' && typeof part.image_url?.url === 'string') {
192
+ const match = part.image_url.url.match(/^data:([^;]+);base64,(.+)$/);
193
+ if (match) return { type: 'image', mimeType: match[1], data: match[2] };
194
+ }
195
+ return null;
196
+ }
197
+
198
+ extractToolCalls(text) {
199
+ const calls = [];
200
+ if (!text || typeof text !== 'string') return calls;
201
+ const regex = /<tool_call>([\s\S]*?)<\/tool_call>/g;
202
+ let match;
203
+ let index = 0;
204
+ while ((match = regex.exec(text)) !== null) {
205
+ try {
206
+ const parsed = JSON.parse(match[1].trim());
207
+ const name = parsed.name || parsed.tool || parsed.function?.name;
208
+ if (name) {
209
+ const rawArgs = parsed.arguments !== undefined ? parsed.arguments : (parsed.parameters !== undefined ? parsed.parameters : (parsed.input !== undefined ? parsed.input : (parsed.function?.arguments || {})));
210
+ calls.push({
211
+ id: `acp_call_${Date.now()}_${index++}`,
212
+ type: 'function',
213
+ function: {
214
+ name,
215
+ arguments: typeof rawArgs === 'string' ? rawArgs : JSON.stringify(rawArgs || {})
216
+ }
217
+ });
218
+ }
219
+ } catch {
220
+ // ignore malformed tool_call blocks
221
+ }
222
+ }
223
+
224
+ if (calls.length === 0) {
225
+ const fenceRegex = /```(?:tool_call|json)?\s*(\{[\s\S]*?"name"\s*:\s*[\s\S]*?\})\s*```/g;
226
+ while ((match = fenceRegex.exec(text)) !== null) {
227
+ try {
228
+ const parsed = JSON.parse(match[1].trim());
229
+ const name = parsed.name || parsed.tool || parsed.function?.name;
230
+ if (name) {
231
+ const rawArgs = parsed.arguments !== undefined ? parsed.arguments : (parsed.parameters !== undefined ? parsed.parameters : (parsed.input !== undefined ? parsed.input : (parsed.function?.arguments || {})));
232
+ calls.push({
233
+ id: `acp_call_${Date.now()}_${index++}`,
234
+ type: 'function',
235
+ function: {
236
+ name,
237
+ arguments: typeof rawArgs === 'string' ? rawArgs : JSON.stringify(rawArgs || {})
238
+ }
239
+ });
240
+ }
241
+ } catch {
242
+ // ignore
243
+ }
244
+ }
245
+ }
246
+
247
+ return calls;
248
+ }
249
+
250
+ async chat(messages, options = {}) {
251
+ const client = new AcpClient({
252
+ command: this.command,
253
+ args: this.args,
254
+ cwd: process.cwd(),
255
+ promptTimeoutMs: 180_000,
256
+ permissionHandler: async (req) => {
257
+ // Auto-approve peer permissions (allow once / allow always)
258
+ const allowOpt = req.options?.find(o => o.kind === 'allow_once' || o.kind === 'allow_always' || o.optionId === 'allow');
259
+ if (allowOpt) return { outcome: 'selected', optionId: allowOpt.optionId };
260
+ return { outcome: 'cancelled' };
261
+ }
262
+ });
263
+
264
+ try {
265
+ await client.start();
266
+ const sessionId = await client.newSession(process.cwd());
267
+
268
+ // OpenCode ids are namespaced (`opencode/<model>`); every other peer
269
+ // takes the id its own CLI publishes. When the resolved model IS the peer
270
+ // name, the peer's configured default is meant and no override is sent.
271
+ let targetModel = this.model;
272
+ if (this.peerId === 'opencode' && targetModel !== this.peerId && !targetModel.startsWith('opencode/')) {
273
+ targetModel = `opencode/${targetModel}`;
274
+ }
275
+ if (targetModel && targetModel !== 'acp' && targetModel !== this.peerId) {
276
+ try {
277
+ await client.setSessionModel(sessionId, targetModel);
278
+ } catch {
279
+ // peer does not support setSessionModel
280
+ }
281
+ }
282
+
283
+ const supportsImages = client.agentCapabilities?.promptCapabilities?.image === true;
284
+ const promptBlocks = this.formatPromptBlocks(messages, options.tools, supportsImages);
285
+ const promptText = promptBlocks.filter(b => b.type === 'text').map(b => b.text).join('\n\n');
286
+ let result;
287
+ try {
288
+ result = await client.prompt(sessionId, promptBlocks);
289
+ } catch (promptErr) {
290
+ // If opencode failed with beam-free, attempt fallback to flint-40b-free
291
+ if (this.peerId === 'opencode' && targetModel !== 'opencode/flint-40b-free') {
292
+ try {
293
+ await client.setSessionModel(sessionId, 'opencode/flint-40b-free');
294
+ result = await client.prompt(sessionId, promptBlocks);
295
+ } catch {
296
+ throw promptErr;
297
+ }
298
+ } else {
299
+ throw promptErr;
300
+ }
301
+ }
302
+
303
+ let rawContent = (result?.text || '').trim();
304
+ const toolCalls = this.extractToolCalls(rawContent);
305
+
306
+ // Strip tool call XML from chat content display
307
+ let content = rawContent.replace(/<tool_call>[\s\S]*?<\/tool_call>/g, '').trim();
308
+
309
+ const response = {
310
+ content: content || (toolCalls.length > 0 ? '' : `Turn completed by ${this.peerId} over ACP.`),
311
+ usage: {
312
+ promptTokens: Math.ceil(promptText.length / 4),
313
+ completionTokens: Math.ceil(rawContent.length / 4),
314
+ cachedPromptTokens: 0
315
+ }
316
+ };
317
+ if (toolCalls.length > 0) {
318
+ response.toolCalls = toolCalls;
319
+ }
320
+ return response;
321
+ } catch (err) {
322
+ const msg = err instanceof Error ? err.message : String(err);
323
+ throw new Error(`ACP Peer Agent (${this.peerId}) Error: ${msg}. Make sure "${this.command}" is installed and running.`);
324
+ } finally {
325
+ await client.close();
326
+ }
327
+ }
328
+ }
@@ -0,0 +1,9 @@
1
+ export const ANTIGRAVITY_MODELS: string[];
2
+ export const ANTIGRAVITY_MODEL_IDS: Record<string, string>;
3
+ export const ANTIGRAVITY_LABEL_BY_ID: Record<string, string>;
4
+ export function resolveAgyModelId(model: string): string;
5
+ export function isAntigravityProvider(provider: string | null | undefined): boolean;
6
+ export function resolveAgyBinary(): string;
7
+ export class AntigravityProvider {
8
+ constructor(config?: Record<string, unknown>);
9
+ }
@@ -0,0 +1,313 @@
1
+ import { spawn } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { LLMProvider } from './base.js';
5
+
6
+ /**
7
+ * Display label → the id `agy --model` actually accepts, exactly as reported
8
+ * by `agy models`. The CLI exposes slugs; the picker shows the readable label.
9
+ * Passing the label through unchanged is what a user would try, so both forms
10
+ * resolve here rather than failing at the provider.
11
+ */
12
+ 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'
26
+ };
27
+
28
+ export const ANTIGRAVITY_LABEL_BY_ID = Object.fromEntries(
29
+ Object.entries(ANTIGRAVITY_MODEL_IDS).map(([label, id]) => [id, label])
30
+ );
31
+
32
+ export const ANTIGRAVITY_MODELS = Object.keys(ANTIGRAVITY_MODEL_IDS);
33
+
34
+ export function resolveAgyModelId(model) {
35
+ if (typeof model !== 'string') return '';
36
+ const trimmed = model.trim();
37
+ return ANTIGRAVITY_MODEL_IDS[trimmed] || trimmed;
38
+ }
39
+
40
+ 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/');
44
+ }
45
+
46
+ 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;
65
+ }
66
+ } catch {
67
+ // ignore inaccessible path
68
+ }
69
+ }
70
+ }
71
+ return 'agy';
72
+ }
73
+
74
+ 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}`);
99
+ }
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>`;
123
+ }
124
+ }
125
+
126
+ if (text.trim()) {
127
+ lines.push(`[${role}]\n${text.trim()}`);
128
+ }
129
+ }
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 || {})
151
+ }
152
+ });
153
+ }
154
+ } catch {
155
+ // ignore malformed tool_call blocks
156
+ }
157
+ }
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
+ }
174
+ });
175
+ }
176
+ } catch {
177
+ // ignore
178
+ }
179
+ }
180
+ }
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
272
+ }
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
289
+ }
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
+ }
309
+ throw err;
310
+ }
311
+ }
312
+ }
313
+ }
@@ -16,6 +16,8 @@ import { DashscopeByokProvider } from './dashscope-byok.js';
16
16
  import { XAIProvider } from './xai.js';
17
17
  import { MoonshotProvider } from './moonshot.js';
18
18
  import { MuseProvider } from './muse.js';
19
+ import { AcpProvider, isAcpProvider } from './acp.js';
20
+ import { AntigravityProvider, isAntigravityProvider } from './antigravity.js';
19
21
 
20
22
  export function createProvider(config) {
21
23
  const p = config.provider?.toLowerCase();
@@ -32,6 +34,8 @@ export function createProvider(config) {
32
34
  // Meta Model API. 'meta' and 'muse' both reach it: the vendor is Meta, the
33
35
  // model family is Muse, and users say either.
34
36
  if (p === 'muse' || p === 'meta') return new MuseProvider(config);
37
+ if (isAcpProvider(p)) return new AcpProvider(config);
38
+ if (isAntigravityProvider(p)) return new AntigravityProvider(config);
35
39
 
36
40
  throw new Error("API Key Required. Causyne is a 100% Sovereign BYOK Engine. Please configure your API Provider and Key in Settings.");
37
41
  }
package/src/reporting.js CHANGED
@@ -9,6 +9,8 @@ import { listSpills, getOutputDir } from './outputStore.js';
9
9
  import { listGroups, undoLast, undoTask, undoStep, getStoreStats } from './checkpoints.js';
10
10
  import { panel } from './tui/block.js';
11
11
  import { terminalWidth, readableWidth } from './tui/theme.js';
12
+ import { isAcpProvider } from './providers/acp.js';
13
+ import { isAntigravityProvider } from './providers/antigravity.js';
12
14
 
13
15
  // The same divisor scripts/measure_context.js uses, so the CLI and the dev
14
16
  // harness never disagree about what a token costs.
@@ -327,7 +329,7 @@ export function buildStatusText({ loop = null } = {}) {
327
329
  lines.push(` Workspace scope : ${sandbox.grantAllAccess ? 'ALL ACCESS' : (sandbox.workspacePaths || []).join(', ')}`);
328
330
  }
329
331
 
330
- if (!config.apiKey && config.provider !== 'ollama') {
332
+ if (!config.apiKey && config.provider !== 'ollama' && !isAcpProvider(config.provider) && !isAntigravityProvider(config.provider)) {
331
333
  lines.push('');
332
334
  lines.push(' No API key is set. Run `causyne config`.');
333
335
  }