@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.
@@ -20,6 +20,27 @@ import type { ConfigOptions } from "./config-options.ts";
20
20
  import type { ConnectResult } from "./client.ts";
21
21
  import { noopLogger, type Logger } from "./logger.ts";
22
22
  import { ResponseAccumulator } from "./response.ts";
23
+ import { MeteringEngine, type OpenOperation } from "./metering/engine.ts";
24
+ import {
25
+ AgentSessionHandoffError,
26
+ AgentSessionOperationError,
27
+ type AgentSessionMeteringSnapshot,
28
+ type MeteredOperationKind,
29
+ type MeteringConfig,
30
+ type MeteringReconciliation,
31
+ type OperationMeteringRecord,
32
+ } from "./metering/record.ts";
33
+ import { createModelsDevResolver } from "./metering/catalog/index.ts";
34
+ import { activeModel, resolveModelReference } from "./metering/provider.ts";
35
+ import { restoreMeteringState, type AgentSessionMeteringState } from "./metering/state.ts";
36
+ import {
37
+ contextWindowChanged,
38
+ parseContextWindow,
39
+ parseProviderCost,
40
+ providerCostChanged,
41
+ type ContextWindowStatus,
42
+ type ProviderCostSnapshot,
43
+ } from "./metering/context.ts";
23
44
  import type { SessionManager, MergedSession } from "./session-manager.ts";
24
45
  import {
25
46
  appendTranscriptLine,
@@ -33,16 +54,19 @@ import type {
33
54
  PromptHandlers,
34
55
  PromptResult,
35
56
  SessionListEntry,
57
+ TokenUsage,
36
58
  WireEntry,
37
59
  } from "./types.ts";
38
60
 
39
61
  interface PromptQueueItem {
40
62
  kind: "prompt";
41
63
  turnId: string;
64
+ /** How this operation is classified in its metering record. */
65
+ operationKind: MeteredOperationKind;
42
66
  text: string;
43
67
  handlers?: PromptHandlers;
44
68
  attachments?: Attachment[];
45
- resolve: (r: PromptResult) => void;
69
+ resolve: (r: AgentSessionPromptResult) => void;
46
70
  reject: (e: unknown) => void;
47
71
  }
48
72
 
@@ -83,6 +107,8 @@ export interface HandoffResult {
83
107
  readonly fromInternalSessionId: string | null;
84
108
  readonly toInternalSessionId: string;
85
109
  readonly summary: string;
110
+ /** One record per token-consuming operation the handoff performed, in order. */
111
+ readonly meteringRecords: readonly OperationMeteringRecord[];
86
112
  }
87
113
 
88
114
  /** Session-owned lifecycle events. Harness activity remains in PromptHandlers.onActivity. */
@@ -105,8 +131,40 @@ export type AgentSessionEvent =
105
131
  fromInternalSessionId: string | null;
106
132
  toInternalSessionId?: string;
107
133
  error: string;
134
+ /** Records produced before and during the failure. */
135
+ meteringRecords: readonly OperationMeteringRecord[];
136
+ }
137
+ /** Latest context-window observation for the ACTIVE provider thread, or null. */
138
+ | { kind: "context_window_changed"; contextWindow: ContextWindowStatus | null }
139
+ /** Latest cumulative provider-reported cost. Telemetry, never asserted to be an invoice. */
140
+ | { kind: "provider_cost_changed"; providerCost: ProviderCostSnapshot | null }
141
+ /** One immutable record per observed operation, emitted before its turn completes. */
142
+ | { kind: "metering_recorded"; record: OperationMeteringRecord }
143
+ /** A strict mode detected a metering failure; later token-consuming work will reject. */
144
+ | { kind: "metering_blocked"; reason: string }
145
+ | { kind: "metering_unblocked" }
146
+ | {
147
+ kind: "metering_reconciled";
148
+ before: AgentSessionMeteringState;
149
+ after: AgentSessionMeteringState;
150
+ reason: string;
151
+ reference?: string;
152
+ reconciledAt: number;
108
153
  };
109
154
 
155
+ /** A prompt result enriched with the operation's metering record. */
156
+ export interface AgentSessionPromptResult extends PromptResult {
157
+ readonly operationId: string;
158
+ /**
159
+ * The operation's record, or null when the operation never reached the provider.
160
+ *
161
+ * Null happens only for a queued prompt cancelled before dispatch (§16). Such an
162
+ * operation consumed nothing, and minting a record for it would put a fabricated
163
+ * entry in the consumer's ledger — so the field is honestly empty instead.
164
+ */
165
+ readonly metering: OperationMeteringRecord | null;
166
+ }
167
+
110
168
  /** Ordered envelope delivered to every AgentSession subscriber. */
111
169
  export interface AgentSessionNotification {
112
170
  readonly seq: number;
@@ -191,7 +249,11 @@ export interface AgentSessionConfig {
191
249
  adapterId: string;
192
250
  /** Talk over ACP ("normal") or scrape a pty ("degraded"). Default "normal". */
193
251
  mode?: AgentMode;
252
+ /** Runtime-specific launcher shared by normal ACP and degraded PTY modes. */
253
+ launcher?: AgentControllerConfig["launcher"];
254
+ /** @deprecated Use launcher. */
194
255
  execPrefix?: string[];
256
+ /** @deprecated Use launcher and its exact spawnEnv. */
195
257
  env?: Record<string, string>;
196
258
  cwd?: string;
197
259
  /** Default MCP servers bound at session creation/switch, unless a call overrides them. */
@@ -200,6 +262,8 @@ export interface AgentSessionConfig {
200
262
  clientInfo?: { name: string; title?: string; version?: string };
201
263
  /** What we let the agent do through us (terminals, filesystem). All on by default. */
202
264
  clientCapabilities?: AgentControllerConfig["clientCapabilities"];
265
+ /** Client-side ACP implementations; their presence determines advertisement. */
266
+ clientHandlers?: AgentControllerConfig["clientHandlers"];
203
267
  logger?: Logger;
204
268
  /** Raw protocol traffic for debugging — see `AcpClientConfig.wire`. */
205
269
  wire?: (entry: WireEntry) => void;
@@ -230,6 +294,12 @@ export interface AgentSessionConfig {
230
294
  agentSessionId?: string;
231
295
  /** Provider-thread startup intent. Default `{ kind: "new" }`. */
232
296
  providerSession?: ProviderSession;
297
+ /**
298
+ * Token/cost metering policy. Optional: omitting it selects best-effort enforcement
299
+ * with the pinned models.dev catalog and no restored state. Metering is not something a
300
+ * consumer must turn on merely to see protocol facts.
301
+ */
302
+ metering?: MeteringConfig;
233
303
  /**
234
304
  * @deprecated Use `providerSession: { kind: "load", internalSessionId, onFailure }`.
235
305
  * Retains the historical fallback-to-new behavior for compatibility.
@@ -266,6 +336,17 @@ export class AgentSession implements AgentClient, Bridgeable {
266
336
  private readonly listeners = new Set<AgentSessionListener>();
267
337
  private lastStateKey = "";
268
338
  private _internalSessionId: string | null;
339
+ private readonly metering: MeteringEngine;
340
+ private _contextWindow: ContextWindowStatus | null = null;
341
+ private _providerCost: ProviderCostSnapshot | null = null;
342
+ /**
343
+ * A usage update that arrived before the provider thread id was known.
344
+ *
345
+ * A harness may notify immediately after session/new, before that response resolves.
346
+ * Dropping the update would lose the observation; applying it without a thread id would
347
+ * attribute it to nothing. Hold the latest one and attribute it on assignment.
348
+ */
349
+ private pendingUsageUpdate: { update: unknown; sessionId: string | null } | null = null;
269
350
  private _mode: AgentMode;
270
351
  private _cwd?: string;
271
352
  private _title?: string;
@@ -317,10 +398,28 @@ export class AgentSession implements AgentClient, Bridgeable {
317
398
  this._cwd = config.cwd;
318
399
  this._title = config.title;
319
400
  this._internalSessionId = requestedInternalSessionId ?? null;
401
+ this.metering = new MeteringEngine({
402
+ agentSessionId: this.agentSessionId,
403
+ adapterId: config.adapterId,
404
+ enforcement: config.metering?.enforcement ?? "best_effort",
405
+ // Absence selects the pinned catalog; `false` is how a consumer says "no rating".
406
+ pricing: config.metering?.pricing ?? createModelsDevResolver(),
407
+ initialState: config.metering?.initialState,
408
+ ...(config.metering?.counterInterpretation
409
+ ? { counterInterpretation: config.metering.counterInterpretation }
410
+ : {}),
411
+ ...(config.metering?.inferenceSource
412
+ ? { inferenceSource: config.metering.inferenceSource }
413
+ : {}),
414
+ // A thread we are about to create has counters starting at zero; one we load does
415
+ // not, and needs restored state to be attributable.
416
+ createdActiveThread: providerSession.kind === "new",
417
+ });
320
418
  this.controller = new AgentController({
321
419
  adapter: config.adapter,
322
420
  adapterId: config.adapterId,
323
421
  mode: this._mode,
422
+ launcher: config.launcher,
324
423
  execPrefix: config.execPrefix,
325
424
  env: config.env,
326
425
  cwd: config.cwd,
@@ -332,12 +431,16 @@ export class AgentSession implements AgentClient, Bridgeable {
332
431
  defaultPermission: config.defaultPermission,
333
432
  clientInfo: config.clientInfo,
334
433
  clientCapabilities: config.clientCapabilities,
434
+ clientHandlers: config.clientHandlers,
335
435
  logger: config.logger,
336
436
  wire: config.wire,
337
437
  });
338
438
  this.controller.subscribeAvailableCommands((commands) => {
339
439
  this.emit({ kind: "internal_session_commands_changed", commands });
340
440
  });
441
+ this.controller.subscribeUsageUpdate((update, sessionId) => {
442
+ this.applyUsageUpdate(update, sessionId);
443
+ });
341
444
  }
342
445
 
343
446
  /**
@@ -348,13 +451,20 @@ export class AgentSession implements AgentClient, Bridgeable {
348
451
  */
349
452
  static async create(config: AgentSessionConfig): Promise<AgentSession> {
350
453
  const session = new AgentSession(config);
351
- await session.start();
352
- return session;
454
+ try {
455
+ await session.start();
456
+ return session;
457
+ } catch (error) {
458
+ await session.stop().catch(() => {});
459
+ throw error;
460
+ }
353
461
  }
354
462
 
355
463
  private async start(): Promise<void> {
356
464
  const result = await this.controller.start();
357
- this._internalSessionId = result.sessionId || this._internalSessionId;
465
+ // A resumed thread's counters did not start at zero, so it needs restored state to
466
+ // be attributable.
467
+ this.setInternalSessionId(result.sessionId || this._internalSessionId, !result.resumed);
358
468
  await this.persist();
359
469
  await this.appendTranscript({
360
470
  v: 1,
@@ -370,6 +480,72 @@ export class AgentSession implements AgentClient, Bridgeable {
370
480
  get internalSessionId(): string | null {
371
481
  return this._internalSessionId;
372
482
  }
483
+
484
+ /**
485
+ * Latest context-window observation for the ACTIVE provider thread, or null.
486
+ *
487
+ * Context does not aggregate across threads: after a handoff or any other thread
488
+ * replacement this is null until the new thread reports, because the old thread's
489
+ * occupancy says nothing about the new one's.
490
+ */
491
+ /**
492
+ * models.dev provider key for the active route, or null when it cannot be established.
493
+ *
494
+ * Comes from a tested adapter mapping, or — for a harness whose model string is
495
+ * `<provider>/<model>` — from that string. Never guessed: see metering/provider.ts.
496
+ */
497
+ get providerId(): string | null {
498
+ return resolveModelReference(this.adapterId, this.advertisedModel)?.providerId ?? null;
499
+ }
500
+
501
+ /**
502
+ * Model key for catalog lookup, or null.
503
+ *
504
+ * For a harness that advertises `<provider>/<model>`, this is the model half — the
505
+ * provider prefix is routing, not part of the model's name. The raw advertised string
506
+ * remains available through `configOptions`.
507
+ */
508
+ get model(): string | null {
509
+ return resolveModelReference(this.adapterId, this.advertisedModel)?.modelId ?? this.advertisedModel;
510
+ }
511
+
512
+ /** Exactly what the harness advertises, before any provider/model split. */
513
+ get advertisedModel(): string | null {
514
+ return activeModel(this.controller.configOptions);
515
+ }
516
+
517
+ /** Bounded metering state, enforcement policy, and the last operation record. */
518
+ get meteringSnapshot(): AgentSessionMeteringSnapshot {
519
+ const restoration = this.metering.restoration;
520
+ return Object.freeze({
521
+ ...this.metering.currentState,
522
+ enforcement: this.metering.enforcement,
523
+ // Carry the version the restore actually reported. The `state` field is dropped
524
+ // because the snapshot already IS the state; the version is not re-stated literally.
525
+ restoration:
526
+ restoration.status === "restored"
527
+ ? { status: "restored" as const, version: restoration.version }
528
+ : restoration,
529
+ blocked: this.metering.blocked,
530
+ blockedReason: this.metering.blockedReason,
531
+ outstandingReports: this.metering.outstandingReports(this._internalSessionId),
532
+ lastOperation: this.metering.lastOperation,
533
+ });
534
+ }
535
+
536
+ get contextWindow(): ContextWindowStatus | null {
537
+ return this._contextWindow;
538
+ }
539
+
540
+ /**
541
+ * Latest cumulative provider-reported cost for the active thread, or null.
542
+ *
543
+ * Provider telemetry, kept distinct from locally rated cost and never asserted to be an
544
+ * invoice — a subscription harness may report an API-equivalent figure.
545
+ */
546
+ get providerCost(): ProviderCostSnapshot | null {
547
+ return this._providerCost;
548
+ }
373
549
  get mode(): AgentMode {
374
550
  return this._mode;
375
551
  }
@@ -417,8 +593,17 @@ export class AgentSession implements AgentClient, Bridgeable {
417
593
  text: string,
418
594
  handlers?: PromptHandlers,
419
595
  attachments?: Attachment[],
420
- ): Promise<PromptResult> {
421
- return new Promise<PromptResult>((resolve, reject) => {
596
+ ): Promise<AgentSessionPromptResult> {
597
+ return this.enqueuePrompt(text, "prompt", handlers, attachments);
598
+ }
599
+
600
+ private enqueuePrompt(
601
+ text: string,
602
+ operationKind: MeteredOperationKind,
603
+ handlers?: PromptHandlers,
604
+ attachments?: Attachment[],
605
+ ): Promise<AgentSessionPromptResult> {
606
+ return new Promise<AgentSessionPromptResult>((resolve, reject) => {
422
607
  if (this.phase === "stopped") {
423
608
  reject(new Error("AgentSession is stopped"));
424
609
  return;
@@ -426,6 +611,7 @@ export class AgentSession implements AgentClient, Bridgeable {
426
611
  this.queue.push({
427
612
  kind: "prompt",
428
613
  turnId: this.mintTurnId(),
614
+ operationKind,
429
615
  text,
430
616
  handlers,
431
617
  attachments,
@@ -448,7 +634,7 @@ export class AgentSession implements AgentClient, Bridgeable {
448
634
  name: string,
449
635
  input?: string,
450
636
  handlers?: PromptHandlers,
451
- ): Promise<PromptResult> {
637
+ ): Promise<AgentSessionPromptResult> {
452
638
  const command = name.trim();
453
639
  if (!command || command.startsWith("/") || /\s/.test(command)) {
454
640
  return Promise.reject(
@@ -456,7 +642,7 @@ export class AgentSession implements AgentClient, Bridgeable {
456
642
  );
457
643
  }
458
644
  const suffix = input == null || input.length === 0 ? "" : ` ${input}`;
459
- return this.prompt(`/${command}${suffix}`, handlers);
645
+ return this.enqueuePrompt(`/${command}${suffix}`, "internal_command", handlers);
460
646
  }
461
647
 
462
648
  /**
@@ -525,6 +711,9 @@ export class AgentSession implements AgentClient, Bridgeable {
525
711
  const fromInternalSessionId = this._internalSessionId;
526
712
  let toInternalSessionId: string | undefined;
527
713
  let summary: string | undefined;
714
+ // Records accumulate as they complete, so a handoff that fails partway still reports
715
+ // the operations it already paid for.
716
+ const records: OperationMeteringRecord[] = [];
528
717
  this.emit({
529
718
  kind: "handoff_started",
530
719
  handoffId: item.handoffId,
@@ -547,9 +736,16 @@ export class AgentSession implements AgentClient, Bridgeable {
547
736
 
548
737
  if (item.options.summary !== undefined) {
549
738
  if (!item.options.summary.trim()) throw new Error("handoff summary cannot be blank");
739
+ // A supplied summary removes the generation operation entirely, so no
740
+ // `:summary` record is ever minted for it.
550
741
  summary = item.options.summary;
551
742
  } else {
552
- const generated = await this.controller.prompt(HANDOFF_SUMMARY_PROMPT);
743
+ const generated = await this.meteredInternalPrompt(
744
+ `${item.handoffId}:summary`,
745
+ "handoff_summary",
746
+ HANDOFF_SUMMARY_PROMPT,
747
+ records,
748
+ );
553
749
  if (generated.status !== "completed" || !generated.text.trim()) {
554
750
  throw new Error(`handoff summary generation ${generated.status}`);
555
751
  }
@@ -559,7 +755,7 @@ export class AgentSession implements AgentClient, Bridgeable {
559
755
  const created = await this.controller.newSession();
560
756
  if (!created.sessionId) throw new Error("harness returned no session id for handoff");
561
757
  toInternalSessionId = created.sessionId;
562
- this._internalSessionId = toInternalSessionId;
758
+ this.setInternalSessionId(toInternalSessionId);
563
759
  this.emitStateIfChanged();
564
760
  await this.persist();
565
761
 
@@ -567,7 +763,12 @@ export class AgentSession implements AgentClient, Bridgeable {
567
763
  throw new Error("harness did not replace the internal session during handoff");
568
764
  }
569
765
 
570
- const seeded = await this.controller.prompt(continuationPrompt(summary));
766
+ const seeded = await this.meteredInternalPrompt(
767
+ `${item.handoffId}:seed`,
768
+ "handoff_seed",
769
+ continuationPrompt(summary),
770
+ records,
771
+ );
571
772
  if (seeded.status !== "completed") {
572
773
  throw new Error(`handoff continuation seeding ${seeded.status}`);
573
774
  }
@@ -578,6 +779,7 @@ export class AgentSession implements AgentClient, Bridgeable {
578
779
  fromInternalSessionId,
579
780
  toInternalSessionId,
580
781
  summary,
782
+ meteringRecords: Object.freeze([...records]),
581
783
  });
582
784
  await this.appendTranscript({
583
785
  v: 1,
@@ -596,7 +798,7 @@ export class AgentSession implements AgentClient, Bridgeable {
596
798
  // public id and catalog truthful even when continuation seeding subsequently fails.
597
799
  const actualSessionId = this.controller.currentSessionId;
598
800
  if (actualSessionId && actualSessionId !== this._internalSessionId) {
599
- this._internalSessionId = actualSessionId;
801
+ this.setInternalSessionId(actualSessionId);
600
802
  toInternalSessionId = actualSessionId;
601
803
  this.emitStateIfChanged();
602
804
  try {
@@ -623,12 +825,15 @@ export class AgentSession implements AgentClient, Bridgeable {
623
825
  fromInternalSessionId,
624
826
  ...(toInternalSessionId ? { toInternalSessionId } : {}),
625
827
  error,
828
+ meteringRecords: Object.freeze([...records]),
626
829
  });
627
- throw err;
830
+ // A rejected handoff cannot return a HandoffResult, but the summary/seed prompts it
831
+ // already ran consumed real tokens; their records travel on the error.
832
+ throw new AgentSessionHandoffError(item.handoffId, records, err);
628
833
  }
629
834
  }
630
835
 
631
- private async runPrompt(item: PromptQueueItem): Promise<PromptResult> {
836
+ private async runPrompt(item: PromptQueueItem): Promise<AgentSessionPromptResult> {
632
837
  this.beginTurn(item.turnId);
633
838
  await this.appendTranscript({
634
839
  v: 1,
@@ -663,6 +868,18 @@ export class AgentSession implements AgentClient, Bridgeable {
663
868
  },
664
869
  };
665
870
 
871
+ // Opened BEFORE dispatch so a strict mode fails preflight rather than after the
872
+ // provider has already been paid, and so the price in force at start is what applies.
873
+ const operation = await this.metering.open({
874
+ operationId: item.turnId,
875
+ operationKind: item.operationKind,
876
+ internalSessionId: this._internalSessionId,
877
+ providerId: this.providerId,
878
+ model: this.model,
879
+ degraded: this.controller.isDegraded,
880
+ });
881
+
882
+ let closed: OperationMeteringRecord | null = null;
666
883
  try {
667
884
  const res = await this.controller.prompt(item.text, wrappedHandlers, item.attachments);
668
885
  // Before the assistant msg: `msg` delimits a turn, so anything still open has to
@@ -672,7 +889,17 @@ export class AgentSession implements AgentClient, Bridgeable {
672
889
  this._title = item.text.trim().replace(/\s+/g, " ").slice(0, 60);
673
890
  }
674
891
  // A session may have been created lazily on first prompt (degraded has none).
675
- this._internalSessionId = this.controller.currentSessionId ?? this._internalSessionId;
892
+ this.setInternalSessionId(this.controller.currentSessionId ?? this._internalSessionId);
893
+ // Metering closes BEFORE local persistence. The provider has already been paid and
894
+ // has already told us what it charged; letting a transcript or catalog write failure
895
+ // send us down the catch path would discard usage we are holding and, in a strict
896
+ // mode, block the session over a local disk problem.
897
+ //
898
+ // `closed` then guards the catch path. Closing twice would accrue the operation
899
+ // twice and emit a second record for it — double-counting tokens and cost, which is
900
+ // a worse failure than the one closing early prevents.
901
+ const record = await this.closeOperation(operation, res.status, res.usage);
902
+ closed = record;
676
903
  await this.persist();
677
904
  await this.appendTranscript({
678
905
  v: 1,
@@ -685,7 +912,7 @@ export class AgentSession implements AgentClient, Bridgeable {
685
912
  stopReason: res.stopReason,
686
913
  status: res.status,
687
914
  });
688
- return res;
915
+ return Object.freeze({ ...res, operationId: item.turnId, metering: record });
689
916
  } catch (err) {
690
917
  // Easy to miss, and the whole point of R4: a turn that died mid-tool still records
691
918
  // what it was doing, at its real status.
@@ -707,10 +934,122 @@ export class AgentSession implements AgentClient, Bridgeable {
707
934
  stopReason: "error",
708
935
  status: "error",
709
936
  });
937
+ // A failed operation may still have consumed tokens, so its record has to survive
938
+ // the rejection rather than only reaching event subscribers.
939
+ // Already metered: the failure happened after the operation closed (a transcript or
940
+ // catalog write), so the record stands and must not be minted a second time.
941
+ const record = closed ?? (await this.closeOperation(operation, "error", null, String(err)));
942
+ throw new AgentSessionOperationError(item.turnId, record, err);
943
+ }
944
+ }
945
+
946
+ /**
947
+ * Replace metering state after an out-of-band reconciliation, and clear any block.
948
+ *
949
+ * The recovery path for a strict mode that stopped on a metering failure, without the
950
+ * unrecorded "assume zero" reset §12 rejects. Deliberately mints no operation record:
951
+ * the adjustment is an accounting correction, not provider usage, and pretending
952
+ * otherwise would put a fabricated operation in the consumer's ledger.
953
+ */
954
+ async reconcileMetering(reconciliation: MeteringReconciliation): Promise<{
955
+ before: AgentSessionMeteringState;
956
+ after: AgentSessionMeteringState;
957
+ }> {
958
+ if (this.isBusy || this.queue.length > 0) {
959
+ throw new Error("reconcileMetering requires an idle session with no queued operations");
960
+ }
961
+ if (!reconciliation.reason?.trim()) {
962
+ throw new Error("reconcileMetering requires a non-blank reason");
963
+ }
964
+ const restoration = restoreMeteringState(reconciliation.state, this.agentSessionId);
965
+ if (restoration.status !== "restored") {
966
+ throw new Error(
967
+ `reconcileMetering state rejected: ${
968
+ restoration.status === "ignored" ? restoration.reason : "no state supplied"
969
+ }`,
970
+ );
971
+ }
972
+ const wasBlocked = this.metering.blocked;
973
+ // Validated first: state is replaced atomically or not at all.
974
+ const { before } = this.metering.reconcile(restoration.state);
975
+ const after = this.metering.currentState;
976
+ this.emit({
977
+ kind: "metering_reconciled",
978
+ before,
979
+ after,
980
+ reason: reconciliation.reason,
981
+ ...(reconciliation.reference ? { reference: reconciliation.reference } : {}),
982
+ reconciledAt: Date.now(),
983
+ });
984
+ if (wasBlocked) this.emit({ kind: "metering_unblocked" });
985
+ return { before, after };
986
+ }
987
+
988
+ /**
989
+ * Run a library-internal prompt through the same metering primitive as a user prompt.
990
+ *
991
+ * Handoff summary generation and continuation seeding consume real tokens. Calling
992
+ * `controller.prompt()` directly for them would spend a consumer's money invisibly, so
993
+ * that path is not permitted any more (§16).
994
+ *
995
+ * Operation ids are deterministic children of the handoff id rather than freshly
996
+ * minted, so a consumer can tie both halves back to the handoff that caused them.
997
+ */
998
+ private async meteredInternalPrompt(
999
+ operationId: string,
1000
+ operationKind: MeteredOperationKind,
1001
+ text: string,
1002
+ records: OperationMeteringRecord[],
1003
+ ): Promise<PromptResult> {
1004
+ const operation = await this.metering.open({
1005
+ operationId,
1006
+ operationKind,
1007
+ internalSessionId: this._internalSessionId,
1008
+ providerId: this.providerId,
1009
+ model: this.model,
1010
+ degraded: this.controller.isDegraded,
1011
+ });
1012
+ let closed = false;
1013
+ try {
1014
+ const result = await this.controller.prompt(text);
1015
+ records.push(await this.closeOperation(operation, result.status, result.usage));
1016
+ closed = true;
1017
+ return result;
1018
+ } catch (err) {
1019
+ if (!closed) {
1020
+ records.push(await this.closeOperation(operation, "error", null, String(err)));
1021
+ }
710
1022
  throw err;
711
1023
  }
712
1024
  }
713
1025
 
1026
+ /**
1027
+ * Close a rating unit, emit its record, and surface a strict-mode block.
1028
+ *
1029
+ * `contextAfter`/`providerCostAfter` are the latest observations seen by completion.
1030
+ * ACP gives no ordering guarantee, so neither is asserted to describe THIS operation.
1031
+ */
1032
+ private async closeOperation(
1033
+ operation: OpenOperation,
1034
+ outcome: "completed" | "cancelled" | "error",
1035
+ reportedCumulative: TokenUsage | null,
1036
+ usageFailureReason?: string,
1037
+ ): Promise<OperationMeteringRecord> {
1038
+ const wasBlocked = this.metering.blocked;
1039
+ const record = await this.metering.close(operation, {
1040
+ outcome,
1041
+ reportedCumulative,
1042
+ ...(usageFailureReason ? { usageFailureReason } : {}),
1043
+ contextAfter: this._contextWindow,
1044
+ providerCostAfter: this._providerCost,
1045
+ });
1046
+ this.emit({ kind: "metering_recorded", record });
1047
+ if (!wasBlocked && this.metering.blocked) {
1048
+ this.emit({ kind: "metering_blocked", reason: this.metering.blockedReason ?? "unknown" });
1049
+ }
1050
+ return record;
1051
+ }
1052
+
714
1053
  // --- activity ----------------------------------------------------------------
715
1054
  /**
716
1055
  * Full state of the turn IN FLIGHT, for a subscriber that joins mid-turn: send these
@@ -804,12 +1143,16 @@ export class AgentSession implements AgentClient, Bridgeable {
804
1143
  const dropped = this.queue.splice(0);
805
1144
  for (const item of dropped) {
806
1145
  if (item.kind === "prompt") {
1146
+ // Cancelled before dispatch: nothing was sent, so nothing was consumed and no
1147
+ // metering record is minted (§16).
807
1148
  item.resolve({
808
1149
  text: "",
809
1150
  messages: Object.freeze([]),
810
1151
  stopReason: "cancelled",
811
1152
  status: "cancelled",
812
1153
  usage: null,
1154
+ operationId: item.turnId,
1155
+ metering: null,
813
1156
  });
814
1157
  } else {
815
1158
  item.reject(new Error("handoff cancelled before it started"));
@@ -835,7 +1178,8 @@ export class AgentSession implements AgentClient, Bridgeable {
835
1178
  async setMode(mode: AgentMode): Promise<ConnectResult> {
836
1179
  const result = await this.controller.setMode(mode);
837
1180
  this._mode = this.controller.currentMode;
838
- this._internalSessionId = result.sessionId || null; // the ACP/harness session changes on swap
1181
+ // The ACP/harness session changes on swap, so context/cost reset with it.
1182
+ this.setInternalSessionId(result.sessionId || null);
839
1183
  await this.persist();
840
1184
  return result;
841
1185
  }
@@ -929,6 +1273,76 @@ export class AgentSession implements AgentClient, Bridgeable {
929
1273
  await this.transcriptWrite;
930
1274
  }
931
1275
 
1276
+ /**
1277
+ * Replace the active provider thread id, resetting observations that belong to it.
1278
+ *
1279
+ * Every reassignment goes through here so the reset cannot be forgotten at one of the
1280
+ * several sites that swap threads (handoff, mode swap, load/resume, lazy creation).
1281
+ * Carrying a stale context window across a thread change would misreport the new
1282
+ * thread's occupancy as the old thread's.
1283
+ */
1284
+ private setInternalSessionId(next: string | null, created = true): void {
1285
+ if (next === this._internalSessionId) return;
1286
+ this._internalSessionId = next;
1287
+ // The new thread's counters restart, so the old baseline no longer describes them.
1288
+ this.metering.onThreadReplaced(next, created);
1289
+ if (this._contextWindow !== null) {
1290
+ this._contextWindow = null;
1291
+ this.emit({ kind: "context_window_changed", contextWindow: null });
1292
+ }
1293
+ if (this._providerCost !== null) {
1294
+ this._providerCost = null;
1295
+ this.emit({ kind: "provider_cost_changed", providerCost: null });
1296
+ }
1297
+ const pending = this.pendingUsageUpdate;
1298
+ this.pendingUsageUpdate = null;
1299
+ // An update buffered before the thread was named belongs to it only if it named the
1300
+ // same thread, or named none at all.
1301
+ if (pending && next && (!pending.sessionId || pending.sessionId === next)) {
1302
+ this.applyUsageUpdate(pending.update, pending.sessionId);
1303
+ }
1304
+ }
1305
+
1306
+ /**
1307
+ * Apply a raw ACP `usage_update`.
1308
+ *
1309
+ * Updates naming a different provider thread are ignored: ACP gives no ordering
1310
+ * guarantee, so a late notification from a replaced thread can arrive after the swap and
1311
+ * must not overwrite current state.
1312
+ */
1313
+ private applyUsageUpdate(update: unknown, sessionId: string | null): void {
1314
+ const active = this._internalSessionId;
1315
+ if (!active) {
1316
+ this.pendingUsageUpdate = { update, sessionId };
1317
+ return;
1318
+ }
1319
+ if (sessionId && sessionId !== active) return;
1320
+
1321
+ const observedAt = Date.now();
1322
+ const context = parseContextWindow(update, active, observedAt);
1323
+ if (context && contextWindowChanged(this._contextWindow, context)) {
1324
+ this._contextWindow = context;
1325
+ this.emit({ kind: "context_window_changed", contextWindow: context });
1326
+ }
1327
+
1328
+ const cost = parseProviderCost(update);
1329
+ if (cost.kind === "invalid") {
1330
+ // Provider cost is optional telemetry: malformed data is dropped with a diagnostic
1331
+ // and never implicitly clears a previously valid value.
1332
+ this.log.warn("provider_cost_invalid", { reason: cost.reason });
1333
+ return;
1334
+ }
1335
+ if (cost.kind === "unchanged") return;
1336
+ const next: ProviderCostSnapshot | null =
1337
+ cost.kind === "cleared"
1338
+ ? null
1339
+ : Object.freeze({ internalSessionId: active, cumulative: cost.cumulative, observedAt });
1340
+ if (providerCostChanged(this._providerCost, next)) {
1341
+ this._providerCost = next;
1342
+ this.emit({ kind: "provider_cost_changed", providerCost: next });
1343
+ }
1344
+ }
1345
+
932
1346
  /** Emit only when a field in the public snapshot changed. */
933
1347
  private emitStateIfChanged(): void {
934
1348
  const state = this.state;