pi-agy-acp 0.1.1 → 0.1.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 ADDED
@@ -0,0 +1,22 @@
1
+ # Changelog
2
+
3
+ ## [0.1.2]
4
+
5
+ - Fix model refresh self-cancellation and support forced or cancelled refreshes.
6
+ - Keep ACP running during compaction and tree navigation while clearing conversation sessions.
7
+ - Report context overflow and exhausted quota in the format Pi uses for recovery and retry decisions.
8
+ - Handle fragmented tool arguments and skip empty system updates.
9
+ - Show cached quota in the status bar and check quota after settled Antigravity runs, with deduplicated low-quota warnings.
10
+ - Stop automatic prompt-cache warming and keep runtime warnings out of the TUI.
11
+ - Report the package version in ACP and MCP handshakes.
12
+
13
+ ## [0.1.1]
14
+
15
+ - Add CI and release workflows, with tag validation and safe release retries.
16
+ - Deduplicate model discovery and clean up temporary ACP session files and rotated logs.
17
+
18
+ ## [0.1.0]
19
+
20
+ - Add the Antigravity ACP provider for Pi, including streaming, images, and parallel tool calls.
21
+ - Discover account models and reasoning levels through ACP.
22
+ - Add status and quota panels with account details, remaining-quota bars, and reset countdowns.
package/README.md CHANGED
@@ -14,38 +14,25 @@ parallel tool calls.
14
14
 
15
15
  ## Install
16
16
 
17
- From GitHub (recommended):
17
+ Install from GitHub (recommended) or npm:
18
18
 
19
19
  ```sh
20
20
  pi install git:github.com/fdkevin0/pi-agy-acp
21
- ```
22
-
23
- From npm:
24
-
25
- ```sh
21
+ # Or:
26
22
  pi install npm:pi-agy-acp
27
23
  ```
28
24
 
29
- To install only for the current project, writing to `.pi/settings.json`:
30
-
31
- ```sh
32
- pi install -l git:github.com/fdkevin0/pi-agy-acp
33
- ```
34
-
35
- To try it for one invocation without saving an installation to settings:
25
+ Add `-l` to install only for the current project (`.pi/settings.json`). To try,
26
+ update, or remove the extension:
36
27
 
37
28
  ```sh
38
29
  pi -e git:github.com/fdkevin0/pi-agy-acp
30
+ pi update --extensions
31
+ pi remove git:github.com/fdkevin0/pi-agy-acp
39
32
  ```
40
33
 
41
- To install a local clone for development:
42
-
43
- ```sh
44
- git clone https://github.com/fdkevin0/pi-agy-acp.git
45
- pi install ./pi-agy-acp
46
- ```
47
-
48
- See [development setup](docs/development.md) for dependencies and local testing.
34
+ For npm, remove `npm:pi-agy-acp` instead. Add `-l` when removing a project-local
35
+ installation. See [development setup](docs/development.md) for local testing.
49
36
 
50
37
  ## Usage
51
38
 
@@ -57,23 +44,11 @@ automatically from your account.
57
44
  | Command | Purpose |
58
45
  | --- | --- |
59
46
  | `/agy-acp` or `/agy-acp status` | Show runtime state, account details, models, sessions, and the last turn. |
60
- | `/agy-acp quota` | Show a loading animation in the TUI, then account email, subscription plan, grouped 5h/weekly quota bars, and reset countdowns when available. |
47
+ | `/agy-acp quota` | Show account details, grouped quota bars, and reset countdowns. |
61
48
  | `/agy-acp reset` | Close ACP sessions; the next request rebuilds the connection. |
62
49
 
63
- Update installed extensions:
64
-
65
- ```sh
66
- pi update --extensions
67
- ```
68
-
69
- Remove a GitHub installation:
70
-
71
- ```sh
72
- pi remove git:github.com/fdkevin0/pi-agy-acp
73
- ```
74
-
75
- For an npm installation, use `pi remove npm:pi-agy-acp`. Add `-l` when removing
76
- a project-local installation.
50
+ After an Antigravity turn settles, the status bar shows remaining quota (for example,
51
+ `AGY 80%`) and warns when quota is low; see [quota status](docs/reference.md#quota-status-and-warnings).
77
52
 
78
53
  Default prices are zero, not a promise of free calls. Pi pricing overrides are
79
54
  used when configured.
@@ -82,4 +57,5 @@ used when configured.
82
57
 
83
58
  - [Reference](docs/reference.md): commands, configuration, stored data, model discovery, and limitations.
84
59
  - [Development](docs/development.md): setup, request flow, source layout, and verification.
60
+ - [Changelog](CHANGELOG.md): release history and upcoming changes.
85
61
  - [Attribution](NOTICE) and [MIT license](LICENSE).
@@ -3,9 +3,11 @@
3
3
  Start with the [installation guide](../README.md#install) to use the extension.
4
4
  For settings and user-visible limits, see the [reference](reference.md).
5
5
 
6
- For development, run these commands from your clone:
6
+ Clone the repository and install its dependencies:
7
7
 
8
8
  ```sh
9
+ git clone https://github.com/fdkevin0/pi-agy-acp.git
10
+ cd pi-agy-acp
9
11
  npm install
10
12
  pi -e ./index.ts
11
13
  ```
@@ -24,13 +26,34 @@ pi -e ./index.ts
24
26
  5. The adapter drains the runtime's generator before publishing completion, so
25
27
  session cleanup finishes before Pi can start its next step.
26
28
 
27
- Provider registration and cache-only refresh do not start processes, sockets, or
28
- timers. Successful session replacement is cleaned up through `session_shutdown`;
29
- pre-switch and pre-fork interception hooks do not reset the runtime.
30
-
31
- The bridge binds to `127.0.0.1`, uses per-session bearer credentials, and checks
32
- structured tool identity before granting permissions. Session changes and
33
- compaction trigger cleanup and rebuilding; shutdown closes processes and the bridge.
29
+ - **Model discovery:** Registration and cache-only refresh start no processes,
30
+ sockets, or timers. Concurrent refreshes share a discovery session; after a live
31
+ catalog is observed, later refreshes reuse it unless forced. Refresh suppresses
32
+ provider re-registration so it cannot cancel itself. Cancellation ends the
33
+ caller's wait; shared discovery still closes its session and cleans its files.
34
+ - **Session lifecycle:** The bridge binds to `127.0.0.1`, uses per-session bearer
35
+ credentials, and validates structured tool identity before granting permissions.
36
+ Tree navigation and compaction close conversation sessions and their files,
37
+ retaining the process, bridge, and caches. Pi 1.5.0 reports completed switches
38
+ through `session_start` (`new`, `resume`, or `fork`), which uses the same light
39
+ reset if the runtime survives. `session_shutdown` and `/agy-acp reset` dispose
40
+ the runtime. Cancelled turns wait for prompt settlement for up to five seconds,
41
+ then mark the conversation for rebuilding.
42
+ - **Quota and TUI:** Settled checks share the reader's TTL and in-flight request
43
+ without blocking Pi. Model selection reads memory only. UI generation checks
44
+ discard stale background results; warning keys include bucket, reset time, and
45
+ threshold. An explicit quota query can discover uncached account tiers through
46
+ one tool-less ACP session per runtime, persisting the tier in `catalog.json`.
47
+ Email lookup reads at most the last 64 KiB of each candidate login log and uses
48
+ the last match in the first matching file. Runtime warnings stay off stderr to
49
+ preserve TUI rendering; diagnostics use status and agy's logs.
50
+ - **Pi stream and error contracts:** `onPayload` can replace the request, and
51
+ `onProviderStreamEvent` observes events before conversion. At the first stream
52
+ event, `onResponse` receives synthetic status `200` and empty headers before
53
+ normalization; startup failures and an initial aborted finish emit no response.
54
+ ACP supplies no HTTP response metadata. Context overflow and exhausted quota
55
+ receive `context_length_exceeded` and `quota exceeded` markers for Pi's
56
+ compaction and retry decisions; transport timeouts remain distinct.
34
57
 
35
58
  ## Source layout
36
59
 
@@ -38,10 +61,11 @@ compaction trigger cleanup and rebuilding; shutdown closes processes and the bri
38
61
  | --- | --- |
39
62
  | `index.ts` | Provider registration, commands, and Pi lifecycle hooks. |
40
63
  | `src/pi-stream.ts`, `src/protocol.ts` | Pi message conversion and bridge event contracts. |
41
- | `src/runtime.ts`, `src/conversation.ts`, `src/history.ts` | Sessions, pending tool calls, streaming, and history replay. |
42
- | `src/acp-process.ts`, `src/jsonrpc.ts`, `src/mcp-bridge.ts` | ACP transport and local MCP server. |
64
+ | `src/runtime.ts`, `src/conversation.ts`, `src/history.ts` | Session orchestration, pending calls, tool identity metadata, streaming, and history replay. |
65
+ | `src/acp-process.ts`, `src/jsonrpc.ts`, `src/mcp-bridge.ts` | ACP transport, local MCP server, tool schema compression, and tool deltas. |
43
66
  | `src/host.ts`, `src/preflight.ts`, `src/config.ts` | Process execution, executable discovery, and isolated home setup. |
44
67
  | `src/catalog.ts`, `src/quota.ts`, `src/format.ts`, `src/util.ts` | Model catalog, quota queries, TUI notice formatting, and shared utilities. |
68
+ | `src/version.ts` | ACP/MCP version read from `package.json`. |
45
69
  | `tests/` | Scripted agy fixture, runtime tests, and Pi integration tests. |
46
70
 
47
71
  Upstream provenance and licensing are recorded in [NOTICE](../NOTICE) and
@@ -59,9 +83,8 @@ Tests run directly with Node's native TypeScript support; `tsx` is not required.
59
83
  Automated tests use a scripted local `agy` substitute so `npm test` runs offline
60
84
  without consuming account quota. They need permission to listen on `127.0.0.1`.
61
85
 
62
- Coverage includes tool suspension and resumption, parallel calls, permission
63
- checks, cancellation, history rewrites, images, quota errors, model discovery,
64
- account metadata caching, bounded login-log reads, and Pi stream completion.
86
+ Tests cover ACP transport and sessions, tool routing and permissions, model and
87
+ account discovery, Pi streaming and cancellation, and quota UI behavior.
65
88
  Listing models verifies extension loading, not access to the real service.
66
89
 
67
90
  To inspect the package contents without publishing:
package/docs/reference.md CHANGED
@@ -63,20 +63,33 @@ response displays `No quota data available.`.
63
63
 
64
64
  ### Account details
65
65
 
66
- Both panels show the email and subscription plan when known. The plan comes from
67
- ACP session metadata and is saved in `catalog.json`. If no plan is cached, the
68
- first quota check also tries a tool-less ACP discovery session in parallel with
69
- the quota query. This starts ACP but sends no model prompt. Discovery is attempted
70
- once per runtime; failure still allows the quota result to appear. Use
71
- `/agy-acp reset` to allow another attempt. Viewing status never starts discovery.
72
-
73
- The email is read from the latest login entry in the last 64 KiB of the isolated
74
- home's `acp.log`; it is not saved in the model cache. With the default home only,
75
- the reader also checks `~/.gemini/antigravity-cli/cli.log` if needed. A custom
76
- `PI_AGY_HOME` never falls back to that global log. Either field appears on its own
77
- when the other is unavailable; the account line is omitted when neither is known.
78
- These details are best-effort: cached plans and login logs can be stale after an
79
- account change.
66
+ Both panels show the email and subscription plan when known, omitting unavailable
67
+ fields. If no plan is cached, the first `/agy-acp quota` query also tries to discover
68
+ it. This may start ACP but sends no model prompt; failure does not prevent quota
69
+ from appearing. Use `/agy-acp reset` to retry discovery. Viewing status never starts it.
70
+
71
+ The email comes from login logs. With the default home only, the extension also
72
+ checks `~/.gemini/antigravity-cli/cli.log` if needed; a custom `PI_AGY_HOME` stays
73
+ isolated. Cached plans and login logs can be stale after an account change.
74
+
75
+ ### Quota status and warnings
76
+
77
+ When a run using `antigravity-acp` fully settles, the extension checks `/usage`
78
+ in the background and shows a compact status such as `AGY 80%`. It uses the
79
+ lowest known window in the selected model family's group, falling back to the
80
+ lowest known quota across groups when the family cannot be matched. Failed
81
+ checks stay silent. Successful results and failures both respect the two-minute
82
+ quota TTL, and overlapping background checks are skipped.
83
+
84
+ At 20% and 5% remaining, a warning appears once per bucket, reset time, and
85
+ threshold. `/agy-acp quota` explicitly refreshes quota and updates the status;
86
+ `/agy-acp status` uses fresh cached quota only. Neither session start nor model
87
+ selection launches a quota command. Selecting another provider hides the status;
88
+ returning to Antigravity uses only a fresh in-memory snapshot. Reset and shutdown
89
+ clear the status.
90
+
91
+ While loaded, this extension vetoes Pi's automatic prompt-cache warming to avoid
92
+ idle requests consuming quota. It does not alter explicit model requests.
80
93
 
81
94
  ## Configuration
82
95
 
@@ -98,13 +111,11 @@ PI_AGY_COMMAND=/absolute/path/to/agy pi -e ./index.ts
98
111
  The dedicated directory isolates the bridge agent from your normal agy tools and
99
112
  plugins. It contains agy-managed session data, logs, and the extension's model cache.
100
113
 
101
- Closed temporary ACP sessions have their database files and brain directories
102
- removed automatically. Before starting ACP, the extension also removes leftover
103
- session files, summary indexes, and numeric `acp.log.<pid>` backups. It retains
104
- the current `acp.log`, model cache, and authentication files; Pi owns the history
105
- used to rebuild sessions. Cleanup is best-effort if files are locked. Use a
106
- different `PI_AGY_HOME` for each concurrently running Pi instance, since startup
107
- cleanup assumes exclusive use of the directory.
114
+ Temporary session data and old logs are removed automatically. The current log,
115
+ model cache, and authentication files are retained; sessions rebuild from Pi's
116
+ history. Cleanup is best-effort if files are locked. Use a different `PI_AGY_HOME`
117
+ for each concurrently running Pi instance, since startup cleanup assumes exclusive
118
+ use of the directory.
108
119
 
109
120
  With file-backed authentication, the extension copies the existing OAuth token
110
121
  from your normal agy directory and sets its permissions to `0600`. Do not commit
@@ -112,16 +123,12 @@ or share this directory. Authentication and token refresh remain agy's responsib
112
123
 
113
124
  ## Models and context
114
125
 
115
- Loading the extension reads the cached model catalog, or falls back to five model
116
- families, without starting agy. Pi's model refresh queries ACP for the account's
117
- catalog once per runtime. Concurrent refreshes share one discovery session;
118
- after a refresh or normal session observes the live catalog, later refreshes
119
- reuse it. The first request also discovers models and validates the selection.
120
- Cache-only refreshes and refreshes already cancelled before startup do not launch
121
- ACP. Server-advertised models are not hidden, and live catalog changes update
122
- Pi's model selector. The selector exposes only the ACP reasoning levels offered
123
- for each model. Direct requests map `minimal` to `low` and `xhigh` or `max` to
124
- `high`; `off` leaves the ACP effort unspecified, using the runtime default.
126
+ Loading the extension uses the cached catalog, or five fallback model families,
127
+ without starting agy. Model refresh or the first request updates available models
128
+ and reasoning levels from ACP. A forced refresh queries again; refreshes can be
129
+ cancelled. The selector exposes only the reasoning levels offered for each model.
130
+ Direct requests map `minimal` to `low` and `xhigh` or `max` to `high`; `off` uses
131
+ the runtime default.
125
132
 
126
133
  The fallback families are:
127
134
 
@@ -156,12 +163,6 @@ Host peer dependencies use `*` as required by Pi package conventions; validation
156
163
  has been performed against version 1.5.0. Compatibility with older
157
164
  `@mariozechner/*` interfaces is not claimed.
158
165
 
159
- The bridge supports `onPayload` request replacement and `onProviderStreamEvent`
160
- observation before conversion to Pi events. At the first ACP stream event, it
161
- invokes `onResponse` with synthetic status `200` and empty headers before
162
- normalizing that event. This is a Pi instrumentation notification, not an HTTP
163
- response from agy. Startup errors before the first event do not emit it.
164
-
165
166
  Sampling parameters, output limits, forced `toolChoice`, and provider-scoped
166
167
  environment overrides are not mapped to ACP. See
167
168
  [development checks](development.md#verification) for the scope of automated validation.
package/index.ts CHANGED
@@ -2,12 +2,18 @@ import {
2
2
  BorderedLoader,
3
3
  type ExtensionAPI,
4
4
  type ProviderModelConfig,
5
+ type ExtensionContext,
5
6
  } from '@earendil-works/pi-coding-agent'
6
7
  import { AntigravityRuntime } from './src/runtime.ts'
7
8
  import { defaults } from './src/config.ts'
8
9
  import { spawnAcp, runCommand } from './src/host.ts'
9
10
  import { streamPi } from './src/pi-stream.ts'
10
- import { formatQuota, formatStatus } from './src/format.ts'
11
+ import {
12
+ formatQuota,
13
+ formatStatus,
14
+ formatQuotaStatus,
15
+ quotaForModel,
16
+ } from './src/format.ts'
11
17
  import type { QuotaSnapshot } from './src/quota.ts'
12
18
 
13
19
  export default function (pi: ExtensionAPI) {
@@ -16,13 +22,16 @@ export default function (pi: ExtensionAPI) {
16
22
  command: process.env.PI_AGY_COMMAND || '',
17
23
  home: process.env.PI_AGY_HOME || '',
18
24
  }
25
+ let refreshDepth = 0
19
26
  const createRuntime = () =>
20
27
  new AntigravityRuntime({
21
28
  config,
22
29
  spawnAcp,
23
30
  runCommand,
24
- log: { info: () => {}, warn: (message) => console.error(message) },
25
- onModelsChanged: () => register(),
31
+ log: { info: () => {}, warn: () => {} },
32
+ onModelsChanged: () => {
33
+ if (refreshDepth === 0) register()
34
+ },
26
35
  })
27
36
  let runtime = createRuntime()
28
37
  const models = (): ProviderModelConfig[] =>
@@ -60,22 +69,100 @@ export default function (pi: ExtensionAPI) {
60
69
  streamSimple: (model, context, options) =>
61
70
  streamPi(runtime, model, context, options),
62
71
  refreshModels: async (context) => {
63
- if (context?.allowNetwork !== false && !context?.signal?.aborted) {
64
- await runtime.warmup()
72
+ refreshDepth++
73
+ try {
74
+ if (context?.allowNetwork !== false && !context?.signal?.aborted) {
75
+ await runtime.warmup({
76
+ force: context?.force,
77
+ signal: context?.signal,
78
+ })
79
+ }
80
+ return models()
81
+ } finally {
82
+ refreshDepth--
65
83
  }
66
- return models()
67
84
  },
68
85
  })
69
86
  register()
87
+ let uiEpoch = 0
88
+ let checkingQuota = false
89
+ const warned = new Set<string>()
90
+ const clearStatus = (ctx?: ExtensionContext) => {
91
+ uiEpoch++
92
+ if (ctx?.hasUI) ctx.ui.setStatus(config.provider, undefined)
93
+ }
94
+ const updateStatus = (
95
+ ctx: ExtensionContext,
96
+ snapshot?: QuotaSnapshot,
97
+ explicit = false,
98
+ model = ctx.model,
99
+ ) => {
100
+ if (ctx.hasUI && (explicit || model?.provider === config.provider))
101
+ ctx.ui.setStatus(
102
+ config.provider,
103
+ snapshot ? formatQuotaStatus(snapshot, model?.id) : undefined,
104
+ )
105
+ }
70
106
  const reset = async () => {
107
+ uiEpoch++
108
+ warned.clear()
71
109
  await runtime.dispose()
72
110
  runtime = createRuntime()
73
111
  }
74
- pi.on('session_tree', reset)
75
- pi.on('session_compact', reset)
76
- pi.on('session_shutdown', async () => {
112
+ pi.on('session_tree', () => runtime.resetConversations())
113
+ pi.on('session_compact', () => runtime.resetConversations())
114
+ pi.on('session_start', async (event, ctx) => {
115
+ clearStatus(ctx)
116
+ if (['new', 'resume', 'fork'].includes(event.reason))
117
+ await runtime.resetConversations()
118
+ updateStatus(ctx, runtime.quota.peek())
119
+ })
120
+ pi.on('session_shutdown', async (_event, ctx) => {
121
+ clearStatus(ctx)
77
122
  await runtime.dispose()
78
123
  })
124
+ pi.on('cache_warming_decision', () => ({ action: 'stop' }))
125
+ pi.on('model_select', (event, ctx) => {
126
+ clearStatus(ctx)
127
+ updateStatus(ctx, runtime.quota.peek(), false, event.model)
128
+ })
129
+ pi.on('agent_settled', (_event, ctx) => {
130
+ if (
131
+ ctx.model?.provider !== config.provider ||
132
+ checkingQuota ||
133
+ runtime.quota.pending
134
+ )
135
+ return
136
+ const current = runtime
137
+ const epoch = uiEpoch
138
+ checkingQuota = true
139
+ void current.quota
140
+ .read(false)
141
+ .then((snapshot) => {
142
+ if (
143
+ current !== runtime ||
144
+ epoch !== uiEpoch ||
145
+ snapshot.status !== 'ok'
146
+ )
147
+ return
148
+ updateStatus(ctx, snapshot)
149
+ if (!ctx.hasUI || ctx.model?.provider !== config.provider) return
150
+ const quota = quotaForModel(snapshot, ctx.model.id)
151
+ if (!quota || quota.fraction > 0.2) return
152
+ const threshold = quota.fraction <= 0.05 ? 5 : 20
153
+ const key = `${quota.group.name}:${quota.bucket.id}:${quota.bucket.window}:${quota.bucket.resetTime || 'none'}:${threshold}`
154
+ if (warned.has(key)) return
155
+ warned.add(key)
156
+ ctx.ui.notify(
157
+ `Antigravity quota low: ${Math.round(quota.fraction * 100)}% remaining (${quota.group.name}, ${quota.bucket.window}).`,
158
+ 'warning',
159
+ )
160
+ })
161
+ .catch(() => {})
162
+ .finally(() => {
163
+ checkingQuota = false
164
+ })
165
+ })
79
166
  pi.registerCommand('agy-acp', {
80
167
  description: 'Antigravity ACP status, quota, or reset',
81
168
  getArgumentCompletions: (prefix) => {
@@ -87,6 +174,7 @@ export default function (pi: ExtensionAPI) {
87
174
  handler: async (args, ctx) => {
88
175
  const command = args.trim()
89
176
  if (command === 'reset') {
177
+ clearStatus(ctx)
90
178
  await reset()
91
179
  ctx.ui.notify('Antigravity ACP sessions reset', 'info')
92
180
  return
@@ -96,6 +184,7 @@ export default function (pi: ExtensionAPI) {
96
184
  return
97
185
  }
98
186
  let snapshot: QuotaSnapshot | null = null
187
+ const epoch = uiEpoch
99
188
  if (command === 'quota') {
100
189
  snapshot =
101
190
  ctx.mode === 'tui' && typeof ctx.ui.custom === 'function'
@@ -123,6 +212,8 @@ export default function (pi: ExtensionAPI) {
123
212
  const notice = snapshot
124
213
  ? formatQuota(snapshot)
125
214
  : formatStatus(runtime.status())
215
+ if (epoch === uiEpoch)
216
+ updateStatus(ctx, snapshot ?? runtime.quota.peek(), true)
126
217
  ctx.ui.notify(notice.text, notice.level)
127
218
  },
128
219
  })
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-agy-acp",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "description": "Google Antigravity ACP provider extension for Pi Coding Agent",
@@ -21,6 +21,7 @@
21
21
  "index.ts",
22
22
  "src",
23
23
  "README.md",
24
+ "CHANGELOG.md",
24
25
  "docs",
25
26
  "LICENSE",
26
27
  "NOTICE"
@@ -30,7 +31,8 @@
30
31
  },
31
32
  "peerDependencies": {
32
33
  "@earendil-works/pi-ai": "*",
33
- "@earendil-works/pi-coding-agent": "*"
34
+ "@earendil-works/pi-coding-agent": "*",
35
+ "@earendil-works/pi-tui": "*"
34
36
  },
35
37
  "scripts": {
36
38
  "test": "node --test tests/*.test.mjs",
@@ -136,8 +136,6 @@ export class AcpProcess {
136
136
  private child: AcpChild | undefined
137
137
  private peer: JsonRpcPeer | undefined
138
138
  private exitError: Error | undefined
139
- /** Agent `initialize` result. */
140
- initializeResult: Record<string, unknown> | undefined
141
139
  private readonly exitListeners = new Set<(error: Error) => void>()
142
140
  private readonly options: AcpProcessOptions
143
141
 
@@ -188,7 +186,7 @@ export class AcpProcess {
188
186
  peer.close(error)
189
187
  this.fail(error)
190
188
  })
191
- this.initializeResult = await peer.request<Record<string, unknown>>(
189
+ await peer.request(
192
190
  'initialize',
193
191
  {
194
192
  protocolVersion: 1,
@@ -13,13 +13,16 @@
13
13
 
14
14
  import { LlmError } from './protocol.ts'
15
15
  import type { ContentBlock, StreamChunk, TokenUsage } from './protocol.ts'
16
- import type { AcpPromptResult, AcpSessionUpdate } from './acp-process.ts'
16
+ import type {
17
+ AcpPromptResult,
18
+ AcpSessionUpdate,
19
+ AcpPermissionRequest,
20
+ AcpToolCallMeta,
21
+ } from './acp-process.ts'
17
22
  import type { BridgeTool, BridgeToolResult } from './mcp-bridge.ts'
18
23
  import { AGENT_TOOL_PREFIX, CALL_TOOL_NAME } from './history.ts'
19
24
  import { AsyncQueue, deferred, type Deferred } from './util.ts'
20
25
 
21
- export { CALL_TOOL_NAME }
22
-
23
26
  /** Agent-side transport retry notice streamed as message text, e.g. `⚠ API error (attempt 1): …`. */
24
27
  const AGENT_RETRY_NOTICE = /^\s*⚠\s*API error \(attempt \d+\)/
25
28
  /** First sentence of the notice agy inserts when one generation hits its own output cap. */
@@ -144,6 +147,9 @@ export class AcpTurn {
144
147
  continuations = 0
145
148
  /** The agent ended the prompt. */
146
149
  finished = false
150
+ /** Settles after the current prompt's result or error has been queued. */
151
+ promptSettled: Promise<void> = Promise.resolve()
152
+ usage?: AcpPromptResult['usage']
147
153
  /** A parked call was answered with a still-running notice and the agent has not resumed waiting yet. */
148
154
  relaying = false
149
155
  /** The turn produced visible text or a tool call. */
@@ -258,8 +264,6 @@ export interface PumpHost {
258
264
  continuePrompt(): Promise<AcpPromptResult>
259
265
  /** Request cancellation of the running turn. */
260
266
  cancel(): void
261
- /** Observe the final usage of a prompt turn. */
262
- recordUsage(usage: AcpPromptResult['usage'], steps: number): void
263
267
  }
264
268
 
265
269
  /**
@@ -427,7 +431,7 @@ export async function* pumpStep(
427
431
  turn.continuations < host.maxContinuations
428
432
  ) {
429
433
  turn.continuations++
430
- void host.continuePrompt().then(
434
+ turn.promptSettled = host.continuePrompt().then(
431
435
  (result) => turn.events.push({ kind: 'done', result }),
432
436
  (error: unknown) =>
433
437
  turn.events.push({
@@ -441,7 +445,7 @@ export async function* pumpStep(
441
445
  turn.finished = true
442
446
  yield* close()
443
447
  const calls = turn.toolSteps + turn.continuations + 1
444
- host.recordUsage(event.result.usage, calls)
448
+ turn.usage = event.result.usage
445
449
  const usage = toTokenUsage(event.result.usage, calls)
446
450
  if (usage !== undefined) yield { type: 'usage', usage }
447
451
  if (stop === 'end_turn' && !turn.produced) {
@@ -518,3 +522,99 @@ export function relayNotice(call: ParkedCall): BridgeToolResult {
518
522
  ],
519
523
  }
520
524
  }
525
+
526
+ /** Structured MCP metadata the agent reported for one tool call. */
527
+ export interface ReportedToolCall {
528
+ kind?: string
529
+ serverName?: string
530
+ toolName?: string
531
+ /** Set when later updates contradicted an already established field. */
532
+ conflict?: boolean
533
+ }
534
+
535
+ /** Read a non-empty string field. */
536
+ function nonEmpty(value: unknown): string | undefined {
537
+ return typeof value === 'string' && value.length > 0 ? value : undefined
538
+ }
539
+
540
+ /**
541
+ * Extract the structured `(serverName, toolName)` an agent claimed in one
542
+ * permission request: top-level `mcpServerName`/`mcpToolName` or `_meta`.
543
+ * `title` and `rawInput` are deliberately not consulted.
544
+ */
545
+ export function structuredToolMeta(
546
+ toolCall: AcpPermissionRequest['toolCall'],
547
+ ): {
548
+ serverName?: string
549
+ toolName?: string
550
+ } {
551
+ const meta: AcpToolCallMeta | undefined = toolCall?._meta
552
+ const serverName =
553
+ nonEmpty(toolCall?.mcpServerName) ??
554
+ nonEmpty(meta?.mcpServerName) ??
555
+ nonEmpty(meta?.serverName) ??
556
+ nonEmpty(meta?.server)
557
+ const toolName =
558
+ nonEmpty(toolCall?.mcpToolName) ??
559
+ nonEmpty(meta?.mcpToolName) ??
560
+ nonEmpty(meta?.toolName) ??
561
+ nonEmpty(meta?.tool)
562
+ return {
563
+ ...(serverName !== undefined ? { serverName } : {}),
564
+ ...(toolName !== undefined ? { toolName } : {}),
565
+ }
566
+ }
567
+
568
+ /**
569
+ * Record the structured metadata of one agent-reported tool-call update.
570
+ * The first report establishes the identity; later updates merge only the
571
+ * fields actually present, so a status-only `tool_call_update` never wipes an
572
+ * established `server`/`tool`/`kind`. A later field that contradicts the
573
+ * established identity keeps the original value and marks the record
574
+ * anomalous — the permission gate refuses every further request for that call.
575
+ * @returns 'created' | 'merged' | 'conflict', or undefined for ignored updates.
576
+ */
577
+ export function recordReportedToolCall(
578
+ conv: { reportedToolCalls: Map<string, ReportedToolCall> },
579
+ update: AcpSessionUpdate,
580
+ ): 'created' | 'merged' | 'conflict' | undefined {
581
+ if (
582
+ update.sessionUpdate !== 'tool_call' &&
583
+ update.sessionUpdate !== 'tool_call_update'
584
+ )
585
+ return
586
+ if (typeof update.toolCallId !== 'string' || update.toolCallId.length === 0)
587
+ return
588
+ const { serverName, toolName } = structuredToolMeta(update)
589
+ const kind = typeof update.kind === 'string' ? update.kind : undefined
590
+ const existing = conv.reportedToolCalls.get(update.toolCallId)
591
+ const merged: ReportedToolCall = existing === undefined ? {} : { ...existing }
592
+ let conflict = false
593
+ if (kind !== undefined) {
594
+ if (merged.kind !== undefined && merged.kind !== kind) conflict = true
595
+ else merged.kind = kind
596
+ }
597
+ if (serverName !== undefined) {
598
+ if (merged.serverName !== undefined && merged.serverName !== serverName)
599
+ conflict = true
600
+ else merged.serverName = serverName
601
+ }
602
+ if (toolName !== undefined) {
603
+ if (merged.toolName !== undefined && merged.toolName !== toolName)
604
+ conflict = true
605
+ else merged.toolName = toolName
606
+ }
607
+ if (conflict) merged.conflict = true
608
+ conv.reportedToolCalls.set(update.toolCallId, merged)
609
+ if (conflict) return 'conflict'
610
+ return existing === undefined ? 'created' : 'merged'
611
+ }
612
+
613
+ /** Whether `rawInput` carries no arguments at all (MCP server loading probes). */
614
+ export function isEmptyInput(rawInput: unknown): boolean {
615
+ if (rawInput === undefined || rawInput === null) return true
616
+ if (typeof rawInput === 'string') return rawInput.trim().length === 0
617
+ if (Array.isArray(rawInput)) return rawInput.length === 0
618
+ if (typeof rawInput === 'object') return Object.keys(rawInput).length === 0
619
+ return false
620
+ }