Repository navigation
Expand file tree
/
Copy pathinstall.mjs
More file actions
436 lines (408 loc) · 17.7 KB
/
Copy pathinstall.mjs
File metadata and controls
436 lines (408 loc) · 17.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
// Installs agy where the machine has none, as Antigravity's own installer
// does (https://antigravity.google/cli/install.sh, install.ps1): the
// platform's manifest names the version, the download and its sha512; a
// Unix download is a tar.gz holding the binary as `antigravity`, a Windows
// one the exe itself. magpie's sign-in runs it (auth.cli) when agy isn't
// there, so a magpie in a container, which has no shell to run the
// installer in, gets agy too (niuniu_8964 on X). It goes into the plugin's
// own folder (ownAgyPath), which only this file writes, and keepAgyCurrent
// keeps that copy at the manifest's version. Not done: `agy install`, which
// the official installer runs to put agy on the user's PATH; the plugin
// finds its copy itself.
import { spawn } from "node:child_process"
import { createHash, randomBytes } from "node:crypto"
import fs from "node:fs"
import os from "node:os"
import path from "node:path"
import { createGunzip } from "node:zlib"
import { agySpawnSpec, childEnv, ownAgyPath } from "./platform.mjs"
import { agyTooOld, oldAgyError } from "./agy-version.mjs"
const MANIFESTS = "https://antigravity-cli-auto-updater-974169037036.us-central1.run.app/manifests/"
export const AGY_MANUAL = process.platform === "win32"
? "irm https://antigravity.google/cli/install.ps1 | iex"
: "curl -fsSL https://antigravity.google/cli/install.sh | bash"
const KEEP_FIRST_MS = 60_000
const KEEP_EVERY_MS = 6 * 60 * 60 * 1000
// manifestBase is where the manifests are read; AGY_BRIDGE_INSTALL_BASE
// points it elsewhere (the tests' own server).
function manifestBase(env = process.env) {
const base = (env.AGY_BRIDGE_INSTALL_BASE || "").trim()
return base ? base.replace(/\/?$/, "/") : MANIFESTS
}
function muslLinux() {
for (const lib of ["/lib/libc.musl-x86_64.so.1", "/lib/libc.musl-aarch64.so.1"]) {
if (fs.existsSync(lib)) return true
}
try {
// Bun and Node say which glibc they run on; a musl build says none
const header = process.report?.getReport?.()?.header
if (header && !header.glibcVersionRuntime) return true
} catch {}
return false
}
// agyPlatform is the installer's name for this machine, null for one
// Antigravity builds nothing for here (Android's Termux needs its own
// installer).
export function agyPlatform(platform = process.platform, arch = process.arch, musl = platform === "linux" && muslLinux()) {
const cpu = { x64: "amd64", arm64: "arm64" }[arch]
if (!cpu) return null
if (platform === "linux") return `linux_${cpu}${musl ? "_musl" : ""}`
if (platform === "darwin") return `darwin_${cpu}`
if (platform === "win32") return `windows_${cpu}`
return null
}
function ownPath() {
return ownAgyPath(process.env, os.homedir())
}
function versionFile(bin) {
return bin + ".version"
}
export async function readManifest(platform = agyPlatform(), { signal } = {}) {
if (!platform) throw new Error(`Antigravity CLI has no build for ${process.platform} ${process.arch}`)
const url = manifestBase() + platform + ".json"
let res
try {
res = await fetch(url, { signal })
} catch (error) {
if (signal?.aborted) throw error
throw new Error(`couldn't reach Antigravity's release server: ${error?.message || error}`)
}
if (!res.ok) throw new Error(`Antigravity's release server answered ${res.status} for ${platform}`)
const m = await res.json().catch(() => null)
if (!m || typeof m.url !== "string" || !/^https?:\/\//.test(m.url) || !/^[0-9a-f]{128}$/i.test(String(m.sha512 || ""))) {
throw new Error("Antigravity's release manifest isn't one")
}
const version = String(m.version || "")
checkReleaseVersion(version)
return { version, url: m.url, sha512: String(m.sha512).toLowerCase(), platform }
}
function checkReleaseVersion(version) {
const tooOld = agyTooOld(version)
if (tooOld) throw new Error(tooOld)
}
// withOutput gives fill a write(chunk) for file that awaits the disk, and
// returns only once the handle has closed (a WriteStream's `finish` comes
// while the fd is still open for writing: ETXTBSY on Linux), failing if
// the write or the close does, after the partial file is closed.
async function withOutput(file, mode, fill) {
const handle = await fs.promises.open(file, "w", mode)
try {
await fill((chunk) => handle.writeFile(chunk))
} finally {
await handle.close()
}
}
// download writes url to file, hashing as it goes, and returns the sha512.
async function download(url, file, signal) {
const res = await fetch(url, { signal })
if (!res.ok || !res.body) throw new Error(`downloading agy failed: ${res.status}`)
const hash = createHash("sha512")
await withOutput(file, 0o600, async (write) => {
for await (const chunk of res.body) {
hash.update(chunk)
await write(chunk)
}
})
return hash.digest("hex")
}
// untarMember copies the regular file named name out of a .tar.gz into
// file (mode 755), and says whether it was there. A tar entry is a
// 512-byte header and its data padded to 512; a GNU long name ("L") or a
// pax header ("x") names the entry after it.
export async function untarMember(archive, name, file) {
const gz = fs.createReadStream(archive).pipe(createGunzip())
const it = gz[Symbol.asyncIterator]()
let buf = Buffer.alloc(0)
const fill = async (n) => {
while (buf.length < n) {
const r = await it.next()
if (r.done) return false
buf = buf.length ? Buffer.concat([buf, r.value]) : r.value
}
return true
}
// pass hands the next n bytes to fn a chunk at a time
const pass = async (n, fn) => {
while (n > 0) {
if (!buf.length) {
const r = await it.next()
if (r.done) throw new Error("the agy download is cut short")
buf = r.value
}
const k = Math.min(n, buf.length)
await fn(buf.subarray(0, k))
buf = buf.subarray(k)
n -= k
}
}
const skip = () => {}
let longName = null
try {
for (;;) {
if (!(await fill(512))) return false
const header = buf.subarray(0, 512)
buf = buf.subarray(512)
if (header.every((b) => b === 0)) continue
const field = (at, len) => header.subarray(at, at + len).toString("utf8").replace(/\0.*$/s, "")
const size = parseInt(field(124, 12).trim() || "0", 8)
if (!Number.isFinite(size) || size < 0) throw new Error("the agy download isn't a tar archive")
const pad = (512 - (size % 512)) % 512
const type = field(156, 1) || "0"
if (type === "L" || type === "x") {
if (size > 1 << 20) throw new Error("the agy download isn't a tar archive")
const parts = []
await pass(size, (c) => { parts.push(Buffer.from(c)) })
await pass(pad, skip)
const text = Buffer.concat(parts).toString("utf8")
if (type === "L") longName = text.replace(/\0.*$/s, "")
else {
const m = /(?:^|\n)\d+ path=([^\n]*)\n/.exec(text)
if (m) longName = m[1]
}
continue
}
const prefix = field(345, 155)
const entry = (longName ?? (prefix ? prefix + "/" + field(0, 100) : field(0, 100))).replace(/^\.\//, "")
longName = null
if ((type === "0" || type === "7") && entry === name) {
await withOutput(file, 0o755, (write) => pass(size, write))
return true
}
await pass(size + pad, skip)
}
} finally {
gz.destroy()
}
}
// run runs agy and resolves with its exit code and output. update runs it
// as a person's own agy runs, with its updates on (asked only when the user
// didn't turn them off, updatesOff).
function run(file, args, { timeoutMs = 30_000, signal, update = false } = {}) {
return new Promise((resolve) => {
let output = ""
let stdout = ""
let child
const env = childEnv(process.env)
if (update) delete env.AGY_CLI_DISABLE_AUTO_UPDATE
try {
const spec = agySpawnSpec(file, args)
child = spawn(spec.file, spec.args, { ...spec.options, env, stdio: ["ignore", "pipe", "pipe"], windowsHide: true })
} catch (error) {
resolve({ code: -1, output: String(error?.message || error), stdout: "" })
return
}
const stop = () => { try { child.kill() } catch {} }
const timer = setTimeout(stop, timeoutMs)
signal?.addEventListener?.("abort", stop, { once: true })
const done = (value) => {
clearTimeout(timer)
signal?.removeEventListener?.("abort", stop)
resolve(value)
}
child.stdout.on("data", (d) => { output += d; stdout += d })
child.stderr.on("data", (d) => { output += d })
child.on("error", (error) => done({ code: -1, output: String(error?.message || error), stdout }))
child.on("close", (code) => done({ code, output, stdout }))
})
}
function lastLine(text) {
return String(text).trim().split(/\r?\n/).filter(Boolean).pop() || ""
}
// installAgy puts the manifest's agy at bin (the plugin's own copy unless
// a test says otherwise): downloaded, checked against the manifest's
// sha512, taken out of its archive, run once with --version, then renamed
// over the old copy, so a running agy and a second install racing this one
// each see a whole binary. It returns the version installed.
export async function installAgy({ signal, bin = ownPath(), platform = agyPlatform(), manifest } = {}) {
const m = manifest || (await readManifest(platform, { signal }))
if (manifest) checkReleaseVersion(m.version)
const windows = (platform || "").startsWith("windows_")
const dir = path.dirname(bin)
fs.mkdirSync(dir, { recursive: true })
const tag = randomBytes(6).toString("hex")
const payload = path.join(dir, `.download-${tag}`)
const staged = path.join(dir, `.agy-${tag}${windows ? ".exe" : ""}`)
try {
const sum = await download(m.url, payload, signal)
if (sum !== m.sha512) throw new Error("the agy download doesn't match the checksum Antigravity's manifest gives; nothing was installed")
if (/\.tar\.gz(?:$|\?)/.test(m.url)) {
if (!(await untarMember(payload, "antigravity", staged))) throw new Error("the agy download has no agy in it")
} else {
fs.renameSync(payload, staged)
}
if (!windows) fs.chmodSync(staged, 0o755)
if (signal?.aborted) throw new DOMException("the install was cancelled", "AbortError")
const check = await run(staged, ["--version"])
if (check.code !== 0) throw new Error(`the downloaded agy doesn't run here (${lastLine(check.output) || `exit ${check.code}`})`)
checkReleaseVersion(lastLine(check.output).replace(/^agy\s+/i, ""))
if (windows && fs.existsSync(bin)) {
// a running exe can't be replaced on Windows, but it can be moved
try { fs.renameSync(bin, path.join(dir, `.old-${tag}.exe`)) } catch {}
}
fs.renameSync(staged, bin)
try { fs.writeFileSync(versionFile(bin), m.version + "\n") } catch {}
return m.version
} finally {
for (const f of [payload, staged]) {
try { fs.rmSync(f, { force: true }) } catch {}
}
sweepOld(dir)
}
}
// sweepOld removes the Windows copies an update moved aside, once nothing
// runs them.
function sweepOld(dir) {
try {
for (const name of fs.readdirSync(dir)) {
if (/^\.old-[0-9a-f]+\.exe$/.test(name)) {
try { fs.rmSync(path.join(dir, name), { force: true }) } catch {}
}
}
} catch {}
}
// installedVersion is the version the plugin's copy at bin is, "" when
// unknown.
export function installedVersion(bin = ownPath()) {
try {
return fs.readFileSync(versionFile(bin), "utf8").trim()
} catch {
return ""
}
}
// updateOwnAgy brings the plugin's copy to the manifest's version. It
// leaves alone an agy the plugin didn't install (the user's own updates
// itself), a machine where the plugin's copy isn't the one used, and a
// user who turned agy's updates off (AGY_CLI_DISABLE_AUTO_UPDATE).
export async function updateOwnAgy({ signal, bin = ownPath(), used, platform = agyPlatform(), env = process.env } = {}) {
if (updatesOff(env)) return "off"
if (!fs.existsSync(bin)) return "none"
if (used && path.resolve(used) !== path.resolve(bin)) return "not used"
const m = await readManifest(platform, { signal })
if (m.version && m.version === installedVersion(bin)) return "current"
await installAgy({ signal, bin, platform, manifest: m })
return "updated"
}
let keeping = false
// keepAgyCurrent checks for a newer agy a minute after the plugin starts
// and every six hours after, as magpie keeps its own Claude Code current.
export function keepAgyCurrent(findAgy) {
if (keeping) return
keeping = true
const tick = async () => {
try {
const was = await updateOwnAgy({ used: findAgy() })
if (was === "updated") console.error(`agy-cli: updated its agy to ${installedVersion()}`)
} catch (error) {
console.error(`agy-cli: couldn't update its agy: ${error?.message || error}`)
}
setTimeout(tick, KEEP_EVERY_MS).unref?.()
}
setTimeout(tick, KEEP_FIRST_MS).unref?.()
}
// updatesOff says the user turned agy's updates off.
function updatesOff(env = process.env) {
return Object.keys(env).some((k) => k.toUpperCase() === "AGY_CLI_DISABLE_AUTO_UPDATE")
}
// ---- an agy too old for this plugin ----------------------------------------
//
// agy updates itself when a person runs it, so an agy only magpie runs can
// stay at the version it came at. One before 1.5.0 has no `agy acp --login`
// and took "acp" for a prompt, so magpie's sign-in failed with "Prompts are
// read only from -p/--print, …" (wangmaoning on X, an Intel Mac). magpie's
// sign-in brings it up first: auth.cli's installed() is false for it, and
// install() runs freshenAgy.
// A first start after an update can take a while to say its version
// (plugins#1544).
const VERSION_TIMEOUT_MS = 30_000
const UPDATE_TIMEOUT_MS = 5 * 60 * 1000
// path, size and mtime → the read of `agy --version` (a promise), and what
// it said once it has
const versionReads = new Map()
const versionsSaid = new Map()
function binaryKey(file) {
try {
const st = fs.statSync(file)
return `${file}\0${st.size}\0${st.mtimeMs}`
} catch {
return null
}
}
// agyVersionOf is what `agy --version` says, read once for each binary (an
// agy updated in place is read again): "" when agy turned the flag down as
// an argument it doesn't know (one older than its --version), null when it
// couldn't be run or didn't say (asked again next time).
export function agyVersionOf(file) {
const key = binaryKey(file)
if (!key) return Promise.resolve(null)
let read = versionReads.get(key)
if (!read) {
read = run(file, ["--version"], { timeoutMs: VERSION_TIMEOUT_MS }).then((r) => {
const said = /\b\d+\.\d+\.\d+\b/.exec(r.stdout)?.[0]
const version = r.code === 0 && said ? said : r.code > 0 && NO_VERSION_FLAG.test(r.output) ? "" : null
if (version === null) versionReads.delete(key)
else versionsSaid.set(key, version)
return version
})
versionReads.set(key, read)
}
return read
}
// an agy with no --version takes it for an argument it doesn't know
const NO_VERSION_FLAG = /unexpected argument|unknown flag|flag provided but not defined|Prompts are read only from/
function isOutdated(version) {
return version === "" || Boolean(agyTooOld(version))
}
// outdatedAgy is { version } when this plugin can't run file: older than
// MIN_AGY_VERSION, or naming no version at all (an agy older than its
// --version). null when it can, or when it couldn't be asked.
export async function outdatedAgy(file) {
const version = await agyVersionOf(file)
return version !== null && isOutdated(version) ? { version } : null
}
// pickAgy is found (the agy the search found first), or the plugin's own
// copy in its place when found is too old and the copy isn't: freshenAgy
// installs one where found couldn't be updated. It never waits: found's
// version is what it said already (asked now when it hasn't been), and the
// copy's is the one installAgy wrote beside it.
export function pickAgy(found, own = ownPath()) {
if (!found || path.resolve(found) === path.resolve(own)) return found
try {
fs.accessSync(own, fs.constants.X_OK)
} catch {
return found
}
const ownVersion = installedVersion(own)
if (!ownVersion || isOutdated(ownVersion)) return found
const key = binaryKey(found)
if (key && versionsSaid.has(key)) return isOutdated(versionsSaid.get(key)) ? own : found
agyVersionOf(found).catch(() => {})
return found
}
// freshenAgy brings found, an agy too old for this plugin, up: with agy's
// own updater (`agy update`, which agy runs itself when a person uses it),
// unless the user turned agy's updates off; where that leaves it old, with
// a copy of the plugin's own (installAgy), which pickAgy uses in its place
// (not copy: the agy the user named in AGY_PATH is never swapped). It says
// which agy, what it needs and what to run when neither worked.
export async function freshenAgy(found, { signal, own = ownPath(), platform = agyPlatform(), env = process.env, updateMs = UPDATE_TIMEOUT_MS, copy = true } = {}) {
const old = await outdatedAgy(found)
if (!old) return "current"
const tried = []
if (path.resolve(found) !== path.resolve(own) && !updatesOff(env)) {
const r = await run(found, ["update"], { timeoutMs: updateMs, signal, update: true })
if (signal?.aborted) throw new DOMException("the install was cancelled", "AbortError")
const still = await outdatedAgy(found)
if (!still) return "updated"
tried.push(r.code === 0 ? `"agy update" left it at ${still.version || "the same version"}`
: `"agy update" failed (${lastLine(r.output) || `exit ${r.code}`})`)
}
if (!copy) throw new Error(oldAgyError(old.version, found, tried.join("; ")))
try {
await installAgy({ signal, bin: own, platform })
if (fs.existsSync(own) && !(await outdatedAgy(own))) return "installed"
} catch (error) {
if (signal?.aborted) throw error
tried.push(`installing a copy for magpie failed (${error?.message || error})`)
}
throw new Error(oldAgyError(old.version, found, tried.join("; ")))
}