labs-claude 0.2.6 → 0.3.3

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.
package/src/agy.js ADDED
@@ -0,0 +1,1016 @@
1
+ const { createHash, randomUUID } = require('crypto');
2
+ const { execFileSync, spawn } = require('child_process');
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const {
6
+ createThreadId,
7
+ extractLatestUserContent,
8
+ formatConversationHistory,
9
+ isValidSessionId,
10
+ lastAssistantContent,
11
+ replySignature
12
+ } = require('./anthropic-protocol');
13
+ const { sanitizeSchema } = require('./gemini');
14
+
15
+ const AGY_PREFIX = 'agy:';
16
+ const DEBUG = process.env.LABS_AGY_DEBUG === '1';
17
+ const dbg = (...args) => { if (DEBUG) console.log('🔍 [agy]', ...args); };
18
+ const MCP_SETTLE_MS = 120;
19
+ const MCP_KEEPALIVE_MS = 10000;
20
+ const REQUEST_TIMEOUT_MS = 600000;
21
+ // A healthy session/new takes 3-4 s; 60 s of waiting looked like Claude Code thinking forever.
22
+ const SESSION_NEW_TIMEOUT_MS = 20000;
23
+ const AGY_SILENCE_MS = Number(process.env.LABS_AGY_SILENCE_MS) || 60000;
24
+ const MAX_SYSTEM_APPEND_CHARS = Number(process.env.LABS_AGY_MAX_SYSTEM_CHARS) || 4000;
25
+ const MAX_TOOL_DESC_CHARS = 120;
26
+ const MAX_REMINDER_CHARS = 4000;
27
+ const MAX_HISTORY_CHARS = 180000;
28
+
29
+ const AGY_MODELS = {
30
+ 'gemini-4-hydrogen': { contextLimit: 1048576, maxReply: 65536, hasEffort: true },
31
+ 'gemini-3.8-flash': { contextLimit: 1048576, maxReply: 65536, hasEffort: true },
32
+ 'claude-sonnet-4-6': { contextLimit: 200000, maxReply: 65536, hasEffort: false },
33
+ 'claude-opus-4-6-thinking': { contextLimit: 200000, maxReply: 65536, hasEffort: false },
34
+ 'gpt-oss-120b-medium': { contextLimit: 131072, maxReply: 32768, hasEffort: false }
35
+ };
36
+
37
+ const EFFORT_TO_THOUGHT = {
38
+ none: 'low',
39
+ minimal: 'low',
40
+ low: 'low',
41
+ medium: 'medium',
42
+ high: 'high',
43
+ xhigh: 'xhigh',
44
+ max: 'xhigh'
45
+ };
46
+
47
+ const BRIDGE_DIRECTIVE = [
48
+ 'CRITICAL CLAUDE CODE BRIDGE INSTRUCTIONS:',
49
+ 'You are acting solely as the LLM backend inside an active Claude Code CLI session.',
50
+ '1. NEVER invoke your built-in Antigravity tools (view_file, write_to_file, replace_file_content, multi_replace_file_content, sed_file, run_command, command_status, send_command_input, grep_search, find_by_name, list_dir, search_web, read_url_content, browser_*, open_browser_url, capture_browser_screenshot, invoke_subagent, define_subagent, manage_subagents, manage_task, schedule, generate_image, finish, etc.). Built-in workspace tools bypass Claude Code hooks, permissions, and MCP servers and write/exec calls will be denied.',
51
+ '2. ALWAYS use ONLY the `mcp_cc_*` tools provided by the `cc` MCP server for every file read, write, edit, search, shell command, subagent, skill, or web call.',
52
+ '3. Follow the Claude Code system instructions below as your primary workspace rules.'
53
+ ].join('\n');
54
+
55
+ let cachedHasAgy = null;
56
+
57
+ function hasAgyCli() {
58
+ if (cachedHasAgy !== null) return cachedHasAgy;
59
+ for (const cmd of process.platform === 'win32' ? ['agy.exe', 'agy'] : ['agy']) {
60
+ try {
61
+ execFileSync(cmd, ['--version'], { stdio: 'ignore', windowsHide: true });
62
+ cachedHasAgy = true;
63
+ return true;
64
+ } catch {
65
+ // Try next candidate.
66
+ }
67
+ }
68
+ cachedHasAgy = false;
69
+ return false;
70
+ }
71
+
72
+ function agyModelId(llm) {
73
+ return typeof llm === 'string' && llm.startsWith(AGY_PREFIX) ? llm.slice(AGY_PREFIX.length) : null;
74
+ }
75
+
76
+ function isAgyFallbackModel(llm) {
77
+ return llm === 'gemini-4-hydrogen' || llm === 'gemini-3.8-flash';
78
+ }
79
+
80
+ // agy log: "Run: attempt 2 failed (transport error (ResourceExhausted, HTTP 429): ...), retrying in 6.7545s"
81
+ function parseAgyRetries(text) {
82
+ const out = [];
83
+ for (const m of String(text).matchAll(/Run: attempt (\d+) failed \((.*?)\), retrying in ([\d.]+)(ms|s)/g)) {
84
+ const code = (m[2].match(/HTTP (\d{3})/) || [])[1] || '';
85
+ const reason = /ResourceExhausted|RESOURCE_EXHAUSTED/.test(m[2]) ? 'Google rate limit (429)' : (code ? `HTTP ${code}` : m[2].slice(0, 80));
86
+ out.push({ attempt: Number(m[1]), reason, waitSeconds: Math.round(Number(m[3]) / (m[4] === 'ms' ? 1000 : 1)) });
87
+ }
88
+ return out;
89
+ }
90
+
91
+ // Turns agy's "Individual quota reached ... Resets in 113h53m49s." into one line with the local reset time.
92
+ function quotaNotice(text, modelId, now = Date.now()) {
93
+ const clean = String(text || '').trim();
94
+ if (!/^⚠\s*(Individual quota reached|.*quota.*reached)/i.test(clean)) {
95
+ // A burst limit agy already retried 5 times; Claude Code's own 10 retries of ~40k tokens each kept it full.
96
+ if (/^\W*RESOURCE_EXHAUSTED/i.test(clean)) return 'Google is rate-limiting this Antigravity account right now (429), and agy already retried 5 times. Wait about a minute, then send your message again.';
97
+ return null;
98
+ }
99
+ const m = clean.match(/Resets in\s*(?:(\d+)h)?\s*(?:(\d+)m)?/i);
100
+ let when = '';
101
+ if (m && (m[1] || m[2])) {
102
+ const at = new Date(now + ((Number(m[1] || 0) * 60) + Number(m[2] || 0)) * 60000);
103
+ when = ` It resets in ${m[1] || 0}h ${m[2] || 0}m (${at.toLocaleString('en-GB', { weekday: 'short', day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' })}).`;
104
+ }
105
+ return `Antigravity quota is used up for ${modelId}, so agy cannot answer.${when} Meanwhile use another brain, for example: labs --model astra`;
106
+ }
107
+
108
+ function agyModelInfo(modelId) {
109
+ return AGY_MODELS[modelId] || { contextLimit: 1048576, maxReply: 65536, hasEffort: /^gemini-/i.test(modelId || '') };
110
+ }
111
+
112
+ function agyEffortFor(effort) {
113
+ return EFFORT_TO_THOUGHT[String(effort || 'high').toLowerCase()] || 'high';
114
+ }
115
+
116
+ // Antigravity prefixes MCP tools as `mcp_cc_<name>`, so keep `<name>` <= 56 chars to stay within 64-char model limits.
117
+ function agyToolName(name) {
118
+ if (/^[a-zA-Z_][a-zA-Z0-9_.:-]{0,55}$/.test(name)) return name;
119
+ const hash = createHash('sha1').update(name).digest('hex').slice(0, 8);
120
+ const cleaned = name.replace(/[^a-zA-Z0-9_.:-]/g, '_');
121
+ const prefixed = /^[a-zA-Z_]/.test(cleaned) ? cleaned : `t_${cleaned}`;
122
+ return `${prefixed.slice(0, 47)}_${hash}`;
123
+ }
124
+
125
+ function systemTextOf(system) {
126
+ if (typeof system === 'string') return system;
127
+ if (!Array.isArray(system)) return '';
128
+ // Filter out Anthropic billing headers and Claude Code's built-in 28k SDK essay (CLAUDE.md & context arrive in messages).
129
+ return system
130
+ .map(block => block?.text || '')
131
+ .filter(t => t && !/^x-anthropic-billing-header:/i.test(t.trim())
132
+ && !/^You are a Claude agent, built on Anthropic's Claude Agent SDK\./i.test(t.trim())
133
+ && !/^\s*You are an agent working with the user toward their goals, using your own judgment/i.test(t))
134
+ .join('\n\n');
135
+ }
136
+
137
+ function buildSystemAppend(system) {
138
+ const raw = systemTextOf(system).trim();
139
+ const trimmed = raw.length > MAX_SYSTEM_APPEND_CHARS
140
+ ? `${raw.slice(0, MAX_SYSTEM_APPEND_CHARS)}\n[... system prompt truncated ...]`
141
+ : raw;
142
+ return trimmed ? `${BRIDGE_DIRECTIVE}\n\n${trimmed}` : BRIDGE_DIRECTIVE;
143
+ }
144
+
145
+ function mcpContentFromToolResult(content) {
146
+ if (typeof content === 'string' || content == null) {
147
+ return [{ type: 'text', text: String(content || '(no output)') }];
148
+ }
149
+ if (!Array.isArray(content)) return [{ type: 'text', text: String(content) }];
150
+ const items = [];
151
+ for (const block of content) {
152
+ if (block?.type === 'text' && block.text) {
153
+ items.push({ type: 'text', text: block.text });
154
+ } else if (block?.type === 'image' && block.source?.type === 'base64' && block.source.data) {
155
+ items.push({ type: 'image', data: block.source.data, mimeType: block.source.media_type || 'image/png' });
156
+ }
157
+ }
158
+ return items.length ? items : [{ type: 'text', text: '(no output)' }];
159
+ }
160
+
161
+ function compactPromptText(text) {
162
+ if (!text || text.length <= 6000) return text;
163
+ return text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, block => {
164
+ if (/The following skills are available|Available agent types for the Agent tool/i.test(block)) {
165
+ return '';
166
+ }
167
+ if (block.length <= MAX_REMINDER_CHARS) return block;
168
+ return `${block.slice(0, MAX_REMINDER_CHARS)}
169
+ [... reminder truncated for context budget ...]
170
+ </system-reminder>`;
171
+ }).replace(/\n{3,}/g, '\n\n').trim();
172
+ }
173
+
174
+ function buildAcpPromptBlocks({ text, images = [], history = [], unmatchedResults = [], hasTools = false }) {
175
+ const parts = [];
176
+ if (history.length) {
177
+ const replay = formatConversationHistory(history, MAX_HISTORY_CHARS);
178
+ if (replay) parts.push(`Conversation so far:\n${replay}`);
179
+ }
180
+ if (unmatchedResults.length) {
181
+ const formatted = unmatchedResults
182
+ .map(r => `${r.isError ? 'Tool error' : 'Tool result'} (${r.toolUseId}):\n${r.content}`)
183
+ .join('\n\n');
184
+ parts.push(formatted);
185
+ }
186
+ if (text) parts.push(compactPromptText(text));
187
+ if (hasTools) {
188
+ parts.push('[Claude Code Bridge: Use ONLY mcp_cc_* tools (mcp_cc_Read, mcp_cc_Edit, mcp_cc_Write, mcp_cc_Bash, mcp_cc_Glob, mcp_cc_Grep, etc.) — NEVER call built-in view_file, write_to_file, replace_file_content, run_command, grep_search, find_by_name, or list_dir.]');
189
+ }
190
+ const combinedText = parts.join('\n\n').trim() || (images.length ? 'See the attached image(s).' : 'Continue.');
191
+
192
+ const blocks = [{ type: 'text', text: combinedText }];
193
+ for (const img of images) {
194
+ if (img?.data && img?.mediaType) {
195
+ blocks.push({ type: 'image', mimeType: img.mediaType, data: img.data });
196
+ }
197
+ }
198
+ return blocks;
199
+ }
200
+
201
+ function toWindowsPath(value) {
202
+ if (process.platform !== 'win32' || typeof value !== 'string' || !value.startsWith('/')) return value;
203
+ const drive = value.match(/^\/([a-zA-Z])(\/.*)?$/);
204
+ return drive ? `${drive[1].toUpperCase()}:\\${(drive[2] || '').slice(1).replace(/\//g, '\\')}` : value;
205
+ }
206
+
207
+ function normalizeToolInput(input) {
208
+ if (!input || typeof input !== 'object') return {};
209
+ const out = { ...input };
210
+ for (const key of ['file_path', 'path', 'notebook_path']) {
211
+ if (typeof out[key] === 'string') out[key] = toWindowsPath(out[key]);
212
+ }
213
+ return out;
214
+ }
215
+
216
+ class AgyAcpClient {
217
+ constructor({ spawnImpl = spawn, onSessionUpdate = null, onUnexpectedExit = null, logFile = null } = {}) {
218
+ this.logFile = logFile;
219
+ this.logOffset = 0;
220
+ this.onAgyRetry = null;
221
+ this.spawnImpl = spawnImpl;
222
+ this.onSessionUpdate = onSessionUpdate;
223
+ this.onUnexpectedExit = onUnexpectedExit;
224
+ this.proc = null;
225
+ this.initPromise = null;
226
+ this.nextId = 1;
227
+ this.pendingRpc = new Map();
228
+ this.buffer = '';
229
+ this.closing = false;
230
+ }
231
+
232
+ async ensureStarted() {
233
+ if (this.initPromise) return this.initPromise;
234
+ this.closing = false;
235
+ this.initPromise = this._start();
236
+ try {
237
+ return await this.initPromise;
238
+ } catch (error) {
239
+ this.initPromise = null;
240
+ throw error;
241
+ }
242
+ }
243
+
244
+ async _start() {
245
+ const cmd = process.platform === 'win32' ? 'agy.exe' : 'agy';
246
+ // agy retries Google 429s inside itself and tells the ACP client nothing; its own log does say it.
247
+ const args = ['acp', '--stdio', '--include-default-customizations=false'];
248
+ if (this.logFile) {
249
+ try { fs.writeFileSync(this.logFile, ''); this.logOffset = 0; args.push('--log-file', this.logFile); } catch { /* no log, no retry notes */ }
250
+ clearInterval(this.logTimer);
251
+ this.logTimer = setInterval(() => this._readLog(), 1000);
252
+ this.logTimer.unref?.();
253
+ }
254
+ const proc = this.spawnImpl(cmd, args, {
255
+ stdio: ['pipe', 'pipe', 'pipe'],
256
+ windowsHide: true
257
+ });
258
+ this.proc = proc;
259
+ this.buffer = '';
260
+
261
+ proc.stdout.on('data', chunk => this._onStdout(chunk));
262
+ proc.stderr.on('data', chunk => {
263
+ const text = chunk.toString().trim();
264
+ if (text) console.error(`⚠️ agy acp stderr: ${text.slice(0, 300)}`);
265
+ });
266
+ proc.on('error', error => { dbg('proc error', error.message); this._handleExit(error); });
267
+ proc.on('exit', (code, signal) => {
268
+ dbg('proc exit', code, signal);
269
+ if (!this.closing) {
270
+ this._handleExit(new Error(`agy acp exited (${code ?? signal ?? 'unknown'})`));
271
+ }
272
+ });
273
+
274
+ dbg('sending initialize');
275
+ return this.request('initialize', { protocolVersion: 1, clientCapabilities: {} }, 45000);
276
+ }
277
+
278
+ _readLog() {
279
+ let text = '';
280
+ try {
281
+ const size = fs.statSync(this.logFile).size;
282
+ if (size < this.logOffset) this.logOffset = 0;
283
+ if (size === this.logOffset) return;
284
+ const fd = fs.openSync(this.logFile, 'r');
285
+ const buf = Buffer.alloc(Math.min(size - this.logOffset, 1 << 20));
286
+ fs.readSync(fd, buf, 0, buf.length, this.logOffset);
287
+ fs.closeSync(fd);
288
+ this.logOffset += buf.length;
289
+ text = buf.toString('utf8');
290
+ } catch {
291
+ return;
292
+ }
293
+ for (const info of parseAgyRetries(text)) this.onAgyRetry?.(info);
294
+ }
295
+
296
+ _handleExit(error) {
297
+ this.proc = null;
298
+ this.initPromise = null;
299
+ for (const [id, entry] of this.pendingRpc) {
300
+ clearTimeout(entry.timer);
301
+ entry.reject(error);
302
+ this.pendingRpc.delete(id);
303
+ }
304
+ this.onUnexpectedExit?.(error);
305
+ }
306
+
307
+ _onStdout(chunk) {
308
+ this.buffer += chunk.toString();
309
+ const lines = this.buffer.split(/\r?\n/);
310
+ this.buffer = lines.pop();
311
+ for (const line of lines) {
312
+ if (!line.trim()) continue;
313
+ let msg;
314
+ try {
315
+ msg = JSON.parse(line);
316
+ } catch {
317
+ continue;
318
+ }
319
+ if (msg.id != null && (msg.result !== undefined || msg.error !== undefined)) {
320
+ const entry = this.pendingRpc.get(msg.id);
321
+ if (!entry) continue;
322
+ this.pendingRpc.delete(msg.id);
323
+ clearTimeout(entry.timer);
324
+ if (msg.error) {
325
+ const err = new Error(msg.error.message || JSON.stringify(msg.error));
326
+ err.code = msg.error.code;
327
+ err.data = msg.error.data;
328
+ entry.reject(err);
329
+ } else {
330
+ entry.resolve(msg.result);
331
+ }
332
+ continue;
333
+ }
334
+ if (msg.method === 'session/update') {
335
+ const u = msg.params?.update?.sessionUpdate;
336
+ if (u && !['available_commands_update', 'config_option_update'].includes(u)) {
337
+ dbg('update', u, msg.params?.update?.toolCall?.name || msg.params?.update?.name || '');
338
+ }
339
+ this.onSessionUpdate?.(msg.params);
340
+ } else if (msg.method === 'session/request_permission' && msg.id != null) {
341
+ dbg('permission_req', msg.params?.toolCall?.name);
342
+ this._handlePermissionRequest(msg);
343
+ }
344
+ }
345
+ }
346
+
347
+ _handlePermissionRequest(msg) {
348
+ const toolName = msg.params?.toolCall?.name || '';
349
+ const allowOption = msg.params?.options?.find(o => o.kind?.startsWith('allow')) || msg.params?.options?.[0];
350
+ const outcome = toolName.startsWith('mcp_cc_') && allowOption
351
+ ? { outcome: 'selected', optionId: allowOption.optionId }
352
+ : { outcome: 'cancelled' };
353
+ this._send({ jsonrpc: '2.0', id: msg.id, result: { outcome } });
354
+ }
355
+
356
+ _send(payload) {
357
+ if (!this.proc?.stdin?.writable) throw new Error('agy acp process is not running');
358
+ this.proc.stdin.write(`${JSON.stringify(payload)}\n`);
359
+ }
360
+
361
+ async request(method, params, timeoutMs = REQUEST_TIMEOUT_MS) {
362
+ if (method !== 'initialize') await this.ensureStarted();
363
+ const id = this.nextId++;
364
+ return new Promise((resolve, reject) => {
365
+ const timer = setTimeout(() => {
366
+ this.pendingRpc.delete(id);
367
+ reject(new Error(`agy acp ${method} timed out after ${Math.round(timeoutMs / 1000)}s`));
368
+ }, timeoutMs);
369
+ this.pendingRpc.set(id, { resolve, reject, timer });
370
+ try {
371
+ this._send({ jsonrpc: '2.0', id, method, params });
372
+ } catch (error) {
373
+ clearTimeout(timer);
374
+ this.pendingRpc.delete(id);
375
+ reject(error);
376
+ }
377
+ });
378
+ }
379
+
380
+ notify(method, params) {
381
+ if (!this.proc?.stdin?.writable) return;
382
+ this._send({ jsonrpc: '2.0', method, params });
383
+ }
384
+
385
+ // A long-lived agy that signed in while the network was down keeps answering "Authentication required"
386
+ // (2026-11-28: every turn failed for an hour while a fresh agy worked in 3 s). A new process signs in again.
387
+ restart(reason = new Error('agy acp restarted')) {
388
+ this.close();
389
+ for (const [id, entry] of this.pendingRpc) {
390
+ clearTimeout(entry.timer);
391
+ entry.reject(reason);
392
+ this.pendingRpc.delete(id);
393
+ }
394
+ this.closing = false;
395
+ }
396
+
397
+ close() {
398
+ this.closing = true;
399
+ if (this.proc) {
400
+ try { this.proc.kill(); } catch { /* ignore */ }
401
+ this.proc = null;
402
+ }
403
+ this.initPromise = null;
404
+ }
405
+ }
406
+
407
+ function createAgyBridge({ port, proxyKey, labsDir, config, client = null } = {}) {
408
+ const sessionsByMcpId = new Map();
409
+ const sessionsByThread = new Map();
410
+ const usageFile = path.join(labsDir, 'agy-usage.jsonl');
411
+
412
+ const acp = client || new AgyAcpClient({ logFile: path.join(labsDir, 'agy-acp.log') });
413
+ acp.onAgyRetry = info => noteRetry(info);
414
+ acp.onSessionUpdate = params => handleSessionUpdate(params);
415
+ acp.onUnexpectedExit = error => retireAllSessions(error);
416
+
417
+ // Errors a fresh agy process cures: stale sign-in, a hung or dead process.
418
+ const RECOVERABLE = /Authentication required|not authenticated|unauthori[sz]ed|timed out|not running|exited/i;
419
+ let lastRestart = 0;
420
+ // One agy process serves every open labs window. Restarting it while another window's turn runs killed that turn
421
+ // (2026-11-28: "agy acp exited (SIGTERM)"), so a restart waits until no other prompt is in flight.
422
+ function safeRestart(reason, keep = null) {
423
+ if (typeof acp.restart !== 'function') return false;
424
+ for (const other of sessionsByMcpId.values()) {
425
+ if (other !== keep && other.promptInFlight) return false;
426
+ }
427
+ acp.restart(reason);
428
+ return true;
429
+ }
430
+ async function newAcpSession(params) {
431
+ try {
432
+ return await acp.request('session/new', params, SESSION_NEW_TIMEOUT_MS);
433
+ } catch (err) {
434
+ if (!RECOVERABLE.test(err.message || '') || Date.now() - lastRestart < 10000) throw err;
435
+ lastRestart = Date.now();
436
+ console.error(`⚠️ agy acp: ${err.message}; restarting agy and retrying once`);
437
+ // Sessions of the old process die with it; the one being made now has no agy id yet and stays.
438
+ for (const old of [...sessionsByMcpId.values()]) if (old.acpSessionId) retireSession(old, err);
439
+ if (typeof acp.restart === "function") acp.restart(err); // a broken sign-in breaks every session anyway
440
+ return acp.request('session/new', params, SESSION_NEW_TIMEOUT_MS);
441
+ }
442
+ }
443
+
444
+ function findSessionByAcpId(acpSessionId) {
445
+ for (const s of sessionsByMcpId.values()) {
446
+ if (s.acpSessionId === acpSessionId) return s;
447
+ }
448
+ return null;
449
+ }
450
+
451
+ function retireSession(session, reason = new Error('Session closed')) {
452
+ if (!session) return;
453
+ sessionsByMcpId.delete(session.mcpId);
454
+ if (sessionsByThread.get(session.threadKey) === session) {
455
+ sessionsByThread.delete(session.threadKey);
456
+ }
457
+ if (session.promptInFlight && session.acpSessionId) {
458
+ acp.notify('session/cancel', { sessionId: session.acpSessionId });
459
+ }
460
+ for (const held of session.heldCalls.values()) {
461
+ clearInterval(held.keepalive);
462
+ try {
463
+ if (held.sse) {
464
+ held.res.write(`event: message\ndata: ${JSON.stringify({ jsonrpc: '2.0', id: held.rpcId, result: { content: [{ type: 'text', text: reason.message }], isError: true } })}\n\n`);
465
+ held.res.end();
466
+ } else {
467
+ held.res.status(200).json({ jsonrpc: '2.0', id: held.rpcId, result: { content: [{ type: 'text', text: reason.message }], isError: true } });
468
+ }
469
+ } catch {
470
+ // Socket may already be closed.
471
+ }
472
+ }
473
+ session.heldCalls.clear();
474
+ if (session.activeTurn && !session.activeTurn.resolved) {
475
+ clearTimeout(session.activeTurn.settleTimer);
476
+ session.activeTurn.resolved = true;
477
+ session.activeTurn.reject(reason);
478
+ }
479
+ session.activeTurn = null;
480
+ if (session.acpSessionId) {
481
+ acp.request('session/close', { sessionId: session.acpSessionId }, 5000).catch(() => {});
482
+ }
483
+ }
484
+
485
+ function retireAllSessions(error) {
486
+ for (const session of [...sessionsByMcpId.values()]) {
487
+ retireSession(session, error);
488
+ }
489
+ }
490
+
491
+ // Shows agy's hidden retries inside the open turn, so Claude Code never sits silent, and keeps the silence
492
+ // watchdog from killing a turn that is only waiting on Google.
493
+ function noteRetry({ attempt, reason, waitSeconds }) {
494
+ console.error(`⏳ agy: ${reason}, try ${attempt} failed; agy retries in ${waitSeconds}s`);
495
+ for (const session of sessionsByMcpId.values()) {
496
+ const turn = session.activeTurn;
497
+ if (!turn || turn.resolved || !session.promptInFlight) continue;
498
+ session.lastActivity = Date.now();
499
+ const note = `[agy] ${reason}: try ${attempt} failed, retrying in ${waitSeconds}s...
500
+ `;
501
+ turn.thinking += note;
502
+ turn.onThinking?.(note);
503
+ }
504
+ }
505
+
506
+ function settleTurn(session) {
507
+ const turn = session.activeTurn;
508
+ if (!turn || turn.resolved) return;
509
+ turn.resolved = true;
510
+ clearTimeout(turn.settleTimer);
511
+ session.activeTurn = null;
512
+ turn.resolve({
513
+ text: turn.text,
514
+ thinking: turn.thinking,
515
+ toolCalls: turn.toolCalls,
516
+ usage: turn.usage
517
+ });
518
+ }
519
+
520
+ function handleSessionUpdate(params) {
521
+ const session = findSessionByAcpId(params?.sessionId);
522
+ if (!session) return;
523
+ const update = params?.update;
524
+ if (!update) return;
525
+ session.lastActivity = Date.now();
526
+ const turn = session.activeTurn;
527
+ if (update.sessionUpdate === 'agent_thought_chunk' && update.content?.text) {
528
+ if (turn && !turn.resolved) {
529
+ turn.thinking += update.content.text;
530
+ turn.onThinking?.(update.content.text);
531
+ }
532
+ } else if (update.sessionUpdate === 'agent_message_chunk' && update.content?.text) {
533
+ if (turn && !turn.resolved) {
534
+ turn.text += update.content.text;
535
+ turn.onText?.(update.content.text);
536
+ }
537
+ } else if (update.sessionUpdate === 'usage_update' && typeof update.used === 'number') {
538
+ session.contextUsed = update.used;
539
+ }
540
+ }
541
+
542
+ function writeHeldCallResponse(held, resultPayload) {
543
+ clearInterval(held.keepalive);
544
+ const rpc = { jsonrpc: '2.0', id: held.rpcId, result: resultPayload };
545
+ if (held.sse) {
546
+ held.res.write(`event: message\ndata: ${JSON.stringify(rpc)}\n\n`);
547
+ held.res.end();
548
+ } else {
549
+ held.res.status(200).json(rpc);
550
+ }
551
+ }
552
+
553
+ function handleMcpHttp(req, res) {
554
+ if (req.method !== 'POST') return res.status(405).json({ error: 'Method Not Allowed' });
555
+ const session = sessionsByMcpId.get(req.params.mcpId);
556
+ if (!session) return res.status(404).json({ jsonrpc: '2.0', error: { code: -32000, message: 'Unknown MCP session' } });
557
+
558
+ const msg = req.body || {};
559
+ dbg('mcp', req.method, msg.method || '', msg.params?.name || '');
560
+ if (msg.method === 'server/discover') {
561
+ return res.json({ jsonrpc: '2.0', id: msg.id, result: {} });
562
+ }
563
+ if (msg.method === 'initialize') {
564
+ return res.json({
565
+ jsonrpc: '2.0',
566
+ id: msg.id,
567
+ result: {
568
+ protocolVersion: msg.params?.protocolVersion || '2025-11-25',
569
+ capabilities: { tools: {} },
570
+ serverInfo: { name: 'cc', version: '1.0.0' }
571
+ }
572
+ });
573
+ }
574
+ if (msg.method === 'notifications/initialized' || msg.method === 'notifications/roots/list_changed') {
575
+ return res.status(202).end();
576
+ }
577
+ if (msg.method === 'tools/list') {
578
+ return res.json({ jsonrpc: '2.0', id: msg.id, result: { tools: session.mcpTools } });
579
+ }
580
+ if (msg.method === 'tools/call') {
581
+ const mcpName = msg.params?.name || '';
582
+ const claudeName = session.toolNameMap.get(mcpName) || mcpName;
583
+ const input = normalizeToolInput(msg.params?.arguments || {});
584
+ const toolUseId = `call_${randomUUID().replace(/-/g, '').slice(0, 20)}`;
585
+ const acceptSse = String(req.get('accept') || '').includes('text/event-stream');
586
+
587
+ let keepalive = null;
588
+ if (acceptSse) {
589
+ res.status(200);
590
+ res.set({ 'Content-Type': 'text/event-stream; charset=utf-8', 'Cache-Control': 'no-cache', Connection: 'keep-alive' });
591
+ res.write(': keepalive\n\n');
592
+ keepalive = setInterval(() => {
593
+ if (!res.writableEnded) res.write(': keepalive\n\n');
594
+ }, MCP_KEEPALIVE_MS);
595
+ }
596
+
597
+ const held = { res, rpcId: msg.id, sse: acceptSse, keepalive };
598
+ session.heldCalls.set(toolUseId, held);
599
+ res.on('close', () => {
600
+ clearInterval(keepalive);
601
+ session.heldCalls.delete(toolUseId);
602
+ });
603
+
604
+ const toolCall = { id: toolUseId, name: claudeName, input };
605
+ console.log(`🔧 agy -> ${claudeName} ${JSON.stringify(input).slice(0, 160)}`);
606
+
607
+ const turn = session.activeTurn;
608
+ if (turn && !turn.resolved) {
609
+ turn.toolCalls.push(toolCall);
610
+ clearTimeout(turn.settleTimer);
611
+ turn.settleTimer = setTimeout(() => settleTurn(session), MCP_SETTLE_MS);
612
+ } else {
613
+ // Arrived slightly after an earlier parallel batch settled; deliver on the next turn.
614
+ session.queuedToolCalls.push(toolCall);
615
+ }
616
+ return;
617
+ }
618
+ return res.json({ jsonrpc: '2.0', id: msg.id, result: {} });
619
+ }
620
+
621
+ function mount(app) {
622
+ app.all('/agy-mcp/:mcpId', handleMcpHttp);
623
+ }
624
+
625
+ async function configureSession(acpSessionId, modelId, effort, created = null) {
626
+ const modelOpt = created?.configOptions?.find(c => c.id === 'model');
627
+ if (!modelOpt || modelOpt.currentValue !== modelId) {
628
+ try {
629
+ await acp.request('session/set_config_option', { sessionId: acpSessionId, configId: 'model', value: modelId }, 30000);
630
+ } catch (err) {
631
+ const current = created?.models?.currentModelId || '';
632
+ if (!current.startsWith(modelId)) throw err;
633
+ }
634
+ }
635
+ if (agyModelInfo(modelId).hasEffort) {
636
+ const thoughtOpt = created?.configOptions?.find(c => c.id === 'thought_level');
637
+ const wanted = agyEffortFor(effort);
638
+ if (!thoughtOpt || thoughtOpt.currentValue !== wanted) {
639
+ await acp.request('session/set_config_option', {
640
+ sessionId: acpSessionId,
641
+ configId: 'thought_level',
642
+ value: wanted
643
+ }, 30000).catch(() => {});
644
+ }
645
+ }
646
+ }
647
+
648
+ async function runSideTurn({ modelId, body, onText, onThinking, signal }) {
649
+ const mcpId = `side_${randomUUID().slice(0, 12)}`;
650
+ const sideModel = config.sideModel && AGY_MODELS[config.sideModel] ? config.sideModel : (AGY_MODELS['gemini-3.8-flash'] ? 'gemini-3.8-flash' : modelId);
651
+ const session = {
652
+ mcpId,
653
+ threadKey: mcpId,
654
+ acpSessionId: null,
655
+ heldCalls: new Map(),
656
+ queuedToolCalls: [],
657
+ activeTurn: null,
658
+ contextUsed: 0
659
+ };
660
+ sessionsByMcpId.set(mcpId, session);
661
+ try {
662
+ const created = await newAcpSession({
663
+ cwd: process.cwd(),
664
+ mcpServers: [],
665
+ _meta: { antigravity: { systemPrompt: { append: systemTextOf(body.system) || 'You are a helpful assistant.' } } }
666
+ });
667
+ session.acpSessionId = created.sessionId;
668
+ await configureSession(created.sessionId, sideModel, 'low', created);
669
+
670
+ const latest = extractLatestUserContent(body.messages || []);
671
+ const assistantIdx = (body.messages || []).findLastIndex(m => m.role === 'assistant');
672
+ const history = assistantIdx >= 0 ? body.messages.slice(0, assistantIdx + 1) : [];
673
+ const promptBlocks = buildAcpPromptBlocks({ text: latest.text, images: latest.images, history });
674
+
675
+ return await new Promise((resolve, reject) => {
676
+ const turn = { text: '', thinking: '', toolCalls: [], usage: {}, settleTimer: null, resolved: false, resolve, reject, onText, onThinking };
677
+ session.activeTurn = turn;
678
+ const onAbort = () => {
679
+ acp.notify('session/cancel', { sessionId: session.acpSessionId });
680
+ if (!turn.resolved) {
681
+ turn.resolved = true;
682
+ reject(new Error('Request aborted'));
683
+ }
684
+ };
685
+ signal?.addEventListener('abort', onAbort, { once: true });
686
+ acp.request('session/prompt', { sessionId: session.acpSessionId, prompt: promptBlocks }).then(result => {
687
+ signal?.removeEventListener('abort', onAbort);
688
+ turn.usage = result?.usage || {};
689
+ settleTurn(session);
690
+ }, err => {
691
+ signal?.removeEventListener('abort', onAbort);
692
+ if (!turn.resolved) {
693
+ turn.resolved = true;
694
+ reject(err);
695
+ }
696
+ });
697
+ });
698
+ } finally {
699
+ retireSession(session);
700
+ }
701
+ }
702
+
703
+ function cleanAgySchema(schema) {
704
+ const out = { ...schema };
705
+ delete out.description;
706
+ if (out.type === 'integer') out.type = 'number';
707
+ if (out.properties && typeof out.properties === 'object') {
708
+ const cleanProps = {};
709
+ for (const [k, v] of Object.entries(out.properties)) {
710
+ // Antigravity ACP drops tools with flag-like property keys (e.g. Grep's -A/-B/-C).
711
+ if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(k)) continue;
712
+ cleanProps[k] = cleanAgySchema(v);
713
+ }
714
+ out.properties = cleanProps;
715
+ if (Array.isArray(out.required)) {
716
+ out.required = out.required.filter(k => k in cleanProps);
717
+ if (!out.required.length) delete out.required;
718
+ }
719
+ }
720
+ if (out.items && typeof out.items === 'object') {
721
+ out.items = cleanAgySchema(out.items);
722
+ }
723
+ return out;
724
+ }
725
+
726
+ function buildToolSpec(tools) {
727
+ const toolNameMap = new Map();
728
+ const mcpTools = tools
729
+ .filter(tool => tool.name !== 'DeferredToolPlaceholder')
730
+ .map(tool => {
731
+ const name = agyToolName(tool.name);
732
+ toolNameMap.set(name, tool.name);
733
+ // Antigravity ACP drops MCP tools with long/multiline descriptions or non-identifier schema keys.
734
+ const firstLine = String(tool.description || tool.name).split(/\r?\n/)[0].replace(/\s+/g, ' ').trim();
735
+ const description = firstLine.length > MAX_TOOL_DESC_CHARS ? `${firstLine.slice(0, MAX_TOOL_DESC_CHARS)}...` : firstLine;
736
+ return {
737
+ name,
738
+ description,
739
+ inputSchema: cleanAgySchema(sanitizeSchema(tool.input_schema))
740
+ };
741
+ });
742
+ const signature = tools.map(t => t.name).sort().join(',');
743
+ return { mcpTools, toolNameMap, signature };
744
+ }
745
+
746
+ async function runTurn({ req, modelId, effort, body, onText, onThinking, signal }) {
747
+ const tools = body.tools || [];
748
+ if (tools.length === 0) {
749
+ return runSideTurn({ modelId, body, onText, onThinking, signal });
750
+ }
751
+
752
+ const messages = body.messages || [];
753
+ const latest = extractLatestUserContent(messages);
754
+ const priorContent = lastAssistantContent(messages);
755
+ const priorReply = priorContent ? replySignature(priorContent) : null;
756
+ const sessionIdHeader = req.get('x-labs-session-id') || body.metadata?.session_id || 'default';
757
+ const threadId = isValidSessionId(sessionIdHeader) ? createThreadId(sessionIdHeader, messages) : createThreadId('anon', messages);
758
+ const threadKey = `${modelId}:${agyEffortFor(effort)}:${threadId}`;
759
+ const { mcpTools, toolNameMap, signature: toolSig } = buildToolSpec(tools);
760
+
761
+ const existing = sessionsByThread.get(threadKey);
762
+ const allResultsHeld = existing && latest.toolResults.length > 0
763
+ && latest.toolResults.every(r => existing.heldCalls.has(r.toolUseId));
764
+ const canContinueTools = Boolean(
765
+ existing
766
+ && existing.promptInFlight
767
+ && existing.lastReply === priorReply
768
+ && allResultsHeld
769
+ && existing.toolSig === toolSig
770
+ );
771
+ const canContinueFollowup = Boolean(
772
+ existing
773
+ && !existing.promptInFlight
774
+ && latest.toolResults.length === 0
775
+ && existing.lastReply === priorReply
776
+ && existing.toolSig === toolSig
777
+ && existing.acpSessionId
778
+ );
779
+
780
+ let session = existing;
781
+ let isContinuation = false;
782
+ let isFollowup = false;
783
+
784
+ if (canContinueTools) {
785
+ isContinuation = true;
786
+ } else if (canContinueFollowup) {
787
+ isFollowup = true;
788
+ } else {
789
+ if (existing) retireSession(existing, new Error('Superseded by new turn'));
790
+ const mcpId = randomUUID();
791
+ session = {
792
+ mcpId,
793
+ threadKey,
794
+ modelId,
795
+ effort: agyEffortFor(effort),
796
+ toolSig,
797
+ mcpTools,
798
+ toolNameMap,
799
+ acpSessionId: null,
800
+ heldCalls: new Map(),
801
+ queuedToolCalls: [],
802
+ activeTurn: null,
803
+ promptInFlight: false,
804
+ lastReply: null,
805
+ contextUsed: 0
806
+ };
807
+ sessionsByMcpId.set(mcpId, session);
808
+ sessionsByThread.set(threadKey, session);
809
+
810
+ const cwd = req.get('x-labs-cwd') || process.cwd();
811
+ dbg('session/new start', { modelId, tools: mcpTools.length, sysLen: buildSystemAppend(body.system).length });
812
+ try {
813
+ const newParams = {
814
+ cwd,
815
+ mcpServers: [{
816
+ type: 'http',
817
+ name: 'cc',
818
+ url: `http://127.0.0.1:${port}/agy-mcp/${mcpId}`,
819
+ headers: [{ name: 'x-api-key', value: proxyKey }]
820
+ }],
821
+ _meta: { antigravity: { systemPrompt: { append: buildSystemAppend(body.system) } } }
822
+ };
823
+ let created = await newAcpSession(newParams);
824
+ if (Array.isArray(created?.models?.availableModels) && created.models.availableModels.length === 0) {
825
+ acp.request('session/close', { sessionId: created.sessionId }, 5000).catch(() => {});
826
+ await new Promise(r => setTimeout(r, 1500));
827
+ created = await newAcpSession(newParams);
828
+ }
829
+ dbg('session/new ok', created.sessionId);
830
+ session.acpSessionId = created.sessionId;
831
+ await configureSession(created.sessionId, modelId, effort, created);
832
+ dbg('configureSession ok', created.sessionId);
833
+ } catch (err) {
834
+ retireSession(session, err);
835
+ throw err;
836
+ }
837
+ }
838
+
839
+ const result = await new Promise((resolve, reject) => {
840
+ const turn = {
841
+ text: '',
842
+ thinking: '',
843
+ toolCalls: [],
844
+ usage: {},
845
+ settleTimer: null,
846
+ resolved: false,
847
+ resolve,
848
+ reject,
849
+ onText,
850
+ onThinking
851
+ };
852
+ session.activeTurn = turn;
853
+ session.lastActivity = Date.now();
854
+
855
+ // agy retries a 429 inside itself and sends nothing meanwhile: Claude Code showed "thinking" with no
856
+ // thought, no tool and no error for minutes (2026-11-28). Silence this long is now an error Claude Code shows.
857
+ const silence = setInterval(() => {
858
+ if (turn.resolved) return clearInterval(silence);
859
+ if (Date.now() - session.lastActivity < AGY_SILENCE_MS) return;
860
+ clearInterval(silence);
861
+ const err = new Error(`agy sent nothing for ${AGY_SILENCE_MS / 1000}s (usually a quota limit it keeps retrying; check: agy acp --login)`);
862
+ retireSession(session, err);
863
+ safeRestart(err);
864
+ }, 1000);
865
+ silence.unref?.();
866
+
867
+ const onAbort = () => {
868
+ acp.notify('session/cancel', { sessionId: session.acpSessionId });
869
+ if (!turn.resolved) {
870
+ turn.resolved = true;
871
+ clearTimeout(turn.settleTimer);
872
+ session.activeTurn = null;
873
+ reject(new Error('Request aborted'));
874
+ }
875
+ };
876
+ signal?.addEventListener('abort', onAbort, { once: true });
877
+
878
+ if (isContinuation) {
879
+ for (const [index, toolResult] of latest.toolResults.entries()) {
880
+ const held = session.heldCalls.get(toolResult.toolUseId);
881
+ session.heldCalls.delete(toolResult.toolUseId);
882
+ const rawBlock = messages.findLast?.(m => m.role === 'user')
883
+ ?.content?.find?.(b => b.type === 'tool_result' && b.tool_use_id === toolResult.toolUseId);
884
+ const content = mcpContentFromToolResult(rawBlock ? rawBlock.content : toolResult.content);
885
+ if (index === 0 && latest.text) {
886
+ content.push({ type: 'text', text: `\n[User/system note]\n${latest.text}` });
887
+ }
888
+ writeHeldCallResponse(held, { content, isError: Boolean(toolResult.isError) });
889
+ }
890
+ if (session.queuedToolCalls.length) {
891
+ turn.toolCalls.push(...session.queuedToolCalls.splice(0));
892
+ turn.settleTimer = setTimeout(() => {
893
+ signal?.removeEventListener('abort', onAbort);
894
+ settleTurn(session);
895
+ }, MCP_SETTLE_MS);
896
+ }
897
+ // Wait for either the next MCP tools/call batch or the active session/prompt promise to complete.
898
+ session.promptDone?.then(promptRes => {
899
+ signal?.removeEventListener('abort', onAbort);
900
+ if (session.activeTurn === turn) {
901
+ turn.usage = promptRes?.usage || {};
902
+ settleTurn(session);
903
+ }
904
+ }, err => {
905
+ signal?.removeEventListener('abort', onAbort);
906
+ if (session.activeTurn === turn && !turn.resolved) {
907
+ turn.resolved = true;
908
+ clearTimeout(turn.settleTimer);
909
+ session.activeTurn = null;
910
+ reject(err);
911
+ }
912
+ });
913
+ return;
914
+ }
915
+
916
+ const assistantIdx = messages.findLastIndex(m => m.role === 'assistant');
917
+ const history = !isFollowup && assistantIdx >= 0 ? messages.slice(0, assistantIdx + 1) : [];
918
+ const promptBlocks = buildAcpPromptBlocks({
919
+ text: latest.text,
920
+ images: latest.images,
921
+ history,
922
+ unmatchedResults: latest.toolResults,
923
+ hasTools: tools.length > 0
924
+ });
925
+
926
+ dbg('session/prompt start', { sessionId: session.acpSessionId, chars: promptBlocks[0]?.text?.length || 0 });
927
+ session.promptInFlight = true;
928
+ session.promptDone = acp.request('session/prompt', {
929
+ sessionId: session.acpSessionId,
930
+ prompt: promptBlocks
931
+ }).then(promptRes => {
932
+ dbg('session/prompt ok', promptRes?.stopReason);
933
+ session.promptInFlight = false;
934
+ signal?.removeEventListener('abort', onAbort);
935
+ if (session.activeTurn === turn) {
936
+ turn.usage = promptRes?.usage || {};
937
+ settleTurn(session);
938
+ }
939
+ return promptRes;
940
+ }, err => {
941
+ dbg('session/prompt err', err.message);
942
+ session.promptInFlight = false;
943
+ signal?.removeEventListener('abort', onAbort);
944
+ if (session.activeTurn === turn && !turn.resolved) {
945
+ turn.resolved = true;
946
+ clearTimeout(turn.settleTimer);
947
+ session.activeTurn = null;
948
+ reject(err);
949
+ }
950
+ throw err;
951
+ });
952
+ // Prevent unhandled rejection when turn settles early on tool_use and promptDone finishes on a later turn.
953
+ session.promptDone.catch(() => {});
954
+ });
955
+
956
+ // agy says "quota reached" as a plain reply. Claude Code retried a 429 ten times, so the window looked
957
+ // stuck for minutes; one clear line with the reset time shows at once instead.
958
+ const quota = !result.toolCalls.length && quotaNotice(result.text, modelId);
959
+ if (quota) {
960
+ console.error(`🚨 agy ${modelId}: ${result.text.trim()}`);
961
+ retireSession(session, new Error('quota reached'));
962
+ // A new process picks up a new sign-in (agy acp --login) on the very next turn.
963
+ safeRestart(new Error('quota reached'));
964
+ return { text: quota, thinking: '', toolCalls: [], usage: result.usage || {}, contextUsed: session.contextUsed };
965
+ }
966
+ if (!result.toolCalls.length && /^⚠\s*(failed to construct executor:|RESOURCE_EXHAUSTED|.*\(code 429\))/i.test(result.text.trim())) {
967
+ const err = new Error(result.text.trim());
968
+ if (/RESOURCE_EXHAUSTED|code 429/i.test(result.text)) err.status = 429;
969
+ retireSession(session, err);
970
+ safeRestart(err);
971
+ throw err;
972
+ }
973
+ const assistantContent = [
974
+ ...(result.text ? [{ type: 'text', text: result.text }] : []),
975
+ ...result.toolCalls.map(t => ({ type: 'tool_use', id: t.id, name: t.name, input: t.input }))
976
+ ];
977
+ session.lastReply = replySignature(assistantContent);
978
+ return { ...result, contextUsed: session.contextUsed };
979
+ }
980
+
981
+ function logUsage(entry) {
982
+ try {
983
+ fs.mkdirSync(labsDir, { recursive: true });
984
+ fs.appendFileSync(usageFile, `${JSON.stringify({ at: new Date().toISOString(), ...entry })}\n`);
985
+ } catch {
986
+ // Non-fatal logging error.
987
+ }
988
+ }
989
+
990
+ function warmup() {
991
+ if (hasAgyCli()) acp.ensureStarted().catch(() => {});
992
+ }
993
+
994
+ function shutdown() {
995
+ retireAllSessions(new Error('Proxy shutting down'));
996
+ acp.close();
997
+ }
998
+
999
+ return { mount, runTurn, logUsage, warmup, shutdown, sessionsByMcpId, sessionsByThread };
1000
+ }
1001
+
1002
+ module.exports = {
1003
+ AGY_MODELS,
1004
+ AGY_PREFIX,
1005
+ AgyAcpClient,
1006
+ agyEffortFor,
1007
+ agyModelId,
1008
+ agyModelInfo,
1009
+ agyToolName,
1010
+ buildSystemAppend,
1011
+ createAgyBridge,
1012
+ hasAgyCli,
1013
+ isAgyFallbackModel,
1014
+ parseAgyRetries,
1015
+ quotaNotice
1016
+ };