@sjawhar/claude-envoy 6.13.0 → 6.14.1

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.
@@ -37255,6 +37255,11 @@ var COMMENT_ARGUMENT = "Comment id (uuid), or a dispatch://KEY/comment/<id> or "
37255
37255
  var MESSAGE_ARGUMENT = "Message id (uuid), or a dispatch://KEY/message/<id> reference; a reference accepts an " + "8+ character id prefix that is unique on its owner.";
37256
37256
  var ASK_BOUND_RULE = "Dispatch bounds an ask's question and its options together, refuses a longer one and names " + "the bound, and `dispatch limits` prints it. An ask is short and asks one thing; its reasoning " + "goes in the document, not in the question.";
37257
37257
  var DISPATCH_HANDOFF_BODY_MAX = 262144;
37258
+ var STEP_RESULTS = ["passed", "failed", "stopped"];
37259
+ var PLANNED_STEP_STATES = ["not started", "running", ...STEP_RESULTS];
37260
+ var STEP_TASK_MAX = 64;
37261
+ var STEP_TASK_PATTERN = new RegExp(`^[a-z0-9][a-z0-9-]{0,${STEP_TASK_MAX - 1}}$`);
37262
+ var STEP_TASK_RULE_WORDS = `lowercase letters, digits and hyphens, starting with a letter or a digit, at most ${STEP_TASK_MAX} bytes`;
37258
37263
  var HANDOFF_PHASE_PATTERN = /^[a-z][a-z0-9-]{0,31}$/;
37259
37264
  var HANDOFF_PHASE_RULE_WORDS = "a lowercase letter, then up to 31 lowercase letters, digits or hyphens, such as implement";
37260
37265
  var HANDOFF_PHASE_RULE = `phase is not a handoff phase: ${HANDOFF_PHASE_RULE_WORDS}`;
@@ -38110,7 +38115,7 @@ var dispatchToolSpecs = [
38110
38115
  {
38111
38116
  name: "dispatch_steps",
38112
38117
  example: { issue: "DSP-1" },
38113
- description: "Print each step that ran on an issue, as the Legion daemon recorded it at the step's " + "start and at its end, and the experiment and the variant the issue was drawn into, where " + "its records name one. The first line is `<KEY>: <n> steps in <m> tasks`. Where the " + "records of the issue's newest run name an experiment, the next line is `Experiment " + "<experiment>: variant <variant>.`, and an issue whose newest run's records name none " + "prints no such line. Then each run of a step prints one line, task by task, in the order " + "each task first ran: `<task> " + "<step> <kind> <role> <type> attempt <attempt> <agent> <model> <started_at> <ended_at> " + "<result>`. kind is step, retro or merge. step is the step's place in its task, from 1, " + "and 0 for a retro or a merge. attempt counts the runs of the same task, step and kind, " + "from 1. agent is the claim of the role that ran the step, and model is the model that " + "answered it, as provider/model. result is passed, failed or stopped. A field with no " + "value prints -, and a run that has not ended prints running for its end and its result. " + "A closed issue's steps read too. An issue that no step ran on prints 0 steps in 0 tasks, " + "and a key Dispatch does not hold fails as dispatch read fails for it, NOT_FOUND: not " + `found. ${ISSUE_REFERENCE}`,
38118
+ description: "Print each task of an issue's plan and each step that ran on the issue, as the Legion " + "daemon recorded it at the step's start and at its end, and the experiment and the " + "variant the issue was drawn into, where its records name one. The first line is " + "`<KEY>: <n> steps in <m> tasks`, where m counts each task listed, a task of the plan " + "with no run included. Where the records of the issue's newest run name an experiment, " + "the next line is `Experiment <experiment>: variant <variant>.`, and an issue whose " + "newest run's records name none prints no such line. The tasks of the issue's newest " + "plan come first, in the plan's order, then each other task with a run, in the order " + "each first ran. A task of the plan prints `task <task> needs <needs>: <place> <step> " + "<state>, ...`: needs is the tasks it needs as a list, [a,b], [] where it needs none, " + "and - where its plan node recorded none, then each step the plan gives it, where state " + "is where Dispatch says it stands among the records of the plan's own run: not started, " + "running, or the result of its newest run there. Then each run of a step of the task " + "prints one line: `<task> " + "<step> <kind> <role> <type> attempt <attempt> <agent> <model> <started_at> <ended_at> " + "<result>`. kind is step, retro or merge. step is the step's place in its task, from 1, " + "and 0 for a retro or a merge. attempt counts the runs of the same task, step and kind, " + "from 1. agent is the claim of the role that ran the step, and model is the model that " + "answered it, as provider/model. result is passed, failed or stopped. A field with no " + "value prints -, and a run that has not ended prints running for its end and its result. " + "A closed issue's steps read too. An issue that no step ran on and that has no plan prints " + "0 steps in 0 tasks, and a key Dispatch does not hold fails as dispatch read fails for it, " + `NOT_FOUND: not found. ${ISSUE_REFERENCE}`,
38114
38119
  arguments: (z) => ({
38115
38120
  issue: z.string().describe(ISSUE_REFERENCE)
38116
38121
  }),
@@ -41982,6 +41987,7 @@ var SESSION_LIVE_WINDOW_MS = 300000;
41982
41987
  var LISTENER_CALL_TIMEOUT_MS = 5000;
41983
41988
  var LISTENER_CALL_RETRY_DELAY_MS = 250;
41984
41989
  var LISTENER_CALL_ATTEMPTS = 2;
41990
+ var BUS_UNANSWERED_PREFIX = "envoy: the message bus did not answer";
41985
41991
  // ../contracts/src/related-forms.ts
41986
41992
  function relatedCheckFormOf(suggestions) {
41987
41993
  const { outcome, missing } = suggestions;
@@ -60381,6 +60387,11 @@ function stepLine(record) {
60381
60387
  ...record.ended_at === null ? ["running", "running"] : [record.ended_at, orDash(record.result)]
60382
60388
  ].join(" ");
60383
60389
  }
60390
+ function taskLine(task, needs, planned) {
60391
+ const states = planned.map((step) => `${step.step} ${step.name} ${step.state}`);
60392
+ const needed = needs === null ? "-" : `[${needs.join(",")}]`;
60393
+ return `task ${task} needs ${needed}: ${states.join(", ")}`;
60394
+ }
60384
60395
  function variantLines(records) {
60385
60396
  const newest = Math.max(...records.map((record) => record.generation));
60386
60397
  const named = records.find((record) => record.generation === newest && record.experiment != null && record.variant != null);
@@ -60389,13 +60400,20 @@ function variantLines(records) {
60389
60400
  async function stepsCommand(context) {
60390
60401
  const { client, issue } = context;
60391
60402
  const read = await client.listSteps(issue());
60392
- const tasks = (read.tasks ?? []).map((task) => ({ task: task.task, steps: task.steps ?? [] }));
60403
+ const tasks = (read.tasks ?? []).map((task) => ({ ...task, steps: task.steps ?? [] }));
60393
60404
  const records = tasks.flatMap((task) => task.steps);
60405
+ const lines = tasks.flatMap((task) => {
60406
+ const runs = task.steps.map(stepLine);
60407
+ const planned = task.planned ?? [];
60408
+ if (planned.length === 0)
60409
+ return runs;
60410
+ return [taskLine(task.task, task.needs ?? null, planned), ...runs];
60411
+ });
60394
60412
  return {
60395
60413
  text: [
60396
60414
  `${read.issue}: ${records.length} steps in ${tasks.length} tasks`,
60397
60415
  ...variantLines(records),
60398
- ...records.map(stepLine)
60416
+ ...lines
60399
60417
  ].join(`
60400
60418
  `),
60401
60419
  details: { issue: read.issue, tasks }
@@ -60869,6 +60887,8 @@ function keepNatsCredential(connection, credential, warn) {
60869
60887
  if (credential.needsReconnect())
60870
60888
  await connection.reconnect();
60871
60889
  } catch (error) {
60890
+ if (stopped)
60891
+ return;
60872
60892
  if (error instanceof SessionMovedError) {
60873
60893
  schedule(0);
60874
60894
  return;
@@ -61602,6 +61622,9 @@ class EnvoyApiError extends Error {
61602
61622
  this.notSent = notSentAnswer && shown.afterUnanswered !== true;
61603
61623
  }
61604
61624
  }
61625
+ function isBusUnanswered(error) {
61626
+ return error instanceof EnvoyApiError && error.details.status === 503 && error.message.startsWith(BUS_UNANSWERED_PREFIX);
61627
+ }
61605
61628
  var mintedDedupeKey2 = new RegExp(MINTED_DEDUPE_KEY_PATTERN);
61606
61629
 
61607
61630
  class EnvoySendUnconfirmedError extends Error {
@@ -61624,6 +61647,28 @@ class EnvoySendUnconfirmedError extends Error {
61624
61647
  this.resendSafe = resendSafe;
61625
61648
  }
61626
61649
  }
61650
+ var STOP_GATE = {
61651
+ subscribe: "refused",
61652
+ unsubscribe: "refused",
61653
+ getInterest: "refused",
61654
+ setRole: "refused",
61655
+ getRole: "refused",
61656
+ unregisterSession: "sent",
61657
+ handBack: "sent",
61658
+ send: "sent",
61659
+ publish: "sent",
61660
+ listSessions: "sent"
61661
+ };
61662
+
61663
+ class EnvoyStoppingError extends Error {
61664
+ call;
61665
+ name = "EnvoyStoppingError";
61666
+ constructor(call, method, url) {
61667
+ super(`this session is stopping, so it sends the listener nothing: ${method} ${url} was not sent`);
61668
+ this.call = call;
61669
+ }
61670
+ }
61671
+ var handBacks = new WeakMap;
61627
61672
  function resolveCallTiming(config) {
61628
61673
  return {
61629
61674
  timeoutMs: config.timeoutMs ?? LISTENER_CALL_TIMEOUT_MS,
@@ -61647,7 +61692,9 @@ function createEnvoyClient(config) {
61647
61692
  }
61648
61693
  };
61649
61694
  const noAnswer = (method, url, error) => new Error(`${method ?? "GET"} ${shown(url)} got no answer: ${errorClass(error)}`);
61650
- const attemptOnce = async (url, init, deadlineMs, actingSession) => {
61695
+ const attemptOnce = async (url, init, deadlineMs, actingSession, refusedByStop) => {
61696
+ if (refusedByStop())
61697
+ return { stopping: true };
61651
61698
  let response;
61652
61699
  let unminted;
61653
61700
  const deadline = AbortSignal.timeout(deadlineMs);
@@ -61663,6 +61710,8 @@ function createEnvoyClient(config) {
61663
61710
  }
61664
61711
  if (unminted !== undefined && deadline.aborted)
61665
61712
  return { notSent: unminted };
61713
+ if (refusedByStop())
61714
+ return { stopping: true };
61666
61715
  sent.note(presented);
61667
61716
  for (const [name, value] of Object.entries(presented ?? {}))
61668
61717
  headers.set(name, value);
@@ -61690,59 +61739,70 @@ function createEnvoyClient(config) {
61690
61739
  return { unanswered: noAnswer(init.method, url, error) };
61691
61740
  }
61692
61741
  };
61693
- const request = async (path, init, options = {}) => {
61742
+ const request = async (call, path, init, options = {}) => {
61694
61743
  const url = `${baseUrl}${path}`;
61695
61744
  const tries = options.retry === false ? 1 : attempts;
61745
+ const gated = STOP_GATE[call] === "refused";
61746
+ const refusedByStop = () => gated && config.stopping?.() === true;
61747
+ let busUnanswered;
61748
+ let sent = false;
61696
61749
  let unanswered = false;
61750
+ let lastEnd;
61697
61751
  for (let attempt = 0;attempt < tries; attempt += 1) {
61698
61752
  options.onAttempt?.();
61699
- const outcome = await attemptOnce(url, init, options.timeoutMs ?? timeoutMs, options.actingSession);
61753
+ const outcome = await attemptOnce(url, init, options.timeoutMs ?? timeoutMs, options.actingSession, refusedByStop);
61754
+ if ("stopping" in outcome) {
61755
+ if (sent && lastEnd !== undefined)
61756
+ throw lastEnd();
61757
+ throw new EnvoyStoppingError(call, init.method ?? "GET", shown(url));
61758
+ }
61759
+ let end;
61700
61760
  if ("unanswered" in outcome) {
61701
61761
  unanswered = true;
61702
61762
  options.onUnanswered?.();
61703
- if (attempt + 1 < tries) {
61704
- await waitForRetry(retryDelayMs);
61705
- continue;
61706
- }
61707
- throw outcome.unanswered;
61708
- }
61709
- if ("notSent" in outcome) {
61710
- if (attempt + 1 < tries) {
61711
- await waitForRetry(retryDelayMs);
61712
- continue;
61713
- }
61714
- options.onNotSent?.();
61715
- throw outcome.notSent;
61716
- }
61717
- const { response, body } = outcome;
61718
- if (response.ok)
61719
- return body;
61720
- const redacted = tokens();
61721
- const error = new EnvoyApiError({
61722
- method: init.method ?? "GET",
61723
- url: shown(url),
61724
- status: response.status,
61725
- responseBody: body
61726
- }, {
61727
- tokens: redacted,
61728
- redirectTo: redirectOrigin(response, url, redacted),
61729
- afterUnanswered: unanswered
61730
- });
61731
- if (mayHaveReachedServer(response.status)) {
61763
+ sent = true;
61764
+ end = () => busUnanswered ?? outcome.unanswered;
61765
+ } else if ("notSent" in outcome) {
61766
+ end = () => {
61767
+ options.onNotSent?.();
61768
+ return busUnanswered ?? outcome.notSent;
61769
+ };
61770
+ } else {
61771
+ const { response, body } = outcome;
61772
+ if (response.ok)
61773
+ return body;
61774
+ const redacted = tokens();
61775
+ const error = new EnvoyApiError({
61776
+ method: init.method ?? "GET",
61777
+ url: shown(url),
61778
+ status: response.status,
61779
+ responseBody: body
61780
+ }, {
61781
+ tokens: redacted,
61782
+ redirectTo: redirectOrigin(response, url, redacted),
61783
+ afterUnanswered: unanswered
61784
+ });
61785
+ if (!mayHaveReachedServer(response.status))
61786
+ throw error;
61732
61787
  if (!error.notSent) {
61733
61788
  unanswered = true;
61734
61789
  options.onUnanswered?.();
61790
+ sent = true;
61735
61791
  }
61736
- if (attempt + 1 < tries) {
61737
- await waitForRetry(retryDelayMs);
61738
- continue;
61739
- }
61792
+ if (options.busUnansweredStands === true && isBusUnanswered(error))
61793
+ busUnanswered = error;
61794
+ end = () => error.reason === undefined ? busUnanswered ?? error : error;
61740
61795
  }
61741
- throw error;
61796
+ lastEnd = end;
61797
+ if (attempt + 1 < tries) {
61798
+ await waitForRetry(retryDelayMs);
61799
+ continue;
61800
+ }
61801
+ throw end();
61742
61802
  }
61743
61803
  throw new Error("Envoy request exhausted retries");
61744
61804
  };
61745
- const post = (path, body, options) => request(path, {
61805
+ const post = (call, path, body, options) => request(call, path, {
61746
61806
  method: "POST",
61747
61807
  headers: {
61748
61808
  "Content-Type": "application/json",
@@ -61766,16 +61826,17 @@ function createEnvoyClient(config) {
61766
61826
  plugin: input.plugin.name,
61767
61827
  plugin_version: input.plugin.version
61768
61828
  });
61769
- return {
61770
- subscribe: async (input) => parseSubscribeAnswer(answerJson(await post("/v1/interests/subscribe", subscribeBody(input), { actingSession: input.sessionID }), "POST", "/v1/interests/subscribe")),
61771
- unsubscribe: async (input) => {
61772
- await post("/v1/interests/unsubscribe", {
61773
- session_id: input.sessionID,
61774
- topics: expandSubscriptionTopics(input.topics),
61775
- ...input.clientInstanceID === undefined ? {} : { client_instance_id: input.clientInstanceID }
61776
- }, { actingSession: input.sessionID });
61777
- },
61778
- getInterest: async (sessionID) => InterestWireSchema.parse(answerJson(await request(`/v1/interests/${sessionID}`, {}), "GET", `/v1/interests/${sessionID}`)),
61829
+ const removeTopics = async (call, input) => {
61830
+ await post(call, "/v1/interests/unsubscribe", {
61831
+ session_id: input.sessionID,
61832
+ topics: expandSubscriptionTopics(input.topics),
61833
+ ...input.clientInstanceID === undefined ? {} : { client_instance_id: input.clientInstanceID }
61834
+ }, { actingSession: input.sessionID, busUnansweredStands: true });
61835
+ };
61836
+ const client = {
61837
+ subscribe: async (input) => parseSubscribeAnswer(answerJson(await post("subscribe", "/v1/interests/subscribe", subscribeBody(input), { actingSession: input.sessionID, busUnansweredStands: true }), "POST", "/v1/interests/subscribe")),
61838
+ unsubscribe: (input) => removeTopics("unsubscribe", input),
61839
+ getInterest: async (sessionID) => InterestWireSchema.parse(answerJson(await request("getInterest", `/v1/interests/${sessionID}`, {}), "GET", `/v1/interests/${sessionID}`)),
61779
61840
  send: async (input) => {
61780
61841
  const idempotencyKey = input.idempotencyKey ?? crypto.randomUUID();
61781
61842
  let unanswered = false;
@@ -61783,7 +61844,7 @@ function createEnvoyClient(config) {
61783
61844
  let made = 0;
61784
61845
  let response;
61785
61846
  try {
61786
- const answer = await post("/v1/messages/send", {
61847
+ const answer = await post("send", "/v1/messages/send", {
61787
61848
  source: input.source ?? "agent",
61788
61849
  ...sourceSession(input.sourceSessionID),
61789
61850
  target_session: input.targetSessionID,
@@ -61813,19 +61874,24 @@ function createEnvoyClient(config) {
61813
61874
  throw error;
61814
61875
  throw new EnvoySendUnconfirmedError(input.targetSessionID, idempotencyKey, made, error);
61815
61876
  }
61816
- return {
61877
+ const stored = {
61817
61878
  envelope: response,
61818
61879
  recipient: response.recipient ?? input.targetSessionID,
61819
61880
  confirmed: response.recipient !== undefined,
61820
- recipientState: response.recipient_state ?? "live",
61821
- state: response.state === "stopped" ? "stopped" : "connected",
61822
61881
  ...lastSeenOf(response.last_seen),
61823
61882
  duplicate: response.duplicate === true
61824
61883
  };
61884
+ if (response.state === "no_receiver")
61885
+ return { ...stored, state: "no_receiver" };
61886
+ return {
61887
+ ...stored,
61888
+ recipientState: response.recipient_state ?? "live",
61889
+ state: response.state === "stopped" ? "stopped" : "connected"
61890
+ };
61825
61891
  },
61826
61892
  publish: async (input) => {
61827
61893
  const idempotencyKey = input.idempotencyKey ?? crypto.randomUUID();
61828
- const raw = answerJson(await post("/v1/messages/publish", {
61894
+ const raw = answerJson(await post("publish", "/v1/messages/publish", {
61829
61895
  source: input.source ?? "agent",
61830
61896
  ...sourceSession(input.sourceSessionID),
61831
61897
  topic: input.topic,
@@ -61853,7 +61919,7 @@ function createEnvoyClient(config) {
61853
61919
  },
61854
61920
  unregisterSession: async (input) => {
61855
61921
  const query = input.clientInstanceID === undefined ? "" : `?client_instance_id=${encodeURIComponent(input.clientInstanceID)}`;
61856
- await request(`/v1/sessions/${encodeURIComponent(input.sessionID)}${query}`, { method: "DELETE" }, {
61922
+ await request("unregisterSession", `/v1/sessions/${encodeURIComponent(input.sessionID)}${query}`, { method: "DELETE" }, {
61857
61923
  actingSession: input.sessionID,
61858
61924
  ...input.timeoutMs === undefined ? {} : { timeoutMs: Math.max(1, input.timeoutMs), retry: false }
61859
61925
  });
@@ -61870,7 +61936,7 @@ function createEnvoyClient(config) {
61870
61936
  };
61871
61937
  let raw;
61872
61938
  try {
61873
- raw = await post("/v1/roles/set", body, { actingSession: input.sessionID });
61939
+ raw = await post("setRole", "/v1/roles/set", body, { actingSession: input.sessionID });
61874
61940
  } catch (error) {
61875
61941
  if (error instanceof EnvoyApiError && error.details.status === 409) {
61876
61942
  let answer;
@@ -61888,7 +61954,7 @@ function createEnvoyClient(config) {
61888
61954
  const { warnings, ...interest } = RoleSetWireSchema.parse(answerJson(raw, "POST", "/v1/roles/set"));
61889
61955
  return { claimed: true, interest, warnings };
61890
61956
  },
61891
- getRole: async (role) => RoleWireSchema.parse(answerJson(await request(`/v1/roles/${encodeURIComponent(role)}`, { method: "GET" }), "GET", `/v1/roles/${encodeURIComponent(role)}`)),
61957
+ getRole: async (role) => RoleWireSchema.parse(answerJson(await request("getRole", `/v1/roles/${encodeURIComponent(role)}`, { method: "GET" }), "GET", `/v1/roles/${encodeURIComponent(role)}`)),
61892
61958
  listSessions: async (input = {}) => {
61893
61959
  const search = new URLSearchParams;
61894
61960
  if (input.directory !== undefined)
@@ -61898,9 +61964,11 @@ function createEnvoyClient(config) {
61898
61964
  if (input.include !== undefined)
61899
61965
  search.set("include", input.include);
61900
61966
  const query = search.size === 0 ? "" : `?${search.toString()}`;
61901
- return SessionWireSchema.array().parse(answerJson(await request(`/v1/sessions${query}`, {}), "GET", `/v1/sessions${query}`));
61967
+ return SessionWireSchema.array().parse(answerJson(await request("listSessions", `/v1/sessions${query}`, {}), "GET", `/v1/sessions${query}`));
61902
61968
  }
61903
61969
  };
61970
+ handBacks.set(client, (input) => removeTopics("handBack", input));
61971
+ return client;
61904
61972
  }
61905
61973
  function waitForRetry(delayMs) {
61906
61974
  const { promise, resolve } = Promise.withResolvers();
@@ -64536,6 +64604,118 @@ function createLedger(now) {
64536
64604
  };
64537
64605
  }
64538
64606
 
64607
+ // ../envoy-client/src/inbound-outage.ts
64608
+ var REPOSITORIES_UNKNOWN = "repositories_unknown";
64609
+ function refusalKind(error) {
64610
+ if (isBusUnanswered(error))
64611
+ return "unrecorded";
64612
+ if (error instanceof EnvoyApiError && error.reason === REPOSITORIES_UNKNOWN) {
64613
+ return "github_withheld";
64614
+ }
64615
+ return "refused";
64616
+ }
64617
+ var OUTAGE_DEPTH = {
64618
+ unrecorded: 0,
64619
+ github_withheld: 1,
64620
+ refused: 2,
64621
+ no_relay: 2
64622
+ };
64623
+ var NO_CONSUMER_NOTICE = {
64624
+ notice: "Envoy inbound unavailable",
64625
+ 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."
64626
+ };
64627
+ var UNAVAILABLE_NOTICES = {
64628
+ unrecorded: {
64629
+ notice: "Envoy inbound unavailable",
64630
+ detail: "This session's registration is not recorded for certain: the listener's message bus did not answer in time, so the listener may or may not have recorded it. Envoy messages may still reach the session, but nothing confirms it until a registration is accepted. Everything else works, and the session registers again at every heartbeat."
64631
+ },
64632
+ github_withheld: {
64633
+ notice: "Envoy GitHub topics withheld",
64634
+ detail: "The listener could not read the repositories of this session's projects. So it follows none of this session's GitHub topics now, and it withholds their messages. It refused this registration. If the listener already held a registration of this session, it kept that registration and the session's consumer, so the session receives the messages of every other topic the listener follows for it; a topic the session began to follow after its last accepted registration is followed only once a registration is accepted. If the listener held no registration of this session, the session receives nothing until a registration is accepted. The session registers again at every heartbeat."
64635
+ },
64636
+ refused: NO_CONSUMER_NOTICE,
64637
+ no_relay: NO_CONSUMER_NOTICE
64638
+ };
64639
+ var RECEIVES_AGAIN_NOTICE = {
64640
+ notice: "Envoy inbound restored",
64641
+ detail: "The listener accepted a registration of this session, so the session receives Envoy messages again. What the stream stored while it received nothing arrives now."
64642
+ };
64643
+ var RESTORED_NOTICES = {
64644
+ unrecorded: {
64645
+ notice: "Envoy inbound restored",
64646
+ detail: "The listener recorded a registration of this session. A message the stream stored that has not reached the session arrives now."
64647
+ },
64648
+ github_withheld: {
64649
+ notice: "Envoy GitHub topics followed again",
64650
+ detail: "The listener accepted a registration of this session, so it follows this session's GitHub topics again, and their messages reach the session again. A GitHub message the listener withheld meanwhile may be missing."
64651
+ },
64652
+ refused: RECEIVES_AGAIN_NOTICE,
64653
+ no_relay: RECEIVES_AGAIN_NOTICE
64654
+ };
64655
+ function inboundUnavailableNoticeText({ kind, why }) {
64656
+ const { notice, detail } = UNAVAILABLE_NOTICES[kind];
64657
+ return envoyNoticeText({ notice, error: why, detail });
64658
+ }
64659
+ function inboundRestoredNoticeText(kind) {
64660
+ const { notice, detail } = RESTORED_NOTICES[kind];
64661
+ return envoyNoticeText({ notice, detail });
64662
+ }
64663
+ var INBOUND_FIRST_OPEN_BOUND_MS = 120000;
64664
+ function inboundUnavailable(tell, {
64665
+ now = () => Date.now(),
64666
+ firstOpenBoundMs = INBOUND_FIRST_OPEN_BOUND_MS,
64667
+ restored,
64668
+ held,
64669
+ stopping = () => false
64670
+ } = {}) {
64671
+ let told;
64672
+ let everAccepted = false;
64673
+ let heldSince;
64674
+ let unansweredSince;
64675
+ const say = (kind, error) => {
64676
+ if (stopping())
64677
+ return;
64678
+ if (told !== undefined && OUTAGE_DEPTH[kind] <= OUTAGE_DEPTH[told.kind])
64679
+ return;
64680
+ told = { kind, why: messageFor(error) };
64681
+ tell(told);
64682
+ };
64683
+ return {
64684
+ noRelay(error, relayMissing) {
64685
+ if (!everAccepted) {
64686
+ const at = now();
64687
+ const begins = heldSince === undefined;
64688
+ heldSince ??= at;
64689
+ if (at < heldSince + firstOpenBoundMs) {
64690
+ if (begins && !stopping())
64691
+ held?.(relayMissing);
64692
+ return;
64693
+ }
64694
+ }
64695
+ say("no_relay", error);
64696
+ },
64697
+ refused(error) {
64698
+ const kind = refusalKind(error);
64699
+ if (kind === "unrecorded") {
64700
+ const at = now();
64701
+ unansweredSince ??= at;
64702
+ if (at < unansweredSince + firstOpenBoundMs)
64703
+ return;
64704
+ }
64705
+ say(kind, error);
64706
+ },
64707
+ accepted() {
64708
+ everAccepted = true;
64709
+ unansweredSince = undefined;
64710
+ const last = told;
64711
+ if (last === undefined || stopping())
64712
+ return;
64713
+ told = undefined;
64714
+ restored?.(last);
64715
+ }
64716
+ };
64717
+ }
64718
+
64539
64719
  // ../envoy-client/src/consumer-delivery.ts
64540
64720
  var DELIVER_SUBJECT_PREFIX = "notifications.envoy.deliver.";
64541
64721
  function deliverSubject(sessionID) {
@@ -64993,36 +65173,6 @@ function gapNoticeFields(notice) {
64993
65173
  function gapNoticeText(notice) {
64994
65174
  return envoyNoticeText(gapNoticeFields(notice));
64995
65175
  }
64996
- function inboundUnavailableNoticeText(why) {
64997
- return envoyNoticeText({
64998
- notice: "Envoy inbound unavailable",
64999
- error: why,
65000
- 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."
65001
- });
65002
- }
65003
- function inboundRestoredNoticeText() {
65004
- return envoyNoticeText({
65005
- notice: "Envoy inbound restored",
65006
- 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."
65007
- });
65008
- }
65009
- function inboundUnavailable(tell, restored) {
65010
- let told = false;
65011
- return {
65012
- refused(error) {
65013
- if (told)
65014
- return;
65015
- told = true;
65016
- tell(messageFor(error));
65017
- },
65018
- accepted() {
65019
- if (!told)
65020
- return;
65021
- told = false;
65022
- restored();
65023
- }
65024
- };
65025
- }
65026
65176
 
65027
65177
  // ../envoy-client/src/nats-connection.ts
65028
65178
  var import_nats2 = __toESM(require_mod4(), 1);
@@ -65670,6 +65820,10 @@ class ListenerRelay {
65670
65820
  #open() {
65671
65821
  if (this.#closedForGood)
65672
65822
  return;
65823
+ if (this.#options.stopping?.() === true) {
65824
+ this.close();
65825
+ return;
65826
+ }
65673
65827
  clearTimeout(this.#reopenTimer);
65674
65828
  this.#reopenTimer = undefined;
65675
65829
  this.#generation += 1;
@@ -65855,8 +66009,11 @@ class ListenerRelay {
65855
66009
  const subscription = "sid" in frame ? this.#subs.get(Number(frame.sid)) : undefined;
65856
66010
  if (subscription !== undefined && SUBSCRIPTION_REFUSALS[code] === true) {
65857
66011
  this.#subs.delete(subscription.sid);
65858
- subscription.fail(new LoggableError(`the listener's relay socket refused the subject ${subscription.subject} (${code})`));
66012
+ const refused = new LoggableError(`the listener's relay socket refused the subject ${subscription.subject} (${code})`);
66013
+ subscription.fail(refused);
65859
66014
  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`);
66015
+ if (subscription.subject === deliverSubject(session))
66016
+ this.#outage.refused(refused);
65860
66017
  return;
65861
66018
  }
65862
66019
  const known = ERR_CODES[code] === true;
@@ -65999,7 +66156,7 @@ async function dialChannelNats(inbound, name, warn, dial = import_nats4.connect,
65999
66156
  signal?.removeEventListener("abort", onAbort);
66000
66157
  }
66001
66158
  }
66002
- async function dialChannelInbound(inbound, listenerUrl, session, name, warn, dial = import_nats4.connect, signal) {
66159
+ async function dialChannelInbound(inbound, listenerUrl, session, name, warn, dial = import_nats4.connect, signal, stopping) {
66003
66160
  if ("natsUrls" in inbound) {
66004
66161
  return { ...await dialChannelNats(inbound, name, warn, dial, signal), liveView: true };
66005
66162
  }
@@ -66007,10 +66164,9 @@ async function dialChannelInbound(inbound, listenerUrl, session, name, warn, dia
66007
66164
  url: listenerUrl,
66008
66165
  session,
66009
66166
  credential: inbound.relayCredential,
66010
- outage: inboundUnavailable((why) => warn(`this session's relay socket has no token: ${why}; the session starts once a trade succeeds`), () => {
66011
- return;
66012
- }),
66013
- log: (line) => warn(line)
66167
+ outage: inboundUnavailable(({ why }) => warn(`this session's relay socket has no token: ${why}; the session starts once a trade succeeds`)),
66168
+ log: (line) => warn(line),
66169
+ ...stopping === undefined ? {} : { stopping }
66014
66170
  }, signal);
66015
66171
  return {
66016
66172
  connection: relay,
@@ -66035,11 +66191,10 @@ function channelReopener(options) {
66035
66191
  return;
66036
66192
  });
66037
66193
  const next = await dialChannelInbound(options.inbound, options.listenerUrl, options.session, options.name, (text, dialError) => {
66038
- process.stderr.write(`envoy-channel: ${text}
66039
- `);
66194
+ options.warn(text);
66040
66195
  if (dialError !== undefined)
66041
66196
  failed(dialError);
66042
- }, import_nats4.connect, options.signal);
66197
+ }, import_nats4.connect, options.signal, options.stopping);
66043
66198
  if (options.signal.aborted) {
66044
66199
  next.stop();
66045
66200
  next.connection.close().catch(() => {
@@ -66103,6 +66258,13 @@ function projectRefusedTopics(error, topics, ownAgentSubject) {
66103
66258
 
66104
66259
  class NoRelaySubjectError extends Error {
66105
66260
  }
66261
+
66262
+ class RegistrationStoppingError extends Error {
66263
+ name = "RegistrationStoppingError";
66264
+ constructor() {
66265
+ super("this session is stopping, so it registers nothing");
66266
+ }
66267
+ }
66106
66268
  async function registerWithRelay({
66107
66269
  relay,
66108
66270
  relayMissing,
@@ -66113,11 +66275,14 @@ async function registerWithRelay({
66113
66275
  send,
66114
66276
  answered,
66115
66277
  drop,
66116
- log
66278
+ log,
66279
+ stopping = () => false
66117
66280
  }) {
66281
+ if (stopping())
66282
+ throw new RegistrationStoppingError;
66118
66283
  if (relay === undefined) {
66119
66284
  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}`}`);
66120
- outage.refused(refused);
66285
+ outage.noRelay(refused, relayMissing);
66121
66286
  throw refused;
66122
66287
  }
66123
66288
  let topics = registrationTopics(ownAgentSubject, followed(), roles);
@@ -66128,7 +66293,7 @@ async function registerWithRelay({
66128
66293
  result = await send(topics, relay.registration());
66129
66294
  } catch (error) {
66130
66295
  const refused = projectRefusedTopics(error, topics, ownAgentSubject);
66131
- if (refused === undefined) {
66296
+ if (refused === undefined || stopping()) {
66132
66297
  outage.refused(error);
66133
66298
  throw error;
66134
66299
  }
@@ -66437,10 +66602,13 @@ function allowedAPIURL(value) {
66437
66602
  }
66438
66603
 
66439
66604
  // ../envoy-client/src/tool-contract.ts
66440
- var SESSION_STATE_GUIDE = "A session is live, unresponsive or gone, by how long ago it last registered: live within 5 " + "minutes, unresponsive after that and within an hour, gone past the hour or with no record at " + `all. ${UNRESPONSIVE_RULE} A session named with no state is live. A send answered with state ` + "stopped means that session is not running: the message is stored for it and reaches it if " + `it runs again within ${DELIVERY_DUPLICATE_WINDOW_HOURS} hours, and nothing of its claims changes.`;
66605
+ var SESSION_STATE_GUIDE = "A session is live, unresponsive or gone, by how long ago it last registered: live within 5 " + "minutes, unresponsive after that and within an hour, gone past the hour or with no record at " + `all. ${UNRESPONSIVE_RULE} A session named with no state is live. A send answered with state ` + "stopped means that session is not running: the message is stored for it and reaches it if " + `it runs again within ${DELIVERY_DUPLICATE_WINDOW_HOURS} hours, and nothing of its claims changes. ` + "A send answered with state no_receiver means that session runs but takes no message into its " + "conversation now, as a Claude Code terminal with no mod does: the message is stored for it and " + `reaches it if it takes messages within ${DELIVERY_DUPLICATE_WINDOW_HOURS} hours.`;
66441
66606
  var DELIVERY_CONTRACT = "Delivery is at-least-once, possibly out of order across topics; use id for dedupe and at for freshness.";
66442
66607
  var PUBLISH_COUNTS = "The answer counts who gets it: recipients is every session other than you that the message " + `goes to, one that is stopped and gets it when it runs again within ${DELIVERY_DUPLICATE_WINDOW_HOURS} hours included, and ` + "recipients_connected is how many of those are running now. A listener that counts neither " + "sends neither, and a role topic names its holder instead.";
66443
- var STORED_DELIVERY = `Every notification topic is stored (${STORED_TOPIC_KINDS.join(", ")}; a role message reaches ` + "its holder as a stored copy on the holder's agent topic), and reaches each subscribed session " + "once from the durable consumer its listener relays to it, also one that was away or restarted. " + "A 200 means the stream stored the message for each subscribed session's consumer, not that any " + "recipient has read it.";
66608
+ var storedDelivery = (stored, kinds) => `${stored} (${kinds.join(", ")}; a role message reaches its holder as a stored copy on the ` + "holder's agent topic), and reaches each subscribed session once from the durable consumer its " + "listener relays to it, also one that was away or restarted. A 200 means the stream stored " + "the message for each subscribed session's consumer, not that any recipient has read it.";
66609
+ var STORED_DELIVERY = storedDelivery("Every notification topic is stored", STORED_TOPIC_KINDS);
66610
+ var PUBLISH_REFUSED_KINDS = ["agent", "dispatch", "github"];
66611
+ var PUBLISHED_DELIVERY = "The listener refuses a publish to each of these topics by name, and stores nothing: an agent " + "topic, since envoy_send sends to one session; a topic under notifications.dispatch., since " + "only Dispatch publishes on Dispatch's lane; a topic under notifications.github., since only " + "the listener that receives GitHub's webhook publishes on GitHub's lane; " + "notifications.legion.wake, since only the listener reports a Legion pod wake; and a topic " + "under notifications.envoy.kept., notifications.envoy.resume. or notifications.envoy.takeover., " + `since those lanes are the listener's own. ${storedDelivery("Every other topic the stream captures is stored", STORED_TOPIC_KINDS.filter((kind) => !PUBLISH_REFUSED_KINDS.includes(kind)))}`;
66444
66612
  var NOT_SENT_GUIDE = "An error that says the message was not sent means nothing was stored, so the same message may " + "be sent again later.";
66445
66613
  var TOPIC_GUIDE = "Topic guide (all are under notifications.): agent.<session_id> (subscribe: own inbox); role.<role> " + "(publish-to; holders claim via envoy_role_set). > matches one or more trailing tokens and does not " + "match the base subject. Envoy registers the concrete base when you subscribe to <subject>.>, so " + "the recommended default remains github.<owner>.<repo>.pr.<n>.>. <owner> and <repo> are one token " + "each, with every dot in the name written _ (sjawhar/.github is github.sjawhar._github; " + "acme/site.io is github.acme.site_io), and a topic spelled with the dot receives nothing. " + "Default PR subscription: " + "github.<owner>.<repo>.pr.<n>.> (it receives the quiet PR family): pr.<n> (lifecycle: " + "opened/synchronize/closed; closed carries merged, merge_commit_sha, merged_by, head_sha), " + "pr.<n>.comment, pr.<n>.review, pr.<n>.mention, pr.<n>.checks (one settlement event per commit whose checks settle, the head or not, naming its sha: " + "passed/failed/cancelled/skipped check runs with failing names and URLs, check_runs, each check's latest run as " + "{name, id, conclusion} with conclusion GitHub's own word for that run where one is recorded (for example " + "success, skipped, neutral or timed_out; a skipped check ran nothing on that commit), and statuses, each commit status as " + "{context, state, created_at} with state success, failure or error and created_at the time GitHub created it, " + "left out when none is recorded; for each context keep the entry with the later created_at, and keep a context " + 'that a settlement leaves out as it was; re-fires with superseded_settlement: "true" ' + "when new runs appear, or a commit status is new or changes state, for the same commit). Other GitHub: issue.<n>, issue.<n>.comment, " + "issue.<n>.mention, mention, push.branch.<name>, push.tag.<name>, workflow.<file>.<action> (only " + "runs without an associated PR); slack.<team>.<channel>.message|mention and " + "slack.<team>.<channel>.thread.<ts>.message|mention; ghostwispr.<session>.<kind>; " + "whatsapp.<phone>.<jid>.<kind>; envoy.exceptions.<original-topic>.";
66446
66614
  var URGENCY_VALUES = EnvelopeSchema.shape.urgency.unwrap().options;
@@ -66524,7 +66692,7 @@ var envoyToolSpecs = [
66524
66692
  },
66525
66693
  {
66526
66694
  name: "envoy_publish",
66527
- description: `Publish an Envoy message to a notifications. topic. ${STORED_DELIVERY} A role or built-in topic is delivered as its guide says. A role message has three possible answers. First, a live session holds the role, and the stream stores the forward for that holder's consumer. Its 200 says the stream stored it. It does not say that the holder read it. It names the holder and the state the listener resolved the holder in. Second, no live session holds the role: nobody claims it, or its holder is unresponsive or gone. The listener then keeps the message for one hour. This is a success. The result says that the listener kept the message, and its kept_until is the time that hour ends. For a holder that is not live, the result also names that holder and its state. The next session to hold the role live before kept_until gets the message. That can be the same holder when it answers again. If no session takes the message by kept_until, Envoy drops it. If the publish named your session as its source, Envoy then sends your session a message that names the dropped message, unless it dropped it more than an hour late. Third, the listener keeps nothing and errs, which tells you to reach the agent some other way: the holder refuses the message, the forward is not stored within four seconds, or no live session holds the role and the publish names no session of yours as its source, so nothing could tell you that a kept copy expired. A team topic (such as notifications.team.deploy-squad.all) is stored like every other, so a session subscribed to it that was away still receives it when it returns, and one that subscribes after you publish does not. A notifications. topic no stream subject captures is refused by name: nothing would store it. ${NOT_SENT_GUIDE} ${PUBLISH_COUNTS} ${SESSION_STATE_GUIDE} ${DELIVERY_CONTRACT}`,
66695
+ description: `Publish an Envoy message to a notifications. topic. ${PUBLISHED_DELIVERY} A role or built-in topic is delivered as its guide says. A role message has three possible answers. First, a live session holds the role, and the stream stores the forward for that holder's consumer. Its 200 says the stream stored it. It does not say that the holder read it. It names the holder and the state the listener resolved the holder in. Second, no live session holds the role: nobody claims it, or its holder is unresponsive or gone. The listener then keeps the message for one hour. This is a success. The result says that the listener kept the message, and its kept_until is the time that hour ends. For a holder that is not live, the result also names that holder and its state. The next session to hold the role live before kept_until gets the message. That can be the same holder when it answers again. If no session takes the message by kept_until, Envoy drops it. If the publish named your session as its source, Envoy then sends your session a message that names the dropped message, unless it dropped it more than an hour late. Third, the listener keeps nothing and errs, which tells you to reach the agent some other way: the holder refuses the message, the forward is not stored within four seconds, or no live session holds the role and the publish names no session of yours as its source, so nothing could tell you that a kept copy expired. A team topic (such as notifications.team.deploy-squad.all) is stored like every other, so a session subscribed to it that was away still receives it when it returns, and one that subscribes after you publish does not. A notifications. topic no stream subject captures is refused by name: nothing would store it. ${NOT_SENT_GUIDE} ${PUBLISH_COUNTS} ${SESSION_STATE_GUIDE} ${DELIVERY_CONTRACT}`,
66528
66696
  arguments: (schema) => ({ topic: schema.string(), ...messageArguments(schema) }),
66529
66697
  operation: EnvoyToolOperation.publish
66530
66698
  },
@@ -66572,9 +66740,9 @@ function lastSeenText(lastSeen) {
66572
66740
  }
66573
66741
  var STORED_ONCE = "an earlier attempt under the same idempotency_key was already stored, so this one stored no " + "second copy";
66574
66742
  function sendConfirmationText(result) {
66575
- if (result.state === "stopped") {
66743
+ if (result.state === "stopped" || result.state === "no_receiver") {
66576
66744
  const seen = result.lastSeen === undefined ? "" : ` (last seen ${lastSeenText(result.lastSeen)})`;
66577
- const waits = `the session is stopped${seen}; if it runs again within ${DELIVERY_DUPLICATE_WINDOW_HOURS} hours, it gets the message`;
66745
+ const waits = result.state === "stopped" ? `the session is stopped${seen}; if it runs again within ${DELIVERY_DUPLICATE_WINDOW_HOURS} hours, it gets the message` : `the session runs but takes no message into its conversation now; the message is stored, and if the session takes messages within ${DELIVERY_DUPLICATE_WINDOW_HOURS} hours, it gets the message`;
66578
66746
  if (result.duplicate) {
66579
66747
  return `queued once for ${result.recipient}: ${STORED_ONCE}; ${waits}`;
66580
66748
  }
@@ -66853,12 +67021,20 @@ async function findHandoffReport(input) {
66853
67021
  return { commit: head, ...report };
66854
67022
  }
66855
67023
 
67024
+ // ../pi-shared/src/role-claim-stopping.ts
67025
+ class RoleClaimStoppingError extends Error {
67026
+ name = "RoleClaimStoppingError";
67027
+ constructor(role) {
67028
+ super(`this session is stopping, so it claims no role: role ${role} is not held here`);
67029
+ }
67030
+ }
67031
+
66856
67032
  // src/envoy-channel-server.ts
66857
67033
  var import_nats5 = __toESM(require_mod4(), 1);
66858
67034
 
66859
67035
  // package.json
66860
67036
  var name2 = "@sjawhar/claude-envoy";
66861
- var version2 = "6.13.0";
67037
+ var version2 = "6.14.1";
66862
67038
  var package_default = {
66863
67039
  name: name2,
66864
67040
  version: version2,
@@ -67845,12 +68021,11 @@ function controlSubscription(options) {
67845
68021
 
67846
68022
  // src/agent-stream-runner.ts
67847
68023
  var AGENT_STREAM_CALL_TIMEOUT_MS = 5000;
68024
+ var LIVE_VIEW_READ_FAILED = "the live view could not read this session's ";
67848
68025
  var AGENT_STREAM_SEEN_ROWS_MAX = 512;
67849
68026
  function startAgentStream(options) {
67850
- const { link } = options;
68027
+ const { link, warn } = options;
67851
68028
  const now = options.now ?? Date.now;
67852
- const warn = options.warn ?? ((text) => void process.stderr.write(`envoy-channel: ${text}
67853
- `));
67854
68029
  let session = options.sessionId;
67855
68030
  const control = controlSubscription({
67856
68031
  connection: options.connection,
@@ -67909,7 +68084,7 @@ function startAgentStream(options) {
67909
68084
  if (!control.stopped)
67910
68085
  publishSettings();
67911
68086
  }).catch((error) => {
67912
- warn(`the live view could not read this session's model \u2014 ${messageFor(error)}`);
68087
+ warn(`${LIVE_VIEW_READ_FAILED}model \u2014 ${messageFor(error)}`);
67913
68088
  }).finally(() => {
67914
68089
  readingSettings = false;
67915
68090
  });
@@ -67923,7 +68098,7 @@ function startAgentStream(options) {
67923
68098
  if (!control.stopped)
67924
68099
  publishCommands();
67925
68100
  }).catch((error) => {
67926
- warn(`the live view could not read this session's commands \u2014 ${messageFor(error)}`);
68101
+ warn(`${LIVE_VIEW_READ_FAILED}commands \u2014 ${messageFor(error)}`);
67927
68102
  }).finally(() => {
67928
68103
  readingCommands = false;
67929
68104
  });
@@ -68233,6 +68408,8 @@ async function pruneStaleSessionRoles(stateDirectory, currentSessionId) {
68233
68408
  // src/envoy-off.ts
68234
68409
  function inboundOffChannelSession(options) {
68235
68410
  const { identity, stateDirectory, why } = options;
68411
+ let shutDown = false;
68412
+ const stopping = () => shutDown || options.stopping();
68236
68413
  return {
68237
68414
  delivery: { enqueue: async () => false, inbox: () => [] },
68238
68415
  topics: () => [],
@@ -68253,13 +68430,16 @@ function inboundOffChannelSession(options) {
68253
68430
  return;
68254
68431
  },
68255
68432
  async rememberRole(role) {
68433
+ if (stopping())
68434
+ return;
68256
68435
  await writePersistedRole(roleStateFile(stateDirectory, identity.id), {
68257
68436
  session_id: identity.id,
68258
68437
  role
68259
68438
  });
68260
68439
  },
68440
+ stopping,
68261
68441
  shutdown: async () => {
68262
- return;
68442
+ shutDown = true;
68263
68443
  }
68264
68444
  };
68265
68445
  }
@@ -68284,6 +68464,46 @@ async function serveEnvoyOff(serverInfo, refusal) {
68284
68464
  }
68285
68465
  }
68286
68466
 
68467
+ // src/inbound-outage-lines.ts
68468
+ var RECEIVES_NOTHING = {
68469
+ line: (why) => `envoy-channel: this session receives nothing (${why}); registering again every heartbeat
68470
+ `,
68471
+ told: "that it receives nothing"
68472
+ };
68473
+ var INBOUND_UNAVAILABLE_LINES = {
68474
+ unrecorded: {
68475
+ line: (why) => `envoy-channel: this session's registration is not recorded for certain (${why}), and the session registers again at every heartbeat
68476
+ `,
68477
+ told: "that its registration is not recorded for certain"
68478
+ },
68479
+ github_withheld: {
68480
+ line: (why) => `envoy-channel: the listener follows none of this session's GitHub topics now (${why}); the session's other messages still reach it if the listener already held its registration, and none reach it until a registration is accepted if it held none; registering again every heartbeat
68481
+ `,
68482
+ told: "that its GitHub messages are withheld"
68483
+ },
68484
+ refused: RECEIVES_NOTHING,
68485
+ no_relay: RECEIVES_NOTHING
68486
+ };
68487
+ var RECEIVES_AGAIN = {
68488
+ line: `envoy-channel: this session receives again: a registration was accepted
68489
+ `,
68490
+ told: "that it receives again"
68491
+ };
68492
+ var INBOUND_RESTORED_LINES = {
68493
+ unrecorded: {
68494
+ line: `envoy-channel: the listener recorded a registration of this session
68495
+ `,
68496
+ told: "that the listener recorded its registration"
68497
+ },
68498
+ github_withheld: {
68499
+ line: `envoy-channel: the listener follows this session's GitHub topics again: a registration was accepted
68500
+ `,
68501
+ told: "that the listener follows its GitHub topics again"
68502
+ },
68503
+ refused: RECEIVES_AGAIN,
68504
+ no_relay: RECEIVES_AGAIN
68505
+ };
68506
+
68287
68507
  // src/installed-build.ts
68288
68508
  import { dirname as dirname5, join as join12, sep } from "path";
68289
68509
  function pluginCacheSegments(bundlePath) {
@@ -69622,27 +69842,39 @@ function isNetworkOrTimeoutError(error) {
69622
69842
  const code = "code" in error && typeof error.code === "string" ? error.code : undefined;
69623
69843
  return code === "ConnectionRefused" || code === "ConnectionTimeout" || code === "EAI_AGAIN" || code === "ECONNREFUSED" || code === "ECONNRESET" || code === "EHOSTUNREACH" || code === "ENETUNREACH" || code === "ENOTFOUND" || code === "ETIMEDOUT" || error instanceof TypeError && (error.message === "Failed to fetch" || error.message === "fetch failed");
69624
69844
  }
69625
- async function callReadyWithRetry(label, call, sleep = (ms) => {
69845
+ async function callReadyWithRetry(label, call, host, sleep = (ms, signal) => {
69626
69846
  const waited = Promise.withResolvers();
69627
- setTimeout(waited.resolve, ms);
69628
- return waited.promise;
69847
+ const timer = setTimeout(waited.resolve, ms);
69848
+ const stop = () => {
69849
+ clearTimeout(timer);
69850
+ waited.resolve();
69851
+ };
69852
+ if (signal?.aborted === true)
69853
+ stop();
69854
+ else
69855
+ signal?.addEventListener("abort", stop, { once: true });
69856
+ return waited.promise.finally(() => signal?.removeEventListener("abort", stop));
69629
69857
  }) {
69858
+ const { log, signal } = host;
69859
+ const stopped = () => signal?.aborted === true;
69630
69860
  for (let attempt = 1;; attempt++) {
69631
69861
  try {
69632
69862
  await call();
69633
69863
  return;
69634
69864
  } catch (error) {
69635
69865
  const retryable = error instanceof LegionDaemonApiError ? outage(error.status) : isNetworkOrTimeoutError(error);
69636
- if (!retryable)
69866
+ if (!retryable || stopped())
69637
69867
  throw error;
69638
69868
  if (attempt === READY_RETRY_ATTEMPTS) {
69639
- console.error(`[legion] ${label} failed after ${attempt} attempts: ${messageFor(error)}`);
69869
+ log(`${label} failed after ${attempt} attempts: ${messageFor(error)}`);
69640
69870
  throw error;
69641
69871
  }
69642
69872
  const asked = error instanceof LegionDaemonApiError ? error.retryAfterMs : 0;
69643
69873
  const wait = Math.min(Math.max(READY_RETRY_DELAY_MS, asked), READY_RETRY_AFTER_MAX_MS);
69644
- console.error(`[legion] ${label} failed (attempt ${attempt}/${READY_RETRY_ATTEMPTS}), retrying in ${wait / 1000} s: ${messageFor(error)}`);
69645
- await sleep(wait);
69874
+ log(`${label} failed (attempt ${attempt}/${READY_RETRY_ATTEMPTS}), retrying in ${wait / 1000} s: ${messageFor(error)}`);
69875
+ await sleep(wait, signal);
69876
+ if (stopped())
69877
+ throw error;
69646
69878
  }
69647
69879
  }
69648
69880
  }
@@ -69836,7 +70068,9 @@ async function bootLegionClaim(host) {
69836
70068
  } catch (error) {
69837
70069
  if (!(error instanceof LegionDaemonApiError))
69838
70070
  throw error;
69839
- host.log(`claims/register registration failed (${error.status}): ${error.detail}`);
70071
+ if (host.signal?.aborted !== true) {
70072
+ host.log(`claims/register registration failed (${error.status}): ${error.detail}`);
70073
+ }
69840
70074
  if (error.status < 400 || outage(error.status))
69841
70075
  throw error;
69842
70076
  host.stop();
@@ -69861,19 +70095,27 @@ async function bootLegionClaim(host) {
69861
70095
  secret: claim.secret,
69862
70096
  generation: claim.generation
69863
70097
  };
69864
- await callReadyWithRetry("claims/ready", () => daemon.ready(ready));
70098
+ await callReadyWithRetry("claims/ready", () => daemon.ready(ready), host);
69865
70099
  host.onRoleRegained(async (role, reason) => {
69866
70100
  if (role !== claim.claimToken)
69867
70101
  return;
70102
+ const stopped = () => host.signal?.aborted === true;
70103
+ if (stopped())
70104
+ return;
69868
70105
  try {
69869
- await callReadyWithRetry("claims/ready after role regain", () => daemon.ready(ready));
70106
+ await callReadyWithRetry("claims/ready after role regain", () => daemon.ready(ready), host);
70107
+ if (stopped())
70108
+ return;
69870
70109
  host.log(`re-ran claims/ready after role ${role} was ${reason}`);
69871
70110
  } catch (error) {
70111
+ if (stopped())
70112
+ return;
69872
70113
  host.log(`claims/ready after role ${role} was ${reason} failed; the daemon's queued task stays undelivered until the next regain or boot: ${messageFor(error)}`);
69873
70114
  }
69874
70115
  });
69875
70116
  } catch (error) {
69876
- stopAfterRegistration(host, claim.claimToken, error);
70117
+ if (host.signal?.aborted !== true)
70118
+ stopAfterRegistration(host, claim.claimToken, error);
69877
70119
  return { claimed: Promise.resolve() };
69878
70120
  }
69879
70121
  return { claimed: claimRoleAtFirstTurn(host, claim.claimToken, claim.replaces, firstTurn) };
@@ -69898,11 +70140,19 @@ function listenForFirstTurn(host) {
69898
70140
  function claimRoleAtFirstTurn(host, role, replaces, firstTurn) {
69899
70141
  const done = Promise.withResolvers();
69900
70142
  let ran = false;
70143
+ const stop = () => {
70144
+ if (ran)
70145
+ return;
70146
+ ran = true;
70147
+ clearTimeout(bound);
70148
+ done.resolve();
70149
+ };
69901
70150
  const claim = () => {
69902
70151
  if (ran)
69903
70152
  return;
69904
70153
  ran = true;
69905
70154
  clearTimeout(bound);
70155
+ host.signal?.removeEventListener("abort", stop);
69906
70156
  (async () => {
69907
70157
  try {
69908
70158
  await claimRoleAgainOnBusy(() => host.claimRole(role, replaces), role, {
@@ -69919,6 +70169,10 @@ function claimRoleAtFirstTurn(host, role, replaces, firstTurn) {
69919
70169
  };
69920
70170
  const bound = setTimeout(claim, host.firstTurnBoundMs);
69921
70171
  bound.unref?.();
70172
+ if (host.signal?.aborted === true)
70173
+ stop();
70174
+ else
70175
+ host.signal?.addEventListener("abort", stop, { once: true });
69922
70176
  firstTurn(claim);
69923
70177
  return done.promise;
69924
70178
  }
@@ -70692,8 +70946,10 @@ function logLegion(line) {
70692
70946
  function endPane() {
70693
70947
  process.kill(process.ppid, "SIGTERM");
70694
70948
  }
70695
- function stopPane(why) {
70696
- logLegion(`${why}; stopping the pane so the daemon launches it again`);
70949
+ function stopPane(why, server) {
70950
+ if (server.stopping())
70951
+ return;
70952
+ server.log(`${why}; stopping the pane so the daemon launches it again`);
70697
70953
  endPane();
70698
70954
  }
70699
70955
  async function waitForTranscript(configDir, sessionID, signal, pollMs = 100) {
@@ -72142,6 +72398,14 @@ async function sessionTitle(environment, directory, sources = {}) {
72142
72398
  };
72143
72399
  }
72144
72400
 
72401
+ // src/stop-gates.ts
72402
+ function gatedStderr(stopping) {
72403
+ return (line) => {
72404
+ if (!stopping())
72405
+ process.stderr.write(line);
72406
+ };
72407
+ }
72408
+
72145
72409
  // ../pi-shared/src/dispatch-user-turn.ts
72146
72410
  function handledAttemptKey(messageId, attempt) {
72147
72411
  return `${messageId}#${attempt}`;
@@ -72621,6 +72885,7 @@ async function postDispatchReply(identity, configFile, delivery, result) {
72621
72885
  throw new Error(config.error ?? config.notice);
72622
72886
  await postDeliveryReply(config, identity.id, delivery, result);
72623
72887
  }
72888
+ var DELIVERY_FAILED_LINE = "envoy-channel: a delivery failed \u2014 ";
72624
72889
  async function userTurnDispatchClient(identity, configFile, ms) {
72625
72890
  const active = activeDispatchSettings((await sessionDispatchSettings(configFile, process.env, {
72626
72891
  cwd: identity.directory,
@@ -72636,7 +72901,7 @@ function createChannelDelivery(input) {
72636
72901
  tail = run.then(() => {
72637
72902
  return;
72638
72903
  }, (error) => {
72639
- process.stderr.write(`envoy-channel: a delivery failed \u2014 ${messageFor(error)}
72904
+ input.stderr(`${DELIVERY_FAILED_LINE}${messageFor(error)}
72640
72905
  `);
72641
72906
  });
72642
72907
  return run;
@@ -72649,7 +72914,7 @@ function createChannelDelivery(input) {
72649
72914
  if (eventId !== undefined && inbox.some((entry) => entry.event_id === eventId))
72650
72915
  return;
72651
72916
  if (rendered.payloadShownAsText !== undefined) {
72652
- process.stderr.write(`envoy-channel: message ${eventId ?? "unknown"}'s payload is shown as its text; the card could not lay it out (${rendered.payloadShownAsText})
72917
+ input.stderr(`envoy-channel: message ${eventId ?? "unknown"}'s payload is shown as its text; the card could not lay it out (${rendered.payloadShownAsText})
72653
72918
  `);
72654
72919
  }
72655
72920
  inbox.unshift({
@@ -72668,7 +72933,7 @@ function createChannelDelivery(input) {
72668
72933
  const passOverLateBtw = (rendered) => {
72669
72934
  if (rendered.delivery?.mode !== "btw")
72670
72935
  return false;
72671
- process.stderr.write(`envoy-channel: passing over late BTW ${rendered.envelope?.event_id ?? "unknown"}: it was asked while this session was not taking messages
72936
+ input.stderr(`envoy-channel: passing over late BTW ${rendered.envelope?.event_id ?? "unknown"}: it was asked while this session was not taking messages
72672
72937
  `);
72673
72938
  return true;
72674
72939
  };
@@ -72679,19 +72944,19 @@ function createChannelDelivery(input) {
72679
72944
  return tail.then(() => false);
72680
72945
  if (rendered.rejectedDelivery !== undefined) {
72681
72946
  const rejected = rendered.rejectedDelivery;
72682
- process.stderr.write(`envoy-channel: rejecting malformed Dispatch targeted delivery ${rejected.id}
72947
+ input.stderr(`envoy-channel: rejecting malformed Dispatch targeted delivery ${rejected.id}
72683
72948
  `);
72684
72949
  return postDispatchReply(input.identity, input.configFile, rejected, {
72685
72950
  error: "Invalid Dispatch targeted delivery frame"
72686
72951
  }).then(() => false, (error) => {
72687
- process.stderr.write(error instanceof DispatchWriteLandedError ? `envoy-channel: the report of the rejected delivery landed on Dispatch, which gave no copy of its answer \u2014 ${error.message}
72952
+ input.stderr(error instanceof DispatchWriteLandedError ? `envoy-channel: the report of the rejected delivery landed on Dispatch, which gave no copy of its answer \u2014 ${error.message}
72688
72953
  ` : `envoy-channel: could not report the rejected delivery to Dispatch \u2014 ${messageFor(error)}
72689
72954
  `);
72690
72955
  return false;
72691
72956
  });
72692
72957
  }
72693
72958
  if (rendered.malformedDelivery === true) {
72694
- process.stderr.write(`envoy-channel: dropping malformed Dispatch targeted delivery without a reply address
72959
+ input.stderr(`envoy-channel: dropping malformed Dispatch targeted delivery without a reply address
72695
72960
  `);
72696
72961
  return tail.then(() => false);
72697
72962
  }
@@ -72710,6 +72975,8 @@ function createChannelDelivery(input) {
72710
72975
  },
72711
72976
  notice(content, addressed) {
72712
72977
  return queued(async () => {
72978
+ if (input.stopping?.() === true)
72979
+ return;
72713
72980
  if (addressed !== undefined && addressed !== input.identity.id) {
72714
72981
  throw new Error(`the notice names session ${addressed}, and this process serves ${input.identity.id}`);
72715
72982
  }
@@ -72797,15 +73064,23 @@ async function startChannelSession(options) {
72797
73064
  const watchedConnections = new WeakSet;
72798
73065
  let router;
72799
73066
  let turns;
73067
+ const userTopics = new Set;
73068
+ let heldRole;
73069
+ let shuttingDown = options.startSignal?.aborted === true;
73070
+ options.startSignal?.addEventListener("abort", () => {
73071
+ shuttingDown = true;
73072
+ }, { once: true });
73073
+ let shutdownStarted = false;
73074
+ const sessionStderr = gatedStderr(() => shuttingDown);
72800
73075
  const delivery = createChannelDelivery({
72801
73076
  identity,
72802
73077
  notifier: options.notifier,
72803
73078
  configFile: options.configFile,
72804
- router: () => router
73079
+ router: () => router,
73080
+ stderr: sessionStderr,
73081
+ stopping: () => shuttingDown
72805
73082
  });
72806
- const userTopics = new Set;
72807
- let heldRole;
72808
- let shuttingDown = false;
73083
+ const showNotice = (content, addressed) => shuttingDown ? Promise.resolve() : delivery.notice(content, addressed);
72809
73084
  const handoffFile = options.handoffPid === undefined ? undefined : sessionHandoffFile(options.stateDirectory, options.handoffPid);
72810
73085
  let registryWrites = Promise.resolve();
72811
73086
  const serialized = (write) => {
@@ -72840,8 +73115,8 @@ async function startChannelSession(options) {
72840
73115
  const dedupe = createDeliveryDedupe();
72841
73116
  let ledgerBound;
72842
73117
  const tellGapNotice = (notice) => {
72843
- delivery.notice(gapNoticeText(notice)).catch((error) => {
72844
- process.stderr.write(`envoy-channel: ${notice.message} (the session could not be told \u2014 ${messageFor(error)})
73118
+ showNotice(gapNoticeText(notice)).catch((error) => {
73119
+ sessionStderr(`envoy-channel: ${notice.message} (the session could not be told \u2014 ${messageFor(error)})
72845
73120
  `);
72846
73121
  });
72847
73122
  };
@@ -72851,13 +73126,13 @@ async function startChannelSession(options) {
72851
73126
  host: {
72852
73127
  sessionID: () => shuttingDown || ledgerBound !== identity.id ? undefined : identity.id,
72853
73128
  followedSubjects: () => replayFollowedSubjects(directSubject, userTopics),
72854
- showFailureNotice: (addressed, notice) => delivery.notice(envoyNoticeText(failureNoticeFields(notice)), addressed),
73129
+ showFailureNotice: (addressed, notice) => showNotice(envoyNoticeText(failureNoticeFields(notice)), addressed),
72855
73130
  failureNoticeFailed: (notice, error) => {
72856
- process.stderr.write(`envoy-channel: message ${notice.eventId} from ${notice.sender} was not shown, nor was the notice naming it \u2014 ${messageFor(error)}
73131
+ sessionStderr(`envoy-channel: message ${notice.eventId} from ${notice.sender} was not shown, nor was the notice naming it \u2014 ${messageFor(error)}
72857
73132
  `);
72858
73133
  },
72859
73134
  log: (message, error) => {
72860
- process.stderr.write(`envoy-channel: ${message}${error === undefined ? "" : ` \u2014 ${messageFor(error)}`}
73135
+ sessionStderr(`envoy-channel: ${message}${error === undefined ? "" : ` \u2014 ${messageFor(error)}`}
72861
73136
  `);
72862
73137
  },
72863
73138
  write: (change) => stateWriter?.ledger(change.snapshot())
@@ -72867,7 +73142,7 @@ async function startChannelSession(options) {
72867
73142
  const sessionId = identity.id;
72868
73143
  const file = replayStateFile(options.stateDirectory, sessionId);
72869
73144
  const snapshot = await readReplayState(file).catch((error) => {
72870
- process.stderr.write(`envoy-channel: could not read the delivery state (${messageFor(error)}); this session's record starts over
73145
+ sessionStderr(`envoy-channel: could not read the delivery state (${messageFor(error)}); this session's record starts over
72871
73146
  `);
72872
73147
  return { ledger: [] };
72873
73148
  });
@@ -72884,7 +73159,7 @@ async function startChannelSession(options) {
72884
73159
  return;
72885
73160
  const file = userTurnStateFile(options.stateDirectory, identity.id);
72886
73161
  const restored = await readUserTurnState(file).catch((error) => {
72887
- process.stderr.write(`envoy-channel: could not read this session's record of the messages it took (${messageFor(error)}); its messages arrive as cards
73162
+ sessionStderr(`envoy-channel: could not read this session's record of the messages it took (${messageFor(error)}); its messages arrive as cards
72888
73163
  `);
72889
73164
  return;
72890
73165
  });
@@ -72944,7 +73219,7 @@ async function startChannelSession(options) {
72944
73219
  deliver: (frame) => deliverRelayed(owner, frame),
72945
73220
  gap: tellGapNotice,
72946
73221
  log: (message, error) => {
72947
- process.stderr.write(`envoy-channel: ${message}${error === undefined ? "" : ` \u2014 ${messageFor(error)}`}
73222
+ sessionStderr(`envoy-channel: ${message}${error === undefined ? "" : ` \u2014 ${messageFor(error)}`}
72948
73223
  `);
72949
73224
  }
72950
73225
  },
@@ -72953,7 +73228,7 @@ async function startChannelSession(options) {
72953
73228
  if (relay !== owner)
72954
73229
  return false;
72955
73230
  state.consumer(snapshot).catch((error) => {
72956
- process.stderr.write(`envoy-channel: could not persist the consumer delivery state \u2014 ${messageFor(error)}
73231
+ sessionStderr(`envoy-channel: could not persist the consumer delivery state \u2014 ${messageFor(error)}
72957
73232
  `);
72958
73233
  });
72959
73234
  return true;
@@ -72987,7 +73262,7 @@ async function startChannelSession(options) {
72987
73262
  owner.delivery.receive(message);
72988
73263
  }
72989
73264
  } catch (error) {
72990
- process.stderr.write(`envoy-channel: the relay subscription of ${owner.sessionID} stopped \u2014 ${natsFailureReason(error)}
73265
+ sessionStderr(`envoy-channel: the relay subscription of ${owner.sessionID} stopped \u2014 ${natsFailureReason(error)}
72991
73266
  `);
72992
73267
  if (owner.subscription !== subscription)
72993
73268
  return;
@@ -73040,7 +73315,9 @@ async function startChannelSession(options) {
73040
73315
  return;
73041
73316
  relay.delivery.beginEpoch();
73042
73317
  serialized(register).catch((error) => {
73043
- process.stderr.write(`envoy-channel: could not register again after a reconnect (${messageFor(error)}); the next heartbeat retries
73318
+ if (shuttingDown)
73319
+ return;
73320
+ sessionStderr(`envoy-channel: could not register again after a reconnect (${messageFor(error)}); the next heartbeat retries
73044
73321
  `);
73045
73322
  });
73046
73323
  };
@@ -73052,7 +73329,8 @@ async function startChannelSession(options) {
73052
73329
  const followedTopics = createChannelTopics(() => connection);
73053
73330
  function unfollowRemovedTopics(topics) {
73054
73331
  dropFromTopicsAndRegistry(topics).catch((error) => {
73055
- process.stderr.write(`envoy-channel: could not drop a removed subscription from the registry \u2014 ${messageFor(error)}; the next heartbeat reconciles it
73332
+ sessionStderr(isBusUnanswered(error) ? `envoy-channel: the listener's message bus did not answer a request to drop a removed subscription from the registry \u2014 ${messageFor(error)}; the registry may already be without it, and the next heartbeat reconciles the registry and sets the consumer's filter to the topics it holds
73333
+ ` : `envoy-channel: could not drop a removed subscription from the registry \u2014 ${messageFor(error)}; the next heartbeat reconciles it
73056
73334
  `);
73057
73335
  });
73058
73336
  }
@@ -73067,24 +73345,23 @@ async function startChannelSession(options) {
73067
73345
  clientInstanceID: options.clientInstanceID
73068
73346
  }));
73069
73347
  }
73070
- const inboundOutage = inboundUnavailable((why) => {
73071
- if (shuttingDown)
73072
- return;
73073
- process.stderr.write(`envoy-channel: this session receives nothing (${why}); registering again every heartbeat
73074
- `);
73075
- delivery.notice(inboundUnavailableNoticeText(why)).catch((noticeError) => {
73076
- process.stderr.write(`envoy-channel: the session could not be told that it receives nothing \u2014 ${messageFor(noticeError)}
73348
+ const inboundOutage = inboundUnavailable((outage) => {
73349
+ const { line, told } = INBOUND_UNAVAILABLE_LINES[outage.kind];
73350
+ sessionStderr(line(outage.why));
73351
+ showNotice(inboundUnavailableNoticeText(outage)).catch((noticeError) => {
73352
+ sessionStderr(`envoy-channel: the session could not be told ${told} \u2014 ${messageFor(noticeError)}
73077
73353
  `);
73078
73354
  });
73079
- }, () => {
73080
- if (shuttingDown)
73081
- return;
73082
- process.stderr.write(`envoy-channel: this session receives again: its registration was accepted
73083
- `);
73084
- delivery.notice(inboundRestoredNoticeText()).catch((noticeError) => {
73085
- process.stderr.write(`envoy-channel: the session could not be told that it receives again \u2014 ${messageFor(noticeError)}
73355
+ }, {
73356
+ restored: ({ kind }) => {
73357
+ const { line, told } = INBOUND_RESTORED_LINES[kind];
73358
+ sessionStderr(line);
73359
+ showNotice(inboundRestoredNoticeText(kind)).catch((noticeError) => {
73360
+ sessionStderr(`envoy-channel: the session could not be told ${told} \u2014 ${messageFor(noticeError)}
73086
73361
  `);
73087
- });
73362
+ });
73363
+ },
73364
+ stopping: () => shuttingDown
73088
73365
  });
73089
73366
  options.reportOutagesTo?.(inboundOutage);
73090
73367
  let stampedTitle;
@@ -73099,9 +73376,11 @@ async function startChannelSession(options) {
73099
73376
  await restoreDelivery();
73100
73377
  handoffDeliveryPending = false;
73101
73378
  await withTimeout(connection.flush(), options.handoffFlushTimeoutMs ?? HANDOFF_FLUSH_TIMEOUT_MS, "flushing NATS").catch((error) => {
73102
- process.stderr.write(`envoy-channel: could not confirm the relay subscription of ${identity.id} \u2014 ${natsFailureReason(error)}
73379
+ sessionStderr(`envoy-channel: could not confirm the relay subscription of ${identity.id} \u2014 ${natsFailureReason(error)}
73103
73380
  `);
73104
73381
  });
73382
+ if (shuttingDown)
73383
+ return;
73105
73384
  }
73106
73385
  const title = options.title?.(identity.id) ?? "";
73107
73386
  if (options.stampTitle !== undefined && title !== "" && (stampedTitle?.sessionID !== identity.id || stampedTitle.title !== title)) {
@@ -73112,7 +73391,7 @@ async function startChannelSession(options) {
73112
73391
  } catch (error) {
73113
73392
  if (!stampFailureReported) {
73114
73393
  stampFailureReported = true;
73115
- process.stderr.write(`envoy-channel: could not write the session title for the dispatch command (${messageFor(error)}); retrying every heartbeat, and the command names this session by its id
73394
+ sessionStderr(`envoy-channel: could not write the session title for the dispatch command (${messageFor(error)}); retrying every heartbeat, and the command names this session by its id
73116
73395
  `);
73117
73396
  }
73118
73397
  }
@@ -73166,29 +73445,39 @@ async function startChannelSession(options) {
73166
73445
  userTopics.delete(topic);
73167
73446
  followedTopics.unfollow(topics);
73168
73447
  ledger.followedChanged().catch((error) => {
73169
- process.stderr.write(`envoy-channel: the topics the listener refused stay in the delivery state until it is written next \u2014 ${messageFor(error)}
73448
+ sessionStderr(`envoy-channel: the topics the listener refused stay in the delivery state until it is written next \u2014 ${messageFor(error)}
73170
73449
  `);
73171
73450
  });
73172
- if (shuttingDown)
73173
- return;
73174
- delivery.notice(refusedTopicsNoticeText(topics, reason)).catch((noticeError) => {
73175
- process.stderr.write(`envoy-channel: the session could not be told which topics the listener refused \u2014 ${messageFor(noticeError)}
73451
+ showNotice(refusedTopicsNoticeText(topics, reason)).catch((noticeError) => {
73452
+ sessionStderr(`envoy-channel: the session could not be told which topics the listener refused \u2014 ${messageFor(noticeError)}
73176
73453
  `);
73177
73454
  });
73178
73455
  },
73179
- log: (line) => process.stderr.write(`envoy-channel: ${line}
73180
- `)
73456
+ log: (line) => sessionStderr(`envoy-channel: ${line}
73457
+ `),
73458
+ stopping: () => shuttingDown
73181
73459
  });
73182
73460
  };
73183
- const writeRoleRecord = (file, role) => writePersistedRole(file, {
73184
- session_id: identity.id,
73185
- role,
73186
- client_instance_id: options.clientInstanceID
73187
- });
73461
+ const writeRoleRecord = async (file, role) => {
73462
+ if (shuttingDown)
73463
+ return;
73464
+ await writePersistedRole(file, {
73465
+ session_id: identity.id,
73466
+ role,
73467
+ client_instance_id: options.clientInstanceID
73468
+ });
73469
+ };
73470
+ const removeRoleRecord = async (file) => {
73471
+ if (shuttingDown)
73472
+ return;
73473
+ await rm5(file, { force: true });
73474
+ };
73188
73475
  let roleTransferFrom;
73189
73476
  const restoreRole = async (previousSessionID) => {
73190
73477
  const previousFile = roleStateFile(options.stateDirectory, previousSessionID);
73191
73478
  const persisted = await readPersistedRole(previousFile);
73479
+ if (shuttingDown)
73480
+ return "pending";
73192
73481
  if (persisted === undefined)
73193
73482
  return "settled";
73194
73483
  if (!mayActOnRoleRecord(persisted.client_instance_id, options.clientInstanceID, heldRole !== undefined)) {
@@ -73202,18 +73491,20 @@ async function startChannelSession(options) {
73202
73491
  previousSessionID: persisted.session_id,
73203
73492
  clientInstanceID: options.clientInstanceID
73204
73493
  });
73494
+ if (shuttingDown)
73495
+ return "pending";
73205
73496
  if (!claim.claimed) {
73206
73497
  if (claim.holder === identity.id)
73207
73498
  return "pending";
73208
73499
  if (claim.holder !== persisted.session_id)
73209
- await rm5(previousFile, { force: true });
73500
+ await removeRoleRecord(previousFile);
73210
73501
  return "settled";
73211
73502
  }
73212
73503
  logRoleClaimWarnings(warnOnStderr, persisted.role, sessionID, claim.warnings);
73213
73504
  heldRole = persisted.role;
73214
73505
  const currentFile = roleStateFile(options.stateDirectory, identity.id);
73215
73506
  if (previousFile !== currentFile)
73216
- await rm5(previousFile, { force: true });
73507
+ await removeRoleRecord(previousFile);
73217
73508
  await writeRoleRecord(currentFile, persisted.role);
73218
73509
  return "settled";
73219
73510
  };
@@ -73223,12 +73514,14 @@ async function startChannelSession(options) {
73223
73514
  if (hook === undefined)
73224
73515
  return;
73225
73516
  Promise.resolve().then(() => hook(role, reason)).catch((error) => {
73226
- process.stderr.write(`envoy-channel: role ${role} regain hook failed (${reason}) \u2014 ${messageFor(error)}
73517
+ sessionStderr(`envoy-channel: role ${role} regain hook failed (${reason}) \u2014 ${messageFor(error)}
73227
73518
  `);
73228
73519
  });
73229
73520
  };
73230
73521
  let roleRefreshFailureReported = false;
73231
73522
  const refreshRoleRecord = async () => {
73523
+ if (shuttingDown)
73524
+ return;
73232
73525
  const roleFile = roleStateFile(options.stateDirectory, identity.id);
73233
73526
  try {
73234
73527
  await touchStateFile(roleFile);
@@ -73236,7 +73529,7 @@ async function startChannelSession(options) {
73236
73529
  } catch (error) {
73237
73530
  if (!roleRefreshFailureReported) {
73238
73531
  roleRefreshFailureReported = true;
73239
- process.stderr.write(`envoy-channel: could not refresh the role record ${roleFile} (${messageFor(error)}); retrying every heartbeat
73532
+ sessionStderr(`envoy-channel: could not refresh the role record ${roleFile} (${messageFor(error)}); retrying every heartbeat
73240
73533
  `);
73241
73534
  }
73242
73535
  }
@@ -73246,9 +73539,11 @@ async function startChannelSession(options) {
73246
73539
  return;
73247
73540
  const role = heldRole;
73248
73541
  const holding = await options.client.getRole(role).catch(undefinedOnNotFound);
73542
+ if (shuttingDown)
73543
+ return;
73249
73544
  if (roleHeldBy(holding, identity.id, options.clientInstanceID)) {
73250
73545
  await refreshRoleRecord();
73251
- if (afterOutage)
73546
+ if (afterOutage && !shuttingDown)
73252
73547
  fireRegained(role, "reregistered");
73253
73548
  return;
73254
73549
  }
@@ -73259,10 +73554,12 @@ async function startChannelSession(options) {
73259
73554
  soft: true,
73260
73555
  clientInstanceID: options.clientInstanceID
73261
73556
  });
73557
+ if (shuttingDown)
73558
+ return;
73262
73559
  if (!result.claimed) {
73263
73560
  if (result.holder !== identity.id) {
73264
73561
  heldRole = undefined;
73265
- await rm5(roleStateFile(options.stateDirectory, identity.id), { force: true });
73562
+ await removeRoleRecord(roleStateFile(options.stateDirectory, identity.id));
73266
73563
  return;
73267
73564
  }
73268
73565
  await refreshRoleRecord();
@@ -73282,7 +73579,7 @@ async function startChannelSession(options) {
73282
73579
  } catch (error) {
73283
73580
  if (!roleTransferFailureReported) {
73284
73581
  roleTransferFailureReported = true;
73285
- process.stderr.write(`envoy-channel: could not take back the role held by ${from} (${messageFor(error)}); retrying every heartbeat
73582
+ sessionStderr(`envoy-channel: could not take back the role held by ${from} (${messageFor(error)}); retrying every heartbeat
73286
73583
  `);
73287
73584
  }
73288
73585
  }
@@ -73301,11 +73598,19 @@ async function startChannelSession(options) {
73301
73598
  followedTopics.follow(nextSubject);
73302
73599
  try {
73303
73600
  await withTimeout(connection.flush(), options.handoffFlushTimeoutMs ?? HANDOFF_FLUSH_TIMEOUT_MS, "flushing NATS");
73601
+ if (shuttingDown) {
73602
+ followedTopics.unfollow([nextSubject]);
73603
+ return;
73604
+ }
73304
73605
  await deregister(previous);
73305
73606
  } catch (error) {
73306
73607
  followedTopics.unfollow([nextSubject]);
73307
73608
  throw error;
73308
73609
  }
73610
+ if (shuttingDown) {
73611
+ followedTopics.unfollow([nextSubject]);
73612
+ return;
73613
+ }
73309
73614
  identity.set(next);
73310
73615
  options.adopted?.(previous, next);
73311
73616
  forgetBrokerSession(previous);
@@ -73317,7 +73622,7 @@ async function startChannelSession(options) {
73317
73622
  roleTransferFrom ??= previous;
73318
73623
  await register();
73319
73624
  await transferRole();
73320
- process.stderr.write(`envoy: session id changed ${previous} -> ${next}; re-registered
73625
+ sessionStderr(`envoy: session id changed ${previous} -> ${next}; re-registered
73321
73626
  `);
73322
73627
  };
73323
73628
  let interestsRead = false;
@@ -73375,6 +73680,8 @@ async function startChannelSession(options) {
73375
73680
  heartbeatInFlight = true;
73376
73681
  try {
73377
73682
  await serialized(async () => {
73683
+ if (shuttingDown)
73684
+ return;
73378
73685
  await adoptHandoff();
73379
73686
  await resubscribeRelay();
73380
73687
  try {
@@ -73386,6 +73693,8 @@ async function startChannelSession(options) {
73386
73693
  if (shuttingDown)
73387
73694
  return;
73388
73695
  await reassertRole(registrationFailed);
73696
+ if (shuttingDown)
73697
+ return;
73389
73698
  await transferRole();
73390
73699
  await syncRegisteredInterests();
73391
73700
  });
@@ -73393,12 +73702,14 @@ async function startChannelSession(options) {
73393
73702
  outageReported = false;
73394
73703
  clearRetry();
73395
73704
  } catch (error) {
73705
+ if (shuttingDown)
73706
+ return;
73396
73707
  const retryIn = fromRetry ? undefined : armRetry();
73397
73708
  if (outageReported)
73398
73709
  return;
73399
73710
  outageReported = true;
73400
73711
  const retrying = retryIn === undefined ? "retrying at the next heartbeat" : `retrying once in ${Math.round(retryIn / 1000)} s, then every heartbeat`;
73401
- process.stderr.write(`envoy-channel: registry heartbeat failed (${messageFor(error)}); ${retrying}
73712
+ sessionStderr(`envoy-channel: registry heartbeat failed (${messageFor(error)}); ${retrying}
73402
73713
  `);
73403
73714
  } finally {
73404
73715
  heartbeatInFlight = false;
@@ -73436,7 +73747,7 @@ async function startChannelSession(options) {
73436
73747
  followedTopics.follow(topic);
73437
73748
  }
73438
73749
  await syncRegisteredInterests().catch((error) => {
73439
- process.stderr.write(`envoy-channel: could not read the registered interests (${messageFor(error)}); the next heartbeat retries
73750
+ sessionStderr(`envoy-channel: could not read the registered interests (${messageFor(error)}); the next heartbeat retries
73440
73751
  `);
73441
73752
  });
73442
73753
  const closedBeforeFlush = await flushThroughRedials(connection, options.startSignal);
@@ -73451,19 +73762,19 @@ async function startChannelSession(options) {
73451
73762
  await serialized(async () => {
73452
73763
  await register().catch((error) => {
73453
73764
  registrationFailed = true;
73454
- process.stderr.write(`envoy-channel: the first registration failed (${messageFor(error)}); the next heartbeat retries
73765
+ sessionStderr(`envoy-channel: the first registration failed (${messageFor(error)}); the next heartbeat retries
73455
73766
  `);
73456
73767
  });
73457
73768
  try {
73458
73769
  roleTransferFrom = await restoreRole(identity.id) === "pending" ? identity.id : undefined;
73459
73770
  } catch (error) {
73460
73771
  if (error instanceof UnparseableRoleRecordError) {
73461
- process.stderr.write(`envoy-channel: ${messageFor(error)}; the session starts without a role
73772
+ sessionStderr(`envoy-channel: ${messageFor(error)}; the session starts without a role
73462
73773
  `);
73463
73774
  } else {
73464
73775
  roleTransferFrom = identity.id;
73465
73776
  roleTransferFailureReported = true;
73466
- process.stderr.write(`envoy-channel: could not restore the role (${messageFor(error)}); the next heartbeat retries
73777
+ sessionStderr(`envoy-channel: could not restore the role (${messageFor(error)}); the next heartbeat retries
73467
73778
  `);
73468
73779
  }
73469
73780
  }
@@ -73474,8 +73785,10 @@ async function startChannelSession(options) {
73474
73785
  () => pruneStaleSessionTurns(options.stateDirectory),
73475
73786
  () => pruneStaleSessionRoles(options.stateDirectory, identity.id)
73476
73787
  ]) {
73788
+ if (shuttingDown)
73789
+ break;
73477
73790
  await prune().catch((error) => {
73478
- process.stderr.write(`envoy-channel: could not prune stale session state (${messageFor(error)})
73791
+ sessionStderr(`envoy-channel: could not prune stale session state (${messageFor(error)})
73479
73792
  `);
73480
73793
  });
73481
73794
  }
@@ -73497,7 +73810,7 @@ async function startChannelSession(options) {
73497
73810
  connectionLost = { closeError, dialError: undefined };
73498
73811
  if (relay !== undefined)
73499
73812
  relay.subscription = undefined;
73500
- process.stderr.write(`envoy-channel: the NATS connection closed for good (${lostConnectionReason(connectionLost)}); ${options.reopen === undefined ? "nothing dials a new one" : "dialing a new one"}
73813
+ sessionStderr(`envoy-channel: the NATS connection closed for good (${lostConnectionReason(connectionLost)}); ${options.reopen === undefined ? "nothing dials a new one" : "dialing a new one"}
73501
73814
  `);
73502
73815
  serialized(register).catch(() => {
73503
73816
  registrationFailed = true;
@@ -73523,10 +73836,10 @@ async function startChannelSession(options) {
73523
73836
  lost.dialError = dialError;
73524
73837
  });
73525
73838
  } catch (error) {
73526
- if (shuttingDown || options.startSignal?.aborted === true)
73839
+ if (shuttingDown)
73527
73840
  return;
73528
73841
  lost.dialError = error;
73529
- process.stderr.write(`envoy-channel: gave up opening a new NATS connection (${natsFailureReason(error)}); dialing again at the next heartbeat
73842
+ sessionStderr(`envoy-channel: gave up opening a new NATS connection (${natsFailureReason(error)}); dialing again at the next heartbeat
73530
73843
  `);
73531
73844
  return;
73532
73845
  }
@@ -73545,7 +73858,7 @@ async function startChannelSession(options) {
73545
73858
  watchConnection(live);
73546
73859
  await serialized(async () => {
73547
73860
  await withTimeout(live.flush(), options.handoffFlushTimeoutMs ?? HANDOFF_FLUSH_TIMEOUT_MS, "flushing NATS").catch((error) => {
73548
- process.stderr.write(`envoy-channel: could not confirm the relay subscription on the new NATS connection \u2014 ${natsFailureReason(error)}
73861
+ sessionStderr(`envoy-channel: could not confirm the relay subscription on the new NATS connection \u2014 ${natsFailureReason(error)}
73549
73862
  `);
73550
73863
  });
73551
73864
  if (shuttingDown || live !== connection || live.isClosed())
@@ -73555,7 +73868,7 @@ async function startChannelSession(options) {
73555
73868
  await register();
73556
73869
  }).catch((error) => {
73557
73870
  registrationFailed = true;
73558
- process.stderr.write(`envoy-channel: could not register on the new NATS connection (${messageFor(error)}); the next heartbeat retries
73871
+ sessionStderr(`envoy-channel: could not register on the new NATS connection (${messageFor(error)}); the next heartbeat retries
73559
73872
  `);
73560
73873
  });
73561
73874
  }
@@ -73571,7 +73884,7 @@ async function startChannelSession(options) {
73571
73884
  renewRelayEpoch();
73572
73885
  }
73573
73886
  } catch (error) {
73574
- process.stderr.write(`envoy-channel: the NATS connection's status reader failed \u2014 ${natsFailureReason(error)}
73887
+ sessionStderr(`envoy-channel: the NATS connection's status reader failed \u2014 ${natsFailureReason(error)}
73575
73888
  `);
73576
73889
  }
73577
73890
  })();
@@ -73602,6 +73915,8 @@ async function startChannelSession(options) {
73602
73915
  return fresh;
73603
73916
  },
73604
73917
  async unfollow(topics) {
73918
+ if (shuttingDown)
73919
+ return [];
73605
73920
  const requested = topics.length === 0 ? [...userTopics] : expandSubscriptionTopics(topics);
73606
73921
  const removed = requested.filter((topic) => userTopics.delete(topic));
73607
73922
  if (removed.length === 0)
@@ -73618,7 +73933,9 @@ async function startChannelSession(options) {
73618
73933
  if (shuttingDown)
73619
73934
  return;
73620
73935
  serialized(register).catch((error) => {
73621
- process.stderr.write(`envoy-channel: could not advertise this session's delivery modes (${messageFor(error)}); the next heartbeat retries
73936
+ if (shuttingDown)
73937
+ return;
73938
+ sessionStderr(`envoy-channel: could not advertise this session's delivery modes (${messageFor(error)}); the next heartbeat retries
73622
73939
  `);
73623
73940
  });
73624
73941
  },
@@ -73630,13 +73947,19 @@ async function startChannelSession(options) {
73630
73947
  },
73631
73948
  async rememberRole(role) {
73632
73949
  await serialized(async () => {
73950
+ if (shuttingDown)
73951
+ return;
73633
73952
  heldRole = role;
73634
73953
  await writeRoleRecord(roleStateFile(options.stateDirectory, identity.id), role);
73635
73954
  });
73636
73955
  },
73956
+ stopping() {
73957
+ return shuttingDown;
73958
+ },
73637
73959
  async shutdown() {
73638
- if (shuttingDown)
73960
+ if (shutdownStarted)
73639
73961
  return;
73962
+ shutdownStarted = true;
73640
73963
  shuttingDown = true;
73641
73964
  clearInterval(heartbeatTimer);
73642
73965
  clearRetry();
@@ -73736,12 +74059,14 @@ async function executeEnvoyTool(runtime, name, input) {
73736
74059
  }
73737
74060
  case EnvoyToolOperation.setRole: {
73738
74061
  const args = parseArguments(spec, input);
74062
+ refuseClaimWhileStopping(runtime.session, args.role);
73739
74063
  const sessionID = identity.id;
73740
74064
  const result = await runtime.client.setRole({
73741
74065
  sessionID,
73742
74066
  role: args.role,
73743
74067
  clientInstanceID: runtime.clientInstanceID
73744
74068
  });
74069
+ refuseClaimWhileStopping(runtime.session, args.role);
73745
74070
  if (!result.claimed)
73746
74071
  throw new Error(`role ${args.role} is held by ${result.holder}`);
73747
74072
  logRoleClaimWarnings(warnOnStderr, args.role, sessionID, result.warnings);
@@ -73767,6 +74092,10 @@ async function executeEnvoyTool(runtime, name, input) {
73767
74092
  }
73768
74093
  }
73769
74094
  }
74095
+ function refuseClaimWhileStopping(session, role) {
74096
+ if (session.stopping())
74097
+ throw new RoleClaimStoppingError(role);
74098
+ }
73770
74099
  function pluginStateDirectory() {
73771
74100
  const pluginData = configuredValue(process.env["CLAUDE_PLUGIN_DATA"]);
73772
74101
  if (pluginData === undefined) {
@@ -73777,6 +74106,13 @@ function pluginStateDirectory() {
73777
74106
  async function runEnvoyChannelServer() {
73778
74107
  const directory = projectDirectory();
73779
74108
  const pane = await legionPane(process.env);
74109
+ let stopping = false;
74110
+ const serverStderr = gatedStderr(() => stopping);
74111
+ const logLegionLine = (line) => {
74112
+ if (!stopping)
74113
+ logLegion(line);
74114
+ };
74115
+ const paneServer = { stopping: () => stopping, log: logLegionLine };
73780
74116
  const configFile = sessionConfigFile("claude", process.env);
73781
74117
  const currentSessionId = () => identity.id;
73782
74118
  const { dispatch, envoy, notice } = await sessionSettings(configFile, process.env, {
@@ -73784,7 +74120,7 @@ async function runEnvoyChannelServer() {
73784
74120
  session: currentSessionId
73785
74121
  });
73786
74122
  if (notice !== null)
73787
- process.stderr.write(`envoy-channel: ${notice}
74123
+ serverStderr(`envoy-channel: ${notice}
73788
74124
  `);
73789
74125
  const overrideSessionId = process.env["ENVOY_SESSION_ID"];
73790
74126
  const pluginData = configuredValue(process.env["CLAUDE_PLUGIN_DATA"]);
@@ -73808,7 +74144,7 @@ async function runEnvoyChannelServer() {
73808
74144
  if (own !== "")
73809
74145
  stampTitle(sessionId, own);
73810
74146
  } catch (error) {
73811
- process.stderr.write(`envoy-channel: could not write the session title for the dispatch command \u2014 ${messageFor(error)}; the dispatch command's writes carry no session title
74147
+ serverStderr(`envoy-channel: could not write the session title for the dispatch command \u2014 ${messageFor(error)}; the dispatch command's writes carry no session title
73812
74148
  `);
73813
74149
  }
73814
74150
  };
@@ -73818,8 +74154,9 @@ async function runEnvoyChannelServer() {
73818
74154
  CLAUDE_CODE_SESSION_ID: process.env["CLAUDE_CODE_SESSION_ID"]
73819
74155
  }));
73820
74156
  const refusal = `Envoy is off for this session: ${envoy.error ?? envoy.notice}`;
73821
- if (pane !== undefined)
73822
- stopPane(`a Legion pane needs Envoy for its task; ${refusal}`);
74157
+ if (pane !== undefined) {
74158
+ stopPane(`a Legion pane needs Envoy for its task; ${refusal}`, paneServer);
74159
+ }
73823
74160
  await serveEnvoyOff(MCP_SERVER_INFO, refusal);
73824
74161
  return;
73825
74162
  }
@@ -73838,14 +74175,15 @@ async function runEnvoyChannelServer() {
73838
74175
  const client = createEnvoyClient({
73839
74176
  baseUrl: envoy.url,
73840
74177
  fetch: globalThis.fetch,
73841
- credential: envoy.credential
74178
+ credential: envoy.credential,
74179
+ stopping: () => stopping
73842
74180
  });
73843
74181
  const clientInstanceID = newClientInstanceID();
73844
74182
  let runtime;
73845
74183
  let starting = "it reads its settings";
73846
74184
  let claim;
73847
74185
  const daemon = pane === undefined ? undefined : paneDaemonClient(pane.daemonUrl);
73848
- const phaseLog = paneReminderLog(logLegion);
74186
+ const phaseLog = paneReminderLog(logLegionLine);
73849
74187
  const claimBooted = Promise.withResolvers();
73850
74188
  let reportFirstTurn;
73851
74189
  const phaseHook = pane === undefined || daemon === undefined ? undefined : createPhaseHookEndpoint({
@@ -73906,7 +74244,7 @@ async function runEnvoyChannelServer() {
73906
74244
  },
73907
74245
  connected: () => modLink?.connected() === true
73908
74246
  },
73909
- warn: (text) => process.stderr.write(`envoy-channel: ${text}
74247
+ warn: (text) => serverStderr(`envoy-channel: ${text}
73910
74248
  `)
73911
74249
  });
73912
74250
  const writer = inbox ?? {
@@ -73927,7 +74265,6 @@ async function runEnvoyChannelServer() {
73927
74265
  const capabilities = () => sessionCapabilities({ pane: inboxSocket !== undefined, mod: modLink?.connected() === true });
73928
74266
  const booting = new AbortController;
73929
74267
  const stopped = Promise.withResolvers();
73930
- let stopping = false;
73931
74268
  let session;
73932
74269
  let stopNatsKeeper = () => {};
73933
74270
  const stop = () => {
@@ -73955,7 +74292,7 @@ async function runEnvoyChannelServer() {
73955
74292
  const linking = startModLink({
73956
74293
  sessionId: claudeSessionId({ CLAUDE_CODE_SESSION_ID: process.env["CLAUDE_CODE_SESSION_ID"] }),
73957
74294
  env: process.env,
73958
- warn: (text) => process.stderr.write(`envoy-channel: ${text}
74295
+ warn: (text) => serverStderr(`envoy-channel: ${text}
73959
74296
  `)
73960
74297
  }).then((link) => {
73961
74298
  modLink = link;
@@ -73966,7 +74303,7 @@ async function runEnvoyChannelServer() {
73966
74303
  else
73967
74304
  linked.resolve(link);
73968
74305
  }, (error) => {
73969
- process.stderr.write(`envoy-channel: no link to this session's Claude Code mod \u2014 ${messageFor(error)}; the session runs on without one
74306
+ serverStderr(`envoy-channel: no link to this session's Claude Code mod \u2014 ${messageFor(error)}; the session runs on without one
73970
74307
  `);
73971
74308
  });
73972
74309
  const router = (state) => {
@@ -73978,7 +74315,7 @@ async function runEnvoyChannelServer() {
73978
74315
  session: claude,
73979
74316
  sessionId: () => identity.id,
73980
74317
  state,
73981
- warn: (text) => process.stderr.write(`envoy-channel: ${text}
74318
+ warn: (text) => serverStderr(`envoy-channel: ${text}
73982
74319
  `),
73983
74320
  ...inboxSocket === undefined ? {} : { inbox: (input) => notifier.notification(input) }
73984
74321
  };
@@ -73989,19 +74326,24 @@ async function runEnvoyChannelServer() {
73989
74326
  const { inbound } = envoy;
73990
74327
  if ("off" in inbound) {
73991
74328
  if (pane !== undefined) {
73992
- stopPane(`a Legion pane's task reaches it over NATS, and inbound messages are off: ${inbound.off}`);
74329
+ stopPane(`a Legion pane's task reaches it over NATS, and inbound messages are off: ${inbound.off}`, paneServer);
73993
74330
  }
73994
74331
  stampOnce(() => identity.id);
73995
- session = inboundOffChannelSession({ identity, stateDirectory, why: inbound.off });
74332
+ session = inboundOffChannelSession({
74333
+ identity,
74334
+ stateDirectory,
74335
+ why: inbound.off,
74336
+ stopping: () => stopping
74337
+ });
73996
74338
  } else {
73997
74339
  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";
73998
74340
  const natsName = channelConnectionName(`claude-envoy-channel-${identity.id}`, bundlePath, name2);
73999
74341
  const dialled = await dialChannelInbound(inbound, envoy.url, currentSessionId, natsName, (text, dialError) => {
74000
74342
  if (dialError !== undefined)
74001
74343
  starting = text;
74002
- process.stderr.write(`envoy-channel: ${text}
74344
+ serverStderr(`envoy-channel: ${text}
74003
74345
  `);
74004
- }, import_nats5.connect, booting.signal).catch((error) => {
74346
+ }, import_nats5.connect, booting.signal, () => stopping).catch((error) => {
74005
74347
  if (stopping)
74006
74348
  return;
74007
74349
  throw error;
@@ -74020,6 +74362,9 @@ async function runEnvoyChannelServer() {
74020
74362
  session: currentSessionId,
74021
74363
  name: natsName,
74022
74364
  signal: booting.signal,
74365
+ stopping: () => stopping,
74366
+ warn: (text) => serverStderr(`envoy-channel: ${text}
74367
+ `),
74023
74368
  swapKeeper: (stop) => {
74024
74369
  stopNatsKeeper();
74025
74370
  stopNatsKeeper = stop;
@@ -74066,6 +74411,8 @@ async function runEnvoyChannelServer() {
74066
74411
  agentStream = startAgentStream({
74067
74412
  connection,
74068
74413
  liveView: dialled.liveView,
74414
+ warn: (text) => serverStderr(`envoy-channel: ${text}
74415
+ `),
74069
74416
  followsSessionId: configuredValue(overrideSessionId) === undefined,
74070
74417
  ...admission === undefined ? {} : { admitted: (id) => admission.admitted(id) },
74071
74418
  isPane: inbox !== undefined,
@@ -74096,7 +74443,7 @@ async function runEnvoyChannelServer() {
74096
74443
  clientInstanceID,
74097
74444
  session,
74098
74445
  signal: booting.signal,
74099
- log: logLegion,
74446
+ log: logLegionLine,
74100
74447
  stop: endPane,
74101
74448
  onFirstTurn: (started) => {
74102
74449
  reportFirstTurn = started;
@@ -75590,13 +75937,14 @@ async function runCodexEnvoyServer() {
75590
75937
  let recheck;
75591
75938
  const endedNow = (sessionId) => sessionEnded(codexEndedFile(stateDirectory, codexPid, sessionId));
75592
75939
  const configFile = sessionConfigFile("codex", process.env);
75593
- const warn = (text) => void process.stderr.write(`envoy-channel: ${text}
75594
- `);
75595
75940
  const bundlePath = resolve5(pluginRoot, process.argv[1] ?? "");
75596
75941
  let record;
75597
75942
  let runtime;
75598
75943
  let notReady = "this session's Envoy side starts at its first prompt";
75599
75944
  const stopping = new AbortController;
75945
+ const serverStderr = gatedStderr(() => stopping.signal.aborted);
75946
+ const warn = (text) => serverStderr(`envoy-channel: ${text}
75947
+ `);
75600
75948
  const server = new Server(MCP_SERVER_INFO, {
75601
75949
  capabilities: { tools: {} },
75602
75950
  instructions: CODEX_INSTRUCTIONS
@@ -75693,7 +76041,7 @@ async function runCodexEnvoyServer() {
75693
76041
  notReady = STANDBY_NOTE;
75694
76042
  const owning = await waitForOwnership(serversDirectory, process.pid, processStarted(process.pid) ?? null, stopping.signal, (entry) => {
75695
76043
  self2 = entry;
75696
- });
76044
+ }, undefined, undefined, warn);
75697
76045
  if (owning === undefined) {
75698
76046
  await stopped.promise;
75699
76047
  await server.close().catch(() => {
@@ -75776,7 +76124,8 @@ async function runCodexEnvoyServer() {
75776
76124
  const client = createEnvoyClient({
75777
76125
  baseUrl: envoy.url,
75778
76126
  credential: envoy.credential,
75779
- fetch: globalThis.fetch
76127
+ fetch: globalThis.fetch,
76128
+ stopping: () => stopping.signal.aborted
75780
76129
  });
75781
76130
  const clientInstanceID = newClientInstanceID();
75782
76131
  const runningSession = () => record?.session_id ?? bound.session_id;
@@ -75814,10 +76163,15 @@ async function runCodexEnvoyServer() {
75814
76163
  try {
75815
76164
  const { inbound } = envoy;
75816
76165
  if ("off" in inbound) {
75817
- session = inboundOffChannelSession({ identity: id, stateDirectory, why: inbound.off });
76166
+ session = inboundOffChannelSession({
76167
+ identity: id,
76168
+ stateDirectory,
76169
+ why: inbound.off,
76170
+ stopping: () => stopping.signal.aborted
76171
+ });
75818
76172
  } else {
75819
76173
  const natsName = channelConnectionName(`codex-envoy-channel-${id.id}`, bundlePath, name);
75820
- const dialled = await dialChannelInbound(inbound, envoy.url, () => id.id, natsName, warn, import_nats6.connect, stopping.signal).catch((error) => {
76174
+ const dialled = await dialChannelInbound(inbound, envoy.url, () => id.id, natsName, warn, import_nats6.connect, stopping.signal, () => stopping.signal.aborted).catch((error) => {
75821
76175
  if (isStopping)
75822
76176
  return;
75823
76177
  throw error;
@@ -75837,6 +76191,8 @@ async function runCodexEnvoyServer() {
75837
76191
  session: () => id.id,
75838
76192
  name: natsName,
75839
76193
  signal: stopping.signal,
76194
+ stopping: () => stopping.signal.aborted,
76195
+ warn,
75840
76196
  swapKeeper: (stop) => {
75841
76197
  stopNatsKeeper();
75842
76198
  stopNatsKeeper = stop;