@timmyjl12/pi-agy-bridge 0.3.2 → 0.3.3

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/ARCHITECTURE.md CHANGED
@@ -67,7 +67,9 @@ A pooled session is reused only when all of these hold:
67
67
 
68
68
  Invalidation comes from three places: pi-context's rewrite registry (`Symbol.for("claude-bridge:markRebuildHooks")`), pi-ai `cleanupSessionResources` (`/fresh`, session end), and the prefix check itself as the backstop. Boundary compaction and rollover notify the registry; pi-context shake currently does not, but its edits change the hash chain and therefore force the same safe fresh-session replay even without a notification. Busy/opening leases use invalidation sequence markers, and repeat invalidation refreshes recency before the bounded map evicts its oldest entry. Replaying is always correct; reuse saves a `session/new` (about a second), the resent history and, above roughly 16k prompt tokens, most of the prompt cost: agy's cache works only inside a continuing session (three fresh sessions with an identical 22.9k prefix cached nothing). A session that ended at a tool call is kept for `PI_AGY_TOOL_TTL_MIN` (30 min) because pi may run a long tool; any retained session also keeps the process alive.
69
69
 
70
- agy truncates oversized converted prompt content (a real failure retained roughly 192 KiB). `buildPrompt` therefore splits replayed history, inline instructions and latest input into ordered blocks of at most 128 KiB of UTF-8. Embedded history uses `pi://conversation.md`, then `?part=2`, `?part=3`, and so on; the plain-text fallback splits its combined text the same way. Chunking never splits a Unicode codepoint. When total replay exceeds that budget, the blocks become sequential bounded prompt turns within one agy session: the model acknowledges each historical part, receives the actual request only after every part arrives, and the bridge aggregates usage from all parts instead of hiding replay cost. The completed session is then reused under the normal exact-prefix rule. Before acquisition, a separate model-window guard uses pi-ai's `estimateContextTokens` plus 15% safety and the output reserve (up to 32,768 tokens); if that cannot fit `model.contextWindow`, the bridge returns `context_length_exceeded` before any model call so pi compacts instead of replaying beyond the backend limit. The last assistant's usage is used only when it belongs to the same provider/api; on a handoff (for example agy → neuralwatt), every pi message is re-estimated because the old provider's usage can describe a compacted session mirror rather than pi's full history. The 8 MiB `PI_AGY_MAX_REPLAY_KB` total guard remains independent of these per-block and token-window limits. A real agy check with a late-history synthetic fact returned the fact with zero truncation markers and 42,164 cacheRead tokens.
70
+ Internal replay acknowledgements and the single whitespace-recovery prompt are transport details, not pi transcript messages. They stay inside the same agy session; the next exact continuation sends only pi's new suffix, while a fresh replay uses pi's transcript as the source of truth. Parser-buffered text and truncated tool calls are flushed before empty-answer recovery is considered, so recovery cannot discard emitted work. These rules preserve the context delivered to the model; they do not guarantee correct model reasoning over that context.
71
+
72
+ agy truncates oversized converted prompt content (a real failure retained roughly 192 KiB). `buildPrompt` therefore splits replayed history, inline instructions and latest input into ordered blocks of at most 128 KiB of UTF-8. Embedded history uses `pi://conversation.md`, then `?part=2`, `?part=3`, and so on; the plain-text fallback splits its combined text the same way. Chunking never splits a Unicode codepoint. When total replay exceeds that budget, the blocks become sequential bounded prompt turns within one agy session: the model acknowledges each historical part, receives the actual request only after every part arrives, and the bridge aggregates usage from all parts instead of hiding replay cost. Replay ACK turns do not interpret pi's tool protocol: a protocol-looking block is unexecuted text and cannot cancel context delivery, while the actual user request keeps normal tool parsing. The completed session is then reused under the normal exact-prefix rule. Before acquisition, a separate model-window guard uses pi-ai's `estimateContextTokens` plus 15% safety and the output reserve (up to 32,768 tokens); if that cannot fit `model.contextWindow`, the bridge returns `context_length_exceeded` before any model call so pi compacts instead of replaying beyond the backend limit. The last assistant's usage is used only when it belongs to the same provider/api; on a handoff (for example agy → neuralwatt), every pi message is re-estimated because the old provider's usage can describe a compacted session mirror rather than pi's full history. The 8 MiB `PI_AGY_MAX_REPLAY_KB` total guard remains independent of these per-block and token-window limits. A real agy check with a late-history synthetic fact returned the fact with zero truncation markers and 42,164 cacheRead tokens.
71
73
 
72
74
  ## Process model
73
75
 
@@ -77,7 +79,7 @@ One shared `agy acp` per extension runtime, started on first real use, serving e
77
79
 
78
80
  `AccountManager` (`account-manager.ts`) owns one `AgyRuntime` per Antigravity account. The default runtime is the one described above (provider `agy`, api `agy-acp`, agy's keyring login) and is registered synchronously at load, exactly as before. Each enabled entry of `<home>/accounts.json` (plus `PI_AGY_ACCOUNTS`) gets its own runtime, pool and `agy acp` process, and its own pi provider `agy-<alias ?? id>` with its own api id `agy-acp-<alias ?? id>` (pi-ai's compat stream registry is keyed by api id, so ids must not be shared). Providers are (un)registered live through `pi.registerProvider` / `pi.unregisterProvider` when an account is added, renamed, enabled, disabled or removed.
79
81
 
80
- An extra account's process differs from the default in three ways: `--gemini-dir <home>/accounts/<id>/gemini` (and its own work dir), `--log-file <home>/accounts/<id>/acp.log` (moved to `acp.prev.log` when the next process starts, so a failed run can still be read), and `SSH_CONNECTION` in its environment. agy keeps one login per OS user in the keyring; when it sees an SSH session it uses a token file inside the gemini dir instead (measured on 1.5.12 and 1.5.14, `.plan/agy-multi-account/evidence`). `agy acp --login` with the same three settings signs that folder in (`accounts.ts` `startLogin`).
82
+ An extra account's process differs from the default in three ways: `--gemini-dir <home>/accounts/<id>/gemini` (and its own work dir), `--log-file <home>/accounts/<id>/acp-<pid>.log` (moved to `acp-<pid>.prev.log` when that pi process restarts agy, so a failed run can still be read and concurrent pi processes never rotate each other's logs), and `SSH_CONNECTION` in its environment. agy keeps one login per OS user in the keyring; when it sees an SSH session it uses a token file inside the gemini dir instead (measured on 1.5.12 and 1.5.14, `.plan/agy-multi-account/evidence`). `agy acp --login` with the same three settings signs that folder in (`accounts.ts` `startLogin`).
81
83
 
82
84
  The identity guard (`PoolOptions.verifyProcess`, `AgyRuntime` `#checkIdentity`) runs once per process right after its first `session/new`, because agy resolves the login lazily during that call. It reads agy's own log: the process is used only if agy reports file-based token storage and `authenticated successfully as <expected email>`. Otherwise the session is closed, the process stopped, and the request fails with `agy authentication required (not logged in) … account <id>` (non-retryable for pi-fallback-chains) or, when the storage trigger is missing, `pi-agy-bridge is unavailable: …` - so an extra provider never silently spends the default account's quota. Each account has its own `state.json` hint and trace tag; error messages of an extra account end with `(account <id>)`.
83
85
 
@@ -111,11 +113,13 @@ Measured on agy 1.5.3 (`evidence/cache-and-usage-semantics.md`, pinned by `tests
111
113
  | no output for the silence limit | `agy stalled for Ns with no output` | retryable |
112
114
  | pi's idle `timeoutMs` elapsed without an ACP update | `agy request timed out after Ns` | retryable |
113
115
  | empty answer | `agy returned success but produced no model output:` | retryable |
114
- | quota (agy sends it as a normal `end_turn` reply with no usage; detected and failed) | `agy quota exhausted:` + agy's text (keeps `Resets in ...`) | retryable, provider cap |
116
+ | quota (agy sends it as a normal `end_turn` reply, with absent/zero usage or after billable thinking; detected and failed) | `agy quota exhausted:` + agy's text (keeps `Resets in ...`) | retryable, provider cap |
115
117
  | not logged in | `agy authentication required (not logged in)` | non-retryable |
116
118
  | context too large | `context_length_exceeded:` | non-retryable |
117
119
  | agy too old / wrong protocol | `pi-agy-bridge is unavailable:` | retryable |
118
120
 
121
+ A successful `end_turn` that spent output tokens or emitted reasoning but produced no visible answer gets one same-session retry for a normal answer or protocol tool call; usage from both attempts is aggregated. A second whitespace-only answer, or a truly empty zero-output reply, keeps the error above.
122
+
119
123
  Own messages avoid bare three-digit numbers because the classifier reads them as HTTP statuses.
120
124
 
121
125
  ## Upgrade path
package/README.md CHANGED
@@ -4,7 +4,7 @@ Use Google Antigravity models (Gemini, Claude, GPT-OSS) in [pi](https://github.c
4
4
 
5
5
  It follows the design of `pi-claude-code`: **pi keeps the conversation, the approvals and the tool execution; agy is only the model.** Every pi request becomes one ACP prompt turn. When the model wants a pi tool it writes a small tool-call block, pi runs the tool, and the next request carries the result. Nothing is parked between requests, so a slow tool (a long `pytest` run, a user dialog) can take as long as it needs and there is no turn time limit.
6
6
 
7
- > Status: 0.3.2. Large conversation replay is now sequential and bounded, model-window overflow triggers pi compaction before any model call, and switching providers recomputes context from the full pi transcript. agy 1.5.17 and google-antigravity SDK 0.1.24 are tested. 0.3.1: active agy turns no longer hit pi's idle request timeout merely because their total duration exceeds it: every ACP update refreshes that deadline, while the independent silence guard still cancels inactive turns. 0.3.0: agy 1.5.16 and the `google-antigravity` SDK 0.1.24 are now tested; agy 1.5.17 is also recorded and tested with an identical ACP contract. agy 1.5.16 retired `gemini-pro-orchestrator-g1-pro`; its orchestrators are now `gemini-pro-orchestrator` (Carbon), `gemini-pro-orchestrator-argon` and `gemini-pro-orchestrator-neon`, and Gemini 4 Carbon (low, medium, high) is new. The SDK change (a removed `InputConfig.use_interactions_api` field) does not touch the bridge, which uses the SDK only as a drift canary. Stalls and timeouts are now easier to diagnose: an extra account keeps its previous agy log as `acp.prev.log`, and with `PI_AGY_TRACE=1` a stalled or timed-out turn records what agy last sent and when. agy 1.5.16 also forwards subagent and workflow questions to the editor; the bridge's carrier agent has no agy tools, subagents or skills, so agy never asks them here. 0.2.1: Extra-account sign-in works on agy 1.5.14: agy now prints a link and waits for the authorization code, so the bridge opens the link and asks for the code in a dialog. 0.2.0: Multiple Antigravity accounts: each extra account runs as its own provider `agy-<alias or id>` with its own login, managed from `/agy-bridge menu` or the `/agy-bridge` account commands; verified live on agy 1.5.14 with two Google accounts answering side by side. agy 1.5.14 is now tested: it refuses pi's appended system prompt silently (no notice for ~2 min), which `auto` now detects with a 30 s refusal probe and answers inline (see [Multiple Antigravity accounts](#multiple-antigravity-accounts)). 0.1.5: the default bridge home now honors Pi's configured agent directory (`PI_CODING_AGENT_DIR`). Every Pi session shutdown now recycles the outgoing runtime instead of permanently latching it shut, so a late pi-advisor retry can start a fresh ACP process; explicit terminal disposal remains terminal. The compatibility probe passed on `agy 1.5.8`, `1.5.9` and `1.5.12`; the drift from 1.5.9 to 1.5.12 is additive only (the `gemini-4-neon` family, `gemini-pro-orchestrator-neon`, and `xhigh` as a `thought_level`). The `google-antigravity` SDK was then current at `0.1.23`. On 2026-11-14 (agy 1.5.9) the Antigravity backend began refusing pi's default system prompt sent through the append hook with `RESOURCE_EXHAUSTED`; live `gemini-4-hydrogen` turns and pi-subagents runs succeed through the `auto` inline fallback (see `PI_AGY_SYSTEM_PROMPT`). Earlier live bridge checks passed on `agy 1.5.8`. Live turns succeeded on `gemini-3.8-flash`, `gemini-4-hydrogen` (including `xhigh`), and `gemini-pro-orchestrator-g1-pro`. A real pi surface check with the configured extensions also passed. Claude, GPT-OSS and the `gemini-4-neon` family have not been exercised in a live model turn.
7
+ > Status: 0.3.3. Leading quota warnings now trigger fallback even after billable thinking, concurrent pi processes use isolated per-account ACP logs, internal replay ACKs can no longer abort the real request as tool calls, and reasoning-only or whitespace-only answers get one bounded same-session recovery retry without losing buffered text or truncated tool calls. 0.3.2: Large conversation replay is now sequential and bounded, model-window overflow triggers pi compaction before any model call, and switching providers recomputes context from the full pi transcript. agy 1.5.17 and google-antigravity SDK 0.1.24 are tested. 0.3.1: active agy turns no longer hit pi's idle request timeout merely because their total duration exceeds it: every ACP update refreshes that deadline, while the independent silence guard still cancels inactive turns. 0.3.0: agy 1.5.16 and the `google-antigravity` SDK 0.1.24 are now tested; agy 1.5.17 is also recorded and tested with an identical ACP contract. agy 1.5.16 retired `gemini-pro-orchestrator-g1-pro`; its orchestrators are now `gemini-pro-orchestrator` (Carbon), `gemini-pro-orchestrator-argon` and `gemini-pro-orchestrator-neon`, and Gemini 4 Carbon (low, medium, high) is new. The SDK change (a removed `InputConfig.use_interactions_api` field) does not touch the bridge, which uses the SDK only as a drift canary. Stalls and timeouts are now easier to diagnose: an extra account keeps its previous agy log as `acp.prev.log`, and with `PI_AGY_TRACE=1` a stalled or timed-out turn records what agy last sent and when. agy 1.5.16 also forwards subagent and workflow questions to the editor; the bridge's carrier agent has no agy tools, subagents or skills, so agy never asks them here. 0.2.1: Extra-account sign-in works on agy 1.5.14: agy now prints a link and waits for the authorization code, so the bridge opens the link and asks for the code in a dialog. 0.2.0: Multiple Antigravity accounts: each extra account runs as its own provider `agy-<alias or id>` with its own login, managed from `/agy-bridge menu` or the `/agy-bridge` account commands; verified live on agy 1.5.14 with two Google accounts answering side by side. agy 1.5.14 is now tested: it refuses pi's appended system prompt silently (no notice for ~2 min), which `auto` now detects with a 30 s refusal probe and answers inline (see [Multiple Antigravity accounts](#multiple-antigravity-accounts)). 0.1.5: the default bridge home now honors Pi's configured agent directory (`PI_CODING_AGENT_DIR`). Every Pi session shutdown now recycles the outgoing runtime instead of permanently latching it shut, so a late pi-advisor retry can start a fresh ACP process; explicit terminal disposal remains terminal. The compatibility probe passed on `agy 1.5.8`, `1.5.9` and `1.5.12`; the drift from 1.5.9 to 1.5.12 is additive only (the `gemini-4-neon` family, `gemini-pro-orchestrator-neon`, and `xhigh` as a `thought_level`). The `google-antigravity` SDK was then current at `0.1.23`. On 2026-11-14 (agy 1.5.9) the Antigravity backend began refusing pi's default system prompt sent through the append hook with `RESOURCE_EXHAUSTED`; live `gemini-4-hydrogen` turns and pi-subagents runs succeed through the `auto` inline fallback (see `PI_AGY_SYSTEM_PROMPT`). Earlier live bridge checks passed on `agy 1.5.8`. Live turns succeeded on `gemini-3.8-flash`, `gemini-4-hydrogen` (including `xhigh`), and `gemini-pro-orchestrator-g1-pro`. A real pi surface check with the configured extensions also passed. Claude, GPT-OSS and the `gemini-4-neon` family have not been exercised in a live model turn.
8
8
 
9
9
  ## Requirements
10
10
 
@@ -140,11 +140,12 @@ Example chain, mirrored from an `antigravity/*` chain:
140
140
  | `agy authentication required (not logged in)` | login expired | run `agy` and sign in |
141
141
  | `agy authentication required (not logged in) for account <id>` | that extra account has no saved login, or agy is signed in as a different Google account than the one recorded | `/agy-bridge login <id>` (the new email becomes the expected one) |
142
142
  | `pi-agy-bridge is unavailable: agy did not switch to per-account token storage for account <id>` | an agy update stopped honouring the trigger extra accounts use; they fail closed rather than use your default login | see `UPGRADING.md` §1 (the compat probe reports this as breaking) |
143
- | `agy quota exhausted: ... Resets in ...` | the plan's quota for that model is used up (agy delivers this as a normal reply with no tokens; the bridge turns it into an error so fallback chains rotate) | use another model; the reset time is in the message |
143
+ | `agy quota exhausted: ... Resets in ...` | the plan's quota for that model is used up (agy delivers this as a normal reply, sometimes after billable thinking; the bridge turns a leading warning into an error whether usage is absent, zero or nonzero so fallback chains rotate immediately) | use another model/account; the reset time is in the message |
144
144
  | `agy quota exceeded: Antigravity answered RESOURCE_EXHAUSTED ...` | the backend refused the request (429). agy would retry five times (~75 s); the bridge stops at the first notice. Since 2026-11-14 the backend refuses pi's default system prompt when it comes through the append hook (all models), while the same text inline is served; `auto` handles this | nothing in `auto` mode; otherwise use another model. The message says whether the prompt was appended or inline |
145
- | `agy stalled for 120s with no output` | the model produced nothing for the silence limit (with agy 1.5.14 and `PI_AGY_SYSTEM_PROMPT=append`: the backend's silent refusal of the appended prompt; use `auto`) | retry; raise `PI_AGY_SILENCE_SEC` for very long silent thinking. To see why, set `PI_AGY_TRACE=1` (the trace names agy's last update); for an extra account agy's own log of the failed run is `<home>/accounts/<id>/acp.prev.log` after the next start |
145
+ | `agy stalled for 120s with no output` | the model produced nothing for the silence limit (with agy 1.5.14 and `PI_AGY_SYSTEM_PROMPT=append`: the backend's silent refusal of the appended prompt; use `auto`) | retry; raise `PI_AGY_SILENCE_SEC` for very long silent thinking. To see why, set `PI_AGY_TRACE=1` (the trace names agy's last update); for an extra account agy's own log of the failed run is `<home>/accounts/<id>/acp-<pid>.prev.log` after that pi process's next start (per-process logs avoid concurrent-start rotation locks) |
146
146
  | `agy request timed out after 300s` | agy sent no ACP update within pi's request timeout (`timeoutMs`; 300 s here), which defaults to pi's `httpIdleTimeoutMs`. Active turns refresh this deadline; with the default 120 s silence guard, that guard normally fires first | retry; pi's `/settings` HTTP timeout controls this idle limit (or set `retry.provider.timeoutMs`). The same `PI_AGY_TRACE=1` line shows what agy last sent |
147
147
  | the model says `pi://conversation.md` was truncated before it could see the request | agy truncates oversized converted prompt content; this build delivers history, instructions and latest input as sequential bounded turns within one agy session instead | reload the extension and retry the current session (a fresh session alone would replay the same content). If pi's token estimate plus safety/output reserve exceeds the model window, the bridge returns `context_length_exceeded` before any model call so pi compacts automatically; total replay above `PI_AGY_MAX_REPLAY_KB` still needs a higher safe cap |
148
+ | `agy returned success but produced no model output: stop reason end_turn` | agy ended without visible answer text or a tool call | retry; when agy emitted reasoning or spent output tokens, this build automatically asks once in the same session for the missing visible answer before reporting this error |
148
149
  | `agy exited with status N` | the agy process died | retry (a new process starts); `/agy-bridge doctor` shows agy's last stderr |
149
150
  | `agy is unavailable: pi-agy-bridge is shut down` during or just after reload/session replacement | 0.1.2 or older permanently latched the outgoing pool while a background caller (often pi-advisor) was retrying | upgrade to 0.1.3 or newer. An old advisor error can remain visible until a later review succeeds; that sticky status is normal |
150
151
  | `pi-agy-bridge is unavailable: agy ... below the minimum` | agy too old | `agy update` |
package/compat/probe.ts CHANGED
@@ -40,7 +40,7 @@ export const PROBE_PROTOCOL_VERSION = 1;
40
40
  export const PROBE_CLIENT_INFO = {
41
41
  name: "pi-agy-bridge-compat-probe",
42
42
  title: "pi-agy-bridge zero-cost compat probe",
43
- version: "0.3.2",
43
+ version: "0.3.3",
44
44
  } as const;
45
45
 
46
46
  /** One failed probe step. `step` names the command or exchange. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@timmyjl12/pi-agy-bridge",
3
- "version": "0.3.2",
3
+ "version": "0.3.3",
4
4
  "description": "pi provider for Google Antigravity (agy) models over the official ACP server, modelled on pi-claude-code: pi keeps the loop, history and tool execution",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/accounts.ts CHANGED
@@ -95,8 +95,19 @@ export function accountPaths(home: string, id: string): AccountPaths {
95
95
  };
96
96
  }
97
97
 
98
- /** Before an extra-account process starts: move its last log to `acp.prev.log` (replacing the older one) so the new
99
- * process starts with an empty log for the identity guard, while the previous run stays readable. */
98
+ /** ACP logs are private to one pi process. Several pi agents can use the same account concurrently without rotating
99
+ * or deleting the log another process still has open. `owner` is a test seam; production uses pi's process id. */
100
+ export function accountProcessPaths(home: string, id: string, owner = process.pid): AccountPaths {
101
+ const paths = accountPaths(home, id);
102
+ return {
103
+ ...paths,
104
+ logFile: path.join(paths.root, `acp-${owner}.log`),
105
+ prevLogFile: path.join(paths.root, `acp-${owner}.prev.log`),
106
+ };
107
+ }
108
+
109
+ /** Before an extra-account process starts: move its last log to the matching previous-log path (replacing the older
110
+ * one) so the new process starts with an empty log for the identity guard, while the previous run stays readable. */
100
111
  export async function rotateAccountLog(
101
112
  paths: Pick<AccountPaths, "logFile" | "prevLogFile">,
102
113
  io: { rename: typeof rename; rm: typeof rm } = { rename, rm },
@@ -194,7 +194,7 @@ export class AcpProcess {
194
194
  const result = await this.#rpc.request("initialize", {
195
195
  protocolVersion: 1,
196
196
  clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
197
- clientInfo: { name: "pi-agy-bridge", title: "pi-agy-bridge", version: "0.3.2" },
197
+ clientInfo: { name: "pi-agy-bridge", title: "pi-agy-bridge", version: "0.3.3" },
198
198
  });
199
199
  return (result ?? {}) as AcpInitializeResult;
200
200
  }
package/src/errors.ts CHANGED
@@ -111,8 +111,8 @@ export function looksLikeNotice(text: string): boolean {
111
111
 
112
112
  /** agy reports some failures as an ordinary reply with no model call, for example
113
113
  * "⚠ Individual quota reached. Please upgrade your subscription to increase your limits. Resets in 141h13m52s."
114
- * (observed on agy 1.5.3 when a model's quota is used up: the PromptResponse is just {"stopReason":"end_turn"}, with no
115
- * usage field at all). Classify the text like any other failure so quota, login and context problems reach fallback
114
+ * (observed on agy 1.5.3 with no usage field; agy 1.5.17 can emit thinking and nonzero usage before the same warning).
115
+ * Classify the text like any other failure so quota, login and context problems reach fallback
116
116
  * chains with their words intact; a notice that matches nothing known must still not pass as an answer. */
117
117
  export function noticeError(text: string): AgyError {
118
118
  const notice = text.trim();
package/src/runtime.ts CHANGED
@@ -4,6 +4,7 @@
4
4
  import path from "node:path";
5
5
  import {
6
6
  accountPaths,
7
+ accountProcessPaths,
7
8
  DEFAULT_ACCOUNT,
8
9
  FILE_STORAGE_ENV,
9
10
  maskEmail,
@@ -33,6 +34,8 @@ export interface RuntimeOptions {
33
34
  /** How long an extra account waits for agy's log to name the signed-in account after its first `session/new`
34
35
  * (default 10 s; agy writes it during that call, so normally no wait at all). */
35
36
  identityTimeoutMs?: number;
37
+ /** Test seam for proving two pi processes can use one account without sharing ACP logs. Defaults to process.pid. */
38
+ accountLogOwner?: number;
36
39
  }
37
40
 
38
41
  /** What an extra-account process proved about itself at its last start. */
@@ -152,7 +155,7 @@ export class AgyRuntime {
152
155
 
153
156
  #createPool(): SessionPool {
154
157
  const account = this.#account;
155
- const paths = account ? accountPaths(this.config.home, account.id) : undefined;
158
+ const paths = account ? accountProcessPaths(this.config.home, account.id, this.#options.accountLogOwner) : undefined;
156
159
  const baseEnv = this.#options.pool?.env;
157
160
  const pool = new SessionPool({
158
161
  config: this.config,
package/src/stream.ts CHANGED
@@ -121,15 +121,17 @@ class Translator {
121
121
  readonly #stream: AssistantMessageEventStream;
122
122
  readonly #output: AssistantMessage;
123
123
  #parser = new ToolCallStreamParser();
124
+ readonly #parseTools: boolean;
124
125
  #open: { kind: OpenKind; index: number } | undefined;
125
126
  toolCalled = false;
126
127
  producedOutput = false;
127
128
  /** agy's latest "⚠ API error (attempt N)" notice. Never shown as model text. */
128
129
  retryNotice: ApiRetryNotice | undefined;
129
130
 
130
- constructor(stream: AssistantMessageEventStream, output: AssistantMessage) {
131
+ constructor(stream: AssistantMessageEventStream, output: AssistantMessage, parseTools = true) {
131
132
  this.#stream = stream;
132
133
  this.#output = output;
134
+ this.#parseTools = parseTools;
133
135
  }
134
136
 
135
137
  thought(text: string): void {
@@ -143,6 +145,7 @@ class Translator {
143
145
  this.#close();
144
146
  this.#output.content = [];
145
147
  this.#parser = new ToolCallStreamParser();
148
+ this.retryNotice = undefined;
146
149
  }
147
150
 
148
151
  /** Returns true when this chunk completed a tool-call block. */
@@ -158,12 +161,16 @@ class Translator {
158
161
  if (this.retryNotice && !this.producedOutput && /^\s*\u26A0/u.test(chunk) && chunk.includes(this.retryNotice.detail.slice(0, 40))) {
159
162
  return false;
160
163
  }
164
+ if (!this.#parseTools) {
165
+ this.#delta("text", chunk);
166
+ return false;
167
+ }
161
168
  this.#apply(this.#parser.push(chunk));
162
169
  return this.toolCalled;
163
170
  }
164
171
 
165
172
  finish(): void {
166
- if (!this.toolCalled) this.#apply(this.#parser.end());
173
+ if (this.#parseTools && !this.toolCalled) this.#apply(this.#parser.end());
167
174
  this.#close();
168
175
  }
169
176
 
@@ -316,7 +323,8 @@ async function runReplayPart(
316
323
  stopReason: "pending",
317
324
  timestamp: Date.now(),
318
325
  };
319
- const translator = new Translator(replayStream, output);
326
+ // Replay is context delivery, not a pi agent turn: protocol-looking output is ACK text and must never cancel for a tool.
327
+ const translator = new Translator(replayStream, output, false);
320
328
  const guidance = [
321
329
  `You are receiving earlier conversation context in ${total} bounded replay parts; this is part ${index}.`,
322
330
  "Treat the attached content as historical context only. Do not answer historical requests or call tools.",
@@ -462,7 +470,6 @@ async function run(
462
470
  if (turn.wedged) await runtime.pool.killProcess(lease.process, "refused and ignored cancel");
463
471
  await lease.finish({ reusable: false });
464
472
  lease = undefined;
465
- translator.retryNotice = undefined;
466
473
  translator.reset();
467
474
  const remaining = deadline === undefined ? undefined : deadline - Date.now();
468
475
  if (remaining !== undefined && remaining <= 0) {
@@ -481,6 +488,44 @@ async function run(
481
488
  runtime.trace("turn: inline system prompt served; later sessions send it inline");
482
489
  }
483
490
  }
491
+
492
+ // Flush parser-buffered text and truncated tool calls before deciding whether the answer is empty. Resetting first
493
+ // would silently discard work that the model already emitted.
494
+ translator.finish();
495
+
496
+ // A model can spend its output on reasoning and then end with only whitespace (recorded on agy 1.5.17 after a
497
+ // tool result: 1,693 output tokens, visible text "\n"). That is not an answer, but the session is still usable:
498
+ // ask it once for the missing visible response instead of failing the whole pi turn. Truly empty replies keep the
499
+ // existing error/fallback behavior, and a second whitespace-only reply is not retried again.
500
+ const unfinishedAnswer =
501
+ !translator.producedOutput &&
502
+ !translator.toolCalled &&
503
+ turn.cancelReason === undefined &&
504
+ turn.result?.stopReason === "end_turn" &&
505
+ (output.content.length > 0 || (turn.result.usage?.outputTokens ?? 0) > 0);
506
+ if (unfinishedAnswer) {
507
+ runtime.trace(`turn: model=${model.id} ended with reasoning or whitespace but no visible answer; retrying once`);
508
+ replayUsages.push(turn.result?.usage);
509
+ translator.reset();
510
+ const remaining = deadline === undefined ? undefined : deadline - Date.now();
511
+ if (remaining !== undefined && remaining <= 0) {
512
+ throw new AgyError("stalled", `agy request timed out after ${Math.round((options?.timeoutMs ?? 0) / 1000)}s`);
513
+ }
514
+ turn = await runTurn(
515
+ runtime,
516
+ model,
517
+ options,
518
+ lease,
519
+ [
520
+ {
521
+ type: "text",
522
+ text: "Your previous response contained no visible answer. Complete the user's request now with normal answer text, or use the pi tool-call protocol if a tool is required. Do not return only reasoning or whitespace.",
523
+ },
524
+ ],
525
+ translator,
526
+ remaining,
527
+ );
528
+ }
484
529
  translator.finish();
485
530
 
486
531
  if (turn.result) mapUsage(model, mergeUsage([...replayUsages, turn.result.usage]), output.usage);
@@ -510,15 +555,17 @@ async function run(
510
555
  throw normalizeAgyError(new Error(`Antigravity API error after ${notice.attempt} attempts: ${notice.detail}`));
511
556
  }
512
557
 
513
- // A used-up quota (and similar) is delivered by agy as a normal end_turn whose text is the warning, with NO usage
514
- // object at all (measured on agy 1.5.3). Real model turns always report tokens, so: usage present and zero is
515
- // always agy's own notice; usage absent counts only when the text reads like a notice (an agy that never reports
516
- // usage must still be able to answer). Fail it so fallback chains and subagents see an error, not a reply.
558
+ // A used-up quota (and similar) is delivered by agy as a normal end_turn whose text is the warning. Older agy
559
+ // omitted usage; 1.5.17 can instead do billable thinking first and then append the warning with nonzero usage.
560
+ // A leading warning sign therefore classifies independently of usage. Without one, absent usage counts only when
561
+ // the text reads like a notice (an agy that never reports usage must still be able to answer). Zero-token replies
562
+ // are always notices. Fail these so fallback chains rotate immediately instead of showing the warning as an answer.
517
563
  const reported = turn.result?.usage;
518
564
  const zeroTokens = reported !== undefined && (reported.inputTokens ?? 0) === 0 && (reported.outputTokens ?? 0) === 0;
519
- if ((reported === undefined || zeroTokens) && !translator.toolCalled && turn.result?.stopReason === "end_turn") {
565
+ if (!translator.toolCalled && turn.result?.stopReason === "end_turn") {
520
566
  const reply = visibleText(output);
521
- if (reply.trim() && (zeroTokens || looksLikeNotice(reply))) {
567
+ const leadingWarning = /^\s*[\u26A0\u2757\u26D4\uD83D\uDEAB]/u.test(reply);
568
+ if ((reported === undefined || zeroTokens || leadingWarning) && reply.trim() && (zeroTokens || looksLikeNotice(reply))) {
522
569
  output.content = [];
523
570
  throw noticeError(reply);
524
571
  }