pi-agy-acp 0.2.0 → 0.2.2

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,31 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.2.2](https://github.com/fdkevin0/pi-agy-acp/compare/v0.2.1...v0.2.2) (2026-11-22)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * **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))
9
+ * **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))
10
+ * **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))
11
+
12
+ ## [0.2.1](https://github.com/fdkevin0/pi-agy-acp/compare/v0.2.0...v0.2.1) (2026-11-22)
13
+
14
+
15
+ ### Features
16
+
17
+ * sync agy 1.5.10+ features, dynamic catalog, and process hardening ([#34](https://github.com/fdkevin0/pi-agy-acp/issues/34)) ([44d2d36](https://github.com/fdkevin0/pi-agy-acp/commit/44d2d3690f927adacda8c37ae281714992736844)), closes [#28](https://github.com/fdkevin0/pi-agy-acp/issues/28) [#31](https://github.com/fdkevin0/pi-agy-acp/issues/31) [#32](https://github.com/fdkevin0/pi-agy-acp/issues/32)
18
+
19
+
20
+ ### Bug Fixes
21
+
22
+ * encapsulate turn prompt liveness and relay lifecycle ([#33](https://github.com/fdkevin0/pi-agy-acp/issues/33)) ([#36](https://github.com/fdkevin0/pi-agy-acp/issues/36)) ([f661d8d](https://github.com/fdkevin0/pi-agy-acp/commit/f661d8d49564a83aada3617936e564f9b352eb44))
23
+
24
+
25
+ ### Miscellaneous Chores
26
+
27
+ * **release:** prepare 0.2.1 ([#37](https://github.com/fdkevin0/pi-agy-acp/issues/37)) ([5ca8a16](https://github.com/fdkevin0/pi-agy-acp/commit/5ca8a164e0b40e4040401ff7455cb34c54d0b9c9))
28
+
3
29
  ## [0.2.0](https://github.com/fdkevin0/pi-agy-acp/compare/v0.1.4...v0.2.0) (2026-11-17)
4
30
 
5
31
 
package/README.md CHANGED
@@ -12,7 +12,7 @@ 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.4.12, signed in with your Google account.
15
+ - The official `agy` CLI >= 1.5.10, signed in with your Google account.
16
16
  Run `agy` in your terminal to complete sign-in before using the extension.
17
17
 
18
18
  ## Install
@@ -39,10 +39,9 @@ installation. See [development setup](docs/development.md) for local testing.
39
39
 
40
40
  ## Usage
41
41
 
42
- Start `pi`, then use `/model` to select a model under `antigravity-acp`.
43
- Examples include `gemini-4-argon`, `gemini-3.8-flash`, `claude-opus-5-5`,
44
- `claude-sonnet-5-5`, and `gpt-oss-120b-medium`. The available list refreshes
45
- automatically from your account.
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`.
46
45
 
47
46
  | Command | Purpose |
48
47
  | --- | --- |
@@ -24,18 +24,46 @@ pi -e ./index.ts
24
24
  3. Model tool calls reach the bridge and remain pending while Pi executes them.
25
25
  Pi receives a `toolUse` result, then supplies tool results on its next request.
26
26
  4. Those results resolve the pending MCP requests, allowing the same ACP turn to
27
- continue. Long-running tools use a relay to keep the agent waiting.
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`).
28
37
  5. The adapter drains the runtime's generator before publishing completion, so
29
38
  session cleanup finishes before Pi can start its next step.
30
39
 
31
40
  - **Model discovery:** Registration and cache-only refresh start no processes,
32
- sockets, or timers. Concurrent refreshes share a discovery session; after a live
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
33
49
  catalog is observed, later refreshes reuse it unless forced. Refresh suppresses
34
50
  provider re-registration so it cannot cancel itself. Cancellation ends the
35
51
  caller's wait; shared discovery still closes its session and cleans its files.
36
52
  - **Session lifecycle:** The bridge binds to `127.0.0.1`, uses per-session bearer
37
53
  credentials, and validates structured tool identity before granting permissions.
38
- Live `agy 1.5.9` sessions issue `session/request_permission` only inside an
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
39
67
  active `session/prompt` turn (never during `session/new` or
40
68
  `session/set_config_option`), so session creation and idle pre-/post-turn
41
69
  windows remain fail-closed (`cancelled` before `session/new` completes;
@@ -52,13 +80,17 @@ pi -e ./index.ts
52
80
  First interruption wins (`abandon` vs. `fail`), cancellation takes priority
53
81
  over buffered output, and turn/tenant identities guard all async callbacks.
54
82
  - **Quota and TUI:** Settled checks share the reader's TTL and in-flight request
55
- without blocking Pi. Model selection reads memory only. UI generation checks
56
- discard stale background results; warning keys include group, bucket, reset
57
- time, and threshold. An explicit quota query can discover uncached account tiers through
58
- one tool-less ACP session per runtime, persisting the tier in `catalog.json`.
59
- Email lookup reads at most the last 64 KiB of each candidate login log and uses
60
- the last match in the first matching file. Runtime warnings stay off stderr to
61
- preserve TUI rendering; diagnostics use status and agy's logs.
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.
62
94
  - **Pi stream and error contracts:** `onPayload` can replace the request, and
63
95
  `onProviderStreamEvent` observes events before conversion. At the first stream
64
96
  event, `onResponse` receives synthetic status `200` and empty headers before
@@ -70,7 +102,7 @@ pi -e ./index.ts
70
102
  ## MCP HTTP boundary
71
103
 
72
104
  The loopback bridge returns 400 for invalid URLs and 413 for authenticated POST
73
- bodies exceeding 1 MiB (1,048,576 bytes), including chunked uploads. Rejected
105
+ bodies exceeding 8 MiB (8,388,608 bytes), including chunked uploads. Rejected
74
106
  oversized uploads close their connection after the error response. JSON parse
75
107
  errors retain the MCP parse-error response. Unexpected handler failures return
76
108
  500 before headers or destroy an already-started response; listener errors go to
@@ -89,7 +121,7 @@ connections and destroys all tracked sockets without waiting for tool promises.
89
121
  | `src/pi-stream.ts`, `src/protocol.ts` | Pi message conversion and bridge event contracts. |
90
122
  | `src/runtime.ts`, `src/conversation.ts`, `src/history.ts` | Session orchestration, pending calls, tool identity metadata, streaming, and history replay. |
91
123
  | `src/acp-process.ts`, `src/jsonrpc.ts`, `src/mcp-bridge.ts` | ACP transport, local MCP server, tool schema compression, and tool deltas. |
92
- | `src/host.ts`, `src/preflight.ts`, `src/config.ts` | Process execution, executable discovery, and isolated home setup. |
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. |
93
125
  | `src/catalog.ts`, `src/quota.ts`, `src/format.ts`, `src/util.ts` | Model catalog, quota queries, TUI notice formatting, and shared utilities. |
94
126
  | `src/version.ts` | ACP/MCP version read from `package.json`. |
95
127
  | `tests/` | Scripted agy fixture, runtime tests, and Pi integration tests. |
package/docs/reference.md CHANGED
@@ -36,9 +36,11 @@ will not appear after cancellation. Non-TUI modes query directly without a loade
36
36
 
37
37
  Quota is read through `agy -p /usage --output-format json`. Each model group has
38
38
  one row per quota window, with a 12-cell bar, a rounded percentage, and a relative
39
- reset time. By default (`used` mode), bars and percentages count up from `0%`; pass
40
- `remaining` (`/agy-acp quota remaining`) to count down from `100%`. The last
41
- selected mode is saved in `settings.json` inside `PI_AGY_HOME`. For example:
39
+ reset time (omitted for untouched rolling windows at `0%` used / `100%` remaining
40
+ whose reset time is still a full window away). By default (`used` mode), bars and
41
+ percentages count up from `0%`; pass `remaining` (`/agy-acp quota remaining`) to
42
+ count down from `100%`. The last selected mode is saved in `settings.json` inside
43
+ `PI_AGY_HOME`. For example:
42
44
 
43
45
  ```text
44
46
  Antigravity Quota
@@ -46,7 +48,7 @@ Antigravity Quota
46
48
 
47
49
  Gemini Models
48
50
  Gemini Flash, Gemini Pro
49
- 5h [░░░░░░░░░░░░] 0% · resets in 4h 59m
51
+ 5h [░░░░░░░░░░░░] 0%
50
52
  weekly [█░░░░░░░░░░░] 9% · resets in 6d 7h
51
53
  ```
52
54
 
@@ -71,8 +73,11 @@ it. This may start ACP but sends no model prompt; failure does not prevent quota
71
73
  from appearing. Use `/agy-acp reset` to retry discovery. Viewing status never starts it.
72
74
 
73
75
  The email comes from login logs. With the default home only, the extension also
74
- checks `~/.gemini/antigravity-cli/cli.log` if needed; a custom `PI_AGY_HOME` stays
75
- isolated. Cached plans and login logs can be stale after an account change.
76
+ checks `ANTIGRAVITY_CLI_HOME`, `AGY_HOME`, and `~/.gemini/antigravity-cli`
77
+ (`cli.log` plus the newest 10 `log/cli-*.log` and `log/acp-server-*.log` files,
78
+ scanning each log's tail 64 KiB and falling back to its head 64 KiB when larger);
79
+ a custom `PI_AGY_HOME` stays isolated. Cached plans and login logs can be stale
80
+ after an account change.
76
81
 
77
82
  ### Quota status and warnings
78
83
 
@@ -106,6 +111,7 @@ Set these environment variables before starting Pi:
106
111
  | `PI_AGY_COMMAND` | Absolute path to the `agy` executable. | Automatic discovery. |
107
112
  | `PI_AGY_HOME` | Dedicated directory for this extension's agy state. | `~/.pi/agent/cache/antigravity-acp` |
108
113
  | `PI_AGY_QUOTA_DISPLAY` | Startup quota display mode (`used` or `remaining`), overriding `settings.json` for startup. Invalid values are ignored; `/agy-acp quota <mode>` overrides it for the active session. | `settings.json`, then `used` |
114
+ | `PI_AGY_DEBUG` | Set to `1` to emit runtime warnings on `stderr` (silent by default to protect the TUI). | Unset (silent) |
109
115
 
110
116
  For example:
111
117
 
@@ -124,32 +130,33 @@ are retained; sessions rebuild from Pi's history. Cleanup is best-effort if file
124
130
  for each concurrently running Pi instance, since startup cleanup assumes exclusive
125
131
  use of the directory.
126
132
 
127
- With file-backed authentication, the extension copies the existing OAuth token
128
- from your normal agy directory and sets its permissions to `0600`. Do not commit
129
- or share this directory. Authentication and token refresh remain agy's responsibility.
133
+ With file-backed authentication and the default `PI_AGY_HOME`, the extension
134
+ atomically syncs the existing OAuth token from your normal agy directory
135
+ (`ANTIGRAVITY_CLI_HOME`, `AGY_HOME`, or `~/.gemini/antigravity-cli`) with `0600`
136
+ permissions while refusing symlinked paths. A custom `PI_AGY_HOME` stays
137
+ isolated and does not copy tokens from default agy directories. Note that quota
138
+ queries (`agy -p /usage`) always query the global `agy` CLI account because
139
+ `agy` does not accept `--gemini-dir` on `/usage`. Do not commit or share this
140
+ directory. Authentication and token refresh remain agy's responsibility.
130
141
 
131
142
  ## Models and context
132
143
 
133
- Loading the extension uses the cached catalog, or five fallback model families,
134
- without starting agy. Model refresh or the first request updates available models
135
- and reasoning levels from ACP. A forced refresh queries again; refreshes can be
136
- cancelled. The selector exposes only the reasoning levels offered for each model.
137
- Direct requests map `minimal` to `low` and `xhigh` or `max` to `high`; `off` uses
138
- the runtime default.
139
-
140
- The fallback families are:
141
-
142
- - `gemini-4-argon`
143
- - `gemini-3.8-flash`
144
- - `claude-opus-5-5`
145
- - `claude-sonnet-5-5`
146
- - `gpt-oss-120b-medium`
147
-
148
- These entries are defaults, not a guarantee of account access. Model context windows
149
- start at `0` until learned dynamically from the server-issued `max_context_tokens`
150
- metadata in the session database and cached per model in `catalog.json`. The history
151
- replay budget is 160,000 bytes; older history can be omitted to fit, and historical
152
- images become text placeholders.
144
+ Loading the extension restores the cached catalog from `catalog.json` (or starts
145
+ empty on a fresh install) without starting agy. Model refresh (such as opening
146
+ `/model`) or the first request discovers available models, reasoning levels
147
+ (including grouped select options and `-effort` suffix variants), and image input
148
+ capability (`promptCapabilities.image`) dynamically from ACP. A forced refresh
149
+ queries again; refreshes can be cancelled. The selector exposes only the
150
+ reasoning levels offered for each model (`low`, `medium`, `high`, `xhigh`, `max`).
151
+ Direct requests map `minimal` to `low` and forward `xhigh` and `max` (clamping to
152
+ the nearest effort offered by that model); `off` uses the runtime default.
153
+
154
+ Model context windows start at `0` until learned dynamically from the
155
+ server-issued `max_context_tokens` metadata in the session database and cached
156
+ per model in `catalog.json` alongside the `agy` binary fingerprint; updating the
157
+ `agy` binary invalidates cached context windows and triggers re-discovery on the
158
+ next refresh or session. The history replay budget is 160,000 bytes; older
159
+ history can be omitted to fit, and historical images become text placeholders.
153
160
 
154
161
  ## Usage and costs
155
162
 
@@ -157,7 +164,8 @@ Usage comes from the ACP session rather than per-step API headers. Parked `toolU
157
164
  steps emit zero usage; statistics arrive on the final step when the full ACP turn
158
165
  finishes (accumulated across any automatic `max_tokens` continuations). `max_context_tokens`
159
166
  recorded in the session SQLite metadata supplies the model's context window, while
160
- `usage_update` supplies live token occupancy.
167
+ `usage_update` (and same-turn `estimated_tokens_used` metadata when `usage_update`
168
+ is absent) supplies live token occupancy.
161
169
 
162
170
  The extension separates cumulative token consumption from final-call context
163
171
  occupancy:
@@ -167,10 +175,11 @@ occupancy:
167
175
  overrides reflect full multi-step consumption.
168
176
  - `totalTokens` (which feeds Pi's context meter and auto-compaction threshold via
169
177
  `calculateContextTokens`) uses the final model call's live `usage_update.used`
170
- count when `agy` provides it. When `usage_update` is absent, it falls back to
171
- averaging the final `session/prompt` segment's prompt tokens across that
172
- segment's model calls plus final-segment output tokens; this fallback is an
173
- estimate rather than an exact per-step measurement.
178
+ count when `agy` provides it. When `usage_update` is absent, it prefers the
179
+ same turn's `estimated_tokens_used` from `gen_metadata`, and otherwise falls
180
+ back to averaging the final `session/prompt` segment's prompt tokens across
181
+ that segment's model calls plus final-segment output tokens; this fallback is
182
+ an estimate rather than an exact per-step measurement.
174
183
 
175
184
  Default model prices are zero because pricing is unavailable. If you configure
176
185
  Pi model pricing overrides, flat per-million rates price the cumulative turn
@@ -184,7 +193,8 @@ scripts.
184
193
 
185
194
  ## Compatibility limits
186
195
 
187
- This version targets the `@earendil-works/*` Pi packages at version 1.5.x.
196
+ This version requires `agy` CLI >= 1.5.10 and targets the `@earendil-works/*`
197
+ Pi packages at version 1.5.x.
188
198
  Host `peerDependencies` use `*` as required by Pi package conventions;
189
199
  `devDependencies` pin a reproducible CI baseline (`1.5.2`), and CI validates
190
200
  both that baseline (on Node.js 22.19.0 and 24) and the `1.5.x` host range
package/index.ts CHANGED
@@ -26,9 +26,10 @@ import type { QuotaSnapshot } from './src/quota.ts'
26
26
 
27
27
  export default function (
28
28
  pi: ExtensionAPI,
29
- host: Partial<Pick<RuntimeHost, 'runCommand'>> = {},
29
+ host: Partial<Pick<RuntimeHost, 'runCommand' | 'spawnAcp' | 'quotaNow'>> = {},
30
30
  ) {
31
31
  const envQuotaDisplay = asQuotaDisplay(process.env.PI_AGY_QUOTA_DISPLAY)
32
+ const debug = process.env.PI_AGY_DEBUG === '1'
32
33
  const config = {
33
34
  ...defaults,
34
35
  command: process.env.PI_AGY_COMMAND || '',
@@ -38,9 +39,17 @@ export default function (
38
39
  const createRuntime = () =>
39
40
  new AntigravityRuntime({
40
41
  config,
41
- spawnAcp,
42
+ spawnAcp: host.spawnAcp ?? spawnAcp,
42
43
  runCommand: host.runCommand ?? runCommand,
43
- log: { info: () => {}, warn: () => {} },
44
+ quotaNow: host.quotaNow,
45
+ log: {
46
+ info: () => {},
47
+ warn: debug
48
+ ? (message) => {
49
+ process.stderr.write(`[pi-agy-acp] ${message}\n`)
50
+ }
51
+ : () => {},
52
+ },
44
53
  onModelsChanged: () => {
45
54
  if (refreshDepth === 0) register()
46
55
  },
@@ -51,13 +60,14 @@ export default function (
51
60
  envQuotaDisplay ??
52
61
  readQuotaDisplayPreference(home) ??
53
62
  DEFAULT_QUOTA_DISPLAY
54
- const models = (): ProviderModelConfig[] =>
55
- runtime.catalog.list().map((m) => {
63
+ const models = (): ProviderModelConfig[] => {
64
+ const input = runtime.catalog.inputModalities()
65
+ return runtime.catalog.list().map((m) => {
56
66
  const efforts = runtime.catalog.effortsFor(m.id)
57
67
  return {
58
68
  id: m.id,
59
69
  name: m.name,
60
- input: ['text', 'image'],
70
+ input,
61
71
  reasoning: efforts.length > 0,
62
72
  thinkingLevelMap:
63
73
  efforts.length > 0
@@ -67,8 +77,8 @@ export default function (
67
77
  low: efforts.includes('low') ? 'low' : null,
68
78
  medium: efforts.includes('medium') ? 'medium' : null,
69
79
  high: efforts.includes('high') ? 'high' : null,
70
- xhigh: null,
71
- max: null,
80
+ xhigh: efforts.includes('xhigh') ? 'xhigh' : null,
81
+ max: efforts.includes('max') ? 'max' : null,
72
82
  }
73
83
  : undefined,
74
84
  cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
@@ -76,6 +86,7 @@ export default function (
76
86
  maxTokens: 65536,
77
87
  }
78
88
  })
89
+ }
79
90
  const register = () =>
80
91
  pi.registerProvider(config.provider, {
81
92
  name: config.displayName,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-agy-acp",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "description": "Google Antigravity ACP provider extension for Pi Coding Agent",
@@ -60,6 +60,20 @@ export interface AcpToolCallMeta {
60
60
  [key: string]: unknown
61
61
  }
62
62
 
63
+ /** One selectable option entry inside an ACP select config option. */
64
+ export interface AcpConfigOptionValue {
65
+ value: string
66
+ name?: string
67
+ description?: string
68
+ }
69
+
70
+ /** One grouped list of selectable option entries inside an ACP select config option. */
71
+ export interface AcpConfigOptionGroup {
72
+ group: string
73
+ name?: string
74
+ options: AcpConfigOptionValue[]
75
+ }
76
+
63
77
  /** One select-type session configuration option. */
64
78
  export interface AcpConfigOption {
65
79
  id: string
@@ -67,7 +81,23 @@ export interface AcpConfigOption {
67
81
  category?: string
68
82
  type?: string
69
83
  currentValue?: string
70
- options?: { value: string; name?: string; description?: string }[]
84
+ options?: (AcpConfigOptionValue | AcpConfigOptionGroup)[]
85
+ }
86
+
87
+ /** `initialize` result. */
88
+ export interface AcpInitializeResult {
89
+ protocolVersion?: number
90
+ agentInfo?: {
91
+ name?: string
92
+ version?: string
93
+ }
94
+ agentCapabilities?: {
95
+ promptCapabilities?: {
96
+ image?: boolean
97
+ audio?: boolean
98
+ embeddedContext?: boolean
99
+ }
100
+ }
71
101
  }
72
102
 
73
103
  /** `session/request_permission` parameters. */
@@ -137,6 +167,8 @@ export class AcpProcess {
137
167
  private readonly listeners = new Map<string, AcpSessionListener>()
138
168
  private child: AcpChild | undefined
139
169
  private peer: JsonRpcPeer | undefined
170
+ private childExited = false
171
+ private childTerminated = false
140
172
  private exitError: Error | undefined
141
173
  private readonly exitListeners = new Set<(error: Error) => void>()
142
174
  private readonly options: AcpProcessOptions
@@ -169,18 +201,24 @@ export class AcpProcess {
169
201
  * Spawn the process and complete the ACP `initialize` handshake.
170
202
  * @param timeoutMs - handshake deadline.
171
203
  */
172
- async start(timeoutMs: number): Promise<void> {
204
+ async start(timeoutMs: number): Promise<AcpInitializeResult | undefined> {
173
205
  const child = this.options.spawn(this.options.argv, this.options.cwd)
174
206
  this.child = child
207
+ this.childExited = false
208
+ this.childTerminated = false
175
209
  const peer = new JsonRpcPeer(child.stdout, child.stdin, {
176
210
  onRequest: (method, params) => this.onRequest(method, params),
177
211
  onNotification: (method, params) => this.onNotification(method, params),
178
- onClose: (error) => this.fail(error),
212
+ onClose: (error) => {
213
+ if (!this.childExited) this.terminateChild()
214
+ this.fail(error)
215
+ },
179
216
  onProtocolError: (detail) =>
180
217
  this.options.log?.(`acp: dropped frame: ${detail}`),
181
218
  })
182
219
  this.peer = peer
183
220
  void child.exited.then(({ code, signal }) => {
221
+ this.childExited = true
184
222
  const tail = child.stderrTail().trim().split('\n').slice(-5).join(' | ')
185
223
  const error = new Error(
186
224
  `agy acp exited (code=${code ?? 'null'} signal=${signal ?? 'null'})${tail ? `: ${tail}` : ''}`,
@@ -188,7 +226,7 @@ export class AcpProcess {
188
226
  peer.close(error)
189
227
  this.fail(error)
190
228
  })
191
- await peer.request(
229
+ return peer.request<AcpInitializeResult | undefined>(
192
230
  'initialize',
193
231
  {
194
232
  protocolVersion: 1,
@@ -207,6 +245,12 @@ export class AcpProcess {
207
245
  const error = new Error('ACP process stopped')
208
246
  this.fail(error)
209
247
  this.peer?.close(error)
248
+ this.terminateChild()
249
+ }
250
+
251
+ private terminateChild(): void {
252
+ if (this.childTerminated || this.childExited) return
253
+ this.childTerminated = true
210
254
  this.child?.terminate()
211
255
  }
212
256