pi-agy-acp 0.2.2 → 0.2.4

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