@sjawhar/claude-envoy 2.8.0 → 2.9.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.
@@ -36300,6 +36300,9 @@ function agentSubject(session) {
36300
36300
  return `${AGENT_TOPIC_PREFIX}${session}`;
36301
36301
  }
36302
36302
  var GHOSTWISPR_TOPIC_PREFIX = "notifications.ghostwispr.";
36303
+ function uncapturedTopicRefusal(topic, sessionID) {
36304
+ return `${topic} was not registered: no stream subject captures it, so nothing would be delivered to ${sessionID} on it; follow a notifications.team.<name> topic instead`;
36305
+ }
36303
36306
 
36304
36307
  // ../contracts/src/legion-roles.ts
36305
36308
  var LEGION_ROLES = [
@@ -44108,58 +44111,6 @@ async function postDeliveryReply(config, sessionId, delivery, result) {
44108
44111
  ...reply
44109
44112
  }, followUp === undefined ? {} : { followUp });
44110
44113
  }
44111
- function expectsLaneReceipt(frame) {
44112
- return frame.reply !== undefined && frame.reply !== "" && frame.subject === frame.directSubject && frame.envelopeTopic !== undefined && frame.envelopeTopic !== frame.directSubject;
44113
- }
44114
- async function* readArrivals(subscription, now = Date.now) {
44115
- const source = subscription[Symbol.asyncIterator]();
44116
- const arrived = [];
44117
- let stopped;
44118
- let left = false;
44119
- let wake;
44120
- const signal = () => {
44121
- wake?.();
44122
- wake = undefined;
44123
- };
44124
- (async () => {
44125
- try {
44126
- for (;; ) {
44127
- const read = await source.next();
44128
- if (read.done === true || left)
44129
- break;
44130
- arrived.push({ message: read.value, receivedAt: now() });
44131
- signal();
44132
- }
44133
- stopped = { failed: false };
44134
- } catch (error) {
44135
- stopped = { error, failed: true };
44136
- }
44137
- signal();
44138
- })();
44139
- try {
44140
- for (;; ) {
44141
- const next = arrived.shift();
44142
- if (next !== undefined) {
44143
- yield next;
44144
- continue;
44145
- }
44146
- if (stopped?.failed === true)
44147
- throw stopped.error;
44148
- if (stopped !== undefined)
44149
- return;
44150
- const { promise, resolve } = Promise.withResolvers();
44151
- wake = resolve;
44152
- await promise;
44153
- }
44154
- } finally {
44155
- if (stopped === undefined) {
44156
- left = true;
44157
- Promise.resolve(source.return?.()).catch(() => {
44158
- return;
44159
- });
44160
- }
44161
- }
44162
- }
44163
44114
  var DedupeIdentitySchema = object({
44164
44115
  event_id: string2().min(1).optional(),
44165
44116
  dedupe_key: string2().min(1).optional(),
@@ -44920,6 +44871,262 @@ function subscriptionRemovedTopics(raw, sessionID) {
44920
44871
  return parsedPayload.data.topics ?? [];
44921
44872
  }
44922
44873
 
44874
+ // ../envoy-client/src/delivery-ledger.ts
44875
+ var DELIVERY_LEDGER_TTL_MS = DELIVERY_DUPLICATE_WINDOW_MS;
44876
+ var DELIVERY_LEDGER_LIMIT = 20000;
44877
+ var LedgerEntrySchema = object({
44878
+ event_id: string2().min(1).optional(),
44879
+ dedupe_key: string2().min(1).optional(),
44880
+ at: number2()
44881
+ });
44882
+ var LedgerStateSchema = object({
44883
+ topics: array(string2()).default([])
44884
+ });
44885
+ var LedgerSnapshotSchema = object({
44886
+ state: LedgerStateSchema.optional(),
44887
+ ledger: array(LedgerEntrySchema)
44888
+ });
44889
+ function createDeliveryLedger(options) {
44890
+ const { host } = options;
44891
+ const now = options.now ?? Date.now;
44892
+ const ledger = createLedger(now);
44893
+ let topics = [];
44894
+ let unwritten = [];
44895
+ let writtenState;
44896
+ let writes = Promise.resolve();
44897
+ let epoch = 0;
44898
+ const safely = (what, call) => {
44899
+ try {
44900
+ call();
44901
+ } catch (error) {
44902
+ try {
44903
+ host.log(`delivery ledger: ${what} failed`, error);
44904
+ } catch {}
44905
+ }
44906
+ };
44907
+ const log = (message, error) => safely("log", () => host.log(message, error));
44908
+ const sessionRead = (read) => () => {
44909
+ try {
44910
+ return read();
44911
+ } catch {
44912
+ return;
44913
+ }
44914
+ };
44915
+ const currentSession = sessionRead(() => host.sessionID());
44916
+ const writeSession = sessionRead(() => host.writeSessionID === undefined ? host.sessionID() : host.writeSessionID());
44917
+ const bindTo = (sessionID, read) => {
44918
+ if (sessionID === undefined || sessionID === "" || read() !== sessionID)
44919
+ return;
44920
+ const bound = epoch;
44921
+ return { sessionID, alive: () => bound === epoch && read() === sessionID };
44922
+ };
44923
+ const bind = () => bindTo(currentSession(), currentSession);
44924
+ const stateJSON = () => JSON.stringify({ topics: [...topics].sort() });
44925
+ const record = (identity) => {
44926
+ const entry = ledger.record(identity);
44927
+ if (entry !== undefined)
44928
+ unwritten.push(entry);
44929
+ };
44930
+ const flush = (alive) => {
44931
+ const written = writes.then(async () => {
44932
+ if (!alive())
44933
+ return false;
44934
+ const json = stateJSON();
44935
+ const delivered = unwritten;
44936
+ if (json === writtenState && delivered.length === 0)
44937
+ return true;
44938
+ unwritten = [];
44939
+ const state = json === writtenState ? undefined : JSON.parse(json);
44940
+ try {
44941
+ await host.write({
44942
+ delivered,
44943
+ state,
44944
+ snapshot: () => ({ state: JSON.parse(json), ledger: ledger.list() })
44945
+ });
44946
+ if (state !== undefined)
44947
+ writtenState = json;
44948
+ return true;
44949
+ } catch (error) {
44950
+ unwritten = [...delivered, ...unwritten];
44951
+ log("delivery ledger: could not persist the state; the next write carries it", error);
44952
+ return false;
44953
+ }
44954
+ });
44955
+ writes = written.then(() => {
44956
+ return;
44957
+ });
44958
+ return written;
44959
+ };
44960
+ const syncFollowed = () => {
44961
+ topics = [...new Set(host.followedSubjects())];
44962
+ };
44963
+ const failureNotice = (envelope, error) => ({
44964
+ eventId: envelope.event_id ?? "unknown",
44965
+ sender: senderLabel(envelope),
44966
+ summary: envelope.payload_summary ?? "unknown",
44967
+ publishedAt: inboundTimestamp(envelope.issued_at),
44968
+ error,
44969
+ readWith: envelope.source === "dispatch" ? "dispatch read" : "envoy_inbox",
44970
+ envelope
44971
+ });
44972
+ const showFailureNotice = async (sessionID, notice, alive) => {
44973
+ let queued;
44974
+ try {
44975
+ queued = await host.showFailureNotice(sessionID, notice) === "queued";
44976
+ } catch (error) {
44977
+ if (alive())
44978
+ safely("failure notice warning", () => host.failureNoticeFailed(notice, error));
44979
+ return false;
44980
+ }
44981
+ if (queued || !alive())
44982
+ return true;
44983
+ record(ledgerIdentity(notice.envelope));
44984
+ await flush(alive);
44985
+ return true;
44986
+ };
44987
+ return {
44988
+ async followedChanged() {
44989
+ const alive = bind()?.alive;
44990
+ if (alive === undefined)
44991
+ return;
44992
+ try {
44993
+ syncFollowed();
44994
+ await flush(alive);
44995
+ } catch (error) {
44996
+ log("delivery ledger: could not take the followed subjects", error);
44997
+ }
44998
+ },
44999
+ delivered: (frame) => ledger.has(ledgerIdentity(frame)),
45000
+ async recordDelivered(frame) {
45001
+ const alive = bind()?.alive;
45002
+ if (alive === undefined)
45003
+ return;
45004
+ record(ledgerIdentity(frame));
45005
+ await flush(alive);
45006
+ },
45007
+ async recordDeliveredFor(sessionID, frame) {
45008
+ const alive = bindTo(sessionID, writeSession)?.alive;
45009
+ if (alive === undefined)
45010
+ return false;
45011
+ record(ledgerIdentity(frame));
45012
+ return await flush(alive);
45013
+ },
45014
+ async liveFailed(sessionID, envelope, error) {
45015
+ const alive = bindTo(sessionID, currentSession)?.alive;
45016
+ if (alive === undefined) {
45017
+ log("delivery ledger: a failed frame was not reported here; the session it names is closed");
45018
+ return false;
45019
+ }
45020
+ try {
45021
+ return await showFailureNotice(sessionID, failureNotice(envelope, messageFor(error)), alive);
45022
+ } catch (thrown) {
45023
+ log("delivery ledger: could not report a frame the session was not shown", thrown);
45024
+ return false;
45025
+ }
45026
+ },
45027
+ restore(snapshot) {
45028
+ epoch += 1;
45029
+ ledger.restore(snapshot.ledger);
45030
+ topics = [...new Set(snapshot.state?.topics ?? [])];
45031
+ writtenState = snapshot.state === undefined ? undefined : stateJSON();
45032
+ unwritten = [];
45033
+ }
45034
+ };
45035
+ }
45036
+ function failureNoticeFields(notice) {
45037
+ const readWith = notice.readWith === "dispatch read" ? "Read it with the `dispatch read` command on the issue or ask it concerns." : "Read it with the envoy_inbox tool.";
45038
+ return {
45039
+ notice: "message not shown",
45040
+ event_id: notice.eventId,
45041
+ from: notice.sender,
45042
+ summary: notice.summary,
45043
+ published_at: notice.publishedAt,
45044
+ error: notice.error,
45045
+ detail: `This session could not be shown this message, so it is not coming back on its own. ${readWith}`
45046
+ };
45047
+ }
45048
+ function envoyNoticeText(fields) {
45049
+ return encode5({ envoy: fields });
45050
+ }
45051
+ async function closeReplayedRemoval(frame, host) {
45052
+ const closed = (subscriptionRemovedTopics(frame.data, host.sessionID) ?? []).filter((topic) => host.relay?.followedBefore(topic, frame.storedAtMs) !== false && host.close(topic));
45053
+ if (closed.length === 0)
45054
+ return closed;
45055
+ const unregistering = host.unregister(closed);
45056
+ await host.followedChanged();
45057
+ await unregistering;
45058
+ return closed;
45059
+ }
45060
+ function ledgerIdentity(frame) {
45061
+ return {
45062
+ ...frame.event_id === undefined || frame.event_id === "" ? {} : { event_id: frame.event_id },
45063
+ ...frame.dedupe_key === undefined || !dedupeKeyNamesItsEvent(frame) ? {} : { dedupe_key: frame.dedupe_key }
45064
+ };
45065
+ }
45066
+ function createLedger(now) {
45067
+ let entries = new Set;
45068
+ const byEvent = new Map;
45069
+ const byKey = new Map;
45070
+ const drop = (entry) => {
45071
+ entries.delete(entry);
45072
+ if (entry.event_id !== undefined && byEvent.get(entry.event_id) === entry) {
45073
+ byEvent.delete(entry.event_id);
45074
+ }
45075
+ if (entry.dedupe_key !== undefined && byKey.get(entry.dedupe_key) === entry) {
45076
+ byKey.delete(entry.dedupe_key);
45077
+ }
45078
+ };
45079
+ const add = (entry) => {
45080
+ if (entries.size >= DELIVERY_LEDGER_LIMIT) {
45081
+ const oldest = entries.values().next();
45082
+ if (oldest.done !== true)
45083
+ drop(oldest.value);
45084
+ }
45085
+ entries.add(entry);
45086
+ if (entry.event_id !== undefined)
45087
+ byEvent.set(entry.event_id, entry);
45088
+ if (entry.dedupe_key !== undefined)
45089
+ byKey.set(entry.dedupe_key, entry);
45090
+ };
45091
+ const expire = () => {
45092
+ const at = now();
45093
+ for (const entry of entries) {
45094
+ if (at - entry.at < DELIVERY_LEDGER_TTL_MS)
45095
+ break;
45096
+ drop(entry);
45097
+ }
45098
+ };
45099
+ const has = (identity) => {
45100
+ expire();
45101
+ return identity.event_id !== undefined && byEvent.has(identity.event_id) || identity.dedupe_key !== undefined && byKey.has(identity.dedupe_key);
45102
+ };
45103
+ return {
45104
+ has,
45105
+ record(identity) {
45106
+ if (identity.event_id === undefined && identity.dedupe_key === undefined)
45107
+ return;
45108
+ if (has(identity))
45109
+ return;
45110
+ const entry = { ...identity, at: now() };
45111
+ add(entry);
45112
+ return entry;
45113
+ },
45114
+ restore(restored) {
45115
+ entries = new Set;
45116
+ byEvent.clear();
45117
+ byKey.clear();
45118
+ const at = now();
45119
+ const kept = restored.filter((entry) => at - entry.at < DELIVERY_LEDGER_TTL_MS && (entry.event_id !== undefined || entry.dedupe_key !== undefined)).sort((a, b) => a.at - b.at);
45120
+ for (const entry of kept)
45121
+ add({ ...entry });
45122
+ },
45123
+ list() {
45124
+ expire();
45125
+ return [...entries];
45126
+ }
45127
+ };
45128
+ }
45129
+
44923
45130
  // ../envoy-client/src/stream-topics.ts
44924
45131
  var EXCEPTION_TOPIC_PREFIX = "notifications.envoy.exceptions.";
44925
45132
  var STREAM_SUBJECT_PREFIXES = [
@@ -44930,42 +45137,103 @@ var STREAM_SUBJECT_PREFIXES = [
44930
45137
  LEGION_NOTICE_TOPIC_PREFIX,
44931
45138
  GHOSTWISPR_TOPIC_PREFIX,
44932
45139
  "notifications.whatsapp.",
44933
- `${EXCEPTION_TOPIC_PREFIX}${AGENT_TOPIC_PREFIX}`
45140
+ "notifications.team.",
45141
+ `${EXCEPTION_TOPIC_PREFIX}${AGENT_TOPIC_PREFIX}`,
45142
+ `${EXCEPTION_TOPIC_PREFIX}notifications.team.`
44934
45143
  ];
44935
45144
  function streamStores(topic) {
44936
45145
  return STREAM_SUBJECT_PREFIXES.some((prefix) => topic.length > prefix.length && topic.startsWith(prefix));
44937
45146
  }
44938
-
44939
- // ../envoy-client/src/machine.ts
44940
- import { hostname as hostname3 } from "os";
44941
- function machineID() {
44942
- return process.env["ENVOY_MACHINE_ID"] || process.env["AGENTBOX_HOST"] || hostname3();
45147
+ function streamDeliversNothing(topic) {
45148
+ return topic.startsWith("notifications.") && !topic.startsWith(ROLE_TOPIC_PREFIX) && !streamStores(topic);
44943
45149
  }
44944
-
44945
- // ../envoy-client/src/transport.ts
44946
- var REPLAY_TIMEOUT_MS = 1e4;
44947
- var REPLAY_UNAVAILABLE_CODE = "REPLAY_UNAVAILABLE";
44948
- var SessionStateSchema = _enum2(["live", "unresponsive", "gone"]);
44949
- var UNRESPONSIVE_RULE = "An unresponsive session is not dead: it keeps its role claims and its issue claims, and a " + "message sent to it is stored until it answers. Start no replacement for it and take no claim " + `from it until it is gone, or until ${ISSUE_CLAIM_UNRESPONSIVE_GRACE_MS / 60000} minutes ` + "have passed since its last_seen, the time of its last registration.";
44950
- var WireStateSchema = SessionStateSchema.default("live");
44951
- var InterestWireSchema = object({
44952
- session_id: string2(),
44953
- machine_id: string2(),
44954
- dir: string2(),
44955
- topics: array(string2()),
44956
- updated_at: number2().int().optional(),
44957
- warnings: array(string2()).optional()
44958
- });
44959
- var DeliveryAnswerWireSchema = discriminatedUnion("mode", [
44960
- object({
44961
- mode: literal("consumer"),
44962
- subject: string2().min(1),
44963
- stream_id: string2(),
44964
- gap: boolean2(),
44965
- consumer_start: number2().int().nonnegative().optional()
44966
- }),
44967
- object({ mode: literal("core"), reason: string2() })
44968
- ]);
45150
+ function subscribeRefusesTopic(ownAgentSubject, topic) {
45151
+ return streamDeliversNothing(topic) && !reachesPrivateStreamSubject(ownAgentSubject, topic);
45152
+ }
45153
+ function refuseUncapturedTopics(sessionID, ownAgentSubject, topics) {
45154
+ const uncaptured = topics.filter((topic) => subscribeRefusesTopic(ownAgentSubject, topic));
45155
+ if (uncaptured.length === 0)
45156
+ return;
45157
+ throw new Error(uncaptured.map((topic) => uncapturedTopicRefusal(topic, sessionID)).join("; "));
45158
+ }
45159
+ var PRIVATE_STREAM_SUBJECTS = [
45160
+ `${AGENT_TOPIC_PREFIX}>`,
45161
+ `${LEGION_NOTICE_TOPIC_PREFIX}>`,
45162
+ `${EXCEPTION_TOPIC_PREFIX}${AGENT_TOPIC_PREFIX}>`,
45163
+ `${EXCEPTION_TOPIC_PREFIX}notifications.team.>`
45164
+ ];
45165
+ var CONTROLLER_NOTICE_SUFFIX = ".controller";
45166
+ function controllerNoticeRole(topic) {
45167
+ if (!topic.startsWith(LEGION_NOTICE_TOPIC_PREFIX) || !topic.endsWith(CONTROLLER_NOTICE_SUFFIX)) {
45168
+ return;
45169
+ }
45170
+ const project = topic.slice(LEGION_NOTICE_TOPIC_PREFIX.length, topic.length - CONTROLLER_NOTICE_SUFFIX.length);
45171
+ if (project === "" || /[.*>]/.test(project))
45172
+ return;
45173
+ return `legion-${project}-controller`;
45174
+ }
45175
+ function subjectsOverlap(a, b) {
45176
+ const aTokens = a.split(".");
45177
+ const bTokens = b.split(".");
45178
+ for (let index = 0;index < aTokens.length && index < bTokens.length; index += 1) {
45179
+ const aToken = aTokens[index];
45180
+ const bToken = bTokens[index];
45181
+ if (aToken === ">" || bToken === ">")
45182
+ return true;
45183
+ if (aToken !== "*" && bToken !== "*" && aToken !== bToken)
45184
+ return false;
45185
+ }
45186
+ return aTokens.length === bTokens.length;
45187
+ }
45188
+ function reachesPrivateStreamSubject(ownAgentSubject, topic, roles = []) {
45189
+ if (!PRIVATE_STREAM_SUBJECTS.some((subject) => subjectsOverlap(topic, subject)))
45190
+ return false;
45191
+ const role = controllerNoticeRole(topic);
45192
+ if (role !== undefined)
45193
+ return !roles.includes(role);
45194
+ return topic !== ownAgentSubject || /[*>]/.test(ownAgentSubject);
45195
+ }
45196
+ function registrationTopics(ownAgentSubject, followed, roles = []) {
45197
+ return [
45198
+ ...new Set([
45199
+ ownAgentSubject,
45200
+ ...[...followed].filter((topic) => !reachesPrivateStreamSubject(ownAgentSubject, topic, roles) && !streamDeliversNothing(topic))
45201
+ ])
45202
+ ];
45203
+ }
45204
+ function replayFollowedSubjects(ownAgentSubject, topics, heldForRole = () => false) {
45205
+ const followed = [...topics].filter((topic) => !topic.startsWith(ROLE_TOPIC_PREFIX) && !reachesPrivateStreamSubject(ownAgentSubject, topic) && !heldForRole(topic));
45206
+ return [...new Set([ownAgentSubject, ...followed])];
45207
+ }
45208
+ function rememberedTopics(topics) {
45209
+ return (topics ?? []).filter((topic) => !topic.startsWith(AGENT_TOPIC_PREFIX) && !topic.startsWith(ROLE_TOPIC_PREFIX));
45210
+ }
45211
+
45212
+ // ../envoy-client/src/machine.ts
45213
+ import { hostname as hostname3 } from "os";
45214
+ function machineID() {
45215
+ return process.env["ENVOY_MACHINE_ID"] || process.env["AGENTBOX_HOST"] || hostname3();
45216
+ }
45217
+
45218
+ // ../envoy-client/src/transport.ts
45219
+ var SessionStateSchema = _enum2(["live", "unresponsive", "gone"]);
45220
+ var UNRESPONSIVE_RULE = "An unresponsive session is not dead: it keeps its role claims and its issue claims, and a " + "message sent to it is stored until it answers. Start no replacement for it and take no claim " + `from it until it is gone, or until ${ISSUE_CLAIM_UNRESPONSIVE_GRACE_MS / 60000} minutes ` + "have passed since its last_seen, the time of its last registration.";
45221
+ var WireStateSchema = SessionStateSchema.default("live");
45222
+ var InterestWireSchema = object({
45223
+ session_id: string2(),
45224
+ machine_id: string2(),
45225
+ dir: string2(),
45226
+ topics: array(string2()),
45227
+ updated_at: number2().int().optional(),
45228
+ warnings: array(string2()).optional()
45229
+ });
45230
+ var DeliveryAnswerWireSchema = object({
45231
+ mode: literal("consumer"),
45232
+ subject: string2().min(1),
45233
+ stream_id: string2(),
45234
+ gap: boolean2(),
45235
+ consumer_start: number2().int().nonnegative().optional()
45236
+ });
44969
45237
  var SessionWireSchema = object({
44970
45238
  session_id: string2(),
44971
45239
  machine_id: string2(),
@@ -44980,7 +45248,8 @@ var SessionWireSchema = object({
44980
45248
  last_seen: number2().int().optional(),
44981
45249
  state: WireStateSchema,
44982
45250
  plugin: string2().optional(),
44983
- plugin_version: string2().optional()
45251
+ plugin_version: string2().optional(),
45252
+ delivery: string2().optional()
44984
45253
  });
44985
45254
  var RoleWireSchema = object({
44986
45255
  role: string2(),
@@ -45000,13 +45269,13 @@ var RoleHeldWireSchema = object({
45000
45269
  var ErrorWireSchema = object({
45001
45270
  error: string2(),
45002
45271
  code: string2().optional(),
45272
+ reason: string2().optional(),
45003
45273
  expected: array(string2()).optional(),
45004
45274
  state: SessionStateSchema.optional(),
45005
45275
  holder: string2().optional(),
45006
45276
  holder_state: SessionStateSchema.optional(),
45007
45277
  last_seen: number2().int().optional(),
45008
- claim_released: boolean2().optional(),
45009
- unresponsive: array(string2()).optional()
45278
+ claim_released: boolean2().optional()
45010
45279
  });
45011
45280
  var EnvelopeResponseSchema = EnvelopeSchema.extend({
45012
45281
  recipient: string2().optional(),
@@ -45014,46 +45283,30 @@ var EnvelopeResponseSchema = EnvelopeSchema.extend({
45014
45283
  holder_state: SessionStateSchema.optional(),
45015
45284
  recipient_state: SessionStateSchema.optional(),
45016
45285
  last_seen: number2().int().optional(),
45017
- unresponsive: array(string2()).optional(),
45018
45286
  duplicate: boolean2().optional()
45019
45287
  });
45020
45288
  var PublishResponseSchema = EnvelopeResponseSchema.extend({
45021
45289
  kept: boolean2().optional(),
45022
45290
  kept_reason: _enum2(["unclaimed", "holder_lapsed"]).optional()
45023
45291
  });
45024
- var ReplayWireSchema = object({
45025
- stream: object({
45026
- id: string2().min(1).optional(),
45027
- created: string2(),
45028
- first_seq: number2().int().nonnegative(),
45029
- last_seq: number2().int().nonnegative()
45030
- }),
45031
- subjects: array(object({
45032
- subject: string2(),
45033
- messages: array(object({
45034
- seq: number2().int().positive(),
45035
- subject: string2(),
45036
- time: string2(),
45037
- data: string2()
45038
- })),
45039
- next_after: number2().int().nonnegative(),
45040
- more: boolean2(),
45041
- refused: string2().optional()
45042
- }))
45043
- });
45044
- var DELIVERY_NOT_ANSWERED = "not_answered";
45045
- var DELIVERY_UNREADABLE = "unreadable_answer";
45292
+ var DeliveryRefusalSchema = object({
45293
+ mode: string2(),
45294
+ reason: string2().optional()
45295
+ });
45296
+ var DELIVERY_UNREADABLE = "answered a delivery field this build cannot read";
45046
45297
  function parseSubscribeAnswer(body) {
45047
45298
  const interest = InterestWireSchema.parse(body);
45048
45299
  const raw = typeof body === "object" && body !== null && "delivery" in body ? body.delivery : undefined;
45049
45300
  if (raw === undefined || raw === null) {
45050
- return { ...interest, delivery: { mode: "core", reason: DELIVERY_NOT_ANSWERED } };
45301
+ throw new Error(`the listener answered no delivery for ${interest.session_id}: it predates session consumers, and a session receives only what its own consumer holds`);
45051
45302
  }
45052
45303
  const delivery = DeliveryAnswerWireSchema.safeParse(raw);
45053
- return {
45054
- ...interest,
45055
- delivery: delivery.success ? delivery.data : { mode: "core", reason: DELIVERY_UNREADABLE }
45056
- };
45304
+ if (!delivery.success) {
45305
+ const named = DeliveryRefusalSchema.safeParse(raw);
45306
+ const said = named.success ? `answered delivery mode ${named.data.mode}${named.data.reason === undefined ? "" : ` (${named.data.reason})`}` : DELIVERY_UNREADABLE;
45307
+ throw new Error(`the listener gave ${interest.session_id} no consumer: it ${said}, and a session receives only what its own consumer holds`);
45308
+ }
45309
+ return { ...interest, delivery: delivery.data };
45057
45310
  }
45058
45311
  function mergeInterestSources(registryTopics, liveTopics) {
45059
45312
  const interests = new Map;
@@ -45099,27 +45352,20 @@ function expandSubscriptionTopics(topics) {
45099
45352
  if (segments.length < 2 || segments.some((segment) => segment.length === 0)) {
45100
45353
  throw new TypeError(`cannot expand Envoy wildcard topic "${topic}": its concrete base must have at least two non-empty segments`);
45101
45354
  }
45102
- expanded.add(base);
45355
+ if (!streamDeliversNothing(base))
45356
+ expanded.add(base);
45103
45357
  expanded.add(topic);
45104
45358
  }
45105
45359
  return [...expanded];
45106
45360
  }
45107
45361
  function refusalStateText(parsed) {
45108
- const sentences = [];
45109
45362
  const state = parsed.holder_state ?? parsed.state;
45110
- if (state !== undefined) {
45111
- const who = parsed.holder === undefined ? "That session" : `Holder ${parsed.holder}`;
45112
- const seen = parsed.last_seen === undefined || parsed.last_seen <= 0 ? "" : `, last seen ${new Date(parsed.last_seen).toISOString()}`;
45113
- sentences.push(`${who} is ${state}${seen}.`);
45114
- }
45115
- const stored = parsed.unresponsive ?? [];
45116
- if (stored.length > 0) {
45117
- const one = stored.length === 1;
45118
- sentences.push(`Envoy stored the message for ${stored.join(", ")}.`, `${one ? "That session" : "Those sessions"} stopped answering, so ${one ? "it" : "they"} did not fail this send.`);
45119
- }
45120
- if (sentences.length === 0)
45363
+ if (state === undefined)
45121
45364
  return "";
45122
- if (state === "unresponsive" || stored.length > 0)
45365
+ const who = parsed.holder === undefined ? "That session" : `Holder ${parsed.holder}`;
45366
+ const seen = parsed.last_seen === undefined || parsed.last_seen <= 0 ? "" : `, last seen ${new Date(parsed.last_seen).toISOString()}`;
45367
+ const sentences = [`${who} is ${state}${seen}.`];
45368
+ if (state === "unresponsive")
45123
45369
  sentences.push(UNRESPONSIVE_RULE);
45124
45370
  return ` ${sentences.join(" ")}`;
45125
45371
  }
@@ -45129,11 +45375,11 @@ class EnvoyApiError extends Error {
45129
45375
  name = "EnvoyApiError";
45130
45376
  expected;
45131
45377
  code;
45378
+ reason;
45132
45379
  holder;
45133
45380
  sessionState;
45134
45381
  lastSeen;
45135
45382
  claimReleased;
45136
- unresponsive;
45137
45383
  constructor(details) {
45138
45384
  let parsed;
45139
45385
  try {
@@ -45141,15 +45387,15 @@ class EnvoyApiError extends Error {
45141
45387
  if (result.success)
45142
45388
  parsed = result.data;
45143
45389
  } catch {}
45144
- super(parsed === undefined ? `${details.method} ${details.url} failed with ${details.status}: ${details.responseBody}` : `${parsed.error}${parsed.expected === undefined ? "" : ` (expected: ${parsed.expected.join(", ")})`}${refusalStateText(parsed)}`);
45390
+ super(parsed === undefined ? `${details.method} ${details.url} failed with ${details.status}: ${details.responseBody}` : `${parsed.error}${parsed.reason === undefined ? "" : ` (reason: ${parsed.reason})`}${parsed.expected === undefined ? "" : ` (expected: ${parsed.expected.join(", ")})`}${refusalStateText(parsed)}`);
45145
45391
  this.details = details;
45146
45392
  this.expected = parsed?.expected;
45147
45393
  this.code = parsed?.code;
45394
+ this.reason = parsed?.reason;
45148
45395
  this.holder = parsed?.holder;
45149
45396
  this.sessionState = parsed?.holder_state ?? parsed?.state;
45150
45397
  this.lastSeen = parsed?.last_seen;
45151
45398
  this.claimReleased = parsed?.claim_released;
45152
- this.unresponsive = parsed?.unresponsive;
45153
45399
  }
45154
45400
  }
45155
45401
  var mintedDedupeKey2 = new RegExp(MINTED_DEDUPE_KEY_PATTERN);
@@ -45259,23 +45505,24 @@ function createEnvoyClient(config) {
45259
45505
  headers: { "Content-Type": "application/json" },
45260
45506
  body: JSON.stringify(body)
45261
45507
  }, options);
45508
+ const subscribeBody = (input) => ({
45509
+ session_id: input.sessionID,
45510
+ dir: input.directory,
45511
+ topics: expandSubscriptionTopics(input.topics),
45512
+ port: input.port,
45513
+ title: input.title,
45514
+ ...input.capabilities === undefined ? {} : { capabilities: input.capabilities },
45515
+ driving: input.driving,
45516
+ ...input.selfSubscribed === undefined ? {} : { self_subscribed: input.selfSubscribed },
45517
+ delivery: input.delivery,
45518
+ ...input.clientInstanceID === undefined ? {} : { client_instance_id: input.clientInstanceID },
45519
+ host: machineID(),
45520
+ ...input.place === undefined ? {} : { tmux_place: input.place },
45521
+ plugin: input.plugin.name,
45522
+ plugin_version: input.plugin.version
45523
+ });
45262
45524
  return {
45263
- subscribe: async (input) => parseSubscribeAnswer(JSON.parse(await post("/v1/interests/subscribe", {
45264
- session_id: input.sessionID,
45265
- dir: input.directory,
45266
- topics: expandSubscriptionTopics(input.topics),
45267
- port: input.port,
45268
- title: input.title,
45269
- ...input.capabilities === undefined ? {} : { capabilities: input.capabilities },
45270
- driving: input.driving,
45271
- ...input.selfSubscribed === undefined ? {} : { self_subscribed: input.selfSubscribed },
45272
- ...input.delivery === undefined ? {} : { delivery: input.delivery },
45273
- ...input.clientInstanceID === undefined ? {} : { client_instance_id: input.clientInstanceID },
45274
- host: machineID(),
45275
- ...input.place === undefined ? {} : { tmux_place: input.place },
45276
- plugin: input.plugin.name,
45277
- plugin_version: input.plugin.version
45278
- }, { actingSession: input.sessionID }))),
45525
+ subscribe: async (input) => parseSubscribeAnswer(JSON.parse(await post("/v1/interests/subscribe", subscribeBody(input), { actingSession: input.sessionID }))),
45279
45526
  unsubscribe: async (input) => {
45280
45527
  await post("/v1/interests/unsubscribe", {
45281
45528
  session_id: input.sessionID,
@@ -45334,915 +45581,74 @@ function createEnvoyClient(config) {
45334
45581
  envelope: response,
45335
45582
  ...response.holder === undefined ? {} : { holder: response.holder },
45336
45583
  ...response.holder_state === undefined ? {} : { holderState: response.holder_state },
45337
- unresponsive: response.unresponsive ?? [],
45338
45584
  ...response.kept === undefined ? {} : { kept: response.kept },
45339
45585
  ...response.kept_reason === undefined ? {} : { keptReason: response.kept_reason }
45340
45586
  };
45341
45587
  },
45342
45588
  unregisterSession: async (input) => {
45343
45589
  const query = input.clientInstanceID === undefined ? "" : `?client_instance_id=${encodeURIComponent(input.clientInstanceID)}`;
45344
- await request(`/v1/sessions/${encodeURIComponent(input.sessionID)}${query}`, { method: "DELETE" }, { actingSession: input.sessionID });
45345
- },
45346
- setRole: async (input) => {
45347
- const soft = input.soft === true;
45348
- const previous = soft ? input.previousSessionID ?? "" : "";
45349
- const body = {
45350
- session_id: input.sessionID,
45351
- role: input.role,
45352
- ...soft ? { soft: true } : {},
45353
- ...previous === "" ? {} : { previous_session_id: previous },
45354
- ...input.clientInstanceID === undefined ? {} : { client_instance_id: input.clientInstanceID }
45355
- };
45356
- let raw;
45357
- try {
45358
- raw = await post("/v1/roles/set", body, { actingSession: input.sessionID });
45359
- } catch (error) {
45360
- if (error instanceof EnvoyApiError && error.details.status === 409) {
45361
- let answer;
45362
- try {
45363
- answer = JSON.parse(error.details.responseBody);
45364
- } catch {
45365
- throw error;
45366
- }
45367
- const held = RoleHeldWireSchema.safeParse(answer);
45368
- if (held.success)
45369
- return { claimed: false, holder: held.data.holder };
45370
- }
45371
- throw error;
45372
- }
45373
- return { claimed: true, interest: InterestWireSchema.parse(JSON.parse(raw)) };
45374
- },
45375
- getRole: async (role) => RoleWireSchema.parse(JSON.parse(await request(`/v1/roles/${encodeURIComponent(role)}`, { method: "GET" }))),
45376
- listSessions: async (input = {}) => {
45377
- const search = new URLSearchParams;
45378
- if (input.directory !== undefined)
45379
- search.set("dir", input.directory);
45380
- if (input.title !== undefined)
45381
- search.set("title", input.title);
45382
- if (input.include !== undefined)
45383
- search.set("include", input.include);
45384
- const query = search.size === 0 ? "" : `?${search.toString()}`;
45385
- return SessionWireSchema.array().parse(JSON.parse(await request(`/v1/sessions${query}`, {})));
45386
- },
45387
- replay: async (input) => ReplayWireSchema.parse(JSON.parse(await post("/v1/replay", {
45388
- session_id: input.sessionID,
45389
- subjects: input.subjects.map((cursor) => cursor.after === undefined ? { subject: cursor.subject } : { subject: cursor.subject, after: cursor.after }),
45390
- ...input.maxMessages === undefined ? {} : { max_messages: input.maxMessages }
45391
- }, {
45392
- timeoutMs: input.timeoutMs ?? REPLAY_TIMEOUT_MS,
45393
- retry: false,
45394
- actingSession: input.sessionID
45395
- })))
45396
- };
45397
- }
45398
- function waitForRetry(delayMs) {
45399
- const { promise, resolve } = Promise.withResolvers();
45400
- setTimeout(resolve, delayMs);
45401
- return promise;
45402
- }
45403
- function messageMetadata(input) {
45404
- return {
45405
- ...input.inReplyTo === undefined ? {} : { in_reply_to: input.inReplyTo },
45406
- ...input.supersedes === undefined ? {} : { supersedes: input.supersedes },
45407
- ...input.urgency === undefined ? {} : { urgency: input.urgency },
45408
- ...input.expectsReply === undefined ? {} : { expects_reply: input.expectsReply },
45409
- ...input.expiresAt === undefined ? {} : { expires_at: input.expiresAt }
45410
- };
45411
- }
45412
- function sourceSession(sessionID) {
45413
- return sessionID === undefined || sessionID === "" ? {} : { source_session: sessionID };
45414
- }
45415
-
45416
- // ../envoy-client/src/replay.ts
45417
- var REPLAY_LEDGER_TTL_MS = DELIVERY_DUPLICATE_WINDOW_MS;
45418
- var REPLAY_LEDGER_LIMIT = 20000;
45419
- var REPLAY_PAGES_PER_SWEEP = 20;
45420
- var REPLAY_FAILURES_BEFORE_NOTICE = 3;
45421
- var REPLAY_STATE_REFRESH_MS = 60 * 60 * 1000;
45422
- var REPLAY_MAX_SUBJECTS = 32;
45423
- var START_CURSORS_TIMEOUT_MS = 2000;
45424
- var ROLE_FORWARD_KEY_PREFIX = "envoy.role.forward.";
45425
- var ReplayLedgerEntrySchema = object({
45426
- event_id: string2().min(1).optional(),
45427
- dedupe_key: string2().min(1).optional(),
45428
- at: number2()
45429
- });
45430
- var ReplayCursorSchema = object({
45431
- since: number2().int().nonnegative().optional(),
45432
- after: number2().int().nonnegative().optional(),
45433
- from_start: number2().int().nonnegative().optional()
45434
- });
45435
- var ReplayPendingNoticeSchema = _enum2([
45436
- "retention_gap",
45437
- "stream_moved_back",
45438
- "stream_recreated"
45439
- ]);
45440
- var PENDING_NOTICE_MESSAGES = {
45441
- stream_recreated: "Envoy's notification stream was recreated, so messages published to this session while its connection was down before that may be lost.",
45442
- stream_moved_back: "Envoy's notification stream was restored to an earlier point, so messages published to this session while its connection was down may be shown again, and any published between that point and the restore are missing.",
45443
- retention_gap: "The notification stream no longer holds some messages published to this session while its connection was down: messages older than 72 hours may be missing."
45444
- };
45445
- var ReplayStateSchema = object({
45446
- stream_id: string2().optional(),
45447
- stream_created: string2().optional(),
45448
- subjects: record(string2(), ReplayCursorSchema),
45449
- notices: array(string2()).optional()
45450
- });
45451
- var ReplaySnapshotSchema = object({
45452
- state: ReplayStateSchema.optional(),
45453
- ledger: array(ReplayLedgerEntrySchema)
45454
- });
45455
- function createReplayEngine(options) {
45456
- const { host, transport, dedupe } = options;
45457
- const now = options.now ?? Date.now;
45458
- const ledger = createLedger(now);
45459
- const cursors = new Map;
45460
- const cursorStarts = new Map;
45461
- let streamID;
45462
- let streamCreated;
45463
- const pending = new Set;
45464
- const failures = new Map;
45465
- let unwritten = [];
45466
- let writtenState;
45467
- let writtenShape;
45468
- let writtenAt;
45469
- let writes = Promise.resolve();
45470
- let epoch = 0;
45471
- let listenerNoticed;
45472
- const answered = new Set;
45473
- let running;
45474
- let rerun;
45475
- let consumerMode = false;
45476
- const safely = (what, call) => {
45477
- try {
45478
- call();
45479
- } catch (error) {
45480
- try {
45481
- host.log(`replay: ${what} failed`, error);
45482
- } catch {}
45483
- }
45484
- };
45485
- const log = (message, error) => safely("log", () => host.log(message, error));
45486
- const notify = (notice) => safely("notice", () => host.notify(notice));
45487
- const tell = (kind) => {
45488
- pending.delete(kind);
45489
- notify({ kind, message: PENDING_NOTICE_MESSAGES[kind] });
45490
- };
45491
- const sessionRead = (read) => () => {
45492
- try {
45493
- return read();
45494
- } catch {
45495
- return;
45496
- }
45497
- };
45498
- const currentSession = sessionRead(() => host.sessionID());
45499
- const writeSession = sessionRead(() => host.writeSessionID === undefined ? host.sessionID() : host.writeSessionID());
45500
- const bindTo = (sessionID, read) => {
45501
- if (sessionID === undefined || sessionID === "" || read() !== sessionID)
45502
- return;
45503
- const bound = epoch;
45504
- return { sessionID, alive: () => bound === epoch && read() === sessionID };
45505
- };
45506
- const bind = () => bindTo(currentSession(), currentSession);
45507
- const stateJSON = (afters = true) => {
45508
- const subjects = {};
45509
- for (const subject of [...cursors.keys()].sort()) {
45510
- const cursor = cursors.get(subject) ?? {};
45511
- subjects[subject] = {
45512
- ...cursor.since === undefined ? {} : { since: cursor.since },
45513
- ...!afters || cursor.after === undefined ? {} : { after: cursor.after },
45514
- ...cursor.from_start === undefined ? {} : { from_start: cursor.from_start }
45515
- };
45516
- }
45517
- return JSON.stringify({
45518
- ...streamID === undefined ? {} : { stream_id: streamID },
45519
- ...streamCreated === undefined ? {} : { stream_created: streamCreated },
45520
- subjects,
45521
- ...pending.size === 0 ? {} : { notices: [...pending].sort() }
45522
- });
45523
- };
45524
- const record2 = (identity) => {
45525
- const entry = ledger.record(identity);
45526
- if (entry !== undefined)
45527
- unwritten.push(entry);
45528
- };
45529
- const flush = (alive, atOnce = false) => {
45530
- const written = writes.then(async () => {
45531
- if (!alive())
45532
- return false;
45533
- const json = stateJSON();
45534
- const delivered = unwritten;
45535
- if (json === writtenState && delivered.length === 0)
45536
- return true;
45537
- const shape = stateJSON(false);
45538
- if (delivered.length === 0 && !atOnce && shape === writtenShape && writtenAt !== undefined && now() - writtenAt < REPLAY_STATE_REFRESH_MS) {
45539
- return true;
45540
- }
45541
- unwritten = [];
45542
- const state = json === writtenState ? undefined : JSON.parse(json);
45543
- try {
45544
- await host.write({
45545
- delivered,
45546
- state,
45547
- snapshot: () => ({ state: JSON.parse(json), ledger: ledger.list() })
45548
- });
45549
- if (state !== undefined) {
45550
- writtenState = json;
45551
- writtenShape = shape;
45552
- writtenAt = now();
45553
- }
45554
- return true;
45555
- } catch (error) {
45556
- unwritten = [...delivered, ...unwritten];
45557
- log("replay: could not persist the replay state; the next write carries it", error);
45558
- return false;
45559
- }
45560
- });
45561
- writes = written.then(() => {
45562
- return;
45563
- });
45564
- return written;
45565
- };
45566
- const syncFollowed = () => {
45567
- const followed = new Set(host.followedSubjects());
45568
- for (const subject of [...cursors.keys()]) {
45569
- if (!followed.has(subject)) {
45570
- cursors.delete(subject);
45571
- cursorStarts.delete(subject);
45572
- }
45573
- }
45574
- for (const subject of followed) {
45575
- if (!cursors.has(subject))
45576
- cursors.set(subject, {});
45577
- }
45578
- };
45579
- const failureNotice = (envelope, publishedAt, error, subject) => ({
45580
- eventId: envelope.event_id ?? "unknown",
45581
- sender: senderLabel(envelope),
45582
- summary: envelope.payload_summary ?? "unknown",
45583
- publishedAt,
45584
- error,
45585
- readWith: envelope.source === "dispatch" ? "dispatch read" : "envoy_inbox",
45586
- ...subject === undefined ? {} : { subject },
45587
- envelope
45588
- });
45589
- const showFailureNotice = async (notice, alive) => {
45590
- let queued;
45591
- try {
45592
- queued = await host.showFailureNotice(notice) === "queued";
45593
- } catch (error) {
45594
- if (!alive())
45595
- return "stopped";
45596
- safely("failure notice warning", () => host.failureNoticeFailed(notice, error));
45597
- return "hole";
45598
- }
45599
- if (!alive())
45600
- return "stopped";
45601
- if (queued)
45602
- return "hole";
45603
- record2(replayLedgerIdentity(notice.envelope));
45604
- await flush(alive);
45605
- return "done";
45606
- };
45607
- const handle = async (seq, buffered, alive) => {
45608
- const { message } = buffered;
45609
- const envelope = parseEnvelope(message.data);
45610
- if (envelope === undefined) {
45611
- log(`replay: skipping stored message ${seq} on ${message.subject}: not an Envoy envelope`);
45612
- return "done";
45613
- }
45614
- if (isRoleForward(envelope))
45615
- return "done";
45616
- const identity = replayLedgerIdentity(envelope);
45617
- if (ledger.has(identity)) {
45618
- failures.delete(seq);
45619
- return "done";
45620
- }
45621
- if (dedupe?.pending(envelope) === true)
45622
- return "hole";
45623
- if (!alive())
45624
- return "stopped";
45625
- const giveUp = async (error) => {
45626
- const handled = await showFailureNotice(failureNotice(envelope, message.time, error, message.subject), alive);
45627
- if (handled === "done")
45628
- failures.delete(seq);
45629
- return handled;
45630
- };
45631
- const failure = failures.get(seq);
45632
- if (failure !== undefined && failure.count >= REPLAY_FAILURES_BEFORE_NOTICE) {
45633
- return giveUp(failure.error);
45634
- }
45635
- const followed = buffered.subjects[0] ?? message.subject;
45636
- let outcome;
45637
- let error = "the host could not show it";
45638
- try {
45639
- outcome = await host.deliver({
45640
- envelope,
45641
- data: message.data,
45642
- seq,
45643
- subject: message.subject,
45644
- followed,
45645
- time: message.time,
45646
- since: cursors.get(followed)?.since
45647
- });
45648
- } catch (thrown) {
45649
- outcome = "failed";
45650
- error = messageFor(thrown);
45651
- }
45652
- if (!alive())
45653
- return "stopped";
45654
- if (outcome === "shown") {
45655
- failures.delete(seq);
45656
- record2(identity);
45657
- await flush(alive);
45658
- return "done";
45659
- }
45660
- if (outcome === "suppressed") {
45661
- failures.delete(seq);
45662
- return "done";
45663
- }
45664
- if (outcome === "queued") {
45665
- failures.delete(seq);
45666
- return "hole";
45667
- }
45668
- const count = (failure?.count ?? 0) + 1;
45669
- failures.set(seq, { count, error });
45670
- if (count >= REPLAY_FAILURES_BEFORE_NOTICE)
45671
- return giveUp(error);
45672
- log(`replay: could not show stored message ${seq} (${envelope.event_id}): ${error}`);
45673
- return "hole";
45674
- };
45675
- const listenerFailed = (error) => {
45676
- if (error instanceof EnvoyApiError) {
45677
- const status = error.details.status;
45678
- if (status === 404) {
45679
- if (listenerNoticed === "not_served")
45680
- return;
45681
- listenerNoticed = "not_served";
45682
- notify({
45683
- kind: "not_served",
45684
- message: "This session's Envoy listener does not serve replay (POST /v1/replay answered 404), so messages published while its connection is down are not recovered."
45685
- });
45686
- return;
45687
- }
45688
- if (status === 503 && error.code === REPLAY_UNAVAILABLE_CODE || status === 401 || status === 403) {
45689
- const key = `unavailable:${status}:${error.message}`;
45690
- if (listenerNoticed === key)
45691
- return;
45692
- listenerNoticed = key;
45693
- notify({
45694
- kind: "unavailable",
45695
- status,
45696
- error: error.message,
45697
- message: `Envoy replay is unavailable (${status}: ${error.message}), so messages published while this session's connection is down are not recovered until it answers.`
45698
- });
45699
- return;
45700
- }
45701
- }
45702
- log("replay: the listener's replay failed; the next trigger tries again", error);
45703
- };
45704
- const streamReplaced = (stream) => {
45705
- if (stream.id === undefined) {
45706
- return streamCreated !== undefined && streamCreated !== "" && stream.created !== streamCreated;
45707
- }
45708
- return streamID !== undefined && streamID !== "" && stream.id !== streamID;
45709
- };
45710
- const streamMovedBack = (stream) => {
45711
- for (const cursor of cursors.values()) {
45712
- if (cursor.after !== undefined && cursor.after > stream.last_seq)
45713
- return true;
45714
- }
45715
- return false;
45716
- };
45717
- const sweepOnce = async () => {
45718
- const binding = bind();
45719
- if (binding === undefined)
45720
- return;
45721
- const { sessionID, alive } = binding;
45722
- syncFollowed();
45723
- const readings = new Map;
45724
- for (const [subject, cursor] of cursors) {
45725
- readings.set(subject, {
45726
- read: cursor.from_start === undefined ? cursor.after : 0,
45727
- more: true
45728
- });
45729
- }
45730
- const buffer = new Map;
45731
- const holes = new Map;
45732
- let gapNoticed = false;
45733
- if (pending.size > 0) {
45734
- for (const kind of [...pending].sort()) {
45735
- if (kind === "retention_gap")
45736
- gapNoticed = true;
45737
- tell(kind);
45738
- }
45739
- await flush(alive);
45740
- if (!alive())
45741
- return;
45742
- }
45743
- if (consumerMode)
45744
- return;
45745
- for (let page = 0;page < REPLAY_PAGES_PER_SWEEP; page += 1) {
45746
- let handledAny = false;
45747
- const asking = [...readings].filter(([, reading]) => reading.more).sort(([, a], [, b]) => (a.read ?? -1) - (b.read ?? -1)).slice(0, REPLAY_MAX_SUBJECTS);
45748
- if (asking.length === 0)
45749
- break;
45750
- let response;
45751
- try {
45752
- response = await transport.replay({
45753
- sessionID,
45754
- subjects: asking.map(([subject, reading]) => reading.read === undefined ? { subject } : { subject, after: reading.read }),
45755
- ...options.maxMessages === undefined ? {} : { maxMessages: options.maxMessages }
45756
- });
45757
- } catch (error) {
45758
- if (alive()) {
45759
- answered.clear();
45760
- listenerFailed(error);
45761
- }
45762
- return;
45763
- }
45764
- if (!alive())
45765
- return;
45766
- listenerNoticed = undefined;
45767
- for (const result of response.subjects) {
45768
- if (result.refused === undefined)
45769
- answered.add(result.subject);
45770
- else
45771
- answered.delete(result.subject);
45772
- }
45773
- const { stream } = response;
45774
- const replaced = streamReplaced(stream);
45775
- streamID = stream.id ?? (replaced ? undefined : streamID);
45776
- streamCreated = stream.created;
45777
- if (replaced) {
45778
- const at = now();
45779
- for (const subject of cursors.keys()) {
45780
- cursors.set(subject, { since: stream.last_seq, after: stream.last_seq });
45781
- cursorStarts.set(subject, at);
45782
- }
45783
- failures.clear();
45784
- pending.add("stream_recreated");
45785
- await flush(alive);
45786
- if (!alive())
45787
- return;
45788
- tell("stream_recreated");
45789
- await flush(alive);
45790
- return;
45791
- }
45792
- if (streamMovedBack(stream)) {
45793
- const from = Math.max(0, stream.first_seq - 1);
45794
- for (const [subject, cursor] of cursors) {
45795
- if (cursor.after === undefined)
45796
- continue;
45797
- cursors.set(subject, { ...cursor, after: from });
45798
- const reading = readings.get(subject);
45799
- if (reading !== undefined) {
45800
- reading.read = from;
45801
- reading.more = true;
45802
- }
45803
- }
45804
- buffer.clear();
45805
- holes.clear();
45806
- failures.clear();
45807
- pending.add("stream_moved_back");
45808
- await flush(alive, true);
45809
- if (!alive())
45810
- return;
45811
- tell("stream_moved_back");
45812
- await flush(alive);
45813
- if (!alive())
45814
- return;
45815
- continue;
45816
- }
45817
- for (const [, reading] of asking)
45818
- reading.more = false;
45819
- for (const result of response.subjects) {
45820
- const reading = readings.get(result.subject);
45821
- const markedAt = cursors.get(result.subject)?.from_start;
45822
- if (reading === undefined || markedAt === undefined || result.refused !== undefined) {
45823
- continue;
45824
- }
45825
- const start = Math.max(0, stream.first_seq - 1);
45826
- cursors.set(result.subject, { since: start, after: start });
45827
- cursorStarts.set(result.subject, now());
45828
- if (now() - markedAt < DELIVERY_DUPLICATE_WINDOW_MS)
45829
- reading.read = start;
45830
- }
45831
- let gapped = false;
45832
- for (const result of response.subjects) {
45833
- const reading = readings.get(result.subject);
45834
- if (reading?.read === undefined || result.refused !== undefined)
45835
- continue;
45836
- if (reading.read >= stream.first_seq - 1)
45837
- continue;
45838
- gapped = true;
45839
- reading.read = stream.first_seq - 1;
45840
- const cursor = cursors.get(result.subject);
45841
- if (cursor?.after !== undefined && cursor.after < reading.read) {
45842
- cursors.set(result.subject, { ...cursor, after: reading.read });
45843
- }
45844
- }
45845
- if (gapped) {
45846
- if (!gapNoticed)
45847
- pending.add("retention_gap");
45848
- await flush(alive, true);
45849
- if (!alive())
45850
- return;
45851
- if (pending.has("retention_gap")) {
45852
- gapNoticed = true;
45853
- tell("retention_gap");
45854
- await flush(alive);
45855
- }
45856
- }
45857
- for (const result of response.subjects) {
45858
- const reading = readings.get(result.subject);
45859
- if (reading === undefined || result.refused !== undefined)
45860
- continue;
45861
- if (reading.read === undefined) {
45862
- const cursor = cursors.get(result.subject);
45863
- if (cursor !== undefined && cursor.after === undefined) {
45864
- cursors.set(result.subject, { since: result.next_after, after: result.next_after });
45865
- cursorStarts.set(result.subject, now());
45866
- }
45867
- reading.read = result.next_after;
45868
- continue;
45869
- }
45870
- for (const message of result.messages) {
45871
- if (message.seq <= reading.read)
45872
- continue;
45873
- const buffered = buffer.get(message.seq);
45874
- if (buffered === undefined) {
45875
- buffer.set(message.seq, { message, subjects: [result.subject] });
45876
- } else if (!buffered.subjects.includes(result.subject)) {
45877
- buffered.subjects.push(result.subject);
45878
- }
45879
- }
45880
- reading.read = Math.max(reading.read, result.next_after);
45881
- reading.more = result.more;
45882
- }
45883
- let bound = Number.POSITIVE_INFINITY;
45884
- for (const reading of readings.values()) {
45885
- if (reading.more && reading.read !== undefined)
45886
- bound = Math.min(bound, reading.read);
45887
- }
45888
- const ready = [...buffer.keys()].filter((seq) => seq <= bound).sort((a, b) => a - b);
45889
- for (const seq of ready) {
45890
- const buffered = buffer.get(seq);
45891
- if (buffered === undefined)
45892
- continue;
45893
- buffer.delete(seq);
45894
- if (!buffered.subjects.some((subject) => cursors.has(subject)))
45895
- continue;
45896
- const handled = await handle(seq, buffered, alive);
45897
- if (handled === "stopped")
45898
- return;
45899
- if (handled === "done")
45900
- handledAny = true;
45901
- if (handled === "hole") {
45902
- for (const subject of buffered.subjects) {
45903
- if (!holes.has(subject))
45904
- holes.set(subject, seq);
45905
- }
45906
- }
45907
- }
45908
- if (!alive())
45909
- return;
45910
- for (const [subject, reading] of readings) {
45911
- const cursor = cursors.get(subject);
45912
- if (cursor?.after === undefined || reading.read === undefined)
45913
- continue;
45914
- let after = Math.min(reading.read, bound);
45915
- const hole = holes.get(subject);
45916
- if (hole !== undefined)
45917
- after = Math.min(after, hole - 1);
45918
- if (after > cursor.after)
45919
- cursors.set(subject, { ...cursor, after });
45920
- }
45921
- await flush(alive, handledAny);
45922
- if (![...readings.values()].some((reading) => reading.more))
45923
- break;
45924
- }
45925
- };
45926
- const runSweep = async () => {
45927
- try {
45928
- await sweepOnce();
45929
- } catch (error) {
45930
- log("replay: a sweep failed", error);
45931
- }
45932
- };
45933
- const sweep = () => {
45934
- if (running === undefined) {
45935
- running = runSweep().finally(() => {
45936
- running = undefined;
45937
- });
45938
- return running;
45939
- }
45940
- rerun ??= running.then(() => {
45941
- rerun = undefined;
45942
- return sweep();
45943
- });
45944
- return rerun;
45945
- };
45946
- const started = (cursor) => cursor?.after !== undefined || cursor?.from_start !== undefined;
45947
- const startOnce = async () => {
45948
- const binding = bind();
45949
- if (binding === undefined)
45950
- return;
45951
- const { sessionID, alive } = binding;
45952
- const unstarted = [...new Set(host.followedSubjects())].filter((subject) => !started(cursors.get(subject)));
45953
- let changed = false;
45954
- for (let index = 0;index < unstarted.length; index += REPLAY_MAX_SUBJECTS) {
45955
- let response;
45956
- try {
45957
- response = await transport.replay({
45958
- sessionID,
45959
- subjects: unstarted.slice(index, index + REPLAY_MAX_SUBJECTS).map((subject) => ({ subject })),
45960
- timeoutMs: START_CURSORS_TIMEOUT_MS
45961
- });
45962
- } catch (error) {
45963
- if (!alive())
45964
- return;
45965
- const own = `${AGENT_TOPIC_PREFIX}${sessionID}`;
45966
- const marked = unstarted.includes(own) && !started(cursors.get(own));
45967
- if (marked) {
45968
- cursors.set(own, { from_start: now() });
45969
- changed = true;
45970
- }
45971
- log(marked ? `replay: could not read the stream's position for ${own} before registering while the session's NATS connection is down; its first sweep once the connection is back reads it from the stream's oldest message, so what is stored for it meanwhile is shown` : "replay: could not read the stream's position before registering while the session's NATS connection is down; the first sweep starts the cursors instead", error);
45972
- break;
45973
- }
45974
- if (!alive())
45975
- return;
45976
- const { stream } = response;
45977
- if (streamReplaced(stream))
45978
- break;
45979
- streamID = stream.id ?? streamID;
45980
- streamCreated = stream.created;
45981
- const at = now();
45982
- for (const result of response.subjects) {
45983
- if (result.refused !== undefined || started(cursors.get(result.subject)))
45984
- continue;
45985
- cursors.set(result.subject, { since: result.next_after, after: result.next_after });
45986
- cursorStarts.set(result.subject, at);
45987
- changed = true;
45988
- }
45989
- }
45990
- if (changed)
45991
- await flush(alive, true);
45992
- };
45993
- const startCursors = async () => {
45994
- while (running !== undefined)
45995
- await running;
45996
- running = startOnce().catch((error) => log("replay: starting the cursors failed", error)).finally(() => {
45997
- running = undefined;
45998
- });
45999
- await running;
46000
- };
46001
- return {
46002
- sweep,
46003
- startCursors,
46004
- startPending: () => [...cursors.values()].some((cursor) => cursor.from_start !== undefined),
46005
- setConsumerMode(on) {
46006
- consumerMode = on;
46007
- },
46008
- async followedChanged() {
46009
- const alive = bind()?.alive;
46010
- if (alive === undefined)
46011
- return;
46012
- try {
46013
- syncFollowed();
46014
- await flush(alive);
46015
- } catch (error) {
46016
- log("replay: could not take the followed subjects", error);
46017
- }
46018
- },
46019
- delivered: (frame) => ledger.has(replayLedgerIdentity(frame)),
46020
- async recordDelivered(frame) {
46021
- const alive = bind()?.alive;
46022
- if (alive === undefined)
46023
- return;
46024
- record2(replayLedgerIdentity(frame));
46025
- await flush(alive);
46026
- },
46027
- async recordDeliveredFor(sessionID, frame) {
46028
- const alive = bindTo(sessionID, writeSession)?.alive;
46029
- if (alive === undefined)
46030
- return false;
46031
- record2(replayLedgerIdentity(frame));
46032
- return await flush(alive);
46033
- },
46034
- async liveFailed(sessionID, followed, envelope, error, receivedAt) {
46035
- const started = cursorStarts.get(followed);
46036
- if (!isRoleForward(envelope) && answered.has(followed) && cursors.get(followed)?.after !== undefined && (started === undefined || started <= receivedAt)) {
46037
- return;
46038
- }
46039
- const alive = bindTo(sessionID, currentSession)?.alive;
46040
- if (alive === undefined) {
46041
- log("replay: a failed frame was not reported here; the session it names is closed");
46042
- return;
46043
- }
46044
- try {
46045
- await showFailureNotice(failureNotice(envelope, inboundTimestamp(envelope.issued_at), messageFor(error)), alive);
46046
- } catch (thrown) {
46047
- log("replay: could not report a failed live frame", thrown);
46048
- }
46049
- },
46050
- followedBefore: (topic, seq) => {
46051
- const since = cursors.get(topic)?.since;
46052
- return since !== undefined && seq > since;
46053
- },
46054
- restore(snapshot) {
46055
- epoch += 1;
46056
- ledger.restore(snapshot.ledger);
46057
- cursors.clear();
46058
- cursorStarts.clear();
46059
- streamID = snapshot.state?.stream_id;
46060
- streamCreated = snapshot.state?.stream_created;
46061
- pending.clear();
46062
- for (const kind of snapshot.state?.notices ?? []) {
46063
- const known = ReplayPendingNoticeSchema.safeParse(kind);
46064
- if (known.success)
46065
- pending.add(known.data);
46066
- }
46067
- for (const [subject, cursor] of Object.entries(snapshot.state?.subjects ?? {})) {
46068
- cursors.set(subject, { ...cursor });
46069
- }
46070
- writtenState = snapshot.state === undefined ? undefined : stateJSON();
46071
- writtenShape = snapshot.state === undefined ? undefined : stateJSON(false);
46072
- writtenAt = undefined;
46073
- unwritten = [];
46074
- failures.clear();
46075
- listenerNoticed = undefined;
46076
- answered.clear();
46077
- },
46078
- state: () => JSON.parse(stateJSON())
46079
- };
46080
- }
46081
- function replaySuppressed(rendered) {
46082
- return rendered.skip || rendered.malformedDelivery === true;
46083
- }
46084
- var REPLAYED_SUFFIX = "while this session's connection was down.";
46085
- function replayedText(content, publishedAt) {
46086
- return `${content}
46087
- Published at ${publishedAt} ${REPLAYED_SUFFIX}`;
46088
- }
46089
- function failureNoticeFields(notice) {
46090
- const readWith = notice.readWith === "dispatch read" ? "Read it with the `dispatch read` command on the issue or ask it concerns." : "Read it with the envoy_inbox tool.";
46091
- return {
46092
- notice: "message not shown",
46093
- event_id: notice.eventId,
46094
- from: notice.sender,
46095
- summary: notice.summary,
46096
- published_at: notice.publishedAt,
46097
- ...notice.subject === undefined ? {} : { subject: notice.subject },
46098
- error: notice.error,
46099
- detail: `This session could not be shown this message, so it is not coming back on its own. ${readWith}`
46100
- };
46101
- }
46102
- var REPLAY_NOTICE_NAMES = {
46103
- stream_recreated: "stream recreated",
46104
- stream_moved_back: "stream moved back"
46105
- };
46106
- function replayNoticeFields(notice) {
46107
- return {
46108
- notice: REPLAY_NOTICE_NAMES[notice.kind] ?? "messages may be missing",
46109
- detail: notice.message
46110
- };
46111
- }
46112
- function envoyNoticeText(fields) {
46113
- return encode5({ envoy: fields });
46114
- }
46115
- var PRIVATE_STREAM_SUBJECTS = [
46116
- `${AGENT_TOPIC_PREFIX}>`,
46117
- `${LEGION_NOTICE_TOPIC_PREFIX}>`,
46118
- `${EXCEPTION_TOPIC_PREFIX}${AGENT_TOPIC_PREFIX}>`
46119
- ];
46120
- function subjectsOverlap(a, b) {
46121
- const aTokens = a.split(".");
46122
- const bTokens = b.split(".");
46123
- for (let index = 0;index < aTokens.length && index < bTokens.length; index += 1) {
46124
- const aToken = aTokens[index];
46125
- const bToken = bTokens[index];
46126
- if (aToken === ">" || bToken === ">")
46127
- return true;
46128
- if (aToken !== "*" && bToken !== "*" && aToken !== bToken)
46129
- return false;
46130
- }
46131
- return aTokens.length === bTokens.length;
46132
- }
46133
- function reachesPrivateStreamSubject(ownAgentSubject, topic) {
46134
- if (!PRIVATE_STREAM_SUBJECTS.some((subject) => subjectsOverlap(topic, subject)))
46135
- return false;
46136
- return topic !== ownAgentSubject || /[*>]/.test(ownAgentSubject);
46137
- }
46138
- function replayFollowedSubjects(ownAgentSubject, topics, heldForRole = () => false) {
46139
- const followed = [...topics].filter((topic) => !topic.startsWith(ROLE_TOPIC_PREFIX) && !reachesPrivateStreamSubject(ownAgentSubject, topic) && !heldForRole(topic));
46140
- return [...new Set([ownAgentSubject, ...followed])];
46141
- }
46142
- function rememberedTopics(state) {
46143
- return Object.keys(state?.subjects ?? {}).filter((topic) => !topic.startsWith(AGENT_TOPIC_PREFIX) && !topic.startsWith(ROLE_TOPIC_PREFIX));
46144
- }
46145
- async function closeReplayedRemoval(frame, host) {
46146
- const closed = (subscriptionRemovedTopics(frame.data, host.sessionID) ?? []).filter((topic) => host.engine.followedBefore(topic, frame.seq) && host.close(topic));
46147
- if (closed.length === 0)
46148
- return closed;
46149
- const unregistering = host.unregister(closed);
46150
- await host.followedChanged();
46151
- await unregistering;
46152
- return closed;
46153
- }
46154
- function routeReplayNotice(notice, routes) {
46155
- if (notice.kind === "not_served" || notice.kind === "unavailable") {
46156
- routes.warn(notice.message);
46157
- return;
46158
- }
46159
- routes.card(envoyNoticeText(replayNoticeFields(notice)));
46160
- }
46161
- function isRoleForward(envelope) {
46162
- return envelope.dedupe_key?.startsWith(ROLE_FORWARD_KEY_PREFIX) === true || envelope.topic?.startsWith(ROLE_TOPIC_PREFIX) === true;
46163
- }
46164
- function replayLedgerIdentity(frame) {
46165
- return {
46166
- ...frame.event_id === undefined || frame.event_id === "" ? {} : { event_id: frame.event_id },
46167
- ...frame.dedupe_key === undefined || !dedupeKeyNamesItsEvent(frame) ? {} : { dedupe_key: frame.dedupe_key }
45590
+ await request(`/v1/sessions/${encodeURIComponent(input.sessionID)}${query}`, { method: "DELETE" }, { actingSession: input.sessionID });
45591
+ },
45592
+ setRole: async (input) => {
45593
+ const soft = input.soft === true;
45594
+ const previous = soft ? input.previousSessionID ?? "" : "";
45595
+ const body = {
45596
+ session_id: input.sessionID,
45597
+ role: input.role,
45598
+ ...soft ? { soft: true } : {},
45599
+ ...previous === "" ? {} : { previous_session_id: previous },
45600
+ ...input.clientInstanceID === undefined ? {} : { client_instance_id: input.clientInstanceID }
45601
+ };
45602
+ let raw;
45603
+ try {
45604
+ raw = await post("/v1/roles/set", body, { actingSession: input.sessionID });
45605
+ } catch (error) {
45606
+ if (error instanceof EnvoyApiError && error.details.status === 409) {
45607
+ let answer;
45608
+ try {
45609
+ answer = JSON.parse(error.details.responseBody);
45610
+ } catch {
45611
+ throw error;
45612
+ }
45613
+ const held = RoleHeldWireSchema.safeParse(answer);
45614
+ if (held.success)
45615
+ return { claimed: false, holder: held.data.holder };
45616
+ }
45617
+ throw error;
45618
+ }
45619
+ return { claimed: true, interest: InterestWireSchema.parse(JSON.parse(raw)) };
45620
+ },
45621
+ getRole: async (role) => RoleWireSchema.parse(JSON.parse(await request(`/v1/roles/${encodeURIComponent(role)}`, { method: "GET" }))),
45622
+ listSessions: async (input = {}) => {
45623
+ const search = new URLSearchParams;
45624
+ if (input.directory !== undefined)
45625
+ search.set("dir", input.directory);
45626
+ if (input.title !== undefined)
45627
+ search.set("title", input.title);
45628
+ if (input.include !== undefined)
45629
+ search.set("include", input.include);
45630
+ const query = search.size === 0 ? "" : `?${search.toString()}`;
45631
+ return SessionWireSchema.array().parse(JSON.parse(await request(`/v1/sessions${query}`, {})));
45632
+ }
46168
45633
  };
46169
45634
  }
46170
- var StoredEnvelopeSchema = EnvelopeSchema.extend({
46171
- expects_reply: InboundExpectsReplySchema.optional()
46172
- });
46173
- function parseEnvelope(data) {
46174
- let parsed;
46175
- try {
46176
- parsed = JSON.parse(data);
46177
- } catch {
46178
- return;
46179
- }
46180
- const result = StoredEnvelopeSchema.safeParse(parsed);
46181
- return result.success ? result.data : undefined;
45635
+ function waitForRetry(delayMs) {
45636
+ const { promise, resolve } = Promise.withResolvers();
45637
+ setTimeout(resolve, delayMs);
45638
+ return promise;
46182
45639
  }
46183
- function createLedger(now) {
46184
- let entries = new Set;
46185
- const byEvent = new Map;
46186
- const byKey = new Map;
46187
- const drop = (entry) => {
46188
- entries.delete(entry);
46189
- if (entry.event_id !== undefined && byEvent.get(entry.event_id) === entry) {
46190
- byEvent.delete(entry.event_id);
46191
- }
46192
- if (entry.dedupe_key !== undefined && byKey.get(entry.dedupe_key) === entry) {
46193
- byKey.delete(entry.dedupe_key);
46194
- }
46195
- };
46196
- const add = (entry) => {
46197
- if (entries.size >= REPLAY_LEDGER_LIMIT) {
46198
- const oldest = entries.values().next();
46199
- if (oldest.done !== true)
46200
- drop(oldest.value);
46201
- }
46202
- entries.add(entry);
46203
- if (entry.event_id !== undefined)
46204
- byEvent.set(entry.event_id, entry);
46205
- if (entry.dedupe_key !== undefined)
46206
- byKey.set(entry.dedupe_key, entry);
46207
- };
46208
- const expire = () => {
46209
- const at = now();
46210
- for (const entry of entries) {
46211
- if (at - entry.at < REPLAY_LEDGER_TTL_MS)
46212
- break;
46213
- drop(entry);
46214
- }
46215
- };
46216
- const has = (identity) => {
46217
- expire();
46218
- return identity.event_id !== undefined && byEvent.has(identity.event_id) || identity.dedupe_key !== undefined && byKey.has(identity.dedupe_key);
46219
- };
45640
+ function messageMetadata(input) {
46220
45641
  return {
46221
- has,
46222
- record(identity) {
46223
- if (identity.event_id === undefined && identity.dedupe_key === undefined)
46224
- return;
46225
- if (has(identity))
46226
- return;
46227
- const entry = { ...identity, at: now() };
46228
- add(entry);
46229
- return entry;
46230
- },
46231
- restore(restored) {
46232
- entries = new Set;
46233
- byEvent.clear();
46234
- byKey.clear();
46235
- const at = now();
46236
- const kept = restored.filter((entry) => at - entry.at < REPLAY_LEDGER_TTL_MS && (entry.event_id !== undefined || entry.dedupe_key !== undefined)).sort((a, b) => a.at - b.at);
46237
- for (const entry of kept)
46238
- add({ ...entry });
46239
- },
46240
- list() {
46241
- expire();
46242
- return [...entries];
46243
- }
45642
+ ...input.inReplyTo === undefined ? {} : { in_reply_to: input.inReplyTo },
45643
+ ...input.supersedes === undefined ? {} : { supersedes: input.supersedes },
45644
+ ...input.urgency === undefined ? {} : { urgency: input.urgency },
45645
+ ...input.expectsReply === undefined ? {} : { expects_reply: input.expectsReply },
45646
+ ...input.expiresAt === undefined ? {} : { expires_at: input.expiresAt }
46244
45647
  };
46245
45648
  }
45649
+ function sourceSession(sessionID) {
45650
+ return sessionID === undefined || sessionID === "" ? {} : { source_session: sessionID };
45651
+ }
46246
45652
 
46247
45653
  // ../envoy-client/src/consumer-delivery.ts
46248
45654
  var DELIVER_SUBJECT_PREFIX = "notifications.envoy.deliver.";
@@ -46347,6 +45753,7 @@ function every(ms, callback) {
46347
45753
  }
46348
45754
  function createConsumerDelivery(options) {
46349
45755
  const { host, ledger, sessionID } = options;
45756
+ const render = options.render ?? renderInbound;
46350
45757
  const now = options.now ?? Date.now;
46351
45758
  const repeat = options.every ?? every;
46352
45759
  const ownSubject = agentSubject(sessionID);
@@ -46358,9 +45765,9 @@ function createConsumerDelivery(options) {
46358
45765
  let registeredResume;
46359
45766
  let gapTold = false;
46360
45767
  let closed = false;
46361
- let relayed;
46362
45768
  let persisted = JSON.stringify({ follows: {} });
46363
45769
  const entries = new Map;
45770
+ const troubled = new Map;
46364
45771
  const queue = [];
46365
45772
  let blocking;
46366
45773
  let pumping = false;
@@ -46382,6 +45789,7 @@ function createConsumerDelivery(options) {
46382
45789
  streamID = id;
46383
45790
  held = new Set;
46384
45791
  written = undefined;
45792
+ troubled.clear();
46385
45793
  };
46386
45794
  const tellReplacedResume = (id) => {
46387
45795
  const asked = resumePoint() ?? registeredResume;
@@ -46402,18 +45810,6 @@ function createConsumerDelivery(options) {
46402
45810
  }
46403
45811
  return earliest;
46404
45812
  };
46405
- const followedOnCorePath = (frame) => {
46406
- const state = ledger.state();
46407
- if (state.stream_id !== frame.streamID)
46408
- return false;
46409
- for (const [topic, cursor] of Object.entries(state.subjects)) {
46410
- if (cursor.since === undefined || frame.streamSeq <= cursor.since)
46411
- continue;
46412
- if (reaches(topic, frame.subject))
46413
- return true;
46414
- }
46415
- return false;
46416
- };
46417
45813
  const settle = (entry, body) => {
46418
45814
  if (entry.settled)
46419
45815
  return;
@@ -46422,6 +45818,8 @@ function createConsumerDelivery(options) {
46422
45818
  entries.delete(entry.key);
46423
45819
  for (const reply of entry.replies)
46424
45820
  send(reply, body);
45821
+ if (body === "done")
45822
+ troubled.delete(entry.key);
46425
45823
  if (body === "done" && entry.frame.streamID === streamID) {
46426
45824
  held.delete(entry.frame.streamSeq);
46427
45825
  written = Math.max(written ?? 0, entry.frame.streamSeq);
@@ -46438,19 +45836,52 @@ function createConsumerDelivery(options) {
46438
45836
  const failed = (entry, error) => {
46439
45837
  if (entry.settled)
46440
45838
  return;
46441
- if (entry.frame.delivered < RELAY_ATTEMPTS_BEFORE_FAILED) {
45839
+ const trouble = troubled.get(entry.key) ?? { failures: 0, givenUp: false };
45840
+ troubled.set(entry.key, trouble);
45841
+ if (trouble.givenUp) {
45842
+ settle(entry, "nak");
45843
+ return;
45844
+ }
45845
+ trouble.failures += 1;
45846
+ if (trouble.failures < RELAY_ATTEMPTS_BEFORE_FAILED) {
46442
45847
  log(`frame ${entry.frame.streamSeq} failed; it comes again`, error);
46443
45848
  settle(entry, "nak");
46444
45849
  return;
46445
45850
  }
46446
45851
  log(`frame ${entry.frame.streamSeq} failed and does not come again; its session gets the notice`, error);
46447
- safely("failure notice", () => {
46448
- const { subject, data } = entry.frame;
46449
- const { envelope } = renderInbound(data, sessionID, subject);
46450
- if (envelope !== undefined)
46451
- ledger.liveFailed(sessionID, subject, envelope, error, now());
45852
+ const goesBack = (why, thrown) => {
45853
+ trouble.givenUp = true;
45854
+ log(`frame ${entry.frame.streamSeq} ${why}; it goes back to the stream`, thrown);
45855
+ settle(entry, "nak");
45856
+ };
45857
+ let envelope;
45858
+ try {
45859
+ envelope = render(entry.frame.data, sessionID, entry.frame.subject).envelope;
45860
+ } catch (thrown) {
45861
+ goesBack("could not be read to report it", thrown);
45862
+ return;
45863
+ }
45864
+ if (envelope === undefined) {
45865
+ log(`frame ${entry.frame.streamSeq} carries no envelope to report; it is dropped`);
45866
+ settle(entry, "done");
45867
+ return;
45868
+ }
45869
+ let telling;
45870
+ try {
45871
+ telling = ledger.liveFailed(sessionID, envelope, error);
45872
+ } catch (thrown) {
45873
+ goesBack("could not be reported", thrown);
45874
+ return;
45875
+ }
45876
+ telling.then((told) => {
45877
+ if (told) {
45878
+ settle(entry, "done");
45879
+ return;
45880
+ }
45881
+ goesBack("was reported to nobody");
45882
+ }, (thrown) => {
45883
+ goesBack("could not be reported", thrown);
46452
45884
  });
46453
- settle(entry, "done");
46454
45885
  };
46455
45886
  const handOff = (entry) => {
46456
45887
  const handle = {
@@ -46531,7 +45962,7 @@ function createConsumerDelivery(options) {
46531
45962
  return;
46532
45963
  }
46533
45964
  const since = followedAt(frame.subject);
46534
- const unfollowed = (since === undefined || frame.storedAtMs < since - FOLLOW_CLOCK_ALLOWANCE_MS) && !followedOnCorePath(frame);
45965
+ const unfollowed = since === undefined || frame.storedAtMs < since - FOLLOW_CLOCK_ALLOWANCE_MS;
46535
45966
  const identity = unfollowed ? undefined : parseIdentity(frame.data);
46536
45967
  if (unfollowed || alreadyWritten(identity)) {
46537
45968
  send(frame.reply, "done");
@@ -46567,20 +45998,6 @@ function createConsumerDelivery(options) {
46567
45998
  return { stream_id: streamID, seq: Math.min(...held) - 1 };
46568
45999
  return written === undefined ? undefined : { stream_id: streamID, seq: written };
46569
46000
  };
46570
- const seededResume = () => {
46571
- const state = ledger.state();
46572
- const stream = state.stream_id;
46573
- if (stream === undefined)
46574
- return;
46575
- let lowest;
46576
- for (const [subject, cursor] of Object.entries(state.subjects)) {
46577
- if (cursor.after === undefined || !streamStores(subject))
46578
- continue;
46579
- if (lowest === undefined || cursor.after < lowest)
46580
- lowest = cursor.after;
46581
- }
46582
- return lowest === undefined ? undefined : { stream_id: stream, seq: lowest };
46583
- };
46584
46001
  const snapshot = () => {
46585
46002
  const resume = resumePoint();
46586
46003
  return {
@@ -46606,7 +46023,7 @@ function createConsumerDelivery(options) {
46606
46023
  return currentEpoch;
46607
46024
  },
46608
46025
  registration() {
46609
- const resume = resumePoint() ?? seededResume();
46026
+ const resume = resumePoint();
46610
46027
  registeredResume = resume;
46611
46028
  return {
46612
46029
  consumer: true,
@@ -46614,29 +46031,24 @@ function createConsumerDelivery(options) {
46614
46031
  ...resume === undefined ? {} : { resume }
46615
46032
  };
46616
46033
  },
46617
- answered(answer, topics) {
46618
- if (answer.mode === "consumer") {
46619
- if (answer.stream_id !== "" && answer.stream_id !== streamID) {
46620
- tellReplacedResume(answer.stream_id);
46621
- switchStream(answer.stream_id);
46622
- }
46623
- const floor = (answer.consumer_start ?? 0) - 1;
46624
- if (answer.stream_id === streamID && floor > (written ?? -1))
46625
- written = floor;
46626
- if (answer.gap) {
46627
- tellGap("retention_gap");
46628
- gapTold = true;
46629
- }
46630
- relayed = new Set([...topics].filter(streamStores));
46631
- } else {
46632
- relayed = undefined;
46034
+ answered(answer) {
46035
+ if (answer.stream_id !== "" && answer.stream_id !== streamID) {
46036
+ tellReplacedResume(answer.stream_id);
46037
+ switchStream(answer.stream_id);
46038
+ }
46039
+ const floor = (answer.consumer_start ?? 0) - 1;
46040
+ if (answer.stream_id === streamID && floor > (written ?? -1))
46041
+ written = floor;
46042
+ if (answer.gap) {
46043
+ tellGap("retention_gap");
46044
+ gapTold = true;
46633
46045
  }
46634
- ledger.setConsumerMode(relayed !== undefined);
46635
46046
  persist();
46636
- return answer.mode;
46637
46047
  },
46638
- relays: (topic) => relayed?.has(topic) === true,
46639
- relaying: () => relayed !== undefined,
46048
+ followedBefore(topic, storedAtMs) {
46049
+ const at = follows.get(topic);
46050
+ return at !== undefined && storedAtMs >= at - FOLLOW_CLOCK_ALLOWANCE_MS;
46051
+ },
46640
46052
  setFollowed(topics) {
46641
46053
  const at = now();
46642
46054
  const next = new Map;
@@ -46664,8 +46076,6 @@ function createConsumerDelivery(options) {
46664
46076
  },
46665
46077
  close() {
46666
46078
  closed = true;
46667
- relayed = undefined;
46668
- ledger.setConsumerMode(false);
46669
46079
  queue.length = 0;
46670
46080
  for (const entry of [...entries.values()])
46671
46081
  settle(entry, "nak");
@@ -46673,6 +46083,62 @@ function createConsumerDelivery(options) {
46673
46083
  }
46674
46084
  };
46675
46085
  }
46086
+ var GAP_NOTICE_NAMES = {
46087
+ retention_gap: "messages may be missing",
46088
+ stream_recreated: "stream recreated"
46089
+ };
46090
+ function gapNoticeFields(notice) {
46091
+ return { notice: GAP_NOTICE_NAMES[notice.kind], detail: notice.message };
46092
+ }
46093
+ function gapNoticeText(notice) {
46094
+ return envoyNoticeText(gapNoticeFields(notice));
46095
+ }
46096
+ function inboundUnavailableNoticeText(why) {
46097
+ return envoyNoticeText({
46098
+ notice: "Envoy inbound unavailable",
46099
+ error: why,
46100
+ detail: "The listener gave this session no durable consumer, which is the only path an Envoy message reaches it by, so it receives none. Everything else works, and the session registers again at every heartbeat; what the stream stored meanwhile arrives once a registration is accepted."
46101
+ });
46102
+ }
46103
+ function inboundUnavailable(tell) {
46104
+ let told = false;
46105
+ return {
46106
+ refused(error) {
46107
+ if (told)
46108
+ return;
46109
+ told = true;
46110
+ tell(messageFor(error));
46111
+ },
46112
+ accepted() {
46113
+ told = false;
46114
+ }
46115
+ };
46116
+ }
46117
+ function registerWithRelay({
46118
+ relay,
46119
+ ownAgentSubject,
46120
+ followed,
46121
+ roles,
46122
+ outage,
46123
+ send,
46124
+ answered
46125
+ }) {
46126
+ if (relay === undefined) {
46127
+ const refused = new Error("this session holds no relay subject, so the listener can give it no consumer and it can receive nothing");
46128
+ outage.refused(refused);
46129
+ return Promise.reject(refused);
46130
+ }
46131
+ const topics = registrationTopics(ownAgentSubject, followed, roles);
46132
+ relay.setFollowed(topics);
46133
+ return send(topics, relay.registration()).then((result) => {
46134
+ outage.accepted();
46135
+ answered(result);
46136
+ return result;
46137
+ }, (error) => {
46138
+ outage.refused(error);
46139
+ throw error;
46140
+ });
46141
+ }
46676
46142
 
46677
46143
  // ../envoy-client/src/envoy-config.ts
46678
46144
  import {
@@ -53197,7 +52663,7 @@ function allowedAPIURL(value) {
53197
52663
  // ../envoy-client/src/tool-contract.ts
53198
52664
  var SESSION_STATE_GUIDE = "A session is live, unresponsive or gone, by how long ago it last registered: live within 5 " + "minutes, unresponsive after that and within an hour, gone past the hour or with no record at " + `all. ${UNRESPONSIVE_RULE} A session named with no state is live.`;
53199
52665
  var DELIVERY_CONTRACT = "Delivery is at-least-once, possibly out of order across topics; use id for dedupe and at for freshness.";
53200
- var STORED_DELIVERY = "Stored topics (agent, dispatch, github, slack, legion, ghostwispr, whatsapp; a role message " + "reaches its holder as a stored copy on the holder's agent topic) reach each subscribed session " + "once from the durable consumer its listener relays to it, also one that was away or restarted. " + "Team and other ad-hoc topics are live only.";
52666
+ var STORED_DELIVERY = "Every notification topic is stored (agent, dispatch, github, slack, legion, ghostwispr, " + "whatsapp, team; a role message reaches its holder as a stored copy on the holder's agent " + "topic), and reaches each subscribed session once from the durable consumer its listener " + "relays to it, also one that was away or restarted. A 200 means the stream stored the message " + "for each subscribed session's consumer, not that any recipient has read it.";
53201
52667
  var TOPIC_GUIDE = "Topic guide (all are under notifications.): agent.<session_id> (subscribe: own inbox); role.<role> " + "(publish-to; holders claim via envoy_role_set). > matches one or more trailing tokens and does not " + "match the base subject. Envoy registers the concrete base when you subscribe to <subject>.>, so " + "the recommended default remains github.<owner>.<repo>.pr.<n>.>. <owner> and <repo> are one token " + "each, with every dot in the name written _ (sjawhar/.github is github.sjawhar._github; " + "acme/site.io is github.acme.site_io), and a topic spelled with the dot receives nothing. " + "Default PR subscription: " + "github.<owner>.<repo>.pr.<n>.> (it receives the quiet PR family): pr.<n> (lifecycle: " + "opened/synchronize/closed; closed carries merged, merge_commit_sha, merged_by, head_sha), " + "pr.<n>.comment, pr.<n>.review, pr.<n>.mention, pr.<n>.checks (one settlement event per commit whose checks settle, the head or not, naming its sha: " + 'passed/failed/cancelled/skipped with failing names and URLs; re-fires with superseded_settlement: "true" ' + "when new runs appear for the same commit). Other GitHub: issue.<n>, issue.<n>.comment, " + "issue.<n>.mention, mention, push.branch.<name>, push.tag.<name>, workflow.<file>.<action> (only " + "runs without an associated PR); slack.<team>.<channel>.message|mention and " + "slack.<team>.<channel>.thread.<ts>.message|mention; ghostwispr.<session>.<kind>; " + "whatsapp.<phone>.<jid>.<kind>; envoy.exceptions.<original-topic>.";
53202
52668
  var URGENCY_VALUES = EnvelopeSchema.shape.urgency.unwrap().options;
53203
52669
  function messageMetadataShape(schema) {
@@ -53238,7 +52704,7 @@ var EnvoyToolOperation = {
53238
52704
  var envoyToolSpecs = [
53239
52705
  {
53240
52706
  name: "envoy_subscribe",
53241
- description: `Subscribe this session to Envoy notification topics. ${STORED_DELIVERY} ${TOPIC_GUIDE}`,
52707
+ description: `Subscribe this session to Envoy notification topics. A notifications. topic no stream subject captures is refused by name: nothing would store it, so you would receive nothing on it; subscribe to a notifications.team.<name> topic instead. ${STORED_DELIVERY} ${TOPIC_GUIDE}`,
53242
52708
  arguments: (schema) => ({
53243
52709
  topics: schema.array(schema.string()).describe("NATS-style topic patterns to subscribe to.")
53244
52710
  }),
@@ -53274,7 +52740,7 @@ var envoyToolSpecs = [
53274
52740
  },
53275
52741
  {
53276
52742
  name: "envoy_publish",
53277
- description: `Publish an Envoy message to a notifications. topic. ${STORED_DELIVERY} A role or built-in topic is delivered as its guide says. A role message has three possible answers. First, the session that holds the role takes the message. That session must confirm the message inside the listener's window, or this tool errs. Second, no session holds the role. The listener then keeps the message, and gives it to the next session that claims that role in the hour that follows. This is a success, and the result says that the listener kept the message. Third, the listener keeps nothing and errs. A holder that stopped answering keeps its role but was not sent the message, and nothing waits for it, so publish the message again once that holder's holder_state reads live, and start no replacement for that session. A team or ad-hoc topic (such as notifications.team.deploy-squad.all) reaches every session subscribed to it when you publish, and is not kept for a session that subscribes later. The listener confirms it with each other session that holds its own NATS connection and registered the topic, and errs naming each session that did not confirm; a session that stopped without unregistering stays registered until Envoy finds it gone and is named until then. A named session is not a failed delivery to the other sessions. A session that is only unresponsive is named as no failure at all. The listener stores that session's copy, asks it for no receipt, and names the session under unresponsive. The accepted publish and the error both name it there. That session takes the message when it answers again. A session that holds its own NATS connection receives such a live topic directly, yours included. ${SESSION_STATE_GUIDE} ${DELIVERY_CONTRACT}`,
52743
+ description: `Publish an Envoy message to a notifications. topic. ${STORED_DELIVERY} A role or built-in topic is delivered as its guide says. A role message has three possible answers. First, a session holds the role, and the stream stores the forward for that holder's consumer. Its 200 says the stream stored it, and it does not say that the holder read it; it names the holder and the state the listener resolved the holder in. Second, no session holds the role. The listener then keeps the message, and gives it to the next session that claims that role in the hour that follows. This is a success, and the result says that the listener kept the message. Third, the listener keeps nothing and errs, which tells you to reach the agent some other way: the holder refuses the message, or the forward is not stored within four seconds. A holder that stopped answering keeps its role but was not sent the message, and nothing waits for it, so publish the message again once that holder's holder_state reads live, and start no replacement for that session. A team topic (such as notifications.team.deploy-squad.all) is stored like every other, so a session subscribed to it that was away still receives it when it returns, and one that subscribes after you publish does not. A notifications. topic no stream subject captures is refused by name: nothing would store it. ${SESSION_STATE_GUIDE} ${DELIVERY_CONTRACT}`,
53278
52744
  arguments: (schema) => ({ topic: schema.string(), ...messageArguments(schema) }),
53279
52745
  operation: EnvoyToolOperation.publish
53280
52746
  },
@@ -53333,10 +52799,6 @@ function publishConfirmationText(result) {
53333
52799
  const state = result.holderState === undefined ? "" : ` (${result.holderState})`;
53334
52800
  sentences.push(`Its role holder is ${result.holder}${state}.`);
53335
52801
  }
53336
- if (result.unresponsive.length > 0) {
53337
- const one = result.unresponsive.length === 1;
53338
- sentences.push(`Envoy stored it for ${result.unresponsive.join(", ")}.`, `${one ? "That session" : "Those sessions"} stopped answering, so ${one ? "it has" : "they have"} not taken it yet.`, UNRESPONSIVE_RULE);
53339
- }
53340
52802
  return sentences.join(" ");
53341
52803
  }
53342
52804
  function sessionsOnMachine(sessions, machine) {
@@ -56697,7 +56159,7 @@ var import_nats2 = __toESM(require_mod4(), 1);
56697
56159
 
56698
56160
  // package.json
56699
56161
  var name = "@sjawhar/claude-envoy";
56700
- var version2 = "2.8.0";
56162
+ var version2 = "2.9.0";
56701
56163
  var legion = {
56702
56164
  daemonApiVersion: 86
56703
56165
  };
@@ -57567,7 +57029,7 @@ function startAgentStream(options) {
57567
57029
  };
57568
57030
  }
57569
57031
 
57570
- // src/channel-forwarder.ts
57032
+ // src/channel-topics.ts
57571
57033
  var DeliveryIdentity = DedupeIdentitySchema.extend({
57572
57034
  event_id: DedupeIdentitySchema.shape.event_id.catch(undefined),
57573
57035
  dedupe_key: DedupeIdentitySchema.shape.dedupe_key.catch(undefined),
@@ -57575,7 +57037,6 @@ var DeliveryIdentity = DedupeIdentitySchema.extend({
57575
57037
  source_event_id: DedupeIdentitySchema.shape.source_event_id.catch(undefined),
57576
57038
  topic: string2().min(1).optional().catch(undefined)
57577
57039
  });
57578
- var decoder6 = new TextDecoder;
57579
57040
  var DEFAULT_DRAIN_TIMEOUT_MS = 1000;
57580
57041
  function deliveryIdentity(raw) {
57581
57042
  let parsed;
@@ -57591,86 +57052,30 @@ function report(what, error) {
57591
57052
  process.stderr.write(`envoy-channel: ${what} \u2014 ${messageFor(error)}
57592
57053
  `);
57593
57054
  }
57594
- function createChannelForwarder(connection, options) {
57595
- const following = new Map;
57596
- const dedupe = options.dedupe ?? createDeliveryDedupe();
57055
+ function createChannelTopics(connection, options = {}) {
57056
+ const following = new Set;
57597
57057
  const drainTimeoutMs = options.drainTimeoutMs ?? DEFAULT_DRAIN_TIMEOUT_MS;
57598
- const deliver = async (topic, subscription) => {
57599
- try {
57600
- for await (const { message, receivedAt } of readArrivals(subscription)) {
57601
- const raw = decoder6.decode(message.data);
57602
- const identity = deliveryIdentity(raw);
57603
- let claim = options.relayed?.(topic) === true ? undefined : dedupe.claim(identity);
57604
- if (claim !== undefined && identity !== undefined && options.ledger?.delivered(identity)) {
57605
- claim.settle();
57606
- claim = undefined;
57607
- }
57608
- const inbound = {
57609
- subject: message.subject,
57610
- data: message.data,
57611
- raw,
57612
- ...message.reply ? { reply: message.reply } : {},
57613
- ...identity?.topic === undefined ? {} : { envelopeTopic: identity.topic },
57614
- ...claim === undefined ? { duplicate: true } : {}
57615
- };
57616
- let handed;
57617
- try {
57618
- handed = await options.deliver(inbound);
57619
- } catch (error) {
57620
- claim?.release();
57621
- report(`could not deliver a message on ${message.subject}`, error);
57622
- if (claim !== undefined)
57623
- options.failed?.(inbound, topic, error, receivedAt);
57624
- continue;
57625
- }
57626
- if (claim === undefined)
57627
- continue;
57628
- if (!handed) {
57629
- claim.release();
57630
- continue;
57631
- }
57632
- const taken = claim;
57633
- const settle = () => taken.settle();
57634
- if (identity === undefined || options.ledger === undefined)
57635
- settle();
57636
- else
57637
- options.ledger.recordDelivered(identity).then(settle, settle);
57638
- }
57639
- } catch (error) {
57640
- report(`delivery from ${topic} stopped`, error);
57641
- }
57642
- };
57643
- const stop = async (topics) => {
57644
- const stopping = topics.flatMap((topic) => {
57645
- const entry = following.get(topic);
57646
- if (entry === undefined)
57647
- return [];
57648
- following.delete(topic);
57649
- entry.subscription.unsubscribe();
57650
- return [entry.done];
57651
- });
57652
- await Promise.all(stopping);
57653
- };
57654
57058
  return {
57655
57059
  follow(topic) {
57656
- for (const subject of expandSubscriptionTopics([topic])) {
57657
- if (following.has(subject))
57658
- continue;
57659
- const subscription = connection.subscribe(subject);
57660
- following.set(subject, { subscription, done: deliver(subject, subscription) });
57661
- }
57060
+ for (const subject of expandSubscriptionTopics([topic]))
57061
+ following.add(subject);
57662
57062
  },
57663
57063
  unfollow(topics) {
57664
- return stop(topics.length === 0 ? [...following.keys()] : expandSubscriptionTopics(topics));
57064
+ if (topics.length === 0) {
57065
+ following.clear();
57066
+ return;
57067
+ }
57068
+ for (const subject of expandSubscriptionTopics(topics))
57069
+ following.delete(subject);
57665
57070
  },
57666
57071
  topics() {
57667
- return [...following.keys()];
57072
+ return [...following];
57668
57073
  },
57669
57074
  isClosed() {
57670
57075
  return connection.isClosed();
57671
57076
  },
57672
57077
  async close() {
57673
- await stop([...following.keys()]);
57078
+ following.clear();
57674
57079
  if (connection.isClosed())
57675
57080
  return;
57676
57081
  const timeout = Promise.withResolvers();
@@ -59928,14 +59333,14 @@ async function readStateFile(file, schema, empty, refusal) {
59928
59333
  }
59929
59334
 
59930
59335
  // src/replay-state.ts
59931
- var ReplayStateFileSchema = ReplaySnapshotSchema.extend({
59336
+ var ReplayStateFileSchema = LedgerSnapshotSchema.extend({
59932
59337
  consumer: ConsumerDeliverySnapshotSchema.optional()
59933
59338
  });
59934
59339
  function replayStateFile(stateDirectory, sessionId) {
59935
59340
  return join10(stateDirectory, `replay-${encodeURIComponent(sessionId)}.json`);
59936
59341
  }
59937
59342
  async function readReplayState(file) {
59938
- return await readStateFile(file, ReplayStateFileSchema, { ledger: [] }, "holds no replay state");
59343
+ return await readStateFile(file, ReplayStateFileSchema, { ledger: [] }, "holds no delivery state");
59939
59344
  }
59940
59345
  async function writeReplayState(file, state) {
59941
59346
  await writeAtomicStateFile(file, `${JSON.stringify(state)}
@@ -59953,7 +59358,7 @@ function replayStateWriter(file, restored) {
59953
59358
  return run;
59954
59359
  };
59955
59360
  return {
59956
- replay: (snapshot) => write(current.consumer === undefined ? snapshot : { ...snapshot, consumer: current.consumer }),
59361
+ ledger: (snapshot) => write(current.consumer === undefined ? snapshot : { ...snapshot, consumer: current.consumer }),
59957
59362
  consumer: (snapshot) => write({ ...current, consumer: snapshot }),
59958
59363
  idle: () => writing
59959
59364
  };
@@ -60481,7 +59886,6 @@ async function pruneStaleSessionTurns(stateDirectory) {
60481
59886
  // src/envoy-channel-server.ts
60482
59887
  var CHANNEL_INSTRUCTIONS = "Envoy delivers trusted, internal session and Dispatch events into this conversation. Use the Envoy tools for Envoy actions, and reach Dispatch through the `dispatch` command in Bash (`dispatch --help` lists its commands; the `dispatch` skill teaches them). Dispatch asks stay on Dispatch.";
60483
59888
  var CHANNEL_INBOX_LIMIT = 50;
60484
- var EMPTY_RECEIPT = new Uint8Array;
60485
59889
  var encoder6 = new TextEncoder;
60486
59890
  var HANDOFF_POLL_MS = 250;
60487
59891
  var HANDOFF_FLUSH_TIMEOUT_MS = 1e4;
@@ -60563,7 +59967,6 @@ function createChannelDelivery(input) {
60563
59967
  });
60564
59968
  return run;
60565
59969
  };
60566
- const write = (notification) => queued(() => input.notifier.notification(notification));
60567
59970
  const list = (rendered) => {
60568
59971
  const envelope = rendered.envelope;
60569
59972
  if (envelope === undefined)
@@ -60584,14 +59987,10 @@ function createChannelDelivery(input) {
60584
59987
  content,
60585
59988
  ...rendered.envelope?.event_id === undefined ? {} : { eventId: rendered.envelope.event_id }
60586
59989
  });
60587
- const show = (rendered, content) => {
60588
- list(rendered);
60589
- return write(notification(rendered, content));
60590
- };
60591
- const passOverBtw = (rendered, how) => {
59990
+ const passOverLateBtw = (rendered) => {
60592
59991
  if (rendered.delivery?.mode !== "btw")
60593
59992
  return false;
60594
- process.stderr.write(`envoy-channel: passing over ${how} BTW ${rendered.envelope?.event_id ?? "unknown"}: it was asked while this session was not taking messages
59993
+ process.stderr.write(`envoy-channel: passing over late BTW ${rendered.envelope?.event_id ?? "unknown"}: it was asked while this session was not taking messages
60595
59994
  `);
60596
59995
  return true;
60597
59996
  };
@@ -60617,7 +60016,7 @@ function createChannelDelivery(input) {
60617
60016
  `);
60618
60017
  return tail.then(() => false);
60619
60018
  }
60620
- if (late === true && passOverBtw(rendered, "late"))
60019
+ if (late === true && passOverLateBtw(rendered))
60621
60020
  return tail.then(() => false);
60622
60021
  return queued(async () => {
60623
60022
  const routed = await input.router?.()?.route(rendered);
@@ -60630,35 +60029,19 @@ function createChannelDelivery(input) {
60630
60029
  return true;
60631
60030
  });
60632
60031
  },
60633
- async replay(frame) {
60634
- const rendered = renderInbound(frame.data, input.identity.id, frame.subject);
60635
- if (replaySuppressed(rendered))
60636
- return "suppressed";
60637
- if (passOverBtw(rendered, "replayed"))
60638
- return "suppressed";
60639
- await show(rendered, replayedText(rendered.content, frame.time));
60640
- return "shown";
60641
- },
60642
- notice(content) {
60643
- return write({ content });
60032
+ notice(content, addressed) {
60033
+ return queued(async () => {
60034
+ if (addressed !== undefined && addressed !== input.identity.id) {
60035
+ throw new Error(`the notice names session ${addressed}, and this process serves ${input.identity.id}`);
60036
+ }
60037
+ await input.notifier.notification({ content });
60038
+ });
60644
60039
  },
60645
60040
  inbox() {
60646
60041
  return [...inbox];
60647
60042
  }
60648
60043
  };
60649
60044
  }
60650
- async function enqueueChannelMessage(delivery, connection, directSubject, message) {
60651
- const queued = message.duplicate ? Promise.resolve(false) : delivery.enqueue({ subject: message.subject, raw: message.raw });
60652
- const lane = {
60653
- subject: message.subject,
60654
- directSubject,
60655
- envelopeTopic: message.envelopeTopic,
60656
- reply: message.reply
60657
- };
60658
- if (expectsLaneReceipt(lane))
60659
- connection.publish(lane.reply, EMPTY_RECEIPT);
60660
- return queued;
60661
- }
60662
60045
  async function startChannelSession(options) {
60663
60046
  const { identity } = options;
60664
60047
  let directSubject = agentSubject(identity.id);
@@ -60705,78 +60088,43 @@ async function startChannelSession(options) {
60705
60088
  });
60706
60089
  };
60707
60090
  const dedupe = createDeliveryDedupe();
60708
- let replayBound;
60709
- const showReplayed = async (frame) => {
60710
- const identityOf = deliveryIdentity(frame.data);
60711
- const claim = dedupe.claim(identityOf);
60712
- if (claim === undefined && identityOf !== undefined && dedupe.pending(identityOf)) {
60713
- return "queued";
60714
- }
60715
- try {
60716
- await closeReplayedRemoval(frame, {
60717
- sessionID: identity.id,
60718
- engine: replay,
60719
- close: (topic) => userTopics.delete(topic),
60720
- unregister: unfollowRemovedTopics,
60721
- followedChanged: () => replay.followedChanged()
60722
- });
60723
- const outcome = await delivery.replay(frame);
60724
- if (outcome === "shown")
60725
- claim?.settle();
60726
- else
60727
- claim?.release();
60728
- return outcome;
60729
- } catch (error) {
60730
- claim?.release();
60731
- throw error;
60732
- }
60733
- };
60734
- const tellNotice = (notice) => {
60735
- routeReplayNotice(notice, {
60736
- warn: (message) => process.stderr.write(`envoy-channel: ${message}
60737
- `),
60738
- card: (content) => {
60739
- delivery.notice(content).catch((error) => {
60740
- process.stderr.write(`envoy-channel: ${notice.message} (the session could not be told \u2014 ${messageFor(error)})
60091
+ let ledgerBound;
60092
+ const tellGapNotice = (notice) => {
60093
+ delivery.notice(gapNoticeText(notice)).catch((error) => {
60094
+ process.stderr.write(`envoy-channel: ${notice.message} (the session could not be told \u2014 ${messageFor(error)})
60741
60095
  `);
60742
- });
60743
- }
60744
60096
  });
60745
60097
  };
60746
60098
  let stateWriter;
60747
- const replay = createReplayEngine({
60099
+ const ledger = createDeliveryLedger({
60748
60100
  host: {
60749
- sessionID: () => shuttingDown || replayBound !== identity.id ? undefined : identity.id,
60101
+ sessionID: () => shuttingDown || ledgerBound !== identity.id ? undefined : identity.id,
60750
60102
  followedSubjects: () => replayFollowedSubjects(directSubject, userTopics),
60751
- deliver: showReplayed,
60752
- showFailureNotice: (notice) => delivery.notice(envoyNoticeText(failureNoticeFields(notice))),
60103
+ showFailureNotice: (addressed, notice) => delivery.notice(envoyNoticeText(failureNoticeFields(notice)), addressed),
60753
60104
  failureNoticeFailed: (notice, error) => {
60754
60105
  process.stderr.write(`envoy-channel: message ${notice.eventId} from ${notice.sender} was not shown, nor was the notice naming it \u2014 ${messageFor(error)}
60755
60106
  `);
60756
60107
  },
60757
- notify: tellNotice,
60758
60108
  log: (message, error) => {
60759
60109
  process.stderr.write(`envoy-channel: ${message}${error === undefined ? "" : ` \u2014 ${messageFor(error)}`}
60760
60110
  `);
60761
60111
  },
60762
- write: (change) => stateWriter?.replay(change.snapshot())
60763
- },
60764
- transport: options.client,
60765
- dedupe
60112
+ write: (change) => stateWriter?.ledger(change.snapshot())
60113
+ }
60766
60114
  });
60767
- const restoreReplay = async () => {
60115
+ const restoreDelivery = async () => {
60768
60116
  const sessionId = identity.id;
60769
60117
  const file = replayStateFile(options.stateDirectory, sessionId);
60770
60118
  const snapshot = await readReplayState(file).catch((error) => {
60771
- process.stderr.write(`envoy-channel: could not read the replay state (${messageFor(error)}); this session's replay starts over
60119
+ process.stderr.write(`envoy-channel: could not read the delivery state (${messageFor(error)}); this session's record starts over
60772
60120
  `);
60773
60121
  return { ledger: [] };
60774
60122
  });
60775
- replay.restore(snapshot);
60123
+ ledger.restore(snapshot);
60776
60124
  stateWriter = replayStateWriter(file, snapshot);
60777
60125
  openRelay(sessionId, stateWriter, snapshot.consumer);
60778
- replayBound = sessionId;
60779
- return rememberedTopics(snapshot.state);
60126
+ ledgerBound = sessionId;
60127
+ return rememberedTopics(snapshot.state?.topics);
60780
60128
  };
60781
60129
  const restoreTurns = async () => {
60782
60130
  router = undefined;
@@ -60794,26 +60142,22 @@ async function startChannelSession(options) {
60794
60142
  turns = userTurnState(file, restored);
60795
60143
  router = options.router(turns);
60796
60144
  };
60797
- const triggerReplay = () => {
60798
- if (!shuttingDown)
60799
- replay.sweep();
60800
- };
60801
- const takeRemovals = (raw) => {
60802
- const removedTopics = subscriptionRemovedTopics(raw, identity.id);
60803
- if (removedTopics !== undefined && removedTopics.length > 0) {
60804
- for (const topic of removedTopics)
60805
- userTopics.delete(topic);
60806
- dropRemovedTopics(removedTopics);
60807
- }
60808
- };
60809
60145
  let relay;
60810
- const relaysCoreTopic = (topic) => relay?.sessionID === identity.id && relay.delivery.relays(topic);
60146
+ const closeRemovedSubscriptions = async (frame) => {
60147
+ await closeReplayedRemoval(frame, {
60148
+ sessionID: identity.id,
60149
+ relay: relay?.sessionID === identity.id ? relay.delivery : undefined,
60150
+ close: (topic) => userTopics.delete(topic),
60151
+ unregister: unfollowRemovedTopics,
60152
+ followedChanged: () => ledger.followedChanged()
60153
+ });
60154
+ };
60811
60155
  const deliverRelayed = async (owner, frame) => {
60812
60156
  if (shuttingDown || relay !== owner || owner.sessionID !== identity.id) {
60813
60157
  frame.nak();
60814
60158
  return;
60815
60159
  }
60816
- takeRemovals(frame.data);
60160
+ await closeRemovedSubscriptions(frame);
60817
60161
  const identityOf = deliveryIdentity(frame.data);
60818
60162
  const claim = dedupe.claim(identityOf);
60819
60163
  if (claim === undefined) {
@@ -60835,7 +60179,7 @@ async function startChannelSession(options) {
60835
60179
  return;
60836
60180
  }
60837
60181
  if (identityOf !== undefined)
60838
- await replay.recordDelivered(identityOf);
60182
+ await ledger.recordDelivered(identityOf);
60839
60183
  claim.settle();
60840
60184
  frame.done();
60841
60185
  owner.delivery.persist();
@@ -60844,10 +60188,10 @@ async function startChannelSession(options) {
60844
60188
  closeRelay();
60845
60189
  const consumer = createConsumerDelivery({
60846
60190
  sessionID,
60847
- ledger: replay,
60191
+ ledger,
60848
60192
  host: {
60849
60193
  deliver: (frame) => deliverRelayed(owner, frame),
60850
- gap: tellNotice,
60194
+ gap: tellGapNotice,
60851
60195
  log: (message, error) => {
60852
60196
  process.stderr.write(`envoy-channel: ${message}${error === undefined ? "" : ` \u2014 ${messageFor(error)}`}
60853
60197
  `);
@@ -60905,56 +60249,37 @@ async function startChannelSession(options) {
60905
60249
  `);
60906
60250
  });
60907
60251
  };
60908
- const takeDeliveryAnswer = (sessionID, topics, asked, result) => {
60252
+ const takeDeliveryAnswer = (sessionID, asked, result) => {
60909
60253
  if (sessionID !== identity.id || relay !== asked)
60910
60254
  return;
60911
- asked?.delivery.answered(result.delivery, topics);
60912
- };
60913
- const forwarder = createChannelForwarder(options.connection, {
60914
- dedupe,
60915
- ledger: replay,
60916
- relayed: relaysCoreTopic,
60917
- failed: (message, topic, error, receivedAt) => {
60918
- const envelope = renderInbound(message.raw, identity.id, message.subject).envelope;
60919
- if (envelope !== undefined)
60920
- replay.liveFailed(identity.id, topic, envelope, error, receivedAt);
60921
- },
60922
- deliver: async (message) => {
60923
- takeRemovals(message.raw);
60924
- return enqueueChannelMessage(delivery, options.connection, directSubject, message);
60925
- }
60926
- });
60927
- function dropRemovedTopics(topics) {
60928
- unfollowRemovedTopics(topics);
60929
- return replay.followedChanged();
60930
- }
60255
+ asked.delivery.answered(result.delivery);
60256
+ };
60257
+ const followedTopics = createChannelTopics(options.connection);
60931
60258
  function unfollowRemovedTopics(topics) {
60932
- const { dropping, unsubscribing } = dropFromForwarderAndRegistry(topics);
60933
- dropping.catch((error) => {
60934
- process.stderr.write(`envoy-channel: could not drop a removed subscription \u2014 ${messageFor(error)}
60935
- `);
60936
- });
60937
- unsubscribing.catch((error) => {
60259
+ dropFromTopicsAndRegistry(topics).catch((error) => {
60938
60260
  process.stderr.write(`envoy-channel: could not drop a removed subscription from the registry \u2014 ${messageFor(error)}; the next heartbeat reconciles it
60939
60261
  `);
60940
60262
  });
60941
60263
  }
60942
- function dropFromForwarderAndRegistry(topics) {
60943
- const dropping = forwarder.unfollow(topics);
60944
- if (relay?.sessionID === identity.id)
60945
- relay.delivery.setFollowed(registeredTopics());
60946
- return {
60947
- dropping,
60948
- unsubscribing: serialized(() => options.client.unsubscribe({
60949
- sessionID: identity.id,
60950
- topics,
60951
- clientInstanceID: options.clientInstanceID
60952
- }))
60953
- };
60954
- }
60955
- function registeredTopics() {
60956
- return forwarder.topics().filter((topic) => !reachesPrivateStreamSubject(directSubject, topic));
60264
+ function dropFromTopicsAndRegistry(topics) {
60265
+ followedTopics.unfollow(topics);
60266
+ if (relay?.sessionID === identity.id) {
60267
+ relay.delivery.setFollowed(registrationTopics(directSubject, followedTopics.topics(), heldRole === undefined ? [] : [heldRole]));
60268
+ }
60269
+ return serialized(() => options.client.unsubscribe({
60270
+ sessionID: identity.id,
60271
+ topics,
60272
+ clientInstanceID: options.clientInstanceID
60273
+ }));
60957
60274
  }
60275
+ const inboundOutage = inboundUnavailable((why) => {
60276
+ process.stderr.write(`envoy-channel: this session receives nothing (${why}); registering again every heartbeat
60277
+ `);
60278
+ delivery.notice(inboundUnavailableNoticeText(why)).catch((noticeError) => {
60279
+ process.stderr.write(`envoy-channel: the session could not be told that it receives nothing \u2014 ${messageFor(noticeError)}
60280
+ `);
60281
+ });
60282
+ });
60958
60283
  let stampedTitle;
60959
60284
  let stampFailureReported = false;
60960
60285
  const register = async () => {
@@ -60973,34 +60298,44 @@ async function startChannelSession(options) {
60973
60298
  }
60974
60299
  }
60975
60300
  const sessionID = identity.id;
60976
- const topics = registeredTopics();
60977
- const asking = relay?.sessionID === identity.id ? relay : undefined;
60978
- asking?.delivery.setFollowed(topics);
60979
- const registering = options.client.subscribe({
60980
- sessionID,
60981
- directory: identity.directory,
60982
- topics,
60983
- port: 0,
60984
- title,
60985
- capabilities: options.capabilities(),
60986
- driving: false,
60987
- selfSubscribed: true,
60988
- clientInstanceID: options.clientInstanceID,
60989
- plugin: { name, version: options.pluginVersion },
60990
- ...asking === undefined ? {} : { delivery: asking.delivery.registration() }
60991
- });
60992
- const settled = registering.then(() => {
60993
- return;
60994
- }, () => {
60995
- return;
60996
- });
60997
- registrationInFlight = settled;
60998
- settled.then(() => {
60999
- if (registrationInFlight === settled)
61000
- registrationInFlight = undefined;
60301
+ const asking = relay?.sessionID === sessionID ? relay : undefined;
60302
+ await registerWithRelay({
60303
+ relay: asking?.delivery,
60304
+ ownAgentSubject: directSubject,
60305
+ followed: followedTopics.topics(),
60306
+ roles: heldRole === undefined ? [] : [heldRole],
60307
+ outage: inboundOutage,
60308
+ send: (topics, deliveryRequest) => {
60309
+ const registering = options.client.subscribe({
60310
+ sessionID,
60311
+ directory: identity.directory,
60312
+ topics,
60313
+ port: 0,
60314
+ title,
60315
+ capabilities: options.capabilities(),
60316
+ driving: false,
60317
+ selfSubscribed: true,
60318
+ clientInstanceID: options.clientInstanceID,
60319
+ plugin: { name, version: options.pluginVersion },
60320
+ delivery: deliveryRequest
60321
+ });
60322
+ const settled = registering.then(() => {
60323
+ return;
60324
+ }, () => {
60325
+ return;
60326
+ });
60327
+ registrationInFlight = settled;
60328
+ settled.then(() => {
60329
+ if (registrationInFlight === settled)
60330
+ registrationInFlight = undefined;
60331
+ });
60332
+ return registering;
60333
+ },
60334
+ answered: (result) => {
60335
+ if (asking !== undefined)
60336
+ takeDeliveryAnswer(sessionID, asking, result);
60337
+ }
61001
60338
  });
61002
- const result = await registering;
61003
- takeDeliveryAnswer(sessionID, topics, asking, result);
61004
60339
  };
61005
60340
  const writeRoleRecord = (file, role) => writePersistedRole(file, {
61006
60341
  session_id: identity.id,
@@ -61114,19 +60449,19 @@ async function startChannelSession(options) {
61114
60449
  const previous = identity.id;
61115
60450
  const previousSubject = directSubject;
61116
60451
  const nextSubject = agentSubject(next);
61117
- forwarder.follow(nextSubject);
60452
+ followedTopics.follow(nextSubject);
61118
60453
  try {
61119
60454
  await withTimeout(options.connection.flush(), options.handoffFlushTimeoutMs ?? HANDOFF_FLUSH_TIMEOUT_MS, "flushing NATS");
61120
60455
  await deregister(previous);
61121
60456
  } catch (error) {
61122
- forwarder.unfollow([nextSubject]);
60457
+ followedTopics.unfollow([nextSubject]);
61123
60458
  throw error;
61124
60459
  }
61125
60460
  identity.set(next);
61126
60461
  forgetBrokerSession(previous);
61127
60462
  directSubject = nextSubject;
61128
- forwarder.unfollow([previousSubject]);
61129
- await restoreReplay();
60463
+ followedTopics.unfollow([previousSubject]);
60464
+ await restoreDelivery();
61130
60465
  await restoreTurns();
61131
60466
  roleTransferFrom ??= previous;
61132
60467
  await withTimeout(options.connection.flush(), options.handoffFlushTimeoutMs ?? HANDOFF_FLUSH_TIMEOUT_MS, "flushing NATS").catch((error) => {
@@ -61150,14 +60485,14 @@ async function startChannelSession(options) {
61150
60485
  if (topic === directSubject || topic.startsWith(ROLE_TOPIC_PREFIX))
61151
60486
  continue;
61152
60487
  userTopics.add(topic);
61153
- forwarder.follow(topic);
60488
+ followedTopics.follow(topic);
61154
60489
  }
61155
60490
  interestsRead = true;
61156
60491
  return;
61157
60492
  }
61158
60493
  if (registry === undefined)
61159
60494
  return;
61160
- const followed = new Set(forwarder.topics());
60495
+ const followed = new Set(followedTopics.topics());
61161
60496
  const drifted = registry.topics.filter((topic) => topic !== directSubject && !topic.startsWith(ROLE_TOPIC_PREFIX) && !followed.has(topic));
61162
60497
  if (drifted.length === 0)
61163
60498
  return;
@@ -61214,7 +60549,6 @@ async function startChannelSession(options) {
61214
60549
  `);
61215
60550
  } finally {
61216
60551
  heartbeatInFlight = false;
61217
- triggerReplay();
61218
60552
  if (heartbeatRequested) {
61219
60553
  heartbeatRequested = false;
61220
60554
  heartbeat();
@@ -61241,12 +60575,12 @@ async function startChannelSession(options) {
61241
60575
  else
61242
60576
  heartbeat();
61243
60577
  };
61244
- const remembered = await restoreReplay();
60578
+ const remembered = await restoreDelivery();
61245
60579
  await restoreTurns();
61246
- forwarder.follow(directSubject);
60580
+ followedTopics.follow(directSubject);
61247
60581
  for (const topic of remembered) {
61248
60582
  userTopics.add(topic);
61249
- forwarder.follow(topic);
60583
+ followedTopics.follow(topic);
61250
60584
  }
61251
60585
  await syncRegisteredInterests().catch((error) => {
61252
60586
  process.stderr.write(`envoy-channel: could not read the registered interests (${messageFor(error)}); the next heartbeat retries
@@ -61254,7 +60588,11 @@ async function startChannelSession(options) {
61254
60588
  });
61255
60589
  await options.connection.flush();
61256
60590
  await serialized(async () => {
61257
- await register();
60591
+ await register().catch((error) => {
60592
+ registrationFailed = true;
60593
+ process.stderr.write(`envoy-channel: the first registration failed (${messageFor(error)}); the next heartbeat retries
60594
+ `);
60595
+ });
61258
60596
  try {
61259
60597
  roleTransferFrom = await restoreRole(identity.id) === "pending" ? identity.id : undefined;
61260
60598
  } catch (error) {
@@ -61269,7 +60607,6 @@ async function startChannelSession(options) {
61269
60607
  }
61270
60608
  }
61271
60609
  });
61272
- triggerReplay();
61273
60610
  for (const prune of [
61274
60611
  () => pruneStaleSessionHandoffs(options.stateDirectory),
61275
60612
  () => pruneStaleSessionTitles(options.stateDirectory),
@@ -61298,7 +60635,6 @@ async function startChannelSession(options) {
61298
60635
  if (status.type !== "reconnect")
61299
60636
  continue;
61300
60637
  renewRelayEpoch();
61301
- triggerReplay();
61302
60638
  }
61303
60639
  } catch (error) {
61304
60640
  process.stderr.write(`envoy-channel: the NATS connection's status reader failed \u2014 ${messageFor(error)}
@@ -61307,8 +60643,9 @@ async function startChannelSession(options) {
61307
60643
  })();
61308
60644
  return {
61309
60645
  delivery,
61310
- topics: () => forwarder.topics(),
60646
+ topics: () => followedTopics.topics(),
61311
60647
  async follow(topics) {
60648
+ refuseUncapturedTopics(identity.id, directSubject, topics);
61312
60649
  if (shuttingDown)
61313
60650
  return [];
61314
60651
  const fresh = [];
@@ -61316,14 +60653,13 @@ async function startChannelSession(options) {
61316
60653
  if (topic === directSubject || userTopics.has(topic))
61317
60654
  continue;
61318
60655
  userTopics.add(topic);
61319
- forwarder.follow(topic);
60656
+ followedTopics.follow(topic);
61320
60657
  fresh.push(topic);
61321
60658
  }
61322
60659
  await options.connection.flush();
61323
60660
  await serialized(register);
61324
60661
  if (fresh.length > 0) {
61325
- await replay.followedChanged();
61326
- triggerReplay();
60662
+ await ledger.followedChanged();
61327
60663
  }
61328
60664
  return fresh;
61329
60665
  },
@@ -61332,10 +60668,9 @@ async function startChannelSession(options) {
61332
60668
  const removed = requested.filter((topic) => userTopics.delete(topic));
61333
60669
  if (removed.length === 0)
61334
60670
  return [];
61335
- const { dropping, unsubscribing } = dropFromForwarderAndRegistry(removed);
61336
- await replay.followedChanged();
60671
+ const unsubscribing = dropFromTopicsAndRegistry(removed);
60672
+ await ledger.followedChanged();
61337
60673
  await unsubscribing;
61338
- await dropping;
61339
60674
  return removed;
61340
60675
  },
61341
60676
  onRoleRegained(hook) {
@@ -61368,7 +60703,7 @@ async function startChannelSession(options) {
61368
60703
  if (handoffFile !== undefined)
61369
60704
  unwatchFile(handoffFile, handoffFileChanged);
61370
60705
  closeRelay();
61371
- await forwarder.close();
60706
+ await followedTopics.close();
61372
60707
  const settleBy = Date.now() + shutdownSettleMs;
61373
60708
  await settledOrGivenUp(registryWrites, shutdownSettleMs);
61374
60709
  await deregister(identity.id, Math.max(0, settleBy - Date.now())).catch((error) => {
@@ -61419,7 +60754,6 @@ async function executeEnvoyTool(runtime, name, input) {
61419
60754
  topic: result.envelope.topic,
61420
60755
  ...result.holder === undefined ? {} : { holder: result.holder },
61421
60756
  ...result.holderState === undefined ? {} : { holder_state: result.holderState },
61422
- unresponsive: result.unresponsive,
61423
60757
  ...result.kept === undefined ? {} : { kept: result.kept },
61424
60758
  ...result.keptReason === undefined ? {} : { kept_reason: result.keptReason }
61425
60759
  };