@sjawhar/claude-envoy 4.21.1 → 4.22.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.
@@ -36648,6 +36648,7 @@ var IDEMPOTENCY_KEY_HEADER = "Idempotency-Key";
36648
36648
  var IDEMPOTENCY_REPLAYED_HEADER = "Idempotency-Replayed";
36649
36649
  var IDEMPOTENCY_KEY_MAX = 128;
36650
36650
  var IDEMPOTENCY_KEY_PATTERN = new RegExp(`^[A-Za-z0-9._:-]{1,${IDEMPOTENCY_KEY_MAX}}$`);
36651
+ var IDEMPOTENCY_KEY_REUSED = "KEY_REUSED";
36651
36652
  var IDEMPOTENCY_KEY_IN_FLIGHT = "KEY_IN_FLIGHT";
36652
36653
  var IDEMPOTENCY_KEY_COMMITTED = "KEY_COMMITTED";
36653
36654
  var IDEMPOTENCY_ANSWER_NOT_KEPT = "ANSWER_NOT_KEPT";
@@ -40197,7 +40198,8 @@ var EnvoySectionSchema = strictObject({
40197
40198
  natsUrls: array(string2().trim().min(1, "must not be empty")).optional(),
40198
40199
  token: string2().optional(),
40199
40200
  natsSeed: string2().optional(),
40200
- natsAuth: string2().optional()
40201
+ natsAuth: string2().optional(),
40202
+ inbound: string2().optional()
40201
40203
  });
40202
40204
  var EnvoyFileSchema = looseObject({
40203
40205
  $schema: string2().optional(),
@@ -43536,7 +43538,7 @@ class DispatchWriteUnsettledError extends Error {
43536
43538
  attempts;
43537
43539
  key;
43538
43540
  name = "DispatchWriteUnsettledError";
43539
- constructor(last, attempts, key, unanswered, keyed = false) {
43541
+ constructor(last, attempts, key, unanswered) {
43540
43542
  let answer;
43541
43543
  let why = last instanceof DispatchServiceError && last.status >= 500 ? "an attempt of the write may have reached Dispatch" : "an earlier attempt of the write may have reached Dispatch";
43542
43544
  if (last instanceof DispatchGatewayError) {
@@ -43551,10 +43553,7 @@ class DispatchWriteUnsettledError extends Error {
43551
43553
  why = "an attempt of the write may have reached Dispatch";
43552
43554
  }
43553
43555
  const tried = attempts === 1 ? "its only attempt" : `the last of ${attempts} attempts`;
43554
- const next = keyed ? ". Dispatch finishes an attempt it received whatever this command does, so read the " + "write back before you send it again: a new command sends it under a new key." : ": check whether it did before retrying it.";
43555
- super(`${answer} (${tried}), and ${why}, so it may or may not have taken effect${next}`, {
43556
- cause: last
43557
- });
43556
+ super(`${answer} (${tried}), and ${why}, so it may or may not have taken effect. Dispatch ` + "finishes an attempt it received whatever this command does, so read the write back " + "before you send it again: a new command sends it under a new key.", { cause: last });
43558
43557
  this.last = last;
43559
43558
  this.attempts = attempts;
43560
43559
  this.key = key;
@@ -43643,43 +43642,6 @@ function retryAfterMs(response) {
43643
43642
  const at = Date.parse(value);
43644
43643
  return Number.isNaN(at) ? 0 : Math.max(0, at - Date.now());
43645
43644
  }
43646
- var KEYED_LAYER_MEMORY_MS = 5 * 60000;
43647
- var KEYED_LAYER_SEEN = new Map;
43648
- var KEYED_LAYER_PROBES = new Map;
43649
- var KEY_LAYER_PROBE_MS = 5000;
43650
- function keyedLayerMemory() {
43651
- const wall = Date.now();
43652
- const now = performance.now();
43653
- const kept = {};
43654
- for (const [origin, seen] of KEYED_LAYER_SEEN) {
43655
- const age = now - seen;
43656
- if (age >= 0 && age < KEYED_LAYER_MEMORY_MS) {
43657
- kept[origin] = new Date(wall - age).toISOString();
43658
- }
43659
- }
43660
- return kept;
43661
- }
43662
- function rememberKeyedLayer(saved) {
43663
- if (typeof saved !== "object" || saved === null)
43664
- return;
43665
- const wall = Date.now();
43666
- const now = performance.now();
43667
- for (const [origin, at] of Object.entries(saved)) {
43668
- if (typeof at !== "string")
43669
- continue;
43670
- const age = wall - Date.parse(at);
43671
- if (!(age >= 0 && age < KEYED_LAYER_MEMORY_MS))
43672
- continue;
43673
- const seen = now - age;
43674
- const known = KEYED_LAYER_SEEN.get(origin);
43675
- if (known === undefined || known < seen)
43676
- KEYED_LAYER_SEEN.set(origin, seen);
43677
- }
43678
- }
43679
- function keyEchoed(response, key) {
43680
- const echoed = response.headers.get(IDEMPOTENCY_KEY_HEADER)?.trim() ?? "";
43681
- return echoed.replace(/^"(.*)"$/, "$1") === key;
43682
- }
43683
43645
  var STREAMED_BODY_MIN = 1 << 20;
43684
43646
  var STREAMED_BODY_CHUNK = 64 << 10;
43685
43647
  function attemptBody(body, headers, progress) {
@@ -43718,17 +43680,18 @@ function parsedJson(response, text) {
43718
43680
  }
43719
43681
  }
43720
43682
  var NULL_BODY_STATUSES = new Set([101, 204, 205, 304]);
43721
- async function writeAnswer(response, echoed) {
43683
+ async function writeAnswer(response) {
43722
43684
  if (NULL_BODY_STATUSES.has(response.status)) {
43723
43685
  return {
43724
43686
  response,
43725
- echoed,
43726
43687
  malformed: false,
43727
43688
  notJson: false,
43728
43689
  text: "",
43729
43690
  json: undefined,
43730
43691
  code: undefined,
43731
- error: undefined
43692
+ error: undefined,
43693
+ replayed: response.headers.get(IDEMPOTENCY_REPLAYED_HEADER)?.trim() === "?1",
43694
+ keyEcho: response.headers.get(IDEMPOTENCY_KEY_HEADER) ?? undefined
43732
43695
  };
43733
43696
  }
43734
43697
  const text = await response.text();
@@ -43738,23 +43701,27 @@ async function writeAnswer(response, echoed) {
43738
43701
  const own = typeof shape.error === "string";
43739
43702
  return {
43740
43703
  response,
43741
- echoed,
43742
43704
  malformed: text !== "" && typed && json === undefined,
43743
43705
  notJson: text === "" || !typed,
43744
43706
  text,
43745
43707
  json,
43746
43708
  code: own ? shape.code : undefined,
43747
- error: own ? shape.error : undefined
43709
+ error: own ? shape.error : undefined,
43710
+ replayed: response.headers.get(IDEMPOTENCY_REPLAYED_HEADER)?.trim() === "?1",
43711
+ keyEcho: response.headers.get(IDEMPOTENCY_KEY_HEADER) ?? undefined
43748
43712
  };
43749
43713
  }
43750
- function answerEvent(answer, canTellDeadToken, layerKnown) {
43714
+ function isStoredKeyStatus(status) {
43715
+ return status >= 400 && status < 500 && status !== 401 && status !== 408 && status !== 429;
43716
+ }
43717
+ function answerEvent(answer, requestKey, keyEchoed, canTellDeadToken) {
43751
43718
  const { status } = answer.response;
43752
43719
  if (status >= 200 && status < 300) {
43753
43720
  if (answer.notJson)
43754
43721
  return "foreign-2xx";
43755
43722
  if (answer.malformed)
43756
43723
  return "body-malformed";
43757
- return !answer.echoed && layerKnown ? "foreign-2xx" : "applied";
43724
+ return keyEchoed && answer.keyEcho !== requestKey ? "foreign-2xx" : "applied";
43758
43725
  }
43759
43726
  if (status >= 300 && status < 400)
43760
43727
  return "redirect";
@@ -43769,7 +43736,13 @@ function answerEvent(answer, canTellDeadToken, layerKnown) {
43769
43736
  return "in-flight";
43770
43737
  return status >= 500 ? "server-error" : "try-later";
43771
43738
  }
43772
- return answer.echoed ? "judged" : "unjudged";
43739
+ if (answer.replayed || answer.code === IDEMPOTENCY_KEY_COMMITTED)
43740
+ return "judged";
43741
+ if (answer.keyEcho !== requestKey || !isStoredKeyStatus(status))
43742
+ return "unjudged";
43743
+ if (answer.code === IDEMPOTENCY_KEY_REUSED)
43744
+ return "judged";
43745
+ return answer.code === IDEMPOTENCY_KEY_IN_FLIGHT ? "unjudged" : "judged";
43773
43746
  }
43774
43747
  function credentialEvent(error) {
43775
43748
  return error instanceof TradeRetryingError ? "no-credential" : "no-credential-final";
@@ -44355,7 +44328,7 @@ class DispatchClient {
44355
44328
  key: key ?? crypto.randomUUID(),
44356
44329
  request: `${method} ${requestForText(this.#baseUrl, url, DISPATCH_URL_SETTING)}`,
44357
44330
  writes,
44358
- progress: { sent: 0, running: false, sawKeyedLayer: false }
44331
+ progress: { sent: 0, running: false, keyEchoed: false }
44359
44332
  };
44360
44333
  }
44361
44334
  async#upload(path, input, key) {
@@ -44373,12 +44346,12 @@ class DispatchClient {
44373
44346
  form.set("file", input.file, input.name);
44374
44347
  return this.#form("POST", path, form, key);
44375
44348
  }
44376
- async#form(method, path, form, key) {
44349
+ async#form(method, path, form, callerKey) {
44377
44350
  const url = this.#url(path);
44378
44351
  const encoded = new Response(form);
44379
44352
  const type = encoded.headers.get("Content-Type") ?? "multipart/form-data";
44380
44353
  const body = { content: new Uint8Array(await encoded.arrayBuffer()), type };
44381
- const write = this.#writeCall(method, url, key);
44354
+ const write = this.#writeCall(method, url, callerKey);
44382
44355
  if (write !== undefined) {
44383
44356
  const answer = await this.#write(method, url, body, "application/json", undefined, write);
44384
44357
  return this.#payloadOf(method, url, answer);
@@ -44463,14 +44436,12 @@ class DispatchClient {
44463
44436
  sent
44464
44437
  };
44465
44438
  }
44466
- const echoed = keyEchoed(response, key);
44467
- const heard = { echoed, retryAfterMs: retryAfterMs(response) };
44468
- if (echoed)
44469
- KEYED_LAYER_SEEN.set(this.#baseUrl, this.#now());
44470
- progress.sawKeyedLayer ||= echoed;
44439
+ const heard = { retryAfterMs: retryAfterMs(response) };
44440
+ if (response.headers.get(IDEMPOTENCY_KEY_HEADER) === key)
44441
+ progress.keyEchoed = true;
44471
44442
  let answer;
44472
44443
  try {
44473
- answer = await writeAnswer(response, echoed);
44444
+ answer = await writeAnswer(response);
44474
44445
  } catch (error) {
44475
44446
  const stop = stoppedEvent(limit, true, error);
44476
44447
  return {
@@ -44482,7 +44453,7 @@ class DispatchClient {
44482
44453
  };
44483
44454
  }
44484
44455
  return {
44485
- event: answerEvent(answer, this.#credential.stale !== undefined && !deadTokenTold, progress.sawKeyedLayer || this.#remembersKeyedLayer()),
44456
+ event: answerEvent(answer, write.key, progress.keyEchoed, this.#credential.stale !== undefined && !deadTokenTold),
44486
44457
  answer,
44487
44458
  presented,
44488
44459
  sent,
@@ -44547,16 +44518,7 @@ class DispatchClient {
44547
44518
  const scheduled = progress.running ? Math.min(pausesMs[paced - 1] ?? inFlightPauseMs, inFlightPauseMs) : pausesMs[paced - 1];
44548
44519
  const wait = Math.max(scheduled ?? 0, last.heard?.retryAfterMs ?? 0);
44549
44520
  const latest = Math.min(started + (progress.running ? inFlightWithinMs : withinMs), lastAsk);
44550
- let again = scheduled !== undefined && this.#now() + wait <= latest;
44551
- const { answer } = last;
44552
- const unjudged = answer !== undefined && !answer.echoed && answer.error !== undefined;
44553
- if (again && state === "may-have-landed") {
44554
- again = (last.heard?.echoed ?? false) || await this.#runsKeyedLayer(unjudged);
44555
- progress.sawKeyedLayer ||= again;
44556
- again &&= this.#now() + wait <= latest;
44557
- } else if (unjudged && state === "nothing-sent") {
44558
- KEYED_LAYER_SEEN.delete(this.#baseUrl);
44559
- }
44521
+ const again = scheduled !== undefined && this.#now() + wait <= latest;
44560
44522
  if (!again) {
44561
44523
  event = "exhausted";
44562
44524
  continue;
@@ -44580,10 +44542,6 @@ class DispatchClient {
44580
44542
  }
44581
44543
  }
44582
44544
  }
44583
- #remembersKeyedLayer() {
44584
- const seen = KEYED_LAYER_SEEN.get(this.#baseUrl);
44585
- return seen !== undefined && this.#now() - seen < KEYED_LAYER_MEMORY_MS;
44586
- }
44587
44545
  #credentialSignal(limit) {
44588
44546
  return credentialDeadline(limit, Math.max(1, this.#deadlineAt - performance.now()));
44589
44547
  }
@@ -44621,7 +44579,7 @@ class DispatchClient {
44621
44579
  let own = failure;
44622
44580
  if (answer?.response.ok === true) {
44623
44581
  const { status } = answer.response;
44624
- own = new Error(answer.notJson ? `${request} answered ${status} with ${bodyForText(answer.text, this.#sent.with(this.token), "JSON")}, though every Dispatch write answers JSON, so something in Dispatch's place answered` : event === "foreign-2xx" ? `${request} answered ${status} without carrying back its ${IDEMPOTENCY_KEY_HEADER}, though this Dispatch answers every keyed write with it, so something in Dispatch's place answered` : `${request} answered ${status} with a body that is not the JSON its Content-Type says`);
44582
+ own = new Error(answer.notJson ? `${request} answered ${status} with ${bodyForText(answer.text, this.#sent.with(this.token), "JSON")}, though every Dispatch write answers JSON, so something in Dispatch's place answered` : event === "foreign-2xx" ? `${request} answered ${status} without carrying back its ${IDEMPOTENCY_KEY_HEADER}, though an earlier answer of this write carried it and Dispatch answers every keyed write with it, so something in Dispatch's place answered` : `${request} answered ${status} with a body that is not the JSON its Content-Type says`);
44625
44583
  } else if (answer !== undefined) {
44626
44584
  own = event === "no-route" && routeSpent ? new DispatchNoRouteError : this.#payloadOrError(method, url, answer);
44627
44585
  }
@@ -44653,39 +44611,7 @@ class DispatchClient {
44653
44611
  unanswered = `${request} failed on its last attempt (${last.message})`;
44654
44612
  }
44655
44613
  }
44656
- return new DispatchWriteUnsettledError(last, progress.sent, write.key, unanswered, progress.sawKeyedLayer);
44657
- }
44658
- async#runsKeyedLayer(unjudged) {
44659
- const origin = this.#baseUrl;
44660
- if (unjudged)
44661
- KEYED_LAYER_SEEN.delete(origin);
44662
- const seen = KEYED_LAYER_SEEN.get(origin);
44663
- if (seen !== undefined && this.#now() - seen < KEYED_LAYER_MEMORY_MS)
44664
- return true;
44665
- let probe = KEYED_LAYER_PROBES.get(origin);
44666
- if (probe === undefined) {
44667
- probe = this.#probeKeyedLayer().finally(() => KEYED_LAYER_PROBES.delete(origin));
44668
- KEYED_LAYER_PROBES.set(origin, probe);
44669
- }
44670
- const runs = await probe;
44671
- if (runs)
44672
- KEYED_LAYER_SEEN.set(origin, this.#now());
44673
- return runs;
44674
- }
44675
- async#probeKeyedLayer() {
44676
- try {
44677
- const response = await this.#fetch(`${this.#baseUrl}/healthz`, {
44678
- method: "GET",
44679
- headers: { Accept: "application/json" },
44680
- signal: AbortSignal.any([this.#signal, AbortSignal.timeout(KEY_LAYER_PROBE_MS)])
44681
- });
44682
- if (!isJson(response))
44683
- return false;
44684
- const health = await response.json();
44685
- return typeof health === "object" && health !== null && Reflect.get(health, "idempotency_keys") === true;
44686
- } catch {
44687
- return false;
44688
- }
44614
+ return new DispatchWriteUnsettledError(last, progress.sent, write.key, unanswered);
44689
44615
  }
44690
44616
  #url(path, query) {
44691
44617
  const url = new URL(`${path.map((segment) => encodeURIComponent(segment)).join("/")}`, `${this.#baseUrl}/`);
@@ -52524,15 +52450,13 @@ function loadSessionMemory(dir, sessionId) {
52524
52450
  const pictures = shownPictures(sessionId);
52525
52451
  for (const address of stringList(state.pictures))
52526
52452
  pictures.add(address);
52527
- rememberKeyedLayer(state.keyedLayer);
52528
52453
  return new Set(stringList(state.follows));
52529
52454
  }
52530
52455
  function writeMemory(dir, sessionId, follows) {
52531
52456
  const state = {
52532
52457
  advice: [...adviceMemory()],
52533
52458
  pictures: [...shownPictures(sessionId)],
52534
- follows: [...follows],
52535
- keyedLayer: keyedLayerMemory()
52459
+ follows: [...follows]
52536
52460
  };
52537
52461
  writeAtomically(join6(dir, "state.json"), `${JSON.stringify(state)}
52538
52462
  `);
@@ -53013,6 +52937,7 @@ function resolvedInterval(raw, fallback) {
53013
52937
  const named = namedInterval(raw);
53014
52938
  return named === undefined ? fallback : Math.min(Math.max(named, MIN_INTERVAL_MS), MAX_INTERVAL_MS);
53015
52939
  }
52940
+ var ENVOY_INBOUND_VAR = "ENVOY_INBOUND";
53016
52941
  function natsSeedFromEnvironment(env) {
53017
52942
  const { NATS_NKEY_SEED_FILE: file, NATS_NKEY_SEED: plain } = env;
53018
52943
  if (file !== undefined) {
@@ -53082,6 +53007,33 @@ function natsCredential(env, section, namedNatsUrls, filePath, session) {
53082
53007
  throw new NoSessionNamedError(auth.source);
53083
53008
  return { kind: "broker", broker: brokerNatsCredential(env, session, auth.source) };
53084
53009
  }
53010
+ var LOOPBACK_HOST = /^(localhost|127(\.\d{1,3}){3}|\[::1\])$/i;
53011
+ function natsConflictText(source, natsSetting) {
53012
+ return `${source} is listener, and ${natsSetting} names NATS servers: set one of the two`;
53013
+ }
53014
+ function listenerInbound(source, natsSetting, credential, session) {
53015
+ if (natsSetting !== undefined)
53016
+ return { off: natsConflictText(source, natsSetting) };
53017
+ if ("noBrokerRoute" in credential) {
53018
+ return { off: `${source} is listener, but ${credential.noBrokerRoute}` };
53019
+ }
53020
+ if (credential.scheme !== "DPoP") {
53021
+ return {
53022
+ off: `${source} is listener, but the listener's credential is a bearer (ENVOY_TOKEN, ENVOY_TOKEN_FILE or envoy.token), and the relay socket admits only the session's broker token`
53023
+ };
53024
+ }
53025
+ if (session === undefined) {
53026
+ return {
53027
+ off: `${source} is listener, but this process names no session for its relay socket's token`,
53028
+ noSessionNamed: true
53029
+ };
53030
+ }
53031
+ return { relaySetting: source, relayCredential: credential };
53032
+ }
53033
+ function plainHttpOffMachine(url) {
53034
+ const host = URL.canParse(url) ? new URL(url) : undefined;
53035
+ return host?.protocol === "http:" && !LOOPBACK_HOST.test(host.hostname) ? host.hostname : undefined;
53036
+ }
53085
53037
  function envoySettings(env, config, options = {}) {
53086
53038
  if (config.kind === "failed")
53087
53039
  return offWithError(config.error);
@@ -53100,7 +53052,18 @@ function envoySettings(env, config, options = {}) {
53100
53052
  }
53101
53053
  const listener = section.url ?? DEFAULT_ENVOY_URL;
53102
53054
  const url = namedUrl ?? listener;
53055
+ const namedInbound = nonEmpty(env.ENVOY_INBOUND);
53056
+ const choice = namedInbound !== undefined ? { value: namedInbound, source: ENVOY_INBOUND_VAR } : section.inbound === undefined ? undefined : { value: section.inbound, source: `envoy.inbound in ${config.path}` };
53057
+ const natsSetting = namedNatsUrls.length > 0 ? "ENVOY_NATS_URL" : (section.natsUrls ?? []).length > 0 ? `envoy.natsUrls in ${config.path}` : undefined;
53058
+ if (choice?.value === "listener") {
53059
+ const host = plainHttpOffMachine(url);
53060
+ if (host !== undefined) {
53061
+ const plainHttp = `the listener's address is plain http to ${host}, which is not this machine, so the session's token would cross the network unencrypted; use an https address`;
53062
+ return offWithError(natsSetting === undefined ? `${choice.source} is listener, but ${plainHttp}` : `${natsConflictText(choice.source, natsSetting)}. And ${plainHttp}`);
53063
+ }
53064
+ }
53103
53065
  let credential;
53066
+ let noBrokerRoute = "";
53104
53067
  try {
53105
53068
  const source = bearerSource(env, "ENVOY", () => section.token === undefined ? undefined : {
53106
53069
  token: section.token,
@@ -53110,7 +53073,10 @@ function envoySettings(env, config, options = {}) {
53110
53073
  checkout: false
53111
53074
  });
53112
53075
  if (source.kind === "none") {
53113
- credential = brokerRouteConfigured(env).traded ? brokerCredential(env, options.session) : undefined;
53076
+ const route = brokerRouteConfigured(env);
53077
+ credential = route.traded ? brokerCredential(env, options.session) : undefined;
53078
+ if (!route.traded)
53079
+ noBrokerRoute = route.gap;
53114
53080
  } else {
53115
53081
  credential = bearerCredential(source.kind === "variable" ? source.token : fileBearer(source, url, "ENVOY", env));
53116
53082
  }
@@ -53121,13 +53087,17 @@ function envoySettings(env, config, options = {}) {
53121
53087
  let inbound;
53122
53088
  if (options.nats === false)
53123
53089
  inbound = { off: NO_NATS_CONNECTION };
53124
- else if (natsUrls.length === 0)
53090
+ else if (choice !== undefined && choice.value !== "nats" && choice.value !== "listener") {
53091
+ inbound = { off: `${choice.source} is neither nats nor listener` };
53092
+ } else if (choice?.value === "listener") {
53093
+ inbound = listenerInbound(choice.source, natsSetting, credential ?? { noBrokerRoute }, options.session);
53094
+ } else if (natsSetting === undefined)
53125
53095
  inbound = { off: NO_NATS_SERVER };
53126
53096
  else {
53127
53097
  try {
53128
53098
  inbound = {
53129
53099
  natsUrls,
53130
- natsServersSetting: namedNatsUrls.length > 0 ? "ENVOY_NATS_URL" : `envoy.natsUrls in ${config.path}`,
53100
+ natsServersSetting: natsSetting,
53131
53101
  natsCredential: natsCredential(env, section, namedNatsUrls, config.path, options.session)
53132
53102
  };
53133
53103
  } catch (error) {
@@ -53204,6 +53174,9 @@ function startNotice(config, dispatch, envoy, nats, lost) {
53204
53174
  if (envoy.enabled && nats && "off" in envoy.inbound) {
53205
53175
  parts.push(`Envoy's inbound messages are off: ${envoy.inbound.off}; the Envoy tools still work`);
53206
53176
  }
53177
+ if (envoy.enabled && nats && "relaySetting" in envoy.inbound) {
53178
+ parts.push(`Envoy's inbound messages come through the listener's relay socket (${envoy.inbound.relaySetting} is listener), which carries no live view: the Agents page shows nothing of this session's turns`);
53179
+ }
53207
53180
  if (envoy.enabled && envoy.passDeadlineRaisedFrom !== undefined) {
53208
53181
  parts.push(`Envoy's pass deadline is ${envoy.passDeadlineMs} ms, not the ${envoy.passDeadlineRaisedFrom} ms ENVOY_PASS_DEADLINE_MS names: a deadline inside one ${envoy.heartbeatMs} ms heartbeat interval would abandon every pass before the next tick, so the registration refresh the heartbeat posts for a stalled pass would never run`);
53209
53182
  }
@@ -53390,6 +53363,7 @@ var ErrorWireSchema = object({
53390
53363
  error: string2(),
53391
53364
  code: string2().optional(),
53392
53365
  reason: string2().optional(),
53366
+ refused: array(string2()).optional(),
53393
53367
  expected: array(string2()).optional(),
53394
53368
  state: SessionStateSchema.optional(),
53395
53369
  holder: string2().optional(),
@@ -53506,6 +53480,7 @@ class EnvoyApiError extends Error {
53506
53480
  lastSeen;
53507
53481
  claimReleased;
53508
53482
  retryAfterSeconds;
53483
+ refused;
53509
53484
  constructor(details, shown = {}) {
53510
53485
  let parsed;
53511
53486
  try {
@@ -53524,6 +53499,7 @@ class EnvoyApiError extends Error {
53524
53499
  this.lastSeen = parsed?.last_seen;
53525
53500
  this.claimReleased = parsed?.claim_released;
53526
53501
  this.retryAfterSeconds = parsed?.retry_after_seconds;
53502
+ this.refused = parsed?.refused;
53527
53503
  }
53528
53504
  }
53529
53505
  var mintedDedupeKey2 = new RegExp(MINTED_DEDUPE_KEY_PATTERN);
@@ -56186,1145 +56162,1812 @@ var import_nats6 = __toESM(require_mod4(), 1);
56186
56162
  // codex/package.json
56187
56163
  var name = "@sjawhar/codex-envoy";
56188
56164
 
56189
- // ../envoy-client/src/nats-connection.ts
56190
- var import_nats2 = __toESM(require_mod4(), 1);
56191
- var import_nats3 = __toESM(require_nats(), 1);
56192
- var import_servers = __toESM(require_servers(), 1);
56193
- import { setTimeout as delay } from "timers/promises";
56194
-
56195
- // ../envoy-client/src/nats-auth.ts
56196
- var import_nats = __toESM(require_mod4(), 1);
56197
- var seedKeys = import_nats.nkeys;
56198
- function natsAuthOptions(credential) {
56199
- switch (credential.kind) {
56200
- case "none":
56201
- return {};
56202
- case "broker":
56203
- return { authenticator: credential.broker.authenticator };
56204
- case "seed": {
56205
- const { seed } = credential;
56206
- const bytes = new TextEncoder().encode(seed.value);
56207
- let publicKey;
56165
+ // ../envoy-client/src/delivery-ledger.ts
56166
+ var DELIVERY_LEDGER_TTL_MS = DELIVERY_DUPLICATE_WINDOW_MS;
56167
+ var DELIVERY_LEDGER_LIMIT = 20000;
56168
+ var LedgerEntrySchema = object({
56169
+ event_id: string2().min(1).optional(),
56170
+ dedupe_key: string2().min(1).optional(),
56171
+ at: number2()
56172
+ });
56173
+ var LedgerStateSchema = object({
56174
+ topics: array(string2()).default([])
56175
+ });
56176
+ var LedgerSnapshotSchema = object({
56177
+ state: LedgerStateSchema.optional(),
56178
+ ledger: array(LedgerEntrySchema)
56179
+ });
56180
+ function createDeliveryLedger(options) {
56181
+ const { host } = options;
56182
+ const now = options.now ?? Date.now;
56183
+ const ledger = createLedger(now);
56184
+ let topics = [];
56185
+ let unwritten = [];
56186
+ let writtenState;
56187
+ let writes = Promise.resolve();
56188
+ let epoch = 0;
56189
+ const safely = (what, call) => {
56190
+ try {
56191
+ call();
56192
+ } catch (error) {
56208
56193
  try {
56209
- publicKey = seedKeys.fromSeed(bytes).getPublicKey();
56194
+ host.log(`delivery ledger: ${what} failed`, error);
56195
+ } catch {}
56196
+ }
56197
+ };
56198
+ const log = (message, error) => safely("log", () => host.log(message, error));
56199
+ const sessionRead = (read) => () => {
56200
+ try {
56201
+ return read();
56202
+ } catch {
56203
+ return;
56204
+ }
56205
+ };
56206
+ const currentSession = sessionRead(() => host.sessionID());
56207
+ const writeSession = sessionRead(() => host.writeSessionID === undefined ? host.sessionID() : host.writeSessionID());
56208
+ const bindTo = (sessionID, read) => {
56209
+ if (sessionID === undefined || sessionID === "" || read() !== sessionID)
56210
+ return;
56211
+ const bound = epoch;
56212
+ return { sessionID, alive: () => bound === epoch && read() === sessionID };
56213
+ };
56214
+ const bind = () => bindTo(currentSession(), currentSession);
56215
+ const stateJSON = () => JSON.stringify({ topics: [...topics].sort() });
56216
+ const record = (identity) => {
56217
+ const entry = ledger.record(identity);
56218
+ if (entry !== undefined)
56219
+ unwritten.push(entry);
56220
+ };
56221
+ const flush = (alive) => {
56222
+ const written = writes.then(async () => {
56223
+ if (!alive())
56224
+ return false;
56225
+ const json = stateJSON();
56226
+ const delivered = unwritten;
56227
+ if (json === writtenState && delivered.length === 0)
56228
+ return true;
56229
+ unwritten = [];
56230
+ const state = json === writtenState ? undefined : JSON.parse(json);
56231
+ try {
56232
+ await host.write({
56233
+ delivered,
56234
+ state,
56235
+ snapshot: () => ({ state: JSON.parse(json), ledger: ledger.list() })
56236
+ });
56237
+ if (state !== undefined)
56238
+ writtenState = json;
56239
+ return true;
56210
56240
  } catch (error) {
56211
- throw new Error(`${seed.source} does not hold a valid nkey seed: ${messageFor(error)}`);
56241
+ unwritten = [...delivered, ...unwritten];
56242
+ log("delivery ledger: could not persist the state; the next write carries it", error);
56243
+ return false;
56212
56244
  }
56213
- if (!publicKey.startsWith("U")) {
56214
- throw new Error(`${seed.source} holds an nkey seed that is not a user's (public key ${publicKey})`);
56245
+ });
56246
+ writes = written.then(() => {
56247
+ return;
56248
+ });
56249
+ return written;
56250
+ };
56251
+ const syncFollowed = () => {
56252
+ topics = [...new Set(host.followedSubjects())];
56253
+ };
56254
+ const failureNotice = (envelope, error) => ({
56255
+ eventId: envelope.event_id ?? "unknown",
56256
+ sender: senderLabel(envelope),
56257
+ summary: envelope.payload_summary ?? "unknown",
56258
+ publishedAt: inboundTimestamp(envelope.issued_at),
56259
+ error,
56260
+ readWith: envelope.source === "dispatch" ? "dispatch read" : "envoy_inbox",
56261
+ envelope
56262
+ });
56263
+ const showFailureNotice = async (sessionID, notice, alive) => {
56264
+ let queued;
56265
+ try {
56266
+ queued = await host.showFailureNotice(sessionID, notice) === "queued";
56267
+ } catch (error) {
56268
+ if (alive())
56269
+ safely("failure notice warning", () => host.failureNoticeFailed(notice, error));
56270
+ return false;
56271
+ }
56272
+ if (queued || !alive())
56273
+ return true;
56274
+ record(ledgerIdentity(notice.envelope));
56275
+ await flush(alive);
56276
+ return true;
56277
+ };
56278
+ return {
56279
+ async followedChanged() {
56280
+ const alive = bind()?.alive;
56281
+ if (alive === undefined)
56282
+ return;
56283
+ try {
56284
+ syncFollowed();
56285
+ await flush(alive);
56286
+ } catch (error) {
56287
+ log("delivery ledger: could not take the followed subjects", error);
56215
56288
  }
56216
- return { authenticator: import_nats.nkeyAuthenticator(bytes) };
56289
+ },
56290
+ delivered: (frame) => ledger.has(ledgerIdentity(frame)),
56291
+ async recordDelivered(frame) {
56292
+ const alive = bind()?.alive;
56293
+ if (alive === undefined)
56294
+ return;
56295
+ record(ledgerIdentity(frame));
56296
+ await flush(alive);
56297
+ },
56298
+ async recordDeliveredFor(sessionID, frame) {
56299
+ const alive = bindTo(sessionID, writeSession)?.alive;
56300
+ if (alive === undefined)
56301
+ return false;
56302
+ record(ledgerIdentity(frame));
56303
+ return await flush(alive);
56304
+ },
56305
+ async liveFailed(sessionID, envelope, error) {
56306
+ const alive = bindTo(sessionID, currentSession)?.alive;
56307
+ if (alive === undefined) {
56308
+ log("delivery ledger: a failed frame was not reported here; the session it names is closed");
56309
+ return false;
56310
+ }
56311
+ try {
56312
+ return await showFailureNotice(sessionID, failureNotice(envelope, messageFor(error)), alive);
56313
+ } catch (thrown) {
56314
+ log("delivery ledger: could not report a frame the session was not shown", thrown);
56315
+ return false;
56316
+ }
56317
+ },
56318
+ restore(snapshot) {
56319
+ epoch += 1;
56320
+ ledger.restore(snapshot.ledger);
56321
+ topics = [...new Set(snapshot.state?.topics ?? [])];
56322
+ writtenState = snapshot.state === undefined ? undefined : stateJSON();
56323
+ unwritten = [];
56217
56324
  }
56218
- }
56325
+ };
56219
56326
  }
56220
-
56221
- // ../envoy-client/src/nats-connection.ts
56222
- var NATS_PING_INTERVAL_MS = 1e4;
56223
- var NATS_MAX_PINGS_OUT = 2;
56224
- var NATS_DIAL_TIMEOUT_MS = 1e4;
56225
- function natsConnectionOptions(input) {
56327
+ function failureNoticeFields(notice) {
56328
+ 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.";
56226
56329
  return {
56227
- servers: [...input.servers],
56228
- name: input.name,
56229
- ...natsAuthOptions(input.credential),
56230
- timeout: NATS_DIAL_TIMEOUT_MS,
56231
- reconnect: true,
56232
- maxReconnectAttempts: -1,
56233
- pingInterval: NATS_PING_INTERVAL_MS,
56234
- maxPingOut: NATS_MAX_PINGS_OUT,
56235
- ...input.credential.kind === "broker" ? {
56236
- ignoreAuthErrorAbort: true,
56237
- reconnectDelayHandler: brokerRedialDelays(input.credential.broker)
56238
- } : { reconnectTimeWait: 2000 }
56330
+ notice: "message not shown",
56331
+ event_id: notice.eventId,
56332
+ from: notice.sender,
56333
+ summary: notice.summary,
56334
+ published_at: notice.publishedAt,
56335
+ error: notice.error,
56336
+ detail: `This session could not be shown this message, so it is not coming back on its own. ${readWith}`
56239
56337
  };
56240
56338
  }
56241
- var BROKER_REDIAL_FIRST_MS = 4000;
56242
- var BROKER_REDIAL_CAP_MS = 20000;
56243
- var BROKER_REDIAL_OUTAGE_GAP_MS = 60000;
56244
- var BROKER_REDIAL_POLL_MS = 1000;
56245
- var DUE_SLACK_MS = 50;
56246
- function brokerRedialWaitBounds(wait) {
56247
- const highestMs = Math.min(BROKER_REDIAL_CAP_MS, BROKER_REDIAL_FIRST_MS * 2 ** Math.min(wait - 1, 30));
56248
- return { lowestMs: highestMs / 2, highestMs };
56339
+ function envoyNoticeText(fields) {
56340
+ return encode3({ envoy: fields });
56249
56341
  }
56250
- function brokerRedialWaitMs(wait, random) {
56251
- const { lowestMs, highestMs } = brokerRedialWaitBounds(wait);
56252
- return Math.round(lowestMs + random() * (highestMs - lowestMs));
56342
+ async function closeReplayedRemoval(frame, host) {
56343
+ const closed = (subscriptionRemovedTopics(frame.data, host.sessionID) ?? []).filter((topic) => host.relay?.followedBefore(topic, frame.storedAtMs) !== false && host.close(topic));
56344
+ if (closed.length === 0)
56345
+ return closed;
56346
+ const unregistering = host.unregister(closed);
56347
+ await host.followedChanged();
56348
+ await unregistering;
56349
+ return closed;
56253
56350
  }
56254
- function brokerRedialDelays(credential, random = Math.random, now = Date.now, pollMs = BROKER_REDIAL_POLL_MS) {
56255
- let lastCall = Number.NEGATIVE_INFINITY;
56256
- let dialedAt = 0;
56257
- let dueAt = Number.NEGATIVE_INFINITY;
56258
- let waits = 0;
56259
- let rushed;
56260
- let dialedSession;
56261
- let rushedInWait = false;
56262
- let admissions = credential.admissions().count;
56263
- return () => {
56264
- const at = now();
56265
- if (at - lastCall > BROKER_REDIAL_OUTAGE_GAP_MS) {
56266
- dueAt = Number.NEGATIVE_INFINITY;
56267
- waits = 0;
56351
+ function ledgerIdentity(frame) {
56352
+ return {
56353
+ ...frame.event_id === undefined || frame.event_id === "" ? {} : { event_id: frame.event_id },
56354
+ ...frame.dedupe_key === undefined || !dedupeKeyNamesItsEvent(frame) ? {} : { dedupe_key: frame.dedupe_key }
56355
+ };
56356
+ }
56357
+ function createLedger(now) {
56358
+ let entries = new Set;
56359
+ const byEvent = new Map;
56360
+ const byKey = new Map;
56361
+ const drop = (entry) => {
56362
+ entries.delete(entry);
56363
+ if (entry.event_id !== undefined && byEvent.get(entry.event_id) === entry) {
56364
+ byEvent.delete(entry.event_id);
56268
56365
  }
56269
- lastCall = at;
56270
- const admitted = credential.admissions();
56271
- if (admitted.count !== admissions) {
56272
- admissions = admitted.count;
56273
- rushedInWait = false;
56274
- if (admitted.dialedAt !== undefined && admitted.dialedAt > dialedAt) {
56275
- dialedAt = admitted.dialedAt;
56276
- }
56366
+ if (entry.dedupe_key !== undefined && byKey.get(entry.dedupe_key) === entry) {
56367
+ byKey.delete(entry.dedupe_key);
56277
56368
  }
56278
- const unpresented = credential.needsReconnect() ? credential.tokenGeneration() : undefined;
56279
- const session = credential.tokenSession();
56280
- if (at < dueAt - DUE_SLACK_MS) {
56281
- const renewal = session === dialedSession;
56282
- if (unpresented === undefined || unpresented === rushed || rushedInWait && renewal) {
56283
- return Math.min(dueAt, at + pollMs) - dialedAt;
56284
- }
56285
- rushed = unpresented;
56286
- rushedInWait = true;
56287
- dialedSession = session;
56288
- dialedAt = at;
56289
- return 0;
56369
+ };
56370
+ const add = (entry) => {
56371
+ if (entries.size >= DELIVERY_LEDGER_LIMIT) {
56372
+ const oldest = entries.values().next();
56373
+ if (oldest.done !== true)
56374
+ drop(oldest.value);
56375
+ }
56376
+ entries.add(entry);
56377
+ if (entry.event_id !== undefined)
56378
+ byEvent.set(entry.event_id, entry);
56379
+ if (entry.dedupe_key !== undefined)
56380
+ byKey.set(entry.dedupe_key, entry);
56381
+ };
56382
+ const expire = () => {
56383
+ const at = now();
56384
+ for (const entry of entries) {
56385
+ if (at - entry.at < DELIVERY_LEDGER_TTL_MS)
56386
+ break;
56387
+ drop(entry);
56388
+ }
56389
+ };
56390
+ const has = (identity) => {
56391
+ expire();
56392
+ return identity.event_id !== undefined && byEvent.has(identity.event_id) || identity.dedupe_key !== undefined && byKey.has(identity.dedupe_key);
56393
+ };
56394
+ return {
56395
+ has,
56396
+ record(identity) {
56397
+ if (identity.event_id === undefined && identity.dedupe_key === undefined)
56398
+ return;
56399
+ if (has(identity))
56400
+ return;
56401
+ const entry = { ...identity, at: now() };
56402
+ add(entry);
56403
+ return entry;
56404
+ },
56405
+ restore(restored) {
56406
+ entries = new Set;
56407
+ byEvent.clear();
56408
+ byKey.clear();
56409
+ const at = now();
56410
+ 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);
56411
+ for (const entry of kept)
56412
+ add({ ...entry });
56413
+ },
56414
+ list() {
56415
+ expire();
56416
+ return [...entries];
56290
56417
  }
56291
- if (unpresented !== undefined)
56292
- rushed = unpresented;
56293
- dialedSession = session;
56294
- rushedInWait = false;
56295
- waits += 1;
56296
- dialedAt = at;
56297
- dueAt = at + brokerRedialWaitMs(waits, random);
56298
- return 0;
56299
56418
  };
56300
56419
  }
56301
- function natsServersForLog(setting, count) {
56302
- return count === 1 ? `the server ${setting} names` : `the ${count} servers ${setting} names`;
56303
- }
56304
- function natsDialFailure(named, error, presenting) {
56305
- const credential = presenting === undefined ? "" : ` presenting ${presenting}`;
56306
- return `could not connect to NATS at ${named}${credential}: ${natsFailureReason(error)}`;
56307
- }
56308
- var NATS_DIAL_PLAN = {
56309
- firstDelayMs: 250,
56310
- maxDelayMs: 4000,
56311
- budgetMs: 25000
56312
- };
56313
- var NATS_DIAL_TOKEN_DROPPED = "the hub refused the session's broker token twice, so the token was dropped and another trade started";
56314
- var NATS_MIN_REDIAL_BOUND_MS = 500;
56315
56420
 
56316
- class NatsDialBoundError extends LoggableError {
56421
+ // ../envoy-client/src/consumer-delivery.ts
56422
+ var DELIVER_SUBJECT_PREFIX = "notifications.envoy.deliver.";
56423
+ function deliverSubject(sessionID) {
56424
+ return `${DELIVER_SUBJECT_PREFIX}${sessionID}`;
56317
56425
  }
56318
- var AUTHORIZATION_REFUSALS = {
56319
- [import_nats2.ErrorCode.AuthorizationViolation]: true,
56320
- [import_nats2.ErrorCode.AuthenticationExpired]: true,
56321
- [import_nats2.ErrorCode.AccountExpired]: true
56322
- };
56323
- var NEVER_CURED = {
56324
- [import_nats2.ErrorCode.BadAuthentication]: true,
56325
- [import_nats2.ErrorCode.BadCreds]: true,
56326
- [import_nats2.ErrorCode.InvalidOption]: true,
56327
- [import_nats2.ErrorCode.NotFunction]: true,
56328
- [import_nats2.ErrorCode.ServerOptionNotAvailable]: true,
56329
- [import_nats2.ErrorCode.WssRequired]: true,
56330
- [import_nats2.ErrorCode.Tls]: true
56426
+ var RelayHeader = {
56427
+ subject: "Envoy-Subject",
56428
+ streamSeq: "Envoy-Stream-Seq",
56429
+ streamID: "Envoy-Stream-Id",
56430
+ delivered: "Envoy-Delivered",
56431
+ storedAt: "Envoy-Stored-At",
56432
+ gap: "Envoy-Gap",
56433
+ probe: "Envoy-Probe"
56331
56434
  };
56332
- function redialCures(error, options) {
56333
- if (error instanceof NatsDialBoundError)
56334
- return true;
56335
- const code = errorCode(error);
56336
- if (code === undefined)
56337
- return false;
56338
- if (AUTHORIZATION_REFUSALS[code] === true)
56339
- return options.ignoreAuthErrorAbort === true;
56340
- return NEVER_CURED[code] !== true && !code.startsWith("ERR_");
56341
- }
56342
- function errorCode(error) {
56343
- return error instanceof Error && "code" in error && typeof error.code === "string" ? error.code : undefined;
56435
+ var RELAY_PROGRESS_INTERVAL_MS = 20000;
56436
+ var FOLLOW_CLOCK_ALLOWANCE_MS = 2000;
56437
+ var RELAY_ATTEMPTS_BEFORE_FAILED = 3;
56438
+ var decoder3 = new TextDecoder;
56439
+ var DECIMAL = /^[0-9]+$/;
56440
+ var RFC3339 = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d+))?(Z|[+-]\d{2}:\d{2})$/;
56441
+ function positiveInteger(text) {
56442
+ if (text === null || text === undefined || !DECIMAL.test(text))
56443
+ return;
56444
+ const value = Number(text);
56445
+ return Number.isSafeInteger(value) && value > 0 ? value : undefined;
56344
56446
  }
56345
- function brokerDialRefusals(credential, random) {
56346
- if (credential?.kind !== "broker")
56447
+ function parseStoredAt(text) {
56448
+ const match = RFC3339.exec(text);
56449
+ if (match === null)
56347
56450
  return;
56348
- const { broker } = credential;
56349
- let refusals = 0;
56451
+ const fraction = (match[2] ?? "").padEnd(3, "0").slice(0, 3);
56452
+ const ms = Date.parse(`${match[1]}.${fraction}${match[3]}`);
56453
+ return Number.isNaN(ms) ? undefined : ms;
56454
+ }
56455
+ function decodeRelayFrame(message) {
56456
+ const reply = message.reply ?? "";
56457
+ if (reply === "")
56458
+ return { error: "no reply subject" };
56459
+ const headers = message.headers;
56460
+ if (headers === undefined)
56461
+ return { error: "no headers" };
56462
+ const subject = headers.get(RelayHeader.subject) ?? "";
56463
+ if (subject === "")
56464
+ return { error: `no ${RelayHeader.subject}` };
56465
+ const streamSeq = positiveInteger(headers.get(RelayHeader.streamSeq));
56466
+ if (streamSeq === undefined)
56467
+ return { error: `bad ${RelayHeader.streamSeq}` };
56468
+ const streamID = headers.get(RelayHeader.streamID) ?? "";
56469
+ if (streamID === "")
56470
+ return { error: `no ${RelayHeader.streamID}` };
56471
+ const delivered = positiveInteger(headers.get(RelayHeader.delivered));
56472
+ if (delivered === undefined)
56473
+ return { error: `bad ${RelayHeader.delivered}` };
56474
+ const storedAt = headers.get(RelayHeader.storedAt) ?? "";
56475
+ const storedAtMs = parseStoredAt(storedAt);
56476
+ if (storedAtMs === undefined)
56477
+ return { error: `bad ${RelayHeader.storedAt}` };
56350
56478
  return {
56351
- refused: (code) => {
56352
- if (code === undefined || AUTHORIZATION_REFUSALS[code] !== true)
56353
- return;
56354
- refusals += 1;
56355
- const dropped = broker.refused(code)?.dropped === true;
56356
- if (dropped)
56357
- broker.renew(AbortSignal.timeout(TRADE_DEADLINE_MS)).catch(() => {});
56358
- return { waitMs: brokerRedialWaitMs(refusals, random), dropped };
56359
- },
56360
- admitted: (dialedAt) => broker.admitted(dialedAt)
56479
+ frame: {
56480
+ subject,
56481
+ streamSeq,
56482
+ streamID,
56483
+ delivered,
56484
+ storedAt,
56485
+ storedAtMs,
56486
+ gap: headers.get(RelayHeader.gap) === "true",
56487
+ data: typeof message.data === "string" ? message.data : decoder3.decode(message.data),
56488
+ reply
56489
+ }
56361
56490
  };
56362
56491
  }
56363
- async function connectNats(connect, options, plan, hooks = {}) {
56364
- const started = performance.now();
56365
- const elapsed = () => performance.now() - started;
56366
- const timeout = options.timeout ?? NATS_DIAL_TIMEOUT_MS;
56367
- const servers = Array.isArray(options.servers) ? Math.max(1, options.servers.length) : 1;
56368
- const brokerRefusals = brokerDialRefusals(hooks.credential, hooks.random ?? Math.random);
56369
- const wait = hooks.delay ?? delay;
56370
- let delayMs = plan.firstDelayMs;
56371
- let failed;
56372
- for (let attempt = 1;; attempt += 1) {
56373
- if (hooks.stopped?.() === true) {
56374
- throw failed ?? new LoggableError("the NATS dial was stopped before it began");
56375
- }
56376
- const bound = Math.max(1, Math.round(Math.min(timeout, attempt === 1 ? hooks.firstBoundMs ?? timeout : plan.budgetMs - elapsed())));
56377
- const dialedAt = Date.now();
56378
- try {
56379
- const nc = await boundedDial(connect, {
56380
- ...options,
56381
- timeout: Math.min(bound, Math.max(NATS_MIN_REDIAL_BOUND_MS, Math.floor(bound / servers)))
56382
- }, bound);
56383
- keepWholeTimeout(nc, timeout);
56384
- brokerRefusals?.admitted(dialedAt);
56385
- return nc;
56386
- } catch (error) {
56387
- failed = error;
56388
- const refusal = brokerRefusals?.refused(errorCode(error));
56389
- if (refusal?.dropped === true)
56390
- hooks.onTokenDropped?.(error, attempt);
56391
- const waitMs = refusal?.waitMs ?? delayMs;
56392
- if (!redialCures(error, options) || elapsed() + waitMs + NATS_MIN_REDIAL_BOUND_MS > plan.budgetMs || hooks.stopped?.() === true) {
56393
- throw error;
56394
- }
56395
- hooks.onRetry?.(error, waitMs, attempt);
56396
- await wait(waitMs);
56397
- if (plan.budgetMs - elapsed() < NATS_MIN_REDIAL_BOUND_MS)
56398
- throw error;
56399
- if (refusal === undefined)
56400
- delayMs = Math.min(delayMs * 2, plan.maxDelayMs);
56401
- }
56402
- }
56492
+ function newEpoch() {
56493
+ return crypto.randomUUID();
56403
56494
  }
56404
- function keepWholeTimeout(nc, timeout) {
56405
- if (!(nc instanceof import_nats3.NatsConnectionImpl))
56495
+ var GAP_MESSAGES = {
56496
+ retention_gap: "The notification stream no longer holds some messages published to this session while it was away: messages older than 72 hours may be missing.",
56497
+ stream_recreated: "Envoy's notification stream was recreated, so messages published to this session before that may be lost."
56498
+ };
56499
+ var ConsumerDeliverySnapshotSchema = object({
56500
+ resume: object({ stream_id: string2().min(1), seq: number2().int().nonnegative() }).optional(),
56501
+ follows: record(string2(), number2()).default({})
56502
+ });
56503
+ function parseIdentity(data) {
56504
+ let parsed;
56505
+ try {
56506
+ parsed = JSON.parse(data);
56507
+ } catch {
56406
56508
  return;
56407
- const opened = nc.options;
56408
- opened.timeout = timeout;
56409
- delete opened.abandonSignal;
56509
+ }
56510
+ const identity = DedupeIdentitySchema.safeParse(parsed);
56511
+ if (!identity.success)
56512
+ return;
56513
+ const { event_id, dedupe_key } = identity.data;
56514
+ return event_id === undefined && dedupe_key === undefined ? undefined : identity.data;
56410
56515
  }
56411
- async function boundedDial(connect, options, boundMs) {
56412
- const abandon = new AbortController;
56413
- const withAbandon = {
56414
- ...options,
56415
- abandonSignal: abandon.signal
56516
+ function reaches(topic, forms) {
56517
+ const patterns = topicForms(topic).flatMap((form) => expandSubscriptionTopics([form]));
56518
+ return forms.some((form) => patterns.some((pattern) => subjectsOverlap(pattern, form)));
56519
+ }
56520
+ function every(ms, callback) {
56521
+ const timer = setInterval(callback, ms);
56522
+ return () => clearInterval(timer);
56523
+ }
56524
+ function createConsumerDelivery(options) {
56525
+ const { host, ledger, sessionID } = options;
56526
+ const render = options.render ?? renderInbound;
56527
+ const now = options.now ?? Date.now;
56528
+ const repeat = options.every ?? every;
56529
+ const ownSubject = legacyAgentSubject(sessionID);
56530
+ const ownsSubject = (subject) => topicForms(subject).includes(ownSubject);
56531
+ let currentEpoch = { id: newEpoch(), startedAt: now() };
56532
+ let follows = new Map;
56533
+ let streamID;
56534
+ let held = new Set;
56535
+ let written;
56536
+ let registeredResume;
56537
+ let gapTold = false;
56538
+ let closed = false;
56539
+ let persisted = JSON.stringify({ follows: {} });
56540
+ const entries = new Map;
56541
+ const troubled = new Map;
56542
+ const queue = [];
56543
+ let blocking;
56544
+ let pumping = false;
56545
+ const safely = (what, call) => {
56546
+ try {
56547
+ call();
56548
+ } catch (error) {
56549
+ try {
56550
+ host.log(`consumer delivery: ${what} failed`, error);
56551
+ } catch {}
56552
+ }
56416
56553
  };
56417
- const dialing = connect(withAbandon);
56418
- const expired = Promise.withResolvers();
56419
- const timer = setTimeout(() => {
56420
- abandon.abort();
56421
- expired.reject(new NatsDialBoundError(`the NATS dial did not complete within ${boundMs} ms`));
56422
- }, boundMs);
56423
- try {
56424
- return await Promise.race([dialing, expired.promise]);
56425
- } catch (error) {
56426
- dialing.then((late) => late.close()).catch(() => {
56554
+ const log = (message, error) => safely("log", () => host.log(`consumer delivery: ${message}`, error));
56555
+ const send = (reply, body) => safely(`reply ${body}`, () => options.publish(reply, body));
56556
+ const tellGap = (kind) => safely("gap notice", () => host.gap({ kind, message: GAP_MESSAGES[kind] }));
56557
+ const switchStream = (id) => {
56558
+ if (streamID === id)
56427
56559
  return;
56428
- });
56429
- throw error;
56430
- } finally {
56431
- clearTimeout(timer);
56432
- }
56433
- }
56434
-
56435
- // src/channel-connection.ts
56436
- var import_nats4 = __toESM(require_mod4(), 1);
56437
- var START_STOPPING = "the channel server stopped before its NATS subscriptions reached the server";
56438
- function sessionAdmission(first) {
56439
- let current = first;
56440
- let pending;
56441
- return {
56442
- admit: (session) => {
56443
- current = session;
56444
- if (pending?.session !== session)
56445
- return;
56446
- pending.wait.resolve();
56447
- pending = undefined;
56448
- },
56449
- admitted: (session) => {
56450
- if (session === current)
56451
- return Promise.resolve();
56452
- if (pending?.session !== session) {
56453
- pending = { session, wait: Promise.withResolvers() };
56454
- }
56455
- return pending.wait.promise;
56560
+ streamID = id;
56561
+ held = new Set;
56562
+ written = undefined;
56563
+ troubled.clear();
56564
+ };
56565
+ const tellReplacedResume = (id) => {
56566
+ const asked = resumePoint() ?? registeredResume;
56567
+ if (asked === undefined || asked.stream_id === id)
56568
+ return;
56569
+ registeredResume = undefined;
56570
+ tellGap("stream_recreated");
56571
+ };
56572
+ const followedAt = (subject) => {
56573
+ if (ownsSubject(subject))
56574
+ return Number.NEGATIVE_INFINITY;
56575
+ const forms = topicForms(subject);
56576
+ let earliest;
56577
+ for (const [topic, at] of follows) {
56578
+ if (!reaches(topic, forms))
56579
+ continue;
56580
+ if (earliest === undefined || at < earliest)
56581
+ earliest = at;
56456
56582
  }
56583
+ return earliest;
56457
56584
  };
56458
- }
56459
- function admittingMoves(admission, identity) {
56460
- return (follow) => follow === undefined || admission === undefined ? undefined : async () => {
56461
- const forSession = identity.id;
56462
- await follow();
56463
- admission.admit(forSession);
56585
+ const settle = (entry, body) => {
56586
+ if (entry.settled)
56587
+ return;
56588
+ entry.settled = true;
56589
+ entry.stopProgress();
56590
+ entries.delete(entry.key);
56591
+ for (const reply of entry.replies)
56592
+ send(reply, body);
56593
+ if (body === "done")
56594
+ troubled.delete(entry.key);
56595
+ if (body === "done" && entry.frame.streamID === streamID) {
56596
+ held.delete(entry.frame.streamSeq);
56597
+ written = Math.max(written ?? 0, entry.frame.streamSeq);
56598
+ }
56599
+ release(entry);
56464
56600
  };
56465
- }
56466
- var CREDENTIAL_NAMES = {
56467
- broker: "the session's broker token",
56468
- seed: "an nkey seed",
56469
- none: "no credential"
56470
- };
56471
- var CHANNEL_DIAL_PLAN = {
56472
- ...NATS_DIAL_PLAN,
56473
- budgetMs: Number.POSITIVE_INFINITY
56474
- };
56475
- async function dialChannelNats(inbound, name, warn, dial = import_nats4.connect, signal, plan = CHANNEL_DIAL_PLAN, waits = {}) {
56476
- const stopped = Promise.withResolvers();
56477
- const onAbort = () => stopped.resolve("stopping");
56478
- if (signal?.aborted === true)
56479
- onAbort();
56480
- signal?.addEventListener("abort", onAbort);
56481
- const unlessStopped = async (waited) => {
56482
- const outcome = await Promise.race([
56483
- waited.then((value) => ({ value }), (error) => ({ error })),
56484
- stopped.promise
56485
- ]);
56486
- if (outcome === "stopping")
56487
- throw new Error(START_STOPPING);
56488
- if ("error" in outcome)
56489
- throw outcome.error;
56490
- return outcome.value;
56601
+ const release = (entry) => {
56602
+ if (blocking !== entry)
56603
+ return;
56604
+ blocking = undefined;
56605
+ pump();
56491
56606
  };
56492
- try {
56493
- const { natsCredential } = inbound;
56494
- const failed = (error) => natsDialFailure(natsServersForLog(inbound.natsServersSetting, inbound.natsUrls.length), error, CREDENTIAL_NAMES[natsCredential.kind]);
56495
- const broker = natsCredential.kind === "broker" ? natsCredential.broker : undefined;
56496
- await unlessStopped(broker?.ready({ life: signal ?? new AbortController().signal }) ?? Promise.resolve());
56497
- const dialing = connectNats(dial, natsConnectionOptions({ servers: inbound.natsUrls, name, credential: natsCredential }), plan, {
56498
- ...waits,
56499
- stopped: () => signal?.aborted === true,
56500
- credential: natsCredential,
56501
- onTokenDropped: (error, attempt) => warn(`${NATS_DIAL_TOKEN_DROPPED} (dial ${attempt})`, error),
56502
- onRetry: (error, delayMs) => warn(`${failed(error)}; dialing again in ${delayMs} ms`, error)
56503
- });
56504
- let connection;
56505
- try {
56506
- connection = await unlessStopped(dialing);
56507
- } catch (error) {
56508
- if (signal?.aborted === true) {
56509
- dialing.then((late) => late.close()).catch(() => {
56510
- return;
56511
- });
56512
- throw new Error(START_STOPPING);
56513
- }
56514
- throw new LoggableError(failed(error));
56607
+ const alreadyWritten = (identity) => identity !== undefined && ledger.delivered(identity);
56608
+ const failed = (entry, error) => {
56609
+ if (entry.settled)
56610
+ return;
56611
+ const trouble = troubled.get(entry.key) ?? { failures: 0, givenUp: false };
56612
+ troubled.set(entry.key, trouble);
56613
+ if (trouble.givenUp) {
56614
+ settle(entry, "nak");
56615
+ return;
56515
56616
  }
56516
- if (broker === undefined)
56517
- return { connection, stop: () => {} };
56518
- return {
56519
- connection,
56520
- stop: keepNatsCredential(connection, broker, warn),
56521
- followSession: () => followNatsCredential(connection, broker)
56522
- };
56523
- } finally {
56524
- signal?.removeEventListener("abort", onAbort);
56525
- }
56526
- }
56527
- var START_DRAIN_BOUND_MS = 2000;
56528
- async function closeUnstartedConnection(connection) {
56529
- await Promise.race([connection.drain().catch(() => {
56530
- return;
56531
- }), Bun.sleep(START_DRAIN_BOUND_MS)]);
56532
- await connection.close().catch(() => {
56533
- return;
56534
- });
56535
- }
56536
- function channelReopener(options) {
56537
- return async (failed) => {
56538
- options.swapKeeper(() => {
56617
+ trouble.failures += 1;
56618
+ if (trouble.failures < RELAY_ATTEMPTS_BEFORE_FAILED) {
56619
+ log(`frame ${entry.frame.streamSeq} failed; it comes again`, error);
56620
+ settle(entry, "nak");
56539
56621
  return;
56540
- });
56541
- const next = await dialChannelNats(options.inbound, options.name, (text, dialError) => {
56542
- process.stderr.write(`envoy-channel: ${text}
56543
- `);
56544
- if (dialError !== undefined)
56545
- failed(dialError);
56546
- }, import_nats4.connect, options.signal);
56547
- if (options.signal.aborted) {
56548
- next.stop();
56549
- next.connection.close().catch(() => {
56550
- return;
56551
- });
56552
- throw new Error(START_STOPPING);
56553
56622
  }
56554
- options.swapKeeper(next.stop);
56555
- options.useConnection(next.connection);
56556
- const followSession = options.admitting(next.followSession);
56557
- return {
56558
- connection: next.connection,
56559
- ...followSession === undefined ? {} : { followSession }
56623
+ log(`frame ${entry.frame.streamSeq} failed and does not come again; its session gets the notice`, error);
56624
+ const goesBack = (why, thrown) => {
56625
+ trouble.givenUp = true;
56626
+ log(`frame ${entry.frame.streamSeq} ${why}; it goes back to the stream`, thrown);
56627
+ settle(entry, "nak");
56560
56628
  };
56629
+ let envelope;
56630
+ try {
56631
+ envelope = render(entry.frame.data, sessionID, entry.frame.subject).envelope;
56632
+ } catch (thrown) {
56633
+ goesBack("could not be read to report it", thrown);
56634
+ return;
56635
+ }
56636
+ if (envelope === undefined) {
56637
+ log(`frame ${entry.frame.streamSeq} carries no envelope to report; it is dropped`);
56638
+ settle(entry, "done");
56639
+ return;
56640
+ }
56641
+ let telling;
56642
+ try {
56643
+ telling = ledger.liveFailed(sessionID, envelope, error);
56644
+ } catch (thrown) {
56645
+ goesBack("could not be reported", thrown);
56646
+ return;
56647
+ }
56648
+ telling.then((told) => {
56649
+ if (told) {
56650
+ settle(entry, "done");
56651
+ return;
56652
+ }
56653
+ goesBack("was reported to nobody");
56654
+ }, (thrown) => {
56655
+ goesBack("could not be reported", thrown);
56656
+ });
56561
56657
  };
56562
- }
56563
-
56564
- // src/claude-session.ts
56565
- function configuredValue(value) {
56566
- return value !== undefined && value.trim().length > 0 ? value : undefined;
56567
- }
56568
- function configuredSessionId(environment) {
56569
- return configuredValue(environment.ENVOY_SESSION_ID) ?? configuredValue(environment.CLAUDE_CODE_SESSION_ID);
56570
- }
56571
- function claudeSessionId(environment) {
56572
- const id = configuredSessionId(environment);
56573
- if (id !== undefined)
56574
- return id;
56575
- throw new Error("Envoy channel requires ENVOY_SESSION_ID or CLAUDE_CODE_SESSION_ID; Claude Code did not provide a session identity");
56576
- }
56577
- function claudeProjectDirectory(environment, fallback) {
56578
- return configuredValue(environment.CLAUDE_PROJECT_DIR) ?? fallback;
56579
- }
56580
-
56581
- // src/envoy-channel-server.ts
56582
- import { unwatchFile, watchFile } from "fs";
56583
- import { rm as rm2 } from "fs/promises";
56584
- import { setImmediate as nextTurn } from "timers/promises";
56585
-
56586
- // ../envoy-client/src/delivery-ledger.ts
56587
- var DELIVERY_LEDGER_TTL_MS = DELIVERY_DUPLICATE_WINDOW_MS;
56588
- var DELIVERY_LEDGER_LIMIT = 20000;
56589
- var LedgerEntrySchema = object({
56590
- event_id: string2().min(1).optional(),
56591
- dedupe_key: string2().min(1).optional(),
56592
- at: number2()
56593
- });
56594
- var LedgerStateSchema = object({
56595
- topics: array(string2()).default([])
56596
- });
56597
- var LedgerSnapshotSchema = object({
56598
- state: LedgerStateSchema.optional(),
56599
- ledger: array(LedgerEntrySchema)
56600
- });
56601
- function createDeliveryLedger(options) {
56602
- const { host } = options;
56603
- const now = options.now ?? Date.now;
56604
- const ledger = createLedger(now);
56605
- let topics = [];
56606
- let unwritten = [];
56607
- let writtenState;
56608
- let writes = Promise.resolve();
56609
- let epoch = 0;
56610
- const safely = (what, call) => {
56658
+ const handOff = (entry) => {
56659
+ const handle = {
56660
+ ...entry.frame,
56661
+ late: entry.late,
56662
+ done: () => settle(entry, "done"),
56663
+ nak: () => settle(entry, "nak"),
56664
+ release: () => release(entry)
56665
+ };
56666
+ blocking = entry;
56667
+ let result;
56611
56668
  try {
56612
- call();
56669
+ result = host.deliver(handle);
56613
56670
  } catch (error) {
56614
- try {
56615
- host.log(`delivery ledger: ${what} failed`, error);
56616
- } catch {}
56671
+ failed(entry, error);
56672
+ release(entry);
56673
+ return;
56617
56674
  }
56675
+ if (!(result instanceof Promise)) {
56676
+ release(entry);
56677
+ return;
56678
+ }
56679
+ result.then(() => release(entry), (error) => {
56680
+ failed(entry, error);
56681
+ release(entry);
56682
+ });
56618
56683
  };
56619
- const log = (message, error) => safely("log", () => host.log(message, error));
56620
- const sessionRead = (read) => () => {
56684
+ function pump() {
56685
+ if (pumping)
56686
+ return;
56687
+ pumping = true;
56621
56688
  try {
56622
- return read();
56623
- } catch {
56689
+ while (blocking === undefined && !closed) {
56690
+ const entry = queue.shift();
56691
+ if (entry === undefined)
56692
+ return;
56693
+ if (entry.settled)
56694
+ continue;
56695
+ if (alreadyWritten(entry.identity)) {
56696
+ settle(entry, "done");
56697
+ continue;
56698
+ }
56699
+ handOff(entry);
56700
+ }
56701
+ } finally {
56702
+ pumping = false;
56703
+ }
56704
+ }
56705
+ const receive = (message) => {
56706
+ if (message.headers?.get(RelayHeader.probe) === "1") {
56707
+ if (message.reply !== undefined && message.reply !== "")
56708
+ send(message.reply, "done");
56709
+ return;
56710
+ }
56711
+ const decoded = decodeRelayFrame(message);
56712
+ if ("error" in decoded) {
56713
+ log(`dropping an undecodable relay frame: ${decoded.error}`);
56714
+ if (message.reply !== undefined && message.reply !== "")
56715
+ send(message.reply, "done");
56716
+ return;
56717
+ }
56718
+ const { frame } = decoded;
56719
+ if (closed) {
56720
+ send(frame.reply, "nak");
56721
+ return;
56722
+ }
56723
+ send(frame.reply, "received");
56724
+ if (frame.gap && !gapTold)
56725
+ tellGap("retention_gap");
56726
+ gapTold = false;
56727
+ if (frame.streamID !== streamID) {
56728
+ if (streamID !== undefined && (written !== undefined || held.size > 0)) {
56729
+ tellGap("stream_recreated");
56730
+ } else if (streamID === undefined) {
56731
+ tellReplacedResume(frame.streamID);
56732
+ }
56733
+ switchStream(frame.streamID);
56734
+ }
56735
+ const key = `${frame.streamID}:${frame.streamSeq}`;
56736
+ const first = entries.get(key);
56737
+ if (first !== undefined) {
56738
+ first.replies.push(frame.reply);
56739
+ return;
56740
+ }
56741
+ const since = followedAt(frame.subject);
56742
+ const unfollowed = since === undefined || frame.storedAtMs < since - FOLLOW_CLOCK_ALLOWANCE_MS;
56743
+ const identity = unfollowed ? undefined : parseIdentity(frame.data);
56744
+ if (unfollowed || alreadyWritten(identity)) {
56745
+ send(frame.reply, "done");
56746
+ written = Math.max(written ?? 0, frame.streamSeq);
56624
56747
  return;
56625
56748
  }
56749
+ held.add(frame.streamSeq);
56750
+ const entry = {
56751
+ frame,
56752
+ identity,
56753
+ late: frame.delivered > 1 || frame.storedAtMs < currentEpoch.startedAt,
56754
+ replies: [frame.reply],
56755
+ key,
56756
+ stopProgress: () => {
56757
+ return;
56758
+ },
56759
+ settled: false
56760
+ };
56761
+ entry.stopProgress = repeat(RELAY_PROGRESS_INTERVAL_MS, () => {
56762
+ if (entry.settled)
56763
+ return;
56764
+ for (const reply of entry.replies)
56765
+ send(reply, "progress");
56766
+ });
56767
+ entries.set(key, entry);
56768
+ queue.push(entry);
56769
+ pump();
56626
56770
  };
56627
- const currentSession = sessionRead(() => host.sessionID());
56628
- const writeSession = sessionRead(() => host.writeSessionID === undefined ? host.sessionID() : host.writeSessionID());
56629
- const bindTo = (sessionID, read) => {
56630
- if (sessionID === undefined || sessionID === "" || read() !== sessionID)
56771
+ const resumePoint = () => {
56772
+ if (streamID === undefined)
56631
56773
  return;
56632
- const bound = epoch;
56633
- return { sessionID, alive: () => bound === epoch && read() === sessionID };
56774
+ if (held.size > 0)
56775
+ return { stream_id: streamID, seq: Math.min(...held) - 1 };
56776
+ return written === undefined ? undefined : { stream_id: streamID, seq: written };
56634
56777
  };
56635
- const bind = () => bindTo(currentSession(), currentSession);
56636
- const stateJSON = () => JSON.stringify({ topics: [...topics].sort() });
56637
- const record = (identity) => {
56638
- const entry = ledger.record(identity);
56639
- if (entry !== undefined)
56640
- unwritten.push(entry);
56778
+ const snapshot = () => {
56779
+ const resume = resumePoint();
56780
+ return {
56781
+ ...resume === undefined ? {} : { resume },
56782
+ follows: Object.fromEntries(follows)
56783
+ };
56641
56784
  };
56642
- const flush = (alive) => {
56643
- const written = writes.then(async () => {
56644
- if (!alive())
56645
- return false;
56646
- const json = stateJSON();
56647
- const delivered = unwritten;
56648
- if (json === writtenState && delivered.length === 0)
56649
- return true;
56650
- unwritten = [];
56651
- const state = json === writtenState ? undefined : JSON.parse(json);
56652
- try {
56653
- await host.write({
56654
- delivered,
56655
- state,
56656
- snapshot: () => ({ state: JSON.parse(json), ledger: ledger.list() })
56657
- });
56658
- if (state !== undefined)
56659
- writtenState = json;
56660
- return true;
56661
- } catch (error) {
56662
- unwritten = [...delivered, ...unwritten];
56663
- log("delivery ledger: could not persist the state; the next write carries it", error);
56664
- return false;
56665
- }
56666
- });
56667
- writes = written.then(() => {
56785
+ const persist = () => {
56786
+ const current = snapshot();
56787
+ const serialized = JSON.stringify(current);
56788
+ if (serialized === persisted)
56668
56789
  return;
56669
- });
56670
- return written;
56671
- };
56672
- const syncFollowed = () => {
56673
- topics = [...new Set(host.followedSubjects())];
56674
- };
56675
- const failureNotice = (envelope, error) => ({
56676
- eventId: envelope.event_id ?? "unknown",
56677
- sender: senderLabel(envelope),
56678
- summary: envelope.payload_summary ?? "unknown",
56679
- publishedAt: inboundTimestamp(envelope.issued_at),
56680
- error,
56681
- readWith: envelope.source === "dispatch" ? "dispatch read" : "envoy_inbox",
56682
- envelope
56683
- });
56684
- const showFailureNotice = async (sessionID, notice, alive) => {
56685
- let queued;
56686
- try {
56687
- queued = await host.showFailureNotice(sessionID, notice) === "queued";
56688
- } catch (error) {
56689
- if (alive())
56690
- safely("failure notice warning", () => host.failureNoticeFailed(notice, error));
56691
- return false;
56692
- }
56693
- if (queued || !alive())
56694
- return true;
56695
- record(ledgerIdentity(notice.envelope));
56696
- await flush(alive);
56697
- return true;
56790
+ if (!options.persist(current))
56791
+ return;
56792
+ persisted = serialized;
56698
56793
  };
56699
56794
  return {
56700
- async followedChanged() {
56701
- const alive = bind()?.alive;
56702
- if (alive === undefined)
56703
- return;
56704
- try {
56705
- syncFollowed();
56706
- await flush(alive);
56707
- } catch (error) {
56708
- log("delivery ledger: could not take the followed subjects", error);
56709
- }
56710
- },
56711
- delivered: (frame) => ledger.has(ledgerIdentity(frame)),
56712
- async recordDelivered(frame) {
56713
- const alive = bind()?.alive;
56714
- if (alive === undefined)
56715
- return;
56716
- record(ledgerIdentity(frame));
56717
- await flush(alive);
56795
+ subject: deliverSubject(sessionID),
56796
+ receive,
56797
+ epoch: () => currentEpoch,
56798
+ beginEpoch() {
56799
+ currentEpoch = { id: newEpoch(), startedAt: now() };
56800
+ return currentEpoch;
56718
56801
  },
56719
- async recordDeliveredFor(sessionID, frame) {
56720
- const alive = bindTo(sessionID, writeSession)?.alive;
56721
- if (alive === undefined)
56722
- return false;
56723
- record(ledgerIdentity(frame));
56724
- return await flush(alive);
56802
+ registration() {
56803
+ const resume = resumePoint();
56804
+ registeredResume = resume;
56805
+ return {
56806
+ consumer: true,
56807
+ epoch: currentEpoch.id,
56808
+ ...resume === undefined ? {} : { resume }
56809
+ };
56725
56810
  },
56726
- async liveFailed(sessionID, envelope, error) {
56727
- const alive = bindTo(sessionID, currentSession)?.alive;
56728
- if (alive === undefined) {
56729
- log("delivery ledger: a failed frame was not reported here; the session it names is closed");
56730
- return false;
56811
+ answered(answer) {
56812
+ if (answer.stream_id !== "" && answer.stream_id !== streamID) {
56813
+ tellReplacedResume(answer.stream_id);
56814
+ switchStream(answer.stream_id);
56731
56815
  }
56732
- try {
56733
- return await showFailureNotice(sessionID, failureNotice(envelope, messageFor(error)), alive);
56734
- } catch (thrown) {
56735
- log("delivery ledger: could not report a frame the session was not shown", thrown);
56736
- return false;
56816
+ const floor = (answer.consumer_start ?? 0) - 1;
56817
+ if (answer.stream_id === streamID && floor > (written ?? -1))
56818
+ written = floor;
56819
+ if (answer.gap) {
56820
+ tellGap("retention_gap");
56821
+ gapTold = true;
56737
56822
  }
56823
+ persist();
56738
56824
  },
56739
- restore(snapshot) {
56740
- epoch += 1;
56741
- ledger.restore(snapshot.ledger);
56742
- topics = [...new Set(snapshot.state?.topics ?? [])];
56743
- writtenState = snapshot.state === undefined ? undefined : stateJSON();
56744
- unwritten = [];
56745
- }
56746
- };
56747
- }
56748
- function failureNoticeFields(notice) {
56749
- 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.";
56750
- return {
56751
- notice: "message not shown",
56752
- event_id: notice.eventId,
56753
- from: notice.sender,
56754
- summary: notice.summary,
56755
- published_at: notice.publishedAt,
56756
- error: notice.error,
56757
- detail: `This session could not be shown this message, so it is not coming back on its own. ${readWith}`
56758
- };
56759
- }
56760
- function envoyNoticeText(fields) {
56761
- return encode3({ envoy: fields });
56762
- }
56763
- async function closeReplayedRemoval(frame, host) {
56764
- const closed = (subscriptionRemovedTopics(frame.data, host.sessionID) ?? []).filter((topic) => host.relay?.followedBefore(topic, frame.storedAtMs) !== false && host.close(topic));
56765
- if (closed.length === 0)
56766
- return closed;
56767
- const unregistering = host.unregister(closed);
56768
- await host.followedChanged();
56769
- await unregistering;
56770
- return closed;
56771
- }
56772
- function ledgerIdentity(frame) {
56773
- return {
56774
- ...frame.event_id === undefined || frame.event_id === "" ? {} : { event_id: frame.event_id },
56775
- ...frame.dedupe_key === undefined || !dedupeKeyNamesItsEvent(frame) ? {} : { dedupe_key: frame.dedupe_key }
56776
- };
56777
- }
56778
- function createLedger(now) {
56779
- let entries = new Set;
56780
- const byEvent = new Map;
56781
- const byKey = new Map;
56782
- const drop = (entry) => {
56783
- entries.delete(entry);
56784
- if (entry.event_id !== undefined && byEvent.get(entry.event_id) === entry) {
56785
- byEvent.delete(entry.event_id);
56786
- }
56787
- if (entry.dedupe_key !== undefined && byKey.get(entry.dedupe_key) === entry) {
56788
- byKey.delete(entry.dedupe_key);
56789
- }
56790
- };
56791
- const add = (entry) => {
56792
- if (entries.size >= DELIVERY_LEDGER_LIMIT) {
56793
- const oldest = entries.values().next();
56794
- if (oldest.done !== true)
56795
- drop(oldest.value);
56796
- }
56797
- entries.add(entry);
56798
- if (entry.event_id !== undefined)
56799
- byEvent.set(entry.event_id, entry);
56800
- if (entry.dedupe_key !== undefined)
56801
- byKey.set(entry.dedupe_key, entry);
56802
- };
56803
- const expire = () => {
56804
- const at = now();
56805
- for (const entry of entries) {
56806
- if (at - entry.at < DELIVERY_LEDGER_TTL_MS)
56807
- break;
56808
- drop(entry);
56825
+ followedBefore(topic, storedAtMs) {
56826
+ const at = follows.get(topic);
56827
+ return at !== undefined && storedAtMs >= at - FOLLOW_CLOCK_ALLOWANCE_MS;
56828
+ },
56829
+ setFollowed(topics) {
56830
+ const at = now();
56831
+ const next = new Map;
56832
+ for (const topic of topics) {
56833
+ if (ownsSubject(topic))
56834
+ continue;
56835
+ next.set(topic, follows.get(topic) ?? at);
56836
+ }
56837
+ follows = next;
56838
+ persist();
56839
+ },
56840
+ unfollow(topics) {
56841
+ for (const topic of topics)
56842
+ follows.delete(topic);
56843
+ persist();
56844
+ },
56845
+ persist,
56846
+ resumePoint,
56847
+ snapshot,
56848
+ restore(restored) {
56849
+ const merged = new Map(Object.entries(restored.follows));
56850
+ for (const [topic, at] of follows)
56851
+ if (!merged.has(topic))
56852
+ merged.set(topic, at);
56853
+ follows = merged;
56854
+ streamID = restored.resume?.stream_id;
56855
+ held = new Set;
56856
+ written = restored.resume?.seq;
56857
+ persisted = JSON.stringify(snapshot());
56858
+ },
56859
+ close() {
56860
+ closed = true;
56861
+ queue.length = 0;
56862
+ for (const entry of [...entries.values()])
56863
+ settle(entry, "nak");
56864
+ blocking = undefined;
56809
56865
  }
56810
56866
  };
56811
- const has = (identity) => {
56812
- expire();
56813
- return identity.event_id !== undefined && byEvent.has(identity.event_id) || identity.dedupe_key !== undefined && byKey.has(identity.dedupe_key);
56814
- };
56867
+ }
56868
+ var GAP_NOTICE_NAMES = {
56869
+ retention_gap: "messages may be missing",
56870
+ stream_recreated: "stream recreated"
56871
+ };
56872
+ function gapNoticeFields(notice) {
56873
+ return { notice: GAP_NOTICE_NAMES[notice.kind], detail: notice.message };
56874
+ }
56875
+ function gapNoticeText(notice) {
56876
+ return envoyNoticeText(gapNoticeFields(notice));
56877
+ }
56878
+ function inboundUnavailableNoticeText(why) {
56879
+ return envoyNoticeText({
56880
+ notice: "Envoy inbound unavailable",
56881
+ error: why,
56882
+ 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."
56883
+ });
56884
+ }
56885
+ function inboundRestoredNoticeText() {
56886
+ return envoyNoticeText({
56887
+ notice: "Envoy inbound restored",
56888
+ detail: "The listener accepted this session's registration and gave it its durable consumer, so Envoy messages reach it again, the ones the stream stored during the outage first."
56889
+ });
56890
+ }
56891
+ function inboundUnavailable(tell, restored) {
56892
+ let told = false;
56815
56893
  return {
56816
- has,
56817
- record(identity) {
56818
- if (identity.event_id === undefined && identity.dedupe_key === undefined)
56819
- return;
56820
- if (has(identity))
56894
+ refused(error) {
56895
+ if (told)
56821
56896
  return;
56822
- const entry = { ...identity, at: now() };
56823
- add(entry);
56824
- return entry;
56825
- },
56826
- restore(restored) {
56827
- entries = new Set;
56828
- byEvent.clear();
56829
- byKey.clear();
56830
- const at = now();
56831
- 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);
56832
- for (const entry of kept)
56833
- add({ ...entry });
56897
+ told = true;
56898
+ tell(messageFor(error));
56834
56899
  },
56835
- list() {
56836
- expire();
56837
- return [...entries];
56900
+ accepted() {
56901
+ if (!told)
56902
+ return;
56903
+ told = false;
56904
+ restored();
56838
56905
  }
56839
56906
  };
56840
56907
  }
56841
56908
 
56842
- // ../envoy-client/src/consumer-delivery.ts
56843
- var DELIVER_SUBJECT_PREFIX = "notifications.envoy.deliver.";
56844
- function deliverSubject(sessionID) {
56845
- return `${DELIVER_SUBJECT_PREFIX}${sessionID}`;
56909
+ // ../envoy-client/src/nats-connection.ts
56910
+ var import_nats2 = __toESM(require_mod4(), 1);
56911
+ var import_nats3 = __toESM(require_nats(), 1);
56912
+ var import_servers = __toESM(require_servers(), 1);
56913
+ import { setTimeout as delay } from "timers/promises";
56914
+
56915
+ // ../envoy-client/src/nats-auth.ts
56916
+ var import_nats = __toESM(require_mod4(), 1);
56917
+ var seedKeys = import_nats.nkeys;
56918
+ function natsAuthOptions(credential) {
56919
+ switch (credential.kind) {
56920
+ case "none":
56921
+ return {};
56922
+ case "broker":
56923
+ return { authenticator: credential.broker.authenticator };
56924
+ case "seed": {
56925
+ const { seed } = credential;
56926
+ const bytes = new TextEncoder().encode(seed.value);
56927
+ let publicKey;
56928
+ try {
56929
+ publicKey = seedKeys.fromSeed(bytes).getPublicKey();
56930
+ } catch (error) {
56931
+ throw new Error(`${seed.source} does not hold a valid nkey seed: ${messageFor(error)}`);
56932
+ }
56933
+ if (!publicKey.startsWith("U")) {
56934
+ throw new Error(`${seed.source} holds an nkey seed that is not a user's (public key ${publicKey})`);
56935
+ }
56936
+ return { authenticator: import_nats.nkeyAuthenticator(bytes) };
56937
+ }
56938
+ }
56846
56939
  }
56847
- var RelayHeader = {
56848
- subject: "Envoy-Subject",
56849
- streamSeq: "Envoy-Stream-Seq",
56850
- streamID: "Envoy-Stream-Id",
56851
- delivered: "Envoy-Delivered",
56852
- storedAt: "Envoy-Stored-At",
56853
- gap: "Envoy-Gap",
56854
- probe: "Envoy-Probe"
56855
- };
56856
- var RELAY_PROGRESS_INTERVAL_MS = 20000;
56857
- var FOLLOW_CLOCK_ALLOWANCE_MS = 2000;
56858
- var RELAY_ATTEMPTS_BEFORE_FAILED = 3;
56859
- var decoder3 = new TextDecoder;
56860
- var DECIMAL = /^[0-9]+$/;
56861
- var RFC3339 = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d+))?(Z|[+-]\d{2}:\d{2})$/;
56862
- function positiveInteger(text) {
56863
- if (text === null || text === undefined || !DECIMAL.test(text))
56864
- return;
56865
- const value = Number(text);
56866
- return Number.isSafeInteger(value) && value > 0 ? value : undefined;
56940
+
56941
+ // ../envoy-client/src/nats-connection.ts
56942
+ var NATS_PING_INTERVAL_MS = 1e4;
56943
+ var NATS_MAX_PINGS_OUT = 2;
56944
+ var NATS_DIAL_TIMEOUT_MS = 1e4;
56945
+ function natsConnectionOptions(input) {
56946
+ return {
56947
+ servers: [...input.servers],
56948
+ name: input.name,
56949
+ ...natsAuthOptions(input.credential),
56950
+ timeout: NATS_DIAL_TIMEOUT_MS,
56951
+ reconnect: true,
56952
+ maxReconnectAttempts: -1,
56953
+ pingInterval: NATS_PING_INTERVAL_MS,
56954
+ maxPingOut: NATS_MAX_PINGS_OUT,
56955
+ ...input.credential.kind === "broker" ? {
56956
+ ignoreAuthErrorAbort: true,
56957
+ reconnectDelayHandler: brokerRedialDelays(input.credential.broker)
56958
+ } : { reconnectTimeWait: 2000 }
56959
+ };
56867
56960
  }
56868
- function parseStoredAt(text) {
56869
- const match = RFC3339.exec(text);
56870
- if (match === null)
56871
- return;
56872
- const fraction = (match[2] ?? "").padEnd(3, "0").slice(0, 3);
56873
- const ms = Date.parse(`${match[1]}.${fraction}${match[3]}`);
56874
- return Number.isNaN(ms) ? undefined : ms;
56961
+ var BROKER_REDIAL_FIRST_MS = 4000;
56962
+ var BROKER_REDIAL_CAP_MS = 20000;
56963
+ var BROKER_REDIAL_OUTAGE_GAP_MS = 60000;
56964
+ var BROKER_REDIAL_POLL_MS = 1000;
56965
+ var DUE_SLACK_MS = 50;
56966
+ function brokerRedialWaitBounds(wait) {
56967
+ const highestMs = Math.min(BROKER_REDIAL_CAP_MS, BROKER_REDIAL_FIRST_MS * 2 ** Math.min(wait - 1, 30));
56968
+ return { lowestMs: highestMs / 2, highestMs };
56875
56969
  }
56876
- function decodeRelayFrame(message) {
56877
- const reply = message.reply ?? "";
56878
- if (reply === "")
56879
- return { error: "no reply subject" };
56880
- const headers = message.headers;
56881
- if (headers === undefined)
56882
- return { error: "no headers" };
56883
- const subject = headers.get(RelayHeader.subject) ?? "";
56884
- if (subject === "")
56885
- return { error: `no ${RelayHeader.subject}` };
56886
- const streamSeq = positiveInteger(headers.get(RelayHeader.streamSeq));
56887
- if (streamSeq === undefined)
56888
- return { error: `bad ${RelayHeader.streamSeq}` };
56889
- const streamID = headers.get(RelayHeader.streamID) ?? "";
56890
- if (streamID === "")
56891
- return { error: `no ${RelayHeader.streamID}` };
56892
- const delivered = positiveInteger(headers.get(RelayHeader.delivered));
56893
- if (delivered === undefined)
56894
- return { error: `bad ${RelayHeader.delivered}` };
56895
- const storedAt = headers.get(RelayHeader.storedAt) ?? "";
56896
- const storedAtMs = parseStoredAt(storedAt);
56897
- if (storedAtMs === undefined)
56898
- return { error: `bad ${RelayHeader.storedAt}` };
56899
- return {
56900
- frame: {
56901
- subject,
56902
- streamSeq,
56903
- streamID,
56904
- delivered,
56905
- storedAt,
56906
- storedAtMs,
56907
- gap: headers.get(RelayHeader.gap) === "true",
56908
- data: typeof message.data === "string" ? message.data : decoder3.decode(message.data),
56909
- reply
56970
+ function brokerRedialWaitMs(wait, random) {
56971
+ const { lowestMs, highestMs } = brokerRedialWaitBounds(wait);
56972
+ return Math.round(lowestMs + random() * (highestMs - lowestMs));
56973
+ }
56974
+ function brokerRedialDelays(credential, random = Math.random, now = Date.now, pollMs = BROKER_REDIAL_POLL_MS) {
56975
+ let lastCall = Number.NEGATIVE_INFINITY;
56976
+ let dialedAt = 0;
56977
+ let dueAt = Number.NEGATIVE_INFINITY;
56978
+ let waits = 0;
56979
+ let rushed;
56980
+ let dialedSession;
56981
+ let rushedInWait = false;
56982
+ let admissions = credential.admissions().count;
56983
+ return () => {
56984
+ const at = now();
56985
+ if (at - lastCall > BROKER_REDIAL_OUTAGE_GAP_MS) {
56986
+ dueAt = Number.NEGATIVE_INFINITY;
56987
+ waits = 0;
56910
56988
  }
56989
+ lastCall = at;
56990
+ const admitted = credential.admissions();
56991
+ if (admitted.count !== admissions) {
56992
+ admissions = admitted.count;
56993
+ rushedInWait = false;
56994
+ if (admitted.dialedAt !== undefined && admitted.dialedAt > dialedAt) {
56995
+ dialedAt = admitted.dialedAt;
56996
+ }
56997
+ }
56998
+ const unpresented = credential.needsReconnect() ? credential.tokenGeneration() : undefined;
56999
+ const session = credential.tokenSession();
57000
+ if (at < dueAt - DUE_SLACK_MS) {
57001
+ const renewal = session === dialedSession;
57002
+ if (unpresented === undefined || unpresented === rushed || rushedInWait && renewal) {
57003
+ return Math.min(dueAt, at + pollMs) - dialedAt;
57004
+ }
57005
+ rushed = unpresented;
57006
+ rushedInWait = true;
57007
+ dialedSession = session;
57008
+ dialedAt = at;
57009
+ return 0;
57010
+ }
57011
+ if (unpresented !== undefined)
57012
+ rushed = unpresented;
57013
+ dialedSession = session;
57014
+ rushedInWait = false;
57015
+ waits += 1;
57016
+ dialedAt = at;
57017
+ dueAt = at + brokerRedialWaitMs(waits, random);
57018
+ return 0;
56911
57019
  };
56912
57020
  }
56913
- function newEpoch() {
56914
- return crypto.randomUUID();
57021
+ function natsServersForLog(setting, count) {
57022
+ return count === 1 ? `the server ${setting} names` : `the ${count} servers ${setting} names`;
57023
+ }
57024
+ function natsDialFailure(named, error, presenting) {
57025
+ const credential = presenting === undefined ? "" : ` presenting ${presenting}`;
57026
+ return `could not connect to NATS at ${named}${credential}: ${natsFailureReason(error)}`;
56915
57027
  }
56916
- var GAP_MESSAGES = {
56917
- retention_gap: "The notification stream no longer holds some messages published to this session while it was away: messages older than 72 hours may be missing.",
56918
- stream_recreated: "Envoy's notification stream was recreated, so messages published to this session before that may be lost."
57028
+ var NATS_DIAL_PLAN = {
57029
+ firstDelayMs: 250,
57030
+ maxDelayMs: 4000,
57031
+ budgetMs: 25000
56919
57032
  };
56920
- var ConsumerDeliverySnapshotSchema = object({
56921
- resume: object({ stream_id: string2().min(1), seq: number2().int().nonnegative() }).optional(),
56922
- follows: record(string2(), number2()).default({})
56923
- });
56924
- function parseIdentity(data) {
56925
- let parsed;
56926
- try {
56927
- parsed = JSON.parse(data);
56928
- } catch {
56929
- return;
56930
- }
56931
- const identity = DedupeIdentitySchema.safeParse(parsed);
56932
- if (!identity.success)
56933
- return;
56934
- const { event_id, dedupe_key } = identity.data;
56935
- return event_id === undefined && dedupe_key === undefined ? undefined : identity.data;
57033
+ var NATS_DIAL_TOKEN_DROPPED = "the hub refused the session's broker token twice, so the token was dropped and another trade started";
57034
+ var NATS_MIN_REDIAL_BOUND_MS = 500;
57035
+
57036
+ class NatsDialBoundError extends LoggableError {
56936
57037
  }
56937
- function reaches(topic, forms) {
56938
- const patterns = topicForms(topic).flatMap((form) => expandSubscriptionTopics([form]));
56939
- return forms.some((form) => patterns.some((pattern) => subjectsOverlap(pattern, form)));
57038
+ var AUTHORIZATION_REFUSALS = {
57039
+ [import_nats2.ErrorCode.AuthorizationViolation]: true,
57040
+ [import_nats2.ErrorCode.AuthenticationExpired]: true,
57041
+ [import_nats2.ErrorCode.AccountExpired]: true
57042
+ };
57043
+ var NEVER_CURED = {
57044
+ [import_nats2.ErrorCode.BadAuthentication]: true,
57045
+ [import_nats2.ErrorCode.BadCreds]: true,
57046
+ [import_nats2.ErrorCode.InvalidOption]: true,
57047
+ [import_nats2.ErrorCode.NotFunction]: true,
57048
+ [import_nats2.ErrorCode.ServerOptionNotAvailable]: true,
57049
+ [import_nats2.ErrorCode.WssRequired]: true,
57050
+ [import_nats2.ErrorCode.Tls]: true
57051
+ };
57052
+ function redialCures(error, options) {
57053
+ if (error instanceof NatsDialBoundError)
57054
+ return true;
57055
+ const code = errorCode(error);
57056
+ if (code === undefined)
57057
+ return false;
57058
+ if (AUTHORIZATION_REFUSALS[code] === true)
57059
+ return options.ignoreAuthErrorAbort === true;
57060
+ return NEVER_CURED[code] !== true && !code.startsWith("ERR_");
56940
57061
  }
56941
- function every(ms, callback) {
56942
- const timer = setInterval(callback, ms);
56943
- return () => clearInterval(timer);
57062
+ function errorCode(error) {
57063
+ return error instanceof Error && "code" in error && typeof error.code === "string" ? error.code : undefined;
56944
57064
  }
56945
- function createConsumerDelivery(options) {
56946
- const { host, ledger, sessionID } = options;
56947
- const render = options.render ?? renderInbound;
56948
- const now = options.now ?? Date.now;
56949
- const repeat = options.every ?? every;
56950
- const ownSubject = legacyAgentSubject(sessionID);
56951
- const ownsSubject = (subject) => topicForms(subject).includes(ownSubject);
56952
- let currentEpoch = { id: newEpoch(), startedAt: now() };
56953
- let follows = new Map;
56954
- let streamID;
56955
- let held = new Set;
56956
- let written;
56957
- let registeredResume;
56958
- let gapTold = false;
56959
- let closed = false;
56960
- let persisted = JSON.stringify({ follows: {} });
56961
- const entries = new Map;
56962
- const troubled = new Map;
56963
- const queue = [];
56964
- let blocking;
56965
- let pumping = false;
56966
- const safely = (what, call) => {
57065
+ function brokerDialRefusals(credential, random) {
57066
+ if (credential?.kind !== "broker")
57067
+ return;
57068
+ const { broker } = credential;
57069
+ let refusals = 0;
57070
+ return {
57071
+ refused: (code) => {
57072
+ if (code === undefined || AUTHORIZATION_REFUSALS[code] !== true)
57073
+ return;
57074
+ refusals += 1;
57075
+ const dropped = broker.refused(code)?.dropped === true;
57076
+ if (dropped)
57077
+ broker.renew(AbortSignal.timeout(TRADE_DEADLINE_MS)).catch(() => {});
57078
+ return { waitMs: brokerRedialWaitMs(refusals, random), dropped };
57079
+ },
57080
+ admitted: (dialedAt) => broker.admitted(dialedAt)
57081
+ };
57082
+ }
57083
+ async function connectNats(connect, options, plan, hooks = {}) {
57084
+ const started = performance.now();
57085
+ const elapsed = () => performance.now() - started;
57086
+ const timeout = options.timeout ?? NATS_DIAL_TIMEOUT_MS;
57087
+ const servers = Array.isArray(options.servers) ? Math.max(1, options.servers.length) : 1;
57088
+ const brokerRefusals = brokerDialRefusals(hooks.credential, hooks.random ?? Math.random);
57089
+ const wait = hooks.delay ?? delay;
57090
+ let delayMs = plan.firstDelayMs;
57091
+ let failed;
57092
+ for (let attempt = 1;; attempt += 1) {
57093
+ if (hooks.stopped?.() === true) {
57094
+ throw failed ?? new LoggableError("the NATS dial was stopped before it began");
57095
+ }
57096
+ const bound = Math.max(1, Math.round(Math.min(timeout, attempt === 1 ? hooks.firstBoundMs ?? timeout : plan.budgetMs - elapsed())));
57097
+ const dialedAt = Date.now();
56967
57098
  try {
56968
- call();
57099
+ const nc = await boundedDial(connect, {
57100
+ ...options,
57101
+ timeout: Math.min(bound, Math.max(NATS_MIN_REDIAL_BOUND_MS, Math.floor(bound / servers)))
57102
+ }, bound);
57103
+ keepWholeTimeout(nc, timeout);
57104
+ brokerRefusals?.admitted(dialedAt);
57105
+ return nc;
56969
57106
  } catch (error) {
56970
- try {
56971
- host.log(`consumer delivery: ${what} failed`, error);
56972
- } catch {}
57107
+ failed = error;
57108
+ const refusal = brokerRefusals?.refused(errorCode(error));
57109
+ if (refusal?.dropped === true)
57110
+ hooks.onTokenDropped?.(error, attempt);
57111
+ const waitMs = refusal?.waitMs ?? delayMs;
57112
+ if (!redialCures(error, options) || elapsed() + waitMs + NATS_MIN_REDIAL_BOUND_MS > plan.budgetMs || hooks.stopped?.() === true) {
57113
+ throw error;
57114
+ }
57115
+ hooks.onRetry?.(error, waitMs, attempt);
57116
+ await wait(waitMs);
57117
+ if (plan.budgetMs - elapsed() < NATS_MIN_REDIAL_BOUND_MS)
57118
+ throw error;
57119
+ if (refusal === undefined)
57120
+ delayMs = Math.min(delayMs * 2, plan.maxDelayMs);
56973
57121
  }
57122
+ }
57123
+ }
57124
+ function keepWholeTimeout(nc, timeout) {
57125
+ if (!(nc instanceof import_nats3.NatsConnectionImpl))
57126
+ return;
57127
+ const opened = nc.options;
57128
+ opened.timeout = timeout;
57129
+ delete opened.abandonSignal;
57130
+ }
57131
+ async function boundedDial(connect, options, boundMs) {
57132
+ const abandon = new AbortController;
57133
+ const withAbandon = {
57134
+ ...options,
57135
+ abandonSignal: abandon.signal
56974
57136
  };
56975
- const log = (message, error) => safely("log", () => host.log(`consumer delivery: ${message}`, error));
56976
- const send = (reply, body) => safely(`reply ${body}`, () => options.publish(reply, body));
56977
- const tellGap = (kind) => safely("gap notice", () => host.gap({ kind, message: GAP_MESSAGES[kind] }));
56978
- const switchStream = (id) => {
56979
- if (streamID === id)
57137
+ const dialing = connect(withAbandon);
57138
+ const expired = Promise.withResolvers();
57139
+ const timer = setTimeout(() => {
57140
+ abandon.abort();
57141
+ expired.reject(new NatsDialBoundError(`the NATS dial did not complete within ${boundMs} ms`));
57142
+ }, boundMs);
57143
+ try {
57144
+ return await Promise.race([dialing, expired.promise]);
57145
+ } catch (error) {
57146
+ dialing.then((late) => late.close()).catch(() => {
56980
57147
  return;
56981
- streamID = id;
56982
- held = new Set;
56983
- written = undefined;
56984
- troubled.clear();
56985
- };
56986
- const tellReplacedResume = (id) => {
56987
- const asked = resumePoint() ?? registeredResume;
56988
- if (asked === undefined || asked.stream_id === id)
57148
+ });
57149
+ throw error;
57150
+ } finally {
57151
+ clearTimeout(timer);
57152
+ }
57153
+ }
57154
+
57155
+ // ../envoy-client/src/listener-relay.ts
57156
+ var RELAY_SUBPROTOCOL = "envoy-relay.v1";
57157
+ var RELAY_STABLE_MS = 60000;
57158
+ var RELAY_LAST_WAIT_MS = 60000;
57159
+ var RELAY_FIRST_WAIT_MS = 1000;
57160
+ var RELAY_BROKER_FIRST_WAIT_MS = 5000;
57161
+ var RELAY_HANDSHAKE_MS = 20000;
57162
+ var CLOSE_EXPIRED = 4401;
57163
+ var CLOSE_REFUSED = 4403;
57164
+ var CLOSE_TRY_AGAIN_LATER = 1013;
57165
+ var CLOSE_STOPPING = 1012;
57166
+ var CLOSE_BAD_FRAME = 1008;
57167
+ var RELAY_MAX_FRAME_BYTES = 2 * 1024 * 1024;
57168
+ var AT_ONCE = new Set([CLOSE_EXPIRED, CLOSE_STOPPING]);
57169
+ var AT_ONCE_FIRST = new Set([1001, 1006]);
57170
+ var TOKEN_REFUSED = new Set([401, 403]);
57171
+ var UPGRADE_UNAVAILABLE = 503;
57172
+ var UPGRADE_STATUS = /Expected 101 status code: (\d{3})\b/;
57173
+ var SUBSCRIPTION_REFUSALS = {
57174
+ subject_not_granted: true,
57175
+ subscription_limit: true
57176
+ };
57177
+ var ERR_CODES = {
57178
+ ...SUBSCRIPTION_REFUSALS,
57179
+ publish_not_granted: true,
57180
+ bad_frame: true
57181
+ };
57182
+ var DRAIN_BOUND_MS = 1000;
57183
+ var BunWebSocket = WebSocket;
57184
+ function relaySocketUrl(url, session) {
57185
+ return `${withoutTrailingSlashes(url)}/v1/sessions/${encodeURIComponent(session)}/relay`;
57186
+ }
57187
+ function relayRun(end) {
57188
+ if ("closed" in end) {
57189
+ if (end.closed === CLOSE_REFUSED)
57190
+ return "token";
57191
+ if (end.closed === CLOSE_TRY_AGAIN_LATER)
57192
+ return "broker";
57193
+ return `closed ${end.closed}`;
57194
+ }
57195
+ if (end.refused !== undefined && TOKEN_REFUSED.has(end.refused))
57196
+ return "token";
57197
+ if (end.refused === UPGRADE_UNAVAILABLE && end.after === CLOSE_TRY_AGAIN_LATER)
57198
+ return "broker";
57199
+ return "unopened";
57200
+ }
57201
+ function tokenCaused(end) {
57202
+ return "closed" in end && end.closed === CLOSE_EXPIRED || relayRun(end) === "token";
57203
+ }
57204
+ function relayReopenDelay(end, streak) {
57205
+ const doubling = (first, times) => Math.min(first * 2 ** times, RELAY_LAST_WAIT_MS);
57206
+ if ("closed" in end && AT_ONCE.has(end.closed))
57207
+ return 0;
57208
+ if ("closed" in end && AT_ONCE_FIRST.has(end.closed)) {
57209
+ return streak === 0 ? 0 : doubling(RELAY_FIRST_WAIT_MS, streak - 1);
57210
+ }
57211
+ if (relayRun(end) === "broker")
57212
+ return doubling(RELAY_BROKER_FIRST_WAIT_MS, streak);
57213
+ return doubling(RELAY_FIRST_WAIT_MS, streak);
57214
+ }
57215
+
57216
+ class Queue {
57217
+ #items = [];
57218
+ #waiting = [];
57219
+ #ended = false;
57220
+ #failed;
57221
+ #onReturn;
57222
+ constructor(onReturn) {
57223
+ this.#onReturn = onReturn;
57224
+ }
57225
+ push(item) {
57226
+ if (this.#ended)
56989
57227
  return;
56990
- registeredResume = undefined;
56991
- tellGap("stream_recreated");
56992
- };
56993
- const followedAt = (subject) => {
56994
- if (ownsSubject(subject))
56995
- return Number.NEGATIVE_INFINITY;
56996
- const forms = topicForms(subject);
56997
- let earliest;
56998
- for (const [topic, at] of follows) {
56999
- if (!reaches(topic, forms))
57000
- continue;
57001
- if (earliest === undefined || at < earliest)
57002
- earliest = at;
57003
- }
57004
- return earliest;
57005
- };
57006
- const settle = (entry, body) => {
57007
- if (entry.settled)
57228
+ const waiting = this.#waiting.shift();
57229
+ if (waiting === undefined)
57230
+ this.#items.push(item);
57231
+ else
57232
+ waiting.resolve({ done: false, value: item });
57233
+ }
57234
+ end() {
57235
+ if (this.#ended)
57008
57236
  return;
57009
- entry.settled = true;
57010
- entry.stopProgress();
57011
- entries.delete(entry.key);
57012
- for (const reply of entry.replies)
57013
- send(reply, body);
57014
- if (body === "done")
57015
- troubled.delete(entry.key);
57016
- if (body === "done" && entry.frame.streamID === streamID) {
57017
- held.delete(entry.frame.streamSeq);
57018
- written = Math.max(written ?? 0, entry.frame.streamSeq);
57019
- }
57020
- release(entry);
57237
+ this.#ended = true;
57238
+ for (const waiting of this.#waiting.splice(0))
57239
+ waiting.resolve({ done: true, value: undefined });
57240
+ }
57241
+ fail(error) {
57242
+ if (this.#ended)
57243
+ return;
57244
+ this.#ended = true;
57245
+ this.#failed = error;
57246
+ for (const waiting of this.#waiting.splice(0))
57247
+ waiting.reject(error);
57248
+ }
57249
+ [Symbol.asyncIterator]() {
57250
+ return {
57251
+ next: () => {
57252
+ if (this.#items.length > 0) {
57253
+ return Promise.resolve({ done: false, value: this.#items.shift() });
57254
+ }
57255
+ if (this.#failed !== undefined)
57256
+ return Promise.reject(this.#failed);
57257
+ if (this.#ended)
57258
+ return Promise.resolve({ done: true, value: undefined });
57259
+ const { promise, resolve, reject } = Promise.withResolvers();
57260
+ this.#waiting.push({ resolve, reject });
57261
+ return promise;
57262
+ },
57263
+ return: () => {
57264
+ this.#onReturn();
57265
+ this.end();
57266
+ return Promise.resolve({ done: true, value: undefined });
57267
+ }
57268
+ };
57269
+ }
57270
+ }
57271
+
57272
+ class RelaySubscription {
57273
+ sid;
57274
+ subject;
57275
+ #queue;
57276
+ constructor(sid, subject, unsubscribe) {
57277
+ this.sid = sid;
57278
+ this.subject = subject;
57279
+ this.#queue = new Queue(unsubscribe);
57280
+ this.unsubscribe = unsubscribe;
57281
+ }
57282
+ unsubscribe;
57283
+ push(message) {
57284
+ this.#queue.push(message);
57285
+ }
57286
+ end() {
57287
+ this.#queue.end();
57288
+ }
57289
+ fail(error) {
57290
+ this.#queue.fail(error);
57291
+ }
57292
+ [Symbol.asyncIterator]() {
57293
+ return this.#queue[Symbol.asyncIterator]();
57294
+ }
57295
+ }
57296
+ function relayHeaders(raw) {
57297
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw))
57298
+ return;
57299
+ const values = new Map;
57300
+ for (const [name, value] of Object.entries(raw)) {
57301
+ if (!Array.isArray(value) || !value.every((one) => typeof one === "string"))
57302
+ return;
57303
+ values.set(name, value);
57304
+ }
57305
+ return {
57306
+ get: (name) => values.get(name)?.[0] ?? "",
57307
+ values: (name) => values.get(name) ?? []
57021
57308
  };
57022
- const release = (entry) => {
57023
- if (blocking !== entry)
57309
+ }
57310
+ function frameText(data) {
57311
+ if (typeof data === "string")
57312
+ return data;
57313
+ if (data instanceof ArrayBuffer)
57314
+ return Buffer.from(data).toString("utf8");
57315
+ if (ArrayBuffer.isView(data)) {
57316
+ return Buffer.from(data.buffer, data.byteOffset, data.byteLength).toString("utf8");
57317
+ }
57318
+ return "";
57319
+ }
57320
+
57321
+ class ListenerRelay {
57322
+ #options;
57323
+ #outage;
57324
+ #socket;
57325
+ #socketSession = "";
57326
+ #presented;
57327
+ #generation = 0;
57328
+ #everOpened = false;
57329
+ #streaks = new Map;
57330
+ #closedWith;
57331
+ #stableTimer;
57332
+ #reopenTimer;
57333
+ #livenessTimer;
57334
+ #pingSeq = 0;
57335
+ #sentSincePong = new Map;
57336
+ #pongSeen = 0;
57337
+ #pongs = [];
57338
+ #openWaiters = [];
57339
+ #lastFailure = "";
57340
+ #loggedFailure = "";
57341
+ #subs = new Map;
57342
+ #nextSid = 0;
57343
+ #statuses = new Set;
57344
+ #closedForGood = false;
57345
+ #closed = Promise.withResolvers();
57346
+ #logged = new Set;
57347
+ constructor(options) {
57348
+ this.#options = options;
57349
+ this.#outage = options.outage;
57350
+ this.#open();
57351
+ }
57352
+ reportOutagesTo(outage) {
57353
+ this.#outage = outage;
57354
+ }
57355
+ subscribe(subject) {
57356
+ if (this.#closedForGood)
57357
+ throw new LoggableError("the listener's relay socket is closed");
57358
+ this.#nextSid += 1;
57359
+ const sid = this.#nextSid;
57360
+ const subscription = new RelaySubscription(sid, subject, () => this.#unsubscribe(sid));
57361
+ this.#subs.set(sid, subscription);
57362
+ this.#send({ op: "sub", sid, subject });
57363
+ return subscription;
57364
+ }
57365
+ publish(subject, data) {
57366
+ if (this.#closedForGood)
57367
+ throw new LoggableError("the listener's relay socket is closed");
57368
+ this.#send({
57369
+ op: "pub",
57370
+ subject,
57371
+ data: Buffer.from(data ?? new Uint8Array).toString("base64")
57372
+ });
57373
+ }
57374
+ async flush() {
57375
+ const socket = await this.#openSocket();
57376
+ if (socket !== this.#socket) {
57377
+ throw new LoggableError("the listener's relay socket closed before the flush was sent");
57378
+ }
57379
+ this.#pingSeq += 1;
57380
+ const seq = this.#pingSeq;
57381
+ const answered = Promise.withResolvers();
57382
+ this.#pongs.push({ seq, resolve: answered.resolve, reject: answered.reject });
57383
+ socket.ping(String(seq));
57384
+ await answered.promise;
57385
+ }
57386
+ isClosed() {
57387
+ return this.#closedForGood;
57388
+ }
57389
+ async drain() {
57390
+ if (this.#closedForGood)
57024
57391
  return;
57025
- blocking = undefined;
57026
- pump();
57027
- };
57028
- const alreadyWritten = (identity) => identity !== undefined && ledger.delivered(identity);
57029
- const failed = (entry, error) => {
57030
- if (entry.settled)
57392
+ for (const sid of [...this.#subs.keys()])
57393
+ this.#unsubscribe(sid);
57394
+ const bound = Promise.withResolvers();
57395
+ const timer = setTimeout(bound.resolve, DRAIN_BOUND_MS);
57396
+ await Promise.race([this.flush().catch(() => {
57031
57397
  return;
57032
- const trouble = troubled.get(entry.key) ?? { failures: 0, givenUp: false };
57033
- troubled.set(entry.key, trouble);
57034
- if (trouble.givenUp) {
57035
- settle(entry, "nak");
57398
+ }), bound.promise]);
57399
+ clearTimeout(timer);
57400
+ await this.close();
57401
+ }
57402
+ async close() {
57403
+ if (this.#closedForGood)
57036
57404
  return;
57405
+ this.#closedForGood = true;
57406
+ this.#generation += 1;
57407
+ this.#stopTimers();
57408
+ clearTimeout(this.#reopenTimer);
57409
+ const socket = this.#socket;
57410
+ this.#socket = undefined;
57411
+ socket?.close(1000, "the session closed its relay socket");
57412
+ for (const subscription of this.#subs.values())
57413
+ subscription.end();
57414
+ this.#subs.clear();
57415
+ for (const status of this.#statuses)
57416
+ status.end();
57417
+ this.#statuses.clear();
57418
+ const closed = new LoggableError("the listener's relay socket is closed");
57419
+ for (const pong of this.#pongs.splice(0))
57420
+ pong.reject(closed);
57421
+ for (const waiter of this.#openWaiters.splice(0))
57422
+ waiter.reject(closed);
57423
+ this.#closed.resolve();
57424
+ }
57425
+ status() {
57426
+ const queue = new Queue(() => this.#statuses.delete(queue));
57427
+ if (this.#closedForGood)
57428
+ queue.end();
57429
+ else
57430
+ this.#statuses.add(queue);
57431
+ return queue;
57432
+ }
57433
+ closed() {
57434
+ return this.#closed.promise;
57435
+ }
57436
+ async follow(boundMs = FOLLOW_DEADLINE_MS) {
57437
+ if (this.#closedForGood)
57438
+ throw new LoggableError("the listener's relay socket is closed");
57439
+ const session = sessionName(this.#options.session);
57440
+ if (session !== this.#socketSession) {
57441
+ this.#streaks.clear();
57442
+ this.#closedWith = undefined;
57443
+ this.#open();
57444
+ }
57445
+ const bound = AbortSignal.timeout(boundMs);
57446
+ await this.#openSocket(bound).catch((error) => {
57447
+ if (!bound.aborted)
57448
+ throw error;
57449
+ throw new LoggableError(`the listener's relay socket did not open as the session ${session} within ${Math.round(boundMs / 1000)} s${this.#failureSuffix()}`);
57450
+ });
57451
+ }
57452
+ async opened(signal) {
57453
+ await this.#openSocket(signal).catch((error) => {
57454
+ if (signal?.aborted !== true)
57455
+ throw error;
57456
+ throw new LoggableError(`the listener's relay socket for ${this.#socketSession} did not open${this.#failureSuffix()}`);
57457
+ });
57458
+ }
57459
+ #failureSuffix() {
57460
+ return this.#lastFailure === "" ? "" : `: ${this.#lastFailure}`;
57461
+ }
57462
+ #openSocket(signal) {
57463
+ const ready = () => this.#socket?.readyState === WebSocket.OPEN && this.#socketSession === sessionName(this.#options.session) ? this.#socket : undefined;
57464
+ const { promise, resolve, reject } = Promise.withResolvers();
57465
+ if (this.#closedForGood) {
57466
+ reject(new LoggableError("the listener's relay socket is closed"));
57467
+ return promise;
57037
57468
  }
57038
- trouble.failures += 1;
57039
- if (trouble.failures < RELAY_ATTEMPTS_BEFORE_FAILED) {
57040
- log(`frame ${entry.frame.streamSeq} failed; it comes again`, error);
57041
- settle(entry, "nak");
57042
- return;
57469
+ if (signal?.aborted === true) {
57470
+ reject(signal.reason);
57471
+ return promise;
57043
57472
  }
57044
- log(`frame ${entry.frame.streamSeq} failed and does not come again; its session gets the notice`, error);
57045
- const goesBack = (why, thrown) => {
57046
- trouble.givenUp = true;
57047
- log(`frame ${entry.frame.streamSeq} ${why}; it goes back to the stream`, thrown);
57048
- settle(entry, "nak");
57473
+ const now = ready();
57474
+ if (now !== undefined) {
57475
+ resolve(now);
57476
+ return promise;
57477
+ }
57478
+ const stop = () => {
57479
+ const index = this.#openWaiters.indexOf(waiter);
57480
+ if (index >= 0)
57481
+ this.#openWaiters.splice(index, 1);
57482
+ reject(signal?.reason);
57049
57483
  };
57050
- let envelope;
57051
- try {
57052
- envelope = render(entry.frame.data, sessionID, entry.frame.subject).envelope;
57053
- } catch (thrown) {
57054
- goesBack("could not be read to report it", thrown);
57484
+ const waiter = {
57485
+ resolve: () => {
57486
+ const socket = ready();
57487
+ if (socket === undefined) {
57488
+ this.#openWaiters.push(waiter);
57489
+ return;
57490
+ }
57491
+ signal?.removeEventListener("abort", stop);
57492
+ resolve(socket);
57493
+ },
57494
+ reject: (error) => {
57495
+ signal?.removeEventListener("abort", stop);
57496
+ reject(error);
57497
+ }
57498
+ };
57499
+ this.#openWaiters.push(waiter);
57500
+ signal?.addEventListener("abort", stop, { once: true });
57501
+ return promise;
57502
+ }
57503
+ #send(frame) {
57504
+ const socket = this.#socket;
57505
+ if (socket?.readyState !== WebSocket.OPEN)
57055
57506
  return;
57056
- }
57057
- if (envelope === undefined) {
57058
- log(`frame ${entry.frame.streamSeq} carries no envelope to report; it is dropped`);
57059
- settle(entry, "done");
57507
+ socket.send(JSON.stringify(frame));
57508
+ this.#sentSincePong.set(frame.op, this.#pingSeq);
57509
+ }
57510
+ #unsubscribe(sid) {
57511
+ const subscription = this.#subs.get(sid);
57512
+ if (subscription === undefined)
57060
57513
  return;
57061
- }
57062
- let telling;
57063
- try {
57064
- telling = ledger.liveFailed(sessionID, envelope, error);
57065
- } catch (thrown) {
57066
- goesBack("could not be reported", thrown);
57514
+ this.#subs.delete(sid);
57515
+ subscription.end();
57516
+ this.#send({ op: "unsub", sid });
57517
+ }
57518
+ #logOnce(key, line) {
57519
+ if (this.#logged.has(key))
57067
57520
  return;
57068
- }
57069
- telling.then((told) => {
57070
- if (told) {
57071
- settle(entry, "done");
57521
+ this.#logged.add(key);
57522
+ this.#options.log(line);
57523
+ }
57524
+ #emit(type) {
57525
+ for (const status of this.#statuses)
57526
+ status.push({ type });
57527
+ }
57528
+ #stopTimers() {
57529
+ clearTimeout(this.#stableTimer);
57530
+ clearInterval(this.#livenessTimer);
57531
+ this.#stableTimer = undefined;
57532
+ this.#livenessTimer = undefined;
57533
+ }
57534
+ #open() {
57535
+ if (this.#closedForGood)
57536
+ return;
57537
+ clearTimeout(this.#reopenTimer);
57538
+ this.#reopenTimer = undefined;
57539
+ this.#generation += 1;
57540
+ const generation = this.#generation;
57541
+ const previous = this.#socket;
57542
+ this.#socket = undefined;
57543
+ this.#stopTimers();
57544
+ previous?.close(1000, "the session opens its relay socket again");
57545
+ const dropped = new LoggableError("the listener's relay socket was opened again before it answered the flush");
57546
+ for (const pong of this.#pongs.splice(0))
57547
+ pong.reject(dropped);
57548
+ this.#sentSincePong.clear();
57549
+ const session = sessionName(this.#options.session);
57550
+ this.#socketSession = session;
57551
+ this.#upgradeHeaders(session).then((upgrade) => {
57552
+ if (generation !== this.#generation)
57553
+ return;
57554
+ if ("failed" in upgrade) {
57555
+ this.#outage.refused(upgrade.error);
57556
+ const delay = this.#reopenAfter({ refused: undefined, after: this.#closedWith });
57557
+ this.#failed(session, upgrade.failed, delay);
57072
57558
  return;
57073
57559
  }
57074
- goesBack("was reported to nobody");
57075
- }, (thrown) => {
57076
- goesBack("could not be reported", thrown);
57560
+ this.#connect(generation, session, upgrade.headers);
57077
57561
  });
57078
- };
57079
- const handOff = (entry) => {
57080
- const handle = {
57081
- ...entry.frame,
57082
- late: entry.late,
57083
- done: () => settle(entry, "done"),
57084
- nak: () => settle(entry, "nak"),
57085
- release: () => release(entry)
57086
- };
57087
- blocking = entry;
57088
- let result;
57562
+ }
57563
+ #failed(session, failure, delay) {
57564
+ this.#lastFailure = failure;
57565
+ if (failure === this.#loggedFailure)
57566
+ return;
57567
+ this.#loggedFailure = failure;
57568
+ this.#options.log(`the listener's relay socket for ${session} could not be opened: ${failure}; it is tried again in ${delay} ms, the wait doubling to a minute while it fails`);
57569
+ }
57570
+ async#upgradeHeaders(session) {
57089
57571
  try {
57090
- result = host.deliver(handle);
57572
+ if (session === "") {
57573
+ throw new LoggableError("this process names no session for its relay socket");
57574
+ }
57575
+ const headers = await this.#options.credential.headers("GET", relaySocketUrl(this.#options.url, session), session, AbortSignal.timeout(TRADE_DEADLINE_MS));
57576
+ return { headers };
57091
57577
  } catch (error) {
57092
- failed(entry, error);
57093
- release(entry);
57094
- return;
57578
+ return { failed: `its token could not be had (${messageFor(error)})`, error };
57095
57579
  }
57096
- if (!(result instanceof Promise)) {
57097
- release(entry);
57580
+ }
57581
+ #connect(generation, session, headers) {
57582
+ this.#presented = headers;
57583
+ const target = relaySocketUrl(this.#options.url, session).replace(/^http/, "ws");
57584
+ let socket;
57585
+ try {
57586
+ socket = new BunWebSocket(target, { headers, protocols: RELAY_SUBPROTOCOL });
57587
+ } catch (error) {
57588
+ const delay = this.#reopenAfter({ refused: undefined, after: this.#closedWith });
57589
+ this.#failed(session, `the socket could not be made (${messageFor(error)})`, delay);
57098
57590
  return;
57099
57591
  }
57100
- result.then(() => release(entry), (error) => {
57101
- failed(entry, error);
57102
- release(entry);
57592
+ this.#socket = socket;
57593
+ let opened = false;
57594
+ let refusal;
57595
+ let failure = "";
57596
+ const handshake = setTimeout(() => {
57597
+ if (generation !== this.#generation || socket.readyState !== WebSocket.CONNECTING)
57598
+ return;
57599
+ refusal = `the upgrade was not answered within ${RELAY_HANDSHAKE_MS / 1000} s`;
57600
+ socket.close();
57601
+ }, RELAY_HANDSHAKE_MS);
57602
+ handshake.unref?.();
57603
+ socket.addEventListener("open", () => {
57604
+ clearTimeout(handshake);
57605
+ if (generation !== this.#generation)
57606
+ return;
57607
+ opened = true;
57608
+ this.#opened(generation, session, socket);
57103
57609
  });
57104
- };
57105
- function pump() {
57106
- if (pumping)
57107
- return;
57108
- pumping = true;
57109
- try {
57110
- while (blocking === undefined && !closed) {
57111
- const entry = queue.shift();
57112
- if (entry === undefined)
57113
- return;
57114
- if (entry.settled)
57115
- continue;
57116
- if (alreadyWritten(entry.identity)) {
57117
- settle(entry, "done");
57118
- continue;
57119
- }
57120
- handOff(entry);
57610
+ socket.addEventListener("error", (event) => {
57611
+ if ("message" in event && typeof event.message === "string")
57612
+ failure = event.message;
57613
+ });
57614
+ socket.addEventListener("message", (event) => {
57615
+ if (generation !== this.#generation)
57616
+ return;
57617
+ this.#message(session, "data" in event ? event.data : undefined);
57618
+ });
57619
+ socket.addEventListener("pong", (event) => {
57620
+ if (generation !== this.#generation)
57621
+ return;
57622
+ this.#pong(frameText("data" in event ? event.data : undefined));
57623
+ });
57624
+ socket.addEventListener("close", (event) => {
57625
+ clearTimeout(handshake);
57626
+ const status = opened ? undefined : UPGRADE_STATUS.exec(failure)?.[1];
57627
+ this.#socketClosed(generation, session, socket, {
57628
+ end: opened ? { closed: event.code } : { refused: status === undefined ? undefined : Number(status), after: this.#closedWith },
57629
+ why: event.reason === "" ? `${event.code}` : `${event.code} ${event.reason}`,
57630
+ refusal,
57631
+ failure
57632
+ });
57633
+ });
57634
+ }
57635
+ #opened(generation, session, socket) {
57636
+ const reopened = this.#everOpened;
57637
+ this.#everOpened = true;
57638
+ this.#lastFailure = "";
57639
+ this.#loggedFailure = "";
57640
+ this.#stableTimer = setTimeout(() => {
57641
+ if (generation === this.#generation)
57642
+ this.#streaks.clear();
57643
+ }, RELAY_STABLE_MS);
57644
+ this.#stableTimer.unref?.();
57645
+ this.#closedWith = undefined;
57646
+ const pingsAtStart = this.#pingSeq;
57647
+ this.#pongSeen = Math.max(this.#pongSeen, pingsAtStart);
57648
+ this.#livenessTimer = setInterval(() => {
57649
+ if (generation !== this.#generation)
57650
+ return;
57651
+ if (this.#pingSeq - this.#pongSeen >= NATS_MAX_PINGS_OUT) {
57652
+ this.#lastFailure = `the socket answered no ping for ${Math.round(NATS_MAX_PINGS_OUT * NATS_PING_INTERVAL_MS / 1000)} s`;
57653
+ this.#options.log(`the listener's relay socket for ${session}: ${this.#lastFailure}`);
57654
+ socket.terminate();
57655
+ return;
57121
57656
  }
57122
- } finally {
57123
- pumping = false;
57657
+ this.#pingSeq += 1;
57658
+ socket.ping(String(this.#pingSeq));
57659
+ }, NATS_PING_INTERVAL_MS);
57660
+ this.#livenessTimer.unref?.();
57661
+ for (const subscription of this.#subs.values()) {
57662
+ this.#send({ op: "sub", sid: subscription.sid, subject: subscription.subject });
57124
57663
  }
57664
+ for (const waiter of this.#openWaiters.splice(0))
57665
+ waiter.resolve();
57666
+ if (reopened)
57667
+ this.#emit("reconnect");
57125
57668
  }
57126
- const receive = (message) => {
57127
- if (message.headers?.get(RelayHeader.probe) === "1") {
57128
- if (message.reply !== undefined && message.reply !== "")
57129
- send(message.reply, "done");
57669
+ #pong(text) {
57670
+ const seq = Number(text);
57671
+ if (!Number.isInteger(seq) || seq <= 0)
57672
+ return;
57673
+ this.#pongSeen = Math.max(this.#pongSeen, seq);
57674
+ const answered = this.#pongs.filter((pong) => pong.seq <= seq);
57675
+ this.#pongs = this.#pongs.filter((pong) => pong.seq > seq);
57676
+ for (const pong of answered)
57677
+ pong.resolve();
57678
+ for (const [op, after] of this.#sentSincePong) {
57679
+ if (after < seq)
57680
+ this.#sentSincePong.delete(op);
57681
+ }
57682
+ }
57683
+ #message(session, raw) {
57684
+ const bytes = typeof raw === "string" ? Buffer.byteLength(raw) : raw instanceof ArrayBuffer || ArrayBuffer.isView(raw) ? raw.byteLength : 0;
57685
+ if (bytes > RELAY_MAX_FRAME_BYTES) {
57686
+ this.#logOnce(`${session}\x00size`, `the listener's relay socket for ${session} sent a frame past 2 MiB, which no relay frame is; it is dropped, and its message comes again after the consumer's ack wait`);
57130
57687
  return;
57131
57688
  }
57132
- const decoded = decodeRelayFrame(message);
57133
- if ("error" in decoded) {
57134
- log(`dropping an undecodable relay frame: ${decoded.error}`);
57135
- if (message.reply !== undefined && message.reply !== "")
57136
- send(message.reply, "done");
57689
+ let frame;
57690
+ try {
57691
+ frame = JSON.parse(frameText(raw));
57692
+ } catch {
57693
+ this.#logOnce(`${session}\x00json`, `the listener's relay socket for ${session} sent a frame that is no JSON`);
57137
57694
  return;
57138
57695
  }
57139
- const { frame } = decoded;
57140
- if (closed) {
57141
- send(frame.reply, "nak");
57696
+ if (typeof frame !== "object" || frame === null || !("op" in frame))
57697
+ return;
57698
+ if (frame.op === "msg" && "sid" in frame && "subject" in frame && "data" in frame) {
57699
+ const subscription = this.#subs.get(Number(frame.sid));
57700
+ if (subscription === undefined)
57701
+ return;
57702
+ const headers = "headers" in frame ? relayHeaders(frame.headers) : undefined;
57703
+ if (headers === undefined) {
57704
+ this.#logOnce(`${session}\x00headers`, `the listener's relay socket for ${session} sent a msg whose headers are not a map of names to lists of strings; it is dropped`);
57705
+ return;
57706
+ }
57707
+ const reply = "reply" in frame && typeof frame.reply === "string" ? frame.reply : undefined;
57708
+ subscription.push({
57709
+ subject: String(frame.subject),
57710
+ data: Buffer.from(String(frame.data), "base64"),
57711
+ ...reply === undefined ? {} : { reply },
57712
+ headers
57713
+ });
57142
57714
  return;
57143
57715
  }
57144
- send(frame.reply, "received");
57145
- if (frame.gap && !gapTold)
57146
- tellGap("retention_gap");
57147
- gapTold = false;
57148
- if (frame.streamID !== streamID) {
57149
- if (streamID !== undefined && (written !== undefined || held.size > 0)) {
57150
- tellGap("stream_recreated");
57151
- } else if (streamID === undefined) {
57152
- tellReplacedResume(frame.streamID);
57716
+ if (frame.op !== "err" || !("code" in frame))
57717
+ return;
57718
+ const code = String(frame.code);
57719
+ const subscription = "sid" in frame ? this.#subs.get(Number(frame.sid)) : undefined;
57720
+ if (subscription !== undefined && SUBSCRIPTION_REFUSALS[code] === true) {
57721
+ this.#subs.delete(subscription.sid);
57722
+ subscription.fail(new LoggableError(`the listener's relay socket refused the subject ${subscription.subject} (${code})`));
57723
+ this.#logOnce(`${session}\x00${code}\x00${subscription.subject}`, `the listener's relay socket for ${session} refused the subject ${subscription.subject} (${code}); that subscription is closed`);
57724
+ return;
57725
+ }
57726
+ const known = ERR_CODES[code] === true;
57727
+ const shown = code.length > 64 ? `${code.slice(0, 64)}\u2026` : code;
57728
+ this.#logOnce(`${session}\x00${known ? code : "another code"}`, known ? `the listener's relay socket for ${session} answered ${code}` : `the listener's relay socket for ${session} answered ${shown}, a code this client does not know; later unknown codes are not logged`);
57729
+ }
57730
+ #socketClosed(generation, session, socket, { end, why, refusal, failure }) {
57731
+ if (this.#socket === socket)
57732
+ this.#socket = undefined;
57733
+ if (generation !== this.#generation || this.#closedForGood)
57734
+ return;
57735
+ this.#stopTimers();
57736
+ const dropped = new LoggableError(`the listener's relay socket closed (${why})`);
57737
+ for (const pong of this.#pongs.splice(0))
57738
+ pong.reject(dropped);
57739
+ if ("closed" in end)
57740
+ this.#emit("disconnect");
57741
+ if (tokenCaused(end))
57742
+ this.#options.credential.stale?.(session, this.#presented);
57743
+ const delay = this.#reopenAfter(end);
57744
+ if ("closed" in end) {
57745
+ this.#closedWith = end.closed;
57746
+ const closed = end.closed === CLOSE_BAD_FRAME ? `${why}: one of the frames sent since its last pong, ${[...this.#sentSincePong.keys()].join(", ") || "none"}` : why;
57747
+ this.#options.log(`the listener's relay socket for ${session} closed (${closed}); it opens again in ${delay} ms`);
57748
+ return;
57749
+ }
57750
+ const said = failure.replace(/^WebSocket connection to '[^']*' failed: /, "");
57751
+ this.#failed(session, end.refused !== undefined ? `the listener refused the upgrade with HTTP ${end.refused}` : refusal ?? `the socket closed before it opened (${why}${said === "" ? "" : `: ${said}`})`, delay);
57752
+ }
57753
+ #reopenAfter(end) {
57754
+ const run = relayRun(end);
57755
+ const streak = this.#streaks.get(run) ?? 0;
57756
+ this.#streaks.set(run, streak + 1);
57757
+ const delay = relayReopenDelay(end, streak);
57758
+ clearTimeout(this.#reopenTimer);
57759
+ this.#reopenTimer = setTimeout(() => this.#open(), delay);
57760
+ return delay;
57761
+ }
57762
+ }
57763
+ async function connectListenerRelay(options, signal) {
57764
+ const relay = new ListenerRelay(options);
57765
+ try {
57766
+ await relay.opened(signal);
57767
+ } catch (error) {
57768
+ await relay.close();
57769
+ throw error;
57770
+ }
57771
+ return relay;
57772
+ }
57773
+
57774
+ // src/channel-connection.ts
57775
+ var import_nats4 = __toESM(require_mod4(), 1);
57776
+ var START_STOPPING = "the channel server stopped before its NATS subscriptions reached the server";
57777
+ function sessionAdmission(first) {
57778
+ let current = first;
57779
+ let pending;
57780
+ return {
57781
+ admit: (session) => {
57782
+ current = session;
57783
+ if (pending?.session !== session)
57784
+ return;
57785
+ pending.wait.resolve();
57786
+ pending = undefined;
57787
+ },
57788
+ admitted: (session) => {
57789
+ if (session === current)
57790
+ return Promise.resolve();
57791
+ if (pending?.session !== session) {
57792
+ pending = { session, wait: Promise.withResolvers() };
57793
+ }
57794
+ return pending.wait.promise;
57795
+ }
57796
+ };
57797
+ }
57798
+ function admittingMoves(admission, identity) {
57799
+ return (follow) => follow === undefined || admission === undefined ? undefined : async () => {
57800
+ const forSession = identity.id;
57801
+ await follow();
57802
+ admission.admit(forSession);
57803
+ };
57804
+ }
57805
+ var CREDENTIAL_NAMES = {
57806
+ broker: "the session's broker token",
57807
+ seed: "an nkey seed",
57808
+ none: "no credential"
57809
+ };
57810
+ var CHANNEL_DIAL_PLAN = {
57811
+ ...NATS_DIAL_PLAN,
57812
+ budgetMs: Number.POSITIVE_INFINITY
57813
+ };
57814
+ async function dialChannelNats(inbound, name, warn, dial = import_nats4.connect, signal, plan = CHANNEL_DIAL_PLAN, waits = {}) {
57815
+ const stopped = Promise.withResolvers();
57816
+ const onAbort = () => stopped.resolve("stopping");
57817
+ if (signal?.aborted === true)
57818
+ onAbort();
57819
+ signal?.addEventListener("abort", onAbort);
57820
+ const unlessStopped = async (waited) => {
57821
+ const outcome = await Promise.race([
57822
+ waited.then((value) => ({ value }), (error) => ({ error })),
57823
+ stopped.promise
57824
+ ]);
57825
+ if (outcome === "stopping")
57826
+ throw new Error(START_STOPPING);
57827
+ if ("error" in outcome)
57828
+ throw outcome.error;
57829
+ return outcome.value;
57830
+ };
57831
+ try {
57832
+ const { natsCredential } = inbound;
57833
+ const failed = (error) => natsDialFailure(natsServersForLog(inbound.natsServersSetting, inbound.natsUrls.length), error, CREDENTIAL_NAMES[natsCredential.kind]);
57834
+ const broker = natsCredential.kind === "broker" ? natsCredential.broker : undefined;
57835
+ await unlessStopped(broker?.ready({ life: signal ?? new AbortController().signal }) ?? Promise.resolve());
57836
+ const dialing = connectNats(dial, natsConnectionOptions({ servers: inbound.natsUrls, name, credential: natsCredential }), plan, {
57837
+ ...waits,
57838
+ stopped: () => signal?.aborted === true,
57839
+ credential: natsCredential,
57840
+ onTokenDropped: (error, attempt) => warn(`${NATS_DIAL_TOKEN_DROPPED} (dial ${attempt})`, error),
57841
+ onRetry: (error, delayMs) => warn(`${failed(error)}; dialing again in ${delayMs} ms`, error)
57842
+ });
57843
+ let connection;
57844
+ try {
57845
+ connection = await unlessStopped(dialing);
57846
+ } catch (error) {
57847
+ if (signal?.aborted === true) {
57848
+ dialing.then((late) => late.close()).catch(() => {
57849
+ return;
57850
+ });
57851
+ throw new Error(START_STOPPING);
57153
57852
  }
57154
- switchStream(frame.streamID);
57155
- }
57156
- const key = `${frame.streamID}:${frame.streamSeq}`;
57157
- const first = entries.get(key);
57158
- if (first !== undefined) {
57159
- first.replies.push(frame.reply);
57160
- return;
57161
- }
57162
- const since = followedAt(frame.subject);
57163
- const unfollowed = since === undefined || frame.storedAtMs < since - FOLLOW_CLOCK_ALLOWANCE_MS;
57164
- const identity = unfollowed ? undefined : parseIdentity(frame.data);
57165
- if (unfollowed || alreadyWritten(identity)) {
57166
- send(frame.reply, "done");
57167
- written = Math.max(written ?? 0, frame.streamSeq);
57168
- return;
57853
+ throw new LoggableError(failed(error));
57169
57854
  }
57170
- held.add(frame.streamSeq);
57171
- const entry = {
57172
- frame,
57173
- identity,
57174
- late: frame.delivered > 1 || frame.storedAtMs < currentEpoch.startedAt,
57175
- replies: [frame.reply],
57176
- key,
57177
- stopProgress: () => {
57178
- return;
57179
- },
57180
- settled: false
57181
- };
57182
- entry.stopProgress = repeat(RELAY_PROGRESS_INTERVAL_MS, () => {
57183
- if (entry.settled)
57184
- return;
57185
- for (const reply of entry.replies)
57186
- send(reply, "progress");
57187
- });
57188
- entries.set(key, entry);
57189
- queue.push(entry);
57190
- pump();
57191
- };
57192
- const resumePoint = () => {
57193
- if (streamID === undefined)
57194
- return;
57195
- if (held.size > 0)
57196
- return { stream_id: streamID, seq: Math.min(...held) - 1 };
57197
- return written === undefined ? undefined : { stream_id: streamID, seq: written };
57198
- };
57199
- const snapshot = () => {
57200
- const resume = resumePoint();
57855
+ if (broker === undefined)
57856
+ return { connection, stop: () => {} };
57201
57857
  return {
57202
- ...resume === undefined ? {} : { resume },
57203
- follows: Object.fromEntries(follows)
57858
+ connection,
57859
+ stop: keepNatsCredential(connection, broker, warn),
57860
+ followSession: () => followNatsCredential(connection, broker)
57204
57861
  };
57205
- };
57206
- const persist = () => {
57207
- const current = snapshot();
57208
- const serialized = JSON.stringify(current);
57209
- if (serialized === persisted)
57210
- return;
57211
- if (!options.persist(current))
57862
+ } finally {
57863
+ signal?.removeEventListener("abort", onAbort);
57864
+ }
57865
+ }
57866
+ async function dialChannelInbound(inbound, listenerUrl, session, name, warn, dial = import_nats4.connect, signal) {
57867
+ if ("natsUrls" in inbound) {
57868
+ return { ...await dialChannelNats(inbound, name, warn, dial, signal), liveView: true };
57869
+ }
57870
+ const relay = await connectListenerRelay({
57871
+ url: listenerUrl,
57872
+ session,
57873
+ credential: inbound.relayCredential,
57874
+ outage: inboundUnavailable((why) => warn(`this session's relay socket has no token: ${why}; the session starts once a trade succeeds`), () => {
57212
57875
  return;
57213
- persisted = serialized;
57214
- };
57876
+ }),
57877
+ log: (line) => warn(line)
57878
+ }, signal);
57215
57879
  return {
57216
- subject: deliverSubject(sessionID),
57217
- receive,
57218
- epoch: () => currentEpoch,
57219
- beginEpoch() {
57220
- currentEpoch = { id: newEpoch(), startedAt: now() };
57221
- return currentEpoch;
57222
- },
57223
- registration() {
57224
- const resume = resumePoint();
57225
- registeredResume = resume;
57226
- return {
57227
- consumer: true,
57228
- epoch: currentEpoch.id,
57229
- ...resume === undefined ? {} : { resume }
57230
- };
57231
- },
57232
- answered(answer) {
57233
- if (answer.stream_id !== "" && answer.stream_id !== streamID) {
57234
- tellReplacedResume(answer.stream_id);
57235
- switchStream(answer.stream_id);
57236
- }
57237
- const floor = (answer.consumer_start ?? 0) - 1;
57238
- if (answer.stream_id === streamID && floor > (written ?? -1))
57239
- written = floor;
57240
- if (answer.gap) {
57241
- tellGap("retention_gap");
57242
- gapTold = true;
57243
- }
57244
- persist();
57245
- },
57246
- followedBefore(topic, storedAtMs) {
57247
- const at = follows.get(topic);
57248
- return at !== undefined && storedAtMs >= at - FOLLOW_CLOCK_ALLOWANCE_MS;
57249
- },
57250
- setFollowed(topics) {
57251
- const at = now();
57252
- const next = new Map;
57253
- for (const topic of topics) {
57254
- if (ownsSubject(topic))
57255
- continue;
57256
- next.set(topic, follows.get(topic) ?? at);
57257
- }
57258
- follows = next;
57259
- persist();
57260
- },
57261
- persist,
57262
- resumePoint,
57263
- snapshot,
57264
- restore(restored) {
57265
- const merged = new Map(Object.entries(restored.follows));
57266
- for (const [topic, at] of follows)
57267
- if (!merged.has(topic))
57268
- merged.set(topic, at);
57269
- follows = merged;
57270
- streamID = restored.resume?.stream_id;
57271
- held = new Set;
57272
- written = restored.resume?.seq;
57273
- persisted = JSON.stringify(snapshot());
57274
- },
57275
- close() {
57276
- closed = true;
57277
- queue.length = 0;
57278
- for (const entry of [...entries.values()])
57279
- settle(entry, "nak");
57280
- blocking = undefined;
57880
+ connection: relay,
57881
+ stop: () => {},
57882
+ followSession: () => relay.follow(),
57883
+ reportOutagesTo: (outage) => relay.reportOutagesTo(outage),
57884
+ liveView: false
57885
+ };
57886
+ }
57887
+ var START_DRAIN_BOUND_MS = 2000;
57888
+ async function closeUnstartedConnection(connection) {
57889
+ await Promise.race([connection.drain().catch(() => {
57890
+ return;
57891
+ }), Bun.sleep(START_DRAIN_BOUND_MS)]);
57892
+ await connection.close().catch(() => {
57893
+ return;
57894
+ });
57895
+ }
57896
+ function channelReopener(options) {
57897
+ return async (failed) => {
57898
+ options.swapKeeper(() => {
57899
+ return;
57900
+ });
57901
+ const next = await dialChannelInbound(options.inbound, options.listenerUrl, options.session, options.name, (text, dialError) => {
57902
+ process.stderr.write(`envoy-channel: ${text}
57903
+ `);
57904
+ if (dialError !== undefined)
57905
+ failed(dialError);
57906
+ }, import_nats4.connect, options.signal);
57907
+ if (options.signal.aborted) {
57908
+ next.stop();
57909
+ next.connection.close().catch(() => {
57910
+ return;
57911
+ });
57912
+ throw new Error(START_STOPPING);
57281
57913
  }
57914
+ options.swapKeeper(next.stop);
57915
+ options.useConnection(next.connection);
57916
+ const followSession = options.admitting(next.followSession);
57917
+ return {
57918
+ connection: next.connection,
57919
+ ...followSession === undefined ? {} : { followSession },
57920
+ ...next.reportOutagesTo === undefined ? {} : { reportOutagesTo: next.reportOutagesTo }
57921
+ };
57282
57922
  };
57283
57923
  }
57284
- var GAP_NOTICE_NAMES = {
57285
- retention_gap: "messages may be missing",
57286
- stream_recreated: "stream recreated"
57287
- };
57288
- function gapNoticeFields(notice) {
57289
- return { notice: GAP_NOTICE_NAMES[notice.kind], detail: notice.message };
57924
+
57925
+ // src/claude-session.ts
57926
+ function configuredValue(value) {
57927
+ return value !== undefined && value.trim().length > 0 ? value : undefined;
57290
57928
  }
57291
- function gapNoticeText(notice) {
57292
- return envoyNoticeText(gapNoticeFields(notice));
57929
+ function configuredSessionId(environment) {
57930
+ return configuredValue(environment.ENVOY_SESSION_ID) ?? configuredValue(environment.CLAUDE_CODE_SESSION_ID);
57293
57931
  }
57294
- function inboundUnavailableNoticeText(why) {
57295
- return envoyNoticeText({
57296
- notice: "Envoy inbound unavailable",
57297
- error: why,
57298
- 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."
57299
- });
57932
+ function claudeSessionId(environment) {
57933
+ const id = configuredSessionId(environment);
57934
+ if (id !== undefined)
57935
+ return id;
57936
+ throw new Error("Envoy channel requires ENVOY_SESSION_ID or CLAUDE_CODE_SESSION_ID; Claude Code did not provide a session identity");
57300
57937
  }
57301
- function inboundRestoredNoticeText() {
57938
+ function claudeProjectDirectory(environment, fallback) {
57939
+ return configuredValue(environment.CLAUDE_PROJECT_DIR) ?? fallback;
57940
+ }
57941
+
57942
+ // src/envoy-channel-server.ts
57943
+ import { unwatchFile, watchFile } from "fs";
57944
+ import { rm as rm2 } from "fs/promises";
57945
+ import { setImmediate as nextTurn } from "timers/promises";
57946
+
57947
+ // ../envoy-client/src/relay-registration.ts
57948
+ function refusedTopicsNoticeText(topics, reason) {
57302
57949
  return envoyNoticeText({
57303
- notice: "Envoy inbound restored",
57304
- detail: "The listener accepted this session's registration and gave it its durable consumer, so Envoy messages reach it again, the ones the stream stored during the outage first."
57950
+ notice: "Envoy topics refused",
57951
+ topics: topics.join(", "),
57952
+ reason,
57953
+ detail: "The listener delivers to this session only the topics of its token's projects, so it refused these, and this session no longer follows them. Every other topic it follows stays followed and goes on being delivered."
57305
57954
  });
57306
57955
  }
57307
- function inboundUnavailable(tell, restored) {
57308
- let told = false;
57309
- return {
57310
- refused(error) {
57311
- if (told)
57312
- return;
57313
- told = true;
57314
- tell(messageFor(error));
57315
- },
57316
- accepted() {
57317
- if (!told)
57318
- return;
57319
- told = false;
57320
- restored();
57321
- }
57322
- };
57956
+ var PROJECT_TOPIC_REFUSALS = ["topic_not_in_project", "repository_not_in_project"];
57957
+ function projectRefusedTopics(error, topics, ownAgentSubject) {
57958
+ if (!(error instanceof EnvoyApiError) || error.details.status !== 403)
57959
+ return;
57960
+ const reason = PROJECT_TOPIC_REFUSALS.find((refusal) => refusal === error.reason);
57961
+ if (reason === undefined)
57962
+ return;
57963
+ const refused = new Set(error.refused ?? []);
57964
+ const named = topics.filter((topic) => topic !== ownAgentSubject && expandSubscriptionTopics([topic]).some((form) => refused.has(form)));
57965
+ return named.length === 0 ? undefined : { reason, topics: named };
57323
57966
  }
57324
57967
 
57325
57968
  class NoRelaySubjectError extends Error {
57326
57969
  }
57327
- function registerWithRelay({
57970
+ async function registerWithRelay({
57328
57971
  relay,
57329
57972
  relayMissing,
57330
57973
  ownAgentSubject,
@@ -57332,23 +57975,38 @@ function registerWithRelay({
57332
57975
  roles,
57333
57976
  outage,
57334
57977
  send,
57335
- answered
57978
+ answered,
57979
+ drop,
57980
+ log
57336
57981
  }) {
57337
57982
  if (relay === undefined) {
57338
57983
  const refused = new NoRelaySubjectError(`this session holds no relay subject, so the listener can give it no consumer and it can receive nothing${relayMissing === undefined ? "" : `, because its relay subject could not be opened: ${relayMissing}`}`);
57339
57984
  outage.refused(refused);
57340
- return Promise.reject(refused);
57985
+ throw refused;
57341
57986
  }
57342
- const topics = registrationTopics(ownAgentSubject, followed, roles);
57987
+ let topics = registrationTopics(ownAgentSubject, followed(), roles);
57343
57988
  relay.setFollowed(topics);
57344
- return send(topics, relay.registration()).then((result) => {
57989
+ for (;; ) {
57990
+ let result;
57991
+ try {
57992
+ result = await send(topics, relay.registration());
57993
+ } catch (error) {
57994
+ const refused = projectRefusedTopics(error, topics, ownAgentSubject);
57995
+ if (refused === undefined) {
57996
+ outage.refused(error);
57997
+ throw error;
57998
+ }
57999
+ drop(refused.topics, refused.reason);
58000
+ log(`the listener refused ${refused.topics.join(", ")} for this session's projects (${refused.reason}); the session no longer follows them and registers the rest`);
58001
+ relay.unfollow(refused.topics);
58002
+ const still = new Set(registrationTopics(ownAgentSubject, followed(), roles));
58003
+ topics = topics.filter((topic) => !refused.topics.includes(topic) && still.has(topic));
58004
+ continue;
58005
+ }
57345
58006
  outage.accepted();
57346
58007
  answered(result);
57347
58008
  return result;
57348
- }, (error) => {
57349
- outage.refused(error);
57350
- throw error;
57351
- });
58009
+ }
57352
58010
  }
57353
58011
 
57354
58012
  // ../envoy-client/src/slack-post.ts
@@ -58025,7 +58683,7 @@ var import_nats5 = __toESM(require_mod4(), 1);
58025
58683
 
58026
58684
  // package.json
58027
58685
  var name2 = "@sjawhar/claude-envoy";
58028
- var version2 = "4.21.1";
58686
+ var version2 = "4.22.0";
58029
58687
  var legion = {
58030
58688
  daemonApiVersion: 202
58031
58689
  };
@@ -58805,7 +59463,7 @@ function controlSubscription(options) {
58805
59463
  retry.unref();
58806
59464
  };
58807
59465
  function subscribe() {
58808
- if (stopped || connection.isClosed())
59466
+ if (stopped || options.liveView === false || connection.isClosed())
58809
59467
  return;
58810
59468
  subscription?.unsubscribe();
58811
59469
  const forSession = options.session();
@@ -58871,6 +59529,7 @@ function startAgentStream(options) {
58871
59529
  connection: options.connection,
58872
59530
  session: () => session,
58873
59531
  ...options.admitted === undefined ? {} : { admitted: options.admitted },
59532
+ ...options.liveView === undefined ? {} : { liveView: options.liveView },
58874
59533
  warn,
58875
59534
  answer: answerControl
58876
59535
  });
@@ -63724,6 +64383,7 @@ async function startChannelSession(options) {
63724
64383
  `);
63725
64384
  });
63726
64385
  });
64386
+ options.reportOutagesTo?.(inboundOutage);
63727
64387
  let stampedTitle;
63728
64388
  let stampFailureReported = false;
63729
64389
  const register = async () => {
@@ -63763,7 +64423,7 @@ async function startChannelSession(options) {
63763
64423
  relay: asking?.delivery,
63764
64424
  ...relayMissing === undefined ? {} : { relayMissing },
63765
64425
  ownAgentSubject: directSubject,
63766
- followed: followedTopics.topics(),
64426
+ followed: () => followedTopics.topics(),
63767
64427
  roles: heldRole === undefined ? [] : [heldRole],
63768
64428
  outage: inboundOutage,
63769
64429
  send: (topics, deliveryRequest) => {
@@ -63795,7 +64455,26 @@ async function startChannelSession(options) {
63795
64455
  answered: (result) => {
63796
64456
  if (asking !== undefined)
63797
64457
  takeDeliveryAnswer(sessionID, asking, result);
63798
- }
64458
+ },
64459
+ drop: (topics, reason) => {
64460
+ if (identity.id !== sessionID)
64461
+ return;
64462
+ for (const topic of topics)
64463
+ userTopics.delete(topic);
64464
+ followedTopics.unfollow(topics);
64465
+ ledger.followedChanged().catch((error) => {
64466
+ process.stderr.write(`envoy-channel: the topics the listener refused stay in the delivery state until it is written next \u2014 ${messageFor(error)}
64467
+ `);
64468
+ });
64469
+ if (shuttingDown)
64470
+ return;
64471
+ delivery.notice(refusedTopicsNoticeText(topics, reason)).catch((noticeError) => {
64472
+ process.stderr.write(`envoy-channel: the session could not be told which topics the listener refused \u2014 ${messageFor(noticeError)}
64473
+ `);
64474
+ });
64475
+ },
64476
+ log: (line) => process.stderr.write(`envoy-channel: ${line}
64477
+ `)
63799
64478
  });
63800
64479
  };
63801
64480
  const writeRoleRecord = (file, role) => writePersistedRole(file, {
@@ -64151,6 +64830,7 @@ async function startChannelSession(options) {
64151
64830
  }
64152
64831
  connection = live;
64153
64832
  followSession = reopened.followSession;
64833
+ reopened.reportOutagesTo?.(inboundOutage);
64154
64834
  if (relay !== undefined && !handoffDeliveryPending)
64155
64835
  subscribeRelay(relay);
64156
64836
  watchConnection(live);
@@ -64604,9 +65284,9 @@ async function runEnvoyChannelServer() {
64604
65284
  stampOnce(() => identity.id);
64605
65285
  session = inboundOffChannelSession({ identity, stateDirectory, why: inbound.off });
64606
65286
  } else {
64607
- starting = inbound.natsCredential.kind === "broker" ? "it waits for this session's broker token, and its stderr says what each trade came to" : "it connects to NATS";
65287
+ starting = "relaySetting" in inbound ? "it opens the listener's relay socket for this session, and its stderr says why an open failed" : inbound.natsCredential.kind === "broker" ? "it waits for this session's broker token, and its stderr says what each trade came to" : "it connects to NATS";
64608
65288
  const natsName = `claude-envoy-channel-${identity.id}`;
64609
- const dialled = await dialChannelNats(inbound, natsName, (text, dialError) => {
65289
+ const dialled = await dialChannelInbound(inbound, envoy.url, currentSessionId, natsName, (text, dialError) => {
64610
65290
  if (dialError !== undefined)
64611
65291
  starting = text;
64612
65292
  process.stderr.write(`envoy-channel: ${text}
@@ -64626,6 +65306,8 @@ async function runEnvoyChannelServer() {
64626
65306
  const followSession = admitting(dialled.followSession);
64627
65307
  const reopen = channelReopener({
64628
65308
  inbound,
65309
+ listenerUrl: envoy.url,
65310
+ session: currentSessionId,
64629
65311
  name: natsName,
64630
65312
  signal: booting.signal,
64631
65313
  swapKeeper: (stop) => {
@@ -64655,6 +65337,7 @@ async function runEnvoyChannelServer() {
64655
65337
  ...stamping ? { stampTitle } : {},
64656
65338
  ...configuredValue(overrideSessionId) === undefined ? { handoffPid: process.ppid } : {},
64657
65339
  ...followSession === undefined ? {} : { followSession },
65340
+ ...dialled.reportOutagesTo === undefined ? {} : { reportOutagesTo: dialled.reportOutagesTo },
64658
65341
  adopted: (previous, next) => agentStream?.sessionAdopted(previous, next),
64659
65342
  reopen,
64660
65343
  startSignal: booting.signal
@@ -64672,6 +65355,7 @@ async function runEnvoyChannelServer() {
64672
65355
  return;
64673
65356
  agentStream = startAgentStream({
64674
65357
  connection,
65358
+ liveView: dialled.liveView,
64675
65359
  followsSessionId: configuredValue(overrideSessionId) === undefined,
64676
65360
  ...admission === undefined ? {} : { admitted: (id) => admission.admitted(id) },
64677
65361
  isPane: inbox !== undefined,
@@ -64741,6 +65425,7 @@ function startCodexAgentStream(options) {
64741
65425
  connection: options.connection,
64742
65426
  session: () => session,
64743
65427
  ...options.admitted === undefined ? {} : { admitted: options.admitted },
65428
+ ...options.liveView === undefined ? {} : { liveView: options.liveView },
64744
65429
  warn,
64745
65430
  answer: answerControl
64746
65431
  });
@@ -66368,7 +67053,7 @@ async function runCodexEnvoyServer() {
66368
67053
  session = inboundOffChannelSession({ identity: id, stateDirectory, why: inbound.off });
66369
67054
  } else {
66370
67055
  const natsName = `codex-envoy-channel-${id.id}`;
66371
- const dialled = await dialChannelNats(inbound, natsName, warn, import_nats6.connect, stopping.signal).catch((error) => {
67056
+ const dialled = await dialChannelInbound(inbound, envoy.url, () => id.id, natsName, warn, import_nats6.connect, stopping.signal).catch((error) => {
66372
67057
  if (isStopping)
66373
67058
  return;
66374
67059
  throw error;
@@ -66384,6 +67069,8 @@ async function runCodexEnvoyServer() {
66384
67069
  const followSession = admitting(dialled.followSession);
66385
67070
  const reopen = channelReopener({
66386
67071
  inbound,
67072
+ listenerUrl: envoy.url,
67073
+ session: () => id.id,
66387
67074
  name: natsName,
66388
67075
  signal: stopping.signal,
66389
67076
  swapKeeper: (stop) => {
@@ -66406,6 +67093,7 @@ async function runCodexEnvoyServer() {
66406
67093
  heartbeatMs: envoy.heartbeatMs,
66407
67094
  identity: id,
66408
67095
  ...followSession === undefined ? {} : { followSession },
67096
+ ...dialled.reportOutagesTo === undefined ? {} : { reportOutagesTo: dialled.reportOutagesTo },
66409
67097
  notifier: {
66410
67098
  notification: ({ content, eventId }) => codexDelivery.deliver({ content, ...eventId === undefined ? {} : { eventId } })
66411
67099
  },
@@ -66443,6 +67131,7 @@ async function runCodexEnvoyServer() {
66443
67131
  session = started;
66444
67132
  stream = startCodexAgentStream({
66445
67133
  connection,
67134
+ liveView: dialled.liveView,
66446
67135
  sessionId: id.id,
66447
67136
  warn,
66448
67137
  ...admission === undefined ? {} : { admitted: (next) => admission.admitted(next) }