@magpie-community/opencode-agy-tui-auth 0.0.0-stage → 0.1.4

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