pi-agy-acp 0.2.1 → 0.2.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/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.2.3](https://github.com/fdkevin0/pi-agy-acp/compare/v0.2.2...v0.2.3) (2026-11-23)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * **runtime:** skip warm-cache startup spawn, reap idle ACP fronts, and add /agy-acp refresh ([#44](https://github.com/fdkevin0/pi-agy-acp/issues/44)) ([b5b0952](https://github.com/fdkevin0/pi-agy-acp/commit/b5b09520a989bb3c79bafcbb243330304dfc1da1))
9
+
10
+ ## [0.2.2](https://github.com/fdkevin0/pi-agy-acp/compare/v0.2.1...v0.2.2) (2026-11-22)
11
+
12
+
13
+ ### Bug Fixes
14
+
15
+ * **host:** harden process lifecycle, OAuth/settings atomic writes, and JSON-RPC framing ([#40](https://github.com/fdkevin0/pi-agy-acp/issues/40)) ([c468085](https://github.com/fdkevin0/pi-agy-acp/commit/c4680859c9b407f6729382484c26dea2340423fe))
16
+ * **quota:** filter disabled buckets, suppress untouched rolling resets, and use monotonic TTL ([#38](https://github.com/fdkevin0/pi-agy-acp/issues/38)) ([707eb80](https://github.com/fdkevin0/pi-agy-acp/commit/707eb80bfec3505b1634ee51f1f55ab9b9636000))
17
+ * **runtime:** atomic MCP relay delivery, re-entry guard, and catalog/sweep hardening ([#42](https://github.com/fdkevin0/pi-agy-acp/issues/42)) ([4016234](https://github.com/fdkevin0/pi-agy-acp/commit/40162349b432746646ed4adfc0d084cac5f390dd))
18
+
3
19
  ## [0.2.1](https://github.com/fdkevin0/pi-agy-acp/compare/v0.2.0...v0.2.1) (2026-11-22)
4
20
 
5
21
 
package/README.md CHANGED
@@ -39,26 +39,30 @@ installation. See [development setup](docs/development.md) for local testing.
39
39
 
40
40
  ## Usage
41
41
 
42
- Start `pi`, then use `/model` to refresh and select a model under `antigravity-acp`.
43
- The available models and reasoning levels are discovered dynamically from your
44
- Antigravity account and cached locally in `catalog.json`.
42
+ Start `pi`, then use `/model` to select a model under `antigravity-acp` (or run
43
+ `/agy-acp refresh` to force a live catalog refresh). Available models and
44
+ reasoning levels are discovered dynamically from your Antigravity account and
45
+ cached locally in `catalog.json`.
45
46
 
46
47
  | Command | Purpose |
47
48
  | --- | --- |
48
49
  | `/agy-acp` or `/agy-acp status` | Show runtime state, account details, models, sessions, and the last turn. |
49
50
  | `/agy-acp quota [used\|remaining]` | Show account details, grouped quota bars, and reset countdowns (remembers the last selected mode). |
50
- | `/agy-acp reset` | Close ACP sessions; the next request rebuilds the connection. |
51
+ | `/agy-acp refresh` | Force a live model catalog refresh from `agy` without starting a conversation. |
52
+ | `/agy-acp reset` | Dispose the ACP runtime and clear sessions, quota cache, and warning history; the next request rebuilds from Pi's history. |
51
53
 
52
54
  After an Antigravity turn settles, the status bar shows quota usage (for example,
53
- `AGY 20%`, or `AGY 80%` in `remaining` mode) and warns when quota is low; see [quota status](docs/reference.md#quota-status-and-warnings).
55
+ `AGY 20%`, or `AGY 80%` in `remaining` mode) and warns when quota is low; see
56
+ [quota status](docs/reference.md#quota-status-and-warnings).
54
57
 
55
58
  Default prices are zero, not a promise of free calls. Pi pricing overrides are
56
59
  used when configured.
57
60
 
58
61
  ## More information
59
62
 
60
- - [Reference](docs/reference.md): commands, configuration, stored data, model discovery, and limitations.
61
- - [Development](docs/development.md): setup, request flow, source layout, and verification.
63
+ - [Reference](docs/reference.md): commands, quota UI, configuration, stored data, model discovery, and limits.
64
+ - [Development](docs/development.md): local setup, source layout, verification, and CI.
65
+ - [Architecture](docs/architecture.md): runtime, transport, security boundaries, and SQLite telemetry internals.
62
66
  - [Changelog](CHANGELOG.md): release history and upcoming changes.
63
67
  - [Attribution](NOTICE) and [MIT license](LICENSE).
64
68
 
@@ -0,0 +1,262 @@
1
+ # Architecture
2
+
3
+ Implementation invariants, transport boundaries, and subsystem contracts for
4
+ contributors working on `pi-agy-acp`. For setup and verification, start with
5
+ [development](development.md).
6
+
7
+ ## Request, history, and tool routing
8
+
9
+ ### ACP spawn and RPC timeouts
10
+
11
+ The runtime launches `agy` with:
12
+
13
+ ```text
14
+ agy acp --gemini-dir <PI_AGY_HOME> --app-data-dir agy --agent pi-bridge \
15
+ --process-per-session --disable-telemetry --log-file <PI_AGY_HOME>/acp.log
16
+ ```
17
+
18
+ Working directory is `<PI_AGY_HOME>/workspace`. ACP JSON-RPC timeouts:
19
+
20
+ | Method | Timeout |
21
+ | --- | --- |
22
+ | `initialize` | 120 s |
23
+ | `session/new` | 120 s |
24
+ | `session/set_config_option` | 60 s |
25
+ | `session/close` | 15 s |
26
+ | `session/prompt` | None (bounded by turn/abort lifecycle) |
27
+
28
+ ### Opening prompt and replay budget
29
+
30
+ - `session/new` attaches only a static MCP routing preamble
31
+ (`bridgeSystemPrompt()`). Live sessions register the local `pi` MCP server;
32
+ discovery (`warmup`) sessions pass `mcpServers: []`.
33
+ - Pi's system prompt (`<system_instructions>`), supplemental tool schemas
34
+ (`<harness_tool_instructions>`), and trailing live input are always emitted
35
+ complete. `<pi_history>` fills the remaining bytes of the 160,000-byte replay
36
+ budget (`REPLAY_BUDGET_BYTES`, kept under `agy`'s 192,000-byte single
37
+ `USER_INPUT` limit) newest-first.
38
+ - If the single newest history item is an oversized tool result and remaining
39
+ budget exceeds 1,024 bytes, it is head-truncated on UTF-8 code-point
40
+ boundaries. Historical images render as `[image]`; trailing user images and
41
+ live tool-result images pass through as native image blocks.
42
+
43
+ ### Tool schemas and dynamic deltas
44
+
45
+ - `tools/list` always includes `pi_await_result` and `pi_call_tool`.
46
+ - Tool schemas larger than `1,350` UTF-8 bytes (`MAX_EAGER_BRIDGE_TOOL_BYTES`,
47
+ below `agy`'s ~1,500-byte lazy threshold) are compacted in up to two passes
48
+ (shortening descriptions while preserving parameter names, types, `required`,
49
+ and `enum`), with full schemas emitted in `<harness_tool_instructions>`.
50
+ - Subsequent turns compare 24-hex SHA-256 tool digests and emit
51
+ `<harness_tool_update>` lines (restored, updated, added, disabled) prepended
52
+ to the prompt or attached to deferred tool-result suffixes. Newly added or
53
+ updated tools route through `pi_call_tool`.
54
+
55
+ ### Parked tool calls, continuations, and relay
56
+
57
+ - Parallel tool calls batch over `parkSettleMs` (250 ms). Resuming a parked
58
+ turn requires an intact history prefix plus matching model and clamped effort;
59
+ otherwise the session rebuilds cleanly.
60
+ - If `session/prompt` settles while Pi is running tools, delivering tool results
61
+ abandons the old turn, clears `reportedToolCalls`, and opens a continuation
62
+ prompt without executing zombie queued calls.
63
+ - Long-running tools time out into relay mode after `relayAfterMs` (85 s),
64
+ marking the call `waiting` and instructing the model to poll via
65
+ `pi_await_result`:
66
+ - While any relay is `waiting`, streamed text/thought chunks buffer up to
67
+ 65,536 chars (`MAX_RELAY_BUFFER_CHARS`).
68
+ - If the model moves on to a new tool call or another awaited result,
69
+ `waiting` relays become `unawaited`, buffered output flushes in order, and
70
+ the next delivered tool result carries deferred suffixes plus a one-time
71
+ `<harness_relay_update>` hint (`notified`).
72
+ - Completing (`end_turn`/`max_tokens`) while `waiting` fails with
73
+ `PROVIDER_ERROR`; completing with only `unawaited`/`notified` entries appends
74
+ an unretrieved-result note and finishes normally.
75
+ - `callDelivery` (`waiting` | `delivered`) guards against concurrent or
76
+ duplicate `pi_await_result` calls.
77
+ - The MCP bridge passes a synchronous `commit(finalize)` callback into
78
+ `handleCall` so `deliverCallResult()` mutates `callDelivery`, relay state,
79
+ and deferred suffixes only while the SSE stream is still writable and
80
+ unaborted.
81
+ - `max_tokens` auto-continues up to `longDecodeContinuations` (3) when not
82
+ relaying, resetting per-segment usage counters. Transient `agy` retry and
83
+ output-limit notices are suppressed and counted in `retryNotices`, while
84
+ terminal `Retries remaining: 0` passes through.
85
+
86
+ ## Model discovery and catalog caching
87
+
88
+ - Cold startup without `catalog.json` starts with an empty catalog and launches
89
+ no processes, sockets, or timers. `catalog.json` is written atomically and
90
+ stores models, per-model efforts, `supportsImage` (defaults optimistically to
91
+ `['text', 'image']` until `promptCapabilities.image === false` is observed),
92
+ `tier`, `contextWindows`, and the subprocess-free binary fingerprint
93
+ (`${realpath}:${dev}:${ino}:${size}:${mtimeNs}`).
94
+ - Both `agy --version` (30 s timeout) and ACP `initialize` (`agentInfo.version`)
95
+ enforce `MIN_AGY_VERSION` (`1.5.10`).
96
+ - Non-forced refreshes reuse `catalog.json` without spawning `agy` whenever
97
+ cached models match the current binary fingerprint. Loading a cache with a
98
+ mismatched fingerprint drops cached `contextWindows` while keeping models
99
+ visible until re-probed without advancing the persisted fingerprint.
100
+ - `reconcileBinaryFingerprint()` runs during `warmup()` and `runPreflight()`:
101
+ when an ACP front is idle with a stale binary fingerprint, it detaches the
102
+ stale process, closes the bridge, removes stale session artifacts, and marks
103
+ idle conversations dirty before probing the new binary. (If an ACP process is
104
+ already alive when `stream()` runs, `ensureReady()` reuses it without
105
+ re-checking the fingerprint until a refresh or process restart.)
106
+ - Concurrent refreshes share a single discovery session; `/agy-acp refresh`
107
+ (`force: true`) bypasses the cache. Standalone discovery tears down an
108
+ ephemeral front process, bridge, and sweeper afterward unless a concurrent
109
+ `stream()` adopted them. Provider re-registration is suppressed during refresh
110
+ so refresh cannot cancel itself.
111
+
112
+ ## Session and process lifecycle
113
+
114
+ - **Capacity and ephemeral sessions:** `capacityMutex` enforces
115
+ `maxLiveSessions` (16), evicting the oldest idle non-opening conversation
116
+ first and failing fast with `CAPACITY_EXCEEDED` (`RATE_LIMIT`) to avoid
117
+ parent/subagent deadlocks. Requests without a `sessionId` use ephemeral
118
+ `anon-*` keys torn down immediately after each idle step.
119
+ - **Idle sweeper:** Runs every 60 s (`.unref()`) with a monotonic delta capped
120
+ at 120 s per tick for sleep resilience. Idle conversations expire after
121
+ `idleSessionTtlMs` (30 min); once no live sessions or in-flight streams remain
122
+ and the front has been idle past `idleSessionTtlMs`, the sweeper stops the
123
+ ACP process, MCP bridge, and itself (waiting for evicted sessions to close
124
+ first).
125
+ - **Pi lifecycle resets:** Compaction, tree navigation, and `session_start`
126
+ (`new`, `resume`, `fork`) perform a light reset (closing conversation sessions
127
+ and artifacts while keeping the ACP process, bridge, and caches).
128
+ `session_shutdown` and `/agy-acp reset` dispose the full runtime.
129
+ - **Turn ownership and disposal:** Disposal is idempotent, drains in-flight
130
+ startup/bridge binding, cancels waiters, and rolls back late session replies
131
+ from obsolete processes or conversations. A turn owns cancellation through
132
+ streaming and parked execution until drained, `agent_settled` runs, or the
133
+ process exits (aborted/undrained turns wait up to 5 s for `promptSettled`);
134
+ only a fully drained `tool-calls` handoff preserves parked calls. First
135
+ interruption wins (`abandon` vs `fail`), and cancellation takes precedence
136
+ over buffered output.
137
+ - **Subprocess hardening (`src/host.ts`, `src/preflight.ts`):**
138
+ - Unix spawns `agy` in detached process groups (`-pid` `SIGTERM` → `SIGKILL`
139
+ after 5 s for ACP or 1 s for helper commands); Windows terminates process
140
+ trees via `taskkill /T /F /PID`. Helper commands wait up to 250 ms
141
+ (`EXIT_DRAIN_MS`) after exit to avoid hangs from inherited stdio handles.
142
+ - Subprocess environments strip `GEMINI_API_KEY`, `GOOGLE_API_KEY`,
143
+ `GEMINI_HOME`, `ELECTRON_RUN_AS_NODE`, and `CHROME_CRASHPAD_PIPE_NAME`, and
144
+ force `AGY_CLI_DISABLE_AUTO_UPDATE=1` and `PYTHONUNBUFFERED=1`.
145
+ - Binary auto-discovery checks `~/.local/bin/agy` and `PATH` on Unix, and
146
+ `%LOCALAPPDATA%\agy\bin\agy.exe`, `~/.local/bin/agy.exe`, then `PATH`
147
+ (`.exe` prioritized ahead of `PATHEXT` wrappers) on Windows.
148
+ - Captured stderr tails (capped at 64 KiB) redact Google OAuth URL queries,
149
+ `Bearer` tokens, `ya29.*`, `AIza*`, and secret query parameters.
150
+
151
+ ## Transport, MCP bridge, and permissions
152
+
153
+ ### MCP HTTP/SSE bridge (`src/mcp-bridge.ts`)
154
+
155
+ - Binds `127.0.0.1` on an ephemeral port with per-session bearer credentials
156
+ checked in constant time (`timingSafeEqual`).
157
+ - Enforces Node HTTP parser deadlines of 10 s for headers and 30 s for
158
+ whole-request reception (checked every 1 s); reception deadlines do not cap
159
+ completed SSE tool streams. SSE streams emit `: keepalive` (and optional
160
+ `notifications/progress`) every 15 s.
161
+ - Caps authenticated POST bodies at 8 MiB (`8,388,608` bytes) across both
162
+ `Content-Length` and chunked streams, closing the connection on rejection.
163
+ - Status behavior: `400` invalid URL (or JSON-RPC `-32700` parse error), `401`
164
+ missing/invalid tenant auth, `404` wrong path, `405` non-`POST`/`DELETE`,
165
+ `413` oversized body, `202` notifications-only, `200` JSON or
166
+ `text/event-stream`, `500` unexpected pre-header failure (or socket destroy if
167
+ headers were already sent). `close()` immediately destroys all open responses
168
+ and sockets without waiting on tool promises. Bridge listener errors route to
169
+ `host.log.info` (discarded in the Pi extension to protect TUI rendering).
170
+
171
+ ### JSON-RPC framing (`src/jsonrpc.ts`)
172
+
173
+ - Newline-delimited JSON-RPC 2.0 over UTF-8 stdio streams.
174
+ - Frames (or unterminated buffers) exceeding 16 MiB chars (`MAX_LINE_CHARS`)
175
+ close the peer with `JsonRpcClosedError`, triggering child termination.
176
+ - Partial remainders are re-materialized via UTF-16LE buffer copy to detach V8
177
+ `SlicedString` backing memory.
178
+ - Malformed/non-object lines are dropped via `onProtocolError` without closing
179
+ the link; malformed `message.error` objects reject the pending request with
180
+ `-32603`; unknown incoming agent requests return `-32601`.
181
+
182
+ ### Fail-closed permission policy
183
+
184
+ - Isolated `<PI_AGY_HOME>/agy/settings.json` sets
185
+ `toolPermission: 'request-review'` and `agentMode: ''`.
186
+ - `session/request_permission` is fail-closed: `cancelled` before `session/new`
187
+ completes (or on owner/tenant mismatch), and `reject_once` whenever no active
188
+ turn owns the session.
189
+ - Active-turn grants issue `allow_once` (never `allow_always`) only after
190
+ verifying non-conflicting structured tool metadata (`mcpServerName` /
191
+ `mcpToolName`, `_meta.*`, flat `name` — never `title` or `rawInput`) against
192
+ `reportedToolCalls`, `serverName === 'pi'`, and an advertised tool name (or
193
+ `pi_await_result`/`pi_call_tool`). A narrow exception allows an identity-less
194
+ `kind === 'other'` probe with empty input only after an MCP handshake on that
195
+ tenant.
196
+
197
+ ## Session SQLite telemetry and usage
198
+
199
+ ### Read-only SQLite inspection (`src/session-db.ts`)
200
+
201
+ - Uses `node:sqlite` (`DatabaseSync`, `readOnly: true`, `timeout: 50`).
202
+ - Validates `sessionId` (`[A-Za-z0-9._-]+`), verifies `realpath` containment
203
+ within `<PI_AGY_HOME>/agy/conversations`, and rejects symlinks or non-regular
204
+ files across `.db`, `.db-wal`, `.db-shm`, and `.db-journal`.
205
+ - Gates streaming reads with cached context window / positive `usage_update`
206
+ checks and `(mtimeNs, size)` stamps across `.db`, `.db-wal`, and
207
+ `.db-journal`. `gen_metadata` scans are bounded (`LIMIT 64`) and advance
208
+ `metaFloorIdx` on mid-session model switches so prior context windows cannot
209
+ bleed across models.
210
+ - On `end_turn` and `refusal`, inspects the newest terminal `steps` row
211
+ (`step_type = 17`, cross-checked against `step_type = 15` model reachability)
212
+ to surface hidden API errors while preserving pure safety refusals:
213
+ - `QUOTA_EXHAUSTED` → `QUOTA` (extracts reset timestamp/delay)
214
+ - Thinking signature validation errors (`thinking.signature: Field required`
215
+ or `Invalid \`signature\` in \`thinking\` block`) → `PROVIDER_ERROR` and
216
+ marks the session dirty for rebuild
217
+ - `429` / `RESOURCE_EXHAUSTED` → `RATE_LIMIT`
218
+ - `404` / `NOT_FOUND` → `SERVER` if the model was reached, else
219
+ `UNKNOWN_MODEL`
220
+ - Scoped artifact cleanup removes `conversations/<id>.db*`, `brain/<id>`, and
221
+ `annotations/<id>.pbtxt` without traversing symlinks.
222
+
223
+ ### Usage and `totalTokens` priority
224
+
225
+ `toTokenUsage()` emits usage only when `session/prompt` includes a `usage`
226
+ object. Cumulative buckets (`inputTokens`, `outputTokens`, `cacheReadTokens`,
227
+ `cacheWriteTokens`, `reasoningTokens`) sum across `max_tokens` continuations;
228
+ `totalTokens` resolves in priority order:
229
+
230
+ 1. Positive `usage_update.used` from the current continuation segment.
231
+ 2. Positive `estimated_tokens_used` from `gen_metadata` in the current segment.
232
+ 3. Final-segment average fallback:
233
+ `round((input + cacheRead + cacheWrite) / max(1, segmentCalls)) + round(output)`.
234
+
235
+ ## Quota reader and Pi stream contracts
236
+
237
+ - **Quota reader (`src/quota.ts`):** Runs `agy -p /usage --output-format json`
238
+ with closed `stdin`, a 1 MiB `stdout` cap, a 45 s timeout, and early abort if
239
+ `stderr` matches `Authentication required`. Uses a monotonic clock
240
+ (`performance.now()`) for its 2-minute TTL, filters `disabled === true`
241
+ buckets, and shares concurrent in-flight queries.
242
+ - **Account email scan (`src/quota.ts`):** Checks `cli.log` plus the newest 10
243
+ contained `log/cli-*.log` and `log/acp-server-*.log` files (newest-first,
244
+ realpath-deduplicated), reading the tail 64 KiB first and falling back to the
245
+ head 64 KiB when larger, cached for 10 s by path stat signatures.
246
+ - **Warning keys and UI freshness (`index.ts`):** UI generation checks discard
247
+ stale background results; `model_select` retargets an in-flight settled check
248
+ when switching between `antigravity-acp` models. Low-quota warning keys
249
+ include group, bucket ID, window label, reset time, and threshold (`20` or
250
+ `5`).
251
+ - **Pi stream hooks (`src/pi-stream.ts`):**
252
+ - `onPayload` can replace the request (strictly validated; invalid shapes
253
+ throw `INVALID_PAYLOAD`; `sessionId` and `signal` are always preserved;
254
+ omitted `tools` inherits original while `tools: []` disables tools).
255
+ - `onResponse` receives synthetic `{ status: 200, headers: {} }` once on the
256
+ first stream chunk (skipped on startup failure or an immediate aborted
257
+ finish), before `onProviderStreamEvent` and Pi event normalization.
258
+ - `CONTEXT_WINDOW_EXCEEDED` and `QUOTA` errors receive
259
+ `context_length_exceeded:` and `quota exceeded:` prefixes for Pi's
260
+ compaction and retry heuristics; transport timeouts remain distinct.
261
+ - `streamPi` drains the runtime generator in `finally` before emitting the
262
+ terminal Pi event.
@@ -1,9 +1,13 @@
1
1
  # Development
2
2
 
3
3
  Start with the [installation guide](../README.md#install) to use the extension.
4
- For settings and user-visible limits, see the [reference](reference.md).
4
+ For user-facing behavior and settings, see the [reference](reference.md). For
5
+ subsystem invariants, transport limits, and protocol details, see
6
+ [architecture](architecture.md).
5
7
 
6
- Clone the repository and install its dependencies:
8
+ ## Setup
9
+
10
+ Clone the repository and run the extension locally:
7
11
 
8
12
  ```sh
9
13
  git clone https://github.com/fdkevin0/pi-agy-acp.git
@@ -14,108 +18,38 @@ pi -e ./index.ts
14
18
 
15
19
  ## Request flow
16
20
 
17
- 1. The extension registers `antigravity-acp` with Pi. The first request starts
18
- `agy acp --process-per-session` and a loopback MCP bridge.
21
+ 1. `index.ts` registers the `antigravity-acp` provider and Pi lifecycle hooks.
22
+ The first live request starts `agy acp --process-per-session` and a loopback
23
+ MCP HTTP/SSE bridge.
19
24
  2. Session creation appends only a static MCP tool-routing preamble to `agy`'s
20
- system prompt; Pi's system prompt, compacted initial tool schemas, and any
21
- replayed history travel in the session's opening prompt within the 160 KB
22
- replay budget. Later turns on an intact history prefix reuse the session and
23
- send only new input (plus any dynamic tool deltas).
24
- 3. Model tool calls reach the bridge and remain pending while Pi executes them.
25
- Pi receives a `toolUse` result, then supplies tool results on its next request.
26
- 4. Those results resolve the pending MCP requests, allowing the same ACP turn to
27
- continue (or, if the ACP prompt already settled while Pi was running tools,
28
- starting a fresh continuation prompt with those results and any deferred
29
- suffixes without executing zombie queued calls). Long-running tools use a
30
- relay (`pi_await_result`) to keep the agent waiting; if the agent instead
31
- moves on to a new tool call or another awaited result, buffered output
32
- flushes in order so later steps stream live, deferred tool/steering suffixes
33
- and a one-time `<harness_relay_update>` hint carry onto the next delivered
34
- tool result, and `end_turn`/`max_tokens` finishes with a note if any relayed
35
- call remained unretrieved (while immediate premature completion with no
36
- further tool progress still fails with `PROVIDER_ERROR`).
37
- 5. The adapter drains the runtime's generator before publishing completion, so
38
- session cleanup finishes before Pi can start its next step.
39
-
40
- - **Model discovery:** Registration and cache-only refresh start no processes,
41
- sockets, or timers; before the first ACP discovery (`catalog.json` absent),
42
- the catalog starts empty with no hardcoded model list. `catalog.json` is
43
- written atomically and persists models, per-model efforts, `promptCapabilities.image`,
44
- tier, `contextWindows`, and a subprocess-free `agy` binary fingerprint
45
- (`realpath`, `dev`, `ino`, `size`, `mtimeNs`); a changed binary invalidates
46
- cached `contextWindows` and `observed` so the next refresh or session re-probes.
47
- The ACP `initialize` handshake also validates `agentInfo.version` against
48
- `MIN_AGY_VERSION`. Concurrent refreshes share a discovery session; after a live
49
- catalog is observed, later refreshes reuse it unless forced. Refresh suppresses
50
- provider re-registration so it cannot cancel itself. Cancellation ends the
51
- caller's wait; shared discovery still closes its session and cleans its files.
52
- - **Session lifecycle:** The bridge binds to `127.0.0.1`, uses per-session bearer
53
- credentials, and validates structured tool identity before granting permissions.
54
- On Unix, `agy acp` and helper commands run in detached process groups so
55
- termination and timeouts signal `-pid` (`SIGTERM`, then `SIGKILL`) without
56
- orphaning `--process-per-session` workers. Session SQLite reads reject
57
- symlinked or non-regular `.db`, `.db-wal`, and `.db-shm` files.
58
- Live `agy 1.5.10+` sessions issue `session/request_permission` only inside an
59
- active `session/prompt` turn (never during `session/new` or
60
- `session/set_config_option`), so session creation and idle pre-/post-turn
61
- windows remain fail-closed (`cancelled` before `session/new` completes;
62
- `reject_once` when no live turn owns the session, even after MCP handshake).
63
- Tree navigation and compaction close conversation sessions and their files,
64
- retaining the process, bridge, and caches. `session_start` (`new`, `resume`, or
65
- `fork`) uses the same light reset if the runtime survives; `session_shutdown`
66
- and `/agy-acp reset` dispose the runtime.
67
- Disposal is idempotent, drains in-flight startup and bridge binding, cancels
68
- waiters, and rolls back late session replies from obsolete processes or
69
- conversations. A turn owns cancellation through streaming and parked tool
70
- execution until its step drains, `agent_settled` runs, or the process exits;
71
- only a fully drained `tool-calls` handoff preserves parked tool calls.
72
- First interruption wins (`abandon` vs. `fail`), cancellation takes priority
73
- over buffered output, and turn/tenant identities guard all async callbacks.
74
- - **Quota and TUI:** Settled checks share the reader's TTL and in-flight request
75
- without blocking Pi. `/usage` commands close stdin, cap stdout at 1 MiB, and
76
- abort early if stderr matches `Authentication required`. Model selection reads
77
- memory only. UI generation checks discard stale background results; warning
78
- keys include group, bucket, reset time, and threshold. An explicit quota query
79
- can discover uncached account tiers through one tool-less ACP session per
80
- runtime, persisting the tier in `catalog.json`. Email lookup scans `cli.log`
81
- and the newest 10 contained `log/cli-*.log` and `log/acp-server-*.log` files
82
- (newest first, deduplicated), checking the tail 64 KiB first and falling back
83
- to the head 64 KiB when larger. Runtime warnings stay off stderr to preserve
84
- TUI rendering; diagnostics use status and agy's logs.
85
- - **Pi stream and error contracts:** `onPayload` can replace the request, and
86
- `onProviderStreamEvent` observes events before conversion. At the first stream
87
- event, `onResponse` receives synthetic status `200` and empty headers before
88
- normalization; startup failures and an initial aborted finish emit no response.
89
- ACP supplies no HTTP response metadata. Context overflow and exhausted quota
90
- receive `context_length_exceeded` and `quota exceeded` markers for Pi's
91
- compaction and retry decisions; transport timeouts remain distinct.
92
-
93
- ## MCP HTTP boundary
94
-
95
- The loopback bridge returns 400 for invalid URLs and 413 for authenticated POST
96
- bodies exceeding 1 MiB (1,048,576 bytes), including chunked uploads. Rejected
97
- oversized uploads close their connection after the error response. JSON parse
98
- errors retain the MCP parse-error response. Unexpected handler failures return
99
- 500 before headers or destroy an already-started response; listener errors go to
100
- the diagnostic sink.
101
-
102
- Node's HTTP parser enforces a 10-second header reception deadline and a 30-second
103
- whole-request reception deadline, checked every second. These are reception limits
104
- only and do not cap completed SSE tool streams. Shutdown stops accepting
105
- connections and destroys all tracked sockets without waiting for tool promises.
25
+ system prompt. Pi's system prompt, compacted tool schemas, and replayed
26
+ history travel in the opening prompt within the 160,000-byte replay budget;
27
+ subsequent turns on an intact history prefix reuse the session and send only
28
+ new input and tool deltas.
29
+ 3. Model tool calls pause at the MCP bridge while Pi executes them. Pi receives
30
+ a `toolUse` turn result and supplies tool results on its next request.
31
+ 4. Those tool results resolve pending MCP requests so the same ACP turn
32
+ continues (or start a continuation prompt if ACP settled early). Long-running
33
+ tools relay via `pi_await_result` to keep the agent waiting cleanly.
34
+ 5. `src/pi-stream.ts` drains the runtime generator before publishing completion
35
+ so turn cleanup finishes before Pi starts the next step.
36
+
37
+ See [architecture](architecture.md) for the full lifecycle, relay, permission,
38
+ SQLite telemetry, and transport boundary invariants.
106
39
 
107
40
  ## Source layout
108
41
 
109
42
  | File or group | Responsibility |
110
43
  | --- | --- |
111
- | `index.ts` | Provider registration, commands, and Pi lifecycle hooks. |
112
- | `src/pi-stream.ts`, `src/protocol.ts` | Pi message conversion and bridge event contracts. |
113
- | `src/runtime.ts`, `src/conversation.ts`, `src/history.ts` | Session orchestration, pending calls, tool identity metadata, streaming, and history replay. |
114
- | `src/acp-process.ts`, `src/jsonrpc.ts`, `src/mcp-bridge.ts` | ACP transport, local MCP server, tool schema compression, and tool deltas. |
115
- | `src/host.ts`, `src/preflight.ts`, `src/config.ts` | Process execution, executable discovery, and isolated home setup. |
116
- | `src/catalog.ts`, `src/quota.ts`, `src/format.ts`, `src/util.ts` | Model catalog, quota queries, TUI notice formatting, and shared utilities. |
117
- | `src/version.ts` | ACP/MCP version read from `package.json`. |
118
- | `tests/` | Scripted agy fixture, runtime tests, and Pi integration tests. |
44
+ | `index.ts` | Provider registration, `/agy-acp` commands, TUI loaders/warnings, and Pi lifecycle hooks. |
45
+ | `src/pi-stream.ts`, `src/protocol.ts` | Pi message/stream conversion, hook contracts, and internal bridge event types. |
46
+ | `src/runtime.ts`, `src/conversation.ts`, `src/history.ts` | Session orchestration, capacity/sweeper lifecycle, pending/relayed tool calls, usage accounting, and history replay. |
47
+ | `src/acp-process.ts`, `src/jsonrpc.ts`, `src/mcp-bridge.ts` | ACP stdio transport, NDJSON JSON-RPC peer, loopback MCP HTTP/SSE bridge, schema compression, and tool deltas. |
48
+ | `src/config.ts` | Default runtime thresholds, effort/display types, and atomic `settings.json` persistence. |
49
+ | `src/host.ts`, `src/preflight.ts`, `src/session-db.ts` | Subprocess management and env/stderr hardening, binary discovery/fingerprinting/OAuth sync, and read-only session SQLite telemetry/error inspection and artifact cleanup. |
50
+ | `src/catalog.ts`, `src/quota.ts`, `src/format.ts`, `src/util.ts` | Model catalog persistence, `/usage` quota reader and login-log email lookup, TUI notice formatting and model-to-group matching, and shared utilities. |
51
+ | `src/version.ts` | Package version read from `package.json` for ACP/MCP handshakes. |
52
+ | `tests/` | Scripted local `agy` fixture (`fake-agy.mjs`), unit tests, and Pi integration tests. |
119
53
 
120
54
  Upstream provenance and licensing are recorded in [NOTICE](../NOTICE) and
121
55
  [LICENSE](../LICENSE).
@@ -128,72 +62,50 @@ npm test
128
62
  pi --no-extensions -e ./index.ts --list-models antigravity-acp
129
63
  ```
130
64
 
131
- Tests run directly with Node's native TypeScript support; `tsx` is not required.
132
- Automated tests use a scripted local `agy` substitute so `npm test` runs offline
133
- without consuming account quota. They need permission to listen on `127.0.0.1`.
65
+ Tests run directly with Node's native TypeScript support (`tsx` is not
66
+ required) using a scripted local `agy` substitute so `npm test` runs offline
67
+ without consuming account quota. Tests bind ephemeral loopback sockets on
68
+ `127.0.0.1`.
134
69
 
135
- Tests cover ACP transport and sessions, tool routing and permissions, model and
136
- account discovery, Pi streaming and cancellation, and quota UI behavior.
137
- Listing models verifies extension loading, not access to the real service.
70
+ Automated tests cover ACP transport and sessions, JSON-RPC framing, MCP bridge
71
+ boundaries and permissions, model/account discovery, session SQLite inspection,
72
+ Pi streaming and cancellation, and quota UI behavior. `--list-models` verifies
73
+ extension loading, not live service access.
138
74
 
139
- To inspect the package contents without publishing:
75
+ Inspect package contents before publishing:
140
76
 
141
77
  ```sh
142
78
  npm pack --dry-run
143
79
  ```
144
80
 
145
- ## CI and releases
146
-
147
- `ci.yml` checks pull requests and pushes to `main`. `release.yml` runs on pushes
148
- to `main` (to run `release-please`), version-tag pushes, or manual runs on an
149
- existing tag, so ordinary commits do not trigger the `publish` job. CI tests the
150
- pinned `devDependencies` baseline on Node.js 22.19.0 and 24, plus a `pi-compat`
151
- matrix across `@earendil-works/pi-*` `1.5.0` and latest `1.5`; releases use
152
- Node.js 24. `.npmrc` sets `package-lock=false` so dependency installation stays
153
- lockfile-free via `npm install`.
154
-
155
- All changes to `main` require a pull request, passing CI on both Node versions,
156
- and resolved review discussions. Squash merge after CI passes; no second-person
157
- approval is required.
158
-
159
- Releases are automated with `release-please` (`release-please-config.json` and
160
- `.release-please-manifest.json`):
161
- - Merging Conventional Commits (`feat:`, `fix:`, etc.) to `main` opens or updates
162
- a release PR that bumps `package.json` and updates `CHANGELOG.md` and
163
- `.release-please-manifest.json`.
164
- - Squash-merging that release PR (preserving its `chore(main): release X.Y.Z`
165
- title) creates the `vX.Y.Z` tag and GitHub Release, then triggers the
166
- `publish` job in `release.yml` to check, test, pack, and publish to npm.
167
- - Enable **Allow GitHub Actions to create and approve pull requests** in
168
- repository Settings → Actions → General. Without a `RELEASE_PLEASE_TOKEN` PAT
169
- (with `contents: write` and `pull-requests: write`) in repository secrets,
170
- `GITHUB_TOKEN` is used; in that case, close and reopen the release PR after
171
- its final update to trigger `ci.yml` when branch protection requires it.
172
- - To recover a failed `publish` job, choose **Re-run failed jobs** on that
173
- workflow run (re-running all jobs on a `main` run skips `publish` once the tag
174
- exists) or run `gh workflow run release.yml --ref vX.Y.Z`. Manual tag pushes
175
- (`vX.Y.Z`) also trigger `publish` but bypass `release-please`, leaving
176
- `CHANGELOG.md` and `.release-please-manifest.json` out of sync.
177
- - The workflow accepts stable versions only, publishes one version at a time,
178
- and never moves a published tag. Only a registry 404 means the version is
179
- absent; network, authentication, and server errors stop the job.
180
-
181
- Configure npm [Trusted Publishing](https://docs.npmjs.com/trusted-publishers/)
182
- for owner `fdkevin0`, repository `pi-agy-acp`, and workflow filename `release.yml`.
183
- The workflow grants OIDC permission to the publish job and uses npm >= 11.5.1.
184
- An optional `NPM_TOKEN` repository secret supports token authentication through
185
- `NODE_AUTH_TOKEN`; use a granular write token with the required 2FA bypass.
186
-
187
- If npm publication succeeds but GitHub Release creation fails, rerun that tagged
188
- workflow, or use `gh workflow run release.yml --ref vX.Y.Z`. Branch-based manual
189
- runs are rejected. Existing npm versions are not republished, and GitHub Releases
190
- are created only for existing tags with `gh release create --verify-tag`.
81
+ ## CI and pull requests
82
+
83
+ - `ci.yml` runs on pull requests and pushes to `main`. It validates the pinned
84
+ `devDependencies` baseline (`1.5.2`) on Node.js 22.19.0 and 24, plus a
85
+ `pi-compat` matrix across `@earendil-works/pi-*` `1.5.0` and latest `1.5` on
86
+ Node.js 24.
87
+ - Host `peerDependencies` stay `*` per Pi package conventions. `.npmrc` sets
88
+ `package-lock=false` so installs remain lockfile-free via `npm install`.
89
+ - All changes to `main` require a pull request, passing CI across the matrix,
90
+ and resolved review discussions, then squash merge (no second-person approval
91
+ is required).
92
+
93
+ For automated releases, npm Trusted Publishing, and recovery procedures, see
94
+ [releasing](releasing.md).
191
95
 
192
96
  ## Documentation conventions
193
97
 
194
- Keep all project documentation in English. Use progressive disclosure:
98
+ Keep all project documentation in English and organize by progressive
99
+ disclosure:
100
+
101
+ - `README.md`: first successful run, commands overview, and essential limits.
102
+ - `docs/reference.md`: user- and operator-facing behavior, configuration, and
103
+ compatibility limits.
104
+ - `docs/development.md`: contributor setup, source layout, verification, and CI.
105
+ - `docs/architecture.md`: subsystem invariants, protocol contracts, and
106
+ security boundaries.
107
+ - `docs/releasing.md`: maintainer release automation and publishing recovery.
195
108
 
196
- - Keep the README focused on the first successful run and essential limitations.
197
- - Put operational details in the reference and implementation details in this guide.
198
- - Link to the relevant section instead of duplicating detailed explanations.
199
- - Include linked documentation in the package's `files` list.
109
+ Link to the owning document instead of duplicating details, and keep all linked
110
+ documentation covered by `package.json`'s `files` list (`docs/` is included as
111
+ a directory).