@wengine-ai/ccr-provider-gemini-agy-acp 0.0.1 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,185 @@
1
+ // Official agy installer, in-process and proxy-aware. It mirrors the vendor
2
+ // bootstrappers (antigravity.google/cli/install.sh / install.ps1) step for
3
+ // step: query the pinned release manifest for THIS platform/architecture,
4
+ // download over HTTPS with curl (which honors the gateway's
5
+ // HTTPS_PROXY/HTTP_PROXY/NO_PROXY environment natively), verify the SHA-512
6
+ // checksum, extract the unix tarball member and place the binary at the
7
+ // official default location. No remote script is ever piped into a shell.
8
+ import { createHash, randomUUID } from 'node:crypto';
9
+ import { execFile } from 'node:child_process';
10
+ import { createReadStream, existsSync } from 'node:fs';
11
+ import { chmod, copyFile, mkdir, mkdtemp, rename, rm, stat } from 'node:fs/promises';
12
+ import { homedir, tmpdir } from 'node:os';
13
+ import { proxyEnvOverlay } from './transport.mjs';
14
+ import { dirname, join } from 'node:path';
15
+ import { failure } from './chat.mjs';
16
+
17
+ const MANIFEST_BASE = 'https://antigravity-cli-auto-updater-974169037036.us-central1.run.app';
18
+ // The manifest endpoint is pinned to the vendor updater; payloads may only
19
+ // come from the vendor's public bucket (or the updater itself), always HTTPS.
20
+ const PAYLOAD_HOSTS = new Set([
21
+ 'storage.googleapis.com',
22
+ 'antigravity-cli-auto-updater-974169037036.us-central1.run.app',
23
+ ]);
24
+ const MAX_PAYLOAD_BYTES = 400 * 1024 * 1024;
25
+ const MANIFEST_TIMEOUT_MS = 20_000;
26
+ const DOWNLOAD_TIMEOUT_MS = 600_000;
27
+ const EXTRACT_TIMEOUT_MS = 120_000;
28
+ const HANDOFF_TIMEOUT_MS = 30_000;
29
+
30
+ /** The vendor manifest key for this OS/CPU, exactly like the bootstrappers'
31
+ * uname/PROCESSOR_ARCHITECTURE detection (including the Linux musl builds). */
32
+ export function platformKey(platform = process.platform, arch = process.arch) {
33
+ const cpu = { x64: 'amd64', arm64: 'arm64' }[arch];
34
+ if (!cpu) throw failure('agy_install_unsupported_platform', 503);
35
+ if (platform === 'darwin') return `darwin_${cpu}`;
36
+ if (platform === 'win32') return `windows_${cpu}`;
37
+ if (platform === 'linux') {
38
+ const musl = arch === 'x64' ? '/lib/libc.musl-x86_64.so.1' : '/lib/libc.musl-aarch64.so.1';
39
+ if (existsSync(musl)) return `linux_${cpu}_musl`;
40
+ return `linux_${cpu}`;
41
+ }
42
+ throw failure('agy_install_unsupported_platform', 503);
43
+ }
44
+
45
+ /** The official default install location: ~/.local/bin/agy on unix,
46
+ * %LOCALAPPDATA%\agy\bin\agy.exe on Windows (install.ps1's TARGET_DIR). */
47
+ export function defaultBinaryPath(platform = process.platform, env = process.env, home = homedir()) {
48
+ if (platform === 'win32') {
49
+ const local = typeof env.LOCALAPPDATA === 'string' && env.LOCALAPPDATA
50
+ ? env.LOCALAPPDATA : join(home, 'AppData', 'Local');
51
+ return join(local, 'agy', 'bin', 'agy.exe');
52
+ }
53
+ return join(home, '.local', 'bin', 'agy');
54
+ }
55
+
56
+ /** Manifest shape + provenance gate: a bounded version string, a 128-hex
57
+ * SHA-512 and an HTTPS payload URL on the vendor allowlist. Anything else
58
+ * fails closed before a single payload byte is fetched. */
59
+ export function validateManifest(text) {
60
+ let manifest;
61
+ try { manifest = JSON.parse(text); } catch { throw failure('agy_install_manifest_invalid', 502); }
62
+ const { version, url, sha512 } = manifest ?? {};
63
+ if (typeof version !== 'string' || !version || version.length > 64 || /[\0-\x1f\x7f]/.test(version)) {
64
+ throw failure('agy_install_manifest_invalid', 502);
65
+ }
66
+ if (typeof sha512 !== 'string' || !/^[0-9a-fA-F]{128}$/.test(sha512)) {
67
+ throw failure('agy_install_manifest_invalid', 502);
68
+ }
69
+ let parsed;
70
+ try { parsed = new URL(url); } catch { throw failure('agy_install_manifest_invalid', 502); }
71
+ if (parsed.protocol !== 'https:' || !PAYLOAD_HOSTS.has(parsed.hostname)) {
72
+ throw failure('agy_install_manifest_invalid', 502);
73
+ }
74
+ return { version, url: parsed.href, sha512: sha512.toLowerCase() };
75
+ }
76
+
77
+ /** execFile wrapper: the inherited environment carries the gateway's proxy
78
+ * variables and curl applies them itself; no shell is involved anywhere. */
79
+ function defaultRun(command, args, { timeoutMs, capture = false, env } = {}) {
80
+ return new Promise((resolve, reject) => {
81
+ execFile(command, args, {
82
+ timeout: timeoutMs,
83
+ windowsHide: true,
84
+ maxBuffer: capture ? 1024 * 1024 : 64 * 1024,
85
+ ...(env ? { env } : {}),
86
+ }, (error, stdout) => {
87
+ if (error) reject(error); else resolve(capture ? String(stdout) : '');
88
+ });
89
+ });
90
+ }
91
+
92
+ /** A single-flight-capable installer bound to one platform/target. `run` is
93
+ * injectable so tests exercise the whole flow without network or real agy. */
94
+ export function createInstaller(options = {}) {
95
+ const {
96
+ platform = process.platform,
97
+ arch = process.arch,
98
+ env = process.env,
99
+ home = homedir(),
100
+ run: baseRun = defaultRun,
101
+ proxyUrl,
102
+ maxPayloadBytes = MAX_PAYLOAD_BYTES,
103
+ manifestTimeoutMs = MANIFEST_TIMEOUT_MS,
104
+ downloadTimeoutMs = DOWNLOAD_TIMEOUT_MS,
105
+ } = options;
106
+ // curl and the agy installer honor the standard proxy variables; fill them
107
+ // from the gateway config when the inherited environment sets none.
108
+ const overlay = proxyEnvOverlay(env, proxyUrl);
109
+ const installEnv = overlay ? { ...env, ...overlay } : undefined;
110
+ const run = (command, args, opts = {}) => baseRun(command, args, installEnv ? { ...opts, env: installEnv } : opts);
111
+ const targetBinary = defaultBinaryPath(platform, env, home);
112
+ const curl = platform === 'win32' ? 'curl.exe' : 'curl';
113
+ const tar = platform === 'win32' ? 'tar.exe' : 'tar';
114
+ // Redirects may never downgrade to plain HTTP or leave the HTTPS scheme.
115
+ const httpsOnly = ['--proto', '=https', '--proto-redir', '=https'];
116
+ const seconds = ms => String(Math.ceil(ms / 1000));
117
+
118
+ async function install() {
119
+ const key = platformKey(platform, arch);
120
+ let manifest;
121
+ try {
122
+ manifest = validateManifest(await run(curl,
123
+ ['-fsSL', ...httpsOnly, '--retry', '2', '--max-time', seconds(manifestTimeoutMs),
124
+ `${MANIFEST_BASE}/manifests/${key}.json`],
125
+ { timeoutMs: manifestTimeoutMs, capture: true }));
126
+ } catch (error) {
127
+ if (typeof error?.code === 'string' && error.code.startsWith('agy_install_')) throw error;
128
+ throw failure('agy_install_manifest_failed', 502);
129
+ }
130
+ const staging = await mkdtemp(join(tmpdir(), 'agy-install-'));
131
+ try {
132
+ const payload = join(staging, 'payload');
133
+ try {
134
+ await run(curl,
135
+ ['-fsSL', ...httpsOnly, '--retry', '2', '--max-time', seconds(downloadTimeoutMs),
136
+ '--max-filesize', String(maxPayloadBytes), '-o', payload, manifest.url],
137
+ { timeoutMs: downloadTimeoutMs + 5000 });
138
+ } catch { throw failure('agy_install_download_failed', 502); }
139
+ // --max-filesize only bites when Content-Length is known; the post-download
140
+ // stat is the unconditional byte cap.
141
+ let size;
142
+ try { size = (await stat(payload)).size; } catch { throw failure('agy_install_download_failed', 502); }
143
+ if (size > maxPayloadBytes) throw failure('agy_install_too_large', 502);
144
+ const hash = createHash('sha512');
145
+ await new Promise((resolve, reject) => {
146
+ createReadStream(payload).on('error', reject).on('data', chunk => hash.update(chunk)).on('end', resolve);
147
+ });
148
+ if (hash.digest('hex') !== manifest.sha512) throw failure('agy_install_checksum_mismatch', 502);
149
+ // Unix releases are tar.gz with a single `antigravity` member (the
150
+ // bootstrapper extracts exactly that name); Windows ships a raw .exe.
151
+ let binarySource = payload;
152
+ if (new URL(manifest.url).pathname.endsWith('.tar.gz')) {
153
+ try {
154
+ await run(tar, ['-xzf', payload, '-C', staging, 'antigravity'], { timeoutMs: EXTRACT_TIMEOUT_MS });
155
+ } catch { throw failure('agy_install_extract_failed', 502); }
156
+ binarySource = join(staging, 'antigravity');
157
+ }
158
+ // Atomic placement: copy to a temp name IN the target directory, chmod
159
+ // there, then rename. A crash mid-copy can never leave a truncated file
160
+ // at the official path (which status would report as detectedBinary),
161
+ // and on unix the rename safely replaces a running executable.
162
+ const temporary = join(dirname(targetBinary), `.agy-${randomUUID()}.tmp`);
163
+ try {
164
+ await mkdir(dirname(targetBinary), { recursive: true });
165
+ await copyFile(binarySource, temporary);
166
+ if (platform !== 'win32') await chmod(temporary, 0o755);
167
+ await rename(temporary, targetBinary);
168
+ } catch {
169
+ await rm(temporary, { force: true }).catch(() => {});
170
+ throw failure('agy_install_write_failed', 500);
171
+ }
172
+ // Best-effort vendor handoff, exactly like the bootstrappers' `|| true`
173
+ // steps: clear macOS quarantine and let agy configure the shell PATH.
174
+ if (platform === 'darwin') {
175
+ await run('xattr', ['-d', 'com.apple.quarantine', targetBinary], { timeoutMs: 5000 }).catch(() => {});
176
+ }
177
+ await run(targetBinary, ['install'], { timeoutMs: HANDOFF_TIMEOUT_MS }).catch(() => {});
178
+ return { version: manifest.version, binary: targetBinary };
179
+ } finally {
180
+ await rm(staging, { recursive: true, force: true }).catch(() => {});
181
+ }
182
+ }
183
+
184
+ return { install, targetBinary };
185
+ }