@muse-code/sdk 1.4.20 → 1.4.23

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.
@@ -27,7 +27,7 @@ import { ApprovalRouter } from "./approval.js";
27
27
  import { TurnSubmitter } from "./turn-submit.js";
28
28
  import { GapFiller } from "./gap-fill.js";
29
29
  import { isAbnormalHostDeath, isItemInProgress, MuseHostDiedError, survivesHostDeath, } from "./host-death.js";
30
- import { MuseForeignSessionError, MuseSessionDiscardedError } from "../errors.js";
30
+ import { MuseCapabilityNotGrantedError, MuseForeignSessionError, MuseSessionDiscardedError, } from "../errors.js";
31
31
  import { PushStream, TurnHandle } from "./turn-handle.js";
32
32
  import { runTurn } from "./run.js";
33
33
  /**
@@ -69,6 +69,69 @@ const NO_IO = Promise.resolve([]);
69
69
  * @internal
70
70
  */
71
71
  export const pumpDropsApplyResults = Symbol("Session.pumpDropsApplyResults");
72
+ /**
73
+ * Frames `MuseClient` builds from a re-sent server request (`approval/request`,
74
+ * `userInput/request`). They carry the cursor of the event that OPENED the
75
+ * request, older than what the session has folded, so they never move the
76
+ * cursor `reload()` resumes from.
77
+ */
78
+ const serverRequestFrames = new WeakSet();
79
+ /** @internal Mark `frame` as built from a re-sent server request; see {@link serverRequestFrames}. */
80
+ export function serverRequestFrame(frame) {
81
+ serverRequestFrames.add(frame);
82
+ return frame;
83
+ }
84
+ /**
85
+ * Module-private friend seam (never on the package barrel): `MuseClient`
86
+ * hands each session its handshake's grants, which `reload()`'s `config` is
87
+ * checked against (FR-79107-3). A session given none has no handshake on
88
+ * record and refuses a config naming servers, as such a client does.
89
+ *
90
+ * @internal
91
+ */
92
+ export const grantedCapabilities = Symbol("Session.grantedCapabilities");
93
+ /**
94
+ * The `config` to forward, or a typed refusal before anything is sent
95
+ * (FR-79107-3). Per-session MCP servers need the `sessionMcp` grant in the
96
+ * handshake (`spawn` requests it; a caller's own handshake must request it
97
+ * too); with no handshake on record it cannot be shown. A config naming no
98
+ * server needs no grant, as on the host (ADR 32760 D3).
99
+ *
100
+ * @internal Shared with `MuseClient`'s open verbs.
101
+ */
102
+ export function forwardedConfig(method, config, granted) {
103
+ if (config.mcpServers == null || Object.keys(config.mcpServers).length === 0)
104
+ return config;
105
+ if (granted?.includes("sessionMcp") === true)
106
+ return config;
107
+ throw new MuseCapabilityNotGrantedError("sessionMcp", method, "config.mcpServers needs the sessionMcp grant, which this connection's handshake does not hold (MuseClient.spawn requests it; a host withholds it when per-session MCP is turned off)");
108
+ }
109
+ /**
110
+ * The resume cursor a frame carries, if any: a view notification's
111
+ * `viewCursor`. A frame built from a re-sent server request carries the
112
+ * older cursor that opened it, and `session/statusChanged`'s cursor is not a
113
+ * resume cursor (tdd SS4.6.10), so neither moves where `reload()` resumes.
114
+ */
115
+ function resumeCursorOf(frame) {
116
+ if (serverRequestFrames.has(frame) || frame.method === "session/statusChanged") {
117
+ return undefined;
118
+ }
119
+ const cursor = frame.params?.viewCursor;
120
+ return typeof cursor === "string" ? cursor : undefined;
121
+ }
122
+ /**
123
+ * The resume result, or a `ProtocolError` when the reply names no session: a
124
+ * reply the SDK cannot use (#97920), not a `TypeError` from reading it.
125
+ *
126
+ * @internal Shared with `MuseClient`'s open path.
127
+ */
128
+ export function resumeResultOf(raw) {
129
+ const session = raw.session;
130
+ if (typeof session?.sessionId !== "string") {
131
+ throw new ProtocolError("session/resume replied without a session");
132
+ }
133
+ return raw;
134
+ }
72
135
  /**
73
136
  * Module-private friend seam (never on the package barrel): `Session.run`'s
74
137
  * abort takes a queued turn back under one `commandId` and sends that same
@@ -77,6 +140,36 @@ export const pumpDropsApplyResults = Symbol("Session.pumpDropsApplyResults");
77
140
  * @internal
78
141
  */
79
142
  export const resendableUnqueue = Symbol("Session.resendableUnqueue");
143
+ /**
144
+ * Module-private friend seam (never on the package barrel): `MuseClient`
145
+ * calls it once its orderly `close()` has shut the host down, which reports
146
+ * no death to the session, so the `events()` streams end here instead.
147
+ *
148
+ * @internal
149
+ */
150
+ export const endEventStreams = Symbol("Session.endEventStreams");
151
+ /**
152
+ * Module-private friend seam (never on the package barrel): `MuseClient`
153
+ * installs how a session follows a sub-agent's session. Following routes the
154
+ * child session's events to `forward` and returns how to stop.
155
+ *
156
+ * @internal
157
+ */
158
+ export const followsSubagents = Symbol("Session.followsSubagents");
159
+ /**
160
+ * Module-private test seam: how many sub-agent follows this session holds,
161
+ * so a test can prove a stopped follow keeps no child fold alive.
162
+ *
163
+ * @internal
164
+ */
165
+ export const followedSubagentCount = Symbol("Session.followedSubagentCount");
166
+ /**
167
+ * Module-private friend seam: `MuseClient` marks the internal session that
168
+ * folds a followed sub-agent's events, handing each one to the parent.
169
+ *
170
+ * @internal
171
+ */
172
+ export const forwardsEvents = Symbol("Session.forwardsEvents");
80
173
  /**
81
174
  * One conversation with the agent.
82
175
  *
@@ -110,6 +203,27 @@ export class Session {
110
203
  #discharge;
111
204
  /** Set on a durable abnormal death, so late handles inherit the rejection. */
112
205
  #deathError;
206
+ /** The cursor of the last view notification folded, else the opening's head: where `reload()` resumes. */
207
+ #viewCursor;
208
+ /** The in-flight `reload()`, shared by concurrent calls. */
209
+ #reloading;
210
+ /** Set through {@link grantedCapabilities} by `MuseClient`. */
211
+ #granted;
212
+ /**
213
+ * Cursors that reached this session since `reload()` sent its resume, so a
214
+ * repeat is dropped: seeded with the frames a running gap fill holds, then
215
+ * every frame applied, held or folded (a page's included). Cleared by the
216
+ * first new cursor after the reply: the repeats (the replay, then the live
217
+ * stream's copy of the same window) come before it. Bounded by the replay
218
+ * and the fill.
219
+ */
220
+ #replayed;
221
+ #replayAnswered = false;
222
+ /**
223
+ * Set when a reload's reply was not a cursor suffix: the host then streams
224
+ * from a newer head, so the fold has a gap no later reload can fill.
225
+ */
226
+ #reloadGap = false;
113
227
  #turns = new Map();
114
228
  /**
115
229
  * `item/delta` frames whose item the fold does not hold yet. The store
@@ -122,7 +236,17 @@ export class Session {
122
236
  */
123
237
  #unattributedDeltas = new Map();
124
238
  /** The live `events()` streams, fed by every folded event. */
125
- #eventStreams = new Set();
239
+ #eventStreams = new Map();
240
+ /** Set by {@link endEventStreams}: the client closed, so a later stream ends at once. */
241
+ #eventsEnded = false;
242
+ /** The `events({ subagents: true })` streams among them, also fed each followed sub-agent's events. */
243
+ #subagentStreams = new Set();
244
+ /** Set through {@link followsSubagents} by `MuseClient`. */
245
+ #subagentFollower;
246
+ /** How to stop following each sub-agent, keyed by its `subagent` item id. */
247
+ #followedSubagents = new Map();
248
+ /** Set through {@link forwardsEvents} on a sub-agent's internal session. */
249
+ #forwardEvents;
126
250
  /** Set through {@link pumpDropsApplyResults} by `MuseClient`. */
127
251
  #applyResultsDropped = false;
128
252
  /** This session's own `unqueue()` calls awaiting their ack, counted per turn id. */
@@ -180,9 +304,21 @@ export class Session {
180
304
  [pumpDropsApplyResults]() {
181
305
  this.#applyResultsDropped = true;
182
306
  }
307
+ /** @internal See {@link followsSubagents}. */
308
+ [followsSubagents](follower) {
309
+ this.#subagentFollower = follower;
310
+ }
311
+ /** @internal See {@link followedSubagentCount}. */
312
+ [followedSubagentCount]() {
313
+ return this.#followedSubagents.size;
314
+ }
315
+ /** @internal See {@link forwardsEvents}. */
316
+ [forwardsEvents](forward) {
317
+ this.#forwardEvents = forward;
318
+ }
183
319
  /** Yield one folded event to every live `events()` stream. */
184
320
  #emit(frame, outcome) {
185
- if (this.#eventStreams.size === 0)
321
+ if (this.#eventStreams.size === 0 && this.#forwardEvents === undefined)
186
322
  return;
187
323
  const fold = outcome.fold;
188
324
  // The item as of THIS event: the store keeps one object per revision, so
@@ -191,8 +327,48 @@ export class Session {
191
327
  ? this.#fold.items.get(fold.outcome.itemId)
192
328
  : undefined;
193
329
  const event = item === undefined ? { frame, outcome } : { frame, item, outcome };
194
- for (const stream of this.#eventStreams)
330
+ for (const stream of this.#eventStreams.keys())
195
331
  stream.push(event);
332
+ this.#forwardEvents?.(event);
333
+ if (item?.kind === "subagent" && this.#subagentStreams.size > 0)
334
+ this.#followSubagent(item);
335
+ }
336
+ /**
337
+ * Follow a `subagent` item's session while it runs, stop when it ends. It
338
+ * runs while `inProgress` with a `childSessionId` (present once the child's
339
+ * start is attested); nested sub-agents' items are on this view too.
340
+ */
341
+ #followSubagent(item) {
342
+ const followed = this.#followedSubagents.get(item.itemId);
343
+ const child = item.status === "inProgress" ? item.childSessionId : undefined;
344
+ if (child == null || item.subagentId == null) {
345
+ // Finish, not stop: each session drains to the connection on its own, so
346
+ // the child's last steps can arrive after its item ended. Kept in the
347
+ // map so the last stream closing or a host death still stops it now.
348
+ followed?.finish();
349
+ return;
350
+ }
351
+ if (followed !== undefined || this.#subagentFollower === undefined)
352
+ return;
353
+ const tag = { itemId: item.itemId, subagentId: item.subagentId, childSessionId: child };
354
+ const itemId = item.itemId;
355
+ const follow = this.#subagentFollower(child, (event) => {
356
+ const tagged = { ...event, subagent: tag };
357
+ for (const stream of this.#subagentStreams)
358
+ stream.push(tagged);
359
+ },
360
+ // A stopped follow leaves the map, so its child fold is not kept alive.
361
+ () => {
362
+ if (this.#followedSubagents.get(itemId) === follow)
363
+ this.#followedSubagents.delete(itemId);
364
+ });
365
+ this.#followedSubagents.set(itemId, follow);
366
+ }
367
+ #unfollowSubagents() {
368
+ const follows = [...this.#followedSubagents.values()];
369
+ this.#followedSubagents.clear();
370
+ for (const follow of follows)
371
+ follow.stop();
196
372
  }
197
373
  /**
198
374
  * Fold one frame an SS4.8 fill splices in, and yield it. Its retirements
@@ -202,6 +378,30 @@ export class Session {
202
378
  const fold = this.#foldAndRoute(frame, into);
203
379
  this.#emit(frame, { fold, io: NO_IO, retirements: [] });
204
380
  }
381
+ /** @internal See {@link grantedCapabilities}. */
382
+ [grantedCapabilities](granted) {
383
+ this.#granted = granted;
384
+ }
385
+ /** @internal See {@link endEventStreams}. */
386
+ [endEventStreams]() {
387
+ this.#eventsEnded = true;
388
+ this.#finishEventStreams((stream) => stream.end());
389
+ }
390
+ /**
391
+ * End or fail every live stream, drop its abort listener and stop following
392
+ * sub-agents: `end()` and `fail()` skip the stream's own cleanup, which only
393
+ * `return()` runs, and a listener left on a long-lived signal would keep this
394
+ * session alive.
395
+ */
396
+ #finishEventStreams(finish) {
397
+ for (const [stream, unlisten] of this.#eventStreams) {
398
+ finish(stream);
399
+ unlisten();
400
+ }
401
+ this.#eventStreams.clear();
402
+ this.#subagentStreams.clear();
403
+ this.#unfollowSubagents();
404
+ }
205
405
  /** @internal See {@link resendableUnqueue}: each call of the result sends the same reclaim. */
206
406
  [resendableUnqueue](turnId) {
207
407
  const commandId = this.#requireLiveConnection("unqueue").mintCommandId();
@@ -225,6 +425,7 @@ export class Session {
225
425
  this.#fold = new SessionFold(options.extensions);
226
426
  this.#discarded = options.discarded;
227
427
  this.opening = options.opening;
428
+ this.#viewCursor = options.opening?.result.viewCursor;
228
429
  this.#pending = new PendingCommandSet(options.discarded === undefined
229
430
  ? undefined
230
431
  : { discardedCommandIds: options.discarded.commandIds });
@@ -265,11 +466,25 @@ export class Session {
265
466
  get knownTurnCount() {
266
467
  return this.#turns.size;
267
468
  }
469
+ /**
470
+ * How many `events()` streams this session still feeds: a stream ended by
471
+ * `break`, `return()`, its signal or the client's close must leave this set.
472
+ *
473
+ * @internal Test observability, stripped from the published declarations,
474
+ * like {@link knownTurnCount}.
475
+ */
476
+ get liveEventStreamCount() {
477
+ return this.#eventStreams.size;
478
+ }
268
479
  apply(event) {
269
480
  const outcome = this.#applyLive(event);
270
- // A frame held for a fill is yielded when the fill splices it in.
271
- if (outcome.fold.kind !== "bufferedDuringGap")
481
+ // A frame held for a fill is yielded when the fill splices it in, and the
482
+ // live twin of a frame the fill already spliced in (or a reload's repeat of
483
+ // one already folded) was yielded then.
484
+ const kind = outcome.fold.kind;
485
+ if (kind !== "bufferedDuringGap" && kind !== "ignoredGapOverlap" && kind !== "ignoredReplayDuplicate") {
272
486
  this.#emit(event, outcome);
487
+ }
273
488
  return outcome;
274
489
  }
275
490
  /**
@@ -281,26 +496,47 @@ export class Session {
281
496
  * are yielded when applied, in order. Buffered like `turn.items()`, so a slow
282
497
  * reader never holds folding up.
283
498
  *
284
- * `break`, `return()` or `options.signal` ends it. It finishes the way a
499
+ * With `{ subagents: true }` on a session `MuseClient` did not open it
500
+ * throws a plain `Error`.
501
+ *
502
+ * `break`, `return()` or `options.signal` ends it, and so does an orderly
503
+ * `MuseClient.close()` (a stream created afterwards ends at once). It finishes the way a
285
504
  * turn's `items()` does when the host dies: it ends after an ephemeral
286
505
  * host's death, and rejects with `MuseHostDiedError` after a durable one's,
287
506
  * once the events it already buffered are read.
288
507
  */
289
508
  events(options = {}) {
509
+ const subagents = options.subagents === true;
510
+ if (subagents && this.#subagentFollower === undefined) {
511
+ // Plain `Error`: API misuse. Only the client can subscribe to a sub-agent's session.
512
+ throw new Error("events({ subagents: true }) needs a session MuseClient opened");
513
+ }
514
+ const unlisten = () => options.signal?.removeEventListener("abort", onAbort);
290
515
  const stream = new PushStream(() => {
291
516
  this.#eventStreams.delete(stream);
292
- options.signal?.removeEventListener("abort", onAbort);
517
+ if (this.#subagentStreams.delete(stream) && this.#subagentStreams.size === 0)
518
+ this.#unfollowSubagents();
519
+ unlisten();
293
520
  });
294
521
  const onAbort = () => void stream.return();
295
522
  if (options.signal?.aborted === true)
296
523
  stream.end();
297
524
  else if (this.#deathError !== undefined)
298
525
  stream.fail(this.#deathError);
299
- else if (this.#discharge?.kind === "discharged")
526
+ else if (this.#discharge?.kind === "discharged" || this.#eventsEnded)
300
527
  stream.end();
301
528
  else {
302
- this.#eventStreams.add(stream);
529
+ this.#eventStreams.set(stream, unlisten);
303
530
  options.signal?.addEventListener("abort", onAbort, { once: true });
531
+ if (subagents) {
532
+ this.#subagentStreams.add(stream);
533
+ // The first such stream follows the sub-agents already running.
534
+ if (this.#subagentStreams.size === 1) {
535
+ for (const item of this.#fold.items.list())
536
+ if (item.kind === "subagent")
537
+ this.#followSubagent(item);
538
+ }
539
+ }
304
540
  }
305
541
  return stream;
306
542
  }
@@ -331,6 +567,14 @@ export class Session {
331
567
  if (this.#discharge?.kind === "discharged") {
332
568
  return { fold: { kind: "refusedSessionDiscarded" }, io: NO_IO, retirements: [] };
333
569
  }
570
+ const repeated = this.#replayRepeat(event);
571
+ if (repeated !== undefined) {
572
+ return {
573
+ fold: { kind: "ignoredReplayDuplicate", method: event.method, viewCursor: repeated },
574
+ io: NO_IO,
575
+ retirements: [],
576
+ };
577
+ }
334
578
  // An SS4.8 fill is in flight, so the live tail waits for the paged prefix
335
579
  // (tdd SS4.8's "buffer live events … splice the buffer after the paged
336
580
  // prefix"). Folding it now would run the fold backwards when the older
@@ -378,6 +622,89 @@ export class Session {
378
622
  retirements: sink.retirements,
379
623
  };
380
624
  }
625
+ /** `reload()`'s repeat, by cursor equality: the repeated cursor, else undefined. */
626
+ #replayRepeat(event) {
627
+ if (this.#replayed === undefined)
628
+ return undefined;
629
+ const cursor = resumeCursorOf(event);
630
+ // `session/closed` names the final view head, often the last replayed
631
+ // cursor: it is the unload notice, never a repeat (tdd SS2.6.2).
632
+ if (cursor === undefined || event.method === "session/closed")
633
+ return undefined;
634
+ if (this.#replayed.has(cursor))
635
+ return cursor;
636
+ if (this.#replayAnswered)
637
+ this.#replayed = undefined;
638
+ else
639
+ this.#replayed.add(cursor);
640
+ return undefined;
641
+ }
642
+ /**
643
+ * Catch this session up in place (#97920): send `session/resume` with the
644
+ * cursor of the last view notification it folded, so the host loads the
645
+ * session if it was unloaded, re-attaches this connection, and streams the
646
+ * suffix after that cursor into THIS session. Its fold, handlers and
647
+ * pending turns stay; a frame the suffix repeats is dropped
648
+ * (`ignoredReplayDuplicate`). Resolves to the resume result once the host
649
+ * replies. Concurrent calls share one resume; a call with `config` while
650
+ * one is in flight is refused (plain `Error`) rather than dropped. `opening`
651
+ * still holds the original open's result. See {@link ReloadOptions}.
652
+ *
653
+ * The fold is caught up only when `result.history.noneReason` is
654
+ * `"cursorSuffix"`. Any other reply (a snapshot for a cursor older than the
655
+ * host keeps, a history budget) means the host served history instead of
656
+ * the missed events, and what streams after it folds over that gap; later
657
+ * reloads then refuse (plain `Error`) before sending: `resumeSession` it
658
+ * instead, for a new `Session` with a fresh fold.
659
+ *
660
+ * Use it before the next command on a session the host may have unloaded
661
+ * (`session/closed`). Refused before anything is sent when the session has
662
+ * folded no cursor yet (plain `Error`): a resume without one would not
663
+ * catch the fold up. A discarded session refuses as every verb does. A
664
+ * refused or failed reload leaves the fold, the other verbs and later
665
+ * reloads usable, except after a reply that was not a cursor suffix (above).
666
+ */
667
+ reload(options = {}) {
668
+ if (this.#reloading === undefined) {
669
+ this.#reloading = this.#reload(options).finally(() => (this.#reloading = undefined));
670
+ return this.#reloading;
671
+ }
672
+ // Sharing the in-flight resume would drop this call's config without a word.
673
+ if (options.config != null) {
674
+ return Promise.reject(new Error(`a reload of session ${this.sessionId} is already in flight; await it, then reload with config`));
675
+ }
676
+ return this.#reloading;
677
+ }
678
+ async #reload(options) {
679
+ const connection = this.#requireLiveConnection("reload");
680
+ if (this.#reloadGap) {
681
+ throw new Error(`session ${this.sessionId} has a gap an earlier reload could not fill (the host served history, not the missed events); resumeSession it instead`);
682
+ }
683
+ const cursor = this.#viewCursor;
684
+ if (cursor === undefined) {
685
+ throw new Error(`session ${this.sessionId} has folded no view cursor to reload from; resumeSession it instead`);
686
+ }
687
+ const config = options.config == null ? undefined : forwardedConfig("session/resume", options.config, this.#granted);
688
+ // A running fill holds live frames the replay will repeat.
689
+ this.#replayed = new Set(this.#gaps.heldCursors());
690
+ this.#replayAnswered = false;
691
+ try {
692
+ const raw = await connection.command("session/resume", {
693
+ sessionId: this.sessionId,
694
+ cursor,
695
+ ...(config === undefined ? {} : { config }),
696
+ });
697
+ const result = resumeResultOf(raw);
698
+ this.#replayAnswered = true;
699
+ if (result.history.noneReason !== "cursorSuffix")
700
+ this.#reloadGap = true;
701
+ return result;
702
+ }
703
+ catch (error) {
704
+ this.#replayed = undefined;
705
+ throw error;
706
+ }
707
+ }
381
708
  /** Observe SS4.8 fills that did not complete. See `MuseGapFillError`. */
382
709
  onGapError(handler) {
383
710
  this.#gaps.onError(handler);
@@ -391,6 +718,11 @@ export class Session {
391
718
  * downstream — the fold, the iterators, and the SS4.13 retirements.
392
719
  */
393
720
  #foldAndRoute(event, sink) {
721
+ const cursor = resumeCursorOf(event);
722
+ if (cursor !== undefined) {
723
+ this.#viewCursor = cursor;
724
+ this.#replayed?.add(cursor);
725
+ }
394
726
  const retirements = [];
395
727
  const tasks = sink.tasks;
396
728
  // A re-sent `approval/request` server request skips the fold, which lists
@@ -640,9 +972,7 @@ export class Session {
640
972
  this.#deathError = died;
641
973
  for (const handle of this.#turns.values())
642
974
  handle.fail(died);
643
- for (const stream of this.#eventStreams)
644
- stream.fail(died);
645
- this.#eventStreams.clear();
975
+ this.#finishEventStreams((stream) => stream.fail(died));
646
976
  this.#discharge = { exit, kind: "durableDeath", profile };
647
977
  return this.#discharge;
648
978
  }
@@ -650,9 +980,7 @@ export class Session {
650
980
  const terminalUnknownItems = this.#fold.markEphemeralHostDeath(isItemInProgress);
651
981
  for (const handle of this.#turns.values())
652
982
  handle.settleTerminalUnknown();
653
- for (const stream of this.#eventStreams)
654
- stream.end();
655
- this.#eventStreams.clear();
983
+ this.#finishEventStreams((stream) => stream.end());
656
984
  // SS2.13.3b "do not attempt to reattach". `discardEphemeral` already wrote
657
985
  // the commandIds into the shared set (it holds it by reference); the
658
986
  // sessionId is this layer's to record, because the pending set does not
@@ -1,4 +1,17 @@
1
1
  export declare const EXPECTED_SCHEMA_FINGERPRINT: string;
2
+ /**
3
+ * The compatibility epoch this SDK was built against (ADR 22936 D3): the
4
+ * stable bundle's declared count of non-additive advances of the stable
5
+ * surface, stamped by the same `prebuild` step from the same bundle bytes
6
+ * as the fingerprint (the bundle records it at its root, ADR 22936 D5).
7
+ * Never a committed literal, for the same reasons as the fingerprint.
8
+ */
9
+ export declare const EXPECTED_SCHEMA_COMPATIBILITY_EPOCH: number;
10
+ /** What a host advertises in `InitializeResult.schema`: the epoch is absent on a host that predates it. */
11
+ export interface ServedSchemaIdentity {
12
+ readonly fingerprint: string;
13
+ readonly compatibilityEpoch?: number | undefined;
14
+ }
2
15
  /**
3
16
  * What a build-time mismatch MEANS, in the words a human needs at 2am.
4
17
  *
@@ -9,15 +22,77 @@ export declare const EXPECTED_SCHEMA_FINGERPRINT: string;
9
22
  * plainly.
10
23
  */
11
24
  export declare function fingerprintMismatchMessage(pinned: string, actual: string): string;
12
- /** The runtime arm (tdd SS1.4.1): advisory only, never a connection failure. */
13
- export interface FingerprintWarning {
25
+ /**
26
+ * The runtime arm (tdd SS1.4.1, ADR 22936 D3): a surfaced mismatch with its
27
+ * tier. The additive tier is advisory only; the declared-breaking tier is a
28
+ * warning by default and a connect-time refusal behind
29
+ * `refuseDeclaredBreakingSchema`. The tier reads `additive` when the served
30
+ * epoch equals the pin or the host omits it (every difference is additive,
31
+ * SS1.5.4) and `declaredBreaking` when the epochs differ (a declared
32
+ * non-additive advance lies between). A union on `tier`: the
33
+ * declared-breaking member always knows the served epoch, so a caller that
34
+ * narrows on the tier needs no second check.
35
+ */
36
+ interface FingerprintWarningBase {
14
37
  readonly kind: "schemaFingerprintMismatch";
15
38
  readonly pinned: string;
16
39
  readonly served: string;
40
+ readonly pinnedEpoch: number;
17
41
  readonly message: string;
18
42
  }
43
+ /** The additive tier: an equal or absent served epoch; today's warning. */
44
+ export interface AdditiveFingerprintWarning extends FingerprintWarningBase {
45
+ readonly tier: "additive";
46
+ /** `undefined` when the host omits the member: unknown, never a substituted value. */
47
+ readonly servedEpoch: number | undefined;
48
+ }
49
+ /** The declared-breaking tier: a served epoch that differs from the pin. */
50
+ export interface DeclaredBreakingFingerprintWarning extends FingerprintWarningBase {
51
+ readonly tier: "declaredBreaking";
52
+ readonly servedEpoch: number;
53
+ }
54
+ export type FingerprintWarning = AdditiveFingerprintWarning | DeclaredBreakingFingerprintWarning;
55
+ /**
56
+ * FR-22936-8's one reading of a served `compatibilityEpoch`, shared by the
57
+ * handshake and the classifier so the two cannot drift apart: absent, or a
58
+ * non-negative integer. Package-internal: not exported from the root.
59
+ */
60
+ export declare function isWellFormedEpoch(raw: unknown): raw is number | undefined;
61
+ /**
62
+ * Classify a host's advertised schema identity against the pin (ADR 22936
63
+ * D3). Equal fingerprints: no check at all, whatever the epochs. A served
64
+ * epoch that is not a non-negative integer reads as absent (FR-22936-8), so
65
+ * this call on `initializeResult.schema` reports the tier the handshake
66
+ * reported. Returns `undefined` when there is nothing to say — a mismatch is
67
+ * surfaced, not thrown; the refusal is the connection's decision, not this
68
+ * function's.
69
+ */
70
+ export declare function classifyServedSchema(served: ServedSchemaIdentity): FingerprintWarning | undefined;
19
71
  /**
20
- * Compare a host's advertised fingerprint against the pin.
21
- * Returns `undefined` when they agree — a mismatch is surfaced, not thrown.
72
+ * Compare a host's advertised fingerprint against the pin, with no epoch:
73
+ * the pre-#22936 reading, kept for callers that have only the fingerprint.
74
+ * `pinned` overrides the fingerprint only: the pin's epoch is always this
75
+ * build's `EXPECTED_SCHEMA_COMPATIBILITY_EPOCH`, so the warning's
76
+ * `pinnedEpoch` names this build whatever `pinned` names. Returns
77
+ * `undefined` when they agree — a mismatch is surfaced, not thrown.
22
78
  */
23
79
  export declare function checkServedFingerprint(served: string, pinned?: string): FingerprintWarning | undefined;
80
+ /**
81
+ * The connect-time refusal of the declared-breaking tier (ADR 22936 D3):
82
+ * one error naming the served fingerprint and epoch as the bundle to rebuild
83
+ * against, and the SDK's own pin. Thrown only when the caller opted in with
84
+ * `refuseDeclaredBreakingSchema`; the SDK has already closed the host it
85
+ * spawned when this reaches the caller, so a refusal orphans nothing. Its
86
+ * fields are the warning's flat fields (`served`, `servedEpoch`, `pinned`,
87
+ * `pinnedEpoch`), so code that handles both sees one shape.
88
+ */
89
+ export declare class SchemaCompatibilityError extends Error {
90
+ readonly kind: "schemaCompatibilityRefused";
91
+ readonly tier: "declaredBreaking";
92
+ readonly served: string;
93
+ readonly servedEpoch: number;
94
+ readonly pinned: string;
95
+ readonly pinnedEpoch: number;
96
+ constructor(warning: DeclaredBreakingFingerprintWarning);
97
+ }
98
+ export {};