@wengine-ai/ccr-provider-gemini-agy-acp 0.0.2 → 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.
package/dist/src/chat.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  import { randomUUID } from 'node:crypto';
2
+ import { MAX_CALLS_PER_TURN } from './agy-tool-bridge.mjs';
2
3
 
3
4
  export function failure(code, statusCode, message = code) {
4
5
  return Object.assign(new Error(message), { code, statusCode, nonRetryable: true });
@@ -17,24 +18,54 @@ function contentText(content) {
17
18
  unsupported('Only text message content is supported.');
18
19
  }
19
20
 
20
- // Check the original Fastify body too: endpoint normalization can drop unknown
21
- // roles, tool details and non-text content before the provider transformer runs.
21
+ /**
22
+ * Text-only validation: the contract for a request that declares no tools.
23
+ */
22
24
  export function textTurns(body) {
25
+ assertNoTools(body);
26
+ return textTurnsOnly(body);
27
+ }
28
+
29
+ /** Reject tool declarations; used only by the text-only path. */
30
+ export function assertNoTools(body) {
23
31
  if ((body.tools !== undefined && !(Array.isArray(body.tools) && !body.tools.length)) ||
24
32
  body.tool_choice != null || body.functions != null || body.function_call != null ||
25
33
  body.parallel_tool_calls != null || body.audio != null ||
26
34
  (body.modalities != null && !(Array.isArray(body.modalities) && body.modalities.length === 1 && body.modalities[0] === 'text'))) {
27
35
  unsupported('Tools, function calling and non-text modalities are unsupported.');
28
36
  }
37
+ }
38
+
39
+ /**
40
+ * Message and content validation shared by both paths.
41
+ *
42
+ * Tool-bearing messages are allowed here, but only when they actually carry a
43
+ * call: an assistant turn with `tool_calls: []` and a `tool` role result have
44
+ * no tool turn behind them, so they stay a text-only rejection. Their payload
45
+ * is carried through, never executed.
46
+ */
47
+ export function textTurnsOnly(body) {
29
48
  if (!Array.isArray(body.messages) || !body.messages.length) unsupported('Expected one or more messages.');
30
49
  const turns = [];
31
50
  if (body.system !== undefined) turns.push({ role: 'system', content: contentText(body.system) });
32
51
  for (const msg of body.messages) {
33
- if (!['system', 'user', 'assistant'].includes(msg?.role)) unsupported('Unsupported message role.');
34
- if (['tool_calls', 'tool_call_id', 'function_call', 'audio', 'refusal', 'thinking', 'name'].some(key => msg[key] != null)) {
52
+ if (!['system', 'user', 'assistant', 'tool', 'function'].includes(msg?.role)) unsupported('Unsupported message role.');
53
+ if (['audio', 'refusal'].some(key => msg[key] != null)) unsupported('Only unnamed text messages are supported.');
54
+ // A tool-bearing message is allowed here, but only when it actually carries
55
+ // a call: `tool_calls: []` declares nothing, so it stays a text-only
56
+ // rejection. A `tool` role message is itself the result, and its id is what
57
+ // ties it back to the call, so that is not an unnamed-text violation either.
58
+ const carriesCall = Array.isArray(msg.tool_calls) && msg.tool_calls.length > 0;
59
+ const isToolResult = msg.role === 'tool';
60
+ const toolKeys = ['tool_call_id', 'function_call', 'thinking', 'name'];
61
+ if (!carriesCall && !isToolResult &&
62
+ (toolKeys.some(key => msg[key] != null) || msg.tool_calls != null)) {
35
63
  unsupported('Only unnamed text messages are supported.');
36
64
  }
37
- turns.push({ role: msg.role, content: contentText(msg.content) });
65
+ // An assistant turn that only carries tool calls, and a tool result, have no
66
+ // text of their own.
67
+ const content = msg.content == null ? '' : contentText(msg.content);
68
+ turns.push({ role: msg.role, content });
38
69
  }
39
70
  return turns;
40
71
  }
@@ -50,18 +81,28 @@ export function toPrompt(body, provider, original) {
50
81
  if (thinking !== undefined && !['none', 'low', 'medium', 'high', 'extra', 'xhigh', 'max'].includes(thinking)) {
51
82
  unsupported('Unsupported thinking effort.');
52
83
  }
53
- const turns = textTurns(body);
84
+ const turns = textTurnsOnly(body);
54
85
  return { model, thinking, prompt: turns.length === 1 && turns[0].role === 'user' ? turns[0].content :
55
86
  'Continue the following conversation as the assistant. Ordered text messages (JSON):\n' + JSON.stringify(turns) };
56
87
  }
57
88
 
89
+ /**
90
+ * Errors the plugin itself raises, whose message is safe to show the caller.
91
+ * Everything else comes from the transport contract, which deliberately
92
+ * exposes stable codes and status only — never a binary path, subprocess
93
+ * stderr, a prompt or a credential value.
94
+ */
95
+ const OWN_CODES = new Set(['agy_tools_unsupported', 'agy_invalid_delta', 'agy_output_limit']);
96
+
58
97
  function safeFailure(error) {
59
- // The transport contract exposes stable codes/status only. Never surface a
60
- // binary path, subprocess stderr, prompts or credential values in messages.
61
98
  const code = typeof error?.code === 'string' && /^[a-z][a-z0-9_]{0,63}$/.test(error.code)
62
99
  ? error.code : 'agy_transport_error';
63
100
  const status = error?.statusCode;
64
- return failure(code, Number.isInteger(status) && status >= 400 && status <= 599 ? status : 502);
101
+ const safe = failure(code, Number.isInteger(status) && status >= 400 && status <= 599 ? status : 502);
102
+ if (OWN_CODES.has(safe.code) && typeof error?.message === 'string' && error.message && error.message !== safe.code) {
103
+ safe.message = error.message;
104
+ }
105
+ return safe;
65
106
  }
66
107
 
67
108
  function finishReason(stopReason) {
@@ -94,6 +135,10 @@ function clientCancellation(req, config) {
94
135
 
95
136
  const MAX_TEXT_BYTES = 1 << 20;
96
137
  const MAX_DELTAS = 8192;
138
+ // The caller is told about at most as many calls as the bridge will park. Using
139
+ // the bridge's own constant is what guarantees that: a parked call the caller is
140
+ // never told about could never be answered, so the turn would hang.
141
+ const MAX_TOOL_CALLS = MAX_CALLS_PER_TURN;
97
142
 
98
143
  export async function chatResponse(transport, prompt, stream, req, config) {
99
144
  const { controller, cleanup } = clientCancellation(req, config);
@@ -102,10 +147,12 @@ export async function chatResponse(transport, prompt, stream, req, config) {
102
147
  let bytes = 0;
103
148
  let deltas = 0;
104
149
  let overflow;
150
+ // Tool calls the agent raised this turn, in arrival order.
151
+ const calls = [];
105
152
  async function run(emit) {
106
153
  try {
107
154
  signal.throwIfAborted();
108
- const result = await transport.run({ ...prompt, signal, onText(text) {
155
+ const turn = { ...prompt, signal, onText(text) {
109
156
  signal.throwIfAborted();
110
157
  if (typeof text !== 'string') throw failure('agy_invalid_delta', 502);
111
158
  if (!text.length) return;
@@ -116,9 +163,26 @@ export async function chatResponse(transport, prompt, stream, req, config) {
116
163
  throw overflow;
117
164
  }
118
165
  emit(text);
119
- } });
166
+ } };
167
+ // Only a tool-bearing request gains the tool-call sink, so a text-only
168
+ // request keeps its exact original transport shape.
169
+ if (prompt.tools?.length || prompt.bridge) {
170
+ turn.onToolCall = call => {
171
+ if (!call || calls.length >= MAX_TOOL_CALLS) return;
172
+ calls.push(call);
173
+ };
174
+ }
175
+ const result = await transport.run(turn);
120
176
  signal.throwIfAborted();
121
- return finishReason(result?.stopReason);
177
+ // The agent parked at least one call: report it instead of a finish
178
+ // reason so the caller does not mistake an unfinished turn for an answer.
179
+ if (result?.parked?.length && calls.length) {
180
+ return { tool_calls: calls.map((call, index) => ({
181
+ index, id: call.id, type: 'function',
182
+ function: { name: call.name, arguments: JSON.stringify(call.arguments ?? {}) },
183
+ })) };
184
+ }
185
+ return { finish_reason: finishReason(result?.stopReason), usage: result.usage };
122
186
  } catch (error) {
123
187
  throw overflow ?? (signal.aborted ? failure('agy_cancelled', 499) : safeFailure(error));
124
188
  } finally {
@@ -127,9 +191,14 @@ export async function chatResponse(transport, prompt, stream, req, config) {
127
191
  }
128
192
  if (!stream) {
129
193
  const parts = [];
130
- const finish_reason = await run(text => parts.push(text));
131
- return Response.json({ ...base, object: 'chat.completion', choices: [{ index: 0,
132
- message: { role: 'assistant', content: parts.join('') }, finish_reason }] });
194
+ const outcome = await run(text => parts.push(text));
195
+ if (outcome.tool_calls) {
196
+ return Response.json({ ...base, object: 'chat.completion', choices: [{ index: 0,
197
+ message: { role: 'assistant', content: parts.join('') || null, tool_calls: outcome.tool_calls },
198
+ finish_reason: 'tool_calls' }] });
199
+ }
200
+ return Response.json({ ...base, object: 'chat.completion', usage: outcome.usage, choices: [{ index: 0,
201
+ message: { role: 'assistant', content: parts.join('') }, finish_reason: outcome.finish_reason }] });
133
202
  }
134
203
 
135
204
  // Wait for text (or a successful empty completion) before publishing headers,
@@ -141,8 +210,13 @@ export async function chatResponse(transport, prompt, stream, req, config) {
141
210
  const body = new ReadableStream({
142
211
  start(output) {
143
212
  function event(data) { output.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`)); }
144
- function chunk(delta, finish_reason = null) {
145
- event({ ...base, object: 'chat.completion.chunk', choices: [{ index: 0, delta, finish_reason }] });
213
+ function chunk(delta, finish_reason = null, usage) {
214
+ event({ ...base, object: 'chat.completion.chunk', usage, choices: [{ index: 0, delta, finish_reason }] });
215
+ }
216
+ function toolChunk(call, index) {
217
+ event({ ...base, object: 'chat.completion.chunk', choices: [{ index: 0, finish_reason: null,
218
+ delta: { tool_calls: [{ index, id: call.id, type: 'function',
219
+ function: { name: call.function.name, arguments: call.function.arguments } }] } }] });
146
220
  }
147
221
  function begin() {
148
222
  if (started) return;
@@ -150,9 +224,14 @@ export async function chatResponse(transport, prompt, stream, req, config) {
150
224
  chunk({ role: 'assistant' });
151
225
  resolveReady();
152
226
  }
153
- run(text => { begin(); chunk({ content: text }); }).then(reason => {
227
+ run(text => { begin(); chunk({ content: text }); }).then(outcome => {
154
228
  begin();
155
- chunk({}, reason);
229
+ if (outcome.tool_calls) {
230
+ outcome.tool_calls.forEach((call, index) => toolChunk(call, index));
231
+ chunk({}, 'tool_calls', outcome.usage);
232
+ } else {
233
+ chunk({}, outcome.finish_reason, outcome.usage);
234
+ }
156
235
  output.enqueue(encoder.encode('data: [DONE]\n\n'));
157
236
  output.close();
158
237
  }).catch(error => {
@@ -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
+ }