@qlairoslabs/acp-client 0.5.0 → 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;
@@ -236,6 +294,12 @@ export interface AgentSessionConfig {
236
294
  agentSessionId?: string;
237
295
  /** Provider-thread startup intent. Default `{ kind: "new" }`. */
238
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;
239
303
  /**
240
304
  * @deprecated Use `providerSession: { kind: "load", internalSessionId, onFailure }`.
241
305
  * Retains the historical fallback-to-new behavior for compatibility.
@@ -272,6 +336,17 @@ export class AgentSession implements AgentClient, Bridgeable {
272
336
  private readonly listeners = new Set<AgentSessionListener>();
273
337
  private lastStateKey = "";
274
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;
275
350
  private _mode: AgentMode;
276
351
  private _cwd?: string;
277
352
  private _title?: string;
@@ -323,6 +398,23 @@ export class AgentSession implements AgentClient, Bridgeable {
323
398
  this._cwd = config.cwd;
324
399
  this._title = config.title;
325
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
+ });
326
418
  this.controller = new AgentController({
327
419
  adapter: config.adapter,
328
420
  adapterId: config.adapterId,
@@ -346,6 +438,9 @@ export class AgentSession implements AgentClient, Bridgeable {
346
438
  this.controller.subscribeAvailableCommands((commands) => {
347
439
  this.emit({ kind: "internal_session_commands_changed", commands });
348
440
  });
441
+ this.controller.subscribeUsageUpdate((update, sessionId) => {
442
+ this.applyUsageUpdate(update, sessionId);
443
+ });
349
444
  }
350
445
 
351
446
  /**
@@ -367,7 +462,9 @@ export class AgentSession implements AgentClient, Bridgeable {
367
462
 
368
463
  private async start(): Promise<void> {
369
464
  const result = await this.controller.start();
370
- 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);
371
468
  await this.persist();
372
469
  await this.appendTranscript({
373
470
  v: 1,
@@ -383,6 +480,72 @@ export class AgentSession implements AgentClient, Bridgeable {
383
480
  get internalSessionId(): string | null {
384
481
  return this._internalSessionId;
385
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
+ }
386
549
  get mode(): AgentMode {
387
550
  return this._mode;
388
551
  }
@@ -430,8 +593,17 @@ export class AgentSession implements AgentClient, Bridgeable {
430
593
  text: string,
431
594
  handlers?: PromptHandlers,
432
595
  attachments?: Attachment[],
433
- ): Promise<PromptResult> {
434
- 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) => {
435
607
  if (this.phase === "stopped") {
436
608
  reject(new Error("AgentSession is stopped"));
437
609
  return;
@@ -439,6 +611,7 @@ export class AgentSession implements AgentClient, Bridgeable {
439
611
  this.queue.push({
440
612
  kind: "prompt",
441
613
  turnId: this.mintTurnId(),
614
+ operationKind,
442
615
  text,
443
616
  handlers,
444
617
  attachments,
@@ -461,7 +634,7 @@ export class AgentSession implements AgentClient, Bridgeable {
461
634
  name: string,
462
635
  input?: string,
463
636
  handlers?: PromptHandlers,
464
- ): Promise<PromptResult> {
637
+ ): Promise<AgentSessionPromptResult> {
465
638
  const command = name.trim();
466
639
  if (!command || command.startsWith("/") || /\s/.test(command)) {
467
640
  return Promise.reject(
@@ -469,7 +642,7 @@ export class AgentSession implements AgentClient, Bridgeable {
469
642
  );
470
643
  }
471
644
  const suffix = input == null || input.length === 0 ? "" : ` ${input}`;
472
- return this.prompt(`/${command}${suffix}`, handlers);
645
+ return this.enqueuePrompt(`/${command}${suffix}`, "internal_command", handlers);
473
646
  }
474
647
 
475
648
  /**
@@ -538,6 +711,9 @@ export class AgentSession implements AgentClient, Bridgeable {
538
711
  const fromInternalSessionId = this._internalSessionId;
539
712
  let toInternalSessionId: string | undefined;
540
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[] = [];
541
717
  this.emit({
542
718
  kind: "handoff_started",
543
719
  handoffId: item.handoffId,
@@ -560,9 +736,16 @@ export class AgentSession implements AgentClient, Bridgeable {
560
736
 
561
737
  if (item.options.summary !== undefined) {
562
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.
563
741
  summary = item.options.summary;
564
742
  } else {
565
- 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
+ );
566
749
  if (generated.status !== "completed" || !generated.text.trim()) {
567
750
  throw new Error(`handoff summary generation ${generated.status}`);
568
751
  }
@@ -572,7 +755,7 @@ export class AgentSession implements AgentClient, Bridgeable {
572
755
  const created = await this.controller.newSession();
573
756
  if (!created.sessionId) throw new Error("harness returned no session id for handoff");
574
757
  toInternalSessionId = created.sessionId;
575
- this._internalSessionId = toInternalSessionId;
758
+ this.setInternalSessionId(toInternalSessionId);
576
759
  this.emitStateIfChanged();
577
760
  await this.persist();
578
761
 
@@ -580,7 +763,12 @@ export class AgentSession implements AgentClient, Bridgeable {
580
763
  throw new Error("harness did not replace the internal session during handoff");
581
764
  }
582
765
 
583
- 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
+ );
584
772
  if (seeded.status !== "completed") {
585
773
  throw new Error(`handoff continuation seeding ${seeded.status}`);
586
774
  }
@@ -591,6 +779,7 @@ export class AgentSession implements AgentClient, Bridgeable {
591
779
  fromInternalSessionId,
592
780
  toInternalSessionId,
593
781
  summary,
782
+ meteringRecords: Object.freeze([...records]),
594
783
  });
595
784
  await this.appendTranscript({
596
785
  v: 1,
@@ -609,7 +798,7 @@ export class AgentSession implements AgentClient, Bridgeable {
609
798
  // public id and catalog truthful even when continuation seeding subsequently fails.
610
799
  const actualSessionId = this.controller.currentSessionId;
611
800
  if (actualSessionId && actualSessionId !== this._internalSessionId) {
612
- this._internalSessionId = actualSessionId;
801
+ this.setInternalSessionId(actualSessionId);
613
802
  toInternalSessionId = actualSessionId;
614
803
  this.emitStateIfChanged();
615
804
  try {
@@ -636,12 +825,15 @@ export class AgentSession implements AgentClient, Bridgeable {
636
825
  fromInternalSessionId,
637
826
  ...(toInternalSessionId ? { toInternalSessionId } : {}),
638
827
  error,
828
+ meteringRecords: Object.freeze([...records]),
639
829
  });
640
- 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);
641
833
  }
642
834
  }
643
835
 
644
- private async runPrompt(item: PromptQueueItem): Promise<PromptResult> {
836
+ private async runPrompt(item: PromptQueueItem): Promise<AgentSessionPromptResult> {
645
837
  this.beginTurn(item.turnId);
646
838
  await this.appendTranscript({
647
839
  v: 1,
@@ -676,6 +868,18 @@ export class AgentSession implements AgentClient, Bridgeable {
676
868
  },
677
869
  };
678
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;
679
883
  try {
680
884
  const res = await this.controller.prompt(item.text, wrappedHandlers, item.attachments);
681
885
  // Before the assistant msg: `msg` delimits a turn, so anything still open has to
@@ -685,7 +889,17 @@ export class AgentSession implements AgentClient, Bridgeable {
685
889
  this._title = item.text.trim().replace(/\s+/g, " ").slice(0, 60);
686
890
  }
687
891
  // A session may have been created lazily on first prompt (degraded has none).
688
- 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;
689
903
  await this.persist();
690
904
  await this.appendTranscript({
691
905
  v: 1,
@@ -698,7 +912,7 @@ export class AgentSession implements AgentClient, Bridgeable {
698
912
  stopReason: res.stopReason,
699
913
  status: res.status,
700
914
  });
701
- return res;
915
+ return Object.freeze({ ...res, operationId: item.turnId, metering: record });
702
916
  } catch (err) {
703
917
  // Easy to miss, and the whole point of R4: a turn that died mid-tool still records
704
918
  // what it was doing, at its real status.
@@ -720,10 +934,122 @@ export class AgentSession implements AgentClient, Bridgeable {
720
934
  stopReason: "error",
721
935
  status: "error",
722
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
+ }
723
1022
  throw err;
724
1023
  }
725
1024
  }
726
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
+
727
1053
  // --- activity ----------------------------------------------------------------
728
1054
  /**
729
1055
  * Full state of the turn IN FLIGHT, for a subscriber that joins mid-turn: send these
@@ -817,12 +1143,16 @@ export class AgentSession implements AgentClient, Bridgeable {
817
1143
  const dropped = this.queue.splice(0);
818
1144
  for (const item of dropped) {
819
1145
  if (item.kind === "prompt") {
1146
+ // Cancelled before dispatch: nothing was sent, so nothing was consumed and no
1147
+ // metering record is minted (§16).
820
1148
  item.resolve({
821
1149
  text: "",
822
1150
  messages: Object.freeze([]),
823
1151
  stopReason: "cancelled",
824
1152
  status: "cancelled",
825
1153
  usage: null,
1154
+ operationId: item.turnId,
1155
+ metering: null,
826
1156
  });
827
1157
  } else {
828
1158
  item.reject(new Error("handoff cancelled before it started"));
@@ -848,7 +1178,8 @@ export class AgentSession implements AgentClient, Bridgeable {
848
1178
  async setMode(mode: AgentMode): Promise<ConnectResult> {
849
1179
  const result = await this.controller.setMode(mode);
850
1180
  this._mode = this.controller.currentMode;
851
- 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);
852
1183
  await this.persist();
853
1184
  return result;
854
1185
  }
@@ -942,6 +1273,76 @@ export class AgentSession implements AgentClient, Bridgeable {
942
1273
  await this.transcriptWrite;
943
1274
  }
944
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
+
945
1346
  /** Emit only when a field in the public snapshot changed. */
946
1347
  private emitStateIfChanged(): void {
947
1348
  const state = this.state;