@magpie-community/opencode-agy-tui-auth 0.0.0-stage → 0.1.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/index.mjs ADDED
@@ -0,0 +1,781 @@
1
+ import { spawn } from "node:child_process"
2
+ import { randomBytes } from "node:crypto"
3
+ import fs from "node:fs"
4
+ import os from "node:os"
5
+ import path from "node:path"
6
+ import { startLogin } from "./login.mjs"
7
+ import { writeDefaultAgentFiles } from "./default-agent.mjs"
8
+ import { agyTooOld, MIN_AGY_VERSION } from "./agy-version.mjs"
9
+
10
+ // agy-tui: Antigravity's models through agy's own interactive mode. Each
11
+ // request starts the real `agy` TUI in a terminal magpie gives it (`magpie
12
+ // tui-helper`, internal/tuihelper), types the conversation into its prompt
13
+ // as a person would paste it, and reads the answer from the transcript agy
14
+ // writes. Nothing here speaks to Google: agy does, as it does for anyone
15
+ // at its prompt.
16
+ //
17
+ // Each account has a home of its own (accountsDir), where agy keeps its
18
+ // sign-in as a file (SSH_CONNECTION, as in the agy-cli plugin), so the
19
+ // user's own ~/.gemini, skills and MCP servers are never used. agy runs
20
+ // on its default agent (default-agent.mjs; a custom agent's session costs
21
+ // about four times the quota from agy 1.5.17, plugins#1684), told to answer
22
+ // in text, with a tool gate that turns every one of agy's tools down: it
23
+ // answers in text; the caller's tools are not offered to the model. A
24
+ // request's images and videos are written to the turn's folder and their
25
+ // paths pasted into the prompt before its text, which agy attaches as it
26
+ // does a file dragged onto its terminal; a file agy can't attach (a PDF,
27
+ // audio) is refused, never dropped.
28
+
29
+ export const PROVIDER_ID = "agy-tui"
30
+ const PROVIDER_NAME = "Antigravity (agy TUI)"
31
+ const NPM = "@ai-sdk/openai-compatible"
32
+ // what the session's AGENTS.md says; its tool gate allows nothing
33
+ const INSTRUCTIONS = "Answer in text. Every tool is turned off in this session."
34
+ const AGY_MANUAL = "https://antigravity.google/docs/cli"
35
+
36
+ // What agy 1.5's footer says: waiting for a message, and in a turn.
37
+ export const READY = "? for shortcuts"
38
+ export const BUSY = "esc to cancel"
39
+
40
+ // What agy asks the terminal before it draws, answered as xterm does.
41
+ export const REPLIES = [
42
+ { ask: "\x1b[>c", answer: "\x1b[>1;10;0c" },
43
+ { ask: "\x1b]11;?\x07", answer: "\x1b]11;rgb:0000/0000/0000\x1b\\" },
44
+ { ask: "\x1b]10;?\x07", answer: "\x1b]10;rgb:ffff/ffff/ffff\x1b\\" },
45
+ ]
46
+
47
+ const START_MS = 90_000
48
+ const SUBMIT_MS = 60_000
49
+ const PASTE_SETTLE_MS = 300
50
+ // how long agy may sit at its prompt after a turn before the transcript has
51
+ // its answer
52
+ const IDLE_MS = 5_000
53
+
54
+ function attachTimeout() {
55
+ const n = Number(process.env.AGY_TUI_ATTACH_TIMEOUT_MS)
56
+ return Number.isFinite(n) && n > 0 ? n : 15_000
57
+ }
58
+
59
+ function turnTimeout() {
60
+ const n = Number(process.env.AGY_TUI_TURN_TIMEOUT_MS)
61
+ return Number.isFinite(n) && n > 0 ? n : 15 * 60_000
62
+ }
63
+
64
+ // ---- accounts
65
+
66
+ const HOME_ID = /^[a-z0-9]{8,32}$/
67
+
68
+ export function accountsDir(env = process.env) {
69
+ const base = env.XDG_STATE_HOME && path.isAbsolute(env.XDG_STATE_HOME) ? env.XDG_STATE_HOME : path.join(os.homedir(), ".local", "state")
70
+ return path.join(base, "magpie-agy-tui", "accounts")
71
+ }
72
+
73
+ export function homeOf(id, env = process.env) {
74
+ return typeof id === "string" && HOME_ID.test(id) ? path.join(accountsDir(env), id) : null
75
+ }
76
+
77
+ export function homeOfAuth(auth) {
78
+ return homeOf(auth?.metadata?.agyHome) ?? homeOf(String(auth?.key ?? "").replace(/^agy-tui:/, ""))
79
+ }
80
+
81
+ function newHome() {
82
+ const id = randomBytes(8).toString("hex")
83
+ const home = homeOf(id)
84
+ fs.mkdirSync(home, { recursive: true, mode: 0o700 })
85
+ return { id, home }
86
+ }
87
+
88
+ export function tokenFile(home) {
89
+ return path.join(home, ".gemini", "antigravity-cli", "antigravity-oauth-token")
90
+ }
91
+
92
+ // agyEnv is what an agy for the account at home runs with: the host's
93
+ // environment, the account's HOME, and its sign-in kept in tokenFile, not
94
+ // the keyring every account would share.
95
+ export function agyEnv(home, parent = process.env, platform = process.platform) {
96
+ const env = { ...parent, HOME: home, SSH_CONNECTION: "127.0.0.1 0 127.0.0.1 0", TERM: "xterm-256color" }
97
+ if (platform === "win32") env.USERPROFILE = home
98
+ if (!Object.keys(parent).some((k) => k.toUpperCase() === "AGY_CLI_DISABLE_AUTO_UPDATE")) env.AGY_CLI_DISABLE_AUTO_UPDATE = "true"
99
+ return env
100
+ }
101
+
102
+ // agy's first-run screens are the account home's own business: they were
103
+ // passed once its sign-in took. Written only where nothing is.
104
+ function settleHome(home) {
105
+ const file = path.join(home, ".gemini", "antigravity-cli", "cache", "onboarding.json")
106
+ if (fs.existsSync(file)) return
107
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })
108
+ fs.writeFileSync(file, JSON.stringify({ consumerOnboardingComplete: true, onboardingComplete: true }), { mode: 0o600 })
109
+ }
110
+
111
+ // ---- agy
112
+
113
+ export function findAgy(env = process.env, platform = process.platform) {
114
+ const windows = platform === "win32"
115
+ const paths = windows ? path.win32 : path.posix
116
+ const home = os.homedir()
117
+ const names = windows ? ["agy.exe"] : ["agy"]
118
+ const candidates = env.AGY_PATH ? [env.AGY_PATH] : []
119
+ for (const dir of (env.PATH || env.Path || "").split(windows ? ";" : ":")) {
120
+ if (dir) candidates.push(...names.map((n) => paths.join(dir.replace(/^"|"$/g, ""), n)))
121
+ }
122
+ const dirs = windows
123
+ ? [paths.join(env.LOCALAPPDATA || paths.join(home, "AppData", "Local"), "agy", "bin"), paths.join(home, ".local", "bin"), paths.join(home, ".gemini", "bin")]
124
+ : [paths.join(home, ".local", "bin"), paths.join(home, ".gemini", "bin"), "/usr/local/bin", "/opt/homebrew/bin"]
125
+ for (const dir of dirs) candidates.push(...names.map((n) => paths.join(dir, n)))
126
+ // the copy the agy-cli plugin installed, when the machine has no other
127
+ const data = windows ? (env.LOCALAPPDATA || paths.join(home, "AppData", "Local")) : (env.XDG_DATA_HOME || paths.join(home, ".local", "share"))
128
+ candidates.push(paths.join(data, "magpie-agy-cli", names[0]))
129
+ for (const c of candidates) {
130
+ try {
131
+ fs.accessSync(c, fs.constants.X_OK)
132
+ return c
133
+ } catch {}
134
+ }
135
+ return null
136
+ }
137
+
138
+ function run(file, args, { env, timeout = 30_000 } = {}) {
139
+ return new Promise((resolve) => {
140
+ let child
141
+ try {
142
+ child = spawn(file, args, { env, cwd: os.tmpdir(), stdio: ["ignore", "pipe", "pipe"], windowsHide: true })
143
+ } catch (error) {
144
+ resolve({ code: -1, stdout: "", stderr: error.message })
145
+ return
146
+ }
147
+ let stdout = ""
148
+ let stderr = ""
149
+ const timer = setTimeout(() => child.kill(), timeout)
150
+ child.stdout.setEncoding("utf8").on("data", (d) => (stdout += d))
151
+ child.stderr.setEncoding("utf8").on("data", (d) => (stderr += d))
152
+ child.on("error", (error) => { clearTimeout(timer); resolve({ code: -1, stdout, stderr: stderr + error.message }) })
153
+ child.on("close", (code) => { clearTimeout(timer); resolve({ code, stdout, stderr }) })
154
+ })
155
+ }
156
+
157
+ const helps = new Map()
158
+ async function agyHelp(agy) {
159
+ if (!helps.has(agy)) helps.set(agy, run(agy, ["--help"], { env: { ...process.env, AGY_CLI_DISABLE_AUTO_UPDATE: "true" } }).then((r) => r.stdout + r.stderr))
160
+ return helps.get(agy)
161
+ }
162
+
163
+ // parseModels reads `agy models`: one "<id> <name>" a line.
164
+ export function parseModels(stdout) {
165
+ const out = []
166
+ for (const raw of String(stdout ?? "").split("\n")) {
167
+ const m = /^(\S+)\s+(.+)$/.exec(raw.trim())
168
+ if (m && /^[a-z0-9][\w.-]*$/i.test(m[1])) out.push({ id: m[1], name: m[2].trim() })
169
+ }
170
+ return out
171
+ }
172
+
173
+ // agyVersion is what `agy --version` says, read once for each agy binary (a
174
+ // new one at the same path is read again); null when agy doesn't say.
175
+ const versions = new Map()
176
+ export async function agyVersion(agy) {
177
+ let key = agy
178
+ try {
179
+ const st = fs.statSync(agy)
180
+ key = `${agy}\0${st.size}\0${st.mtimeMs}`
181
+ } catch {}
182
+ if (!versions.has(key)) {
183
+ versions.set(key, run(agy, ["--version"], { env: { ...process.env, AGY_CLI_DISABLE_AUTO_UPDATE: "true" } }).then((r) => {
184
+ const v = r.code === 0 ? /\b\d+\.\d+\.\d+\b/.exec(r.stdout)?.[0] ?? null : null
185
+ if (!v) versions.delete(key)
186
+ return v
187
+ }))
188
+ }
189
+ return versions.get(key)
190
+ }
191
+
192
+ // agyRefusal is why this agy can't run a turn, or null. The default agent's
193
+ // instructions and tool gate were checked on agy 1.5.19; an agy that can't
194
+ // say its version isn't taken for one that can.
195
+ export async function agyRefusal(agy) {
196
+ const version = await agyVersion(agy)
197
+ if (!version) return `agy didn't say its version (agy --version), so it can't be checked against ${MIN_AGY_VERSION}, the oldest this plugin runs on. Update agy (agy update).`
198
+ return agyTooOld(version)
199
+ }
200
+
201
+ async function listModels(agy, home) {
202
+ // the account's provider, not a modelProvider a settings file names
203
+ const args = (await agyHelp(agy)).includes("--settings") ? ["--settings", '{"modelProvider":""}', "models"] : ["models"]
204
+ const r = await run(agy, args, { env: agyEnv(home) })
205
+ const models = r.code === 0 ? parseModels(r.stdout) : []
206
+ if (!models.length) throw new Error(`agy lists no models for this account${lastLine(r.stderr || r.stdout) ? `: ${lastLine(r.stderr || r.stdout)}` : ""}`)
207
+ return models
208
+ }
209
+
210
+ function lastLine(text) {
211
+ return String(text ?? "").split(/\r?\n/).map((l) => l.trim()).filter(Boolean).at(-1) ?? ""
212
+ }
213
+
214
+ // ---- the conversation, as typed
215
+
216
+ // What agy attaches when its path is pasted into the prompt, as a file
217
+ // dragged onto the terminal is: the types agy 1.5.19's mimeTypeFromPath
218
+ // knows, by extension (clipboard.go), and the most ReadMediaFile reads of
219
+ // each, 50 MB of a video and 10 MB of anything else. Any other file's path
220
+ // (a PDF, audio, text or code, a HEIC) stays text in the prompt.
221
+ export const MEDIA_TYPES = {
222
+ "image/png": "png", "image/jpeg": "jpg", "image/gif": "gif", "image/webp": "webp", "image/bmp": "bmp", "image/tiff": "tiff", "image/svg+xml": "svg",
223
+ "video/mp4": "mp4", "video/quicktime": "mov", "video/webm": "webm", "video/x-msvideo": "avi",
224
+ }
225
+ const SAME_TYPE = { "image/jpg": "image/jpeg", "image/tif": "image/tiff", "video/avi": "video/x-msvideo", "video/msvideo": "video/x-msvideo", "video/mov": "video/quicktime" }
226
+ const MB = 1024 * 1024
227
+ const maxBytes = (type) => (type.startsWith("video/") ? 50 : 10) * MB
228
+ const kindOf = (type) => (type.startsWith("video/") ? "video" : "image")
229
+ const TAKES = "agy's prompt attaches images (PNG, JPEG, GIF, WebP, BMP, TIFF, SVG) and videos (MP4, MOV, WebM, AVI) only"
230
+ // where an image or a video sat in the conversation, in the text pasted
231
+ // with it
232
+ const mediaMark = (kind, n) => `[${kind === "video" ? "Video" : "Image"} ${n}]`
233
+ const MEDIA_MARK = /\[(?:Image|Video) \d+\]/g
234
+ // what magpie's gateway puts in a message for a file it can't send on
235
+ // Chat (internal/gateway attachmentText): a PDF, a sound, a document
236
+ const ATTACHMENT_NOTE = /\[attachment ([^\]\s:]+)(?::[^\]]*)?\]/
237
+
238
+ const refuse = (message) => Object.assign(new Error(message), { status: 400 })
239
+
240
+ // what a type is called in a refusal
241
+ function named(type) {
242
+ const t = String(type ?? "").toLowerCase()
243
+ if (!t) return "a file of no type"
244
+ if (t === "application/pdf") return "a PDF"
245
+ if (t.startsWith("audio/")) return `audio (${t})`
246
+ if (t.startsWith("image/")) return `an image of type ${t}`
247
+ if (t.startsWith("video/")) return `a video of type ${t}`
248
+ return `a file of type ${t}`
249
+ }
250
+
251
+ // mediaOf is a data: URL's image or video, or a refusal: agy is given a
252
+ // file, so a link elsewhere would have to be fetched for it.
253
+ function mediaOf(url, mediaType) {
254
+ const m = /^data:([^;,]*)((?:;[^;,]*)*),(.*)$/s.exec(String(url ?? ""))
255
+ if (!m) throw refuse(`agy-tui takes images and videos sent inline (a data: URL), not a link to one`)
256
+ let type = (m[1].trim() || String(mediaType ?? "").trim()).toLowerCase()
257
+ type = SAME_TYPE[type] ?? type
258
+ if (!MEDIA_TYPES[type]) throw refuse(`${TAKES}; the message has ${named(type)}`)
259
+ const base64 = /;base64$/i.test(m[2])
260
+ let data
261
+ try {
262
+ data = base64 ? Buffer.from(m[3], "base64") : Buffer.from(decodeURIComponent(m[3]), "utf8")
263
+ } catch {
264
+ throw refuse(`the message has ${kindOf(type) === "video" ? "a video" : "an image"} that can't be read`)
265
+ }
266
+ if (!data.length) throw refuse(`the message has an empty ${kindOf(type)}`)
267
+ if (data.length > maxBytes(type)) throw refuse(`${kindOf(type) === "video" ? "a video" : "an image"} is ${Math.ceil(data.length / MB)} MB; agy attaches up to ${maxBytes(type) / MB} MB of one`)
268
+ return { type, data }
269
+ }
270
+
271
+ // the type agy gives a file of this name, as mimeTypeFromPath does
272
+ function typeByName(name) {
273
+ const ext = path.extname(String(name ?? "")).slice(1).toLowerCase()
274
+ if (!ext) return undefined
275
+ return { jpeg: "image/jpeg", tif: "image/tiff" }[ext] ?? Object.keys(MEDIA_TYPES).find((t) => MEDIA_TYPES[t] === ext)
276
+ }
277
+
278
+ // the data: URL of a file part, in each shape a Chat body has one: Chat's
279
+ // {file: {file_data}}, Responses' input_file, the AI SDK's {data, mediaType}
280
+ function fileOf(part) {
281
+ const f = part.type === "input_file" ? part : part.file ?? part
282
+ const type = String(f.mediaType ?? f.media_type ?? f.mime_type ?? typeByName(f.filename) ?? "").toLowerCase()
283
+ const src = f.file_data ?? f.data ?? f.file_url ?? f.url
284
+ if (typeof src !== "string" || !src) {
285
+ throw refuse(`${TAKES}; the message has ${f.file_id ? "a file by its id" : named(type)}`)
286
+ }
287
+ if (src.startsWith("data:")) return mediaOf(src, type)
288
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(src)) {
289
+ if (!MEDIA_TYPES[SAME_TYPE[type] ?? type]) throw refuse(`${TAKES}; the message has ${named(type)}`)
290
+ return mediaOf(src)
291
+ }
292
+ return mediaOf(`data:${type};base64,${src}`)
293
+ }
294
+
295
+ // partsOf is a message's text, each image or video in it marked where it
296
+ // was and added to media.
297
+ function partsOf(content, media) {
298
+ if (typeof content === "string") return content
299
+ if (!Array.isArray(content)) return ""
300
+ const out = []
301
+ const add = (m) => {
302
+ media.push(m)
303
+ out.push(mediaMark(kindOf(m.type), media.filter((x) => kindOf(x.type) === kindOf(m.type)).length))
304
+ }
305
+ for (const part of content) {
306
+ const type = part?.type
307
+ if (type === "text" || type === "input_text") out.push(part.text ?? "")
308
+ else if (type === "image_url" || type === "input_image") add(mediaOf(typeof part.image_url === "string" ? part.image_url : part.image_url?.url))
309
+ else if (type === "video_url" || type === "input_video") add(mediaOf(typeof part.video_url === "string" ? part.video_url : part.video_url?.url))
310
+ else if (type === "file" || type === "input_file") add(fileOf(part))
311
+ else if (type === "input_audio" || type === "audio") throw refuse(`${TAKES}; the message has audio${part.input_audio?.format ? ` (${part.input_audio.format})` : ""}`)
312
+ else if (type) throw refuse(`${TAKES}; the message has a ${type} part`)
313
+ }
314
+ return out.join("\n")
315
+ }
316
+
317
+ // turnOf is what goes into agy's prompt: the images and videos, attached in
318
+ // the order they came, and the text pasted after them, the last user
319
+ // message alone, or with the instructions and the conversation before it.
320
+ // A file magpie could only name in words (ATTACHMENT_NOTE) in the last
321
+ // user message is refused: the model would be told of a file it can't
322
+ // see. One in an earlier turn stays, as what was said then.
323
+ export function turnOf(messages) {
324
+ if (!Array.isArray(messages) || !messages.length) throw refuse("no messages")
325
+ const system = []
326
+ const turns = []
327
+ const media = []
328
+ for (const m of messages) {
329
+ if (m?.role === "system" || m?.role === "developer") {
330
+ const text = partsOf(m?.content, media).trim()
331
+ if (text) system.push(text)
332
+ } else if (m?.role === "user" || m?.role === "assistant") {
333
+ const text = partsOf(m?.content, media).trim()
334
+ if (text) turns.push({ role: m.role, text })
335
+ } else if (m?.role === "tool") {
336
+ throw refuse("agy-tui runs no tools: the conversation has a tool result")
337
+ }
338
+ }
339
+ if (!turns.length || turns.at(-1).role !== "user") throw refuse("the last message is not the user's")
340
+ const note = ATTACHMENT_NOTE.exec(turns.at(-1).text)
341
+ if (note) throw refuse(`${TAKES}; the message has ${named(note[1])}`)
342
+ if (!system.length && turns.length === 1) return { prompt: turns[0].text, media }
343
+ const parts = []
344
+ if (system.length) parts.push(system.join("\n\n"))
345
+ if (turns.length > 1) {
346
+ parts.push(turns.slice(0, -1).map((t) => `${t.role === "user" ? "User" : "Assistant"}: ${t.text}`).join("\n\n"))
347
+ parts.push(`User: ${turns.at(-1).text}`)
348
+ } else {
349
+ parts.push(turns[0].text)
350
+ }
351
+ return { prompt: parts.join("\n\n"), media }
352
+ }
353
+
354
+ // promptOf is the text turnOf pastes.
355
+ export function promptOf(messages) {
356
+ return turnOf(messages).prompt
357
+ }
358
+
359
+ // writeMedia writes a turn's images and videos into dir, named in order
360
+ // (image-1.png, video-1.mp4), and gives their paths.
361
+ export function writeMedia(dir, media) {
362
+ if (!media.length) return []
363
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
364
+ const count = { image: 0, video: 0 }
365
+ return media.map((m) => {
366
+ const kind = kindOf(m.type)
367
+ const file = path.join(dir, `${kind}-${++count[kind]}.${MEDIA_TYPES[m.type]}`)
368
+ fs.writeFileSync(file, m.data, { mode: 0o600 })
369
+ return file
370
+ })
371
+ }
372
+
373
+ // pastedPaths is the paste that attaches the files: one path a line, each
374
+ // quoted as a terminal quotes a dragged file's when it has a space.
375
+ export function pastedPaths(files, platform = process.platform) {
376
+ return files.map((f) => {
377
+ if (!/[\s'"\\]/.test(f) || (platform === "win32" && !/[\s'"]/.test(f))) return f
378
+ return platform === "win32" ? `"${f}"` : `'${f.replace(/'/g, `'\\''`)}'`
379
+ }).join("\n")
380
+ }
381
+
382
+ // attached is how many files agy's prompt shows attached ("📎 2 media
383
+ // attached"), 0 for none.
384
+ export function attached(screen) {
385
+ const m = /📎\s*(\d+)\s+media attached/.exec(String(screen ?? ""))
386
+ return m ? Number(m[1]) : 0
387
+ }
388
+
389
+ // ---- one turn in agy's TUI
390
+
391
+ const claimed = new Set()
392
+
393
+ // answerOf is the turn's answer in agy's transcript: a conversation agy
394
+ // started since `before`, whose user input is the prompt, and its last
395
+ // PLANNER_RESPONSE. The screen is not read for it: agy draws a refused
396
+ // call there too.
397
+ export function answerOf(brain, before, prompt, own = null) {
398
+ // its own words, not an image's or a video's mark, which other turns have too
399
+ const lines = prompt.split("\n").map((l) => l.trim())
400
+ const snip = (lines.find((l) => l.replace(MEDIA_MARK, "").trim()) ?? lines.find(Boolean))?.slice(0, 60) ?? ""
401
+ let ids = []
402
+ try { ids = fs.readdirSync(brain) } catch {}
403
+ for (const id of ids) {
404
+ // another turn's, of the same words, running beside this one
405
+ if (before.has(id) || (claimed.has(id) && id !== own)) continue
406
+ const file = path.join(brain, id, ".system_generated", "logs", "transcript_full.jsonl")
407
+ let text
408
+ try { text = fs.readFileSync(file, "utf8") } catch { continue }
409
+ let mine = false
410
+ let answer = ""
411
+ for (const line of text.split("\n")) {
412
+ let row
413
+ try { row = JSON.parse(line) } catch { continue }
414
+ const type = row.type ?? row.Type
415
+ const content = row.content ?? row.Content
416
+ if (type === "PLANNER_RESPONSE") {
417
+ if (mine && typeof content === "string" && content) answer = content
418
+ } else if (!mine && snip && Object.values(row).some((v) => typeof v === "string" && v.includes(snip))) {
419
+ mine = true
420
+ }
421
+ }
422
+ if (mine) return { id, answer }
423
+ }
424
+ return null
425
+ }
426
+
427
+ // screenTail is what agy drew last, for an error: its warning when it
428
+ // shows one ("⚠ …" up to the next rule), else the last lines.
429
+ export function screenTail(screen, n = 8) {
430
+ const lines = String(screen ?? "").split("\n").map((l) => l.trimEnd()).filter((l) => l.trim() && !l.includes(READY))
431
+ const warn = lines.findLastIndex((l) => l.trimStart().startsWith("⚠"))
432
+ if (warn >= 0) {
433
+ const out = []
434
+ for (const l of lines.slice(warn)) {
435
+ if (/^\s*─{3,}/.test(l)) break
436
+ out.push(l.trim())
437
+ }
438
+ return out.join("\n")
439
+ }
440
+ return lines.slice(-n).join("\n")
441
+ }
442
+
443
+ class Failure extends Error {
444
+ constructor(status, message, headers) {
445
+ super(message)
446
+ this.status = status
447
+ this.headers = headers
448
+ }
449
+ }
450
+
451
+ // startTurn starts agy in its terminal and types the prompt; it resolves
452
+ // once agy has the message, with `answer`, a promise of its reply.
453
+ export async function startTurn({ agy, home, model, prompt, media = [], signal, helper = process.env.MAGPIE_EXE }) {
454
+ if (!helper) throw new Failure(501, "this magpie has no tui-helper: update magpie")
455
+ settleHome(home)
456
+ const ws = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "agy-tui-")))
457
+ // agy's default agent, never --agent: the instructions in AGENTS.md, agy's
458
+ // bundled skills left out, and a PreToolUse hook that denies every tool
459
+ // call (what the old agent's `tools: []` did)
460
+ let hookEnv
461
+ let files
462
+ try {
463
+ hookEnv = await writeDefaultAgentFiles(ws, { instructions: INSTRUCTIONS, allowed: [], geminiDir: path.join(home, ".gemini") })
464
+ // the images and videos, in the turn's folder: agy copies each one it
465
+ // attaches into the conversation's own (forget removes it), and the
466
+ // folder goes with the turn
467
+ files = writeMedia(path.join(ws, "attachments"), media)
468
+ } catch (error) {
469
+ fs.rmSync(ws, { recursive: true, force: true })
470
+ throw new Failure(500, `agy-tui couldn't ready the turn's folder: ${error.message}`)
471
+ }
472
+ const brain = path.join(home, ".gemini", "antigravity-cli", "brain")
473
+ let before
474
+ try { before = new Set(fs.readdirSync(brain)) } catch { before = new Set() }
475
+
476
+ // the folder is trusted for this session only (never saved)
477
+ const settings = { trustedWorkspaces: [ws] }
478
+ const args = ["--settings", JSON.stringify(settings)]
479
+ // agy's own default customizations stay out, as the old agent's
480
+ // inheritCustomizations: false kept them
481
+ if ((await agyHelp(agy)).includes("--include-default-customizations")) args.push("--include-default-customizations=false")
482
+ if (model) args.push("--model", model)
483
+ const child = spawn(helper, ["tui-helper"], { env: { ...agyEnv(home), ...hookEnv }, cwd: ws, stdio: ["pipe", "pipe", "pipe"], windowsHide: true })
484
+ let screen = ""
485
+ let ended = null
486
+ let errorLine = ""
487
+ let stderr = ""
488
+ const waiters = new Set()
489
+ const poke = () => { for (const w of waiters) w() }
490
+ let buf = ""
491
+ child.stdout.setEncoding("utf8").on("data", (d) => {
492
+ buf += d
493
+ let i
494
+ while ((i = buf.indexOf("\n")) >= 0) {
495
+ const line = buf.slice(0, i)
496
+ buf = buf.slice(i + 1)
497
+ let o
498
+ try { o = JSON.parse(line) } catch { continue }
499
+ if (typeof o.screen === "string") screen = o.screen
500
+ if (o.error) errorLine = o.error
501
+ if (o.exit) ended = o.exit
502
+ }
503
+ poke()
504
+ })
505
+ child.stderr.setEncoding("utf8").on("data", (d) => { stderr = (stderr + d).slice(-4000) })
506
+ child.stdin.on("error", () => {})
507
+ const closed = new Promise((resolve) => child.on("close", () => { ended ??= { code: -1, error: errorLine || lastLine(stderr) || "the terminal ended" }; poke(); resolve() }))
508
+ child.on("error", (e) => { errorLine = e.message })
509
+ const send = (v) => { try { child.stdin.write(JSON.stringify(v) + "\n") } catch {} }
510
+ let cleaned = false
511
+ const cleanup = async () => {
512
+ if (cleaned) return
513
+ cleaned = true
514
+ send({ stop: true })
515
+ try { child.stdin.end() } catch {}
516
+ const late = setTimeout(() => { try { child.kill("SIGKILL") } catch {} }, 5000)
517
+ await closed
518
+ clearTimeout(late)
519
+ if (process.env.AGY_TUI_KEEP) return
520
+ fs.rmSync(ws, { recursive: true, force: true })
521
+ }
522
+ const onAbort = () => { cleanup() }
523
+ signal?.addEventListener?.("abort", onAbort, { once: true })
524
+
525
+ const waitFor = (what, ok, ms) => new Promise((resolve, reject) => {
526
+ const check = () => {
527
+ if (ok()) return done(resolve)
528
+ if (signal?.aborted) return done(() => reject(new Failure(499, "the request was cancelled")))
529
+ if (ended) return done(() => reject(new Failure(502, `agy ended ${what}: ${errorLine || ended.error || `exit ${ended.code}`}${screenTail(screen) ? `\n${screenTail(screen)}` : ""}`)))
530
+ }
531
+ const timer = setTimeout(() => done(() => reject(new Failure(504, `agy: no ${what} in ${Math.round(ms / 1000)}s${screenTail(screen) ? `:\n${screenTail(screen)}` : ""}`))), ms)
532
+ const tick = setInterval(check, 250)
533
+ const done = (f) => { clearTimeout(timer); clearInterval(tick); waiters.delete(check); f() }
534
+ waiters.add(check)
535
+ check()
536
+ })
537
+ const ready = () => screen.includes(READY) && !screen.includes(BUSY)
538
+
539
+ try {
540
+ send({ start: { path: agy, args, dir: ws, replies: REPLIES } })
541
+ await waitFor("prompt", ready, START_MS)
542
+ if (files.length) {
543
+ // pasted alone, the paths are attached, as files dragged onto the
544
+ // terminal are; the turn waits until agy shows every one attached,
545
+ // so a path agy took for text is never sent as the message
546
+ send({ write: `\x1b[200~${pastedPaths(files)}\x1b[201~` })
547
+ try {
548
+ await waitFor("attachment", () => attached(screen) >= files.length, attachTimeout())
549
+ } catch (error) {
550
+ if (error.status !== 504) throw error
551
+ throw new Failure(502, `agy didn't attach the ${files.length === 1 ? kindOf(media[0].type) : `${files.length} files`} (it shows ${attached(screen)})${screenTail(screen) ? `:\n${screenTail(screen)}` : ""}`)
552
+ }
553
+ }
554
+ send({ write: `\x1b[200~${prompt}\x1b[201~` })
555
+ await new Promise((r) => setTimeout(r, PASTE_SETTLE_MS))
556
+ send({ write: "\r" })
557
+ // agy has the message once it is in a turn, or its transcript has it
558
+ // (a turn that failed at once may never draw "esc to cancel")
559
+ await waitFor("turn", () => screen.includes(BUSY) || Boolean(answerOf(brain, before, prompt)), SUBMIT_MS)
560
+ } catch (error) {
561
+ await cleanup()
562
+ throw error
563
+ }
564
+
565
+ const answer = (async () => {
566
+ let found = null
567
+ try {
568
+ // back at its prompt with nothing in the transcript for a while:
569
+ // the turn failed, and what agy drew says why (a quota, a refusal)
570
+ let idleSince = 0
571
+ await waitFor("answer", () => {
572
+ if (!ready()) {
573
+ idleSince = 0
574
+ return false
575
+ }
576
+ found = answerOf(brain, before, prompt, found?.id)
577
+ if (found?.id) claimed.add(found.id)
578
+ if (found?.answer) return true
579
+ idleSince ||= Date.now()
580
+ return Date.now() - idleSince > IDLE_MS
581
+ }, turnTimeout())
582
+ if (!found?.answer) throw new Failure(502, `agy answered nothing${screenTail(screen) ? `:\n${screenTail(screen)}` : ""}`)
583
+ return found.answer
584
+ } finally {
585
+ await cleanup()
586
+ forget(brain, found?.id)
587
+ }
588
+ })()
589
+ return { answer }
590
+ }
591
+
592
+ // forget removes the conversation agy kept for a turn from the account's
593
+ // home: each request is a conversation of its own.
594
+ function forget(brain, id) {
595
+ if (!id) return
596
+ claimed.delete(id)
597
+ if (process.env.AGY_TUI_KEEP) return
598
+ fs.rmSync(path.join(brain, id), { recursive: true, force: true })
599
+ const conv = path.join(path.dirname(brain), "conversations")
600
+ try {
601
+ for (const name of fs.readdirSync(conv)) if (name.startsWith(id)) fs.rmSync(path.join(conv, name), { recursive: true, force: true })
602
+ } catch {}
603
+ }
604
+
605
+ // ---- OpenAI chat completions
606
+
607
+ function jsonError(status, message, headers = {}) {
608
+ return new Response(JSON.stringify({ error: { message, type: "agy_tui_error" } }), {
609
+ status,
610
+ headers: { "Content-Type": "application/json", ...headers },
611
+ })
612
+ }
613
+
614
+ function completion(id, model, text) {
615
+ return {
616
+ id,
617
+ object: "chat.completion",
618
+ created: Math.floor(Date.now() / 1000),
619
+ model,
620
+ choices: [{ index: 0, message: { role: "assistant", content: text }, finish_reason: "stop" }],
621
+ }
622
+ }
623
+
624
+ function streamOf(id, model, answer) {
625
+ const enc = new TextEncoder()
626
+ const created = Math.floor(Date.now() / 1000)
627
+ const chunk = (delta, finish = null) => `data: ${JSON.stringify({ id, object: "chat.completion.chunk", created, model, choices: [{ index: 0, delta, finish_reason: finish }] })}\n\n`
628
+ let keep
629
+ return new ReadableStream({
630
+ async start(c) {
631
+ c.enqueue(enc.encode(chunk({ role: "assistant", content: "" })))
632
+ // the turn may take minutes: a comment now and then keeps the
633
+ // connection from looking dead
634
+ keep = setInterval(() => { try { c.enqueue(enc.encode(": working\n\n")) } catch {} }, 15_000)
635
+ try {
636
+ const text = await answer
637
+ c.enqueue(enc.encode(chunk({ content: text })))
638
+ c.enqueue(enc.encode(chunk({}, "stop")))
639
+ } catch (error) {
640
+ c.enqueue(enc.encode(`data: ${JSON.stringify({ error: { message: error.message, type: "agy_tui_error" } })}\n\n`))
641
+ } finally {
642
+ clearInterval(keep)
643
+ }
644
+ c.enqueue(enc.encode("data: [DONE]\n\n"))
645
+ c.close()
646
+ },
647
+ cancel() { clearInterval(keep) },
648
+ })
649
+ }
650
+
651
+ export async function handle(home, input, init = {}) {
652
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input?.url || ""
653
+ if (!/\/chat\/completions(?:$|[?#])/.test(url)) return jsonError(404, `agy-tui serves chat completions, not ${url}`)
654
+ let body
655
+ try {
656
+ const raw = init.body != null ? (typeof init.body === "string" ? init.body : new TextDecoder().decode(init.body)) : await input.text()
657
+ body = JSON.parse(raw)
658
+ } catch {
659
+ return jsonError(400, "the request is not JSON")
660
+ }
661
+ if (!home) return jsonError(401, "agy-tui: no account; sign in again", { "X-Magpie-Sign-In": "expired" })
662
+ if (!fs.existsSync(tokenFile(home))) return jsonError(401, "agy-tui: the account's agy is signed out; sign in again", { "X-Magpie-Sign-In": "expired" })
663
+ const agy = findAgy()
664
+ if (!agy) return jsonError(503, `agy CLI not found on this machine: ${AGY_MANUAL}`)
665
+ const refusal = await agyRefusal(agy)
666
+ if (refusal) return jsonError(503, refusal)
667
+ const signal = init.signal ?? input?.signal
668
+ const id = `chatcmpl-${randomBytes(12).toString("hex")}`
669
+ const model = String(body.model ?? "")
670
+ let turn
671
+ try {
672
+ const { prompt, media } = turnOf(body.messages)
673
+ // agy attaches a video for any model, but only Gemini's see one
674
+ if (media.some((m) => kindOf(m.type) === "video") && !/^gemini-/.test(model)) throw refuse(`${model || "this model"} takes no video; a Gemini model does`)
675
+ turn = await startTurn({ agy, home, model, prompt, media, signal })
676
+ } catch (error) {
677
+ return jsonError(error.status ?? 502, error.message, error.headers)
678
+ }
679
+ if (body.stream) {
680
+ return new Response(streamOf(id, model, turn.answer), { status: 200, headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" } })
681
+ }
682
+ try {
683
+ return new Response(JSON.stringify(completion(id, model, await turn.answer)), { status: 200, headers: { "Content-Type": "application/json" } })
684
+ } catch (error) {
685
+ return jsonError(error.status ?? 502, error.message)
686
+ }
687
+ }
688
+
689
+ // ---- the plugin
690
+
691
+ export function modelEntry(m) {
692
+ return {
693
+ id: m.id,
694
+ name: m.name,
695
+ npm: NPM,
696
+ api: { id: m.id, url: "agy-tui://local", npm: NPM },
697
+ limit: { context: 1_000_000, output: 65_536 },
698
+ // Gemini's and Claude's see the images agy attaches, as agy-cli says,
699
+ // and Gemini's the videos too
700
+ ...(/^(?:gemini-|claude-)/.test(m.id) ? { capabilities: { attachment: true, input: { text: true, image: true, video: m.id.startsWith("gemini-"), audio: false, pdf: false }, output: { text: true } } } : {}),
701
+ }
702
+ }
703
+
704
+ function signIn(agy) {
705
+ let account
706
+ try {
707
+ account = newHome()
708
+ } catch (error) {
709
+ return { type: "failed", error: `couldn't make a folder for the account: ${error.message}` }
710
+ }
711
+ const fail = (error) => {
712
+ fs.rmSync(account.home, { recursive: true, force: true })
713
+ return { type: "failed", error }
714
+ }
715
+ return startLogin(agy, agyEnv(account.home)).then((login) => {
716
+ if (login.error) return fail(login.error)
717
+ return {
718
+ url: login.url,
719
+ instructions: "",
720
+ method: "code",
721
+ callback: async (code, opts = {}) => {
722
+ const done = await login.finish(code, { signal: opts.signal })
723
+ if (done.error) return fail(done.error)
724
+ try {
725
+ await listModels(agy, account.home)
726
+ } catch (error) {
727
+ return fail(`agy signed in, but ${error.message}`)
728
+ }
729
+ return { type: "success", key: `agy-tui:${account.id}`, metadata: { agyHome: account.id } }
730
+ },
731
+ }
732
+ })
733
+ }
734
+
735
+ export const AgyTuiPlugin = async () => ({
736
+ auth: {
737
+ provider: PROVIDER_ID,
738
+ methods: [
739
+ {
740
+ // agy's own Google sign-in (`agy acp --login`), in the account's
741
+ // home: magpie opens its link and takes the code the page shows
742
+ type: "oauth",
743
+ label: "Sign in with Google",
744
+ labels: { zh: "使用 Google 登录", "zh-TW": "使用 Google 登入", ja: "Google でサインイン" },
745
+ authorize: async () => {
746
+ const agy = findAgy()
747
+ if (!agy) return { type: "failed", error: `agy CLI not found. Install Antigravity CLI: ${AGY_MANUAL}` }
748
+ return signIn(agy)
749
+ },
750
+ },
751
+ ],
752
+ loader: async (getAuth) => {
753
+ const auth = typeof getAuth === "function" ? await getAuth() : getAuth
754
+ const home = homeOfAuth(auth)
755
+ return {
756
+ baseURL: "agy-tui://local",
757
+ apiKey: "agy-tui",
758
+ fetch: (input, init) => handle(home, input, init),
759
+ }
760
+ },
761
+ },
762
+ config: async (cfg) => {
763
+ cfg.provider ??= {}
764
+ const was = cfg.provider[PROVIDER_ID] ?? {}
765
+ cfg.provider[PROVIDER_ID] = { npm: NPM, ...was, name: was.name || PROVIDER_NAME }
766
+ },
767
+ provider: {
768
+ id: PROVIDER_ID,
769
+ npm: NPM,
770
+ models: async (_given, ctx) => {
771
+ const home = homeOfAuth(ctx?.auth)
772
+ const agy = findAgy()
773
+ if (!home || !agy) return {}
774
+ const out = {}
775
+ for (const m of await listModels(agy, home)) out[m.id] = modelEntry(m)
776
+ return out
777
+ },
778
+ },
779
+ })
780
+
781
+ export default { id: PROVIDER_ID, server: AgyTuiPlugin }