@sjawhar/pi-envoy 16.9.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/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;
@@ -29836,6 +29837,8 @@ var CommentEventPayloadSchema = object({
29836
29837
  project_key: string2().optional(),
29837
29838
  artifact_slug: string2().optional(),
29838
29839
  body: string2().optional(),
29840
+ body_truncated: boolean2().optional(),
29841
+ payload_omitted: boolean2().optional(),
29839
29842
  reply_to: string2().nullish(),
29840
29843
  ask_id: string2().nullish(),
29841
29844
  ask_question: string2().optional(),
@@ -29861,6 +29864,8 @@ var CommentEventPayloadSchema = object({
29861
29864
  var MessageEventPayloadSchema = object({
29862
29865
  id: string2().optional(),
29863
29866
  body: string2().optional(),
29867
+ body_truncated: boolean2().optional(),
29868
+ payload_omitted: boolean2().optional(),
29864
29869
  target: string2().nullish(),
29865
29870
  in_reply_to: string2().nullish(),
29866
29871
  reply_body: string2().optional(),
@@ -30164,12 +30169,14 @@ function componentsArgument(z) {
30164
30169
  }).describe("Attach the issue to architecture components. Attach the root before decomposing it; children inherit unless they choose.");
30165
30170
  }
30166
30171
  var SPEC_WRITING_POINTER = "Write a spec as skill://dispatch-writing-specs says.";
30167
- function imagesArgument(z, owner, cap) {
30168
- return z.array(z.string({ min: 1 }), { min: 1 }).describe(`Optional local picture files to show inline: PNG, JPEG, GIF or WebP (by their bytes, not their name), each at most 25 MiB. Each is uploaded to ${owner} and appended after a blank line as one ![<file name>](dispatch://\u2026@vN) line, in this order; those lines count toward ${cap}.`).optional();
30172
+ function imagesArgument(z, owner) {
30173
+ return z.array(z.string({ min: 1 }), { min: 1 }).describe(`Optional local picture files to show inline: PNG, JPEG, GIF or WebP (by their bytes, not their name), each at most 25 MiB. Each is uploaded to ${owner} and appended after a blank line as one ![<file name>](dispatch://\u2026@vN) line, in this order; those lines count toward the bound Dispatch holds the text to, which it names in its refusal.`).optional();
30169
30174
  }
30170
30175
  var ASK_URGENCIES = ["low", "med", "high", "blocking"];
30171
- var ASK_QUESTION_MAX = 2000;
30172
- var DISPATCH_BODY_MAX = 32000;
30176
+ var DISPATCH_BLOCK_UNITS = 32000;
30177
+ var DISPATCH_ITEM_BLOCKS = 32768;
30178
+ var BODY_BLOCK_RULE = `Each block (a paragraph, list, quote, table or code block) holds at most ${DISPATCH_BLOCK_UNITS} ` + `characters and a body at most ${DISPATCH_ITEM_BLOCKS} blocks; Dispatch refuses a longer one and ` + "names it, and `dispatch limits` prints the bounds.";
30179
+ 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.";
30173
30180
  var DISPATCH_HANDOFF_BODY_MAX = 262144;
30174
30181
  var HANDOFF_PHASE_PATTERN = /^[a-z][a-z0-9-]{0,31}$/;
30175
30182
  var HANDOFF_PHASE_RULE_WORDS = "a lowercase letter, then up to 31 lowercase letters, digits or hyphens, such as implement";
@@ -30188,16 +30195,12 @@ function handoffProblem(value) {
30188
30195
  return HANDOFF_PHASE_RULE;
30189
30196
  if (typeof body !== "string")
30190
30197
  return;
30191
- const bytes = new TextEncoder().encode(body).length;
30192
- if (bytes > DISPATCH_HANDOFF_BODY_MAX) {
30193
- return `body is ${bytes - DISPATCH_HANDOFF_BODY_MAX} bytes over the ${DISPATCH_HANDOFF_BODY_MAX}-byte limit (${bytes}/${DISPATCH_HANDOFF_BODY_MAX})`;
30194
- }
30195
30198
  if (!isJsonObjectText(body)) {
30196
30199
  return 'body is not one JSON object: a handoff body is a JSON object such as {"schemaVersion":1}';
30197
30200
  }
30198
30201
  return;
30199
30202
  }
30200
- var HANDOFF_RULE = `${HANDOFF_PHASE_RULE}; the body is one JSON object of at most ${DISPATCH_HANDOFF_BODY_MAX} bytes.`;
30203
+ var HANDOFF_RULE = `${HANDOFF_PHASE_RULE}; the body is one JSON object.`;
30201
30204
  var handoffValidation = {
30202
30205
  check: (value) => handoffProblem(value) === undefined,
30203
30206
  message: HANDOFF_RULE,
@@ -30220,7 +30223,12 @@ var ISSUE_STATUSES = [
30220
30223
  "retro",
30221
30224
  "done"
30222
30225
  ];
30223
- var ISSUE_ROUTE_STATUSES = ["live", "no_holder", "unknown"];
30226
+ var ISSUE_ROUTE_STATUSES = [
30227
+ "live",
30228
+ "holder_unresponsive",
30229
+ "no_holder",
30230
+ "unknown"
30231
+ ];
30224
30232
  var DOC_EDIT_OPS = [
30225
30233
  "replace",
30226
30234
  "delete",
@@ -30262,7 +30270,7 @@ var dispatchToolSpecs = [
30262
30270
  arguments: (z) => ({
30263
30271
  issue: z.string().describe(ISSUE_REFERENCE),
30264
30272
  status: z.enum(ISSUE_STATUSES).describe("New lifecycle status.").optional(),
30265
- reason: z.string({ max: DISPATCH_BODY_MAX }).describe(`Required with status done, and only with it: why the issue is closing, at most ${DISPATCH_BODY_MAX} characters. Posted on the issue as a message before it closes.`).optional(),
30273
+ reason: z.string().describe(`Required with status done, and only with it: why the issue is closing. Posted on the issue as a message before it closes. ${BODY_BLOCK_RULE}`).optional(),
30266
30274
  title: z.string({ min: 1, max: ISSUE_TITLE_MAX }).describe("Replacement title, at most 1,000 characters.").optional(),
30267
30275
  labels: z.array(z.string({ min: 1, max: 40 }), { max: 20 }).describe("Replacement label set, at most 20 labels of up to 40 characters; replaces every existing label.").optional(),
30268
30276
  priority: z.number({ int: true, min: 0, max: 3 }).nullable().optional().describe("Coarse priority: 0 is P0 (highest) through 3 is P3 (lowest); null clears it."),
@@ -30308,13 +30316,13 @@ var dispatchToolSpecs = [
30308
30316
  }
30309
30317
  ]
30310
30318
  },
30311
- description: "Open a to-do or permission only a human can give, or a decision that has no document to " + "live in. A question about the design an issue's document records is not this tool: write " + "it into that document as a decision block (dispatch doc-edit inserting an ask block at the " + "end of the section it concerns), at every phase, approved spec or not; the block reaches " + "the Inbox and its answer lands next to its context. Never give an ask an Approve option: a " + "document is approved through dispatch request-approval. Do not use this tool for a status " + "update or discussion; use dispatch message instead. Never create an issue to park a " + "question: the question is an ask on the issue it concerns. " + ASK_QUESTION_CONTRACT + " " + ASK_OPTIONS_CONTRACT + " For an action only a human can perform, state what it changes and risks as constraints. " + "Anything that requires a human to do, including a credential or grant renewal, is an ask, " + "never a message. Measure what you can first, and put the measurement and the size of the " + "population it covers in the question; drop an option that cannot fix most of that " + "population, never offer it cut down, and keep an option not to act (Hold). Set urgency high " + "when your work halts on the answer, and keep working on everything else. " + "Anchor a to-do about a document passage, thread reply_to/reply_to_ask, or cite a dispatch:// " + `reference \u2014 it must be answerable from its own text and anchor alone, never "see above". ` + `A quote anchor is pinned to its block. Question is at most ${ASK_QUESTION_MAX} characters, ` + `the lines images appends included, and has at most 8 options. ${RELATED_CHECK_RESULT} ` + `An ask among the related items says whether it is answered, by whom and with which options. ${OWNER_REFERENCE}`,
30319
+ description: "Open a to-do or permission only a human can give, or a decision that has no document to " + "live in. A question about the design an issue's document records is not this tool: write " + "it into that document as a decision block (dispatch doc-edit inserting an ask block at the " + "end of the section it concerns), at every phase, approved spec or not; the block reaches " + "the Inbox and its answer lands next to its context. Never give an ask an Approve option: a " + "document is approved through dispatch request-approval. Do not use this tool for a status " + "update or discussion; use dispatch message instead. Never create an issue to park a " + "question: the question is an ask on the issue it concerns. " + ASK_QUESTION_CONTRACT + " " + ASK_OPTIONS_CONTRACT + " For an action only a human can perform, state what it changes and risks as constraints. " + "Anything that requires a human to do, including a credential or grant renewal, is an ask, " + "never a message. Measure what you can first, and put the measurement and the size of the " + "population it covers in the question; drop an option that cannot fix most of that " + "population, never offer it cut down, and keep an option not to act (Hold). Set urgency high " + "when your work halts on the answer, and keep working on everything else. " + "Anchor a to-do about a document passage, thread reply_to/reply_to_ask, or cite a dispatch:// " + `reference \u2014 it must be answerable from its own text and anchor alone, never "see above". ` + `A quote anchor is pinned to its block. ${ASK_BOUND_RULE} The lines images appends count ` + `toward that bound, and an ask has at most 8 options. ${RELATED_CHECK_RESULT} ` + `An ask among the related items says whether it is answered, by whom and with which options. ${OWNER_REFERENCE}`,
30312
30320
  arguments: (z) => ({
30313
30321
  issue: z.string().describe(ISSUE_REFERENCE).optional(),
30314
30322
  project: z.string().describe("Project key owning the document.").optional(),
30315
30323
  artifact: z.string().describe("Project document artifact id, slug, or filename.").optional(),
30316
30324
  ref: z.string().describe("Optional dispatch:// reference (issue, document, block, message, or ask); appended to the question and rendered as a link.").optional(),
30317
- question: z.string({ max: ASK_QUESTION_MAX }).describe(`${ASK_QUESTION_CONTRACT} At most ${ASK_QUESTION_MAX} characters.`),
30325
+ question: z.string().describe(`${ASK_QUESTION_CONTRACT} ${ASK_BOUND_RULE}`),
30318
30326
  options: z.array(z.object({
30319
30327
  label: z.string().describe("Selectable option label."),
30320
30328
  description: z.string().optional().describe("What this option costs.")
@@ -30326,7 +30334,7 @@ var dispatchToolSpecs = [
30326
30334
  quote: z.string().describe("Exact text the decision concerns."),
30327
30335
  occurrence: z.number({ int: true, min: 0 }).describe("Zero-based occurrence of the quote.").optional()
30328
30336
  }).describe("Optional document location for the question.").optional(),
30329
- images: imagesArgument(z, "the issue (or the project document's project)", `the ${ASK_QUESTION_MAX}-character question limit`)
30337
+ images: imagesArgument(z, "the issue (or the project document's project)")
30330
30338
  }),
30331
30339
  validation: documentOwnerValidation(true)
30332
30340
  },
@@ -30349,7 +30357,7 @@ var dispatchToolSpecs = [
30349
30357
  description: "Edit an open question in place. Use it to correct or refine the same decision; retract the " + "old ask and open a new one when the decision itself changes. " + ASK_QUESTION_CONTRACT + " " + ASK_OPTIONS_CONTRACT + " Previous text remains in the event log. Only the asking session can edit it; answered or " + "resolved asks cannot be edited. An ask that lives as an `ask` block in a document is written " + "in the document too, changing only the fields you name - pass urgency alone and the " + "question's wording, formatting, links and comment anchors are untouched - so the edit " + "writes a document version and closes a spec's design gate until that version is approved; " + "text the block cannot carry back unchanged is refused, naming the field - an option label " + 'containing ": ", the separator between a label and its description, is one example.',
30350
30358
  arguments: (z) => ({
30351
30359
  ask: z.string().describe("Ask id (uuid); an 8+ hex prefix unique among this session's own open asks works too."),
30352
- question: z.string({ max: ASK_QUESTION_MAX }).optional().describe(`${ASK_QUESTION_CONTRACT} Replaces the ask's question; at most ${ASK_QUESTION_MAX} characters.`),
30360
+ question: z.string().optional().describe(`${ASK_QUESTION_CONTRACT} Replaces the ask's question. ${ASK_BOUND_RULE}`),
30353
30361
  options: z.array(z.object({
30354
30362
  label: z.string().describe("Selectable option label."),
30355
30363
  description: z.string().optional().describe("What this option costs.")
@@ -30401,7 +30409,7 @@ var dispatchToolSpecs = [
30401
30409
  {
30402
30410
  name: "dispatch_comment",
30403
30411
  example: { issue: "DSP-1", body: "Looks good." },
30404
- description: "Add review feedback to an issue or project document quote, or reply to a question asked with dispatch ask. " + "Do not use it for an exact replacement; use " + `dispatch suggest instead. A quote anchor is pinned to its block. A reply under an open ask asks for clarification, not an answer: answer it with reply_to_ask, or reword the ask with dispatch edit-ask, rather than opening a second ask. Body is at most ${DISPATCH_BODY_MAX} characters, the lines images appends included. ${OWNER_REFERENCE}`,
30412
+ description: "Add review feedback to an issue or project document quote, or reply to a question asked with dispatch ask. " + "Do not use it for an exact replacement; use " + `dispatch suggest instead. A quote anchor is pinned to its block. A reply under an open ask asks for clarification, not an answer: answer it with reply_to_ask, or reword the ask with dispatch edit-ask, rather than opening a second ask. ${BODY_BLOCK_RULE} The lines images appends count toward it. ${OWNER_REFERENCE}`,
30405
30413
  arguments: (z) => ({
30406
30414
  issue: z.string().describe(ISSUE_REFERENCE).optional(),
30407
30415
  project: z.string().describe("Project key owning the document.").optional(),
@@ -30409,11 +30417,11 @@ var dispatchToolSpecs = [
30409
30417
  ref: z.string().describe("Optional dispatch:// issue or document reference.").optional(),
30410
30418
  quote: z.string().describe("Optional exact quoted document text.").optional(),
30411
30419
  occurrence: z.number({ int: true, min: 0 }).describe("Optional zero-based occurrence of quote.").optional(),
30412
- body: z.string({ max: DISPATCH_BODY_MAX }).describe(`Review comment, at most ${DISPATCH_BODY_MAX} characters.`),
30420
+ body: z.string().describe(`Review comment. ${BODY_BLOCK_RULE}`),
30413
30421
  reply_to: z.string().describe("A comment id (uuid); replying to any comment in a thread continues that thread (an " + "ask's clarification thread included). A block reference to one block of the comment " + "(dispatch://KEY/comment/<id>#b-<block id>) replies to that comment and names the " + "passage the reply answers. To reply to an ask, use reply_to_ask with the ask id, or " + "with a reference to one of its parts, instead.").optional(),
30414
30422
  reply_to_ask: z.string().describe("Optional ask id to reply to, threading this comment under that question. A block " + "reference to one part of the ask (dispatch://KEY/ask/<id>#b-<part id>, the id an " + "option or the answer carries) threads under that ask and names the part the reply " + "answers. Mutually exclusive with reply_to.").optional(),
30415
30423
  turn: z.enum(["agent", "human"]).describe("Only with reply_to_ask: who holds the turn after this reply. agent: a progress note - " + "you keep the turn and the ask stays 'Waiting on agents' for the human; human (default): " + "you need the human to act - the ask returns to 'Waiting on you'. human does not " + "apply to an approval request a newer version moved: it stays with you until dispatch " + "request-approval hands it back at the current version.").optional(),
30416
- images: imagesArgument(z, "the issue (or the project document's project)", `the ${DISPATCH_BODY_MAX}-character body limit`)
30424
+ images: imagesArgument(z, "the issue (or the project document's project)")
30417
30425
  }),
30418
30426
  validation: commentValidation
30419
30427
  },
@@ -30425,7 +30433,7 @@ var dispatchToolSpecs = [
30425
30433
  quote: "old wording",
30426
30434
  replace_with: "new wording"
30427
30435
  },
30428
- description: "Propose an exact replacement for quoted document text. Do not use it for general feedback; use " + `dispatch comment instead. Optional explanation is at most ${DISPATCH_BODY_MAX} characters. ${OWNER_REFERENCE}`,
30436
+ description: "Propose an exact replacement for quoted document text. Do not use it for general feedback; use " + `dispatch comment instead. ${BODY_BLOCK_RULE} ${OWNER_REFERENCE}`,
30429
30437
  arguments: (z) => ({
30430
30438
  issue: z.string().describe(ISSUE_REFERENCE).optional(),
30431
30439
  project: z.string().describe("Project key owning the document.").optional(),
@@ -30433,7 +30441,7 @@ var dispatchToolSpecs = [
30433
30441
  ref: z.string().describe("Optional dispatch:// issue or document reference.").optional(),
30434
30442
  quote: z.string().describe("Exact document text to replace."),
30435
30443
  replace_with: z.string().describe("Replacement text; a CR LF or a lone carriage return in it is written as a line feed."),
30436
- body: z.string({ max: DISPATCH_BODY_MAX }).describe(`Optional rationale, at most ${DISPATCH_BODY_MAX} characters.`).optional(),
30444
+ body: z.string().describe(`Optional rationale. ${BODY_BLOCK_RULE}`).optional(),
30437
30445
  occurrence: z.number({ int: true, min: 0 }).describe("Optional zero-based occurrence of quote.").optional()
30438
30446
  }),
30439
30447
  validation: documentOwnerValidation(true, true)
@@ -30441,12 +30449,12 @@ var dispatchToolSpecs = [
30441
30449
  {
30442
30450
  name: "dispatch_message",
30443
30451
  example: { issue: "DSP-1", body: "Implementation started." },
30444
- description: "Post a note humans must read now: a reply to a human's message or a deliverable that landed. A to-do only a human can " + "complete is an ask (dispatch ask), so it reaches their inbox. Never progress or status updates - Dispatch is a high-signal " + "record, not a log. Not a design decision (write it as a decision block in the document) or document feedback (dispatch comment). " + "To answer a human's direct message to this session - one sent from the Agents page, which names no issue - pass that message's bare id as " + "in_reply_to and no issue; the reply lands in that conversation. Another call with the same in_reply_to and new text posts a follow-up, " + "threaded under this session's first reply; the same text again posts nothing. dispatch read --message <id> reads " + "that conversation back. " + "Every other message names its issue; keep --issue whenever the frame you answer gave one. A BTW, Aside or Steer " + "frame carries a reply_with command: answer with it, on that issue. On Oh My Pi an Agents-page Send or Aside " + "arrives as a user message: answer in the conversation, with no dispatch message. " + `Body is at most ${DISPATCH_BODY_MAX} characters, the lines images appends included. ${ISSUE_REFERENCE}`,
30452
+ description: "Post a note humans must read now: a reply to a human's message or a deliverable that landed. A to-do only a human can " + "complete is an ask (dispatch ask), so it reaches their inbox. Never progress or status updates - Dispatch is a high-signal " + "record, not a log. Not a design decision (write it as a decision block in the document) or document feedback (dispatch comment). " + "To answer a human's direct message to this session - one sent from the Agents page, which names no issue - pass that message's bare id as " + "in_reply_to and no issue; the reply lands in that conversation. Another call with the same in_reply_to and new text posts a follow-up, " + "threaded under this session's first reply; the same text again posts nothing. dispatch read --message <id> reads " + "that conversation back. " + "Every other message names its issue; keep --issue whenever the frame you answer gave one. A BTW, Aside or Steer " + "frame carries a reply_with command: answer with it, on that issue. On Oh My Pi an Agents-page Send or Aside " + "arrives as a user message: answer in the conversation, with no dispatch message. " + `${BODY_BLOCK_RULE} The lines images appends count toward it. ${ISSUE_REFERENCE}`,
30445
30453
  arguments: (z) => ({
30446
30454
  issue: z.string().describe(`${ISSUE_REFERENCE} Omit it only when in_reply_to answers a human's direct message to this session.`).optional(),
30447
- body: z.string({ max: DISPATCH_BODY_MAX }).describe(`Update text, at most ${DISPATCH_BODY_MAX} characters.`),
30455
+ body: z.string().describe(`Update text. ${BODY_BLOCK_RULE}`),
30448
30456
  in_reply_to: z.string().describe("Optional message id or dispatch://KEY/message/<id> reference to reply to, threading " + "this message under it so the reply stays with the original in the Conversation. " + "A block reference to one block of the message (dispatch://KEY/message/<id>#b-<block id>) " + "replies to that message and names the passage the reply answers. " + "A bare id with no issue answers a human's direct message to this session; a " + "dispatch://KEY/message/<id> names the issue its message lives on, so that form is a " + "reply on that issue.").optional(),
30449
- images: imagesArgument(z, "the issue (a reply to a direct message: your own conversation, dispatch://agent/<your session id>)", `the ${DISPATCH_BODY_MAX}-character body limit`)
30457
+ images: imagesArgument(z, "the issue (a reply to a direct message: your own conversation, dispatch://agent/<your session id>)")
30450
30458
  }),
30451
30459
  validation: messageValidation
30452
30460
  },
@@ -30645,7 +30653,7 @@ var dispatchToolSpecs = [
30645
30653
  label: z.string().describe("Optional label filter.").optional(),
30646
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(),
30647
30655
  updated_since: z.string().describe("Optional RFC3339 timestamp; only issues updated at or after it.").optional(),
30648
- 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(),
30649
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(),
30650
30658
  offset: z.number({ int: true, min: 0 }).describe("Rows to skip before the page; nonnegative integer; default 0.").optional(),
30651
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()
@@ -30708,6 +30716,13 @@ var dispatchToolSpecs = [
30708
30716
  arguments: () => ({}),
30709
30717
  strict: true
30710
30718
  },
30719
+ {
30720
+ name: "dispatch_limits",
30721
+ example: {},
30722
+ description: "The bounds this Dispatch server holds a write to, read from the server itself: how long one block of a body may be and how many blocks a body may hold, how many options an ask may have and how long an ask's question and options are together, how long a body an event carries whole may be, and how many bytes a request, a document and a handoff body may hold. Dispatch refuses a text over a bound and names the block or the field it passed; no tool and no command cuts or refuses your text before the server reads it, so these numbers are what decides whether a write is taken.",
30723
+ arguments: () => ({}),
30724
+ strict: true
30725
+ },
30711
30726
  {
30712
30727
  name: "dispatch_handoff_write",
30713
30728
  example: {
@@ -35004,6 +35019,9 @@ class DispatchClient {
35004
35019
  async whoami() {
35005
35020
  return this.#json("GET", ["api", "v1", "whoami"]);
35006
35021
  }
35022
+ async limits() {
35023
+ return this.#json("GET", ["api", "v1", "limits"]);
35024
+ }
35007
35025
  async inbox(assignee) {
35008
35026
  return this.#json("GET", ["api", "v1", "inbox"], undefined, { assignee });
35009
35027
  }
@@ -35940,6 +35958,40 @@ function eventPictures(event) {
35940
35958
  }
35941
35959
  return typeof text === "string" ? pictureAddresses(text) : [];
35942
35960
  }
35961
+ function carriedItem(event) {
35962
+ const resource = event.type.startsWith("comment.") || event.type.startsWith("suggestion.") ? "comment" : event.type.startsWith("message.") ? "message" : undefined;
35963
+ if (resource === undefined || !isObject3(event.payload))
35964
+ return;
35965
+ const id = event.payload["id"];
35966
+ if (typeof id !== "string" || id === "")
35967
+ return;
35968
+ return { resource, id, issueKey: event.issue_key };
35969
+ }
35970
+ function bodyWasCut(payload) {
35971
+ return isObject3(payload) && (payload["body_truncated"] === true || payload["payload_omitted"] === true);
35972
+ }
35973
+ function wholeItemRoute(item) {
35974
+ return `GET /api/v1/${item.resource === "comment" ? "comments" : "messages"}/${item.id}`;
35975
+ }
35976
+ function carriedBodyNote(event) {
35977
+ if (!bodyWasCut(event.payload))
35978
+ return;
35979
+ const what = isObject3(event.payload) && event.payload["payload_omitted"] === true ? "this event carries no body: it was too large for the bus" : "the body is its first part only";
35980
+ const item = carriedItem(event);
35981
+ return item === undefined ? what : `${what}; read it whole with ${wholeItemRoute(item)}`;
35982
+ }
35983
+ async function wholeCarriedBody(client, item, session) {
35984
+ try {
35985
+ if (item.resource === "comment") {
35986
+ const read = await client.getComment(item.id);
35987
+ return [read.comment, ...read.replies].find((comment) => comment.id === item.id)?.body;
35988
+ }
35989
+ const read = item.issueKey === null ? session === undefined ? undefined : await client.getMessageThread(item.id, session) : await client.getMessage(item.issueKey, item.id);
35990
+ return read === undefined ? undefined : [read.message, ...read.replies].find((message) => message.id === item.id)?.body;
35991
+ } catch {
35992
+ return;
35993
+ }
35994
+ }
35943
35995
  function senderLabel(envelope) {
35944
35996
  const sender = envelope.source_session ?? envelope.source ?? "unknown";
35945
35997
  return envelope.sender?.title === undefined ? sender : `${sender} (${envelope.sender.title})`;
@@ -36145,7 +36197,13 @@ function dispatchReplyRef(event, topic, inReplyTo, comment) {
36145
36197
  function isObject3(value) {
36146
36198
  return typeof value === "object" && value !== null;
36147
36199
  }
36148
- function parseDispatchFrame(rawPayload) {
36200
+ function withWholeBody(event, body) {
36201
+ if (body === undefined || !isObject3(event.payload) || !bodyWasCut(event.payload))
36202
+ return event;
36203
+ const { body_truncated: _cut, payload_omitted: _omitted, ...carried } = event.payload;
36204
+ return { ...event, payload: { ...carried, body } };
36205
+ }
36206
+ function parseDispatchFrame(rawPayload, wholeBody) {
36149
36207
  let value;
36150
36208
  try {
36151
36209
  value = JSON.parse(rawPayload);
@@ -36157,7 +36215,7 @@ function parseDispatchFrame(rawPayload) {
36157
36215
  if (targeted.success) {
36158
36216
  const wireFrame = value;
36159
36217
  return {
36160
- event: targeted.data.event,
36218
+ event: withWholeBody(targeted.data.event, wholeBody),
36161
36219
  notify: wireFrame.event.notify,
36162
36220
  quiet: wireFrame.event.quiet,
36163
36221
  delivery: targeted.data.delivery
@@ -36191,7 +36249,7 @@ function parseDispatchFrame(rawPayload) {
36191
36249
  return { raw: value };
36192
36250
  const wireEvent = value;
36193
36251
  return {
36194
- event: parsed.data,
36252
+ event: withWholeBody(parsed.data, wholeBody),
36195
36253
  notify: wireEvent.notify,
36196
36254
  quiet: wireEvent.quiet,
36197
36255
  delivery: undefined
@@ -36203,7 +36261,7 @@ function inboundTimestamp(milliseconds) {
36203
36261
  const date = new Date(Math.floor(milliseconds / 1000) * 1000);
36204
36262
  return Number.isNaN(date.getTime()) ? "unknown" : date.toISOString().replace(".000Z", "Z");
36205
36263
  }
36206
- function renderInbound(raw, sessionID, subject) {
36264
+ function renderInbound(raw, sessionID, subject, wholeBody) {
36207
36265
  let value;
36208
36266
  try {
36209
36267
  value = JSON.parse(raw);
@@ -36239,6 +36297,8 @@ function renderInbound(raw, sessionID, subject) {
36239
36297
  let rejectedDelivery;
36240
36298
  let malformedDelivery = false;
36241
36299
  let pictures = [];
36300
+ let bodyNote;
36301
+ let cutItem;
36242
36302
  let inReplyTo = envelope.in_reply_to;
36243
36303
  let askAuthor;
36244
36304
  let trailer = "";
@@ -36248,7 +36308,7 @@ function renderInbound(raw, sessionID, subject) {
36248
36308
  if (envelope.payload === undefined) {
36249
36309
  dispatchIssue = "payload";
36250
36310
  } else {
36251
- const frame = parseDispatchFrame(envelope.payload);
36311
+ const frame = parseDispatchFrame(envelope.payload, wholeBody);
36252
36312
  if ("event" in frame) {
36253
36313
  const quiet = frame.quiet === undefined ? frame.notify === false : frame.quiet === true;
36254
36314
  if (quiet && topic?.startsWith(DISPATCH_TOPIC_PREFIX) === true) {
@@ -36309,6 +36369,7 @@ function renderInbound(raw, sessionID, subject) {
36309
36369
  replyFields: {},
36310
36370
  issueKey: frame.event.issue_key,
36311
36371
  body: message.data.body,
36372
+ ...message.data.body_truncated === true ? { bodyTruncated: true } : {},
36312
36373
  ...typeof message.data.broadcast_id === "string" ? { broadcastId: message.data.broadcast_id } : {}
36313
36374
  };
36314
36375
  dispatchReply = {
@@ -36331,7 +36392,8 @@ function renderInbound(raw, sessionID, subject) {
36331
36392
  replyPath: dispatchReplyPath("comment", requested.data.comment_id),
36332
36393
  replyFields: { target: requested.data.target },
36333
36394
  issueKey: frame.event.issue_key,
36334
- body: comment.data.body
36395
+ body: comment.data.body,
36396
+ ...comment.data.body_truncated === true ? { bodyTruncated: true } : {}
36335
36397
  };
36336
36398
  }
36337
36399
  }
@@ -36346,6 +36408,9 @@ function renderInbound(raw, sessionID, subject) {
36346
36408
  ...compactRecord ?? { payload: dispatchPayloadForReader(frame.event, sessionID) }
36347
36409
  };
36348
36410
  dispatchActor = frame.event.actor;
36411
+ bodyNote = carriedBodyNote(frame.event);
36412
+ if (bodyWasCut(frame.event.payload))
36413
+ cutItem = carriedItem(frame.event);
36349
36414
  pictures = eventPictures(frame.event);
36350
36415
  if (frame.event.type === "artifact.human_edited") {
36351
36416
  const edit = ArtifactHumanEditedEventPayloadSchema.safeParse(frame.event.payload);
@@ -36411,6 +36476,7 @@ function renderInbound(raw, sessionID, subject) {
36411
36476
  ...summaryIsHead ? {} : { summary: payloadSummary },
36412
36477
  ...message === undefined ? {} : { message }
36413
36478
  },
36479
+ ...bodyNote === undefined ? {} : { body_note: bodyNote },
36414
36480
  ...foreignSession === undefined ? {} : {
36415
36481
  note: `body names session ${foreignSession}; the sender is ${envelope.source_session ?? "unknown"}`
36416
36482
  },
@@ -36426,7 +36492,8 @@ ${trailer}`,
36426
36492
  ...delivery === undefined ? {} : { delivery },
36427
36493
  ...rejectedDelivery === undefined ? {} : { rejectedDelivery },
36428
36494
  ...malformedDelivery ? { malformedDelivery: true } : {},
36429
- ...pictures.length === 0 ? {} : { pictures }
36495
+ ...pictures.length === 0 ? {} : { pictures },
36496
+ ...cutItem === undefined ? {} : { cutItem }
36430
36497
  };
36431
36498
  }
36432
36499
 
@@ -36993,6 +37060,13 @@ var DEFAULT_HEARTBEAT_MS = 90000;
36993
37060
  var MIN_PASS_DEADLINE_MS = 30000;
36994
37061
  var MIN_INTERVAL_MS = 25;
36995
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
+ }
36996
37070
  function namedInterval(raw) {
36997
37071
  const parsed = Number(raw);
36998
37072
  return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;
@@ -37115,6 +37189,9 @@ var DEFAULT_TIMEOUT_MS = 5000;
37115
37189
  var RETRY_DELAY_MS = 250;
37116
37190
  var REPLAY_TIMEOUT_MS = 1e4;
37117
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");
37118
37195
  var InterestWireSchema = object({
37119
37196
  session_id: string2(),
37120
37197
  machine_id: string2(),
@@ -37144,6 +37221,7 @@ var SessionWireSchema = object({
37144
37221
  capabilities: array(string2()).optional(),
37145
37222
  self_subscribed: boolean2(),
37146
37223
  last_seen: number2().int().optional(),
37224
+ state: WireStateSchema,
37147
37225
  plugin: string2().optional(),
37148
37226
  plugin_version: string2().optional()
37149
37227
  });
@@ -37151,7 +37229,9 @@ var RoleWireSchema = object({
37151
37229
  role: string2(),
37152
37230
  holder: string2(),
37153
37231
  host: string2().optional(),
37154
- last_seen: number2().int()
37232
+ last_seen: number2().int(),
37233
+ state: WireStateSchema,
37234
+ holder_state: SessionStateSchema.optional()
37155
37235
  });
37156
37236
  var RoleHeldWireSchema = object({
37157
37237
  error: string2(),
@@ -37161,11 +37241,21 @@ var RoleHeldWireSchema = object({
37161
37241
  var ErrorWireSchema = object({
37162
37242
  error: string2(),
37163
37243
  code: string2().optional(),
37164
- 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()
37165
37251
  });
37166
37252
  var EnvelopeResponseSchema = EnvelopeSchema.extend({
37167
37253
  recipient: string2().optional(),
37168
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(),
37169
37259
  duplicate: boolean2().optional()
37170
37260
  });
37171
37261
  var PublishResponseSchema = EnvelopeResponseSchema.extend({
@@ -37217,6 +37307,9 @@ function mergeInterestSources(registryTopics, liveTopics) {
37217
37307
  }
37218
37308
  return interests;
37219
37309
  }
37310
+ function holderStateOf(role) {
37311
+ return role.holder_state ?? role.state;
37312
+ }
37220
37313
  function newClientInstanceID() {
37221
37314
  return Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, "0")).join("");
37222
37315
  }
@@ -37237,12 +37330,36 @@ function expandSubscriptionTopics(topics) {
37237
37330
  }
37238
37331
  return [...expanded];
37239
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
+ }
37240
37352
 
37241
37353
  class EnvoyApiError extends Error {
37242
37354
  details;
37243
37355
  name = "EnvoyApiError";
37244
37356
  expected;
37245
37357
  code;
37358
+ holder;
37359
+ sessionState;
37360
+ lastSeen;
37361
+ claimReleased;
37362
+ unresponsive;
37246
37363
  constructor(details) {
37247
37364
  let parsed;
37248
37365
  try {
@@ -37250,10 +37367,15 @@ class EnvoyApiError extends Error {
37250
37367
  if (result.success)
37251
37368
  parsed = result.data;
37252
37369
  } catch {}
37253
- 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)}`);
37254
37371
  this.details = details;
37255
37372
  this.expected = parsed?.expected;
37256
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;
37257
37379
  }
37258
37380
  }
37259
37381
  var mintedDedupeKey2 = new RegExp(MINTED_DEDUPE_KEY_PATTERN);
@@ -37409,6 +37531,8 @@ function createEnvoyClient(config) {
37409
37531
  envelope: response,
37410
37532
  recipient: response.recipient ?? input.targetSessionID,
37411
37533
  confirmed: response.recipient !== undefined,
37534
+ recipientState: response.recipient_state ?? "live",
37535
+ ...response.last_seen === undefined || response.last_seen <= 0 ? {} : { lastSeen: response.last_seen },
37412
37536
  duplicate: response.duplicate === true
37413
37537
  };
37414
37538
  },
@@ -37427,6 +37551,8 @@ function createEnvoyClient(config) {
37427
37551
  return {
37428
37552
  envelope: response,
37429
37553
  ...response.holder === undefined ? {} : { holder: response.holder },
37554
+ ...response.holder_state === undefined ? {} : { holderState: response.holder_state },
37555
+ unresponsive: response.unresponsive ?? [],
37430
37556
  ...response.kept === undefined ? {} : { kept: response.kept },
37431
37557
  ...response.kept_reason === undefined ? {} : { keptReason: response.kept_reason }
37432
37558
  };
@@ -37470,6 +37596,8 @@ function createEnvoyClient(config) {
37470
37596
  search.set("dir", input.directory);
37471
37597
  if (input.title !== undefined)
37472
37598
  search.set("title", input.title);
37599
+ if (input.include !== undefined)
37600
+ search.set("include", input.include);
37473
37601
  const query = search.size === 0 ? "" : `?${search.toString()}`;
37474
37602
  return SessionWireSchema.array().parse(JSON.parse(await request(`/v1/sessions${query}`, {})));
37475
37603
  },
@@ -38926,148 +39054,6 @@ function readDispatchFirstContext(skillFile) {
38926
39054
  `);
38927
39055
  }
38928
39056
 
38929
- // ../envoy-client/src/tool-input-errors.ts
38930
- class ToolInputError extends Error {
38931
- tool;
38932
- problems;
38933
- constructor(tool, problems) {
38934
- const count = problems.length;
38935
- const cli = isDispatchTool(tool);
38936
- const help = cli ? [
38937
- `Allowed flags: ${commandFlags(tool).join(", ")}`,
38938
- `Example: ${commandLine(tool, exampleFor(tool))}`
38939
- ] : [];
38940
- super([
38941
- `${cli ? `dispatch ${commandName(tool)}` : tool} was not called: ${count} problem${count === 1 ? "" : "s"}`,
38942
- ...problems.map((problem) => `- ${problem}`),
38943
- ...help.map((line) => `- ${line}`)
38944
- ].join(`
38945
- `));
38946
- this.name = "ToolInputError";
38947
- this.tool = tool;
38948
- this.problems = problems;
38949
- }
38950
- }
38951
- function isDispatchTool(tool) {
38952
- return dispatchToolSpecs.some((spec) => spec.name === tool);
38953
- }
38954
- function exampleFor(tool) {
38955
- const spec = dispatchToolSpecs.find((candidate) => candidate.name === tool);
38956
- return { ...spec?.example };
38957
- }
38958
- function unwrap(schema) {
38959
- let current = schema;
38960
- while (current !== undefined) {
38961
- const def = current.def;
38962
- if (!("innerType" in def) || !(def.type === "optional" || def.type === "nullable" || def.type === "default"))
38963
- break;
38964
- current = def.innerType;
38965
- }
38966
- return current;
38967
- }
38968
- function shapeOf(schema) {
38969
- const unwrapped = unwrap(schema);
38970
- if (unwrapped === undefined)
38971
- return;
38972
- const def = unwrapped.def;
38973
- return def.type === "object" && "shape" in def ? def.shape : undefined;
38974
- }
38975
- function schemaAt(schema, path) {
38976
- let current = schema;
38977
- for (const key of path) {
38978
- const unwrapped = unwrap(current);
38979
- if (unwrapped === undefined)
38980
- return;
38981
- const def = unwrapped.def;
38982
- if (def.type === "object" && "shape" in def) {
38983
- current = shapeOf(unwrapped)?.[String(key)];
38984
- } else if (def.type === "array" && "element" in def) {
38985
- current = def.element;
38986
- } else {
38987
- return;
38988
- }
38989
- }
38990
- return unwrap(current);
38991
- }
38992
- function describeInput(value) {
38993
- if (value === null)
38994
- return "null";
38995
- if (Array.isArray(value))
38996
- return "an array";
38997
- switch (typeof value) {
38998
- case "number":
38999
- case "boolean":
39000
- return String(value);
39001
- case "string":
39002
- return "a string";
39003
- case "object":
39004
- return "an object";
39005
- default:
39006
- return typeof value;
39007
- }
39008
- }
39009
- function describeExpected(expected, schema) {
39010
- switch (expected) {
39011
- case "int":
39012
- return "an integer";
39013
- case "object": {
39014
- const shape = shapeOf(schema);
39015
- const keys = shape === undefined ? [] : Object.entries(shape).map(([key, field]) => `${key}${field.def.type === "optional" ? "?" : ""}`);
39016
- return keys.length === 0 ? "an object" : `an object {${keys.join(", ")}}`;
39017
- }
39018
- case "array":
39019
- return "an array";
39020
- default:
39021
- return `a ${expected}`;
39022
- }
39023
- }
39024
- function pathText(path, cliTool) {
39025
- const [head, ...rest] = path.map(String);
39026
- if (cliTool === undefined || head === undefined)
39027
- return path.map(String).join(".");
39028
- let flag = fieldFlag(cliTool, head);
39029
- let index = 0;
39030
- for (;index < rest.length && /^\d+$/.test(rest[index]); index++) {
39031
- flag += `[${rest[index]}]`;
39032
- }
39033
- const tail = rest.slice(index).map((segment) => /^\d+$/.test(segment) ? `[${segment}]` : `.${segment}`).join("").replace(/^\./, "");
39034
- return tail === "" ? flag : `${flag} ${tail}`;
39035
- }
39036
- function formatZodIssues(issues, schema, tool) {
39037
- const cliTool = isDispatchTool(tool) ? tool : undefined;
39038
- const allowed = Object.keys(shapeOf(schema) ?? {}).join(", ");
39039
- return issues.flatMap((issue) => {
39040
- const path = pathText(issue.path, cliTool);
39041
- switch (issue.code) {
39042
- case "invalid_type":
39043
- return issue.input === undefined ? [`${path} is required (${issue.expected})`] : [
39044
- `${path} must be ${describeExpected(issue.expected, schemaAt(schema, issue.path))}, not ${describeInput(issue.input)}`
39045
- ];
39046
- case "unrecognized_keys": {
39047
- if (cliTool !== undefined && issue.path.length === 0) {
39048
- return issue.keys.map((key) => `unknown flag ${fieldFlag(cliTool, key)}`);
39049
- }
39050
- const here = Object.keys(shapeOf(schemaAt(schema, issue.path)) ?? {}).join(", ") || allowed;
39051
- const where = path === "" ? "" : ` in ${path}`;
39052
- return issue.keys.map((key) => `unknown field "${key}"${where}; allowed: ${here}`);
39053
- }
39054
- case "invalid_value":
39055
- return [
39056
- `${path} must be one of ${issue.values.map(String).join("|")}; got ${JSON.stringify(issue.input)}`
39057
- ];
39058
- case "too_big":
39059
- if (issue.origin === "array" && Array.isArray(issue.input)) {
39060
- return [`${path} has ${issue.input.length} items; the limit is ${issue.maximum}`];
39061
- }
39062
- return [`${path} ${issue.message}`];
39063
- case "custom":
39064
- return [issue.message];
39065
- default:
39066
- return [path === "" ? issue.message : `${path}: ${issue.message}`];
39067
- }
39068
- });
39069
- }
39070
-
39071
39057
  // ../envoy-client/src/dispatch-picture-tools.ts
39072
39058
  var PICTURE_TYPE_NAMES = "a PNG, JPEG, GIF or WebP";
39073
39059
  var AGENT_ARTIFACT_REF = new RegExp(`^dispatch://agent/(${SESSION_ID_PATTERN})/artifact/([^/@]+)(?:@v(\\d+))?$`, "u");
@@ -39606,6 +39592,148 @@ async function readSessionAnswers(options) {
39606
39592
  };
39607
39593
  }
39608
39594
 
39595
+ // ../envoy-client/src/tool-input-errors.ts
39596
+ class ToolInputError extends Error {
39597
+ tool;
39598
+ problems;
39599
+ constructor(tool, problems) {
39600
+ const count = problems.length;
39601
+ const cli = isDispatchTool(tool);
39602
+ const help = cli ? [
39603
+ `Allowed flags: ${commandFlags(tool).join(", ")}`,
39604
+ `Example: ${commandLine(tool, exampleFor(tool))}`
39605
+ ] : [];
39606
+ super([
39607
+ `${cli ? `dispatch ${commandName(tool)}` : tool} was not called: ${count} problem${count === 1 ? "" : "s"}`,
39608
+ ...problems.map((problem) => `- ${problem}`),
39609
+ ...help.map((line) => `- ${line}`)
39610
+ ].join(`
39611
+ `));
39612
+ this.name = "ToolInputError";
39613
+ this.tool = tool;
39614
+ this.problems = problems;
39615
+ }
39616
+ }
39617
+ function isDispatchTool(tool) {
39618
+ return dispatchToolSpecs.some((spec) => spec.name === tool);
39619
+ }
39620
+ function exampleFor(tool) {
39621
+ const spec = dispatchToolSpecs.find((candidate) => candidate.name === tool);
39622
+ return { ...spec?.example };
39623
+ }
39624
+ function unwrap(schema) {
39625
+ let current = schema;
39626
+ while (current !== undefined) {
39627
+ const def = current.def;
39628
+ if (!("innerType" in def) || !(def.type === "optional" || def.type === "nullable" || def.type === "default"))
39629
+ break;
39630
+ current = def.innerType;
39631
+ }
39632
+ return current;
39633
+ }
39634
+ function shapeOf(schema) {
39635
+ const unwrapped = unwrap(schema);
39636
+ if (unwrapped === undefined)
39637
+ return;
39638
+ const def = unwrapped.def;
39639
+ return def.type === "object" && "shape" in def ? def.shape : undefined;
39640
+ }
39641
+ function schemaAt(schema, path) {
39642
+ let current = schema;
39643
+ for (const key of path) {
39644
+ const unwrapped = unwrap(current);
39645
+ if (unwrapped === undefined)
39646
+ return;
39647
+ const def = unwrapped.def;
39648
+ if (def.type === "object" && "shape" in def) {
39649
+ current = shapeOf(unwrapped)?.[String(key)];
39650
+ } else if (def.type === "array" && "element" in def) {
39651
+ current = def.element;
39652
+ } else {
39653
+ return;
39654
+ }
39655
+ }
39656
+ return unwrap(current);
39657
+ }
39658
+ function describeInput(value) {
39659
+ if (value === null)
39660
+ return "null";
39661
+ if (Array.isArray(value))
39662
+ return "an array";
39663
+ switch (typeof value) {
39664
+ case "number":
39665
+ case "boolean":
39666
+ return String(value);
39667
+ case "string":
39668
+ return "a string";
39669
+ case "object":
39670
+ return "an object";
39671
+ default:
39672
+ return typeof value;
39673
+ }
39674
+ }
39675
+ function describeExpected(expected, schema) {
39676
+ switch (expected) {
39677
+ case "int":
39678
+ return "an integer";
39679
+ case "object": {
39680
+ const shape = shapeOf(schema);
39681
+ const keys = shape === undefined ? [] : Object.entries(shape).map(([key, field]) => `${key}${field.def.type === "optional" ? "?" : ""}`);
39682
+ return keys.length === 0 ? "an object" : `an object {${keys.join(", ")}}`;
39683
+ }
39684
+ case "array":
39685
+ return "an array";
39686
+ default:
39687
+ return `a ${expected}`;
39688
+ }
39689
+ }
39690
+ function pathText(path, cliTool) {
39691
+ const [head, ...rest] = path.map(String);
39692
+ if (cliTool === undefined || head === undefined)
39693
+ return path.map(String).join(".");
39694
+ let flag = fieldFlag(cliTool, head);
39695
+ let index = 0;
39696
+ for (;index < rest.length && /^\d+$/.test(rest[index]); index++) {
39697
+ flag += `[${rest[index]}]`;
39698
+ }
39699
+ const tail = rest.slice(index).map((segment) => /^\d+$/.test(segment) ? `[${segment}]` : `.${segment}`).join("").replace(/^\./, "");
39700
+ return tail === "" ? flag : `${flag} ${tail}`;
39701
+ }
39702
+ function formatZodIssues(issues, schema, tool) {
39703
+ const cliTool = isDispatchTool(tool) ? tool : undefined;
39704
+ const allowed = Object.keys(shapeOf(schema) ?? {}).join(", ");
39705
+ return issues.flatMap((issue) => {
39706
+ const path = pathText(issue.path, cliTool);
39707
+ switch (issue.code) {
39708
+ case "invalid_type":
39709
+ return issue.input === undefined ? [`${path} is required (${issue.expected})`] : [
39710
+ `${path} must be ${describeExpected(issue.expected, schemaAt(schema, issue.path))}, not ${describeInput(issue.input)}`
39711
+ ];
39712
+ case "unrecognized_keys": {
39713
+ if (cliTool !== undefined && issue.path.length === 0) {
39714
+ return issue.keys.map((key) => `unknown flag ${fieldFlag(cliTool, key)}`);
39715
+ }
39716
+ const here = Object.keys(shapeOf(schemaAt(schema, issue.path)) ?? {}).join(", ") || allowed;
39717
+ const where = path === "" ? "" : ` in ${path}`;
39718
+ return issue.keys.map((key) => `unknown field "${key}"${where}; allowed: ${here}`);
39719
+ }
39720
+ case "invalid_value":
39721
+ return [
39722
+ `${path} must be one of ${issue.values.map(String).join("|")}; got ${JSON.stringify(issue.input)}`
39723
+ ];
39724
+ case "too_big":
39725
+ if (issue.origin === "array" && Array.isArray(issue.input)) {
39726
+ return [`${path} has ${issue.input.length} items; the limit is ${issue.maximum}`];
39727
+ }
39728
+ return [`${path} ${issue.message}`];
39729
+ case "custom":
39730
+ return [issue.message];
39731
+ default:
39732
+ return [path === "" ? issue.message : `${path}: ${issue.message}`];
39733
+ }
39734
+ });
39735
+ }
39736
+
39609
39737
  // ../envoy-client/src/dispatch-execute.ts
39610
39738
  var triageAdviceShown = new Set;
39611
39739
  var nativeIssueKeyPattern = /^[A-Z][A-Z0-9]{1,9}-[0-9]+$/;
@@ -39625,6 +39753,7 @@ var issueFreeTools = {
39625
39753
  dispatch_open_asks: true,
39626
39754
  dispatch_answers: true,
39627
39755
  dispatch_whoami: true,
39756
+ dispatch_limits: true,
39628
39757
  dispatch_inbox: true,
39629
39758
  dispatch_architecture_sync: true
39630
39759
  };
@@ -40582,6 +40711,7 @@ function allowedAPIURL(value) {
40582
40711
  }
40583
40712
 
40584
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.`;
40585
40715
  var DELIVERY_CONTRACT = "Delivery is at-least-once, possibly out of order across topics; use id for dedupe and at for freshness.";
40586
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.";
40587
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>.";
@@ -40651,7 +40781,7 @@ var envoyToolSpecs = [
40651
40781
  },
40652
40782
  {
40653
40783
  name: "envoy_send",
40654
- 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.`,
40655
40785
  arguments: (schema) => ({
40656
40786
  session_id: schema.string().describe("Target session ID; find it with envoy_sessions or envoy_whoami."),
40657
40787
  ...messageArguments(schema),
@@ -40661,7 +40791,7 @@ var envoyToolSpecs = [
40661
40791
  },
40662
40792
  {
40663
40793
  name: "envoy_publish",
40664
- 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}`,
40665
40795
  arguments: (schema) => ({ topic: schema.string(), ...messageArguments(schema) }),
40666
40796
  operation: EnvoyToolOperation.publish
40667
40797
  },
@@ -40673,7 +40803,7 @@ var envoyToolSpecs = [
40673
40803
  },
40674
40804
  {
40675
40805
  name: "envoy_role_get",
40676
- 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}`,
40677
40807
  arguments: (schema) => ({ role: schema.string() }),
40678
40808
  operation: EnvoyToolOperation.getRole
40679
40809
  },
@@ -40685,7 +40815,7 @@ var envoyToolSpecs = [
40685
40815
  },
40686
40816
  {
40687
40817
  name: "envoy_sessions",
40688
- 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}`,
40689
40819
  arguments: (schema) => ({
40690
40820
  machine: schema.string().optional(),
40691
40821
  dir: schema.string().optional(),
@@ -40708,14 +40838,23 @@ function sendConfirmationText(result) {
40708
40838
  if (result.duplicate) {
40709
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`;
40710
40840
  }
40711
- 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)"}`;
40712
40844
  }
40713
40845
  function publishConfirmationText(result) {
40714
- const published = `published ${result.envelope.event_id}`;
40846
+ const sentences = [`published ${result.envelope.event_id}.`];
40715
40847
  if (result.kept === true) {
40716
- 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}.`);
40717
40852
  }
40718
- return result.holder === undefined ? published : `${published}; holder ${result.holder}`;
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);
40856
+ }
40857
+ return sentences.join(" ");
40719
40858
  }
40720
40859
  function sessionsOnMachine(sessions, machine) {
40721
40860
  if (machine === undefined || machine === "")
@@ -41041,7 +41180,7 @@ var import_nats2 = __toESM(require_mod4(), 1);
41041
41180
 
41042
41181
  // package.json
41043
41182
  var name = "@sjawhar/pi-envoy";
41044
- var version2 = "16.9.0";
41183
+ var version2 = "16.11.0";
41045
41184
  var package_default = {
41046
41185
  name,
41047
41186
  version: version2,
@@ -42159,22 +42298,18 @@ function handledAttempts(entries) {
42159
42298
  function typedInputReply(text, outcome) {
42160
42299
  const typed = /^\/\S+/.exec(text)?.[0];
42161
42300
  const command = typed ?? "This message";
42162
- let reply;
42163
42301
  if ("error" in outcome)
42164
- reply = `${command} was not run: ${outcome.error}`;
42165
- else if ("hostVersion" in outcome) {
42166
- if (typed !== undefined) {
42167
- reply = `${typed} was not run: this session's Oh My Pi ${outcome.hostVersion} cannot run commands sent from Dispatch; nothing was sent.`;
42168
- }
42169
- } else if (outcome.handled === "terminal-only") {
42170
- reply = `${command} runs only in the session's own terminal; nothing was sent.`;
42171
- } else if (outcome.handled === "unavailable") {
42172
- reply = `${command} was not run: this session's host cannot run typed input from Dispatch; nothing was sent.`;
42173
- } else if (outcome.output?.trim())
42174
- reply = outcome.output;
42175
- if (reply === undefined || reply.length <= DISPATCH_BODY_MAX)
42176
- return reply;
42177
- return `${reply.slice(0, DISPATCH_BODY_MAX - 1)}\u2026`;
42302
+ return `${command} was not run: ${outcome.error}`;
42303
+ if ("hostVersion" in outcome) {
42304
+ return typed === undefined ? undefined : `${typed} was not run: this session's Oh My Pi ${outcome.hostVersion} cannot run commands sent from Dispatch; nothing was sent.`;
42305
+ }
42306
+ if (outcome.handled === "terminal-only") {
42307
+ return `${command} runs only in the session's own terminal; nothing was sent.`;
42308
+ }
42309
+ if (outcome.handled === "unavailable") {
42310
+ return `${command} was not run: this session's host cannot run typed input from Dispatch; nothing was sent.`;
42311
+ }
42312
+ return outcome.output?.trim() ? outcome.output : undefined;
42178
42313
  }
42179
42314
 
42180
42315
  // src/envoy-session.ts
@@ -46743,6 +46878,7 @@ function liveSessionSettings(live) {
46743
46878
  var codec2 = import_nats2.StringCodec();
46744
46879
  var NATS_RETRY_INTERVAL_MS = 15000;
46745
46880
  var DELIVERY_PICTURES_TIMEOUT_MS = 20000;
46881
+ var WHOLE_BODY_TIMEOUT_MS = 1e4;
46746
46882
  var BTW_EVENTS_LIMIT = 1000;
46747
46883
  var REPLAYED_BTW_NOTE = "This BTW was asked while this session was not taking messages. It is shown for your information only: it runs no side turn and needs no answer. Dispatch shows whether it was answered.";
46748
46884
  var CAPABILITIES_WITHOUT_BTW = DELIVERY_CAPABILITIES.filter((capability) => capability !== "btw");
@@ -47040,6 +47176,14 @@ function envoyExtension(pi) {
47040
47176
  forgetInjectedUserTurns(previousSessionID);
47041
47177
  typedPictures.dropOtherSessions(sessionID);
47042
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
+ }
47043
47187
  }
47044
47188
  };
47045
47189
  let dispatchLedger;
@@ -47278,8 +47422,15 @@ function envoyExtension(pi) {
47278
47422
  return typedInputReply(turn.body, { error: messageFor(error) });
47279
47423
  }).then(async (reply) => {
47280
47424
  refreshAgentStreamSettings(sessionID);
47281
- if (reply !== undefined)
47425
+ if (reply === undefined)
47426
+ return;
47427
+ try {
47282
47428
  await postDispatchReply(delivery, { body: reply }, replySessionID);
47429
+ } catch (error) {
47430
+ if (!(error instanceof DispatchServiceError) || !error.fromDispatch)
47431
+ throw error;
47432
+ await postDispatchReply(delivery, { body: `Your command ran, and Dispatch refused its output: ${error.message}` }, replySessionID);
47433
+ }
47283
47434
  }).catch((error) => {
47284
47435
  logger3.warn("envoy: the reply to a person's typed input did not reach Dispatch", {
47285
47436
  attempt: delivery.attempt,
@@ -47318,7 +47469,7 @@ function envoyExtension(pi) {
47318
47469
  }
47319
47470
  };
47320
47471
  const deliver = async (topic, subject, raw, reply, receivedAt, relayed) => {
47321
- const rendered = renderInbound(raw, sessionID, subject);
47472
+ let rendered = renderInbound(raw, sessionID, subject);
47322
47473
  const directSubject = agentSubject(sessionID);
47323
47474
  if (expectsLaneReceipt({
47324
47475
  subject,
@@ -47374,6 +47525,12 @@ function envoyExtension(pi) {
47374
47525
  claim.settle();
47375
47526
  return;
47376
47527
  }
47528
+ if (rendered.cutItem !== undefined) {
47529
+ const dispatch = timedDispatchClient(WHOLE_BODY_TIMEOUT_MS);
47530
+ const body = dispatch === undefined ? undefined : await wholeCarriedBody(dispatch, rendered.cutItem, sessionID);
47531
+ if (body !== undefined)
47532
+ rendered = renderInbound(raw, sessionID, subject, body);
47533
+ }
47377
47534
  const envelope = rendered.envelope;
47378
47535
  if (envelope !== undefined)
47379
47536
  noteInbox(envelope);
@@ -48038,6 +48195,38 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
48038
48195
  closeIntentionally(subject);
48039
48196
  return false;
48040
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
+ };
48041
48230
  const registrationInput = (asking) => {
48042
48231
  const own = agentSubject(sessionID);
48043
48232
  const topics = [
@@ -48070,7 +48259,7 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
48070
48259
  return result;
48071
48260
  });
48072
48261
  };
48073
- const registerSession = () => sendRegistration(registrationState.refreshRegistration);
48262
+ const registerSession = () => trackRegistration(sessionID, sendRegistration(registrationState.refreshRegistration));
48074
48263
  const ensureHeartbeat = (context) => {
48075
48264
  if (heartbeatRegistered)
48076
48265
  return;
@@ -48078,6 +48267,7 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
48078
48267
  let stallNotified = false;
48079
48268
  let registrationFailed = false;
48080
48269
  let healing = false;
48270
+ let retryArmed = false;
48081
48271
  const noteStall = (detail) => {
48082
48272
  if (stallNotified)
48083
48273
  return;
@@ -48088,7 +48278,9 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
48088
48278
  });
48089
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");
48090
48280
  };
48091
- context.setInterval(() => {
48281
+ const tick = (fromRetry) => {
48282
+ if (shuttingDown)
48283
+ return;
48092
48284
  if (context.sessionManager.getSessionId() === "")
48093
48285
  return;
48094
48286
  unwritten.handBackWithdrawn();
@@ -48110,6 +48302,7 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
48110
48302
  registrationFailed = false;
48111
48303
  heartbeatOutageNotified = false;
48112
48304
  stallNotified = false;
48305
+ retryArmed = false;
48113
48306
  };
48114
48307
  reconcile(context, { heartbeat: true, afterOutage }).then(settled, (error) => {
48115
48308
  if (error instanceof InboundError)
@@ -48123,14 +48316,30 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
48123
48316
  registrationFailed = true;
48124
48317
  throw error instanceof RegistrationError ? error.cause : error;
48125
48318
  }).catch((error) => {
48319
+ const retryIn = fromRetry ? undefined : armRetry();
48126
48320
  if (heartbeatOutageNotified)
48127
48321
  return;
48128
48322
  heartbeatOutageNotified = true;
48129
- 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");
48130
48325
  }).finally(() => {
48131
48326
  healing = false;
48132
48327
  });
48133
- }, 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);
48134
48343
  heartbeatRegistered = true;
48135
48344
  };
48136
48345
  const recoverRegisteredInterests = async (handle) => {
@@ -48275,7 +48484,7 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
48275
48484
  handle.check();
48276
48485
  if (inboundFailure !== undefined && replay !== undefined)
48277
48486
  await replay.startCursors();
48278
- const registration = await sendRegistration(handle.register).then(() => {
48487
+ const registration = await trackRegistration(host, sendRegistration(handle.register)).then(() => {
48279
48488
  return;
48280
48489
  }, (error) => ({ error }));
48281
48490
  handle.check();
@@ -48542,9 +48751,9 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
48542
48751
  closeStore(askgateOwner.store);
48543
48752
  }
48544
48753
  const deadline = Promise.withResolvers();
48545
- const timer = setTimeout(deadline.resolve, 1000);
48754
+ const timer = setTimeout(deadline.resolve, SHUTDOWN_DEADLINE_MS);
48546
48755
  try {
48547
- const deregistration = sessionID === "" || active === undefined ? Promise.resolve() : registrationState.deregister(sessionID).catch(() => {
48756
+ const deregistration = deregisterSession(sessionID, SHUTDOWN_SETTLE_MS).catch(() => {
48548
48757
  return;
48549
48758
  });
48550
48759
  const draining = connection?.drain().catch(() => {
@@ -48947,6 +49156,7 @@ Kept (they last while this session holds role ${registrationState.heldRole()}):
48947
49156
  return toolSuccess(sendConfirmationText(result), {
48948
49157
  event_id: result.envelope.event_id,
48949
49158
  recipient: result.recipient,
49159
+ recipient_state: result.recipientState,
48950
49160
  confirmed: result.confirmed
48951
49161
  });
48952
49162
  }
@@ -48967,6 +49177,8 @@ Not delivered: that holder is the session this subagent sends as, and the listen
48967
49177
  event_id: result.envelope.event_id,
48968
49178
  topic,
48969
49179
  ...result.holder === undefined ? {} : { holder: result.holder },
49180
+ ...result.holderState === undefined ? {} : { holder_state: result.holderState },
49181
+ ...result.unresponsive.length === 0 ? {} : { unresponsive: result.unresponsive },
48970
49182
  ...result.kept === undefined ? {} : { kept: result.kept },
48971
49183
  ...result.keptReason === undefined ? {} : { kept_reason: result.keptReason },
48972
49184
  ...undelivered ? { undelivered_echo: true } : {}
@@ -48997,7 +49209,8 @@ Not delivered: that holder is the session this subagent sends as, and the listen
48997
49209
  }
48998
49210
  case EnvoyToolOperation.getRole: {
48999
49211
  const role = await client.getRole(stringFor(parameters, "role"));
49000
- 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);
49001
49214
  }
49002
49215
  case EnvoyToolOperation.whoami: {
49003
49216
  const inSubagent = await isSubagent(context);
@@ -49021,10 +49234,15 @@ Not delivered: that holder is the session this subagent sends as, and the listen
49021
49234
  const machine = optionalStringFor(parameters, "machine");
49022
49235
  const directory = optionalStringFor(parameters, "dir");
49023
49236
  const title = optionalStringFor(parameters, "title");
49024
- const sessions = await client.listSessions({ directory, title });
49237
+ const sessions = await client.listSessions({
49238
+ directory,
49239
+ title,
49240
+ include: "unresponsive"
49241
+ });
49025
49242
  const result = sessionsOnMachine(sessions, machine);
49026
49243
  return toolSuccess(JSON.stringify(result, null, 2), {
49027
49244
  count: result.length,
49245
+ unresponsive: result.filter((session) => session.state === "unresponsive").length,
49028
49246
  machine,
49029
49247
  dir: directory,
49030
49248
  title