@sjawhar/pi-envoy 11.2.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/README.md +18 -1
- package/dist/dispatch.js +88 -25
- package/dist/envoy.js +2026 -518
- package/dist/skills/envoy/SKILL.md +1 -1
- package/dist/skills/envoy/references/deliveries.md +1 -1
- package/package.json +1 -1
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(),
|
|
@@ -30295,7 +30304,7 @@ var dispatchToolSpecs = [
|
|
|
30295
30304
|
ops: [{ op: "delete_column", block: "table-123", index: 1 }],
|
|
30296
30305
|
precondition: { blocks: [{ id: "table-123", token: "sha256:current-table-token" }] }
|
|
30297
30306
|
},
|
|
30298
|
-
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. " + "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}`,
|
|
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}`,
|
|
30299
30308
|
arguments: (z2) => ({
|
|
30300
30309
|
issue: z2.string().describe(ISSUE_REFERENCE).optional(),
|
|
30301
30310
|
project: z2.string().describe("Project key owning the document.").optional(),
|
|
@@ -30355,7 +30364,7 @@ var dispatchToolSpecs = [
|
|
|
30355
30364
|
name: "dispatch_artifact",
|
|
30356
30365
|
example: { issue: "DSP-1", name: "design.md", content: `# Design
|
|
30357
30366
|
` },
|
|
30358
|
-
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}`,
|
|
30359
30368
|
arguments: (z2) => ({
|
|
30360
30369
|
issue: z2.string().describe(ISSUE_REFERENCE).optional(),
|
|
30361
30370
|
project: z2.string().describe("Project key for an unlinked document.").optional(),
|
|
@@ -30533,6 +30542,7 @@ function dedupeKeyNamesItsEvent(envelope) {
|
|
|
30533
30542
|
// ../contracts/src/subject.ts
|
|
30534
30543
|
var AGENT_TOPIC_PREFIX = "notifications.agent.";
|
|
30535
30544
|
var ROLE_TOPIC_PREFIX = "notifications.role.";
|
|
30545
|
+
var LEGION_NOTICE_TOPIC_PREFIX = "notifications.legion.";
|
|
30536
30546
|
var DISPATCH_TOPIC_PREFIX = "notifications.dispatch.";
|
|
30537
30547
|
var DISPATCH_ISSUE_TOPIC_PREFIX = `${DISPATCH_TOPIC_PREFIX}issue.`;
|
|
30538
30548
|
var DISPATCH_DOCUMENT_TOPIC_PREFIX = `${DISPATCH_TOPIC_PREFIX}document.`;
|
|
@@ -31502,6 +31512,47 @@ function pictureAddresses(text) {
|
|
|
31502
31512
|
return [...text.matchAll(PICTURE_SYNTAX)].map((match) => match[1]);
|
|
31503
31513
|
}
|
|
31504
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
|
+
|
|
31505
31556
|
// ../envoy-client/src/delivery.ts
|
|
31506
31557
|
var KNOWN_SOURCES = EnvelopeSchema.shape.source.enum;
|
|
31507
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;
|
|
@@ -31562,6 +31613,55 @@ async function postDeliveryReply(config2, sessionId, delivery, result) {
|
|
|
31562
31613
|
function expectsLaneReceipt(frame) {
|
|
31563
31614
|
return frame.reply !== undefined && frame.reply !== "" && frame.subject === frame.directSubject && frame.envelopeTopic !== undefined && frame.envelopeTopic !== frame.directSubject;
|
|
31564
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
|
+
}
|
|
31565
31665
|
var DedupeIdentitySchema = exports_external.object({
|
|
31566
31666
|
event_id: exports_external.string().min(1).optional(),
|
|
31567
31667
|
dedupe_key: exports_external.string().min(1).optional(),
|
|
@@ -31574,6 +31674,8 @@ function createDeliveryDedupe(now = Date.now) {
|
|
|
31574
31674
|
const keys = new Map;
|
|
31575
31675
|
let events = new Map;
|
|
31576
31676
|
let olderEvents = new Map;
|
|
31677
|
+
const pendingKeys = new Map;
|
|
31678
|
+
const pendingEvents = new Map;
|
|
31577
31679
|
let claims = 0;
|
|
31578
31680
|
return {
|
|
31579
31681
|
claim(frame) {
|
|
@@ -31609,10 +31711,25 @@ function createDeliveryDedupe(now = Date.now) {
|
|
|
31609
31711
|
events = new Map;
|
|
31610
31712
|
}
|
|
31611
31713
|
events.set(eventId, claim);
|
|
31714
|
+
pendingEvents.set(eventId, claim);
|
|
31612
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
|
+
};
|
|
31613
31729
|
let released = false;
|
|
31614
31730
|
return {
|
|
31615
31731
|
release() {
|
|
31732
|
+
close();
|
|
31616
31733
|
if (released)
|
|
31617
31734
|
return;
|
|
31618
31735
|
released = true;
|
|
@@ -31624,8 +31741,14 @@ function createDeliveryDedupe(now = Date.now) {
|
|
|
31624
31741
|
events.delete(eventId);
|
|
31625
31742
|
if (olderEvents.get(eventId) === claim)
|
|
31626
31743
|
olderEvents.delete(eventId);
|
|
31627
|
-
}
|
|
31744
|
+
},
|
|
31745
|
+
settle: close
|
|
31628
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);
|
|
31629
31752
|
}
|
|
31630
31753
|
};
|
|
31631
31754
|
}
|
|
@@ -31704,6 +31827,7 @@ var DISPATCH_PAYLOAD_SCHEMAS = {
|
|
|
31704
31827
|
"issue.closed": IssueEventPayloadSchema,
|
|
31705
31828
|
"artifact.created": ArtifactCreatedEventPayloadSchema,
|
|
31706
31829
|
"artifact.version": ArtifactVersionEventPayloadSchema,
|
|
31830
|
+
"artifact.human_edited": ArtifactHumanEditedEventPayloadSchema,
|
|
31707
31831
|
"ask.opened": AskEventPayloadSchema,
|
|
31708
31832
|
"ask.anchor_refreshed": AskEventPayloadSchema,
|
|
31709
31833
|
"ask.edited": AskEditedEventPayloadSchema,
|
|
@@ -31775,6 +31899,12 @@ function askResolutionText(resolution) {
|
|
|
31775
31899
|
return reason === "" ? kind : `${kind}: ${reason}`;
|
|
31776
31900
|
}
|
|
31777
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
|
+
}
|
|
31778
31908
|
if (event.type === "comment.created") {
|
|
31779
31909
|
if (comment?.ask_id === undefined || comment.ask_id === null)
|
|
31780
31910
|
return;
|
|
@@ -31974,6 +32104,7 @@ function renderInbound(raw, sessionID, subject2) {
|
|
|
31974
32104
|
let pictures = [];
|
|
31975
32105
|
let inReplyTo = envelope2.in_reply_to;
|
|
31976
32106
|
let askAuthor;
|
|
32107
|
+
let trailer = "";
|
|
31977
32108
|
const dispatchRendered = envelope2.source === "dispatch" && envelope2.payload !== undefined;
|
|
31978
32109
|
if (envelope2.source === "dispatch") {
|
|
31979
32110
|
const topic = subject2 ?? envelope2.topic;
|
|
@@ -32078,6 +32209,11 @@ function renderInbound(raw, sessionID, subject2) {
|
|
|
32078
32209
|
};
|
|
32079
32210
|
dispatchActor = frame.event.actor;
|
|
32080
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
|
+
}
|
|
32081
32217
|
} else {
|
|
32082
32218
|
dispatchEvent = frame.raw;
|
|
32083
32219
|
rejectedDelivery = frame.rejectedDelivery;
|
|
@@ -32143,7 +32279,9 @@ function renderInbound(raw, sessionID, subject2) {
|
|
|
32143
32279
|
};
|
|
32144
32280
|
return {
|
|
32145
32281
|
skip: false,
|
|
32146
|
-
content: encode3({ envoy: rendered })
|
|
32282
|
+
content: trailer === "" ? encode3({ envoy: rendered }) : `${encode3({ envoy: rendered })}
|
|
32283
|
+
|
|
32284
|
+
${trailer}`,
|
|
32147
32285
|
envelope: envelope2,
|
|
32148
32286
|
...dispatchActor === undefined ? {} : { dispatchActor },
|
|
32149
32287
|
...delivery === undefined ? {} : { delivery },
|
|
@@ -33854,115 +33992,1127 @@ function natsAuthOptions(seed) {
|
|
|
33854
33992
|
return { authenticator: import_nats.nkeyAuthenticator(bytes) };
|
|
33855
33993
|
}
|
|
33856
33994
|
|
|
33857
|
-
// ../envoy-client/src/
|
|
33858
|
-
|
|
33859
|
-
|
|
33860
|
-
|
|
33861
|
-
|
|
33862
|
-
|
|
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");
|
|
33863
34069
|
}
|
|
34070
|
+
return interests;
|
|
33864
34071
|
}
|
|
33865
|
-
function
|
|
33866
|
-
|
|
33867
|
-
|
|
33868
|
-
|
|
33869
|
-
|
|
33870
|
-
|
|
33871
|
-
|
|
33872
|
-
if (missing !== null && dispatchQuiet && envoyQuiet) {
|
|
33873
|
-
parts.push(missingConfigNotice(config2.path, missing, "Dispatch and Envoy are off"));
|
|
33874
|
-
} else {
|
|
33875
|
-
if (!dispatch.enabled && dispatch.error !== null)
|
|
33876
|
-
parts.push(`Dispatch is off: ${dispatch.error}`);
|
|
33877
|
-
else if (dispatchQuiet && missing !== null) {
|
|
33878
|
-
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;
|
|
33879
34079
|
}
|
|
33880
|
-
|
|
33881
|
-
|
|
33882
|
-
|
|
33883
|
-
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`);
|
|
33884
34083
|
}
|
|
34084
|
+
expanded.add(base);
|
|
34085
|
+
expanded.add(topic);
|
|
33885
34086
|
}
|
|
33886
|
-
|
|
33887
|
-
parts.push(checkout.envoyError);
|
|
33888
|
-
if (checkout?.kind === "invalid" && (dispatch.enabled || dispatch.error !== checkout.error)) {
|
|
33889
|
-
parts.push(`${checkout.error}; not read while DISPATCH_URL is set`);
|
|
33890
|
-
}
|
|
33891
|
-
parts.push(...config2.warnings);
|
|
33892
|
-
if (envoy.enabled && nats && "off" in envoy.inbound) {
|
|
33893
|
-
parts.push(`Envoy's inbound messages are off: ${envoy.inbound.off}; the Envoy tools still work`);
|
|
33894
|
-
}
|
|
33895
|
-
if (envoy.enabled && envoy.passDeadlineRaisedFrom !== undefined) {
|
|
33896
|
-
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`);
|
|
33897
|
-
}
|
|
33898
|
-
return parts.length === 0 ? null : parts.join("; ");
|
|
34087
|
+
return [...expanded];
|
|
33899
34088
|
}
|
|
33900
|
-
|
|
33901
|
-
|
|
33902
|
-
|
|
33903
|
-
|
|
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;
|
|
33904
34106
|
}
|
|
33905
|
-
const config2 = readEnvoyConfig(file2.path, env, options);
|
|
33906
|
-
const dispatch = dispatchSettings(env, config2);
|
|
33907
|
-
const envoy = envoySettings(env, config2, { nats: options.nats });
|
|
33908
|
-
return {
|
|
33909
|
-
dispatch,
|
|
33910
|
-
envoy,
|
|
33911
|
-
notice: startNotice(config2, dispatch, envoy, options.nats !== false)
|
|
33912
|
-
};
|
|
33913
34107
|
}
|
|
33914
|
-
function
|
|
33915
|
-
|
|
33916
|
-
|
|
33917
|
-
const
|
|
33918
|
-
|
|
33919
|
-
|
|
33920
|
-
|
|
33921
|
-
|
|
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");
|
|
33922
34150
|
};
|
|
33923
|
-
|
|
33924
|
-
|
|
33925
|
-
|
|
33926
|
-
|
|
33927
|
-
|
|
33928
|
-
|
|
33929
|
-
|
|
33930
|
-
|
|
33931
|
-
|
|
33932
|
-
|
|
33933
|
-
|
|
33934
|
-
|
|
33935
|
-
|
|
33936
|
-
|
|
33937
|
-
|
|
33938
|
-
|
|
33939
|
-
|
|
33940
|
-
|
|
33941
|
-
|
|
33942
|
-
|
|
33943
|
-
|
|
33944
|
-
|
|
33945
|
-
|
|
33946
|
-
|
|
33947
|
-
|
|
33948
|
-
|
|
33949
|
-
|
|
33950
|
-
|
|
33951
|
-
|
|
33952
|
-
|
|
33953
|
-
|
|
33954
|
-
|
|
33955
|
-
|
|
33956
|
-
|
|
33957
|
-
|
|
33958
|
-
|
|
33959
|
-
|
|
33960
|
-
|
|
33961
|
-
|
|
33962
|
-
|
|
33963
|
-
|
|
33964
|
-
|
|
33965
|
-
|
|
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",
|
|
35095
|
+
"duplicate_channel_not_found",
|
|
35096
|
+
"duplicate_message_not_found",
|
|
35097
|
+
"ekm_access_denied",
|
|
35098
|
+
"enterprise_is_restricted",
|
|
35099
|
+
"fatal_error",
|
|
35100
|
+
"internal_error",
|
|
35101
|
+
"invalid_arg_name",
|
|
35102
|
+
"invalid_arguments",
|
|
35103
|
+
"invalid_array_arg",
|
|
35104
|
+
"invalid_auth",
|
|
35105
|
+
"invalid_blocks",
|
|
35106
|
+
"invalid_blocks_format",
|
|
35107
|
+
"invalid_charset",
|
|
35108
|
+
"invalid_form_data",
|
|
35109
|
+
"invalid_metadata_format",
|
|
35110
|
+
"invalid_metadata_schema",
|
|
35111
|
+
"invalid_post_type",
|
|
35112
|
+
"is_archived",
|
|
35113
|
+
"markdown_text_conflict",
|
|
35114
|
+
"message_limit_exceeded",
|
|
35115
|
+
"messages_tab_disabled",
|
|
33966
35116
|
"metadata_must_be_sent_from_app",
|
|
33967
35117
|
"metadata_too_large",
|
|
33968
35118
|
"method_deprecated",
|
|
@@ -34196,403 +35346,162 @@ function posterLine(stdout) {
|
|
|
34196
35346
|
return;
|
|
34197
35347
|
try {
|
|
34198
35348
|
const parsed = JSON.parse(last);
|
|
34199
|
-
return typeof parsed === "object" && parsed !== null ? parsed : undefined;
|
|
34200
|
-
} catch {
|
|
34201
|
-
return;
|
|
34202
|
-
}
|
|
34203
|
-
}
|
|
34204
|
-
function allowedAPIURL(value) {
|
|
34205
|
-
let url2;
|
|
34206
|
-
try {
|
|
34207
|
-
url2 = new URL(value);
|
|
34208
|
-
} catch {
|
|
34209
|
-
return false;
|
|
34210
|
-
}
|
|
34211
|
-
if (url2.protocol === "https:")
|
|
34212
|
-
return true;
|
|
34213
|
-
return url2.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]"].includes(url2.hostname);
|
|
34214
|
-
}
|
|
34215
|
-
|
|
34216
|
-
// ../envoy-client/src/tool-contract.ts
|
|
34217
|
-
var DELIVERY_CONTRACT = "Delivery is at-least-once, possibly out of order across topics; use id for dedupe and at for freshness.";
|
|
34218
|
-
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>.";
|
|
34219
|
-
var URGENCY_VALUES = EnvelopeSchema.shape.urgency.unwrap().options;
|
|
34220
|
-
var EXPECTS_REPLY_VALUES = EnvelopeSchema.shape.expects_reply.unwrap().options;
|
|
34221
|
-
function messageMetadataShape(schema) {
|
|
34222
|
-
return {
|
|
34223
|
-
in_reply_to: schema.string().optional(),
|
|
34224
|
-
supersedes: schema.string().optional(),
|
|
34225
|
-
urgency: schema.enum(URGENCY_VALUES).describe("low | med | high | blocking").optional(),
|
|
34226
|
-
expects_reply: schema.enum(EXPECTS_REPLY_VALUES).describe("none | optional | required").optional(),
|
|
34227
|
-
expires_at: schema.number({ int: true }).optional()
|
|
34228
|
-
};
|
|
34229
|
-
}
|
|
34230
|
-
var MessageMetadataSchema = exports_external.object(messageMetadataShape(zodSchemaApi(exports_external)));
|
|
34231
|
-
function toMessageMetadata(args) {
|
|
34232
|
-
return {
|
|
34233
|
-
...args.in_reply_to === undefined ? {} : { inReplyTo: args.in_reply_to },
|
|
34234
|
-
...args.supersedes === undefined ? {} : { supersedes: args.supersedes },
|
|
34235
|
-
...args.urgency === undefined ? {} : { urgency: args.urgency },
|
|
34236
|
-
...args.expects_reply === undefined ? {} : { expectsReply: args.expects_reply },
|
|
34237
|
-
...args.expires_at === undefined ? {} : { expiresAt: args.expires_at }
|
|
34238
|
-
};
|
|
34239
|
-
}
|
|
34240
|
-
function messageArguments(schema) {
|
|
34241
|
-
return { message: schema.string(), ...messageMetadataShape(schema) };
|
|
34242
|
-
}
|
|
34243
|
-
var EnvoyToolOperation = {
|
|
34244
|
-
subscribe: "subscribe",
|
|
34245
|
-
unsubscribe: "unsubscribe",
|
|
34246
|
-
listInterests: "listInterests",
|
|
34247
|
-
inbox: "inbox",
|
|
34248
|
-
send: "send",
|
|
34249
|
-
publish: "publish",
|
|
34250
|
-
setRole: "setRole",
|
|
34251
|
-
getRole: "getRole",
|
|
34252
|
-
whoami: "whoami",
|
|
34253
|
-
listSessions: "listSessions",
|
|
34254
|
-
slackPost: "slackPost"
|
|
34255
|
-
};
|
|
34256
|
-
var envoyToolSpecs = [
|
|
34257
|
-
{
|
|
34258
|
-
name: "envoy_subscribe",
|
|
34259
|
-
description: `Subscribe this session to Envoy notification topics. ${TOPIC_GUIDE}`,
|
|
34260
|
-
arguments: (schema) => ({
|
|
34261
|
-
topics: schema.array(schema.string()).describe("NATS-style topic patterns to subscribe to.")
|
|
34262
|
-
}),
|
|
34263
|
-
operation: EnvoyToolOperation.subscribe
|
|
34264
|
-
},
|
|
34265
|
-
{
|
|
34266
|
-
name: "envoy_unsubscribe",
|
|
34267
|
-
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.",
|
|
34268
|
-
arguments: (schema) => ({ topics: schema.array(schema.string()).optional() }),
|
|
34269
|
-
operation: EnvoyToolOperation.unsubscribe
|
|
34270
|
-
},
|
|
34271
|
-
{
|
|
34272
|
-
name: "envoy_list",
|
|
34273
|
-
description: "List the current Envoy topic subscriptions for this session so you can confirm the exact topic shapes that are active.",
|
|
34274
|
-
arguments: () => ({}),
|
|
34275
|
-
operation: EnvoyToolOperation.listInterests
|
|
34276
|
-
},
|
|
34277
|
-
{
|
|
34278
|
-
name: "envoy_inbox",
|
|
34279
|
-
description: "List this Pi session's 50 most recent rendered Envoy deliveries, newest first.",
|
|
34280
|
-
arguments: () => ({}),
|
|
34281
|
-
operation: EnvoyToolOperation.inbox
|
|
34282
|
-
},
|
|
34283
|
-
{
|
|
34284
|
-
name: "envoy_send",
|
|
34285
|
-
description: `Send an Envoy agent-to-agent message directly to another session by session ID. ${DELIVERY_CONTRACT}`,
|
|
34286
|
-
arguments: (schema) => ({
|
|
34287
|
-
session_id: schema.string().describe("Target session ID; find it with envoy_sessions or envoy_whoami."),
|
|
34288
|
-
...messageArguments(schema)
|
|
34289
|
-
}),
|
|
34290
|
-
operation: EnvoyToolOperation.send
|
|
34291
|
-
},
|
|
34292
|
-
{
|
|
34293
|
-
name: "envoy_publish",
|
|
34294
|
-
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}`,
|
|
34295
|
-
arguments: (schema) => ({ topic: schema.string(), ...messageArguments(schema) }),
|
|
34296
|
-
operation: EnvoyToolOperation.publish
|
|
34297
|
-
},
|
|
34298
|
-
{
|
|
34299
|
-
name: "envoy_role_set",
|
|
34300
|
-
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.",
|
|
34301
|
-
arguments: (schema) => ({ role: schema.string() }),
|
|
34302
|
-
operation: EnvoyToolOperation.setRole
|
|
34303
|
-
},
|
|
34304
|
-
{
|
|
34305
|
-
name: "envoy_role_get",
|
|
34306
|
-
description: "Get the live holder of a named Envoy role.",
|
|
34307
|
-
arguments: (schema) => ({ role: schema.string() }),
|
|
34308
|
-
operation: EnvoyToolOperation.getRole
|
|
34309
|
-
},
|
|
34310
|
-
{
|
|
34311
|
-
name: "envoy_whoami",
|
|
34312
|
-
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.",
|
|
34313
|
-
arguments: () => ({}),
|
|
34314
|
-
operation: EnvoyToolOperation.whoami
|
|
34315
|
-
},
|
|
34316
|
-
{
|
|
34317
|
-
name: "envoy_sessions",
|
|
34318
|
-
description: "List all live sessions registered with Envoy. Filter by optional machine, directory, or title.",
|
|
34319
|
-
arguments: (schema) => ({
|
|
34320
|
-
machine: schema.string().optional(),
|
|
34321
|
-
dir: schema.string().optional(),
|
|
34322
|
-
title: schema.string().optional()
|
|
34323
|
-
}),
|
|
34324
|
-
operation: EnvoyToolOperation.listSessions
|
|
34325
|
-
},
|
|
34326
|
-
{
|
|
34327
|
-
name: "slack_post",
|
|
34328
|
-
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.",
|
|
34329
|
-
arguments: (schema) => ({
|
|
34330
|
-
channel: schema.string({ min: 1 }).describe("Slack channel id, such as C0123ABCD."),
|
|
34331
|
-
thread_ts: schema.string({ min: 1 }).describe("The thread's root ts, which keeps the reply in the mention's thread."),
|
|
34332
|
-
text: schema.string({ min: 1, max: SLACK_POST_TEXT_MAX }).describe(`The reply, in Slack mrkdwn, at most ${SLACK_POST_TEXT_MAX} characters.`)
|
|
34333
|
-
}),
|
|
34334
|
-
operation: EnvoyToolOperation.slackPost
|
|
34335
|
-
}
|
|
34336
|
-
];
|
|
34337
|
-
function sendConfirmationText(result) {
|
|
34338
|
-
return `sent ${result.envelope.event_id} to ${result.recipient}${result.confirmed ? "" : " (recipient unconfirmed by listener)"}`;
|
|
34339
|
-
}
|
|
34340
|
-
var envoyToolSchemas = new Map;
|
|
34341
|
-
function parseEnvoyToolArguments(operation, parameters) {
|
|
34342
|
-
const spec = envoyToolSpecs.find((candidate) => candidate.operation === operation);
|
|
34343
|
-
if (spec === undefined)
|
|
34344
|
-
throw new Error(`missing Envoy tool specification for ${operation}`);
|
|
34345
|
-
let schema = envoyToolSchemas.get(operation);
|
|
34346
|
-
if (schema === undefined) {
|
|
34347
|
-
schema = exports_external.object(spec.arguments(zodSchemaApi(exports_external))).strict();
|
|
34348
|
-
envoyToolSchemas.set(operation, schema);
|
|
34349
|
-
}
|
|
34350
|
-
const parsed = schema.safeParse(parameters, { reportInput: true });
|
|
34351
|
-
if (!parsed.success) {
|
|
34352
|
-
throw new ToolInputError(spec.name, formatZodIssues(parsed.error.issues, schema, spec.name));
|
|
34353
|
-
}
|
|
34354
|
-
return parsed.data;
|
|
34355
|
-
}
|
|
34356
|
-
|
|
34357
|
-
// ../envoy-client/src/transport.ts
|
|
34358
|
-
var DEFAULT_TIMEOUT_MS = 5000;
|
|
34359
|
-
var RETRY_DELAY_MS = 250;
|
|
34360
|
-
var InterestWireSchema = exports_external.object({
|
|
34361
|
-
session_id: exports_external.string(),
|
|
34362
|
-
machine_id: exports_external.string(),
|
|
34363
|
-
dir: exports_external.string(),
|
|
34364
|
-
topics: exports_external.array(exports_external.string()),
|
|
34365
|
-
updated_at: exports_external.number().int().optional(),
|
|
34366
|
-
warnings: exports_external.array(exports_external.string()).optional()
|
|
34367
|
-
});
|
|
34368
|
-
var SessionWireSchema = exports_external.object({
|
|
34369
|
-
session_id: exports_external.string(),
|
|
34370
|
-
machine_id: exports_external.string(),
|
|
34371
|
-
host: exports_external.string().optional(),
|
|
34372
|
-
dir: exports_external.string(),
|
|
34373
|
-
port: exports_external.number().int(),
|
|
34374
|
-
title: exports_external.string(),
|
|
34375
|
-
topics: exports_external.array(exports_external.string()),
|
|
34376
|
-
roles: exports_external.array(exports_external.string()).optional(),
|
|
34377
|
-
capabilities: exports_external.array(exports_external.string()).optional(),
|
|
34378
|
-
self_subscribed: exports_external.boolean(),
|
|
34379
|
-
last_seen: exports_external.number().int().optional()
|
|
34380
|
-
});
|
|
34381
|
-
var RoleWireSchema = exports_external.object({
|
|
34382
|
-
role: exports_external.string(),
|
|
34383
|
-
holder: exports_external.string(),
|
|
34384
|
-
host: exports_external.string().optional(),
|
|
34385
|
-
last_seen: exports_external.number().int()
|
|
34386
|
-
});
|
|
34387
|
-
var RoleHeldWireSchema = exports_external.object({
|
|
34388
|
-
error: exports_external.string(),
|
|
34389
|
-
role: exports_external.string(),
|
|
34390
|
-
holder: exports_external.string()
|
|
34391
|
-
});
|
|
34392
|
-
var ErrorWireSchema = exports_external.object({
|
|
34393
|
-
error: exports_external.string(),
|
|
34394
|
-
expected: exports_external.array(exports_external.string()).optional()
|
|
34395
|
-
});
|
|
34396
|
-
var EnvelopeResponseSchema = EnvelopeSchema.extend({
|
|
34397
|
-
recipient: exports_external.string().optional(),
|
|
34398
|
-
holder: exports_external.string().optional()
|
|
34399
|
-
});
|
|
34400
|
-
function mergeInterestSources(registryTopics, liveTopics) {
|
|
34401
|
-
const interests = new Map;
|
|
34402
|
-
for (const topic of registryTopics) {
|
|
34403
|
-
interests.set(topic, liveTopics.includes(topic) ? "both" : "registry");
|
|
34404
|
-
}
|
|
34405
|
-
for (const topic of liveTopics) {
|
|
34406
|
-
if (!interests.has(topic))
|
|
34407
|
-
interests.set(topic, "live");
|
|
35349
|
+
return typeof parsed === "object" && parsed !== null ? parsed : undefined;
|
|
35350
|
+
} catch {
|
|
35351
|
+
return;
|
|
34408
35352
|
}
|
|
34409
|
-
return interests;
|
|
34410
35353
|
}
|
|
34411
|
-
function
|
|
34412
|
-
|
|
34413
|
-
|
|
34414
|
-
|
|
34415
|
-
|
|
34416
|
-
|
|
34417
|
-
continue;
|
|
34418
|
-
}
|
|
34419
|
-
const segments = base.split(".");
|
|
34420
|
-
if (segments.length < 2 || segments.some((segment) => segment.length === 0)) {
|
|
34421
|
-
throw new TypeError(`cannot expand Envoy wildcard topic "${topic}": its concrete base must have at least two non-empty segments`);
|
|
34422
|
-
}
|
|
34423
|
-
expanded.add(base);
|
|
34424
|
-
expanded.add(topic);
|
|
35354
|
+
function allowedAPIURL(value) {
|
|
35355
|
+
let url2;
|
|
35356
|
+
try {
|
|
35357
|
+
url2 = new URL(value);
|
|
35358
|
+
} catch {
|
|
35359
|
+
return false;
|
|
34425
35360
|
}
|
|
34426
|
-
|
|
35361
|
+
if (url2.protocol === "https:")
|
|
35362
|
+
return true;
|
|
35363
|
+
return url2.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]"].includes(url2.hostname);
|
|
34427
35364
|
}
|
|
34428
35365
|
|
|
34429
|
-
|
|
34430
|
-
|
|
34431
|
-
|
|
34432
|
-
|
|
34433
|
-
|
|
34434
|
-
|
|
34435
|
-
try {
|
|
34436
|
-
const result = ErrorWireSchema.safeParse(JSON.parse(details.responseBody));
|
|
34437
|
-
if (result.success)
|
|
34438
|
-
parsed = result.data;
|
|
34439
|
-
} catch {}
|
|
34440
|
-
super(parsed === undefined ? `${details.method} ${details.url} failed with ${details.status}: ${details.responseBody}` : `${parsed.error}${parsed.expected === undefined ? "" : ` (expected: ${parsed.expected.join(", ")})`}`);
|
|
34441
|
-
this.details = details;
|
|
34442
|
-
this.expected = parsed?.expected;
|
|
34443
|
-
}
|
|
34444
|
-
}
|
|
34445
|
-
function createEnvoyClient(config2) {
|
|
34446
|
-
const baseUrl = normalizeEnvoyUrl(config2.baseUrl);
|
|
34447
|
-
const timeoutMs = config2.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
34448
|
-
const apiToken = config2.token;
|
|
34449
|
-
const request = async (path2, init) => {
|
|
34450
|
-
const url2 = `${baseUrl}${path2}`;
|
|
34451
|
-
const attempts = config2.retry === false ? 1 : 2;
|
|
34452
|
-
for (let attempt = 0;attempt < attempts; attempt += 1) {
|
|
34453
|
-
let response;
|
|
34454
|
-
try {
|
|
34455
|
-
const headers = new Headers(init.headers);
|
|
34456
|
-
if (apiToken)
|
|
34457
|
-
headers.set("Authorization", `Bearer ${apiToken}`);
|
|
34458
|
-
response = await config2.fetch(url2, {
|
|
34459
|
-
...init,
|
|
34460
|
-
headers,
|
|
34461
|
-
signal: AbortSignal.timeout(timeoutMs)
|
|
34462
|
-
});
|
|
34463
|
-
} catch (error49) {
|
|
34464
|
-
if (attempt + 1 < attempts) {
|
|
34465
|
-
await waitForRetry();
|
|
34466
|
-
continue;
|
|
34467
|
-
}
|
|
34468
|
-
throw error49;
|
|
34469
|
-
}
|
|
34470
|
-
const responseBody = await response.text();
|
|
34471
|
-
if (response.ok)
|
|
34472
|
-
return responseBody;
|
|
34473
|
-
const error48 = new EnvoyApiError({
|
|
34474
|
-
method: init.method ?? "GET",
|
|
34475
|
-
url: url2,
|
|
34476
|
-
status: response.status,
|
|
34477
|
-
responseBody
|
|
34478
|
-
});
|
|
34479
|
-
if (response.status >= 500 && attempt + 1 < attempts) {
|
|
34480
|
-
await waitForRetry();
|
|
34481
|
-
continue;
|
|
34482
|
-
}
|
|
34483
|
-
throw error48;
|
|
34484
|
-
}
|
|
34485
|
-
throw new Error("Envoy request exhausted retries");
|
|
34486
|
-
};
|
|
34487
|
-
const post = (path2, body) => request(path2, {
|
|
34488
|
-
method: "POST",
|
|
34489
|
-
headers: { "Content-Type": "application/json" },
|
|
34490
|
-
body: JSON.stringify(body)
|
|
34491
|
-
});
|
|
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) {
|
|
34492
35372
|
return {
|
|
34493
|
-
|
|
34494
|
-
|
|
34495
|
-
|
|
34496
|
-
|
|
34497
|
-
|
|
34498
|
-
title: input.title,
|
|
34499
|
-
...input.capabilities === undefined ? {} : { capabilities: input.capabilities },
|
|
34500
|
-
driving: input.driving,
|
|
34501
|
-
...input.selfSubscribed === undefined ? {} : { self_subscribed: input.selfSubscribed },
|
|
34502
|
-
host: machineID()
|
|
34503
|
-
}))),
|
|
34504
|
-
unsubscribe: async (input) => {
|
|
34505
|
-
await post("/v1/interests/unsubscribe", {
|
|
34506
|
-
session_id: input.sessionID,
|
|
34507
|
-
topics: expandSubscriptionTopics(input.topics)
|
|
34508
|
-
});
|
|
34509
|
-
},
|
|
34510
|
-
getInterest: async (sessionID) => InterestWireSchema.parse(JSON.parse(await request(`/v1/interests/${sessionID}`, {}))),
|
|
34511
|
-
send: async (input) => {
|
|
34512
|
-
const idempotencyKey = input.idempotencyKey ?? crypto.randomUUID();
|
|
34513
|
-
const response = EnvelopeResponseSchema.parse(JSON.parse(await post("/v1/messages/send", {
|
|
34514
|
-
source: input.source ?? "agent",
|
|
34515
|
-
...sourceSession(input.sourceSessionID),
|
|
34516
|
-
target_session: input.targetSessionID,
|
|
34517
|
-
message: input.message,
|
|
34518
|
-
idempotency_key: idempotencyKey,
|
|
34519
|
-
...messageMetadata(input)
|
|
34520
|
-
})));
|
|
34521
|
-
return {
|
|
34522
|
-
envelope: response,
|
|
34523
|
-
recipient: response.recipient ?? input.targetSessionID,
|
|
34524
|
-
confirmed: response.recipient !== undefined
|
|
34525
|
-
};
|
|
34526
|
-
},
|
|
34527
|
-
publish: async (input) => {
|
|
34528
|
-
const idempotencyKey = input.idempotencyKey ?? crypto.randomUUID();
|
|
34529
|
-
const response = EnvelopeResponseSchema.parse(JSON.parse(await post("/v1/messages/publish", {
|
|
34530
|
-
source: input.source ?? "agent",
|
|
34531
|
-
...sourceSession(input.sourceSessionID),
|
|
34532
|
-
topic: input.topic,
|
|
34533
|
-
message: input.message,
|
|
34534
|
-
...input.payload === undefined ? {} : { payload: input.payload },
|
|
34535
|
-
idempotency_key: idempotencyKey,
|
|
34536
|
-
...messageMetadata(input)
|
|
34537
|
-
})));
|
|
34538
|
-
return {
|
|
34539
|
-
envelope: response,
|
|
34540
|
-
...response.holder === undefined ? {} : { holder: response.holder }
|
|
34541
|
-
};
|
|
34542
|
-
},
|
|
34543
|
-
unregisterSession: async (sessionID) => {
|
|
34544
|
-
await request(`/v1/sessions/${encodeURIComponent(sessionID)}`, { method: "DELETE" });
|
|
34545
|
-
},
|
|
34546
|
-
setRole: async (input) => {
|
|
34547
|
-
const soft = input.soft === true;
|
|
34548
|
-
const previous = soft ? input.previousSessionID ?? "" : "";
|
|
34549
|
-
const body = {
|
|
34550
|
-
session_id: input.sessionID,
|
|
34551
|
-
role: input.role,
|
|
34552
|
-
...soft ? { soft: true } : {},
|
|
34553
|
-
...previous === "" ? {} : { previous_session_id: previous }
|
|
34554
|
-
};
|
|
34555
|
-
let raw;
|
|
34556
|
-
try {
|
|
34557
|
-
raw = await post("/v1/roles/set", body);
|
|
34558
|
-
} catch (error48) {
|
|
34559
|
-
if (error48 instanceof EnvoyApiError && error48.details.status === 409) {
|
|
34560
|
-
const held = RoleHeldWireSchema.safeParse(JSON.parse(error48.details.responseBody));
|
|
34561
|
-
if (held.success)
|
|
34562
|
-
return { claimed: false, holder: held.data.holder };
|
|
34563
|
-
}
|
|
34564
|
-
throw error48;
|
|
34565
|
-
}
|
|
34566
|
-
return { claimed: true, interest: InterestWireSchema.parse(JSON.parse(raw)) };
|
|
34567
|
-
},
|
|
34568
|
-
getRole: async (role) => RoleWireSchema.parse(JSON.parse(await request(`/v1/roles/${encodeURIComponent(role)}`, { method: "GET" }))),
|
|
34569
|
-
listSessions: async (input = {}) => {
|
|
34570
|
-
const search = new URLSearchParams;
|
|
34571
|
-
if (input.directory !== undefined)
|
|
34572
|
-
search.set("dir", input.directory);
|
|
34573
|
-
if (input.title !== undefined)
|
|
34574
|
-
search.set("title", input.title);
|
|
34575
|
-
const query = search.size === 0 ? "" : `?${search.toString()}`;
|
|
34576
|
-
return SessionWireSchema.array().parse(JSON.parse(await request(`/v1/sessions${query}`, {})));
|
|
34577
|
-
}
|
|
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()
|
|
34578
35378
|
};
|
|
34579
35379
|
}
|
|
34580
|
-
|
|
34581
|
-
|
|
34582
|
-
setTimeout(resolve2, RETRY_DELAY_MS);
|
|
34583
|
-
return promise2;
|
|
34584
|
-
}
|
|
34585
|
-
function messageMetadata(input) {
|
|
35380
|
+
var MessageMetadataSchema = exports_external.object(messageMetadataShape(zodSchemaApi(exports_external)));
|
|
35381
|
+
function toMessageMetadata(args) {
|
|
34586
35382
|
return {
|
|
34587
|
-
...
|
|
34588
|
-
...
|
|
34589
|
-
...
|
|
34590
|
-
...
|
|
34591
|
-
...
|
|
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 }
|
|
34592
35388
|
};
|
|
34593
35389
|
}
|
|
34594
|
-
function
|
|
34595
|
-
return
|
|
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;
|
|
34596
35505
|
}
|
|
34597
35506
|
|
|
34598
35507
|
// ../pi-shared/src/interface.ts
|
|
@@ -35380,6 +36289,166 @@ function resolveEnvoySession(sessionFile) {
|
|
|
35380
36289
|
return [...sessions.values()][0] ?? "";
|
|
35381
36290
|
}
|
|
35382
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
|
+
|
|
35383
36452
|
// src/opens-ask.ts
|
|
35384
36453
|
function adviceCount(details, key) {
|
|
35385
36454
|
const count = asObject(asObject(details)?.advice)?.[key];
|
|
@@ -35471,6 +36540,219 @@ class TypedPictures {
|
|
|
35471
36540
|
}
|
|
35472
36541
|
}
|
|
35473
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
|
+
|
|
35474
36756
|
// extensions/envoy-message-renderer.ts
|
|
35475
36757
|
import { Box, Spacer, Text } from "@oh-my-pi/pi-tui";
|
|
35476
36758
|
var ENVOY_MESSAGE_COLLAPSED_LINES = 12;
|
|
@@ -35554,6 +36836,8 @@ function liveSessionSettings(live) {
|
|
|
35554
36836
|
var codec2 = import_nats2.StringCodec();
|
|
35555
36837
|
var NATS_RETRY_INTERVAL_MS = 15000;
|
|
35556
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.";
|
|
35557
36841
|
var UNFENCED = () => true;
|
|
35558
36842
|
|
|
35559
36843
|
class AbandonedTaskError extends Error {
|
|
@@ -35851,13 +37135,17 @@ function envoyExtension(pi) {
|
|
|
35851
37135
|
awarenessGeneration++;
|
|
35852
37136
|
}
|
|
35853
37137
|
legionManagedTranscript = branch.some(isLegionManagedEntry);
|
|
35854
|
-
|
|
37138
|
+
const entries = context.sessionManager.getEntries();
|
|
37139
|
+
handledDispatchAttempts = handledAttempts(entries);
|
|
37140
|
+
replay?.restore(replaySnapshot(entries));
|
|
37141
|
+
unwritten.requeueNotices(heldReplayNotices(entries));
|
|
35855
37142
|
markPicturesShown(shownPictures(sessionID), transcriptPictures(branch));
|
|
35856
37143
|
if (previousSessionID !== sessionID) {
|
|
35857
37144
|
forgetShownPictures(previousSessionID);
|
|
35858
37145
|
if (notedSessionIDs.delete(previousSessionID))
|
|
35859
37146
|
forgetInjectedUserTurns(previousSessionID);
|
|
35860
37147
|
typedPictures.dropOtherSessions(sessionID);
|
|
37148
|
+
unwritten.releaseOtherSessions(sessionID);
|
|
35861
37149
|
}
|
|
35862
37150
|
};
|
|
35863
37151
|
let dispatchLedger;
|
|
@@ -35914,8 +37202,23 @@ function envoyExtension(pi) {
|
|
|
35914
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");
|
|
35915
37203
|
}
|
|
35916
37204
|
connection = dialled;
|
|
37205
|
+
watchReconnects(dialled);
|
|
35917
37206
|
return connection;
|
|
35918
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
|
+
};
|
|
35919
37222
|
const postDispatchReply = async (delivery, result, replySessionID = sessionID) => {
|
|
35920
37223
|
await postDeliveryReply(currentDispatchConfig(), replySessionID, delivery, result);
|
|
35921
37224
|
};
|
|
@@ -35926,6 +37229,80 @@ function envoyExtension(pi) {
|
|
|
35926
37229
|
const images = typedPictures.handOver(event.text);
|
|
35927
37230
|
return images === undefined ? undefined : { images: [...event.images ?? [], ...images] };
|
|
35928
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
|
+
};
|
|
35929
37306
|
const runTypedInput = (sendUserInput, delivery, replySessionID, turn, content, pictureAddresses2) => {
|
|
35930
37307
|
const images = typeof content === "string" ? [] : content.filter((block) => block.type === "image");
|
|
35931
37308
|
const noted = sessionID;
|
|
@@ -35946,14 +37323,17 @@ function envoyExtension(pi) {
|
|
|
35946
37323
|
const submitted = result.handled === "prompt" || result.handled === "skill";
|
|
35947
37324
|
if (submitted) {
|
|
35948
37325
|
typedPictures.inputPassed(turn.messageId);
|
|
37326
|
+
unwritten.turnSubmitted(turn.messageId);
|
|
35949
37327
|
} else {
|
|
35950
37328
|
dropInjectedUserTurn(noted, turn.messageId);
|
|
35951
37329
|
typedPictures.withdraw(turn.messageId);
|
|
37330
|
+
unwritten.turnHandled(turn.messageId);
|
|
35952
37331
|
}
|
|
35953
37332
|
return typedInputReply(turn.body, result);
|
|
35954
37333
|
}, (error48) => {
|
|
35955
37334
|
dropInjectedUserTurn(noted, turn.messageId);
|
|
35956
37335
|
typedPictures.withdraw(turn.messageId);
|
|
37336
|
+
unwritten.turnHandled(turn.messageId);
|
|
35957
37337
|
return typedInputReply(turn.body, { error: messageFor(error48) });
|
|
35958
37338
|
}).then(async (reply) => {
|
|
35959
37339
|
refreshAgentStreamSettings(sessionID);
|
|
@@ -35996,7 +37376,7 @@ function envoyExtension(pi) {
|
|
|
35996
37376
|
return;
|
|
35997
37377
|
}
|
|
35998
37378
|
};
|
|
35999
|
-
const deliver = async (subject2, raw, reply) => {
|
|
37379
|
+
const deliver = async (topic, subject2, raw, reply, receivedAt) => {
|
|
36000
37380
|
const rendered = renderInbound(raw, sessionID, subject2);
|
|
36001
37381
|
const directSubject = agentSubject(sessionID);
|
|
36002
37382
|
if (expectsLaneReceipt({
|
|
@@ -36011,22 +37391,30 @@ function envoyExtension(pi) {
|
|
|
36011
37391
|
console.warn(`[envoy] failed to acknowledge envelope ${rendered.envelope?.event_id ?? "unknown"}`, error48);
|
|
36012
37392
|
}
|
|
36013
37393
|
}
|
|
36014
|
-
|
|
36015
|
-
|
|
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();
|
|
36016
37401
|
const dedupeIdentity = ClaimIdentitySchema.safeParse(rendered.envelope);
|
|
36017
|
-
const
|
|
37402
|
+
const identity = dedupeIdentity.success ? dedupeIdentity.data : undefined;
|
|
37403
|
+
const claim2 = rendered.skip ? undefined : delivered.claim(identity);
|
|
36018
37404
|
if (claim2 !== undefined) {
|
|
36019
|
-
|
|
36020
|
-
|
|
36021
|
-
|
|
36022
|
-
event_id: envelope2.event_id ?? "unknown",
|
|
36023
|
-
at: inboundTimestamp(envelope2.issued_at),
|
|
36024
|
-
from: senderLabel(envelope2),
|
|
36025
|
-
summary: envelope2.payload_summary ?? "unknown"
|
|
36026
|
-
});
|
|
36027
|
-
if (inbox.length > 50)
|
|
36028
|
-
inbox.pop();
|
|
37405
|
+
if (identity !== undefined && replay?.delivered(identity) === true) {
|
|
37406
|
+
claim2.settle();
|
|
37407
|
+
return;
|
|
36029
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
|
+
};
|
|
36030
37418
|
const refuse = async (delivery, error48) => {
|
|
36031
37419
|
claim2.release();
|
|
36032
37420
|
await postDispatchReply(delivery, { error: error48 });
|
|
@@ -36037,7 +37425,12 @@ function envoyExtension(pi) {
|
|
|
36037
37425
|
await refuse(rendered.rejectedDelivery, "Invalid Dispatch targeted delivery frame");
|
|
36038
37426
|
} else if (rendered.malformedDelivery === true) {
|
|
36039
37427
|
console.warn("[envoy] dropping malformed Dispatch targeted delivery without a reply address");
|
|
37428
|
+
claim2.settle();
|
|
36040
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
|
+
}
|
|
36041
37434
|
const answer = sideTurn(activeSessionContext);
|
|
36042
37435
|
if (shuttingDown) {
|
|
36043
37436
|
await refuse(rendered.delivery, "This OMP session is shutting down");
|
|
@@ -36047,6 +37440,7 @@ function envoyExtension(pi) {
|
|
|
36047
37440
|
try {
|
|
36048
37441
|
const reply2 = await answer({ prompt: rendered.delivery.body });
|
|
36049
37442
|
await postDispatchReply(rendered.delivery, { body: reply2.replyText });
|
|
37443
|
+
await taken();
|
|
36050
37444
|
} catch (error48) {
|
|
36051
37445
|
await refuse(rendered.delivery, messageFor(error48));
|
|
36052
37446
|
}
|
|
@@ -36057,10 +37451,7 @@ function envoyExtension(pi) {
|
|
|
36057
37451
|
const shown = shownPictures(sessionID);
|
|
36058
37452
|
if (accepted === undefined) {
|
|
36059
37453
|
const card = await withDeliveredPictures(rendered.content, rendered.pictures ?? [], () => timedDispatchClient(DELIVERY_PICTURES_TIMEOUT_MS), true, shown);
|
|
36060
|
-
|
|
36061
|
-
deliverAs: rendered.delivery?.mode === "aside" ? "aside" : "steer",
|
|
36062
|
-
triggerTurn: true
|
|
36063
|
-
});
|
|
37454
|
+
unwritten.sendCard(card.content, rendered.delivery?.mode === "aside" ? "aside" : "steer", identity, claim2);
|
|
36064
37455
|
markPicturesShown(shownPictures(sessionID), card.shown);
|
|
36065
37456
|
} else {
|
|
36066
37457
|
const { turn } = accepted;
|
|
@@ -36070,14 +37461,22 @@ function envoyExtension(pi) {
|
|
|
36070
37461
|
const refusal = typedInputReply(turn.body, { hostVersion: VERSION });
|
|
36071
37462
|
if (refusal !== undefined) {
|
|
36072
37463
|
await postDispatchReply(accepted.delivery, { body: refusal }, acceptedSessionID);
|
|
37464
|
+
await taken();
|
|
36073
37465
|
} else {
|
|
36074
37466
|
const injectionSessionID = sessionID;
|
|
36075
37467
|
noteInjectedUserTurn(injectionSessionID, turn.body, turn.messageId);
|
|
36076
37468
|
notedSessionIDs.add(injectionSessionID);
|
|
36077
37469
|
pi.sendUserMessage(delivery.content, turn.mode === "aside" ? { deliverAs: "aside" } : undefined);
|
|
36078
37470
|
markPicturesShown(shownPictures(injectionSessionID), delivery.shown);
|
|
37471
|
+
unwritten.awaitTurn(turn.messageId, {
|
|
37472
|
+
sessionID: injectionSessionID,
|
|
37473
|
+
identity,
|
|
37474
|
+
claim: claim2,
|
|
37475
|
+
via: "text"
|
|
37476
|
+
});
|
|
36079
37477
|
}
|
|
36080
37478
|
} else {
|
|
37479
|
+
unwritten.awaitTurn(turn.messageId, { sessionID, identity, claim: claim2, via: "typed" });
|
|
36081
37480
|
runTypedInput(sendUserInput, accepted.delivery, acceptedSessionID, turn, delivery.content, delivery.shown);
|
|
36082
37481
|
}
|
|
36083
37482
|
}
|
|
@@ -36085,6 +37484,8 @@ function envoyExtension(pi) {
|
|
|
36085
37484
|
} catch (error48) {
|
|
36086
37485
|
claim2.release();
|
|
36087
37486
|
console.warn(`[envoy] failed to deliver envelope ${envelope2?.event_id ?? "unknown"}`, error48);
|
|
37487
|
+
if (envelope2 !== undefined)
|
|
37488
|
+
replay?.liveFailed(topic, envelope2, error48, receivedAt);
|
|
36088
37489
|
throw error48;
|
|
36089
37490
|
}
|
|
36090
37491
|
}
|
|
@@ -36118,7 +37519,7 @@ function envoyExtension(pi) {
|
|
|
36118
37519
|
};
|
|
36119
37520
|
const pump = async (topic, subscription) => {
|
|
36120
37521
|
try {
|
|
36121
|
-
for await (const message of subscription) {
|
|
37522
|
+
for await (const { message, receivedAt } of readArrivals(subscription)) {
|
|
36122
37523
|
if (replacedSessionTopic(topic)) {
|
|
36123
37524
|
logger3.warn("envoy: frame for a session a switch replaced left undelivered", {
|
|
36124
37525
|
subject: message.subject
|
|
@@ -36126,7 +37527,7 @@ function envoyExtension(pi) {
|
|
|
36126
37527
|
continue;
|
|
36127
37528
|
}
|
|
36128
37529
|
try {
|
|
36129
|
-
await deliver(message.subject, codec2.decode(message.data), message.reply ?? "");
|
|
37530
|
+
await deliver(topic, message.subject, codec2.decode(message.data), message.reply ?? "", receivedAt);
|
|
36130
37531
|
} catch {}
|
|
36131
37532
|
}
|
|
36132
37533
|
} catch {}
|
|
@@ -36145,7 +37546,10 @@ function envoyExtension(pi) {
|
|
|
36145
37546
|
return;
|
|
36146
37547
|
if (intentionallyClosed.delete(topic))
|
|
36147
37548
|
return;
|
|
36148
|
-
subscribeUnlessRoleEnds(topic, snapshot).
|
|
37549
|
+
subscribeUnlessRoleEnds(topic, snapshot).then((wanted) => {
|
|
37550
|
+
if (wanted)
|
|
37551
|
+
triggerReplay();
|
|
37552
|
+
}, () => retry(NATS_RETRY_INTERVAL_MS));
|
|
36149
37553
|
}, delayMs);
|
|
36150
37554
|
};
|
|
36151
37555
|
retry(RESUBSCRIBE_DELAY_MS);
|
|
@@ -36165,6 +37569,92 @@ function envoyExtension(pi) {
|
|
|
36165
37569
|
}
|
|
36166
37570
|
return true;
|
|
36167
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
|
+
};
|
|
36168
37658
|
const agentStream = new AgentStreamPublisher({
|
|
36169
37659
|
now: () => Date.now(),
|
|
36170
37660
|
publish: (subject2, payload) => connection?.publish(subject2, codec2.encode(payload))
|
|
@@ -36305,6 +37795,7 @@ function envoyExtension(pi) {
|
|
|
36305
37795
|
});
|
|
36306
37796
|
pi.on("message_end", async (event) => {
|
|
36307
37797
|
recordAgentStreamMessage(event.message, false);
|
|
37798
|
+
await unwritten.written(event.message);
|
|
36308
37799
|
});
|
|
36309
37800
|
pi.on("turn_start", async () => {
|
|
36310
37801
|
refreshAgentStreamSettings(sessionID);
|
|
@@ -36358,6 +37849,7 @@ function envoyExtension(pi) {
|
|
|
36358
37849
|
let registeredAt = -Infinity;
|
|
36359
37850
|
const registerSession = () => {
|
|
36360
37851
|
const registeringFor = sessionID;
|
|
37852
|
+
const own = agentSubject(sessionID);
|
|
36361
37853
|
for (const [key, hold] of abandonedHolds) {
|
|
36362
37854
|
if (hold.id !== sessionID)
|
|
36363
37855
|
continue;
|
|
@@ -36369,8 +37861,8 @@ function envoyExtension(pi) {
|
|
|
36369
37861
|
directory: sessionDirectory2,
|
|
36370
37862
|
topics: [
|
|
36371
37863
|
...new Set([
|
|
36372
|
-
|
|
36373
|
-
...[...subscriptions.keys()].filter((subject2) => !isRoleBound(subject2))
|
|
37864
|
+
own,
|
|
37865
|
+
...[...subscriptions.keys()].filter((subject2) => !isRoleBound(subject2) && !reachesPrivateStreamSubject(own, subject2))
|
|
36374
37866
|
])
|
|
36375
37867
|
],
|
|
36376
37868
|
port: 0,
|
|
@@ -36451,6 +37943,8 @@ function envoyExtension(pi) {
|
|
|
36451
37943
|
context.setInterval(() => {
|
|
36452
37944
|
if (context.sessionManager.getSessionId() === "")
|
|
36453
37945
|
return;
|
|
37946
|
+
unwritten.handBackWithdrawn();
|
|
37947
|
+
triggerReplay();
|
|
36454
37948
|
if (healing) {
|
|
36455
37949
|
const refreshMs = requireEnvoy().settings.heartbeatMs;
|
|
36456
37950
|
if (registeredFor === sessionID && Date.now() - registeredAt < refreshMs)
|
|
@@ -36496,9 +37990,11 @@ function envoyExtension(pi) {
|
|
|
36496
37990
|
const registry2 = await client.getInterest(sessionID).catch(() => {
|
|
36497
37991
|
return;
|
|
36498
37992
|
});
|
|
36499
|
-
if (
|
|
37993
|
+
if (!live())
|
|
36500
37994
|
return;
|
|
36501
|
-
const
|
|
37995
|
+
const slackRetired = publishedInterface?.roleClaim.slackRoleOwned === true;
|
|
37996
|
+
const registered = registry2?.topics ?? [];
|
|
37997
|
+
const retired = slackRetired ? registered.filter((topic) => slackTopicChannel(topic) !== undefined) : [];
|
|
36502
37998
|
if (retired.length > 0) {
|
|
36503
37999
|
await client.unsubscribe({ sessionID, topics: retired }).catch((error48) => {
|
|
36504
38000
|
logger3.warn("envoy: could not unregister a resumed controller's retired Slack topics", {
|
|
@@ -36510,7 +38006,8 @@ function envoyExtension(pi) {
|
|
|
36510
38006
|
}
|
|
36511
38007
|
if (!live())
|
|
36512
38008
|
return;
|
|
36513
|
-
|
|
38009
|
+
const remembered = rememberedSubjects(activeSessionContext?.sessionManager.getEntries() ?? []).filter((topic) => !(slackRetired && slackTopicChannel(topic) !== undefined));
|
|
38010
|
+
for (const topic of new Set([...registered, ...remembered])) {
|
|
36514
38011
|
if (topic === agentSubject(sessionID) || topic.startsWith(ROLE_TOPIC_PREFIX))
|
|
36515
38012
|
continue;
|
|
36516
38013
|
if (retired.includes(topic))
|
|
@@ -36727,6 +38224,7 @@ function envoyExtension(pi) {
|
|
|
36727
38224
|
return true;
|
|
36728
38225
|
}
|
|
36729
38226
|
let inboundFailure;
|
|
38227
|
+
let openedInbound = false;
|
|
36730
38228
|
if (inbound && inboundOpenFor !== host3) {
|
|
36731
38229
|
try {
|
|
36732
38230
|
agentSessions.add(host3);
|
|
@@ -36745,6 +38243,7 @@ function envoyExtension(pi) {
|
|
|
36745
38243
|
return false;
|
|
36746
38244
|
}
|
|
36747
38245
|
inboundOpenFor = host3;
|
|
38246
|
+
openedInbound = true;
|
|
36748
38247
|
} catch (error48) {
|
|
36749
38248
|
inboundFailure = error48;
|
|
36750
38249
|
}
|
|
@@ -36760,6 +38259,8 @@ function envoyExtension(pi) {
|
|
|
36760
38259
|
establishedSession = host3;
|
|
36761
38260
|
ensureHeartbeat(context);
|
|
36762
38261
|
}
|
|
38262
|
+
if (openedInbound)
|
|
38263
|
+
triggerReplay();
|
|
36763
38264
|
const decided = await roleMoves.run((moveLive) => settleRole(context, host3, cause, registration === undefined, moveLive));
|
|
36764
38265
|
if (!owns())
|
|
36765
38266
|
return false;
|
|
@@ -37113,8 +38614,11 @@ function envoyExtension(pi) {
|
|
|
37113
38614
|
}
|
|
37114
38615
|
pi.on("agent_end", async (event, context) => {
|
|
37115
38616
|
const id = context.sessionManager.getSessionId();
|
|
37116
|
-
endInjectedUserTurns(sessionID);
|
|
37117
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();
|
|
37118
38622
|
if (runUnderAnnouncement !== undefined && event.willContinue !== true) {
|
|
37119
38623
|
if (announced === runUnderAnnouncement && announced.from === id && lastReply !== undefined && lastReply.stopReason !== "aborted") {
|
|
37120
38624
|
announced = undefined;
|
|
@@ -37261,6 +38765,8 @@ function envoyExtension(pi) {
|
|
|
37261
38765
|
} catch (error48) {
|
|
37262
38766
|
registrationError = messageFor(error48);
|
|
37263
38767
|
}
|
|
38768
|
+
await replayFollowedChanged();
|
|
38769
|
+
triggerReplay();
|
|
37264
38770
|
}
|
|
37265
38771
|
const subscribed = `Subscribed: ${added.join(", ") || "(none new)"}`;
|
|
37266
38772
|
return toolSuccess(warnings === undefined || warnings.length === 0 ? subscribed : `${subscribed}
|
|
@@ -37276,6 +38782,8 @@ Warnings: ${warnings.join("; ")}`, {
|
|
|
37276
38782
|
const candidates = topicsFor(parameters, [...subscriptions.keys()]).filter((subject2) => subject2 !== inbox2);
|
|
37277
38783
|
const kept = candidates.filter(isRoleBound);
|
|
37278
38784
|
const removed = candidates.filter((subject2) => !isRoleBound(subject2)).filter(closeIntentionally);
|
|
38785
|
+
if (removed.length > 0)
|
|
38786
|
+
await replayFollowedChanged();
|
|
37279
38787
|
const registryRemoved = removed.filter((topic) => !topic.startsWith(ROLE_TOPIC_PREFIX));
|
|
37280
38788
|
const registrationError = registryRemoved.length === 0 ? undefined : await client.unsubscribe({ sessionID, topics: registryRemoved }).then(registerSession).then(() => {
|
|
37281
38789
|
return;
|