@sjawhar/pi-envoy 16.0.0 → 16.2.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
@@ -30033,7 +30033,12 @@ function documentOwnerValidation(requireArtifact, alwaysRequireArtifact = false)
30033
30033
  message: alwaysRequireArtifact ? "Exactly one of issue and project is required; artifact or ref must name the document." : "Exactly one of issue and project is required; with project, artifact names the document."
30034
30034
  };
30035
30035
  }
30036
- var ARTIFACT_OWNER_AND_SOURCE_RULE = "Exactly one of path or content is required. Exactly one of issue and project is required; with project, artifact names the document.";
30036
+ var ARTIFACT_SOURCE_RULE = "Exactly one of path or content is required.";
30037
+ var ARTIFACT_OWNER_AND_SOURCE_RULE = `${ARTIFACT_SOURCE_RULE} Exactly one of issue and project is required; with project, artifact names the document.`;
30038
+ function brokenParts(parts) {
30039
+ const broken = parts.filter(([kept]) => !kept).map(([, message]) => message);
30040
+ return broken.length === 0 ? undefined : broken.join(" ");
30041
+ }
30037
30042
  var CONTENT_IS_MARKDOWN = "content is stored as a Markdown document, which rewrites other text (a JSONL file's lines come back joined into one paragraph)";
30038
30043
  var PATH_KEEPS_BYTES = "path (--path <file>), which stores a file whose path does not end in .md or .markdown as its bytes, unchanged";
30039
30044
  var ARTIFACT_CONTENT_NAME_RULE = `${CONTENT_IS_MARKDOWN}, so with content the name ends in .md or .markdown or has no extension; upload any other file (.jsonl, .tsv, .json, .txt) with ${PATH_KEEPS_BYTES}.`;
@@ -30042,9 +30047,15 @@ var MARKDOWN_EXTENSION = /^(md|markdown)$/i;
30042
30047
  var artifactOwner = documentOwnerValidation(false);
30043
30048
  function artifactProblem(value) {
30044
30049
  const input = value;
30045
- if (!artifactOwner.check(value) || typeof input.path === "string" === (typeof input.content === "string")) {
30046
- return ARTIFACT_OWNER_AND_SOURCE_RULE;
30047
- }
30050
+ const ownerOrSourceProblem = brokenParts([
30051
+ [artifactOwner.check(value), artifactOwner.message],
30052
+ [
30053
+ typeof input.path === "string" !== (typeof input.content === "string"),
30054
+ ARTIFACT_SOURCE_RULE
30055
+ ]
30056
+ ]);
30057
+ if (ownerOrSourceProblem !== undefined)
30058
+ return ownerOrSourceProblem;
30048
30059
  if (typeof input.content !== "string" || typeof input.name !== "string")
30049
30060
  return;
30050
30061
  const extension = NAME_EXTENSION.exec(input.name.trim())?.[1];
@@ -30053,27 +30064,40 @@ function artifactProblem(value) {
30053
30064
  return `${CONTENT_IS_MARKDOWN}, and ${JSON.stringify(input.name)} is not a Markdown name. Upload the file under the same name with ${PATH_KEEPS_BYTES}; content takes a name ending in .md or .markdown or with no extension.`;
30054
30065
  }
30055
30066
  var documentEditOwner = documentOwnerValidation(true);
30067
+ var PRECONDITION_RULE = "A precondition selects exactly one of document or blocks.";
30068
+ function preconditionKept(value) {
30069
+ const input = value;
30070
+ if (input.precondition === undefined)
30071
+ return true;
30072
+ if (typeof input.precondition !== "object" || input.precondition === null)
30073
+ return false;
30074
+ const precondition = input.precondition;
30075
+ return typeof precondition.document === "string" !== Array.isArray(precondition.blocks);
30076
+ }
30077
+ function documentEditProblem(value) {
30078
+ return brokenParts([
30079
+ [documentEditOwner.check(value), documentEditOwner.message],
30080
+ [preconditionKept(value), PRECONDITION_RULE]
30081
+ ]);
30082
+ }
30056
30083
  var documentEditValidation = {
30057
- check: (value) => {
30058
- if (!documentEditOwner.check(value))
30059
- return false;
30060
- const input = value;
30061
- if (input.precondition === undefined)
30062
- return true;
30063
- if (typeof input.precondition !== "object" || input.precondition === null)
30064
- return false;
30065
- const precondition = input.precondition;
30066
- return typeof precondition.document === "string" !== Array.isArray(precondition.blocks);
30067
- },
30068
- message: `${documentEditOwner.message} A precondition selects exactly one of document or blocks.`
30084
+ check: (value) => documentEditProblem(value) === undefined,
30085
+ message: `${documentEditOwner.message} ${PRECONDITION_RULE}`,
30086
+ refusal: (value) => documentEditProblem(value) ?? `${documentEditOwner.message} ${PRECONDITION_RULE}`
30069
30087
  };
30070
30088
  var commentOwner = documentOwnerValidation(true);
30089
+ var COMMENT_TURN_RULE = "turn requires reply_to_ask: turn says who holds an open ask's thread after the reply. Pass reply_to_ask with the open ask's id, or drop turn.";
30090
+ function commentProblem(value) {
30091
+ const input = value;
30092
+ return brokenParts([
30093
+ [commentOwner.check(value), commentOwner.message],
30094
+ [input.turn === undefined || typeof input.reply_to_ask === "string", COMMENT_TURN_RULE]
30095
+ ]);
30096
+ }
30071
30097
  var commentValidation = {
30072
- check: (value) => {
30073
- const input = value;
30074
- return commentOwner.check(value) && (input.turn === undefined || typeof input.reply_to_ask === "string");
30075
- },
30076
- message: `${commentOwner.message} turn requires reply_to_ask.`
30098
+ check: (value) => commentProblem(value) === undefined,
30099
+ message: `${commentOwner.message} ${COMMENT_TURN_RULE}`,
30100
+ refusal: (value) => commentProblem(value) ?? `${commentOwner.message} ${COMMENT_TURN_RULE}`
30077
30101
  };
30078
30102
  var ISSUE_UPDATE_FIELDS_RULE = "Issue update requires at least one field besides issue: status, title, labels, priority, external_links, route, parent, blocked_by, components, repo, before, or after.";
30079
30103
  var ISSUE_UPDATE_DONE_RULE = "status done requires reason, a non-empty note saying why the issue is closing, posted on the issue before it closes because a closed issue refuses messages, comments, and artifacts";
@@ -30100,14 +30124,20 @@ var messageValidation = {
30100
30124
  message: "issue is required unless in_reply_to names a message delivered to this session, which is the one message with no issue."
30101
30125
  };
30102
30126
  var readOwner = documentOwnerValidation(false);
30127
+ var READ_OWNER_RULE = "Exactly one of issue and project is required; project alone lists its documents, and with artifact names one.";
30128
+ var READ_MESSAGE_RULE = "message stands alone: it names the conversation, so name no issue, project, artifact, or ref with it.";
30129
+ function readProblem(value) {
30130
+ const input = value;
30131
+ if (typeof input.message !== "string") {
30132
+ return readOwner.check(value) ? undefined : READ_OWNER_RULE;
30133
+ }
30134
+ const alone = input.issue === undefined && input.project === undefined && input.artifact === undefined && input.ref === undefined;
30135
+ return alone ? undefined : READ_MESSAGE_RULE;
30136
+ }
30103
30137
  var readValidation = {
30104
- check: (value) => {
30105
- const input = value;
30106
- if (typeof input.message !== "string")
30107
- return readOwner.check(value);
30108
- return input.issue === undefined && input.project === undefined && input.artifact === undefined && input.ref === undefined;
30109
- },
30110
- message: "Exactly one of issue and project is required; project alone lists its documents, and with artifact names one. " + "message stands alone: it names the conversation, so name no issue, project, artifact, or ref with it."
30138
+ check: (value) => readProblem(value) === undefined,
30139
+ message: `${READ_OWNER_RULE} ${READ_MESSAGE_RULE}`,
30140
+ refusal: (value) => readProblem(value) ?? `${READ_OWNER_RULE} ${READ_MESSAGE_RULE}`
30111
30141
  };
30112
30142
  var ISSUE_COMPONENTS_MODES = ["inherit", "explicit", "none"];
30113
30143
  function componentsArgument(z) {
@@ -30445,13 +30475,13 @@ var dispatchToolSpecs = [
30445
30475
  {
30446
30476
  name: "dispatch_doc_read",
30447
30477
  example: { issue: "DSP-1" },
30448
- description: "Read a live document or a named document version, or the text of an uploaded file at its latest or named version. " + "Do not use it for issue status, asks, or events; " + "use dispatch read instead. Supply ref, issue, or project plus artifact; issue plus an omitted artifact reads the primary document. " + "A live read returns its document token for an optional dispatch doc-edit precondition. With blocks it lists the live document's blocks instead of its markdown, in document order: each block's id, type, token, anchored comments and asks, and opening words, and under a table each row by the index delete_row takes and each cell by its row and the column delete_column takes; block ids, block tokens and those indexes are what dispatch doc-edit takes. " + "After the markdown it prints every open thread anchored on the document in full: an open ask with its id and question and each reply's author, time and text, and a comment thread with its root's id, author, time, quote and text and each reply's author, time and text, in order; a resolved thread, and an ask that is answered or resolved, is not printed. " + "A picture (an uploaded PNG, JPEG, GIF or WebP of at most 3,750,000 bytes, 5 MB once base64-encoded) comes back as an image you see, with its name, type, size and version, every time you ask, including one a read already showed this session; " + "any other file that is not UTF-8 text is described, with the route that serves its bytes. " + OWNER_REFERENCE,
30478
+ description: "Read a live document or a named document version, or the text of an uploaded file at its latest or named version. " + "Do not use it for issue status, asks, or events; " + "use dispatch read instead. Supply ref, issue, or project plus artifact; issue plus an omitted artifact reads the primary document. " + "A live read returns its document token for an optional dispatch doc-edit precondition. With blocks it lists the live document's blocks instead of its markdown, in document order: each block's id, type, token, anchored comments and asks, and opening words, a typed block's serves and needs under it, and under a table each row by the index delete_row takes and each cell by its row and the column delete_column takes; block ids, block tokens and those indexes are what dispatch doc-edit takes. " + "After the markdown it prints every open thread anchored on the document in full: an open ask with its id and question and each reply's author, time and text, and a comment thread with its root's id, author, time, quote and text and each reply's author, time and text, in order; a resolved thread, and an ask that is answered or resolved, is not printed. " + "A picture (an uploaded PNG, JPEG, GIF or WebP of at most 3,750,000 bytes, 5 MB once base64-encoded) comes back as an image you see, with its name, type, size and version, every time you ask, including one a read already showed this session; " + "any other file that is not UTF-8 text is described, with the route that serves its bytes. " + OWNER_REFERENCE,
30449
30479
  arguments: (z) => ({
30450
30480
  issue: z.string().describe(ISSUE_REFERENCE).optional(),
30451
30481
  project: z.string().describe("Project key owning the document.").optional(),
30452
30482
  artifact: z.string().describe("Optional project document artifact id, slug, or filename; primary document by default for an issue.").optional(),
30453
30483
  version: z.number({ int: true, min: 1 }).describe("Optional version number.").optional(),
30454
- blocks: z.boolean().describe("List the live document's blocks, with each table's rows and cells, instead of its markdown; refused with a version, or for an uploaded file.").optional(),
30484
+ blocks: z.boolean().describe("List the live document's blocks, with a typed block's serves and needs and each table's rows and cells, instead of its markdown; refused with a version, or for an uploaded file.").optional(),
30455
30485
  ref: z.string().describe("Optional dispatch:// document reference; a picture in a conversation on the Agents page is dispatch://agent/<session id>/artifact/<slug>@vN.").optional()
30456
30486
  }),
30457
30487
  validation: documentOwnerValidation(true)
@@ -30459,15 +30489,60 @@ var dispatchToolSpecs = [
30459
30489
  {
30460
30490
  name: "dispatch_request_approval",
30461
30491
  example: { issue: "DSP-1", summary: "A live sync replaces the nightly export." },
30462
- description: "Ask a human to approve a document at its current version. Before calling, have a fresh read-only reader check the spec against the code and the human's words, then resolve every finding; a Legion architect runs `plan-gap-analyst` and `plan-reviewer`. Opens an approval ask (Approve / " + "Request changes) in the human's Inbox whose question names the document and version, " + "followed by the summary; the answer pins a review to that version and arrives as " + "artifact.approved or artifact.changes_requested. An open request follows the document: a " + "later version moves it to that version and leaves it waiting on you, as a human's reply in " + "its thread does. Only the first move since the request was opened or handed back sends an " + "event, and never to the session whose version made it; dispatch doc-read shows whom it " + "waits on. Once the revision is complete and " + HUMAN_AGREED_TO_DOCUMENT + ", call this again to hand that same Inbox row back. The request carries nothing new. A " + "call while it already waits on the human hands nothing back: the same summary changes " + "nothing, and a different one is refused, since it would rewrite the card the human is " + "reading. Approve and Request changes each close the request, so the next call opens a new " + "one. Call it once per revision, when the revision is complete, never after each edit. An " + "approval goes stale when the document changes outside its decision blocks after it, until " + "a later version's text is exactly the approved version's again, as when an accidental " + "edit is undone exactly, and no decision block in it was decided since: that version " + "carries the approval and the document reads approved at it, so nothing is requested for " + "it. When the document does not read approved, request approval again once that revision " + "is complete and " + HUMAN_AGREED_TO_DOCUMENT + ", with a one-sentence summary naming what changed since the earlier approval: the card " + "names that approval (version, date, reviewer) and its Show diff control carries the detail. " + "A human's own answer to a decision block carries the approval to the version it writes when " + "that answer is the whole change since the approved version, so nothing is requested for " + "it. A new version of a Legion root spec closes its armed design gate until a human " + "approves it; a carried approval reopens it too. " + "Refused, with nothing sent, while the document holds an open decision block, even when a " + "human asked for approval: the refusal names each block; ask the human to answer or waive " + "it first. " + OWNER_REFERENCE,
30492
+ description: "Ask a human to approve a document at its current version. Before calling, have a fresh read-only reader check the spec against the code and the human's words, then resolve every finding; a Legion architect runs `plan-gap-analyst` and `plan-reviewer`. Opens an approval ask (Approve / " + "Request changes) in the human's Inbox whose question names the document and version, " + "followed by the summary; the answer pins a review to that version and arrives as " + "artifact.approved or artifact.changes_requested. An open request follows the document: a " + "later version moves it to that version and leaves it waiting on you, as a human's reply in " + "its thread does. Only the first move since the request was opened or handed back sends an " + "event, and never to the session whose version made it; dispatch doc-read shows whom it " + "waits on. Once the revision is complete and " + HUMAN_AGREED_TO_DOCUMENT + ", call this again to hand that same Inbox row back. The request carries nothing new. A " + "call while it already waits on the human hands nothing back: the same summary changes " + "nothing, and a different one is refused, since it would rewrite the card the human is " + "reading. Approve and Request changes each close the request, so the next call opens a new " + "one. Call it once per revision, when the revision is complete, never after each edit. An " + "approval goes stale when the document changes outside its decision blocks after it, until " + "a later version's text is exactly the approved version's again, as when an accidental " + "edit is undone exactly, and no decision block in it was decided since: that version " + "carries the approval and the document reads approved at it, so nothing is requested for " + "it. When the document does not read approved, request approval again once that revision " + "is complete and " + HUMAN_AGREED_TO_DOCUMENT + ", with a one-sentence summary naming what changed since the earlier approval: the card " + "names that approval (version, date, reviewer) and its Show diff control carries the detail. " + "A human's own answer to a decision block carries the approval to the version it writes when " + "that answer is the whole change since the approved version, so nothing is requested for " + "it. A new version of a Legion root spec closes its armed design gate until a human " + "approves it; a carried approval reopens it too. " + "Refused, with nothing sent, while the document holds an open decision block, even when a " + "human asked for approval: the refusal names each block; ask the human to answer or waive " + "it first. " + "Refused 409 PLAN_APPROVED_BY_REVIEW on an issue's plan, which its plan review approves " + "(dispatch plan-approve), never a person. " + "On an issue's spec the answer ends with a `Coverage of <name>:` line naming each requirement " + "the spec marks that no check serves, in any document of the issue or of its descendants, or saying " + "the spec marks no requirements; a spec every requirement of which has a check gets no such line. It never " + "names a missing plan task, and a gap refuses nothing. " + OWNER_REFERENCE,
30463
30493
  arguments: (z) => ({
30464
30494
  issue: z.string().describe(ISSUE_REFERENCE).optional(),
30465
30495
  project: z.string().describe("Project key owning the document.").optional(),
30466
30496
  artifact: z.string().describe("Project document artifact id, slug, or filename; primary document by default for an issue.").optional(),
30467
- summary: z.string({ min: 1 }).describe(`What the human is approving, in one to three sentences, and nothing else: no commentary on itself or the conversation, and no question; after an earlier approval, one sentence naming what changed since it, since the card shows that approval and a diff. A Legion architect adds one last sentence with its two spec reviews' results. Request approval only once ${HUMAN_AGREED_TO_DOCUMENT}.`)
30497
+ summary: z.string({ min: 1 }).describe(`What the human is approving, in one to three sentences, and nothing else: no commentary on itself or the conversation, and no question; after an earlier approval, one sentence naming what changed since it, since the card shows that approval and a diff. A Legion architect adds one last sentence with its two spec reviews' results. Request approval only once ${HUMAN_AGREED_TO_DOCUMENT}.`),
30498
+ include_verification: z.boolean().describe("Ask for the issue's Verification document in the same request, beside this one: one Inbox card names both at their current versions, and the answer records the human's review on each. 409 NO_VERIFICATION_DOCUMENT when the issue has no verification.md. Without it the request names this document alone and records nothing on the Verification document.").optional()
30468
30499
  }),
30469
30500
  validation: documentOwnerValidation(true)
30470
30501
  },
30502
+ {
30503
+ name: "dispatch_plan_approve",
30504
+ example: { issue: "DSP-1", version: 2 },
30505
+ description: "Record the plan review's approval of an issue's plan at the version it reviewed. A plan is " + "approved by that review, never by a person: dispatch request-approval on a plan is refused " + "409 PLAN_APPROVED_BY_REVIEW, so no plan approval ever reaches a human's Inbox. The approval " + "is pinned to the version named, so a later plan version makes it stale and the review runs " + "again. Refused 409 NOT_PLAN_DOCUMENT on any other document, the issue's spec included, and " + "400 INVALID_REVIEW for a version the plan does not have. " + ISSUE_REFERENCE,
30506
+ arguments: (z) => ({
30507
+ issue: z.string().describe(ISSUE_REFERENCE),
30508
+ artifact: z.string().describe("Plan document artifact id, slug, or filename; the issue's plan.md by default.").optional(),
30509
+ version: z.number({ int: true, min: 1 }).describe("The plan version the review read and approved.")
30510
+ })
30511
+ },
30512
+ {
30513
+ name: "dispatch_result",
30514
+ example: {
30515
+ issue: "DSP-1",
30516
+ check: "k1",
30517
+ role: "implementer",
30518
+ verdict: "pass",
30519
+ commit: "1111111111111111111111111111111111111111"
30520
+ },
30521
+ description: "Record one result of one check of an issue's Verification document, and print the " + "pull-request body line it implies. The check is named by its block id, or, when two " + "Verification documents in reach share that id, by its canonical reference " + "(dispatch://KEY/artifact/verification-md#b-<id>); 409 CHECK_AMBIGUOUS names them, and an " + "id no Verification document of the issue or of an issue above it holds is 400 " + "UNKNOWN_CHECK. A pass counting any failed, skipped or excluded case contradicts itself " + "and is 400 RESULT_CONTRADICTS. The result is recorded against the check's own issue, so " + "a child's run of a parent's check appears under that check. A closed issue takes a " + "result only for a check whose when is after_merge or default_branch \u2014 the production " + "check after the merge \u2014 and refuses every other one with 409 ISSUE_CLOSED, as it refuses " + "every other write. Write the printed line into the pull-request body unchanged: it is " + "the one grammar every writer uses, and it carries no link to Dispatch. " + ISSUE_REFERENCE,
30522
+ arguments: (z) => ({
30523
+ issue: z.string().describe(ISSUE_REFERENCE),
30524
+ check: z.string().describe("The check block's id, or its canonical reference dispatch://KEY/artifact/verification-md#b-<id> when the id is not unique among the issue's Verification document and those of the issues above it."),
30525
+ role: z.string({ max: 32 }).describe("Who ran it: implementer, tester, reviewer. At most 32 characters of a-z and -, printed in the pull-request line."),
30526
+ verdict: z.enum(["pass", "fail"]).describe("Whether the check passed."),
30527
+ commit: z.string().describe("The 40-character lowercase hex commit the check ran at."),
30528
+ surface: z.string().describe("Where a person reaches the change.").optional(),
30529
+ run: z.string().describe("The command that proved it.").optional(),
30530
+ observed: z.string().describe("What the command printed.").optional(),
30531
+ negative_control: z.string().describe("The deliberately broken input and the refusal seen.").optional(),
30532
+ failed: z.number({ int: true, min: 0 }).describe("Cases the run failed; 0 by default.").optional(),
30533
+ skipped: z.number({ int: true, min: 0 }).describe("Cases the run skipped; 0 by default.").optional(),
30534
+ excluded: z.number({ int: true, min: 0 }).describe("Cases the run excluded; 0 by default.").optional(),
30535
+ screenshots: z.array(z.string()).describe("dispatch:// references to image documents of this issue or of the check's issue.").optional()
30536
+ })
30537
+ },
30538
+ {
30539
+ name: "dispatch_results",
30540
+ example: { issue: "DSP-1" },
30541
+ description: "Print each check of an issue's Verification document with its latest result and whether " + "that result is current. A result is current when it ran at the commit the work stands at " + "\u2014 the head of an open pull request of the check's issue, the final head of a merged one, " + "or, for an after_merge or default_branch check, a commit on the repository's default " + "branch \u2014 and the check's words have not changed since; older otherwise, and unknown when " + "Dispatch cannot read the repository. A push that moves the pull request's head makes a " + "result older with no write of anyone's: record it again at the new head. " + ISSUE_REFERENCE,
30542
+ arguments: (z) => ({
30543
+ issue: z.string().describe(ISSUE_REFERENCE)
30544
+ })
30545
+ },
30471
30546
  {
30472
30547
  name: "dispatch_artifact",
30473
30548
  example: { issue: "DSP-1", name: "design.md", content: `# Design
@@ -30490,7 +30565,7 @@ var dispatchToolSpecs = [
30490
30565
  {
30491
30566
  name: "dispatch_read",
30492
30567
  example: { issue: "DSP-1" },
30493
- description: "Read an issue or document summary, targeted ask, or targeted comment reply chain, or the conversation " + "a message belongs to. Do not use it for document contents; use dispatch doc-read instead. Supply ref, issue, " + "issue plus artifact (one of its documents), project plus artifact, or project alone, which lists the project's documents on no issue and nothing more; or message alone, which reads a human's direct message to this session and every " + "reply to it (they belong to no issue). A document summary names its issue, reference, versions and approval. " + "An issue read lists every document, picture and file the issue holds under `Documents:`, each by slug, filename and kind. " + "An anchored comment or ask also says where its quote sits, as `Position:`: the block's path from the top, " + "and in a table the row (0 is the header), the cells before the anchored one, and the column's header; " + "`Position: unavailable (<code>)` when Dispatch could not read the document: `DOC_SERVICE_UNAVAILABLE` " + "(try again shortly), `DOC_SCHEMA` (the document needs repair), `DOCUMENT_UNLOADABLE` (the document " + "needs a rebuild) or `INTERNAL`. " + "An issue read carries a `Progress:` line, `tasks 3/7, children 2/5`: its spec's task-list items " + "(`- [ ]` / `- [x]`, nested lists included) and its direct children, each done of total and each only " + "when it has any (`Progress: none` otherwise). " + `An issue read, and its dispatch://KEY/log, lists the issue's last ${DEFAULT_ISSUE_READ_EVENTS} events, oldest first; ` + "--events N lists the last N, and --all-events every one. " + "Every read ends with `Referenced by:` (what cites or hangs off this node, each with its dispatch:// address, " + "an excerpt, and when) and `Links:` (what it cites), so tracing provenance is one call. " + "A block read prints `Block:`, `Document:`, `Changed in version:` and `Text:`, then those two sections; a pinned one adds " + "the block's text at that version and whether it is unchanged, changed or removed since, and an absent block, unpinned, " + "reads `No block <id> in <document>.` " + "The pictures the shown messages, asks and comments embed come back as images you see, newest first, at most 8 " + "and 10 MiB of them per read, each a PNG, JPEG, GIF or WebP of at most 3,750,000 bytes (5 MB of base64); a `Pictures:` section names each " + "one shown, in order, and the rest by reference, for dispatch doc-read. A picture this session was already shown is named, not sent again " + "(every request carries the session's history, and the provider refuses one over 32 MB); dispatch doc-read shows it again. " + OWNER_REFERENCE,
30568
+ description: "Read an issue or document summary, targeted ask, or targeted comment reply chain, or the conversation " + "a message belongs to. Do not use it for document contents; use dispatch doc-read instead. Supply ref, issue, " + "issue plus artifact (one of its documents), project plus artifact, or project alone, which lists the project's documents on no issue and nothing more; or message alone, which reads a human's direct message to this session and every " + "reply to it (they belong to no issue). A document summary names its issue, reference, versions and approval. " + "An issue read lists every document, picture and file the issue holds under `Documents:`, each by slug, filename and kind. " + "An anchored comment or ask also says where its quote sits, as `Position:`: the block's path from the top, " + "and in a table the row (0 is the header), the cells before the anchored one, and the column's header; " + "`Position: unavailable (<code>)` when Dispatch could not read the document: `DOC_SERVICE_UNAVAILABLE` " + "(try again shortly), `DOC_SCHEMA` (the document needs repair), `DOCUMENT_UNLOADABLE` (the document " + "needs a rebuild) or `INTERNAL`. " + "An issue read carries a `Progress:` line, `tasks 3/7, children 2/5`: its spec's task-list items " + "(`- [ ]` / `- [x]`, nested lists included) and its direct children, each done of total and each only " + "when it has any (`Progress: none` otherwise). " + "An issue whose spec marks requirements carries one `Coverage:` line per gap, `Coverage: R3 has no check` or " + "`Coverage: R3 has no plan task` (the second only once the issue has a plan document), counting the `check` and " + "`plan_task` blocks of every document of the issue and of its descendants; a spec that marks none reads " + "`Coverage: the spec marks no requirements`. Nothing is refused for a gap. " + `An issue read, and its dispatch://KEY/log, lists the issue's last ${DEFAULT_ISSUE_READ_EVENTS} events, oldest first; ` + "--events N lists the last N, and --all-events every one. " + "Every read ends with `Referenced by:` (what cites or hangs off this node, each with its dispatch:// address, " + "an excerpt, and when) and `Links:` (what it cites), so tracing provenance is one call. " + "A block read prints `Block:`, `Type:` for a block of a document, `Document:`, every attribute a typed block carries " + "(a `check`'s serves, surface, run, when and negative_control; a `plan_task`'s serves and needs), `Changed in version:` " + "and `Text:`, then those two sections; a pinned one adds " + "the block's text at that version and whether it is unchanged, changed or removed since, and an absent block, unpinned, " + "reads `No block <id> in <document>.` " + "The pictures the shown messages, asks and comments embed come back as images you see, newest first, at most 8 " + "and 10 MiB of them per read, each a PNG, JPEG, GIF or WebP of at most 3,750,000 bytes (5 MB of base64); a `Pictures:` section names each " + "one shown, in order, and the rest by reference, for dispatch doc-read. A picture this session was already shown is named, not sent again " + "(every request carries the session's history, and the provider refuses one over 32 MB); dispatch doc-read shows it again. " + OWNER_REFERENCE,
30494
30569
  arguments: (z) => ({
30495
30570
  issue: z.string().describe(ISSUE_REFERENCE).optional(),
30496
30571
  project: z.string().describe("Project key owning the document.").optional(),
@@ -30879,6 +30954,7 @@ var EnvelopeSchema = object({
30879
30954
  dedupe_key: string2().min(1),
30880
30955
  issued_at: number2().int(),
30881
30956
  expires_at: number2().int().optional(),
30957
+ kept_at: number2().int().optional(),
30882
30958
  payload_summary: string2().min(1),
30883
30959
  payload: string2().optional(),
30884
30960
  payload_ref: string2().optional(),
@@ -32552,6 +32628,15 @@ class DispatchClient {
32552
32628
  const answer = await this.#jsonAnswer("POST", ["api", "v1", "artifacts", artifactID, "approval-requests"], input);
32553
32629
  return { ...answer.payload, recorded: answer.status === 201 };
32554
32630
  }
32631
+ async planApprove(artifactID, input) {
32632
+ return this.#json("POST", ["api", "v1", "artifacts", artifactID, "plan-reviews"], input);
32633
+ }
32634
+ async recordResult(issue, input) {
32635
+ return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "results"], input);
32636
+ }
32637
+ async issueResults(issue) {
32638
+ return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue), "results"]);
32639
+ }
32555
32640
  async editAsk(id, input) {
32556
32641
  return this.#json("PATCH", ["api", "v1", "asks", id], input);
32557
32642
  }
@@ -32635,6 +32720,15 @@ class DispatchClient {
32635
32720
  async artifactBlocks(id) {
32636
32721
  return this.#json("GET", ["api", "v1", "artifacts", id, "blocks"]);
32637
32722
  }
32723
+ async issueArtifactBlocks(issue, slug) {
32724
+ return this.#json("GET", ["api", "v1", "issues", issue, "artifacts", slug, "blocks"]);
32725
+ }
32726
+ async projectArtifactBlocks(project, slug) {
32727
+ return this.#json("GET", ["api", "v1", "projects", project, "artifacts", slug, "blocks"]);
32728
+ }
32729
+ async issueCoverage(key) {
32730
+ return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(key), "coverage"]);
32731
+ }
32638
32732
  async commentBlocks(id) {
32639
32733
  return this.#json("GET", ["api", "v1", "comments", id, "blocks"]);
32640
32734
  }
@@ -33161,6 +33255,7 @@ var InboundEnvelopeSchema = object({
33161
33255
  dedupe_key: string2().optional(),
33162
33256
  issued_at: number2().int().optional(),
33163
33257
  expires_at: number2().int().optional(),
33258
+ kept_at: number2().int().optional(),
33164
33259
  payload_summary: string2().optional(),
33165
33260
  payload: string2().optional(),
33166
33261
  sender: InboundSenderSchema.optional(),
@@ -33838,6 +33933,7 @@ function renderInbound(raw, sessionID, subject) {
33838
33933
  from: senderLabel(envelope),
33839
33934
  at: inboundTimestamp(envelope.issued_at),
33840
33935
  id: envelope.event_id ?? "unknown",
33936
+ ...envelope.kept_at === undefined ? {} : { kept_at: inboundTimestamp(envelope.kept_at) },
33841
33937
  ...envelope.expires_at === undefined ? {} : { by: inboundTimestamp(envelope.expires_at) },
33842
33938
  ...envelope.urgency === undefined ? {} : { urgency: envelope.urgency },
33843
33939
  ...envelope.expects_reply === undefined ? {} : { expects_reply: envelope.expects_reply },
@@ -34600,6 +34696,10 @@ var EnvelopeResponseSchema = EnvelopeSchema.extend({
34600
34696
  holder: string2().optional(),
34601
34697
  duplicate: boolean2().optional()
34602
34698
  });
34699
+ var PublishResponseSchema = EnvelopeResponseSchema.extend({
34700
+ kept: boolean2().optional(),
34701
+ kept_reason: _enum2(["unclaimed", "holder_lapsed"]).optional()
34702
+ });
34603
34703
  var ReplayWireSchema = object({
34604
34704
  stream: object({
34605
34705
  id: string2().min(1).optional(),
@@ -34828,18 +34928,21 @@ function createEnvoyClient(config) {
34828
34928
  },
34829
34929
  publish: async (input) => {
34830
34930
  const idempotencyKey = input.idempotencyKey ?? crypto.randomUUID();
34831
- const response = EnvelopeResponseSchema.parse(JSON.parse(await post("/v1/messages/publish", {
34931
+ const response = PublishResponseSchema.parse(JSON.parse(await post("/v1/messages/publish", {
34832
34932
  source: input.source ?? "agent",
34833
34933
  ...sourceSession(input.sourceSessionID),
34834
34934
  topic: input.topic,
34835
34935
  message: input.message,
34836
34936
  ...input.payload === undefined ? {} : { payload: input.payload },
34837
34937
  idempotency_key: idempotencyKey,
34838
- ...messageMetadata(input)
34938
+ ...messageMetadata(input),
34939
+ ...input.keep === undefined ? {} : { keep: input.keep }
34839
34940
  })));
34840
34941
  return {
34841
34942
  envelope: response,
34842
- ...response.holder === undefined ? {} : { holder: response.holder }
34943
+ ...response.holder === undefined ? {} : { holder: response.holder },
34944
+ ...response.kept === undefined ? {} : { kept: response.kept },
34945
+ ...response.kept_reason === undefined ? {} : { keptReason: response.kept_reason }
34843
34946
  };
34844
34947
  },
34845
34948
  unregisterSession: async (input) => {
@@ -37959,7 +38062,7 @@ var envoyToolSpecs = [
37959
38062
  },
37960
38063
  {
37961
38064
  name: "envoy_publish",
37962
- 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 errs when its holder did not confirm it within the listener's window. 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}`,
38065
+ 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}`,
37963
38066
  arguments: (schema) => ({ topic: schema.string(), ...messageArguments(schema) }),
37964
38067
  operation: EnvoyToolOperation.publish
37965
38068
  },
@@ -38008,6 +38111,13 @@ function sendConfirmationText(result) {
38008
38111
  }
38009
38112
  return `sent ${result.envelope.event_id} to ${result.recipient}${result.confirmed ? "" : " (recipient unconfirmed by listener)"}`;
38010
38113
  }
38114
+ function publishConfirmationText(result) {
38115
+ const published = `published ${result.envelope.event_id}`;
38116
+ if (result.kept === true) {
38117
+ return `${published}; kept for the role: no session holds it yet, and the message waits for the session that claims it next`;
38118
+ }
38119
+ return result.holder === undefined ? published : `${published}; holder ${result.holder}`;
38120
+ }
38011
38121
  function sessionsOnMachine(sessions, machine) {
38012
38122
  if (machine === undefined || machine === "")
38013
38123
  return sessions;
@@ -38327,7 +38437,7 @@ var import_nats2 = __toESM(require_mod4(), 1);
38327
38437
 
38328
38438
  // package.json
38329
38439
  var name = "@sjawhar/pi-envoy";
38330
- var version2 = "16.0.0";
38440
+ var version2 = "16.2.0";
38331
38441
  var package_default = {
38332
38442
  name,
38333
38443
  version: version2,
@@ -38346,7 +38456,7 @@ var package_default = {
38346
38456
  },
38347
38457
  repository: {
38348
38458
  type: "git",
38349
- url: "https://github.com/sjawhar/legion"
38459
+ url: "https://github.com/cybermonklabs/legion"
38350
38460
  },
38351
38461
  files: [
38352
38462
  "dist",
@@ -44203,6 +44313,7 @@ function envoyExtension(pi) {
44203
44313
  };
44204
44314
  const passDeadlineMs = () => active?.settings.passDeadlineMs ?? MIN_PASS_DEADLINE_MS;
44205
44315
  const subscriptions = new Map;
44316
+ const confirming = new Map;
44206
44317
  const delivered = createDeliveryDedupe();
44207
44318
  let connection;
44208
44319
  let sessionDirectory2 = "";
@@ -44414,6 +44525,7 @@ function envoyExtension(pi) {
44414
44525
  return;
44415
44526
  if (status.type !== import_nats2.Events.Reconnect)
44416
44527
  continue;
44528
+ unanswered.delete(watched);
44417
44529
  renewRelayEpoch();
44418
44530
  triggerReplay();
44419
44531
  }
@@ -44768,8 +44880,8 @@ ${REPLAYED_BTW_NOTE}`, "inert", identity, claim);
44768
44880
  let shuttingDown = false;
44769
44881
  const intentionallyClosed = new Set;
44770
44882
  const awaitingRetry = new Set;
44771
- const SUBSCRIBE_FLUSH_TIMEOUT_MS = 1e4;
44772
- const unconfirmed = new Map;
44883
+ const SUBSCRIBE_FLUSH_TIMEOUT_MS = Number(process.env.ENVOY_SUBSCRIBE_FLUSH_TIMEOUT_MS ?? "") || 1e4;
44884
+ const unanswered = new Set;
44773
44885
  const closeIntentionally = (topic) => {
44774
44886
  const subscription = subscriptions.get(topic);
44775
44887
  if (subscription === undefined) {
@@ -44818,7 +44930,7 @@ ${REPLAYED_BTW_NOTE}`, "inert", identity, claim);
44818
44930
  awaitingRetry.add(topic);
44819
44931
  setTimeout(() => {
44820
44932
  awaitingRetry.delete(topic);
44821
- if (shuttingDown || subscriptions.has(topic) && !unconfirmed.has(topic))
44933
+ if (shuttingDown || subscriptions.has(topic))
44822
44934
  return;
44823
44935
  if (intentionallyClosed.delete(topic))
44824
44936
  return;
@@ -44839,52 +44951,81 @@ ${REPLAYED_BTW_NOTE}`, "inert", identity, claim);
44839
44951
  clearTimeout(timer);
44840
44952
  }
44841
44953
  };
44954
+ const BACKGROUND_CONFIRM_CAP_MS = 600000;
44955
+ const confirmSubscribed = async (connection, what) => {
44956
+ if (unanswered.has(connection))
44957
+ return;
44958
+ try {
44959
+ await within(connection.flush(), SUBSCRIBE_FLUSH_TIMEOUT_MS, `confirming ${what}`);
44960
+ } catch (error) {
44961
+ if (shuttingDown || connection.isClosed())
44962
+ throw error;
44963
+ unanswered.add(connection);
44964
+ confirmInBackground(connection, what);
44965
+ }
44966
+ };
44967
+ const confirmInBackground = async (connection, what) => {
44968
+ const until = Date.now() + BACKGROUND_CONFIRM_CAP_MS;
44969
+ try {
44970
+ while (!shuttingDown && !connection.isClosed() && Date.now() < until) {
44971
+ await new Promise((resolve) => setTimeout(resolve, RESUBSCRIBE_DELAY_MS));
44972
+ if (shuttingDown || connection.isClosed())
44973
+ return;
44974
+ try {
44975
+ await within(connection.flush(), SUBSCRIBE_FLUSH_TIMEOUT_MS, `confirming ${what}`);
44976
+ return;
44977
+ } catch {}
44978
+ }
44979
+ } finally {
44980
+ unanswered.delete(connection);
44981
+ }
44982
+ };
44842
44983
  const subscribe = async (topic, connect = ensureConnection) => {
44843
44984
  const subjects = expandSubscriptionTopics([topic]);
44985
+ const inFlight = subjects.flatMap((subject) => confirming.get(subject) ?? []);
44986
+ if (inFlight.length > 0)
44987
+ await Promise.allSettled(inFlight);
44844
44988
  const fresh = subjects.filter((candidate) => !subscriptions.has(candidate));
44845
- const confirming = subjects.filter((candidate) => !subscriptions.has(candidate) || unconfirmed.has(candidate));
44846
- if (confirming.length === 0)
44989
+ if (fresh.length === 0)
44847
44990
  return false;
44848
44991
  const activeConnection = await connect();
44849
- for (const subject of fresh) {
44850
- const subscription = activeConnection.subscribe(subject);
44851
- intentionallyClosed.delete(subject);
44852
- subscriptions.set(subject, subscription);
44853
- pump(subject, subscription);
44854
- }
44855
- const pending = confirming.flatMap((subject) => {
44856
- const subscription = subscriptions.get(subject);
44857
- return subscription === undefined ? [] : [[subject, subscription]];
44858
- });
44859
- for (const [subject, subscription] of pending)
44860
- unconfirmed.set(subject, subscription);
44861
- await within(activeConnection.flush(), SUBSCRIBE_FLUSH_TIMEOUT_MS, `confirming the subscription to ${topic}`);
44862
- for (const [subject, subscription] of pending) {
44863
- if (unconfirmed.get(subject) === subscription && subscriptions.get(subject) === subscription) {
44864
- unconfirmed.delete(subject);
44992
+ const opened = [];
44993
+ const closeOpened = () => {
44994
+ for (const [subject, subscription] of opened) {
44995
+ if (subscriptions.get(subject) === subscription)
44996
+ closeIntentionally(subject);
44865
44997
  }
44998
+ };
44999
+ try {
45000
+ for (const subject of fresh) {
45001
+ const subscription = activeConnection.subscribe(subject);
45002
+ intentionallyClosed.delete(subject);
45003
+ subscriptions.set(subject, subscription);
45004
+ opened.push([subject, subscription]);
45005
+ pump(subject, subscription);
45006
+ }
45007
+ } catch (error) {
45008
+ closeOpened();
45009
+ throw error;
44866
45010
  }
44867
- return true;
44868
- };
44869
- const confirmPending = async (connect = ensureConnection) => {
44870
- for (const [subject, subscription] of unconfirmed) {
44871
- if (subscriptions.get(subject) !== subscription)
44872
- unconfirmed.delete(subject);
44873
- }
44874
- const pending = [...unconfirmed];
44875
- if (pending.length === 0)
45011
+ const settled = confirmSubscribed(activeConnection, `the subscription to ${topic}`);
45012
+ const confirmation = settled.catch(() => {
44876
45013
  return;
44877
- const activeConnection = await connect();
44878
- await within(activeConnection.flush(), SUBSCRIBE_FLUSH_TIMEOUT_MS, `confirming the subscriptions to ${pending.map(([subject]) => subject).join(", ")}`);
44879
- for (const [subject, subscription] of pending) {
44880
- if (unconfirmed.get(subject) === subscription && subscriptions.get(subject) === subscription) {
44881
- unconfirmed.delete(subject);
45014
+ });
45015
+ for (const [subject] of opened)
45016
+ confirming.set(subject, confirmation);
45017
+ try {
45018
+ await settled;
45019
+ } catch (error) {
45020
+ closeOpened();
45021
+ throw error;
45022
+ } finally {
45023
+ for (const [subject] of opened) {
45024
+ if (confirming.get(subject) === confirmation)
45025
+ confirming.delete(subject);
44882
45026
  }
44883
45027
  }
44884
- };
44885
- const agentSubjectUnconfirmed = (session) => {
44886
- const own = agentSubject(session);
44887
- return subscriptions.has(own) && unconfirmed.has(own);
45028
+ return true;
44888
45029
  };
44889
45030
  const noteInbox = (envelope) => {
44890
45031
  inbox.unshift({
@@ -45027,6 +45168,14 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
45027
45168
  owner.subscription = subscription;
45028
45169
  owner.delivery.beginEpoch();
45029
45170
  pumpRelay(owner, subscription);
45171
+ try {
45172
+ await confirmSubscribed(connected, `the relay subscription for ${owner.sessionID}`);
45173
+ } catch (error) {
45174
+ if (owner.subscription === subscription)
45175
+ owner.subscription = undefined;
45176
+ subscription.unsubscribe();
45177
+ throw error;
45178
+ }
45030
45179
  };
45031
45180
  const openRelay = async (context, id, connect) => {
45032
45181
  if (replay === undefined)
@@ -45094,7 +45243,6 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
45094
45243
  });
45095
45244
  let agentStreamControl;
45096
45245
  let agentStreamControlSession = "";
45097
- let agentStreamControlConfirmed = false;
45098
45246
  let agentStreamCommandsRefreshedOnWatchAt = -Infinity;
45099
45247
  let agentStreamViewerAttached = false;
45100
45248
  const refreshAgentStreamCommands = (session) => {
@@ -45196,30 +45344,28 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
45196
45344
  }, RESUBSCRIBE_DELAY_MS);
45197
45345
  };
45198
45346
  const watchAgentStream = async (session, connect = ensureConnection) => {
45199
- let subscription = agentStreamControlSession === session ? agentStreamControl : undefined;
45200
- let connected;
45201
- if (subscription !== undefined) {
45202
- if (agentStreamControlConfirmed)
45203
- return;
45204
- connected = await connect();
45205
- } else {
45206
- agentStreamControl?.unsubscribe();
45207
- agentStreamControl = undefined;
45208
- if (agentStreamControlSession !== session) {
45209
- agentStream.reset();
45210
- agentStreamViewerAttached = false;
45211
- agentStreamCommandsRefreshedOnWatchAt = -Infinity;
45212
- }
45213
- agentStreamControlSession = session;
45214
- connected = await connect();
45215
- subscription = connected.subscribe(agentStreamControlSubject(session));
45216
- agentStreamControl = subscription;
45217
- agentStreamControlConfirmed = false;
45218
- pumpAgentStreamControl(subscription, session);
45219
- }
45220
- await within(connected.flush(), SUBSCRIBE_FLUSH_TIMEOUT_MS, `confirming the agent stream control subscription for ${session}`);
45221
- if (agentStreamControl === subscription)
45222
- agentStreamControlConfirmed = true;
45347
+ if (agentStreamControlSession === session && agentStreamControl !== undefined)
45348
+ return;
45349
+ agentStreamControl?.unsubscribe();
45350
+ agentStreamControl = undefined;
45351
+ if (agentStreamControlSession !== session) {
45352
+ agentStream.reset();
45353
+ agentStreamViewerAttached = false;
45354
+ agentStreamCommandsRefreshedOnWatchAt = -Infinity;
45355
+ }
45356
+ agentStreamControlSession = session;
45357
+ const connected = await connect();
45358
+ const subscription = connected.subscribe(agentStreamControlSubject(session));
45359
+ agentStreamControl = subscription;
45360
+ pumpAgentStreamControl(subscription, session);
45361
+ try {
45362
+ await confirmSubscribed(connected, `the agent stream control subscription for ${session}`);
45363
+ } catch (error) {
45364
+ if (agentStreamControl === subscription)
45365
+ agentStreamControl = undefined;
45366
+ subscription.unsubscribe();
45367
+ throw error;
45368
+ }
45223
45369
  };
45224
45370
  const recordAgentStreamMessage = (message, streaming) => {
45225
45371
  if (sessionID === "")
@@ -45289,7 +45435,7 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
45289
45435
  const topics = [
45290
45436
  ...new Set([
45291
45437
  own,
45292
- ...[...subscriptions.keys()].filter((subject) => !unconfirmed.has(subject) && !registrationState.isRoleBound(subject) && !reachesPrivateStreamSubject(own, subject))
45438
+ ...[...subscriptions.keys()].filter((subject) => !registrationState.isRoleBound(subject) && !reachesPrivateStreamSubject(own, subject))
45293
45439
  ])
45294
45440
  ];
45295
45441
  if (asking !== undefined)
@@ -45309,9 +45455,6 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
45309
45455
  };
45310
45456
  const sendRegistration = (send) => {
45311
45457
  const registeringFor = sessionID;
45312
- if (agentSubjectUnconfirmed(registeringFor)) {
45313
- return Promise.reject(new Error(`the server has not confirmed this session's subscription to ${agentSubject(registeringFor)}, so the session is not registered until it does`));
45314
- }
45315
45458
  const asking = relay?.sessionID === registeringFor && relay.subscription !== undefined ? relay : undefined;
45316
45459
  const input = registrationInput(asking);
45317
45460
  return send(input).then((result) => {
@@ -45518,18 +45661,10 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
45518
45661
  inboundFailure = error;
45519
45662
  }
45520
45663
  }
45521
- let confirmFailure;
45522
- if (inbound && inboundFailure === undefined) {
45523
- await confirmPending(handle.connect).catch((error) => {
45524
- confirmFailure = error;
45525
- });
45526
- }
45527
45664
  handle.check();
45528
45665
  const registration = await sendRegistration(handle.register).then(() => {
45529
45666
  return;
45530
- }, (error) => ({
45531
- error: agentSubjectUnconfirmed(host) ? inboundFailure ?? confirmFailure ?? error : error
45532
- }));
45667
+ }, (error) => ({ error }));
45533
45668
  handle.check();
45534
45669
  if (registration === undefined) {
45535
45670
  handle.markEstablished(host);
@@ -45811,6 +45946,7 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
45811
45946
  subscriptions.clear();
45812
45947
  intentionallyClosed.clear();
45813
45948
  awaitingRetry.clear();
45949
+ unanswered.clear();
45814
45950
  agentStreamControl = undefined;
45815
45951
  agentStreamControlSession = "";
45816
45952
  const liveSessionID = context.sessionManager.getSessionId();
@@ -46120,8 +46256,14 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
46120
46256
  case EnvoyToolOperation.subscribe: {
46121
46257
  const added = [];
46122
46258
  const already = [];
46259
+ let openFailure;
46123
46260
  for (const topic of topicsFor(parameters)) {
46124
- (await subscribe(topic) ? added : already).push(topic);
46261
+ try {
46262
+ (await subscribe(topic) ? added : already).push(topic);
46263
+ } catch (error) {
46264
+ openFailure = error;
46265
+ break;
46266
+ }
46125
46267
  }
46126
46268
  let warnings;
46127
46269
  let registrationError;
@@ -46134,6 +46276,8 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
46134
46276
  await replayFollowedChanged();
46135
46277
  triggerReplay();
46136
46278
  }
46279
+ if (openFailure !== undefined)
46280
+ throw openFailure;
46137
46281
  const subscribed = `Subscribed: ${added.join(", ") || "(none new)"}`;
46138
46282
  return toolSuccess(warnings === undefined || warnings.length === 0 ? subscribed : `${subscribed}
46139
46283
  Warnings: ${warnings.join("; ")}`, {
@@ -46197,13 +46341,15 @@ Kept (they last while this session holds role ${registrationState.heldRole()}):
46197
46341
  message: stringFor(parameters, "message"),
46198
46342
  ...toMessageMetadata(parameters)
46199
46343
  });
46200
- const undelivered = source !== "" && result.holder === source && inSubagent;
46201
- const published = result.holder === undefined ? `published ${result.envelope.event_id}` : `published ${result.envelope.event_id}; holder ${result.holder}`;
46344
+ const undelivered = result.kept !== true && source !== "" && result.holder === source && inSubagent;
46345
+ const published = publishConfirmationText(result);
46202
46346
  return toolSuccess(undelivered ? `${published}
46203
46347
  Not delivered: that holder is the session this subagent sends as, and the listener drops a message whose source session is its recipient, so the agent that spawned you did not receive it. Reach it with a write to its agent:// address instead.` : published, {
46204
46348
  event_id: result.envelope.event_id,
46205
46349
  topic,
46206
46350
  ...result.holder === undefined ? {} : { holder: result.holder },
46351
+ ...result.kept === undefined ? {} : { kept: result.kept },
46352
+ ...result.keptReason === undefined ? {} : { kept_reason: result.keptReason },
46207
46353
  ...undelivered ? { undelivered_echo: true } : {}
46208
46354
  });
46209
46355
  }