@sjawhar/pi-envoy 11.1.0 → 11.3.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
@@ -29691,6 +29691,15 @@ var ArtifactVersionEventPayloadSchema = exports_external.object({
29691
29691
  version: exports_external.object({ number: exports_external.number().optional(), summary: exports_external.string().nullish() }).optional(),
29692
29692
  diff: exports_external.string().optional()
29693
29693
  });
29694
+ var ArtifactHumanEditedEventPayloadSchema = exports_external.object({
29695
+ artifact_id: exports_external.string().optional(),
29696
+ name: exports_external.string().optional(),
29697
+ from_version: exports_external.number().int().optional(),
29698
+ to_version: exports_external.number().int().optional(),
29699
+ editors: exports_external.array(exports_external.string()).optional(),
29700
+ diff: exports_external.string().optional(),
29701
+ diff_truncated: exports_external.boolean().optional()
29702
+ });
29694
29703
  var ArtifactReviewEventPayloadSchema = exports_external.object({
29695
29704
  artifact_id: exports_external.string().optional(),
29696
29705
  name: exports_external.string().optional(),
@@ -29899,6 +29908,38 @@ function capAgentStreamText(text, limit) {
29899
29908
  return text;
29900
29909
  return text.slice(0, limit) + AGENT_STREAM_TRUNCATION_SUFFIX;
29901
29910
  }
29911
+ // ../contracts/src/dispatch-href.ts
29912
+ function hasControlCharacter(value) {
29913
+ return /\p{Cc}/u.test(value);
29914
+ }
29915
+
29916
+ // ../contracts/src/dispatch-block-ref.ts
29917
+ var encoder = new TextEncoder;
29918
+ function decodeBlockId(encoded) {
29919
+ if (encoded === "" || encoded.includes("@")) {
29920
+ return;
29921
+ }
29922
+ let id;
29923
+ try {
29924
+ id = decodeURIComponent(encoded);
29925
+ } catch {
29926
+ return;
29927
+ }
29928
+ return id === "" || hasControlCharacter(id) ? undefined : id;
29929
+ }
29930
+ var MAX_BLOCK_PIN = 9223372036854775807n;
29931
+ function parseBlockFragment(encoded) {
29932
+ const at = encoded.indexOf("@");
29933
+ const pin = at === -1 ? undefined : encoded.slice(at + 1).match(/^v([1-9][0-9]*)$/)?.[1];
29934
+ if (at !== -1 && (pin === undefined || BigInt(pin) > MAX_BLOCK_PIN)) {
29935
+ return;
29936
+ }
29937
+ const block = decodeBlockId(at === -1 ? encoded : encoded.slice(0, at));
29938
+ if (block === undefined) {
29939
+ return;
29940
+ }
29941
+ return pin === undefined ? { block } : { block, pin };
29942
+ }
29902
29943
  // ../contracts/src/dispatch-text-rules.ts
29903
29944
  var SESSION_ID_PATTERN = "[^/?#\\s\\p{Z}\\p{Cc}<>\"'`\\[\\]|]+";
29904
29945
  var sessionIdOnly = new RegExp(`^${SESSION_ID_PATTERN}$`, "u");
@@ -30118,7 +30159,7 @@ var dispatchToolSpecs = [
30118
30159
  issue: z2.string().describe(ISSUE_REFERENCE).optional(),
30119
30160
  project: z2.string().describe("Project key owning the document.").optional(),
30120
30161
  artifact: z2.string().describe("Project document artifact id, slug, or filename.").optional(),
30121
- ref: z2.string().describe("Optional dispatch:// reference (issue, document, message, or ask); appended to the question and rendered as a link.").optional(),
30162
+ ref: z2.string().describe("Optional dispatch:// reference (issue, document, block, message, or ask); appended to the question and rendered as a link.").optional(),
30122
30163
  question: z2.string({ max: ASK_QUESTION_MAX }).describe(`${ASK_QUESTION_CONTRACT} At most ${ASK_QUESTION_MAX} characters.`),
30123
30164
  options: z2.array(z2.object({
30124
30165
  label: z2.string().describe("Selectable option label."),
@@ -30263,7 +30304,7 @@ var dispatchToolSpecs = [
30263
30304
  ops: [{ op: "delete_column", block: "table-123", index: 1 }],
30264
30305
  precondition: { blocks: [{ id: "table-123", token: "sha256:current-table-token" }] }
30265
30306
  },
30266
- description: "Apply deterministic document edits: replace or delete quoted text, insert markdown at an anchor, retype an identified paragraph or typed block into a schema-declared typed block, delete or move a whole block by its id, or delete a table row or column in place. " + "Do not use it for review feedback or for reading; use dispatch comment, dispatch suggest, or dispatch doc-read instead. " + `For replace, delete, and quote anchors, find text as rendered: inline Markdown (**bold**, \`code\`) is tolerated and must be balanced; a leading '# ' matches a heading at any level. replace is inline: with is the new text of the matched span, so a marker of a different kind from the block's own stays literal text ('4. Design' written into a heading). A with that opens with a marker of the same kind as the matched block's own would write it twice and is INVALID_OP - including prose that merely looks like one ('1999. was a year' into an ordered item), which you write as text by escaping it ('1999\\. was a year'). The exception is a heading rename whose find carried a heading marker: replace(find="## Old", with="## New") gives '## New', and a different level applies only when find named the heading's actual level (find "## Old" with "### New" makes it an h3), since '# ' selects a heading without naming its level. A task item (\`- [ ]\` / \`- [x]\`) is ticked the same way: when find matches from the start of the item's text and with opens with '[x] ' or '[ ] ', the opening sets the item's box and the rest is its new text (replace(find="Write it", with="[x] Write it") ticks it); the same opening over a plain list item or a paragraph stays literal text. Any non-empty with that renders to no text - a line indented four spaces or a tab, which markdown reads as a code block, or whitespace alone - is INVALID_OP rather than a silent deletion; pass an empty with to delete the matched text on purpose - a list item, quote, typed block or footnote definition left holding only the emptied paragraph keeps it. ` + "with cannot open a new block: after a hard line break inside with (two trailing spaces, or a backslash, before the newline) a heading, bullet, '1.'/'1)' ordered, or '>' blockquote marker is INVALID_OP too, since that line would stay escaped text inside the matched block - use insert, plus delete for what it replaces, to add the block. A hard break in with is itself INVALID_OP when the matched text is in a heading or a table cell, which are written on one line. " + "A delete whose find is a block's entire text removes the block (a list emptied of its items goes too); delete with block removes any block by id, and move with block relocates one. A delete or retype that would take an ask block out of the document while its ask is open is refused, with nothing sent. delete_row and delete_column take a table block and a zero-based index, preserving the table block id and refusing to remove cells with open asks or unresolved comments. " + `Insert and move anchors also accept "start", "end", "heading:<exact heading text>", and "block:<id>"; dispatch doc-read --blocks lists every block's id, type, opening words and token, and each table's rows and cells with the indexes delete_row and delete_column take (GET /api/v1/artifacts/{artifact UUID}/blocks serves the same list). ` + "Optionally require the state just read: precondition selects exactly one of a document token from dispatch doc-read, or block {id, token} values from dispatch doc-read --blocks. A block guard must include every block the batch changes; Dispatch resolves quote targets and rejects an uncovered batch rather than applying it. Use a document token for insert or move, which depend on document order. Prefer block tokens when the covered content blocks are independent sections. Tokens include inline marks, so a fresh human comment also makes a stale edit fail. PRECONDITION_FAILED means re-read; EDIT_QUEUE_FULL means back off before retrying. " + "The result carries the document token this edit produced, so a chain of guarded edits passes each result's token as the next edit's precondition with no dispatch doc-read between them. " + "A batch that leaves the document exactly as it was mints no version, named or not, and the result says nothing changed and names each operation that did nothing. " + "A change a browser removes while the edit is in flight is never reported as applied: EDIT_LOST_TO_CONCURRENT_CHANGE means the write was refused and nothing was written, so re-read the document and decide again, as with PRECONDITION_FAILED; lost_ops on a successful result names operations whose text the live document no longer has, because the deletion landed after the version was written. " + "One replace per paragraph: more new paragraphs go in one insert after the last one you rewrote, since two inserts at one anchor come out reversed; read the passage back with dispatch doc-read afterwards. " + `The spec holds requirements, design, and decisions - never progress, status, or timestamps; a record of open items or progress is a document of its own. ${OWNER_REFERENCE} ${SPEC_WRITING_POINTER}`,
30307
+ description: "Apply deterministic document edits: replace or delete quoted text, insert markdown at an anchor, retype an identified paragraph or typed block into a schema-declared typed block, delete or move a whole block by its id, or delete a table row or column in place. " + "Do not use it for review feedback or for reading; use dispatch comment, dispatch suggest, or dispatch doc-read instead. " + `For replace, delete, and quote anchors, find text as rendered: inline Markdown (**bold**, \`code\`) is tolerated and must be balanced; a leading '# ' matches a heading at any level. replace is inline: with is the new text of the matched span, so a marker of a different kind from the block's own stays literal text ('4. Design' written into a heading). A with that opens with a marker of the same kind as the matched block's own would write it twice and is INVALID_OP - including prose that merely looks like one ('1999. was a year' into an ordered item), which you write as text by escaping it ('1999\\. was a year'). The exception is a heading rename whose find carried a heading marker: replace(find="## Old", with="## New") gives '## New', and a different level applies only when find named the heading's actual level (find "## Old" with "### New" makes it an h3), since '# ' selects a heading without naming its level. A task item (\`- [ ]\` / \`- [x]\`) is ticked the same way: when find matches from the start of the item's text and with opens with '[x] ' or '[ ] ', the opening sets the item's box and the rest is its new text (replace(find="Write it", with="[x] Write it") ticks it); the same opening over a plain list item or a paragraph stays literal text. Any non-empty with that renders to no text - a line indented four spaces or a tab, which markdown reads as a code block, or whitespace alone - is INVALID_OP rather than a silent deletion; pass an empty with to delete the matched text on purpose - a list item, quote, typed block or footnote definition left holding only the emptied paragraph keeps it. ` + "with cannot open a new block: after a hard line break inside with (two trailing spaces, or a backslash, before the newline) a heading, bullet, '1.'/'1)' ordered, or '>' blockquote marker is INVALID_OP too, since that line would stay escaped text inside the matched block - use insert, plus delete for what it replaces, to add the block. A hard break in with is itself INVALID_OP when the matched text is in a heading or a table cell, which are written on one line. In a table cell, with is the cell's text: write a | in it bare, in code too, since code whose text has an odd run of backslashes right before a | cannot be stored in a cell and is INVALID_OP, naming the cell. " + "A delete whose find is a block's entire text removes the block (a list emptied of its items goes too); delete with block removes any block by id, and move with block relocates one. A delete or retype that would take an ask block out of the document while its ask is open is refused, with nothing sent. delete_row and delete_column take a table block and a zero-based index, preserving the table block id and refusing to remove cells with open asks or unresolved comments. " + `Insert and move anchors also accept "start", "end", "heading:<exact heading text>", and "block:<id>"; dispatch doc-read --blocks lists every block's id, type, opening words and token, and each table's rows and cells with the indexes delete_row and delete_column take (GET /api/v1/artifacts/{artifact UUID}/blocks serves the same list). ` + "Optionally require the state just read: precondition selects exactly one of a document token from dispatch doc-read, or block {id, token} values from dispatch doc-read --blocks. A block guard must include every block the batch changes; Dispatch resolves quote targets and rejects an uncovered batch rather than applying it. Use a document token for insert or move, which depend on document order. Prefer block tokens when the covered content blocks are independent sections. Tokens include inline marks, so a fresh human comment also makes a stale edit fail. PRECONDITION_FAILED means re-read; EDIT_QUEUE_FULL means back off before retrying. " + "The result carries the document token this edit produced, so a chain of guarded edits passes each result's token as the next edit's precondition with no dispatch doc-read between them. " + "A batch that leaves the document exactly as it was mints no version, named or not, and the result says nothing changed and names each operation that did nothing. " + "A change a browser removes while the edit is in flight is never reported as applied: EDIT_LOST_TO_CONCURRENT_CHANGE means the write was refused and nothing was written, so re-read the document and decide again, as with PRECONDITION_FAILED; lost_ops on a successful result names operations whose text the live document no longer has, because the deletion landed after the version was written. " + "One replace per paragraph: more new paragraphs go in one insert after the last one you rewrote, since two inserts at one anchor come out reversed; read the passage back with dispatch doc-read afterwards. " + "A block id written as {#id} longer than 256 bytes is stored, but its block is no graph node, so no reference reaches it. " + `The spec holds requirements, design, and decisions - never progress, status, or timestamps; a record of open items or progress is a document of its own. ${OWNER_REFERENCE} ${SPEC_WRITING_POINTER}`,
30267
30308
  arguments: (z2) => ({
30268
30309
  issue: z2.string().describe(ISSUE_REFERENCE).optional(),
30269
30310
  project: z2.string().describe("Project key owning the document.").optional(),
@@ -30323,7 +30364,7 @@ var dispatchToolSpecs = [
30323
30364
  name: "dispatch_artifact",
30324
30365
  example: { issue: "DSP-1", name: "design.md", content: `# Design
30325
30366
  ` },
30326
- description: "Attach a local file or inline text as an issue artifact or project document. Do not use it to edit a live document; use " + "dispatch doc-edit instead. Never upload a document's own name to change it (spec.md replaces the spec whole); edit it with dispatch doc-edit. Uploading the same name again makes its next version. Exactly one of path or content is required; a markdown document is at most 1 MiB and any other file at most 25 MiB. " + "Markdown is also refused with 413 CAP_EXCEEDED when it makes more than 65,536 elements (a block weighs 3, and an empty list item, quote, footnote definition or typed block 3 more for the empty paragraph it holds; a table cell 4, a hard line break 3, an image 3, a piece of inline HTML 2, an autolink 2, a footnote reference 2; inline syntax, marks, lines of text and backslash escapes or character references 1 each), or when a new version would leave the document's stored markdown (what its text reads back as) longer than 1 MiB or making more than 65,536 elements, and longer or heavier than before; shorten it or split it across documents. " + "Markdown holding an ask block whose body breaks its content rule (one or more question paragraphs, then at most one bullet list of options, last) is refused with 400 INVALID_ASK_BLOCK; a new version of a document is held to it only for the asks it writes or changes. " + `${OWNER_REFERENCE}`,
30367
+ description: "Attach a local file or inline text as an issue artifact or project document. Do not use it to edit a live document; use " + "dispatch doc-edit instead. Never upload a document's own name to change it (spec.md replaces the spec whole); edit it with dispatch doc-edit. Uploading the same name again makes its next version. Exactly one of path or content is required; a markdown document is at most 1 MiB and any other file at most 25 MiB. " + "Markdown is also refused with 413 CAP_EXCEEDED when it makes more than 65,536 elements (a block weighs 3, and an empty list item, quote, footnote definition or typed block 3 more for the empty paragraph it holds; a table cell 4, a hard line break 3, an image 3, a piece of inline HTML 2, an autolink 2, a footnote reference 2; inline syntax, marks, lines of text and backslash escapes or character references 1 each), or when a new version would leave the document's stored markdown (what its text reads back as) longer than 1 MiB or making more than 65,536 elements, and longer or heavier than before; shorten it or split it across documents. " + "In a table row, write every | in a cell as \\|, in code too: a | after two backslashes ends the cell, and a row with more cells than its table is refused. " + "Markdown holding an ask block whose body breaks its content rule (one or more question paragraphs, then at most one bullet list of options, last) is refused with 400 INVALID_ASK_BLOCK; a new version of a document is held to it only for the asks it writes or changes. " + `${OWNER_REFERENCE}`,
30327
30368
  arguments: (z2) => ({
30328
30369
  issue: z2.string().describe(ISSUE_REFERENCE).optional(),
30329
30370
  project: z2.string().describe("Project key for an unlinked document.").optional(),
@@ -30343,12 +30384,12 @@ var dispatchToolSpecs = [
30343
30384
  {
30344
30385
  name: "dispatch_read",
30345
30386
  example: { issue: "DSP-1" },
30346
- 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), or project plus artifact; 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 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. " + "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,
30387
+ 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), or project plus artifact; 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 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,
30347
30388
  arguments: (z2) => ({
30348
30389
  issue: z2.string().describe(ISSUE_REFERENCE).optional(),
30349
30390
  project: z2.string().describe("Project key owning the document.").optional(),
30350
30391
  artifact: z2.string().describe("Document artifact id, slug, or filename: one of the issue's, or a project document.").optional(),
30351
- ref: z2.string().describe("Optional dispatch:// reference: dispatch://KEY, dispatch://KEY/spec, " + "dispatch://KEY/artifact/<slug>[@vN], dispatch://KEY/ask/<id>, dispatch://KEY/comment/<id>, " + "dispatch://KEY/message/<id>, dispatch://PROJECT/artifact/<slug>[@vN], and its " + "/ask/<id> and /comment/<id>; or the dashboard URL of one.").optional(),
30392
+ ref: z2.string().describe("Optional dispatch:// reference: dispatch://KEY, dispatch://KEY/spec, " + "dispatch://KEY/artifact/<slug>[@vN], dispatch://KEY/ask/<id>, dispatch://KEY/comment/<id>, " + "dispatch://KEY/message/<id>, dispatch://PROJECT/artifact/<slug>[@vN], and its " + "/ask/<id> and /comment/<id>; or the dashboard URL of one. A block: " + "dispatch://KEY/spec#b-<block id>[@vN], dispatch://KEY/artifact/<slug>#b-<block id>[@vN] or " + "dispatch://PROJECT/artifact/<slug>#b-<block id>[@vN], the id percent-encoded except ASCII " + "letters, digits and -.").optional(),
30352
30393
  message: z2.string().describe("A message id (uuid): reads the conversation it belongs to, the root message and every " + "reply. Name nothing else with it.").optional(),
30353
30394
  events: z2.number({ int: true, min: 1 }).describe(`How many of the issue's newest events an issue read or its dispatch://KEY/log lists, oldest first; default ${DEFAULT_ISSUE_READ_EVENTS}. Name no --all-events with it.`).optional(),
30354
30395
  all_events: z2.boolean().describe(`List every one of the issue's events, oldest first, on an issue read or its dispatch://KEY/log, in place of the last ${DEFAULT_ISSUE_READ_EVENTS}. Name no --events with it.`).optional()
@@ -30501,6 +30542,7 @@ function dedupeKeyNamesItsEvent(envelope) {
30501
30542
  // ../contracts/src/subject.ts
30502
30543
  var AGENT_TOPIC_PREFIX = "notifications.agent.";
30503
30544
  var ROLE_TOPIC_PREFIX = "notifications.role.";
30545
+ var LEGION_NOTICE_TOPIC_PREFIX = "notifications.legion.";
30504
30546
  var DISPATCH_TOPIC_PREFIX = "notifications.dispatch.";
30505
30547
  var DISPATCH_ISSUE_TOPIC_PREFIX = `${DISPATCH_TOPIC_PREFIX}issue.`;
30506
30548
  var DISPATCH_DOCUMENT_TOPIC_PREFIX = `${DISPATCH_TOPIC_PREFIX}document.`;
@@ -31355,7 +31397,27 @@ function dispatchDocumentRef(owner, slug) {
31355
31397
  function dispatchChildRef(ownerRef, kind, id) {
31356
31398
  return `${ownerRef}/${kind}/${id}`;
31357
31399
  }
31400
+ function parseBlockRef(document, fragment) {
31401
+ const target = parseBlockFragment(fragment);
31402
+ const parsed = parseDispatchRef(document);
31403
+ if (target === undefined || parsed === null || parsed.version !== undefined || parsed.kind !== "spec" && parsed.kind !== "artifact") {
31404
+ return null;
31405
+ }
31406
+ return {
31407
+ owner: parsed.owner,
31408
+ kind: "block",
31409
+ id: parsed.id,
31410
+ block: target.block,
31411
+ document,
31412
+ ...parsed.owner.kind === "project" ? { artifact: parsed.id } : {},
31413
+ ...target.pin === undefined ? {} : { pin: target.pin }
31414
+ };
31415
+ }
31358
31416
  function parseDispatchRef(ref) {
31417
+ const hash2 = ref.indexOf("#");
31418
+ if (hash2 !== -1 && ref.startsWith("b-", hash2 + 1)) {
31419
+ return parseBlockRef(ref.slice(0, hash2), ref.slice(hash2 + 3));
31420
+ }
31359
31421
  const projectDocument = ref.match(/^dispatch:\/\/([A-Z][A-Z0-9]{1,9})\/artifact\/([^/@]+)(?:@v(\d+))?(?:\/(ask|comment)\/([^/]+))?$/);
31360
31422
  if (projectDocument) {
31361
31423
  const [, project, artifact2, version3, targetKind, targetID] = projectDocument;
@@ -31450,6 +31512,47 @@ function pictureAddresses(text) {
31450
31512
  return [...text.matchAll(PICTURE_SYNTAX)].map((match) => match[1]);
31451
31513
  }
31452
31514
 
31515
+ // ../envoy-client/src/human-edit.ts
31516
+ function humanEditHead(edit) {
31517
+ const editors = edit.editors ?? [];
31518
+ const by = editors.length === 0 ? "" : `, edited by ${editors.join(", ")}`;
31519
+ return `${edit.name ?? "document"} v${edit.from_version ?? "?"} to v${edit.to_version ?? "?"}${by}`;
31520
+ }
31521
+ var HUMAN_EDIT_DIFF_CUT_NOTE = "(diff cut at 4,096 bytes)";
31522
+ var HUMAN_EDIT_DIFF_MAX = 4096;
31523
+ function humanEditDiffBlock(diff, cut) {
31524
+ if (diff === undefined || diff === "")
31525
+ return cut === true ? HUMAN_EDIT_DIFF_CUT_NOTE : "";
31526
+ const bytes = new TextEncoder;
31527
+ let shown = diff;
31528
+ let note = cut === true;
31529
+ if (bytes.encode(shown).length > HUMAN_EDIT_DIFF_MAX) {
31530
+ let kept = "";
31531
+ let size = 0;
31532
+ for (const line of shown.split(`
31533
+ `).slice(0, -1)) {
31534
+ size += bytes.encode(`${line}
31535
+ `).length;
31536
+ if (size > HUMAN_EDIT_DIFF_MAX)
31537
+ break;
31538
+ kept += `${line}
31539
+ `;
31540
+ }
31541
+ shown = kept;
31542
+ note = true;
31543
+ }
31544
+ if (shown === "")
31545
+ return HUMAN_EDIT_DIFF_CUT_NOTE;
31546
+ const longestRun = Math.max(0, ...(shown.match(/`+/g) ?? []).map((run) => run.length));
31547
+ const fence = "`".repeat(Math.max(3, longestRun + 1));
31548
+ const body = shown.endsWith(`
31549
+ `) ? shown : `${shown}
31550
+ `;
31551
+ return `${fence}diff
31552
+ ${body}${fence}${note ? `
31553
+ ${HUMAN_EDIT_DIFF_CUT_NOTE}` : ""}`;
31554
+ }
31555
+
31453
31556
  // ../envoy-client/src/delivery.ts
31454
31557
  var KNOWN_SOURCES = EnvelopeSchema.shape.source.enum;
31455
31558
  var FOREIGN_SESSION_ID = /\b01a0[0-9a-f]{4}-[0-9a-f]{4}-7[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}\b/g;
@@ -31510,6 +31613,55 @@ async function postDeliveryReply(config2, sessionId, delivery, result) {
31510
31613
  function expectsLaneReceipt(frame) {
31511
31614
  return frame.reply !== undefined && frame.reply !== "" && frame.subject === frame.directSubject && frame.envelopeTopic !== undefined && frame.envelopeTopic !== frame.directSubject;
31512
31615
  }
31616
+ async function* readArrivals(subscription, now = Date.now) {
31617
+ const source = subscription[Symbol.asyncIterator]();
31618
+ const arrived = [];
31619
+ let stopped;
31620
+ let left = false;
31621
+ let wake;
31622
+ const signal = () => {
31623
+ wake?.();
31624
+ wake = undefined;
31625
+ };
31626
+ (async () => {
31627
+ try {
31628
+ for (;; ) {
31629
+ const read = await source.next();
31630
+ if (read.done === true || left)
31631
+ break;
31632
+ arrived.push({ message: read.value, receivedAt: now() });
31633
+ signal();
31634
+ }
31635
+ stopped = { failed: false };
31636
+ } catch (error48) {
31637
+ stopped = { error: error48, failed: true };
31638
+ }
31639
+ signal();
31640
+ })();
31641
+ try {
31642
+ for (;; ) {
31643
+ const next = arrived.shift();
31644
+ if (next !== undefined) {
31645
+ yield next;
31646
+ continue;
31647
+ }
31648
+ if (stopped?.failed === true)
31649
+ throw stopped.error;
31650
+ if (stopped !== undefined)
31651
+ return;
31652
+ const { promise: promise2, resolve } = Promise.withResolvers();
31653
+ wake = resolve;
31654
+ await promise2;
31655
+ }
31656
+ } finally {
31657
+ if (stopped === undefined) {
31658
+ left = true;
31659
+ Promise.resolve(source.return?.()).catch(() => {
31660
+ return;
31661
+ });
31662
+ }
31663
+ }
31664
+ }
31513
31665
  var DedupeIdentitySchema = exports_external.object({
31514
31666
  event_id: exports_external.string().min(1).optional(),
31515
31667
  dedupe_key: exports_external.string().min(1).optional(),
@@ -31522,6 +31674,8 @@ function createDeliveryDedupe(now = Date.now) {
31522
31674
  const keys = new Map;
31523
31675
  let events = new Map;
31524
31676
  let olderEvents = new Map;
31677
+ const pendingKeys = new Map;
31678
+ const pendingEvents = new Map;
31525
31679
  let claims = 0;
31526
31680
  return {
31527
31681
  claim(frame) {
@@ -31557,10 +31711,25 @@ function createDeliveryDedupe(now = Date.now) {
31557
31711
  events = new Map;
31558
31712
  }
31559
31713
  events.set(eventId, claim);
31714
+ pendingEvents.set(eventId, claim);
31560
31715
  }
31716
+ if (named)
31717
+ pendingKeys.set(key, claim);
31718
+ let open = true;
31719
+ const close = () => {
31720
+ if (!open)
31721
+ return;
31722
+ open = false;
31723
+ if (eventId !== undefined && pendingEvents.get(eventId) === claim) {
31724
+ pendingEvents.delete(eventId);
31725
+ }
31726
+ if (named && pendingKeys.get(key) === claim)
31727
+ pendingKeys.delete(key);
31728
+ };
31561
31729
  let released = false;
31562
31730
  return {
31563
31731
  release() {
31732
+ close();
31564
31733
  if (released)
31565
31734
  return;
31566
31735
  released = true;
@@ -31572,8 +31741,14 @@ function createDeliveryDedupe(now = Date.now) {
31572
31741
  events.delete(eventId);
31573
31742
  if (olderEvents.get(eventId) === claim)
31574
31743
  olderEvents.delete(eventId);
31575
- }
31744
+ },
31745
+ settle: close
31576
31746
  };
31747
+ },
31748
+ pending(frame) {
31749
+ const eventId = frame.event_id;
31750
+ const key = frame.dedupe_key;
31751
+ return eventId !== undefined && pendingEvents.has(eventId) || key !== undefined && dedupeKeyNamesItsEvent(frame) && pendingKeys.has(key);
31577
31752
  }
31578
31753
  };
31579
31754
  }
@@ -31652,6 +31827,7 @@ var DISPATCH_PAYLOAD_SCHEMAS = {
31652
31827
  "issue.closed": IssueEventPayloadSchema,
31653
31828
  "artifact.created": ArtifactCreatedEventPayloadSchema,
31654
31829
  "artifact.version": ArtifactVersionEventPayloadSchema,
31830
+ "artifact.human_edited": ArtifactHumanEditedEventPayloadSchema,
31655
31831
  "ask.opened": AskEventPayloadSchema,
31656
31832
  "ask.anchor_refreshed": AskEventPayloadSchema,
31657
31833
  "ask.edited": AskEditedEventPayloadSchema,
@@ -31723,6 +31899,12 @@ function askResolutionText(resolution) {
31723
31899
  return reason === "" ? kind : `${kind}: ${reason}`;
31724
31900
  }
31725
31901
  function dispatchCompact(event, comment) {
31902
+ if (event.type === "artifact.human_edited") {
31903
+ const edit = ArtifactHumanEditedEventPayloadSchema.safeParse(event.payload);
31904
+ if (!edit.success)
31905
+ return;
31906
+ return { askId: undefined, record: { edit: humanEditHead(edit.data) } };
31907
+ }
31726
31908
  if (event.type === "comment.created") {
31727
31909
  if (comment?.ask_id === undefined || comment.ask_id === null)
31728
31910
  return;
@@ -31922,6 +32104,7 @@ function renderInbound(raw, sessionID, subject2) {
31922
32104
  let pictures = [];
31923
32105
  let inReplyTo = envelope2.in_reply_to;
31924
32106
  let askAuthor;
32107
+ let trailer = "";
31925
32108
  const dispatchRendered = envelope2.source === "dispatch" && envelope2.payload !== undefined;
31926
32109
  if (envelope2.source === "dispatch") {
31927
32110
  const topic = subject2 ?? envelope2.topic;
@@ -32026,6 +32209,11 @@ function renderInbound(raw, sessionID, subject2) {
32026
32209
  };
32027
32210
  dispatchActor = frame.event.actor;
32028
32211
  pictures = eventPictures(frame.event);
32212
+ if (frame.event.type === "artifact.human_edited") {
32213
+ const edit = ArtifactHumanEditedEventPayloadSchema.safeParse(frame.event.payload);
32214
+ if (edit.success)
32215
+ trailer = humanEditDiffBlock(edit.data.diff, edit.data.diff_truncated);
32216
+ }
32029
32217
  } else {
32030
32218
  dispatchEvent = frame.raw;
32031
32219
  rejectedDelivery = frame.rejectedDelivery;
@@ -32091,7 +32279,9 @@ function renderInbound(raw, sessionID, subject2) {
32091
32279
  };
32092
32280
  return {
32093
32281
  skip: false,
32094
- content: encode3({ envoy: rendered }),
32282
+ content: trailer === "" ? encode3({ envoy: rendered }) : `${encode3({ envoy: rendered })}
32283
+
32284
+ ${trailer}`,
32095
32285
  envelope: envelope2,
32096
32286
  ...dispatchActor === undefined ? {} : { dispatchActor },
32097
32287
  ...delivery === undefined ? {} : { delivery },
@@ -33579,7 +33769,7 @@ function subscriptionRemovedTopics(raw, sessionID) {
33579
33769
 
33580
33770
  // ../envoy-client/src/dispatch-execute.ts
33581
33771
  var triageAdviceShown = new Set;
33582
- var refGrammarProblem = "ref must be a valid dispatch:// reference such as dispatch://KEY-1, " + "dispatch://KEY-1/ask/<uuid>, dispatch://KEY-1/comment/<uuid>, " + "dispatch://KEY-1/message/<uuid>, dispatch://KEY-1/artifact/<slug>, " + "dispatch://PROJECT/artifact/<document-ref> (an artifact id, slug, or filename), or " + "dispatch://agent/<session id>/artifact/<slug> (a picture in a conversation on the Agents page, " + "for dispatch doc-read); a dashboard URL on this Dispatch server is accepted too";
33772
+ var refGrammarProblem = "ref must be a valid dispatch:// reference such as dispatch://KEY-1, " + "dispatch://KEY-1/ask/<uuid>, dispatch://KEY-1/comment/<uuid>, " + "dispatch://KEY-1/message/<uuid>, dispatch://KEY-1/artifact/<slug>, " + "dispatch://PROJECT/artifact/<document-ref> (an artifact id, slug, or filename), " + "dispatch://KEY-1/spec#b-<block id>, dispatch://KEY-1/artifact/<slug>#b-<block id> or " + "dispatch://PROJECT/artifact/<slug>#b-<block id> (one block of a document, its id " + "percent-encoded, optionally pinned to a version of the document with @v<N> after it; for " + "dispatch read), or " + "dispatch://agent/<session id>/artifact/<slug> (a picture in a conversation on the Agents page, " + "for dispatch doc-read); a dashboard URL on this Dispatch server is accepted too";
33583
33773
  var toolSchemas = new Map;
33584
33774
  function asObject(value) {
33585
33775
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
@@ -33802,94 +33992,1106 @@ function natsAuthOptions(seed) {
33802
33992
  return { authenticator: import_nats.nkeyAuthenticator(bytes) };
33803
33993
  }
33804
33994
 
33805
- // ../envoy-client/src/session-settings.ts
33806
- function sessionConfigFile(harness, env) {
33807
- try {
33808
- return { path: envoyConfigPath(harness, env), error: null };
33809
- } catch (error48) {
33810
- return { path: null, error: messageFor(error48) };
33995
+ // ../envoy-client/src/transport.ts
33996
+ var DEFAULT_TIMEOUT_MS = 5000;
33997
+ var RETRY_DELAY_MS = 250;
33998
+ var REPLAY_TIMEOUT_MS = 1e4;
33999
+ var REPLAY_UNAVAILABLE_CODE = "REPLAY_UNAVAILABLE";
34000
+ var InterestWireSchema = exports_external.object({
34001
+ session_id: exports_external.string(),
34002
+ machine_id: exports_external.string(),
34003
+ dir: exports_external.string(),
34004
+ topics: exports_external.array(exports_external.string()),
34005
+ updated_at: exports_external.number().int().optional(),
34006
+ warnings: exports_external.array(exports_external.string()).optional()
34007
+ });
34008
+ var SessionWireSchema = exports_external.object({
34009
+ session_id: exports_external.string(),
34010
+ machine_id: exports_external.string(),
34011
+ host: exports_external.string().optional(),
34012
+ dir: exports_external.string(),
34013
+ port: exports_external.number().int(),
34014
+ title: exports_external.string(),
34015
+ topics: exports_external.array(exports_external.string()),
34016
+ roles: exports_external.array(exports_external.string()).optional(),
34017
+ capabilities: exports_external.array(exports_external.string()).optional(),
34018
+ self_subscribed: exports_external.boolean(),
34019
+ last_seen: exports_external.number().int().optional()
34020
+ });
34021
+ var RoleWireSchema = exports_external.object({
34022
+ role: exports_external.string(),
34023
+ holder: exports_external.string(),
34024
+ host: exports_external.string().optional(),
34025
+ last_seen: exports_external.number().int()
34026
+ });
34027
+ var RoleHeldWireSchema = exports_external.object({
34028
+ error: exports_external.string(),
34029
+ role: exports_external.string(),
34030
+ holder: exports_external.string()
34031
+ });
34032
+ var ErrorWireSchema = exports_external.object({
34033
+ error: exports_external.string(),
34034
+ code: exports_external.string().optional(),
34035
+ expected: exports_external.array(exports_external.string()).optional()
34036
+ });
34037
+ var EnvelopeResponseSchema = EnvelopeSchema.extend({
34038
+ recipient: exports_external.string().optional(),
34039
+ holder: exports_external.string().optional()
34040
+ });
34041
+ var ReplayWireSchema = exports_external.object({
34042
+ stream: exports_external.object({
34043
+ id: exports_external.string().min(1).optional(),
34044
+ created: exports_external.string(),
34045
+ first_seq: exports_external.number().int().nonnegative(),
34046
+ last_seq: exports_external.number().int().nonnegative()
34047
+ }),
34048
+ subjects: exports_external.array(exports_external.object({
34049
+ subject: exports_external.string(),
34050
+ messages: exports_external.array(exports_external.object({
34051
+ seq: exports_external.number().int().positive(),
34052
+ subject: exports_external.string(),
34053
+ time: exports_external.string(),
34054
+ data: exports_external.string()
34055
+ })),
34056
+ next_after: exports_external.number().int().nonnegative(),
34057
+ more: exports_external.boolean(),
34058
+ refused: exports_external.string().optional()
34059
+ }))
34060
+ });
34061
+ function mergeInterestSources(registryTopics, liveTopics) {
34062
+ const interests = new Map;
34063
+ for (const topic of registryTopics) {
34064
+ interests.set(topic, liveTopics.includes(topic) ? "both" : "registry");
34065
+ }
34066
+ for (const topic of liveTopics) {
34067
+ if (!interests.has(topic))
34068
+ interests.set(topic, "live");
33811
34069
  }
34070
+ return interests;
33812
34071
  }
33813
- function startNotice(config2, dispatch, envoy, nats) {
33814
- if (config2.kind === "failed")
33815
- return `${config2.error}: Dispatch and Envoy are off`;
33816
- const { missing, checkout } = config2;
33817
- const dispatchQuiet = !dispatch.enabled && dispatch.error === null;
33818
- const envoyQuiet = !envoy.enabled && envoy.error === null;
33819
- const parts = [];
33820
- if (missing !== null && dispatchQuiet && envoyQuiet) {
33821
- parts.push(missingConfigNotice(config2.path, missing, "Dispatch and Envoy are off"));
33822
- } else {
33823
- if (!dispatch.enabled && dispatch.error !== null)
33824
- parts.push(`Dispatch is off: ${dispatch.error}`);
33825
- else if (dispatchQuiet && missing !== null) {
33826
- parts.push(missingConfigNotice(config2.path, missing, "Dispatch is off"));
34072
+ function expandSubscriptionTopics(topics) {
34073
+ const expanded = new Set;
34074
+ for (const topic of topics) {
34075
+ const base = topic.endsWith(".>") ? topic.slice(0, -2) : undefined;
34076
+ if (base === undefined || base.includes("*") || base.includes(">")) {
34077
+ expanded.add(topic);
34078
+ continue;
33827
34079
  }
33828
- if (!envoy.enabled && envoy.error !== null)
33829
- parts.push(`Envoy is off: ${envoy.error}`);
33830
- else if (envoyQuiet && missing !== null) {
33831
- parts.push(missingConfigNotice(config2.path, missing, "Envoy is off"));
34080
+ const segments = base.split(".");
34081
+ if (segments.length < 2 || segments.some((segment) => segment.length === 0)) {
34082
+ throw new TypeError(`cannot expand Envoy wildcard topic "${topic}": its concrete base must have at least two non-empty segments`);
33832
34083
  }
34084
+ expanded.add(base);
34085
+ expanded.add(topic);
33833
34086
  }
33834
- if (checkout?.kind === "valid" && checkout.envoyError !== null)
33835
- parts.push(checkout.envoyError);
33836
- if (checkout?.kind === "invalid" && (dispatch.enabled || dispatch.error !== checkout.error)) {
33837
- parts.push(`${checkout.error}; not read while DISPATCH_URL is set`);
33838
- }
33839
- parts.push(...config2.warnings);
33840
- if (envoy.enabled && nats && "off" in envoy.inbound) {
33841
- parts.push(`Envoy's inbound messages are off: ${envoy.inbound.off}; the Envoy tools still work`);
33842
- }
33843
- if (envoy.enabled && envoy.passDeadlineRaisedFrom !== undefined) {
33844
- parts.push(`Envoy's pass deadline is ${envoy.passDeadlineMs} ms, not the ${envoy.passDeadlineRaisedFrom} ms ENVOY_PASS_DEADLINE_MS names: a deadline inside one ${envoy.heartbeatMs} ms heartbeat interval would abandon every pass before the next tick, so the registration refresh the heartbeat posts for a stalled pass would never run`);
33845
- }
33846
- return parts.length === 0 ? null : parts.join("; ");
34087
+ return [...expanded];
33847
34088
  }
33848
- function sessionSettings(file2, env, options) {
33849
- if (file2.path === null) {
33850
- const off = offWithError(file2.error);
33851
- return { dispatch: off, envoy: off, notice: `${file2.error}: Dispatch and Envoy are off` };
34089
+
34090
+ class EnvoyApiError extends Error {
34091
+ details;
34092
+ name = "EnvoyApiError";
34093
+ expected;
34094
+ code;
34095
+ constructor(details) {
34096
+ let parsed;
34097
+ try {
34098
+ const result = ErrorWireSchema.safeParse(JSON.parse(details.responseBody));
34099
+ if (result.success)
34100
+ parsed = result.data;
34101
+ } catch {}
34102
+ super(parsed === undefined ? `${details.method} ${details.url} failed with ${details.status}: ${details.responseBody}` : `${parsed.error}${parsed.expected === undefined ? "" : ` (expected: ${parsed.expected.join(", ")})`}`);
34103
+ this.details = details;
34104
+ this.expected = parsed?.expected;
34105
+ this.code = parsed?.code;
33852
34106
  }
33853
- const config2 = readEnvoyConfig(file2.path, env, options);
33854
- const dispatch = dispatchSettings(env, config2);
33855
- const envoy = envoySettings(env, config2, { nats: options.nats });
33856
- return {
33857
- dispatch,
33858
- envoy,
33859
- notice: startNotice(config2, dispatch, envoy, options.nats !== false)
33860
- };
33861
34107
  }
33862
- function sessionDispatchSettings(file2, env, options) {
33863
- if (file2.path === null)
33864
- return { dispatch: offWithError(file2.error), warnings: [], missing: null };
33865
- const config2 = readEnvoyConfig(file2.path, env, options);
33866
- return {
33867
- dispatch: dispatchSettings(env, config2),
33868
- warnings: config2.kind === "read" ? config2.warnings : [],
33869
- missing: config2.kind === "read" ? config2.missing : null
34108
+ function createEnvoyClient(config2) {
34109
+ const baseUrl = normalizeEnvoyUrl(config2.baseUrl);
34110
+ const timeoutMs = config2.timeoutMs ?? DEFAULT_TIMEOUT_MS;
34111
+ const apiToken = config2.token;
34112
+ const request = async (path2, init, options = {}) => {
34113
+ const url2 = `${baseUrl}${path2}`;
34114
+ const attempts = config2.retry === false ? 1 : 2;
34115
+ const tries = options.retry === false ? 1 : attempts;
34116
+ for (let attempt = 0;attempt < tries; attempt += 1) {
34117
+ let response;
34118
+ try {
34119
+ const headers = new Headers(init.headers);
34120
+ if (apiToken)
34121
+ headers.set("Authorization", `Bearer ${apiToken}`);
34122
+ response = await config2.fetch(url2, {
34123
+ ...init,
34124
+ headers,
34125
+ signal: AbortSignal.timeout(options.timeoutMs ?? timeoutMs)
34126
+ });
34127
+ } catch (error49) {
34128
+ if (attempt + 1 < tries) {
34129
+ await waitForRetry();
34130
+ continue;
34131
+ }
34132
+ throw error49;
34133
+ }
34134
+ const responseBody = await response.text();
34135
+ if (response.ok)
34136
+ return responseBody;
34137
+ const error48 = new EnvoyApiError({
34138
+ method: init.method ?? "GET",
34139
+ url: url2,
34140
+ status: response.status,
34141
+ responseBody
34142
+ });
34143
+ if (response.status >= 500 && attempt + 1 < tries) {
34144
+ await waitForRetry();
34145
+ continue;
34146
+ }
34147
+ throw error48;
34148
+ }
34149
+ throw new Error("Envoy request exhausted retries");
33870
34150
  };
33871
- }
33872
-
33873
- // ../envoy-client/src/slack-post.ts
33874
- import { BlockList, isIP } from "net";
33875
- var SLACK_BOT_TOKEN_SECRET = "LEGION_SLACK_BOT_TOKEN";
33876
- var SLACK_POST_API_URL_VARIABLE = "SLACK_POST_API_URL";
33877
- var POST_TIMEOUT_MS = 30000;
33878
- var SLACK_ERROR_CODES = [
33879
- "access_denied",
33880
- "accesslimited",
33881
- "account_inactive",
33882
- "agent_prompt_display_not_allowed",
33883
- "app_access_restricted",
33884
- "as_user_not_supported",
33885
- "attachment_payload_limit_exceeded",
33886
- "cannot_reply_to_message",
33887
- "channel_not_found",
33888
- "deprecated_endpoint",
33889
- "draft_already_deleted",
33890
- "draft_already_sent",
33891
- "draft_has_conflict",
33892
- "draft_not_found",
34151
+ const post = (path2, body, options) => request(path2, {
34152
+ method: "POST",
34153
+ headers: { "Content-Type": "application/json" },
34154
+ body: JSON.stringify(body)
34155
+ }, options);
34156
+ return {
34157
+ subscribe: async (input) => InterestWireSchema.parse(JSON.parse(await post("/v1/interests/subscribe", {
34158
+ session_id: input.sessionID,
34159
+ dir: input.directory,
34160
+ topics: expandSubscriptionTopics(input.topics),
34161
+ port: input.port,
34162
+ title: input.title,
34163
+ ...input.capabilities === undefined ? {} : { capabilities: input.capabilities },
34164
+ driving: input.driving,
34165
+ ...input.selfSubscribed === undefined ? {} : { self_subscribed: input.selfSubscribed },
34166
+ host: machineID()
34167
+ }))),
34168
+ unsubscribe: async (input) => {
34169
+ await post("/v1/interests/unsubscribe", {
34170
+ session_id: input.sessionID,
34171
+ topics: expandSubscriptionTopics(input.topics)
34172
+ });
34173
+ },
34174
+ getInterest: async (sessionID) => InterestWireSchema.parse(JSON.parse(await request(`/v1/interests/${sessionID}`, {}))),
34175
+ send: async (input) => {
34176
+ const idempotencyKey = input.idempotencyKey ?? crypto.randomUUID();
34177
+ const response = EnvelopeResponseSchema.parse(JSON.parse(await post("/v1/messages/send", {
34178
+ source: input.source ?? "agent",
34179
+ ...sourceSession(input.sourceSessionID),
34180
+ target_session: input.targetSessionID,
34181
+ message: input.message,
34182
+ idempotency_key: idempotencyKey,
34183
+ ...messageMetadata(input)
34184
+ })));
34185
+ return {
34186
+ envelope: response,
34187
+ recipient: response.recipient ?? input.targetSessionID,
34188
+ confirmed: response.recipient !== undefined
34189
+ };
34190
+ },
34191
+ publish: async (input) => {
34192
+ const idempotencyKey = input.idempotencyKey ?? crypto.randomUUID();
34193
+ const response = EnvelopeResponseSchema.parse(JSON.parse(await post("/v1/messages/publish", {
34194
+ source: input.source ?? "agent",
34195
+ ...sourceSession(input.sourceSessionID),
34196
+ topic: input.topic,
34197
+ message: input.message,
34198
+ ...input.payload === undefined ? {} : { payload: input.payload },
34199
+ idempotency_key: idempotencyKey,
34200
+ ...messageMetadata(input)
34201
+ })));
34202
+ return {
34203
+ envelope: response,
34204
+ ...response.holder === undefined ? {} : { holder: response.holder }
34205
+ };
34206
+ },
34207
+ unregisterSession: async (sessionID) => {
34208
+ await request(`/v1/sessions/${encodeURIComponent(sessionID)}`, { method: "DELETE" });
34209
+ },
34210
+ setRole: async (input) => {
34211
+ const soft = input.soft === true;
34212
+ const previous = soft ? input.previousSessionID ?? "" : "";
34213
+ const body = {
34214
+ session_id: input.sessionID,
34215
+ role: input.role,
34216
+ ...soft ? { soft: true } : {},
34217
+ ...previous === "" ? {} : { previous_session_id: previous }
34218
+ };
34219
+ let raw;
34220
+ try {
34221
+ raw = await post("/v1/roles/set", body);
34222
+ } catch (error48) {
34223
+ if (error48 instanceof EnvoyApiError && error48.details.status === 409) {
34224
+ const held = RoleHeldWireSchema.safeParse(JSON.parse(error48.details.responseBody));
34225
+ if (held.success)
34226
+ return { claimed: false, holder: held.data.holder };
34227
+ }
34228
+ throw error48;
34229
+ }
34230
+ return { claimed: true, interest: InterestWireSchema.parse(JSON.parse(raw)) };
34231
+ },
34232
+ getRole: async (role) => RoleWireSchema.parse(JSON.parse(await request(`/v1/roles/${encodeURIComponent(role)}`, { method: "GET" }))),
34233
+ listSessions: async (input = {}) => {
34234
+ const search = new URLSearchParams;
34235
+ if (input.directory !== undefined)
34236
+ search.set("dir", input.directory);
34237
+ if (input.title !== undefined)
34238
+ search.set("title", input.title);
34239
+ const query = search.size === 0 ? "" : `?${search.toString()}`;
34240
+ return SessionWireSchema.array().parse(JSON.parse(await request(`/v1/sessions${query}`, {})));
34241
+ },
34242
+ replay: async (input) => ReplayWireSchema.parse(JSON.parse(await post("/v1/replay", {
34243
+ session_id: input.sessionID,
34244
+ subjects: input.subjects.map((cursor) => cursor.after === undefined ? { subject: cursor.subject } : { subject: cursor.subject, after: cursor.after }),
34245
+ ...input.maxMessages === undefined ? {} : { max_messages: input.maxMessages }
34246
+ }, { timeoutMs: REPLAY_TIMEOUT_MS, retry: false })))
34247
+ };
34248
+ }
34249
+ function waitForRetry() {
34250
+ const { promise: promise2, resolve: resolve2 } = Promise.withResolvers();
34251
+ setTimeout(resolve2, RETRY_DELAY_MS);
34252
+ return promise2;
34253
+ }
34254
+ function messageMetadata(input) {
34255
+ return {
34256
+ ...input.inReplyTo === undefined ? {} : { in_reply_to: input.inReplyTo },
34257
+ ...input.supersedes === undefined ? {} : { supersedes: input.supersedes },
34258
+ ...input.urgency === undefined ? {} : { urgency: input.urgency },
34259
+ ...input.expectsReply === undefined ? {} : { expects_reply: input.expectsReply },
34260
+ ...input.expiresAt === undefined ? {} : { expires_at: input.expiresAt }
34261
+ };
34262
+ }
34263
+ function sourceSession(sessionID) {
34264
+ return sessionID === undefined || sessionID === "" ? {} : { source_session: sessionID };
34265
+ }
34266
+
34267
+ // ../envoy-client/src/replay.ts
34268
+ var REPLAY_LEDGER_TTL_MS = DELIVERY_DUPLICATE_WINDOW_MS;
34269
+ var REPLAY_LEDGER_LIMIT = 20000;
34270
+ var REPLAY_PAGES_PER_SWEEP = 20;
34271
+ var REPLAY_FAILURES_BEFORE_NOTICE = 3;
34272
+ var REPLAY_STATE_REFRESH_MS = 60 * 60 * 1000;
34273
+ var REPLAY_MAX_SUBJECTS = 32;
34274
+ var ROLE_FORWARD_KEY_PREFIX = "envoy.role.forward.";
34275
+ var ReplayLedgerEntrySchema = exports_external.object({
34276
+ event_id: exports_external.string().min(1).optional(),
34277
+ dedupe_key: exports_external.string().min(1).optional(),
34278
+ at: exports_external.number()
34279
+ });
34280
+ var ReplayCursorSchema = exports_external.object({
34281
+ since: exports_external.number().int().nonnegative().optional(),
34282
+ after: exports_external.number().int().nonnegative().optional()
34283
+ });
34284
+ var ReplayPendingNoticeSchema = exports_external.enum([
34285
+ "retention_gap",
34286
+ "stream_moved_back",
34287
+ "stream_recreated"
34288
+ ]);
34289
+ var PENDING_NOTICE_MESSAGES = {
34290
+ stream_recreated: "Envoy's notification stream was recreated, so messages published to this session while its connection was down before that may be lost.",
34291
+ stream_moved_back: "Envoy's notification stream was restored to an earlier point, so messages published to this session while its connection was down may be shown again, and any published between that point and the restore are missing.",
34292
+ retention_gap: "The notification stream no longer holds some messages published to this session while its connection was down: messages older than 72 hours may be missing."
34293
+ };
34294
+ var ReplayStateSchema = exports_external.object({
34295
+ stream_id: exports_external.string().optional(),
34296
+ stream_created: exports_external.string().optional(),
34297
+ subjects: exports_external.record(exports_external.string(), ReplayCursorSchema),
34298
+ notices: exports_external.array(exports_external.string()).optional()
34299
+ });
34300
+ var ReplaySnapshotSchema = exports_external.object({
34301
+ state: ReplayStateSchema.optional(),
34302
+ ledger: exports_external.array(ReplayLedgerEntrySchema)
34303
+ });
34304
+ function createReplayEngine(options) {
34305
+ const { host, transport, dedupe } = options;
34306
+ const now = options.now ?? Date.now;
34307
+ const ledger = createLedger(now);
34308
+ const cursors = new Map;
34309
+ const cursorStarts = new Map;
34310
+ let streamID;
34311
+ let streamCreated;
34312
+ const pending = new Set;
34313
+ const failures = new Map;
34314
+ let unwritten = [];
34315
+ let writtenState;
34316
+ let writtenShape;
34317
+ let writtenAt;
34318
+ let writes = Promise.resolve();
34319
+ let epoch = 0;
34320
+ let listenerNoticed;
34321
+ const answered = new Set;
34322
+ let running;
34323
+ let rerun;
34324
+ const safely = (what, call) => {
34325
+ try {
34326
+ call();
34327
+ } catch (error48) {
34328
+ try {
34329
+ host.log(`replay: ${what} failed`, error48);
34330
+ } catch {}
34331
+ }
34332
+ };
34333
+ const log = (message, error48) => safely("log", () => host.log(message, error48));
34334
+ const notify = (notice) => safely("notice", () => host.notify(notice));
34335
+ const tell = (kind) => {
34336
+ pending.delete(kind);
34337
+ notify({ kind, message: PENDING_NOTICE_MESSAGES[kind] });
34338
+ };
34339
+ const sessionRead = (read) => () => {
34340
+ try {
34341
+ return read();
34342
+ } catch {
34343
+ return;
34344
+ }
34345
+ };
34346
+ const currentSession = sessionRead(() => host.sessionID());
34347
+ const writeSession = sessionRead(() => host.writeSessionID === undefined ? host.sessionID() : host.writeSessionID());
34348
+ const bindTo = (sessionID, read) => {
34349
+ if (sessionID === undefined || sessionID === "" || read() !== sessionID)
34350
+ return;
34351
+ const bound = epoch;
34352
+ return { sessionID, alive: () => bound === epoch && read() === sessionID };
34353
+ };
34354
+ const bind = () => bindTo(currentSession(), currentSession);
34355
+ const stateJSON = (afters = true) => {
34356
+ const subjects = {};
34357
+ for (const subject2 of [...cursors.keys()].sort()) {
34358
+ const cursor = cursors.get(subject2) ?? {};
34359
+ subjects[subject2] = {
34360
+ ...cursor.since === undefined ? {} : { since: cursor.since },
34361
+ ...!afters || cursor.after === undefined ? {} : { after: cursor.after }
34362
+ };
34363
+ }
34364
+ return JSON.stringify({
34365
+ ...streamID === undefined ? {} : { stream_id: streamID },
34366
+ ...streamCreated === undefined ? {} : { stream_created: streamCreated },
34367
+ subjects,
34368
+ ...pending.size === 0 ? {} : { notices: [...pending].sort() }
34369
+ });
34370
+ };
34371
+ const record2 = (identity) => {
34372
+ const entry = ledger.record(identity);
34373
+ if (entry !== undefined)
34374
+ unwritten.push(entry);
34375
+ };
34376
+ const flush = (alive, atOnce = false) => {
34377
+ writes = writes.then(async () => {
34378
+ if (!alive())
34379
+ return;
34380
+ const json2 = stateJSON();
34381
+ const delivered = unwritten;
34382
+ if (json2 === writtenState && delivered.length === 0)
34383
+ return;
34384
+ const shape = stateJSON(false);
34385
+ if (delivered.length === 0 && !atOnce && shape === writtenShape && writtenAt !== undefined && now() - writtenAt < REPLAY_STATE_REFRESH_MS) {
34386
+ return;
34387
+ }
34388
+ unwritten = [];
34389
+ const state = json2 === writtenState ? undefined : JSON.parse(json2);
34390
+ try {
34391
+ await host.write({
34392
+ delivered,
34393
+ state,
34394
+ snapshot: () => ({ state: JSON.parse(json2), ledger: ledger.list() })
34395
+ });
34396
+ if (state !== undefined) {
34397
+ writtenState = json2;
34398
+ writtenShape = shape;
34399
+ writtenAt = now();
34400
+ }
34401
+ } catch (error48) {
34402
+ unwritten = [...delivered, ...unwritten];
34403
+ log("replay: could not persist the replay state; the next write carries it", error48);
34404
+ }
34405
+ });
34406
+ return writes;
34407
+ };
34408
+ const syncFollowed = () => {
34409
+ const followed = new Set(host.followedSubjects());
34410
+ for (const subject2 of [...cursors.keys()]) {
34411
+ if (!followed.has(subject2)) {
34412
+ cursors.delete(subject2);
34413
+ cursorStarts.delete(subject2);
34414
+ }
34415
+ }
34416
+ for (const subject2 of followed) {
34417
+ if (!cursors.has(subject2))
34418
+ cursors.set(subject2, {});
34419
+ }
34420
+ };
34421
+ const failureNotice = (envelope2, publishedAt, error48, subject2) => ({
34422
+ eventId: envelope2.event_id ?? "unknown",
34423
+ sender: senderLabel(envelope2),
34424
+ summary: envelope2.payload_summary ?? "unknown",
34425
+ publishedAt,
34426
+ error: error48,
34427
+ readWith: envelope2.source === "dispatch" ? "dispatch read" : "envoy_inbox",
34428
+ ...subject2 === undefined ? {} : { subject: subject2 },
34429
+ envelope: envelope2
34430
+ });
34431
+ const showFailureNotice = async (notice, alive) => {
34432
+ let queued;
34433
+ try {
34434
+ queued = await host.showFailureNotice(notice) === "queued";
34435
+ } catch (error48) {
34436
+ if (!alive())
34437
+ return "stopped";
34438
+ safely("failure notice warning", () => host.failureNoticeFailed(notice, error48));
34439
+ return "hole";
34440
+ }
34441
+ if (!alive())
34442
+ return "stopped";
34443
+ if (queued)
34444
+ return "hole";
34445
+ record2(replayLedgerIdentity(notice.envelope));
34446
+ await flush(alive);
34447
+ return "done";
34448
+ };
34449
+ const handle = async (seq, buffered, alive) => {
34450
+ const { message } = buffered;
34451
+ const envelope2 = parseEnvelope(message.data);
34452
+ if (envelope2 === undefined) {
34453
+ log(`replay: skipping stored message ${seq} on ${message.subject}: not an Envoy envelope`);
34454
+ return "done";
34455
+ }
34456
+ if (isRoleForward(envelope2))
34457
+ return "done";
34458
+ const identity = replayLedgerIdentity(envelope2);
34459
+ if (ledger.has(identity)) {
34460
+ failures.delete(seq);
34461
+ return "done";
34462
+ }
34463
+ if (dedupe?.pending(envelope2) === true)
34464
+ return "hole";
34465
+ if (!alive())
34466
+ return "stopped";
34467
+ const giveUp = async (error49) => {
34468
+ const handled = await showFailureNotice(failureNotice(envelope2, message.time, error49, message.subject), alive);
34469
+ if (handled === "done")
34470
+ failures.delete(seq);
34471
+ return handled;
34472
+ };
34473
+ const failure = failures.get(seq);
34474
+ if (failure !== undefined && failure.count >= REPLAY_FAILURES_BEFORE_NOTICE) {
34475
+ return giveUp(failure.error);
34476
+ }
34477
+ const followed = buffered.subjects[0] ?? message.subject;
34478
+ let outcome;
34479
+ let error48 = "the host could not show it";
34480
+ try {
34481
+ outcome = await host.deliver({
34482
+ envelope: envelope2,
34483
+ data: message.data,
34484
+ seq,
34485
+ subject: message.subject,
34486
+ followed,
34487
+ time: message.time,
34488
+ since: cursors.get(followed)?.since
34489
+ });
34490
+ } catch (thrown) {
34491
+ outcome = "failed";
34492
+ error48 = messageFor(thrown);
34493
+ }
34494
+ if (!alive())
34495
+ return "stopped";
34496
+ if (outcome === "shown") {
34497
+ failures.delete(seq);
34498
+ record2(identity);
34499
+ await flush(alive);
34500
+ return "done";
34501
+ }
34502
+ if (outcome === "suppressed") {
34503
+ failures.delete(seq);
34504
+ return "done";
34505
+ }
34506
+ if (outcome === "queued") {
34507
+ failures.delete(seq);
34508
+ return "hole";
34509
+ }
34510
+ const count = (failure?.count ?? 0) + 1;
34511
+ failures.set(seq, { count, error: error48 });
34512
+ if (count >= REPLAY_FAILURES_BEFORE_NOTICE)
34513
+ return giveUp(error48);
34514
+ log(`replay: could not show stored message ${seq} (${envelope2.event_id}): ${error48}`);
34515
+ return "hole";
34516
+ };
34517
+ const listenerFailed = (error48) => {
34518
+ if (error48 instanceof EnvoyApiError) {
34519
+ const status = error48.details.status;
34520
+ if (status === 404) {
34521
+ if (listenerNoticed === "not_served")
34522
+ return;
34523
+ listenerNoticed = "not_served";
34524
+ notify({
34525
+ kind: "not_served",
34526
+ message: "This session's Envoy listener does not serve replay (POST /v1/replay answered 404), so messages published while its connection is down are not recovered."
34527
+ });
34528
+ return;
34529
+ }
34530
+ if (status === 503 && error48.code === REPLAY_UNAVAILABLE_CODE || status === 401 || status === 403) {
34531
+ const key = `unavailable:${status}:${error48.message}`;
34532
+ if (listenerNoticed === key)
34533
+ return;
34534
+ listenerNoticed = key;
34535
+ notify({
34536
+ kind: "unavailable",
34537
+ status,
34538
+ error: error48.message,
34539
+ message: `Envoy replay is unavailable (${status}: ${error48.message}), so messages published while this session's connection is down are not recovered until it answers.`
34540
+ });
34541
+ return;
34542
+ }
34543
+ }
34544
+ log("replay: the listener's replay failed; the next trigger tries again", error48);
34545
+ };
34546
+ const streamReplaced = (stream) => {
34547
+ if (stream.id === undefined) {
34548
+ return streamCreated !== undefined && streamCreated !== "" && stream.created !== streamCreated;
34549
+ }
34550
+ return streamID !== undefined && streamID !== "" && stream.id !== streamID;
34551
+ };
34552
+ const streamMovedBack = (stream) => {
34553
+ for (const cursor of cursors.values()) {
34554
+ if (cursor.after !== undefined && cursor.after > stream.last_seq)
34555
+ return true;
34556
+ }
34557
+ return false;
34558
+ };
34559
+ const sweepOnce = async () => {
34560
+ const binding = bind();
34561
+ if (binding === undefined)
34562
+ return;
34563
+ const { sessionID, alive } = binding;
34564
+ syncFollowed();
34565
+ const readings = new Map;
34566
+ for (const [subject2, cursor] of cursors) {
34567
+ readings.set(subject2, { read: cursor.after, more: true });
34568
+ }
34569
+ const buffer = new Map;
34570
+ const holes = new Map;
34571
+ let gapNoticed = false;
34572
+ if (pending.size > 0) {
34573
+ for (const kind of [...pending].sort()) {
34574
+ if (kind === "retention_gap")
34575
+ gapNoticed = true;
34576
+ tell(kind);
34577
+ }
34578
+ await flush(alive);
34579
+ if (!alive())
34580
+ return;
34581
+ }
34582
+ for (let page = 0;page < REPLAY_PAGES_PER_SWEEP; page += 1) {
34583
+ let handledAny = false;
34584
+ const asking = [...readings].filter(([, reading]) => reading.more).sort(([, a], [, b]) => (a.read ?? -1) - (b.read ?? -1)).slice(0, REPLAY_MAX_SUBJECTS);
34585
+ if (asking.length === 0)
34586
+ break;
34587
+ let response;
34588
+ try {
34589
+ response = await transport.replay({
34590
+ sessionID,
34591
+ subjects: asking.map(([subject2, reading]) => reading.read === undefined ? { subject: subject2 } : { subject: subject2, after: reading.read }),
34592
+ ...options.maxMessages === undefined ? {} : { maxMessages: options.maxMessages }
34593
+ });
34594
+ } catch (error48) {
34595
+ if (alive()) {
34596
+ answered.clear();
34597
+ listenerFailed(error48);
34598
+ }
34599
+ return;
34600
+ }
34601
+ if (!alive())
34602
+ return;
34603
+ listenerNoticed = undefined;
34604
+ for (const result of response.subjects) {
34605
+ if (result.refused === undefined)
34606
+ answered.add(result.subject);
34607
+ else
34608
+ answered.delete(result.subject);
34609
+ }
34610
+ const { stream } = response;
34611
+ const replaced = streamReplaced(stream);
34612
+ streamID = stream.id ?? (replaced ? undefined : streamID);
34613
+ streamCreated = stream.created;
34614
+ if (replaced) {
34615
+ const at = now();
34616
+ for (const subject2 of cursors.keys()) {
34617
+ cursors.set(subject2, { since: stream.last_seq, after: stream.last_seq });
34618
+ cursorStarts.set(subject2, at);
34619
+ }
34620
+ failures.clear();
34621
+ pending.add("stream_recreated");
34622
+ await flush(alive);
34623
+ if (!alive())
34624
+ return;
34625
+ tell("stream_recreated");
34626
+ await flush(alive);
34627
+ return;
34628
+ }
34629
+ if (streamMovedBack(stream)) {
34630
+ const from = Math.max(0, stream.first_seq - 1);
34631
+ for (const [subject2, cursor] of cursors) {
34632
+ if (cursor.after === undefined)
34633
+ continue;
34634
+ cursors.set(subject2, { ...cursor, after: from });
34635
+ const reading = readings.get(subject2);
34636
+ if (reading !== undefined) {
34637
+ reading.read = from;
34638
+ reading.more = true;
34639
+ }
34640
+ }
34641
+ buffer.clear();
34642
+ holes.clear();
34643
+ failures.clear();
34644
+ pending.add("stream_moved_back");
34645
+ await flush(alive, true);
34646
+ if (!alive())
34647
+ return;
34648
+ tell("stream_moved_back");
34649
+ await flush(alive);
34650
+ if (!alive())
34651
+ return;
34652
+ continue;
34653
+ }
34654
+ for (const [, reading] of asking)
34655
+ reading.more = false;
34656
+ let gapped = false;
34657
+ for (const result of response.subjects) {
34658
+ const reading = readings.get(result.subject);
34659
+ if (reading?.read === undefined || result.refused !== undefined)
34660
+ continue;
34661
+ if (reading.read >= stream.first_seq - 1)
34662
+ continue;
34663
+ gapped = true;
34664
+ reading.read = stream.first_seq - 1;
34665
+ const cursor = cursors.get(result.subject);
34666
+ if (cursor?.after !== undefined && cursor.after < reading.read) {
34667
+ cursors.set(result.subject, { ...cursor, after: reading.read });
34668
+ }
34669
+ }
34670
+ if (gapped) {
34671
+ if (!gapNoticed)
34672
+ pending.add("retention_gap");
34673
+ await flush(alive, true);
34674
+ if (!alive())
34675
+ return;
34676
+ if (pending.has("retention_gap")) {
34677
+ gapNoticed = true;
34678
+ tell("retention_gap");
34679
+ await flush(alive);
34680
+ }
34681
+ }
34682
+ for (const result of response.subjects) {
34683
+ const reading = readings.get(result.subject);
34684
+ if (reading === undefined || result.refused !== undefined)
34685
+ continue;
34686
+ if (reading.read === undefined) {
34687
+ const cursor = cursors.get(result.subject);
34688
+ if (cursor !== undefined && cursor.after === undefined) {
34689
+ cursors.set(result.subject, { since: result.next_after, after: result.next_after });
34690
+ cursorStarts.set(result.subject, now());
34691
+ }
34692
+ reading.read = result.next_after;
34693
+ continue;
34694
+ }
34695
+ for (const message of result.messages) {
34696
+ if (message.seq <= reading.read)
34697
+ continue;
34698
+ const buffered = buffer.get(message.seq);
34699
+ if (buffered === undefined) {
34700
+ buffer.set(message.seq, { message, subjects: [result.subject] });
34701
+ } else if (!buffered.subjects.includes(result.subject)) {
34702
+ buffered.subjects.push(result.subject);
34703
+ }
34704
+ }
34705
+ reading.read = Math.max(reading.read, result.next_after);
34706
+ reading.more = result.more;
34707
+ }
34708
+ let bound = Number.POSITIVE_INFINITY;
34709
+ for (const reading of readings.values()) {
34710
+ if (reading.more && reading.read !== undefined)
34711
+ bound = Math.min(bound, reading.read);
34712
+ }
34713
+ const ready = [...buffer.keys()].filter((seq) => seq <= bound).sort((a, b) => a - b);
34714
+ for (const seq of ready) {
34715
+ const buffered = buffer.get(seq);
34716
+ if (buffered === undefined)
34717
+ continue;
34718
+ buffer.delete(seq);
34719
+ if (!buffered.subjects.some((subject2) => cursors.has(subject2)))
34720
+ continue;
34721
+ const handled = await handle(seq, buffered, alive);
34722
+ if (handled === "stopped")
34723
+ return;
34724
+ if (handled === "done")
34725
+ handledAny = true;
34726
+ if (handled === "hole") {
34727
+ for (const subject2 of buffered.subjects) {
34728
+ if (!holes.has(subject2))
34729
+ holes.set(subject2, seq);
34730
+ }
34731
+ }
34732
+ }
34733
+ if (!alive())
34734
+ return;
34735
+ for (const [subject2, reading] of readings) {
34736
+ const cursor = cursors.get(subject2);
34737
+ if (cursor?.after === undefined || reading.read === undefined)
34738
+ continue;
34739
+ let after = Math.min(reading.read, bound);
34740
+ const hole = holes.get(subject2);
34741
+ if (hole !== undefined)
34742
+ after = Math.min(after, hole - 1);
34743
+ if (after > cursor.after)
34744
+ cursors.set(subject2, { ...cursor, after });
34745
+ }
34746
+ await flush(alive, handledAny);
34747
+ if (![...readings.values()].some((reading) => reading.more))
34748
+ break;
34749
+ }
34750
+ };
34751
+ const runSweep = async () => {
34752
+ try {
34753
+ await sweepOnce();
34754
+ } catch (error48) {
34755
+ log("replay: a sweep failed", error48);
34756
+ }
34757
+ };
34758
+ const sweep = () => {
34759
+ if (running === undefined) {
34760
+ running = runSweep().finally(() => {
34761
+ running = undefined;
34762
+ });
34763
+ return running;
34764
+ }
34765
+ rerun ??= running.then(() => {
34766
+ rerun = undefined;
34767
+ return sweep();
34768
+ });
34769
+ return rerun;
34770
+ };
34771
+ return {
34772
+ sweep,
34773
+ async followedChanged() {
34774
+ const alive = bind()?.alive;
34775
+ if (alive === undefined)
34776
+ return;
34777
+ try {
34778
+ syncFollowed();
34779
+ await flush(alive);
34780
+ } catch (error48) {
34781
+ log("replay: could not take the followed subjects", error48);
34782
+ }
34783
+ },
34784
+ delivered: (frame) => ledger.has(replayLedgerIdentity(frame)),
34785
+ async recordDelivered(frame) {
34786
+ const alive = bind()?.alive;
34787
+ if (alive === undefined)
34788
+ return;
34789
+ record2(replayLedgerIdentity(frame));
34790
+ await flush(alive);
34791
+ },
34792
+ async recordDeliveredFor(sessionID, frame) {
34793
+ const alive = bindTo(sessionID, writeSession)?.alive;
34794
+ if (alive === undefined)
34795
+ return;
34796
+ record2(replayLedgerIdentity(frame));
34797
+ await flush(alive);
34798
+ },
34799
+ async liveFailed(followed, envelope2, error48, receivedAt) {
34800
+ const started = cursorStarts.get(followed);
34801
+ if (!isRoleForward(envelope2) && answered.has(followed) && cursors.get(followed)?.after !== undefined && (started === undefined || started <= receivedAt)) {
34802
+ return;
34803
+ }
34804
+ const alive = bind()?.alive;
34805
+ if (alive === undefined)
34806
+ return;
34807
+ try {
34808
+ await showFailureNotice(failureNotice(envelope2, inboundTimestamp(envelope2.issued_at), messageFor(error48)), alive);
34809
+ } catch (thrown) {
34810
+ log("replay: could not report a failed live frame", thrown);
34811
+ }
34812
+ },
34813
+ followedBefore: (topic, seq) => {
34814
+ const since = cursors.get(topic)?.since;
34815
+ return since !== undefined && seq > since;
34816
+ },
34817
+ restore(snapshot) {
34818
+ epoch += 1;
34819
+ ledger.restore(snapshot.ledger);
34820
+ cursors.clear();
34821
+ cursorStarts.clear();
34822
+ streamID = snapshot.state?.stream_id;
34823
+ streamCreated = snapshot.state?.stream_created;
34824
+ pending.clear();
34825
+ for (const kind of snapshot.state?.notices ?? []) {
34826
+ const known = ReplayPendingNoticeSchema.safeParse(kind);
34827
+ if (known.success)
34828
+ pending.add(known.data);
34829
+ }
34830
+ for (const [subject2, cursor] of Object.entries(snapshot.state?.subjects ?? {})) {
34831
+ cursors.set(subject2, { ...cursor });
34832
+ }
34833
+ writtenState = snapshot.state === undefined ? undefined : stateJSON();
34834
+ writtenShape = snapshot.state === undefined ? undefined : stateJSON(false);
34835
+ writtenAt = undefined;
34836
+ unwritten = [];
34837
+ failures.clear();
34838
+ listenerNoticed = undefined;
34839
+ answered.clear();
34840
+ },
34841
+ state: () => JSON.parse(stateJSON())
34842
+ };
34843
+ }
34844
+ function replaySuppressed(rendered) {
34845
+ return rendered.skip || rendered.malformedDelivery === true;
34846
+ }
34847
+ function replayedText(content, publishedAt) {
34848
+ return `${content}
34849
+ Published at ${publishedAt} while this session's connection was down.`;
34850
+ }
34851
+ function failureNoticeFields(notice) {
34852
+ const readWith = notice.readWith === "dispatch read" ? "Read it with the `dispatch read` command on the issue or ask it concerns." : "Read it with the envoy_inbox tool.";
34853
+ return {
34854
+ notice: "message not shown",
34855
+ event_id: notice.eventId,
34856
+ from: notice.sender,
34857
+ summary: notice.summary,
34858
+ published_at: notice.publishedAt,
34859
+ ...notice.subject === undefined ? {} : { subject: notice.subject },
34860
+ error: notice.error,
34861
+ detail: `This session could not be shown this message, so it is not coming back on its own. ${readWith}`
34862
+ };
34863
+ }
34864
+ var REPLAY_NOTICE_NAMES = {
34865
+ stream_recreated: "stream recreated",
34866
+ stream_moved_back: "stream moved back"
34867
+ };
34868
+ function replayNoticeFields(notice) {
34869
+ return {
34870
+ notice: REPLAY_NOTICE_NAMES[notice.kind] ?? "messages may be missing",
34871
+ detail: notice.message
34872
+ };
34873
+ }
34874
+ function envoyNoticeText(fields) {
34875
+ return encode3({ envoy: fields });
34876
+ }
34877
+ var EXCEPTION_TOPIC_PREFIX = "notifications.envoy.exceptions.";
34878
+ var PRIVATE_STREAM_SUBJECTS = [
34879
+ `${AGENT_TOPIC_PREFIX}>`,
34880
+ `${LEGION_NOTICE_TOPIC_PREFIX}>`,
34881
+ `${EXCEPTION_TOPIC_PREFIX}${AGENT_TOPIC_PREFIX}>`
34882
+ ];
34883
+ function subjectsOverlap(a, b) {
34884
+ const aTokens = a.split(".");
34885
+ const bTokens = b.split(".");
34886
+ for (let index = 0;index < aTokens.length && index < bTokens.length; index += 1) {
34887
+ const aToken = aTokens[index];
34888
+ const bToken = bTokens[index];
34889
+ if (aToken === ">" || bToken === ">")
34890
+ return true;
34891
+ if (aToken !== "*" && bToken !== "*" && aToken !== bToken)
34892
+ return false;
34893
+ }
34894
+ return aTokens.length === bTokens.length;
34895
+ }
34896
+ function reachesPrivateStreamSubject(ownAgentSubject, topic) {
34897
+ if (!PRIVATE_STREAM_SUBJECTS.some((subject2) => subjectsOverlap(topic, subject2)))
34898
+ return false;
34899
+ return topic !== ownAgentSubject || /[*>]/.test(ownAgentSubject);
34900
+ }
34901
+ function replayFollowedSubjects(ownAgentSubject, topics, heldForRole = () => false) {
34902
+ const followed = [...topics].filter((topic) => !topic.startsWith(ROLE_TOPIC_PREFIX) && !reachesPrivateStreamSubject(ownAgentSubject, topic) && !heldForRole(topic));
34903
+ return [...new Set([ownAgentSubject, ...followed])];
34904
+ }
34905
+ function rememberedTopics(state) {
34906
+ return Object.keys(state?.subjects ?? {}).filter((topic) => !topic.startsWith(AGENT_TOPIC_PREFIX) && !topic.startsWith(ROLE_TOPIC_PREFIX));
34907
+ }
34908
+ async function closeReplayedRemoval(frame, host) {
34909
+ const closed = (subscriptionRemovedTopics(frame.data, host.sessionID) ?? []).filter((topic) => host.engine.followedBefore(topic, frame.seq) && host.close(topic));
34910
+ if (closed.length === 0)
34911
+ return closed;
34912
+ const unregistering = host.unregister(closed);
34913
+ await host.followedChanged();
34914
+ await unregistering;
34915
+ return closed;
34916
+ }
34917
+ function routeReplayNotice(notice, routes) {
34918
+ if (notice.kind === "not_served" || notice.kind === "unavailable") {
34919
+ routes.warn(notice.message);
34920
+ return;
34921
+ }
34922
+ routes.card(envoyNoticeText(replayNoticeFields(notice)));
34923
+ }
34924
+ function isRoleForward(envelope2) {
34925
+ return envelope2.dedupe_key?.startsWith(ROLE_FORWARD_KEY_PREFIX) === true || envelope2.topic?.startsWith(ROLE_TOPIC_PREFIX) === true;
34926
+ }
34927
+ function replayLedgerIdentity(frame) {
34928
+ return {
34929
+ ...frame.event_id === undefined || frame.event_id === "" ? {} : { event_id: frame.event_id },
34930
+ ...frame.dedupe_key === undefined || !dedupeKeyNamesItsEvent(frame) ? {} : { dedupe_key: frame.dedupe_key }
34931
+ };
34932
+ }
34933
+ function parseEnvelope(data) {
34934
+ let parsed;
34935
+ try {
34936
+ parsed = JSON.parse(data);
34937
+ } catch {
34938
+ return;
34939
+ }
34940
+ const result = EnvelopeSchema.safeParse(parsed);
34941
+ return result.success ? result.data : undefined;
34942
+ }
34943
+ function createLedger(now) {
34944
+ let entries = new Set;
34945
+ const byEvent = new Map;
34946
+ const byKey = new Map;
34947
+ const drop = (entry) => {
34948
+ entries.delete(entry);
34949
+ if (entry.event_id !== undefined && byEvent.get(entry.event_id) === entry) {
34950
+ byEvent.delete(entry.event_id);
34951
+ }
34952
+ if (entry.dedupe_key !== undefined && byKey.get(entry.dedupe_key) === entry) {
34953
+ byKey.delete(entry.dedupe_key);
34954
+ }
34955
+ };
34956
+ const add = (entry) => {
34957
+ if (entries.size >= REPLAY_LEDGER_LIMIT) {
34958
+ const oldest = entries.values().next();
34959
+ if (oldest.done !== true)
34960
+ drop(oldest.value);
34961
+ }
34962
+ entries.add(entry);
34963
+ if (entry.event_id !== undefined)
34964
+ byEvent.set(entry.event_id, entry);
34965
+ if (entry.dedupe_key !== undefined)
34966
+ byKey.set(entry.dedupe_key, entry);
34967
+ };
34968
+ const expire = () => {
34969
+ const at = now();
34970
+ for (const entry of entries) {
34971
+ if (at - entry.at < REPLAY_LEDGER_TTL_MS)
34972
+ break;
34973
+ drop(entry);
34974
+ }
34975
+ };
34976
+ const has = (identity) => {
34977
+ expire();
34978
+ return identity.event_id !== undefined && byEvent.has(identity.event_id) || identity.dedupe_key !== undefined && byKey.has(identity.dedupe_key);
34979
+ };
34980
+ return {
34981
+ has,
34982
+ record(identity) {
34983
+ if (identity.event_id === undefined && identity.dedupe_key === undefined)
34984
+ return;
34985
+ if (has(identity))
34986
+ return;
34987
+ const entry = { ...identity, at: now() };
34988
+ add(entry);
34989
+ return entry;
34990
+ },
34991
+ restore(restored) {
34992
+ entries = new Set;
34993
+ byEvent.clear();
34994
+ byKey.clear();
34995
+ const at = now();
34996
+ const kept = restored.filter((entry) => at - entry.at < REPLAY_LEDGER_TTL_MS && (entry.event_id !== undefined || entry.dedupe_key !== undefined)).sort((a, b) => a.at - b.at);
34997
+ for (const entry of kept)
34998
+ add({ ...entry });
34999
+ },
35000
+ list() {
35001
+ expire();
35002
+ return [...entries];
35003
+ }
35004
+ };
35005
+ }
35006
+
35007
+ // ../envoy-client/src/session-settings.ts
35008
+ function sessionConfigFile(harness, env) {
35009
+ try {
35010
+ return { path: envoyConfigPath(harness, env), error: null };
35011
+ } catch (error48) {
35012
+ return { path: null, error: messageFor(error48) };
35013
+ }
35014
+ }
35015
+ function startNotice(config2, dispatch, envoy, nats) {
35016
+ if (config2.kind === "failed")
35017
+ return `${config2.error}: Dispatch and Envoy are off`;
35018
+ const { missing, checkout } = config2;
35019
+ const dispatchQuiet = !dispatch.enabled && dispatch.error === null;
35020
+ const envoyQuiet = !envoy.enabled && envoy.error === null;
35021
+ const parts = [];
35022
+ if (missing !== null && dispatchQuiet && envoyQuiet) {
35023
+ parts.push(missingConfigNotice(config2.path, missing, "Dispatch and Envoy are off"));
35024
+ } else {
35025
+ if (!dispatch.enabled && dispatch.error !== null)
35026
+ parts.push(`Dispatch is off: ${dispatch.error}`);
35027
+ else if (dispatchQuiet && missing !== null) {
35028
+ parts.push(missingConfigNotice(config2.path, missing, "Dispatch is off"));
35029
+ }
35030
+ if (!envoy.enabled && envoy.error !== null)
35031
+ parts.push(`Envoy is off: ${envoy.error}`);
35032
+ else if (envoyQuiet && missing !== null) {
35033
+ parts.push(missingConfigNotice(config2.path, missing, "Envoy is off"));
35034
+ }
35035
+ }
35036
+ if (checkout?.kind === "valid" && checkout.envoyError !== null)
35037
+ parts.push(checkout.envoyError);
35038
+ if (checkout?.kind === "invalid" && (dispatch.enabled || dispatch.error !== checkout.error)) {
35039
+ parts.push(`${checkout.error}; not read while DISPATCH_URL is set`);
35040
+ }
35041
+ parts.push(...config2.warnings);
35042
+ if (envoy.enabled && nats && "off" in envoy.inbound) {
35043
+ parts.push(`Envoy's inbound messages are off: ${envoy.inbound.off}; the Envoy tools still work`);
35044
+ }
35045
+ if (envoy.enabled && envoy.passDeadlineRaisedFrom !== undefined) {
35046
+ parts.push(`Envoy's pass deadline is ${envoy.passDeadlineMs} ms, not the ${envoy.passDeadlineRaisedFrom} ms ENVOY_PASS_DEADLINE_MS names: a deadline inside one ${envoy.heartbeatMs} ms heartbeat interval would abandon every pass before the next tick, so the registration refresh the heartbeat posts for a stalled pass would never run`);
35047
+ }
35048
+ return parts.length === 0 ? null : parts.join("; ");
35049
+ }
35050
+ function sessionSettings(file2, env, options) {
35051
+ if (file2.path === null) {
35052
+ const off = offWithError(file2.error);
35053
+ return { dispatch: off, envoy: off, notice: `${file2.error}: Dispatch and Envoy are off` };
35054
+ }
35055
+ const config2 = readEnvoyConfig(file2.path, env, options);
35056
+ const dispatch = dispatchSettings(env, config2);
35057
+ const envoy = envoySettings(env, config2, { nats: options.nats });
35058
+ return {
35059
+ dispatch,
35060
+ envoy,
35061
+ notice: startNotice(config2, dispatch, envoy, options.nats !== false)
35062
+ };
35063
+ }
35064
+ function sessionDispatchSettings(file2, env, options) {
35065
+ if (file2.path === null)
35066
+ return { dispatch: offWithError(file2.error), warnings: [], missing: null };
35067
+ const config2 = readEnvoyConfig(file2.path, env, options);
35068
+ return {
35069
+ dispatch: dispatchSettings(env, config2),
35070
+ warnings: config2.kind === "read" ? config2.warnings : [],
35071
+ missing: config2.kind === "read" ? config2.missing : null
35072
+ };
35073
+ }
35074
+
35075
+ // ../envoy-client/src/slack-post.ts
35076
+ import { BlockList, isIP } from "net";
35077
+ var SLACK_BOT_TOKEN_SECRET = "LEGION_SLACK_BOT_TOKEN";
35078
+ var SLACK_POST_API_URL_VARIABLE = "SLACK_POST_API_URL";
35079
+ var POST_TIMEOUT_MS = 30000;
35080
+ var SLACK_ERROR_CODES = [
35081
+ "access_denied",
35082
+ "accesslimited",
35083
+ "account_inactive",
35084
+ "agent_prompt_display_not_allowed",
35085
+ "app_access_restricted",
35086
+ "as_user_not_supported",
35087
+ "attachment_payload_limit_exceeded",
35088
+ "cannot_reply_to_message",
35089
+ "channel_not_found",
35090
+ "deprecated_endpoint",
35091
+ "draft_already_deleted",
35092
+ "draft_already_sent",
35093
+ "draft_has_conflict",
35094
+ "draft_not_found",
33893
35095
  "duplicate_channel_not_found",
33894
35096
  "duplicate_message_not_found",
33895
35097
  "ekm_access_denied",
@@ -34145,402 +35347,161 @@ function posterLine(stdout) {
34145
35347
  try {
34146
35348
  const parsed = JSON.parse(last);
34147
35349
  return typeof parsed === "object" && parsed !== null ? parsed : undefined;
34148
- } catch {
34149
- return;
34150
- }
34151
- }
34152
- function allowedAPIURL(value) {
34153
- let url2;
34154
- try {
34155
- url2 = new URL(value);
34156
- } catch {
34157
- return false;
34158
- }
34159
- if (url2.protocol === "https:")
34160
- return true;
34161
- return url2.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]"].includes(url2.hostname);
34162
- }
34163
-
34164
- // ../envoy-client/src/tool-contract.ts
34165
- var DELIVERY_CONTRACT = "Delivery is at-least-once, possibly out of order across topics; use id for dedupe and at for freshness.";
34166
- 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>.";
34167
- var URGENCY_VALUES = EnvelopeSchema.shape.urgency.unwrap().options;
34168
- var EXPECTS_REPLY_VALUES = EnvelopeSchema.shape.expects_reply.unwrap().options;
34169
- function messageMetadataShape(schema) {
34170
- return {
34171
- in_reply_to: schema.string().optional(),
34172
- supersedes: schema.string().optional(),
34173
- urgency: schema.enum(URGENCY_VALUES).describe("low | med | high | blocking").optional(),
34174
- expects_reply: schema.enum(EXPECTS_REPLY_VALUES).describe("none | optional | required").optional(),
34175
- expires_at: schema.number({ int: true }).optional()
34176
- };
34177
- }
34178
- var MessageMetadataSchema = exports_external.object(messageMetadataShape(zodSchemaApi(exports_external)));
34179
- function toMessageMetadata(args) {
34180
- return {
34181
- ...args.in_reply_to === undefined ? {} : { inReplyTo: args.in_reply_to },
34182
- ...args.supersedes === undefined ? {} : { supersedes: args.supersedes },
34183
- ...args.urgency === undefined ? {} : { urgency: args.urgency },
34184
- ...args.expects_reply === undefined ? {} : { expectsReply: args.expects_reply },
34185
- ...args.expires_at === undefined ? {} : { expiresAt: args.expires_at }
34186
- };
34187
- }
34188
- function messageArguments(schema) {
34189
- return { message: schema.string(), ...messageMetadataShape(schema) };
34190
- }
34191
- var EnvoyToolOperation = {
34192
- subscribe: "subscribe",
34193
- unsubscribe: "unsubscribe",
34194
- listInterests: "listInterests",
34195
- inbox: "inbox",
34196
- send: "send",
34197
- publish: "publish",
34198
- setRole: "setRole",
34199
- getRole: "getRole",
34200
- whoami: "whoami",
34201
- listSessions: "listSessions",
34202
- slackPost: "slackPost"
34203
- };
34204
- var envoyToolSpecs = [
34205
- {
34206
- name: "envoy_subscribe",
34207
- description: `Subscribe this session to Envoy notification topics. ${TOPIC_GUIDE}`,
34208
- arguments: (schema) => ({
34209
- topics: schema.array(schema.string()).describe("NATS-style topic patterns to subscribe to.")
34210
- }),
34211
- operation: EnvoyToolOperation.subscribe
34212
- },
34213
- {
34214
- name: "envoy_unsubscribe",
34215
- description: "Unsubscribe this session from Envoy topics, or remove all current subscriptions if topics are omitted. A subscription another plugin holds for this session's role stays, and the result lists it as kept.",
34216
- arguments: (schema) => ({ topics: schema.array(schema.string()).optional() }),
34217
- operation: EnvoyToolOperation.unsubscribe
34218
- },
34219
- {
34220
- name: "envoy_list",
34221
- description: "List the current Envoy topic subscriptions for this session so you can confirm the exact topic shapes that are active.",
34222
- arguments: () => ({}),
34223
- operation: EnvoyToolOperation.listInterests
34224
- },
34225
- {
34226
- name: "envoy_inbox",
34227
- description: "List this Pi session's 50 most recent rendered Envoy deliveries, newest first.",
34228
- arguments: () => ({}),
34229
- operation: EnvoyToolOperation.inbox
34230
- },
34231
- {
34232
- name: "envoy_send",
34233
- description: `Send an Envoy agent-to-agent message directly to another session by session ID. ${DELIVERY_CONTRACT}`,
34234
- arguments: (schema) => ({
34235
- session_id: schema.string().describe("Target session ID; find it with envoy_sessions or envoy_whoami."),
34236
- ...messageArguments(schema)
34237
- }),
34238
- operation: EnvoyToolOperation.send
34239
- },
34240
- {
34241
- name: "envoy_publish",
34242
- description: `Publish an Envoy message to a notifications. topic. A role or built-in topic is delivered as its guide says; any other notifications. topic you name (a team topic such as notifications.team.deploy-squad.all) is live only: it reaches every session subscribed to it when you publish, and is not retained. A session that holds its own NATS connection receives it directly, yours included; a session the listener delivers to over a serve port, such as an OpenCode agent, receives it through its machine's listener when that listener subscribes to every topic (ENVOY_SUBSCRIBE_ALL_TOPICS=1; the shared hub's listener does not). ${DELIVERY_CONTRACT}`,
34243
- arguments: (schema) => ({ topic: schema.string(), ...messageArguments(schema) }),
34244
- operation: EnvoyToolOperation.publish
34245
- },
34246
- {
34247
- name: "envoy_role_set",
34248
- description: "Set the current session as the holder of a named role. Messages published to notifications.role.<role> route to this session. Moving to a different role is refused while another plugin holds subscriptions that last only as long as this session keeps its current role.",
34249
- arguments: (schema) => ({ role: schema.string() }),
34250
- operation: EnvoyToolOperation.setRole
34251
- },
34252
- {
34253
- name: "envoy_role_get",
34254
- description: "Get the live holder of a named Envoy role.",
34255
- arguments: (schema) => ({ role: schema.string() }),
34256
- operation: EnvoyToolOperation.getRole
34257
- },
34258
- {
34259
- name: "envoy_whoami",
34260
- description: "Returns this session's Envoy identity: session ID, machine ID, port, and directory. session_id is the address a reply reaches. Where a host runs a task subagent inside its parent's process, such a subagent registers no Envoy session of its own, so its session_id is the parent session that spawned it and the result says so.",
34261
- arguments: () => ({}),
34262
- operation: EnvoyToolOperation.whoami
34263
- },
34264
- {
34265
- name: "envoy_sessions",
34266
- description: "List all live sessions registered with Envoy. Filter by optional machine, directory, or title.",
34267
- arguments: (schema) => ({
34268
- machine: schema.string().optional(),
34269
- dir: schema.string().optional(),
34270
- title: schema.string().optional()
34271
- }),
34272
- operation: EnvoyToolOperation.listSessions
34273
- },
34274
- {
34275
- name: "slack_post",
34276
- description: "Reply in a Slack thread as the Legion Slack app, with the bot token the secrets broker grants this session (LEGION_SLACK_BOT_TOKEN); the session never holds it. channel is the Slack channel id (a mention's channel_id); thread_ts is the thread's root ts: the mention's thread_ts, or its own ts when it has none. Answers the new message's ts. A refusal carries Slack's own error code (not_in_channel: the app is not in that channel) or the broker's state (waiting for approval, denied). Sent once and never retried: after 'Slack did not answer' the reply may already be in the thread, so do not post it again.",
34277
- arguments: (schema) => ({
34278
- channel: schema.string({ min: 1 }).describe("Slack channel id, such as C0123ABCD."),
34279
- thread_ts: schema.string({ min: 1 }).describe("The thread's root ts, which keeps the reply in the mention's thread."),
34280
- text: schema.string({ min: 1, max: SLACK_POST_TEXT_MAX }).describe(`The reply, in Slack mrkdwn, at most ${SLACK_POST_TEXT_MAX} characters.`)
34281
- }),
34282
- operation: EnvoyToolOperation.slackPost
34283
- }
34284
- ];
34285
- function sendConfirmationText(result) {
34286
- return `sent ${result.envelope.event_id} to ${result.recipient}${result.confirmed ? "" : " (recipient unconfirmed by listener)"}`;
34287
- }
34288
- var envoyToolSchemas = new Map;
34289
- function parseEnvoyToolArguments(operation, parameters) {
34290
- const spec = envoyToolSpecs.find((candidate) => candidate.operation === operation);
34291
- if (spec === undefined)
34292
- throw new Error(`missing Envoy tool specification for ${operation}`);
34293
- let schema = envoyToolSchemas.get(operation);
34294
- if (schema === undefined) {
34295
- schema = exports_external.object(spec.arguments(zodSchemaApi(exports_external))).strict();
34296
- envoyToolSchemas.set(operation, schema);
34297
- }
34298
- const parsed = schema.safeParse(parameters, { reportInput: true });
34299
- if (!parsed.success) {
34300
- throw new ToolInputError(spec.name, formatZodIssues(parsed.error.issues, schema, spec.name));
34301
- }
34302
- return parsed.data;
34303
- }
34304
-
34305
- // ../envoy-client/src/transport.ts
34306
- var DEFAULT_TIMEOUT_MS = 5000;
34307
- var RETRY_DELAY_MS = 250;
34308
- var InterestWireSchema = exports_external.object({
34309
- session_id: exports_external.string(),
34310
- machine_id: exports_external.string(),
34311
- dir: exports_external.string(),
34312
- topics: exports_external.array(exports_external.string()),
34313
- updated_at: exports_external.number().int().optional(),
34314
- warnings: exports_external.array(exports_external.string()).optional()
34315
- });
34316
- var SessionWireSchema = exports_external.object({
34317
- session_id: exports_external.string(),
34318
- machine_id: exports_external.string(),
34319
- host: exports_external.string().optional(),
34320
- dir: exports_external.string(),
34321
- port: exports_external.number().int(),
34322
- title: exports_external.string(),
34323
- topics: exports_external.array(exports_external.string()),
34324
- roles: exports_external.array(exports_external.string()).optional(),
34325
- capabilities: exports_external.array(exports_external.string()).optional(),
34326
- self_subscribed: exports_external.boolean(),
34327
- last_seen: exports_external.number().int().optional()
34328
- });
34329
- var RoleWireSchema = exports_external.object({
34330
- role: exports_external.string(),
34331
- holder: exports_external.string(),
34332
- host: exports_external.string().optional(),
34333
- last_seen: exports_external.number().int()
34334
- });
34335
- var RoleHeldWireSchema = exports_external.object({
34336
- error: exports_external.string(),
34337
- role: exports_external.string(),
34338
- holder: exports_external.string()
34339
- });
34340
- var ErrorWireSchema = exports_external.object({
34341
- error: exports_external.string(),
34342
- expected: exports_external.array(exports_external.string()).optional()
34343
- });
34344
- var EnvelopeResponseSchema = EnvelopeSchema.extend({
34345
- recipient: exports_external.string().optional(),
34346
- holder: exports_external.string().optional()
34347
- });
34348
- function mergeInterestSources(registryTopics, liveTopics) {
34349
- const interests = new Map;
34350
- for (const topic of registryTopics) {
34351
- interests.set(topic, liveTopics.includes(topic) ? "both" : "registry");
34352
- }
34353
- for (const topic of liveTopics) {
34354
- if (!interests.has(topic))
34355
- interests.set(topic, "live");
35350
+ } catch {
35351
+ return;
34356
35352
  }
34357
- return interests;
34358
35353
  }
34359
- function expandSubscriptionTopics(topics) {
34360
- const expanded = new Set;
34361
- for (const topic of topics) {
34362
- const base = topic.endsWith(".>") ? topic.slice(0, -2) : undefined;
34363
- if (base === undefined || base.includes("*") || base.includes(">")) {
34364
- expanded.add(topic);
34365
- continue;
34366
- }
34367
- const segments = base.split(".");
34368
- if (segments.length < 2 || segments.some((segment) => segment.length === 0)) {
34369
- throw new TypeError(`cannot expand Envoy wildcard topic "${topic}": its concrete base must have at least two non-empty segments`);
34370
- }
34371
- expanded.add(base);
34372
- expanded.add(topic);
35354
+ function allowedAPIURL(value) {
35355
+ let url2;
35356
+ try {
35357
+ url2 = new URL(value);
35358
+ } catch {
35359
+ return false;
34373
35360
  }
34374
- return [...expanded];
35361
+ if (url2.protocol === "https:")
35362
+ return true;
35363
+ return url2.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]"].includes(url2.hostname);
34375
35364
  }
34376
35365
 
34377
- class EnvoyApiError extends Error {
34378
- details;
34379
- name = "EnvoyApiError";
34380
- expected;
34381
- constructor(details) {
34382
- let parsed;
34383
- try {
34384
- const result = ErrorWireSchema.safeParse(JSON.parse(details.responseBody));
34385
- if (result.success)
34386
- parsed = result.data;
34387
- } catch {}
34388
- super(parsed === undefined ? `${details.method} ${details.url} failed with ${details.status}: ${details.responseBody}` : `${parsed.error}${parsed.expected === undefined ? "" : ` (expected: ${parsed.expected.join(", ")})`}`);
34389
- this.details = details;
34390
- this.expected = parsed?.expected;
34391
- }
34392
- }
34393
- function createEnvoyClient(config2) {
34394
- const baseUrl = normalizeEnvoyUrl(config2.baseUrl);
34395
- const timeoutMs = config2.timeoutMs ?? DEFAULT_TIMEOUT_MS;
34396
- const apiToken = config2.token;
34397
- const request = async (path2, init) => {
34398
- const url2 = `${baseUrl}${path2}`;
34399
- const attempts = config2.retry === false ? 1 : 2;
34400
- for (let attempt = 0;attempt < attempts; attempt += 1) {
34401
- let response;
34402
- try {
34403
- const headers = new Headers(init.headers);
34404
- if (apiToken)
34405
- headers.set("Authorization", `Bearer ${apiToken}`);
34406
- response = await config2.fetch(url2, {
34407
- ...init,
34408
- headers,
34409
- signal: AbortSignal.timeout(timeoutMs)
34410
- });
34411
- } catch (error49) {
34412
- if (attempt + 1 < attempts) {
34413
- await waitForRetry();
34414
- continue;
34415
- }
34416
- throw error49;
34417
- }
34418
- const responseBody = await response.text();
34419
- if (response.ok)
34420
- return responseBody;
34421
- const error48 = new EnvoyApiError({
34422
- method: init.method ?? "GET",
34423
- url: url2,
34424
- status: response.status,
34425
- responseBody
34426
- });
34427
- if (response.status >= 500 && attempt + 1 < attempts) {
34428
- await waitForRetry();
34429
- continue;
34430
- }
34431
- throw error48;
34432
- }
34433
- throw new Error("Envoy request exhausted retries");
34434
- };
34435
- const post = (path2, body) => request(path2, {
34436
- method: "POST",
34437
- headers: { "Content-Type": "application/json" },
34438
- body: JSON.stringify(body)
34439
- });
35366
+ // ../envoy-client/src/tool-contract.ts
35367
+ var DELIVERY_CONTRACT = "Delivery is at-least-once, possibly out of order across topics; use id for dedupe and at for freshness.";
35368
+ 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>.";
35369
+ var URGENCY_VALUES = EnvelopeSchema.shape.urgency.unwrap().options;
35370
+ var EXPECTS_REPLY_VALUES = EnvelopeSchema.shape.expects_reply.unwrap().options;
35371
+ function messageMetadataShape(schema) {
34440
35372
  return {
34441
- subscribe: async (input) => InterestWireSchema.parse(JSON.parse(await post("/v1/interests/subscribe", {
34442
- session_id: input.sessionID,
34443
- dir: input.directory,
34444
- topics: expandSubscriptionTopics(input.topics),
34445
- port: input.port,
34446
- title: input.title,
34447
- ...input.capabilities === undefined ? {} : { capabilities: input.capabilities },
34448
- driving: input.driving,
34449
- ...input.selfSubscribed === undefined ? {} : { self_subscribed: input.selfSubscribed },
34450
- host: machineID()
34451
- }))),
34452
- unsubscribe: async (input) => {
34453
- await post("/v1/interests/unsubscribe", {
34454
- session_id: input.sessionID,
34455
- topics: expandSubscriptionTopics(input.topics)
34456
- });
34457
- },
34458
- getInterest: async (sessionID) => InterestWireSchema.parse(JSON.parse(await request(`/v1/interests/${sessionID}`, {}))),
34459
- send: async (input) => {
34460
- const idempotencyKey = input.idempotencyKey ?? crypto.randomUUID();
34461
- const response = EnvelopeResponseSchema.parse(JSON.parse(await post("/v1/messages/send", {
34462
- source: input.source ?? "agent",
34463
- ...sourceSession(input.sourceSessionID),
34464
- target_session: input.targetSessionID,
34465
- message: input.message,
34466
- idempotency_key: idempotencyKey,
34467
- ...messageMetadata(input)
34468
- })));
34469
- return {
34470
- envelope: response,
34471
- recipient: response.recipient ?? input.targetSessionID,
34472
- confirmed: response.recipient !== undefined
34473
- };
34474
- },
34475
- publish: async (input) => {
34476
- const idempotencyKey = input.idempotencyKey ?? crypto.randomUUID();
34477
- const response = EnvelopeResponseSchema.parse(JSON.parse(await post("/v1/messages/publish", {
34478
- source: input.source ?? "agent",
34479
- ...sourceSession(input.sourceSessionID),
34480
- topic: input.topic,
34481
- message: input.message,
34482
- ...input.payload === undefined ? {} : { payload: input.payload },
34483
- idempotency_key: idempotencyKey,
34484
- ...messageMetadata(input)
34485
- })));
34486
- return {
34487
- envelope: response,
34488
- ...response.holder === undefined ? {} : { holder: response.holder }
34489
- };
34490
- },
34491
- unregisterSession: async (sessionID) => {
34492
- await request(`/v1/sessions/${encodeURIComponent(sessionID)}`, { method: "DELETE" });
34493
- },
34494
- setRole: async (input) => {
34495
- const soft = input.soft === true;
34496
- const previous = soft ? input.previousSessionID ?? "" : "";
34497
- const body = {
34498
- session_id: input.sessionID,
34499
- role: input.role,
34500
- ...soft ? { soft: true } : {},
34501
- ...previous === "" ? {} : { previous_session_id: previous }
34502
- };
34503
- let raw;
34504
- try {
34505
- raw = await post("/v1/roles/set", body);
34506
- } catch (error48) {
34507
- if (error48 instanceof EnvoyApiError && error48.details.status === 409) {
34508
- const held = RoleHeldWireSchema.safeParse(JSON.parse(error48.details.responseBody));
34509
- if (held.success)
34510
- return { claimed: false, holder: held.data.holder };
34511
- }
34512
- throw error48;
34513
- }
34514
- return { claimed: true, interest: InterestWireSchema.parse(JSON.parse(raw)) };
34515
- },
34516
- getRole: async (role) => RoleWireSchema.parse(JSON.parse(await request(`/v1/roles/${encodeURIComponent(role)}`, { method: "GET" }))),
34517
- listSessions: async (input = {}) => {
34518
- const search = new URLSearchParams;
34519
- if (input.directory !== undefined)
34520
- search.set("dir", input.directory);
34521
- if (input.title !== undefined)
34522
- search.set("title", input.title);
34523
- const query = search.size === 0 ? "" : `?${search.toString()}`;
34524
- return SessionWireSchema.array().parse(JSON.parse(await request(`/v1/sessions${query}`, {})));
34525
- }
35373
+ in_reply_to: schema.string().optional(),
35374
+ supersedes: schema.string().optional(),
35375
+ urgency: schema.enum(URGENCY_VALUES).describe("low | med | high | blocking").optional(),
35376
+ expects_reply: schema.enum(EXPECTS_REPLY_VALUES).describe("none | optional | required").optional(),
35377
+ expires_at: schema.number({ int: true }).optional()
34526
35378
  };
34527
35379
  }
34528
- function waitForRetry() {
34529
- const { promise: promise2, resolve: resolve2 } = Promise.withResolvers();
34530
- setTimeout(resolve2, RETRY_DELAY_MS);
34531
- return promise2;
34532
- }
34533
- function messageMetadata(input) {
35380
+ var MessageMetadataSchema = exports_external.object(messageMetadataShape(zodSchemaApi(exports_external)));
35381
+ function toMessageMetadata(args) {
34534
35382
  return {
34535
- ...input.inReplyTo === undefined ? {} : { in_reply_to: input.inReplyTo },
34536
- ...input.supersedes === undefined ? {} : { supersedes: input.supersedes },
34537
- ...input.urgency === undefined ? {} : { urgency: input.urgency },
34538
- ...input.expectsReply === undefined ? {} : { expects_reply: input.expectsReply },
34539
- ...input.expiresAt === undefined ? {} : { expires_at: input.expiresAt }
35383
+ ...args.in_reply_to === undefined ? {} : { inReplyTo: args.in_reply_to },
35384
+ ...args.supersedes === undefined ? {} : { supersedes: args.supersedes },
35385
+ ...args.urgency === undefined ? {} : { urgency: args.urgency },
35386
+ ...args.expects_reply === undefined ? {} : { expectsReply: args.expects_reply },
35387
+ ...args.expires_at === undefined ? {} : { expiresAt: args.expires_at }
34540
35388
  };
34541
35389
  }
34542
- function sourceSession(sessionID) {
34543
- return sessionID === undefined || sessionID === "" ? {} : { source_session: sessionID };
35390
+ function messageArguments(schema) {
35391
+ return { message: schema.string(), ...messageMetadataShape(schema) };
35392
+ }
35393
+ var EnvoyToolOperation = {
35394
+ subscribe: "subscribe",
35395
+ unsubscribe: "unsubscribe",
35396
+ listInterests: "listInterests",
35397
+ inbox: "inbox",
35398
+ send: "send",
35399
+ publish: "publish",
35400
+ setRole: "setRole",
35401
+ getRole: "getRole",
35402
+ whoami: "whoami",
35403
+ listSessions: "listSessions",
35404
+ slackPost: "slackPost"
35405
+ };
35406
+ var envoyToolSpecs = [
35407
+ {
35408
+ name: "envoy_subscribe",
35409
+ description: `Subscribe this session to Envoy notification topics. ${TOPIC_GUIDE}`,
35410
+ arguments: (schema) => ({
35411
+ topics: schema.array(schema.string()).describe("NATS-style topic patterns to subscribe to.")
35412
+ }),
35413
+ operation: EnvoyToolOperation.subscribe
35414
+ },
35415
+ {
35416
+ name: "envoy_unsubscribe",
35417
+ description: "Unsubscribe this session from Envoy topics, or remove all current subscriptions if topics are omitted. A subscription another plugin holds for this session's role stays, and the result lists it as kept.",
35418
+ arguments: (schema) => ({ topics: schema.array(schema.string()).optional() }),
35419
+ operation: EnvoyToolOperation.unsubscribe
35420
+ },
35421
+ {
35422
+ name: "envoy_list",
35423
+ description: "List the current Envoy topic subscriptions for this session so you can confirm the exact topic shapes that are active.",
35424
+ arguments: () => ({}),
35425
+ operation: EnvoyToolOperation.listInterests
35426
+ },
35427
+ {
35428
+ name: "envoy_inbox",
35429
+ description: "List this Pi session's 50 most recent rendered Envoy deliveries, newest first.",
35430
+ arguments: () => ({}),
35431
+ operation: EnvoyToolOperation.inbox
35432
+ },
35433
+ {
35434
+ name: "envoy_send",
35435
+ description: `Send an Envoy agent-to-agent message directly to another session by session ID. ${DELIVERY_CONTRACT}`,
35436
+ arguments: (schema) => ({
35437
+ session_id: schema.string().describe("Target session ID; find it with envoy_sessions or envoy_whoami."),
35438
+ ...messageArguments(schema)
35439
+ }),
35440
+ operation: EnvoyToolOperation.send
35441
+ },
35442
+ {
35443
+ name: "envoy_publish",
35444
+ description: `Publish an Envoy message to a notifications. topic. A role or built-in topic is delivered as its guide says; any other notifications. topic you name (a team topic such as notifications.team.deploy-squad.all) is live only: it reaches every session subscribed to it when you publish, and is not retained. A session that holds its own NATS connection receives it directly, yours included; a session the listener delivers to over a serve port, such as an OpenCode agent, receives it through its machine's listener when that listener subscribes to every topic (ENVOY_SUBSCRIBE_ALL_TOPICS=1; the shared hub's listener does not). ${DELIVERY_CONTRACT}`,
35445
+ arguments: (schema) => ({ topic: schema.string(), ...messageArguments(schema) }),
35446
+ operation: EnvoyToolOperation.publish
35447
+ },
35448
+ {
35449
+ name: "envoy_role_set",
35450
+ description: "Set the current session as the holder of a named role. Messages published to notifications.role.<role> route to this session. Moving to a different role is refused while another plugin holds subscriptions that last only as long as this session keeps its current role.",
35451
+ arguments: (schema) => ({ role: schema.string() }),
35452
+ operation: EnvoyToolOperation.setRole
35453
+ },
35454
+ {
35455
+ name: "envoy_role_get",
35456
+ description: "Get the live holder of a named Envoy role.",
35457
+ arguments: (schema) => ({ role: schema.string() }),
35458
+ operation: EnvoyToolOperation.getRole
35459
+ },
35460
+ {
35461
+ name: "envoy_whoami",
35462
+ description: "Returns this session's Envoy identity: session ID, machine ID, port, and directory. session_id is the address a reply reaches. Where a host runs a task subagent inside its parent's process, such a subagent registers no Envoy session of its own, so its session_id is the parent session that spawned it and the result says so.",
35463
+ arguments: () => ({}),
35464
+ operation: EnvoyToolOperation.whoami
35465
+ },
35466
+ {
35467
+ name: "envoy_sessions",
35468
+ description: "List all live sessions registered with Envoy. Filter by optional machine, directory, or title.",
35469
+ arguments: (schema) => ({
35470
+ machine: schema.string().optional(),
35471
+ dir: schema.string().optional(),
35472
+ title: schema.string().optional()
35473
+ }),
35474
+ operation: EnvoyToolOperation.listSessions
35475
+ },
35476
+ {
35477
+ name: "slack_post",
35478
+ description: "Reply in a Slack thread as the Legion Slack app, with the bot token the secrets broker grants this session (LEGION_SLACK_BOT_TOKEN); the session never holds it. channel is the Slack channel id (a mention's channel_id); thread_ts is the thread's root ts: the mention's thread_ts, or its own ts when it has none. Answers the new message's ts. A refusal carries Slack's own error code (not_in_channel: the app is not in that channel) or the broker's state (waiting for approval, denied). Sent once and never retried: after 'Slack did not answer' the reply may already be in the thread, so do not post it again.",
35479
+ arguments: (schema) => ({
35480
+ channel: schema.string({ min: 1 }).describe("Slack channel id, such as C0123ABCD."),
35481
+ thread_ts: schema.string({ min: 1 }).describe("The thread's root ts, which keeps the reply in the mention's thread."),
35482
+ text: schema.string({ min: 1, max: SLACK_POST_TEXT_MAX }).describe(`The reply, in Slack mrkdwn, at most ${SLACK_POST_TEXT_MAX} characters.`)
35483
+ }),
35484
+ operation: EnvoyToolOperation.slackPost
35485
+ }
35486
+ ];
35487
+ function sendConfirmationText(result) {
35488
+ return `sent ${result.envelope.event_id} to ${result.recipient}${result.confirmed ? "" : " (recipient unconfirmed by listener)"}`;
35489
+ }
35490
+ var envoyToolSchemas = new Map;
35491
+ function parseEnvoyToolArguments(operation, parameters) {
35492
+ const spec = envoyToolSpecs.find((candidate) => candidate.operation === operation);
35493
+ if (spec === undefined)
35494
+ throw new Error(`missing Envoy tool specification for ${operation}`);
35495
+ let schema = envoyToolSchemas.get(operation);
35496
+ if (schema === undefined) {
35497
+ schema = exports_external.object(spec.arguments(zodSchemaApi(exports_external))).strict();
35498
+ envoyToolSchemas.set(operation, schema);
35499
+ }
35500
+ const parsed = schema.safeParse(parameters, { reportInput: true });
35501
+ if (!parsed.success) {
35502
+ throw new ToolInputError(spec.name, formatZodIssues(parsed.error.issues, schema, spec.name));
35503
+ }
35504
+ return parsed.data;
34544
35505
  }
34545
35506
 
34546
35507
  // ../pi-shared/src/interface.ts
@@ -34683,7 +35644,7 @@ var BLANK_LINE = /^[ \t]*$/;
34683
35644
  var REFUSED_UNQUOTED = "\n;&|$`<>()#\\";
34684
35645
  var REFUSED_DOUBLE_QUOTED = "$`\\";
34685
35646
  function dispatchCommandHead(command) {
34686
- if (typeof command !== "string" || hasControlCharacter(command))
35647
+ if (typeof command !== "string" || hasControlCharacter2(command))
34687
35648
  return;
34688
35649
  const all = command.split(`
34689
35650
  `);
@@ -34710,7 +35671,7 @@ function dispatchCommandHead(command) {
34710
35671
  function firstWord(head) {
34711
35672
  return head.split(/[ \t]/, 1)[0] ?? "";
34712
35673
  }
34713
- function hasControlCharacter(text) {
35674
+ function hasControlCharacter2(text) {
34714
35675
  for (let index = 0;index < text.length; index += 1) {
34715
35676
  const code = text.charCodeAt(index);
34716
35677
  if (code < 32 && code !== 10 && code !== 9 || code === 127)
@@ -34807,10 +35768,10 @@ import { logger as logger3, procmgr, VERSION } from "@oh-my-pi/pi-utils";
34807
35768
  var import_nats2 = __toESM(require_mod4(), 1);
34808
35769
 
34809
35770
  // src/agent-stream.ts
34810
- var encoder = new TextEncoder;
35771
+ var encoder2 = new TextEncoder;
34811
35772
  var REPLAY_ARRAY_BYTES = 2;
34812
35773
  function jsonBytes(value) {
34813
- return encoder.encode(JSON.stringify(value)).length;
35774
+ return encoder2.encode(JSON.stringify(value)).length;
34814
35775
  }
34815
35776
  var SEQ_PER_MS = 1000;
34816
35777
  function modelReference(provider, id) {
@@ -35328,6 +36289,166 @@ function resolveEnvoySession(sessionFile) {
35328
36289
  return [...sessions.values()][0] ?? "";
35329
36290
  }
35330
36291
 
36292
+ // src/missed-messages.ts
36293
+ var ENVOY_MESSAGE = "envoy-message";
36294
+ var REPLAY_DELIVERED_ENTRY = "envoy-replay-delivered";
36295
+ var REPLAY_STATE_ENTRY = "envoy-replay-state";
36296
+ var REPLAY_NOTICE_ENTRY = "envoy-replay-notice";
36297
+ function customEntries(entries, customType) {
36298
+ const found = [];
36299
+ for (const entry of entries) {
36300
+ if (typeof entry !== "object" || entry === null)
36301
+ continue;
36302
+ if (!("type" in entry) || entry.type !== "custom")
36303
+ continue;
36304
+ if (!("customType" in entry) || entry.customType !== customType)
36305
+ continue;
36306
+ if (!("data" in entry))
36307
+ continue;
36308
+ found.push(entry.data);
36309
+ }
36310
+ return found;
36311
+ }
36312
+ function newestState(entries) {
36313
+ const states = customEntries(entries, REPLAY_STATE_ENTRY);
36314
+ for (let index = states.length - 1;index >= 0; index -= 1) {
36315
+ const parsed = ReplayStateSchema.safeParse(states[index]);
36316
+ if (parsed.success)
36317
+ return parsed.data;
36318
+ }
36319
+ return;
36320
+ }
36321
+ function replaySnapshot(entries, now = Date.now()) {
36322
+ const ledger = [];
36323
+ for (const data of customEntries(entries, REPLAY_DELIVERED_ENTRY)) {
36324
+ const parsed = ReplayLedgerEntrySchema.safeParse(data);
36325
+ if (parsed.success)
36326
+ ledger.push(parsed.data);
36327
+ }
36328
+ ledger.push(...writtenCards(entries, ledger, now));
36329
+ const state = newestState(entries);
36330
+ return state === undefined ? { ledger } : { state, ledger };
36331
+ }
36332
+ function stringField(value, field) {
36333
+ const found = field in value ? Reflect.get(value, field) : undefined;
36334
+ return typeof found === "string" && found !== "" ? found : undefined;
36335
+ }
36336
+ function cardText(content) {
36337
+ if (typeof content === "string")
36338
+ return content;
36339
+ if (!Array.isArray(content))
36340
+ return "";
36341
+ const texts = [];
36342
+ for (const block of content) {
36343
+ if (typeof block !== "object" || block === null)
36344
+ continue;
36345
+ if (stringField(block, "type") !== "text")
36346
+ continue;
36347
+ const text = stringField(block, "text");
36348
+ if (text !== undefined)
36349
+ texts.push(text);
36350
+ }
36351
+ return texts.join(`
36352
+ `);
36353
+ }
36354
+ function cardEventID(text) {
36355
+ const lines = text.split(`
36356
+ `);
36357
+ if (lines[0] !== "envoy:")
36358
+ return;
36359
+ for (const line of lines.slice(1)) {
36360
+ const match = /^ {2}(id|event_id): (.+)$/.exec(line);
36361
+ const raw = match?.[2];
36362
+ if (raw === undefined)
36363
+ continue;
36364
+ let value = raw;
36365
+ if (raw.startsWith('"')) {
36366
+ try {
36367
+ value = JSON.parse(raw);
36368
+ } catch {
36369
+ return;
36370
+ }
36371
+ }
36372
+ return typeof value === "string" && value !== "" && value !== "unknown" ? value : undefined;
36373
+ }
36374
+ return;
36375
+ }
36376
+ function writtenCardIdentity(message) {
36377
+ if (typeof message !== "object" || message === null)
36378
+ return;
36379
+ if (stringField(message, "customType") !== ENVOY_MESSAGE)
36380
+ return;
36381
+ const details = "details" in message ? message.details : undefined;
36382
+ if (typeof details === "object" && details !== null) {
36383
+ const eventID2 = stringField(details, "event_id");
36384
+ const key = stringField(details, "dedupe_key");
36385
+ if (eventID2 !== undefined || key !== undefined) {
36386
+ return {
36387
+ ...eventID2 === undefined ? {} : { event_id: eventID2 },
36388
+ ...key === undefined ? {} : { dedupe_key: key }
36389
+ };
36390
+ }
36391
+ }
36392
+ const eventID = cardEventID(cardText("content" in message ? message.content : undefined));
36393
+ return eventID === undefined ? undefined : { event_id: eventID };
36394
+ }
36395
+ function writtenCards(entries, recorded, now) {
36396
+ const events = new Set;
36397
+ const keys = new Set;
36398
+ const note = (identity) => {
36399
+ if (identity.event_id !== undefined)
36400
+ events.add(identity.event_id);
36401
+ if (identity.dedupe_key !== undefined)
36402
+ keys.add(identity.dedupe_key);
36403
+ };
36404
+ for (const entry of recorded)
36405
+ note(entry);
36406
+ const found = [];
36407
+ for (const entry of entries) {
36408
+ if (typeof entry !== "object" || entry === null)
36409
+ continue;
36410
+ if (stringField(entry, "type") !== "custom_message")
36411
+ continue;
36412
+ const identity = writtenCardIdentity(entry);
36413
+ if (identity === undefined)
36414
+ continue;
36415
+ if (identity.event_id !== undefined && events.has(identity.event_id) || identity.dedupe_key !== undefined && keys.has(identity.dedupe_key)) {
36416
+ continue;
36417
+ }
36418
+ note(identity);
36419
+ const written = Date.parse(stringField(entry, "timestamp") ?? "");
36420
+ found.push({ ...identity, at: Number.isNaN(written) ? now : written });
36421
+ }
36422
+ return found;
36423
+ }
36424
+ function rememberedSubjects(entries) {
36425
+ return rememberedTopics(newestState(entries));
36426
+ }
36427
+ function heldReplayNotices(entries) {
36428
+ const held = new Map;
36429
+ const handed = new Set;
36430
+ for (const data of customEntries(entries, REPLAY_NOTICE_ENTRY)) {
36431
+ if (typeof data !== "object" || data === null)
36432
+ continue;
36433
+ const id = stringField(data, "id");
36434
+ if (id === undefined)
36435
+ continue;
36436
+ if (Reflect.get(data, "handed") === true) {
36437
+ handed.add(id);
36438
+ continue;
36439
+ }
36440
+ const content = stringField(data, "content");
36441
+ if (content !== undefined && !held.has(id))
36442
+ held.set(id, content);
36443
+ }
36444
+ const notices = [];
36445
+ for (const [id, content] of held) {
36446
+ if (!handed.has(id))
36447
+ notices.push({ id, content });
36448
+ }
36449
+ return notices;
36450
+ }
36451
+
35331
36452
  // src/opens-ask.ts
35332
36453
  function adviceCount(details, key) {
35333
36454
  const count = asObject(asObject(details)?.advice)?.[key];
@@ -35419,6 +36540,219 @@ class TypedPictures {
35419
36540
  }
35420
36541
  }
35421
36542
 
36543
+ // src/unwritten-frames.ts
36544
+ function unwrittenCardKeys(identity) {
36545
+ return [
36546
+ ...identity.event_id === undefined ? [] : [`event:${identity.event_id}`],
36547
+ ...identity.dedupe_key === undefined ? [] : [`key:${identity.dedupe_key}`]
36548
+ ];
36549
+ }
36550
+
36551
+ class UnwrittenFrames {
36552
+ #host;
36553
+ #cards = new Map;
36554
+ #turns = new Map;
36555
+ #notices = [];
36556
+ #handedNotices = new Set;
36557
+ #moments = 0;
36558
+ constructor(host2) {
36559
+ this.#host = host2;
36560
+ }
36561
+ sendCard(content, deliverAs, identity, claim) {
36562
+ const hand = deliverAs !== "inert" || this.#host.settled();
36563
+ const keys = identity === undefined ? [] : unwrittenCardKeys(replayLedgerIdentity(identity));
36564
+ const card = identity === undefined || keys.length === 0 ? undefined : {
36565
+ sessionID: this.#host.sessionID(),
36566
+ identity,
36567
+ claim,
36568
+ keys,
36569
+ content,
36570
+ deliverAs,
36571
+ handedAt: hand ? this.#moments : undefined
36572
+ };
36573
+ if (card !== undefined)
36574
+ this.#awaitWrite(card);
36575
+ if (!hand) {
36576
+ if (card === undefined)
36577
+ claim?.release();
36578
+ return "queued";
36579
+ }
36580
+ try {
36581
+ this.#host.handCard(content, deliverAs, identity);
36582
+ } catch (error48) {
36583
+ if (card !== undefined)
36584
+ this.#stopAwaitingWrite(card);
36585
+ claim?.release();
36586
+ throw error48;
36587
+ }
36588
+ if (card !== undefined)
36589
+ return "queued";
36590
+ claim?.settle();
36591
+ return "shown";
36592
+ }
36593
+ waitsOnCard(identity) {
36594
+ return unwrittenCardKeys(replayLedgerIdentity(identity)).some((key) => this.#cards.has(key));
36595
+ }
36596
+ sendNotice(content) {
36597
+ const notice = {
36598
+ id: crypto.randomUUID(),
36599
+ sessionID: this.#host.sessionID(),
36600
+ content,
36601
+ recorded: false
36602
+ };
36603
+ this.#notices.push(notice);
36604
+ if (this.#host.settled())
36605
+ this.#handNotices();
36606
+ if (!this.#notices.includes(notice))
36607
+ return;
36608
+ try {
36609
+ this.#host.recordNotice(notice.id, content);
36610
+ notice.recorded = true;
36611
+ } catch (error48) {
36612
+ this.#host.recordNoticeFailed(error48);
36613
+ }
36614
+ }
36615
+ requeueNotices(notices) {
36616
+ const sessionID = this.#host.sessionID();
36617
+ for (const { id, content } of notices) {
36618
+ if (this.#handedNotices.has(JSON.stringify([sessionID, id])) || this.#notices.some((held) => held.sessionID === sessionID && held.id === id)) {
36619
+ continue;
36620
+ }
36621
+ this.#notices.push({ id, sessionID, content, recorded: true });
36622
+ }
36623
+ }
36624
+ awaitTurn(messageID, turn) {
36625
+ const { identity } = turn;
36626
+ if (identity === undefined) {
36627
+ turn.claim?.settle();
36628
+ return;
36629
+ }
36630
+ this.#turns.set(messageID, {
36631
+ ...turn,
36632
+ identity,
36633
+ handedAt: turn.via === "text" ? this.#moments : undefined
36634
+ });
36635
+ }
36636
+ turnSubmitted(messageID) {
36637
+ const waiting = this.#turns.get(messageID);
36638
+ if (waiting !== undefined)
36639
+ this.#turns.set(messageID, { ...waiting, handedAt: this.#moments });
36640
+ }
36641
+ async turnHandled(messageID) {
36642
+ const turn = this.#turns.get(messageID);
36643
+ if (turn === undefined)
36644
+ return;
36645
+ this.#turns.delete(messageID);
36646
+ await this.#recordWritten(turn);
36647
+ }
36648
+ async written(message) {
36649
+ const card = writtenCardIdentity(message);
36650
+ const waiting = unwrittenCardKeys(card ?? {}).map((key) => this.#cards.get(key)).find((found) => found !== undefined);
36651
+ if (waiting !== undefined) {
36652
+ this.#stopAwaitingWrite(waiting);
36653
+ await this.#recordWritten(waiting);
36654
+ }
36655
+ if (this.#turns.size === 0)
36656
+ return;
36657
+ const turn = this.#host.matchTurn(message);
36658
+ if (turn !== undefined)
36659
+ await this.turnHandled(turn);
36660
+ }
36661
+ runAborted() {
36662
+ this.#moments += 1;
36663
+ }
36664
+ async textTurnsEnded() {
36665
+ for (const [messageID, turn] of this.#turns) {
36666
+ if (turn.via === "text" && turn.sessionID === this.#host.sessionID()) {
36667
+ await this.turnHandled(messageID);
36668
+ }
36669
+ }
36670
+ }
36671
+ handBackWithdrawn() {
36672
+ const since = this.#moments;
36673
+ this.#moments += 1;
36674
+ if (!this.#host.settled())
36675
+ return;
36676
+ this.#handNotices();
36677
+ const sessionID = this.#host.sessionID();
36678
+ for (const card of new Set(this.#cards.values())) {
36679
+ if (card.sessionID !== sessionID)
36680
+ continue;
36681
+ if (card.handedAt !== undefined && card.handedAt >= since)
36682
+ continue;
36683
+ const again = { ...card, handedAt: this.#moments };
36684
+ this.#awaitWrite(again);
36685
+ try {
36686
+ this.#host.handCard(card.content, card.deliverAs, card.identity);
36687
+ } catch (error48) {
36688
+ this.#stopAwaitingWrite(again);
36689
+ this.#awaitWrite(card);
36690
+ this.#host.handBackFailed(card.identity, error48);
36691
+ }
36692
+ }
36693
+ for (const [messageID, turn] of this.#turns) {
36694
+ if (turn.sessionID !== sessionID || turn.handedAt === undefined || turn.handedAt >= since) {
36695
+ continue;
36696
+ }
36697
+ this.#turns.delete(messageID);
36698
+ this.#host.turnWithdrawn(turn.sessionID, messageID);
36699
+ turn.claim?.release();
36700
+ }
36701
+ }
36702
+ releaseOtherSessions(sessionID) {
36703
+ for (const waiting of [this.#cards, this.#turns]) {
36704
+ for (const [key, frame] of waiting) {
36705
+ if (frame.sessionID === sessionID)
36706
+ continue;
36707
+ waiting.delete(key);
36708
+ frame.claim?.release();
36709
+ }
36710
+ }
36711
+ this.#notices = this.#notices.filter((notice) => notice.sessionID === sessionID);
36712
+ }
36713
+ #handNotices() {
36714
+ const sessionID = this.#host.sessionID();
36715
+ for (let index = 0;index < this.#notices.length; ) {
36716
+ const notice = this.#notices[index];
36717
+ if (notice === undefined || notice.sessionID !== sessionID) {
36718
+ index += 1;
36719
+ continue;
36720
+ }
36721
+ try {
36722
+ this.#host.handNotice(notice.content);
36723
+ } catch (error48) {
36724
+ this.#host.handNoticeFailed(error48);
36725
+ return;
36726
+ }
36727
+ this.#notices.splice(index, 1);
36728
+ if (!notice.recorded)
36729
+ continue;
36730
+ this.#handedNotices.add(JSON.stringify([notice.sessionID, notice.id]));
36731
+ try {
36732
+ this.#host.noticeHanded(notice.id);
36733
+ } catch (error48) {
36734
+ this.#host.recordNoticeFailed(error48);
36735
+ }
36736
+ }
36737
+ }
36738
+ async#recordWritten(frame) {
36739
+ if (frame.sessionID === this.#host.sessionID()) {
36740
+ await this.#host.recordDelivered(frame.identity);
36741
+ }
36742
+ frame.claim?.settle();
36743
+ }
36744
+ #awaitWrite(card) {
36745
+ for (const key of card.keys)
36746
+ this.#cards.set(key, card);
36747
+ }
36748
+ #stopAwaitingWrite(card) {
36749
+ for (const key of card.keys) {
36750
+ if (this.#cards.get(key) === card)
36751
+ this.#cards.delete(key);
36752
+ }
36753
+ }
36754
+ }
36755
+
35422
36756
  // extensions/envoy-message-renderer.ts
35423
36757
  import { Box, Spacer, Text } from "@oh-my-pi/pi-tui";
35424
36758
  var ENVOY_MESSAGE_COLLAPSED_LINES = 12;
@@ -35502,6 +36836,8 @@ function liveSessionSettings(live) {
35502
36836
  var codec2 = import_nats2.StringCodec();
35503
36837
  var NATS_RETRY_INTERVAL_MS = 15000;
35504
36838
  var DELIVERY_PICTURES_TIMEOUT_MS = 20000;
36839
+ var BTW_EVENTS_LIMIT = 1000;
36840
+ 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.";
35505
36841
  var UNFENCED = () => true;
35506
36842
 
35507
36843
  class AbandonedTaskError extends Error {
@@ -35799,13 +37135,17 @@ function envoyExtension(pi) {
35799
37135
  awarenessGeneration++;
35800
37136
  }
35801
37137
  legionManagedTranscript = branch.some(isLegionManagedEntry);
35802
- handledDispatchAttempts = handledAttempts(context.sessionManager.getEntries());
37138
+ const entries = context.sessionManager.getEntries();
37139
+ handledDispatchAttempts = handledAttempts(entries);
37140
+ replay?.restore(replaySnapshot(entries));
37141
+ unwritten.requeueNotices(heldReplayNotices(entries));
35803
37142
  markPicturesShown(shownPictures(sessionID), transcriptPictures(branch));
35804
37143
  if (previousSessionID !== sessionID) {
35805
37144
  forgetShownPictures(previousSessionID);
35806
37145
  if (notedSessionIDs.delete(previousSessionID))
35807
37146
  forgetInjectedUserTurns(previousSessionID);
35808
37147
  typedPictures.dropOtherSessions(sessionID);
37148
+ unwritten.releaseOtherSessions(sessionID);
35809
37149
  }
35810
37150
  };
35811
37151
  let dispatchLedger;
@@ -35862,8 +37202,23 @@ function envoyExtension(pi) {
35862
37202
  throw new AbandonedTaskError(shuttingDown ? "the session shut down while its NATS dial was in flight; the connection it opened was closed" : "the pass that dialled NATS was abandoned at its deadline while the dial was in flight; the connection it opened was closed");
35863
37203
  }
35864
37204
  connection = dialled;
37205
+ watchReconnects(dialled);
35865
37206
  return connection;
35866
37207
  };
37208
+ const watchReconnects = async (watched) => {
37209
+ try {
37210
+ for await (const status of watched.status()) {
37211
+ if (connection !== watched)
37212
+ return;
37213
+ if (status.type === import_nats2.Events.Reconnect)
37214
+ triggerReplay();
37215
+ }
37216
+ } catch (error48) {
37217
+ logger3.warn("envoy: the NATS connection's status reader failed", {
37218
+ error: messageFor(error48)
37219
+ });
37220
+ }
37221
+ };
35867
37222
  const postDispatchReply = async (delivery, result, replySessionID = sessionID) => {
35868
37223
  await postDeliveryReply(currentDispatchConfig(), replySessionID, delivery, result);
35869
37224
  };
@@ -35874,6 +37229,80 @@ function envoyExtension(pi) {
35874
37229
  const images = typedPictures.handOver(event.text);
35875
37230
  return images === undefined ? undefined : { images: [...event.images ?? [], ...images] };
35876
37231
  });
37232
+ const handCard = (content, deliverAs, identity) => {
37233
+ const known = identity === undefined ? {} : replayLedgerIdentity(identity);
37234
+ pi.sendMessage({
37235
+ customType: "envoy-message",
37236
+ content,
37237
+ display: true,
37238
+ ...unwrittenCardKeys(known).length === 0 ? {} : { details: { ...known } }
37239
+ }, deliverAs === "inert" ? { deliverAs: "steer", triggerTurn: false } : { deliverAs, triggerTurn: true });
37240
+ };
37241
+ const hostSettled = () => {
37242
+ const hostContext = activeSessionContext;
37243
+ return hostContext?.isIdle?.() === true && hostContext.hasPendingMessages?.() === false && !shuttingDown && hostSessionID() === sessionID;
37244
+ };
37245
+ const unwritten = new UnwrittenFrames({
37246
+ sessionID: () => sessionID,
37247
+ settled: hostSettled,
37248
+ recordDelivered: async (identity) => {
37249
+ await replay?.recordDelivered(identity);
37250
+ },
37251
+ handCard,
37252
+ handNotice: (content) => {
37253
+ pi.sendMessage({ customType: "envoy-message", content, display: true, details: LOCAL_ENVOY_NOTICE }, { deliverAs: "steer", triggerTurn: false });
37254
+ },
37255
+ matchTurn: (message) => matchInjectedUserTurn(sessionID, message),
37256
+ turnWithdrawn: (turnSessionID, messageID) => {
37257
+ dropInjectedUserTurn(turnSessionID, messageID);
37258
+ typedPictures.withdraw(messageID);
37259
+ },
37260
+ handBackFailed: (identity, error48) => {
37261
+ logger3.warn("envoy: a card waiting for a settled host could not be handed", {
37262
+ eventID: identity.event_id,
37263
+ error: messageFor(error48)
37264
+ });
37265
+ },
37266
+ handNoticeFailed: (error48) => {
37267
+ logger3.warn("envoy: a replay notice waiting for a settled host could not be handed", {
37268
+ error: messageFor(error48)
37269
+ });
37270
+ },
37271
+ recordNotice: (id, content) => {
37272
+ if (hostSessionID() !== sessionID)
37273
+ throw new Error("the host is on another session");
37274
+ pi.appendEntry(REPLAY_NOTICE_ENTRY, { id, content });
37275
+ },
37276
+ noticeHanded: (id) => {
37277
+ pi.appendEntry(REPLAY_NOTICE_ENTRY, { id, handed: true });
37278
+ },
37279
+ recordNoticeFailed: (error48) => {
37280
+ logger3.warn("envoy: a held replay notice could not be recorded in the session file", {
37281
+ error: messageFor(error48)
37282
+ });
37283
+ }
37284
+ });
37285
+ const showReplayCard = (content, envelope2, deliverAs = "steer") => {
37286
+ const parsed = ClaimIdentitySchema.safeParse(envelope2);
37287
+ const identity = parsed.success ? parsed.data : undefined;
37288
+ const claim2 = delivered.claim(identity);
37289
+ if (claim2 === undefined && identity !== undefined && (delivered.pending(identity) || unwritten.waitsOnCard(identity))) {
37290
+ return "queued";
37291
+ }
37292
+ return unwritten.sendCard(content, deliverAs, identity, claim2);
37293
+ };
37294
+ const btwEvents = new Set;
37295
+ const noteBtw = (eventID) => {
37296
+ if (eventID === undefined)
37297
+ return;
37298
+ btwEvents.delete(eventID);
37299
+ btwEvents.add(eventID);
37300
+ if (btwEvents.size > BTW_EVENTS_LIMIT) {
37301
+ const oldest = btwEvents.values().next();
37302
+ if (oldest.done !== true)
37303
+ btwEvents.delete(oldest.value);
37304
+ }
37305
+ };
35877
37306
  const runTypedInput = (sendUserInput, delivery, replySessionID, turn, content, pictureAddresses2) => {
35878
37307
  const images = typeof content === "string" ? [] : content.filter((block) => block.type === "image");
35879
37308
  const noted = sessionID;
@@ -35894,14 +37323,17 @@ function envoyExtension(pi) {
35894
37323
  const submitted = result.handled === "prompt" || result.handled === "skill";
35895
37324
  if (submitted) {
35896
37325
  typedPictures.inputPassed(turn.messageId);
37326
+ unwritten.turnSubmitted(turn.messageId);
35897
37327
  } else {
35898
37328
  dropInjectedUserTurn(noted, turn.messageId);
35899
37329
  typedPictures.withdraw(turn.messageId);
37330
+ unwritten.turnHandled(turn.messageId);
35900
37331
  }
35901
37332
  return typedInputReply(turn.body, result);
35902
37333
  }, (error48) => {
35903
37334
  dropInjectedUserTurn(noted, turn.messageId);
35904
37335
  typedPictures.withdraw(turn.messageId);
37336
+ unwritten.turnHandled(turn.messageId);
35905
37337
  return typedInputReply(turn.body, { error: messageFor(error48) });
35906
37338
  }).then(async (reply) => {
35907
37339
  refreshAgentStreamSettings(sessionID);
@@ -35944,7 +37376,7 @@ function envoyExtension(pi) {
35944
37376
  return;
35945
37377
  }
35946
37378
  };
35947
- const deliver = async (subject2, raw, reply) => {
37379
+ const deliver = async (topic, subject2, raw, reply, receivedAt) => {
35948
37380
  const rendered = renderInbound(raw, sessionID, subject2);
35949
37381
  const directSubject = agentSubject(sessionID);
35950
37382
  if (expectsLaneReceipt({
@@ -35959,22 +37391,30 @@ function envoyExtension(pi) {
35959
37391
  console.warn(`[envoy] failed to acknowledge envelope ${rendered.envelope?.event_id ?? "unknown"}`, error48);
35960
37392
  }
35961
37393
  }
35962
- for (const topic of subscriptionRemovedTopics(raw, sessionID) ?? [])
35963
- closeIntentionally(topic);
37394
+ let removed = false;
37395
+ for (const topic2 of subscriptionRemovedTopics(raw, sessionID) ?? []) {
37396
+ if (closeIntentionally(topic2))
37397
+ removed = true;
37398
+ }
37399
+ if (removed)
37400
+ replayFollowedChanged();
35964
37401
  const dedupeIdentity = ClaimIdentitySchema.safeParse(rendered.envelope);
35965
- const claim2 = rendered.skip ? undefined : delivered.claim(dedupeIdentity.success ? dedupeIdentity.data : undefined);
37402
+ const identity = dedupeIdentity.success ? dedupeIdentity.data : undefined;
37403
+ const claim2 = rendered.skip ? undefined : delivered.claim(identity);
35966
37404
  if (claim2 !== undefined) {
35967
- const envelope2 = rendered.envelope;
35968
- if (envelope2 !== undefined) {
35969
- inbox.unshift({
35970
- event_id: envelope2.event_id ?? "unknown",
35971
- at: inboundTimestamp(envelope2.issued_at),
35972
- from: senderLabel(envelope2),
35973
- summary: envelope2.payload_summary ?? "unknown"
35974
- });
35975
- if (inbox.length > 50)
35976
- inbox.pop();
37405
+ if (identity !== undefined && replay?.delivered(identity) === true) {
37406
+ claim2.settle();
37407
+ return;
35977
37408
  }
37409
+ const envelope2 = rendered.envelope;
37410
+ if (envelope2 !== undefined)
37411
+ noteInbox(envelope2);
37412
+ const deliveredIn = sessionID;
37413
+ const taken = async () => {
37414
+ if (identity !== undefined)
37415
+ await replay?.recordDeliveredFor(deliveredIn, identity);
37416
+ claim2.settle();
37417
+ };
35978
37418
  const refuse = async (delivery, error48) => {
35979
37419
  claim2.release();
35980
37420
  await postDispatchReply(delivery, { error: error48 });
@@ -35985,7 +37425,12 @@ function envoyExtension(pi) {
35985
37425
  await refuse(rendered.rejectedDelivery, "Invalid Dispatch targeted delivery frame");
35986
37426
  } else if (rendered.malformedDelivery === true) {
35987
37427
  console.warn("[envoy] dropping malformed Dispatch targeted delivery without a reply address");
37428
+ claim2.settle();
35988
37429
  } else if (rendered.delivery?.mode === "btw") {
37430
+ noteBtw(identity?.event_id);
37431
+ if (identity?.event_id !== undefined) {
37432
+ await replay?.recordDeliveredFor(deliveredIn, { event_id: identity.event_id });
37433
+ }
35989
37434
  const answer = sideTurn(activeSessionContext);
35990
37435
  if (shuttingDown) {
35991
37436
  await refuse(rendered.delivery, "This OMP session is shutting down");
@@ -35995,6 +37440,7 @@ function envoyExtension(pi) {
35995
37440
  try {
35996
37441
  const reply2 = await answer({ prompt: rendered.delivery.body });
35997
37442
  await postDispatchReply(rendered.delivery, { body: reply2.replyText });
37443
+ await taken();
35998
37444
  } catch (error48) {
35999
37445
  await refuse(rendered.delivery, messageFor(error48));
36000
37446
  }
@@ -36005,10 +37451,7 @@ function envoyExtension(pi) {
36005
37451
  const shown = shownPictures(sessionID);
36006
37452
  if (accepted === undefined) {
36007
37453
  const card = await withDeliveredPictures(rendered.content, rendered.pictures ?? [], () => timedDispatchClient(DELIVERY_PICTURES_TIMEOUT_MS), true, shown);
36008
- pi.sendMessage({ customType: "envoy-message", content: card.content, display: true }, {
36009
- deliverAs: rendered.delivery?.mode === "aside" ? "aside" : "steer",
36010
- triggerTurn: true
36011
- });
37454
+ unwritten.sendCard(card.content, rendered.delivery?.mode === "aside" ? "aside" : "steer", identity, claim2);
36012
37455
  markPicturesShown(shownPictures(sessionID), card.shown);
36013
37456
  } else {
36014
37457
  const { turn } = accepted;
@@ -36018,14 +37461,22 @@ function envoyExtension(pi) {
36018
37461
  const refusal = typedInputReply(turn.body, { hostVersion: VERSION });
36019
37462
  if (refusal !== undefined) {
36020
37463
  await postDispatchReply(accepted.delivery, { body: refusal }, acceptedSessionID);
37464
+ await taken();
36021
37465
  } else {
36022
37466
  const injectionSessionID = sessionID;
36023
37467
  noteInjectedUserTurn(injectionSessionID, turn.body, turn.messageId);
36024
37468
  notedSessionIDs.add(injectionSessionID);
36025
37469
  pi.sendUserMessage(delivery.content, turn.mode === "aside" ? { deliverAs: "aside" } : undefined);
36026
37470
  markPicturesShown(shownPictures(injectionSessionID), delivery.shown);
37471
+ unwritten.awaitTurn(turn.messageId, {
37472
+ sessionID: injectionSessionID,
37473
+ identity,
37474
+ claim: claim2,
37475
+ via: "text"
37476
+ });
36027
37477
  }
36028
37478
  } else {
37479
+ unwritten.awaitTurn(turn.messageId, { sessionID, identity, claim: claim2, via: "typed" });
36029
37480
  runTypedInput(sendUserInput, accepted.delivery, acceptedSessionID, turn, delivery.content, delivery.shown);
36030
37481
  }
36031
37482
  }
@@ -36033,6 +37484,8 @@ function envoyExtension(pi) {
36033
37484
  } catch (error48) {
36034
37485
  claim2.release();
36035
37486
  console.warn(`[envoy] failed to deliver envelope ${envelope2?.event_id ?? "unknown"}`, error48);
37487
+ if (envelope2 !== undefined)
37488
+ replay?.liveFailed(topic, envelope2, error48, receivedAt);
36036
37489
  throw error48;
36037
37490
  }
36038
37491
  }
@@ -36066,7 +37519,7 @@ function envoyExtension(pi) {
36066
37519
  };
36067
37520
  const pump = async (topic, subscription) => {
36068
37521
  try {
36069
- for await (const message of subscription) {
37522
+ for await (const { message, receivedAt } of readArrivals(subscription)) {
36070
37523
  if (replacedSessionTopic(topic)) {
36071
37524
  logger3.warn("envoy: frame for a session a switch replaced left undelivered", {
36072
37525
  subject: message.subject
@@ -36074,7 +37527,7 @@ function envoyExtension(pi) {
36074
37527
  continue;
36075
37528
  }
36076
37529
  try {
36077
- await deliver(message.subject, codec2.decode(message.data), message.reply ?? "");
37530
+ await deliver(topic, message.subject, codec2.decode(message.data), message.reply ?? "", receivedAt);
36078
37531
  } catch {}
36079
37532
  }
36080
37533
  } catch {}
@@ -36093,7 +37546,10 @@ function envoyExtension(pi) {
36093
37546
  return;
36094
37547
  if (intentionallyClosed.delete(topic))
36095
37548
  return;
36096
- subscribeUnlessRoleEnds(topic, snapshot).catch(() => retry(NATS_RETRY_INTERVAL_MS));
37549
+ subscribeUnlessRoleEnds(topic, snapshot).then((wanted) => {
37550
+ if (wanted)
37551
+ triggerReplay();
37552
+ }, () => retry(NATS_RETRY_INTERVAL_MS));
36097
37553
  }, delayMs);
36098
37554
  };
36099
37555
  retry(RESUBSCRIBE_DELAY_MS);
@@ -36113,6 +37569,92 @@ function envoyExtension(pi) {
36113
37569
  }
36114
37570
  return true;
36115
37571
  };
37572
+ const noteInbox = (envelope2) => {
37573
+ inbox.unshift({
37574
+ event_id: envelope2.event_id ?? "unknown",
37575
+ at: inboundTimestamp(envelope2.issued_at),
37576
+ from: senderLabel(envelope2),
37577
+ summary: envelope2.payload_summary ?? "unknown"
37578
+ });
37579
+ if (inbox.length > 50)
37580
+ inbox.pop();
37581
+ };
37582
+ const followedSubjects = () => {
37583
+ if (sessionID === "")
37584
+ return [];
37585
+ const open = [...subscriptions.keys(), ...awaitingRetry].filter((subject2) => !intentionallyClosed.has(subject2));
37586
+ return replayFollowedSubjects(agentSubject(sessionID), open, isRoleBound);
37587
+ };
37588
+ const showReplayed = async (frame) => {
37589
+ const rendered = renderInbound(frame.data, sessionID, frame.subject);
37590
+ if (replay !== undefined) {
37591
+ await closeReplayedRemoval(frame, {
37592
+ sessionID,
37593
+ engine: replay,
37594
+ close: closeIntentionally,
37595
+ unregister: async (topics) => {
37596
+ await active?.client.unsubscribe({ sessionID, topics }).catch((error48) => logger3.warn("envoy: a replayed subscription removal was not taken out of the registry", { topics, error: messageFor(error48) }));
37597
+ },
37598
+ followedChanged: replayFollowedChanged
37599
+ });
37600
+ }
37601
+ if (replaySuppressed(rendered))
37602
+ return "suppressed";
37603
+ if (rendered.envelope !== undefined)
37604
+ noteInbox(rendered.envelope);
37605
+ const shown = replayedText(rendered.content, frame.time);
37606
+ if (rendered.delivery?.mode === "btw") {
37607
+ noteBtw(rendered.envelope?.event_id);
37608
+ return showReplayCard(`${shown}
37609
+ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
37610
+ }
37611
+ return showReplayCard(shown, frame.envelope);
37612
+ };
37613
+ const transcriptSessionID = () => {
37614
+ const host3 = hostSessionID();
37615
+ return host3 !== "" && host3 === sessionID ? host3 : undefined;
37616
+ };
37617
+ const replay = active === undefined || !inbound ? undefined : createReplayEngine({
37618
+ host: {
37619
+ sessionID: () => shuttingDown ? undefined : transcriptSessionID(),
37620
+ writeSessionID: transcriptSessionID,
37621
+ followedSubjects,
37622
+ deliver: showReplayed,
37623
+ showFailureNotice: async (notice) => showReplayCard(envoyNoticeText(failureNoticeFields(notice)), notice.envelope, btwEvents.has(notice.eventId) ? "inert" : "steer"),
37624
+ failureNoticeFailed: (notice, error48) => {
37625
+ logger3.warn("envoy: a message this session was not shown could not be reported", {
37626
+ eventID: notice.eventId,
37627
+ error: messageFor(error48)
37628
+ });
37629
+ activeSessionContext?.ui.notify(`envoy: message ${notice.eventId} from ${notice.sender} was not shown, nor was the notice naming it (${messageFor(error48)})`, "warning");
37630
+ },
37631
+ notify: (notice) => {
37632
+ logger3.warn(`envoy: ${notice.message}`);
37633
+ routeReplayNotice(notice, {
37634
+ warn: (message) => activeSessionContext?.ui.notify(`envoy: ${message}`, "warning"),
37635
+ card: (content) => unwritten.sendNotice(content)
37636
+ });
37637
+ },
37638
+ log: (message, error48) => logger3.warn(`envoy: ${message}`, error48 === undefined ? undefined : { error: messageFor(error48) }),
37639
+ write: (change) => {
37640
+ for (const entry of change.delivered)
37641
+ pi.appendEntry(REPLAY_DELIVERED_ENTRY, entry);
37642
+ if (change.state !== undefined)
37643
+ pi.appendEntry(REPLAY_STATE_ENTRY, change.state);
37644
+ }
37645
+ },
37646
+ transport: active.client,
37647
+ dedupe: delivered
37648
+ });
37649
+ const replayOpen = () => !shuttingDown && sessionID !== "" && inboundOpenFor === sessionID;
37650
+ const triggerReplay = () => {
37651
+ if (replay !== undefined && replayOpen())
37652
+ replay.sweep();
37653
+ };
37654
+ const replayFollowedChanged = async () => {
37655
+ if (replay !== undefined && replayOpen())
37656
+ await replay.followedChanged();
37657
+ };
36116
37658
  const agentStream = new AgentStreamPublisher({
36117
37659
  now: () => Date.now(),
36118
37660
  publish: (subject2, payload) => connection?.publish(subject2, codec2.encode(payload))
@@ -36253,6 +37795,7 @@ function envoyExtension(pi) {
36253
37795
  });
36254
37796
  pi.on("message_end", async (event) => {
36255
37797
  recordAgentStreamMessage(event.message, false);
37798
+ await unwritten.written(event.message);
36256
37799
  });
36257
37800
  pi.on("turn_start", async () => {
36258
37801
  refreshAgentStreamSettings(sessionID);
@@ -36306,6 +37849,7 @@ function envoyExtension(pi) {
36306
37849
  let registeredAt = -Infinity;
36307
37850
  const registerSession = () => {
36308
37851
  const registeringFor = sessionID;
37852
+ const own = agentSubject(sessionID);
36309
37853
  for (const [key, hold] of abandonedHolds) {
36310
37854
  if (hold.id !== sessionID)
36311
37855
  continue;
@@ -36317,8 +37861,8 @@ function envoyExtension(pi) {
36317
37861
  directory: sessionDirectory2,
36318
37862
  topics: [
36319
37863
  ...new Set([
36320
- agentSubject(sessionID),
36321
- ...[...subscriptions.keys()].filter((subject2) => !isRoleBound(subject2))
37864
+ own,
37865
+ ...[...subscriptions.keys()].filter((subject2) => !isRoleBound(subject2) && !reachesPrivateStreamSubject(own, subject2))
36322
37866
  ])
36323
37867
  ],
36324
37868
  port: 0,
@@ -36399,6 +37943,8 @@ function envoyExtension(pi) {
36399
37943
  context.setInterval(() => {
36400
37944
  if (context.sessionManager.getSessionId() === "")
36401
37945
  return;
37946
+ unwritten.handBackWithdrawn();
37947
+ triggerReplay();
36402
37948
  if (healing) {
36403
37949
  const refreshMs = requireEnvoy().settings.heartbeatMs;
36404
37950
  if (registeredFor === sessionID && Date.now() - registeredAt < refreshMs)
@@ -36444,9 +37990,11 @@ function envoyExtension(pi) {
36444
37990
  const registry2 = await client.getInterest(sessionID).catch(() => {
36445
37991
  return;
36446
37992
  });
36447
- if (registry2 === undefined || !live())
37993
+ if (!live())
36448
37994
  return;
36449
- const retired = publishedInterface?.roleClaim.slackRoleOwned === true ? registry2.topics.filter((topic) => slackTopicChannel(topic) !== undefined) : [];
37995
+ const slackRetired = publishedInterface?.roleClaim.slackRoleOwned === true;
37996
+ const registered = registry2?.topics ?? [];
37997
+ const retired = slackRetired ? registered.filter((topic) => slackTopicChannel(topic) !== undefined) : [];
36450
37998
  if (retired.length > 0) {
36451
37999
  await client.unsubscribe({ sessionID, topics: retired }).catch((error48) => {
36452
38000
  logger3.warn("envoy: could not unregister a resumed controller's retired Slack topics", {
@@ -36458,7 +38006,8 @@ function envoyExtension(pi) {
36458
38006
  }
36459
38007
  if (!live())
36460
38008
  return;
36461
- for (const topic of registry2.topics) {
38009
+ const remembered = rememberedSubjects(activeSessionContext?.sessionManager.getEntries() ?? []).filter((topic) => !(slackRetired && slackTopicChannel(topic) !== undefined));
38010
+ for (const topic of new Set([...registered, ...remembered])) {
36462
38011
  if (topic === agentSubject(sessionID) || topic.startsWith(ROLE_TOPIC_PREFIX))
36463
38012
  continue;
36464
38013
  if (retired.includes(topic))
@@ -36675,6 +38224,7 @@ function envoyExtension(pi) {
36675
38224
  return true;
36676
38225
  }
36677
38226
  let inboundFailure;
38227
+ let openedInbound = false;
36678
38228
  if (inbound && inboundOpenFor !== host3) {
36679
38229
  try {
36680
38230
  agentSessions.add(host3);
@@ -36693,6 +38243,7 @@ function envoyExtension(pi) {
36693
38243
  return false;
36694
38244
  }
36695
38245
  inboundOpenFor = host3;
38246
+ openedInbound = true;
36696
38247
  } catch (error48) {
36697
38248
  inboundFailure = error48;
36698
38249
  }
@@ -36708,6 +38259,8 @@ function envoyExtension(pi) {
36708
38259
  establishedSession = host3;
36709
38260
  ensureHeartbeat(context);
36710
38261
  }
38262
+ if (openedInbound)
38263
+ triggerReplay();
36711
38264
  const decided = await roleMoves.run((moveLive) => settleRole(context, host3, cause, registration === undefined, moveLive));
36712
38265
  if (!owns())
36713
38266
  return false;
@@ -37061,8 +38614,11 @@ function envoyExtension(pi) {
37061
38614
  }
37062
38615
  pi.on("agent_end", async (event, context) => {
37063
38616
  const id = context.sessionManager.getSessionId();
37064
- endInjectedUserTurns(sessionID);
37065
38617
  const lastReply = event.messages?.findLast((message) => message.role === "assistant");
38618
+ if (lastReply?.stopReason === "aborted")
38619
+ unwritten.runAborted();
38620
+ endInjectedUserTurns(sessionID);
38621
+ await unwritten.textTurnsEnded();
37066
38622
  if (runUnderAnnouncement !== undefined && event.willContinue !== true) {
37067
38623
  if (announced === runUnderAnnouncement && announced.from === id && lastReply !== undefined && lastReply.stopReason !== "aborted") {
37068
38624
  announced = undefined;
@@ -37209,6 +38765,8 @@ function envoyExtension(pi) {
37209
38765
  } catch (error48) {
37210
38766
  registrationError = messageFor(error48);
37211
38767
  }
38768
+ await replayFollowedChanged();
38769
+ triggerReplay();
37212
38770
  }
37213
38771
  const subscribed = `Subscribed: ${added.join(", ") || "(none new)"}`;
37214
38772
  return toolSuccess(warnings === undefined || warnings.length === 0 ? subscribed : `${subscribed}
@@ -37224,6 +38782,8 @@ Warnings: ${warnings.join("; ")}`, {
37224
38782
  const candidates = topicsFor(parameters, [...subscriptions.keys()]).filter((subject2) => subject2 !== inbox2);
37225
38783
  const kept = candidates.filter(isRoleBound);
37226
38784
  const removed = candidates.filter((subject2) => !isRoleBound(subject2)).filter(closeIntentionally);
38785
+ if (removed.length > 0)
38786
+ await replayFollowedChanged();
37227
38787
  const registryRemoved = removed.filter((topic) => !topic.startsWith(ROLE_TOPIC_PREFIX));
37228
38788
  const registrationError = registryRemoved.length === 0 ? undefined : await client.unsubscribe({ sessionID, topics: registryRemoved }).then(registerSession).then(() => {
37229
38789
  return;