@sjawhar/claude-envoy 2.7.1 → 2.9.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/.claude-plugin/plugin.json +1 -1
- package/.omp-plugin/plugin.json +1 -1
- package/AGENTS.md +67 -71
- package/README.md +26 -33
- package/dist/dispatch.js +159 -164
- package/dist/envoy-channel.js +717 -1385
- package/dist/session-hook.js +27 -78
- package/package.json +1 -1
- package/skills/envoy/SKILL.md +96 -22
- package/skills/envoy/references/deliveries.md +71 -15
- package/skills/envoy/references/legion.md +34 -8
- package/src/agent-stream-runner.ts +2 -2
- package/src/channel-topics.ts +148 -0
- package/src/envoy-channel-server.ts +279 -378
- package/src/replay-state.ts +17 -17
- package/src/channel-forwarder.ts +0 -262
package/dist/envoy-channel.js
CHANGED
|
@@ -36300,6 +36300,9 @@ function agentSubject(session) {
|
|
|
36300
36300
|
return `${AGENT_TOPIC_PREFIX}${session}`;
|
|
36301
36301
|
}
|
|
36302
36302
|
var GHOSTWISPR_TOPIC_PREFIX = "notifications.ghostwispr.";
|
|
36303
|
+
function uncapturedTopicRefusal(topic, sessionID) {
|
|
36304
|
+
return `${topic} was not registered: no stream subject captures it, so nothing would be delivered to ${sessionID} on it; follow a notifications.team.<name> topic instead`;
|
|
36305
|
+
}
|
|
36303
36306
|
|
|
36304
36307
|
// ../contracts/src/legion-roles.ts
|
|
36305
36308
|
var LEGION_ROLES = [
|
|
@@ -36585,6 +36588,8 @@ var ArtifactCreatedEventPayloadSchema = object({
|
|
|
36585
36588
|
name: artifactFields.name.optional()
|
|
36586
36589
|
}).optional()
|
|
36587
36590
|
});
|
|
36591
|
+
var ArtifactRenamedEventPayloadSchema = strictObject({ artifact: ArtifactSchema, previous_name: string2() }).readonly();
|
|
36592
|
+
var ArtifactRemovedEventPayloadSchema = strictObject({ artifact: ArtifactSchema }).readonly();
|
|
36588
36593
|
var artifactVersionEventPayloadFields = {
|
|
36589
36594
|
artifact_id: string2(),
|
|
36590
36595
|
name: string2(),
|
|
@@ -36680,15 +36685,16 @@ function documentOwnerValidation(requireArtifact, alwaysRequireArtifact = false)
|
|
|
36680
36685
|
message: alwaysRequireArtifact ? "Exactly one of issue and project is required; artifact or ref must name the document." : "Exactly one of issue and project is required; with project, artifact names the document."
|
|
36681
36686
|
};
|
|
36682
36687
|
}
|
|
36683
|
-
var ARTIFACT_SOURCE_RULE = "
|
|
36688
|
+
var ARTIFACT_SOURCE_RULE = "Give at most one of path and content. A call with neither makes an empty document under the name, which a person or an agent writes in afterwards with dispatch doc-edit.";
|
|
36684
36689
|
var ARTIFACT_OWNER_AND_SOURCE_RULE = `${ARTIFACT_SOURCE_RULE} Exactly one of issue and project is required; with project, artifact names the document.`;
|
|
36685
36690
|
function brokenParts(parts) {
|
|
36686
36691
|
const broken = parts.filter(([kept]) => !kept).map(([, message]) => message);
|
|
36687
36692
|
return broken.length === 0 ? undefined : broken.join(" ");
|
|
36688
36693
|
}
|
|
36689
36694
|
var CONTENT_IS_MARKDOWN = "content is stored as a Markdown document, which rewrites other text (a JSONL file's lines come back joined into one paragraph)";
|
|
36695
|
+
var DOCUMENT_IS_MARKDOWN = "a document holds Markdown, which rewrites other text (a JSONL file's lines come back joined into one paragraph)";
|
|
36690
36696
|
var PATH_KEEPS_BYTES = "path (--path <file>), which stores a file whose path does not end in .md or .markdown as its bytes, unchanged";
|
|
36691
|
-
var ARTIFACT_CONTENT_NAME_RULE = `${CONTENT_IS_MARKDOWN}, so
|
|
36697
|
+
var ARTIFACT_CONTENT_NAME_RULE = `${CONTENT_IS_MARKDOWN}, so a document's name ends in .md or .markdown or has no extension, under content and under neither flag alike; upload any other file (.jsonl, .tsv, .json, .txt) with ${PATH_KEEPS_BYTES}.`;
|
|
36692
36698
|
var ARTIFACT_NAME_EXISTS_RULE = "An upload under the name of a document the owner already holds is refused: it writes that document's next version, over the text it holds. Change a document with dispatch doc-edit. Send the upload again with force (--force) to write the next version.";
|
|
36693
36699
|
var ARTIFACT_STORED_TEXT_RULE = `content and content-file hold text Dispatch stores as Markdown, and a text the store would write under another spelling is refused. The refusal prints the text Dispatch stores: send that text. A name that does not end in .md or .markdown has a second way out, which keeps the text as it was written: send it as a file with ${PATH_KEEPS_BYTES}.`;
|
|
36694
36700
|
var NAME_EXTENSION = /\.([^\s.]+)$/u;
|
|
@@ -36702,19 +36708,16 @@ function artifactProblem(value) {
|
|
|
36702
36708
|
const input = value;
|
|
36703
36709
|
const ownerOrSourceProblem = brokenParts([
|
|
36704
36710
|
[artifactOwner.check(value), artifactOwner.message],
|
|
36705
|
-
[
|
|
36706
|
-
typeof input.path === "string" !== (typeof input.content === "string"),
|
|
36707
|
-
ARTIFACT_SOURCE_RULE
|
|
36708
|
-
]
|
|
36711
|
+
[typeof input.path !== "string" || typeof input.content !== "string", ARTIFACT_SOURCE_RULE]
|
|
36709
36712
|
]);
|
|
36710
36713
|
if (ownerOrSourceProblem !== undefined)
|
|
36711
36714
|
return ownerOrSourceProblem;
|
|
36712
|
-
if (typeof input.
|
|
36715
|
+
if (typeof input.path === "string" || typeof input.name !== "string")
|
|
36713
36716
|
return;
|
|
36714
36717
|
const extension = NAME_EXTENSION.exec(input.name.trim())?.[1];
|
|
36715
36718
|
if (extension === undefined || MARKDOWN_EXTENSION.test(extension))
|
|
36716
36719
|
return;
|
|
36717
|
-
return `${
|
|
36720
|
+
return `${DOCUMENT_IS_MARKDOWN}, and ${JSON.stringify(input.name)} is not a Markdown name. Upload the file under the same name with ${PATH_KEEPS_BYTES}; a document takes a name ending in .md or .markdown or with no extension.`;
|
|
36718
36721
|
}
|
|
36719
36722
|
var documentEditOwner = documentOwnerValidation(true);
|
|
36720
36723
|
var PRECONDITION_RULE = "A precondition selects exactly one of document or blocks.";
|
|
@@ -37265,7 +37268,7 @@ var dispatchToolSpecs = [
|
|
|
37265
37268
|
name: "dispatch_artifact",
|
|
37266
37269
|
example: { issue: "DSP-1", name: "design.md", content: `# Design
|
|
37267
37270
|
` },
|
|
37268
|
-
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.
|
|
37271
|
+
description: "Attach a local file or inline text as an issue artifact or project document, or make an empty document from its name alone. 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. " + `${ARTIFACT_SOURCE_RULE} ` + `${ARTIFACT_NAME_EXISTS_RULE} A call that stores nothing - no path, and content absent or blank - is refused under a held name even with force, so a title typed twice never empties the document that holds it. ` + "A markdown document is at most 1 MiB and any other file at most 25 MiB. " + `${ARTIFACT_CONTENT_NAME_RULE} ${ARTIFACT_STORED_TEXT_RULE} ` + "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}`,
|
|
37269
37272
|
arguments: (z) => ({
|
|
37270
37273
|
issue: z.string().describe(ISSUE_REFERENCE).optional(),
|
|
37271
37274
|
project: z.string().describe("Project key for an unlinked document.").optional(),
|
|
@@ -43604,8 +43607,9 @@ class DispatchClient {
|
|
|
43604
43607
|
return { status: response.status, payload: await this.#response(method, url, response) };
|
|
43605
43608
|
}
|
|
43606
43609
|
async#upload(path, input, key) {
|
|
43607
|
-
if (
|
|
43610
|
+
if (input.file === undefined) {
|
|
43608
43611
|
return this.#json("POST", path, input, undefined, undefined, key);
|
|
43612
|
+
}
|
|
43609
43613
|
const form = new FormData;
|
|
43610
43614
|
form.set("name", input.name);
|
|
43611
43615
|
if (input.summary !== undefined)
|
|
@@ -44107,58 +44111,6 @@ async function postDeliveryReply(config, sessionId, delivery, result) {
|
|
|
44107
44111
|
...reply
|
|
44108
44112
|
}, followUp === undefined ? {} : { followUp });
|
|
44109
44113
|
}
|
|
44110
|
-
function expectsLaneReceipt(frame) {
|
|
44111
|
-
return frame.reply !== undefined && frame.reply !== "" && frame.subject === frame.directSubject && frame.envelopeTopic !== undefined && frame.envelopeTopic !== frame.directSubject;
|
|
44112
|
-
}
|
|
44113
|
-
async function* readArrivals(subscription, now = Date.now) {
|
|
44114
|
-
const source = subscription[Symbol.asyncIterator]();
|
|
44115
|
-
const arrived = [];
|
|
44116
|
-
let stopped;
|
|
44117
|
-
let left = false;
|
|
44118
|
-
let wake;
|
|
44119
|
-
const signal = () => {
|
|
44120
|
-
wake?.();
|
|
44121
|
-
wake = undefined;
|
|
44122
|
-
};
|
|
44123
|
-
(async () => {
|
|
44124
|
-
try {
|
|
44125
|
-
for (;; ) {
|
|
44126
|
-
const read = await source.next();
|
|
44127
|
-
if (read.done === true || left)
|
|
44128
|
-
break;
|
|
44129
|
-
arrived.push({ message: read.value, receivedAt: now() });
|
|
44130
|
-
signal();
|
|
44131
|
-
}
|
|
44132
|
-
stopped = { failed: false };
|
|
44133
|
-
} catch (error) {
|
|
44134
|
-
stopped = { error, failed: true };
|
|
44135
|
-
}
|
|
44136
|
-
signal();
|
|
44137
|
-
})();
|
|
44138
|
-
try {
|
|
44139
|
-
for (;; ) {
|
|
44140
|
-
const next = arrived.shift();
|
|
44141
|
-
if (next !== undefined) {
|
|
44142
|
-
yield next;
|
|
44143
|
-
continue;
|
|
44144
|
-
}
|
|
44145
|
-
if (stopped?.failed === true)
|
|
44146
|
-
throw stopped.error;
|
|
44147
|
-
if (stopped !== undefined)
|
|
44148
|
-
return;
|
|
44149
|
-
const { promise, resolve } = Promise.withResolvers();
|
|
44150
|
-
wake = resolve;
|
|
44151
|
-
await promise;
|
|
44152
|
-
}
|
|
44153
|
-
} finally {
|
|
44154
|
-
if (stopped === undefined) {
|
|
44155
|
-
left = true;
|
|
44156
|
-
Promise.resolve(source.return?.()).catch(() => {
|
|
44157
|
-
return;
|
|
44158
|
-
});
|
|
44159
|
-
}
|
|
44160
|
-
}
|
|
44161
|
-
}
|
|
44162
44114
|
var DedupeIdentitySchema = object({
|
|
44163
44115
|
event_id: string2().min(1).optional(),
|
|
44164
44116
|
dedupe_key: string2().min(1).optional(),
|
|
@@ -44919,6 +44871,262 @@ function subscriptionRemovedTopics(raw, sessionID) {
|
|
|
44919
44871
|
return parsedPayload.data.topics ?? [];
|
|
44920
44872
|
}
|
|
44921
44873
|
|
|
44874
|
+
// ../envoy-client/src/delivery-ledger.ts
|
|
44875
|
+
var DELIVERY_LEDGER_TTL_MS = DELIVERY_DUPLICATE_WINDOW_MS;
|
|
44876
|
+
var DELIVERY_LEDGER_LIMIT = 20000;
|
|
44877
|
+
var LedgerEntrySchema = object({
|
|
44878
|
+
event_id: string2().min(1).optional(),
|
|
44879
|
+
dedupe_key: string2().min(1).optional(),
|
|
44880
|
+
at: number2()
|
|
44881
|
+
});
|
|
44882
|
+
var LedgerStateSchema = object({
|
|
44883
|
+
topics: array(string2()).default([])
|
|
44884
|
+
});
|
|
44885
|
+
var LedgerSnapshotSchema = object({
|
|
44886
|
+
state: LedgerStateSchema.optional(),
|
|
44887
|
+
ledger: array(LedgerEntrySchema)
|
|
44888
|
+
});
|
|
44889
|
+
function createDeliveryLedger(options) {
|
|
44890
|
+
const { host } = options;
|
|
44891
|
+
const now = options.now ?? Date.now;
|
|
44892
|
+
const ledger = createLedger(now);
|
|
44893
|
+
let topics = [];
|
|
44894
|
+
let unwritten = [];
|
|
44895
|
+
let writtenState;
|
|
44896
|
+
let writes = Promise.resolve();
|
|
44897
|
+
let epoch = 0;
|
|
44898
|
+
const safely = (what, call) => {
|
|
44899
|
+
try {
|
|
44900
|
+
call();
|
|
44901
|
+
} catch (error) {
|
|
44902
|
+
try {
|
|
44903
|
+
host.log(`delivery ledger: ${what} failed`, error);
|
|
44904
|
+
} catch {}
|
|
44905
|
+
}
|
|
44906
|
+
};
|
|
44907
|
+
const log = (message, error) => safely("log", () => host.log(message, error));
|
|
44908
|
+
const sessionRead = (read) => () => {
|
|
44909
|
+
try {
|
|
44910
|
+
return read();
|
|
44911
|
+
} catch {
|
|
44912
|
+
return;
|
|
44913
|
+
}
|
|
44914
|
+
};
|
|
44915
|
+
const currentSession = sessionRead(() => host.sessionID());
|
|
44916
|
+
const writeSession = sessionRead(() => host.writeSessionID === undefined ? host.sessionID() : host.writeSessionID());
|
|
44917
|
+
const bindTo = (sessionID, read) => {
|
|
44918
|
+
if (sessionID === undefined || sessionID === "" || read() !== sessionID)
|
|
44919
|
+
return;
|
|
44920
|
+
const bound = epoch;
|
|
44921
|
+
return { sessionID, alive: () => bound === epoch && read() === sessionID };
|
|
44922
|
+
};
|
|
44923
|
+
const bind = () => bindTo(currentSession(), currentSession);
|
|
44924
|
+
const stateJSON = () => JSON.stringify({ topics: [...topics].sort() });
|
|
44925
|
+
const record = (identity) => {
|
|
44926
|
+
const entry = ledger.record(identity);
|
|
44927
|
+
if (entry !== undefined)
|
|
44928
|
+
unwritten.push(entry);
|
|
44929
|
+
};
|
|
44930
|
+
const flush = (alive) => {
|
|
44931
|
+
const written = writes.then(async () => {
|
|
44932
|
+
if (!alive())
|
|
44933
|
+
return false;
|
|
44934
|
+
const json = stateJSON();
|
|
44935
|
+
const delivered = unwritten;
|
|
44936
|
+
if (json === writtenState && delivered.length === 0)
|
|
44937
|
+
return true;
|
|
44938
|
+
unwritten = [];
|
|
44939
|
+
const state = json === writtenState ? undefined : JSON.parse(json);
|
|
44940
|
+
try {
|
|
44941
|
+
await host.write({
|
|
44942
|
+
delivered,
|
|
44943
|
+
state,
|
|
44944
|
+
snapshot: () => ({ state: JSON.parse(json), ledger: ledger.list() })
|
|
44945
|
+
});
|
|
44946
|
+
if (state !== undefined)
|
|
44947
|
+
writtenState = json;
|
|
44948
|
+
return true;
|
|
44949
|
+
} catch (error) {
|
|
44950
|
+
unwritten = [...delivered, ...unwritten];
|
|
44951
|
+
log("delivery ledger: could not persist the state; the next write carries it", error);
|
|
44952
|
+
return false;
|
|
44953
|
+
}
|
|
44954
|
+
});
|
|
44955
|
+
writes = written.then(() => {
|
|
44956
|
+
return;
|
|
44957
|
+
});
|
|
44958
|
+
return written;
|
|
44959
|
+
};
|
|
44960
|
+
const syncFollowed = () => {
|
|
44961
|
+
topics = [...new Set(host.followedSubjects())];
|
|
44962
|
+
};
|
|
44963
|
+
const failureNotice = (envelope, error) => ({
|
|
44964
|
+
eventId: envelope.event_id ?? "unknown",
|
|
44965
|
+
sender: senderLabel(envelope),
|
|
44966
|
+
summary: envelope.payload_summary ?? "unknown",
|
|
44967
|
+
publishedAt: inboundTimestamp(envelope.issued_at),
|
|
44968
|
+
error,
|
|
44969
|
+
readWith: envelope.source === "dispatch" ? "dispatch read" : "envoy_inbox",
|
|
44970
|
+
envelope
|
|
44971
|
+
});
|
|
44972
|
+
const showFailureNotice = async (sessionID, notice, alive) => {
|
|
44973
|
+
let queued;
|
|
44974
|
+
try {
|
|
44975
|
+
queued = await host.showFailureNotice(sessionID, notice) === "queued";
|
|
44976
|
+
} catch (error) {
|
|
44977
|
+
if (alive())
|
|
44978
|
+
safely("failure notice warning", () => host.failureNoticeFailed(notice, error));
|
|
44979
|
+
return false;
|
|
44980
|
+
}
|
|
44981
|
+
if (queued || !alive())
|
|
44982
|
+
return true;
|
|
44983
|
+
record(ledgerIdentity(notice.envelope));
|
|
44984
|
+
await flush(alive);
|
|
44985
|
+
return true;
|
|
44986
|
+
};
|
|
44987
|
+
return {
|
|
44988
|
+
async followedChanged() {
|
|
44989
|
+
const alive = bind()?.alive;
|
|
44990
|
+
if (alive === undefined)
|
|
44991
|
+
return;
|
|
44992
|
+
try {
|
|
44993
|
+
syncFollowed();
|
|
44994
|
+
await flush(alive);
|
|
44995
|
+
} catch (error) {
|
|
44996
|
+
log("delivery ledger: could not take the followed subjects", error);
|
|
44997
|
+
}
|
|
44998
|
+
},
|
|
44999
|
+
delivered: (frame) => ledger.has(ledgerIdentity(frame)),
|
|
45000
|
+
async recordDelivered(frame) {
|
|
45001
|
+
const alive = bind()?.alive;
|
|
45002
|
+
if (alive === undefined)
|
|
45003
|
+
return;
|
|
45004
|
+
record(ledgerIdentity(frame));
|
|
45005
|
+
await flush(alive);
|
|
45006
|
+
},
|
|
45007
|
+
async recordDeliveredFor(sessionID, frame) {
|
|
45008
|
+
const alive = bindTo(sessionID, writeSession)?.alive;
|
|
45009
|
+
if (alive === undefined)
|
|
45010
|
+
return false;
|
|
45011
|
+
record(ledgerIdentity(frame));
|
|
45012
|
+
return await flush(alive);
|
|
45013
|
+
},
|
|
45014
|
+
async liveFailed(sessionID, envelope, error) {
|
|
45015
|
+
const alive = bindTo(sessionID, currentSession)?.alive;
|
|
45016
|
+
if (alive === undefined) {
|
|
45017
|
+
log("delivery ledger: a failed frame was not reported here; the session it names is closed");
|
|
45018
|
+
return false;
|
|
45019
|
+
}
|
|
45020
|
+
try {
|
|
45021
|
+
return await showFailureNotice(sessionID, failureNotice(envelope, messageFor(error)), alive);
|
|
45022
|
+
} catch (thrown) {
|
|
45023
|
+
log("delivery ledger: could not report a frame the session was not shown", thrown);
|
|
45024
|
+
return false;
|
|
45025
|
+
}
|
|
45026
|
+
},
|
|
45027
|
+
restore(snapshot) {
|
|
45028
|
+
epoch += 1;
|
|
45029
|
+
ledger.restore(snapshot.ledger);
|
|
45030
|
+
topics = [...new Set(snapshot.state?.topics ?? [])];
|
|
45031
|
+
writtenState = snapshot.state === undefined ? undefined : stateJSON();
|
|
45032
|
+
unwritten = [];
|
|
45033
|
+
}
|
|
45034
|
+
};
|
|
45035
|
+
}
|
|
45036
|
+
function failureNoticeFields(notice) {
|
|
45037
|
+
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.";
|
|
45038
|
+
return {
|
|
45039
|
+
notice: "message not shown",
|
|
45040
|
+
event_id: notice.eventId,
|
|
45041
|
+
from: notice.sender,
|
|
45042
|
+
summary: notice.summary,
|
|
45043
|
+
published_at: notice.publishedAt,
|
|
45044
|
+
error: notice.error,
|
|
45045
|
+
detail: `This session could not be shown this message, so it is not coming back on its own. ${readWith}`
|
|
45046
|
+
};
|
|
45047
|
+
}
|
|
45048
|
+
function envoyNoticeText(fields) {
|
|
45049
|
+
return encode5({ envoy: fields });
|
|
45050
|
+
}
|
|
45051
|
+
async function closeReplayedRemoval(frame, host) {
|
|
45052
|
+
const closed = (subscriptionRemovedTopics(frame.data, host.sessionID) ?? []).filter((topic) => host.relay?.followedBefore(topic, frame.storedAtMs) !== false && host.close(topic));
|
|
45053
|
+
if (closed.length === 0)
|
|
45054
|
+
return closed;
|
|
45055
|
+
const unregistering = host.unregister(closed);
|
|
45056
|
+
await host.followedChanged();
|
|
45057
|
+
await unregistering;
|
|
45058
|
+
return closed;
|
|
45059
|
+
}
|
|
45060
|
+
function ledgerIdentity(frame) {
|
|
45061
|
+
return {
|
|
45062
|
+
...frame.event_id === undefined || frame.event_id === "" ? {} : { event_id: frame.event_id },
|
|
45063
|
+
...frame.dedupe_key === undefined || !dedupeKeyNamesItsEvent(frame) ? {} : { dedupe_key: frame.dedupe_key }
|
|
45064
|
+
};
|
|
45065
|
+
}
|
|
45066
|
+
function createLedger(now) {
|
|
45067
|
+
let entries = new Set;
|
|
45068
|
+
const byEvent = new Map;
|
|
45069
|
+
const byKey = new Map;
|
|
45070
|
+
const drop = (entry) => {
|
|
45071
|
+
entries.delete(entry);
|
|
45072
|
+
if (entry.event_id !== undefined && byEvent.get(entry.event_id) === entry) {
|
|
45073
|
+
byEvent.delete(entry.event_id);
|
|
45074
|
+
}
|
|
45075
|
+
if (entry.dedupe_key !== undefined && byKey.get(entry.dedupe_key) === entry) {
|
|
45076
|
+
byKey.delete(entry.dedupe_key);
|
|
45077
|
+
}
|
|
45078
|
+
};
|
|
45079
|
+
const add = (entry) => {
|
|
45080
|
+
if (entries.size >= DELIVERY_LEDGER_LIMIT) {
|
|
45081
|
+
const oldest = entries.values().next();
|
|
45082
|
+
if (oldest.done !== true)
|
|
45083
|
+
drop(oldest.value);
|
|
45084
|
+
}
|
|
45085
|
+
entries.add(entry);
|
|
45086
|
+
if (entry.event_id !== undefined)
|
|
45087
|
+
byEvent.set(entry.event_id, entry);
|
|
45088
|
+
if (entry.dedupe_key !== undefined)
|
|
45089
|
+
byKey.set(entry.dedupe_key, entry);
|
|
45090
|
+
};
|
|
45091
|
+
const expire = () => {
|
|
45092
|
+
const at = now();
|
|
45093
|
+
for (const entry of entries) {
|
|
45094
|
+
if (at - entry.at < DELIVERY_LEDGER_TTL_MS)
|
|
45095
|
+
break;
|
|
45096
|
+
drop(entry);
|
|
45097
|
+
}
|
|
45098
|
+
};
|
|
45099
|
+
const has = (identity) => {
|
|
45100
|
+
expire();
|
|
45101
|
+
return identity.event_id !== undefined && byEvent.has(identity.event_id) || identity.dedupe_key !== undefined && byKey.has(identity.dedupe_key);
|
|
45102
|
+
};
|
|
45103
|
+
return {
|
|
45104
|
+
has,
|
|
45105
|
+
record(identity) {
|
|
45106
|
+
if (identity.event_id === undefined && identity.dedupe_key === undefined)
|
|
45107
|
+
return;
|
|
45108
|
+
if (has(identity))
|
|
45109
|
+
return;
|
|
45110
|
+
const entry = { ...identity, at: now() };
|
|
45111
|
+
add(entry);
|
|
45112
|
+
return entry;
|
|
45113
|
+
},
|
|
45114
|
+
restore(restored) {
|
|
45115
|
+
entries = new Set;
|
|
45116
|
+
byEvent.clear();
|
|
45117
|
+
byKey.clear();
|
|
45118
|
+
const at = now();
|
|
45119
|
+
const kept = restored.filter((entry) => at - entry.at < DELIVERY_LEDGER_TTL_MS && (entry.event_id !== undefined || entry.dedupe_key !== undefined)).sort((a, b) => a.at - b.at);
|
|
45120
|
+
for (const entry of kept)
|
|
45121
|
+
add({ ...entry });
|
|
45122
|
+
},
|
|
45123
|
+
list() {
|
|
45124
|
+
expire();
|
|
45125
|
+
return [...entries];
|
|
45126
|
+
}
|
|
45127
|
+
};
|
|
45128
|
+
}
|
|
45129
|
+
|
|
44922
45130
|
// ../envoy-client/src/stream-topics.ts
|
|
44923
45131
|
var EXCEPTION_TOPIC_PREFIX = "notifications.envoy.exceptions.";
|
|
44924
45132
|
var STREAM_SUBJECT_PREFIXES = [
|
|
@@ -44929,42 +45137,103 @@ var STREAM_SUBJECT_PREFIXES = [
|
|
|
44929
45137
|
LEGION_NOTICE_TOPIC_PREFIX,
|
|
44930
45138
|
GHOSTWISPR_TOPIC_PREFIX,
|
|
44931
45139
|
"notifications.whatsapp.",
|
|
44932
|
-
|
|
45140
|
+
"notifications.team.",
|
|
45141
|
+
`${EXCEPTION_TOPIC_PREFIX}${AGENT_TOPIC_PREFIX}`,
|
|
45142
|
+
`${EXCEPTION_TOPIC_PREFIX}notifications.team.`
|
|
44933
45143
|
];
|
|
44934
45144
|
function streamStores(topic) {
|
|
44935
45145
|
return STREAM_SUBJECT_PREFIXES.some((prefix) => topic.length > prefix.length && topic.startsWith(prefix));
|
|
44936
45146
|
}
|
|
44937
|
-
|
|
44938
|
-
|
|
44939
|
-
import { hostname as hostname3 } from "os";
|
|
44940
|
-
function machineID() {
|
|
44941
|
-
return process.env["ENVOY_MACHINE_ID"] || process.env["AGENTBOX_HOST"] || hostname3();
|
|
45147
|
+
function streamDeliversNothing(topic) {
|
|
45148
|
+
return topic.startsWith("notifications.") && !topic.startsWith(ROLE_TOPIC_PREFIX) && !streamStores(topic);
|
|
44942
45149
|
}
|
|
44943
|
-
|
|
44944
|
-
|
|
44945
|
-
|
|
44946
|
-
|
|
44947
|
-
|
|
44948
|
-
|
|
44949
|
-
|
|
44950
|
-
|
|
44951
|
-
|
|
44952
|
-
|
|
44953
|
-
|
|
44954
|
-
|
|
44955
|
-
|
|
45150
|
+
function subscribeRefusesTopic(ownAgentSubject, topic) {
|
|
45151
|
+
return streamDeliversNothing(topic) && !reachesPrivateStreamSubject(ownAgentSubject, topic);
|
|
45152
|
+
}
|
|
45153
|
+
function refuseUncapturedTopics(sessionID, ownAgentSubject, topics) {
|
|
45154
|
+
const uncaptured = topics.filter((topic) => subscribeRefusesTopic(ownAgentSubject, topic));
|
|
45155
|
+
if (uncaptured.length === 0)
|
|
45156
|
+
return;
|
|
45157
|
+
throw new Error(uncaptured.map((topic) => uncapturedTopicRefusal(topic, sessionID)).join("; "));
|
|
45158
|
+
}
|
|
45159
|
+
var PRIVATE_STREAM_SUBJECTS = [
|
|
45160
|
+
`${AGENT_TOPIC_PREFIX}>`,
|
|
45161
|
+
`${LEGION_NOTICE_TOPIC_PREFIX}>`,
|
|
45162
|
+
`${EXCEPTION_TOPIC_PREFIX}${AGENT_TOPIC_PREFIX}>`,
|
|
45163
|
+
`${EXCEPTION_TOPIC_PREFIX}notifications.team.>`
|
|
45164
|
+
];
|
|
45165
|
+
var CONTROLLER_NOTICE_SUFFIX = ".controller";
|
|
45166
|
+
function controllerNoticeRole(topic) {
|
|
45167
|
+
if (!topic.startsWith(LEGION_NOTICE_TOPIC_PREFIX) || !topic.endsWith(CONTROLLER_NOTICE_SUFFIX)) {
|
|
45168
|
+
return;
|
|
45169
|
+
}
|
|
45170
|
+
const project = topic.slice(LEGION_NOTICE_TOPIC_PREFIX.length, topic.length - CONTROLLER_NOTICE_SUFFIX.length);
|
|
45171
|
+
if (project === "" || /[.*>]/.test(project))
|
|
45172
|
+
return;
|
|
45173
|
+
return `legion-${project}-controller`;
|
|
45174
|
+
}
|
|
45175
|
+
function subjectsOverlap(a, b) {
|
|
45176
|
+
const aTokens = a.split(".");
|
|
45177
|
+
const bTokens = b.split(".");
|
|
45178
|
+
for (let index = 0;index < aTokens.length && index < bTokens.length; index += 1) {
|
|
45179
|
+
const aToken = aTokens[index];
|
|
45180
|
+
const bToken = bTokens[index];
|
|
45181
|
+
if (aToken === ">" || bToken === ">")
|
|
45182
|
+
return true;
|
|
45183
|
+
if (aToken !== "*" && bToken !== "*" && aToken !== bToken)
|
|
45184
|
+
return false;
|
|
45185
|
+
}
|
|
45186
|
+
return aTokens.length === bTokens.length;
|
|
45187
|
+
}
|
|
45188
|
+
function reachesPrivateStreamSubject(ownAgentSubject, topic, roles = []) {
|
|
45189
|
+
if (!PRIVATE_STREAM_SUBJECTS.some((subject) => subjectsOverlap(topic, subject)))
|
|
45190
|
+
return false;
|
|
45191
|
+
const role = controllerNoticeRole(topic);
|
|
45192
|
+
if (role !== undefined)
|
|
45193
|
+
return !roles.includes(role);
|
|
45194
|
+
return topic !== ownAgentSubject || /[*>]/.test(ownAgentSubject);
|
|
45195
|
+
}
|
|
45196
|
+
function registrationTopics(ownAgentSubject, followed, roles = []) {
|
|
45197
|
+
return [
|
|
45198
|
+
...new Set([
|
|
45199
|
+
ownAgentSubject,
|
|
45200
|
+
...[...followed].filter((topic) => !reachesPrivateStreamSubject(ownAgentSubject, topic, roles) && !streamDeliversNothing(topic))
|
|
45201
|
+
])
|
|
45202
|
+
];
|
|
45203
|
+
}
|
|
45204
|
+
function replayFollowedSubjects(ownAgentSubject, topics, heldForRole = () => false) {
|
|
45205
|
+
const followed = [...topics].filter((topic) => !topic.startsWith(ROLE_TOPIC_PREFIX) && !reachesPrivateStreamSubject(ownAgentSubject, topic) && !heldForRole(topic));
|
|
45206
|
+
return [...new Set([ownAgentSubject, ...followed])];
|
|
45207
|
+
}
|
|
45208
|
+
function rememberedTopics(topics) {
|
|
45209
|
+
return (topics ?? []).filter((topic) => !topic.startsWith(AGENT_TOPIC_PREFIX) && !topic.startsWith(ROLE_TOPIC_PREFIX));
|
|
45210
|
+
}
|
|
45211
|
+
|
|
45212
|
+
// ../envoy-client/src/machine.ts
|
|
45213
|
+
import { hostname as hostname3 } from "os";
|
|
45214
|
+
function machineID() {
|
|
45215
|
+
return process.env["ENVOY_MACHINE_ID"] || process.env["AGENTBOX_HOST"] || hostname3();
|
|
45216
|
+
}
|
|
45217
|
+
|
|
45218
|
+
// ../envoy-client/src/transport.ts
|
|
45219
|
+
var SessionStateSchema = _enum2(["live", "unresponsive", "gone"]);
|
|
45220
|
+
var UNRESPONSIVE_RULE = "An unresponsive session is not dead: it keeps its role claims and its issue claims, and a " + "message sent to it is stored until it answers. Start no replacement for it and take no claim " + `from it until it is gone, or until ${ISSUE_CLAIM_UNRESPONSIVE_GRACE_MS / 60000} minutes ` + "have passed since its last_seen, the time of its last registration.";
|
|
45221
|
+
var WireStateSchema = SessionStateSchema.default("live");
|
|
45222
|
+
var InterestWireSchema = object({
|
|
45223
|
+
session_id: string2(),
|
|
45224
|
+
machine_id: string2(),
|
|
45225
|
+
dir: string2(),
|
|
45226
|
+
topics: array(string2()),
|
|
45227
|
+
updated_at: number2().int().optional(),
|
|
44956
45228
|
warnings: array(string2()).optional()
|
|
44957
45229
|
});
|
|
44958
|
-
var DeliveryAnswerWireSchema =
|
|
44959
|
-
|
|
44960
|
-
|
|
44961
|
-
|
|
44962
|
-
|
|
44963
|
-
|
|
44964
|
-
|
|
44965
|
-
}),
|
|
44966
|
-
object({ mode: literal("core"), reason: string2() })
|
|
44967
|
-
]);
|
|
45230
|
+
var DeliveryAnswerWireSchema = object({
|
|
45231
|
+
mode: literal("consumer"),
|
|
45232
|
+
subject: string2().min(1),
|
|
45233
|
+
stream_id: string2(),
|
|
45234
|
+
gap: boolean2(),
|
|
45235
|
+
consumer_start: number2().int().nonnegative().optional()
|
|
45236
|
+
});
|
|
44968
45237
|
var SessionWireSchema = object({
|
|
44969
45238
|
session_id: string2(),
|
|
44970
45239
|
machine_id: string2(),
|
|
@@ -44979,7 +45248,8 @@ var SessionWireSchema = object({
|
|
|
44979
45248
|
last_seen: number2().int().optional(),
|
|
44980
45249
|
state: WireStateSchema,
|
|
44981
45250
|
plugin: string2().optional(),
|
|
44982
|
-
plugin_version: string2().optional()
|
|
45251
|
+
plugin_version: string2().optional(),
|
|
45252
|
+
delivery: string2().optional()
|
|
44983
45253
|
});
|
|
44984
45254
|
var RoleWireSchema = object({
|
|
44985
45255
|
role: string2(),
|
|
@@ -44999,13 +45269,13 @@ var RoleHeldWireSchema = object({
|
|
|
44999
45269
|
var ErrorWireSchema = object({
|
|
45000
45270
|
error: string2(),
|
|
45001
45271
|
code: string2().optional(),
|
|
45272
|
+
reason: string2().optional(),
|
|
45002
45273
|
expected: array(string2()).optional(),
|
|
45003
45274
|
state: SessionStateSchema.optional(),
|
|
45004
45275
|
holder: string2().optional(),
|
|
45005
45276
|
holder_state: SessionStateSchema.optional(),
|
|
45006
45277
|
last_seen: number2().int().optional(),
|
|
45007
|
-
claim_released: boolean2().optional()
|
|
45008
|
-
unresponsive: array(string2()).optional()
|
|
45278
|
+
claim_released: boolean2().optional()
|
|
45009
45279
|
});
|
|
45010
45280
|
var EnvelopeResponseSchema = EnvelopeSchema.extend({
|
|
45011
45281
|
recipient: string2().optional(),
|
|
@@ -45013,46 +45283,30 @@ var EnvelopeResponseSchema = EnvelopeSchema.extend({
|
|
|
45013
45283
|
holder_state: SessionStateSchema.optional(),
|
|
45014
45284
|
recipient_state: SessionStateSchema.optional(),
|
|
45015
45285
|
last_seen: number2().int().optional(),
|
|
45016
|
-
unresponsive: array(string2()).optional(),
|
|
45017
45286
|
duplicate: boolean2().optional()
|
|
45018
45287
|
});
|
|
45019
45288
|
var PublishResponseSchema = EnvelopeResponseSchema.extend({
|
|
45020
45289
|
kept: boolean2().optional(),
|
|
45021
45290
|
kept_reason: _enum2(["unclaimed", "holder_lapsed"]).optional()
|
|
45022
45291
|
});
|
|
45023
|
-
var
|
|
45024
|
-
|
|
45025
|
-
|
|
45026
|
-
|
|
45027
|
-
|
|
45028
|
-
last_seq: number2().int().nonnegative()
|
|
45029
|
-
}),
|
|
45030
|
-
subjects: array(object({
|
|
45031
|
-
subject: string2(),
|
|
45032
|
-
messages: array(object({
|
|
45033
|
-
seq: number2().int().positive(),
|
|
45034
|
-
subject: string2(),
|
|
45035
|
-
time: string2(),
|
|
45036
|
-
data: string2()
|
|
45037
|
-
})),
|
|
45038
|
-
next_after: number2().int().nonnegative(),
|
|
45039
|
-
more: boolean2(),
|
|
45040
|
-
refused: string2().optional()
|
|
45041
|
-
}))
|
|
45042
|
-
});
|
|
45043
|
-
var DELIVERY_NOT_ANSWERED = "not_answered";
|
|
45044
|
-
var DELIVERY_UNREADABLE = "unreadable_answer";
|
|
45292
|
+
var DeliveryRefusalSchema = object({
|
|
45293
|
+
mode: string2(),
|
|
45294
|
+
reason: string2().optional()
|
|
45295
|
+
});
|
|
45296
|
+
var DELIVERY_UNREADABLE = "answered a delivery field this build cannot read";
|
|
45045
45297
|
function parseSubscribeAnswer(body) {
|
|
45046
45298
|
const interest = InterestWireSchema.parse(body);
|
|
45047
45299
|
const raw = typeof body === "object" && body !== null && "delivery" in body ? body.delivery : undefined;
|
|
45048
45300
|
if (raw === undefined || raw === null) {
|
|
45049
|
-
|
|
45301
|
+
throw new Error(`the listener answered no delivery for ${interest.session_id}: it predates session consumers, and a session receives only what its own consumer holds`);
|
|
45050
45302
|
}
|
|
45051
45303
|
const delivery = DeliveryAnswerWireSchema.safeParse(raw);
|
|
45052
|
-
|
|
45053
|
-
|
|
45054
|
-
|
|
45055
|
-
|
|
45304
|
+
if (!delivery.success) {
|
|
45305
|
+
const named = DeliveryRefusalSchema.safeParse(raw);
|
|
45306
|
+
const said = named.success ? `answered delivery mode ${named.data.mode}${named.data.reason === undefined ? "" : ` (${named.data.reason})`}` : DELIVERY_UNREADABLE;
|
|
45307
|
+
throw new Error(`the listener gave ${interest.session_id} no consumer: it ${said}, and a session receives only what its own consumer holds`);
|
|
45308
|
+
}
|
|
45309
|
+
return { ...interest, delivery: delivery.data };
|
|
45056
45310
|
}
|
|
45057
45311
|
function mergeInterestSources(registryTopics, liveTopics) {
|
|
45058
45312
|
const interests = new Map;
|
|
@@ -45098,27 +45352,20 @@ function expandSubscriptionTopics(topics) {
|
|
|
45098
45352
|
if (segments.length < 2 || segments.some((segment) => segment.length === 0)) {
|
|
45099
45353
|
throw new TypeError(`cannot expand Envoy wildcard topic "${topic}": its concrete base must have at least two non-empty segments`);
|
|
45100
45354
|
}
|
|
45101
|
-
|
|
45355
|
+
if (!streamDeliversNothing(base))
|
|
45356
|
+
expanded.add(base);
|
|
45102
45357
|
expanded.add(topic);
|
|
45103
45358
|
}
|
|
45104
45359
|
return [...expanded];
|
|
45105
45360
|
}
|
|
45106
45361
|
function refusalStateText(parsed) {
|
|
45107
|
-
const sentences = [];
|
|
45108
45362
|
const state = parsed.holder_state ?? parsed.state;
|
|
45109
|
-
if (state
|
|
45110
|
-
const who = parsed.holder === undefined ? "That session" : `Holder ${parsed.holder}`;
|
|
45111
|
-
const seen = parsed.last_seen === undefined || parsed.last_seen <= 0 ? "" : `, last seen ${new Date(parsed.last_seen).toISOString()}`;
|
|
45112
|
-
sentences.push(`${who} is ${state}${seen}.`);
|
|
45113
|
-
}
|
|
45114
|
-
const stored = parsed.unresponsive ?? [];
|
|
45115
|
-
if (stored.length > 0) {
|
|
45116
|
-
const one = stored.length === 1;
|
|
45117
|
-
sentences.push(`Envoy stored the message for ${stored.join(", ")}.`, `${one ? "That session" : "Those sessions"} stopped answering, so ${one ? "it" : "they"} did not fail this send.`);
|
|
45118
|
-
}
|
|
45119
|
-
if (sentences.length === 0)
|
|
45363
|
+
if (state === undefined)
|
|
45120
45364
|
return "";
|
|
45121
|
-
|
|
45365
|
+
const who = parsed.holder === undefined ? "That session" : `Holder ${parsed.holder}`;
|
|
45366
|
+
const seen = parsed.last_seen === undefined || parsed.last_seen <= 0 ? "" : `, last seen ${new Date(parsed.last_seen).toISOString()}`;
|
|
45367
|
+
const sentences = [`${who} is ${state}${seen}.`];
|
|
45368
|
+
if (state === "unresponsive")
|
|
45122
45369
|
sentences.push(UNRESPONSIVE_RULE);
|
|
45123
45370
|
return ` ${sentences.join(" ")}`;
|
|
45124
45371
|
}
|
|
@@ -45128,11 +45375,11 @@ class EnvoyApiError extends Error {
|
|
|
45128
45375
|
name = "EnvoyApiError";
|
|
45129
45376
|
expected;
|
|
45130
45377
|
code;
|
|
45378
|
+
reason;
|
|
45131
45379
|
holder;
|
|
45132
45380
|
sessionState;
|
|
45133
45381
|
lastSeen;
|
|
45134
45382
|
claimReleased;
|
|
45135
|
-
unresponsive;
|
|
45136
45383
|
constructor(details) {
|
|
45137
45384
|
let parsed;
|
|
45138
45385
|
try {
|
|
@@ -45140,15 +45387,15 @@ class EnvoyApiError extends Error {
|
|
|
45140
45387
|
if (result.success)
|
|
45141
45388
|
parsed = result.data;
|
|
45142
45389
|
} catch {}
|
|
45143
|
-
super(parsed === undefined ? `${details.method} ${details.url} failed with ${details.status}: ${details.responseBody}` : `${parsed.error}${parsed.expected === undefined ? "" : ` (expected: ${parsed.expected.join(", ")})`}${refusalStateText(parsed)}`);
|
|
45390
|
+
super(parsed === undefined ? `${details.method} ${details.url} failed with ${details.status}: ${details.responseBody}` : `${parsed.error}${parsed.reason === undefined ? "" : ` (reason: ${parsed.reason})`}${parsed.expected === undefined ? "" : ` (expected: ${parsed.expected.join(", ")})`}${refusalStateText(parsed)}`);
|
|
45144
45391
|
this.details = details;
|
|
45145
45392
|
this.expected = parsed?.expected;
|
|
45146
45393
|
this.code = parsed?.code;
|
|
45394
|
+
this.reason = parsed?.reason;
|
|
45147
45395
|
this.holder = parsed?.holder;
|
|
45148
45396
|
this.sessionState = parsed?.holder_state ?? parsed?.state;
|
|
45149
45397
|
this.lastSeen = parsed?.last_seen;
|
|
45150
45398
|
this.claimReleased = parsed?.claim_released;
|
|
45151
|
-
this.unresponsive = parsed?.unresponsive;
|
|
45152
45399
|
}
|
|
45153
45400
|
}
|
|
45154
45401
|
var mintedDedupeKey2 = new RegExp(MINTED_DEDUPE_KEY_PATTERN);
|
|
@@ -45258,23 +45505,24 @@ function createEnvoyClient(config) {
|
|
|
45258
45505
|
headers: { "Content-Type": "application/json" },
|
|
45259
45506
|
body: JSON.stringify(body)
|
|
45260
45507
|
}, options);
|
|
45508
|
+
const subscribeBody = (input) => ({
|
|
45509
|
+
session_id: input.sessionID,
|
|
45510
|
+
dir: input.directory,
|
|
45511
|
+
topics: expandSubscriptionTopics(input.topics),
|
|
45512
|
+
port: input.port,
|
|
45513
|
+
title: input.title,
|
|
45514
|
+
...input.capabilities === undefined ? {} : { capabilities: input.capabilities },
|
|
45515
|
+
driving: input.driving,
|
|
45516
|
+
...input.selfSubscribed === undefined ? {} : { self_subscribed: input.selfSubscribed },
|
|
45517
|
+
delivery: input.delivery,
|
|
45518
|
+
...input.clientInstanceID === undefined ? {} : { client_instance_id: input.clientInstanceID },
|
|
45519
|
+
host: machineID(),
|
|
45520
|
+
...input.place === undefined ? {} : { tmux_place: input.place },
|
|
45521
|
+
plugin: input.plugin.name,
|
|
45522
|
+
plugin_version: input.plugin.version
|
|
45523
|
+
});
|
|
45261
45524
|
return {
|
|
45262
|
-
subscribe: async (input) => parseSubscribeAnswer(JSON.parse(await post("/v1/interests/subscribe", {
|
|
45263
|
-
session_id: input.sessionID,
|
|
45264
|
-
dir: input.directory,
|
|
45265
|
-
topics: expandSubscriptionTopics(input.topics),
|
|
45266
|
-
port: input.port,
|
|
45267
|
-
title: input.title,
|
|
45268
|
-
...input.capabilities === undefined ? {} : { capabilities: input.capabilities },
|
|
45269
|
-
driving: input.driving,
|
|
45270
|
-
...input.selfSubscribed === undefined ? {} : { self_subscribed: input.selfSubscribed },
|
|
45271
|
-
...input.delivery === undefined ? {} : { delivery: input.delivery },
|
|
45272
|
-
...input.clientInstanceID === undefined ? {} : { client_instance_id: input.clientInstanceID },
|
|
45273
|
-
host: machineID(),
|
|
45274
|
-
...input.place === undefined ? {} : { tmux_place: input.place },
|
|
45275
|
-
plugin: input.plugin.name,
|
|
45276
|
-
plugin_version: input.plugin.version
|
|
45277
|
-
}, { actingSession: input.sessionID }))),
|
|
45525
|
+
subscribe: async (input) => parseSubscribeAnswer(JSON.parse(await post("/v1/interests/subscribe", subscribeBody(input), { actingSession: input.sessionID }))),
|
|
45278
45526
|
unsubscribe: async (input) => {
|
|
45279
45527
|
await post("/v1/interests/unsubscribe", {
|
|
45280
45528
|
session_id: input.sessionID,
|
|
@@ -45333,7 +45581,6 @@ function createEnvoyClient(config) {
|
|
|
45333
45581
|
envelope: response,
|
|
45334
45582
|
...response.holder === undefined ? {} : { holder: response.holder },
|
|
45335
45583
|
...response.holder_state === undefined ? {} : { holderState: response.holder_state },
|
|
45336
|
-
unresponsive: response.unresponsive ?? [],
|
|
45337
45584
|
...response.kept === undefined ? {} : { kept: response.kept },
|
|
45338
45585
|
...response.kept_reason === undefined ? {} : { keptReason: response.kept_reason }
|
|
45339
45586
|
};
|
|
@@ -45351,897 +45598,57 @@ function createEnvoyClient(config) {
|
|
|
45351
45598
|
...soft ? { soft: true } : {},
|
|
45352
45599
|
...previous === "" ? {} : { previous_session_id: previous },
|
|
45353
45600
|
...input.clientInstanceID === undefined ? {} : { client_instance_id: input.clientInstanceID }
|
|
45354
|
-
};
|
|
45355
|
-
let raw;
|
|
45356
|
-
try {
|
|
45357
|
-
raw = await post("/v1/roles/set", body, { actingSession: input.sessionID });
|
|
45358
|
-
} catch (error) {
|
|
45359
|
-
if (error instanceof EnvoyApiError && error.details.status === 409) {
|
|
45360
|
-
let answer;
|
|
45361
|
-
try {
|
|
45362
|
-
answer = JSON.parse(error.details.responseBody);
|
|
45363
|
-
} catch {
|
|
45364
|
-
throw error;
|
|
45365
|
-
}
|
|
45366
|
-
const held = RoleHeldWireSchema.safeParse(answer);
|
|
45367
|
-
if (held.success)
|
|
45368
|
-
return { claimed: false, holder: held.data.holder };
|
|
45369
|
-
}
|
|
45370
|
-
throw error;
|
|
45371
|
-
}
|
|
45372
|
-
return { claimed: true, interest: InterestWireSchema.parse(JSON.parse(raw)) };
|
|
45373
|
-
},
|
|
45374
|
-
getRole: async (role) => RoleWireSchema.parse(JSON.parse(await request(`/v1/roles/${encodeURIComponent(role)}`, { method: "GET" }))),
|
|
45375
|
-
listSessions: async (input = {}) => {
|
|
45376
|
-
const search = new URLSearchParams;
|
|
45377
|
-
if (input.directory !== undefined)
|
|
45378
|
-
search.set("dir", input.directory);
|
|
45379
|
-
if (input.title !== undefined)
|
|
45380
|
-
search.set("title", input.title);
|
|
45381
|
-
if (input.include !== undefined)
|
|
45382
|
-
search.set("include", input.include);
|
|
45383
|
-
const query = search.size === 0 ? "" : `?${search.toString()}`;
|
|
45384
|
-
return SessionWireSchema.array().parse(JSON.parse(await request(`/v1/sessions${query}`, {})));
|
|
45385
|
-
}
|
|
45386
|
-
replay: async (input) => ReplayWireSchema.parse(JSON.parse(await post("/v1/replay", {
|
|
45387
|
-
session_id: input.sessionID,
|
|
45388
|
-
subjects: input.subjects.map((cursor) => cursor.after === undefined ? { subject: cursor.subject } : { subject: cursor.subject, after: cursor.after }),
|
|
45389
|
-
...input.maxMessages === undefined ? {} : { max_messages: input.maxMessages }
|
|
45390
|
-
}, {
|
|
45391
|
-
timeoutMs: input.timeoutMs ?? REPLAY_TIMEOUT_MS,
|
|
45392
|
-
retry: false,
|
|
45393
|
-
actingSession: input.sessionID
|
|
45394
|
-
})))
|
|
45395
|
-
};
|
|
45396
|
-
}
|
|
45397
|
-
function waitForRetry(delayMs) {
|
|
45398
|
-
const { promise, resolve } = Promise.withResolvers();
|
|
45399
|
-
setTimeout(resolve, delayMs);
|
|
45400
|
-
return promise;
|
|
45401
|
-
}
|
|
45402
|
-
function messageMetadata(input) {
|
|
45403
|
-
return {
|
|
45404
|
-
...input.inReplyTo === undefined ? {} : { in_reply_to: input.inReplyTo },
|
|
45405
|
-
...input.supersedes === undefined ? {} : { supersedes: input.supersedes },
|
|
45406
|
-
...input.urgency === undefined ? {} : { urgency: input.urgency },
|
|
45407
|
-
...input.expectsReply === undefined ? {} : { expects_reply: input.expectsReply },
|
|
45408
|
-
...input.expiresAt === undefined ? {} : { expires_at: input.expiresAt }
|
|
45409
|
-
};
|
|
45410
|
-
}
|
|
45411
|
-
function sourceSession(sessionID) {
|
|
45412
|
-
return sessionID === undefined || sessionID === "" ? {} : { source_session: sessionID };
|
|
45413
|
-
}
|
|
45414
|
-
|
|
45415
|
-
// ../envoy-client/src/replay.ts
|
|
45416
|
-
var REPLAY_LEDGER_TTL_MS = DELIVERY_DUPLICATE_WINDOW_MS;
|
|
45417
|
-
var REPLAY_LEDGER_LIMIT = 20000;
|
|
45418
|
-
var REPLAY_PAGES_PER_SWEEP = 20;
|
|
45419
|
-
var REPLAY_FAILURES_BEFORE_NOTICE = 3;
|
|
45420
|
-
var REPLAY_STATE_REFRESH_MS = 60 * 60 * 1000;
|
|
45421
|
-
var REPLAY_MAX_SUBJECTS = 32;
|
|
45422
|
-
var START_CURSORS_TIMEOUT_MS = 2000;
|
|
45423
|
-
var ROLE_FORWARD_KEY_PREFIX = "envoy.role.forward.";
|
|
45424
|
-
var ReplayLedgerEntrySchema = object({
|
|
45425
|
-
event_id: string2().min(1).optional(),
|
|
45426
|
-
dedupe_key: string2().min(1).optional(),
|
|
45427
|
-
at: number2()
|
|
45428
|
-
});
|
|
45429
|
-
var ReplayCursorSchema = object({
|
|
45430
|
-
since: number2().int().nonnegative().optional(),
|
|
45431
|
-
after: number2().int().nonnegative().optional(),
|
|
45432
|
-
from_start: number2().int().nonnegative().optional()
|
|
45433
|
-
});
|
|
45434
|
-
var ReplayPendingNoticeSchema = _enum2([
|
|
45435
|
-
"retention_gap",
|
|
45436
|
-
"stream_moved_back",
|
|
45437
|
-
"stream_recreated"
|
|
45438
|
-
]);
|
|
45439
|
-
var PENDING_NOTICE_MESSAGES = {
|
|
45440
|
-
stream_recreated: "Envoy's notification stream was recreated, so messages published to this session while its connection was down before that may be lost.",
|
|
45441
|
-
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.",
|
|
45442
|
-
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."
|
|
45443
|
-
};
|
|
45444
|
-
var ReplayStateSchema = object({
|
|
45445
|
-
stream_id: string2().optional(),
|
|
45446
|
-
stream_created: string2().optional(),
|
|
45447
|
-
subjects: record(string2(), ReplayCursorSchema),
|
|
45448
|
-
notices: array(string2()).optional()
|
|
45449
|
-
});
|
|
45450
|
-
var ReplaySnapshotSchema = object({
|
|
45451
|
-
state: ReplayStateSchema.optional(),
|
|
45452
|
-
ledger: array(ReplayLedgerEntrySchema)
|
|
45453
|
-
});
|
|
45454
|
-
function createReplayEngine(options) {
|
|
45455
|
-
const { host, transport, dedupe } = options;
|
|
45456
|
-
const now = options.now ?? Date.now;
|
|
45457
|
-
const ledger = createLedger(now);
|
|
45458
|
-
const cursors = new Map;
|
|
45459
|
-
const cursorStarts = new Map;
|
|
45460
|
-
let streamID;
|
|
45461
|
-
let streamCreated;
|
|
45462
|
-
const pending = new Set;
|
|
45463
|
-
const failures = new Map;
|
|
45464
|
-
let unwritten = [];
|
|
45465
|
-
let writtenState;
|
|
45466
|
-
let writtenShape;
|
|
45467
|
-
let writtenAt;
|
|
45468
|
-
let writes = Promise.resolve();
|
|
45469
|
-
let epoch = 0;
|
|
45470
|
-
let listenerNoticed;
|
|
45471
|
-
const answered = new Set;
|
|
45472
|
-
let running;
|
|
45473
|
-
let rerun;
|
|
45474
|
-
let consumerMode = false;
|
|
45475
|
-
const safely = (what, call) => {
|
|
45476
|
-
try {
|
|
45477
|
-
call();
|
|
45478
|
-
} catch (error) {
|
|
45479
|
-
try {
|
|
45480
|
-
host.log(`replay: ${what} failed`, error);
|
|
45481
|
-
} catch {}
|
|
45482
|
-
}
|
|
45483
|
-
};
|
|
45484
|
-
const log = (message, error) => safely("log", () => host.log(message, error));
|
|
45485
|
-
const notify = (notice) => safely("notice", () => host.notify(notice));
|
|
45486
|
-
const tell = (kind) => {
|
|
45487
|
-
pending.delete(kind);
|
|
45488
|
-
notify({ kind, message: PENDING_NOTICE_MESSAGES[kind] });
|
|
45489
|
-
};
|
|
45490
|
-
const sessionRead = (read) => () => {
|
|
45491
|
-
try {
|
|
45492
|
-
return read();
|
|
45493
|
-
} catch {
|
|
45494
|
-
return;
|
|
45495
|
-
}
|
|
45496
|
-
};
|
|
45497
|
-
const currentSession = sessionRead(() => host.sessionID());
|
|
45498
|
-
const writeSession = sessionRead(() => host.writeSessionID === undefined ? host.sessionID() : host.writeSessionID());
|
|
45499
|
-
const bindTo = (sessionID, read) => {
|
|
45500
|
-
if (sessionID === undefined || sessionID === "" || read() !== sessionID)
|
|
45501
|
-
return;
|
|
45502
|
-
const bound = epoch;
|
|
45503
|
-
return { sessionID, alive: () => bound === epoch && read() === sessionID };
|
|
45504
|
-
};
|
|
45505
|
-
const bind = () => bindTo(currentSession(), currentSession);
|
|
45506
|
-
const stateJSON = (afters = true) => {
|
|
45507
|
-
const subjects = {};
|
|
45508
|
-
for (const subject of [...cursors.keys()].sort()) {
|
|
45509
|
-
const cursor = cursors.get(subject) ?? {};
|
|
45510
|
-
subjects[subject] = {
|
|
45511
|
-
...cursor.since === undefined ? {} : { since: cursor.since },
|
|
45512
|
-
...!afters || cursor.after === undefined ? {} : { after: cursor.after },
|
|
45513
|
-
...cursor.from_start === undefined ? {} : { from_start: cursor.from_start }
|
|
45514
|
-
};
|
|
45515
|
-
}
|
|
45516
|
-
return JSON.stringify({
|
|
45517
|
-
...streamID === undefined ? {} : { stream_id: streamID },
|
|
45518
|
-
...streamCreated === undefined ? {} : { stream_created: streamCreated },
|
|
45519
|
-
subjects,
|
|
45520
|
-
...pending.size === 0 ? {} : { notices: [...pending].sort() }
|
|
45521
|
-
});
|
|
45522
|
-
};
|
|
45523
|
-
const record2 = (identity) => {
|
|
45524
|
-
const entry = ledger.record(identity);
|
|
45525
|
-
if (entry !== undefined)
|
|
45526
|
-
unwritten.push(entry);
|
|
45527
|
-
};
|
|
45528
|
-
const flush = (alive, atOnce = false) => {
|
|
45529
|
-
const written = writes.then(async () => {
|
|
45530
|
-
if (!alive())
|
|
45531
|
-
return false;
|
|
45532
|
-
const json = stateJSON();
|
|
45533
|
-
const delivered = unwritten;
|
|
45534
|
-
if (json === writtenState && delivered.length === 0)
|
|
45535
|
-
return true;
|
|
45536
|
-
const shape = stateJSON(false);
|
|
45537
|
-
if (delivered.length === 0 && !atOnce && shape === writtenShape && writtenAt !== undefined && now() - writtenAt < REPLAY_STATE_REFRESH_MS) {
|
|
45538
|
-
return true;
|
|
45539
|
-
}
|
|
45540
|
-
unwritten = [];
|
|
45541
|
-
const state = json === writtenState ? undefined : JSON.parse(json);
|
|
45542
|
-
try {
|
|
45543
|
-
await host.write({
|
|
45544
|
-
delivered,
|
|
45545
|
-
state,
|
|
45546
|
-
snapshot: () => ({ state: JSON.parse(json), ledger: ledger.list() })
|
|
45547
|
-
});
|
|
45548
|
-
if (state !== undefined) {
|
|
45549
|
-
writtenState = json;
|
|
45550
|
-
writtenShape = shape;
|
|
45551
|
-
writtenAt = now();
|
|
45552
|
-
}
|
|
45553
|
-
return true;
|
|
45554
|
-
} catch (error) {
|
|
45555
|
-
unwritten = [...delivered, ...unwritten];
|
|
45556
|
-
log("replay: could not persist the replay state; the next write carries it", error);
|
|
45557
|
-
return false;
|
|
45558
|
-
}
|
|
45559
|
-
});
|
|
45560
|
-
writes = written.then(() => {
|
|
45561
|
-
return;
|
|
45562
|
-
});
|
|
45563
|
-
return written;
|
|
45564
|
-
};
|
|
45565
|
-
const syncFollowed = () => {
|
|
45566
|
-
const followed = new Set(host.followedSubjects());
|
|
45567
|
-
for (const subject of [...cursors.keys()]) {
|
|
45568
|
-
if (!followed.has(subject)) {
|
|
45569
|
-
cursors.delete(subject);
|
|
45570
|
-
cursorStarts.delete(subject);
|
|
45571
|
-
}
|
|
45572
|
-
}
|
|
45573
|
-
for (const subject of followed) {
|
|
45574
|
-
if (!cursors.has(subject))
|
|
45575
|
-
cursors.set(subject, {});
|
|
45576
|
-
}
|
|
45577
|
-
};
|
|
45578
|
-
const failureNotice = (envelope, publishedAt, error, subject) => ({
|
|
45579
|
-
eventId: envelope.event_id ?? "unknown",
|
|
45580
|
-
sender: senderLabel(envelope),
|
|
45581
|
-
summary: envelope.payload_summary ?? "unknown",
|
|
45582
|
-
publishedAt,
|
|
45583
|
-
error,
|
|
45584
|
-
readWith: envelope.source === "dispatch" ? "dispatch read" : "envoy_inbox",
|
|
45585
|
-
...subject === undefined ? {} : { subject },
|
|
45586
|
-
envelope
|
|
45587
|
-
});
|
|
45588
|
-
const showFailureNotice = async (notice, alive) => {
|
|
45589
|
-
let queued;
|
|
45590
|
-
try {
|
|
45591
|
-
queued = await host.showFailureNotice(notice) === "queued";
|
|
45592
|
-
} catch (error) {
|
|
45593
|
-
if (!alive())
|
|
45594
|
-
return "stopped";
|
|
45595
|
-
safely("failure notice warning", () => host.failureNoticeFailed(notice, error));
|
|
45596
|
-
return "hole";
|
|
45597
|
-
}
|
|
45598
|
-
if (!alive())
|
|
45599
|
-
return "stopped";
|
|
45600
|
-
if (queued)
|
|
45601
|
-
return "hole";
|
|
45602
|
-
record2(replayLedgerIdentity(notice.envelope));
|
|
45603
|
-
await flush(alive);
|
|
45604
|
-
return "done";
|
|
45605
|
-
};
|
|
45606
|
-
const handle = async (seq, buffered, alive) => {
|
|
45607
|
-
const { message } = buffered;
|
|
45608
|
-
const envelope = parseEnvelope(message.data);
|
|
45609
|
-
if (envelope === undefined) {
|
|
45610
|
-
log(`replay: skipping stored message ${seq} on ${message.subject}: not an Envoy envelope`);
|
|
45611
|
-
return "done";
|
|
45612
|
-
}
|
|
45613
|
-
if (isRoleForward(envelope))
|
|
45614
|
-
return "done";
|
|
45615
|
-
const identity = replayLedgerIdentity(envelope);
|
|
45616
|
-
if (ledger.has(identity)) {
|
|
45617
|
-
failures.delete(seq);
|
|
45618
|
-
return "done";
|
|
45619
|
-
}
|
|
45620
|
-
if (dedupe?.pending(envelope) === true)
|
|
45621
|
-
return "hole";
|
|
45622
|
-
if (!alive())
|
|
45623
|
-
return "stopped";
|
|
45624
|
-
const giveUp = async (error) => {
|
|
45625
|
-
const handled = await showFailureNotice(failureNotice(envelope, message.time, error, message.subject), alive);
|
|
45626
|
-
if (handled === "done")
|
|
45627
|
-
failures.delete(seq);
|
|
45628
|
-
return handled;
|
|
45629
|
-
};
|
|
45630
|
-
const failure = failures.get(seq);
|
|
45631
|
-
if (failure !== undefined && failure.count >= REPLAY_FAILURES_BEFORE_NOTICE) {
|
|
45632
|
-
return giveUp(failure.error);
|
|
45633
|
-
}
|
|
45634
|
-
const followed = buffered.subjects[0] ?? message.subject;
|
|
45635
|
-
let outcome;
|
|
45636
|
-
let error = "the host could not show it";
|
|
45637
|
-
try {
|
|
45638
|
-
outcome = await host.deliver({
|
|
45639
|
-
envelope,
|
|
45640
|
-
data: message.data,
|
|
45641
|
-
seq,
|
|
45642
|
-
subject: message.subject,
|
|
45643
|
-
followed,
|
|
45644
|
-
time: message.time,
|
|
45645
|
-
since: cursors.get(followed)?.since
|
|
45646
|
-
});
|
|
45647
|
-
} catch (thrown) {
|
|
45648
|
-
outcome = "failed";
|
|
45649
|
-
error = messageFor(thrown);
|
|
45650
|
-
}
|
|
45651
|
-
if (!alive())
|
|
45652
|
-
return "stopped";
|
|
45653
|
-
if (outcome === "shown") {
|
|
45654
|
-
failures.delete(seq);
|
|
45655
|
-
record2(identity);
|
|
45656
|
-
await flush(alive);
|
|
45657
|
-
return "done";
|
|
45658
|
-
}
|
|
45659
|
-
if (outcome === "suppressed") {
|
|
45660
|
-
failures.delete(seq);
|
|
45661
|
-
return "done";
|
|
45662
|
-
}
|
|
45663
|
-
if (outcome === "queued") {
|
|
45664
|
-
failures.delete(seq);
|
|
45665
|
-
return "hole";
|
|
45666
|
-
}
|
|
45667
|
-
const count = (failure?.count ?? 0) + 1;
|
|
45668
|
-
failures.set(seq, { count, error });
|
|
45669
|
-
if (count >= REPLAY_FAILURES_BEFORE_NOTICE)
|
|
45670
|
-
return giveUp(error);
|
|
45671
|
-
log(`replay: could not show stored message ${seq} (${envelope.event_id}): ${error}`);
|
|
45672
|
-
return "hole";
|
|
45673
|
-
};
|
|
45674
|
-
const listenerFailed = (error) => {
|
|
45675
|
-
if (error instanceof EnvoyApiError) {
|
|
45676
|
-
const status = error.details.status;
|
|
45677
|
-
if (status === 404) {
|
|
45678
|
-
if (listenerNoticed === "not_served")
|
|
45679
|
-
return;
|
|
45680
|
-
listenerNoticed = "not_served";
|
|
45681
|
-
notify({
|
|
45682
|
-
kind: "not_served",
|
|
45683
|
-
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."
|
|
45684
|
-
});
|
|
45685
|
-
return;
|
|
45686
|
-
}
|
|
45687
|
-
if (status === 503 && error.code === REPLAY_UNAVAILABLE_CODE || status === 401 || status === 403) {
|
|
45688
|
-
const key = `unavailable:${status}:${error.message}`;
|
|
45689
|
-
if (listenerNoticed === key)
|
|
45690
|
-
return;
|
|
45691
|
-
listenerNoticed = key;
|
|
45692
|
-
notify({
|
|
45693
|
-
kind: "unavailable",
|
|
45694
|
-
status,
|
|
45695
|
-
error: error.message,
|
|
45696
|
-
message: `Envoy replay is unavailable (${status}: ${error.message}), so messages published while this session's connection is down are not recovered until it answers.`
|
|
45697
|
-
});
|
|
45698
|
-
return;
|
|
45699
|
-
}
|
|
45700
|
-
}
|
|
45701
|
-
log("replay: the listener's replay failed; the next trigger tries again", error);
|
|
45702
|
-
};
|
|
45703
|
-
const streamReplaced = (stream) => {
|
|
45704
|
-
if (stream.id === undefined) {
|
|
45705
|
-
return streamCreated !== undefined && streamCreated !== "" && stream.created !== streamCreated;
|
|
45706
|
-
}
|
|
45707
|
-
return streamID !== undefined && streamID !== "" && stream.id !== streamID;
|
|
45708
|
-
};
|
|
45709
|
-
const streamMovedBack = (stream) => {
|
|
45710
|
-
for (const cursor of cursors.values()) {
|
|
45711
|
-
if (cursor.after !== undefined && cursor.after > stream.last_seq)
|
|
45712
|
-
return true;
|
|
45713
|
-
}
|
|
45714
|
-
return false;
|
|
45715
|
-
};
|
|
45716
|
-
const sweepOnce = async () => {
|
|
45717
|
-
const binding = bind();
|
|
45718
|
-
if (binding === undefined)
|
|
45719
|
-
return;
|
|
45720
|
-
const { sessionID, alive } = binding;
|
|
45721
|
-
syncFollowed();
|
|
45722
|
-
const readings = new Map;
|
|
45723
|
-
for (const [subject, cursor] of cursors) {
|
|
45724
|
-
readings.set(subject, {
|
|
45725
|
-
read: cursor.from_start === undefined ? cursor.after : 0,
|
|
45726
|
-
more: true
|
|
45727
|
-
});
|
|
45728
|
-
}
|
|
45729
|
-
const buffer = new Map;
|
|
45730
|
-
const holes = new Map;
|
|
45731
|
-
let gapNoticed = false;
|
|
45732
|
-
if (pending.size > 0) {
|
|
45733
|
-
for (const kind of [...pending].sort()) {
|
|
45734
|
-
if (kind === "retention_gap")
|
|
45735
|
-
gapNoticed = true;
|
|
45736
|
-
tell(kind);
|
|
45737
|
-
}
|
|
45738
|
-
await flush(alive);
|
|
45739
|
-
if (!alive())
|
|
45740
|
-
return;
|
|
45741
|
-
}
|
|
45742
|
-
if (consumerMode)
|
|
45743
|
-
return;
|
|
45744
|
-
for (let page = 0;page < REPLAY_PAGES_PER_SWEEP; page += 1) {
|
|
45745
|
-
let handledAny = false;
|
|
45746
|
-
const asking = [...readings].filter(([, reading]) => reading.more).sort(([, a], [, b]) => (a.read ?? -1) - (b.read ?? -1)).slice(0, REPLAY_MAX_SUBJECTS);
|
|
45747
|
-
if (asking.length === 0)
|
|
45748
|
-
break;
|
|
45749
|
-
let response;
|
|
45750
|
-
try {
|
|
45751
|
-
response = await transport.replay({
|
|
45752
|
-
sessionID,
|
|
45753
|
-
subjects: asking.map(([subject, reading]) => reading.read === undefined ? { subject } : { subject, after: reading.read }),
|
|
45754
|
-
...options.maxMessages === undefined ? {} : { maxMessages: options.maxMessages }
|
|
45755
|
-
});
|
|
45756
|
-
} catch (error) {
|
|
45757
|
-
if (alive()) {
|
|
45758
|
-
answered.clear();
|
|
45759
|
-
listenerFailed(error);
|
|
45760
|
-
}
|
|
45761
|
-
return;
|
|
45762
|
-
}
|
|
45763
|
-
if (!alive())
|
|
45764
|
-
return;
|
|
45765
|
-
listenerNoticed = undefined;
|
|
45766
|
-
for (const result of response.subjects) {
|
|
45767
|
-
if (result.refused === undefined)
|
|
45768
|
-
answered.add(result.subject);
|
|
45769
|
-
else
|
|
45770
|
-
answered.delete(result.subject);
|
|
45771
|
-
}
|
|
45772
|
-
const { stream } = response;
|
|
45773
|
-
const replaced = streamReplaced(stream);
|
|
45774
|
-
streamID = stream.id ?? (replaced ? undefined : streamID);
|
|
45775
|
-
streamCreated = stream.created;
|
|
45776
|
-
if (replaced) {
|
|
45777
|
-
const at = now();
|
|
45778
|
-
for (const subject of cursors.keys()) {
|
|
45779
|
-
cursors.set(subject, { since: stream.last_seq, after: stream.last_seq });
|
|
45780
|
-
cursorStarts.set(subject, at);
|
|
45781
|
-
}
|
|
45782
|
-
failures.clear();
|
|
45783
|
-
pending.add("stream_recreated");
|
|
45784
|
-
await flush(alive);
|
|
45785
|
-
if (!alive())
|
|
45786
|
-
return;
|
|
45787
|
-
tell("stream_recreated");
|
|
45788
|
-
await flush(alive);
|
|
45789
|
-
return;
|
|
45790
|
-
}
|
|
45791
|
-
if (streamMovedBack(stream)) {
|
|
45792
|
-
const from = Math.max(0, stream.first_seq - 1);
|
|
45793
|
-
for (const [subject, cursor] of cursors) {
|
|
45794
|
-
if (cursor.after === undefined)
|
|
45795
|
-
continue;
|
|
45796
|
-
cursors.set(subject, { ...cursor, after: from });
|
|
45797
|
-
const reading = readings.get(subject);
|
|
45798
|
-
if (reading !== undefined) {
|
|
45799
|
-
reading.read = from;
|
|
45800
|
-
reading.more = true;
|
|
45801
|
-
}
|
|
45802
|
-
}
|
|
45803
|
-
buffer.clear();
|
|
45804
|
-
holes.clear();
|
|
45805
|
-
failures.clear();
|
|
45806
|
-
pending.add("stream_moved_back");
|
|
45807
|
-
await flush(alive, true);
|
|
45808
|
-
if (!alive())
|
|
45809
|
-
return;
|
|
45810
|
-
tell("stream_moved_back");
|
|
45811
|
-
await flush(alive);
|
|
45812
|
-
if (!alive())
|
|
45813
|
-
return;
|
|
45814
|
-
continue;
|
|
45815
|
-
}
|
|
45816
|
-
for (const [, reading] of asking)
|
|
45817
|
-
reading.more = false;
|
|
45818
|
-
for (const result of response.subjects) {
|
|
45819
|
-
const reading = readings.get(result.subject);
|
|
45820
|
-
const markedAt = cursors.get(result.subject)?.from_start;
|
|
45821
|
-
if (reading === undefined || markedAt === undefined || result.refused !== undefined) {
|
|
45822
|
-
continue;
|
|
45823
|
-
}
|
|
45824
|
-
const start = Math.max(0, stream.first_seq - 1);
|
|
45825
|
-
cursors.set(result.subject, { since: start, after: start });
|
|
45826
|
-
cursorStarts.set(result.subject, now());
|
|
45827
|
-
if (now() - markedAt < DELIVERY_DUPLICATE_WINDOW_MS)
|
|
45828
|
-
reading.read = start;
|
|
45829
|
-
}
|
|
45830
|
-
let gapped = false;
|
|
45831
|
-
for (const result of response.subjects) {
|
|
45832
|
-
const reading = readings.get(result.subject);
|
|
45833
|
-
if (reading?.read === undefined || result.refused !== undefined)
|
|
45834
|
-
continue;
|
|
45835
|
-
if (reading.read >= stream.first_seq - 1)
|
|
45836
|
-
continue;
|
|
45837
|
-
gapped = true;
|
|
45838
|
-
reading.read = stream.first_seq - 1;
|
|
45839
|
-
const cursor = cursors.get(result.subject);
|
|
45840
|
-
if (cursor?.after !== undefined && cursor.after < reading.read) {
|
|
45841
|
-
cursors.set(result.subject, { ...cursor, after: reading.read });
|
|
45842
|
-
}
|
|
45843
|
-
}
|
|
45844
|
-
if (gapped) {
|
|
45845
|
-
if (!gapNoticed)
|
|
45846
|
-
pending.add("retention_gap");
|
|
45847
|
-
await flush(alive, true);
|
|
45848
|
-
if (!alive())
|
|
45849
|
-
return;
|
|
45850
|
-
if (pending.has("retention_gap")) {
|
|
45851
|
-
gapNoticed = true;
|
|
45852
|
-
tell("retention_gap");
|
|
45853
|
-
await flush(alive);
|
|
45854
|
-
}
|
|
45855
|
-
}
|
|
45856
|
-
for (const result of response.subjects) {
|
|
45857
|
-
const reading = readings.get(result.subject);
|
|
45858
|
-
if (reading === undefined || result.refused !== undefined)
|
|
45859
|
-
continue;
|
|
45860
|
-
if (reading.read === undefined) {
|
|
45861
|
-
const cursor = cursors.get(result.subject);
|
|
45862
|
-
if (cursor !== undefined && cursor.after === undefined) {
|
|
45863
|
-
cursors.set(result.subject, { since: result.next_after, after: result.next_after });
|
|
45864
|
-
cursorStarts.set(result.subject, now());
|
|
45865
|
-
}
|
|
45866
|
-
reading.read = result.next_after;
|
|
45867
|
-
continue;
|
|
45868
|
-
}
|
|
45869
|
-
for (const message of result.messages) {
|
|
45870
|
-
if (message.seq <= reading.read)
|
|
45871
|
-
continue;
|
|
45872
|
-
const buffered = buffer.get(message.seq);
|
|
45873
|
-
if (buffered === undefined) {
|
|
45874
|
-
buffer.set(message.seq, { message, subjects: [result.subject] });
|
|
45875
|
-
} else if (!buffered.subjects.includes(result.subject)) {
|
|
45876
|
-
buffered.subjects.push(result.subject);
|
|
45877
|
-
}
|
|
45878
|
-
}
|
|
45879
|
-
reading.read = Math.max(reading.read, result.next_after);
|
|
45880
|
-
reading.more = result.more;
|
|
45881
|
-
}
|
|
45882
|
-
let bound = Number.POSITIVE_INFINITY;
|
|
45883
|
-
for (const reading of readings.values()) {
|
|
45884
|
-
if (reading.more && reading.read !== undefined)
|
|
45885
|
-
bound = Math.min(bound, reading.read);
|
|
45886
|
-
}
|
|
45887
|
-
const ready = [...buffer.keys()].filter((seq) => seq <= bound).sort((a, b) => a - b);
|
|
45888
|
-
for (const seq of ready) {
|
|
45889
|
-
const buffered = buffer.get(seq);
|
|
45890
|
-
if (buffered === undefined)
|
|
45891
|
-
continue;
|
|
45892
|
-
buffer.delete(seq);
|
|
45893
|
-
if (!buffered.subjects.some((subject) => cursors.has(subject)))
|
|
45894
|
-
continue;
|
|
45895
|
-
const handled = await handle(seq, buffered, alive);
|
|
45896
|
-
if (handled === "stopped")
|
|
45897
|
-
return;
|
|
45898
|
-
if (handled === "done")
|
|
45899
|
-
handledAny = true;
|
|
45900
|
-
if (handled === "hole") {
|
|
45901
|
-
for (const subject of buffered.subjects) {
|
|
45902
|
-
if (!holes.has(subject))
|
|
45903
|
-
holes.set(subject, seq);
|
|
45904
|
-
}
|
|
45905
|
-
}
|
|
45906
|
-
}
|
|
45907
|
-
if (!alive())
|
|
45908
|
-
return;
|
|
45909
|
-
for (const [subject, reading] of readings) {
|
|
45910
|
-
const cursor = cursors.get(subject);
|
|
45911
|
-
if (cursor?.after === undefined || reading.read === undefined)
|
|
45912
|
-
continue;
|
|
45913
|
-
let after = Math.min(reading.read, bound);
|
|
45914
|
-
const hole = holes.get(subject);
|
|
45915
|
-
if (hole !== undefined)
|
|
45916
|
-
after = Math.min(after, hole - 1);
|
|
45917
|
-
if (after > cursor.after)
|
|
45918
|
-
cursors.set(subject, { ...cursor, after });
|
|
45919
|
-
}
|
|
45920
|
-
await flush(alive, handledAny);
|
|
45921
|
-
if (![...readings.values()].some((reading) => reading.more))
|
|
45922
|
-
break;
|
|
45923
|
-
}
|
|
45924
|
-
};
|
|
45925
|
-
const runSweep = async () => {
|
|
45926
|
-
try {
|
|
45927
|
-
await sweepOnce();
|
|
45928
|
-
} catch (error) {
|
|
45929
|
-
log("replay: a sweep failed", error);
|
|
45930
|
-
}
|
|
45931
|
-
};
|
|
45932
|
-
const sweep = () => {
|
|
45933
|
-
if (running === undefined) {
|
|
45934
|
-
running = runSweep().finally(() => {
|
|
45935
|
-
running = undefined;
|
|
45936
|
-
});
|
|
45937
|
-
return running;
|
|
45938
|
-
}
|
|
45939
|
-
rerun ??= running.then(() => {
|
|
45940
|
-
rerun = undefined;
|
|
45941
|
-
return sweep();
|
|
45942
|
-
});
|
|
45943
|
-
return rerun;
|
|
45944
|
-
};
|
|
45945
|
-
const started = (cursor) => cursor?.after !== undefined || cursor?.from_start !== undefined;
|
|
45946
|
-
const startOnce = async () => {
|
|
45947
|
-
const binding = bind();
|
|
45948
|
-
if (binding === undefined)
|
|
45949
|
-
return;
|
|
45950
|
-
const { sessionID, alive } = binding;
|
|
45951
|
-
const unstarted = [...new Set(host.followedSubjects())].filter((subject) => !started(cursors.get(subject)));
|
|
45952
|
-
let changed = false;
|
|
45953
|
-
for (let index = 0;index < unstarted.length; index += REPLAY_MAX_SUBJECTS) {
|
|
45954
|
-
let response;
|
|
45955
|
-
try {
|
|
45956
|
-
response = await transport.replay({
|
|
45957
|
-
sessionID,
|
|
45958
|
-
subjects: unstarted.slice(index, index + REPLAY_MAX_SUBJECTS).map((subject) => ({ subject })),
|
|
45959
|
-
timeoutMs: START_CURSORS_TIMEOUT_MS
|
|
45960
|
-
});
|
|
45961
|
-
} catch (error) {
|
|
45962
|
-
if (!alive())
|
|
45963
|
-
return;
|
|
45964
|
-
const own = `${AGENT_TOPIC_PREFIX}${sessionID}`;
|
|
45965
|
-
const marked = unstarted.includes(own) && !started(cursors.get(own));
|
|
45966
|
-
if (marked) {
|
|
45967
|
-
cursors.set(own, { from_start: now() });
|
|
45968
|
-
changed = true;
|
|
45969
|
-
}
|
|
45970
|
-
log(marked ? `replay: could not read the stream's position for ${own} before registering while the session's NATS connection is down; its first sweep once the connection is back reads it from the stream's oldest message, so what is stored for it meanwhile is shown` : "replay: could not read the stream's position before registering while the session's NATS connection is down; the first sweep starts the cursors instead", error);
|
|
45971
|
-
break;
|
|
45972
|
-
}
|
|
45973
|
-
if (!alive())
|
|
45974
|
-
return;
|
|
45975
|
-
const { stream } = response;
|
|
45976
|
-
if (streamReplaced(stream))
|
|
45977
|
-
break;
|
|
45978
|
-
streamID = stream.id ?? streamID;
|
|
45979
|
-
streamCreated = stream.created;
|
|
45980
|
-
const at = now();
|
|
45981
|
-
for (const result of response.subjects) {
|
|
45982
|
-
if (result.refused !== undefined || started(cursors.get(result.subject)))
|
|
45983
|
-
continue;
|
|
45984
|
-
cursors.set(result.subject, { since: result.next_after, after: result.next_after });
|
|
45985
|
-
cursorStarts.set(result.subject, at);
|
|
45986
|
-
changed = true;
|
|
45987
|
-
}
|
|
45988
|
-
}
|
|
45989
|
-
if (changed)
|
|
45990
|
-
await flush(alive, true);
|
|
45991
|
-
};
|
|
45992
|
-
const startCursors = async () => {
|
|
45993
|
-
while (running !== undefined)
|
|
45994
|
-
await running;
|
|
45995
|
-
running = startOnce().catch((error) => log("replay: starting the cursors failed", error)).finally(() => {
|
|
45996
|
-
running = undefined;
|
|
45997
|
-
});
|
|
45998
|
-
await running;
|
|
45999
|
-
};
|
|
46000
|
-
return {
|
|
46001
|
-
sweep,
|
|
46002
|
-
startCursors,
|
|
46003
|
-
startPending: () => [...cursors.values()].some((cursor) => cursor.from_start !== undefined),
|
|
46004
|
-
setConsumerMode(on) {
|
|
46005
|
-
consumerMode = on;
|
|
46006
|
-
},
|
|
46007
|
-
async followedChanged() {
|
|
46008
|
-
const alive = bind()?.alive;
|
|
46009
|
-
if (alive === undefined)
|
|
46010
|
-
return;
|
|
46011
|
-
try {
|
|
46012
|
-
syncFollowed();
|
|
46013
|
-
await flush(alive);
|
|
46014
|
-
} catch (error) {
|
|
46015
|
-
log("replay: could not take the followed subjects", error);
|
|
46016
|
-
}
|
|
46017
|
-
},
|
|
46018
|
-
delivered: (frame) => ledger.has(replayLedgerIdentity(frame)),
|
|
46019
|
-
async recordDelivered(frame) {
|
|
46020
|
-
const alive = bind()?.alive;
|
|
46021
|
-
if (alive === undefined)
|
|
46022
|
-
return;
|
|
46023
|
-
record2(replayLedgerIdentity(frame));
|
|
46024
|
-
await flush(alive);
|
|
46025
|
-
},
|
|
46026
|
-
async recordDeliveredFor(sessionID, frame) {
|
|
46027
|
-
const alive = bindTo(sessionID, writeSession)?.alive;
|
|
46028
|
-
if (alive === undefined)
|
|
46029
|
-
return false;
|
|
46030
|
-
record2(replayLedgerIdentity(frame));
|
|
46031
|
-
return await flush(alive);
|
|
46032
|
-
},
|
|
46033
|
-
async liveFailed(sessionID, followed, envelope, error, receivedAt) {
|
|
46034
|
-
const started = cursorStarts.get(followed);
|
|
46035
|
-
if (!isRoleForward(envelope) && answered.has(followed) && cursors.get(followed)?.after !== undefined && (started === undefined || started <= receivedAt)) {
|
|
46036
|
-
return;
|
|
46037
|
-
}
|
|
46038
|
-
const alive = bindTo(sessionID, currentSession)?.alive;
|
|
46039
|
-
if (alive === undefined) {
|
|
46040
|
-
log("replay: a failed frame was not reported here; the session it names is closed");
|
|
46041
|
-
return;
|
|
46042
|
-
}
|
|
46043
|
-
try {
|
|
46044
|
-
await showFailureNotice(failureNotice(envelope, inboundTimestamp(envelope.issued_at), messageFor(error)), alive);
|
|
46045
|
-
} catch (thrown) {
|
|
46046
|
-
log("replay: could not report a failed live frame", thrown);
|
|
46047
|
-
}
|
|
46048
|
-
},
|
|
46049
|
-
followedBefore: (topic, seq) => {
|
|
46050
|
-
const since = cursors.get(topic)?.since;
|
|
46051
|
-
return since !== undefined && seq > since;
|
|
46052
|
-
},
|
|
46053
|
-
restore(snapshot) {
|
|
46054
|
-
epoch += 1;
|
|
46055
|
-
ledger.restore(snapshot.ledger);
|
|
46056
|
-
cursors.clear();
|
|
46057
|
-
cursorStarts.clear();
|
|
46058
|
-
streamID = snapshot.state?.stream_id;
|
|
46059
|
-
streamCreated = snapshot.state?.stream_created;
|
|
46060
|
-
pending.clear();
|
|
46061
|
-
for (const kind of snapshot.state?.notices ?? []) {
|
|
46062
|
-
const known = ReplayPendingNoticeSchema.safeParse(kind);
|
|
46063
|
-
if (known.success)
|
|
46064
|
-
pending.add(known.data);
|
|
46065
|
-
}
|
|
46066
|
-
for (const [subject, cursor] of Object.entries(snapshot.state?.subjects ?? {})) {
|
|
46067
|
-
cursors.set(subject, { ...cursor });
|
|
46068
|
-
}
|
|
46069
|
-
writtenState = snapshot.state === undefined ? undefined : stateJSON();
|
|
46070
|
-
writtenShape = snapshot.state === undefined ? undefined : stateJSON(false);
|
|
46071
|
-
writtenAt = undefined;
|
|
46072
|
-
unwritten = [];
|
|
46073
|
-
failures.clear();
|
|
46074
|
-
listenerNoticed = undefined;
|
|
46075
|
-
answered.clear();
|
|
46076
|
-
},
|
|
46077
|
-
state: () => JSON.parse(stateJSON())
|
|
46078
|
-
};
|
|
46079
|
-
}
|
|
46080
|
-
function replaySuppressed(rendered) {
|
|
46081
|
-
return rendered.skip || rendered.malformedDelivery === true;
|
|
46082
|
-
}
|
|
46083
|
-
var REPLAYED_SUFFIX = "while this session's connection was down.";
|
|
46084
|
-
function replayedText(content, publishedAt) {
|
|
46085
|
-
return `${content}
|
|
46086
|
-
Published at ${publishedAt} ${REPLAYED_SUFFIX}`;
|
|
46087
|
-
}
|
|
46088
|
-
function failureNoticeFields(notice) {
|
|
46089
|
-
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.";
|
|
46090
|
-
return {
|
|
46091
|
-
notice: "message not shown",
|
|
46092
|
-
event_id: notice.eventId,
|
|
46093
|
-
from: notice.sender,
|
|
46094
|
-
summary: notice.summary,
|
|
46095
|
-
published_at: notice.publishedAt,
|
|
46096
|
-
...notice.subject === undefined ? {} : { subject: notice.subject },
|
|
46097
|
-
error: notice.error,
|
|
46098
|
-
detail: `This session could not be shown this message, so it is not coming back on its own. ${readWith}`
|
|
46099
|
-
};
|
|
46100
|
-
}
|
|
46101
|
-
var REPLAY_NOTICE_NAMES = {
|
|
46102
|
-
stream_recreated: "stream recreated",
|
|
46103
|
-
stream_moved_back: "stream moved back"
|
|
46104
|
-
};
|
|
46105
|
-
function replayNoticeFields(notice) {
|
|
46106
|
-
return {
|
|
46107
|
-
notice: REPLAY_NOTICE_NAMES[notice.kind] ?? "messages may be missing",
|
|
46108
|
-
detail: notice.message
|
|
46109
|
-
};
|
|
46110
|
-
}
|
|
46111
|
-
function envoyNoticeText(fields) {
|
|
46112
|
-
return encode5({ envoy: fields });
|
|
46113
|
-
}
|
|
46114
|
-
var PRIVATE_STREAM_SUBJECTS = [
|
|
46115
|
-
`${AGENT_TOPIC_PREFIX}>`,
|
|
46116
|
-
`${LEGION_NOTICE_TOPIC_PREFIX}>`,
|
|
46117
|
-
`${EXCEPTION_TOPIC_PREFIX}${AGENT_TOPIC_PREFIX}>`
|
|
46118
|
-
];
|
|
46119
|
-
function subjectsOverlap(a, b) {
|
|
46120
|
-
const aTokens = a.split(".");
|
|
46121
|
-
const bTokens = b.split(".");
|
|
46122
|
-
for (let index = 0;index < aTokens.length && index < bTokens.length; index += 1) {
|
|
46123
|
-
const aToken = aTokens[index];
|
|
46124
|
-
const bToken = bTokens[index];
|
|
46125
|
-
if (aToken === ">" || bToken === ">")
|
|
46126
|
-
return true;
|
|
46127
|
-
if (aToken !== "*" && bToken !== "*" && aToken !== bToken)
|
|
46128
|
-
return false;
|
|
46129
|
-
}
|
|
46130
|
-
return aTokens.length === bTokens.length;
|
|
46131
|
-
}
|
|
46132
|
-
function reachesPrivateStreamSubject(ownAgentSubject, topic) {
|
|
46133
|
-
if (!PRIVATE_STREAM_SUBJECTS.some((subject) => subjectsOverlap(topic, subject)))
|
|
46134
|
-
return false;
|
|
46135
|
-
return topic !== ownAgentSubject || /[*>]/.test(ownAgentSubject);
|
|
46136
|
-
}
|
|
46137
|
-
function replayFollowedSubjects(ownAgentSubject, topics, heldForRole = () => false) {
|
|
46138
|
-
const followed = [...topics].filter((topic) => !topic.startsWith(ROLE_TOPIC_PREFIX) && !reachesPrivateStreamSubject(ownAgentSubject, topic) && !heldForRole(topic));
|
|
46139
|
-
return [...new Set([ownAgentSubject, ...followed])];
|
|
46140
|
-
}
|
|
46141
|
-
function rememberedTopics(state) {
|
|
46142
|
-
return Object.keys(state?.subjects ?? {}).filter((topic) => !topic.startsWith(AGENT_TOPIC_PREFIX) && !topic.startsWith(ROLE_TOPIC_PREFIX));
|
|
46143
|
-
}
|
|
46144
|
-
async function closeReplayedRemoval(frame, host) {
|
|
46145
|
-
const closed = (subscriptionRemovedTopics(frame.data, host.sessionID) ?? []).filter((topic) => host.engine.followedBefore(topic, frame.seq) && host.close(topic));
|
|
46146
|
-
if (closed.length === 0)
|
|
46147
|
-
return closed;
|
|
46148
|
-
const unregistering = host.unregister(closed);
|
|
46149
|
-
await host.followedChanged();
|
|
46150
|
-
await unregistering;
|
|
46151
|
-
return closed;
|
|
46152
|
-
}
|
|
46153
|
-
function routeReplayNotice(notice, routes) {
|
|
46154
|
-
if (notice.kind === "not_served" || notice.kind === "unavailable") {
|
|
46155
|
-
routes.warn(notice.message);
|
|
46156
|
-
return;
|
|
46157
|
-
}
|
|
46158
|
-
routes.card(envoyNoticeText(replayNoticeFields(notice)));
|
|
46159
|
-
}
|
|
46160
|
-
function isRoleForward(envelope) {
|
|
46161
|
-
return envelope.dedupe_key?.startsWith(ROLE_FORWARD_KEY_PREFIX) === true || envelope.topic?.startsWith(ROLE_TOPIC_PREFIX) === true;
|
|
46162
|
-
}
|
|
46163
|
-
function replayLedgerIdentity(frame) {
|
|
46164
|
-
return {
|
|
46165
|
-
...frame.event_id === undefined || frame.event_id === "" ? {} : { event_id: frame.event_id },
|
|
46166
|
-
...frame.dedupe_key === undefined || !dedupeKeyNamesItsEvent(frame) ? {} : { dedupe_key: frame.dedupe_key }
|
|
45601
|
+
};
|
|
45602
|
+
let raw;
|
|
45603
|
+
try {
|
|
45604
|
+
raw = await post("/v1/roles/set", body, { actingSession: input.sessionID });
|
|
45605
|
+
} catch (error) {
|
|
45606
|
+
if (error instanceof EnvoyApiError && error.details.status === 409) {
|
|
45607
|
+
let answer;
|
|
45608
|
+
try {
|
|
45609
|
+
answer = JSON.parse(error.details.responseBody);
|
|
45610
|
+
} catch {
|
|
45611
|
+
throw error;
|
|
45612
|
+
}
|
|
45613
|
+
const held = RoleHeldWireSchema.safeParse(answer);
|
|
45614
|
+
if (held.success)
|
|
45615
|
+
return { claimed: false, holder: held.data.holder };
|
|
45616
|
+
}
|
|
45617
|
+
throw error;
|
|
45618
|
+
}
|
|
45619
|
+
return { claimed: true, interest: InterestWireSchema.parse(JSON.parse(raw)) };
|
|
45620
|
+
},
|
|
45621
|
+
getRole: async (role) => RoleWireSchema.parse(JSON.parse(await request(`/v1/roles/${encodeURIComponent(role)}`, { method: "GET" }))),
|
|
45622
|
+
listSessions: async (input = {}) => {
|
|
45623
|
+
const search = new URLSearchParams;
|
|
45624
|
+
if (input.directory !== undefined)
|
|
45625
|
+
search.set("dir", input.directory);
|
|
45626
|
+
if (input.title !== undefined)
|
|
45627
|
+
search.set("title", input.title);
|
|
45628
|
+
if (input.include !== undefined)
|
|
45629
|
+
search.set("include", input.include);
|
|
45630
|
+
const query = search.size === 0 ? "" : `?${search.toString()}`;
|
|
45631
|
+
return SessionWireSchema.array().parse(JSON.parse(await request(`/v1/sessions${query}`, {})));
|
|
45632
|
+
}
|
|
46167
45633
|
};
|
|
46168
45634
|
}
|
|
46169
|
-
|
|
46170
|
-
|
|
46171
|
-
|
|
46172
|
-
|
|
46173
|
-
let parsed;
|
|
46174
|
-
try {
|
|
46175
|
-
parsed = JSON.parse(data);
|
|
46176
|
-
} catch {
|
|
46177
|
-
return;
|
|
46178
|
-
}
|
|
46179
|
-
const result = StoredEnvelopeSchema.safeParse(parsed);
|
|
46180
|
-
return result.success ? result.data : undefined;
|
|
45635
|
+
function waitForRetry(delayMs) {
|
|
45636
|
+
const { promise, resolve } = Promise.withResolvers();
|
|
45637
|
+
setTimeout(resolve, delayMs);
|
|
45638
|
+
return promise;
|
|
46181
45639
|
}
|
|
46182
|
-
function
|
|
46183
|
-
let entries = new Set;
|
|
46184
|
-
const byEvent = new Map;
|
|
46185
|
-
const byKey = new Map;
|
|
46186
|
-
const drop = (entry) => {
|
|
46187
|
-
entries.delete(entry);
|
|
46188
|
-
if (entry.event_id !== undefined && byEvent.get(entry.event_id) === entry) {
|
|
46189
|
-
byEvent.delete(entry.event_id);
|
|
46190
|
-
}
|
|
46191
|
-
if (entry.dedupe_key !== undefined && byKey.get(entry.dedupe_key) === entry) {
|
|
46192
|
-
byKey.delete(entry.dedupe_key);
|
|
46193
|
-
}
|
|
46194
|
-
};
|
|
46195
|
-
const add = (entry) => {
|
|
46196
|
-
if (entries.size >= REPLAY_LEDGER_LIMIT) {
|
|
46197
|
-
const oldest = entries.values().next();
|
|
46198
|
-
if (oldest.done !== true)
|
|
46199
|
-
drop(oldest.value);
|
|
46200
|
-
}
|
|
46201
|
-
entries.add(entry);
|
|
46202
|
-
if (entry.event_id !== undefined)
|
|
46203
|
-
byEvent.set(entry.event_id, entry);
|
|
46204
|
-
if (entry.dedupe_key !== undefined)
|
|
46205
|
-
byKey.set(entry.dedupe_key, entry);
|
|
46206
|
-
};
|
|
46207
|
-
const expire = () => {
|
|
46208
|
-
const at = now();
|
|
46209
|
-
for (const entry of entries) {
|
|
46210
|
-
if (at - entry.at < REPLAY_LEDGER_TTL_MS)
|
|
46211
|
-
break;
|
|
46212
|
-
drop(entry);
|
|
46213
|
-
}
|
|
46214
|
-
};
|
|
46215
|
-
const has = (identity) => {
|
|
46216
|
-
expire();
|
|
46217
|
-
return identity.event_id !== undefined && byEvent.has(identity.event_id) || identity.dedupe_key !== undefined && byKey.has(identity.dedupe_key);
|
|
46218
|
-
};
|
|
45640
|
+
function messageMetadata(input) {
|
|
46219
45641
|
return {
|
|
46220
|
-
|
|
46221
|
-
|
|
46222
|
-
|
|
46223
|
-
|
|
46224
|
-
|
|
46225
|
-
return;
|
|
46226
|
-
const entry = { ...identity, at: now() };
|
|
46227
|
-
add(entry);
|
|
46228
|
-
return entry;
|
|
46229
|
-
},
|
|
46230
|
-
restore(restored) {
|
|
46231
|
-
entries = new Set;
|
|
46232
|
-
byEvent.clear();
|
|
46233
|
-
byKey.clear();
|
|
46234
|
-
const at = now();
|
|
46235
|
-
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);
|
|
46236
|
-
for (const entry of kept)
|
|
46237
|
-
add({ ...entry });
|
|
46238
|
-
},
|
|
46239
|
-
list() {
|
|
46240
|
-
expire();
|
|
46241
|
-
return [...entries];
|
|
46242
|
-
}
|
|
45642
|
+
...input.inReplyTo === undefined ? {} : { in_reply_to: input.inReplyTo },
|
|
45643
|
+
...input.supersedes === undefined ? {} : { supersedes: input.supersedes },
|
|
45644
|
+
...input.urgency === undefined ? {} : { urgency: input.urgency },
|
|
45645
|
+
...input.expectsReply === undefined ? {} : { expects_reply: input.expectsReply },
|
|
45646
|
+
...input.expiresAt === undefined ? {} : { expires_at: input.expiresAt }
|
|
46243
45647
|
};
|
|
46244
45648
|
}
|
|
45649
|
+
function sourceSession(sessionID) {
|
|
45650
|
+
return sessionID === undefined || sessionID === "" ? {} : { source_session: sessionID };
|
|
45651
|
+
}
|
|
46245
45652
|
|
|
46246
45653
|
// ../envoy-client/src/consumer-delivery.ts
|
|
46247
45654
|
var DELIVER_SUBJECT_PREFIX = "notifications.envoy.deliver.";
|
|
@@ -46346,6 +45753,7 @@ function every(ms, callback) {
|
|
|
46346
45753
|
}
|
|
46347
45754
|
function createConsumerDelivery(options) {
|
|
46348
45755
|
const { host, ledger, sessionID } = options;
|
|
45756
|
+
const render = options.render ?? renderInbound;
|
|
46349
45757
|
const now = options.now ?? Date.now;
|
|
46350
45758
|
const repeat = options.every ?? every;
|
|
46351
45759
|
const ownSubject = agentSubject(sessionID);
|
|
@@ -46357,9 +45765,9 @@ function createConsumerDelivery(options) {
|
|
|
46357
45765
|
let registeredResume;
|
|
46358
45766
|
let gapTold = false;
|
|
46359
45767
|
let closed = false;
|
|
46360
|
-
let relayed;
|
|
46361
45768
|
let persisted = JSON.stringify({ follows: {} });
|
|
46362
45769
|
const entries = new Map;
|
|
45770
|
+
const troubled = new Map;
|
|
46363
45771
|
const queue = [];
|
|
46364
45772
|
let blocking;
|
|
46365
45773
|
let pumping = false;
|
|
@@ -46381,6 +45789,7 @@ function createConsumerDelivery(options) {
|
|
|
46381
45789
|
streamID = id;
|
|
46382
45790
|
held = new Set;
|
|
46383
45791
|
written = undefined;
|
|
45792
|
+
troubled.clear();
|
|
46384
45793
|
};
|
|
46385
45794
|
const tellReplacedResume = (id) => {
|
|
46386
45795
|
const asked = resumePoint() ?? registeredResume;
|
|
@@ -46401,18 +45810,6 @@ function createConsumerDelivery(options) {
|
|
|
46401
45810
|
}
|
|
46402
45811
|
return earliest;
|
|
46403
45812
|
};
|
|
46404
|
-
const followedOnCorePath = (frame) => {
|
|
46405
|
-
const state = ledger.state();
|
|
46406
|
-
if (state.stream_id !== frame.streamID)
|
|
46407
|
-
return false;
|
|
46408
|
-
for (const [topic, cursor] of Object.entries(state.subjects)) {
|
|
46409
|
-
if (cursor.since === undefined || frame.streamSeq <= cursor.since)
|
|
46410
|
-
continue;
|
|
46411
|
-
if (reaches(topic, frame.subject))
|
|
46412
|
-
return true;
|
|
46413
|
-
}
|
|
46414
|
-
return false;
|
|
46415
|
-
};
|
|
46416
45813
|
const settle = (entry, body) => {
|
|
46417
45814
|
if (entry.settled)
|
|
46418
45815
|
return;
|
|
@@ -46421,6 +45818,8 @@ function createConsumerDelivery(options) {
|
|
|
46421
45818
|
entries.delete(entry.key);
|
|
46422
45819
|
for (const reply of entry.replies)
|
|
46423
45820
|
send(reply, body);
|
|
45821
|
+
if (body === "done")
|
|
45822
|
+
troubled.delete(entry.key);
|
|
46424
45823
|
if (body === "done" && entry.frame.streamID === streamID) {
|
|
46425
45824
|
held.delete(entry.frame.streamSeq);
|
|
46426
45825
|
written = Math.max(written ?? 0, entry.frame.streamSeq);
|
|
@@ -46437,19 +45836,52 @@ function createConsumerDelivery(options) {
|
|
|
46437
45836
|
const failed = (entry, error) => {
|
|
46438
45837
|
if (entry.settled)
|
|
46439
45838
|
return;
|
|
46440
|
-
|
|
45839
|
+
const trouble = troubled.get(entry.key) ?? { failures: 0, givenUp: false };
|
|
45840
|
+
troubled.set(entry.key, trouble);
|
|
45841
|
+
if (trouble.givenUp) {
|
|
45842
|
+
settle(entry, "nak");
|
|
45843
|
+
return;
|
|
45844
|
+
}
|
|
45845
|
+
trouble.failures += 1;
|
|
45846
|
+
if (trouble.failures < RELAY_ATTEMPTS_BEFORE_FAILED) {
|
|
46441
45847
|
log(`frame ${entry.frame.streamSeq} failed; it comes again`, error);
|
|
46442
45848
|
settle(entry, "nak");
|
|
46443
45849
|
return;
|
|
46444
45850
|
}
|
|
46445
45851
|
log(`frame ${entry.frame.streamSeq} failed and does not come again; its session gets the notice`, error);
|
|
46446
|
-
|
|
46447
|
-
|
|
46448
|
-
|
|
46449
|
-
|
|
46450
|
-
|
|
45852
|
+
const goesBack = (why, thrown) => {
|
|
45853
|
+
trouble.givenUp = true;
|
|
45854
|
+
log(`frame ${entry.frame.streamSeq} ${why}; it goes back to the stream`, thrown);
|
|
45855
|
+
settle(entry, "nak");
|
|
45856
|
+
};
|
|
45857
|
+
let envelope;
|
|
45858
|
+
try {
|
|
45859
|
+
envelope = render(entry.frame.data, sessionID, entry.frame.subject).envelope;
|
|
45860
|
+
} catch (thrown) {
|
|
45861
|
+
goesBack("could not be read to report it", thrown);
|
|
45862
|
+
return;
|
|
45863
|
+
}
|
|
45864
|
+
if (envelope === undefined) {
|
|
45865
|
+
log(`frame ${entry.frame.streamSeq} carries no envelope to report; it is dropped`);
|
|
45866
|
+
settle(entry, "done");
|
|
45867
|
+
return;
|
|
45868
|
+
}
|
|
45869
|
+
let telling;
|
|
45870
|
+
try {
|
|
45871
|
+
telling = ledger.liveFailed(sessionID, envelope, error);
|
|
45872
|
+
} catch (thrown) {
|
|
45873
|
+
goesBack("could not be reported", thrown);
|
|
45874
|
+
return;
|
|
45875
|
+
}
|
|
45876
|
+
telling.then((told) => {
|
|
45877
|
+
if (told) {
|
|
45878
|
+
settle(entry, "done");
|
|
45879
|
+
return;
|
|
45880
|
+
}
|
|
45881
|
+
goesBack("was reported to nobody");
|
|
45882
|
+
}, (thrown) => {
|
|
45883
|
+
goesBack("could not be reported", thrown);
|
|
46451
45884
|
});
|
|
46452
|
-
settle(entry, "done");
|
|
46453
45885
|
};
|
|
46454
45886
|
const handOff = (entry) => {
|
|
46455
45887
|
const handle = {
|
|
@@ -46530,7 +45962,7 @@ function createConsumerDelivery(options) {
|
|
|
46530
45962
|
return;
|
|
46531
45963
|
}
|
|
46532
45964
|
const since = followedAt(frame.subject);
|
|
46533
|
-
const unfollowed =
|
|
45965
|
+
const unfollowed = since === undefined || frame.storedAtMs < since - FOLLOW_CLOCK_ALLOWANCE_MS;
|
|
46534
45966
|
const identity = unfollowed ? undefined : parseIdentity(frame.data);
|
|
46535
45967
|
if (unfollowed || alreadyWritten(identity)) {
|
|
46536
45968
|
send(frame.reply, "done");
|
|
@@ -46566,20 +45998,6 @@ function createConsumerDelivery(options) {
|
|
|
46566
45998
|
return { stream_id: streamID, seq: Math.min(...held) - 1 };
|
|
46567
45999
|
return written === undefined ? undefined : { stream_id: streamID, seq: written };
|
|
46568
46000
|
};
|
|
46569
|
-
const seededResume = () => {
|
|
46570
|
-
const state = ledger.state();
|
|
46571
|
-
const stream = state.stream_id;
|
|
46572
|
-
if (stream === undefined)
|
|
46573
|
-
return;
|
|
46574
|
-
let lowest;
|
|
46575
|
-
for (const [subject, cursor] of Object.entries(state.subjects)) {
|
|
46576
|
-
if (cursor.after === undefined || !streamStores(subject))
|
|
46577
|
-
continue;
|
|
46578
|
-
if (lowest === undefined || cursor.after < lowest)
|
|
46579
|
-
lowest = cursor.after;
|
|
46580
|
-
}
|
|
46581
|
-
return lowest === undefined ? undefined : { stream_id: stream, seq: lowest };
|
|
46582
|
-
};
|
|
46583
46001
|
const snapshot = () => {
|
|
46584
46002
|
const resume = resumePoint();
|
|
46585
46003
|
return {
|
|
@@ -46605,7 +46023,7 @@ function createConsumerDelivery(options) {
|
|
|
46605
46023
|
return currentEpoch;
|
|
46606
46024
|
},
|
|
46607
46025
|
registration() {
|
|
46608
|
-
const resume = resumePoint()
|
|
46026
|
+
const resume = resumePoint();
|
|
46609
46027
|
registeredResume = resume;
|
|
46610
46028
|
return {
|
|
46611
46029
|
consumer: true,
|
|
@@ -46613,29 +46031,24 @@ function createConsumerDelivery(options) {
|
|
|
46613
46031
|
...resume === undefined ? {} : { resume }
|
|
46614
46032
|
};
|
|
46615
46033
|
},
|
|
46616
|
-
answered(answer
|
|
46617
|
-
if (answer.
|
|
46618
|
-
|
|
46619
|
-
|
|
46620
|
-
|
|
46621
|
-
|
|
46622
|
-
|
|
46623
|
-
|
|
46624
|
-
|
|
46625
|
-
|
|
46626
|
-
|
|
46627
|
-
gapTold = true;
|
|
46628
|
-
}
|
|
46629
|
-
relayed = new Set([...topics].filter(streamStores));
|
|
46630
|
-
} else {
|
|
46631
|
-
relayed = undefined;
|
|
46034
|
+
answered(answer) {
|
|
46035
|
+
if (answer.stream_id !== "" && answer.stream_id !== streamID) {
|
|
46036
|
+
tellReplacedResume(answer.stream_id);
|
|
46037
|
+
switchStream(answer.stream_id);
|
|
46038
|
+
}
|
|
46039
|
+
const floor = (answer.consumer_start ?? 0) - 1;
|
|
46040
|
+
if (answer.stream_id === streamID && floor > (written ?? -1))
|
|
46041
|
+
written = floor;
|
|
46042
|
+
if (answer.gap) {
|
|
46043
|
+
tellGap("retention_gap");
|
|
46044
|
+
gapTold = true;
|
|
46632
46045
|
}
|
|
46633
|
-
ledger.setConsumerMode(relayed !== undefined);
|
|
46634
46046
|
persist();
|
|
46635
|
-
return answer.mode;
|
|
46636
46047
|
},
|
|
46637
|
-
|
|
46638
|
-
|
|
46048
|
+
followedBefore(topic, storedAtMs) {
|
|
46049
|
+
const at = follows.get(topic);
|
|
46050
|
+
return at !== undefined && storedAtMs >= at - FOLLOW_CLOCK_ALLOWANCE_MS;
|
|
46051
|
+
},
|
|
46639
46052
|
setFollowed(topics) {
|
|
46640
46053
|
const at = now();
|
|
46641
46054
|
const next = new Map;
|
|
@@ -46663,8 +46076,6 @@ function createConsumerDelivery(options) {
|
|
|
46663
46076
|
},
|
|
46664
46077
|
close() {
|
|
46665
46078
|
closed = true;
|
|
46666
|
-
relayed = undefined;
|
|
46667
|
-
ledger.setConsumerMode(false);
|
|
46668
46079
|
queue.length = 0;
|
|
46669
46080
|
for (const entry of [...entries.values()])
|
|
46670
46081
|
settle(entry, "nak");
|
|
@@ -46672,6 +46083,62 @@ function createConsumerDelivery(options) {
|
|
|
46672
46083
|
}
|
|
46673
46084
|
};
|
|
46674
46085
|
}
|
|
46086
|
+
var GAP_NOTICE_NAMES = {
|
|
46087
|
+
retention_gap: "messages may be missing",
|
|
46088
|
+
stream_recreated: "stream recreated"
|
|
46089
|
+
};
|
|
46090
|
+
function gapNoticeFields(notice) {
|
|
46091
|
+
return { notice: GAP_NOTICE_NAMES[notice.kind], detail: notice.message };
|
|
46092
|
+
}
|
|
46093
|
+
function gapNoticeText(notice) {
|
|
46094
|
+
return envoyNoticeText(gapNoticeFields(notice));
|
|
46095
|
+
}
|
|
46096
|
+
function inboundUnavailableNoticeText(why) {
|
|
46097
|
+
return envoyNoticeText({
|
|
46098
|
+
notice: "Envoy inbound unavailable",
|
|
46099
|
+
error: why,
|
|
46100
|
+
detail: "The listener gave this session no durable consumer, which is the only path an Envoy message reaches it by, so it receives none. Everything else works, and the session registers again at every heartbeat; what the stream stored meanwhile arrives once a registration is accepted."
|
|
46101
|
+
});
|
|
46102
|
+
}
|
|
46103
|
+
function inboundUnavailable(tell) {
|
|
46104
|
+
let told = false;
|
|
46105
|
+
return {
|
|
46106
|
+
refused(error) {
|
|
46107
|
+
if (told)
|
|
46108
|
+
return;
|
|
46109
|
+
told = true;
|
|
46110
|
+
tell(messageFor(error));
|
|
46111
|
+
},
|
|
46112
|
+
accepted() {
|
|
46113
|
+
told = false;
|
|
46114
|
+
}
|
|
46115
|
+
};
|
|
46116
|
+
}
|
|
46117
|
+
function registerWithRelay({
|
|
46118
|
+
relay,
|
|
46119
|
+
ownAgentSubject,
|
|
46120
|
+
followed,
|
|
46121
|
+
roles,
|
|
46122
|
+
outage,
|
|
46123
|
+
send,
|
|
46124
|
+
answered
|
|
46125
|
+
}) {
|
|
46126
|
+
if (relay === undefined) {
|
|
46127
|
+
const refused = new Error("this session holds no relay subject, so the listener can give it no consumer and it can receive nothing");
|
|
46128
|
+
outage.refused(refused);
|
|
46129
|
+
return Promise.reject(refused);
|
|
46130
|
+
}
|
|
46131
|
+
const topics = registrationTopics(ownAgentSubject, followed, roles);
|
|
46132
|
+
relay.setFollowed(topics);
|
|
46133
|
+
return send(topics, relay.registration()).then((result) => {
|
|
46134
|
+
outage.accepted();
|
|
46135
|
+
answered(result);
|
|
46136
|
+
return result;
|
|
46137
|
+
}, (error) => {
|
|
46138
|
+
outage.refused(error);
|
|
46139
|
+
throw error;
|
|
46140
|
+
});
|
|
46141
|
+
}
|
|
46675
46142
|
|
|
46676
46143
|
// ../envoy-client/src/envoy-config.ts
|
|
46677
46144
|
import {
|
|
@@ -50778,13 +50245,17 @@ function withoutFinalLineFeed(text) {
|
|
|
50778
50245
|
return text.endsWith(`
|
|
50779
50246
|
`) ? text.slice(0, -1) : text;
|
|
50780
50247
|
}
|
|
50248
|
+
var goBlankPattern = /^[\t\n\v\f\r \u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]*$/u;
|
|
50781
50249
|
async function artifactCommand(context) {
|
|
50782
50250
|
const { args, client, actor, input, documentOwner, issue } = context;
|
|
50783
50251
|
const summary = optionalString(args, "summary");
|
|
50784
50252
|
const name = stringArg(args, "name");
|
|
50785
50253
|
const content = optionalString(args, "content");
|
|
50254
|
+
const path = optionalString(args, "path");
|
|
50255
|
+
const options = { name, ...summary === undefined ? {} : { summary }, actor };
|
|
50786
50256
|
const artifactOwner = documentOwner();
|
|
50787
|
-
|
|
50257
|
+
const blank = content === undefined || goBlankPattern.test(content);
|
|
50258
|
+
if ((path !== undefined || !blank) && optionalBoolean(args, "force") !== true) {
|
|
50788
50259
|
const held = artifactUnderName(artifactOwner.kind === "project" ? await client.listProjectArtifacts(artifactOwner.project, true) : await client.listIssueArtifacts(issue()), name);
|
|
50789
50260
|
if (held !== undefined) {
|
|
50790
50261
|
throw new ToolInputError(input.tool, [
|
|
@@ -50792,7 +50263,7 @@ async function artifactCommand(context) {
|
|
|
50792
50263
|
]);
|
|
50793
50264
|
}
|
|
50794
50265
|
}
|
|
50795
|
-
if (
|
|
50266
|
+
if (!blank) {
|
|
50796
50267
|
let stored;
|
|
50797
50268
|
try {
|
|
50798
50269
|
stored = await client.markdownRoundTrip(content);
|
|
@@ -50805,19 +50276,12 @@ async function artifactCommand(context) {
|
|
|
50805
50276
|
throw new ToolInputError(input.tool, [storedTextProblem(content, stored, name)]);
|
|
50806
50277
|
}
|
|
50807
50278
|
}
|
|
50808
|
-
const artifactInput =
|
|
50809
|
-
|
|
50810
|
-
file: input.uploadBytes === undefined ? Bun.file(resolvePath2(input.cwd,
|
|
50811
|
-
type: Bun.file(resolvePath2(input.cwd,
|
|
50812
|
-
})
|
|
50813
|
-
|
|
50814
|
-
actor
|
|
50815
|
-
} : {
|
|
50816
|
-
name,
|
|
50817
|
-
content,
|
|
50818
|
-
...summary === undefined ? {} : { summary },
|
|
50819
|
-
actor
|
|
50820
|
-
};
|
|
50279
|
+
const artifactInput = path !== undefined ? {
|
|
50280
|
+
...options,
|
|
50281
|
+
file: input.uploadBytes === undefined ? Bun.file(resolvePath2(input.cwd, path)) : new Blob([new Uint8Array(input.uploadBytes)], {
|
|
50282
|
+
type: Bun.file(resolvePath2(input.cwd, path)).type
|
|
50283
|
+
})
|
|
50284
|
+
} : content !== undefined ? { ...options, content } : options;
|
|
50821
50285
|
const result = artifactOwner.kind === "project" ? await client.projectArtifact(artifactOwner.project, artifactInput) : await client.artifact(issue(), artifactInput);
|
|
50822
50286
|
const artifactRef = dispatchDocumentRef(artifactOwner.kind === "project" ? artifactOwner.project : issue(), result.artifact.slug);
|
|
50823
50287
|
const uploadOwner = artifactOwner.kind === "project" ? documentTopic(result.artifact) : issueTopic(issue());
|
|
@@ -50826,7 +50290,7 @@ async function artifactCommand(context) {
|
|
|
50826
50290
|
});
|
|
50827
50291
|
return {
|
|
50828
50292
|
text: [
|
|
50829
|
-
`Uploaded ${result.artifact.name} as version ${result.version.number} (artifact slug ${result.artifact.slug}; ${artifactRef})${await notSubscribed(uploadOwner, input.subscriptions)}`,
|
|
50293
|
+
path === undefined && content === undefined ? `Made ${result.artifact.name} as an empty document (artifact slug ${result.artifact.slug}; ${artifactRef}). Write in it with dispatch doc-edit.${await notSubscribed(uploadOwner, input.subscriptions)}` : `Uploaded ${result.artifact.name} as version ${result.version.number} (artifact slug ${result.artifact.slug}; ${artifactRef})${await notSubscribed(uploadOwner, input.subscriptions)}`,
|
|
50830
50294
|
...adviceLines
|
|
50831
50295
|
].join(`
|
|
50832
50296
|
`),
|
|
@@ -53199,7 +52663,7 @@ function allowedAPIURL(value) {
|
|
|
53199
52663
|
// ../envoy-client/src/tool-contract.ts
|
|
53200
52664
|
var SESSION_STATE_GUIDE = "A session is live, unresponsive or gone, by how long ago it last registered: live within 5 " + "minutes, unresponsive after that and within an hour, gone past the hour or with no record at " + `all. ${UNRESPONSIVE_RULE} A session named with no state is live.`;
|
|
53201
52665
|
var DELIVERY_CONTRACT = "Delivery is at-least-once, possibly out of order across topics; use id for dedupe and at for freshness.";
|
|
53202
|
-
var STORED_DELIVERY = "
|
|
52666
|
+
var STORED_DELIVERY = "Every notification topic is stored (agent, dispatch, github, slack, legion, ghostwispr, " + "whatsapp, team; a role message reaches its holder as a stored copy on the holder's agent " + "topic), and reaches each subscribed session once from the durable consumer its listener " + "relays to it, also one that was away or restarted. A 200 means the stream stored the message " + "for each subscribed session's consumer, not that any recipient has read it.";
|
|
53203
52667
|
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>.";
|
|
53204
52668
|
var URGENCY_VALUES = EnvelopeSchema.shape.urgency.unwrap().options;
|
|
53205
52669
|
function messageMetadataShape(schema) {
|
|
@@ -53240,7 +52704,7 @@ var EnvoyToolOperation = {
|
|
|
53240
52704
|
var envoyToolSpecs = [
|
|
53241
52705
|
{
|
|
53242
52706
|
name: "envoy_subscribe",
|
|
53243
|
-
description: `Subscribe this session to Envoy notification topics. ${STORED_DELIVERY} ${TOPIC_GUIDE}`,
|
|
52707
|
+
description: `Subscribe this session to Envoy notification topics. A notifications. topic no stream subject captures is refused by name: nothing would store it, so you would receive nothing on it; subscribe to a notifications.team.<name> topic instead. ${STORED_DELIVERY} ${TOPIC_GUIDE}`,
|
|
53244
52708
|
arguments: (schema) => ({
|
|
53245
52709
|
topics: schema.array(schema.string()).describe("NATS-style topic patterns to subscribe to.")
|
|
53246
52710
|
}),
|
|
@@ -53276,7 +52740,7 @@ var envoyToolSpecs = [
|
|
|
53276
52740
|
},
|
|
53277
52741
|
{
|
|
53278
52742
|
name: "envoy_publish",
|
|
53279
|
-
description: `Publish an Envoy message to a notifications. topic. ${STORED_DELIVERY} A role or built-in topic is delivered as its guide says. A role message has three possible answers. First,
|
|
52743
|
+
description: `Publish an Envoy message to a notifications. topic. ${STORED_DELIVERY} A role or built-in topic is delivered as its guide says. A role message has three possible answers. First, a session holds the role, and the stream stores the forward for that holder's consumer. Its 200 says the stream stored it, and it does not say that the holder read it; it names the holder and the state the listener resolved the holder in. Second, no session holds the role. The listener then keeps the message, and gives it to the next session that claims that role in the hour that follows. This is a success, and the result says that the listener kept the message. Third, the listener keeps nothing and errs, which tells you to reach the agent some other way: the holder refuses the message, or the forward is not stored within four seconds. A holder that stopped answering keeps its role but was not sent the message, and nothing waits for it, so publish the message again once that holder's holder_state reads live, and start no replacement for that session. A team topic (such as notifications.team.deploy-squad.all) is stored like every other, so a session subscribed to it that was away still receives it when it returns, and one that subscribes after you publish does not. A notifications. topic no stream subject captures is refused by name: nothing would store it. ${SESSION_STATE_GUIDE} ${DELIVERY_CONTRACT}`,
|
|
53280
52744
|
arguments: (schema) => ({ topic: schema.string(), ...messageArguments(schema) }),
|
|
53281
52745
|
operation: EnvoyToolOperation.publish
|
|
53282
52746
|
},
|
|
@@ -53335,10 +52799,6 @@ function publishConfirmationText(result) {
|
|
|
53335
52799
|
const state = result.holderState === undefined ? "" : ` (${result.holderState})`;
|
|
53336
52800
|
sentences.push(`Its role holder is ${result.holder}${state}.`);
|
|
53337
52801
|
}
|
|
53338
|
-
if (result.unresponsive.length > 0) {
|
|
53339
|
-
const one = result.unresponsive.length === 1;
|
|
53340
|
-
sentences.push(`Envoy stored it for ${result.unresponsive.join(", ")}.`, `${one ? "That session" : "Those sessions"} stopped answering, so ${one ? "it has" : "they have"} not taken it yet.`, UNRESPONSIVE_RULE);
|
|
53341
|
-
}
|
|
53342
52802
|
return sentences.join(" ");
|
|
53343
52803
|
}
|
|
53344
52804
|
function sessionsOnMachine(sessions, machine) {
|
|
@@ -56699,7 +56159,7 @@ var import_nats2 = __toESM(require_mod4(), 1);
|
|
|
56699
56159
|
|
|
56700
56160
|
// package.json
|
|
56701
56161
|
var name = "@sjawhar/claude-envoy";
|
|
56702
|
-
var version2 = "2.
|
|
56162
|
+
var version2 = "2.9.0";
|
|
56703
56163
|
var legion = {
|
|
56704
56164
|
daemonApiVersion: 86
|
|
56705
56165
|
};
|
|
@@ -57569,7 +57029,7 @@ function startAgentStream(options) {
|
|
|
57569
57029
|
};
|
|
57570
57030
|
}
|
|
57571
57031
|
|
|
57572
|
-
// src/channel-
|
|
57032
|
+
// src/channel-topics.ts
|
|
57573
57033
|
var DeliveryIdentity = DedupeIdentitySchema.extend({
|
|
57574
57034
|
event_id: DedupeIdentitySchema.shape.event_id.catch(undefined),
|
|
57575
57035
|
dedupe_key: DedupeIdentitySchema.shape.dedupe_key.catch(undefined),
|
|
@@ -57577,7 +57037,6 @@ var DeliveryIdentity = DedupeIdentitySchema.extend({
|
|
|
57577
57037
|
source_event_id: DedupeIdentitySchema.shape.source_event_id.catch(undefined),
|
|
57578
57038
|
topic: string2().min(1).optional().catch(undefined)
|
|
57579
57039
|
});
|
|
57580
|
-
var decoder6 = new TextDecoder;
|
|
57581
57040
|
var DEFAULT_DRAIN_TIMEOUT_MS = 1000;
|
|
57582
57041
|
function deliveryIdentity(raw) {
|
|
57583
57042
|
let parsed;
|
|
@@ -57593,86 +57052,30 @@ function report(what, error) {
|
|
|
57593
57052
|
process.stderr.write(`envoy-channel: ${what} \u2014 ${messageFor(error)}
|
|
57594
57053
|
`);
|
|
57595
57054
|
}
|
|
57596
|
-
function
|
|
57597
|
-
const following = new
|
|
57598
|
-
const dedupe = options.dedupe ?? createDeliveryDedupe();
|
|
57055
|
+
function createChannelTopics(connection, options = {}) {
|
|
57056
|
+
const following = new Set;
|
|
57599
57057
|
const drainTimeoutMs = options.drainTimeoutMs ?? DEFAULT_DRAIN_TIMEOUT_MS;
|
|
57600
|
-
const deliver = async (topic, subscription) => {
|
|
57601
|
-
try {
|
|
57602
|
-
for await (const { message, receivedAt } of readArrivals(subscription)) {
|
|
57603
|
-
const raw = decoder6.decode(message.data);
|
|
57604
|
-
const identity = deliveryIdentity(raw);
|
|
57605
|
-
let claim = options.relayed?.(topic) === true ? undefined : dedupe.claim(identity);
|
|
57606
|
-
if (claim !== undefined && identity !== undefined && options.ledger?.delivered(identity)) {
|
|
57607
|
-
claim.settle();
|
|
57608
|
-
claim = undefined;
|
|
57609
|
-
}
|
|
57610
|
-
const inbound = {
|
|
57611
|
-
subject: message.subject,
|
|
57612
|
-
data: message.data,
|
|
57613
|
-
raw,
|
|
57614
|
-
...message.reply ? { reply: message.reply } : {},
|
|
57615
|
-
...identity?.topic === undefined ? {} : { envelopeTopic: identity.topic },
|
|
57616
|
-
...claim === undefined ? { duplicate: true } : {}
|
|
57617
|
-
};
|
|
57618
|
-
let handed;
|
|
57619
|
-
try {
|
|
57620
|
-
handed = await options.deliver(inbound);
|
|
57621
|
-
} catch (error) {
|
|
57622
|
-
claim?.release();
|
|
57623
|
-
report(`could not deliver a message on ${message.subject}`, error);
|
|
57624
|
-
if (claim !== undefined)
|
|
57625
|
-
options.failed?.(inbound, topic, error, receivedAt);
|
|
57626
|
-
continue;
|
|
57627
|
-
}
|
|
57628
|
-
if (claim === undefined)
|
|
57629
|
-
continue;
|
|
57630
|
-
if (!handed) {
|
|
57631
|
-
claim.release();
|
|
57632
|
-
continue;
|
|
57633
|
-
}
|
|
57634
|
-
const taken = claim;
|
|
57635
|
-
const settle = () => taken.settle();
|
|
57636
|
-
if (identity === undefined || options.ledger === undefined)
|
|
57637
|
-
settle();
|
|
57638
|
-
else
|
|
57639
|
-
options.ledger.recordDelivered(identity).then(settle, settle);
|
|
57640
|
-
}
|
|
57641
|
-
} catch (error) {
|
|
57642
|
-
report(`delivery from ${topic} stopped`, error);
|
|
57643
|
-
}
|
|
57644
|
-
};
|
|
57645
|
-
const stop = async (topics) => {
|
|
57646
|
-
const stopping = topics.flatMap((topic) => {
|
|
57647
|
-
const entry = following.get(topic);
|
|
57648
|
-
if (entry === undefined)
|
|
57649
|
-
return [];
|
|
57650
|
-
following.delete(topic);
|
|
57651
|
-
entry.subscription.unsubscribe();
|
|
57652
|
-
return [entry.done];
|
|
57653
|
-
});
|
|
57654
|
-
await Promise.all(stopping);
|
|
57655
|
-
};
|
|
57656
57058
|
return {
|
|
57657
57059
|
follow(topic) {
|
|
57658
|
-
for (const subject of expandSubscriptionTopics([topic]))
|
|
57659
|
-
|
|
57660
|
-
continue;
|
|
57661
|
-
const subscription = connection.subscribe(subject);
|
|
57662
|
-
following.set(subject, { subscription, done: deliver(subject, subscription) });
|
|
57663
|
-
}
|
|
57060
|
+
for (const subject of expandSubscriptionTopics([topic]))
|
|
57061
|
+
following.add(subject);
|
|
57664
57062
|
},
|
|
57665
57063
|
unfollow(topics) {
|
|
57666
|
-
|
|
57064
|
+
if (topics.length === 0) {
|
|
57065
|
+
following.clear();
|
|
57066
|
+
return;
|
|
57067
|
+
}
|
|
57068
|
+
for (const subject of expandSubscriptionTopics(topics))
|
|
57069
|
+
following.delete(subject);
|
|
57667
57070
|
},
|
|
57668
57071
|
topics() {
|
|
57669
|
-
return [...following
|
|
57072
|
+
return [...following];
|
|
57670
57073
|
},
|
|
57671
57074
|
isClosed() {
|
|
57672
57075
|
return connection.isClosed();
|
|
57673
57076
|
},
|
|
57674
57077
|
async close() {
|
|
57675
|
-
|
|
57078
|
+
following.clear();
|
|
57676
57079
|
if (connection.isClosed())
|
|
57677
57080
|
return;
|
|
57678
57081
|
const timeout = Promise.withResolvers();
|
|
@@ -59930,14 +59333,14 @@ async function readStateFile(file, schema, empty, refusal) {
|
|
|
59930
59333
|
}
|
|
59931
59334
|
|
|
59932
59335
|
// src/replay-state.ts
|
|
59933
|
-
var ReplayStateFileSchema =
|
|
59336
|
+
var ReplayStateFileSchema = LedgerSnapshotSchema.extend({
|
|
59934
59337
|
consumer: ConsumerDeliverySnapshotSchema.optional()
|
|
59935
59338
|
});
|
|
59936
59339
|
function replayStateFile(stateDirectory, sessionId) {
|
|
59937
59340
|
return join10(stateDirectory, `replay-${encodeURIComponent(sessionId)}.json`);
|
|
59938
59341
|
}
|
|
59939
59342
|
async function readReplayState(file) {
|
|
59940
|
-
return await readStateFile(file, ReplayStateFileSchema, { ledger: [] }, "holds no
|
|
59343
|
+
return await readStateFile(file, ReplayStateFileSchema, { ledger: [] }, "holds no delivery state");
|
|
59941
59344
|
}
|
|
59942
59345
|
async function writeReplayState(file, state) {
|
|
59943
59346
|
await writeAtomicStateFile(file, `${JSON.stringify(state)}
|
|
@@ -59955,7 +59358,7 @@ function replayStateWriter(file, restored) {
|
|
|
59955
59358
|
return run;
|
|
59956
59359
|
};
|
|
59957
59360
|
return {
|
|
59958
|
-
|
|
59361
|
+
ledger: (snapshot) => write(current.consumer === undefined ? snapshot : { ...snapshot, consumer: current.consumer }),
|
|
59959
59362
|
consumer: (snapshot) => write({ ...current, consumer: snapshot }),
|
|
59960
59363
|
idle: () => writing
|
|
59961
59364
|
};
|
|
@@ -60483,7 +59886,6 @@ async function pruneStaleSessionTurns(stateDirectory) {
|
|
|
60483
59886
|
// src/envoy-channel-server.ts
|
|
60484
59887
|
var CHANNEL_INSTRUCTIONS = "Envoy delivers trusted, internal session and Dispatch events into this conversation. Use the Envoy tools for Envoy actions, and reach Dispatch through the `dispatch` command in Bash (`dispatch --help` lists its commands; the `dispatch` skill teaches them). Dispatch asks stay on Dispatch.";
|
|
60485
59888
|
var CHANNEL_INBOX_LIMIT = 50;
|
|
60486
|
-
var EMPTY_RECEIPT = new Uint8Array;
|
|
60487
59889
|
var encoder6 = new TextEncoder;
|
|
60488
59890
|
var HANDOFF_POLL_MS = 250;
|
|
60489
59891
|
var HANDOFF_FLUSH_TIMEOUT_MS = 1e4;
|
|
@@ -60565,7 +59967,6 @@ function createChannelDelivery(input) {
|
|
|
60565
59967
|
});
|
|
60566
59968
|
return run;
|
|
60567
59969
|
};
|
|
60568
|
-
const write = (notification) => queued(() => input.notifier.notification(notification));
|
|
60569
59970
|
const list = (rendered) => {
|
|
60570
59971
|
const envelope = rendered.envelope;
|
|
60571
59972
|
if (envelope === undefined)
|
|
@@ -60586,14 +59987,10 @@ function createChannelDelivery(input) {
|
|
|
60586
59987
|
content,
|
|
60587
59988
|
...rendered.envelope?.event_id === undefined ? {} : { eventId: rendered.envelope.event_id }
|
|
60588
59989
|
});
|
|
60589
|
-
const
|
|
60590
|
-
list(rendered);
|
|
60591
|
-
return write(notification(rendered, content));
|
|
60592
|
-
};
|
|
60593
|
-
const passOverBtw = (rendered, how) => {
|
|
59990
|
+
const passOverLateBtw = (rendered) => {
|
|
60594
59991
|
if (rendered.delivery?.mode !== "btw")
|
|
60595
59992
|
return false;
|
|
60596
|
-
process.stderr.write(`envoy-channel: passing over
|
|
59993
|
+
process.stderr.write(`envoy-channel: passing over late BTW ${rendered.envelope?.event_id ?? "unknown"}: it was asked while this session was not taking messages
|
|
60597
59994
|
`);
|
|
60598
59995
|
return true;
|
|
60599
59996
|
};
|
|
@@ -60619,7 +60016,7 @@ function createChannelDelivery(input) {
|
|
|
60619
60016
|
`);
|
|
60620
60017
|
return tail.then(() => false);
|
|
60621
60018
|
}
|
|
60622
|
-
if (late === true &&
|
|
60019
|
+
if (late === true && passOverLateBtw(rendered))
|
|
60623
60020
|
return tail.then(() => false);
|
|
60624
60021
|
return queued(async () => {
|
|
60625
60022
|
const routed = await input.router?.()?.route(rendered);
|
|
@@ -60632,35 +60029,19 @@ function createChannelDelivery(input) {
|
|
|
60632
60029
|
return true;
|
|
60633
60030
|
});
|
|
60634
60031
|
},
|
|
60635
|
-
|
|
60636
|
-
|
|
60637
|
-
|
|
60638
|
-
|
|
60639
|
-
|
|
60640
|
-
|
|
60641
|
-
|
|
60642
|
-
return "shown";
|
|
60643
|
-
},
|
|
60644
|
-
notice(content) {
|
|
60645
|
-
return write({ content });
|
|
60032
|
+
notice(content, addressed) {
|
|
60033
|
+
return queued(async () => {
|
|
60034
|
+
if (addressed !== undefined && addressed !== input.identity.id) {
|
|
60035
|
+
throw new Error(`the notice names session ${addressed}, and this process serves ${input.identity.id}`);
|
|
60036
|
+
}
|
|
60037
|
+
await input.notifier.notification({ content });
|
|
60038
|
+
});
|
|
60646
60039
|
},
|
|
60647
60040
|
inbox() {
|
|
60648
60041
|
return [...inbox];
|
|
60649
60042
|
}
|
|
60650
60043
|
};
|
|
60651
60044
|
}
|
|
60652
|
-
async function enqueueChannelMessage(delivery, connection, directSubject, message) {
|
|
60653
|
-
const queued = message.duplicate ? Promise.resolve(false) : delivery.enqueue({ subject: message.subject, raw: message.raw });
|
|
60654
|
-
const lane = {
|
|
60655
|
-
subject: message.subject,
|
|
60656
|
-
directSubject,
|
|
60657
|
-
envelopeTopic: message.envelopeTopic,
|
|
60658
|
-
reply: message.reply
|
|
60659
|
-
};
|
|
60660
|
-
if (expectsLaneReceipt(lane))
|
|
60661
|
-
connection.publish(lane.reply, EMPTY_RECEIPT);
|
|
60662
|
-
return queued;
|
|
60663
|
-
}
|
|
60664
60045
|
async function startChannelSession(options) {
|
|
60665
60046
|
const { identity } = options;
|
|
60666
60047
|
let directSubject = agentSubject(identity.id);
|
|
@@ -60707,78 +60088,43 @@ async function startChannelSession(options) {
|
|
|
60707
60088
|
});
|
|
60708
60089
|
};
|
|
60709
60090
|
const dedupe = createDeliveryDedupe();
|
|
60710
|
-
let
|
|
60711
|
-
const
|
|
60712
|
-
|
|
60713
|
-
|
|
60714
|
-
if (claim === undefined && identityOf !== undefined && dedupe.pending(identityOf)) {
|
|
60715
|
-
return "queued";
|
|
60716
|
-
}
|
|
60717
|
-
try {
|
|
60718
|
-
await closeReplayedRemoval(frame, {
|
|
60719
|
-
sessionID: identity.id,
|
|
60720
|
-
engine: replay,
|
|
60721
|
-
close: (topic) => userTopics.delete(topic),
|
|
60722
|
-
unregister: unfollowRemovedTopics,
|
|
60723
|
-
followedChanged: () => replay.followedChanged()
|
|
60724
|
-
});
|
|
60725
|
-
const outcome = await delivery.replay(frame);
|
|
60726
|
-
if (outcome === "shown")
|
|
60727
|
-
claim?.settle();
|
|
60728
|
-
else
|
|
60729
|
-
claim?.release();
|
|
60730
|
-
return outcome;
|
|
60731
|
-
} catch (error) {
|
|
60732
|
-
claim?.release();
|
|
60733
|
-
throw error;
|
|
60734
|
-
}
|
|
60735
|
-
};
|
|
60736
|
-
const tellNotice = (notice) => {
|
|
60737
|
-
routeReplayNotice(notice, {
|
|
60738
|
-
warn: (message) => process.stderr.write(`envoy-channel: ${message}
|
|
60739
|
-
`),
|
|
60740
|
-
card: (content) => {
|
|
60741
|
-
delivery.notice(content).catch((error) => {
|
|
60742
|
-
process.stderr.write(`envoy-channel: ${notice.message} (the session could not be told \u2014 ${messageFor(error)})
|
|
60091
|
+
let ledgerBound;
|
|
60092
|
+
const tellGapNotice = (notice) => {
|
|
60093
|
+
delivery.notice(gapNoticeText(notice)).catch((error) => {
|
|
60094
|
+
process.stderr.write(`envoy-channel: ${notice.message} (the session could not be told \u2014 ${messageFor(error)})
|
|
60743
60095
|
`);
|
|
60744
|
-
});
|
|
60745
|
-
}
|
|
60746
60096
|
});
|
|
60747
60097
|
};
|
|
60748
60098
|
let stateWriter;
|
|
60749
|
-
const
|
|
60099
|
+
const ledger = createDeliveryLedger({
|
|
60750
60100
|
host: {
|
|
60751
|
-
sessionID: () => shuttingDown ||
|
|
60101
|
+
sessionID: () => shuttingDown || ledgerBound !== identity.id ? undefined : identity.id,
|
|
60752
60102
|
followedSubjects: () => replayFollowedSubjects(directSubject, userTopics),
|
|
60753
|
-
|
|
60754
|
-
showFailureNotice: (notice) => delivery.notice(envoyNoticeText(failureNoticeFields(notice))),
|
|
60103
|
+
showFailureNotice: (addressed, notice) => delivery.notice(envoyNoticeText(failureNoticeFields(notice)), addressed),
|
|
60755
60104
|
failureNoticeFailed: (notice, error) => {
|
|
60756
60105
|
process.stderr.write(`envoy-channel: message ${notice.eventId} from ${notice.sender} was not shown, nor was the notice naming it \u2014 ${messageFor(error)}
|
|
60757
60106
|
`);
|
|
60758
60107
|
},
|
|
60759
|
-
notify: tellNotice,
|
|
60760
60108
|
log: (message, error) => {
|
|
60761
60109
|
process.stderr.write(`envoy-channel: ${message}${error === undefined ? "" : ` \u2014 ${messageFor(error)}`}
|
|
60762
60110
|
`);
|
|
60763
60111
|
},
|
|
60764
|
-
write: (change) => stateWriter?.
|
|
60765
|
-
}
|
|
60766
|
-
transport: options.client,
|
|
60767
|
-
dedupe
|
|
60112
|
+
write: (change) => stateWriter?.ledger(change.snapshot())
|
|
60113
|
+
}
|
|
60768
60114
|
});
|
|
60769
|
-
const
|
|
60115
|
+
const restoreDelivery = async () => {
|
|
60770
60116
|
const sessionId = identity.id;
|
|
60771
60117
|
const file = replayStateFile(options.stateDirectory, sessionId);
|
|
60772
60118
|
const snapshot = await readReplayState(file).catch((error) => {
|
|
60773
|
-
process.stderr.write(`envoy-channel: could not read the
|
|
60119
|
+
process.stderr.write(`envoy-channel: could not read the delivery state (${messageFor(error)}); this session's record starts over
|
|
60774
60120
|
`);
|
|
60775
60121
|
return { ledger: [] };
|
|
60776
60122
|
});
|
|
60777
|
-
|
|
60123
|
+
ledger.restore(snapshot);
|
|
60778
60124
|
stateWriter = replayStateWriter(file, snapshot);
|
|
60779
60125
|
openRelay(sessionId, stateWriter, snapshot.consumer);
|
|
60780
|
-
|
|
60781
|
-
return rememberedTopics(snapshot.state);
|
|
60126
|
+
ledgerBound = sessionId;
|
|
60127
|
+
return rememberedTopics(snapshot.state?.topics);
|
|
60782
60128
|
};
|
|
60783
60129
|
const restoreTurns = async () => {
|
|
60784
60130
|
router = undefined;
|
|
@@ -60796,26 +60142,22 @@ async function startChannelSession(options) {
|
|
|
60796
60142
|
turns = userTurnState(file, restored);
|
|
60797
60143
|
router = options.router(turns);
|
|
60798
60144
|
};
|
|
60799
|
-
const triggerReplay = () => {
|
|
60800
|
-
if (!shuttingDown)
|
|
60801
|
-
replay.sweep();
|
|
60802
|
-
};
|
|
60803
|
-
const takeRemovals = (raw) => {
|
|
60804
|
-
const removedTopics = subscriptionRemovedTopics(raw, identity.id);
|
|
60805
|
-
if (removedTopics !== undefined && removedTopics.length > 0) {
|
|
60806
|
-
for (const topic of removedTopics)
|
|
60807
|
-
userTopics.delete(topic);
|
|
60808
|
-
dropRemovedTopics(removedTopics);
|
|
60809
|
-
}
|
|
60810
|
-
};
|
|
60811
60145
|
let relay;
|
|
60812
|
-
const
|
|
60146
|
+
const closeRemovedSubscriptions = async (frame) => {
|
|
60147
|
+
await closeReplayedRemoval(frame, {
|
|
60148
|
+
sessionID: identity.id,
|
|
60149
|
+
relay: relay?.sessionID === identity.id ? relay.delivery : undefined,
|
|
60150
|
+
close: (topic) => userTopics.delete(topic),
|
|
60151
|
+
unregister: unfollowRemovedTopics,
|
|
60152
|
+
followedChanged: () => ledger.followedChanged()
|
|
60153
|
+
});
|
|
60154
|
+
};
|
|
60813
60155
|
const deliverRelayed = async (owner, frame) => {
|
|
60814
60156
|
if (shuttingDown || relay !== owner || owner.sessionID !== identity.id) {
|
|
60815
60157
|
frame.nak();
|
|
60816
60158
|
return;
|
|
60817
60159
|
}
|
|
60818
|
-
|
|
60160
|
+
await closeRemovedSubscriptions(frame);
|
|
60819
60161
|
const identityOf = deliveryIdentity(frame.data);
|
|
60820
60162
|
const claim = dedupe.claim(identityOf);
|
|
60821
60163
|
if (claim === undefined) {
|
|
@@ -60837,7 +60179,7 @@ async function startChannelSession(options) {
|
|
|
60837
60179
|
return;
|
|
60838
60180
|
}
|
|
60839
60181
|
if (identityOf !== undefined)
|
|
60840
|
-
await
|
|
60182
|
+
await ledger.recordDelivered(identityOf);
|
|
60841
60183
|
claim.settle();
|
|
60842
60184
|
frame.done();
|
|
60843
60185
|
owner.delivery.persist();
|
|
@@ -60846,10 +60188,10 @@ async function startChannelSession(options) {
|
|
|
60846
60188
|
closeRelay();
|
|
60847
60189
|
const consumer = createConsumerDelivery({
|
|
60848
60190
|
sessionID,
|
|
60849
|
-
ledger
|
|
60191
|
+
ledger,
|
|
60850
60192
|
host: {
|
|
60851
60193
|
deliver: (frame) => deliverRelayed(owner, frame),
|
|
60852
|
-
gap:
|
|
60194
|
+
gap: tellGapNotice,
|
|
60853
60195
|
log: (message, error) => {
|
|
60854
60196
|
process.stderr.write(`envoy-channel: ${message}${error === undefined ? "" : ` \u2014 ${messageFor(error)}`}
|
|
60855
60197
|
`);
|
|
@@ -60907,56 +60249,37 @@ async function startChannelSession(options) {
|
|
|
60907
60249
|
`);
|
|
60908
60250
|
});
|
|
60909
60251
|
};
|
|
60910
|
-
const takeDeliveryAnswer = (sessionID,
|
|
60252
|
+
const takeDeliveryAnswer = (sessionID, asked, result) => {
|
|
60911
60253
|
if (sessionID !== identity.id || relay !== asked)
|
|
60912
60254
|
return;
|
|
60913
|
-
asked
|
|
60914
|
-
};
|
|
60915
|
-
const
|
|
60916
|
-
dedupe,
|
|
60917
|
-
ledger: replay,
|
|
60918
|
-
relayed: relaysCoreTopic,
|
|
60919
|
-
failed: (message, topic, error, receivedAt) => {
|
|
60920
|
-
const envelope = renderInbound(message.raw, identity.id, message.subject).envelope;
|
|
60921
|
-
if (envelope !== undefined)
|
|
60922
|
-
replay.liveFailed(identity.id, topic, envelope, error, receivedAt);
|
|
60923
|
-
},
|
|
60924
|
-
deliver: async (message) => {
|
|
60925
|
-
takeRemovals(message.raw);
|
|
60926
|
-
return enqueueChannelMessage(delivery, options.connection, directSubject, message);
|
|
60927
|
-
}
|
|
60928
|
-
});
|
|
60929
|
-
function dropRemovedTopics(topics) {
|
|
60930
|
-
unfollowRemovedTopics(topics);
|
|
60931
|
-
return replay.followedChanged();
|
|
60932
|
-
}
|
|
60255
|
+
asked.delivery.answered(result.delivery);
|
|
60256
|
+
};
|
|
60257
|
+
const followedTopics = createChannelTopics(options.connection);
|
|
60933
60258
|
function unfollowRemovedTopics(topics) {
|
|
60934
|
-
|
|
60935
|
-
dropping.catch((error) => {
|
|
60936
|
-
process.stderr.write(`envoy-channel: could not drop a removed subscription \u2014 ${messageFor(error)}
|
|
60937
|
-
`);
|
|
60938
|
-
});
|
|
60939
|
-
unsubscribing.catch((error) => {
|
|
60259
|
+
dropFromTopicsAndRegistry(topics).catch((error) => {
|
|
60940
60260
|
process.stderr.write(`envoy-channel: could not drop a removed subscription from the registry \u2014 ${messageFor(error)}; the next heartbeat reconciles it
|
|
60941
60261
|
`);
|
|
60942
60262
|
});
|
|
60943
60263
|
}
|
|
60944
|
-
function
|
|
60945
|
-
|
|
60946
|
-
if (relay?.sessionID === identity.id)
|
|
60947
|
-
relay.delivery.setFollowed(
|
|
60948
|
-
|
|
60949
|
-
|
|
60950
|
-
|
|
60951
|
-
|
|
60952
|
-
|
|
60953
|
-
|
|
60954
|
-
}))
|
|
60955
|
-
};
|
|
60956
|
-
}
|
|
60957
|
-
function registeredTopics() {
|
|
60958
|
-
return forwarder.topics().filter((topic) => !reachesPrivateStreamSubject(directSubject, topic));
|
|
60264
|
+
function dropFromTopicsAndRegistry(topics) {
|
|
60265
|
+
followedTopics.unfollow(topics);
|
|
60266
|
+
if (relay?.sessionID === identity.id) {
|
|
60267
|
+
relay.delivery.setFollowed(registrationTopics(directSubject, followedTopics.topics(), heldRole === undefined ? [] : [heldRole]));
|
|
60268
|
+
}
|
|
60269
|
+
return serialized(() => options.client.unsubscribe({
|
|
60270
|
+
sessionID: identity.id,
|
|
60271
|
+
topics,
|
|
60272
|
+
clientInstanceID: options.clientInstanceID
|
|
60273
|
+
}));
|
|
60959
60274
|
}
|
|
60275
|
+
const inboundOutage = inboundUnavailable((why) => {
|
|
60276
|
+
process.stderr.write(`envoy-channel: this session receives nothing (${why}); registering again every heartbeat
|
|
60277
|
+
`);
|
|
60278
|
+
delivery.notice(inboundUnavailableNoticeText(why)).catch((noticeError) => {
|
|
60279
|
+
process.stderr.write(`envoy-channel: the session could not be told that it receives nothing \u2014 ${messageFor(noticeError)}
|
|
60280
|
+
`);
|
|
60281
|
+
});
|
|
60282
|
+
});
|
|
60960
60283
|
let stampedTitle;
|
|
60961
60284
|
let stampFailureReported = false;
|
|
60962
60285
|
const register = async () => {
|
|
@@ -60975,34 +60298,44 @@ async function startChannelSession(options) {
|
|
|
60975
60298
|
}
|
|
60976
60299
|
}
|
|
60977
60300
|
const sessionID = identity.id;
|
|
60978
|
-
const
|
|
60979
|
-
|
|
60980
|
-
|
|
60981
|
-
|
|
60982
|
-
|
|
60983
|
-
|
|
60984
|
-
|
|
60985
|
-
|
|
60986
|
-
|
|
60987
|
-
|
|
60988
|
-
|
|
60989
|
-
|
|
60990
|
-
|
|
60991
|
-
|
|
60992
|
-
|
|
60993
|
-
|
|
60994
|
-
|
|
60995
|
-
|
|
60996
|
-
|
|
60997
|
-
|
|
60998
|
-
|
|
60999
|
-
|
|
61000
|
-
|
|
61001
|
-
|
|
61002
|
-
|
|
60301
|
+
const asking = relay?.sessionID === sessionID ? relay : undefined;
|
|
60302
|
+
await registerWithRelay({
|
|
60303
|
+
relay: asking?.delivery,
|
|
60304
|
+
ownAgentSubject: directSubject,
|
|
60305
|
+
followed: followedTopics.topics(),
|
|
60306
|
+
roles: heldRole === undefined ? [] : [heldRole],
|
|
60307
|
+
outage: inboundOutage,
|
|
60308
|
+
send: (topics, deliveryRequest) => {
|
|
60309
|
+
const registering = options.client.subscribe({
|
|
60310
|
+
sessionID,
|
|
60311
|
+
directory: identity.directory,
|
|
60312
|
+
topics,
|
|
60313
|
+
port: 0,
|
|
60314
|
+
title,
|
|
60315
|
+
capabilities: options.capabilities(),
|
|
60316
|
+
driving: false,
|
|
60317
|
+
selfSubscribed: true,
|
|
60318
|
+
clientInstanceID: options.clientInstanceID,
|
|
60319
|
+
plugin: { name, version: options.pluginVersion },
|
|
60320
|
+
delivery: deliveryRequest
|
|
60321
|
+
});
|
|
60322
|
+
const settled = registering.then(() => {
|
|
60323
|
+
return;
|
|
60324
|
+
}, () => {
|
|
60325
|
+
return;
|
|
60326
|
+
});
|
|
60327
|
+
registrationInFlight = settled;
|
|
60328
|
+
settled.then(() => {
|
|
60329
|
+
if (registrationInFlight === settled)
|
|
60330
|
+
registrationInFlight = undefined;
|
|
60331
|
+
});
|
|
60332
|
+
return registering;
|
|
60333
|
+
},
|
|
60334
|
+
answered: (result) => {
|
|
60335
|
+
if (asking !== undefined)
|
|
60336
|
+
takeDeliveryAnswer(sessionID, asking, result);
|
|
60337
|
+
}
|
|
61003
60338
|
});
|
|
61004
|
-
const result = await registering;
|
|
61005
|
-
takeDeliveryAnswer(sessionID, topics, asking, result);
|
|
61006
60339
|
};
|
|
61007
60340
|
const writeRoleRecord = (file, role) => writePersistedRole(file, {
|
|
61008
60341
|
session_id: identity.id,
|
|
@@ -61116,19 +60449,19 @@ async function startChannelSession(options) {
|
|
|
61116
60449
|
const previous = identity.id;
|
|
61117
60450
|
const previousSubject = directSubject;
|
|
61118
60451
|
const nextSubject = agentSubject(next);
|
|
61119
|
-
|
|
60452
|
+
followedTopics.follow(nextSubject);
|
|
61120
60453
|
try {
|
|
61121
60454
|
await withTimeout(options.connection.flush(), options.handoffFlushTimeoutMs ?? HANDOFF_FLUSH_TIMEOUT_MS, "flushing NATS");
|
|
61122
60455
|
await deregister(previous);
|
|
61123
60456
|
} catch (error) {
|
|
61124
|
-
|
|
60457
|
+
followedTopics.unfollow([nextSubject]);
|
|
61125
60458
|
throw error;
|
|
61126
60459
|
}
|
|
61127
60460
|
identity.set(next);
|
|
61128
60461
|
forgetBrokerSession(previous);
|
|
61129
60462
|
directSubject = nextSubject;
|
|
61130
|
-
|
|
61131
|
-
await
|
|
60463
|
+
followedTopics.unfollow([previousSubject]);
|
|
60464
|
+
await restoreDelivery();
|
|
61132
60465
|
await restoreTurns();
|
|
61133
60466
|
roleTransferFrom ??= previous;
|
|
61134
60467
|
await withTimeout(options.connection.flush(), options.handoffFlushTimeoutMs ?? HANDOFF_FLUSH_TIMEOUT_MS, "flushing NATS").catch((error) => {
|
|
@@ -61152,14 +60485,14 @@ async function startChannelSession(options) {
|
|
|
61152
60485
|
if (topic === directSubject || topic.startsWith(ROLE_TOPIC_PREFIX))
|
|
61153
60486
|
continue;
|
|
61154
60487
|
userTopics.add(topic);
|
|
61155
|
-
|
|
60488
|
+
followedTopics.follow(topic);
|
|
61156
60489
|
}
|
|
61157
60490
|
interestsRead = true;
|
|
61158
60491
|
return;
|
|
61159
60492
|
}
|
|
61160
60493
|
if (registry === undefined)
|
|
61161
60494
|
return;
|
|
61162
|
-
const followed = new Set(
|
|
60495
|
+
const followed = new Set(followedTopics.topics());
|
|
61163
60496
|
const drifted = registry.topics.filter((topic) => topic !== directSubject && !topic.startsWith(ROLE_TOPIC_PREFIX) && !followed.has(topic));
|
|
61164
60497
|
if (drifted.length === 0)
|
|
61165
60498
|
return;
|
|
@@ -61216,7 +60549,6 @@ async function startChannelSession(options) {
|
|
|
61216
60549
|
`);
|
|
61217
60550
|
} finally {
|
|
61218
60551
|
heartbeatInFlight = false;
|
|
61219
|
-
triggerReplay();
|
|
61220
60552
|
if (heartbeatRequested) {
|
|
61221
60553
|
heartbeatRequested = false;
|
|
61222
60554
|
heartbeat();
|
|
@@ -61243,12 +60575,12 @@ async function startChannelSession(options) {
|
|
|
61243
60575
|
else
|
|
61244
60576
|
heartbeat();
|
|
61245
60577
|
};
|
|
61246
|
-
const remembered = await
|
|
60578
|
+
const remembered = await restoreDelivery();
|
|
61247
60579
|
await restoreTurns();
|
|
61248
|
-
|
|
60580
|
+
followedTopics.follow(directSubject);
|
|
61249
60581
|
for (const topic of remembered) {
|
|
61250
60582
|
userTopics.add(topic);
|
|
61251
|
-
|
|
60583
|
+
followedTopics.follow(topic);
|
|
61252
60584
|
}
|
|
61253
60585
|
await syncRegisteredInterests().catch((error) => {
|
|
61254
60586
|
process.stderr.write(`envoy-channel: could not read the registered interests (${messageFor(error)}); the next heartbeat retries
|
|
@@ -61256,7 +60588,11 @@ async function startChannelSession(options) {
|
|
|
61256
60588
|
});
|
|
61257
60589
|
await options.connection.flush();
|
|
61258
60590
|
await serialized(async () => {
|
|
61259
|
-
await register()
|
|
60591
|
+
await register().catch((error) => {
|
|
60592
|
+
registrationFailed = true;
|
|
60593
|
+
process.stderr.write(`envoy-channel: the first registration failed (${messageFor(error)}); the next heartbeat retries
|
|
60594
|
+
`);
|
|
60595
|
+
});
|
|
61260
60596
|
try {
|
|
61261
60597
|
roleTransferFrom = await restoreRole(identity.id) === "pending" ? identity.id : undefined;
|
|
61262
60598
|
} catch (error) {
|
|
@@ -61271,7 +60607,6 @@ async function startChannelSession(options) {
|
|
|
61271
60607
|
}
|
|
61272
60608
|
}
|
|
61273
60609
|
});
|
|
61274
|
-
triggerReplay();
|
|
61275
60610
|
for (const prune of [
|
|
61276
60611
|
() => pruneStaleSessionHandoffs(options.stateDirectory),
|
|
61277
60612
|
() => pruneStaleSessionTitles(options.stateDirectory),
|
|
@@ -61300,7 +60635,6 @@ async function startChannelSession(options) {
|
|
|
61300
60635
|
if (status.type !== "reconnect")
|
|
61301
60636
|
continue;
|
|
61302
60637
|
renewRelayEpoch();
|
|
61303
|
-
triggerReplay();
|
|
61304
60638
|
}
|
|
61305
60639
|
} catch (error) {
|
|
61306
60640
|
process.stderr.write(`envoy-channel: the NATS connection's status reader failed \u2014 ${messageFor(error)}
|
|
@@ -61309,8 +60643,9 @@ async function startChannelSession(options) {
|
|
|
61309
60643
|
})();
|
|
61310
60644
|
return {
|
|
61311
60645
|
delivery,
|
|
61312
|
-
topics: () =>
|
|
60646
|
+
topics: () => followedTopics.topics(),
|
|
61313
60647
|
async follow(topics) {
|
|
60648
|
+
refuseUncapturedTopics(identity.id, directSubject, topics);
|
|
61314
60649
|
if (shuttingDown)
|
|
61315
60650
|
return [];
|
|
61316
60651
|
const fresh = [];
|
|
@@ -61318,14 +60653,13 @@ async function startChannelSession(options) {
|
|
|
61318
60653
|
if (topic === directSubject || userTopics.has(topic))
|
|
61319
60654
|
continue;
|
|
61320
60655
|
userTopics.add(topic);
|
|
61321
|
-
|
|
60656
|
+
followedTopics.follow(topic);
|
|
61322
60657
|
fresh.push(topic);
|
|
61323
60658
|
}
|
|
61324
60659
|
await options.connection.flush();
|
|
61325
60660
|
await serialized(register);
|
|
61326
60661
|
if (fresh.length > 0) {
|
|
61327
|
-
await
|
|
61328
|
-
triggerReplay();
|
|
60662
|
+
await ledger.followedChanged();
|
|
61329
60663
|
}
|
|
61330
60664
|
return fresh;
|
|
61331
60665
|
},
|
|
@@ -61334,10 +60668,9 @@ async function startChannelSession(options) {
|
|
|
61334
60668
|
const removed = requested.filter((topic) => userTopics.delete(topic));
|
|
61335
60669
|
if (removed.length === 0)
|
|
61336
60670
|
return [];
|
|
61337
|
-
const
|
|
61338
|
-
await
|
|
60671
|
+
const unsubscribing = dropFromTopicsAndRegistry(removed);
|
|
60672
|
+
await ledger.followedChanged();
|
|
61339
60673
|
await unsubscribing;
|
|
61340
|
-
await dropping;
|
|
61341
60674
|
return removed;
|
|
61342
60675
|
},
|
|
61343
60676
|
onRoleRegained(hook) {
|
|
@@ -61370,7 +60703,7 @@ async function startChannelSession(options) {
|
|
|
61370
60703
|
if (handoffFile !== undefined)
|
|
61371
60704
|
unwatchFile(handoffFile, handoffFileChanged);
|
|
61372
60705
|
closeRelay();
|
|
61373
|
-
await
|
|
60706
|
+
await followedTopics.close();
|
|
61374
60707
|
const settleBy = Date.now() + shutdownSettleMs;
|
|
61375
60708
|
await settledOrGivenUp(registryWrites, shutdownSettleMs);
|
|
61376
60709
|
await deregister(identity.id, Math.max(0, settleBy - Date.now())).catch((error) => {
|
|
@@ -61421,7 +60754,6 @@ async function executeEnvoyTool(runtime, name, input) {
|
|
|
61421
60754
|
topic: result.envelope.topic,
|
|
61422
60755
|
...result.holder === undefined ? {} : { holder: result.holder },
|
|
61423
60756
|
...result.holderState === undefined ? {} : { holder_state: result.holderState },
|
|
61424
|
-
unresponsive: result.unresponsive,
|
|
61425
60757
|
...result.kept === undefined ? {} : { kept: result.kept },
|
|
61426
60758
|
...result.keptReason === undefined ? {} : { kept_reason: result.keptReason }
|
|
61427
60759
|
};
|