@hexdecimal16/nexo 0.4.14 → 0.4.16

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,768 @@
1
+ import { spawn } from "node:child_process";
2
+ import { rmSync } from "node:fs";
3
+ import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { createInterface } from "node:readline";
7
+ import { createAssistantMessageEventStream, createProvider, getCurrentSystemPrompt, getCurrentTools, } from "@earendil-works/pi-ai";
8
+ import { getBuiltinModels } from "@earendil-works/pi-ai/providers/all";
9
+ import { renderTranscriptParts } from "./claude-p.js";
10
+ import { parseReply } from "./kiro-p.js";
11
+ import { ReplyTextExtractor } from "./reply-text.js";
12
+ /** Provider id: models are referenced as `agy-p/<model>`, e.g. `agy-p/gemini-4-neon` or `agy-p/claude-sonnet-5-5`. */
13
+ export const AGY_P_PROVIDER = "agy-p";
14
+ const AGY_P_API = "agy-p";
15
+ /** Environment variable naming the Antigravity CLI executable; `agy` on the PATH otherwise. */
16
+ export const AGY_P_COMMAND_ENV = "NEXO_AGY_P_COMMAND";
17
+ /** Environment variable overriding how long a turn may stay silent before it is cancelled (milliseconds). */
18
+ export const AGY_P_IDLE_ENV = "NEXO_AGY_P_IDLE_MS";
19
+ const IDLE_MS_DEFAULT = 120_000;
20
+ /** How long a cancelled turn gets to settle before the whole process is considered stuck and killed. */
21
+ const CANCEL_GRACE_MS = 5_000;
22
+ const AGENT_NAME = "nexo";
23
+ /** `thought_level` values in ascending order; pi's `minimal` maps to `low`, and `max` maps to the model's highest level. */
24
+ const THOUGHT_LEVELS = ["low", "medium", "high", "xhigh"];
25
+ const isWindows = process.platform === "win32";
26
+ const liveGroups = new Set();
27
+ const liveDirs = new Set();
28
+ let exitHandlerRegistered = false;
29
+ function registerExitHandler() {
30
+ if (exitHandlerRegistered)
31
+ return;
32
+ exitHandlerRegistered = true;
33
+ process.on("exit", () => {
34
+ for (const pgid of liveGroups) {
35
+ try {
36
+ process.kill(-pgid, "SIGKILL");
37
+ }
38
+ catch {
39
+ // the process group already exited
40
+ }
41
+ }
42
+ for (const dir of liveDirs)
43
+ rmSync(dir, { recursive: true, force: true });
44
+ });
45
+ }
46
+ function killGroup(child) {
47
+ try {
48
+ if (!isWindows && child.pid !== undefined)
49
+ process.kill(-child.pid, "SIGKILL");
50
+ else
51
+ child.kill("SIGKILL");
52
+ }
53
+ catch {
54
+ // the process group already exited
55
+ }
56
+ }
57
+ /** Spawns the server in its own process group; the pipes are unref'd so an idle server never keeps the host alive. */
58
+ function spawnRunner(command) {
59
+ return ({ args, cwd }) => {
60
+ registerExitHandler();
61
+ const child = spawn(command, args, { cwd, stdio: ["pipe", "pipe", "pipe"], detached: !isWindows });
62
+ const pgid = child.pid;
63
+ if (pgid !== undefined && !isWindows)
64
+ liveGroups.add(pgid);
65
+ let stderr = "";
66
+ child.stderr.setEncoding("utf8");
67
+ child.stderr.on("data", (chunk) => {
68
+ if (stderr.length < 16_384)
69
+ stderr += chunk;
70
+ });
71
+ child.stdin.on("error", () => { });
72
+ const exit = new Promise((resolve) => {
73
+ child.on("error", (error) => {
74
+ if (pgid !== undefined)
75
+ liveGroups.delete(pgid);
76
+ resolve({ code: null, stderr: stderr || error.message });
77
+ });
78
+ child.on("close", (code) => {
79
+ if (pgid !== undefined)
80
+ liveGroups.delete(pgid);
81
+ resolve({ code, stderr });
82
+ });
83
+ });
84
+ return {
85
+ write: (line) => {
86
+ child.stdin.write(`${line}\n`);
87
+ },
88
+ lines: createInterface({ input: child.stdout, crlfDelay: Infinity }),
89
+ exit,
90
+ kill: () => killGroup(child),
91
+ hold: (on) => {
92
+ const method = on ? "ref" : "unref";
93
+ child[method]();
94
+ for (const s of [child.stdin, child.stdout, child.stderr])
95
+ s[method]?.();
96
+ },
97
+ };
98
+ };
99
+ }
100
+ /**
101
+ * Antigravity CLI base model ids (the `model` config option in `agy acp`), paired with display name, context window and
102
+ * reasoning support. Effort maps to ACP's `thought_level` option. Antigravity uses account quota rather than API
103
+ * billing, so cost stays zero.
104
+ */
105
+ const AGY_MODELS = [
106
+ ["gemini-4-neon", "Gemini 4 Neon", 1_048_576, true],
107
+ ["gemini-4-carbon", "Gemini 4 Carbon", 1_048_576, true],
108
+ ["gemini-4-argon", "Gemini 4 Argon", 1_048_576, true],
109
+ ["gemini-4-hydrogen", "Gemini 4 Hydrogen", 1_048_576, true],
110
+ ["gemini-3.8-flash", "Gemini 3.8 Flash", 1_048_576, true],
111
+ ["gemini-pro-orchestrator-neon", "Orchestrator (Neon)", 1_048_576, false],
112
+ ["gemini-pro-orchestrator", "Orchestrator (Carbon)", 1_048_576, false],
113
+ ["gemini-pro-orchestrator-argon", "Orchestrator (Argon)", 1_048_576, false],
114
+ ["claude-opus-5-5", "Claude Opus 5.5", 1_000_000, true],
115
+ ["claude-sonnet-5-5", "Claude Sonnet 5.5", 1_000_000, true],
116
+ ["gpt-oss-120b-medium", "GPT-OSS 120B (Medium)", 128_000, false],
117
+ ];
118
+ /** Antigravity's base models, borrowing `maxTokens` from pi-ai's Google/Anthropic catalog where an entry matches. */
119
+ function agyPModels() {
120
+ const builtin = new Map();
121
+ for (const provider of ["google", "anthropic"]) {
122
+ for (const m of getBuiltinModels(provider))
123
+ builtin.set(m.id, m);
124
+ }
125
+ return AGY_MODELS.map(([id, displayName, contextWindow, reasoning]) => {
126
+ const base = builtin.get(id);
127
+ return {
128
+ ...(base ?? { maxTokens: id.startsWith("gemini-") ? 65_536 : 32_000 }),
129
+ id,
130
+ name: `${displayName} (agy)`,
131
+ api: AGY_P_API,
132
+ provider: AGY_P_PROVIDER,
133
+ baseUrl: "",
134
+ reasoning,
135
+ input: ["text", "image"],
136
+ contextWindow,
137
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
138
+ };
139
+ });
140
+ }
141
+ function plainSchema(tool) {
142
+ return JSON.parse(JSON.stringify(tool.parameters));
143
+ }
144
+ /**
145
+ * System-prompt section describing the tools and the JSON reply format. `agy acp` has no structured-output flag, so the
146
+ * format is asked for here and parsed by `parseAgyReply`.
147
+ */
148
+ export function agyToolsSection(tools) {
149
+ const defs = tools.map((t) => JSON.stringify({ name: t.name, description: t.description, parameters: plainSchema(t) })).join("\n");
150
+ return [
151
+ "# Actions",
152
+ "",
153
+ 'Every reply must be exactly one JSON object and nothing else (no prose around it, no code fence): {"text": string, "tool_calls": [{"name": string, "arguments": object}]}.',
154
+ "`text` is what you say to the user (may be empty). `tool_calls` lists actions for the caller to run now, with arguments matching the action's parameters.",
155
+ "The actions below are not tools you can invoke: never call them directly and never invoke any built-in tool (such as `manage_task`), only list actions in `tool_calls`. The caller runs them and sends the results back in the next turn as <tool_result> entries. When you are finished, leave `tool_calls` empty and put the final answer in `text`.",
156
+ "",
157
+ "Available actions, one JSON definition per line:",
158
+ defs,
159
+ ].join("\n");
160
+ }
161
+ let callSeq = 0;
162
+ function toolCallId() {
163
+ callSeq = (callSeq + 1) % 1_000_000;
164
+ return `agy_p_${Date.now().toString(36)}_${callSeq}`;
165
+ }
166
+ /** Parses a tools-turn reply using `parseReply`, assigning `agy_p_*` tool call ids. */
167
+ export function parseAgyReply(raw, tools) {
168
+ const parsed = parseReply(raw, tools);
169
+ if (!parsed)
170
+ return undefined;
171
+ return { text: parsed.text, calls: parsed.calls.map((c) => ({ ...c, id: toolCallId() })) };
172
+ }
173
+ /**
174
+ * Maps nexo's reasoning effort to a `thought_level` value accepted by the active model. When the server reports
175
+ * `configOptions`, models without a `thought_level` option skip it, `max`/`xhigh` clamp to the model's highest level,
176
+ * and an already-active level is skipped.
177
+ */
178
+ export function resolveThoughtLevel(reasoning, configOptions) {
179
+ if (!reasoning)
180
+ return undefined;
181
+ const mapped = reasoning === "minimal" ? "low" : reasoning === "max" ? "xhigh" : reasoning;
182
+ if (!THOUGHT_LEVELS.includes(mapped))
183
+ return undefined;
184
+ if (configOptions === undefined)
185
+ return mapped;
186
+ const opt = configOptions.find((c) => c.id === "thought_level");
187
+ const values = Array.isArray(opt?.options) ? opt.options.map((o) => o?.value).filter((v) => typeof v === "string") : [];
188
+ if (values.length === 0)
189
+ return undefined;
190
+ let target;
191
+ if (values.includes(mapped))
192
+ target = mapped;
193
+ else if (mapped === "xhigh")
194
+ target = [...THOUGHT_LEVELS].reverse().find((v) => values.includes(v));
195
+ else
196
+ return undefined;
197
+ return target && target !== opt?.currentValue ? target : undefined;
198
+ }
199
+ function finiteNonNeg(value) {
200
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0;
201
+ }
202
+ function emptyUsage() {
203
+ return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } };
204
+ }
205
+ /** `agy acp` reports `inputTokens` inclusive of cached tokens (and `outputTokens` inclusive of `thoughtTokens`); cost stays $0. */
206
+ function toUsage(u) {
207
+ if (!u || typeof u !== "object")
208
+ return emptyUsage();
209
+ const cacheRead = finiteNonNeg(u.cachedReadTokens);
210
+ const cacheWrite = finiteNonNeg(u.cachedWriteTokens);
211
+ const input = Math.max(0, finiteNonNeg(u.inputTokens) - cacheRead - cacheWrite);
212
+ const output = finiteNonNeg(u.outputTokens);
213
+ return {
214
+ input,
215
+ output,
216
+ cacheRead,
217
+ cacheWrite,
218
+ totalTokens: input + output + cacheRead + cacheWrite,
219
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
220
+ };
221
+ }
222
+ function addUsage(a, b) {
223
+ return {
224
+ input: a.input + b.input,
225
+ output: a.output + b.output,
226
+ cacheRead: a.cacheRead + b.cacheRead,
227
+ cacheWrite: a.cacheWrite + b.cacheWrite,
228
+ totalTokens: a.totalTokens + b.totalTokens,
229
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
230
+ };
231
+ }
232
+ function parseIdleMs(raw) {
233
+ const value = Number(raw);
234
+ return Number.isFinite(value) && value > 0 ? value : IDLE_MS_DEFAULT;
235
+ }
236
+ /** Formats a JSON-RPC error object, including `data` details when they add context beyond `message`. */
237
+ function rpcErrorMessage(error) {
238
+ const base = error.message?.trim() || `error ${error.code ?? ""}`.trim();
239
+ const data = error.data;
240
+ let detail = "";
241
+ if (typeof data === "string")
242
+ detail = data.trim();
243
+ else if (data && typeof data === "object") {
244
+ const obj = data;
245
+ if (typeof obj.details === "string")
246
+ detail = obj.details.trim();
247
+ else if (typeof obj.message === "string")
248
+ detail = obj.message.trim();
249
+ else {
250
+ try {
251
+ detail = JSON.stringify(data);
252
+ }
253
+ catch {
254
+ detail = "";
255
+ }
256
+ }
257
+ }
258
+ return detail && !base.includes(detail) ? `${base}: ${detail}` : base;
259
+ }
260
+ const AGENT_FILE = [
261
+ "---",
262
+ `name: ${AGENT_NAME}`,
263
+ "description: nexo model turn",
264
+ "tools: []",
265
+ "mainAgent: true",
266
+ "---",
267
+ "Follow the instructions provided for this session. Do not invoke any built-in tools.",
268
+ "Your own working directory is an empty scratch directory unrelated to the caller's. Never resolve or link file paths against it: use relative paths as given, or only absolute paths named in the conversation.",
269
+ "",
270
+ ].join("\n");
271
+ /**
272
+ * One long-lived `agy acp` server running a minimal custom agent with `tools: []` in a throwaway workspace. Requests
273
+ * are matched to responses by id, session updates are routed by session id, and every pending request fails at once
274
+ * when the process goes away.
275
+ */
276
+ class AcpConnection {
277
+ closed = false;
278
+ dir;
279
+ nextId = 0;
280
+ heldCount = 0;
281
+ pending = new Map();
282
+ listeners = new Map();
283
+ proc;
284
+ onClose;
285
+ constructor(proc, dir, onClose) {
286
+ this.proc = proc;
287
+ this.dir = dir;
288
+ this.onClose = onClose;
289
+ }
290
+ /** Starts the server and completes the `initialize` handshake. */
291
+ static async open(run, onClose) {
292
+ registerExitHandler();
293
+ // Throwaway workspace holding the no-tools custom agent under ./.agents/agents, with no project files in reach.
294
+ const dir = await mkdtemp(join(tmpdir(), "nexo-agy-p-"));
295
+ liveDirs.add(dir);
296
+ await mkdir(join(dir, ".agents", "agents"), { recursive: true });
297
+ await writeFile(join(dir, ".agents", "agents", `${AGENT_NAME}.md`), AGENT_FILE, "utf8");
298
+ const proc = run({ args: ["acp", "--agent", AGENT_NAME, "--include-default-customizations=false"], cwd: dir });
299
+ const conn = new AcpConnection(proc, dir, onClose);
300
+ void conn.pump();
301
+ void proc.exit.then((exit) => conn.shutdown(new Error(exit.stderr.trim().split("\n").at(-1) || `agy exited with code ${exit.code ?? "null"}`)));
302
+ try {
303
+ await conn.request("initialize", { protocolVersion: 1, clientCapabilities: {}, clientInfo: { name: "nexo", version: "0" } });
304
+ }
305
+ catch (error) {
306
+ conn.shutdown(error instanceof Error ? error : new Error(String(error)));
307
+ throw error;
308
+ }
309
+ return conn;
310
+ }
311
+ async pump() {
312
+ try {
313
+ for await (const line of this.proc.lines)
314
+ this.handle(line);
315
+ }
316
+ catch {
317
+ // the stream was torn down with the process
318
+ }
319
+ this.shutdown(new Error("agy closed its output"));
320
+ }
321
+ handle(line) {
322
+ if (!line.trim())
323
+ return;
324
+ let m;
325
+ try {
326
+ m = JSON.parse(line);
327
+ }
328
+ catch {
329
+ return;
330
+ }
331
+ if (!m || typeof m !== "object")
332
+ return;
333
+ if (m.id !== undefined && m.id !== null && m.method) {
334
+ // Agent-to-client request: refuse permissions and error on the rest, so the agent never waits.
335
+ if (m.method === "session/request_permission") {
336
+ const rawOptions = m.params?.options;
337
+ const options = Array.isArray(rawOptions) ? rawOptions : [];
338
+ const pick = options.find((o) => typeof o?.optionId === "string" && o.kind === "reject_once") ??
339
+ options.find((o) => typeof o?.optionId === "string" && o.kind === "reject_always");
340
+ this.send({ id: m.id, result: { outcome: pick ? { outcome: "selected", optionId: pick.optionId } : { outcome: "cancelled" } } });
341
+ }
342
+ else
343
+ this.send({ id: m.id, error: { code: -32601, message: "Method not found" } });
344
+ }
345
+ else if (m.id !== undefined && m.id !== null) {
346
+ const id = Number(m.id);
347
+ const p = this.pending.get(id);
348
+ if (!p)
349
+ return;
350
+ this.settle(id, p);
351
+ if (m.error)
352
+ p.reject(new Error(rpcErrorMessage(m.error)));
353
+ else
354
+ p.resolve(m.result);
355
+ }
356
+ else if (m.method === "session/update") {
357
+ const sessionId = m.params?.sessionId;
358
+ const update = m.params?.update;
359
+ if (typeof sessionId === "string" && update && typeof update === "object")
360
+ this.listeners.get(sessionId)?.(update);
361
+ }
362
+ }
363
+ send(message) {
364
+ try {
365
+ this.proc.write(JSON.stringify({ jsonrpc: "2.0", ...message }));
366
+ }
367
+ catch {
368
+ // a dead process is reported through exit
369
+ }
370
+ }
371
+ settle(id, entry) {
372
+ this.pending.delete(id);
373
+ if (entry.keepAlive) {
374
+ this.heldCount = Math.max(0, this.heldCount - 1);
375
+ // Idle server: let the host exit (the exit handler kills the server); foreground requests keep the host alive.
376
+ if (this.heldCount === 0 && !this.closed)
377
+ this.proc.hold?.(false);
378
+ }
379
+ }
380
+ request(method, params, keepAlive = true) {
381
+ if (this.closed)
382
+ return Promise.reject(new Error("agy is not running"));
383
+ const id = ++this.nextId;
384
+ return new Promise((resolve, reject) => {
385
+ if (keepAlive) {
386
+ if (this.heldCount === 0)
387
+ this.proc.hold?.(true);
388
+ this.heldCount++;
389
+ }
390
+ this.pending.set(id, { resolve, reject, keepAlive });
391
+ this.send({ id, method, params });
392
+ });
393
+ }
394
+ notify(method, params) {
395
+ this.send({ method, params });
396
+ }
397
+ listen(sessionId, fn) {
398
+ this.listeners.set(sessionId, fn);
399
+ }
400
+ unlisten(sessionId) {
401
+ this.listeners.delete(sessionId);
402
+ }
403
+ /** Fails everything in flight, stops the process and removes the workspace. Safe to call more than once. */
404
+ shutdown(reason) {
405
+ if (this.closed)
406
+ return;
407
+ this.closed = true;
408
+ this.heldCount = 0;
409
+ this.onClose();
410
+ for (const p of this.pending.values())
411
+ p.reject(reason);
412
+ this.pending.clear();
413
+ this.listeners.clear();
414
+ this.proc.kill();
415
+ liveDirs.delete(this.dir);
416
+ void rm(this.dir, { recursive: true, force: true }).catch(() => { });
417
+ }
418
+ }
419
+ /** Why a tools turn ended without a usable reply; the engine retries it a few times (see `isFormatFailure`). */
420
+ export const AGY_P_BAD_REPLY = "reply was not a JSON object in the required format";
421
+ /** True when a reply that did not parse was an attempt at the JSON format rather than a plain-prose answer. */
422
+ function looksLikeReplyAttempt(text) {
423
+ return /"tool_calls"\s*:/.test(text) || /^\s*(```|\{)/.test(text);
424
+ }
425
+ const RETRY_NOTE = "Your previous reply was not a single valid JSON object in the required format. Reply again with only that JSON object.";
426
+ function raceAbort(promise, signal) {
427
+ if (!signal)
428
+ return promise;
429
+ if (signal.aborted)
430
+ return Promise.resolve("aborted");
431
+ let onAbort;
432
+ const aborted = new Promise((resolve) => {
433
+ onAbort = () => resolve("aborted");
434
+ signal.addEventListener("abort", onAbort, { once: true });
435
+ });
436
+ return Promise.race([promise, aborted]).finally(() => {
437
+ signal.removeEventListener("abort", onAbort);
438
+ });
439
+ }
440
+ function streamAgyP(getConn, model, context, options) {
441
+ const stream = createAssistantMessageEventStream();
442
+ const partial = {
443
+ role: "assistant",
444
+ content: [],
445
+ api: model.api,
446
+ provider: model.provider,
447
+ model: model.id,
448
+ usage: emptyUsage(),
449
+ stopReason: "pending",
450
+ timestamp: Date.now(),
451
+ };
452
+ const snapshot = () => ({ ...partial, content: [...partial.content] });
453
+ const fail = (reason, message, usage) => {
454
+ const error = { ...snapshot(), stopReason: reason, errorMessage: message, ...(usage ? { usage } : {}) };
455
+ stream.push({ type: "error", reason, error });
456
+ stream.end(error);
457
+ };
458
+ const emitText = (text) => {
459
+ const contentIndex = partial.content.length;
460
+ partial.content.push({ type: "text", text: "" });
461
+ stream.push({ type: "text_start", contentIndex, partial: snapshot() });
462
+ partial.content[contentIndex].text = text;
463
+ stream.push({ type: "text_delta", contentIndex, delta: text, partial: snapshot() });
464
+ stream.push({ type: "text_end", contentIndex, content: text, partial: snapshot() });
465
+ };
466
+ queueMicrotask(async () => {
467
+ const signal = options?.signal;
468
+ if (signal?.aborted)
469
+ return fail("aborted", "Request was aborted");
470
+ const tools = getCurrentTools(context.messages);
471
+ const useTools = tools.length > 0 && options?.toolChoice !== "none";
472
+ const systemPrompt = [getCurrentSystemPrompt(context.messages), useTools ? agyToolsSection(tools) : ""].filter((s) => s.length > 0).join("\n\n");
473
+ const idleMs = parseIdleMs(process.env[AGY_P_IDLE_ENV]);
474
+ const closeSession = (session) => {
475
+ if (!session || session.conn.closed)
476
+ return;
477
+ // Non-blocking cleanup: never keep the host alive waiting for `session/close`.
478
+ void session.conn.request("session/close", { sessionId: session.id }, false).catch(() => { });
479
+ };
480
+ /** Opens one session on the shared server, retrying once if a reused server died during setup. */
481
+ const openSessionOnce = async () => {
482
+ const connRes = await raceAbort(getConn(), signal);
483
+ if (connRes === "aborted")
484
+ return { aborted: true };
485
+ const conn = connRes;
486
+ let sessionId;
487
+ try {
488
+ const createdRes = await raceAbort(conn.request("session/new", {
489
+ cwd: conn.dir,
490
+ mcpServers: [],
491
+ ...(systemPrompt ? { _meta: { antigravity: { systemPrompt: { append: systemPrompt } } } } : {}),
492
+ }), signal);
493
+ if (createdRes === "aborted")
494
+ return { aborted: true };
495
+ const created = createdRes;
496
+ if (typeof created?.sessionId !== "string" || !created.sessionId)
497
+ throw new Error("session/new returned no sessionId");
498
+ sessionId = created.sessionId;
499
+ const modelRes = await raceAbort(conn.request("session/set_config_option", { sessionId, configId: "model", value: model.id }), signal);
500
+ if (modelRes === "aborted") {
501
+ closeSession({ conn, id: sessionId });
502
+ return { aborted: true };
503
+ }
504
+ const modelOpts = modelRes?.configOptions;
505
+ const level = resolveThoughtLevel(options?.reasoning, modelOpts ?? created.configOptions);
506
+ if (level) {
507
+ const levelRes = await raceAbort(conn.request("session/set_config_option", { sessionId, configId: "thought_level", value: level }), signal);
508
+ if (levelRes === "aborted") {
509
+ closeSession({ conn, id: sessionId });
510
+ return { aborted: true };
511
+ }
512
+ }
513
+ return { session: { conn, id: sessionId } };
514
+ }
515
+ catch (error) {
516
+ if (sessionId)
517
+ closeSession({ conn, id: sessionId });
518
+ if (conn.closed)
519
+ return { lost: true };
520
+ throw error;
521
+ }
522
+ };
523
+ const startSession = async (allowRetry = true) => {
524
+ const first = await openSessionOnce();
525
+ if (first.aborted)
526
+ return "aborted";
527
+ if (first.session)
528
+ return first.session;
529
+ if (first.lost && allowRetry && !signal?.aborted) {
530
+ const second = await openSessionOnce();
531
+ if (second.aborted)
532
+ return "aborted";
533
+ if (second.session)
534
+ return second.session;
535
+ }
536
+ throw new Error("agy closed before session could start");
537
+ };
538
+ /**
539
+ * One prompt on a session. Thinking and text stream into `partial` as they arrive; on a tools turn the text shown
540
+ * is the reply's `text` field, read out of the JSON while it is still being written (`streamText` off: none).
541
+ */
542
+ const runOnce = async (session, input, streamText = true) => {
543
+ // ACP content blocks: text, and images as base64 (`agy acp` advertises promptCapabilities.image).
544
+ const prompt = typeof input === "string"
545
+ ? [{ type: "text", text: input }]
546
+ : input.map((p) => (p.type === "text" ? { type: "text", text: p.text } : { type: "image", data: p.data, mimeType: p.mimeType }));
547
+ const { conn, id } = session;
548
+ const outcome = { text: "", usage: emptyUsage() };
549
+ const replyText = useTools ? new ReplyTextExtractor() : undefined;
550
+ // A native tool call cancels the turn so the engine retries cleanly.
551
+ let nativeCall;
552
+ let stalled = false;
553
+ let open;
554
+ let idle;
555
+ let killTimer;
556
+ const cancel = () => conn.notify("session/cancel", { sessionId: id });
557
+ const arm = () => {
558
+ clearTimeout(idle);
559
+ idle = setTimeout(() => {
560
+ stalled = true;
561
+ cancel();
562
+ killTimer = setTimeout(() => conn.shutdown(new Error("agy did not answer the cancel")), CANCEL_GRACE_MS);
563
+ }, idleMs);
564
+ };
565
+ const close = () => {
566
+ if (!open)
567
+ return;
568
+ const block = partial.content[open.index];
569
+ if (block?.type === "text")
570
+ stream.push({ type: "text_end", contentIndex: open.index, content: block.text, partial: snapshot() });
571
+ else if (block?.type === "thinking")
572
+ stream.push({ type: "thinking_end", contentIndex: open.index, content: block.thinking, partial: snapshot() });
573
+ open = undefined;
574
+ };
575
+ conn.listen(id, (u) => {
576
+ arm();
577
+ if (u.sessionUpdate === "tool_call") {
578
+ if (!nativeCall) {
579
+ nativeCall = u.title ?? "tool";
580
+ cancel();
581
+ }
582
+ return;
583
+ }
584
+ const kind = u.sessionUpdate === "agent_message_chunk" ? "text" : u.sessionUpdate === "agent_thought_chunk" ? "thinking" : undefined;
585
+ const chunk = u.content?.type === "text" ? u.content.text : undefined;
586
+ if (!kind || !chunk)
587
+ return;
588
+ if (kind === "text")
589
+ outcome.text += chunk;
590
+ const delta = kind === "text" && replyText ? (streamText ? replyText.push(chunk) : "") : chunk;
591
+ if (!delta)
592
+ return;
593
+ if (open?.kind !== kind) {
594
+ close();
595
+ open = { kind, index: partial.content.length };
596
+ partial.content.push(kind === "text" ? { type: "text", text: "" } : { type: "thinking", thinking: "" });
597
+ stream.push({ type: kind === "text" ? "text_start" : "thinking_start", contentIndex: open.index, partial: snapshot() });
598
+ }
599
+ const block = partial.content[open.index];
600
+ if (block.type === "text")
601
+ block.text += delta;
602
+ else if (block.type === "thinking")
603
+ block.thinking += delta;
604
+ stream.push({ type: kind === "text" ? "text_delta" : "thinking_delta", contentIndex: open.index, delta, partial: snapshot() });
605
+ });
606
+ let abort;
607
+ const aborted = new Promise((resolve) => {
608
+ abort = () => resolve("aborted");
609
+ });
610
+ const onAbort = () => {
611
+ cancel();
612
+ abort();
613
+ };
614
+ signal?.addEventListener("abort", onAbort, { once: true });
615
+ arm();
616
+ try {
617
+ const settled = await Promise.race([
618
+ conn.request("session/prompt", { sessionId: id, prompt }).then((r) => ({ r: r }), (e) => ({ e })),
619
+ aborted,
620
+ ]);
621
+ close();
622
+ if (settled === "aborted")
623
+ outcome.aborted = true;
624
+ else if (stalled)
625
+ outcome.error = `no output for ${Math.round(idleMs / 1000)}s`;
626
+ else if (nativeCall)
627
+ outcome.error = `stopped: native tool call "${nativeCall}" (the nexo agent offers no tools)`;
628
+ else if ("e" in settled) {
629
+ outcome.error = settled.e.message;
630
+ outcome.lost = conn.closed;
631
+ }
632
+ else {
633
+ outcome.stopReason = settled.r?.stopReason;
634
+ outcome.usage = toUsage(settled.r?.usage);
635
+ if (outcome.stopReason === "cancelled")
636
+ outcome.error = "run cancelled";
637
+ }
638
+ }
639
+ finally {
640
+ clearTimeout(idle);
641
+ clearTimeout(killTimer);
642
+ conn.unlisten(id);
643
+ signal?.removeEventListener("abort", onAbort);
644
+ }
645
+ return outcome;
646
+ };
647
+ let session;
648
+ try {
649
+ stream.push({ type: "start", partial: snapshot() });
650
+ const prompt = renderTranscriptParts(context.messages);
651
+ const opened = await startSession();
652
+ if (opened === "aborted" || signal?.aborted)
653
+ return fail("aborted", "Request was aborted");
654
+ session = opened;
655
+ let outcome = await runOnce(session, prompt);
656
+ // The shared server died under this turn before anything streamed: start a fresh one and run it again, once.
657
+ if (outcome.lost && !signal?.aborted && partial.content.length === 0) {
658
+ const reopened = await startSession(false);
659
+ if (reopened === "aborted" || signal?.aborted)
660
+ return fail("aborted", "Request was aborted");
661
+ session = reopened;
662
+ outcome = await runOnce(session, prompt);
663
+ }
664
+ let usage = outcome.usage;
665
+ if (outcome.aborted || signal?.aborted)
666
+ return fail("aborted", "Request was aborted", usage);
667
+ if (outcome.error)
668
+ return fail("error", `agy failed: ${outcome.error}`, usage);
669
+ let stopReason = outcome.stopReason === "max_tokens" ? "length" : "stop";
670
+ if (useTools) {
671
+ let reply = parseAgyReply(outcome.text, tools);
672
+ if (!reply) {
673
+ // Same session, so the model still has the transcript: only the correction is sent. Text the first
674
+ // attempt already streamed is not streamed again.
675
+ outcome = await runOnce(session, RETRY_NOTE, !partial.content.some((b) => b.type === "text"));
676
+ usage = addUsage(usage, outcome.usage);
677
+ if (outcome.aborted || signal?.aborted)
678
+ return fail("aborted", "Request was aborted", usage);
679
+ if (outcome.error)
680
+ return fail("error", `agy failed: ${outcome.error}`, usage);
681
+ reply = parseAgyReply(outcome.text, tools);
682
+ }
683
+ // Still not the format. A botched attempt at it (JSON naming an unknown action, a truncated object) is an
684
+ // error the engine retries; plain prose is kept.
685
+ if (!reply && looksLikeReplyAttempt(outcome.text))
686
+ return fail("error", `agy failed: ${AGY_P_BAD_REPLY}`, usage);
687
+ const { text, calls } = reply ?? { text: outcome.text, calls: [] };
688
+ // The parsed reply is the answer. Text that streamed is normally the same; where it is not, the block takes it.
689
+ const streamed = partial.content.findIndex((b) => b.type === "text");
690
+ if (streamed < 0) {
691
+ if (text)
692
+ emitText(text);
693
+ }
694
+ else if (text)
695
+ partial.content[streamed].text = text;
696
+ else
697
+ partial.content.splice(streamed, 1);
698
+ for (const call of calls) {
699
+ const contentIndex = partial.content.length;
700
+ partial.content.push({ ...call, arguments: {} });
701
+ stream.push({ type: "toolcall_start", contentIndex, partial: snapshot() });
702
+ partial.content[contentIndex] = call;
703
+ stream.push({ type: "toolcall_delta", contentIndex, delta: JSON.stringify(call.arguments), partial: snapshot() });
704
+ stream.push({ type: "toolcall_end", contentIndex, toolCall: call, partial: snapshot() });
705
+ }
706
+ stopReason = calls.length > 0 ? "toolUse" : "stop";
707
+ }
708
+ else if (!partial.content.some((b) => b.type === "text") && outcome.text) {
709
+ emitText(outcome.text);
710
+ }
711
+ const message = { ...snapshot(), usage, stopReason };
712
+ stream.push({ type: "done", reason: stopReason, message });
713
+ stream.end(message);
714
+ }
715
+ catch (error) {
716
+ if (signal?.aborted)
717
+ return fail("aborted", "Request was aborted");
718
+ fail("error", `agy failed: ${error instanceof Error ? error.message : String(error)}`);
719
+ }
720
+ finally {
721
+ closeSession(session);
722
+ }
723
+ });
724
+ return stream;
725
+ }
726
+ /**
727
+ * Runs models through one long-lived Antigravity CLI ACP server (`agy acp`), authenticated by the CLI's own login.
728
+ * The server starts on the first call and is shared by every call after it, avoiding per-call language-server start-up.
729
+ * It runs a minimal custom agent with `tools: []` in a throwaway workspace; each turn opens a fresh session carrying
730
+ * nexo's system prompt via `_meta.antigravity.systemPrompt.append`, sets the base model and `thought_level` from
731
+ * reasoning effort, and closes the session afterwards. Any native tool call cancels the turn. Nexo tools are described
732
+ * in the prompt and parsed as `{ text, tool_calls }` (one correction retry when it does not parse); `text` streams as
733
+ * it is written. Token counts are reported from ACP usage while cost stays $0.
734
+ */
735
+ export function agyPProvider(options = {}) {
736
+ const run = options.run ?? spawnRunner(options.command ?? process.env[AGY_P_COMMAND_ENV] ?? "agy");
737
+ let current;
738
+ const getConn = () => {
739
+ if (current)
740
+ return current;
741
+ const opened = AcpConnection.open(run, () => {
742
+ if (current === opened)
743
+ current = undefined;
744
+ });
745
+ current = opened;
746
+ opened.catch(() => {
747
+ if (current === opened)
748
+ current = undefined;
749
+ });
750
+ return opened;
751
+ };
752
+ const api = {
753
+ stream: (model, context, opts) => streamAgyP(getConn, model, context, opts),
754
+ streamSimple: (model, context, opts) => streamAgyP(getConn, model, context, opts),
755
+ };
756
+ return createProvider({
757
+ id: AGY_P_PROVIDER,
758
+ name: "Antigravity CLI (agy acp)",
759
+ auth: {
760
+ apiKey: {
761
+ name: "Antigravity CLI login",
762
+ resolve: async () => ({ auth: {}, source: "agy CLI login" }),
763
+ },
764
+ },
765
+ models: agyPModels(),
766
+ api,
767
+ });
768
+ }