@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.
@@ -14052,6 +14052,7 @@ var IDEMPOTENCY_KEY_HEADER = "Idempotency-Key";
14052
14052
  var IDEMPOTENCY_REPLAYED_HEADER = "Idempotency-Replayed";
14053
14053
  var IDEMPOTENCY_KEY_MAX = 128;
14054
14054
  var IDEMPOTENCY_KEY_PATTERN = new RegExp(`^[A-Za-z0-9._:-]{1,${IDEMPOTENCY_KEY_MAX}}$`);
14055
+ var IDEMPOTENCY_KEY_REUSED = "KEY_REUSED";
14055
14056
  var IDEMPOTENCY_KEY_IN_FLIGHT = "KEY_IN_FLIGHT";
14056
14057
  var IDEMPOTENCY_KEY_COMMITTED = "KEY_COMMITTED";
14057
14058
  var IDEMPOTENCY_ANSWER_NOT_KEPT = "ANSWER_NOT_KEPT";
@@ -19217,7 +19218,8 @@ var EnvoySectionSchema = strictObject({
19217
19218
  natsUrls: array(string2().trim().min(1, "must not be empty")).optional(),
19218
19219
  token: string2().optional(),
19219
19220
  natsSeed: string2().optional(),
19220
- natsAuth: string2().optional()
19221
+ natsAuth: string2().optional(),
19222
+ inbound: string2().optional()
19221
19223
  });
19222
19224
  var EnvoyFileSchema = looseObject({
19223
19225
  $schema: string2().optional(),
@@ -19675,7 +19677,7 @@ class DispatchWriteUnsettledError extends Error {
19675
19677
  attempts;
19676
19678
  key;
19677
19679
  name = "DispatchWriteUnsettledError";
19678
- constructor(last, attempts, key, unanswered, keyed = false) {
19680
+ constructor(last, attempts, key, unanswered) {
19679
19681
  let answer;
19680
19682
  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";
19681
19683
  if (last instanceof DispatchGatewayError) {
@@ -19690,10 +19692,7 @@ class DispatchWriteUnsettledError extends Error {
19690
19692
  why = "an attempt of the write may have reached Dispatch";
19691
19693
  }
19692
19694
  const tried = attempts === 1 ? "its only attempt" : `the last of ${attempts} attempts`;
19693
- 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.";
19694
- super(`${answer} (${tried}), and ${why}, so it may or may not have taken effect${next}`, {
19695
- cause: last
19696
- });
19695
+ 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 });
19697
19696
  this.last = last;
19698
19697
  this.attempts = attempts;
19699
19698
  this.key = key;
@@ -19782,43 +19781,6 @@ function retryAfterMs(response) {
19782
19781
  const at = Date.parse(value);
19783
19782
  return Number.isNaN(at) ? 0 : Math.max(0, at - Date.now());
19784
19783
  }
19785
- var KEYED_LAYER_MEMORY_MS = 5 * 60000;
19786
- var KEYED_LAYER_SEEN = new Map;
19787
- var KEYED_LAYER_PROBES = new Map;
19788
- var KEY_LAYER_PROBE_MS = 5000;
19789
- function keyedLayerMemory() {
19790
- const wall = Date.now();
19791
- const now = performance.now();
19792
- const kept = {};
19793
- for (const [origin, seen] of KEYED_LAYER_SEEN) {
19794
- const age = now - seen;
19795
- if (age >= 0 && age < KEYED_LAYER_MEMORY_MS) {
19796
- kept[origin] = new Date(wall - age).toISOString();
19797
- }
19798
- }
19799
- return kept;
19800
- }
19801
- function rememberKeyedLayer(saved) {
19802
- if (typeof saved !== "object" || saved === null)
19803
- return;
19804
- const wall = Date.now();
19805
- const now = performance.now();
19806
- for (const [origin, at] of Object.entries(saved)) {
19807
- if (typeof at !== "string")
19808
- continue;
19809
- const age = wall - Date.parse(at);
19810
- if (!(age >= 0 && age < KEYED_LAYER_MEMORY_MS))
19811
- continue;
19812
- const seen = now - age;
19813
- const known = KEYED_LAYER_SEEN.get(origin);
19814
- if (known === undefined || known < seen)
19815
- KEYED_LAYER_SEEN.set(origin, seen);
19816
- }
19817
- }
19818
- function keyEchoed(response, key) {
19819
- const echoed = response.headers.get(IDEMPOTENCY_KEY_HEADER)?.trim() ?? "";
19820
- return echoed.replace(/^"(.*)"$/, "$1") === key;
19821
- }
19822
19784
  var STREAMED_BODY_MIN = 1 << 20;
19823
19785
  var STREAMED_BODY_CHUNK = 64 << 10;
19824
19786
  function attemptBody(body, headers, progress) {
@@ -19857,17 +19819,18 @@ function parsedJson(response, text) {
19857
19819
  }
19858
19820
  }
19859
19821
  var NULL_BODY_STATUSES = new Set([101, 204, 205, 304]);
19860
- async function writeAnswer(response, echoed) {
19822
+ async function writeAnswer(response) {
19861
19823
  if (NULL_BODY_STATUSES.has(response.status)) {
19862
19824
  return {
19863
19825
  response,
19864
- echoed,
19865
19826
  malformed: false,
19866
19827
  notJson: false,
19867
19828
  text: "",
19868
19829
  json: undefined,
19869
19830
  code: undefined,
19870
- error: undefined
19831
+ error: undefined,
19832
+ replayed: response.headers.get(IDEMPOTENCY_REPLAYED_HEADER)?.trim() === "?1",
19833
+ keyEcho: response.headers.get(IDEMPOTENCY_KEY_HEADER) ?? undefined
19871
19834
  };
19872
19835
  }
19873
19836
  const text = await response.text();
@@ -19877,23 +19840,27 @@ async function writeAnswer(response, echoed) {
19877
19840
  const own = typeof shape.error === "string";
19878
19841
  return {
19879
19842
  response,
19880
- echoed,
19881
19843
  malformed: text !== "" && typed && json === undefined,
19882
19844
  notJson: text === "" || !typed,
19883
19845
  text,
19884
19846
  json,
19885
19847
  code: own ? shape.code : undefined,
19886
- error: own ? shape.error : undefined
19848
+ error: own ? shape.error : undefined,
19849
+ replayed: response.headers.get(IDEMPOTENCY_REPLAYED_HEADER)?.trim() === "?1",
19850
+ keyEcho: response.headers.get(IDEMPOTENCY_KEY_HEADER) ?? undefined
19887
19851
  };
19888
19852
  }
19889
- function answerEvent(answer, canTellDeadToken, layerKnown) {
19853
+ function isStoredKeyStatus(status) {
19854
+ return status >= 400 && status < 500 && status !== 401 && status !== 408 && status !== 429;
19855
+ }
19856
+ function answerEvent(answer, requestKey, keyEchoed, canTellDeadToken) {
19890
19857
  const { status } = answer.response;
19891
19858
  if (status >= 200 && status < 300) {
19892
19859
  if (answer.notJson)
19893
19860
  return "foreign-2xx";
19894
19861
  if (answer.malformed)
19895
19862
  return "body-malformed";
19896
- return !answer.echoed && layerKnown ? "foreign-2xx" : "applied";
19863
+ return keyEchoed && answer.keyEcho !== requestKey ? "foreign-2xx" : "applied";
19897
19864
  }
19898
19865
  if (status >= 300 && status < 400)
19899
19866
  return "redirect";
@@ -19908,7 +19875,13 @@ function answerEvent(answer, canTellDeadToken, layerKnown) {
19908
19875
  return "in-flight";
19909
19876
  return status >= 500 ? "server-error" : "try-later";
19910
19877
  }
19911
- return answer.echoed ? "judged" : "unjudged";
19878
+ if (answer.replayed || answer.code === IDEMPOTENCY_KEY_COMMITTED)
19879
+ return "judged";
19880
+ if (answer.keyEcho !== requestKey || !isStoredKeyStatus(status))
19881
+ return "unjudged";
19882
+ if (answer.code === IDEMPOTENCY_KEY_REUSED)
19883
+ return "judged";
19884
+ return answer.code === IDEMPOTENCY_KEY_IN_FLIGHT ? "unjudged" : "judged";
19912
19885
  }
19913
19886
  function credentialEvent(error) {
19914
19887
  return error instanceof TradeRetryingError ? "no-credential" : "no-credential-final";
@@ -20494,7 +20467,7 @@ class DispatchClient {
20494
20467
  key: key ?? crypto.randomUUID(),
20495
20468
  request: `${method} ${requestForText(this.#baseUrl, url, DISPATCH_URL_SETTING)}`,
20496
20469
  writes,
20497
- progress: { sent: 0, running: false, sawKeyedLayer: false }
20470
+ progress: { sent: 0, running: false, keyEchoed: false }
20498
20471
  };
20499
20472
  }
20500
20473
  async#upload(path, input, key) {
@@ -20512,12 +20485,12 @@ class DispatchClient {
20512
20485
  form.set("file", input.file, input.name);
20513
20486
  return this.#form("POST", path, form, key);
20514
20487
  }
20515
- async#form(method, path, form, key) {
20488
+ async#form(method, path, form, callerKey) {
20516
20489
  const url = this.#url(path);
20517
20490
  const encoded = new Response(form);
20518
20491
  const type = encoded.headers.get("Content-Type") ?? "multipart/form-data";
20519
20492
  const body = { content: new Uint8Array(await encoded.arrayBuffer()), type };
20520
- const write = this.#writeCall(method, url, key);
20493
+ const write = this.#writeCall(method, url, callerKey);
20521
20494
  if (write !== undefined) {
20522
20495
  const answer = await this.#write(method, url, body, "application/json", undefined, write);
20523
20496
  return this.#payloadOf(method, url, answer);
@@ -20602,14 +20575,12 @@ class DispatchClient {
20602
20575
  sent
20603
20576
  };
20604
20577
  }
20605
- const echoed = keyEchoed(response, key);
20606
- const heard = { echoed, retryAfterMs: retryAfterMs(response) };
20607
- if (echoed)
20608
- KEYED_LAYER_SEEN.set(this.#baseUrl, this.#now());
20609
- progress.sawKeyedLayer ||= echoed;
20578
+ const heard = { retryAfterMs: retryAfterMs(response) };
20579
+ if (response.headers.get(IDEMPOTENCY_KEY_HEADER) === key)
20580
+ progress.keyEchoed = true;
20610
20581
  let answer;
20611
20582
  try {
20612
- answer = await writeAnswer(response, echoed);
20583
+ answer = await writeAnswer(response);
20613
20584
  } catch (error) {
20614
20585
  const stop = stoppedEvent(limit, true, error);
20615
20586
  return {
@@ -20621,7 +20592,7 @@ class DispatchClient {
20621
20592
  };
20622
20593
  }
20623
20594
  return {
20624
- event: answerEvent(answer, this.#credential.stale !== undefined && !deadTokenTold, progress.sawKeyedLayer || this.#remembersKeyedLayer()),
20595
+ event: answerEvent(answer, write.key, progress.keyEchoed, this.#credential.stale !== undefined && !deadTokenTold),
20625
20596
  answer,
20626
20597
  presented,
20627
20598
  sent,
@@ -20686,16 +20657,7 @@ class DispatchClient {
20686
20657
  const scheduled = progress.running ? Math.min(pausesMs[paced - 1] ?? inFlightPauseMs, inFlightPauseMs) : pausesMs[paced - 1];
20687
20658
  const wait = Math.max(scheduled ?? 0, last.heard?.retryAfterMs ?? 0);
20688
20659
  const latest = Math.min(started + (progress.running ? inFlightWithinMs : withinMs), lastAsk);
20689
- let again = scheduled !== undefined && this.#now() + wait <= latest;
20690
- const { answer } = last;
20691
- const unjudged = answer !== undefined && !answer.echoed && answer.error !== undefined;
20692
- if (again && state === "may-have-landed") {
20693
- again = (last.heard?.echoed ?? false) || await this.#runsKeyedLayer(unjudged);
20694
- progress.sawKeyedLayer ||= again;
20695
- again &&= this.#now() + wait <= latest;
20696
- } else if (unjudged && state === "nothing-sent") {
20697
- KEYED_LAYER_SEEN.delete(this.#baseUrl);
20698
- }
20660
+ const again = scheduled !== undefined && this.#now() + wait <= latest;
20699
20661
  if (!again) {
20700
20662
  event = "exhausted";
20701
20663
  continue;
@@ -20719,10 +20681,6 @@ class DispatchClient {
20719
20681
  }
20720
20682
  }
20721
20683
  }
20722
- #remembersKeyedLayer() {
20723
- const seen = KEYED_LAYER_SEEN.get(this.#baseUrl);
20724
- return seen !== undefined && this.#now() - seen < KEYED_LAYER_MEMORY_MS;
20725
- }
20726
20684
  #credentialSignal(limit) {
20727
20685
  return credentialDeadline(limit, Math.max(1, this.#deadlineAt - performance.now()));
20728
20686
  }
@@ -20760,7 +20718,7 @@ class DispatchClient {
20760
20718
  let own = failure;
20761
20719
  if (answer?.response.ok === true) {
20762
20720
  const { status } = answer.response;
20763
- 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`);
20721
+ 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`);
20764
20722
  } else if (answer !== undefined) {
20765
20723
  own = event === "no-route" && routeSpent ? new DispatchNoRouteError : this.#payloadOrError(method, url, answer);
20766
20724
  }
@@ -20792,39 +20750,7 @@ class DispatchClient {
20792
20750
  unanswered = `${request} failed on its last attempt (${last.message})`;
20793
20751
  }
20794
20752
  }
20795
- return new DispatchWriteUnsettledError(last, progress.sent, write.key, unanswered, progress.sawKeyedLayer);
20796
- }
20797
- async#runsKeyedLayer(unjudged) {
20798
- const origin = this.#baseUrl;
20799
- if (unjudged)
20800
- KEYED_LAYER_SEEN.delete(origin);
20801
- const seen = KEYED_LAYER_SEEN.get(origin);
20802
- if (seen !== undefined && this.#now() - seen < KEYED_LAYER_MEMORY_MS)
20803
- return true;
20804
- let probe = KEYED_LAYER_PROBES.get(origin);
20805
- if (probe === undefined) {
20806
- probe = this.#probeKeyedLayer().finally(() => KEYED_LAYER_PROBES.delete(origin));
20807
- KEYED_LAYER_PROBES.set(origin, probe);
20808
- }
20809
- const runs = await probe;
20810
- if (runs)
20811
- KEYED_LAYER_SEEN.set(origin, this.#now());
20812
- return runs;
20813
- }
20814
- async#probeKeyedLayer() {
20815
- try {
20816
- const response = await this.#fetch(`${this.#baseUrl}/healthz`, {
20817
- method: "GET",
20818
- headers: { Accept: "application/json" },
20819
- signal: AbortSignal.any([this.#signal, AbortSignal.timeout(KEY_LAYER_PROBE_MS)])
20820
- });
20821
- if (!isJson(response))
20822
- return false;
20823
- const health = await response.json();
20824
- return typeof health === "object" && health !== null && Reflect.get(health, "idempotency_keys") === true;
20825
- } catch {
20826
- return false;
20827
- }
20753
+ return new DispatchWriteUnsettledError(last, progress.sent, write.key, unanswered);
20828
20754
  }
20829
20755
  #url(path, query) {
20830
20756
  const url = new URL(`${path.map((segment) => encodeURIComponent(segment)).join("/")}`, `${this.#baseUrl}/`);
@@ -29879,6 +29805,7 @@ function resolvedInterval(raw, fallback) {
29879
29805
  const named = namedInterval(raw);
29880
29806
  return named === undefined ? fallback : Math.min(Math.max(named, MIN_INTERVAL_MS), MAX_INTERVAL_MS);
29881
29807
  }
29808
+ var ENVOY_INBOUND_VAR = "ENVOY_INBOUND";
29882
29809
  function natsSeedFromEnvironment(env) {
29883
29810
  const { NATS_NKEY_SEED_FILE: file, NATS_NKEY_SEED: plain } = env;
29884
29811
  if (file !== undefined) {
@@ -29948,6 +29875,33 @@ function natsCredential(env, section, namedNatsUrls, filePath, session) {
29948
29875
  throw new NoSessionNamedError(auth.source);
29949
29876
  return { kind: "broker", broker: brokerNatsCredential(env, session, auth.source) };
29950
29877
  }
29878
+ var LOOPBACK_HOST = /^(localhost|127(\.\d{1,3}){3}|\[::1\])$/i;
29879
+ function natsConflictText(source, natsSetting) {
29880
+ return `${source} is listener, and ${natsSetting} names NATS servers: set one of the two`;
29881
+ }
29882
+ function listenerInbound(source, natsSetting, credential, session) {
29883
+ if (natsSetting !== undefined)
29884
+ return { off: natsConflictText(source, natsSetting) };
29885
+ if ("noBrokerRoute" in credential) {
29886
+ return { off: `${source} is listener, but ${credential.noBrokerRoute}` };
29887
+ }
29888
+ if (credential.scheme !== "DPoP") {
29889
+ return {
29890
+ 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`
29891
+ };
29892
+ }
29893
+ if (session === undefined) {
29894
+ return {
29895
+ off: `${source} is listener, but this process names no session for its relay socket's token`,
29896
+ noSessionNamed: true
29897
+ };
29898
+ }
29899
+ return { relaySetting: source, relayCredential: credential };
29900
+ }
29901
+ function plainHttpOffMachine(url) {
29902
+ const host = URL.canParse(url) ? new URL(url) : undefined;
29903
+ return host?.protocol === "http:" && !LOOPBACK_HOST.test(host.hostname) ? host.hostname : undefined;
29904
+ }
29951
29905
  function envoySettings(env, config, options = {}) {
29952
29906
  if (config.kind === "failed")
29953
29907
  return offWithError(config.error);
@@ -29966,7 +29920,18 @@ function envoySettings(env, config, options = {}) {
29966
29920
  }
29967
29921
  const listener = section.url ?? DEFAULT_ENVOY_URL;
29968
29922
  const url = namedUrl ?? listener;
29923
+ const namedInbound = nonEmpty(env.ENVOY_INBOUND);
29924
+ const choice = namedInbound !== undefined ? { value: namedInbound, source: ENVOY_INBOUND_VAR } : section.inbound === undefined ? undefined : { value: section.inbound, source: `envoy.inbound in ${config.path}` };
29925
+ const natsSetting = namedNatsUrls.length > 0 ? "ENVOY_NATS_URL" : (section.natsUrls ?? []).length > 0 ? `envoy.natsUrls in ${config.path}` : undefined;
29926
+ if (choice?.value === "listener") {
29927
+ const host = plainHttpOffMachine(url);
29928
+ if (host !== undefined) {
29929
+ 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`;
29930
+ return offWithError(natsSetting === undefined ? `${choice.source} is listener, but ${plainHttp}` : `${natsConflictText(choice.source, natsSetting)}. And ${plainHttp}`);
29931
+ }
29932
+ }
29969
29933
  let credential;
29934
+ let noBrokerRoute = "";
29970
29935
  try {
29971
29936
  const source = bearerSource(env, "ENVOY", () => section.token === undefined ? undefined : {
29972
29937
  token: section.token,
@@ -29976,7 +29941,10 @@ function envoySettings(env, config, options = {}) {
29976
29941
  checkout: false
29977
29942
  });
29978
29943
  if (source.kind === "none") {
29979
- credential = brokerRouteConfigured(env).traded ? brokerCredential(env, options.session) : undefined;
29944
+ const route = brokerRouteConfigured(env);
29945
+ credential = route.traded ? brokerCredential(env, options.session) : undefined;
29946
+ if (!route.traded)
29947
+ noBrokerRoute = route.gap;
29980
29948
  } else {
29981
29949
  credential = bearerCredential(source.kind === "variable" ? source.token : fileBearer(source, url, "ENVOY", env));
29982
29950
  }
@@ -29987,13 +29955,17 @@ function envoySettings(env, config, options = {}) {
29987
29955
  let inbound;
29988
29956
  if (options.nats === false)
29989
29957
  inbound = { off: NO_NATS_CONNECTION };
29990
- else if (natsUrls.length === 0)
29958
+ else if (choice !== undefined && choice.value !== "nats" && choice.value !== "listener") {
29959
+ inbound = { off: `${choice.source} is neither nats nor listener` };
29960
+ } else if (choice?.value === "listener") {
29961
+ inbound = listenerInbound(choice.source, natsSetting, credential ?? { noBrokerRoute }, options.session);
29962
+ } else if (natsSetting === undefined)
29991
29963
  inbound = { off: NO_NATS_SERVER };
29992
29964
  else {
29993
29965
  try {
29994
29966
  inbound = {
29995
29967
  natsUrls,
29996
- natsServersSetting: namedNatsUrls.length > 0 ? "ENVOY_NATS_URL" : `envoy.natsUrls in ${config.path}`,
29968
+ natsServersSetting: natsSetting,
29997
29969
  natsCredential: natsCredential(env, section, namedNatsUrls, config.path, options.session)
29998
29970
  };
29999
29971
  } catch (error) {
@@ -30070,6 +30042,9 @@ function startNotice(config, dispatch, envoy, nats, lost) {
30070
30042
  if (envoy.enabled && nats && "off" in envoy.inbound) {
30071
30043
  parts.push(`Envoy's inbound messages are off: ${envoy.inbound.off}; the Envoy tools still work`);
30072
30044
  }
30045
+ if (envoy.enabled && nats && "relaySetting" in envoy.inbound) {
30046
+ 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`);
30047
+ }
30073
30048
  if (envoy.enabled && envoy.passDeadlineRaisedFrom !== undefined) {
30074
30049
  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`);
30075
30050
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sjawhar/claude-envoy",
3
- "version": "4.21.1",
3
+ "version": "4.22.0",
4
4
  "license": "Apache-2.0",
5
5
  "description": "Claude Code plugin for Legion's Envoy bus",
6
6
  "type": "module",
@@ -61,6 +61,10 @@ export interface AgentStreamOptions {
61
61
  * subjects, and the new control subject is taken at once.
62
62
  */
63
63
  readonly admitted?: (session: string) => Promise<void>
64
+ /** Whether a viewer can take this session: false over the listener's relay socket, which
65
+ * carries no agent stream (`ControlSubscriptionOptions.liveView`). The mod's events still
66
+ * reach `observe`. True by default. */
67
+ readonly liveView?: boolean
64
68
  /** Whether this session is a Legion pane, whose first command the daemon's bridge writes
65
69
  * rather than a person (`./agent-stream-claude`, `PANE_SEEDED_COMMAND`). */
66
70
  readonly isPane?: boolean
@@ -151,6 +155,7 @@ export function startAgentStream(options: AgentStreamOptions): AgentStreamRunner
151
155
  connection: options.connection,
152
156
  session: () => session,
153
157
  ...(options.admitted === undefined ? {} : { admitted: options.admitted }),
158
+ ...(options.liveView === undefined ? {} : { liveView: options.liveView }),
154
159
  warn,
155
160
  answer: answerControl,
156
161
  })
@@ -1,10 +1,15 @@
1
- // The NATS connection a channel server holds for its session, over the session's life: dialed with
2
- // the session's credential and redialed until it opens (`dialChannelNats`), admitted as one session
3
- // id at a time where it presents the session's broker token (`sessionAdmission`,
4
- // `admittingMoves`), replaced once it closes for good (`channelReopener`), and closed with a bound
5
- // where no session took it (`closeUnstartedConnection`). Both channel servers take theirs from
6
- // here: Claude Code's (`./envoy-channel-server`) and Codex's (`./codex/codex-server`).
1
+ // The inbound connection a channel server holds for its session, over the session's life: NATS,
2
+ // dialed with the session's credential and redialed until it opens (`dialChannelNats`), or the
3
+ // listener's relay socket where the settings say `ENVOY_INBOUND=listener` (`dialChannelInbound`);
4
+ // admitted as one session id at a time where it presents the session's broker token
5
+ // (`sessionAdmission`, `admittingMoves`), replaced once it closes for good (`channelReopener`),
6
+ // and closed with a bound where no session took it (`closeUnstartedConnection`). Both channel
7
+ // servers take theirs from here: Claude Code's (`./envoy-channel-server`) and Codex's
8
+ // (`./codex/codex-server`).
9
+ import type { RequestCredential } from "@legion/envoy-client/bearer"
10
+ import { inboundUnavailable } from "@legion/envoy-client/consumer-delivery"
7
11
  import { LoggableError } from "@legion/envoy-client/errors"
12
+ import { connectListenerRelay, type RelayOutage } from "@legion/envoy-client/listener-relay"
8
13
  import {
9
14
  connectNats,
10
15
  NATS_DIAL_PLAN,
@@ -121,6 +126,16 @@ export interface ChannelNatsSettings {
121
126
  readonly natsCredential: NatsCredential
122
127
  }
123
128
 
129
+ /** What `dialChannelInbound` opens the listener's relay socket with (`EnvoyInbound` where
130
+ * `ENVOY_INBOUND=listener`): the setting that chose it, and the session's broker credential. */
131
+ export interface ChannelRelaySettings {
132
+ readonly relaySetting: string
133
+ readonly relayCredential: RequestCredential
134
+ }
135
+
136
+ /** How a server takes its session's inbound messages (`EnvoyInbound` where they are on). */
137
+ export type ChannelInboundSettings = ChannelNatsSettings | ChannelRelaySettings
138
+
124
139
  /**
125
140
  * Opens the session's NATS connection with the credential `inbound` resolved. A broker token is
126
141
  * signed into the CONNECT itself, so a live one is taken before the dial; and the connection is
@@ -231,6 +246,77 @@ export async function dialChannelNats(
231
246
  }
232
247
  }
233
248
 
249
+ /** The channel server's inbound connection, over NATS or the listener's relay socket
250
+ * (`dialChannelInbound`). */
251
+ export interface ChannelInbound {
252
+ readonly connection: ChannelConnection
253
+ /** Stops the keeper of a NATS connection's broker token; nothing for the others. */
254
+ readonly stop: () => void
255
+ /** The move a `/clear` or a `/new` runs before the new id's relay subject opens, where the
256
+ * connection is admitted as one session at a time: a NATS connection presenting the session's
257
+ * broker token (`followNatsCredential`), and the relay socket, which is opened for one session
258
+ * with that session's own token (`ListenerRelay.follow`). */
259
+ readonly followSession?: () => Promise<void>
260
+ /** Has a refused trade of the connection's own told `outage`, the session's, rather than the
261
+ * report it was opened with: the relay socket's (`ListenerRelay.reportOutagesTo`); absent for
262
+ * NATS, which trades no token of its own outside the keeper. */
263
+ readonly reportOutagesTo?: (outage: RelayOutage) => void
264
+ /** Whether the session's live view takes its control subject on the connection: never over the
265
+ * relay socket, which carries no agent stream (`ControlSubscriptionOptions.liveView`). */
266
+ readonly liveView: boolean
267
+ }
268
+
269
+ /**
270
+ * Opens the session's inbound as its settings say: NATS (`dialChannelNats`, `dial` its `connect`),
271
+ * or the relay socket of the listener at `listenerUrl` for the session `session` names now, with
272
+ * the session's broker credential (`connectListenerRelay`), answered once its first socket is
273
+ * open. The socket opens again on its own after a close for the server's life, warning on `warn`
274
+ * why an open failed; a token the broker refused is told on `warn` until the session holds the
275
+ * socket and tells its own outage (`ListenerRelay.reportOutagesTo`), which the session's first
276
+ * accepted registration ends. `signal` aborting (the process is stopping) ends either wait at once.
277
+ */
278
+ export async function dialChannelInbound(
279
+ inbound: ChannelInboundSettings,
280
+ listenerUrl: string,
281
+ session: () => string,
282
+ name: string,
283
+ warn: (text: string, dialError?: unknown) => void,
284
+ dial: (options: ConnectionOptions) => Promise<NatsConnection> = connect,
285
+ signal?: AbortSignal,
286
+ ): Promise<ChannelInbound> {
287
+ if ("natsUrls" in inbound) {
288
+ return { ...(await dialChannelNats(inbound, name, warn, dial, signal)), liveView: true }
289
+ }
290
+ const relay = await connectListenerRelay(
291
+ {
292
+ url: listenerUrl,
293
+ session,
294
+ credential: inbound.relayCredential,
295
+ // The socket's report until the session holds it (`reportOutagesTo`): before the session
296
+ // starts there is no session to tell, so a refused trade is said once on stderr, worded
297
+ // (`inboundUnavailable`), however many trades fail. The socket tries the trade again on its
298
+ // own, 1 s doubling to a minute; once one succeeds the socket opens and the session starts,
299
+ // and nothing tells the session of the refusals before.
300
+ outage: inboundUnavailable(
301
+ (why) =>
302
+ warn(
303
+ `this session's relay socket has no token: ${why}; the session starts once a trade succeeds`,
304
+ ),
305
+ () => undefined,
306
+ ),
307
+ log: (line) => warn(line),
308
+ },
309
+ signal,
310
+ )
311
+ return {
312
+ connection: relay,
313
+ stop: () => {},
314
+ followSession: () => relay.follow(),
315
+ reportOutagesTo: (outage) => relay.reportOutagesTo(outage),
316
+ liveView: false,
317
+ }
318
+ }
319
+
234
320
  /** How long a start that failed waits for its connection to drain before closing it. */
235
321
  const START_DRAIN_BOUND_MS = 2_000
236
322
 
@@ -251,15 +337,22 @@ export interface ReopenedConnection {
251
337
  readonly connection: ChannelConnection
252
338
  /** `ChannelSessionOptions.followSession`, for this connection. */
253
339
  readonly followSession?: () => Promise<void>
340
+ /** `ChannelSessionOptions.reportOutagesTo`, for this connection. */
341
+ readonly reportOutagesTo?: (outage: RelayOutage) => void
254
342
  }
255
343
 
256
- /** Opens a new NATS connection in place of one closed for good (`ChannelSessionOptions.reopen`). */
344
+ /** Opens a new inbound connection in place of one closed for good
345
+ * (`ChannelSessionOptions.reopen`). */
257
346
  export type ReopenConnection = (failed: (dialError: unknown) => void) => Promise<ReopenedConnection>
258
347
 
259
348
  /** What a server hands `channelReopener`. */
260
349
  export interface ChannelReopenerOptions {
261
- /** What the server's first connection was dialed with. */
262
- readonly inbound: ChannelNatsSettings
350
+ /** What the server's first connection was opened with. */
351
+ readonly inbound: ChannelInboundSettings
352
+ /** The listener a relay socket is opened at (`EnabledEnvoySettings.url`). */
353
+ readonly listenerUrl: string
354
+ /** The session id the server holds now, which a relay socket is opened for. */
355
+ readonly session: () => string
263
356
  /** The connection name every connection of the server presents. */
264
357
  readonly name: string
265
358
  /** Aborts when the server stops: it ends a dial's waits and its redials, and closes a connection
@@ -276,8 +369,10 @@ export interface ChannelReopenerOptions {
276
369
 
277
370
  /**
278
371
  * A server's `ChannelSessionOptions.reopen`: a new connection once the session's closed for good,
279
- * dialed as the server's first one was, warning of each redial on stderr, until one opens or the
280
- * server stops. The closed connection's token keeper stops before the dial, and the new one's is
372
+ * opened as the server's first one was (`dialChannelInbound`), warning of each redial on stderr,
373
+ * until one opens or the server stops. A relay socket opens again on its own after every close, so
374
+ * it closes for good only as the server closes it; a NATS connection is what this replaces in a
375
+ * running session. The closed connection's token keeper stops before the dial, and the new one's is
281
376
  * the one the teardown stops; the live view moves to the new connection. Under a broker token the
282
377
  * new connection presents the token the session's credential holds as it dials, the one traded
283
378
  * last (a lapsed one is traded again for the id the session has now): through a `/clear`, the old
@@ -292,8 +387,10 @@ export interface ChannelReopenerOptions {
292
387
  export function channelReopener(options: ChannelReopenerOptions): ReopenConnection {
293
388
  return async (failed) => {
294
389
  options.swapKeeper(() => undefined)
295
- const next = await dialChannelNats(
390
+ const next = await dialChannelInbound(
296
391
  options.inbound,
392
+ options.listenerUrl,
393
+ options.session,
297
394
  options.name,
298
395
  (text, dialError) => {
299
396
  process.stderr.write(`envoy-channel: ${text}\n`)
@@ -313,6 +410,7 @@ export function channelReopener(options: ChannelReopenerOptions): ReopenConnecti
313
410
  return {
314
411
  connection: next.connection,
315
412
  ...(followSession === undefined ? {} : { followSession }),
413
+ ...(next.reportOutagesTo === undefined ? {} : { reportOutagesTo: next.reportOutagesTo }),
316
414
  }
317
415
  }
318
416
  }
@@ -1,50 +1,37 @@
1
- import type { RelayHeaders } from "@legion/envoy-client/consumer-delivery"
2
1
  import { DedupeIdentitySchema } from "@legion/envoy-client/delivery"
3
2
  import { natsFailureReason } from "@legion/envoy-client/errors"
3
+ import type {
4
+ InboundConnection,
5
+ InboundMessage,
6
+ InboundStatus,
7
+ InboundSubscription,
8
+ } from "@legion/envoy-client/inbound-connection"
4
9
  import { expandSubscriptionTopics } from "@legion/envoy-client/transport"
5
10
  import { z } from "zod"
6
11
 
7
- /** A message as the broker yields it (a nats.js `Msg` satisfies this). */
8
- export interface ChannelBrokerMessage {
9
- readonly subject: string
10
- readonly data: Uint8Array
11
- /**
12
- * The message's reply subject. Two kinds of message carry one: a relay frame, whose reply is
13
- * the relay's own answer token (`RelayMessage`, consumer delivery), and a request on the live
14
- * view's control subject, answered there (`./agent-stream-runner`). No Envoy envelope is
15
- * answered on a reply: a session publishes no receipt.
16
- */
17
- readonly reply?: string
18
- /** The message's NATS headers; only a relay frame (consumer delivery) carries any read here. */
19
- readonly headers?: RelayHeaders
20
- }
12
+ /**
13
+ * A message as the connection yields it (a nats.js `Msg`, or a relay socket's). Two kinds carry a
14
+ * reply: a relay frame, whose reply is the relay's own answer token (`RelayMessage`, consumer
15
+ * delivery), and a request on the live view's control subject, answered there
16
+ * (`./agent-stream-runner`). No Envoy envelope is answered on a reply: a session publishes no
17
+ * receipt. Only a relay frame carries headers read here.
18
+ */
19
+ export type ChannelBrokerMessage = InboundMessage
21
20
 
22
- export interface ChannelTopicSubscription extends AsyncIterable<ChannelBrokerMessage> {
23
- unsubscribe(): void
24
- }
21
+ /** A subscription of the channel session's connection. */
22
+ export type ChannelTopicSubscription = InboundSubscription
25
23
 
26
- /** A nats.js connection status event; only its `type` is read. */
27
- export interface ChannelConnectionStatus {
28
- readonly type: string
29
- }
24
+ /** A status event of the channel session's connection; only its `type` is read. */
25
+ export type ChannelConnectionStatus = InboundStatus
30
26
 
31
- /** The NATS connection surface a channel session holds. */
32
- export interface ChannelConnection {
33
- /** Subscribes one subject. A channel session opens two: the session's relay subject, where
34
- * every Envoy message arrives, and the live view's control subject, which a viewer takes
35
- * the session on (`./agent-stream-runner`). */
36
- subscribe(subject: string): ChannelTopicSubscription
37
- publish(subject: string, data: Uint8Array): void
38
- flush(): Promise<void>
39
- isClosed(): boolean
40
- drain(): Promise<void>
41
- close(): Promise<void>
42
- /** The connection's status events (nats.js `status()`), which end when it closes. */
43
- status(): AsyncIterable<ChannelConnectionStatus>
44
- /** Settles once the connection is closed for good, with the error that closed it, if any
45
- * (nats.js `closed()`); already settled for one closed before the call. */
46
- closed(): Promise<unknown>
47
- }
27
+ /**
28
+ * The inbound connection a channel session holds, NATS or the listener's relay socket
29
+ * (`@legion/envoy-client/inbound-connection`). Over NATS a channel session opens two
30
+ * subscriptions on it: the session's relay subject, where every Envoy message arrives, and the
31
+ * live view's control subject, which a viewer takes the session on (`./agent-stream-runner`). Over
32
+ * the relay socket it opens the relay subject alone: the socket carries no live view.
33
+ */
34
+ export type ChannelConnection = InboundConnection
48
35
 
49
36
  /**
50
37
  * The topics this session follows, and the broker connection it holds now. Nothing is subscribed