@causyne/agent 1.14.0 → 1.17.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.
@@ -28,6 +28,26 @@
28
28
  // WHEN A PROVIDER SHIPS A NEW MODEL: add it here, run `npm test`, and the test
29
29
  // will name every other file that must be updated to match.
30
30
 
31
+ /**
32
+ * Models published by a peer CLI's own `models` command. Only ids verified
33
+ * against the installed binary live here; a peer with no published list is
34
+ * absent and uses its own default rather than an invented id.
35
+ */
36
+ export const PEER_MODEL_CATALOGUE = {
37
+ opencode: [
38
+ 'opencode/beam-free',
39
+ 'opencode/big-pickle',
40
+ 'opencode/deepseek-v4.1-flash-free',
41
+ 'opencode/flint-40b-free',
42
+ 'opencode/glm-5.3-flash-free',
43
+ 'opencode/mimo-v2.6-flash-free',
44
+ 'opencode/nemotron-3-ultra-free',
45
+ 'opencode/nemotron-3.5-lightning-free',
46
+ 'opencode/nemotron-3.5-super-vl-free'
47
+ ],
48
+ claude: ['sonnet', 'opus', 'haiku']
49
+ };
50
+
31
51
  /**
32
52
  * Selectable models per provider, newest first.
33
53
  *
@@ -98,7 +118,25 @@ export const MODEL_CATALOGUE = {
98
118
  'deepseek-v4-flash', 'deepseek-v4-pro'
99
119
  ],
100
120
  'Moonshot (Kimi)': ['kimi-k3', 'kimi-k2.7-code', 'kimi-k2.6'],
101
- 'xAI (Grok)': ['grok-3', 'grok-3-mini', 'grok-2-1212', 'grok-4.5', 'grok-latest']
121
+ 'xAI (Grok)': ['grok-3', 'grok-3-mini', 'grok-2-1212', 'grok-4.5', 'grok-latest'],
122
+ 'Google Antigravity': [
123
+ 'Gemini 3.8 Flash (Low)',
124
+ 'Gemini 3.8 Flash (Medium)',
125
+ 'Gemini 3.8 Flash (High)',
126
+ 'Gemini 4 Argon (Low)',
127
+ 'Gemini 4 Argon (Medium)',
128
+ 'Gemini 4 Argon (High)',
129
+ 'Claude Sonnet 5.5 (Low)',
130
+ 'Claude Sonnet 5.5 (Medium)',
131
+ 'Claude Sonnet 5.5 (High)',
132
+ 'Claude Opus 5.5 (Low)',
133
+ 'Claude Opus 5.5 (Medium)',
134
+ 'Claude Opus 5.5 (High)',
135
+ 'GPT-OSS 120B (Medium)'
136
+ ],
137
+ 'ACP (Peer Agents)': ['opencode', 'claude', 'codex', 'gemini', 'cursor', 'hermes', 'qwen', 'copilot', 'kimi', 'goose'],
138
+ 'OpenCode (ACP)': PEER_MODEL_CATALOGUE.opencode,
139
+ 'Claude Code (ACP)': PEER_MODEL_CATALOGUE.claude
102
140
  };
103
141
 
104
142
  /** Provider labels in picker order. */
@@ -117,6 +155,18 @@ export const DEFAULT_MODEL_BY_PROVIDER = {
117
155
  moonshot: 'kimi-k3',
118
156
  xai: 'grok-3',
119
157
  ollama: 'llama3.3',
158
+ acp: 'opencode',
159
+ 'acp/opencode': 'opencode/beam-free',
160
+ 'acp/claude': 'sonnet',
161
+ 'acp/codex': 'codex',
162
+ 'acp/gemini': 'gemini',
163
+ 'acp/cursor': 'cursor',
164
+ 'acp/qwen': 'qwen',
165
+ 'acp/copilot': 'copilot',
166
+ 'acp/kimi': 'kimi',
167
+ 'acp/goose': 'goose',
168
+ 'acp/hermes': 'hermes',
169
+ antigravity: 'Gemini 3.8 Flash (Low)',
120
170
  'openai-compatible': ''
121
171
  };
122
172
 
@@ -0,0 +1,295 @@
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
+ if (tools && tools.length > 0) {
66
+ const toolSummaries = tools.map(t => {
67
+ const name = t.name || t.function?.name || 'unknown';
68
+ const desc = t.description || t.function?.description || '';
69
+ const params = t.parameters || t.input_schema || t.function?.parameters || {};
70
+ const paramKeys = Object.keys(params.properties || {}).join(', ');
71
+ return `- ${name}(${paramKeys}): ${desc}`;
72
+ }).join('\n');
73
+ lines.push(`[Available Tools]\nYou may invoke tools when needed by outputting:\n<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>\n\n${toolSummaries}`);
74
+ }
75
+ for (const msg of messages) {
76
+ const role = msg.role === 'user'
77
+ ? 'User'
78
+ : (msg.role === 'assistant'
79
+ ? 'Assistant'
80
+ : (msg.role === 'system'
81
+ ? 'System Instructions'
82
+ : (msg.role === 'tool'
83
+ ? `Tool Result (${msg.name || 'tool'})`
84
+ : 'Context')));
85
+
86
+ let text = '';
87
+ if (typeof msg.content === 'string') {
88
+ text = msg.content;
89
+ } else if (Array.isArray(msg.content)) {
90
+ text = msg.content.map(c => typeof c === 'string' ? c : (c?.text || '')).filter(Boolean).join('\n');
91
+ }
92
+
93
+ if (msg.tool_calls && Array.isArray(msg.tool_calls)) {
94
+ for (const tc of msg.tool_calls) {
95
+ const fn = tc.function || {};
96
+ const fnArgs = typeof fn.arguments === 'string' ? fn.arguments : JSON.stringify(fn.arguments || {});
97
+ text += `\n<tool_call>{"name": "${fn.name}", "arguments": ${fnArgs}}</tool_call>`;
98
+ }
99
+ }
100
+
101
+ if (text.trim()) {
102
+ lines.push(`[${role}]\n${text.trim()}`);
103
+ }
104
+ }
105
+ return lines.join('\n\n');
106
+ }
107
+
108
+ /**
109
+ * The same transcript as formatConversation, split into ACP content blocks so
110
+ * images the agent loop attached reach a peer that can see them instead of
111
+ * being dropped by a text-only formatter. When the peer's initialize result
112
+ * does not advertise image input, the image is replaced with a plain note —
113
+ * the model must know it is blind, not guess at what it cannot see.
114
+ */
115
+ formatPromptBlocks(messages, tools = [], imageSupport = false) {
116
+ const blocks = [];
117
+ let pending = [];
118
+ const flush = () => {
119
+ if (pending.length === 0) return;
120
+ blocks.push({ type: 'text', text: pending.join('\n\n') });
121
+ pending = [];
122
+ };
123
+
124
+ if (tools && tools.length > 0) {
125
+ const toolSummaries = tools.map(t => {
126
+ const name = t.name || t.function?.name || 'unknown';
127
+ const desc = t.description || t.function?.description || '';
128
+ const params = t.parameters || t.input_schema || t.function?.parameters || {};
129
+ const paramKeys = Object.keys(params.properties || {}).join(', ');
130
+ return `- ${name}(${paramKeys}): ${desc}`;
131
+ }).join('\n');
132
+ pending.push(`[Available Tools]\nYou may invoke tools when needed by outputting:\n<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>\n\n${toolSummaries}`);
133
+ }
134
+
135
+ for (const msg of messages) {
136
+ const role = this._roleLabel(msg);
137
+ let text = '';
138
+ if (typeof msg.content === 'string') {
139
+ text = msg.content;
140
+ } else if (Array.isArray(msg.content)) {
141
+ text = msg.content.map(c => typeof c === 'string' ? c : (c?.text || '')).filter(Boolean).join('\n');
142
+ }
143
+
144
+ if (msg.tool_calls && Array.isArray(msg.tool_calls)) {
145
+ for (const tc of msg.tool_calls) {
146
+ const fn = tc.function || {};
147
+ const fnArgs = typeof fn.arguments === 'string' ? fn.arguments : JSON.stringify(fn.arguments || {});
148
+ text += `\n<tool_call>{"name": "${fn.name}", "arguments": ${fnArgs}}</tool_call>`;
149
+ }
150
+ }
151
+
152
+ if (text.trim()) {
153
+ pending.push(`[${role}]\n${text.trim()}`);
154
+ }
155
+
156
+ if (Array.isArray(msg.content)) {
157
+ for (const part of msg.content) {
158
+ const image = this._imageBlock(part);
159
+ if (!image) continue;
160
+ flush();
161
+ if (imageSupport) {
162
+ blocks.push(image);
163
+ } else {
164
+ pending.push(`[Image omitted — ${this.peerId} does not accept image input]`);
165
+ }
166
+ }
167
+ }
168
+ }
169
+
170
+ flush();
171
+ return blocks.length > 0 ? blocks : [{ type: 'text', text: 'Continue.' }];
172
+ }
173
+
174
+ _roleLabel(msg) {
175
+ if (msg.role === 'user') return 'User';
176
+ if (msg.role === 'assistant') return 'Assistant';
177
+ if (msg.role === 'system') return 'System Instructions';
178
+ if (msg.role === 'tool') return `Tool Result (${msg.name || 'tool'})`;
179
+ return 'Context';
180
+ }
181
+
182
+ _imageBlock(part) {
183
+ if (!part || typeof part !== 'object') return null;
184
+ if (part.type === 'image' && part.source?.type === 'base64') {
185
+ return { type: 'image', mimeType: part.source.media_type, data: part.source.data };
186
+ }
187
+ if (part.type === 'image_url' && typeof part.image_url?.url === 'string') {
188
+ const match = part.image_url.url.match(/^data:([^;]+);base64,(.+)$/);
189
+ if (match) return { type: 'image', mimeType: match[1], data: match[2] };
190
+ }
191
+ return null;
192
+ }
193
+
194
+ extractToolCalls(text) {
195
+ const calls = [];
196
+ if (!text || typeof text !== 'string') return calls;
197
+ const regex = /<tool_call>([\s\S]*?)<\/tool_call>/g;
198
+ let match;
199
+ let index = 0;
200
+ while ((match = regex.exec(text)) !== null) {
201
+ try {
202
+ const parsed = JSON.parse(match[1].trim());
203
+ if (parsed.name) {
204
+ calls.push({
205
+ id: `acp_call_${Date.now()}_${index++}`,
206
+ type: 'function',
207
+ function: {
208
+ name: parsed.name,
209
+ arguments: typeof parsed.arguments === 'string' ? parsed.arguments : JSON.stringify(parsed.arguments || {})
210
+ }
211
+ });
212
+ }
213
+ } catch {
214
+ // ignore malformed tool_call blocks
215
+ }
216
+ }
217
+ return calls;
218
+ }
219
+
220
+ async chat(messages, options = {}) {
221
+ const client = new AcpClient({
222
+ command: this.command,
223
+ args: this.args,
224
+ cwd: process.cwd(),
225
+ promptTimeoutMs: 180_000,
226
+ permissionHandler: async (req) => {
227
+ // Auto-approve peer permissions (allow once / allow always)
228
+ const allowOpt = req.options?.find(o => o.kind === 'allow_once' || o.kind === 'allow_always' || o.optionId === 'allow');
229
+ if (allowOpt) return { outcome: 'selected', optionId: allowOpt.optionId };
230
+ return { outcome: 'cancelled' };
231
+ }
232
+ });
233
+
234
+ try {
235
+ await client.start();
236
+ const sessionId = await client.newSession(process.cwd());
237
+
238
+ // OpenCode ids are namespaced (`opencode/<model>`); every other peer
239
+ // takes the id its own CLI publishes. When the resolved model IS the peer
240
+ // name, the peer's configured default is meant and no override is sent.
241
+ let targetModel = this.model;
242
+ if (this.peerId === 'opencode' && targetModel !== this.peerId && !targetModel.startsWith('opencode/')) {
243
+ targetModel = `opencode/${targetModel}`;
244
+ }
245
+ if (targetModel && targetModel !== 'acp' && targetModel !== this.peerId) {
246
+ try {
247
+ await client.setSessionModel(sessionId, targetModel);
248
+ } catch {
249
+ // peer does not support setSessionModel
250
+ }
251
+ }
252
+
253
+ const supportsImages = client.agentCapabilities?.promptCapabilities?.image === true;
254
+ const promptBlocks = this.formatPromptBlocks(messages, options.tools, supportsImages);
255
+ const promptText = promptBlocks.filter(b => b.type === 'text').map(b => b.text).join('\n\n');
256
+ let result;
257
+ try {
258
+ result = await client.prompt(sessionId, promptBlocks);
259
+ } catch (promptErr) {
260
+ // If opencode failed with beam-free, attempt fallback to flint-40b-free
261
+ if (this.peerId === 'opencode' && targetModel !== 'opencode/flint-40b-free') {
262
+ try {
263
+ await client.setSessionModel(sessionId, 'opencode/flint-40b-free');
264
+ result = await client.prompt(sessionId, promptBlocks);
265
+ } catch {
266
+ throw promptErr;
267
+ }
268
+ } else {
269
+ throw promptErr;
270
+ }
271
+ }
272
+
273
+ const content = (result?.text || '').trim();
274
+ const toolCalls = this.extractToolCalls(content);
275
+
276
+ const response = {
277
+ content: content || `Turn completed by ${this.peerId} over ACP.`,
278
+ usage: {
279
+ promptTokens: Math.ceil(promptText.length / 4),
280
+ completionTokens: Math.ceil((content || '').length / 4),
281
+ cachedPromptTokens: 0
282
+ }
283
+ };
284
+ if (toolCalls.length > 0) {
285
+ response.toolCalls = toolCalls;
286
+ }
287
+ return response;
288
+ } catch (err) {
289
+ const msg = err instanceof Error ? err.message : String(err);
290
+ throw new Error(`ACP Peer Agent (${this.peerId}) Error: ${msg}. Make sure "${this.command}" is installed and running.`);
291
+ } finally {
292
+ await client.close();
293
+ }
294
+ }
295
+ }
@@ -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,272 @@
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
+ if (tools && tools.length > 0) {
89
+ const toolSummaries = tools.map(t => {
90
+ const name = t.name || t.function?.name || 'unknown';
91
+ const desc = t.description || t.function?.description || '';
92
+ const params = t.parameters || t.input_schema || t.function?.parameters || {};
93
+ const paramKeys = Object.keys(params.properties || {}).join(', ');
94
+ return `- ${name}(${paramKeys}): ${desc}`;
95
+ }).join('\n');
96
+ lines.push(`[Available Tools]\nYou may invoke tools when needed by outputting:\n<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>\n\n${toolSummaries}`);
97
+ }
98
+ for (const msg of messages) {
99
+ const role = msg.role === 'user'
100
+ ? 'User'
101
+ : (msg.role === 'assistant'
102
+ ? 'Assistant'
103
+ : (msg.role === 'system'
104
+ ? 'System Instructions'
105
+ : (msg.role === 'tool'
106
+ ? `Tool Result (${msg.name || 'tool'})`
107
+ : 'Context')));
108
+
109
+ let text = '';
110
+ if (typeof msg.content === 'string') {
111
+ text = msg.content;
112
+ } else if (Array.isArray(msg.content)) {
113
+ text = msg.content.map(c => typeof c === 'string' ? c : (c?.text || '')).filter(Boolean).join('\n');
114
+ }
115
+
116
+ if (msg.tool_calls && Array.isArray(msg.tool_calls)) {
117
+ for (const tc of msg.tool_calls) {
118
+ const fn = tc.function || {};
119
+ const fnArgs = typeof fn.arguments === 'string' ? fn.arguments : JSON.stringify(fn.arguments || {});
120
+ text += `\n<tool_call>{"name": "${fn.name}", "arguments": ${fnArgs}}</tool_call>`;
121
+ }
122
+ }
123
+
124
+ if (text.trim()) {
125
+ lines.push(`[${role}]\n${text.trim()}`);
126
+ }
127
+ }
128
+ return lines.join('\n\n');
129
+ }
130
+
131
+ extractToolCalls(text) {
132
+ const calls = [];
133
+ if (!text || typeof text !== 'string') return calls;
134
+ const regex = /<tool_call>([\s\S]*?)<\/tool_call>/g;
135
+ let match;
136
+ let index = 0;
137
+ while ((match = regex.exec(text)) !== null) {
138
+ try {
139
+ const parsed = JSON.parse(match[1].trim());
140
+ if (parsed.name) {
141
+ calls.push({
142
+ id: `agy_call_${Date.now()}_${index++}`,
143
+ type: 'function',
144
+ function: {
145
+ name: parsed.name,
146
+ arguments: typeof parsed.arguments === 'string' ? parsed.arguments : JSON.stringify(parsed.arguments || {})
147
+ }
148
+ });
149
+ }
150
+ } catch {
151
+ // ignore malformed tool_call blocks
152
+ }
153
+ }
154
+ return calls;
155
+ }
156
+
157
+ _isTransientError(errMessage) {
158
+ if (!errMessage) return false;
159
+ const msg = String(errMessage).toLowerCase();
160
+ return msg.includes('connection reset') ||
161
+ msg.includes('econnreset') ||
162
+ msg.includes('etimedout') ||
163
+ msg.includes('streamgeneratecontent') ||
164
+ msg.includes('socket hang up') ||
165
+ msg.includes('network error') ||
166
+ msg.includes('temporarily unavailable') ||
167
+ msg.includes('status 503') ||
168
+ msg.includes('status 504') ||
169
+ msg.includes('status 429');
170
+ }
171
+
172
+ async _executeOnce(messages, options = {}) {
173
+ const promptText = this.formatConversation(messages, options.tools);
174
+
175
+ const args = [
176
+ '--output-format',
177
+ 'json',
178
+ '--model',
179
+ resolveAgyModelId(this.model),
180
+ `-p=${promptText}`
181
+ ];
182
+
183
+ return new Promise((resolve, reject) => {
184
+ const child = spawn(this.command, args, {
185
+ cwd: process.cwd(),
186
+ env: process.env,
187
+ windowsHide: true
188
+ });
189
+
190
+ let stdout = '';
191
+ let stderr = '';
192
+
193
+ child.stdout.setEncoding('utf8');
194
+ child.stdout.on('data', chunk => { stdout += chunk; });
195
+
196
+ child.stderr.setEncoding('utf8');
197
+ child.stderr.on('data', chunk => { stderr += chunk; });
198
+
199
+ child.on('error', err => {
200
+ reject(new Error(`Antigravity Agent (agy) spawn error: ${err.message}. Make sure Antigravity CLI is installed.`));
201
+ });
202
+
203
+ child.on('close', code => {
204
+ const rawOut = stdout.trim();
205
+ if (code !== 0 && !rawOut) {
206
+ const errDetail = stderr.trim() || `exit code ${code}`;
207
+ reject(new Error(`Antigravity Agent (agy) failed: ${errDetail}`));
208
+ return;
209
+ }
210
+
211
+ try {
212
+ const parsed = JSON.parse(rawOut);
213
+ if (parsed.status === 'ERROR') {
214
+ reject(new Error(`Antigravity Agent returned error: ${parsed.error || 'Unknown error'}`));
215
+ return;
216
+ }
217
+
218
+ const content = (parsed.response || '').trim();
219
+ const toolCalls = this.extractToolCalls(content);
220
+
221
+ const promptTokens = Number(parsed.usage?.input_tokens) || Math.ceil(promptText.length / 4);
222
+ const completionTokens = Number(parsed.usage?.output_tokens) || Math.ceil(content.length / 4);
223
+ const thinkingTokens = Number(parsed.usage?.thinking_tokens) || 0;
224
+
225
+ const response = {
226
+ content: content || 'Turn completed by Antigravity Agent.',
227
+ usage: {
228
+ promptTokens,
229
+ completionTokens: completionTokens + thinkingTokens,
230
+ cachedPromptTokens: Number(parsed.usage?.cache_read_tokens) || 0
231
+ }
232
+ };
233
+
234
+ if (toolCalls.length > 0) {
235
+ response.toolCalls = toolCalls;
236
+ }
237
+
238
+ resolve(response);
239
+ } catch {
240
+ // If non-JSON returned, wrap raw output
241
+ const content = rawOut || stderr.trim();
242
+ resolve({
243
+ content: content || 'Turn completed by Antigravity Agent.',
244
+ usage: {
245
+ promptTokens: Math.ceil(promptText.length / 4),
246
+ completionTokens: Math.ceil((content || '').length / 4),
247
+ cachedPromptTokens: 0
248
+ }
249
+ });
250
+ }
251
+ });
252
+ });
253
+ }
254
+
255
+ async chat(messages, options = {}) {
256
+ const maxRetries = options.maxRetries ?? 2;
257
+ let attempt = 0;
258
+ while (attempt <= maxRetries) {
259
+ try {
260
+ return await this._executeOnce(messages, options);
261
+ } catch (err) {
262
+ if (attempt < maxRetries && this._isTransientError(err.message)) {
263
+ attempt++;
264
+ const delay = attempt * 1200;
265
+ await new Promise(r => setTimeout(r, delay));
266
+ continue;
267
+ }
268
+ throw err;
269
+ }
270
+ }
271
+ }
272
+ }
@@ -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
  }