@timmyjl12/pi-agy-bridge 0.1.4 → 0.2.0

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.
@@ -13,7 +13,8 @@ export const PROVIDER_ID = "agy";
13
13
  export const API_ID = "agy-acp";
14
14
  export const BASE_URL = "process://agy-acp";
15
15
 
16
- export type AgyModel = Model<typeof API_ID>;
16
+ /** API ids are per account (`agy-acp`, `agy-acp-<name>`), so the model type is open over the api string. */
17
+ export type AgyModel = Model<string>;
17
18
 
18
19
  export interface AgyModelDescriptor {
19
20
  /** Value of the ACP `model` config option; also the pi model id. */
@@ -122,14 +123,25 @@ function levelMap(descriptor: AgyModelDescriptor): LevelMap {
122
123
  return map as LevelMap;
123
124
  }
124
125
 
125
- export function toPiModel(descriptor: AgyModelDescriptor, observedWindow?: number): AgyModel {
126
+ /** Which pi provider/api a model belongs to: `agy`/`agy-acp` for the default account, `agy-<name>`/`agy-acp-<name>`
127
+ * for an extra account. */
128
+ export interface ProviderIds {
129
+ provider: string;
130
+ api: string;
131
+ /** Appended to model display names of an extra account, e.g. " · work". */
132
+ nameSuffix?: string;
133
+ }
134
+
135
+ export const DEFAULT_IDS: Readonly<ProviderIds> = Object.freeze({ provider: PROVIDER_ID, api: API_ID });
136
+
137
+ export function toPiModel(descriptor: AgyModelDescriptor, observedWindow?: number, ids: ProviderIds = DEFAULT_IDS): AgyModel {
126
138
  const reasoning = descriptor.levels.length > 0 || descriptor.fixedLevel !== undefined;
127
139
  const limits = limitsFor(descriptor.id, observedWindow);
128
140
  return {
129
141
  id: descriptor.id,
130
- name: descriptor.name,
131
- api: API_ID,
132
- provider: PROVIDER_ID,
142
+ name: `${descriptor.name}${ids.nameSuffix ?? ""}`,
143
+ api: ids.api,
144
+ provider: ids.provider,
133
145
  baseUrl: BASE_URL,
134
146
  reasoning,
135
147
  ...(reasoning ? { thinkingLevelMap: levelMap(descriptor) } : {}),
@@ -144,8 +156,9 @@ export function toPiModel(descriptor: AgyModelDescriptor, observedWindow?: numbe
144
156
  export function toPiModels(
145
157
  descriptors: readonly AgyModelDescriptor[],
146
158
  observedWindows: ReadonlyMap<string, number> = new Map(),
159
+ ids: ProviderIds = DEFAULT_IDS,
147
160
  ): AgyModel[] {
148
- return descriptors.map((descriptor) => toPiModel(descriptor, observedWindows.get(descriptor.id)));
161
+ return descriptors.map((descriptor) => toPiModel(descriptor, observedWindows.get(descriptor.id), ids));
149
162
  }
150
163
 
151
164
  export const STATIC_MODELS: AgyModel[] = toPiModels(FALLBACK_DESCRIPTORS);
package/src/provider.ts CHANGED
@@ -3,7 +3,17 @@
3
3
 
4
4
  import { createProvider, type AuthContext, type ProviderEnv } from "@earendil-works/pi-ai";
5
5
  import { CONFIG_ENV_NAMES } from "./config.ts";
6
- import { describeModels, FALLBACK_DESCRIPTORS, PROVIDER_ID, STATIC_MODELS, toPiModels, API_ID } from "./model-catalog.ts";
6
+ import { apiIdFor, labelFor, maskEmail, providerIdFor } from "./accounts.ts";
7
+ import {
8
+ describeModels,
9
+ DEFAULT_IDS,
10
+ FALLBACK_DESCRIPTORS,
11
+ PROVIDER_ID,
12
+ STATIC_MODELS,
13
+ toPiModels,
14
+ API_ID,
15
+ type ProviderIds,
16
+ } from "./model-catalog.ts";
7
17
  import type { AgyRuntime } from "./runtime.ts";
8
18
  import { makeStreamAgy } from "./stream.ts";
9
19
 
@@ -21,7 +31,15 @@ async function providerEnvironment(ctx: AuthContext): Promise<ProviderEnv | unde
21
31
  }
22
32
 
23
33
  export function createAgyProvider(runtime: AgyRuntime) {
24
- let discoveredIds: Set<string> | undefined;
34
+ const account = runtime.account;
35
+ const ids: ProviderIds = account
36
+ ? { provider: providerIdFor(account), api: apiIdFor(account), nameSuffix: ` · ${labelFor(account)}` }
37
+ : DEFAULT_IDS;
38
+ const accountName = account ? `Antigravity · ${labelFor(account)}${account.email ? ` (${maskEmail(account.email)})` : ""}` : undefined;
39
+ // A provider registered again (alias rename, account edit) starts from what this account's process already reported,
40
+ // not from the static list: an account on a smaller plan must keep showing only its own models.
41
+ const known = account && runtime.pool.cachedDiscovery ? describeModels(runtime.pool.cachedDiscovery) : [];
42
+ let discoveredIds: Set<string> | undefined = known.length > 0 ? new Set(known.map((descriptor) => descriptor.id)) : undefined;
25
43
  const streamAgy = makeStreamAgy(runtime);
26
44
  const externalOAuthMarker = () => ({
27
45
  type: "oauth" as const,
@@ -30,9 +48,9 @@ export function createAgyProvider(runtime: AgyRuntime) {
30
48
  expires: Date.now() + 365 * 24 * 60 * 60 * 1_000,
31
49
  });
32
50
  return createProvider({
33
- id: PROVIDER_ID,
34
- name: "Antigravity (agy acp)",
35
- baseUrl: "process://agy-acp",
51
+ id: ids.provider,
52
+ name: accountName ?? "Antigravity (agy acp)",
53
+ baseUrl: `process://${ids.api}`,
36
54
  auth: {
37
55
  apiKey: {
38
56
  name: "Antigravity login (agy)",
@@ -60,7 +78,11 @@ export function createAgyProvider(runtime: AgyRuntime) {
60
78
  name: "Antigravity subscription (managed by agy)",
61
79
  isSubscription: true,
62
80
  async login() {
63
- throw new Error("Antigravity manages its own login. Run `agy` in a terminal and sign in; this provider uses it automatically.");
81
+ throw new Error(
82
+ account
83
+ ? `Antigravity manages its own login. Run /agy-bridge login ${account.id} (or /agy-bridge menu) to sign this account in.`
84
+ : "Antigravity manages its own login. Run `agy` in a terminal and sign in; this provider uses it automatically.",
85
+ );
64
86
  },
65
87
  async refresh() {
66
88
  await runtime.pool.discover(true);
@@ -71,12 +93,12 @@ export function createAgyProvider(runtime: AgyRuntime) {
71
93
  },
72
94
  },
73
95
  },
74
- models: STATIC_MODELS,
96
+ models: account ? toPiModels(known.length > 0 ? known : FALLBACK_DESCRIPTORS, runtime.observedWindows, ids) : STATIC_MODELS,
75
97
  async fetchModels() {
76
98
  runtime.trace("provider.fetchModels");
77
99
  const discovery = await runtime.pool.discover();
78
100
  const descriptors = describeModels(discovery);
79
- const models = toPiModels(descriptors.length > 0 ? descriptors : FALLBACK_DESCRIPTORS, runtime.observedWindows);
101
+ const models = toPiModels(descriptors.length > 0 ? descriptors : FALLBACK_DESCRIPTORS, runtime.observedWindows, ids);
80
102
  discoveredIds = new Set(models.map((model) => model.id));
81
103
  return models;
82
104
  },
package/src/runtime.ts CHANGED
@@ -1,7 +1,19 @@
1
1
  // The per-extension runtime: configuration, the shared session pool, agy compatibility state and facts learned
2
2
  // while running (observed context windows). One instance per extension load; tests build their own.
3
3
 
4
+ import { rm } from "node:fs/promises";
5
+ import path from "node:path";
6
+ import {
7
+ accountPaths,
8
+ DEFAULT_ACCOUNT,
9
+ FILE_STORAGE_ENV,
10
+ maskEmail,
11
+ waitForIdentity,
12
+ type AccountRecord,
13
+ type Identity,
14
+ } from "./accounts.ts";
4
15
  import { findAgyCommand } from "./acp/command.ts";
16
+ import type { AcpProcess } from "./acp/connection.ts";
5
17
  import type { AcpInitializeResult } from "./acp/types.ts";
6
18
  import { AgyCompatError, assertUsable, deriveFeatures, type AgyFeatures, type FeatureReport } from "./compat/features.ts";
7
19
  import { getMatrix } from "./compat/matrix.ts";
@@ -16,6 +28,19 @@ export interface RuntimeOptions {
16
28
  /** Test seams for the pool (fake argv, custom validator). */
17
29
  pool?: Partial<Pick<PoolOptions, "buildArgs" | "validate" | "env">>;
18
30
  log?: (message: string) => void;
31
+ /** The Antigravity account this runtime serves. Absent = the default (keyring) account, exactly as before. */
32
+ account?: AccountRecord;
33
+ /** How long an extra account waits for agy's log to name the signed-in account after its first `session/new`
34
+ * (default 10 s; agy writes it during that call, so normally no wait at all). */
35
+ identityTimeoutMs?: number;
36
+ }
37
+
38
+ /** What an extra-account process proved about itself at its last start. */
39
+ export interface AccountIdentityState {
40
+ at: number;
41
+ identity: Identity;
42
+ ok: boolean;
43
+ message?: string;
19
44
  }
20
45
 
21
46
  /** How long a recorded "logged out" or "too old" finding hides the models without re-checking. */
@@ -49,14 +74,58 @@ export class AgyRuntime {
49
74
  /** Disposals of pools replaced by applyEnv; dispose() waits for them so no old agy process outlives pi. */
50
75
  readonly #retiring = new Set<Promise<void>>();
51
76
  #writes = new Set<Promise<void>>();
77
+ #account: AccountRecord | undefined;
78
+ #identity: AccountIdentityState | undefined;
52
79
 
53
80
  constructor(options: RuntimeOptions = {}) {
54
81
  this.#options = options;
82
+ this.#account = options.account && options.account.id !== DEFAULT_ACCOUNT ? { ...options.account } : undefined;
55
83
  this.config = loadConfig(options.env ?? process.env);
56
- this.trace = options.log ?? createTrace(options.env ?? process.env, this.config.home);
84
+ const trace = options.log ?? createTrace(options.env ?? process.env, this.config.home);
85
+ this.trace = this.#account ? (message) => trace(`[${this.accountLabel}] ${message}`) : trace;
57
86
  this.#pool = this.#createPool();
58
87
  }
59
88
 
89
+ /** The extra account this runtime serves, or undefined for the default (keyring) account. */
90
+ get account(): AccountRecord | undefined {
91
+ return this.#account;
92
+ }
93
+
94
+ get accountLabel(): string {
95
+ return this.#account ? (this.#account.alias ?? this.#account.id) : "default";
96
+ }
97
+
98
+ /** What the last start of an extra-account process proved (email, storage); undefined before the first start. */
99
+ get identity(): AccountIdentityState | undefined {
100
+ return this.#identity;
101
+ }
102
+
103
+ /** Directory for this account's state hint (state.json): the shared home for the default account. */
104
+ get stateDir(): string {
105
+ return this.#account ? accountPaths(this.config.home, this.#account.id).root : this.config.home;
106
+ }
107
+
108
+ /** Change alias/email/enabled of the bound account. A changed email stops the process so the next use re-checks. */
109
+ updateAccount(next: AccountRecord): void {
110
+ if (!this.#account || next.id !== this.#account.id) return;
111
+ const emailChanged = next.email !== this.#account.email;
112
+ this.#account = { ...next };
113
+ if (emailChanged) {
114
+ this.#identity = undefined;
115
+ void this.#pool.reset().catch((error: unknown) => this.trace(`reset after account change failed: ${describeError(error)}`));
116
+ this.#pool.resetDiscovery();
117
+ }
118
+ }
119
+
120
+ /** Forget a recorded "unusable" hint (after a successful sign-in) so the provider is offered again at once. */
121
+ async clearUnusable(): Promise<void> {
122
+ this.#hintRecorded = false;
123
+ const state = await readState(this.stateDir);
124
+ if (!state.unusable) return;
125
+ const { unusable: _dropped, ...rest } = state;
126
+ await writeState(this.stateDir, rest);
127
+ }
128
+
60
129
  get pool(): SessionPool {
61
130
  return this.#pool;
62
131
  }
@@ -82,10 +151,23 @@ export class AgyRuntime {
82
151
  }
83
152
 
84
153
  #createPool(): SessionPool {
154
+ const account = this.#account;
155
+ const paths = account ? accountPaths(this.config.home, account.id) : undefined;
156
+ const baseEnv = this.#options.pool?.env;
85
157
  const pool = new SessionPool({
86
158
  config: this.config,
87
159
  buildArgs: this.#options.pool?.buildArgs,
88
- env: this.#options.pool?.env,
160
+ env: account ? { ...(baseEnv ?? process.env), ...FILE_STORAGE_ENV } : baseEnv,
161
+ ...(paths
162
+ ? {
163
+ stagingOverride: { geminiDir: paths.geminiDir, workDir: path.join(paths.root, "work") },
164
+ extraArgs: (staging) =>
165
+ // The real argv already names the gemini dir through the staging override; a test argv may not.
166
+ this.#options.pool?.buildArgs ? ["--gemini-dir", staging.geminiDir, "--log-file", paths.logFile] : ["--log-file", paths.logFile],
167
+ beforeStart: () => rm(paths.logFile, { force: true }),
168
+ verifyProcess: (proc, sessionFailure) => this.#checkIdentity(paths.logFile, proc, sessionFailure),
169
+ }
170
+ : {}),
89
171
  log: this.trace,
90
172
  onHealth: (event) => this.#onHealth(event),
91
173
  features: () => this.features,
@@ -110,6 +192,51 @@ export class AgyRuntime {
110
192
  return pool;
111
193
  }
112
194
 
195
+ /** Error text as pi sees it: default account unchanged; an extra account's message names the account so a fallback
196
+ * notice says which one failed. An account id is always prefixed by "account ", so it cannot form a bare
197
+ * three-digit number that the classifier would read as an HTTP status; agy's own text is left untouched. */
198
+ decorateError(message: string): string {
199
+ if (!this.#account) return message;
200
+ const id = this.#account.id;
201
+ return message.includes(`account ${id}`) ? message : `${message} (account ${id})`;
202
+ }
203
+
204
+ /** Identity guard for an extra account: agy must use the account's own token file and be signed in as the expected
205
+ * email. Anything else (keyring fallback, signed out, another account) stops the process before it serves a turn. */
206
+ async #checkIdentity(logFile: string, proc: AcpProcess, sessionFailure: unknown): Promise<void> {
207
+ const account = this.#account;
208
+ if (!account) return;
209
+ // Stop waiting as soon as the process is gone: it will never write the line.
210
+ const gone = new AbortController();
211
+ void proc.exited.then(() => gone.abort());
212
+ const identity = await waitForIdentity(logFile, this.#options.identityTimeoutMs ?? 10_000, gone.signal);
213
+ // session/new failed before agy resolved any login (we stopped the process, it crashed, the call timed out): that
214
+ // is not evidence about the account. Report the original failure instead of a guard verdict, so no 5-minute
215
+ // "unusable" hint is recorded for an ordinary reset.
216
+ const resolved = identity.fileStorage || identity.email !== undefined || identity.signedOut;
217
+ if (sessionFailure !== undefined && !resolved) throw sessionFailure;
218
+ const fail = (kind: "auth" | "compat", message: string): never => {
219
+ this.#identity = { at: Date.now(), identity, ok: false, message };
220
+ this.trace(`identity: FAILED ${message}`);
221
+ throw new AgyError(kind, message);
222
+ };
223
+ const login = `run /agy-bridge login ${account.id}`;
224
+ if (!identity.fileStorage) {
225
+ fail("compat", `pi-agy-bridge is unavailable: agy did not switch to per-account token storage for account ${account.id}, so it would use the default login (see UPGRADING.md)`);
226
+ }
227
+ if (!identity.email) {
228
+ fail("auth", `agy authentication required (not logged in) for account ${account.id}; ${login}`);
229
+ }
230
+ if (account.email && identity.email?.toLowerCase() !== account.email.toLowerCase()) {
231
+ fail(
232
+ "auth",
233
+ `agy authentication required (not logged in) for account ${account.id}: agy is signed in as ${maskEmail(identity.email)}, expected ${maskEmail(account.email)}; ${login}`,
234
+ );
235
+ }
236
+ this.#identity = { at: Date.now(), identity, ok: true };
237
+ this.trace(`identity: ok ${maskEmail(identity.email)} (file storage)`);
238
+ }
239
+
113
240
  /** Cheap, process-free answer to "should agy models be offered?": the executable exists and the last real use did
114
241
  * not find agy logged out or too old (within UNUSABLE_HINT_MS). pi waits for this during startup, so it must not
115
242
  * start agy; the handshake happens on first real use and records the outcome. */
@@ -118,7 +245,7 @@ export class AgyRuntime {
118
245
  if (!found) {
119
246
  return { available: false, reason: `agy was not found (command "${this.config.command}"); install the Antigravity CLI or set PI_AGY_COMMAND` };
120
247
  }
121
- const state = await readState(this.config.home);
248
+ const state = await readState(this.stateDir);
122
249
  const bad = state.unusable;
123
250
  if (bad && Date.now() - bad.at < UNUSABLE_HINT_MS) {
124
251
  this.#hintRecorded = true;
@@ -163,11 +290,11 @@ export class AgyRuntime {
163
290
  if (!event.ok) {
164
291
  this.#hintRecorded = true;
165
292
  const unusable = { at: Date.now(), kind: event.kind, message: event.message };
166
- update = readState(this.config.home).then((state: BridgeState) => writeState(this.config.home, { ...state, unusable }));
293
+ update = readState(this.stateDir).then((state: BridgeState) => writeState(this.stateDir, { ...state, unusable }));
167
294
  } else if (this.#hintRecorded) {
168
295
  this.#hintRecorded = false;
169
- update = readState(this.config.home).then((state: BridgeState) =>
170
- writeState(this.config.home, {
296
+ update = readState(this.stateDir).then((state: BridgeState) =>
297
+ writeState(this.stateDir, {
171
298
  lastOkAt: Date.now(),
172
299
  agyVersion: event.version ?? state.agyVersion,
173
300
  ...(state.appendRefused ? { appendRefused: state.appendRefused } : {}),
@@ -7,6 +7,7 @@
7
7
  // of the hash chain), the previous turn ended cleanly, and nobody invalidated it. Everything else replays history
8
8
  // into a fresh session, which is always correct.
9
9
 
10
+ import { mkdir } from "node:fs/promises";
10
11
  import { registerSessionResourceCleanup } from "@earendil-works/pi-ai";
11
12
  import { resolveAgyCommand } from "./acp/command.ts";
12
13
  import { AcpProcess } from "./acp/connection.ts";
@@ -69,6 +70,20 @@ export interface PoolOptions {
69
70
  buildArgs?: (staging: Staging) => string[];
70
71
  /** Reject an unusable agy (version/protocol) right after `initialize`. */
71
72
  validate?: (init: AcpInitializeResult) => void;
73
+ /** Replace parts of the staging layout (an extra account's own `--gemini-dir` and work dir). The stage/carrier agent
74
+ * stays shared. */
75
+ stagingOverride?: Partial<Pick<Staging, "geminiDir" | "workDir">>;
76
+ /** Arguments appended after the base argv (also after `buildArgs`), e.g. an account's `--log-file`. */
77
+ extraArgs?: (staging: Staging) => string[];
78
+ /** Runs before each process start (e.g. clear the account's previous log). */
79
+ beforeStart?: () => Promise<void>;
80
+ /** Identity guard. agy resolves its login lazily (measured on 1.5.14: the token-store and "authenticated as" lines
81
+ * appear while the first `session/new` runs), so this is called once per process right after its first
82
+ * `session/new` and before any model switch or prompt. A throw closes that session and stops the process.
83
+ * `sessionFailure` is the error of that `session/new`, if it failed: the guard rethrows it unchanged when agy never
84
+ * got as far as resolving its login (process stopped, timeout), so an ordinary reset is not reported as a guard
85
+ * failure. */
86
+ verifyProcess?: (proc: AcpProcess, sessionFailure: unknown) => Promise<void>;
72
87
  env?: NodeJS.ProcessEnv;
73
88
  log?: (message: string) => void;
74
89
  onHealth?: (event: HealthEvent) => void;
@@ -127,6 +142,9 @@ export class SessionPool {
127
142
  #invalidationSeq = 0;
128
143
  #invalidatedAll = 0;
129
144
  readonly #invalidatedAt = new Map<string, number>();
145
+ /** Processes whose identity check passed (see PoolOptions.verifyProcess). */
146
+ readonly #verified = new WeakSet<AcpProcess>();
147
+ readonly #verifying = new WeakMap<AcpProcess, Promise<void>>();
130
148
 
131
149
  constructor(options: PoolOptions) {
132
150
  this.#options = options;
@@ -147,6 +165,11 @@ export class SessionPool {
147
165
  };
148
166
  }
149
167
 
168
+ /** The last successful discovery, without starting anything (menus and status lines). */
169
+ get cachedDiscovery(): Discovery | undefined {
170
+ return this.#discovery?.value;
171
+ }
172
+
150
173
  get processAlive(): boolean {
151
174
  return this.#process?.alive === true;
152
175
  }
@@ -178,11 +201,15 @@ export class SessionPool {
178
201
 
179
202
  async #startProcess(): Promise<AcpProcess> {
180
203
  const generation = this.#generation;
181
- const staging = (this.#staging ??= await ensureStaging(this.#config.home));
204
+ const staging = (this.#staging ??= await this.#stage());
182
205
  const command = await resolveAgyCommand(this.#config.command);
183
- const args = this.#options.buildArgs
184
- ? this.#options.buildArgs(staging)
185
- : ["acp", "--add-dir", staging.addDir, "--agent", staging.agentName, "--gemini-dir", staging.geminiDir];
206
+ const args = [
207
+ ...(this.#options.buildArgs
208
+ ? this.#options.buildArgs(staging)
209
+ : ["acp", "--add-dir", staging.addDir, "--agent", staging.agentName, "--gemini-dir", staging.geminiDir]),
210
+ ...(this.#options.extraArgs?.(staging) ?? []),
211
+ ];
212
+ await this.#options.beforeStart?.();
186
213
  const proc = AcpProcess.start({
187
214
  command,
188
215
  args,
@@ -221,6 +248,61 @@ export class SessionPool {
221
248
  return proc;
222
249
  }
223
250
 
251
+ /** `session/new`, plus the one-time identity check of a process (see PoolOptions.verifyProcess). A process that
252
+ * fails the check is stopped; a failed `session/new` on an unverified process is still checked, because agy reports
253
+ * a missing login exactly that way and the guard words it for the user. */
254
+ async #newSession(proc: AcpProcess, params: { cwd: string; systemPromptAppend?: string }): Promise<AcpNewSessionResult> {
255
+ const verify = this.#options.verifyProcess;
256
+ if (!verify || this.#verified.has(proc)) return proc.newSession(params);
257
+ // Single-flight: concurrent first callers wait for one verification instead of each racing their own.
258
+ const pending = this.#verifying.get(proc);
259
+ if (pending) {
260
+ await pending;
261
+ return proc.newSession(params);
262
+ }
263
+ let release: () => void = () => undefined;
264
+ let fail: (error: unknown) => void = () => undefined;
265
+ const gate = new Promise<void>((resolve, reject) => {
266
+ release = resolve;
267
+ fail = reject;
268
+ });
269
+ gate.catch(() => undefined); // waiters observe the rejection; an unobserved one must not crash pi
270
+ this.#verifying.set(proc, gate);
271
+ try {
272
+ let created: AcpNewSessionResult | undefined;
273
+ let failure: unknown;
274
+ try {
275
+ created = await proc.newSession(params);
276
+ } catch (error) {
277
+ failure = error;
278
+ }
279
+ try {
280
+ await verify(proc, failure);
281
+ } catch (error) {
282
+ if (created?.sessionId && this.#canClose()) void this.#track(proc.closeSession(created.sessionId));
283
+ if (error !== failure) await this.killProcess(proc, "identity check failed");
284
+ throw error;
285
+ }
286
+ if (failure !== undefined || !created) throw failure;
287
+ this.#verified.add(proc);
288
+ release();
289
+ return created;
290
+ } catch (error) {
291
+ fail(error);
292
+ throw error;
293
+ } finally {
294
+ this.#verifying.delete(proc);
295
+ }
296
+ }
297
+
298
+ async #stage(): Promise<Staging> {
299
+ const base = await ensureStaging(this.#config.home);
300
+ const override = this.#options.stagingOverride;
301
+ if (!override) return base;
302
+ for (const dir of [override.geminiDir, override.workDir]) if (dir) await mkdir(dir, { recursive: true });
303
+ return { ...base, ...override };
304
+ }
305
+
224
306
  #onProcessExit(proc: AcpProcess): void {
225
307
  for (const entry of [...this.#entries]) {
226
308
  if (entry.process !== proc) continue;
@@ -280,7 +362,7 @@ export class SessionPool {
280
362
  this.#inflight += 1;
281
363
  try {
282
364
  const proc = await this.#ensureProcess();
283
- const created = await proc.newSession({ cwd: this.#staging?.workDir ?? this.#config.home });
365
+ const created = await this.#newSession(proc, { cwd: this.#staging?.workDir ?? this.#config.home });
284
366
  if (created.sessionId && this.#canClose()) void this.#track(proc.closeSession(created.sessionId));
285
367
  const value: Discovery = {
286
368
  init: this.#init ?? {},
@@ -390,7 +472,7 @@ export class SessionPool {
390
472
  const workDir = this.#staging?.workDir ?? this.#config.home;
391
473
  // Without agy's append hook the system text cannot ride session/new: the caller inlines it into the first prompt.
392
474
  const viaMeta = this.#options.features?.().systemPromptAppend !== false && request.systemInline !== true;
393
- const created = await proc.newSession({ cwd: workDir, systemPromptAppend: viaMeta ? request.systemAppend : undefined });
475
+ const created = await this.#newSession(proc, { cwd: workDir, systemPromptAppend: viaMeta ? request.systemAppend : undefined });
394
476
  const acpSessionId = created.sessionId as string;
395
477
  try {
396
478
  await proc.setConfigOption(acpSessionId, "model", request.modelId);
package/src/stream.ts CHANGED
@@ -184,7 +184,10 @@ class Translator {
184
184
  }
185
185
  }
186
186
 
187
- type CancelReason = "tool" | "abort" | "stall" | "timeout" | "exhausted";
187
+ /** `exhausted`: agy's RESOURCE_EXHAUSTED notice arrived (agy <= 1.5.12 sends one per retry). `refused`: a fresh session
188
+ * with the appended system prompt produced nothing within the refusal probe window (agy 1.5.14 retries silently and
189
+ * sends one notice only after ~140 s). Both mean "retry inline" in auto mode. */
190
+ type CancelReason = "tool" | "abort" | "stall" | "timeout" | "exhausted" | "refused";
188
191
 
189
192
  interface TurnResult {
190
193
  result: AcpPromptResult | undefined;
@@ -231,7 +234,7 @@ export function makeStreamAgy(runtime: AgyRuntime) {
231
234
  // error handling: an unhandled rejection here could take down the whole pi process.
232
235
  void run(runtime, model, sourceContext, options, stream, output).catch((error: unknown) => {
233
236
  output.stopReason = "error";
234
- output.errorMessage = normalizeAgyError(error).message;
237
+ output.errorMessage = runtime.decorateError(normalizeAgyError(error).message);
235
238
  stream.push({ type: "error", reason: "error", error: output });
236
239
  stream.end();
237
240
  });
@@ -281,15 +284,24 @@ async function run(
281
284
  // Stop at the first RESOURCE_EXHAUSTED only when the inline retry below can follow. Anywhere else agy's own retries
282
285
  // (~75 s) are the best chance of getting through a short throttle, e.g. in the middle of a subagent's tool loop.
283
286
  const inlineFallback = runtime.config.systemPrompt === "auto" && !lease.reused && !lease.systemInline;
284
- let turn = await runTurn(runtime, model, options, lease, prompt, translator, undefined, inlineFallback);
287
+ // agy 1.5.14 retries the refused prompt silently for ~140 s and only then sends one notice, so the notice alone no
288
+ // longer arrives in time. A fresh appended session that produced no model output (text or thinking) within the probe
289
+ // window is treated as refused too. Measured first output on 1.5.14: 0.4-3.4 s across Claude, Gemini 4 xhigh and the
290
+ // orchestrator; a false positive only costs one inline session, which is always served.
291
+ let turn = await runTurn(runtime, model, options, lease, prompt, translator, undefined, inlineFallback, runtime.config.refusalProbeMs);
285
292
 
286
293
  // The Antigravity backend refuses some system prompts sent through the append hook with RESOURCE_EXHAUSTED on
287
294
  // every try, while the same text inside the first prompt is served (measured on agy 1.5.9, 2026-11-14: pi's
288
295
  // default prompt, three models). In `auto` mode retry such a turn once with the system text inline and, if that
289
296
  // works, keep sending it inline for this runtime.
290
- if (turn.cancelReason === "exhausted" && inlineFallback && !translator.producedOutput) {
291
- runtime.trace(`turn: model=${model.id} RESOURCE_EXHAUSTED with the appended system prompt; retrying inline`);
292
- if (turn.wedged) await runtime.pool.killProcess(lease.process, "exhausted and ignored cancel");
297
+ const refused = turn.cancelReason === "exhausted" || turn.cancelReason === "refused";
298
+ if (refused && inlineFallback && !translator.producedOutput) {
299
+ runtime.trace(
300
+ turn.cancelReason === "refused"
301
+ ? `turn: model=${model.id} no output within ${runtime.config.refusalProbeMs}ms with the appended system prompt; retrying inline`
302
+ : `turn: model=${model.id} RESOURCE_EXHAUSTED with the appended system prompt; retrying inline`,
303
+ );
304
+ if (turn.wedged) await runtime.pool.killProcess(lease.process, "refused and ignored cancel");
293
305
  await lease.finish({ reusable: false });
294
306
  lease = undefined;
295
307
  translator.retryNotice = undefined;
@@ -374,7 +386,7 @@ async function run(
374
386
  stream.end();
375
387
  } catch (error) {
376
388
  output.stopReason = options?.signal?.aborted ? "aborted" : "error";
377
- output.errorMessage = options?.signal?.aborted ? "aborted" : normalizeAgyError(error).message;
389
+ output.errorMessage = options?.signal?.aborted ? "aborted" : runtime.decorateError(normalizeAgyError(error).message);
378
390
  if (!options?.signal?.aborted) runtime.noteFailure(error);
379
391
  await lease?.finish({ reusable: false });
380
392
  stream.push({ type: "error", reason: output.stopReason, error: output });
@@ -464,6 +476,8 @@ async function runTurn(
464
476
  remainingMs?: number,
465
477
  /** Cancel at agy's first RESOURCE_EXHAUSTED notice instead of letting it retry. */
466
478
  failFastExhausted = false,
479
+ /** With failFastExhausted: also cancel when no model output (text or thinking) arrived within this many ms. */
480
+ refusalProbeMs = 0,
467
481
  ): Promise<TurnResult> {
468
482
  const { process: proc, acpSessionId } = lease;
469
483
  const silenceMs = runtime.config.silenceMs;
@@ -473,6 +487,7 @@ async function runTurn(
473
487
  let cancelReason: CancelReason | undefined;
474
488
  let graceTimer: NodeJS.Timeout | undefined;
475
489
  let silenceTimer: NodeJS.Timeout | undefined;
490
+ let probeTimer: NodeJS.Timeout | undefined;
476
491
  let settled = false;
477
492
  let expire: () => void = () => undefined;
478
493
  const graceExpired = new Promise<"grace">((resolve) => {
@@ -484,6 +499,7 @@ async function runTurn(
484
499
  cancelReason = reason;
485
500
  if (silenceTimer) clearTimeout(silenceTimer);
486
501
  if (totalTimer) clearTimeout(totalTimer);
502
+ if (probeTimer) clearTimeout(probeTimer);
487
503
  proc.cancel(acpSessionId);
488
504
  graceTimer = setTimeout(expire, graceMs);
489
505
  graceTimer.unref();
@@ -495,18 +511,28 @@ async function runTurn(
495
511
  silenceTimer.unref();
496
512
  };
497
513
  const onAbort = (): void => requestCancel("abort");
514
+ /** Any model chunk (text or thinking) proves the backend accepted the prompt: the refusal probe ends. */
515
+ const modelSpoke = (): void => {
516
+ if (probeTimer) clearTimeout(probeTimer);
517
+ probeTimer = undefined;
518
+ };
498
519
 
499
520
  const stop = proc.listen(acpSessionId, (update) => {
500
521
  arm();
501
522
  switch (update.sessionUpdate) {
502
523
  case "agent_message_chunk":
503
524
  if (cancelReason) break;
525
+ // agy's own "⚠ ..." notices are not the model speaking; anything else is.
526
+ if (!/^\s*\u26A0/u.test(updateText(update))) modelSpoke();
504
527
  if (translator.message(updateText(update))) requestCancel("tool");
505
528
  // agy would back off and retry up to five times (~75 s), each try counting against the same limit.
506
529
  else if (failFastExhausted && translator.retryNotice?.exhausted) requestCancel("exhausted");
507
530
  break;
508
531
  case "agent_thought_chunk":
509
- if (!cancelReason) translator.thought(updateText(update));
532
+ if (!cancelReason) {
533
+ modelSpoke();
534
+ translator.thought(updateText(update));
535
+ }
510
536
  break;
511
537
  case "usage_update":
512
538
  if (typeof update.size === "number") runtime.observeWindow(model.id, update.size);
@@ -528,6 +554,12 @@ async function runTurn(
528
554
  totalTimer = setTimeout(() => requestCancel("timeout"), totalMs);
529
555
  totalTimer.unref();
530
556
  }
557
+ if (failFastExhausted && refusalProbeMs > 0) {
558
+ probeTimer = setTimeout(() => {
559
+ if (!translator.producedOutput) requestCancel("refused");
560
+ }, refusalProbeMs);
561
+ probeTimer.unref();
562
+ }
531
563
  const promptPromise = proc.prompt(acpSessionId, prompt).then(
532
564
  (result) => ({ kind: "result" as const, result }),
533
565
  (error: unknown) => ({ kind: "error" as const, error }),
@@ -550,6 +582,7 @@ async function runTurn(
550
582
  settled = true;
551
583
  if (silenceTimer) clearTimeout(silenceTimer);
552
584
  if (totalTimer) clearTimeout(totalTimer);
585
+ if (probeTimer) clearTimeout(probeTimer);
553
586
  if (graceTimer) clearTimeout(graceTimer);
554
587
  options?.signal?.removeEventListener("abort", onAbort);
555
588
  stop();