@kumiai/rpc 0.10.1 → 0.10.3

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,177 @@
1
+ export function checkedFetchResult(result) {
2
+ if (typeof result.gap !== 'boolean') {
3
+ throw new Error('Commit fetch requires a boolean gap');
4
+ }
5
+ return result;
6
+ }
7
+ /** Publication evidence stays in memory. A prepared durable attempt proves nothing. */ export function createLogDelivery(params) {
8
+ const publications = new Map();
9
+ const proven = new Set();
10
+ let acknowledgements = 0;
11
+ let removed = false;
12
+ let closed = false;
13
+ let active = false;
14
+ let needed = false;
15
+ let immediate = false;
16
+ let retrying = false;
17
+ let timer;
18
+ let backoff = 1000;
19
+ const headPastFloor = (head, floor)=>head != null && (floor.position == null || head > floor.position);
20
+ const removeProven = async ()=>{
21
+ for (const seq of proven){
22
+ await params.remove(seq);
23
+ params.queue.remove(seq);
24
+ publications.delete(seq);
25
+ proven.delete(seq);
26
+ if (closed) return false;
27
+ }
28
+ return true;
29
+ };
30
+ const certify = (epoch, started)=>{
31
+ for (const [seq, publication] of publications){
32
+ if (publication.epoch === epoch && publication.acknowledged <= started) proven.add(seq);
33
+ }
34
+ };
35
+ const pass = async ()=>{
36
+ await params.ready();
37
+ await params.queue.ready();
38
+ if (closed) return;
39
+ if (removed) {
40
+ if (params.queue.lowestUnresolvedSeq() != null) return;
41
+ const seqs = params.queue.entries().map((entry)=>entry.seq);
42
+ if (seqs.length === 0) return;
43
+ await params.clear();
44
+ params.queue.clear();
45
+ publications.clear();
46
+ proven.clear();
47
+ if (!closed) params.cleared({
48
+ reason: 'removed',
49
+ seqs
50
+ });
51
+ return;
52
+ }
53
+ // A failed durable removal retries alone, even after another epoch arrives.
54
+ if (!await removeProven()) return;
55
+ if (params.queue.entries().length === 0) return;
56
+ let count = 0;
57
+ for (const entry of params.queue.entries()){
58
+ if (closed) return;
59
+ const fence = params.queue.lowestUnresolvedSeq();
60
+ if (fence != null && entry.seq >= fence) return;
61
+ if (count++ === 64) {
62
+ immediate = true;
63
+ break;
64
+ }
65
+ if (proven.has(entry.seq)) continue;
66
+ const before = await params.probe();
67
+ if (headPastFloor(before.head, params.floor())) await params.pull();
68
+ if (closed || removed) {
69
+ immediate = removed && params.queue.lowestUnresolvedSeq() == null;
70
+ return;
71
+ }
72
+ if (params.held()) return;
73
+ const floor = params.floor();
74
+ if (publications.get(entry.seq)?.epoch === floor.epoch) continue;
75
+ const frame = await params.seal(entry);
76
+ if (closed || params.held()) return;
77
+ const needsEarlierPublication = ()=>params.queue.entries().some((earlier)=>earlier.seq < entry.seq && !proven.has(earlier.seq) && publications.get(earlier.seq)?.epoch !== frame.floor.epoch);
78
+ if (needsEarlierPublication()) {
79
+ immediate = true;
80
+ break;
81
+ }
82
+ const updated = {
83
+ ...entry,
84
+ lastAttempt: {
85
+ epoch: frame.floor.epoch,
86
+ floor: frame.floor.position,
87
+ attempts: (entry.lastAttempt?.attempts ?? 0) + 1
88
+ }
89
+ };
90
+ await params.put(updated);
91
+ params.queue.replace(updated);
92
+ if (closed || params.held()) return;
93
+ if (needsEarlierPublication()) {
94
+ immediate = true;
95
+ break;
96
+ }
97
+ const submission = params.publish(frame);
98
+ if (submission == null) return;
99
+ await submission;
100
+ if (closed) return;
101
+ publications.set(entry.seq, {
102
+ epoch: frame.floor.epoch,
103
+ floor: frame.floor.position,
104
+ acknowledged: ++acknowledgements
105
+ });
106
+ // A later entry must not reach the new epoch before this one is re-sealed there.
107
+ if (params.floor().epoch !== frame.floor.epoch) {
108
+ immediate = true;
109
+ break;
110
+ }
111
+ }
112
+ const result = await params.probe();
113
+ if (closed) return;
114
+ for (const [seq, publication] of publications){
115
+ if (result.head == null || publication.floor != null && result.head <= publication.floor) {
116
+ proven.add(seq);
117
+ }
118
+ }
119
+ if (headPastFloor(result.head, params.floor())) {
120
+ await params.pull();
121
+ if (!params.floor().covered && !params.held() && publications.size > 0) await params.heal();
122
+ }
123
+ if ([
124
+ ...publications.values()
125
+ ].some((publication)=>publication.epoch !== params.floor().epoch)) immediate = true;
126
+ await removeProven();
127
+ };
128
+ const schedule = (delay)=>{
129
+ if (closed || active || timer != null) return;
130
+ timer = setTimeout(()=>{
131
+ timer = undefined;
132
+ active = true;
133
+ needed = false;
134
+ immediate = false;
135
+ void (async ()=>{
136
+ let failed = false;
137
+ try {
138
+ await pass();
139
+ backoff = 1000;
140
+ } catch {
141
+ failed = true;
142
+ } finally{
143
+ active = false;
144
+ if (!closed) {
145
+ retrying = failed;
146
+ if (failed || params.queue.entries().length > 0 || removed && needed) {
147
+ schedule(!failed && immediate ? 0 : backoff);
148
+ if (failed) backoff = Math.min(backoff * 2, 60_000);
149
+ } else if (needed) schedule(0);
150
+ }
151
+ }
152
+ })();
153
+ }, delay);
154
+ };
155
+ return {
156
+ trigger: ()=>{
157
+ needed = true;
158
+ if (!active && !retrying && timer != null) {
159
+ clearTimeout(timer);
160
+ timer = undefined;
161
+ }
162
+ schedule(0);
163
+ },
164
+ beginWalk: ()=>acknowledgements,
165
+ certify,
166
+ removed: ()=>{
167
+ removed = true;
168
+ params.queue.stop();
169
+ needed = true;
170
+ schedule(0);
171
+ },
172
+ close: ()=>{
173
+ closed = true;
174
+ clearTimeout(timer);
175
+ }
176
+ };
177
+ }
@@ -0,0 +1,47 @@
1
+ import type { ProtocolDefinition } from '@enkaku/protocol';
2
+ import { type SuppressConfig } from '@kumiai/broadcast';
3
+ import type { Runtime } from '@sozai/runtime';
4
+ import type { Anchor } from './anchor.js';
5
+ import type { AppLane } from './app-lane.js';
6
+ import { type GroupCrypto } from './crypto.js';
7
+ import { type HostBoundary } from './host-boundary.js';
8
+ import type { HubMux } from './hub-mux.js';
9
+ import type { GroupPeerParams, InternalSurface } from './peer-types.js';
10
+ /** A frame sealed for, and addressed to, the segment its seal epoch belongs to. */
11
+ export type SegmentFrame = {
12
+ topicID: string;
13
+ payload: Uint8Array;
14
+ };
15
+ export type EpochRuntimeParams<Protocols extends Record<string, ProtocolDefinition>> = {
16
+ boundary: HostBoundary;
17
+ mux: HubMux;
18
+ crypto: GroupCrypto;
19
+ localDID: string;
20
+ protocols: Protocols;
21
+ handlers: GroupPeerParams<Protocols>['handlers'];
22
+ suppress: SuppressConfig | undefined;
23
+ runtime: Runtime | undefined;
24
+ appLogRetentionSeconds: number;
25
+ /** Read at every derivation, never captured: the anchor moves under a live epoch. */
26
+ anchor: () => Anchor;
27
+ /** Pending while an advance can move the handle before its new anchor is captured. */
28
+ sealBarrier: () => Promise<void> | undefined;
29
+ /** Set while the anchor needs confirmed recovery; every seal refuses with it. */
30
+ sealError: () => Error | undefined;
31
+ isDisposed: () => boolean;
32
+ note: AppLane['note'];
33
+ requestAppPull: () => void;
34
+ };
35
+ export type EpochRuntime = {
36
+ buildEpoch: () => Promise<void>;
37
+ teardownEpoch: () => Promise<void>;
38
+ /** Teardown then build; a teardown failure still builds, then rethrows. */
39
+ rebuildEpoch: () => Promise<void>;
40
+ surfaceFor: (name: string) => InternalSurface;
41
+ sealForSegment: (name: string, bytes: Uint8Array, intent?: 'ephemeral' | 'log') => Promise<SegmentFrame>;
42
+ hasInboxLane: () => boolean;
43
+ /** Dispose-only: `to()` has no lane left to build a directed client against. */
44
+ releaseInboxLane: () => void;
45
+ };
46
+ /** The app lane's anchor-bound runtimes per protocol, plus the peer's one inbox lane. */
47
+ export declare function createEpochRuntime<Protocols extends Record<string, ProtocolDefinition>>(params: EpochRuntimeParams<Protocols>): EpochRuntime;
@@ -0,0 +1,376 @@
1
+ import { normalizeDID } from '@kokuin/token';
2
+ import { BroadcastClient, createBroadcastResponder, createBroadcastTransport, encodeEventFrame } from '@kumiai/broadcast';
3
+ import { decodeAppAAD, encodeAppAAD } from './app-aad.js';
4
+ import { isFrameAhead } from './crypto.js';
5
+ import { createDirectedClient, createInboxAcceptor, createInboxPath, createUnroutedTagResponder } from './directed.js';
6
+ import { assertFrameFits } from './frame-size.js';
7
+ import { adaptBusHandlers } from './handlers.js';
8
+ import { wrapGatherOptions } from './host-boundary.js';
9
+ import { createOpenOncePath } from './open-once.js';
10
+ import { retentionOf } from './protocol.js';
11
+ import { inboxTopic, protocolTopic } from './topic.js';
12
+ /** The app lane's anchor-bound runtimes per protocol, plus the peer's one inbox lane. */ export function createEpochRuntime(params) {
13
+ const { boundary, mux, crypto, localDID, protocols, handlers, suppress, appLogRetentionSeconds, anchor, sealBarrier, sealError, isDisposed } = params;
14
+ let runtimes = new Map();
15
+ /**
16
+ * The epoch's self-inbox topic and the one path that opens its frames. Held per peer rather
17
+ * than per protocol because the topic is not per protocol, and rebuilt with the epoch — the
18
+ * topic is anchor-bound, so a roster change moves it.
19
+ */ let inboxLane;
20
+ /**
21
+ * The one peer-level consumer of the shared inbox path that NACKs a frame tagged for a protocol
22
+ * no acceptor here serves — every acceptor filters on its own tag, so such a frame would
23
+ * otherwise be dropped silently. Rebuilt with the epoch, since it replies on the anchor-bound
24
+ * inbox topics the rotation moves.
25
+ */ let unroutedTagResponder;
26
+ /**
27
+ * The opened form of a live frame, keyed by the plaintext the open produced. Written by the
28
+ * inbound path below and read by every transport built on it, so one open serves all of them.
29
+ *
30
+ * {@link GroupUnwrapResult}, not `@kumiai/broadcast`'s `UnwrapResult`: what is stored here
31
+ * reaches `BroadcastClient.gather` as the sender it keys its quorum on, and broadcast's type
32
+ * says `senderDID?`. `crypto.unwrap` REQUIRES the field, so the narrowing below checks a promise
33
+ * already made — a frame that breaks it is refused rather than fanned out.
34
+ */ const openedFrames = new WeakMap();
35
+ /**
36
+ * Whether a frame `unwrap` just refused might still open once this handle catches up — read from
37
+ * the refusal's locked answer ({@link "crypto".FrameEpochError}), never the epoch hint.
38
+ * On the open-once failure path ({@link "open-once".OpenOncePathParams.retainOnFailure}) answering
39
+ * `true` withholds the ack so the frame survives a reconnect. Mailbox-class frames have no staging
40
+ * of their own (unlike `app-lane.ts`'s `note`/`ahead`), which is what made acking a transient
41
+ * refusal here a permanent loss.
42
+ */ const retainOnFailure = (_message, error)=>isFrameAhead(error);
43
+ /**
44
+ * The app lane's inbound path: one open per topic, fanned out as plaintext, with each frame's
45
+ * log position noted once its open settles. Every consumer's own `unwrap` is then a pure lookup of the
46
+ * opened result ({@link openedFrames}), and nothing downstream touches the handle.
47
+ *
48
+ * See {@link createOpenOncePath} for why a lane may only open a frame once.
49
+ */ const createInboundPath = (name, topicID)=>{
50
+ return createOpenOncePath({
51
+ mux,
52
+ topicID,
53
+ unwrap: (b)=>{
54
+ const hinted = crypto.frameAAD(b);
55
+ const decoded = hinted == null ? null : decodeAppAAD(hinted);
56
+ const intent = decoded?.topicID === topicID ? decoded.intent : 'ephemeral';
57
+ return crypto.unwrap(b, {
58
+ expectedAAD: encodeAppAAD({
59
+ topicID,
60
+ intent
61
+ })
62
+ });
63
+ },
64
+ retainOnFailure,
65
+ project: (_message, opened)=>{
66
+ const { payload, senderDID } = opened;
67
+ if (typeof senderDID !== 'string' || senderDID === '') {
68
+ // `project` returning `undefined` drops the frame deliberately (see
69
+ // `OpenOncePathParams.project`): the app lane is always MLS-sealed, so an open that
70
+ // recovers no sender is not a frame to deliver unattributed. Fails CLOSED against the
71
+ // shared open-once signature's wider `UnwrapResult`.
72
+ return undefined;
73
+ }
74
+ // Normalized at the open, before it is keyed: every consumer of `openedFrames` (the
75
+ // acceptor, `gather`'s quorum) must see one canonical sender regardless of which DID form
76
+ // MLS recovered this frame under.
77
+ openedFrames.set(payload, {
78
+ ...opened,
79
+ senderDID: normalizeDID(senderDID)
80
+ });
81
+ return payload;
82
+ },
83
+ note: (message, failure)=>params.note(name, topicID, message, failure),
84
+ wakeup: (message)=>{
85
+ if (crypto.pending == null) return false;
86
+ const aad = crypto.frameAAD(message.payload);
87
+ if (aad == null || decodeAppAAD(aad)?.intent !== 'log') return false;
88
+ params.requestAppPull();
89
+ return true;
90
+ }
91
+ });
92
+ };
93
+ /**
94
+ * One protocol's live-lane transport: LISTENS on the topic the runtime is built for, and
95
+ * PUBLISHES to the segment that contains each frame's own seal epoch — see
96
+ * {@link sealForSegment} for why those can differ mid-rotation.
97
+ *
98
+ * The topic is decided by the SEAL and carried to the publish, since the two are separate calls
99
+ * with an anchor that can move between them: `wrap` records the topic under the ciphertext it
100
+ * produced, keyed by the bytes' own identity rather than a slot, since two transports share this
101
+ * lane and interleave their writes.
102
+ *
103
+ * The subscribe keeps the runtime's topic — a rotation rebuilds the listeners, but a topic stays
104
+ * subscribed at the mux for the member's whole life either way.
105
+ */ const segmentBoundTransport = (name, topicID, inbound)=>{
106
+ const sealedOn = new WeakMap();
107
+ return createBroadcastTransport({
108
+ topicID,
109
+ bus: {
110
+ // `builtFor` is the topic this transport was constructed with, and it is the fallback
111
+ // rather than the answer: anything published through here was sealed by the `wrap` below,
112
+ // so the recorded topic is the one that agrees with the seal.
113
+ publish: async (builtFor, payload)=>{
114
+ await mux.bus.publish(sealedOn.get(payload) ?? builtFor, payload);
115
+ },
116
+ // Already-opened plaintext, from the topic's one inbound path. The `unwrap` below only
117
+ // recovers the sender the open already authenticated.
118
+ subscribe: (_listenOn, onMessage)=>inbound(onMessage)
119
+ },
120
+ wrap: async (bytes)=>{
121
+ const sealed = await sealForSegment(name, bytes);
122
+ sealedOn.set(sealed.payload, sealed.topicID);
123
+ return sealed.payload;
124
+ },
125
+ unwrap: (payload)=>openedFrames.get(payload) ?? payload
126
+ });
127
+ };
128
+ const buildEpoch = async ()=>{
129
+ const next = new Map();
130
+ // ONE inbox lane for the whole peer, not one per protocol: the topic does not name a
131
+ // protocol, so every acceptor and directed client opening its own frames is the defect this
132
+ // shape prevents.
133
+ const selfInbox = inboxTopic(anchor().secret, anchor().epoch, localDID);
134
+ inboxLane = {
135
+ topicID: selfInbox,
136
+ path: createInboxPath({
137
+ mux,
138
+ topicID: selfInbox,
139
+ unwrap: (b)=>crypto.unwrap(b, {
140
+ expectedAAD: encodeAppAAD({
141
+ topicID: selfInbox,
142
+ intent: 'ephemeral'
143
+ })
144
+ }),
145
+ retainOnFailure
146
+ })
147
+ };
148
+ // ONE responder for the whole peer, on the shared path: it NACKs any frame whose tag names a
149
+ // protocol not in `protocols`, restoring the legible reply an acceptor's own filter drops.
150
+ unroutedTagResponder = createUnroutedTagResponder({
151
+ mux,
152
+ localDID,
153
+ inbound: inboxLane.path,
154
+ isRegistered: (name)=>Object.hasOwn(protocols, name),
155
+ sealReply: sealDirectedReply
156
+ });
157
+ for (const [name, protocol] of Object.entries(protocols)){
158
+ // The app topic is bound to the ANCHOR, not the live epoch — see {@link sealForSegment}.
159
+ // Content stays sealed under the live epoch crypto below; only the topic ID is anchor-bound.
160
+ const topicID = protocolTopic(anchor().secret, anchor().epoch, name);
161
+ // Subscribed for the member's whole life, like the commit and rendezvous topics: the mux
162
+ // never unsubscribes on rotation, only tears down the LISTENERS on the epoch left.
163
+ // Unsubscribing would tell the hub to drop this member's pending deliveries and free any
164
+ // frame it was the last reader of — deleting unread messages for everyone.
165
+ //
166
+ // Subscribed HERE, not left to the transports below, because the subscription is also what
167
+ // asks the hub how long to hold the log; a bus is a fan-out abstraction with no such request.
168
+ mux.retainTopic(topicID, {
169
+ retention: appLogRetentionSeconds
170
+ });
171
+ // One path, two consumers: the frame is opened once here and both are given the plaintext.
172
+ const inbound = createInboundPath(name, topicID);
173
+ const client = new BroadcastClient({
174
+ transport: segmentBoundTransport(name, topicID, inbound),
175
+ ...params.runtime != null ? {
176
+ runtime: params.runtime
177
+ } : {}
178
+ });
179
+ const { events, requestHandlers } = adaptBusHandlers(protocol, handlers[name], suppress);
180
+ const busServer = createBroadcastResponder({
181
+ transport: segmentBoundTransport(name, topicID, inbound),
182
+ from: localDID,
183
+ requestHandlers,
184
+ events
185
+ });
186
+ const acceptor = createInboxAcceptor({
187
+ mux,
188
+ localDID,
189
+ selfInboxTopic: selfInbox,
190
+ inbound: inboxLane.path,
191
+ resolveSendTopic: (senderDID)=>inboxTopic(anchor().secret, anchor().epoch, senderDID),
192
+ protocol: protocol,
193
+ protocolName: name,
194
+ handlers: handlers[name],
195
+ wrap: crypto.wrap
196
+ });
197
+ next.set(name, {
198
+ client,
199
+ busServer,
200
+ acceptor,
201
+ directed: new Map()
202
+ });
203
+ }
204
+ runtimes = next;
205
+ };
206
+ const teardownEpoch = async ()=>{
207
+ // Disposal order is independent, so tear everything down concurrently and surface every
208
+ // failure rather than dying on the first.
209
+ const disposals = [];
210
+ // A bare unsubscribe of the shared path — synchronous, cannot reject — dropped alongside the
211
+ // acceptor consumers of that same path.
212
+ unroutedTagResponder?.dispose();
213
+ unroutedTagResponder = undefined;
214
+ for (const runtime of runtimes.values()){
215
+ for (const directed of runtime.directed.values())disposals.push(directed.dispose());
216
+ runtime.directed.clear();
217
+ disposals.push(runtime.busServer.dispose());
218
+ disposals.push(runtime.acceptor.dispose());
219
+ disposals.push(runtime.client.dispose());
220
+ }
221
+ runtimes = new Map();
222
+ const results = await Promise.allSettled(disposals);
223
+ const reasons = results.flatMap((r)=>r.status === 'rejected' ? [
224
+ r.reason
225
+ ] : []);
226
+ // Defensive: no child rejects today — all are enkaku `Disposer`-based (a failing dispose is
227
+ // swallowed to `console.warn`, the promise still resolves) or a refcount decrement that cannot
228
+ // throw — so this guards a future non-`Disposer` child. Kept live because rotation shares this
229
+ // path, and a `BroadcastClient.prototype.dispose` spy forces it in test.
230
+ if (reasons.length > 0) {
231
+ throw new AggregateError(reasons, 'Group epoch teardown failed');
232
+ }
233
+ };
234
+ /** Wait while an advance can move the handle before its new anchor is captured. */ const sealForSegment = async (name, bytes, intent = 'ephemeral')=>{
235
+ while(true){
236
+ const refused = sealError();
237
+ if (refused != null) throw refused;
238
+ const barrier = sealBarrier();
239
+ if (barrier != null) {
240
+ await barrier;
241
+ continue;
242
+ }
243
+ const at = anchor();
244
+ const topicID = protocolTopic(at.secret, at.epoch, name);
245
+ const payload = await crypto.wrap(bytes, {
246
+ aad: encodeAppAAD({
247
+ topicID,
248
+ intent
249
+ })
250
+ });
251
+ const refusedAfter = sealError();
252
+ if (refusedAfter != null) throw refusedAfter;
253
+ if (anchor() === at && sealBarrier() == null) {
254
+ assertFrameFits(payload);
255
+ return {
256
+ topicID,
257
+ payload
258
+ };
259
+ }
260
+ }
261
+ };
262
+ /**
263
+ * Seal a directed reply (the unrouted-tag NACK) to a recipient's inbox under ONE anchor snapshot.
264
+ * The reply topic and the seal must agree on the epoch: were the topic read from the live anchor
265
+ * and the seal taken as a separate step, a rotation landing between them would address an
266
+ * old-epoch inbox with new-epoch ciphertext, published onto a topic the recipient no longer reads
267
+ * and silently lost. Re-read the anchor after the seal and re-seal if it moved — same identity
268
+ * (not epoch-equality) guard as {@link sealForSegment}.
269
+ */ const sealDirectedReply = async (recipientDID, tagged)=>{
270
+ while(true){
271
+ const at = anchor();
272
+ const topicID = inboxTopic(at.secret, at.epoch, recipientDID);
273
+ const payload = await crypto.wrap(tagged, {
274
+ aad: encodeAppAAD({
275
+ topicID,
276
+ intent: 'ephemeral'
277
+ })
278
+ });
279
+ if (anchor() === at) return {
280
+ topicID,
281
+ payload
282
+ };
283
+ }
284
+ };
285
+ const surfaceFor = (name)=>{
286
+ const runtime = runtimes.get(name);
287
+ if (runtime == null) throw new Error(`Unknown protocol: ${name}`);
288
+ return {
289
+ dispatch: async (prc, config)=>{
290
+ const data = config?.data ?? {};
291
+ // Route by the procedure's declared retention. A `log` event goes to the app topic's log
292
+ // lane (retained, pullable); ephemeral events and RPC stay on the live mailbox lane. The
293
+ // log payload is byte-identical to what the broadcast transport would produce, so online
294
+ // subscribers still receive it through the same drain.
295
+ const protocol = protocols[name];
296
+ if (protocol === undefined) throw new Error(`Unknown protocol: ${name}`);
297
+ if (retentionOf(protocol, prc) === 'log') {
298
+ const { topicID, payload } = await sealForSegment(name, encodeEventFrame(prc, data), 'log');
299
+ await mux.publish({
300
+ topicID,
301
+ payload,
302
+ retain: 'log'
303
+ });
304
+ return;
305
+ }
306
+ await runtime.client.dispatch(prc, data);
307
+ },
308
+ request: (prc, config)=>runtime.client.request(prc, config?.param, {
309
+ errorThreshold: config?.errorThreshold,
310
+ timeoutMs: config?.timeoutMs
311
+ }),
312
+ gather: (prc, config)=>runtime.client.gather(prc, config?.param, {
313
+ quorum: config?.quorum,
314
+ timeoutMs: config?.timeoutMs,
315
+ onReply: config == null ? undefined : wrapGatherOptions(boundary, config).onReply,
316
+ signal: config?.signal
317
+ }),
318
+ to: async (memberDID)=>{
319
+ // Normalized ONCE, at the ingress: the cache key, the topic derivation and the
320
+ // directed client's own filter (`senderDID !== memberDID`) must all see one canonical
321
+ // form, or a long-form caller never converges onto the short form MLS actually replies
322
+ // under.
323
+ const member = normalizeDID(memberDID);
324
+ const cached = runtime.directed.get(member);
325
+ if (cached != null) return cached.client;
326
+ const lane = inboxLane;
327
+ if (lane == null) throw new Error('Peer is not started');
328
+ const created = createDirectedClient({
329
+ mux,
330
+ localDID,
331
+ memberDID: member,
332
+ sendTopicID: inboxTopic(anchor().secret, anchor().epoch, member),
333
+ // The epoch's own inbox topic and its one open path: reading replies through a path
334
+ // built for a topic this client does not receive on would spend keys opening frames for
335
+ // a lane nobody listens to.
336
+ receiveTopicID: lane.topicID,
337
+ inbound: lane.path,
338
+ wrap: crypto.wrap,
339
+ protocol: name,
340
+ ...params.runtime != null ? {
341
+ runtime: params.runtime
342
+ } : {}
343
+ });
344
+ runtime.directed.set(member, created);
345
+ return created.client;
346
+ }
347
+ };
348
+ };
349
+ const rebuildEpoch = async ()=>{
350
+ if (isDisposed()) return;
351
+ // Teardown empties the runtimes before it reports a failed child, and a later walk sees the
352
+ // advance as history. Build anyway, then report the failure.
353
+ let failure;
354
+ try {
355
+ await teardownEpoch();
356
+ } catch (error) {
357
+ failure = {
358
+ error
359
+ };
360
+ }
361
+ if (isDisposed()) return;
362
+ await buildEpoch();
363
+ if (failure != null) throw failure.error;
364
+ };
365
+ return {
366
+ buildEpoch,
367
+ teardownEpoch,
368
+ rebuildEpoch,
369
+ surfaceFor,
370
+ sealForSegment,
371
+ hasInboxLane: ()=>inboxLane != null,
372
+ releaseInboxLane: ()=>{
373
+ inboxLane = undefined;
374
+ }
375
+ };
376
+ }