@sjawhar/pi-envoy 16.10.0 → 16.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/dispatch.js CHANGED
@@ -14571,6 +14571,7 @@ function serviceSubjectLabel(subject) {
14571
14571
  }
14572
14572
  return subject;
14573
14573
  }
14574
+ var ISSUE_CLAIM_UNRESPONSIVE_GRACE_MS = 20 * 60 * 1000;
14574
14575
  var MAX_ISSUE_BLOCKERS = 20;
14575
14576
  var ISSUE_TITLE_MAX = 1000;
14576
14577
  var PROJECT_NAME_MAX = 80;
@@ -14900,15 +14901,38 @@ var AGENT_STREAM_LIMITS = {
14900
14901
  commandDescriptionChars: 200
14901
14902
  };
14902
14903
  // ../contracts/src/claim-holds.ts
14903
- function claimHolds(claim, titles) {
14904
+ var HOLDING_OF = {
14905
+ gone: "lapsed",
14906
+ live: "holds",
14907
+ unknown: "unknown",
14908
+ unresponsive: "unresponsive"
14909
+ };
14910
+ function claimHolds(claim, titles, liveness = {}) {
14904
14911
  if (claim.actor.kind !== "session") {
14905
14912
  return "holds";
14906
14913
  }
14914
+ const state = liveness.holder_state;
14915
+ if (state != null) {
14916
+ return HOLDING_OF[state];
14917
+ }
14907
14918
  if (titles === undefined) {
14908
14919
  return "unknown";
14909
14920
  }
14910
14921
  return titles.has(claim.actor.id) ? "holds" : "lapsed";
14911
14922
  }
14923
+ function claimTakeableAt(liveness, lastSeen = undefined) {
14924
+ if (liveness.takeable_at != null) {
14925
+ return liveness.takeable_at;
14926
+ }
14927
+ if (liveness.holder_state !== "unresponsive") {
14928
+ return null;
14929
+ }
14930
+ const seen = liveness.last_seen == null ? lastSeen : Date.parse(liveness.last_seen);
14931
+ if (seen === undefined || !Number.isFinite(seen) || seen <= 0) {
14932
+ return null;
14933
+ }
14934
+ return new Date(seen + ISSUE_CLAIM_UNRESPONSIVE_GRACE_MS).toISOString();
14935
+ }
14912
14936
  // ../contracts/src/dispatch-href.ts
14913
14937
  function hasControlCharacter(value) {
14914
14938
  return /\p{Cc}/u.test(value);
@@ -15150,7 +15174,12 @@ var ISSUE_STATUSES = [
15150
15174
  "retro",
15151
15175
  "done"
15152
15176
  ];
15153
- var ISSUE_ROUTE_STATUSES = ["live", "no_holder", "unknown"];
15177
+ var ISSUE_ROUTE_STATUSES = [
15178
+ "live",
15179
+ "holder_unresponsive",
15180
+ "no_holder",
15181
+ "unknown"
15182
+ ];
15154
15183
  var DOC_EDIT_OPS = [
15155
15184
  "replace",
15156
15185
  "delete",
@@ -15575,7 +15604,7 @@ var dispatchToolSpecs = [
15575
15604
  label: z.string().describe("Optional label filter.").optional(),
15576
15605
  priority: z.array(z.number({ int: true, min: 0, max: 3 }).nullable(), { min: 1, max: 5 }).describe("Optional priority filter: one or more of 0 (P0, highest) through 3 (P3, lowest), and null " + "for an issue with no priority; an issue matching any listed value is returned.").optional(),
15577
15606
  updated_since: z.string().describe("Optional RFC3339 timestamp; only issues updated at or after it.").optional(),
15578
- route_status: z.enum(ISSUE_ROUTE_STATUSES).describe("Optional: only open issues whose route is in this state. live: a running session holds " + "the role or is the routed session. no_holder: nobody running holds the role, or the " + "session is not running, right now. unknown: the Envoy listener did not answer.").optional(),
15607
+ route_status: z.enum(ISSUE_ROUTE_STATUSES).describe("Optional: only open issues whose route is in this state. live: a running session holds " + "the role or is the routed session. holder_unresponsive: that session has missed its " + "heartbeats without ending, so the route still reaches it and its messages wait. " + "no_holder: nobody running holds the role, or the session is gone, right now. " + "unknown: the Envoy listener did not answer.").optional(),
15579
15608
  limit: z.number({ int: true, min: 1, max: MAX_ISSUE_PAGE_LIMIT }).describe(`Maximum rows, 1-${MAX_ISSUE_PAGE_LIMIT}; default ${DEFAULT_ISSUE_PAGE_LIMIT}.`).optional(),
15580
15609
  offset: z.number({ int: true, min: 0 }).describe("Rows to skip before the page; nonnegative integer; default 0.").optional(),
15581
15610
  all: z.boolean().describe("Take every matching issue in one unpaged read, so no row is missed or repeated while " + "the list changes. Refused with limit or offset.").optional()
@@ -19732,22 +19761,50 @@ function componentsLine(components) {
19732
19761
  return "Components: unassigned";
19733
19762
  }
19734
19763
  }
19735
- function claimText(claim, titles) {
19736
- const holding = claimHolds(claim, titles);
19737
- const marker = holding === "unknown" ? " \xB7 liveness unknown" : holding === "lapsed" ? " \xB7 not running" : "";
19764
+ function claimText(claim, agents, read = {}) {
19765
+ const titles = agents?.titles;
19766
+ const liveness = holderLiveness(claim, agents, read);
19767
+ const holding = claimHolds(claim, titles, liveness);
19768
+ const takeableAt = claimTakeableAt(liveness);
19769
+ const unresponsive = liveness.holder_state === "unresponsive" && liveness.last_seen != null ? ` \xB7 unresponsive since ${liveness.last_seen}${takeableAt === null ? "" : `, takeable at ${takeableAt}`}` : " \xB7 unresponsive";
19770
+ const marker = holding === "unknown" ? " \xB7 liveness unknown" : holding === "lapsed" ? " \xB7 not running" : holding === "unresponsive" ? unresponsive : "";
19738
19771
  return `${actorLabel(claim.actor, titles)} since ${claim.at}${marker}`;
19739
19772
  }
19740
- async function liveSessionTitles(client, needed) {
19773
+ function holderLiveness(claim, agents, read) {
19774
+ if (claim.actor.kind !== "session")
19775
+ return read;
19776
+ const row = agents?.liveness.get(claim.actor.id);
19777
+ if (row === undefined)
19778
+ return read;
19779
+ const holderState = read.holder_state ?? row.holder_state;
19780
+ const lastSeen = read.last_seen ?? row.last_seen;
19781
+ const takeableAt = read.takeable_at ?? row.takeable_at;
19782
+ return {
19783
+ ...holderState === undefined ? {} : { holder_state: holderState },
19784
+ ...lastSeen === undefined ? {} : { last_seen: lastSeen },
19785
+ ...takeableAt === undefined ? {} : { takeable_at: takeableAt }
19786
+ };
19787
+ }
19788
+ async function liveAgents(client, needed) {
19741
19789
  if (!needed) {
19742
19790
  return;
19743
19791
  }
19744
19792
  try {
19745
19793
  const agents = await client.listAgents();
19746
- return new Map(agents.map((agent) => [agent.session_id, agent.title]));
19794
+ return {
19795
+ titles: new Map(agents.map((agent) => [agent.session_id, agent.title])),
19796
+ liveness: new Map(agents.map((agent) => [agent.session_id, agentLiveness(agent)]))
19797
+ };
19747
19798
  } catch {
19748
19799
  return;
19749
19800
  }
19750
19801
  }
19802
+ function agentLiveness(agent) {
19803
+ return {
19804
+ ...agent.state === undefined ? {} : { holder_state: agent.state },
19805
+ ...agent.last_seen > 0 ? { last_seen: new Date(agent.last_seen).toISOString() } : {}
19806
+ };
19807
+ }
19751
19808
  function holdsSession(claim) {
19752
19809
  return claim?.actor.kind === "session";
19753
19810
  }
@@ -19760,8 +19817,9 @@ function routeText(issue, titles) {
19760
19817
  const holder = issue.route_holder ?? null;
19761
19818
  const reach = {
19762
19819
  live: routeHeldBySession(issue) && holder !== null ? ` (held by ${titles?.get(holder) ?? holder})` : "",
19820
+ holder_unresponsive: issue.route.startsWith("role:") ? ` (its holder${holder === null ? "" : ` ${titles?.get(holder) ?? holder}`} is unresponsive: messages wait for it)` : " (that session is unresponsive: messages wait for it)",
19763
19821
  no_holder: issue.route.startsWith("role:") ? " (nobody holds it right now)" : " (that session is not running right now)",
19764
- unknown: " (the Envoy listener did not answer, so whether it reaches anyone is unknown)"
19822
+ unknown: issue.route_status_reason === "refilling" ? " (the Envoy listener's agent list is refilling, so whether it reaches anyone is unknown; try again in a moment)" : " (the Envoy listener did not answer, so whether it reaches anyone is unknown)"
19765
19823
  };
19766
19824
  return issue.route + (issue.route_status == null ? "" : reach[issue.route_status]);
19767
19825
  }
@@ -19819,7 +19877,7 @@ function refuseUnsavedRepository(verb, issue, repo) {
19819
19877
  const lost = repo === "" ? "the repository was not cleared" : `${repo} was not saved`;
19820
19878
  throw new Error(`Dispatch ${verb} ${issue.key} without its repository: this Dispatch server predates repository fields, so ${lost}; upgrade the server`);
19821
19879
  }
19822
- function issueSummary(issue, events, references, graph, linkBase, coverage, titles) {
19880
+ function issueSummary(issue, events, references, graph, linkBase, coverage, agents) {
19823
19881
  const asks = issue.open_asks;
19824
19882
  const spec = issue.artifacts?.find((artifact) => artifact.primary);
19825
19883
  const specApproval = spec === undefined ? undefined : approvalLine(spec);
@@ -19840,11 +19898,11 @@ function issueSummary(issue, events, references, graph, linkBase, coverage, titl
19840
19898
  `Link: ${new URL(`/issues/${encodeURIComponent(issue.key)}`, linkBase).toString()}`,
19841
19899
  `Status: ${issue.status}`,
19842
19900
  `Assignee: ${issue.assignee ?? "unassigned"}`,
19843
- `Claimed by: ${issue.claim === null ? "nobody" : claimText(issue.claim, titles)}`,
19901
+ `Claimed by: ${issue.claim === null ? "nobody" : claimText(issue.claim, agents, issue)}`,
19844
19902
  ...issue.priority === null ? [] : [`Priority: P${issue.priority}`],
19845
19903
  `Labels: ${issue.labels.length === 0 ? "none" : issue.labels.join(", ")}`,
19846
19904
  componentsLine(issue.components),
19847
- `Route: ${routeText(issue, titles)}`,
19905
+ `Route: ${routeText(issue, agents?.titles)}`,
19848
19906
  repositoryLine(issue),
19849
19907
  `Progress: ${progressText(issue.progress, ", ") || "none"}`,
19850
19908
  ...specApproval === undefined ? [] : [`Spec ${specApproval.replace(/^Approval/, "approval")}`],
@@ -21047,10 +21105,11 @@ async function executeDispatchTool(input) {
21047
21105
  route: row.route ?? null,
21048
21106
  route_status: row.route_status ?? null,
21049
21107
  route_holder: row.route_holder ?? null,
21108
+ route_status_reason: row.route_status_reason ?? null,
21050
21109
  updated_at: row.updated_at,
21051
21110
  progress: row.progress
21052
21111
  }));
21053
- const titles = await liveSessionTitles(client, rows.some((row) => holdsSession(row.claim)));
21112
+ const agents = await liveAgents(client, rows.some((row) => holdsSession(row.claim)));
21054
21113
  const isPartial = offset !== 0 || rows.length !== total;
21055
21114
  const showing = !isPartial ? "" : rows.length === 0 ? `showing 0-0 of ${total}` : pageSummaryText(offset, rows.length, total);
21056
21115
  return {
@@ -21058,7 +21117,7 @@ async function executeDispatchTool(input) {
21058
21117
  `${rows.length} ${rows.length === 1 ? "issue" : "issues"} in ${project}` + (isPartial ? ` (${showing})` : ""),
21059
21118
  ...rows.map((row) => {
21060
21119
  const progress = progressText(row.progress, " \xB7 ");
21061
- return `${row.key} [${row.status}]${row.priority === null ? "" : ` P${row.priority}`} ${row.title}` + (row.open_asks === 0 ? "" : ` \xB7 ${row.open_asks} open ${row.open_asks === 1 ? "ask" : "asks"}`) + (row.claim === null ? "" : ` \xB7 claimed by ${claimText(row.claim, titles)}`) + (progress === "" ? "" : ` \xB7 ${progress}`) + (row.route === null || row.route_status === "live" || row.route_status === null ? "" : ` \xB7 route ${routeText(row)}`);
21120
+ return `${row.key} [${row.status}]${row.priority === null ? "" : ` P${row.priority}`} ${row.title}` + (row.open_asks === 0 ? "" : ` \xB7 ${row.open_asks} open ${row.open_asks === 1 ? "ask" : "asks"}`) + (row.claim === null ? "" : ` \xB7 claimed by ${claimText(row.claim, agents)}`) + (progress === "" ? "" : ` \xB7 ${progress}`) + (row.route === null || row.route_status === "live" || row.route_status === null ? "" : ` \xB7 route ${routeText(row)}`);
21062
21121
  })
21063
21122
  ].join(`
21064
21123
  `),
@@ -21844,10 +21903,10 @@ ${handoff.body}`,
21844
21903
  const readPromise = client.read(issueKey, readEvents);
21845
21904
  const referencesPromise = issueReferencesOrUnavailable(client, issueKey);
21846
21905
  const read = await readPromise;
21847
- const [references, graph, titles, pictures, coverage] = await Promise.all([
21906
+ const [references, graph, agents, pictures, coverage] = await Promise.all([
21848
21907
  referencesPromise,
21849
21908
  graphSections(client, dispatchIssueRef(read.issue.key)),
21850
- liveSessionTitles(client, holdsSession(read.issue.claim) || routeHeldBySession(read.issue)),
21909
+ liveAgents(client, holdsSession(read.issue.claim) || routeHeldBySession(read.issue)),
21851
21910
  picturesOf([
21852
21911
  ...read.issue.open_asks.map((ask) => ({ text: ask.question, at: ask.created_at })),
21853
21912
  ...await eventTextsWhole(client, read.events)
@@ -21855,7 +21914,7 @@ ${handoff.body}`,
21855
21914
  issueCoverageOrReason(client, read.issue.key)
21856
21915
  ]);
21857
21916
  return {
21858
- text: issueSummary(read.issue, read.events, references, [...pictures.lines, ...graph], linkBase, coverage, titles),
21917
+ text: issueSummary(read.issue, read.events, references, [...pictures.lines, ...graph], linkBase, coverage, agents),
21859
21918
  details: { issue: read.issue.key },
21860
21919
  ...showImages(pictures),
21861
21920
  ...repositoryFieldsWarnings(read.issue)
@@ -25225,6 +25284,9 @@ function sessionEnvoySettings(file, env, options) {
25225
25284
  var DEFAULT_TIMEOUT_MS = 5000;
25226
25285
  var RETRY_DELAY_MS = 250;
25227
25286
  var REPLAY_TIMEOUT_MS = 1e4;
25287
+ var SessionStateSchema = _enum2(["live", "unresponsive", "gone"]);
25288
+ var UNRESPONSIVE_RULE = "An unresponsive session is not dead: it keeps its role claims and its issue claims, and a " + "message sent to it is stored until it answers. Start no replacement for it and take no claim " + `from it until it is gone, or until ${ISSUE_CLAIM_UNRESPONSIVE_GRACE_MS / 60000} minutes ` + "have passed since its last_seen, the time of its last registration.";
25289
+ var WireStateSchema = SessionStateSchema.default("live");
25228
25290
  var InterestWireSchema = object({
25229
25291
  session_id: string2(),
25230
25292
  machine_id: string2(),
@@ -25254,6 +25316,7 @@ var SessionWireSchema = object({
25254
25316
  capabilities: array(string2()).optional(),
25255
25317
  self_subscribed: boolean2(),
25256
25318
  last_seen: number2().int().optional(),
25319
+ state: WireStateSchema,
25257
25320
  plugin: string2().optional(),
25258
25321
  plugin_version: string2().optional()
25259
25322
  });
@@ -25261,7 +25324,9 @@ var RoleWireSchema = object({
25261
25324
  role: string2(),
25262
25325
  holder: string2(),
25263
25326
  host: string2().optional(),
25264
- last_seen: number2().int()
25327
+ last_seen: number2().int(),
25328
+ state: WireStateSchema,
25329
+ holder_state: SessionStateSchema.optional()
25265
25330
  });
25266
25331
  var RoleHeldWireSchema = object({
25267
25332
  error: string2(),
@@ -25271,11 +25336,21 @@ var RoleHeldWireSchema = object({
25271
25336
  var ErrorWireSchema = object({
25272
25337
  error: string2(),
25273
25338
  code: string2().optional(),
25274
- expected: array(string2()).optional()
25339
+ expected: array(string2()).optional(),
25340
+ state: SessionStateSchema.optional(),
25341
+ holder: string2().optional(),
25342
+ holder_state: SessionStateSchema.optional(),
25343
+ last_seen: number2().int().optional(),
25344
+ claim_released: boolean2().optional(),
25345
+ unresponsive: array(string2()).optional()
25275
25346
  });
25276
25347
  var EnvelopeResponseSchema = EnvelopeSchema.extend({
25277
25348
  recipient: string2().optional(),
25278
25349
  holder: string2().optional(),
25350
+ holder_state: SessionStateSchema.optional(),
25351
+ recipient_state: SessionStateSchema.optional(),
25352
+ last_seen: number2().int().optional(),
25353
+ unresponsive: array(string2()).optional(),
25279
25354
  duplicate: boolean2().optional()
25280
25355
  });
25281
25356
  var PublishResponseSchema = EnvelopeResponseSchema.extend({
@@ -25333,12 +25408,36 @@ function expandSubscriptionTopics(topics) {
25333
25408
  }
25334
25409
  return [...expanded];
25335
25410
  }
25411
+ function refusalStateText(parsed) {
25412
+ const sentences = [];
25413
+ const state = parsed.holder_state ?? parsed.state;
25414
+ if (state !== undefined) {
25415
+ const who = parsed.holder === undefined ? "That session" : `Holder ${parsed.holder}`;
25416
+ const seen = parsed.last_seen === undefined || parsed.last_seen <= 0 ? "" : `, last seen ${new Date(parsed.last_seen).toISOString()}`;
25417
+ sentences.push(`${who} is ${state}${seen}.`);
25418
+ }
25419
+ const stored = parsed.unresponsive ?? [];
25420
+ if (stored.length > 0) {
25421
+ const one = stored.length === 1;
25422
+ sentences.push(`Envoy stored the message for ${stored.join(", ")}.`, `${one ? "That session" : "Those sessions"} stopped answering, so ${one ? "it" : "they"} did not fail this send.`);
25423
+ }
25424
+ if (sentences.length === 0)
25425
+ return "";
25426
+ if (state === "unresponsive" || stored.length > 0)
25427
+ sentences.push(UNRESPONSIVE_RULE);
25428
+ return ` ${sentences.join(" ")}`;
25429
+ }
25336
25430
 
25337
25431
  class EnvoyApiError extends Error {
25338
25432
  details;
25339
25433
  name = "EnvoyApiError";
25340
25434
  expected;
25341
25435
  code;
25436
+ holder;
25437
+ sessionState;
25438
+ lastSeen;
25439
+ claimReleased;
25440
+ unresponsive;
25342
25441
  constructor(details) {
25343
25442
  let parsed;
25344
25443
  try {
@@ -25346,10 +25445,15 @@ class EnvoyApiError extends Error {
25346
25445
  if (result.success)
25347
25446
  parsed = result.data;
25348
25447
  } catch {}
25349
- super(parsed === undefined ? `${details.method} ${details.url} failed with ${details.status}: ${details.responseBody}` : `${parsed.error}${parsed.expected === undefined ? "" : ` (expected: ${parsed.expected.join(", ")})`}`);
25448
+ super(parsed === undefined ? `${details.method} ${details.url} failed with ${details.status}: ${details.responseBody}` : `${parsed.error}${parsed.expected === undefined ? "" : ` (expected: ${parsed.expected.join(", ")})`}${refusalStateText(parsed)}`);
25350
25449
  this.details = details;
25351
25450
  this.expected = parsed?.expected;
25352
25451
  this.code = parsed?.code;
25452
+ this.holder = parsed?.holder;
25453
+ this.sessionState = parsed?.holder_state ?? parsed?.state;
25454
+ this.lastSeen = parsed?.last_seen;
25455
+ this.claimReleased = parsed?.claim_released;
25456
+ this.unresponsive = parsed?.unresponsive;
25353
25457
  }
25354
25458
  }
25355
25459
  var mintedDedupeKey2 = new RegExp(MINTED_DEDUPE_KEY_PATTERN);
@@ -25505,6 +25609,8 @@ function createEnvoyClient(config) {
25505
25609
  envelope: response,
25506
25610
  recipient: response.recipient ?? input.targetSessionID,
25507
25611
  confirmed: response.recipient !== undefined,
25612
+ recipientState: response.recipient_state ?? "live",
25613
+ ...response.last_seen === undefined || response.last_seen <= 0 ? {} : { lastSeen: response.last_seen },
25508
25614
  duplicate: response.duplicate === true
25509
25615
  };
25510
25616
  },
@@ -25523,6 +25629,8 @@ function createEnvoyClient(config) {
25523
25629
  return {
25524
25630
  envelope: response,
25525
25631
  ...response.holder === undefined ? {} : { holder: response.holder },
25632
+ ...response.holder_state === undefined ? {} : { holderState: response.holder_state },
25633
+ unresponsive: response.unresponsive ?? [],
25526
25634
  ...response.kept === undefined ? {} : { kept: response.kept },
25527
25635
  ...response.kept_reason === undefined ? {} : { keptReason: response.kept_reason }
25528
25636
  };
@@ -25566,6 +25674,8 @@ function createEnvoyClient(config) {
25566
25674
  search.set("dir", input.directory);
25567
25675
  if (input.title !== undefined)
25568
25676
  search.set("title", input.title);
25677
+ if (input.include !== undefined)
25678
+ search.set("include", input.include);
25569
25679
  const query = search.size === 0 ? "" : `?${search.toString()}`;
25570
25680
  return SessionWireSchema.array().parse(JSON.parse(await request(`/v1/sessions${query}`, {})));
25571
25681
  },
package/dist/envoy.js CHANGED
@@ -29662,6 +29662,7 @@ function date4(params) {
29662
29662
  // ../../node_modules/.bun/zod@4.3.6/node_modules/zod/v4/classic/external.js
29663
29663
  config(en_default());
29664
29664
  // ../contracts/src/dispatch-api.ts
29665
+ var ISSUE_CLAIM_UNRESPONSIVE_GRACE_MS = 20 * 60 * 1000;
29665
29666
  var MAX_ISSUE_BLOCKERS = 20;
29666
29667
  var ISSUE_TITLE_MAX = 1000;
29667
29668
  var PROJECT_NAME_MAX = 80;
@@ -30222,7 +30223,12 @@ var ISSUE_STATUSES = [
30222
30223
  "retro",
30223
30224
  "done"
30224
30225
  ];
30225
- var ISSUE_ROUTE_STATUSES = ["live", "no_holder", "unknown"];
30226
+ var ISSUE_ROUTE_STATUSES = [
30227
+ "live",
30228
+ "holder_unresponsive",
30229
+ "no_holder",
30230
+ "unknown"
30231
+ ];
30226
30232
  var DOC_EDIT_OPS = [
30227
30233
  "replace",
30228
30234
  "delete",
@@ -30647,7 +30653,7 @@ var dispatchToolSpecs = [
30647
30653
  label: z.string().describe("Optional label filter.").optional(),
30648
30654
  priority: z.array(z.number({ int: true, min: 0, max: 3 }).nullable(), { min: 1, max: 5 }).describe("Optional priority filter: one or more of 0 (P0, highest) through 3 (P3, lowest), and null " + "for an issue with no priority; an issue matching any listed value is returned.").optional(),
30649
30655
  updated_since: z.string().describe("Optional RFC3339 timestamp; only issues updated at or after it.").optional(),
30650
- route_status: z.enum(ISSUE_ROUTE_STATUSES).describe("Optional: only open issues whose route is in this state. live: a running session holds " + "the role or is the routed session. no_holder: nobody running holds the role, or the " + "session is not running, right now. unknown: the Envoy listener did not answer.").optional(),
30656
+ route_status: z.enum(ISSUE_ROUTE_STATUSES).describe("Optional: only open issues whose route is in this state. live: a running session holds " + "the role or is the routed session. holder_unresponsive: that session has missed its " + "heartbeats without ending, so the route still reaches it and its messages wait. " + "no_holder: nobody running holds the role, or the session is gone, right now. " + "unknown: the Envoy listener did not answer.").optional(),
30651
30657
  limit: z.number({ int: true, min: 1, max: MAX_ISSUE_PAGE_LIMIT }).describe(`Maximum rows, 1-${MAX_ISSUE_PAGE_LIMIT}; default ${DEFAULT_ISSUE_PAGE_LIMIT}.`).optional(),
30652
30658
  offset: z.number({ int: true, min: 0 }).describe("Rows to skip before the page; nonnegative integer; default 0.").optional(),
30653
30659
  all: z.boolean().describe("Take every matching issue in one unpaged read, so no row is missed or repeated while " + "the list changes. Refused with limit or offset.").optional()
@@ -37054,6 +37060,13 @@ var DEFAULT_HEARTBEAT_MS = 90000;
37054
37060
  var MIN_PASS_DEADLINE_MS = 30000;
37055
37061
  var MIN_INTERVAL_MS = 25;
37056
37062
  var MAX_INTERVAL_MS = 2147483647;
37063
+ var REGISTRATION_SETTLE_MS = 5000;
37064
+ var SHUTDOWN_SETTLE_MS = 250;
37065
+ var HEARTBEAT_RETRY_MIN_MS = 20000;
37066
+ var HEARTBEAT_RETRY_MAX_MS = 40000;
37067
+ function heartbeatRetryDelayMs(draw = Math.random) {
37068
+ return Math.round(HEARTBEAT_RETRY_MIN_MS + draw() * (HEARTBEAT_RETRY_MAX_MS - HEARTBEAT_RETRY_MIN_MS));
37069
+ }
37057
37070
  function namedInterval(raw) {
37058
37071
  const parsed = Number(raw);
37059
37072
  return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;
@@ -37176,6 +37189,9 @@ var DEFAULT_TIMEOUT_MS = 5000;
37176
37189
  var RETRY_DELAY_MS = 250;
37177
37190
  var REPLAY_TIMEOUT_MS = 1e4;
37178
37191
  var REPLAY_UNAVAILABLE_CODE = "REPLAY_UNAVAILABLE";
37192
+ var SessionStateSchema = _enum2(["live", "unresponsive", "gone"]);
37193
+ var UNRESPONSIVE_RULE = "An unresponsive session is not dead: it keeps its role claims and its issue claims, and a " + "message sent to it is stored until it answers. Start no replacement for it and take no claim " + `from it until it is gone, or until ${ISSUE_CLAIM_UNRESPONSIVE_GRACE_MS / 60000} minutes ` + "have passed since its last_seen, the time of its last registration.";
37194
+ var WireStateSchema = SessionStateSchema.default("live");
37179
37195
  var InterestWireSchema = object({
37180
37196
  session_id: string2(),
37181
37197
  machine_id: string2(),
@@ -37205,6 +37221,7 @@ var SessionWireSchema = object({
37205
37221
  capabilities: array(string2()).optional(),
37206
37222
  self_subscribed: boolean2(),
37207
37223
  last_seen: number2().int().optional(),
37224
+ state: WireStateSchema,
37208
37225
  plugin: string2().optional(),
37209
37226
  plugin_version: string2().optional()
37210
37227
  });
@@ -37212,7 +37229,9 @@ var RoleWireSchema = object({
37212
37229
  role: string2(),
37213
37230
  holder: string2(),
37214
37231
  host: string2().optional(),
37215
- last_seen: number2().int()
37232
+ last_seen: number2().int(),
37233
+ state: WireStateSchema,
37234
+ holder_state: SessionStateSchema.optional()
37216
37235
  });
37217
37236
  var RoleHeldWireSchema = object({
37218
37237
  error: string2(),
@@ -37222,11 +37241,21 @@ var RoleHeldWireSchema = object({
37222
37241
  var ErrorWireSchema = object({
37223
37242
  error: string2(),
37224
37243
  code: string2().optional(),
37225
- expected: array(string2()).optional()
37244
+ expected: array(string2()).optional(),
37245
+ state: SessionStateSchema.optional(),
37246
+ holder: string2().optional(),
37247
+ holder_state: SessionStateSchema.optional(),
37248
+ last_seen: number2().int().optional(),
37249
+ claim_released: boolean2().optional(),
37250
+ unresponsive: array(string2()).optional()
37226
37251
  });
37227
37252
  var EnvelopeResponseSchema = EnvelopeSchema.extend({
37228
37253
  recipient: string2().optional(),
37229
37254
  holder: string2().optional(),
37255
+ holder_state: SessionStateSchema.optional(),
37256
+ recipient_state: SessionStateSchema.optional(),
37257
+ last_seen: number2().int().optional(),
37258
+ unresponsive: array(string2()).optional(),
37230
37259
  duplicate: boolean2().optional()
37231
37260
  });
37232
37261
  var PublishResponseSchema = EnvelopeResponseSchema.extend({
@@ -37278,6 +37307,9 @@ function mergeInterestSources(registryTopics, liveTopics) {
37278
37307
  }
37279
37308
  return interests;
37280
37309
  }
37310
+ function holderStateOf(role) {
37311
+ return role.holder_state ?? role.state;
37312
+ }
37281
37313
  function newClientInstanceID() {
37282
37314
  return Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, "0")).join("");
37283
37315
  }
@@ -37298,12 +37330,36 @@ function expandSubscriptionTopics(topics) {
37298
37330
  }
37299
37331
  return [...expanded];
37300
37332
  }
37333
+ function refusalStateText(parsed) {
37334
+ const sentences = [];
37335
+ const state = parsed.holder_state ?? parsed.state;
37336
+ if (state !== undefined) {
37337
+ const who = parsed.holder === undefined ? "That session" : `Holder ${parsed.holder}`;
37338
+ const seen = parsed.last_seen === undefined || parsed.last_seen <= 0 ? "" : `, last seen ${new Date(parsed.last_seen).toISOString()}`;
37339
+ sentences.push(`${who} is ${state}${seen}.`);
37340
+ }
37341
+ const stored = parsed.unresponsive ?? [];
37342
+ if (stored.length > 0) {
37343
+ const one = stored.length === 1;
37344
+ sentences.push(`Envoy stored the message for ${stored.join(", ")}.`, `${one ? "That session" : "Those sessions"} stopped answering, so ${one ? "it" : "they"} did not fail this send.`);
37345
+ }
37346
+ if (sentences.length === 0)
37347
+ return "";
37348
+ if (state === "unresponsive" || stored.length > 0)
37349
+ sentences.push(UNRESPONSIVE_RULE);
37350
+ return ` ${sentences.join(" ")}`;
37351
+ }
37301
37352
 
37302
37353
  class EnvoyApiError extends Error {
37303
37354
  details;
37304
37355
  name = "EnvoyApiError";
37305
37356
  expected;
37306
37357
  code;
37358
+ holder;
37359
+ sessionState;
37360
+ lastSeen;
37361
+ claimReleased;
37362
+ unresponsive;
37307
37363
  constructor(details) {
37308
37364
  let parsed;
37309
37365
  try {
@@ -37311,10 +37367,15 @@ class EnvoyApiError extends Error {
37311
37367
  if (result.success)
37312
37368
  parsed = result.data;
37313
37369
  } catch {}
37314
- super(parsed === undefined ? `${details.method} ${details.url} failed with ${details.status}: ${details.responseBody}` : `${parsed.error}${parsed.expected === undefined ? "" : ` (expected: ${parsed.expected.join(", ")})`}`);
37370
+ super(parsed === undefined ? `${details.method} ${details.url} failed with ${details.status}: ${details.responseBody}` : `${parsed.error}${parsed.expected === undefined ? "" : ` (expected: ${parsed.expected.join(", ")})`}${refusalStateText(parsed)}`);
37315
37371
  this.details = details;
37316
37372
  this.expected = parsed?.expected;
37317
37373
  this.code = parsed?.code;
37374
+ this.holder = parsed?.holder;
37375
+ this.sessionState = parsed?.holder_state ?? parsed?.state;
37376
+ this.lastSeen = parsed?.last_seen;
37377
+ this.claimReleased = parsed?.claim_released;
37378
+ this.unresponsive = parsed?.unresponsive;
37318
37379
  }
37319
37380
  }
37320
37381
  var mintedDedupeKey2 = new RegExp(MINTED_DEDUPE_KEY_PATTERN);
@@ -37470,6 +37531,8 @@ function createEnvoyClient(config) {
37470
37531
  envelope: response,
37471
37532
  recipient: response.recipient ?? input.targetSessionID,
37472
37533
  confirmed: response.recipient !== undefined,
37534
+ recipientState: response.recipient_state ?? "live",
37535
+ ...response.last_seen === undefined || response.last_seen <= 0 ? {} : { lastSeen: response.last_seen },
37473
37536
  duplicate: response.duplicate === true
37474
37537
  };
37475
37538
  },
@@ -37488,6 +37551,8 @@ function createEnvoyClient(config) {
37488
37551
  return {
37489
37552
  envelope: response,
37490
37553
  ...response.holder === undefined ? {} : { holder: response.holder },
37554
+ ...response.holder_state === undefined ? {} : { holderState: response.holder_state },
37555
+ unresponsive: response.unresponsive ?? [],
37491
37556
  ...response.kept === undefined ? {} : { kept: response.kept },
37492
37557
  ...response.kept_reason === undefined ? {} : { keptReason: response.kept_reason }
37493
37558
  };
@@ -37531,6 +37596,8 @@ function createEnvoyClient(config) {
37531
37596
  search.set("dir", input.directory);
37532
37597
  if (input.title !== undefined)
37533
37598
  search.set("title", input.title);
37599
+ if (input.include !== undefined)
37600
+ search.set("include", input.include);
37534
37601
  const query = search.size === 0 ? "" : `?${search.toString()}`;
37535
37602
  return SessionWireSchema.array().parse(JSON.parse(await request(`/v1/sessions${query}`, {})));
37536
37603
  },
@@ -40644,6 +40711,7 @@ function allowedAPIURL(value) {
40644
40711
  }
40645
40712
 
40646
40713
  // ../envoy-client/src/tool-contract.ts
40714
+ 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.`;
40647
40715
  var DELIVERY_CONTRACT = "Delivery is at-least-once, possibly out of order across topics; use id for dedupe and at for freshness.";
40648
40716
  var STORED_DELIVERY = "Stored topics (agent, dispatch, github, slack, legion, ghostwispr, whatsapp; a role message " + "reaches its holder as a stored copy on the holder's agent topic) reach each subscribed session " + "once from the durable consumer its listener relays to it, also one that was away or restarted. " + "Team and other ad-hoc topics are live only.";
40649
40717
  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 with failing names and URLs; re-fires with superseded_settlement: "true" ' + "when new runs appear 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>.";
@@ -40713,7 +40781,7 @@ var envoyToolSpecs = [
40713
40781
  },
40714
40782
  {
40715
40783
  name: "envoy_send",
40716
- description: `Send an Envoy agent-to-agent message directly to another session by session ID. ${DELIVERY_CONTRACT} A send that is not confirmed delivered errs naming its idempotency_key; send the same message again with that idempotency_key within 72 hours, and Envoy drops it as a repeat if the first copy arrived.`,
40784
+ description: `Send an Envoy agent-to-agent message directly to another session by session ID. The confirmation names the recipient's state. A message to an unresponsive session is stored and reaches it when it answers again, so an unresponsive recipient is not a failed send and no reason to send to someone else instead. ${SESSION_STATE_GUIDE} ${DELIVERY_CONTRACT} A send that is not confirmed delivered errs naming its idempotency_key; send the same message again with that idempotency_key within 72 hours, and Envoy drops it as a repeat if the first copy arrived.`,
40717
40785
  arguments: (schema) => ({
40718
40786
  session_id: schema.string().describe("Target session ID; find it with envoy_sessions or envoy_whoami."),
40719
40787
  ...messageArguments(schema),
@@ -40723,7 +40791,7 @@ var envoyToolSpecs = [
40723
40791
  },
40724
40792
  {
40725
40793
  name: "envoy_publish",
40726
- 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, the session that holds the role takes the message. That session must confirm the message inside the listener's window, or this tool errs. Second, no session holds the role, or its holder's claim has lapsed. The listener then keeps the message, and gives it to the next session that claims that role in the hour that follows. This is a success, and the result says that the listener kept the message. Third, the listener keeps nothing and errs, which tells you to reach the agent some other way. A team or ad-hoc topic (such as notifications.team.deploy-squad.all) reaches every session subscribed to it when you publish, and is not kept for a session that subscribes later. The listener confirms it with each other session that holds its own NATS connection and registered the topic, and errs naming each session that did not confirm; a session that stopped without unregistering stays registered for up to 5 minutes and is named in that time, and a named session is not a failed delivery to the other sessions. A session that holds its own NATS connection receives such a live topic directly, yours included. ${DELIVERY_CONTRACT}`,
40794
+ 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, the session that holds the role takes the message. That session must confirm the message inside the listener's window, or this tool errs. Second, no session holds the role. The listener then keeps the message, and gives it to the next session that claims that role in the hour that follows. This is a success, and the result says that the listener kept the message. Third, the listener keeps nothing and errs. A holder that stopped answering keeps its role but was not sent the message, and nothing waits for it, so publish the message again once that holder's holder_state reads live, and start no replacement for that session. A team or ad-hoc topic (such as notifications.team.deploy-squad.all) reaches every session subscribed to it when you publish, and is not kept for a session that subscribes later. The listener confirms it with each other session that holds its own NATS connection and registered the topic, and errs naming each session that did not confirm; a session that stopped without unregistering stays registered until Envoy finds it gone and is named until then. A named session is not a failed delivery to the other sessions. A session that is only unresponsive is named as no failure at all. The listener stores that session's copy, asks it for no receipt, and names the session under unresponsive. The accepted publish and the error both name it there. That session takes the message when it answers again. A session that holds its own NATS connection receives such a live topic directly, yours included. ${SESSION_STATE_GUIDE} ${DELIVERY_CONTRACT}`,
40727
40795
  arguments: (schema) => ({ topic: schema.string(), ...messageArguments(schema) }),
40728
40796
  operation: EnvoyToolOperation.publish
40729
40797
  },
@@ -40735,7 +40803,7 @@ var envoyToolSpecs = [
40735
40803
  },
40736
40804
  {
40737
40805
  name: "envoy_role_get",
40738
- description: "Get the live holder of a named Envoy role.",
40806
+ description: `Get the holder of a named Envoy role, with its holder_state and the holder's last_seen. A holder that is only unresponsive still holds the role: nothing a lookup does releases its claim, and only a gone holder leaves the role unheld. ${SESSION_STATE_GUIDE}`,
40739
40807
  arguments: (schema) => ({ role: schema.string() }),
40740
40808
  operation: EnvoyToolOperation.getRole
40741
40809
  },
@@ -40747,7 +40815,7 @@ var envoyToolSpecs = [
40747
40815
  },
40748
40816
  {
40749
40817
  name: "envoy_sessions",
40750
- description: "List all live sessions registered with Envoy. Filter by optional machine, directory, or title.",
40818
+ description: "List the Envoy sessions that are live or unresponsive; a gone session is listed by neither. " + "Filter by optional machine, directory, or title. Each row carries its state and its " + `last_seen, the epoch milliseconds of its last registration. ${SESSION_STATE_GUIDE}`,
40751
40819
  arguments: (schema) => ({
40752
40820
  machine: schema.string().optional(),
40753
40821
  dir: schema.string().optional(),
@@ -40770,14 +40838,23 @@ function sendConfirmationText(result) {
40770
40838
  if (result.duplicate) {
40771
40839
  return `sent to ${result.recipient} once: an earlier attempt under the same idempotency_key was already stored, so this one stored no second copy`;
40772
40840
  }
40773
- return `sent ${result.envelope.event_id} to ${result.recipient}${result.confirmed ? "" : " (recipient unconfirmed by listener)"}`;
40841
+ const since = result.lastSeen === undefined ? "" : ` since ${new Date(result.lastSeen).toISOString()}`;
40842
+ const state = result.recipientState === "unresponsive" ? `unresponsive${since}, so it is stored until that session answers; ${UNRESPONSIVE_RULE}` : result.recipientState;
40843
+ return `sent ${result.envelope.event_id} to ${result.recipient} (${state})${result.confirmed ? "" : " (recipient unconfirmed by listener)"}`;
40774
40844
  }
40775
40845
  function publishConfirmationText(result) {
40776
- const published = `published ${result.envelope.event_id}`;
40846
+ const sentences = [`published ${result.envelope.event_id}.`];
40777
40847
  if (result.kept === true) {
40778
- return `${published}; kept for the role: no session holds it yet, and the message waits for the session that claims it next`;
40848
+ sentences.push("Envoy kept it for the role: no session holds it yet, and the message waits for the session that claims it next.");
40849
+ } else if (result.holder !== undefined) {
40850
+ const state = result.holderState === undefined ? "" : ` (${result.holderState})`;
40851
+ sentences.push(`Its role holder is ${result.holder}${state}.`);
40852
+ }
40853
+ if (result.unresponsive.length > 0) {
40854
+ const one = result.unresponsive.length === 1;
40855
+ sentences.push(`Envoy stored it for ${result.unresponsive.join(", ")}.`, `${one ? "That session" : "Those sessions"} stopped answering, so ${one ? "it has" : "they have"} not taken it yet.`, UNRESPONSIVE_RULE);
40779
40856
  }
40780
- return result.holder === undefined ? published : `${published}; holder ${result.holder}`;
40857
+ return sentences.join(" ");
40781
40858
  }
40782
40859
  function sessionsOnMachine(sessions, machine) {
40783
40860
  if (machine === undefined || machine === "")
@@ -41103,7 +41180,7 @@ var import_nats2 = __toESM(require_mod4(), 1);
41103
41180
 
41104
41181
  // package.json
41105
41182
  var name = "@sjawhar/pi-envoy";
41106
- var version2 = "16.10.0";
41183
+ var version2 = "16.11.0";
41107
41184
  var package_default = {
41108
41185
  name,
41109
41186
  version: version2,
@@ -47099,6 +47176,14 @@ function envoyExtension(pi) {
47099
47176
  forgetInjectedUserTurns(previousSessionID);
47100
47177
  typedPictures.dropOtherSessions(sessionID);
47101
47178
  unwritten.releaseOtherSessions(sessionID);
47179
+ if (previousSessionID !== "") {
47180
+ deregisterSession(previousSessionID).catch((error) => {
47181
+ logger3.warn("envoy: the session this process left could not be deregistered", {
47182
+ sessionID: previousSessionID,
47183
+ detail: messageFor(error)
47184
+ });
47185
+ });
47186
+ }
47102
47187
  }
47103
47188
  };
47104
47189
  let dispatchLedger;
@@ -48110,6 +48195,38 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
48110
48195
  closeIntentionally(subject);
48111
48196
  return false;
48112
48197
  };
48198
+ const registrationsInFlight = new Map;
48199
+ const trackRegistration = (id, registering) => {
48200
+ if (id === "")
48201
+ return registering;
48202
+ const settled = registering.then(() => {
48203
+ return;
48204
+ }, () => {
48205
+ return;
48206
+ });
48207
+ registrationsInFlight.set(id, settled);
48208
+ settled.then(() => {
48209
+ if (registrationsInFlight.get(id) === settled)
48210
+ registrationsInFlight.delete(id);
48211
+ });
48212
+ return registering;
48213
+ };
48214
+ const SHUTDOWN_DEADLINE_MS = 1000;
48215
+ const deregisterSession = async (id, settleMs = REGISTRATION_SETTLE_MS) => {
48216
+ if (id === "" || active === undefined)
48217
+ return;
48218
+ const registering = registrationsInFlight.get(id);
48219
+ if (registering !== undefined) {
48220
+ const waited = Promise.withResolvers();
48221
+ const timer = setTimeout(waited.resolve, settleMs);
48222
+ try {
48223
+ await Promise.race([registering, waited.promise]);
48224
+ } finally {
48225
+ clearTimeout(timer);
48226
+ }
48227
+ }
48228
+ await registrationState.deregister(id);
48229
+ };
48113
48230
  const registrationInput = (asking) => {
48114
48231
  const own = agentSubject(sessionID);
48115
48232
  const topics = [
@@ -48142,7 +48259,7 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
48142
48259
  return result;
48143
48260
  });
48144
48261
  };
48145
- const registerSession = () => sendRegistration(registrationState.refreshRegistration);
48262
+ const registerSession = () => trackRegistration(sessionID, sendRegistration(registrationState.refreshRegistration));
48146
48263
  const ensureHeartbeat = (context) => {
48147
48264
  if (heartbeatRegistered)
48148
48265
  return;
@@ -48150,6 +48267,7 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
48150
48267
  let stallNotified = false;
48151
48268
  let registrationFailed = false;
48152
48269
  let healing = false;
48270
+ let retryArmed = false;
48153
48271
  const noteStall = (detail) => {
48154
48272
  if (stallNotified)
48155
48273
  return;
@@ -48160,7 +48278,9 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
48160
48278
  });
48161
48279
  context.ui.notify(`envoy: a reconcile pass has stalled (${detail}); the session registration is being refreshed on its own, and recovers once the pass settles`, "warning");
48162
48280
  };
48163
- context.setInterval(() => {
48281
+ const tick = (fromRetry) => {
48282
+ if (shuttingDown)
48283
+ return;
48164
48284
  if (context.sessionManager.getSessionId() === "")
48165
48285
  return;
48166
48286
  unwritten.handBackWithdrawn();
@@ -48182,6 +48302,7 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
48182
48302
  registrationFailed = false;
48183
48303
  heartbeatOutageNotified = false;
48184
48304
  stallNotified = false;
48305
+ retryArmed = false;
48185
48306
  };
48186
48307
  reconcile(context, { heartbeat: true, afterOutage }).then(settled, (error) => {
48187
48308
  if (error instanceof InboundError)
@@ -48195,14 +48316,30 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
48195
48316
  registrationFailed = true;
48196
48317
  throw error instanceof RegistrationError ? error.cause : error;
48197
48318
  }).catch((error) => {
48319
+ const retryIn = fromRetry ? undefined : armRetry();
48198
48320
  if (heartbeatOutageNotified)
48199
48321
  return;
48200
48322
  heartbeatOutageNotified = true;
48201
- context.ui.notify(`envoy: registry heartbeat failed (${messageFor(error)}); retrying every heartbeat`, "warning");
48323
+ const retrying = retryIn === undefined ? "retrying at the next heartbeat" : `retrying once in ${Math.round(retryIn / 1000)} s, then every heartbeat`;
48324
+ context.ui.notify(`envoy: registry heartbeat failed (${messageFor(error)}); ${retrying}`, "warning");
48202
48325
  }).finally(() => {
48203
48326
  healing = false;
48204
48327
  });
48205
- }, requireEnvoy().settings.heartbeatMs);
48328
+ };
48329
+ const armRetry = () => {
48330
+ if (retryArmed)
48331
+ return;
48332
+ retryArmed = true;
48333
+ const delayMs = heartbeatRetryDelayMs();
48334
+ context.setTimeout(() => {
48335
+ if (!retryArmed)
48336
+ return;
48337
+ retryArmed = false;
48338
+ tick(true);
48339
+ }, delayMs);
48340
+ return delayMs;
48341
+ };
48342
+ context.setInterval(() => tick(false), requireEnvoy().settings.heartbeatMs);
48206
48343
  heartbeatRegistered = true;
48207
48344
  };
48208
48345
  const recoverRegisteredInterests = async (handle) => {
@@ -48347,7 +48484,7 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
48347
48484
  handle.check();
48348
48485
  if (inboundFailure !== undefined && replay !== undefined)
48349
48486
  await replay.startCursors();
48350
- const registration = await sendRegistration(handle.register).then(() => {
48487
+ const registration = await trackRegistration(host, sendRegistration(handle.register)).then(() => {
48351
48488
  return;
48352
48489
  }, (error) => ({ error }));
48353
48490
  handle.check();
@@ -48614,9 +48751,9 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
48614
48751
  closeStore(askgateOwner.store);
48615
48752
  }
48616
48753
  const deadline = Promise.withResolvers();
48617
- const timer = setTimeout(deadline.resolve, 1000);
48754
+ const timer = setTimeout(deadline.resolve, SHUTDOWN_DEADLINE_MS);
48618
48755
  try {
48619
- const deregistration = sessionID === "" || active === undefined ? Promise.resolve() : registrationState.deregister(sessionID).catch(() => {
48756
+ const deregistration = deregisterSession(sessionID, SHUTDOWN_SETTLE_MS).catch(() => {
48620
48757
  return;
48621
48758
  });
48622
48759
  const draining = connection?.drain().catch(() => {
@@ -49019,6 +49156,7 @@ Kept (they last while this session holds role ${registrationState.heldRole()}):
49019
49156
  return toolSuccess(sendConfirmationText(result), {
49020
49157
  event_id: result.envelope.event_id,
49021
49158
  recipient: result.recipient,
49159
+ recipient_state: result.recipientState,
49022
49160
  confirmed: result.confirmed
49023
49161
  });
49024
49162
  }
@@ -49039,6 +49177,8 @@ Not delivered: that holder is the session this subagent sends as, and the listen
49039
49177
  event_id: result.envelope.event_id,
49040
49178
  topic,
49041
49179
  ...result.holder === undefined ? {} : { holder: result.holder },
49180
+ ...result.holderState === undefined ? {} : { holder_state: result.holderState },
49181
+ ...result.unresponsive.length === 0 ? {} : { unresponsive: result.unresponsive },
49042
49182
  ...result.kept === undefined ? {} : { kept: result.kept },
49043
49183
  ...result.keptReason === undefined ? {} : { kept_reason: result.keptReason },
49044
49184
  ...undelivered ? { undelivered_echo: true } : {}
@@ -49069,7 +49209,8 @@ Not delivered: that holder is the session this subagent sends as, and the listen
49069
49209
  }
49070
49210
  case EnvoyToolOperation.getRole: {
49071
49211
  const role = await client.getRole(stringFor(parameters, "role"));
49072
- return toolSuccess(JSON.stringify(role, null, 2), role);
49212
+ const held = { ...role, holder_state: holderStateOf(role) };
49213
+ return toolSuccess(JSON.stringify(held, null, 2), held);
49073
49214
  }
49074
49215
  case EnvoyToolOperation.whoami: {
49075
49216
  const inSubagent = await isSubagent(context);
@@ -49093,10 +49234,15 @@ Not delivered: that holder is the session this subagent sends as, and the listen
49093
49234
  const machine = optionalStringFor(parameters, "machine");
49094
49235
  const directory = optionalStringFor(parameters, "dir");
49095
49236
  const title = optionalStringFor(parameters, "title");
49096
- const sessions = await client.listSessions({ directory, title });
49237
+ const sessions = await client.listSessions({
49238
+ directory,
49239
+ title,
49240
+ include: "unresponsive"
49241
+ });
49097
49242
  const result = sessionsOnMachine(sessions, machine);
49098
49243
  return toolSuccess(JSON.stringify(result, null, 2), {
49099
49244
  count: result.length,
49245
+ unresponsive: result.filter((session) => session.state === "unresponsive").length,
49100
49246
  machine,
49101
49247
  dir: directory,
49102
49248
  title
@@ -41,7 +41,9 @@ The question and the recommendation, as `skill://dispatch-writing-specs` writes
41
41
 
42
42
  ## Issue status is yours to move
43
43
 
44
- Outside Legion, claim your issue (`dispatch claim`) and move it and your children: `in_progress` at implementation, `testing` on a production-like surface, `needs_review` while its PR waits, `done` with `--reason` once driven in production. Never write or route the status of an issue with the `legion` label or under one, and claim one only as a role of its tree, even when its claim reads `· not running`: an outside claim can take the tree out of the workflow. A status write is set back or stands.
44
+ Outside Legion, claim your issue (`dispatch claim`) and move it and your children: `in_progress` at implementation, `testing` on a production-like surface, `needs_review` while its PR waits, `done` with `--reason` once driven in production. Never write or route the status of an issue with the `legion` label or under one, and claim one only as a role of its tree: an outside claim can take the tree out of the workflow. A status write is set back or stands.
45
+
46
+ `unresponsive` holders keep their claims 20 minutes (`skill://envoy`).
45
47
 
46
48
  A claim, or `dispatch issue-update --route session:<your id>` (`--route ''` on release), brings a person's answers, comments and messages; for agents' activity, `envoy_subscribe notifications.dispatch.issue.<KEY>.>`, which shows no quiet event.
47
49
 
@@ -38,6 +38,16 @@ envoy_send(session_id="<id>", message="Review complete: <url>", in_reply_to="<id
38
38
  - A peer's message is its sender's view at `at`, not the current state. Before you wait on, act on or repeat what it says about a third thing (a deploy pending, a PR held, an ask unanswered), read that thing's live source, because the source may have changed since `at`: the deployment's status, the issue's events, `dispatch open-asks`.
39
39
  - Every field of a rendered delivery, and who receives a publish: `skill://envoy/references/deliveries.md`.
40
40
 
41
+ ## Whether a session is live
42
+
43
+ A session's state comes from the registry's record of it, never from its presence in a list, a process list, a tmux pane or a transcript's modification time. `envoy_sessions` and a lookup of one session carry each session's `state` and `last_seen`.
44
+
45
+ - `live`: it registered within the live window (`ENVOY_SESSION_LIVE_WINDOW`, 5m by default).
46
+ - `unresponsive`: it last registered longer ago than the live window but inside the gone horizon (`ENVOY_SESSION_GONE_HORIZON`, 1h by default). **It is not dead.** Start no replacement for it, take no role claim and no issue claim from it, and never report it as gone. A message you send it is stored and reaches it when it answers again.
47
+ - `gone`: it last registered before the gone horizon, or the registry holds no record of it.
48
+ - Take an issue claim from a session only when it reads `gone`, or its `last_seen` is more than 20 minutes old. A role claim is released only by the role-claim reaper, once the holder is `gone`: no lookup, publish or delivery failure releases one, in the listener or in Dispatch's outbox, which share that one resolution.
49
+ - A send refused because the target is not live names the target's `state` and `last_seen`. Read those two fields before you decide anything about that session: a refusal on an `unresponsive` target means "it has not answered yet", not "it ended".
50
+
41
51
  ## Subscribe to a topic
42
52
 
43
53
  Every topic starts with `notifications.`.
@@ -66,7 +76,7 @@ Every topic starts with `notifications.`.
66
76
  ## Roles and team topics
67
77
 
68
78
  - Send to one session with `envoy_send`, to the one session that holds a named duty with a role, and to a group with a team topic.
69
- - Publish to a role with `envoy_publish(topic="notifications.role.<role>", ...)`; never subscribe to a role topic, because the listener forwards a role message to its holder only. A publish returns once the holder's session confirmed it, with the live `holder`. When nobody holds the role, or its holder's claim has lapsed, Envoy keeps the message for the session that claims the role next. The answer then says the message was kept, and that session is handed it once, within one hour of the keep. A holder that did not confirm the message within about 4 seconds returns an error that names the holder, and you see it after about 8 seconds, because the client tries once more. `envoy_role_get(role=...)` finds the holder first. The stream keeps the forward on the holder's inbox, so the holder's session gets it once from its own durable consumer, also after a restart or a reconnect.
70
- - For a team, the group subscribes to `notifications.team.<name>.>`, and any member publishes to `notifications.team.<name>.all`. Envoy treats any other `notifications.` topic that no source in the table uses the same way. It reaches every session subscribed when it is published, yours too when you subscribe. The listener also asks each other session that holds its own NATS connection and registered the topic (every session that follows it with `envoy_subscribe`) to confirm the message; your own session is never asked. A publish returns an error naming each such session that did not confirm within about 4 seconds, and you see it after about 8 seconds, because the client tries once more. A session named with `receipt_timeout` still gets the message: the listener kept a copy in that session's inbox, which the session reads back once its connection returns. A session that stopped without unregistering stays registered for up to 5 minutes and is named in that time; a named session is not a failed delivery to the others. A team topic is not kept for a session that subscribes later. A topic outside `notifications.` is refused.
79
+ - Publish to a role with `envoy_publish(topic="notifications.role.<role>", ...)`; never subscribe to a role topic, because the listener forwards a role message to its holder only. A publish returns once the holder's session confirmed it, with the live `holder` and its `holder_state`. When nobody holds the role, Envoy keeps the message for the session that claims the role next: the answer says it was kept, and that session is handed it once, within one hour of the keep. A holder that is not `live` returns an error instead: that refusal names the holder, its `holder_state` (`unresponsive` or `gone`), its `last_seen` and `claim_released: false`, and nothing was forwarded and nothing kept, so publish the message again once the holder answers rather than starting a replacement for it or taking anything from it. A live holder that did not confirm the message within about 4 seconds errs too, and you see that one after about 8 seconds, because the client tries once more. No error releases the role's claim: a holder whose `holder_state` is `unresponsive` keeps its role. `envoy_role_get(role=...)` finds the holder first. The stream keeps a forward on the holder's inbox, so a holder that was forwarded to gets it once from its own durable consumer, also after a restart or a reconnect.
80
+ - For a team, the group subscribes to `notifications.team.<name>.>`, and any member publishes to `notifications.team.<name>.all`. Envoy treats any other `notifications.` topic that no source in the table uses the same way. It reaches every session subscribed when it is published, yours too when you subscribe. The listener also asks each other session that holds its own NATS connection and registered the topic (every session that follows it with `envoy_subscribe`) to confirm the message; your own session is never asked. A publish returns an error naming each such session that did not confirm within about 4 seconds, and you see it after about 8 seconds, because the client tries once more. A session named with `receipt_timeout` still gets the message: the listener kept a copy in that session's inbox, which the session reads back once its connection returns. An `unresponsive` session is sent the message the same way, asked for no receipt and named under `unresponsive` in the answer, which is no failure. A session that stopped without unregistering stays in the registry until the reaper finds it `gone`, and is named until then; a named session is not a failed delivery to the others. A team topic is not kept for a session that subscribes later. A topic outside `notifications.` is refused.
71
81
  - How a role claim survives a resume, a fork or a dead process: `skill://envoy/references/roles.md`.
72
82
  - In a Legion pane, the plugin claims your role at session start; read `skill://envoy/references/legion.md` before you claim, release or publish to a role, or answer a role delivery failure there.
@@ -5,9 +5,10 @@ Read this in a Legion pane before you touch a role claim, or when a Legion role
5
5
  - The Legion plugin claims your assigned role at session start through a daemon-minted role token. Never call `envoy_role_set` and never subscribe to your role topic yourself, because the claim is already made (`packages/pi-shared/src/legion-claim-core.ts`).
6
6
  - Never build a role token from an issue number or title: only the daemon maps tokens to issues.
7
7
  - A Legion claim is last-claim-wins. It survives parking and worker re-creation, and stays through the issue's linger after close (the deployment's `linger_hours`).
8
- - `no_holder`, `delivery_failed` and `receipt_timeout` on a Legion role are the daemon's liveness signals. Never add a second subscriber or retry by hand: the daemon revives or recreates the worker and re-delivers, or relaunches the root process, which gets a `catch-up` notice of its tree and reads each issue's handoffs on its Dispatch issue (`dispatch handoff-read`).
9
- - `no_holder`: no live session holds the role.
10
- - `delivery_failed`: the message is not known to have reached the holder: the holder lookup failed, the holder was stale, the publish errored, or the stream did not store the forward. In the last case the holder can have seen the message live, and its dedupe drops a re-sent copy.
11
- - `receipt_timeout`: the listener forwarded the message to a live holder and no receipt arrived in time. Its payload keeps `original_topic`, `event_id`, `payload` and the original `dedupe_key`, so the daemon can re-send it and the receiver's dedupe drops a copy that did arrive.
8
+ - `no_holder`, `holder_lapsed`, `delivery_failed` and `receipt_timeout` on a Legion role are the daemon's liveness signals. Never add a second subscriber or retry by hand: the daemon revives or recreates the worker and re-delivers, or relaunches the root process, which gets a `catch-up` notice of its tree and reads each issue's handoffs on its Dispatch issue (`dispatch handoff-read`).
9
+ - `no_holder`: no session holds the role's claim. Only the reaper releases a claim, once its holder is `gone`; a Legion role whose agent process exits is `gone` at once, so its successor's soft claim takes the role without waiting out the live window.
10
+ - `holder_lapsed`: a session holds the claim but has not registered within the live window, so the listener refused the publish `404` and forwarded nothing. The error names the holder, its `holder_state` and its `last_seen`, and says `claim_released: false`. An `unresponsive` holder is not dead: it keeps the role, nothing replaces it, and the daemon holds the packet and publishes it again.
11
+ - `delivery_failed`: the message is not known to have reached the holder: the holder lookup failed, the holder's session could not be reached, the publish errored, or the stream did not store the forward. A role message published straight onto NATS gives it for an unresponsive holder too. In the stream case the holder can have seen the message live, and its dedupe drops a re-sent copy. It releases no claim.
12
+ - `receipt_timeout`: the listener forwarded the message to a live holder and no receipt arrived in time. The error names the holder. Its payload keeps `original_topic`, `event_id`, `payload` and the original `dedupe_key`, so the daemon can re-send it and the receiver's dedupe drops a copy that did arrive.
12
13
  - A role message forwarded to you is kept on your inbox in the stream, which your own durable consumer reads, so your session gets it once, also after the pane restarts or reconnects.
13
14
  - Never forward these failure payloads to an architect, because the daemon already acts on them.
@@ -2,11 +2,11 @@
2
2
 
3
3
  Read this when a role you held is gone after a resume, fork or restart, when `envoy_role_set` is refused, or when Envoy keeps a role publish because no live session holds the role.
4
4
 
5
- - A claim belongs to the session, not the process. `omp --resume` re-claims the role recorded in the session transcript, also after the listener removed the dead session's old row (a session's registration lapses 5 minutes after its last heartbeat).
5
+ - A claim belongs to the session, not the process. `omp --resume` re-claims the role recorded in the session transcript, also after the reaper removed the old session's row (the reaper removes a row only once that session is `gone`: past the gone horizon, `ENVOY_SESSION_GONE_HORIZON`, 1h by default).
6
6
  - `/fork`, `/branch`, `/handoff` and any other switch that carries the transcript read the role the previous session id held and move it to the new id while the new session starts. `/new` and `/resume` install an unrelated transcript and carry nothing.
7
- - A process that dies and is never resumed stops being a live holder. Until its registration lapses, role publishes return an error that names the holder and says it did not confirm the message (`receipt_timeout`). Once it lapses, Envoy keeps each role message for the session that claims the role next, and the publish's answer says it was kept, until that transcript resumes or another session claims the role. A client that stops cleanly deregisters its own session and sends its client instance id. The listener then removes the registration only when the registration carries the same id or none. So a departing client never removes a registration another process made under the same session id.
7
+ - A holder that has not registered for longer than the live window (`ENVOY_SESSION_LIVE_WINDOW`, 5m by default) reads `unresponsive`, and keeps its role: a role publish to it is refused `404 holder_lapsed`, which names the holder, its `holder_state`, its `last_seen` and `claim_released: false`, and nothing is forwarded and nothing kept. An unresponsive holder is not dead, so hold the message and publish it again later, start no replacement for that session, and take nothing from it. Only the role-claim reaper releases a claim, once the holder is `gone`; from then Envoy keeps each role publish for the session that claims the role next, and the answer says it was kept, until that transcript resumes or another session claims the role. A client that stops cleanly deregisters its own session and sends its client instance id, and the listener removes the registration only when the registration carries the same id or none, so a departing client never removes a registration another process made under the same session id.
8
8
  - A role message the listener forwarded to your session while you held the role is kept on your inbox in the stream, which your own durable consumer reads, so your session gets it once after a resume or a reconnect within 72 hours, also when the role moved to another session in the meantime.
9
- - An automatic reclaim never steals. It is a soft claim. The listener grants it when the role is unheld, and when its holder is no longer live. It also grants it when the holder is the session this claim continues, in three cases: that predecessor has no live registration, or its live registration carries this client instance's own id, or one of the two sides carries no instance id. A client instance is one Oh My Pi Envoy extension instance, or one Claude Code channel-server process. Each mints its id when it starts. A predecessor that another client instance still runs keeps the role. The listener then refuses the claim and names that holder.
10
- - A refusal does not stop the session. The session keeps running, and it stays registered, but without the role. It does not claim again at each heartbeat. The Oh My Pi plugin takes the role at its next session event, after the holder is gone. The Claude Code channel takes the role at an explicit claim. Use `envoy_role_get` to read who holds the role now.
9
+ - An automatic reclaim never steals. It is a soft claim, which the listener grants when the role is unheld, when its holder is not `live` — `gone`, or `unresponsive` past the live window, which is how a relaunched Legion role recovers it — and when its holder is the id this session continues (a fork's parent) and that predecessor is this client instance's: the predecessor is not `live`, or its live registration carries this instance's own id, or one of the two sides carries no instance id. A client instance is one Oh My Pi Envoy extension instance, or one Claude Code channel-server process; each mints its id when it starts. Any other `live` session keeps the role — the parent of a `/fork` whose role moved to the child, a second process on the same transcript, a named predecessor another client instance still runs — and the listener refuses atomically, naming that holder, while the resumed session logs a warning and holds nothing.
10
+ - A refusal does not stop the session. The session keeps running, and it stays registered, but without the role. It does not claim again at each heartbeat. The Oh My Pi plugin takes the role at its next session event, once the holder is no longer live. The Claude Code channel takes the role at an explicit claim. Use `envoy_role_get` to read who holds the role now.
11
11
  - Only an explicit `envoy_role_set` is last-claim-wins. Running it again for a role this session already holds is harmless.
12
12
  - If another plugin made subscriptions that depend on your current role, `envoy_role_set` to a different role is refused, and the refusal names those subscriptions. `envoy_unsubscribe` keeps those subscriptions and lists them as kept.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sjawhar/pi-envoy",
3
- "version": "16.10.0",
3
+ "version": "16.11.0",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "omp": {