@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.
@@ -3,15 +3,30 @@ import { readFileSync } from 'node:fs';
3
3
  import { mkdir, mkdtemp, rm } from 'node:fs/promises';
4
4
  import { tmpdir } from 'node:os';
5
5
  import { isAbsolute, join } from 'node:path';
6
- import { configureSession } from './acp-config.mjs';
6
+ import { setTimeout as delay } from 'node:timers/promises';
7
+ import { configureSession, modelOptions, modelSelector } from './acp-config.mjs';
7
8
  import { AcpError } from './acp-errors.mjs';
8
9
  import { AcpStdio } from './acp-stdio.mjs';
10
+ import { accountEmailShapeOk, extractAccountEmail } from './account.mjs';
11
+ import { promptUsage } from './acp-usage.mjs';
9
12
 
10
13
  const AUTH_METHOD = 'gemini-api-key';
14
+ const OAUTH_METHOD = 'oauth-personal';
15
+ const AUTH_METHODS = new Set([AUTH_METHOD, OAUTH_METHOD]);
11
16
  const MAX_PROMPT_BYTES = 1024 * 1024;
12
17
  const IDLE_MS = 30_000;
13
18
  const MAX_SESSIONS = 64;
19
+ const PROBE_MS = 5000;
20
+ const MODEL_SYNC_MS = 5000;
21
+ const OAUTH_VERIFY_MS = 10_000;
22
+ const MAX_STDERR_TAIL_BYTES = 64 * 1024;
14
23
  const STOP_REASONS = new Set(['end_turn', 'max_tokens', 'max_turn_requests', 'refusal', 'cancelled']);
24
+ // Startup auth race: right after spawn the CLI can reject authenticate or
25
+ // session/new with a transient "not logged in" style error while its login
26
+ // state is still loading (observed on the plugin-MCP path). Real credential
27
+ // failures and rate/quota errors are never retried.
28
+ const AUTH_RACE_MESSAGE = /authentication required|auth_required|not logged in|not signed in/i;
29
+ const AUTH_NO_RETRY_MESSAGE = /invalid_grant|api.?key|429|resource_exhausted|quota/i;
15
30
 
16
31
  function clientVersion() {
17
32
  try {
@@ -23,15 +38,100 @@ function clientVersion() {
23
38
  }
24
39
  const clientInfo = { name: 'ccr-gemini-agy-acp', version: clientVersion() };
25
40
 
26
- function supportedVersion(output) {
41
+ /**
42
+ * Scoped permission answer for agy's session/request_permission. Only a call
43
+ * that names our own caller-tool bridge server is approved — the caller
44
+ * declared those tools and executes them itself. Anything else (native agent
45
+ * tools) stays cancelled, so the agent can never run host commands through
46
+ * an approved permission.
47
+ */
48
+ export function bridgePermissionOutcome(params) {
49
+ let text;
50
+ try { text = JSON.stringify(params ?? {}); } catch { return { outcome: 'cancelled' }; }
51
+ if (!text.includes('ccr-caller-tools')) return { outcome: 'cancelled' };
52
+ const options = Array.isArray(params?.options) ? params.options : [];
53
+ const allow = options.find(option => option?.kind === 'allow_once') ??
54
+ options.find(option => typeof option?.kind === 'string' && option.kind.startsWith('allow'));
55
+ return allow && allow.optionId != null ? { outcome: 'selected', optionId: allow.optionId } : { outcome: 'cancelled' };
56
+ }
57
+
58
+ function cliVersion(output) {
27
59
  const versions = [...output.matchAll(/(?:^|[\s:(])v?(\d+\.\d+\.\d+(?:-[\w.-]+)?(?:\+[\w.-]+)?)(?=$|[\s,)])/gi)];
28
- if (versions.length !== 1) return false;
29
- const [release, prerelease] = versions[0][1].split('+')[0].split('-');
60
+ return versions.length === 1 ? versions[0][1] : null;
61
+ }
62
+
63
+ function supportedVersion(version) {
64
+ if (!version) return false;
65
+ const [release, prerelease] = version.split('+')[0].split('-');
30
66
  const [major, minor, patch] = release.split('.').map(Number);
31
67
  return major > 1 || (major === 1 && (minor > 5 || (minor === 5 && (patch > 1 || (patch === 1 && !prerelease)))));
32
68
  }
33
69
 
34
- async function isolatedEnvironment(root) {
70
+ // The CLI honors the standard proxy variables for its own upstream calls;
71
+ // forward whichever are set in the CCR process (isolated otherwise).
72
+ const PROXY_ENV_VARS = ['HTTPS_PROXY', 'https_proxy', 'HTTP_PROXY', 'http_proxy', 'ALL_PROXY', 'all_proxy', 'NO_PROXY', 'no_proxy'];
73
+
74
+ // An isolated runtime is NOT guaranteed to share the CLI's Google login, so
75
+ // oauth-personal workers run in the real user context with a whitelist of
76
+ // only what the child needs to run, reach its network endpoints and use the
77
+ // OS keyring/browser login: runtime paths, real HOME, temp dirs, platform
78
+ // config locations, GUI/DBus sessions and the standard proxy variables.
79
+ // Never a blanket process.env copy — credential variables such as
80
+ // GEMINI_API_KEY and GOOGLE_APPLICATION_CREDENTIALS are absent by design.
81
+ const OAUTH_ENV_VARS = ['PATH', 'HOME', 'USERPROFILE', 'LANG', 'TMPDIR', 'TEMP', 'TMP',
82
+ 'APPDATA', 'LOCALAPPDATA', 'XDG_CONFIG_HOME', 'SystemRoot', 'COMSPEC', 'PATHEXT',
83
+ 'DBUS_SESSION_BUS_ADDRESS', 'DISPLAY', 'WAYLAND_DISPLAY', 'XAUTHORITY', ...PROXY_ENV_VARS];
84
+
85
+ // Mirror the core proxy policy for the agy CLI's own upstream calls. The
86
+ // process environment always wins (it is what an operator set explicitly);
87
+ // otherwise the gateway's configured proxy — applied when the global proxy
88
+ // is enabled (the core default) or the managed provider opts in — fills the
89
+ // standard variables the CLI honors. A desktop-managed gateway typically
90
+ // inherits no proxy variables at all, which left the CLI dialing Google
91
+ // directly and every turn timing out behind a regional network.
92
+ export function proxyEnvOverlay(env, proxyUrl) {
93
+ if (!proxyUrl) return undefined;
94
+ // An explicit ALL_PROXY is the operator's chosen route for every protocol;
95
+ // injecting protocol-specific variables would shadow it.
96
+ if (env.ALL_PROXY || env.all_proxy) return undefined;
97
+ const overlay = {};
98
+ // Case variants are one setting: an explicit value in either case wins
99
+ // for the whole pair, so the fallback never mixes two proxies.
100
+ for (const [upper, lower] of [['HTTPS_PROXY', 'https_proxy'], ['HTTP_PROXY', 'http_proxy']]) {
101
+ if (!env[upper] && !env[lower]) {
102
+ overlay[upper] = proxyUrl;
103
+ overlay[lower] = proxyUrl;
104
+ }
105
+ }
106
+ if (Object.keys(overlay).length) {
107
+ // The caller-tool MCP bridge is plain HTTP on loopback; without a
108
+ // NO_PROXY exclusion the injected http_proxy could route the agent's
109
+ // local tools/list and tools/call through the upstream proxy.
110
+ const loopback = ['127.0.0.1', 'localhost', '::1'];
111
+ const entries = (env.NO_PROXY || env.no_proxy || '').split(',').map(item => item.trim()).filter(Boolean);
112
+ const missing = loopback.filter(host => !entries.includes(host));
113
+ // Mirror both case variants so a lowercase-only client also exempts loopback.
114
+ const merged = [...entries, ...missing].join(',');
115
+ overlay.NO_PROXY = merged;
116
+ overlay.no_proxy = merged;
117
+ }
118
+ return Object.keys(overlay).length ? overlay : undefined;
119
+ }
120
+
121
+ function withConfiguredProxy(env, proxyUrl) {
122
+ return Object.assign(env, proxyEnvOverlay(env, proxyUrl) ?? {});
123
+ }
124
+
125
+ export function oauthEnvironment(proxyUrl) {
126
+ const env = {};
127
+ for (const name of OAUTH_ENV_VARS) {
128
+ const value = process.env[name];
129
+ if (value !== undefined) env[name] = value;
130
+ }
131
+ return withConfiguredProxy(env, proxyUrl);
132
+ }
133
+
134
+ export async function isolatedEnvironment(root, proxyUrl) {
35
135
  const dirs = Object.fromEntries(['home', 'config', 'data', 'cache', 'state', 'tmp', 'runtime', 'work']
36
136
  .map(name => [name, join(root, name)]));
37
137
  await Promise.all(Object.values(dirs).map(path => mkdir(path, { mode: 0o700 })));
@@ -41,29 +141,45 @@ async function isolatedEnvironment(root) {
41
141
  APPDATA: dirs.config, LOCALAPPDATA: dirs.data, TMPDIR: dirs.tmp, TEMP: dirs.tmp, TMP: dirs.tmp,
42
142
  PATH: '/usr/bin:/bin', LANG: 'C',
43
143
  };
144
+ for (const name of PROXY_ENV_VARS) {
145
+ const value = process.env[name];
146
+ if (value) env[name] = value;
147
+ }
44
148
  if (process.platform === 'win32') {
45
149
  env.SystemRoot = process.env.SystemRoot;
46
150
  env.PATH = join(env.SystemRoot, 'System32');
47
151
  }
48
- return { env, cwd: dirs.work };
152
+ return { env: withConfiguredProxy(env, proxyUrl), cwd: dirs.work };
49
153
  }
50
154
 
51
155
  class Worker {
52
- constructor(binary, onRetired) {
156
+ constructor(binary, authMethod, onRetired, log, { captureStderr = false, proxyUrl } = {}) {
53
157
  this.binary = binary;
158
+ this.proxyUrl = proxyUrl;
159
+ this.authMethod = authMethod;
54
160
  this.onRetired = onRetired;
161
+ this.log = log;
162
+ this.captureStderr = captureStderr;
163
+ this.stderrChunks = [];
164
+ this.stderrBytes = 0;
55
165
  this.sessions = new Set();
166
+ // The warm ACP session kept alive while the caller executes a parked tool
167
+ // call, so a follow-up request can resume the same turn.
168
+ this.binding = null;
56
169
  }
57
170
 
58
171
  check() {
59
172
  if (this.failure) throw this.failure;
60
173
  }
61
174
 
62
- spawnChild(args, env) {
175
+ spawnChild(args, env, captureStderr = false) {
63
176
  this.check();
64
177
  const child = spawn(this.binary, args, {
65
178
  cwd: this.cwd, env, shell: false, windowsHide: true, detached: process.platform !== 'win32',
66
- stdio: ['pipe', 'pipe', 'ignore'], // subprocess diagnostics may contain credentials or prompts
179
+ // Subprocess diagnostics may contain credentials or prompts; they are
180
+ // captured only for the bounded oauth login verification below and are
181
+ // never logged or returned raw.
182
+ stdio: ['pipe', 'pipe', captureStderr ? 'pipe' : 'ignore'],
67
183
  });
68
184
  this.child = child;
69
185
  this.childClosed = new Promise(resolve => child.once('close', resolve));
@@ -71,14 +187,46 @@ class Worker {
71
187
  child.on('error', fail);
72
188
  child.stdin.on('error', fail);
73
189
  child.stdout.on('error', fail);
190
+ child.stderr?.on('error', fail);
191
+ if (captureStderr) {
192
+ // Bounded rolling tail (last 64 KiB) of THIS child's diagnostics.
193
+ child.stderr.on('data', chunk => {
194
+ this.stderrChunks.push(chunk);
195
+ this.stderrBytes += chunk.length;
196
+ while (this.stderrBytes > MAX_STDERR_TAIL_BYTES && this.stderrChunks.length) {
197
+ const drop = Math.min(this.stderrBytes - MAX_STDERR_TAIL_BYTES, this.stderrChunks[0].length);
198
+ this.stderrChunks[0] = this.stderrChunks[0].subarray(drop);
199
+ if (this.stderrChunks[0].length === 0) this.stderrChunks.shift();
200
+ this.stderrBytes -= drop;
201
+ }
202
+ });
203
+ }
74
204
  return child;
75
205
  }
76
206
 
77
- async start(apiKey) {
78
- this.root = await mkdtemp(join(tmpdir(), 'ccr-agy-acp-'));
79
- const isolation = await isolatedEnvironment(this.root);
80
- this.cwd = isolation.cwd;
81
- const probe = this.spawnChild(['--version'], isolation.env);
207
+ /** The captured diagnostics tail, scanned only for the account email. */
208
+ stderrText() {
209
+ return Buffer.concat(this.stderrChunks, this.stderrBytes).toString('utf8');
210
+ }
211
+
212
+ /** The bounded `--version` probe. Returns the advertised CLI version and
213
+ * leaves the workspace in place for the ACP child that follows. OAuth
214
+ * workers use a private temporary cwd and the whitelisted real environment
215
+ * so the CLI can use its native login. */
216
+ async probe() {
217
+ this.rootReady = (async () => {
218
+ this.root = await mkdtemp(join(tmpdir(), 'ccr-agy-acp-'));
219
+ if (this.authMethod === OAUTH_METHOD) {
220
+ this.cwd = this.root;
221
+ this.spawnEnv = oauthEnvironment(this.proxyUrl);
222
+ } else {
223
+ const isolation = await isolatedEnvironment(this.root, this.proxyUrl);
224
+ this.cwd = isolation.cwd;
225
+ this.spawnEnv = isolation.env;
226
+ }
227
+ })();
228
+ await this.rootReady;
229
+ const probe = this.spawnChild(['--version'], this.spawnEnv);
82
230
  let output = '';
83
231
  let bytes = 0;
84
232
  probe.stdout.on('data', chunk => {
@@ -87,48 +235,211 @@ class Worker {
87
235
  else output += chunk.toString('ascii');
88
236
  });
89
237
  probe.stdin.end();
90
- const probeTimeout = setTimeout(() => this.retire(new AcpError('timeout')), 5000);
238
+ const probeTimeout = setTimeout(() => this.retire(new AcpError('timeout')), PROBE_MS);
91
239
  let exitCode;
92
240
  try { exitCode = await this.childClosed; } finally { clearTimeout(probeTimeout); }
93
241
  this.child = null;
94
242
  this.check();
95
- if (exitCode !== 0 || !supportedVersion(output)) throw new AcpError('unsupported_version');
243
+ const version = cliVersion(output);
244
+ if (exitCode !== 0 || !supportedVersion(version)) throw new AcpError('unsupported_version');
245
+ this.version = version;
246
+ return version;
247
+ }
248
+
249
+ async start(apiKey) {
250
+ await this.probe();
251
+ this.check();
96
252
 
97
- const child = this.spawnChild(['acp', '--sandbox'], { ...isolation.env, GEMINI_API_KEY: apiKey });
253
+ // --process-per-session is required for client HTTP MCP; --sandbox
254
+ // restricts the agent toolset and excludes session MCP tools entirely.
255
+ const child = this.spawnChild(['acp', '--process-per-session'],
256
+ this.authMethod === OAUTH_METHOD ? this.spawnEnv : { ...this.spawnEnv, GEMINI_API_KEY: apiKey },
257
+ this.captureStderr);
98
258
  child.once('exit', () => this.retire(new AcpError('worker_failed')));
99
259
  child.stdout.once('end', () => this.retire(new AcpError('worker_failed')));
100
260
  this.rpc = new AcpStdio(child, error => this.retire(error));
261
+ // agy may ask permission before an MCP tool call. The caller already
262
+ // sanctioned its own bridged tools by declaring them, and the caller —
263
+ // never the agent — executes them, so approve only those; every native
264
+ // agent tool stays denied.
265
+ this.rpc.onPermission = bridgePermissionOutcome;
101
266
  const init = await this.rpc.request('initialize', { protocolVersion: 1, clientInfo, clientCapabilities: {} });
102
267
  if (init.protocolVersion !== 1) throw new AcpError('protocol_error');
103
- if (!Array.isArray(init.authMethods) || !init.authMethods.some(method => method?.id === AUTH_METHOD &&
268
+ if (!Array.isArray(init.authMethods) || !init.authMethods.some(method => method?.id === this.authMethod &&
104
269
  (method.type == null || method.type === 'agent'))) throw new AcpError('auth_required');
105
- await this.rpc.request('authenticate', { methodId: AUTH_METHOD }, 'auth_required');
270
+ // The official `_meta.antigravity` session extensions are only valid when
271
+ // the agent advertises the capability object at initialize; gate on it.
272
+ const antigravity = init.agentCapabilities?._meta?.antigravity;
273
+ this.antigravityMeta = antigravity && typeof antigravity === 'object' && !Array.isArray(antigravity) ? antigravity : null;
274
+ await this.retryStartupAuthRace(() => this.rpc.request('authenticate', { methodId: this.authMethod }, 'auth_required'));
275
+ // Explicit ACP account metadata of THIS handshake, when the CLI reports
276
+ // it; verified against the bounded email shape before it is kept.
277
+ this.initAccountEmail = accountEmailShapeOk(init.accountInfo?.email) ? init.accountInfo.email : null;
278
+ // One bounded spawn log per worker start: binary path and CLI version only,
279
+ // never key material or prompt content.
280
+ this.log?.info?.(`gemini-agy-acp worker started (agy ${this.version}, binary: ${this.binary})`);
106
281
  }
107
282
 
108
- async turn({ model, thinking, prompt, onText }, apiKey) {
283
+ /**
284
+ * One bounded retry for the startup auth race only: a transient "not logged
285
+ * in" style rejection inside the first 2s of the attempt is retried once
286
+ * after 250ms. Credential failures (invalid_grant, api key) and rate/quota
287
+ * errors (429, RESOURCE_EXHAUSTED) are rethrown immediately, and a retired
288
+ * worker never retries.
289
+ */
290
+ async retryStartupAuthRace(call) {
291
+ // Monotonic clock: a wall-clock NTP step or suspend/resume must not widen the retry window.
292
+ const started = performance.now();
293
+ try {
294
+ return await call();
295
+ } catch (error) {
296
+ const text = typeof error.agentMessage === 'string' ? error.agentMessage : error.message;
297
+ if (this.failure || performance.now() - started >= 2000 ||
298
+ !AUTH_RACE_MESSAGE.test(text) || AUTH_NO_RETRY_MESSAGE.test(text)) throw error;
299
+ await delay(250, undefined, { ref: false });
300
+ if (this.failure) throw error;
301
+ return call();
302
+ }
303
+ }
304
+
305
+ /**
306
+ * The live tool bridge of the warm binding, if a call is still parked. A
307
+ * resume turn reuses it so the agent keeps seeing the same tools and the
308
+ * parked call resolves inside its original MCP request.
309
+ */
310
+ toolBridge() {
311
+ return this.binding?.bridge;
312
+ }
313
+
314
+ /**
315
+ * One ACP turn.
316
+ *
317
+ * When the caller declared tools, `bridge` is the live MCP bridge the plugin
318
+ * already started; its stdio descriptor goes into `session/new` so the agent
319
+ * spawns the forwarder and discovers the tools through it (the agent's HTTP
320
+ * MCP path does not surface bridged tools to the model), and the session
321
+ * stays warm in `this.binding` while a call is parked, so a follow-up
322
+ * request can resume the same ACP turn.
323
+ */
324
+ async turn({ model, thinking, prompt, onText, onToolCall, bridge, resume }, apiKey) {
109
325
  if (!this.rpc) await this.start(apiKey);
110
326
  this.check();
111
- const cwd = await mkdtemp(join(this.root, 'session-'));
327
+ const cwd = await mkdtemp(join(this.authMethod === OAUTH_METHOD ? tmpdir() : this.root, 'session-'));
328
+ const hasTools = !!bridge && !bridge.empty;
329
+ const descriptor = hasTools ? bridge.stdioDescriptor() : undefined;
330
+ const mcpServers = descriptor ? [descriptor] : [];
331
+ let sessionId;
112
332
  try {
113
- const session = await this.rpc.request('session/new', { cwd, mcpServers: [] });
114
- const { sessionId } = session;
115
- if (typeof sessionId !== 'string' || !sessionId || sessionId.length > 4096 || this.sessions.has(sessionId)) {
116
- throw new AcpError('protocol_error');
333
+ if (resume && this.binding?.sessionId && this.binding.bridge === bridge) {
334
+ // The parked turn left its prompt in flight; drop it so this turn can
335
+ // issue a fresh one on the same session.
336
+ sessionId = this.binding.sessionId;
337
+ this.rpc.abandon();
338
+ } else {
339
+ if (this.binding) await this.closeBinding();
340
+ const params = { cwd, mcpServers };
341
+ // Eager connect avoids the preload race where the first prompt runs
342
+ // before the CLI has connected to the session's MCP server. Sent only
343
+ // when initialize advertised the antigravity capability object.
344
+ if (descriptor && this.antigravityMeta) {
345
+ params._meta = { antigravity: { eagerMcpServers: [descriptor.name] } };
346
+ }
347
+ const session = await this.retryStartupAuthRace(() => this.rpc.request('session/new', params));
348
+ sessionId = session.sessionId;
349
+ if (typeof sessionId !== 'string' || !sessionId || sessionId.length > 4096 || this.sessions.has(sessionId)) {
350
+ throw new AcpError('protocol_error');
351
+ }
352
+ this.sessions.add(sessionId);
353
+ await configureSession(this.rpc, session, model, thinking);
354
+ this.binding = { sessionId, bridge };
117
355
  }
118
- this.sessions.add(sessionId);
119
- await configureSession(this.rpc, session, model, thinking);
120
356
  this.rpc.sessionId = sessionId;
121
357
  this.rpc.onText = onText;
122
- const { stopReason } = await this.rpc.request('session/prompt', { sessionId, prompt: [{ type: 'text', text: prompt }] });
358
+ // A raised tool call parks the turn: the agent is blocked inside its own
359
+ // MCP request and will not answer the prompt until the caller does. Stop
360
+ // waiting on the prompt and report the parked call instead. A resume turn
361
+ // has already been answered, so the agent will finish on its own and no
362
+ // parking race is needed.
363
+ let parkedNow;
364
+ const parked = new Promise(resolve => { parkedNow = resolve; });
365
+ this.rpc.parked = resume ? null : parkedNow;
366
+ // The bridge mints the caller-visible call when the agent starts it, so
367
+ // that is the authoritative id; the agent's own ACP notification id is
368
+ // ignored. A text-only turn has no bridge and keeps its exact shape.
369
+ //
370
+ // Parked ids are captured the moment each call is raised: reading the
371
+ // bridge's map later is wrong, because the agent may finish a call
372
+ // immediately and the entry is gone by then.
373
+ const raised = [];
374
+ // A turn that parks must still unwind if the worker is retired underneath
375
+ // it (caller abort, idle reaping, pool close), or its `finally` — which
376
+ // closes the bridge and drops the warm binding — would never run and the
377
+ // listening socket would leak.
378
+ let parkFailed;
379
+ const parkDead = new Promise((_, reject) => { parkFailed = reject; });
380
+ const unwind = () => parkFailed?.(this.failure ?? new AcpError('worker_failed'));
381
+ this.unwind = unwind;
382
+ if (bridge) bridge.onParked = invocation => {
383
+ raised.push(invocation.id);
384
+ if (typeof onToolCall === 'function') {
385
+ onToolCall({ id: invocation.id, name: invocation.name, arguments: invocation.arguments });
386
+ }
387
+ // The agent is now blocked inside this MCP request, so the prompt will
388
+ // not be answered until the caller returns a result.
389
+ parkedNow?.();
390
+ };
391
+ const promptDone = this.rpc.request('session/prompt', { sessionId, prompt: [{ type: 'text', text: prompt }] });
392
+ // A parked turn abandons its prompt; the agent answers it later, once the
393
+ // caller's result unblocks its MCP request. Swallow that late answer so
394
+ // it cannot surface as an unhandled rejection on the warm worker.
395
+ promptDone.catch(() => {});
396
+ const outcome = resume
397
+ ? await promptDone
398
+ : await Promise.race([promptDone, parked, parkDead]);
399
+ // A turn that parked a tool call is not finished: keep the session warm
400
+ // and report the parked ids so the caller knows to answer. The parked ids
401
+ // — not the prompt's outcome — are what the caller acts on, so a turn that
402
+ // parked has no stop reason to report.
403
+ if (hasTools && raised.length) {
404
+ return { parked: [...raised] };
405
+ }
406
+ if (outcome === undefined) throw new AcpError('protocol_error');
407
+ const { stopReason } = outcome;
123
408
  if (!STOP_REASONS.has(stopReason)) throw new AcpError('protocol_error');
124
- return { stopReason };
409
+ const usage = promptUsage(outcome);
410
+ return usage ? { stopReason, usage } : { stopReason };
125
411
  } finally {
126
412
  this.rpc.sessionId = null;
127
413
  this.rpc.onText = null;
414
+ this.rpc.onToolCall = null;
415
+ this.rpc.parked = null;
416
+ this.unwind = null;
417
+ if (bridge?.onParked) bridge.onParked = null;
418
+ // A binding stays warm only while a tool call is parked. Every other
419
+ // exit — including a session/new that threw before an id existed — must
420
+ // drop it, or a later turn would reuse a dead session.
421
+ if (this.binding && this.binding.bridge?.pending?.size === 0) await this.closeBinding();
128
422
  await rm(cwd, { recursive: true, force: true });
129
423
  }
130
424
  }
131
425
 
426
+ /**
427
+ * Drop the warm binding. The session id stays in `this.sessions` for the
428
+ * worker's lifetime, so an agent that reuses an id is still rejected as a
429
+ * protocol violation.
430
+ */
431
+ async closeBinding() {
432
+ const binding = this.binding;
433
+ this.binding = null;
434
+ if (!binding) return;
435
+ // The parked turn left its prompt in flight on this worker's rpc. Drop it
436
+ // first, or the next turn's request would collide with it and the whole
437
+ // worker would fail with a protocol error. A retired worker has already
438
+ // settled it, so there is nothing to abandon.
439
+ if (!this.failure) this.rpc?.abandon();
440
+ await binding.bridge?.close().catch(() => {});
441
+ }
442
+
132
443
  async run(request, apiKey, timeoutMs) {
133
444
  clearTimeout(this.idleTimer);
134
445
  this.rpc?.resetBudget();
@@ -147,7 +458,11 @@ class Worker {
147
458
  try {
148
459
  const result = await Promise.race([this.task, interrupted]);
149
460
  this.check();
150
- if (this.sessions.size >= MAX_SESSIONS) this.retire(new AcpError('closed'));
461
+ // Retiring on session-count exhaustion would close the bridge of a call
462
+ // the caller is still waiting to answer, so only reap an idle worker.
463
+ if (!this.binding?.bridge?.pending?.size && this.sessions.size >= MAX_SESSIONS) {
464
+ this.retire(new AcpError('closed'));
465
+ }
151
466
  else this.idleTimer = setTimeout(() => this.retire(new AcpError('closed')), IDLE_MS).unref();
152
467
  return result;
153
468
  } catch (error) {
@@ -168,7 +483,16 @@ class Worker {
168
483
  retire(error) {
169
484
  if (this.cleanup) return this.cleanup;
170
485
  this.failure = error;
486
+ // Unwind a turn that is parked on a tool call, so its `finally` runs and
487
+ // the bridge it holds is closed rather than left listening.
488
+ this.unwind?.();
171
489
  clearTimeout(this.idleTimer);
490
+ // A warm binding's parked calls must never outlive the worker: closing the
491
+ // bridge settles them as errors so a waiting MCP request cannot hang the
492
+ // caller.
493
+ const binding = this.binding;
494
+ this.binding = null;
495
+ binding?.bridge?.close().catch(() => {});
172
496
  this.rpc?.stop(error);
173
497
  const child = this.child;
174
498
  child?.stdin.destroy();
@@ -183,6 +507,7 @@ class Worker {
183
507
  this.cleanup = (async () => {
184
508
  try {
185
509
  await this.task?.catch(() => {});
510
+ await this.rootReady?.catch(() => {});
186
511
  await this.childClosed;
187
512
  if (this.root) await rm(this.root, { recursive: true, force: true, maxRetries: 3 });
188
513
  } catch {
@@ -197,33 +522,99 @@ class Worker {
197
522
  }
198
523
  }
199
524
 
200
- export function createTransport({ binary, authMethod, timeoutMs = 60_000, maxWorkers = 2 } = {}) {
201
- if (typeof binary !== 'string' || !isAbsolute(binary) || binary.includes('\0') || authMethod !== AUTH_METHOD ||
525
+ function validProxyUrl(proxyUrl) {
526
+ if (proxyUrl == null || proxyUrl === '') return undefined;
527
+ if (typeof proxyUrl !== 'string' || !/^https?:\/\//i.test(proxyUrl)) throw new AcpError('invalid_config');
528
+ return proxyUrl;
529
+ }
530
+
531
+ export function createTransport({ binary, authMethod = AUTH_METHOD, timeoutMs = 60_000, maxWorkers = 2, apiKey, log, proxyUrl } = {}) {
532
+ const oauth = authMethod === OAUTH_METHOD;
533
+ proxyUrl = validProxyUrl(proxyUrl);
534
+ if (typeof binary !== 'string' || !isAbsolute(binary) || binary.includes('\0') || !AUTH_METHODS.has(authMethod) ||
202
535
  !Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 300_000 ||
203
- !Number.isInteger(maxWorkers) || maxWorkers < 1 || maxWorkers > 8) throw new AcpError('invalid_config');
204
- // The host reads settings once per activation. Capture credentials at the
205
- // same boundary so every worker in this pool has one billing identity.
206
- const apiKey = process.env.GEMINI_API_KEY;
536
+ !Number.isInteger(maxWorkers) || maxWorkers < 1 || maxWorkers > 8 ||
537
+ (apiKey != null && (oauth || typeof apiKey !== 'string' || !apiKey.trim()))) throw new AcpError('invalid_config');
538
+ // The plugin resolves the sidecar apiKey against the process environment at
539
+ // pool start; a standalone caller may omit it entirely and fall back to the
540
+ // environment here. One capture boundary gives every worker in this pool a
541
+ // single billing identity, immune to later environment edits. oauth-personal
542
+ // pools carry no credential at all: the CLI uses its own OS-keyring login.
543
+ const credential = oauth ? undefined
544
+ : typeof apiKey === 'string' && apiKey.trim() ? apiKey : process.env.GEMINI_API_KEY;
207
545
  const workers = new Set();
208
546
  let closed = false;
209
547
  return {
548
+ /**
549
+ * The tool bridge whose parked calls are exactly the ones this caller is
550
+ * answering. Matching on the ids keeps two interleaved conversations from
551
+ * stealing each other's bridge — and therefore each other's ACP session.
552
+ */
553
+ toolBridge(ids) {
554
+ const wanted = ids instanceof Set ? ids : new Set(ids ?? []);
555
+ for (const worker of workers) {
556
+ const bridge = worker.toolBridge?.();
557
+ if (!bridge) continue;
558
+ const parked = [...bridge.pending.keys()];
559
+ // A strict bijection, not a subset: a caller that quotes more ids than
560
+ // are parked — including ids borrowed from another conversation — must
561
+ // not be able to resume a bridge it does not own.
562
+ if (parked.length && parked.length === wanted.size && parked.every(id => wanted.has(id))) {
563
+ return bridge;
564
+ }
565
+ }
566
+ return undefined;
567
+ },
210
568
  async run(request) {
211
569
  if (closed) throw new AcpError('closed');
212
- const { model, thinking, prompt, signal, onText } = request ?? {};
570
+ const { model, thinking, prompt, signal, onText, onToolCall, bridge, resume } = request ?? {};
213
571
  if (signal != null && !(signal instanceof AbortSignal)) throw new AcpError('invalid_request');
214
572
  if (signal?.aborted) throw new AcpError('cancelled');
215
573
  if (typeof prompt !== 'string' || typeof model !== 'string' || !model || model.length > 1024 ||
216
574
  (thinking != null && (typeof thinking !== 'string' || !thinking || thinking.length > 128)) ||
217
575
  typeof onText !== 'function') throw new AcpError('invalid_request');
576
+ // A bridge is the plugin's own object; only shape is checked here. Both
577
+ // descriptors are required: stdio for session/new, HTTP for internal use.
578
+ if (bridge != null && (typeof bridge.descriptor !== 'function' || typeof bridge.stdioDescriptor !== 'function' ||
579
+ !(bridge.pending instanceof Map))) {
580
+ throw new AcpError('invalid_request');
581
+ }
218
582
  if (Buffer.byteLength(prompt) > MAX_PROMPT_BYTES) throw new AcpError('input_limit');
219
- if (!apiKey?.trim()) throw new AcpError('auth_required');
220
- let worker = [...workers].find(candidate => !candidate.task && !candidate.failure);
583
+ if (!oauth && !credential?.trim()) throw new AcpError('auth_required');
584
+ // A resume turn must land on the worker that holds its bridge: that is
585
+ // where the parked call and the warm ACP session live.
586
+ let worker = resume
587
+ ? [...workers].find(candidate => candidate.binding?.bridge === bridge && !candidate.task && !candidate.failure)
588
+ // Any other turn must avoid a worker holding a live parked call, which is
589
+ // reserved for the resume that will answer it — taking it over would tear
590
+ // that call down. A binding with nothing parked is not reserved.
591
+ : [...workers].find(candidate => !candidate.task && !candidate.failure &&
592
+ !(candidate.binding?.bridge?.pending?.size > 0));
221
593
  if (!worker) {
222
594
  if (workers.size >= maxWorkers) throw new AcpError('busy');
223
- worker = new Worker(binary, retired => workers.delete(retired));
595
+ worker = new Worker(binary, authMethod, retired => workers.delete(retired), log, { proxyUrl });
224
596
  workers.add(worker);
225
597
  }
226
- return worker.run({ model, thinking, prompt, signal, onText }, apiKey, timeoutMs);
598
+ return worker.run({ model, thinking, prompt, signal, onText, onToolCall, bridge, resume }, credential, timeoutMs);
599
+ },
600
+ /** Pool reset without closing: every live or idle worker is retired so the
601
+ * next run() respawns with fresh settings. Connect and disconnect use this
602
+ * to drop stale billing identities immediately. */
603
+ async retireExisting() {
604
+ await Promise.all([...workers].map(worker => worker.retire(new AcpError('closed'))));
605
+ },
606
+ /** Drain only idle workers: busy turns keep their spawn environment and
607
+ * finish on this pool, then idle-retire naturally. Used for proxy-only
608
+ * pool swaps so a config edit never SIGKILLs an in-flight turn. */
609
+ async retireIdle() {
610
+ // A parked tool turn has no active task but reserves its worker and
611
+ // bridge for the caller's resume; draining it would SIGKILL the turn.
612
+ await Promise.all([...workers].filter(worker => !worker.task && !worker.failure &&
613
+ !(worker.binding?.bridge?.pending?.size > 0)).map(worker => worker.retire(new AcpError('closed'))));
614
+ },
615
+ /** True while any worker holds a parked caller tool call. */
616
+ hasParked() {
617
+ return [...workers].some(worker => worker.binding?.bridge?.pending?.size > 0);
227
618
  },
228
619
  async close() {
229
620
  closed = true;
@@ -231,3 +622,84 @@ export function createTransport({ binary, authMethod, timeoutMs = 60_000, maxWor
231
622
  },
232
623
  };
233
624
  }
625
+
626
+ /** Validate one binary in isolation: a bounded `--version` probe with the
627
+ * supported-version gate. Returns the advertised CLI version string. This is
628
+ * the connect route's only look at the binary — no ACP child is spawned. The
629
+ * probe runs in the same auth mode as the pool that follows (oauth probes
630
+ * use the whitelisted real environment; gemini probes the isolated one). */
631
+ export async function probeVersion(binary, authMethod = AUTH_METHOD, proxyUrl) {
632
+ if (typeof binary !== 'string' || !isAbsolute(binary) || binary.includes('\0') || !AUTH_METHODS.has(authMethod)) {
633
+ throw new AcpError('invalid_config');
634
+ }
635
+ const worker = new Worker(binary, authMethod, () => {}, undefined, { proxyUrl });
636
+ const deadline = setTimeout(() => worker.retire(new AcpError('timeout')), PROBE_MS);
637
+ try {
638
+ return await worker.probe();
639
+ } finally {
640
+ clearTimeout(deadline);
641
+ await worker.retire(worker.failure ?? new AcpError('closed')).catch(() => {});
642
+ }
643
+ }
644
+
645
+ /** One bounded temporary oauth-personal worker that proves the selected
646
+ * binary's real login: version probe, ACP handshake authenticating the CLI's
647
+ * own OS-keyring Google account, then one session/new. A `--version` probe
648
+ * cannot prove the keyring login works. Returns { version, accountEmail }
649
+ * where the email — when the CLI provides one at all — comes exclusively from
650
+ * THIS handshake's explicit ACP account metadata or this child's own bounded
651
+ * diagnostics tail; never from stale logs, other processes or token stores,
652
+ * and only the validated email ever leaves this function. */
653
+ export async function verifyOauthHandshake({ binary, log, proxyUrl } = {}) {
654
+ if (typeof binary !== 'string' || !isAbsolute(binary) || binary.includes('\0')) throw new AcpError('invalid_config');
655
+ const worker = new Worker(binary, OAUTH_METHOD, () => {}, log, { captureStderr: true, proxyUrl });
656
+ const deadline = setTimeout(() => worker.retire(new AcpError('timeout')), OAUTH_VERIFY_MS);
657
+ try {
658
+ await worker.start();
659
+ worker.check();
660
+ const cwd = await mkdtemp(join(tmpdir(), 'session-'));
661
+ try {
662
+ const session = await worker.rpc.request('session/new', { cwd, mcpServers: [] });
663
+ if (typeof session?.sessionId !== 'string' || !session.sessionId || session.sessionId.length > 4096) {
664
+ throw new AcpError('protocol_error');
665
+ }
666
+ return {
667
+ version: worker.version ?? null,
668
+ // Explicit ACP metadata wins over the child's own login diagnostics.
669
+ accountEmail: worker.initAccountEmail ?? extractAccountEmail(worker.stderrText()),
670
+ };
671
+ } finally {
672
+ await rm(cwd, { recursive: true, force: true });
673
+ }
674
+ } finally {
675
+ clearTimeout(deadline);
676
+ await worker.retire(worker.failure ?? new AcpError('closed')).catch(() => {});
677
+ }
678
+ }
679
+
680
+ /** One bounded temporary worker for catalog discovery: version probe, ACP
681
+ * handshake with the resolved key, session/new, then the advertised model
682
+ * selector options from the session config. Never touches the request pool.
683
+ * oauth-personal syncs authenticate the CLI's own login without any key. */
684
+ export async function syncModelOptions({ binary, authMethod = AUTH_METHOD, apiKey, log, proxyUrl } = {}) {
685
+ const oauth = authMethod === OAUTH_METHOD;
686
+ if (typeof binary !== 'string' || !isAbsolute(binary) || binary.includes('\0') || !AUTH_METHODS.has(authMethod) ||
687
+ (oauth ? apiKey != null : typeof apiKey !== 'string' || !apiKey.trim())) throw new AcpError('invalid_config');
688
+ const worker = new Worker(binary, authMethod, () => {}, log, { proxyUrl });
689
+ const deadline = setTimeout(() => worker.retire(new AcpError('timeout')), MODEL_SYNC_MS);
690
+ try {
691
+ await worker.start(oauth ? undefined : apiKey);
692
+ worker.check();
693
+ const cwd = await mkdtemp(join(oauth ? tmpdir() : worker.root, 'session-'));
694
+ try {
695
+ const session = await worker.rpc.request('session/new', { cwd, mcpServers: [] });
696
+ const models = modelOptions(modelSelector(session.configOptions));
697
+ return { models, version: worker.version ?? null };
698
+ } finally {
699
+ await rm(cwd, { recursive: true, force: true });
700
+ }
701
+ } finally {
702
+ clearTimeout(deadline);
703
+ await worker.retire(worker.failure ?? new AcpError('closed')).catch(() => {});
704
+ }
705
+ }