@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.
@@ -2,5 +2,5 @@
2
2
  "name": "claude-envoy",
3
3
  "description": "Put Envoy events into the Claude Code session's own conversation and expose Envoy MCP tools.",
4
4
  "mcpServers": "./.mcp.json",
5
- "version": "6.13.0"
5
+ "version": "6.14.1"
6
6
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-envoy",
3
- "version": "6.13.0",
3
+ "version": "6.14.1",
4
4
  "description": "Put Envoy events into the Claude Code session's own conversation and expose Envoy MCP tools.",
5
5
  "mcpServers": {}
6
6
  }
package/README.md CHANGED
@@ -113,7 +113,26 @@ message from Dispatch's Agents page as that person's own turn.
113
113
  to 20,000 messages in 72 hours); a crash between handing a message over and recording it
114
114
  can deliver it twice, never lose it. A message that fails three times is replaced by one notice
115
115
  naming it. A registration the listener can give no consumer is refused by name, and the server
116
- says once on stderr that Envoy inbound is unavailable and asks again at every heartbeat.
116
+ says once, on stderr and as a notice to the session, that Envoy inbound is unavailable, and asks
117
+ again at every heartbeat. When a registration is accepted after that, it says once on stderr that
118
+ the session receives again, and tells the session once, as a notice, that Envoy inbound is
119
+ restored and that what the stream stored meanwhile arrives now. A registration the listener
120
+ answers with the bus-outage 503 (its message bus did not answer) is held for two minutes from
121
+ the first such answer, also where its retry got no answer or a 5xx that names no reason; after
122
+ that the server says once that the registration is not recorded for certain, since the retry
123
+ may have landed, and, when one is accepted, that the listener recorded one. A retry the
124
+ listener refuses with a reason, such as `consumer_limit`, is told at once as Envoy inbound
125
+ unavailable. A refusal or a lost relay subject after that notice is told once more, as Envoy
126
+ inbound unavailable, and the accepted registration after it says that Envoy inbound is
127
+ restored. An edge listener's 503 `repositories_unknown` (it could not read the repositories of
128
+ the session's projects) is told at once as Envoy GitHub topics withheld: the listener withholds
129
+ the messages of the session's GitHub topics. If the listener already held the session's
130
+ registration, it kept that registration and the session's consumer, so the session receives its
131
+ other messages; if it held none, the session receives nothing until a registration is accepted.
132
+ The notice and the stderr line say both. The accepted registration after it says that the
133
+ listener follows those topics again. A refusal or a lost relay subject after that notice is told
134
+ once more, as Envoy inbound unavailable. A session whose shutdown has begun registers nothing,
135
+ and is told neither that Envoy inbound is unavailable nor that it is restored.
117
136
  - No receipt is published. A role message reaches this session as a forward the listener stored on
118
137
  the session's own subject, which its consumer relays and whose `done` answers for it; the
119
138
  listener waits only for the stream's acknowledgement that it stored the forward. A frame's reply
@@ -128,7 +147,9 @@ message from Dispatch's Agents page as that person's own turn.
128
147
  so Dispatch learns what the session takes without waiting for a heartbeat. With no capability
129
148
  the listener refuses every targeted delivery (`session … does not advertise aside`) and
130
149
  Dispatch shows the session as taking no messages, which is the right answer for a session
131
- nothing can reach.
150
+ nothing can reach. A plain `envoy_send` names no mode, so the listener stores it, and it
151
+ answers `no_receiver` with no `recipient_state`: the sender reads that the session runs but
152
+ takes no message into its conversation now, and never that it is `live`.
132
153
  - A targeted Dispatch delivery the shared renderer rejects is never shown to the model: when it
133
154
  names a message, the server posts `Invalid Dispatch targeted delivery frame` to
134
155
  `POST /api/v1/messages/{id}/reply` so the attempt fails visibly; otherwise it is logged and dropped.
@@ -512,6 +533,25 @@ both committed files to none; the range is a field of the entry's source, not a
512
533
  entry.
513
534
  A checkout's `package.json` version names no release either, for the same reason: the build job
514
535
  writes the release's version into the manifest it packs.
536
+ On npm 12 or later, `claude plugin update claude-envoy@legion-plugins` fails with
537
+ `code EALLOWREMOTE`, unless the one command allows a fetch from a URL:
538
+
539
+ ```sh
540
+ npm_config_allow_remote=all claude plugin update claude-envoy@legion-plugins
541
+ ```
542
+
543
+ Claude Code fetches the package by its tarball URL on the registry
544
+ (`https://registry.npmjs.org/@sjawhar/claude-envoy/-/claude-envoy-<version>.tgz`) and not by its
545
+ name. npm 12 sets `allow-remote` to `none` by default, and with that setting it refuses to fetch a
546
+ package from a URL: `Could not download @sjawhar/claude-envoy@2.31.4 from the npm registry: code
547
+ EALLOWREMOTE` (Claude Code 2.1.325, npm 12.0.1). The same package fetched by its name passes, and
548
+ the package declares no dependencies, so the cause is in how Claude Code asks npm and no change to
549
+ this package or to the marketplace entry removes it. The variable applies to that one command, so
550
+ every other install on the machine keeps npm's default.
551
+ In a shell that a Claude Code session started, `CLAUDE_CONFIG_DIR` names that session's
552
+ configuration directory, so put `env -u CLAUDE_CONFIG_DIR` in front of the command to update the
553
+ default `~/.claude`. Each scope that holds the plugin (user, project) updates on its own, so run
554
+ the update in each one.
515
555
  Each release publishes its own changelog entries into its GitHub release body, rendered from the
516
556
  fragments its own commits added, and each fragment stays under `.changes/unreleased/`.
517
557
  `CHANGELOG.md` is the history before that and stops where the fragments begin.
@@ -14455,6 +14455,11 @@ var COMMENT_ARGUMENT = "Comment id (uuid), or a dispatch://KEY/comment/<id> or "
14455
14455
  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.";
14456
14456
  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.";
14457
14457
  var DISPATCH_HANDOFF_BODY_MAX = 262144;
14458
+ var STEP_RESULTS = ["passed", "failed", "stopped"];
14459
+ var PLANNED_STEP_STATES = ["not started", "running", ...STEP_RESULTS];
14460
+ var STEP_TASK_MAX = 64;
14461
+ var STEP_TASK_PATTERN = new RegExp(`^[a-z0-9][a-z0-9-]{0,${STEP_TASK_MAX - 1}}$`);
14462
+ var STEP_TASK_RULE_WORDS = `lowercase letters, digits and hyphens, starting with a letter or a digit, at most ${STEP_TASK_MAX} bytes`;
14458
14463
  var HANDOFF_PHASE_PATTERN = /^[a-z][a-z0-9-]{0,31}$/;
14459
14464
  var HANDOFF_PHASE_RULE_WORDS = "a lowercase letter, then up to 31 lowercase letters, digits or hyphens, such as implement";
14460
14465
  var HANDOFF_PHASE_RULE = `phase is not a handoff phase: ${HANDOFF_PHASE_RULE_WORDS}`;
@@ -15310,7 +15315,7 @@ var dispatchToolSpecs = [
15310
15315
  {
15311
15316
  name: "dispatch_steps",
15312
15317
  example: { issue: "DSP-1" },
15313
- 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}`,
15318
+ 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}`,
15314
15319
  arguments: (z) => ({
15315
15320
  issue: z.string().describe(ISSUE_REFERENCE)
15316
15321
  }),
@@ -19182,6 +19187,7 @@ var SESSION_LIVE_WINDOW_MS = 300000;
19182
19187
  var LISTENER_CALL_TIMEOUT_MS = 5000;
19183
19188
  var LISTENER_CALL_RETRY_DELAY_MS = 250;
19184
19189
  var LISTENER_CALL_ATTEMPTS = 2;
19190
+ var BUS_UNANSWERED_PREFIX = "envoy: the message bus did not answer";
19185
19191
  // ../contracts/src/related-forms.ts
19186
19192
  function relatedCheckFormOf(suggestions) {
19187
19193
  const { outcome, missing } = suggestions;
@@ -32990,6 +32996,11 @@ function stepLine(record) {
32990
32996
  ...record.ended_at === null ? ["running", "running"] : [record.ended_at, orDash(record.result)]
32991
32997
  ].join(" ");
32992
32998
  }
32999
+ function taskLine(task, needs, planned) {
33000
+ const states = planned.map((step) => `${step.step} ${step.name} ${step.state}`);
33001
+ const needed = needs === null ? "-" : `[${needs.join(",")}]`;
33002
+ return `task ${task} needs ${needed}: ${states.join(", ")}`;
33003
+ }
32993
33004
  function variantLines(records) {
32994
33005
  const newest = Math.max(...records.map((record) => record.generation));
32995
33006
  const named = records.find((record) => record.generation === newest && record.experiment != null && record.variant != null);
@@ -32998,13 +33009,20 @@ function variantLines(records) {
32998
33009
  async function stepsCommand(context) {
32999
33010
  const { client, issue } = context;
33000
33011
  const read = await client.listSteps(issue());
33001
- const tasks = (read.tasks ?? []).map((task) => ({ task: task.task, steps: task.steps ?? [] }));
33012
+ const tasks = (read.tasks ?? []).map((task) => ({ ...task, steps: task.steps ?? [] }));
33002
33013
  const records = tasks.flatMap((task) => task.steps);
33014
+ const lines = tasks.flatMap((task) => {
33015
+ const runs = task.steps.map(stepLine);
33016
+ const planned = task.planned ?? [];
33017
+ if (planned.length === 0)
33018
+ return runs;
33019
+ return [taskLine(task.task, task.needs ?? null, planned), ...runs];
33020
+ });
33003
33021
  return {
33004
33022
  text: [
33005
33023
  `${read.issue}: ${records.length} steps in ${tasks.length} tasks`,
33006
33024
  ...variantLines(records),
33007
- ...records.map(stepLine)
33025
+ ...lines
33008
33026
  ].join(`
33009
33027
  `),
33010
33028
  details: { issue: read.issue, tasks }
@@ -38042,6 +38060,8 @@ function keepNatsCredential(connection, credential, warn) {
38042
38060
  if (credential.needsReconnect())
38043
38061
  await connection.reconnect();
38044
38062
  } catch (error) {
38063
+ if (stopped)
38064
+ return;
38045
38065
  if (error instanceof SessionMovedError) {
38046
38066
  schedule(0);
38047
38067
  return;
package/dist/dispatch.js CHANGED
@@ -15055,6 +15055,11 @@ var COMMENT_ARGUMENT = "Comment id (uuid), or a dispatch://KEY/comment/<id> or "
15055
15055
  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.";
15056
15056
  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.";
15057
15057
  var DISPATCH_HANDOFF_BODY_MAX = 262144;
15058
+ var STEP_RESULTS = ["passed", "failed", "stopped"];
15059
+ var PLANNED_STEP_STATES = ["not started", "running", ...STEP_RESULTS];
15060
+ var STEP_TASK_MAX = 64;
15061
+ var STEP_TASK_PATTERN = new RegExp(`^[a-z0-9][a-z0-9-]{0,${STEP_TASK_MAX - 1}}$`);
15062
+ var STEP_TASK_RULE_WORDS = `lowercase letters, digits and hyphens, starting with a letter or a digit, at most ${STEP_TASK_MAX} bytes`;
15058
15063
  var HANDOFF_PHASE_PATTERN = /^[a-z][a-z0-9-]{0,31}$/;
15059
15064
  var HANDOFF_PHASE_RULE_WORDS = "a lowercase letter, then up to 31 lowercase letters, digits or hyphens, such as implement";
15060
15065
  var HANDOFF_PHASE_RULE = `phase is not a handoff phase: ${HANDOFF_PHASE_RULE_WORDS}`;
@@ -15910,7 +15915,7 @@ var dispatchToolSpecs = [
15910
15915
  {
15911
15916
  name: "dispatch_steps",
15912
15917
  example: { issue: "DSP-1" },
15913
- 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}`,
15918
+ 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}`,
15914
15919
  arguments: (z) => ({
15915
15920
  issue: z.string().describe(ISSUE_REFERENCE)
15916
15921
  }),
@@ -19782,6 +19787,7 @@ var SESSION_LIVE_WINDOW_MS = 300000;
19782
19787
  var LISTENER_CALL_TIMEOUT_MS = 5000;
19783
19788
  var LISTENER_CALL_RETRY_DELAY_MS = 250;
19784
19789
  var LISTENER_CALL_ATTEMPTS = 2;
19790
+ var BUS_UNANSWERED_PREFIX = "envoy: the message bus did not answer";
19785
19791
  // ../contracts/src/related-forms.ts
19786
19792
  function relatedCheckFormOf(suggestions) {
19787
19793
  const { outcome, missing } = suggestions;
@@ -29802,6 +29808,8 @@ function keepNatsCredential(connection, credential, warn) {
29802
29808
  if (credential.needsReconnect())
29803
29809
  await connection.reconnect();
29804
29810
  } catch (error) {
29811
+ if (stopped)
29812
+ return;
29805
29813
  if (error instanceof SessionMovedError) {
29806
29814
  schedule(0);
29807
29815
  return;
@@ -39096,6 +39104,11 @@ function stepLine(record) {
39096
39104
  ...record.ended_at === null ? ["running", "running"] : [record.ended_at, orDash(record.result)]
39097
39105
  ].join(" ");
39098
39106
  }
39107
+ function taskLine(task, needs, planned) {
39108
+ const states = planned.map((step) => `${step.step} ${step.name} ${step.state}`);
39109
+ const needed = needs === null ? "-" : `[${needs.join(",")}]`;
39110
+ return `task ${task} needs ${needed}: ${states.join(", ")}`;
39111
+ }
39099
39112
  function variantLines(records) {
39100
39113
  const newest = Math.max(...records.map((record) => record.generation));
39101
39114
  const named = records.find((record) => record.generation === newest && record.experiment != null && record.variant != null);
@@ -39104,13 +39117,20 @@ function variantLines(records) {
39104
39117
  async function stepsCommand(context) {
39105
39118
  const { client, issue } = context;
39106
39119
  const read = await client.listSteps(issue());
39107
- const tasks = (read.tasks ?? []).map((task) => ({ task: task.task, steps: task.steps ?? [] }));
39120
+ const tasks = (read.tasks ?? []).map((task) => ({ ...task, steps: task.steps ?? [] }));
39108
39121
  const records = tasks.flatMap((task) => task.steps);
39122
+ const lines = tasks.flatMap((task) => {
39123
+ const runs = task.steps.map(stepLine);
39124
+ const planned = task.planned ?? [];
39125
+ if (planned.length === 0)
39126
+ return runs;
39127
+ return [taskLine(task.task, task.needs ?? null, planned), ...runs];
39128
+ });
39109
39129
  return {
39110
39130
  text: [
39111
39131
  `${read.issue}: ${records.length} steps in ${tasks.length} tasks`,
39112
39132
  ...variantLines(records),
39113
- ...records.map(stepLine)
39133
+ ...lines
39114
39134
  ].join(`
39115
39135
  `),
39116
39136
  details: { issue: read.issue, tasks }
@@ -40163,6 +40183,9 @@ class EnvoyApiError extends Error {
40163
40183
  this.notSent = notSentAnswer && shown.afterUnanswered !== true;
40164
40184
  }
40165
40185
  }
40186
+ function isBusUnanswered(error) {
40187
+ return error instanceof EnvoyApiError && error.details.status === 503 && error.message.startsWith(BUS_UNANSWERED_PREFIX);
40188
+ }
40166
40189
  var mintedDedupeKey2 = new RegExp(MINTED_DEDUPE_KEY_PATTERN);
40167
40190
 
40168
40191
  class EnvoySendUnconfirmedError extends Error {
@@ -40185,6 +40208,28 @@ class EnvoySendUnconfirmedError extends Error {
40185
40208
  this.resendSafe = resendSafe;
40186
40209
  }
40187
40210
  }
40211
+ var STOP_GATE = {
40212
+ subscribe: "refused",
40213
+ unsubscribe: "refused",
40214
+ getInterest: "refused",
40215
+ setRole: "refused",
40216
+ getRole: "refused",
40217
+ unregisterSession: "sent",
40218
+ handBack: "sent",
40219
+ send: "sent",
40220
+ publish: "sent",
40221
+ listSessions: "sent"
40222
+ };
40223
+
40224
+ class EnvoyStoppingError extends Error {
40225
+ call;
40226
+ name = "EnvoyStoppingError";
40227
+ constructor(call, method, url) {
40228
+ super(`this session is stopping, so it sends the listener nothing: ${method} ${url} was not sent`);
40229
+ this.call = call;
40230
+ }
40231
+ }
40232
+ var handBacks = new WeakMap;
40188
40233
  function resolveCallTiming(config) {
40189
40234
  return {
40190
40235
  timeoutMs: config.timeoutMs ?? LISTENER_CALL_TIMEOUT_MS,
@@ -40208,7 +40253,9 @@ function createEnvoyClient(config) {
40208
40253
  }
40209
40254
  };
40210
40255
  const noAnswer = (method, url, error) => new Error(`${method ?? "GET"} ${shown(url)} got no answer: ${errorClass(error)}`);
40211
- const attemptOnce = async (url, init, deadlineMs, actingSession) => {
40256
+ const attemptOnce = async (url, init, deadlineMs, actingSession, refusedByStop) => {
40257
+ if (refusedByStop())
40258
+ return { stopping: true };
40212
40259
  let response;
40213
40260
  let unminted;
40214
40261
  const deadline = AbortSignal.timeout(deadlineMs);
@@ -40224,6 +40271,8 @@ function createEnvoyClient(config) {
40224
40271
  }
40225
40272
  if (unminted !== undefined && deadline.aborted)
40226
40273
  return { notSent: unminted };
40274
+ if (refusedByStop())
40275
+ return { stopping: true };
40227
40276
  sent.note(presented);
40228
40277
  for (const [name, value] of Object.entries(presented ?? {}))
40229
40278
  headers.set(name, value);
@@ -40251,59 +40300,70 @@ function createEnvoyClient(config) {
40251
40300
  return { unanswered: noAnswer(init.method, url, error) };
40252
40301
  }
40253
40302
  };
40254
- const request = async (path, init, options = {}) => {
40303
+ const request = async (call, path, init, options = {}) => {
40255
40304
  const url = `${baseUrl}${path}`;
40256
40305
  const tries = options.retry === false ? 1 : attempts;
40306
+ const gated = STOP_GATE[call] === "refused";
40307
+ const refusedByStop = () => gated && config.stopping?.() === true;
40308
+ let busUnanswered;
40309
+ let sent = false;
40257
40310
  let unanswered = false;
40311
+ let lastEnd;
40258
40312
  for (let attempt = 0;attempt < tries; attempt += 1) {
40259
40313
  options.onAttempt?.();
40260
- const outcome = await attemptOnce(url, init, options.timeoutMs ?? timeoutMs, options.actingSession);
40314
+ const outcome = await attemptOnce(url, init, options.timeoutMs ?? timeoutMs, options.actingSession, refusedByStop);
40315
+ if ("stopping" in outcome) {
40316
+ if (sent && lastEnd !== undefined)
40317
+ throw lastEnd();
40318
+ throw new EnvoyStoppingError(call, init.method ?? "GET", shown(url));
40319
+ }
40320
+ let end;
40261
40321
  if ("unanswered" in outcome) {
40262
40322
  unanswered = true;
40263
40323
  options.onUnanswered?.();
40264
- if (attempt + 1 < tries) {
40265
- await waitForRetry(retryDelayMs);
40266
- continue;
40267
- }
40268
- throw outcome.unanswered;
40269
- }
40270
- if ("notSent" in outcome) {
40271
- if (attempt + 1 < tries) {
40272
- await waitForRetry(retryDelayMs);
40273
- continue;
40274
- }
40275
- options.onNotSent?.();
40276
- throw outcome.notSent;
40277
- }
40278
- const { response, body } = outcome;
40279
- if (response.ok)
40280
- return body;
40281
- const redacted = tokens();
40282
- const error = new EnvoyApiError({
40283
- method: init.method ?? "GET",
40284
- url: shown(url),
40285
- status: response.status,
40286
- responseBody: body
40287
- }, {
40288
- tokens: redacted,
40289
- redirectTo: redirectOrigin(response, url, redacted),
40290
- afterUnanswered: unanswered
40291
- });
40292
- if (mayHaveReachedServer(response.status)) {
40324
+ sent = true;
40325
+ end = () => busUnanswered ?? outcome.unanswered;
40326
+ } else if ("notSent" in outcome) {
40327
+ end = () => {
40328
+ options.onNotSent?.();
40329
+ return busUnanswered ?? outcome.notSent;
40330
+ };
40331
+ } else {
40332
+ const { response, body } = outcome;
40333
+ if (response.ok)
40334
+ return body;
40335
+ const redacted = tokens();
40336
+ const error = new EnvoyApiError({
40337
+ method: init.method ?? "GET",
40338
+ url: shown(url),
40339
+ status: response.status,
40340
+ responseBody: body
40341
+ }, {
40342
+ tokens: redacted,
40343
+ redirectTo: redirectOrigin(response, url, redacted),
40344
+ afterUnanswered: unanswered
40345
+ });
40346
+ if (!mayHaveReachedServer(response.status))
40347
+ throw error;
40293
40348
  if (!error.notSent) {
40294
40349
  unanswered = true;
40295
40350
  options.onUnanswered?.();
40351
+ sent = true;
40296
40352
  }
40297
- if (attempt + 1 < tries) {
40298
- await waitForRetry(retryDelayMs);
40299
- continue;
40300
- }
40353
+ if (options.busUnansweredStands === true && isBusUnanswered(error))
40354
+ busUnanswered = error;
40355
+ end = () => error.reason === undefined ? busUnanswered ?? error : error;
40301
40356
  }
40302
- throw error;
40357
+ lastEnd = end;
40358
+ if (attempt + 1 < tries) {
40359
+ await waitForRetry(retryDelayMs);
40360
+ continue;
40361
+ }
40362
+ throw end();
40303
40363
  }
40304
40364
  throw new Error("Envoy request exhausted retries");
40305
40365
  };
40306
- const post = (path, body, options) => request(path, {
40366
+ const post = (call, path, body, options) => request(call, path, {
40307
40367
  method: "POST",
40308
40368
  headers: {
40309
40369
  "Content-Type": "application/json",
@@ -40327,16 +40387,17 @@ function createEnvoyClient(config) {
40327
40387
  plugin: input.plugin.name,
40328
40388
  plugin_version: input.plugin.version
40329
40389
  });
40330
- return {
40331
- subscribe: async (input) => parseSubscribeAnswer(answerJson(await post("/v1/interests/subscribe", subscribeBody(input), { actingSession: input.sessionID }), "POST", "/v1/interests/subscribe")),
40332
- unsubscribe: async (input) => {
40333
- await post("/v1/interests/unsubscribe", {
40334
- session_id: input.sessionID,
40335
- topics: expandSubscriptionTopics(input.topics),
40336
- ...input.clientInstanceID === undefined ? {} : { client_instance_id: input.clientInstanceID }
40337
- }, { actingSession: input.sessionID });
40338
- },
40339
- getInterest: async (sessionID) => InterestWireSchema.parse(answerJson(await request(`/v1/interests/${sessionID}`, {}), "GET", `/v1/interests/${sessionID}`)),
40390
+ const removeTopics = async (call, input) => {
40391
+ await post(call, "/v1/interests/unsubscribe", {
40392
+ session_id: input.sessionID,
40393
+ topics: expandSubscriptionTopics(input.topics),
40394
+ ...input.clientInstanceID === undefined ? {} : { client_instance_id: input.clientInstanceID }
40395
+ }, { actingSession: input.sessionID, busUnansweredStands: true });
40396
+ };
40397
+ const client = {
40398
+ subscribe: async (input) => parseSubscribeAnswer(answerJson(await post("subscribe", "/v1/interests/subscribe", subscribeBody(input), { actingSession: input.sessionID, busUnansweredStands: true }), "POST", "/v1/interests/subscribe")),
40399
+ unsubscribe: (input) => removeTopics("unsubscribe", input),
40400
+ getInterest: async (sessionID) => InterestWireSchema.parse(answerJson(await request("getInterest", `/v1/interests/${sessionID}`, {}), "GET", `/v1/interests/${sessionID}`)),
40340
40401
  send: async (input) => {
40341
40402
  const idempotencyKey = input.idempotencyKey ?? crypto.randomUUID();
40342
40403
  let unanswered = false;
@@ -40344,7 +40405,7 @@ function createEnvoyClient(config) {
40344
40405
  let made = 0;
40345
40406
  let response;
40346
40407
  try {
40347
- const answer = await post("/v1/messages/send", {
40408
+ const answer = await post("send", "/v1/messages/send", {
40348
40409
  source: input.source ?? "agent",
40349
40410
  ...sourceSession(input.sourceSessionID),
40350
40411
  target_session: input.targetSessionID,
@@ -40374,19 +40435,24 @@ function createEnvoyClient(config) {
40374
40435
  throw error;
40375
40436
  throw new EnvoySendUnconfirmedError(input.targetSessionID, idempotencyKey, made, error);
40376
40437
  }
40377
- return {
40438
+ const stored = {
40378
40439
  envelope: response,
40379
40440
  recipient: response.recipient ?? input.targetSessionID,
40380
40441
  confirmed: response.recipient !== undefined,
40381
- recipientState: response.recipient_state ?? "live",
40382
- state: response.state === "stopped" ? "stopped" : "connected",
40383
40442
  ...lastSeenOf(response.last_seen),
40384
40443
  duplicate: response.duplicate === true
40385
40444
  };
40445
+ if (response.state === "no_receiver")
40446
+ return { ...stored, state: "no_receiver" };
40447
+ return {
40448
+ ...stored,
40449
+ recipientState: response.recipient_state ?? "live",
40450
+ state: response.state === "stopped" ? "stopped" : "connected"
40451
+ };
40386
40452
  },
40387
40453
  publish: async (input) => {
40388
40454
  const idempotencyKey = input.idempotencyKey ?? crypto.randomUUID();
40389
- const raw = answerJson(await post("/v1/messages/publish", {
40455
+ const raw = answerJson(await post("publish", "/v1/messages/publish", {
40390
40456
  source: input.source ?? "agent",
40391
40457
  ...sourceSession(input.sourceSessionID),
40392
40458
  topic: input.topic,
@@ -40414,7 +40480,7 @@ function createEnvoyClient(config) {
40414
40480
  },
40415
40481
  unregisterSession: async (input) => {
40416
40482
  const query = input.clientInstanceID === undefined ? "" : `?client_instance_id=${encodeURIComponent(input.clientInstanceID)}`;
40417
- await request(`/v1/sessions/${encodeURIComponent(input.sessionID)}${query}`, { method: "DELETE" }, {
40483
+ await request("unregisterSession", `/v1/sessions/${encodeURIComponent(input.sessionID)}${query}`, { method: "DELETE" }, {
40418
40484
  actingSession: input.sessionID,
40419
40485
  ...input.timeoutMs === undefined ? {} : { timeoutMs: Math.max(1, input.timeoutMs), retry: false }
40420
40486
  });
@@ -40431,7 +40497,7 @@ function createEnvoyClient(config) {
40431
40497
  };
40432
40498
  let raw;
40433
40499
  try {
40434
- raw = await post("/v1/roles/set", body, { actingSession: input.sessionID });
40500
+ raw = await post("setRole", "/v1/roles/set", body, { actingSession: input.sessionID });
40435
40501
  } catch (error) {
40436
40502
  if (error instanceof EnvoyApiError && error.details.status === 409) {
40437
40503
  let answer;
@@ -40449,7 +40515,7 @@ function createEnvoyClient(config) {
40449
40515
  const { warnings, ...interest } = RoleSetWireSchema.parse(answerJson(raw, "POST", "/v1/roles/set"));
40450
40516
  return { claimed: true, interest, warnings };
40451
40517
  },
40452
- getRole: async (role) => RoleWireSchema.parse(answerJson(await request(`/v1/roles/${encodeURIComponent(role)}`, { method: "GET" }), "GET", `/v1/roles/${encodeURIComponent(role)}`)),
40518
+ getRole: async (role) => RoleWireSchema.parse(answerJson(await request("getRole", `/v1/roles/${encodeURIComponent(role)}`, { method: "GET" }), "GET", `/v1/roles/${encodeURIComponent(role)}`)),
40453
40519
  listSessions: async (input = {}) => {
40454
40520
  const search = new URLSearchParams;
40455
40521
  if (input.directory !== undefined)
@@ -40459,9 +40525,11 @@ function createEnvoyClient(config) {
40459
40525
  if (input.include !== undefined)
40460
40526
  search.set("include", input.include);
40461
40527
  const query = search.size === 0 ? "" : `?${search.toString()}`;
40462
- return SessionWireSchema.array().parse(answerJson(await request(`/v1/sessions${query}`, {}), "GET", `/v1/sessions${query}`));
40528
+ return SessionWireSchema.array().parse(answerJson(await request("listSessions", `/v1/sessions${query}`, {}), "GET", `/v1/sessions${query}`));
40463
40529
  }
40464
40530
  };
40531
+ handBacks.set(client, (input) => removeTopics("handBack", input));
40532
+ return client;
40465
40533
  }
40466
40534
  function waitForRetry(delayMs) {
40467
40535
  const { promise, resolve } = Promise.withResolvers();