@sjawhar/claude-envoy 2.8.0 → 2.10.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.
package/dist/dispatch.js CHANGED
@@ -14660,6 +14660,9 @@ function agentSubject(session) {
14660
14660
  return `${AGENT_TOPIC_PREFIX}${session}`;
14661
14661
  }
14662
14662
  var GHOSTWISPR_TOPIC_PREFIX = "notifications.ghostwispr.";
14663
+ function uncapturedTopicRefusal(topic, sessionID) {
14664
+ 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`;
14665
+ }
14663
14666
 
14664
14667
  // ../contracts/src/legion-roles.ts
14665
14668
  var LEGION_ROLES = [
@@ -20140,58 +20143,6 @@ async function postDeliveryReply(config, sessionId, delivery, result) {
20140
20143
  ...reply
20141
20144
  }, followUp === undefined ? {} : { followUp });
20142
20145
  }
20143
- function expectsLaneReceipt(frame) {
20144
- return frame.reply !== undefined && frame.reply !== "" && frame.subject === frame.directSubject && frame.envelopeTopic !== undefined && frame.envelopeTopic !== frame.directSubject;
20145
- }
20146
- async function* readArrivals(subscription, now = Date.now) {
20147
- const source = subscription[Symbol.asyncIterator]();
20148
- const arrived = [];
20149
- let stopped;
20150
- let left = false;
20151
- let wake;
20152
- const signal = () => {
20153
- wake?.();
20154
- wake = undefined;
20155
- };
20156
- (async () => {
20157
- try {
20158
- for (;; ) {
20159
- const read = await source.next();
20160
- if (read.done === true || left)
20161
- break;
20162
- arrived.push({ message: read.value, receivedAt: now() });
20163
- signal();
20164
- }
20165
- stopped = { failed: false };
20166
- } catch (error) {
20167
- stopped = { error, failed: true };
20168
- }
20169
- signal();
20170
- })();
20171
- try {
20172
- for (;; ) {
20173
- const next = arrived.shift();
20174
- if (next !== undefined) {
20175
- yield next;
20176
- continue;
20177
- }
20178
- if (stopped?.failed === true)
20179
- throw stopped.error;
20180
- if (stopped !== undefined)
20181
- return;
20182
- const { promise, resolve } = Promise.withResolvers();
20183
- wake = resolve;
20184
- await promise;
20185
- }
20186
- } finally {
20187
- if (stopped === undefined) {
20188
- left = true;
20189
- Promise.resolve(source.return?.()).catch(() => {
20190
- return;
20191
- });
20192
- }
20193
- }
20194
- }
20195
20146
  var DedupeIdentitySchema = object({
20196
20147
  event_id: string2().min(1).optional(),
20197
20148
  dedupe_key: string2().min(1).optional(),
@@ -29136,9 +29087,89 @@ function sessionEnvoySettings(file, env, options) {
29136
29087
  });
29137
29088
  }
29138
29089
 
29090
+ // ../envoy-client/src/stream-topics.ts
29091
+ var EXCEPTION_TOPIC_PREFIX = "notifications.envoy.exceptions.";
29092
+ var STREAM_SUBJECT_PREFIXES = [
29093
+ AGENT_TOPIC_PREFIX,
29094
+ DISPATCH_TOPIC_PREFIX,
29095
+ "notifications.github.",
29096
+ "notifications.slack.",
29097
+ LEGION_NOTICE_TOPIC_PREFIX,
29098
+ GHOSTWISPR_TOPIC_PREFIX,
29099
+ "notifications.whatsapp.",
29100
+ "notifications.team.",
29101
+ `${EXCEPTION_TOPIC_PREFIX}${AGENT_TOPIC_PREFIX}`,
29102
+ `${EXCEPTION_TOPIC_PREFIX}notifications.team.`
29103
+ ];
29104
+ function streamStores(topic) {
29105
+ return STREAM_SUBJECT_PREFIXES.some((prefix) => topic.length > prefix.length && topic.startsWith(prefix));
29106
+ }
29107
+ function streamDeliversNothing(topic) {
29108
+ return topic.startsWith("notifications.") && !topic.startsWith(ROLE_TOPIC_PREFIX) && !streamStores(topic);
29109
+ }
29110
+ function subscribeRefusesTopic(ownAgentSubject, topic) {
29111
+ return streamDeliversNothing(topic) && !reachesPrivateStreamSubject(ownAgentSubject, topic);
29112
+ }
29113
+ function refuseUncapturedTopics(sessionID, ownAgentSubject, topics) {
29114
+ const uncaptured = topics.filter((topic) => subscribeRefusesTopic(ownAgentSubject, topic));
29115
+ if (uncaptured.length === 0)
29116
+ return;
29117
+ throw new Error(uncaptured.map((topic) => uncapturedTopicRefusal(topic, sessionID)).join("; "));
29118
+ }
29119
+ var PRIVATE_STREAM_SUBJECTS = [
29120
+ `${AGENT_TOPIC_PREFIX}>`,
29121
+ `${LEGION_NOTICE_TOPIC_PREFIX}>`,
29122
+ `${EXCEPTION_TOPIC_PREFIX}${AGENT_TOPIC_PREFIX}>`,
29123
+ `${EXCEPTION_TOPIC_PREFIX}notifications.team.>`
29124
+ ];
29125
+ var CONTROLLER_NOTICE_SUFFIX = ".controller";
29126
+ function controllerNoticeRole(topic) {
29127
+ if (!topic.startsWith(LEGION_NOTICE_TOPIC_PREFIX) || !topic.endsWith(CONTROLLER_NOTICE_SUFFIX)) {
29128
+ return;
29129
+ }
29130
+ const project = topic.slice(LEGION_NOTICE_TOPIC_PREFIX.length, topic.length - CONTROLLER_NOTICE_SUFFIX.length);
29131
+ if (project === "" || /[.*>]/.test(project))
29132
+ return;
29133
+ return `legion-${project}-controller`;
29134
+ }
29135
+ function subjectsOverlap(a, b) {
29136
+ const aTokens = a.split(".");
29137
+ const bTokens = b.split(".");
29138
+ for (let index = 0;index < aTokens.length && index < bTokens.length; index += 1) {
29139
+ const aToken = aTokens[index];
29140
+ const bToken = bTokens[index];
29141
+ if (aToken === ">" || bToken === ">")
29142
+ return true;
29143
+ if (aToken !== "*" && bToken !== "*" && aToken !== bToken)
29144
+ return false;
29145
+ }
29146
+ return aTokens.length === bTokens.length;
29147
+ }
29148
+ function reachesPrivateStreamSubject(ownAgentSubject, topic, roles = []) {
29149
+ if (!PRIVATE_STREAM_SUBJECTS.some((subject) => subjectsOverlap(topic, subject)))
29150
+ return false;
29151
+ const role = controllerNoticeRole(topic);
29152
+ if (role !== undefined)
29153
+ return !roles.includes(role);
29154
+ return topic !== ownAgentSubject || /[*>]/.test(ownAgentSubject);
29155
+ }
29156
+ function registrationTopics(ownAgentSubject, followed, roles = []) {
29157
+ return [
29158
+ ...new Set([
29159
+ ownAgentSubject,
29160
+ ...[...followed].filter((topic) => !reachesPrivateStreamSubject(ownAgentSubject, topic, roles) && !streamDeliversNothing(topic))
29161
+ ])
29162
+ ];
29163
+ }
29164
+ function replayFollowedSubjects(ownAgentSubject, topics, heldForRole = () => false) {
29165
+ const followed = [...topics].filter((topic) => !topic.startsWith(ROLE_TOPIC_PREFIX) && !reachesPrivateStreamSubject(ownAgentSubject, topic) && !heldForRole(topic));
29166
+ return [...new Set([ownAgentSubject, ...followed])];
29167
+ }
29168
+ function rememberedTopics(topics) {
29169
+ return (topics ?? []).filter((topic) => !topic.startsWith(AGENT_TOPIC_PREFIX) && !topic.startsWith(ROLE_TOPIC_PREFIX));
29170
+ }
29171
+
29139
29172
  // ../envoy-client/src/transport.ts
29140
- var REPLAY_TIMEOUT_MS = 1e4;
29141
- var REPLAY_UNAVAILABLE_CODE = "REPLAY_UNAVAILABLE";
29142
29173
  var SessionStateSchema = _enum2(["live", "unresponsive", "gone"]);
29143
29174
  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.";
29144
29175
  var WireStateSchema = SessionStateSchema.default("live");
@@ -29150,16 +29181,13 @@ var InterestWireSchema = object({
29150
29181
  updated_at: number2().int().optional(),
29151
29182
  warnings: array(string2()).optional()
29152
29183
  });
29153
- var DeliveryAnswerWireSchema = discriminatedUnion("mode", [
29154
- object({
29155
- mode: literal("consumer"),
29156
- subject: string2().min(1),
29157
- stream_id: string2(),
29158
- gap: boolean2(),
29159
- consumer_start: number2().int().nonnegative().optional()
29160
- }),
29161
- object({ mode: literal("core"), reason: string2() })
29162
- ]);
29184
+ var DeliveryAnswerWireSchema = object({
29185
+ mode: literal("consumer"),
29186
+ subject: string2().min(1),
29187
+ stream_id: string2(),
29188
+ gap: boolean2(),
29189
+ consumer_start: number2().int().nonnegative().optional()
29190
+ });
29163
29191
  var SessionWireSchema = object({
29164
29192
  session_id: string2(),
29165
29193
  machine_id: string2(),
@@ -29174,7 +29202,8 @@ var SessionWireSchema = object({
29174
29202
  last_seen: number2().int().optional(),
29175
29203
  state: WireStateSchema,
29176
29204
  plugin: string2().optional(),
29177
- plugin_version: string2().optional()
29205
+ plugin_version: string2().optional(),
29206
+ delivery: string2().optional()
29178
29207
  });
29179
29208
  var RoleWireSchema = object({
29180
29209
  role: string2(),
@@ -29194,13 +29223,13 @@ var RoleHeldWireSchema = object({
29194
29223
  var ErrorWireSchema = object({
29195
29224
  error: string2(),
29196
29225
  code: string2().optional(),
29226
+ reason: string2().optional(),
29197
29227
  expected: array(string2()).optional(),
29198
29228
  state: SessionStateSchema.optional(),
29199
29229
  holder: string2().optional(),
29200
29230
  holder_state: SessionStateSchema.optional(),
29201
29231
  last_seen: number2().int().optional(),
29202
- claim_released: boolean2().optional(),
29203
- unresponsive: array(string2()).optional()
29232
+ claim_released: boolean2().optional()
29204
29233
  });
29205
29234
  var EnvelopeResponseSchema = EnvelopeSchema.extend({
29206
29235
  recipient: string2().optional(),
@@ -29208,46 +29237,30 @@ var EnvelopeResponseSchema = EnvelopeSchema.extend({
29208
29237
  holder_state: SessionStateSchema.optional(),
29209
29238
  recipient_state: SessionStateSchema.optional(),
29210
29239
  last_seen: number2().int().optional(),
29211
- unresponsive: array(string2()).optional(),
29212
29240
  duplicate: boolean2().optional()
29213
29241
  });
29214
29242
  var PublishResponseSchema = EnvelopeResponseSchema.extend({
29215
29243
  kept: boolean2().optional(),
29216
29244
  kept_reason: _enum2(["unclaimed", "holder_lapsed"]).optional()
29217
29245
  });
29218
- var ReplayWireSchema = object({
29219
- stream: object({
29220
- id: string2().min(1).optional(),
29221
- created: string2(),
29222
- first_seq: number2().int().nonnegative(),
29223
- last_seq: number2().int().nonnegative()
29224
- }),
29225
- subjects: array(object({
29226
- subject: string2(),
29227
- messages: array(object({
29228
- seq: number2().int().positive(),
29229
- subject: string2(),
29230
- time: string2(),
29231
- data: string2()
29232
- })),
29233
- next_after: number2().int().nonnegative(),
29234
- more: boolean2(),
29235
- refused: string2().optional()
29236
- }))
29246
+ var DeliveryRefusalSchema = object({
29247
+ mode: string2(),
29248
+ reason: string2().optional()
29237
29249
  });
29238
- var DELIVERY_NOT_ANSWERED = "not_answered";
29239
- var DELIVERY_UNREADABLE = "unreadable_answer";
29250
+ var DELIVERY_UNREADABLE = "answered a delivery field this build cannot read";
29240
29251
  function parseSubscribeAnswer(body) {
29241
29252
  const interest = InterestWireSchema.parse(body);
29242
29253
  const raw = typeof body === "object" && body !== null && "delivery" in body ? body.delivery : undefined;
29243
29254
  if (raw === undefined || raw === null) {
29244
- return { ...interest, delivery: { mode: "core", reason: DELIVERY_NOT_ANSWERED } };
29255
+ 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`);
29245
29256
  }
29246
29257
  const delivery = DeliveryAnswerWireSchema.safeParse(raw);
29247
- return {
29248
- ...interest,
29249
- delivery: delivery.success ? delivery.data : { mode: "core", reason: DELIVERY_UNREADABLE }
29250
- };
29258
+ if (!delivery.success) {
29259
+ const named = DeliveryRefusalSchema.safeParse(raw);
29260
+ const said = named.success ? `answered delivery mode ${named.data.mode}${named.data.reason === undefined ? "" : ` (${named.data.reason})`}` : DELIVERY_UNREADABLE;
29261
+ throw new Error(`the listener gave ${interest.session_id} no consumer: it ${said}, and a session receives only what its own consumer holds`);
29262
+ }
29263
+ return { ...interest, delivery: delivery.data };
29251
29264
  }
29252
29265
  function mergeInterestSources(registryTopics, liveTopics) {
29253
29266
  const interests = new Map;
@@ -29293,27 +29306,20 @@ function expandSubscriptionTopics(topics) {
29293
29306
  if (segments.length < 2 || segments.some((segment) => segment.length === 0)) {
29294
29307
  throw new TypeError(`cannot expand Envoy wildcard topic "${topic}": its concrete base must have at least two non-empty segments`);
29295
29308
  }
29296
- expanded.add(base);
29309
+ if (!streamDeliversNothing(base))
29310
+ expanded.add(base);
29297
29311
  expanded.add(topic);
29298
29312
  }
29299
29313
  return [...expanded];
29300
29314
  }
29301
29315
  function refusalStateText(parsed) {
29302
- const sentences = [];
29303
29316
  const state = parsed.holder_state ?? parsed.state;
29304
- if (state !== undefined) {
29305
- const who = parsed.holder === undefined ? "That session" : `Holder ${parsed.holder}`;
29306
- const seen = parsed.last_seen === undefined || parsed.last_seen <= 0 ? "" : `, last seen ${new Date(parsed.last_seen).toISOString()}`;
29307
- sentences.push(`${who} is ${state}${seen}.`);
29308
- }
29309
- const stored = parsed.unresponsive ?? [];
29310
- if (stored.length > 0) {
29311
- const one = stored.length === 1;
29312
- 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.`);
29313
- }
29314
- if (sentences.length === 0)
29317
+ if (state === undefined)
29315
29318
  return "";
29316
- if (state === "unresponsive" || stored.length > 0)
29319
+ const who = parsed.holder === undefined ? "That session" : `Holder ${parsed.holder}`;
29320
+ const seen = parsed.last_seen === undefined || parsed.last_seen <= 0 ? "" : `, last seen ${new Date(parsed.last_seen).toISOString()}`;
29321
+ const sentences = [`${who} is ${state}${seen}.`];
29322
+ if (state === "unresponsive")
29317
29323
  sentences.push(UNRESPONSIVE_RULE);
29318
29324
  return ` ${sentences.join(" ")}`;
29319
29325
  }
@@ -29323,11 +29329,11 @@ class EnvoyApiError extends Error {
29323
29329
  name = "EnvoyApiError";
29324
29330
  expected;
29325
29331
  code;
29332
+ reason;
29326
29333
  holder;
29327
29334
  sessionState;
29328
29335
  lastSeen;
29329
29336
  claimReleased;
29330
- unresponsive;
29331
29337
  constructor(details) {
29332
29338
  let parsed;
29333
29339
  try {
@@ -29335,15 +29341,15 @@ class EnvoyApiError extends Error {
29335
29341
  if (result.success)
29336
29342
  parsed = result.data;
29337
29343
  } catch {}
29338
- super(parsed === undefined ? `${details.method} ${details.url} failed with ${details.status}: ${details.responseBody}` : `${parsed.error}${parsed.expected === undefined ? "" : ` (expected: ${parsed.expected.join(", ")})`}${refusalStateText(parsed)}`);
29344
+ 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)}`);
29339
29345
  this.details = details;
29340
29346
  this.expected = parsed?.expected;
29341
29347
  this.code = parsed?.code;
29348
+ this.reason = parsed?.reason;
29342
29349
  this.holder = parsed?.holder;
29343
29350
  this.sessionState = parsed?.holder_state ?? parsed?.state;
29344
29351
  this.lastSeen = parsed?.last_seen;
29345
29352
  this.claimReleased = parsed?.claim_released;
29346
- this.unresponsive = parsed?.unresponsive;
29347
29353
  }
29348
29354
  }
29349
29355
  var mintedDedupeKey2 = new RegExp(MINTED_DEDUPE_KEY_PATTERN);
@@ -29453,23 +29459,24 @@ function createEnvoyClient(config) {
29453
29459
  headers: { "Content-Type": "application/json" },
29454
29460
  body: JSON.stringify(body)
29455
29461
  }, options);
29462
+ const subscribeBody = (input) => ({
29463
+ session_id: input.sessionID,
29464
+ dir: input.directory,
29465
+ topics: expandSubscriptionTopics(input.topics),
29466
+ port: input.port,
29467
+ title: input.title,
29468
+ ...input.capabilities === undefined ? {} : { capabilities: input.capabilities },
29469
+ driving: input.driving,
29470
+ ...input.selfSubscribed === undefined ? {} : { self_subscribed: input.selfSubscribed },
29471
+ delivery: input.delivery,
29472
+ ...input.clientInstanceID === undefined ? {} : { client_instance_id: input.clientInstanceID },
29473
+ host: machineID(),
29474
+ ...input.place === undefined ? {} : { tmux_place: input.place },
29475
+ plugin: input.plugin.name,
29476
+ plugin_version: input.plugin.version
29477
+ });
29456
29478
  return {
29457
- subscribe: async (input) => parseSubscribeAnswer(JSON.parse(await post("/v1/interests/subscribe", {
29458
- session_id: input.sessionID,
29459
- dir: input.directory,
29460
- topics: expandSubscriptionTopics(input.topics),
29461
- port: input.port,
29462
- title: input.title,
29463
- ...input.capabilities === undefined ? {} : { capabilities: input.capabilities },
29464
- driving: input.driving,
29465
- ...input.selfSubscribed === undefined ? {} : { self_subscribed: input.selfSubscribed },
29466
- ...input.delivery === undefined ? {} : { delivery: input.delivery },
29467
- ...input.clientInstanceID === undefined ? {} : { client_instance_id: input.clientInstanceID },
29468
- host: machineID(),
29469
- ...input.place === undefined ? {} : { tmux_place: input.place },
29470
- plugin: input.plugin.name,
29471
- plugin_version: input.plugin.version
29472
- }, { actingSession: input.sessionID }))),
29479
+ subscribe: async (input) => parseSubscribeAnswer(JSON.parse(await post("/v1/interests/subscribe", subscribeBody(input), { actingSession: input.sessionID }))),
29473
29480
  unsubscribe: async (input) => {
29474
29481
  await post("/v1/interests/unsubscribe", {
29475
29482
  session_id: input.sessionID,
@@ -29528,7 +29535,6 @@ function createEnvoyClient(config) {
29528
29535
  envelope: response,
29529
29536
  ...response.holder === undefined ? {} : { holder: response.holder },
29530
29537
  ...response.holder_state === undefined ? {} : { holderState: response.holder_state },
29531
- unresponsive: response.unresponsive ?? [],
29532
29538
  ...response.kept === undefined ? {} : { kept: response.kept },
29533
29539
  ...response.kept_reason === undefined ? {} : { keptReason: response.kept_reason }
29534
29540
  };
@@ -29577,16 +29583,7 @@ function createEnvoyClient(config) {
29577
29583
  search.set("include", input.include);
29578
29584
  const query = search.size === 0 ? "" : `?${search.toString()}`;
29579
29585
  return SessionWireSchema.array().parse(JSON.parse(await request(`/v1/sessions${query}`, {})));
29580
- },
29581
- replay: async (input) => ReplayWireSchema.parse(JSON.parse(await post("/v1/replay", {
29582
- session_id: input.sessionID,
29583
- subjects: input.subjects.map((cursor) => cursor.after === undefined ? { subject: cursor.subject } : { subject: cursor.subject, after: cursor.after }),
29584
- ...input.maxMessages === undefined ? {} : { max_messages: input.maxMessages }
29585
- }, {
29586
- timeoutMs: input.timeoutMs ?? REPLAY_TIMEOUT_MS,
29587
- retry: false,
29588
- actingSession: input.sessionID
29589
- })))
29586
+ }
29590
29587
  };
29591
29588
  }
29592
29589
  function waitForRetry(delayMs) {