pi-agy-acp 0.2.6 → 0.2.8

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,19 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.2.8](https://github.com/fdkevin0/pi-agy-acp/compare/v0.2.7...v0.2.8) (2026-12-06)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * **runtime:** unify error classification, session/turn state, and module naming ([#67](https://github.com/fdkevin0/pi-agy-acp/issues/67)) ([bc52ba9](https://github.com/fdkevin0/pi-agy-acp/commit/bc52ba9eabf08c3321d8cf9d5a642008c2e34070))
9
+
10
+ ## [0.2.7](https://github.com/fdkevin0/pi-agy-acp/compare/v0.2.6...v0.2.7) (2026-12-03)
11
+
12
+
13
+ ### Bug Fixes
14
+
15
+ * **history:** split oversized opening instructions into prelude prompts ([#65](https://github.com/fdkevin0/pi-agy-acp/issues/65)) ([adebbb2](https://github.com/fdkevin0/pi-agy-acp/commit/adebbb2816901b8fe4f3b5f427ec9867026bd713))
16
+
3
17
  ## [0.2.6](https://github.com/fdkevin0/pi-agy-acp/compare/v0.2.5...v0.2.6) (2026-12-03)
4
18
 
5
19
 
@@ -35,7 +35,13 @@ Working directory is `<PI_AGY_HOME>/workspace`. ACP JSON-RPC timeouts:
35
35
  (`<harness_tool_instructions>`), and trailing live input are always emitted
36
36
  complete. `<pi_history>` fills the remaining bytes of the 160,000-byte replay
37
37
  budget (`REPLAY_BUDGET_BYTES`, kept under `agy`'s 192,000-byte single
38
- `USER_INPUT` limit) newest-first.
38
+ `USER_INPUT` limit) newest-first. When `<system_instructions>` +
39
+ `<harness_tool_instructions>` + live input would starve history or exceed
40
+ `PRELUDE_CHUNK_BYTES` (`184,000` bytes), `openingPrompts()` sends the
41
+ instructions first as one or more prelude prompts (asking for `OK` with no
42
+ bound turn, while still inspecting SQLite hidden errors and marking the
43
+ session dirty on abort/failure) so `<pi_history>` and the live input stay
44
+ intact in the final prompt.
39
45
  - If the single newest history item is an oversized tool result and remaining
40
46
  budget exceeds 1,024 bytes, it is head-truncated on UTF-8 code-point
41
47
  boundaries. Historical images render as `[image]`; trailing user images and
@@ -73,12 +79,13 @@ Working directory is `<PI_AGY_HOME>/workspace`. ACP JSON-RPC timeouts:
73
79
  - Completing (`end_turn`/`max_tokens`) while `waiting` fails with
74
80
  `PROVIDER_ERROR`; completing with only `unawaited`/`notified` entries appends
75
81
  an unretrieved-result note and finishes normally.
76
- - `callDelivery` (`waiting` | `delivered`) guards against concurrent or
77
- duplicate `pi_await_result` calls.
82
+ - `ToolCallEntry.delivery` (`idle` | `waiting` | `delivered`) inside
83
+ `AcpTurn.calls` guards against concurrent or duplicate `pi_await_result`
84
+ calls.
78
85
  - 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.
86
+ `handleCall` so `deliverCallResult()` mutates `ToolCallEntry.delivery`,
87
+ relay state, and deferred suffixes only while the SSE stream is still
88
+ writable and unaborted.
82
89
  - `max_tokens` auto-continues up to `longDecodeContinuations` (3) when not
83
90
  relaying, resetting per-segment usage counters. Transient `agy` retry and
84
91
  output-limit notices are suppressed and counted in `retryNotices`, while
@@ -114,10 +121,13 @@ Working directory is `<PI_AGY_HOME>/workspace`. ACP JSON-RPC timeouts:
114
121
 
115
122
  ## Session and process lifecycle
116
123
 
117
- - **Capacity and ephemeral sessions:** `capacityMutex` enforces
118
- `maxLiveSessions` (16), evicting the oldest idle non-opening conversation
119
- first and failing fast with `CAPACITY_EXCEEDED` (`RATE_LIMIT`) to avoid
120
- parent/subagent deadlocks. Requests without a `sessionId` use ephemeral
124
+ - **Capacity, atomic `LiveSession` state, and ephemeral sessions:** Each
125
+ conversation stores its live binding in an atomic `LiveSession` object
126
+ (`sessionId`, `tenantKey`, `tenantSecret`, `process`) so a conversation is
127
+ either bound to one complete session or cleanly unbound. `capacityMutex`
128
+ enforces `maxLiveSessions` (16), evicting the oldest idle non-opening
129
+ conversation first and failing fast with `CAPACITY_EXCEEDED` (`RATE_LIMIT`) to
130
+ avoid parent/subagent deadlocks. Requests without a `sessionId` use ephemeral
121
131
  `anon-*` keys torn down immediately after each idle step.
122
132
  - **Idle sweeper and `session/resume`:** Runs every 60 s (`.unref()`) with a
123
133
  monotonic delta capped at 120 s per tick for sleep resilience. Idle
@@ -170,6 +180,8 @@ Working directory is `<PI_AGY_HOME>/workspace`. ACP JSON-RPC timeouts:
170
180
 
171
181
  ### MCP HTTP/SSE bridge (`src/mcp-bridge.ts`)
172
182
 
183
+ - Owns the centralized MCP bridge constants (`MCP_SERVER_NAME`,
184
+ `AGENT_TOOL_PREFIX`, `CALL_TOOL_NAME`, `AWAIT_TOOL_NAME`).
173
185
  - Binds `127.0.0.1` on an ephemeral port with per-session bearer credentials
174
186
  checked in constant time (`timingSafeEqual`).
175
187
  - Enforces Node HTTP parser deadlines of 10 s for headers and 30 s for
@@ -233,11 +245,13 @@ Working directory is `<PI_AGY_HOME>/workspace`. ACP JSON-RPC timeouts:
233
245
  remains necessary in `agy` 1.5.23 because certain API errors (such as
234
246
  `INVALID_ARGUMENT (code 400)` on malformed images) still complete
235
247
  `session/prompt` with `stopReason: "end_turn"`:
236
- - `QUOTA_EXHAUSTED` → `QUOTA` (extracts reset timestamp/delay)
248
+ - `QUOTA_EXHAUSTED` / explicit quota exhaustion → `QUOTA` (extracts reset
249
+ timestamp/delay)
237
250
  - Thinking signature validation errors (`thinking.signature: Field required`
238
251
  or `Invalid \`signature\` in \`thinking\` block`) → `PROVIDER_ERROR` and
239
252
  marks the session dirty for rebuild
240
- - `429` / `RESOURCE_EXHAUSTED` → `RATE_LIMIT`
253
+ - `429` / `RESOURCE_EXHAUSTED` (without explicit quota exhaustion) →
254
+ `RATE_LIMIT` (unified across both RPC `mapError()` and SQLite hidden errors)
241
255
  - `400` / `INVALID_ARGUMENT` (including malformed-image rejections) →
242
256
  `INVALID_REQUEST`
243
257
  - `404` / `NOT_FOUND` → `SERVER` if the model was reached, else
@@ -271,20 +285,25 @@ tool-heavy or continued turns:
271
285
 
272
286
  ## Quota reader and Pi stream contracts
273
287
 
274
- - **Quota reader (`src/quota.ts`):** Runs `agy usage --output-format json`
275
- with closed `stdin`, a 1 MiB `stdout` cap, a 45 s timeout, and early abort if
276
- `stderr` matches `Authentication required`. Uses a monotonic clock
277
- (`performance.now()`) for its 2-minute TTL, filters `disabled === true`
278
- buckets, and shares concurrent in-flight queries.
288
+ - **Quota reader and model matching (`src/quota.ts`):** Runs
289
+ `agy usage --output-format json` with closed `stdin`, a 1 MiB `stdout` cap, a
290
+ 45 s timeout, and early abort if `stderr` matches `Authentication required`.
291
+ Uses a monotonic clock (`performance.now()`) for its 2-minute TTL, filters
292
+ `disabled === true` buckets, shares concurrent in-flight queries, and owns
293
+ model-to-group quota matching (`quotaForModel`), leaving `src/format.ts`
294
+ focused on TUI notice formatting.
279
295
  - **Account email scan (`src/quota.ts`):** Checks `cli.log` plus the newest 10
280
296
  contained `log/cli-*.log` and `log/acp-server-*.log` files (newest-first,
281
297
  realpath-deduplicated), reading the tail 64 KiB first and falling back to the
282
298
  head 64 KiB when larger, cached for 10 s by path stat signatures.
283
- - **Warning keys and UI freshness (`index.ts`):** UI generation checks discard
284
- stale background results; `model_select` retargets an in-flight settled check
285
- when switching between `antigravity-acp` models. Low-quota warning keys
286
- include group, bucket ID, window label, reset time, and threshold (`20` or
287
- `5`).
299
+ - **Warning keys, UI freshness, and reset coordination (`index.ts`):** Visual
300
+ status clearing (`clearStatusDisplay`) is decoupled from invalidating pending
301
+ async UI work (`invalidatePendingUi`), so intra-provider `model_select`
302
+ retargets an in-flight settled check while discarding stale `session_start`
303
+ or command updates. Low-quota warning keys include group, bucket ID, window
304
+ label, reset time, and threshold (`20` or `5`). `streamSimple` and network
305
+ `refreshModels` wait on an in-flight `/agy-acp reset` (abortable via
306
+ `signal`) before using the replacement active runtime.
288
307
  - **Pi stream hooks (`src/pi-stream.ts`):**
289
308
  - `onPayload` can replace the request (strictly validated; invalid shapes
290
309
  throw `INVALID_PAYLOAD`; `sessionId` and `signal` are always preserved;
@@ -43,11 +43,11 @@ SQLite telemetry, and transport boundary invariants.
43
43
  | --- | --- |
44
44
  | `index.ts` | Provider registration, `/agy-acp` commands, TUI loaders/warnings, and Pi lifecycle hooks. |
45
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. |
46
+ | `src/runtime.ts`, `src/conversation.ts`, `src/history.ts` | Session orchestration, capacity/sweeper lifecycle, turn/retry/usage and pending/relayed tool-call logic, 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, MCP bridge constants, schema compression, and tool deltas. |
48
48
  | `src/config.ts` | Default runtime thresholds, effort/display types, and atomic `settings.json` persistence. |
49
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, `agy usage` quota reader and login-log email lookup, TUI notice formatting and model-to-group matching, and shared utilities. |
50
+ | `src/catalog.ts`, `src/quota.ts`, `src/format.ts`, `src/util.ts` | Model catalog persistence, `agy usage` quota reader, login-log email lookup, and model-to-group matching, TUI notice formatting, and shared utilities. |
51
51
  | `src/version.ts` | Package version read from `package.json` for ACP/MCP handshakes. |
52
52
  | `tests/` | Scripted local `agy` fixture (`fake-agy.mjs`), unit tests, and Pi integration tests. |
53
53
 
package/index.ts CHANGED
@@ -7,22 +7,22 @@ import {
7
7
  import { AntigravityRuntime, type RuntimeHost } from './src/runtime.ts'
8
8
  import {
9
9
  asQuotaDisplay,
10
+ DEFAULT_CONFIG,
10
11
  DEFAULT_QUOTA_DISPLAY,
11
- defaults,
12
12
  readQuotaDisplayPreference,
13
13
  writeQuotaDisplayPreference,
14
14
  type QuotaDisplay,
15
15
  } from './src/config.ts'
16
16
  import { spawnAcp, runCommand } from './src/host.ts'
17
- import { streamPi } from './src/pi-stream.ts'
17
+ import { streamPi, type StreamRuntime } from './src/pi-stream.ts'
18
18
  import {
19
19
  displayFraction,
20
20
  formatQuota,
21
21
  formatStatus,
22
22
  formatQuotaStatus,
23
- quotaForModel,
24
23
  } from './src/format.ts'
25
- import type { QuotaSnapshot } from './src/quota.ts'
24
+ import { quotaForModel, type QuotaSnapshot } from './src/quota.ts'
25
+ import { abortable } from './src/util.ts'
26
26
 
27
27
  export default function (
28
28
  pi: ExtensionAPI,
@@ -31,13 +31,18 @@ export default function (
31
31
  const envQuotaDisplay = asQuotaDisplay(process.env.PI_AGY_QUOTA_DISPLAY)
32
32
  const debug = process.env.PI_AGY_DEBUG === '1'
33
33
  const config = {
34
- ...defaults,
34
+ ...DEFAULT_CONFIG,
35
35
  command: process.env.PI_AGY_COMMAND || '',
36
36
  home: process.env.PI_AGY_HOME || '',
37
37
  }
38
38
  let refreshDepth = 0
39
- const createRuntime = () =>
40
- new AntigravityRuntime({
39
+ let uiEpoch = 0
40
+ let shutDown = false
41
+ let runtime!: AntigravityRuntime
42
+ let activeRuntime: AntigravityRuntime | undefined
43
+ let resetting: Promise<void> | undefined
44
+ const createRuntime = () => {
45
+ const instance: AntigravityRuntime = new AntigravityRuntime({
41
46
  config,
42
47
  spawnAcp: host.spawnAcp ?? spawnAcp,
43
48
  runCommand: host.runCommand ?? runCommand,
@@ -51,19 +56,38 @@ export default function (
51
56
  : () => {},
52
57
  },
53
58
  onModelsChanged: () => {
54
- if (refreshDepth === 0) register()
59
+ if (refreshDepth === 0 && !shutDown && activeRuntime === instance)
60
+ register()
55
61
  },
56
62
  })
57
- let runtime = createRuntime()
63
+ return instance
64
+ }
65
+ runtime = activeRuntime = createRuntime()
58
66
  const home = runtime.status().home
59
67
  let quotaDisplay: QuotaDisplay =
60
68
  envQuotaDisplay ??
61
69
  readQuotaDisplayPreference(home) ??
62
70
  DEFAULT_QUOTA_DISPLAY
63
- const models = (): ProviderModelConfig[] => {
64
- const input = runtime.catalog.inputModalities()
65
- return runtime.catalog.list().map((m) => {
66
- const efforts = runtime.catalog.effortsFor(m.id)
71
+ const waitForActiveRuntime = async (
72
+ signal?: AbortSignal,
73
+ ): Promise<AntigravityRuntime> => {
74
+ while (resetting) await abortable(resetting, signal)
75
+ if (shutDown || !activeRuntime)
76
+ throw new Error('Antigravity ACP runtime is disposed.')
77
+ return activeRuntime
78
+ }
79
+ const streamRuntime: StreamRuntime = {
80
+ async *stream(request) {
81
+ const current = await waitForActiveRuntime(request.signal)
82
+ yield* current.stream(request)
83
+ },
84
+ }
85
+ const models = (
86
+ target: AntigravityRuntime = activeRuntime ?? runtime,
87
+ ): ProviderModelConfig[] => {
88
+ const input = target.catalog.inputModalities()
89
+ return target.catalog.list().map((m) => {
90
+ const efforts = target.catalog.effortsFor(m.id)
67
91
  return {
68
92
  id: m.id,
69
93
  name: m.name,
@@ -82,7 +106,7 @@ export default function (
82
106
  }
83
107
  : undefined,
84
108
  cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
85
- contextWindow: runtime.contextWindowFor(m.id),
109
+ contextWindow: target.contextWindowFor(m.id),
86
110
  maxTokens: 65536,
87
111
  }
88
112
  })
@@ -95,39 +119,38 @@ export default function (
95
119
  apiKey: 'local-agy',
96
120
  models: models(),
97
121
  streamSimple: (model, context, options) =>
98
- streamPi(runtime, model, context, options),
122
+ streamPi(streamRuntime, model, context, options),
99
123
  refreshModels: async (context) => {
100
124
  refreshDepth++
101
125
  try {
126
+ let current = activeRuntime
102
127
  if (context?.allowNetwork !== false && !context?.signal?.aborted) {
103
- await runtime.warmup({
128
+ current = await waitForActiveRuntime(context?.signal)
129
+ await current.warmup({
104
130
  force: context?.force,
105
131
  signal: context?.signal,
106
132
  })
107
133
  }
108
- return models()
134
+ return models(current ?? activeRuntime ?? runtime)
109
135
  } finally {
110
136
  refreshDepth--
111
137
  }
112
138
  },
113
139
  })
114
140
  register()
115
- let uiEpoch = 0
116
- let shutDown = false
117
- let activeRuntime: AntigravityRuntime | undefined = runtime
118
- let resetting: Promise<void> | undefined
119
141
  interface PendingSettle {
120
142
  runtime: AntigravityRuntime
121
- epoch: number
122
143
  ctx: ExtensionContext
123
144
  model: ExtensionContext['model']
124
145
  }
125
146
  let pendingSettle: PendingSettle | undefined
126
147
  const warned = new Set<string>()
127
- const clearStatus = (ctx?: ExtensionContext) => {
148
+ const clearStatusDisplay = (ctx?: ExtensionContext) => {
149
+ if (!shutDown && ctx?.hasUI) ctx.ui.setStatus(config.provider, undefined)
150
+ }
151
+ const invalidatePendingUi = () => {
128
152
  uiEpoch++
129
153
  pendingSettle = undefined
130
- if (!shutDown && ctx?.hasUI) ctx.ui.setStatus(config.provider, undefined)
131
154
  }
132
155
  const updateStatus = (
133
156
  ctx: ExtensionContext,
@@ -143,9 +166,8 @@ export default function (
143
166
  )
144
167
  }
145
168
  const reset = () => {
146
- uiEpoch++
169
+ invalidatePendingUi()
147
170
  warned.clear()
148
- pendingSettle = undefined
149
171
  activeRuntime = undefined
150
172
  if (resetting) return resetting
151
173
  const previous = runtime
@@ -163,7 +185,8 @@ export default function (
163
185
  pi.on('session_tree', () => activeRuntime?.resetConversations())
164
186
  pi.on('session_compact', () => activeRuntime?.resetConversations())
165
187
  pi.on('session_start', async (event, ctx) => {
166
- clearStatus(ctx)
188
+ invalidatePendingUi()
189
+ clearStatusDisplay(ctx)
167
190
  const epoch = uiEpoch
168
191
  if (resetting) await resetting.catch(() => {})
169
192
  if (shutDown) return
@@ -173,10 +196,10 @@ export default function (
173
196
  updateStatus(ctx, activeRuntime?.quota.peek())
174
197
  })
175
198
  pi.on('session_shutdown', async (_event, ctx) => {
176
- clearStatus(ctx)
199
+ invalidatePendingUi()
200
+ clearStatusDisplay(ctx)
177
201
  shutDown = true
178
202
  activeRuntime = undefined
179
- pendingSettle = undefined
180
203
  if (resetting) await resetting.catch(() => {})
181
204
  await runtime.dispose()
182
205
  })
@@ -191,19 +214,19 @@ export default function (
191
214
  : undefined,
192
215
  )
193
216
  pi.on('model_select', (event, ctx) => {
194
- const retarget =
217
+ clearStatusDisplay(ctx)
218
+ if (
219
+ event.model?.provider === config.provider &&
195
220
  pendingSettle &&
196
- pendingSettle.runtime === activeRuntime &&
197
- pendingSettle.epoch === uiEpoch &&
198
- event.model?.provider === config.provider
199
- ? pendingSettle
200
- : undefined
201
- clearStatus(ctx)
202
- if (retarget) {
203
- retarget.epoch = uiEpoch
204
- retarget.ctx = ctx
205
- retarget.model = event.model
206
- pendingSettle = retarget
221
+ pendingSettle.runtime === activeRuntime
222
+ ) {
223
+ // Advance uiEpoch so in-flight session_start or command updates cannot
224
+ // overwrite the new model, while retargeting the active settled check.
225
+ uiEpoch++
226
+ pendingSettle.ctx = ctx
227
+ pendingSettle.model = event.model
228
+ } else {
229
+ invalidatePendingUi()
207
230
  }
208
231
  updateStatus(ctx, activeRuntime?.quota.peek(), event.model)
209
232
  })
@@ -213,14 +236,12 @@ export default function (
213
236
  const current = activeRuntime
214
237
  if (!current || !ctx.hasUI || ctx.model?.provider !== config.provider) return
215
238
  if (pendingSettle?.runtime === current) {
216
- pendingSettle.epoch = uiEpoch
217
239
  pendingSettle.ctx = ctx
218
240
  pendingSettle.model = ctx.model
219
241
  return
220
242
  }
221
243
  const state: PendingSettle = {
222
244
  runtime: current,
223
- epoch: uiEpoch,
224
245
  ctx,
225
246
  model: ctx.model,
226
247
  }
@@ -232,7 +253,6 @@ export default function (
232
253
  shutDown ||
233
254
  pendingSettle !== state ||
234
255
  state.runtime !== activeRuntime ||
235
- state.epoch !== uiEpoch ||
236
256
  snapshot.status !== 'ok'
237
257
  )
238
258
  return
@@ -376,7 +396,7 @@ export default function (
376
396
  return
377
397
  }
378
398
  if (command === 'reset' && tokens.length === 1) {
379
- clearStatus(ctx)
399
+ clearStatusDisplay(ctx)
380
400
  await reset()
381
401
  if (!shutDown) ctx.ui.notify('Antigravity ACP sessions reset', 'info')
382
402
  return
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-agy-acp",
3
- "version": "0.2.6",
3
+ "version": "0.2.8",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "description": "Google Antigravity ACP provider extension for Pi Coding Agent",
@@ -39,9 +39,9 @@
39
39
  },
40
40
  "devDependencies": {
41
41
  "typescript": "7.0.2",
42
- "@types/node": "22.20.5",
43
- "@earendil-works/pi-ai": "1.5.2",
44
- "@earendil-works/pi-coding-agent": "1.5.2"
42
+ "@types/node": "22.20.7",
43
+ "@earendil-works/pi-ai": "1.7.0",
44
+ "@earendil-works/pi-coding-agent": "1.7.0"
45
45
  },
46
46
  "keywords": [
47
47
  "pi-package",
@@ -9,6 +9,7 @@
9
9
 
10
10
  import type { Readable, Writable } from 'node:stream'
11
11
  import { JsonRpcPeer, JsonRpcRemoteError } from './jsonrpc.ts'
12
+ import { isRecord } from './util.ts'
12
13
 
13
14
  /** Minimal handle of a spawned ACP process. */
14
15
  export interface AcpChild {
@@ -131,8 +132,8 @@ export interface AcpTierInfo {
131
132
  upgradeUri?: string
132
133
  }
133
134
 
134
- /** `session/new` result. */
135
- export interface AcpNewSessionResult {
135
+ /** `session/new` and `session/resume` result. */
136
+ export interface AcpSessionResult {
136
137
  sessionId: string
137
138
  configOptions?: AcpConfigOption[]
138
139
  /** Full model inventory, including one entry per effort variant. */
@@ -269,8 +270,8 @@ export class AcpProcess {
269
270
  params: Record<string, unknown>,
270
271
  listener: AcpSessionListener,
271
272
  timeoutMs: number,
272
- ): Promise<AcpNewSessionResult> {
273
- const result = await this.link().request<AcpNewSessionResult>(
273
+ ): Promise<AcpSessionResult> {
274
+ const result = await this.link().request<AcpSessionResult>(
274
275
  'session/new',
275
276
  params,
276
277
  { timeoutMs },
@@ -291,8 +292,8 @@ export class AcpProcess {
291
292
  params: Record<string, unknown>,
292
293
  listener: AcpSessionListener,
293
294
  timeoutMs: number,
294
- ): Promise<AcpNewSessionResult> {
295
- const result = await this.link().request<AcpNewSessionResult>(
295
+ ): Promise<AcpSessionResult> {
296
+ const result = await this.link().request<AcpSessionResult>(
296
297
  'session/resume',
297
298
  params,
298
299
  { timeoutMs },
@@ -388,33 +389,18 @@ export class AcpProcess {
388
389
 
389
390
  private onNotification(method: string, params: unknown): void {
390
391
  if (method !== 'session/update') return
391
- if (params === null || typeof params !== 'object' || Array.isArray(params))
392
- return
393
- const record = params as { sessionId?: unknown; update?: unknown }
394
- if (
395
- typeof record.sessionId !== 'string' ||
396
- record.update === null ||
397
- typeof record.update !== 'object' ||
398
- Array.isArray(record.update)
399
- )
400
- return
392
+ if (!isRecord(params)) return
393
+ if (typeof params.sessionId !== 'string' || !isRecord(params.update)) return
401
394
  this.listeners
402
- .get(record.sessionId)
403
- ?.onUpdate(record.update as AcpSessionUpdate)
395
+ .get(params.sessionId)
396
+ ?.onUpdate(params.update as AcpSessionUpdate)
404
397
  }
405
398
 
406
399
  private onRequest(method: string, params: unknown): unknown {
407
400
  if (method === 'session/request_permission') {
408
- if (
409
- params === null ||
410
- typeof params !== 'object' ||
411
- Array.isArray(params)
412
- )
413
- return { outcome: { outcome: 'cancelled' } }
414
- const record = params as { sessionId?: unknown }
415
- if (typeof record.sessionId !== 'string')
401
+ if (!isRecord(params) || typeof params.sessionId !== 'string')
416
402
  return { outcome: { outcome: 'cancelled' } }
417
- const request = params as AcpPermissionRequest
403
+ const request = params as unknown as AcpPermissionRequest
418
404
  const outcome = this.listeners
419
405
  .get(request.sessionId)
420
406
  ?.onPermission?.(request)