@qlairoslabs/acp-client 0.4.3 → 0.6.0

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.
@@ -0,0 +1,421 @@
1
+ // Bounded live metering state and its accumulation rules. See 9-6-SPEC-metering.md §11.
2
+ //
3
+ // The session keeps totals, the active baseline, and the last record — never an unbounded
4
+ // operation history. Consumers own durable accounting; the library hands them each
5
+ // immutable record plus the state to persist beside it.
6
+ //
7
+ // The counters exist so a partial total cannot look complete. "180k tokens" and "at least
8
+ // 180k tokens, with two operations we could not measure" are different claims, and per
9
+ // category they are different again: a harness may report input and output while never
10
+ // mentioning cache. Coverage distinguishes a category nobody could measure from one the
11
+ // model simply does not use.
12
+
13
+ import type { TokenUsage } from "../types.ts";
14
+ import {
15
+ CATEGORY_FIELD,
16
+ CATEGORY_TOTAL,
17
+ TOKEN_CATEGORY_KEYS,
18
+ USAGE_KEYS,
19
+ isTokenCount,
20
+ } from "./categories.ts";
21
+ import {
22
+ EMPTY_MONEY_TOTAL,
23
+ addMoney,
24
+ addToTotal,
25
+ canonicalizeMoney,
26
+ isValidMoney,
27
+ mergeTotals,
28
+ type Money,
29
+ type MoneyTotal,
30
+ } from "./money.ts";
31
+ import type { CategoryApplicability, TokenCategory } from "./pricing.ts";
32
+ import type { AttributableUsage } from "./rating.ts";
33
+
34
+ export type CategoryCoverage = "complete" | "partial" | "none" | "not_applicable";
35
+
36
+ export interface UsageCategoryTotal {
37
+ /** Sum of deltas that were actually attributable; always a lower bound. */
38
+ readonly knownTokens: number;
39
+ /** Applicable operations that supplied an attributable value, including explicit 0. */
40
+ readonly attributedOperationCount: number;
41
+ /** Operations explicitly known not to use this category. */
42
+ readonly notApplicableOperationCount: number;
43
+ /** Applicable/unknown operations for which this category could not be established. */
44
+ readonly unavailableOperationCount: number;
45
+ readonly coverage: CategoryCoverage;
46
+ }
47
+
48
+ export interface AggregateUsageTotal {
49
+ readonly knownTokens: number;
50
+ readonly attributedOperationCount: number;
51
+ readonly unavailableOperationCount: number;
52
+ /** Total usage is always applicable, so this never reads "not_applicable". */
53
+ readonly coverage: "complete" | "partial" | "none";
54
+ }
55
+
56
+ export interface UsageTotals {
57
+ readonly total: AggregateUsageTotal;
58
+ readonly input: UsageCategoryTotal;
59
+ readonly output: UsageCategoryTotal;
60
+ readonly cachedRead: UsageCategoryTotal;
61
+ readonly cachedWrite: UsageCategoryTotal;
62
+ readonly thought: UsageCategoryTotal;
63
+ }
64
+
65
+ export interface UnallocatedUsageState {
66
+ /** Number of observed inference records not assigned to an operation. */
67
+ readonly recordCount: number;
68
+ /** Known unallocated tokens. Absent categories remain absent, never zero-filled. */
69
+ readonly knownTokens: Partial<TokenUsage>;
70
+ /**
71
+ * Rated unallocated amounts.
72
+ *
73
+ * MoneyTotal carries its own completeness, so the separate costed/uncosted counters this
74
+ * once needed are gone — an unaccounted cost is `ratedCosts.unaccounted`.
75
+ */
76
+ readonly ratedCosts: MoneyTotal;
77
+ }
78
+
79
+ export interface MeteringBaseline {
80
+ readonly adapterId: string;
81
+ readonly internalSessionId: string;
82
+ readonly reportedUsage: TokenUsage;
83
+ }
84
+
85
+ export interface AgentSessionMeteringState {
86
+ readonly version: MeteringStateVersion;
87
+ readonly agentSessionId: string;
88
+ readonly operationCount: number;
89
+ readonly meteredOperationCount: number;
90
+ readonly unmeteredOperationCount: number;
91
+ readonly totals: UsageTotals;
92
+ /** Session cost across every operation. Multi-currency by design; see MoneyTotal. */
93
+ readonly ratedCosts: MoneyTotal;
94
+ readonly unallocatedUsage: UnallocatedUsageState;
95
+ readonly activeBaseline: MeteringBaseline | null;
96
+ }
97
+
98
+ /**
99
+ * The persisted shape's version, declared ONCE.
100
+ *
101
+ * It previously appeared as a literal in four places, and the last bump missed one — the
102
+ * session snapshot reported restoring version 2 beside version-3 state. A number that has
103
+ * to be updated in several places is a number that will eventually disagree with itself.
104
+ */
105
+ export type MeteringStateVersion = 3;
106
+ export const METERING_STATE_VERSION: MeteringStateVersion = 3;
107
+
108
+ /** Category → the TokenUsage field carrying it. */
109
+ function emptyCategoryTotal(): UsageCategoryTotal {
110
+ return Object.freeze({
111
+ knownTokens: 0,
112
+ attributedOperationCount: 0,
113
+ notApplicableOperationCount: 0,
114
+ unavailableOperationCount: 0,
115
+ coverage: "none" as const,
116
+ });
117
+ }
118
+
119
+ function deriveCoverage(total: Omit<UsageCategoryTotal, "coverage">): CategoryCoverage {
120
+ const { attributedOperationCount, notApplicableOperationCount, unavailableOperationCount } = total;
121
+ const seen = attributedOperationCount + notApplicableOperationCount + unavailableOperationCount;
122
+ if (seen === 0) return "none";
123
+ // Wholly inapplicable: a non-reasoning model never reports thought tokens, and that is
124
+ // not a metering gap.
125
+ if (notApplicableOperationCount === seen) return "not_applicable";
126
+ if (unavailableOperationCount === 0) return "complete";
127
+ if (attributedOperationCount === 0) return "none";
128
+ return "partial";
129
+ }
130
+
131
+ export function emptyMeteringState(agentSessionId: string): AgentSessionMeteringState {
132
+ return Object.freeze({
133
+ version: METERING_STATE_VERSION,
134
+ agentSessionId,
135
+ operationCount: 0,
136
+ meteredOperationCount: 0,
137
+ unmeteredOperationCount: 0,
138
+ totals: Object.freeze({
139
+ total: Object.freeze({
140
+ knownTokens: 0,
141
+ attributedOperationCount: 0,
142
+ unavailableOperationCount: 0,
143
+ coverage: "none" as const,
144
+ }),
145
+ input: emptyCategoryTotal(),
146
+ output: emptyCategoryTotal(),
147
+ cachedRead: emptyCategoryTotal(),
148
+ cachedWrite: emptyCategoryTotal(),
149
+ thought: emptyCategoryTotal(),
150
+ }),
151
+ ratedCosts: EMPTY_MONEY_TOTAL,
152
+ unallocatedUsage: Object.freeze({
153
+ recordCount: 0,
154
+ knownTokens: Object.freeze({}),
155
+ ratedCosts: EMPTY_MONEY_TOTAL,
156
+ }),
157
+ activeBaseline: null,
158
+ });
159
+ }
160
+
161
+ /**
162
+ * One piece of observed work that no operation can claim.
163
+ *
164
+ * Carries its cost and the reason it went unattributed: a consumer reconciling against a
165
+ * provider invoice needs the amount, and anyone debugging a gap needs to know whether it
166
+ * was a replaced thread, background activity, or a lost report.
167
+ */
168
+ export interface UnallocatedUsageAccrual {
169
+ readonly usage: TokenUsage;
170
+ readonly ratedCost: Money | null;
171
+ readonly reason: string;
172
+ }
173
+
174
+ export interface OperationAccrual {
175
+ /** Attributable usage, or null when the operation could not be measured. */
176
+ readonly attributable: AttributableUsage | null;
177
+ /** Applicability from the resolved policy; unknown when no policy was resolved. */
178
+ readonly applicability: Readonly<Record<TokenCategory, CategoryApplicability>> | null;
179
+ readonly baseline: MeteringBaseline | null;
180
+ /** Usage observed but belonging to no operation — never merged into totals. */
181
+ readonly unallocated?: readonly UnallocatedUsageAccrual[];
182
+ }
183
+
184
+ /**
185
+ * Fold one completed operation into the running state.
186
+ *
187
+ * Returns a new frozen state; the previous one stays valid, because records already handed
188
+ * to a consumer embed it.
189
+ */
190
+ export function accrueOperation(
191
+ previous: AgentSessionMeteringState,
192
+ accrual: OperationAccrual,
193
+ ): AgentSessionMeteringState {
194
+ const { attributable, applicability } = accrual;
195
+ const measured = attributable !== null;
196
+
197
+ const aggregate = previous.totals.total;
198
+ const nextAggregate = {
199
+ knownTokens: aggregate.knownTokens + (attributable?.totalTokens ?? 0),
200
+ attributedOperationCount: aggregate.attributedOperationCount + (measured ? 1 : 0),
201
+ unavailableOperationCount: aggregate.unavailableOperationCount + (measured ? 0 : 1),
202
+ };
203
+
204
+ const categoryTotals: Record<string, UsageCategoryTotal> = {};
205
+ for (const category of Object.keys(CATEGORY_FIELD) as TokenCategory[]) {
206
+ const key = CATEGORY_TOTAL[category];
207
+ const current = previous.totals[key];
208
+ const value = attributable?.reportedDelta[CATEGORY_FIELD[category]];
209
+ const notApplicable = applicability?.[category] === "not_applicable";
210
+
211
+ const next = {
212
+ knownTokens: current.knownTokens + (value ?? 0),
213
+ // An explicit reported zero counts as attributed: it is a measurement, unlike an
214
+ // absent counter.
215
+ attributedOperationCount: current.attributedOperationCount + (value !== undefined ? 1 : 0),
216
+ notApplicableOperationCount:
217
+ current.notApplicableOperationCount + (value === undefined && notApplicable ? 1 : 0),
218
+ unavailableOperationCount:
219
+ current.unavailableOperationCount + (value === undefined && !notApplicable ? 1 : 0),
220
+ };
221
+ categoryTotals[key] = Object.freeze({ ...next, coverage: deriveCoverage(next) });
222
+ }
223
+
224
+ // Always accounted: a total that could not absorb an operation's cost records that,
225
+ // rather than leaving the session silently short.
226
+ const ratedCosts = attributable
227
+ ? mergeTotals(previous.ratedCosts, attributable.ratedTotal)
228
+ : previous.ratedCosts;
229
+
230
+ return Object.freeze({
231
+ ...previous,
232
+ operationCount: previous.operationCount + 1,
233
+ meteredOperationCount: previous.meteredOperationCount + (measured ? 1 : 0),
234
+ unmeteredOperationCount: previous.unmeteredOperationCount + (measured ? 0 : 1),
235
+ totals: Object.freeze({
236
+ total: Object.freeze({ ...nextAggregate, coverage: deriveAggregateCoverage(nextAggregate) }),
237
+ input: categoryTotals.input!,
238
+ output: categoryTotals.output!,
239
+ cachedRead: categoryTotals.cachedRead!,
240
+ cachedWrite: categoryTotals.cachedWrite!,
241
+ thought: categoryTotals.thought!,
242
+ }),
243
+ ratedCosts,
244
+ unallocatedUsage: accrueUnallocated(previous.unallocatedUsage, accrual.unallocated ?? []),
245
+ activeBaseline: accrual.baseline,
246
+ });
247
+ }
248
+
249
+ /**
250
+ * Fold observed-but-unattributed usage into its own bucket.
251
+ *
252
+ * Kept strictly apart from `totals`: §11 requires that late or background work is never
253
+ * charged to the next operation, and a consumer must be able to see that it happened.
254
+ * Absent categories stay absent rather than being zero-filled.
255
+ */
256
+ function accrueUnallocated(
257
+ previous: UnallocatedUsageState,
258
+ additions: readonly UnallocatedUsageAccrual[],
259
+ ): UnallocatedUsageState {
260
+ if (additions.length === 0) return previous;
261
+ const known: Partial<TokenUsage> = { ...previous.knownTokens };
262
+ let ratedCosts = previous.ratedCosts;
263
+ for (const { usage, ratedCost } of additions) {
264
+ // addToTotal counts what it cannot include, so a missing cost cannot vanish.
265
+ ratedCosts = addToTotal(ratedCosts, ratedCost);
266
+ for (const key of USAGE_KEYS) {
267
+ const value = usage[key];
268
+ if (value === undefined) continue;
269
+ known[key] = (known[key] ?? 0) + value;
270
+ }
271
+ }
272
+ return Object.freeze({
273
+ recordCount: previous.recordCount + additions.length,
274
+ knownTokens: Object.freeze(known),
275
+ ratedCosts,
276
+ });
277
+ }
278
+
279
+ function deriveAggregateCoverage(
280
+ total: Omit<AggregateUsageTotal, "coverage">,
281
+ ): AggregateUsageTotal["coverage"] {
282
+ if (total.attributedOperationCount === 0) return "none";
283
+ return total.unavailableOperationCount === 0 ? "complete" : "partial";
284
+ }
285
+
286
+ /**
287
+ * Add one amount into a per-currency accumulation.
288
+ *
289
+ * Amounts are already-rounded operation totals, so the sum is exact and never re-rounded.
290
+ * Currencies are kept as separate facts rather than converted.
291
+ */
292
+ export function accumulateByCurrency(
293
+ totals: readonly Money[],
294
+ addition: Money,
295
+ ): { ok: true; value: readonly Money[] } | { ok: false; reason: string } {
296
+ const next: Money[] = [];
297
+ let merged = false;
298
+ for (const existing of totals) {
299
+ if (existing.currency !== addition.currency) {
300
+ next.push(existing);
301
+ continue;
302
+ }
303
+ const sum = addMoney(existing, addition);
304
+ if (!sum.ok) return { ok: false, reason: sum.reason };
305
+ next.push(sum.value);
306
+ merged = true;
307
+ }
308
+ if (!merged) {
309
+ const canonical = canonicalizeMoney(addition);
310
+ if (!canonical.ok) return { ok: false, reason: canonical.reason };
311
+ next.push(canonical.value);
312
+ }
313
+ return { ok: true, value: Object.freeze(next) };
314
+ }
315
+
316
+ export type StateRestoration =
317
+ | { readonly status: "not_provided" }
318
+ | {
319
+ readonly status: "restored";
320
+ readonly version: MeteringStateVersion;
321
+ readonly state: AgentSessionMeteringState;
322
+ }
323
+ | {
324
+ readonly status: "ignored";
325
+ readonly reason:
326
+ | "initial_state_version_unsupported"
327
+ | "initial_state_identity_mismatch"
328
+ | "initial_state_malformed";
329
+ readonly providedVersion?: number;
330
+ };
331
+
332
+ /**
333
+ * Validate restored state before any version-specific field is read.
334
+ *
335
+ * A foreign version is refused wholesale rather than partially read: fields that happen to
336
+ * line up between versions are the most dangerous kind of near-match, because the result
337
+ * looks like a successful restore.
338
+ */
339
+ function isMoneyTotal(value: unknown): boolean {
340
+ if (typeof value !== "object" || value === null) return false;
341
+ const total = value as Record<string, unknown>;
342
+ return (
343
+ Array.isArray(total.amounts) &&
344
+ total.amounts.every((amount) => isValidMoney(amount as Money)) &&
345
+ isTokenCount(total.unaccounted)
346
+ );
347
+ }
348
+
349
+ function isCategoryTotal(value: unknown): boolean {
350
+ if (typeof value !== "object" || value === null) return false;
351
+ const total = value as Record<string, unknown>;
352
+ return (
353
+ isTokenCount(total.knownTokens) &&
354
+ isTokenCount(total.attributedOperationCount) &&
355
+ isTokenCount(total.unavailableOperationCount)
356
+ );
357
+ }
358
+
359
+ /** Check the shape a restored state must have before any of it is trusted. */
360
+ function isStructurallyValid(state: AgentSessionMeteringState): boolean {
361
+ if (
362
+ !isTokenCount(state.operationCount) ||
363
+ !isTokenCount(state.meteredOperationCount) ||
364
+ !isTokenCount(state.unmeteredOperationCount)
365
+ ) {
366
+ return false;
367
+ }
368
+ const totals = state.totals as unknown as Record<string, unknown> | undefined;
369
+ if (!totals) return false;
370
+ // `total` is an AggregateUsageTotal, but the three counters checked here are exactly the
371
+ // ones both shapes share, so one predicate covers it and the five categories alike.
372
+ if (!isCategoryTotal(totals.total)) return false;
373
+ for (const key of TOKEN_CATEGORY_KEYS) {
374
+ if (!isCategoryTotal(totals[key])) return false;
375
+ }
376
+ if (!isMoneyTotal(state.ratedCosts)) return false;
377
+
378
+ const unallocated = state.unallocatedUsage as unknown as Record<string, unknown> | undefined;
379
+ if (!unallocated || !isTokenCount(unallocated.recordCount) || !isMoneyTotal(unallocated.ratedCosts)) {
380
+ return false;
381
+ }
382
+
383
+ const baseline = state.activeBaseline;
384
+ if (baseline !== null) {
385
+ if (typeof baseline !== "object") return false;
386
+ if (typeof baseline.adapterId !== "string" || typeof baseline.internalSessionId !== "string") {
387
+ return false;
388
+ }
389
+ const usage = baseline.reportedUsage as unknown as Record<string, unknown> | undefined;
390
+ if (!usage || !isTokenCount(usage.totalTokens) || !isTokenCount(usage.inputTokens) || !isTokenCount(usage.outputTokens)) {
391
+ return false;
392
+ }
393
+ }
394
+ return true;
395
+ }
396
+
397
+ export function restoreMeteringState(
398
+ provided: AgentSessionMeteringState | undefined,
399
+ agentSessionId: string,
400
+ ): StateRestoration {
401
+ if (provided === undefined) return { status: "not_provided" };
402
+
403
+ const version = (provided as { version?: unknown }).version;
404
+ if (version !== METERING_STATE_VERSION) {
405
+ return {
406
+ status: "ignored",
407
+ reason: "initial_state_version_unsupported",
408
+ ...(typeof version === "number" ? { providedVersion: version } : {}),
409
+ };
410
+ }
411
+ if (provided.agentSessionId !== agentSessionId) {
412
+ return { status: "ignored", reason: "initial_state_identity_mismatch" };
413
+ }
414
+ // A matching version and id is not proof the rest is intact. This state comes back from
415
+ // a consumer's database or a JSON file and feeds straight into totals a bill is drawn
416
+ // from, so a truncated write or a hand-edit must be refused rather than absorbed.
417
+ if (!isStructurallyValid(provided)) {
418
+ return { status: "ignored", reason: "initial_state_malformed" };
419
+ }
420
+ return { status: "restored", version: METERING_STATE_VERSION, state: provided };
421
+ }
@@ -0,0 +1,72 @@
1
+ // ACP usage normalization. The ONLY place raw `PromptResponse.usage` is turned into the
2
+ // library's public TokenUsage shape. See 9-6-SPEC-metering.md §4.
3
+ //
4
+ // Two things this module deliberately does NOT do:
5
+ // 1. Coerce a missing or malformed counter to zero. Absence is not zero — a harness
6
+ // that omits cachedWriteTokens has told us nothing, not that it wrote no cache.
7
+ // 2. Decide whether the harness emits cumulative or per-turn counters. The installed
8
+ // ACP SDK contradicts itself (PromptResponse.usage says "for this turn", the Usage
9
+ // fields say "across all turns"/"across session") and exposes no discriminator, so
10
+ // the interpretation is adapter evidence recorded in provenance, never a heuristic
11
+ // applied here.
12
+
13
+ import type { TokenUsage } from "../types.ts";
14
+ import { OPTIONAL_USAGE_KEYS, REQUIRED_USAGE_KEYS, isTokenCount } from "./categories.ts";
15
+
16
+ export type UsageNormalization =
17
+ | { readonly ok: true; readonly usage: TokenUsage }
18
+ /** `reason` is a stable, safe-to-log string; it becomes MeteringUsageResult.reason. */
19
+ | { readonly ok: false; readonly reason: string };
20
+
21
+ function describe(value: unknown): string {
22
+ if (typeof value === "number") return Number.isFinite(value) ? String(value) : String(value);
23
+ if (value === null) return "null";
24
+ return typeof value;
25
+ }
26
+
27
+ /**
28
+ * Normalize a raw ACP usage object.
29
+ *
30
+ * Absent/null report → unavailable (the harness reported nothing).
31
+ * Malformed REQUIRED counter → unavailable, never zero-filled.
32
+ * Malformed PRESENT optional counter → unavailable. A present-but-corrupt value is not
33
+ * the same as absence: silently dropping it would assert the harness never reported
34
+ * the category, which is exactly the fabrication §4 forbids.
35
+ * Absent/null optional counter → omitted from the result, so absence stays absence.
36
+ */
37
+ export function normalizeTokenUsage(raw: unknown): UsageNormalization {
38
+ if (raw === null || raw === undefined) {
39
+ return { ok: false, reason: "harness reported no usage" };
40
+ }
41
+ if (typeof raw !== "object") {
42
+ return { ok: false, reason: `usage is ${typeof raw}, not an object` };
43
+ }
44
+
45
+ const source = raw as Record<string, unknown>;
46
+ const required: Record<string, number> = {};
47
+ for (const key of REQUIRED_USAGE_KEYS) {
48
+ const value = source[key];
49
+ if (!isTokenCount(value)) {
50
+ return { ok: false, reason: `usage.${key} is ${describe(value)}, not a token count` };
51
+ }
52
+ required[key] = value;
53
+ }
54
+
55
+ const usage: TokenUsage = {
56
+ totalTokens: required.totalTokens!,
57
+ inputTokens: required.inputTokens!,
58
+ outputTokens: required.outputTokens!,
59
+ };
60
+
61
+ for (const key of OPTIONAL_USAGE_KEYS) {
62
+ const value = source[key];
63
+ // ACP types these as `number | null | undefined`; both nullish forms mean "not reported".
64
+ if (value === null || value === undefined) continue;
65
+ if (!isTokenCount(value)) {
66
+ return { ok: false, reason: `usage.${key} is ${describe(value)}, not a token count` };
67
+ }
68
+ usage[key] = value;
69
+ }
70
+
71
+ return { ok: true, usage: Object.freeze(usage) };
72
+ }
@@ -6,6 +6,7 @@
6
6
  import * as acp from "@agentclientprotocol/sdk";
7
7
  import type * as schema from "@agentclientprotocol/sdk";
8
8
  import { ProcessCrashError } from "../errors.ts";
9
+ import { onceDispose, type PreparedLaunch } from "../launcher.ts";
9
10
  import type { WireEntry } from "../types.ts";
10
11
 
11
12
  /** The five `terminal/*` methods a client that advertises `terminal: true` must serve. */
@@ -20,11 +21,8 @@ export interface TerminalHandlers {
20
21
  }
21
22
 
22
23
  export interface AcpTransportOptions {
23
- /** Full command to spawn: [...execPrefix, ...adapter.command]. */
24
- command: string[];
25
- /** cwd for the spawned process. Omit for `docker exec` (host path won't resolve in-container). */
26
- cwd?: string;
27
- env?: Record<string, string>;
24
+ /** Exact host-side process launch, already resolved by the caller's launcher. */
25
+ launch: PreparedLaunch;
28
26
 
29
27
  /**
30
28
  * A session/update notification arrived, exactly as the agent sent it — the transport
@@ -67,8 +65,11 @@ export class AcpTransport {
67
65
  private connection: acp.ClientSideConnection | null = null;
68
66
  private stopping = false;
69
67
  private tap?: (dir: WireEntry["dir"], line: string) => void;
68
+ private readonly disposeLaunch: () => Promise<void>;
70
69
 
71
- constructor(private opts: AcpTransportOptions) {}
70
+ constructor(private opts: AcpTransportOptions) {
71
+ this.disposeLaunch = onceDispose(opts.launch.dispose);
72
+ }
72
73
 
73
74
  async start(): Promise<void> {
74
75
  if (this.proc) return;
@@ -77,54 +78,90 @@ export class AcpTransport {
77
78
  // Bun's FileSink (from stdin:"pipe") lacks getWriter().
78
79
  const stdinTransform = new TransformStream<Uint8Array, Uint8Array>();
79
80
 
80
- const proc = Bun.spawn(this.opts.command, {
81
- cwd: this.opts.cwd,
82
- env: { ...process.env, ...(this.opts.env ?? {}) },
83
- stdin: stdinTransform.readable,
84
- stdout: "pipe",
85
- stderr: "pipe",
86
- });
81
+ let proc: ReturnType<typeof Bun.spawn>;
82
+ try {
83
+ proc = Bun.spawn(this.opts.launch.command, {
84
+ cwd: this.opts.launch.spawnCwd,
85
+ env: this.opts.launch.spawnEnv,
86
+ stdin: stdinTransform.readable,
87
+ stdout: "pipe",
88
+ stderr: "pipe",
89
+ });
90
+ } catch (error) {
91
+ await this.disposeLaunch().catch(() => {});
92
+ throw error;
93
+ }
87
94
  this.proc = proc;
88
95
 
89
- const wire = this.opts.onWire;
90
- const tap = wire ? (dir: WireEntry["dir"], line: string) => wire({ dir, ts: Date.now(), line }) : undefined;
96
+ try {
97
+ const wire = this.opts.onWire;
98
+ const tap = wire ? (dir: WireEntry["dir"], line: string) => wire({ dir, ts: Date.now(), line }) : undefined;
91
99
 
92
- const stream = acp.ndJsonStream(
93
- // Outgoing bytes are forwarded untouched; the tap only reads them on the way past.
94
- tap ? tapOutgoing(stdinTransform.writable, (line) => tap("out", line)) : stdinTransform.writable,
95
- interceptUpdates(
96
- proc.stdout as ReadableStream<Uint8Array>,
97
- (m) => this.opts.onUpdate?.(m.params as schema.SessionNotification),
98
- tap && ((line) => tap("in", line)),
99
- ),
100
- );
101
- this.tap = tap;
102
- const handler = new ClientHandler(this.opts);
103
- this.connection = new acp.ClientSideConnection(() => handler, stream);
100
+ const stream = acp.ndJsonStream(
101
+ // Outgoing bytes are forwarded untouched; the tap only reads them on the way past.
102
+ tap ? tapOutgoing(stdinTransform.writable, (line) => tap("out", line)) : stdinTransform.writable,
103
+ interceptUpdates(
104
+ proc.stdout as ReadableStream<Uint8Array>,
105
+ (m) => this.opts.onUpdate?.(m.params as schema.SessionNotification),
106
+ tap && ((line) => tap("in", line)),
107
+ ),
108
+ );
109
+ this.tap = tap;
110
+ const handler = new ClientHandler(this.opts);
111
+ this.connection = new acp.ClientSideConnection(() => handler, stream);
104
112
 
105
- if (proc.stderr) this.pumpStderr(proc.stderr as ReadableStream<Uint8Array>);
113
+ if (proc.stderr) this.pumpStderr(proc.stderr as ReadableStream<Uint8Array>);
106
114
 
107
- proc.exited
108
- .then((code) => {
109
- if (this.proc === proc && !this.stopping) {
110
- this.proc = null;
111
- this.connection = null;
112
- this.opts.onCrash?.(code ?? null);
113
- }
114
- })
115
- .catch(() => {});
115
+ proc.exited
116
+ .then(async (code) => {
117
+ if (this.proc === proc && !this.stopping) {
118
+ this.proc = null;
119
+ this.connection = null;
120
+ await this.disposeLaunch().catch(() => {});
121
+ this.opts.onCrash?.(code ?? null);
122
+ }
123
+ }, async () => {
124
+ if (this.proc === proc && !this.stopping) {
125
+ this.proc = null;
126
+ this.connection = null;
127
+ await this.disposeLaunch().catch(() => {});
128
+ this.opts.onCrash?.(null);
129
+ }
130
+ })
131
+ .catch(() => {});
132
+ } catch (error) {
133
+ await this.stop().catch(() => {});
134
+ throw error;
135
+ }
116
136
  }
117
137
 
118
138
  async stop(): Promise<void> {
119
139
  this.stopping = true;
120
- if (!this.proc) return;
140
+ const proc = this.proc;
141
+ this.proc = null;
142
+ this.connection = null;
143
+ if (!proc) {
144
+ await this.disposeLaunch();
145
+ return;
146
+ }
121
147
  try {
122
- this.proc.kill("SIGTERM");
148
+ proc.kill("SIGTERM");
123
149
  } catch {
124
150
  /* already exited */
125
151
  }
126
- this.proc = null;
127
- this.connection = null;
152
+ const exited = await Promise.race([
153
+ proc.exited.then(() => true, () => true),
154
+ new Promise<boolean>((resolve) => setTimeout(() => resolve(false), 500)),
155
+ ]);
156
+ if (!exited) {
157
+ try {
158
+ proc.kill("SIGKILL");
159
+ } catch {
160
+ /* already exited */
161
+ }
162
+ await proc.exited.catch(() => {});
163
+ }
164
+ await this.disposeLaunch();
128
165
  }
129
166
 
130
167
  private conn(): acp.ClientSideConnection {