@sjawhar/pi-envoy 17.6.1 → 17.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +48 -48
- package/dist/dispatch.js +105 -111
- package/dist/envoy.js +717 -1429
- package/dist/skills/envoy/SKILL.md +96 -22
- package/dist/skills/envoy/references/deliveries.md +71 -15
- package/dist/skills/envoy/references/legion.md +34 -8
- package/package.json +1 -1
package/dist/envoy.js
CHANGED
|
@@ -29706,6 +29706,9 @@ function agentSubject(session) {
|
|
|
29706
29706
|
return `${AGENT_TOPIC_PREFIX}${session}`;
|
|
29707
29707
|
}
|
|
29708
29708
|
var GHOSTWISPR_TOPIC_PREFIX = "notifications.ghostwispr.";
|
|
29709
|
+
function uncapturedTopicRefusal(topic, sessionID) {
|
|
29710
|
+
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`;
|
|
29711
|
+
}
|
|
29709
29712
|
|
|
29710
29713
|
// ../contracts/src/legion-roles.ts
|
|
29711
29714
|
var GATED_STEPS = ["decisions", "criteria", "spec"];
|
|
@@ -29947,6 +29950,8 @@ var ArtifactCreatedEventPayloadSchema = object({
|
|
|
29947
29950
|
name: artifactFields.name.optional()
|
|
29948
29951
|
}).optional()
|
|
29949
29952
|
});
|
|
29953
|
+
var ArtifactRenamedEventPayloadSchema = strictObject({ artifact: ArtifactSchema, previous_name: string2() }).readonly();
|
|
29954
|
+
var ArtifactRemovedEventPayloadSchema = strictObject({ artifact: ArtifactSchema }).readonly();
|
|
29950
29955
|
var artifactVersionEventPayloadFields = {
|
|
29951
29956
|
artifact_id: string2(),
|
|
29952
29957
|
name: string2(),
|
|
@@ -30042,15 +30047,16 @@ function documentOwnerValidation(requireArtifact, alwaysRequireArtifact = false)
|
|
|
30042
30047
|
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."
|
|
30043
30048
|
};
|
|
30044
30049
|
}
|
|
30045
|
-
var ARTIFACT_SOURCE_RULE = "
|
|
30050
|
+
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.";
|
|
30046
30051
|
var ARTIFACT_OWNER_AND_SOURCE_RULE = `${ARTIFACT_SOURCE_RULE} Exactly one of issue and project is required; with project, artifact names the document.`;
|
|
30047
30052
|
function brokenParts(parts) {
|
|
30048
30053
|
const broken = parts.filter(([kept]) => !kept).map(([, message]) => message);
|
|
30049
30054
|
return broken.length === 0 ? undefined : broken.join(" ");
|
|
30050
30055
|
}
|
|
30051
30056
|
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)";
|
|
30057
|
+
var DOCUMENT_IS_MARKDOWN = "a document holds Markdown, which rewrites other text (a JSONL file's lines come back joined into one paragraph)";
|
|
30052
30058
|
var PATH_KEEPS_BYTES = "path (--path <file>), which stores a file whose path does not end in .md or .markdown as its bytes, unchanged";
|
|
30053
|
-
var ARTIFACT_CONTENT_NAME_RULE = `${CONTENT_IS_MARKDOWN}, so
|
|
30059
|
+
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}.`;
|
|
30054
30060
|
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.";
|
|
30055
30061
|
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}.`;
|
|
30056
30062
|
var NAME_EXTENSION = /\.([^\s.]+)$/u;
|
|
@@ -30064,19 +30070,16 @@ function artifactProblem(value) {
|
|
|
30064
30070
|
const input = value;
|
|
30065
30071
|
const ownerOrSourceProblem = brokenParts([
|
|
30066
30072
|
[artifactOwner.check(value), artifactOwner.message],
|
|
30067
|
-
[
|
|
30068
|
-
typeof input.path === "string" !== (typeof input.content === "string"),
|
|
30069
|
-
ARTIFACT_SOURCE_RULE
|
|
30070
|
-
]
|
|
30073
|
+
[typeof input.path !== "string" || typeof input.content !== "string", ARTIFACT_SOURCE_RULE]
|
|
30071
30074
|
]);
|
|
30072
30075
|
if (ownerOrSourceProblem !== undefined)
|
|
30073
30076
|
return ownerOrSourceProblem;
|
|
30074
|
-
if (typeof input.
|
|
30077
|
+
if (typeof input.path === "string" || typeof input.name !== "string")
|
|
30075
30078
|
return;
|
|
30076
30079
|
const extension = NAME_EXTENSION.exec(input.name.trim())?.[1];
|
|
30077
30080
|
if (extension === undefined || MARKDOWN_EXTENSION.test(extension))
|
|
30078
30081
|
return;
|
|
30079
|
-
return `${
|
|
30082
|
+
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.`;
|
|
30080
30083
|
}
|
|
30081
30084
|
var documentEditOwner = documentOwnerValidation(true);
|
|
30082
30085
|
var PRECONDITION_RULE = "A precondition selects exactly one of document or blocks.";
|
|
@@ -30627,7 +30630,7 @@ var dispatchToolSpecs = [
|
|
|
30627
30630
|
name: "dispatch_artifact",
|
|
30628
30631
|
example: { issue: "DSP-1", name: "design.md", content: `# Design
|
|
30629
30632
|
` },
|
|
30630
|
-
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.
|
|
30633
|
+
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}`,
|
|
30631
30634
|
arguments: (z) => ({
|
|
30632
30635
|
issue: z.string().describe(ISSUE_REFERENCE).optional(),
|
|
30633
30636
|
project: z.string().describe("Project key for an unlinked document.").optional(),
|
|
@@ -36975,8 +36978,9 @@ class DispatchClient {
|
|
|
36975
36978
|
return { status: response.status, payload: await this.#response(method, url, response) };
|
|
36976
36979
|
}
|
|
36977
36980
|
async#upload(path, input, key) {
|
|
36978
|
-
if (
|
|
36981
|
+
if (input.file === undefined) {
|
|
36979
36982
|
return this.#json("POST", path, input, undefined, undefined, key);
|
|
36983
|
+
}
|
|
36980
36984
|
const form = new FormData;
|
|
36981
36985
|
form.set("name", input.name);
|
|
36982
36986
|
if (input.summary !== undefined)
|
|
@@ -37464,58 +37468,6 @@ async function postDeliveryReply(config, sessionId, delivery, result) {
|
|
|
37464
37468
|
...reply
|
|
37465
37469
|
}, followUp === undefined ? {} : { followUp });
|
|
37466
37470
|
}
|
|
37467
|
-
function expectsLaneReceipt(frame) {
|
|
37468
|
-
return frame.reply !== undefined && frame.reply !== "" && frame.subject === frame.directSubject && frame.envelopeTopic !== undefined && frame.envelopeTopic !== frame.directSubject;
|
|
37469
|
-
}
|
|
37470
|
-
async function* readArrivals(subscription, now = Date.now) {
|
|
37471
|
-
const source = subscription[Symbol.asyncIterator]();
|
|
37472
|
-
const arrived = [];
|
|
37473
|
-
let stopped;
|
|
37474
|
-
let left = false;
|
|
37475
|
-
let wake;
|
|
37476
|
-
const signal = () => {
|
|
37477
|
-
wake?.();
|
|
37478
|
-
wake = undefined;
|
|
37479
|
-
};
|
|
37480
|
-
(async () => {
|
|
37481
|
-
try {
|
|
37482
|
-
for (;; ) {
|
|
37483
|
-
const read = await source.next();
|
|
37484
|
-
if (read.done === true || left)
|
|
37485
|
-
break;
|
|
37486
|
-
arrived.push({ message: read.value, receivedAt: now() });
|
|
37487
|
-
signal();
|
|
37488
|
-
}
|
|
37489
|
-
stopped = { failed: false };
|
|
37490
|
-
} catch (error) {
|
|
37491
|
-
stopped = { error, failed: true };
|
|
37492
|
-
}
|
|
37493
|
-
signal();
|
|
37494
|
-
})();
|
|
37495
|
-
try {
|
|
37496
|
-
for (;; ) {
|
|
37497
|
-
const next = arrived.shift();
|
|
37498
|
-
if (next !== undefined) {
|
|
37499
|
-
yield next;
|
|
37500
|
-
continue;
|
|
37501
|
-
}
|
|
37502
|
-
if (stopped?.failed === true)
|
|
37503
|
-
throw stopped.error;
|
|
37504
|
-
if (stopped !== undefined)
|
|
37505
|
-
return;
|
|
37506
|
-
const { promise, resolve } = Promise.withResolvers();
|
|
37507
|
-
wake = resolve;
|
|
37508
|
-
await promise;
|
|
37509
|
-
}
|
|
37510
|
-
} finally {
|
|
37511
|
-
if (stopped === undefined) {
|
|
37512
|
-
left = true;
|
|
37513
|
-
Promise.resolve(source.return?.()).catch(() => {
|
|
37514
|
-
return;
|
|
37515
|
-
});
|
|
37516
|
-
}
|
|
37517
|
-
}
|
|
37518
|
-
}
|
|
37519
37471
|
var DedupeIdentitySchema = object({
|
|
37520
37472
|
event_id: string2().min(1).optional(),
|
|
37521
37473
|
dedupe_key: string2().min(1).optional(),
|
|
@@ -38254,6 +38206,267 @@ function subscriptionRemovedTopics(raw, sessionID) {
|
|
|
38254
38206
|
return parsedPayload.data.topics ?? [];
|
|
38255
38207
|
}
|
|
38256
38208
|
|
|
38209
|
+
// ../envoy-client/src/delivery-ledger.ts
|
|
38210
|
+
var DELIVERY_LEDGER_TTL_MS = DELIVERY_DUPLICATE_WINDOW_MS;
|
|
38211
|
+
var DELIVERY_LEDGER_LIMIT = 20000;
|
|
38212
|
+
var LedgerEntrySchema = object({
|
|
38213
|
+
event_id: string2().min(1).optional(),
|
|
38214
|
+
dedupe_key: string2().min(1).optional(),
|
|
38215
|
+
at: number2()
|
|
38216
|
+
});
|
|
38217
|
+
var LedgerStateSchema = object({
|
|
38218
|
+
topics: array(string2()).default([])
|
|
38219
|
+
});
|
|
38220
|
+
var LedgerSnapshotSchema = object({
|
|
38221
|
+
state: LedgerStateSchema.optional(),
|
|
38222
|
+
ledger: array(LedgerEntrySchema)
|
|
38223
|
+
});
|
|
38224
|
+
function createDeliveryLedger(options) {
|
|
38225
|
+
const { host } = options;
|
|
38226
|
+
const now = options.now ?? Date.now;
|
|
38227
|
+
const ledger = createLedger(now);
|
|
38228
|
+
let topics = [];
|
|
38229
|
+
let unwritten = [];
|
|
38230
|
+
let writtenState;
|
|
38231
|
+
let writes = Promise.resolve();
|
|
38232
|
+
let epoch = 0;
|
|
38233
|
+
const safely = (what, call) => {
|
|
38234
|
+
try {
|
|
38235
|
+
call();
|
|
38236
|
+
} catch (error) {
|
|
38237
|
+
try {
|
|
38238
|
+
host.log(`delivery ledger: ${what} failed`, error);
|
|
38239
|
+
} catch {}
|
|
38240
|
+
}
|
|
38241
|
+
};
|
|
38242
|
+
const log = (message, error) => safely("log", () => host.log(message, error));
|
|
38243
|
+
const sessionRead = (read) => () => {
|
|
38244
|
+
try {
|
|
38245
|
+
return read();
|
|
38246
|
+
} catch {
|
|
38247
|
+
return;
|
|
38248
|
+
}
|
|
38249
|
+
};
|
|
38250
|
+
const currentSession = sessionRead(() => host.sessionID());
|
|
38251
|
+
const writeSession = sessionRead(() => host.writeSessionID === undefined ? host.sessionID() : host.writeSessionID());
|
|
38252
|
+
const bindTo = (sessionID, read) => {
|
|
38253
|
+
if (sessionID === undefined || sessionID === "" || read() !== sessionID)
|
|
38254
|
+
return;
|
|
38255
|
+
const bound = epoch;
|
|
38256
|
+
return { sessionID, alive: () => bound === epoch && read() === sessionID };
|
|
38257
|
+
};
|
|
38258
|
+
const bind = () => bindTo(currentSession(), currentSession);
|
|
38259
|
+
const stateJSON = () => JSON.stringify({ topics: [...topics].sort() });
|
|
38260
|
+
const record = (identity) => {
|
|
38261
|
+
const entry = ledger.record(identity);
|
|
38262
|
+
if (entry !== undefined)
|
|
38263
|
+
unwritten.push(entry);
|
|
38264
|
+
};
|
|
38265
|
+
const flush = (alive) => {
|
|
38266
|
+
const written = writes.then(async () => {
|
|
38267
|
+
if (!alive())
|
|
38268
|
+
return false;
|
|
38269
|
+
const json = stateJSON();
|
|
38270
|
+
const delivered = unwritten;
|
|
38271
|
+
if (json === writtenState && delivered.length === 0)
|
|
38272
|
+
return true;
|
|
38273
|
+
unwritten = [];
|
|
38274
|
+
const state = json === writtenState ? undefined : JSON.parse(json);
|
|
38275
|
+
try {
|
|
38276
|
+
await host.write({
|
|
38277
|
+
delivered,
|
|
38278
|
+
state,
|
|
38279
|
+
snapshot: () => ({ state: JSON.parse(json), ledger: ledger.list() })
|
|
38280
|
+
});
|
|
38281
|
+
if (state !== undefined)
|
|
38282
|
+
writtenState = json;
|
|
38283
|
+
return true;
|
|
38284
|
+
} catch (error) {
|
|
38285
|
+
unwritten = [...delivered, ...unwritten];
|
|
38286
|
+
log("delivery ledger: could not persist the state; the next write carries it", error);
|
|
38287
|
+
return false;
|
|
38288
|
+
}
|
|
38289
|
+
});
|
|
38290
|
+
writes = written.then(() => {
|
|
38291
|
+
return;
|
|
38292
|
+
});
|
|
38293
|
+
return written;
|
|
38294
|
+
};
|
|
38295
|
+
const syncFollowed = () => {
|
|
38296
|
+
topics = [...new Set(host.followedSubjects())];
|
|
38297
|
+
};
|
|
38298
|
+
const failureNotice = (envelope, error) => ({
|
|
38299
|
+
eventId: envelope.event_id ?? "unknown",
|
|
38300
|
+
sender: senderLabel(envelope),
|
|
38301
|
+
summary: envelope.payload_summary ?? "unknown",
|
|
38302
|
+
publishedAt: inboundTimestamp(envelope.issued_at),
|
|
38303
|
+
error,
|
|
38304
|
+
readWith: envelope.source === "dispatch" ? "dispatch read" : "envoy_inbox",
|
|
38305
|
+
envelope
|
|
38306
|
+
});
|
|
38307
|
+
const showFailureNotice = async (sessionID, notice, alive) => {
|
|
38308
|
+
let queued;
|
|
38309
|
+
try {
|
|
38310
|
+
queued = await host.showFailureNotice(sessionID, notice) === "queued";
|
|
38311
|
+
} catch (error) {
|
|
38312
|
+
if (alive())
|
|
38313
|
+
safely("failure notice warning", () => host.failureNoticeFailed(notice, error));
|
|
38314
|
+
return false;
|
|
38315
|
+
}
|
|
38316
|
+
if (queued || !alive())
|
|
38317
|
+
return true;
|
|
38318
|
+
record(ledgerIdentity(notice.envelope));
|
|
38319
|
+
await flush(alive);
|
|
38320
|
+
return true;
|
|
38321
|
+
};
|
|
38322
|
+
return {
|
|
38323
|
+
async followedChanged() {
|
|
38324
|
+
const alive = bind()?.alive;
|
|
38325
|
+
if (alive === undefined)
|
|
38326
|
+
return;
|
|
38327
|
+
try {
|
|
38328
|
+
syncFollowed();
|
|
38329
|
+
await flush(alive);
|
|
38330
|
+
} catch (error) {
|
|
38331
|
+
log("delivery ledger: could not take the followed subjects", error);
|
|
38332
|
+
}
|
|
38333
|
+
},
|
|
38334
|
+
delivered: (frame) => ledger.has(ledgerIdentity(frame)),
|
|
38335
|
+
async recordDelivered(frame) {
|
|
38336
|
+
const alive = bind()?.alive;
|
|
38337
|
+
if (alive === undefined)
|
|
38338
|
+
return;
|
|
38339
|
+
record(ledgerIdentity(frame));
|
|
38340
|
+
await flush(alive);
|
|
38341
|
+
},
|
|
38342
|
+
async recordDeliveredFor(sessionID, frame) {
|
|
38343
|
+
const alive = bindTo(sessionID, writeSession)?.alive;
|
|
38344
|
+
if (alive === undefined)
|
|
38345
|
+
return false;
|
|
38346
|
+
record(ledgerIdentity(frame));
|
|
38347
|
+
return await flush(alive);
|
|
38348
|
+
},
|
|
38349
|
+
async liveFailed(sessionID, envelope, error) {
|
|
38350
|
+
const alive = bindTo(sessionID, currentSession)?.alive;
|
|
38351
|
+
if (alive === undefined) {
|
|
38352
|
+
log("delivery ledger: a failed frame was not reported here; the session it names is closed");
|
|
38353
|
+
return false;
|
|
38354
|
+
}
|
|
38355
|
+
try {
|
|
38356
|
+
return await showFailureNotice(sessionID, failureNotice(envelope, messageFor(error)), alive);
|
|
38357
|
+
} catch (thrown) {
|
|
38358
|
+
log("delivery ledger: could not report a frame the session was not shown", thrown);
|
|
38359
|
+
return false;
|
|
38360
|
+
}
|
|
38361
|
+
},
|
|
38362
|
+
restore(snapshot) {
|
|
38363
|
+
epoch += 1;
|
|
38364
|
+
ledger.restore(snapshot.ledger);
|
|
38365
|
+
topics = [...new Set(snapshot.state?.topics ?? [])];
|
|
38366
|
+
writtenState = snapshot.state === undefined ? undefined : stateJSON();
|
|
38367
|
+
unwritten = [];
|
|
38368
|
+
}
|
|
38369
|
+
};
|
|
38370
|
+
}
|
|
38371
|
+
var STORED_WHILE_AWAY_SUFFIX = "while this session's connection was down.";
|
|
38372
|
+
function storedText(content, publishedAt) {
|
|
38373
|
+
return `${content}
|
|
38374
|
+
Published at ${publishedAt} ${STORED_WHILE_AWAY_SUFFIX}`;
|
|
38375
|
+
}
|
|
38376
|
+
function failureNoticeFields(notice) {
|
|
38377
|
+
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.";
|
|
38378
|
+
return {
|
|
38379
|
+
notice: "message not shown",
|
|
38380
|
+
event_id: notice.eventId,
|
|
38381
|
+
from: notice.sender,
|
|
38382
|
+
summary: notice.summary,
|
|
38383
|
+
published_at: notice.publishedAt,
|
|
38384
|
+
error: notice.error,
|
|
38385
|
+
detail: `This session could not be shown this message, so it is not coming back on its own. ${readWith}`
|
|
38386
|
+
};
|
|
38387
|
+
}
|
|
38388
|
+
function envoyNoticeText(fields) {
|
|
38389
|
+
return encode5({ envoy: fields });
|
|
38390
|
+
}
|
|
38391
|
+
async function closeReplayedRemoval(frame, host) {
|
|
38392
|
+
const closed = (subscriptionRemovedTopics(frame.data, host.sessionID) ?? []).filter((topic) => host.relay?.followedBefore(topic, frame.storedAtMs) !== false && host.close(topic));
|
|
38393
|
+
if (closed.length === 0)
|
|
38394
|
+
return closed;
|
|
38395
|
+
const unregistering = host.unregister(closed);
|
|
38396
|
+
await host.followedChanged();
|
|
38397
|
+
await unregistering;
|
|
38398
|
+
return closed;
|
|
38399
|
+
}
|
|
38400
|
+
function ledgerIdentity(frame) {
|
|
38401
|
+
return {
|
|
38402
|
+
...frame.event_id === undefined || frame.event_id === "" ? {} : { event_id: frame.event_id },
|
|
38403
|
+
...frame.dedupe_key === undefined || !dedupeKeyNamesItsEvent(frame) ? {} : { dedupe_key: frame.dedupe_key }
|
|
38404
|
+
};
|
|
38405
|
+
}
|
|
38406
|
+
function createLedger(now) {
|
|
38407
|
+
let entries = new Set;
|
|
38408
|
+
const byEvent = new Map;
|
|
38409
|
+
const byKey = new Map;
|
|
38410
|
+
const drop = (entry) => {
|
|
38411
|
+
entries.delete(entry);
|
|
38412
|
+
if (entry.event_id !== undefined && byEvent.get(entry.event_id) === entry) {
|
|
38413
|
+
byEvent.delete(entry.event_id);
|
|
38414
|
+
}
|
|
38415
|
+
if (entry.dedupe_key !== undefined && byKey.get(entry.dedupe_key) === entry) {
|
|
38416
|
+
byKey.delete(entry.dedupe_key);
|
|
38417
|
+
}
|
|
38418
|
+
};
|
|
38419
|
+
const add = (entry) => {
|
|
38420
|
+
if (entries.size >= DELIVERY_LEDGER_LIMIT) {
|
|
38421
|
+
const oldest = entries.values().next();
|
|
38422
|
+
if (oldest.done !== true)
|
|
38423
|
+
drop(oldest.value);
|
|
38424
|
+
}
|
|
38425
|
+
entries.add(entry);
|
|
38426
|
+
if (entry.event_id !== undefined)
|
|
38427
|
+
byEvent.set(entry.event_id, entry);
|
|
38428
|
+
if (entry.dedupe_key !== undefined)
|
|
38429
|
+
byKey.set(entry.dedupe_key, entry);
|
|
38430
|
+
};
|
|
38431
|
+
const expire = () => {
|
|
38432
|
+
const at = now();
|
|
38433
|
+
for (const entry of entries) {
|
|
38434
|
+
if (at - entry.at < DELIVERY_LEDGER_TTL_MS)
|
|
38435
|
+
break;
|
|
38436
|
+
drop(entry);
|
|
38437
|
+
}
|
|
38438
|
+
};
|
|
38439
|
+
const has = (identity) => {
|
|
38440
|
+
expire();
|
|
38441
|
+
return identity.event_id !== undefined && byEvent.has(identity.event_id) || identity.dedupe_key !== undefined && byKey.has(identity.dedupe_key);
|
|
38442
|
+
};
|
|
38443
|
+
return {
|
|
38444
|
+
has,
|
|
38445
|
+
record(identity) {
|
|
38446
|
+
if (identity.event_id === undefined && identity.dedupe_key === undefined)
|
|
38447
|
+
return;
|
|
38448
|
+
if (has(identity))
|
|
38449
|
+
return;
|
|
38450
|
+
const entry = { ...identity, at: now() };
|
|
38451
|
+
add(entry);
|
|
38452
|
+
return entry;
|
|
38453
|
+
},
|
|
38454
|
+
restore(restored) {
|
|
38455
|
+
entries = new Set;
|
|
38456
|
+
byEvent.clear();
|
|
38457
|
+
byKey.clear();
|
|
38458
|
+
const at = now();
|
|
38459
|
+
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);
|
|
38460
|
+
for (const entry of kept)
|
|
38461
|
+
add({ ...entry });
|
|
38462
|
+
},
|
|
38463
|
+
list() {
|
|
38464
|
+
expire();
|
|
38465
|
+
return [...entries];
|
|
38466
|
+
}
|
|
38467
|
+
};
|
|
38468
|
+
}
|
|
38469
|
+
|
|
38257
38470
|
// ../envoy-client/src/stream-topics.ts
|
|
38258
38471
|
var EXCEPTION_TOPIC_PREFIX = "notifications.envoy.exceptions.";
|
|
38259
38472
|
var STREAM_SUBJECT_PREFIXES = [
|
|
@@ -38264,42 +38477,103 @@ var STREAM_SUBJECT_PREFIXES = [
|
|
|
38264
38477
|
LEGION_NOTICE_TOPIC_PREFIX,
|
|
38265
38478
|
GHOSTWISPR_TOPIC_PREFIX,
|
|
38266
38479
|
"notifications.whatsapp.",
|
|
38267
|
-
|
|
38480
|
+
"notifications.team.",
|
|
38481
|
+
`${EXCEPTION_TOPIC_PREFIX}${AGENT_TOPIC_PREFIX}`,
|
|
38482
|
+
`${EXCEPTION_TOPIC_PREFIX}notifications.team.`
|
|
38268
38483
|
];
|
|
38269
38484
|
function streamStores(topic) {
|
|
38270
38485
|
return STREAM_SUBJECT_PREFIXES.some((prefix) => topic.length > prefix.length && topic.startsWith(prefix));
|
|
38271
38486
|
}
|
|
38272
|
-
|
|
38273
|
-
|
|
38274
|
-
import { hostname as hostname3 } from "os";
|
|
38275
|
-
function machineID() {
|
|
38276
|
-
return process.env["ENVOY_MACHINE_ID"] || process.env["AGENTBOX_HOST"] || hostname3();
|
|
38487
|
+
function streamDeliversNothing(topic) {
|
|
38488
|
+
return topic.startsWith("notifications.") && !topic.startsWith(ROLE_TOPIC_PREFIX) && !streamStores(topic);
|
|
38277
38489
|
}
|
|
38278
|
-
|
|
38279
|
-
|
|
38280
|
-
|
|
38281
|
-
|
|
38282
|
-
|
|
38283
|
-
|
|
38284
|
-
|
|
38285
|
-
|
|
38286
|
-
|
|
38287
|
-
|
|
38288
|
-
|
|
38289
|
-
|
|
38290
|
-
|
|
38490
|
+
function subscribeRefusesTopic(ownAgentSubject, topic) {
|
|
38491
|
+
return streamDeliversNothing(topic) && !reachesPrivateStreamSubject(ownAgentSubject, topic);
|
|
38492
|
+
}
|
|
38493
|
+
function refuseUncapturedTopics(sessionID, ownAgentSubject, topics) {
|
|
38494
|
+
const uncaptured = topics.filter((topic) => subscribeRefusesTopic(ownAgentSubject, topic));
|
|
38495
|
+
if (uncaptured.length === 0)
|
|
38496
|
+
return;
|
|
38497
|
+
throw new Error(uncaptured.map((topic) => uncapturedTopicRefusal(topic, sessionID)).join("; "));
|
|
38498
|
+
}
|
|
38499
|
+
var PRIVATE_STREAM_SUBJECTS = [
|
|
38500
|
+
`${AGENT_TOPIC_PREFIX}>`,
|
|
38501
|
+
`${LEGION_NOTICE_TOPIC_PREFIX}>`,
|
|
38502
|
+
`${EXCEPTION_TOPIC_PREFIX}${AGENT_TOPIC_PREFIX}>`,
|
|
38503
|
+
`${EXCEPTION_TOPIC_PREFIX}notifications.team.>`
|
|
38504
|
+
];
|
|
38505
|
+
var CONTROLLER_NOTICE_SUFFIX = ".controller";
|
|
38506
|
+
function controllerNoticeRole(topic) {
|
|
38507
|
+
if (!topic.startsWith(LEGION_NOTICE_TOPIC_PREFIX) || !topic.endsWith(CONTROLLER_NOTICE_SUFFIX)) {
|
|
38508
|
+
return;
|
|
38509
|
+
}
|
|
38510
|
+
const project = topic.slice(LEGION_NOTICE_TOPIC_PREFIX.length, topic.length - CONTROLLER_NOTICE_SUFFIX.length);
|
|
38511
|
+
if (project === "" || /[.*>]/.test(project))
|
|
38512
|
+
return;
|
|
38513
|
+
return `legion-${project}-controller`;
|
|
38514
|
+
}
|
|
38515
|
+
function subjectsOverlap(a, b) {
|
|
38516
|
+
const aTokens = a.split(".");
|
|
38517
|
+
const bTokens = b.split(".");
|
|
38518
|
+
for (let index = 0;index < aTokens.length && index < bTokens.length; index += 1) {
|
|
38519
|
+
const aToken = aTokens[index];
|
|
38520
|
+
const bToken = bTokens[index];
|
|
38521
|
+
if (aToken === ">" || bToken === ">")
|
|
38522
|
+
return true;
|
|
38523
|
+
if (aToken !== "*" && bToken !== "*" && aToken !== bToken)
|
|
38524
|
+
return false;
|
|
38525
|
+
}
|
|
38526
|
+
return aTokens.length === bTokens.length;
|
|
38527
|
+
}
|
|
38528
|
+
function reachesPrivateStreamSubject(ownAgentSubject, topic, roles = []) {
|
|
38529
|
+
if (!PRIVATE_STREAM_SUBJECTS.some((subject) => subjectsOverlap(topic, subject)))
|
|
38530
|
+
return false;
|
|
38531
|
+
const role = controllerNoticeRole(topic);
|
|
38532
|
+
if (role !== undefined)
|
|
38533
|
+
return !roles.includes(role);
|
|
38534
|
+
return topic !== ownAgentSubject || /[*>]/.test(ownAgentSubject);
|
|
38535
|
+
}
|
|
38536
|
+
function registrationTopics(ownAgentSubject, followed, roles = []) {
|
|
38537
|
+
return [
|
|
38538
|
+
...new Set([
|
|
38539
|
+
ownAgentSubject,
|
|
38540
|
+
...[...followed].filter((topic) => !reachesPrivateStreamSubject(ownAgentSubject, topic, roles) && !streamDeliversNothing(topic))
|
|
38541
|
+
])
|
|
38542
|
+
];
|
|
38543
|
+
}
|
|
38544
|
+
function replayFollowedSubjects(ownAgentSubject, topics, heldForRole = () => false) {
|
|
38545
|
+
const followed = [...topics].filter((topic) => !topic.startsWith(ROLE_TOPIC_PREFIX) && !reachesPrivateStreamSubject(ownAgentSubject, topic) && !heldForRole(topic));
|
|
38546
|
+
return [...new Set([ownAgentSubject, ...followed])];
|
|
38547
|
+
}
|
|
38548
|
+
function rememberedTopics(topics) {
|
|
38549
|
+
return (topics ?? []).filter((topic) => !topic.startsWith(AGENT_TOPIC_PREFIX) && !topic.startsWith(ROLE_TOPIC_PREFIX));
|
|
38550
|
+
}
|
|
38551
|
+
|
|
38552
|
+
// ../envoy-client/src/machine.ts
|
|
38553
|
+
import { hostname as hostname3 } from "os";
|
|
38554
|
+
function machineID() {
|
|
38555
|
+
return process.env["ENVOY_MACHINE_ID"] || process.env["AGENTBOX_HOST"] || hostname3();
|
|
38556
|
+
}
|
|
38557
|
+
|
|
38558
|
+
// ../envoy-client/src/transport.ts
|
|
38559
|
+
var SessionStateSchema = _enum2(["live", "unresponsive", "gone"]);
|
|
38560
|
+
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.";
|
|
38561
|
+
var WireStateSchema = SessionStateSchema.default("live");
|
|
38562
|
+
var InterestWireSchema = object({
|
|
38563
|
+
session_id: string2(),
|
|
38564
|
+
machine_id: string2(),
|
|
38565
|
+
dir: string2(),
|
|
38566
|
+
topics: array(string2()),
|
|
38567
|
+
updated_at: number2().int().optional(),
|
|
38291
38568
|
warnings: array(string2()).optional()
|
|
38292
38569
|
});
|
|
38293
|
-
var DeliveryAnswerWireSchema =
|
|
38294
|
-
|
|
38295
|
-
|
|
38296
|
-
|
|
38297
|
-
|
|
38298
|
-
|
|
38299
|
-
|
|
38300
|
-
}),
|
|
38301
|
-
object({ mode: literal("core"), reason: string2() })
|
|
38302
|
-
]);
|
|
38570
|
+
var DeliveryAnswerWireSchema = object({
|
|
38571
|
+
mode: literal("consumer"),
|
|
38572
|
+
subject: string2().min(1),
|
|
38573
|
+
stream_id: string2(),
|
|
38574
|
+
gap: boolean2(),
|
|
38575
|
+
consumer_start: number2().int().nonnegative().optional()
|
|
38576
|
+
});
|
|
38303
38577
|
var SessionWireSchema = object({
|
|
38304
38578
|
session_id: string2(),
|
|
38305
38579
|
machine_id: string2(),
|
|
@@ -38314,7 +38588,8 @@ var SessionWireSchema = object({
|
|
|
38314
38588
|
last_seen: number2().int().optional(),
|
|
38315
38589
|
state: WireStateSchema,
|
|
38316
38590
|
plugin: string2().optional(),
|
|
38317
|
-
plugin_version: string2().optional()
|
|
38591
|
+
plugin_version: string2().optional(),
|
|
38592
|
+
delivery: string2().optional()
|
|
38318
38593
|
});
|
|
38319
38594
|
var RoleWireSchema = object({
|
|
38320
38595
|
role: string2(),
|
|
@@ -38334,13 +38609,13 @@ var RoleHeldWireSchema = object({
|
|
|
38334
38609
|
var ErrorWireSchema = object({
|
|
38335
38610
|
error: string2(),
|
|
38336
38611
|
code: string2().optional(),
|
|
38612
|
+
reason: string2().optional(),
|
|
38337
38613
|
expected: array(string2()).optional(),
|
|
38338
38614
|
state: SessionStateSchema.optional(),
|
|
38339
38615
|
holder: string2().optional(),
|
|
38340
38616
|
holder_state: SessionStateSchema.optional(),
|
|
38341
38617
|
last_seen: number2().int().optional(),
|
|
38342
|
-
claim_released: boolean2().optional()
|
|
38343
|
-
unresponsive: array(string2()).optional()
|
|
38618
|
+
claim_released: boolean2().optional()
|
|
38344
38619
|
});
|
|
38345
38620
|
var EnvelopeResponseSchema = EnvelopeSchema.extend({
|
|
38346
38621
|
recipient: string2().optional(),
|
|
@@ -38348,46 +38623,30 @@ var EnvelopeResponseSchema = EnvelopeSchema.extend({
|
|
|
38348
38623
|
holder_state: SessionStateSchema.optional(),
|
|
38349
38624
|
recipient_state: SessionStateSchema.optional(),
|
|
38350
38625
|
last_seen: number2().int().optional(),
|
|
38351
|
-
unresponsive: array(string2()).optional(),
|
|
38352
38626
|
duplicate: boolean2().optional()
|
|
38353
38627
|
});
|
|
38354
38628
|
var PublishResponseSchema = EnvelopeResponseSchema.extend({
|
|
38355
38629
|
kept: boolean2().optional(),
|
|
38356
38630
|
kept_reason: _enum2(["unclaimed", "holder_lapsed"]).optional()
|
|
38357
38631
|
});
|
|
38358
|
-
var
|
|
38359
|
-
|
|
38360
|
-
|
|
38361
|
-
|
|
38362
|
-
|
|
38363
|
-
last_seq: number2().int().nonnegative()
|
|
38364
|
-
}),
|
|
38365
|
-
subjects: array(object({
|
|
38366
|
-
subject: string2(),
|
|
38367
|
-
messages: array(object({
|
|
38368
|
-
seq: number2().int().positive(),
|
|
38369
|
-
subject: string2(),
|
|
38370
|
-
time: string2(),
|
|
38371
|
-
data: string2()
|
|
38372
|
-
})),
|
|
38373
|
-
next_after: number2().int().nonnegative(),
|
|
38374
|
-
more: boolean2(),
|
|
38375
|
-
refused: string2().optional()
|
|
38376
|
-
}))
|
|
38377
|
-
});
|
|
38378
|
-
var DELIVERY_NOT_ANSWERED = "not_answered";
|
|
38379
|
-
var DELIVERY_UNREADABLE = "unreadable_answer";
|
|
38632
|
+
var DeliveryRefusalSchema = object({
|
|
38633
|
+
mode: string2(),
|
|
38634
|
+
reason: string2().optional()
|
|
38635
|
+
});
|
|
38636
|
+
var DELIVERY_UNREADABLE = "answered a delivery field this build cannot read";
|
|
38380
38637
|
function parseSubscribeAnswer(body) {
|
|
38381
38638
|
const interest = InterestWireSchema.parse(body);
|
|
38382
38639
|
const raw = typeof body === "object" && body !== null && "delivery" in body ? body.delivery : undefined;
|
|
38383
38640
|
if (raw === undefined || raw === null) {
|
|
38384
|
-
|
|
38641
|
+
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`);
|
|
38385
38642
|
}
|
|
38386
38643
|
const delivery = DeliveryAnswerWireSchema.safeParse(raw);
|
|
38387
|
-
|
|
38388
|
-
|
|
38389
|
-
|
|
38390
|
-
|
|
38644
|
+
if (!delivery.success) {
|
|
38645
|
+
const named = DeliveryRefusalSchema.safeParse(raw);
|
|
38646
|
+
const said = named.success ? `answered delivery mode ${named.data.mode}${named.data.reason === undefined ? "" : ` (${named.data.reason})`}` : DELIVERY_UNREADABLE;
|
|
38647
|
+
throw new Error(`the listener gave ${interest.session_id} no consumer: it ${said}, and a session receives only what its own consumer holds`);
|
|
38648
|
+
}
|
|
38649
|
+
return { ...interest, delivery: delivery.data };
|
|
38391
38650
|
}
|
|
38392
38651
|
function mergeInterestSources(registryTopics, liveTopics) {
|
|
38393
38652
|
const interests = new Map;
|
|
@@ -38433,27 +38692,20 @@ function expandSubscriptionTopics(topics) {
|
|
|
38433
38692
|
if (segments.length < 2 || segments.some((segment) => segment.length === 0)) {
|
|
38434
38693
|
throw new TypeError(`cannot expand Envoy wildcard topic "${topic}": its concrete base must have at least two non-empty segments`);
|
|
38435
38694
|
}
|
|
38436
|
-
|
|
38695
|
+
if (!streamDeliversNothing(base))
|
|
38696
|
+
expanded.add(base);
|
|
38437
38697
|
expanded.add(topic);
|
|
38438
38698
|
}
|
|
38439
38699
|
return [...expanded];
|
|
38440
38700
|
}
|
|
38441
38701
|
function refusalStateText(parsed) {
|
|
38442
|
-
const sentences = [];
|
|
38443
38702
|
const state = parsed.holder_state ?? parsed.state;
|
|
38444
|
-
if (state
|
|
38445
|
-
const who = parsed.holder === undefined ? "That session" : `Holder ${parsed.holder}`;
|
|
38446
|
-
const seen = parsed.last_seen === undefined || parsed.last_seen <= 0 ? "" : `, last seen ${new Date(parsed.last_seen).toISOString()}`;
|
|
38447
|
-
sentences.push(`${who} is ${state}${seen}.`);
|
|
38448
|
-
}
|
|
38449
|
-
const stored = parsed.unresponsive ?? [];
|
|
38450
|
-
if (stored.length > 0) {
|
|
38451
|
-
const one = stored.length === 1;
|
|
38452
|
-
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.`);
|
|
38453
|
-
}
|
|
38454
|
-
if (sentences.length === 0)
|
|
38703
|
+
if (state === undefined)
|
|
38455
38704
|
return "";
|
|
38456
|
-
|
|
38705
|
+
const who = parsed.holder === undefined ? "That session" : `Holder ${parsed.holder}`;
|
|
38706
|
+
const seen = parsed.last_seen === undefined || parsed.last_seen <= 0 ? "" : `, last seen ${new Date(parsed.last_seen).toISOString()}`;
|
|
38707
|
+
const sentences = [`${who} is ${state}${seen}.`];
|
|
38708
|
+
if (state === "unresponsive")
|
|
38457
38709
|
sentences.push(UNRESPONSIVE_RULE);
|
|
38458
38710
|
return ` ${sentences.join(" ")}`;
|
|
38459
38711
|
}
|
|
@@ -38463,11 +38715,11 @@ class EnvoyApiError extends Error {
|
|
|
38463
38715
|
name = "EnvoyApiError";
|
|
38464
38716
|
expected;
|
|
38465
38717
|
code;
|
|
38718
|
+
reason;
|
|
38466
38719
|
holder;
|
|
38467
38720
|
sessionState;
|
|
38468
38721
|
lastSeen;
|
|
38469
38722
|
claimReleased;
|
|
38470
|
-
unresponsive;
|
|
38471
38723
|
constructor(details) {
|
|
38472
38724
|
let parsed;
|
|
38473
38725
|
try {
|
|
@@ -38475,15 +38727,15 @@ class EnvoyApiError extends Error {
|
|
|
38475
38727
|
if (result.success)
|
|
38476
38728
|
parsed = result.data;
|
|
38477
38729
|
} catch {}
|
|
38478
|
-
super(parsed === undefined ? `${details.method} ${details.url} failed with ${details.status}: ${details.responseBody}` : `${parsed.error}${parsed.expected === undefined ? "" : ` (expected: ${parsed.expected.join(", ")})`}${refusalStateText(parsed)}`);
|
|
38730
|
+
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)}`);
|
|
38479
38731
|
this.details = details;
|
|
38480
38732
|
this.expected = parsed?.expected;
|
|
38481
38733
|
this.code = parsed?.code;
|
|
38734
|
+
this.reason = parsed?.reason;
|
|
38482
38735
|
this.holder = parsed?.holder;
|
|
38483
38736
|
this.sessionState = parsed?.holder_state ?? parsed?.state;
|
|
38484
38737
|
this.lastSeen = parsed?.last_seen;
|
|
38485
38738
|
this.claimReleased = parsed?.claim_released;
|
|
38486
|
-
this.unresponsive = parsed?.unresponsive;
|
|
38487
38739
|
}
|
|
38488
38740
|
}
|
|
38489
38741
|
var mintedDedupeKey2 = new RegExp(MINTED_DEDUPE_KEY_PATTERN);
|
|
@@ -38593,23 +38845,24 @@ function createEnvoyClient(config) {
|
|
|
38593
38845
|
headers: { "Content-Type": "application/json" },
|
|
38594
38846
|
body: JSON.stringify(body)
|
|
38595
38847
|
}, options);
|
|
38848
|
+
const subscribeBody = (input) => ({
|
|
38849
|
+
session_id: input.sessionID,
|
|
38850
|
+
dir: input.directory,
|
|
38851
|
+
topics: expandSubscriptionTopics(input.topics),
|
|
38852
|
+
port: input.port,
|
|
38853
|
+
title: input.title,
|
|
38854
|
+
...input.capabilities === undefined ? {} : { capabilities: input.capabilities },
|
|
38855
|
+
driving: input.driving,
|
|
38856
|
+
...input.selfSubscribed === undefined ? {} : { self_subscribed: input.selfSubscribed },
|
|
38857
|
+
delivery: input.delivery,
|
|
38858
|
+
...input.clientInstanceID === undefined ? {} : { client_instance_id: input.clientInstanceID },
|
|
38859
|
+
host: machineID(),
|
|
38860
|
+
...input.place === undefined ? {} : { tmux_place: input.place },
|
|
38861
|
+
plugin: input.plugin.name,
|
|
38862
|
+
plugin_version: input.plugin.version
|
|
38863
|
+
});
|
|
38596
38864
|
return {
|
|
38597
|
-
subscribe: async (input) => parseSubscribeAnswer(JSON.parse(await post("/v1/interests/subscribe", {
|
|
38598
|
-
session_id: input.sessionID,
|
|
38599
|
-
dir: input.directory,
|
|
38600
|
-
topics: expandSubscriptionTopics(input.topics),
|
|
38601
|
-
port: input.port,
|
|
38602
|
-
title: input.title,
|
|
38603
|
-
...input.capabilities === undefined ? {} : { capabilities: input.capabilities },
|
|
38604
|
-
driving: input.driving,
|
|
38605
|
-
...input.selfSubscribed === undefined ? {} : { self_subscribed: input.selfSubscribed },
|
|
38606
|
-
...input.delivery === undefined ? {} : { delivery: input.delivery },
|
|
38607
|
-
...input.clientInstanceID === undefined ? {} : { client_instance_id: input.clientInstanceID },
|
|
38608
|
-
host: machineID(),
|
|
38609
|
-
...input.place === undefined ? {} : { tmux_place: input.place },
|
|
38610
|
-
plugin: input.plugin.name,
|
|
38611
|
-
plugin_version: input.plugin.version
|
|
38612
|
-
}, { actingSession: input.sessionID }))),
|
|
38865
|
+
subscribe: async (input) => parseSubscribeAnswer(JSON.parse(await post("/v1/interests/subscribe", subscribeBody(input), { actingSession: input.sessionID }))),
|
|
38613
38866
|
unsubscribe: async (input) => {
|
|
38614
38867
|
await post("/v1/interests/unsubscribe", {
|
|
38615
38868
|
session_id: input.sessionID,
|
|
@@ -38668,7 +38921,6 @@ function createEnvoyClient(config) {
|
|
|
38668
38921
|
envelope: response,
|
|
38669
38922
|
...response.holder === undefined ? {} : { holder: response.holder },
|
|
38670
38923
|
...response.holder_state === undefined ? {} : { holderState: response.holder_state },
|
|
38671
|
-
unresponsive: response.unresponsive ?? [],
|
|
38672
38924
|
...response.kept === undefined ? {} : { kept: response.kept },
|
|
38673
38925
|
...response.kept_reason === undefined ? {} : { keptReason: response.kept_reason }
|
|
38674
38926
|
};
|
|
@@ -38708,875 +38960,35 @@ function createEnvoyClient(config) {
|
|
|
38708
38960
|
},
|
|
38709
38961
|
getRole: async (role) => RoleWireSchema.parse(JSON.parse(await request(`/v1/roles/${encodeURIComponent(role)}`, { method: "GET" }))),
|
|
38710
38962
|
listSessions: async (input = {}) => {
|
|
38711
|
-
const search = new URLSearchParams;
|
|
38712
|
-
if (input.directory !== undefined)
|
|
38713
|
-
search.set("dir", input.directory);
|
|
38714
|
-
if (input.title !== undefined)
|
|
38715
|
-
search.set("title", input.title);
|
|
38716
|
-
if (input.include !== undefined)
|
|
38717
|
-
search.set("include", input.include);
|
|
38718
|
-
const query = search.size === 0 ? "" : `?${search.toString()}`;
|
|
38719
|
-
return SessionWireSchema.array().parse(JSON.parse(await request(`/v1/sessions${query}`, {})));
|
|
38720
|
-
}
|
|
38721
|
-
replay: async (input) => ReplayWireSchema.parse(JSON.parse(await post("/v1/replay", {
|
|
38722
|
-
session_id: input.sessionID,
|
|
38723
|
-
subjects: input.subjects.map((cursor) => cursor.after === undefined ? { subject: cursor.subject } : { subject: cursor.subject, after: cursor.after }),
|
|
38724
|
-
...input.maxMessages === undefined ? {} : { max_messages: input.maxMessages }
|
|
38725
|
-
}, {
|
|
38726
|
-
timeoutMs: input.timeoutMs ?? REPLAY_TIMEOUT_MS,
|
|
38727
|
-
retry: false,
|
|
38728
|
-
actingSession: input.sessionID
|
|
38729
|
-
})))
|
|
38730
|
-
};
|
|
38731
|
-
}
|
|
38732
|
-
function waitForRetry(delayMs) {
|
|
38733
|
-
const { promise, resolve } = Promise.withResolvers();
|
|
38734
|
-
setTimeout(resolve, delayMs);
|
|
38735
|
-
return promise;
|
|
38736
|
-
}
|
|
38737
|
-
function messageMetadata(input) {
|
|
38738
|
-
return {
|
|
38739
|
-
...input.inReplyTo === undefined ? {} : { in_reply_to: input.inReplyTo },
|
|
38740
|
-
...input.supersedes === undefined ? {} : { supersedes: input.supersedes },
|
|
38741
|
-
...input.urgency === undefined ? {} : { urgency: input.urgency },
|
|
38742
|
-
...input.expectsReply === undefined ? {} : { expects_reply: input.expectsReply },
|
|
38743
|
-
...input.expiresAt === undefined ? {} : { expires_at: input.expiresAt }
|
|
38744
|
-
};
|
|
38745
|
-
}
|
|
38746
|
-
function sourceSession(sessionID) {
|
|
38747
|
-
return sessionID === undefined || sessionID === "" ? {} : { source_session: sessionID };
|
|
38748
|
-
}
|
|
38749
|
-
|
|
38750
|
-
// ../envoy-client/src/replay.ts
|
|
38751
|
-
var REPLAY_LEDGER_TTL_MS = DELIVERY_DUPLICATE_WINDOW_MS;
|
|
38752
|
-
var REPLAY_LEDGER_LIMIT = 20000;
|
|
38753
|
-
var REPLAY_PAGES_PER_SWEEP = 20;
|
|
38754
|
-
var REPLAY_FAILURES_BEFORE_NOTICE = 3;
|
|
38755
|
-
var REPLAY_STATE_REFRESH_MS = 60 * 60 * 1000;
|
|
38756
|
-
var REPLAY_MAX_SUBJECTS = 32;
|
|
38757
|
-
var START_CURSORS_TIMEOUT_MS = 2000;
|
|
38758
|
-
var ROLE_FORWARD_KEY_PREFIX = "envoy.role.forward.";
|
|
38759
|
-
var ReplayLedgerEntrySchema = object({
|
|
38760
|
-
event_id: string2().min(1).optional(),
|
|
38761
|
-
dedupe_key: string2().min(1).optional(),
|
|
38762
|
-
at: number2()
|
|
38763
|
-
});
|
|
38764
|
-
var ReplayCursorSchema = object({
|
|
38765
|
-
since: number2().int().nonnegative().optional(),
|
|
38766
|
-
after: number2().int().nonnegative().optional(),
|
|
38767
|
-
from_start: number2().int().nonnegative().optional()
|
|
38768
|
-
});
|
|
38769
|
-
var ReplayPendingNoticeSchema = _enum2([
|
|
38770
|
-
"retention_gap",
|
|
38771
|
-
"stream_moved_back",
|
|
38772
|
-
"stream_recreated"
|
|
38773
|
-
]);
|
|
38774
|
-
var PENDING_NOTICE_MESSAGES = {
|
|
38775
|
-
stream_recreated: "Envoy's notification stream was recreated, so messages published to this session while its connection was down before that may be lost.",
|
|
38776
|
-
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.",
|
|
38777
|
-
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."
|
|
38778
|
-
};
|
|
38779
|
-
var ReplayStateSchema = object({
|
|
38780
|
-
stream_id: string2().optional(),
|
|
38781
|
-
stream_created: string2().optional(),
|
|
38782
|
-
subjects: record(string2(), ReplayCursorSchema),
|
|
38783
|
-
notices: array(string2()).optional()
|
|
38784
|
-
});
|
|
38785
|
-
var ReplaySnapshotSchema = object({
|
|
38786
|
-
state: ReplayStateSchema.optional(),
|
|
38787
|
-
ledger: array(ReplayLedgerEntrySchema)
|
|
38788
|
-
});
|
|
38789
|
-
function createReplayEngine(options) {
|
|
38790
|
-
const { host, transport, dedupe } = options;
|
|
38791
|
-
const now = options.now ?? Date.now;
|
|
38792
|
-
const ledger = createLedger(now);
|
|
38793
|
-
const cursors = new Map;
|
|
38794
|
-
const cursorStarts = new Map;
|
|
38795
|
-
let streamID;
|
|
38796
|
-
let streamCreated;
|
|
38797
|
-
const pending = new Set;
|
|
38798
|
-
const failures = new Map;
|
|
38799
|
-
let unwritten = [];
|
|
38800
|
-
let writtenState;
|
|
38801
|
-
let writtenShape;
|
|
38802
|
-
let writtenAt;
|
|
38803
|
-
let writes = Promise.resolve();
|
|
38804
|
-
let epoch = 0;
|
|
38805
|
-
let listenerNoticed;
|
|
38806
|
-
const answered = new Set;
|
|
38807
|
-
let running;
|
|
38808
|
-
let rerun;
|
|
38809
|
-
let consumerMode = false;
|
|
38810
|
-
const safely = (what, call) => {
|
|
38811
|
-
try {
|
|
38812
|
-
call();
|
|
38813
|
-
} catch (error) {
|
|
38814
|
-
try {
|
|
38815
|
-
host.log(`replay: ${what} failed`, error);
|
|
38816
|
-
} catch {}
|
|
38817
|
-
}
|
|
38818
|
-
};
|
|
38819
|
-
const log = (message, error) => safely("log", () => host.log(message, error));
|
|
38820
|
-
const notify = (notice) => safely("notice", () => host.notify(notice));
|
|
38821
|
-
const tell = (kind) => {
|
|
38822
|
-
pending.delete(kind);
|
|
38823
|
-
notify({ kind, message: PENDING_NOTICE_MESSAGES[kind] });
|
|
38824
|
-
};
|
|
38825
|
-
const sessionRead = (read) => () => {
|
|
38826
|
-
try {
|
|
38827
|
-
return read();
|
|
38828
|
-
} catch {
|
|
38829
|
-
return;
|
|
38830
|
-
}
|
|
38831
|
-
};
|
|
38832
|
-
const currentSession = sessionRead(() => host.sessionID());
|
|
38833
|
-
const writeSession = sessionRead(() => host.writeSessionID === undefined ? host.sessionID() : host.writeSessionID());
|
|
38834
|
-
const bindTo = (sessionID, read) => {
|
|
38835
|
-
if (sessionID === undefined || sessionID === "" || read() !== sessionID)
|
|
38836
|
-
return;
|
|
38837
|
-
const bound = epoch;
|
|
38838
|
-
return { sessionID, alive: () => bound === epoch && read() === sessionID };
|
|
38839
|
-
};
|
|
38840
|
-
const bind = () => bindTo(currentSession(), currentSession);
|
|
38841
|
-
const stateJSON = (afters = true) => {
|
|
38842
|
-
const subjects = {};
|
|
38843
|
-
for (const subject of [...cursors.keys()].sort()) {
|
|
38844
|
-
const cursor = cursors.get(subject) ?? {};
|
|
38845
|
-
subjects[subject] = {
|
|
38846
|
-
...cursor.since === undefined ? {} : { since: cursor.since },
|
|
38847
|
-
...!afters || cursor.after === undefined ? {} : { after: cursor.after },
|
|
38848
|
-
...cursor.from_start === undefined ? {} : { from_start: cursor.from_start }
|
|
38849
|
-
};
|
|
38850
|
-
}
|
|
38851
|
-
return JSON.stringify({
|
|
38852
|
-
...streamID === undefined ? {} : { stream_id: streamID },
|
|
38853
|
-
...streamCreated === undefined ? {} : { stream_created: streamCreated },
|
|
38854
|
-
subjects,
|
|
38855
|
-
...pending.size === 0 ? {} : { notices: [...pending].sort() }
|
|
38856
|
-
});
|
|
38857
|
-
};
|
|
38858
|
-
const record2 = (identity) => {
|
|
38859
|
-
const entry = ledger.record(identity);
|
|
38860
|
-
if (entry !== undefined)
|
|
38861
|
-
unwritten.push(entry);
|
|
38862
|
-
};
|
|
38863
|
-
const flush = (alive, atOnce = false) => {
|
|
38864
|
-
const written = writes.then(async () => {
|
|
38865
|
-
if (!alive())
|
|
38866
|
-
return false;
|
|
38867
|
-
const json = stateJSON();
|
|
38868
|
-
const delivered = unwritten;
|
|
38869
|
-
if (json === writtenState && delivered.length === 0)
|
|
38870
|
-
return true;
|
|
38871
|
-
const shape = stateJSON(false);
|
|
38872
|
-
if (delivered.length === 0 && !atOnce && shape === writtenShape && writtenAt !== undefined && now() - writtenAt < REPLAY_STATE_REFRESH_MS) {
|
|
38873
|
-
return true;
|
|
38874
|
-
}
|
|
38875
|
-
unwritten = [];
|
|
38876
|
-
const state = json === writtenState ? undefined : JSON.parse(json);
|
|
38877
|
-
try {
|
|
38878
|
-
await host.write({
|
|
38879
|
-
delivered,
|
|
38880
|
-
state,
|
|
38881
|
-
snapshot: () => ({ state: JSON.parse(json), ledger: ledger.list() })
|
|
38882
|
-
});
|
|
38883
|
-
if (state !== undefined) {
|
|
38884
|
-
writtenState = json;
|
|
38885
|
-
writtenShape = shape;
|
|
38886
|
-
writtenAt = now();
|
|
38887
|
-
}
|
|
38888
|
-
return true;
|
|
38889
|
-
} catch (error) {
|
|
38890
|
-
unwritten = [...delivered, ...unwritten];
|
|
38891
|
-
log("replay: could not persist the replay state; the next write carries it", error);
|
|
38892
|
-
return false;
|
|
38893
|
-
}
|
|
38894
|
-
});
|
|
38895
|
-
writes = written.then(() => {
|
|
38896
|
-
return;
|
|
38897
|
-
});
|
|
38898
|
-
return written;
|
|
38899
|
-
};
|
|
38900
|
-
const syncFollowed = () => {
|
|
38901
|
-
const followed = new Set(host.followedSubjects());
|
|
38902
|
-
for (const subject of [...cursors.keys()]) {
|
|
38903
|
-
if (!followed.has(subject)) {
|
|
38904
|
-
cursors.delete(subject);
|
|
38905
|
-
cursorStarts.delete(subject);
|
|
38906
|
-
}
|
|
38907
|
-
}
|
|
38908
|
-
for (const subject of followed) {
|
|
38909
|
-
if (!cursors.has(subject))
|
|
38910
|
-
cursors.set(subject, {});
|
|
38911
|
-
}
|
|
38912
|
-
};
|
|
38913
|
-
const failureNotice = (envelope, publishedAt, error, subject) => ({
|
|
38914
|
-
eventId: envelope.event_id ?? "unknown",
|
|
38915
|
-
sender: senderLabel(envelope),
|
|
38916
|
-
summary: envelope.payload_summary ?? "unknown",
|
|
38917
|
-
publishedAt,
|
|
38918
|
-
error,
|
|
38919
|
-
readWith: envelope.source === "dispatch" ? "dispatch read" : "envoy_inbox",
|
|
38920
|
-
...subject === undefined ? {} : { subject },
|
|
38921
|
-
envelope
|
|
38922
|
-
});
|
|
38923
|
-
const showFailureNotice = async (notice, alive) => {
|
|
38924
|
-
let queued;
|
|
38925
|
-
try {
|
|
38926
|
-
queued = await host.showFailureNotice(notice) === "queued";
|
|
38927
|
-
} catch (error) {
|
|
38928
|
-
if (!alive())
|
|
38929
|
-
return "stopped";
|
|
38930
|
-
safely("failure notice warning", () => host.failureNoticeFailed(notice, error));
|
|
38931
|
-
return "hole";
|
|
38932
|
-
}
|
|
38933
|
-
if (!alive())
|
|
38934
|
-
return "stopped";
|
|
38935
|
-
if (queued)
|
|
38936
|
-
return "hole";
|
|
38937
|
-
record2(replayLedgerIdentity(notice.envelope));
|
|
38938
|
-
await flush(alive);
|
|
38939
|
-
return "done";
|
|
38940
|
-
};
|
|
38941
|
-
const handle = async (seq, buffered, alive) => {
|
|
38942
|
-
const { message } = buffered;
|
|
38943
|
-
const envelope = parseEnvelope(message.data);
|
|
38944
|
-
if (envelope === undefined) {
|
|
38945
|
-
log(`replay: skipping stored message ${seq} on ${message.subject}: not an Envoy envelope`);
|
|
38946
|
-
return "done";
|
|
38947
|
-
}
|
|
38948
|
-
if (isRoleForward(envelope))
|
|
38949
|
-
return "done";
|
|
38950
|
-
const identity = replayLedgerIdentity(envelope);
|
|
38951
|
-
if (ledger.has(identity)) {
|
|
38952
|
-
failures.delete(seq);
|
|
38953
|
-
return "done";
|
|
38954
|
-
}
|
|
38955
|
-
if (dedupe?.pending(envelope) === true)
|
|
38956
|
-
return "hole";
|
|
38957
|
-
if (!alive())
|
|
38958
|
-
return "stopped";
|
|
38959
|
-
const giveUp = async (error) => {
|
|
38960
|
-
const handled = await showFailureNotice(failureNotice(envelope, message.time, error, message.subject), alive);
|
|
38961
|
-
if (handled === "done")
|
|
38962
|
-
failures.delete(seq);
|
|
38963
|
-
return handled;
|
|
38964
|
-
};
|
|
38965
|
-
const failure = failures.get(seq);
|
|
38966
|
-
if (failure !== undefined && failure.count >= REPLAY_FAILURES_BEFORE_NOTICE) {
|
|
38967
|
-
return giveUp(failure.error);
|
|
38968
|
-
}
|
|
38969
|
-
const followed = buffered.subjects[0] ?? message.subject;
|
|
38970
|
-
let outcome;
|
|
38971
|
-
let error = "the host could not show it";
|
|
38972
|
-
try {
|
|
38973
|
-
outcome = await host.deliver({
|
|
38974
|
-
envelope,
|
|
38975
|
-
data: message.data,
|
|
38976
|
-
seq,
|
|
38977
|
-
subject: message.subject,
|
|
38978
|
-
followed,
|
|
38979
|
-
time: message.time,
|
|
38980
|
-
since: cursors.get(followed)?.since
|
|
38981
|
-
});
|
|
38982
|
-
} catch (thrown) {
|
|
38983
|
-
outcome = "failed";
|
|
38984
|
-
error = messageFor(thrown);
|
|
38985
|
-
}
|
|
38986
|
-
if (!alive())
|
|
38987
|
-
return "stopped";
|
|
38988
|
-
if (outcome === "shown") {
|
|
38989
|
-
failures.delete(seq);
|
|
38990
|
-
record2(identity);
|
|
38991
|
-
await flush(alive);
|
|
38992
|
-
return "done";
|
|
38993
|
-
}
|
|
38994
|
-
if (outcome === "suppressed") {
|
|
38995
|
-
failures.delete(seq);
|
|
38996
|
-
return "done";
|
|
38997
|
-
}
|
|
38998
|
-
if (outcome === "queued") {
|
|
38999
|
-
failures.delete(seq);
|
|
39000
|
-
return "hole";
|
|
39001
|
-
}
|
|
39002
|
-
const count = (failure?.count ?? 0) + 1;
|
|
39003
|
-
failures.set(seq, { count, error });
|
|
39004
|
-
if (count >= REPLAY_FAILURES_BEFORE_NOTICE)
|
|
39005
|
-
return giveUp(error);
|
|
39006
|
-
log(`replay: could not show stored message ${seq} (${envelope.event_id}): ${error}`);
|
|
39007
|
-
return "hole";
|
|
39008
|
-
};
|
|
39009
|
-
const listenerFailed = (error) => {
|
|
39010
|
-
if (error instanceof EnvoyApiError) {
|
|
39011
|
-
const status = error.details.status;
|
|
39012
|
-
if (status === 404) {
|
|
39013
|
-
if (listenerNoticed === "not_served")
|
|
39014
|
-
return;
|
|
39015
|
-
listenerNoticed = "not_served";
|
|
39016
|
-
notify({
|
|
39017
|
-
kind: "not_served",
|
|
39018
|
-
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."
|
|
39019
|
-
});
|
|
39020
|
-
return;
|
|
39021
|
-
}
|
|
39022
|
-
if (status === 503 && error.code === REPLAY_UNAVAILABLE_CODE || status === 401 || status === 403) {
|
|
39023
|
-
const key = `unavailable:${status}:${error.message}`;
|
|
39024
|
-
if (listenerNoticed === key)
|
|
39025
|
-
return;
|
|
39026
|
-
listenerNoticed = key;
|
|
39027
|
-
notify({
|
|
39028
|
-
kind: "unavailable",
|
|
39029
|
-
status,
|
|
39030
|
-
error: error.message,
|
|
39031
|
-
message: `Envoy replay is unavailable (${status}: ${error.message}), so messages published while this session's connection is down are not recovered until it answers.`
|
|
39032
|
-
});
|
|
39033
|
-
return;
|
|
39034
|
-
}
|
|
39035
|
-
}
|
|
39036
|
-
log("replay: the listener's replay failed; the next trigger tries again", error);
|
|
39037
|
-
};
|
|
39038
|
-
const streamReplaced = (stream) => {
|
|
39039
|
-
if (stream.id === undefined) {
|
|
39040
|
-
return streamCreated !== undefined && streamCreated !== "" && stream.created !== streamCreated;
|
|
39041
|
-
}
|
|
39042
|
-
return streamID !== undefined && streamID !== "" && stream.id !== streamID;
|
|
39043
|
-
};
|
|
39044
|
-
const streamMovedBack = (stream) => {
|
|
39045
|
-
for (const cursor of cursors.values()) {
|
|
39046
|
-
if (cursor.after !== undefined && cursor.after > stream.last_seq)
|
|
39047
|
-
return true;
|
|
39048
|
-
}
|
|
39049
|
-
return false;
|
|
39050
|
-
};
|
|
39051
|
-
const sweepOnce = async () => {
|
|
39052
|
-
const binding = bind();
|
|
39053
|
-
if (binding === undefined)
|
|
39054
|
-
return;
|
|
39055
|
-
const { sessionID, alive } = binding;
|
|
39056
|
-
syncFollowed();
|
|
39057
|
-
const readings = new Map;
|
|
39058
|
-
for (const [subject, cursor] of cursors) {
|
|
39059
|
-
readings.set(subject, {
|
|
39060
|
-
read: cursor.from_start === undefined ? cursor.after : 0,
|
|
39061
|
-
more: true
|
|
39062
|
-
});
|
|
39063
|
-
}
|
|
39064
|
-
const buffer = new Map;
|
|
39065
|
-
const holes = new Map;
|
|
39066
|
-
let gapNoticed = false;
|
|
39067
|
-
if (pending.size > 0) {
|
|
39068
|
-
for (const kind of [...pending].sort()) {
|
|
39069
|
-
if (kind === "retention_gap")
|
|
39070
|
-
gapNoticed = true;
|
|
39071
|
-
tell(kind);
|
|
39072
|
-
}
|
|
39073
|
-
await flush(alive);
|
|
39074
|
-
if (!alive())
|
|
39075
|
-
return;
|
|
39076
|
-
}
|
|
39077
|
-
if (consumerMode)
|
|
39078
|
-
return;
|
|
39079
|
-
for (let page = 0;page < REPLAY_PAGES_PER_SWEEP; page += 1) {
|
|
39080
|
-
let handledAny = false;
|
|
39081
|
-
const asking = [...readings].filter(([, reading]) => reading.more).sort(([, a], [, b]) => (a.read ?? -1) - (b.read ?? -1)).slice(0, REPLAY_MAX_SUBJECTS);
|
|
39082
|
-
if (asking.length === 0)
|
|
39083
|
-
break;
|
|
39084
|
-
let response;
|
|
39085
|
-
try {
|
|
39086
|
-
response = await transport.replay({
|
|
39087
|
-
sessionID,
|
|
39088
|
-
subjects: asking.map(([subject, reading]) => reading.read === undefined ? { subject } : { subject, after: reading.read }),
|
|
39089
|
-
...options.maxMessages === undefined ? {} : { maxMessages: options.maxMessages }
|
|
39090
|
-
});
|
|
39091
|
-
} catch (error) {
|
|
39092
|
-
if (alive()) {
|
|
39093
|
-
answered.clear();
|
|
39094
|
-
listenerFailed(error);
|
|
39095
|
-
}
|
|
39096
|
-
return;
|
|
39097
|
-
}
|
|
39098
|
-
if (!alive())
|
|
39099
|
-
return;
|
|
39100
|
-
listenerNoticed = undefined;
|
|
39101
|
-
for (const result of response.subjects) {
|
|
39102
|
-
if (result.refused === undefined)
|
|
39103
|
-
answered.add(result.subject);
|
|
39104
|
-
else
|
|
39105
|
-
answered.delete(result.subject);
|
|
39106
|
-
}
|
|
39107
|
-
const { stream } = response;
|
|
39108
|
-
const replaced = streamReplaced(stream);
|
|
39109
|
-
streamID = stream.id ?? (replaced ? undefined : streamID);
|
|
39110
|
-
streamCreated = stream.created;
|
|
39111
|
-
if (replaced) {
|
|
39112
|
-
const at = now();
|
|
39113
|
-
for (const subject of cursors.keys()) {
|
|
39114
|
-
cursors.set(subject, { since: stream.last_seq, after: stream.last_seq });
|
|
39115
|
-
cursorStarts.set(subject, at);
|
|
39116
|
-
}
|
|
39117
|
-
failures.clear();
|
|
39118
|
-
pending.add("stream_recreated");
|
|
39119
|
-
await flush(alive);
|
|
39120
|
-
if (!alive())
|
|
39121
|
-
return;
|
|
39122
|
-
tell("stream_recreated");
|
|
39123
|
-
await flush(alive);
|
|
39124
|
-
return;
|
|
39125
|
-
}
|
|
39126
|
-
if (streamMovedBack(stream)) {
|
|
39127
|
-
const from = Math.max(0, stream.first_seq - 1);
|
|
39128
|
-
for (const [subject, cursor] of cursors) {
|
|
39129
|
-
if (cursor.after === undefined)
|
|
39130
|
-
continue;
|
|
39131
|
-
cursors.set(subject, { ...cursor, after: from });
|
|
39132
|
-
const reading = readings.get(subject);
|
|
39133
|
-
if (reading !== undefined) {
|
|
39134
|
-
reading.read = from;
|
|
39135
|
-
reading.more = true;
|
|
39136
|
-
}
|
|
39137
|
-
}
|
|
39138
|
-
buffer.clear();
|
|
39139
|
-
holes.clear();
|
|
39140
|
-
failures.clear();
|
|
39141
|
-
pending.add("stream_moved_back");
|
|
39142
|
-
await flush(alive, true);
|
|
39143
|
-
if (!alive())
|
|
39144
|
-
return;
|
|
39145
|
-
tell("stream_moved_back");
|
|
39146
|
-
await flush(alive);
|
|
39147
|
-
if (!alive())
|
|
39148
|
-
return;
|
|
39149
|
-
continue;
|
|
39150
|
-
}
|
|
39151
|
-
for (const [, reading] of asking)
|
|
39152
|
-
reading.more = false;
|
|
39153
|
-
for (const result of response.subjects) {
|
|
39154
|
-
const reading = readings.get(result.subject);
|
|
39155
|
-
const markedAt = cursors.get(result.subject)?.from_start;
|
|
39156
|
-
if (reading === undefined || markedAt === undefined || result.refused !== undefined) {
|
|
39157
|
-
continue;
|
|
39158
|
-
}
|
|
39159
|
-
const start = Math.max(0, stream.first_seq - 1);
|
|
39160
|
-
cursors.set(result.subject, { since: start, after: start });
|
|
39161
|
-
cursorStarts.set(result.subject, now());
|
|
39162
|
-
if (now() - markedAt < DELIVERY_DUPLICATE_WINDOW_MS)
|
|
39163
|
-
reading.read = start;
|
|
39164
|
-
}
|
|
39165
|
-
let gapped = false;
|
|
39166
|
-
for (const result of response.subjects) {
|
|
39167
|
-
const reading = readings.get(result.subject);
|
|
39168
|
-
if (reading?.read === undefined || result.refused !== undefined)
|
|
39169
|
-
continue;
|
|
39170
|
-
if (reading.read >= stream.first_seq - 1)
|
|
39171
|
-
continue;
|
|
39172
|
-
gapped = true;
|
|
39173
|
-
reading.read = stream.first_seq - 1;
|
|
39174
|
-
const cursor = cursors.get(result.subject);
|
|
39175
|
-
if (cursor?.after !== undefined && cursor.after < reading.read) {
|
|
39176
|
-
cursors.set(result.subject, { ...cursor, after: reading.read });
|
|
39177
|
-
}
|
|
39178
|
-
}
|
|
39179
|
-
if (gapped) {
|
|
39180
|
-
if (!gapNoticed)
|
|
39181
|
-
pending.add("retention_gap");
|
|
39182
|
-
await flush(alive, true);
|
|
39183
|
-
if (!alive())
|
|
39184
|
-
return;
|
|
39185
|
-
if (pending.has("retention_gap")) {
|
|
39186
|
-
gapNoticed = true;
|
|
39187
|
-
tell("retention_gap");
|
|
39188
|
-
await flush(alive);
|
|
39189
|
-
}
|
|
39190
|
-
}
|
|
39191
|
-
for (const result of response.subjects) {
|
|
39192
|
-
const reading = readings.get(result.subject);
|
|
39193
|
-
if (reading === undefined || result.refused !== undefined)
|
|
39194
|
-
continue;
|
|
39195
|
-
if (reading.read === undefined) {
|
|
39196
|
-
const cursor = cursors.get(result.subject);
|
|
39197
|
-
if (cursor !== undefined && cursor.after === undefined) {
|
|
39198
|
-
cursors.set(result.subject, { since: result.next_after, after: result.next_after });
|
|
39199
|
-
cursorStarts.set(result.subject, now());
|
|
39200
|
-
}
|
|
39201
|
-
reading.read = result.next_after;
|
|
39202
|
-
continue;
|
|
39203
|
-
}
|
|
39204
|
-
for (const message of result.messages) {
|
|
39205
|
-
if (message.seq <= reading.read)
|
|
39206
|
-
continue;
|
|
39207
|
-
const buffered = buffer.get(message.seq);
|
|
39208
|
-
if (buffered === undefined) {
|
|
39209
|
-
buffer.set(message.seq, { message, subjects: [result.subject] });
|
|
39210
|
-
} else if (!buffered.subjects.includes(result.subject)) {
|
|
39211
|
-
buffered.subjects.push(result.subject);
|
|
39212
|
-
}
|
|
39213
|
-
}
|
|
39214
|
-
reading.read = Math.max(reading.read, result.next_after);
|
|
39215
|
-
reading.more = result.more;
|
|
39216
|
-
}
|
|
39217
|
-
let bound = Number.POSITIVE_INFINITY;
|
|
39218
|
-
for (const reading of readings.values()) {
|
|
39219
|
-
if (reading.more && reading.read !== undefined)
|
|
39220
|
-
bound = Math.min(bound, reading.read);
|
|
39221
|
-
}
|
|
39222
|
-
const ready = [...buffer.keys()].filter((seq) => seq <= bound).sort((a, b) => a - b);
|
|
39223
|
-
for (const seq of ready) {
|
|
39224
|
-
const buffered = buffer.get(seq);
|
|
39225
|
-
if (buffered === undefined)
|
|
39226
|
-
continue;
|
|
39227
|
-
buffer.delete(seq);
|
|
39228
|
-
if (!buffered.subjects.some((subject) => cursors.has(subject)))
|
|
39229
|
-
continue;
|
|
39230
|
-
const handled = await handle(seq, buffered, alive);
|
|
39231
|
-
if (handled === "stopped")
|
|
39232
|
-
return;
|
|
39233
|
-
if (handled === "done")
|
|
39234
|
-
handledAny = true;
|
|
39235
|
-
if (handled === "hole") {
|
|
39236
|
-
for (const subject of buffered.subjects) {
|
|
39237
|
-
if (!holes.has(subject))
|
|
39238
|
-
holes.set(subject, seq);
|
|
39239
|
-
}
|
|
39240
|
-
}
|
|
39241
|
-
}
|
|
39242
|
-
if (!alive())
|
|
39243
|
-
return;
|
|
39244
|
-
for (const [subject, reading] of readings) {
|
|
39245
|
-
const cursor = cursors.get(subject);
|
|
39246
|
-
if (cursor?.after === undefined || reading.read === undefined)
|
|
39247
|
-
continue;
|
|
39248
|
-
let after = Math.min(reading.read, bound);
|
|
39249
|
-
const hole = holes.get(subject);
|
|
39250
|
-
if (hole !== undefined)
|
|
39251
|
-
after = Math.min(after, hole - 1);
|
|
39252
|
-
if (after > cursor.after)
|
|
39253
|
-
cursors.set(subject, { ...cursor, after });
|
|
39254
|
-
}
|
|
39255
|
-
await flush(alive, handledAny);
|
|
39256
|
-
if (![...readings.values()].some((reading) => reading.more))
|
|
39257
|
-
break;
|
|
39258
|
-
}
|
|
39259
|
-
};
|
|
39260
|
-
const runSweep = async () => {
|
|
39261
|
-
try {
|
|
39262
|
-
await sweepOnce();
|
|
39263
|
-
} catch (error) {
|
|
39264
|
-
log("replay: a sweep failed", error);
|
|
39265
|
-
}
|
|
39266
|
-
};
|
|
39267
|
-
const sweep = () => {
|
|
39268
|
-
if (running === undefined) {
|
|
39269
|
-
running = runSweep().finally(() => {
|
|
39270
|
-
running = undefined;
|
|
39271
|
-
});
|
|
39272
|
-
return running;
|
|
39273
|
-
}
|
|
39274
|
-
rerun ??= running.then(() => {
|
|
39275
|
-
rerun = undefined;
|
|
39276
|
-
return sweep();
|
|
39277
|
-
});
|
|
39278
|
-
return rerun;
|
|
39279
|
-
};
|
|
39280
|
-
const started = (cursor) => cursor?.after !== undefined || cursor?.from_start !== undefined;
|
|
39281
|
-
const startOnce = async () => {
|
|
39282
|
-
const binding = bind();
|
|
39283
|
-
if (binding === undefined)
|
|
39284
|
-
return;
|
|
39285
|
-
const { sessionID, alive } = binding;
|
|
39286
|
-
const unstarted = [...new Set(host.followedSubjects())].filter((subject) => !started(cursors.get(subject)));
|
|
39287
|
-
let changed = false;
|
|
39288
|
-
for (let index = 0;index < unstarted.length; index += REPLAY_MAX_SUBJECTS) {
|
|
39289
|
-
let response;
|
|
39290
|
-
try {
|
|
39291
|
-
response = await transport.replay({
|
|
39292
|
-
sessionID,
|
|
39293
|
-
subjects: unstarted.slice(index, index + REPLAY_MAX_SUBJECTS).map((subject) => ({ subject })),
|
|
39294
|
-
timeoutMs: START_CURSORS_TIMEOUT_MS
|
|
39295
|
-
});
|
|
39296
|
-
} catch (error) {
|
|
39297
|
-
if (!alive())
|
|
39298
|
-
return;
|
|
39299
|
-
const own = `${AGENT_TOPIC_PREFIX}${sessionID}`;
|
|
39300
|
-
const marked = unstarted.includes(own) && !started(cursors.get(own));
|
|
39301
|
-
if (marked) {
|
|
39302
|
-
cursors.set(own, { from_start: now() });
|
|
39303
|
-
changed = true;
|
|
39304
|
-
}
|
|
39305
|
-
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);
|
|
39306
|
-
break;
|
|
39307
|
-
}
|
|
39308
|
-
if (!alive())
|
|
39309
|
-
return;
|
|
39310
|
-
const { stream } = response;
|
|
39311
|
-
if (streamReplaced(stream))
|
|
39312
|
-
break;
|
|
39313
|
-
streamID = stream.id ?? streamID;
|
|
39314
|
-
streamCreated = stream.created;
|
|
39315
|
-
const at = now();
|
|
39316
|
-
for (const result of response.subjects) {
|
|
39317
|
-
if (result.refused !== undefined || started(cursors.get(result.subject)))
|
|
39318
|
-
continue;
|
|
39319
|
-
cursors.set(result.subject, { since: result.next_after, after: result.next_after });
|
|
39320
|
-
cursorStarts.set(result.subject, at);
|
|
39321
|
-
changed = true;
|
|
39322
|
-
}
|
|
39323
|
-
}
|
|
39324
|
-
if (changed)
|
|
39325
|
-
await flush(alive, true);
|
|
39326
|
-
};
|
|
39327
|
-
const startCursors = async () => {
|
|
39328
|
-
while (running !== undefined)
|
|
39329
|
-
await running;
|
|
39330
|
-
running = startOnce().catch((error) => log("replay: starting the cursors failed", error)).finally(() => {
|
|
39331
|
-
running = undefined;
|
|
39332
|
-
});
|
|
39333
|
-
await running;
|
|
39334
|
-
};
|
|
39335
|
-
return {
|
|
39336
|
-
sweep,
|
|
39337
|
-
startCursors,
|
|
39338
|
-
startPending: () => [...cursors.values()].some((cursor) => cursor.from_start !== undefined),
|
|
39339
|
-
setConsumerMode(on) {
|
|
39340
|
-
consumerMode = on;
|
|
39341
|
-
},
|
|
39342
|
-
async followedChanged() {
|
|
39343
|
-
const alive = bind()?.alive;
|
|
39344
|
-
if (alive === undefined)
|
|
39345
|
-
return;
|
|
39346
|
-
try {
|
|
39347
|
-
syncFollowed();
|
|
39348
|
-
await flush(alive);
|
|
39349
|
-
} catch (error) {
|
|
39350
|
-
log("replay: could not take the followed subjects", error);
|
|
39351
|
-
}
|
|
39352
|
-
},
|
|
39353
|
-
delivered: (frame) => ledger.has(replayLedgerIdentity(frame)),
|
|
39354
|
-
async recordDelivered(frame) {
|
|
39355
|
-
const alive = bind()?.alive;
|
|
39356
|
-
if (alive === undefined)
|
|
39357
|
-
return;
|
|
39358
|
-
record2(replayLedgerIdentity(frame));
|
|
39359
|
-
await flush(alive);
|
|
39360
|
-
},
|
|
39361
|
-
async recordDeliveredFor(sessionID, frame) {
|
|
39362
|
-
const alive = bindTo(sessionID, writeSession)?.alive;
|
|
39363
|
-
if (alive === undefined)
|
|
39364
|
-
return false;
|
|
39365
|
-
record2(replayLedgerIdentity(frame));
|
|
39366
|
-
return await flush(alive);
|
|
39367
|
-
},
|
|
39368
|
-
async liveFailed(sessionID, followed, envelope, error, receivedAt) {
|
|
39369
|
-
const started = cursorStarts.get(followed);
|
|
39370
|
-
if (!isRoleForward(envelope) && answered.has(followed) && cursors.get(followed)?.after !== undefined && (started === undefined || started <= receivedAt)) {
|
|
39371
|
-
return;
|
|
39372
|
-
}
|
|
39373
|
-
const alive = bindTo(sessionID, currentSession)?.alive;
|
|
39374
|
-
if (alive === undefined) {
|
|
39375
|
-
log("replay: a failed frame was not reported here; the session it names is closed");
|
|
39376
|
-
return;
|
|
39377
|
-
}
|
|
39378
|
-
try {
|
|
39379
|
-
await showFailureNotice(failureNotice(envelope, inboundTimestamp(envelope.issued_at), messageFor(error)), alive);
|
|
39380
|
-
} catch (thrown) {
|
|
39381
|
-
log("replay: could not report a failed live frame", thrown);
|
|
39382
|
-
}
|
|
39383
|
-
},
|
|
39384
|
-
followedBefore: (topic, seq) => {
|
|
39385
|
-
const since = cursors.get(topic)?.since;
|
|
39386
|
-
return since !== undefined && seq > since;
|
|
39387
|
-
},
|
|
39388
|
-
restore(snapshot) {
|
|
39389
|
-
epoch += 1;
|
|
39390
|
-
ledger.restore(snapshot.ledger);
|
|
39391
|
-
cursors.clear();
|
|
39392
|
-
cursorStarts.clear();
|
|
39393
|
-
streamID = snapshot.state?.stream_id;
|
|
39394
|
-
streamCreated = snapshot.state?.stream_created;
|
|
39395
|
-
pending.clear();
|
|
39396
|
-
for (const kind of snapshot.state?.notices ?? []) {
|
|
39397
|
-
const known = ReplayPendingNoticeSchema.safeParse(kind);
|
|
39398
|
-
if (known.success)
|
|
39399
|
-
pending.add(known.data);
|
|
39400
|
-
}
|
|
39401
|
-
for (const [subject, cursor] of Object.entries(snapshot.state?.subjects ?? {})) {
|
|
39402
|
-
cursors.set(subject, { ...cursor });
|
|
39403
|
-
}
|
|
39404
|
-
writtenState = snapshot.state === undefined ? undefined : stateJSON();
|
|
39405
|
-
writtenShape = snapshot.state === undefined ? undefined : stateJSON(false);
|
|
39406
|
-
writtenAt = undefined;
|
|
39407
|
-
unwritten = [];
|
|
39408
|
-
failures.clear();
|
|
39409
|
-
listenerNoticed = undefined;
|
|
39410
|
-
answered.clear();
|
|
39411
|
-
},
|
|
39412
|
-
state: () => JSON.parse(stateJSON())
|
|
39413
|
-
};
|
|
39414
|
-
}
|
|
39415
|
-
function replaySuppressed(rendered) {
|
|
39416
|
-
return rendered.skip || rendered.malformedDelivery === true;
|
|
39417
|
-
}
|
|
39418
|
-
var REPLAYED_SUFFIX = "while this session's connection was down.";
|
|
39419
|
-
function replayedText(content, publishedAt) {
|
|
39420
|
-
return `${content}
|
|
39421
|
-
Published at ${publishedAt} ${REPLAYED_SUFFIX}`;
|
|
39422
|
-
}
|
|
39423
|
-
function failureNoticeFields(notice) {
|
|
39424
|
-
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.";
|
|
39425
|
-
return {
|
|
39426
|
-
notice: "message not shown",
|
|
39427
|
-
event_id: notice.eventId,
|
|
39428
|
-
from: notice.sender,
|
|
39429
|
-
summary: notice.summary,
|
|
39430
|
-
published_at: notice.publishedAt,
|
|
39431
|
-
...notice.subject === undefined ? {} : { subject: notice.subject },
|
|
39432
|
-
error: notice.error,
|
|
39433
|
-
detail: `This session could not be shown this message, so it is not coming back on its own. ${readWith}`
|
|
39434
|
-
};
|
|
39435
|
-
}
|
|
39436
|
-
var REPLAY_NOTICE_NAMES = {
|
|
39437
|
-
stream_recreated: "stream recreated",
|
|
39438
|
-
stream_moved_back: "stream moved back"
|
|
39439
|
-
};
|
|
39440
|
-
function replayNoticeFields(notice) {
|
|
39441
|
-
return {
|
|
39442
|
-
notice: REPLAY_NOTICE_NAMES[notice.kind] ?? "messages may be missing",
|
|
39443
|
-
detail: notice.message
|
|
39444
|
-
};
|
|
39445
|
-
}
|
|
39446
|
-
function envoyNoticeText(fields) {
|
|
39447
|
-
return encode5({ envoy: fields });
|
|
39448
|
-
}
|
|
39449
|
-
var PRIVATE_STREAM_SUBJECTS = [
|
|
39450
|
-
`${AGENT_TOPIC_PREFIX}>`,
|
|
39451
|
-
`${LEGION_NOTICE_TOPIC_PREFIX}>`,
|
|
39452
|
-
`${EXCEPTION_TOPIC_PREFIX}${AGENT_TOPIC_PREFIX}>`
|
|
39453
|
-
];
|
|
39454
|
-
function subjectsOverlap(a, b) {
|
|
39455
|
-
const aTokens = a.split(".");
|
|
39456
|
-
const bTokens = b.split(".");
|
|
39457
|
-
for (let index = 0;index < aTokens.length && index < bTokens.length; index += 1) {
|
|
39458
|
-
const aToken = aTokens[index];
|
|
39459
|
-
const bToken = bTokens[index];
|
|
39460
|
-
if (aToken === ">" || bToken === ">")
|
|
39461
|
-
return true;
|
|
39462
|
-
if (aToken !== "*" && bToken !== "*" && aToken !== bToken)
|
|
39463
|
-
return false;
|
|
39464
|
-
}
|
|
39465
|
-
return aTokens.length === bTokens.length;
|
|
39466
|
-
}
|
|
39467
|
-
function reachesPrivateStreamSubject(ownAgentSubject, topic) {
|
|
39468
|
-
if (!PRIVATE_STREAM_SUBJECTS.some((subject) => subjectsOverlap(topic, subject)))
|
|
39469
|
-
return false;
|
|
39470
|
-
return topic !== ownAgentSubject || /[*>]/.test(ownAgentSubject);
|
|
39471
|
-
}
|
|
39472
|
-
function replayFollowedSubjects(ownAgentSubject, topics, heldForRole = () => false) {
|
|
39473
|
-
const followed = [...topics].filter((topic) => !topic.startsWith(ROLE_TOPIC_PREFIX) && !reachesPrivateStreamSubject(ownAgentSubject, topic) && !heldForRole(topic));
|
|
39474
|
-
return [...new Set([ownAgentSubject, ...followed])];
|
|
39475
|
-
}
|
|
39476
|
-
function rememberedTopics(state) {
|
|
39477
|
-
return Object.keys(state?.subjects ?? {}).filter((topic) => !topic.startsWith(AGENT_TOPIC_PREFIX) && !topic.startsWith(ROLE_TOPIC_PREFIX));
|
|
39478
|
-
}
|
|
39479
|
-
async function closeReplayedRemoval(frame, host) {
|
|
39480
|
-
const closed = (subscriptionRemovedTopics(frame.data, host.sessionID) ?? []).filter((topic) => host.engine.followedBefore(topic, frame.seq) && host.close(topic));
|
|
39481
|
-
if (closed.length === 0)
|
|
39482
|
-
return closed;
|
|
39483
|
-
const unregistering = host.unregister(closed);
|
|
39484
|
-
await host.followedChanged();
|
|
39485
|
-
await unregistering;
|
|
39486
|
-
return closed;
|
|
39487
|
-
}
|
|
39488
|
-
function routeReplayNotice(notice, routes) {
|
|
39489
|
-
if (notice.kind === "not_served" || notice.kind === "unavailable") {
|
|
39490
|
-
routes.warn(notice.message);
|
|
39491
|
-
return;
|
|
39492
|
-
}
|
|
39493
|
-
routes.card(envoyNoticeText(replayNoticeFields(notice)));
|
|
39494
|
-
}
|
|
39495
|
-
function isRoleForward(envelope) {
|
|
39496
|
-
return envelope.dedupe_key?.startsWith(ROLE_FORWARD_KEY_PREFIX) === true || envelope.topic?.startsWith(ROLE_TOPIC_PREFIX) === true;
|
|
39497
|
-
}
|
|
39498
|
-
function replayLedgerIdentity(frame) {
|
|
39499
|
-
return {
|
|
39500
|
-
...frame.event_id === undefined || frame.event_id === "" ? {} : { event_id: frame.event_id },
|
|
39501
|
-
...frame.dedupe_key === undefined || !dedupeKeyNamesItsEvent(frame) ? {} : { dedupe_key: frame.dedupe_key }
|
|
38963
|
+
const search = new URLSearchParams;
|
|
38964
|
+
if (input.directory !== undefined)
|
|
38965
|
+
search.set("dir", input.directory);
|
|
38966
|
+
if (input.title !== undefined)
|
|
38967
|
+
search.set("title", input.title);
|
|
38968
|
+
if (input.include !== undefined)
|
|
38969
|
+
search.set("include", input.include);
|
|
38970
|
+
const query = search.size === 0 ? "" : `?${search.toString()}`;
|
|
38971
|
+
return SessionWireSchema.array().parse(JSON.parse(await request(`/v1/sessions${query}`, {})));
|
|
38972
|
+
}
|
|
39502
38973
|
};
|
|
39503
38974
|
}
|
|
39504
|
-
|
|
39505
|
-
|
|
39506
|
-
|
|
39507
|
-
|
|
39508
|
-
let parsed;
|
|
39509
|
-
try {
|
|
39510
|
-
parsed = JSON.parse(data);
|
|
39511
|
-
} catch {
|
|
39512
|
-
return;
|
|
39513
|
-
}
|
|
39514
|
-
const result = StoredEnvelopeSchema.safeParse(parsed);
|
|
39515
|
-
return result.success ? result.data : undefined;
|
|
38975
|
+
function waitForRetry(delayMs) {
|
|
38976
|
+
const { promise, resolve } = Promise.withResolvers();
|
|
38977
|
+
setTimeout(resolve, delayMs);
|
|
38978
|
+
return promise;
|
|
39516
38979
|
}
|
|
39517
|
-
function
|
|
39518
|
-
let entries = new Set;
|
|
39519
|
-
const byEvent = new Map;
|
|
39520
|
-
const byKey = new Map;
|
|
39521
|
-
const drop = (entry) => {
|
|
39522
|
-
entries.delete(entry);
|
|
39523
|
-
if (entry.event_id !== undefined && byEvent.get(entry.event_id) === entry) {
|
|
39524
|
-
byEvent.delete(entry.event_id);
|
|
39525
|
-
}
|
|
39526
|
-
if (entry.dedupe_key !== undefined && byKey.get(entry.dedupe_key) === entry) {
|
|
39527
|
-
byKey.delete(entry.dedupe_key);
|
|
39528
|
-
}
|
|
39529
|
-
};
|
|
39530
|
-
const add = (entry) => {
|
|
39531
|
-
if (entries.size >= REPLAY_LEDGER_LIMIT) {
|
|
39532
|
-
const oldest = entries.values().next();
|
|
39533
|
-
if (oldest.done !== true)
|
|
39534
|
-
drop(oldest.value);
|
|
39535
|
-
}
|
|
39536
|
-
entries.add(entry);
|
|
39537
|
-
if (entry.event_id !== undefined)
|
|
39538
|
-
byEvent.set(entry.event_id, entry);
|
|
39539
|
-
if (entry.dedupe_key !== undefined)
|
|
39540
|
-
byKey.set(entry.dedupe_key, entry);
|
|
39541
|
-
};
|
|
39542
|
-
const expire = () => {
|
|
39543
|
-
const at = now();
|
|
39544
|
-
for (const entry of entries) {
|
|
39545
|
-
if (at - entry.at < REPLAY_LEDGER_TTL_MS)
|
|
39546
|
-
break;
|
|
39547
|
-
drop(entry);
|
|
39548
|
-
}
|
|
39549
|
-
};
|
|
39550
|
-
const has = (identity) => {
|
|
39551
|
-
expire();
|
|
39552
|
-
return identity.event_id !== undefined && byEvent.has(identity.event_id) || identity.dedupe_key !== undefined && byKey.has(identity.dedupe_key);
|
|
39553
|
-
};
|
|
38980
|
+
function messageMetadata(input) {
|
|
39554
38981
|
return {
|
|
39555
|
-
|
|
39556
|
-
|
|
39557
|
-
|
|
39558
|
-
|
|
39559
|
-
|
|
39560
|
-
return;
|
|
39561
|
-
const entry = { ...identity, at: now() };
|
|
39562
|
-
add(entry);
|
|
39563
|
-
return entry;
|
|
39564
|
-
},
|
|
39565
|
-
restore(restored) {
|
|
39566
|
-
entries = new Set;
|
|
39567
|
-
byEvent.clear();
|
|
39568
|
-
byKey.clear();
|
|
39569
|
-
const at = now();
|
|
39570
|
-
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);
|
|
39571
|
-
for (const entry of kept)
|
|
39572
|
-
add({ ...entry });
|
|
39573
|
-
},
|
|
39574
|
-
list() {
|
|
39575
|
-
expire();
|
|
39576
|
-
return [...entries];
|
|
39577
|
-
}
|
|
38982
|
+
...input.inReplyTo === undefined ? {} : { in_reply_to: input.inReplyTo },
|
|
38983
|
+
...input.supersedes === undefined ? {} : { supersedes: input.supersedes },
|
|
38984
|
+
...input.urgency === undefined ? {} : { urgency: input.urgency },
|
|
38985
|
+
...input.expectsReply === undefined ? {} : { expects_reply: input.expectsReply },
|
|
38986
|
+
...input.expiresAt === undefined ? {} : { expires_at: input.expiresAt }
|
|
39578
38987
|
};
|
|
39579
38988
|
}
|
|
38989
|
+
function sourceSession(sessionID) {
|
|
38990
|
+
return sessionID === undefined || sessionID === "" ? {} : { source_session: sessionID };
|
|
38991
|
+
}
|
|
39580
38992
|
|
|
39581
38993
|
// ../envoy-client/src/consumer-delivery.ts
|
|
39582
38994
|
var DELIVER_SUBJECT_PREFIX = "notifications.envoy.deliver.";
|
|
@@ -39681,6 +39093,7 @@ function every(ms, callback) {
|
|
|
39681
39093
|
}
|
|
39682
39094
|
function createConsumerDelivery(options) {
|
|
39683
39095
|
const { host, ledger, sessionID } = options;
|
|
39096
|
+
const render = options.render ?? renderInbound;
|
|
39684
39097
|
const now = options.now ?? Date.now;
|
|
39685
39098
|
const repeat = options.every ?? every;
|
|
39686
39099
|
const ownSubject = agentSubject(sessionID);
|
|
@@ -39692,9 +39105,9 @@ function createConsumerDelivery(options) {
|
|
|
39692
39105
|
let registeredResume;
|
|
39693
39106
|
let gapTold = false;
|
|
39694
39107
|
let closed = false;
|
|
39695
|
-
let relayed;
|
|
39696
39108
|
let persisted = JSON.stringify({ follows: {} });
|
|
39697
39109
|
const entries = new Map;
|
|
39110
|
+
const troubled = new Map;
|
|
39698
39111
|
const queue = [];
|
|
39699
39112
|
let blocking;
|
|
39700
39113
|
let pumping = false;
|
|
@@ -39716,6 +39129,7 @@ function createConsumerDelivery(options) {
|
|
|
39716
39129
|
streamID = id;
|
|
39717
39130
|
held = new Set;
|
|
39718
39131
|
written = undefined;
|
|
39132
|
+
troubled.clear();
|
|
39719
39133
|
};
|
|
39720
39134
|
const tellReplacedResume = (id) => {
|
|
39721
39135
|
const asked = resumePoint() ?? registeredResume;
|
|
@@ -39736,18 +39150,6 @@ function createConsumerDelivery(options) {
|
|
|
39736
39150
|
}
|
|
39737
39151
|
return earliest;
|
|
39738
39152
|
};
|
|
39739
|
-
const followedOnCorePath = (frame) => {
|
|
39740
|
-
const state = ledger.state();
|
|
39741
|
-
if (state.stream_id !== frame.streamID)
|
|
39742
|
-
return false;
|
|
39743
|
-
for (const [topic, cursor] of Object.entries(state.subjects)) {
|
|
39744
|
-
if (cursor.since === undefined || frame.streamSeq <= cursor.since)
|
|
39745
|
-
continue;
|
|
39746
|
-
if (reaches(topic, frame.subject))
|
|
39747
|
-
return true;
|
|
39748
|
-
}
|
|
39749
|
-
return false;
|
|
39750
|
-
};
|
|
39751
39153
|
const settle = (entry, body) => {
|
|
39752
39154
|
if (entry.settled)
|
|
39753
39155
|
return;
|
|
@@ -39756,6 +39158,8 @@ function createConsumerDelivery(options) {
|
|
|
39756
39158
|
entries.delete(entry.key);
|
|
39757
39159
|
for (const reply of entry.replies)
|
|
39758
39160
|
send(reply, body);
|
|
39161
|
+
if (body === "done")
|
|
39162
|
+
troubled.delete(entry.key);
|
|
39759
39163
|
if (body === "done" && entry.frame.streamID === streamID) {
|
|
39760
39164
|
held.delete(entry.frame.streamSeq);
|
|
39761
39165
|
written = Math.max(written ?? 0, entry.frame.streamSeq);
|
|
@@ -39772,19 +39176,52 @@ function createConsumerDelivery(options) {
|
|
|
39772
39176
|
const failed = (entry, error) => {
|
|
39773
39177
|
if (entry.settled)
|
|
39774
39178
|
return;
|
|
39775
|
-
|
|
39179
|
+
const trouble = troubled.get(entry.key) ?? { failures: 0, givenUp: false };
|
|
39180
|
+
troubled.set(entry.key, trouble);
|
|
39181
|
+
if (trouble.givenUp) {
|
|
39182
|
+
settle(entry, "nak");
|
|
39183
|
+
return;
|
|
39184
|
+
}
|
|
39185
|
+
trouble.failures += 1;
|
|
39186
|
+
if (trouble.failures < RELAY_ATTEMPTS_BEFORE_FAILED) {
|
|
39776
39187
|
log(`frame ${entry.frame.streamSeq} failed; it comes again`, error);
|
|
39777
39188
|
settle(entry, "nak");
|
|
39778
39189
|
return;
|
|
39779
39190
|
}
|
|
39780
39191
|
log(`frame ${entry.frame.streamSeq} failed and does not come again; its session gets the notice`, error);
|
|
39781
|
-
|
|
39782
|
-
|
|
39783
|
-
|
|
39784
|
-
|
|
39785
|
-
|
|
39192
|
+
const goesBack = (why, thrown) => {
|
|
39193
|
+
trouble.givenUp = true;
|
|
39194
|
+
log(`frame ${entry.frame.streamSeq} ${why}; it goes back to the stream`, thrown);
|
|
39195
|
+
settle(entry, "nak");
|
|
39196
|
+
};
|
|
39197
|
+
let envelope;
|
|
39198
|
+
try {
|
|
39199
|
+
envelope = render(entry.frame.data, sessionID, entry.frame.subject).envelope;
|
|
39200
|
+
} catch (thrown) {
|
|
39201
|
+
goesBack("could not be read to report it", thrown);
|
|
39202
|
+
return;
|
|
39203
|
+
}
|
|
39204
|
+
if (envelope === undefined) {
|
|
39205
|
+
log(`frame ${entry.frame.streamSeq} carries no envelope to report; it is dropped`);
|
|
39206
|
+
settle(entry, "done");
|
|
39207
|
+
return;
|
|
39208
|
+
}
|
|
39209
|
+
let telling;
|
|
39210
|
+
try {
|
|
39211
|
+
telling = ledger.liveFailed(sessionID, envelope, error);
|
|
39212
|
+
} catch (thrown) {
|
|
39213
|
+
goesBack("could not be reported", thrown);
|
|
39214
|
+
return;
|
|
39215
|
+
}
|
|
39216
|
+
telling.then((told) => {
|
|
39217
|
+
if (told) {
|
|
39218
|
+
settle(entry, "done");
|
|
39219
|
+
return;
|
|
39220
|
+
}
|
|
39221
|
+
goesBack("was reported to nobody");
|
|
39222
|
+
}, (thrown) => {
|
|
39223
|
+
goesBack("could not be reported", thrown);
|
|
39786
39224
|
});
|
|
39787
|
-
settle(entry, "done");
|
|
39788
39225
|
};
|
|
39789
39226
|
const handOff = (entry) => {
|
|
39790
39227
|
const handle = {
|
|
@@ -39865,7 +39302,7 @@ function createConsumerDelivery(options) {
|
|
|
39865
39302
|
return;
|
|
39866
39303
|
}
|
|
39867
39304
|
const since = followedAt(frame.subject);
|
|
39868
|
-
const unfollowed =
|
|
39305
|
+
const unfollowed = since === undefined || frame.storedAtMs < since - FOLLOW_CLOCK_ALLOWANCE_MS;
|
|
39869
39306
|
const identity = unfollowed ? undefined : parseIdentity(frame.data);
|
|
39870
39307
|
if (unfollowed || alreadyWritten(identity)) {
|
|
39871
39308
|
send(frame.reply, "done");
|
|
@@ -39901,20 +39338,6 @@ function createConsumerDelivery(options) {
|
|
|
39901
39338
|
return { stream_id: streamID, seq: Math.min(...held) - 1 };
|
|
39902
39339
|
return written === undefined ? undefined : { stream_id: streamID, seq: written };
|
|
39903
39340
|
};
|
|
39904
|
-
const seededResume = () => {
|
|
39905
|
-
const state = ledger.state();
|
|
39906
|
-
const stream = state.stream_id;
|
|
39907
|
-
if (stream === undefined)
|
|
39908
|
-
return;
|
|
39909
|
-
let lowest;
|
|
39910
|
-
for (const [subject, cursor] of Object.entries(state.subjects)) {
|
|
39911
|
-
if (cursor.after === undefined || !streamStores(subject))
|
|
39912
|
-
continue;
|
|
39913
|
-
if (lowest === undefined || cursor.after < lowest)
|
|
39914
|
-
lowest = cursor.after;
|
|
39915
|
-
}
|
|
39916
|
-
return lowest === undefined ? undefined : { stream_id: stream, seq: lowest };
|
|
39917
|
-
};
|
|
39918
39341
|
const snapshot = () => {
|
|
39919
39342
|
const resume = resumePoint();
|
|
39920
39343
|
return {
|
|
@@ -39940,7 +39363,7 @@ function createConsumerDelivery(options) {
|
|
|
39940
39363
|
return currentEpoch;
|
|
39941
39364
|
},
|
|
39942
39365
|
registration() {
|
|
39943
|
-
const resume = resumePoint()
|
|
39366
|
+
const resume = resumePoint();
|
|
39944
39367
|
registeredResume = resume;
|
|
39945
39368
|
return {
|
|
39946
39369
|
consumer: true,
|
|
@@ -39948,29 +39371,24 @@ function createConsumerDelivery(options) {
|
|
|
39948
39371
|
...resume === undefined ? {} : { resume }
|
|
39949
39372
|
};
|
|
39950
39373
|
},
|
|
39951
|
-
answered(answer
|
|
39952
|
-
if (answer.
|
|
39953
|
-
|
|
39954
|
-
|
|
39955
|
-
|
|
39956
|
-
|
|
39957
|
-
|
|
39958
|
-
|
|
39959
|
-
|
|
39960
|
-
|
|
39961
|
-
|
|
39962
|
-
gapTold = true;
|
|
39963
|
-
}
|
|
39964
|
-
relayed = new Set([...topics].filter(streamStores));
|
|
39965
|
-
} else {
|
|
39966
|
-
relayed = undefined;
|
|
39374
|
+
answered(answer) {
|
|
39375
|
+
if (answer.stream_id !== "" && answer.stream_id !== streamID) {
|
|
39376
|
+
tellReplacedResume(answer.stream_id);
|
|
39377
|
+
switchStream(answer.stream_id);
|
|
39378
|
+
}
|
|
39379
|
+
const floor = (answer.consumer_start ?? 0) - 1;
|
|
39380
|
+
if (answer.stream_id === streamID && floor > (written ?? -1))
|
|
39381
|
+
written = floor;
|
|
39382
|
+
if (answer.gap) {
|
|
39383
|
+
tellGap("retention_gap");
|
|
39384
|
+
gapTold = true;
|
|
39967
39385
|
}
|
|
39968
|
-
ledger.setConsumerMode(relayed !== undefined);
|
|
39969
39386
|
persist();
|
|
39970
|
-
return answer.mode;
|
|
39971
39387
|
},
|
|
39972
|
-
|
|
39973
|
-
|
|
39388
|
+
followedBefore(topic, storedAtMs) {
|
|
39389
|
+
const at = follows.get(topic);
|
|
39390
|
+
return at !== undefined && storedAtMs >= at - FOLLOW_CLOCK_ALLOWANCE_MS;
|
|
39391
|
+
},
|
|
39974
39392
|
setFollowed(topics) {
|
|
39975
39393
|
const at = now();
|
|
39976
39394
|
const next = new Map;
|
|
@@ -39998,8 +39416,6 @@ function createConsumerDelivery(options) {
|
|
|
39998
39416
|
},
|
|
39999
39417
|
close() {
|
|
40000
39418
|
closed = true;
|
|
40001
|
-
relayed = undefined;
|
|
40002
|
-
ledger.setConsumerMode(false);
|
|
40003
39419
|
queue.length = 0;
|
|
40004
39420
|
for (const entry of [...entries.values()])
|
|
40005
39421
|
settle(entry, "nak");
|
|
@@ -40007,13 +39423,61 @@ function createConsumerDelivery(options) {
|
|
|
40007
39423
|
}
|
|
40008
39424
|
};
|
|
40009
39425
|
}
|
|
40010
|
-
var
|
|
40011
|
-
|
|
40012
|
-
|
|
40013
|
-
|
|
40014
|
-
|
|
40015
|
-
}
|
|
40016
|
-
|
|
39426
|
+
var GAP_NOTICE_NAMES = {
|
|
39427
|
+
retention_gap: "messages may be missing",
|
|
39428
|
+
stream_recreated: "stream recreated"
|
|
39429
|
+
};
|
|
39430
|
+
function gapNoticeFields(notice) {
|
|
39431
|
+
return { notice: GAP_NOTICE_NAMES[notice.kind], detail: notice.message };
|
|
39432
|
+
}
|
|
39433
|
+
function gapNoticeText(notice) {
|
|
39434
|
+
return envoyNoticeText(gapNoticeFields(notice));
|
|
39435
|
+
}
|
|
39436
|
+
function inboundUnavailableNoticeText(why) {
|
|
39437
|
+
return envoyNoticeText({
|
|
39438
|
+
notice: "Envoy inbound unavailable",
|
|
39439
|
+
error: why,
|
|
39440
|
+
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."
|
|
39441
|
+
});
|
|
39442
|
+
}
|
|
39443
|
+
function inboundUnavailable(tell) {
|
|
39444
|
+
let told = false;
|
|
39445
|
+
return {
|
|
39446
|
+
refused(error) {
|
|
39447
|
+
if (told)
|
|
39448
|
+
return;
|
|
39449
|
+
told = true;
|
|
39450
|
+
tell(messageFor(error));
|
|
39451
|
+
},
|
|
39452
|
+
accepted() {
|
|
39453
|
+
told = false;
|
|
39454
|
+
}
|
|
39455
|
+
};
|
|
39456
|
+
}
|
|
39457
|
+
function registerWithRelay({
|
|
39458
|
+
relay,
|
|
39459
|
+
ownAgentSubject,
|
|
39460
|
+
followed,
|
|
39461
|
+
roles,
|
|
39462
|
+
outage,
|
|
39463
|
+
send,
|
|
39464
|
+
answered
|
|
39465
|
+
}) {
|
|
39466
|
+
if (relay === undefined) {
|
|
39467
|
+
const refused = new Error("this session holds no relay subject, so the listener can give it no consumer and it can receive nothing");
|
|
39468
|
+
outage.refused(refused);
|
|
39469
|
+
return Promise.reject(refused);
|
|
39470
|
+
}
|
|
39471
|
+
const topics = registrationTopics(ownAgentSubject, followed, roles);
|
|
39472
|
+
relay.setFollowed(topics);
|
|
39473
|
+
return send(topics, relay.registration()).then((result) => {
|
|
39474
|
+
outage.accepted();
|
|
39475
|
+
answered(result);
|
|
39476
|
+
return result;
|
|
39477
|
+
}, (error) => {
|
|
39478
|
+
outage.refused(error);
|
|
39479
|
+
throw error;
|
|
39480
|
+
});
|
|
40017
39481
|
}
|
|
40018
39482
|
|
|
40019
39483
|
// ../envoy-client/src/envoy-config.ts
|
|
@@ -43553,13 +43017,17 @@ function withoutFinalLineFeed(text) {
|
|
|
43553
43017
|
return text.endsWith(`
|
|
43554
43018
|
`) ? text.slice(0, -1) : text;
|
|
43555
43019
|
}
|
|
43020
|
+
var goBlankPattern = /^[\t\n\v\f\r \u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]*$/u;
|
|
43556
43021
|
async function artifactCommand(context) {
|
|
43557
43022
|
const { args, client, actor, input, documentOwner, issue } = context;
|
|
43558
43023
|
const summary = optionalString(args, "summary");
|
|
43559
43024
|
const name = stringArg(args, "name");
|
|
43560
43025
|
const content = optionalString(args, "content");
|
|
43026
|
+
const path = optionalString(args, "path");
|
|
43027
|
+
const options = { name, ...summary === undefined ? {} : { summary }, actor };
|
|
43561
43028
|
const artifactOwner = documentOwner();
|
|
43562
|
-
|
|
43029
|
+
const blank = content === undefined || goBlankPattern.test(content);
|
|
43030
|
+
if ((path !== undefined || !blank) && optionalBoolean(args, "force") !== true) {
|
|
43563
43031
|
const held = artifactUnderName(artifactOwner.kind === "project" ? await client.listProjectArtifacts(artifactOwner.project, true) : await client.listIssueArtifacts(issue()), name);
|
|
43564
43032
|
if (held !== undefined) {
|
|
43565
43033
|
throw new ToolInputError(input.tool, [
|
|
@@ -43567,7 +43035,7 @@ async function artifactCommand(context) {
|
|
|
43567
43035
|
]);
|
|
43568
43036
|
}
|
|
43569
43037
|
}
|
|
43570
|
-
if (
|
|
43038
|
+
if (!blank) {
|
|
43571
43039
|
let stored;
|
|
43572
43040
|
try {
|
|
43573
43041
|
stored = await client.markdownRoundTrip(content);
|
|
@@ -43580,19 +43048,12 @@ async function artifactCommand(context) {
|
|
|
43580
43048
|
throw new ToolInputError(input.tool, [storedTextProblem(content, stored, name)]);
|
|
43581
43049
|
}
|
|
43582
43050
|
}
|
|
43583
|
-
const artifactInput =
|
|
43584
|
-
|
|
43585
|
-
file: input.uploadBytes === undefined ? Bun.file(resolvePath(input.cwd,
|
|
43586
|
-
type: Bun.file(resolvePath(input.cwd,
|
|
43587
|
-
})
|
|
43588
|
-
|
|
43589
|
-
actor
|
|
43590
|
-
} : {
|
|
43591
|
-
name,
|
|
43592
|
-
content,
|
|
43593
|
-
...summary === undefined ? {} : { summary },
|
|
43594
|
-
actor
|
|
43595
|
-
};
|
|
43051
|
+
const artifactInput = path !== undefined ? {
|
|
43052
|
+
...options,
|
|
43053
|
+
file: input.uploadBytes === undefined ? Bun.file(resolvePath(input.cwd, path)) : new Blob([new Uint8Array(input.uploadBytes)], {
|
|
43054
|
+
type: Bun.file(resolvePath(input.cwd, path)).type
|
|
43055
|
+
})
|
|
43056
|
+
} : content !== undefined ? { ...options, content } : options;
|
|
43596
43057
|
const result = artifactOwner.kind === "project" ? await client.projectArtifact(artifactOwner.project, artifactInput) : await client.artifact(issue(), artifactInput);
|
|
43597
43058
|
const artifactRef = dispatchDocumentRef(artifactOwner.kind === "project" ? artifactOwner.project : issue(), result.artifact.slug);
|
|
43598
43059
|
const uploadOwner = artifactOwner.kind === "project" ? documentTopic(result.artifact) : issueTopic(issue());
|
|
@@ -43601,7 +43062,7 @@ async function artifactCommand(context) {
|
|
|
43601
43062
|
});
|
|
43602
43063
|
return {
|
|
43603
43064
|
text: [
|
|
43604
|
-
`Uploaded ${result.artifact.name} as version ${result.version.number} (artifact slug ${result.artifact.slug}; ${artifactRef})${await notSubscribed(uploadOwner, input.subscriptions)}`,
|
|
43065
|
+
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)}`,
|
|
43605
43066
|
...adviceLines
|
|
43606
43067
|
].join(`
|
|
43607
43068
|
`),
|
|
@@ -46046,7 +45507,7 @@ function every2(ms, callback) {
|
|
|
46046
45507
|
// ../envoy-client/src/tool-contract.ts
|
|
46047
45508
|
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.`;
|
|
46048
45509
|
var DELIVERY_CONTRACT = "Delivery is at-least-once, possibly out of order across topics; use id for dedupe and at for freshness.";
|
|
46049
|
-
var STORED_DELIVERY = "
|
|
45510
|
+
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.";
|
|
46050
45511
|
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>.";
|
|
46051
45512
|
var URGENCY_VALUES = EnvelopeSchema.shape.urgency.unwrap().options;
|
|
46052
45513
|
function messageMetadataShape(schema) {
|
|
@@ -46087,7 +45548,7 @@ var EnvoyToolOperation = {
|
|
|
46087
45548
|
var envoyToolSpecs = [
|
|
46088
45549
|
{
|
|
46089
45550
|
name: "envoy_subscribe",
|
|
46090
|
-
description: `Subscribe this session to Envoy notification topics. ${STORED_DELIVERY} ${TOPIC_GUIDE}`,
|
|
45551
|
+
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}`,
|
|
46091
45552
|
arguments: (schema) => ({
|
|
46092
45553
|
topics: schema.array(schema.string()).describe("NATS-style topic patterns to subscribe to.")
|
|
46093
45554
|
}),
|
|
@@ -46123,7 +45584,7 @@ var envoyToolSpecs = [
|
|
|
46123
45584
|
},
|
|
46124
45585
|
{
|
|
46125
45586
|
name: "envoy_publish",
|
|
46126
|
-
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,
|
|
45587
|
+
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}`,
|
|
46127
45588
|
arguments: (schema) => ({ topic: schema.string(), ...messageArguments(schema) }),
|
|
46128
45589
|
operation: EnvoyToolOperation.publish
|
|
46129
45590
|
},
|
|
@@ -46182,10 +45643,6 @@ function publishConfirmationText(result) {
|
|
|
46182
45643
|
const state = result.holderState === undefined ? "" : ` (${result.holderState})`;
|
|
46183
45644
|
sentences.push(`Its role holder is ${result.holder}${state}.`);
|
|
46184
45645
|
}
|
|
46185
|
-
if (result.unresponsive.length > 0) {
|
|
46186
|
-
const one = result.unresponsive.length === 1;
|
|
46187
|
-
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);
|
|
46188
|
-
}
|
|
46189
45646
|
return sentences.join(" ");
|
|
46190
45647
|
}
|
|
46191
45648
|
function sessionsOnMachine(sessions, machine) {
|
|
@@ -47042,7 +46499,7 @@ var import_nats2 = __toESM(require_mod4(), 1);
|
|
|
47042
46499
|
|
|
47043
46500
|
// package.json
|
|
47044
46501
|
var name = "@sjawhar/pi-envoy";
|
|
47045
|
-
var version2 = "17.
|
|
46502
|
+
var version2 = "17.8.0";
|
|
47046
46503
|
var package_default = {
|
|
47047
46504
|
name,
|
|
47048
46505
|
version: version2,
|
|
@@ -47115,7 +46572,7 @@ function customEntries(entries, customType) {
|
|
|
47115
46572
|
function newestState(entries) {
|
|
47116
46573
|
const states = customEntries(entries, REPLAY_STATE_ENTRY);
|
|
47117
46574
|
for (let index = states.length - 1;index >= 0; index -= 1) {
|
|
47118
|
-
const parsed =
|
|
46575
|
+
const parsed = LedgerStateSchema.safeParse(states[index]);
|
|
47119
46576
|
if (parsed.success)
|
|
47120
46577
|
return parsed.data;
|
|
47121
46578
|
}
|
|
@@ -47124,7 +46581,7 @@ function newestState(entries) {
|
|
|
47124
46581
|
function replaySnapshot(entries, now = Date.now()) {
|
|
47125
46582
|
const ledger = [];
|
|
47126
46583
|
for (const data of customEntries(entries, REPLAY_DELIVERED_ENTRY)) {
|
|
47127
|
-
const parsed =
|
|
46584
|
+
const parsed = LedgerEntrySchema.safeParse(data);
|
|
47128
46585
|
if (parsed.success)
|
|
47129
46586
|
ledger.push(parsed.data);
|
|
47130
46587
|
}
|
|
@@ -47225,7 +46682,7 @@ function writtenCards(entries, recorded, now) {
|
|
|
47225
46682
|
return found;
|
|
47226
46683
|
}
|
|
47227
46684
|
function rememberedSubjects(entries) {
|
|
47228
|
-
return rememberedTopics(newestState(entries));
|
|
46685
|
+
return rememberedTopics(newestState(entries)?.topics);
|
|
47229
46686
|
}
|
|
47230
46687
|
function heldReplayNotices(entries) {
|
|
47231
46688
|
const held = new Map;
|
|
@@ -47903,12 +47360,14 @@ function createRegistrationState(deps) {
|
|
|
47903
47360
|
const heldRole = () => claimedRoleTopic?.slice(ROLE_TOPIC_PREFIX.length);
|
|
47904
47361
|
const isRoleBound = (subject) => roleNoticeSubjects.has(subject);
|
|
47905
47362
|
const endRole = () => {
|
|
47363
|
+
const held = claimedRoleSessionID ?? "";
|
|
47364
|
+
const closed = [...roleNoticeSubjects];
|
|
47906
47365
|
claimedRoleTopic = undefined;
|
|
47907
47366
|
claimedRoleSessionID = undefined;
|
|
47908
47367
|
roleEnds += 1;
|
|
47909
|
-
for (const subject of roleNoticeSubjects)
|
|
47910
|
-
deps.closeSubject(subject);
|
|
47911
47368
|
roleNoticeSubjects.clear();
|
|
47369
|
+
if (closed.length > 0)
|
|
47370
|
+
deps.closeSubjects(held, closed);
|
|
47912
47371
|
};
|
|
47913
47372
|
const refreshRegistration = (input) => {
|
|
47914
47373
|
holds.adoptFor(input.sessionID);
|
|
@@ -48732,7 +48191,7 @@ class UnwrittenFrames {
|
|
|
48732
48191
|
return "closed";
|
|
48733
48192
|
}
|
|
48734
48193
|
const hand = deliverAs !== "inert" || this.#host.settled();
|
|
48735
|
-
const keys = identity === undefined ? [] : unwrittenCardKeys(
|
|
48194
|
+
const keys = identity === undefined ? [] : unwrittenCardKeys(ledgerIdentity(identity));
|
|
48736
48195
|
const card = identity === undefined || keys.length === 0 ? undefined : {
|
|
48737
48196
|
sessionID: session,
|
|
48738
48197
|
identity,
|
|
@@ -48763,7 +48222,7 @@ class UnwrittenFrames {
|
|
|
48763
48222
|
return "shown";
|
|
48764
48223
|
}
|
|
48765
48224
|
waitsOnCard(identity) {
|
|
48766
|
-
return unwrittenCardKeys(
|
|
48225
|
+
return unwrittenCardKeys(ledgerIdentity(identity)).some((key) => this.#cards.has(key));
|
|
48767
48226
|
}
|
|
48768
48227
|
sendNotice(content) {
|
|
48769
48228
|
const notice = {
|
|
@@ -52564,7 +52023,7 @@ var NATS_RETRY_INTERVAL_MS = 15000;
|
|
|
52564
52023
|
var DELIVERY_PICTURES_TIMEOUT_MS = 20000;
|
|
52565
52024
|
var WHOLE_BODY_TIMEOUT_MS = 1e4;
|
|
52566
52025
|
var BTW_EVENTS_LIMIT = 1000;
|
|
52567
|
-
var
|
|
52026
|
+
var LATE_BTW_NOTE = "This BTW was asked while this session was not taking messages. It is shown for your information only: it runs no side turn and needs no answer. Dispatch shows whether it was answered.";
|
|
52568
52027
|
var MOVED_SESSION_REFUSAL = `The message was not sent: ${MOVED_SESSION_REASON}`;
|
|
52569
52028
|
var CAPABILITIES_WITHOUT_BTW = DELIVERY_CAPABILITIES.filter((capability) => capability !== "btw");
|
|
52570
52029
|
var ClaimIdentitySchema = DedupeIdentitySchema.extend({
|
|
@@ -52748,8 +52207,6 @@ function envoyExtension(pi) {
|
|
|
52748
52207
|
return active;
|
|
52749
52208
|
};
|
|
52750
52209
|
const passDeadlineMs = () => active?.settings.passDeadlineMs ?? MIN_PASS_DEADLINE_MS;
|
|
52751
|
-
const subscriptions = new Map;
|
|
52752
|
-
const confirming = new Map;
|
|
52753
52210
|
const delivered = createDeliveryDedupe();
|
|
52754
52211
|
let connection;
|
|
52755
52212
|
let sessionDirectory2 = "";
|
|
@@ -52860,7 +52317,7 @@ function envoyExtension(pi) {
|
|
|
52860
52317
|
legionManagedTranscript = branch.some(isLegionManagedEntry);
|
|
52861
52318
|
const entries = context.sessionManager.getEntries();
|
|
52862
52319
|
handledDispatchAttempts = handledAttempts(entries);
|
|
52863
|
-
|
|
52320
|
+
ledger?.restore(replaySnapshot(entries));
|
|
52864
52321
|
unwritten.requeueNotices(heldReplayNotices(entries));
|
|
52865
52322
|
markPicturesShown(shownPictures(sessionID), transcriptPictures(branch));
|
|
52866
52323
|
if (previousSessionID !== sessionID) {
|
|
@@ -52972,7 +52429,6 @@ function envoyExtension(pi) {
|
|
|
52972
52429
|
continue;
|
|
52973
52430
|
unanswered.delete(watched);
|
|
52974
52431
|
renewRelayEpoch();
|
|
52975
|
-
triggerReplay();
|
|
52976
52432
|
}
|
|
52977
52433
|
} catch (error) {
|
|
52978
52434
|
logger3.warn("envoy: the NATS connection's status reader failed", {
|
|
@@ -53008,7 +52464,7 @@ function envoyExtension(pi) {
|
|
|
53008
52464
|
clockOffset: () => serverClock.offset()
|
|
53009
52465
|
});
|
|
53010
52466
|
const handCard = (content, deliverAs, identity) => {
|
|
53011
|
-
const known = identity === undefined ? {} :
|
|
52467
|
+
const known = identity === undefined ? {} : ledgerIdentity(identity);
|
|
53012
52468
|
if (deliverAs === "inert") {
|
|
53013
52469
|
pi.sendMessage({
|
|
53014
52470
|
customType: "envoy-message",
|
|
@@ -53030,7 +52486,7 @@ function envoyExtension(pi) {
|
|
|
53030
52486
|
hostIsOn: (card) => hostSessionID() === card,
|
|
53031
52487
|
settled: hostSettled,
|
|
53032
52488
|
recordDelivered: async (card, identity) => {
|
|
53033
|
-
await
|
|
52489
|
+
await ledger?.recordDeliveredFor(card, identity);
|
|
53034
52490
|
},
|
|
53035
52491
|
handCard,
|
|
53036
52492
|
cardNotShown: (card, identity) => {
|
|
@@ -53073,14 +52529,13 @@ function envoyExtension(pi) {
|
|
|
53073
52529
|
});
|
|
53074
52530
|
}
|
|
53075
52531
|
});
|
|
53076
|
-
const showReplayCard =
|
|
52532
|
+
const showReplayCard = (session, content, envelope, deliverAs = "card") => {
|
|
53077
52533
|
const parsed = ClaimIdentitySchema.safeParse(envelope);
|
|
53078
52534
|
const identity = parsed.success ? parsed.data : undefined;
|
|
53079
52535
|
const claim = delivered.claim(identity);
|
|
53080
52536
|
if (claim === undefined && identity !== undefined && (delivered.pending(identity) || unwritten.waitsOnCard(identity))) {
|
|
53081
52537
|
return "queued";
|
|
53082
52538
|
}
|
|
53083
|
-
await beforeHandOff?.();
|
|
53084
52539
|
const outcome = unwritten.sendCard(session, content, deliverAs, identity, claim);
|
|
53085
52540
|
return outcome === "closed" ? "failed" : outcome;
|
|
53086
52541
|
};
|
|
@@ -53267,49 +52722,21 @@ function envoyExtension(pi) {
|
|
|
53267
52722
|
logger3.warn("envoy: Dispatch did not accept a direct message as this session's turn; it arrives as a card", { ...fields, error: messageFor(refusal.error) });
|
|
53268
52723
|
}
|
|
53269
52724
|
});
|
|
53270
|
-
const deliver = async (
|
|
53271
|
-
const
|
|
53272
|
-
const addressedSessionOpen = () => addressedSession === undefined || sessionOpen(session);
|
|
52725
|
+
const deliver = async (session, subject, raw, relayed) => {
|
|
52726
|
+
const addressedSessionOpen = () => sessionOpen(session);
|
|
53273
52727
|
let rendered = renderInbound(raw, session, subject);
|
|
53274
|
-
const cardSession = () => rendered.delivery !== undefined
|
|
53275
|
-
|
|
53276
|
-
if (expectsLaneReceipt({
|
|
53277
|
-
subject,
|
|
53278
|
-
directSubject,
|
|
53279
|
-
envelopeTopic: rendered.envelope?.topic,
|
|
53280
|
-
reply
|
|
53281
|
-
})) {
|
|
53282
|
-
try {
|
|
53283
|
-
(await ensureConnection()).publish(reply);
|
|
53284
|
-
} catch (error) {
|
|
53285
|
-
console.warn(`[envoy] failed to acknowledge envelope ${rendered.envelope?.event_id ?? "unknown"}`, error);
|
|
53286
|
-
}
|
|
53287
|
-
}
|
|
53288
|
-
if (relayed === undefined && relaysCoreTopic(topic))
|
|
53289
|
-
return;
|
|
53290
|
-
let removed = false;
|
|
53291
|
-
for (const topic of subscriptionRemovedTopics(raw, sessionID) ?? []) {
|
|
53292
|
-
if (closeIntentionally(topic))
|
|
53293
|
-
removed = true;
|
|
53294
|
-
}
|
|
53295
|
-
if (removed) {
|
|
53296
|
-
replayFollowedChanged();
|
|
53297
|
-
if (relay?.sessionID === sessionID && relay.delivery.relaying()) {
|
|
53298
|
-
Promise.resolve().then(registerSession).catch(() => {
|
|
53299
|
-
return;
|
|
53300
|
-
});
|
|
53301
|
-
}
|
|
53302
|
-
}
|
|
52728
|
+
const cardSession = () => rendered.delivery !== undefined ? session : hostSessionID();
|
|
52729
|
+
await closeRemovedSubscriptions(raw, relayed.storedAtMs);
|
|
53303
52730
|
const dedupeIdentity = ClaimIdentitySchema.safeParse(rendered.envelope);
|
|
53304
52731
|
const identity = dedupeIdentity.success ? dedupeIdentity.data : undefined;
|
|
53305
52732
|
const held = rendered.skip ? undefined : delivered.claim(identity);
|
|
53306
52733
|
if (held === undefined) {
|
|
53307
|
-
relayed
|
|
52734
|
+
relayed.done();
|
|
53308
52735
|
return;
|
|
53309
52736
|
}
|
|
53310
52737
|
let handing = true;
|
|
53311
52738
|
let releasedWhileHanding = false;
|
|
53312
|
-
const claim =
|
|
52739
|
+
const claim = {
|
|
53313
52740
|
settle: () => {
|
|
53314
52741
|
held.settle();
|
|
53315
52742
|
relayed.done();
|
|
@@ -53323,7 +52750,7 @@ function envoyExtension(pi) {
|
|
|
53323
52750
|
relayed.nak();
|
|
53324
52751
|
}
|
|
53325
52752
|
};
|
|
53326
|
-
if (identity !== undefined &&
|
|
52753
|
+
if (identity !== undefined && ledger?.delivered(identity) === true) {
|
|
53327
52754
|
claim.settle();
|
|
53328
52755
|
return;
|
|
53329
52756
|
}
|
|
@@ -53337,7 +52764,7 @@ function envoyExtension(pi) {
|
|
|
53337
52764
|
if (envelope !== undefined)
|
|
53338
52765
|
noteInbox(envelope);
|
|
53339
52766
|
const recordTaken = async (frame) => {
|
|
53340
|
-
if (
|
|
52767
|
+
if (ledger === undefined || await ledger.recordDeliveredFor(session, frame))
|
|
53341
52768
|
return;
|
|
53342
52769
|
logger3.warn("envoy: a delivery was not recorded in the session it was addressed to", {
|
|
53343
52770
|
addressed: session,
|
|
@@ -53361,17 +52788,14 @@ function envoyExtension(pi) {
|
|
|
53361
52788
|
const refuse = async (delivery, error) => {
|
|
53362
52789
|
held.release();
|
|
53363
52790
|
await postDispatchReply(delivery, { error }, session);
|
|
53364
|
-
relayed
|
|
52791
|
+
relayed.done();
|
|
53365
52792
|
};
|
|
53366
52793
|
const offWorker = (work) => {
|
|
53367
|
-
relayed
|
|
52794
|
+
relayed.release();
|
|
53368
52795
|
work().catch((error) => {
|
|
53369
52796
|
held.release();
|
|
53370
52797
|
console.warn(`[envoy] failed to deliver envelope ${envelope?.event_id ?? "unknown"}`, error);
|
|
53371
|
-
|
|
53372
|
-
relayed.done();
|
|
53373
|
-
else if (envelope !== undefined)
|
|
53374
|
-
replay?.liveFailed(cardSession(), topic, envelope, error, receivedAt);
|
|
52798
|
+
relayed.done();
|
|
53375
52799
|
});
|
|
53376
52800
|
};
|
|
53377
52801
|
try {
|
|
@@ -53382,10 +52806,10 @@ function envoyExtension(pi) {
|
|
|
53382
52806
|
} else if (rendered.malformedDelivery === true) {
|
|
53383
52807
|
console.warn("[envoy] dropping malformed Dispatch targeted delivery without a reply address");
|
|
53384
52808
|
claim.settle();
|
|
53385
|
-
} else if (rendered.delivery?.mode === "btw" && relayed
|
|
52809
|
+
} else if (rendered.delivery?.mode === "btw" && relayed.late === true) {
|
|
53386
52810
|
noteBtw(identity?.event_id);
|
|
53387
|
-
unwritten.sendCard(cardSession(), `${
|
|
53388
|
-
${
|
|
52811
|
+
unwritten.sendCard(cardSession(), `${storedText(rendered.content, relayed.storedAt)}
|
|
52812
|
+
${LATE_BTW_NOTE}`, "inert", identity, claim);
|
|
53389
52813
|
} else if (rendered.delivery?.mode === "btw") {
|
|
53390
52814
|
noteBtw(identity?.event_id);
|
|
53391
52815
|
if (identity?.event_id !== undefined) {
|
|
@@ -53468,84 +52892,35 @@ ${REPLAYED_BTW_NOTE}`, "inert", identity, claim);
|
|
|
53468
52892
|
handing = false;
|
|
53469
52893
|
held.release();
|
|
53470
52894
|
console.warn(`[envoy] failed to deliver envelope ${envelope?.event_id ?? "unknown"}`, error);
|
|
53471
|
-
if (relayed === undefined && envelope !== undefined) {
|
|
53472
|
-
replay?.liveFailed(cardSession(), topic, envelope, error, receivedAt);
|
|
53473
|
-
}
|
|
53474
52895
|
throw error;
|
|
53475
52896
|
}
|
|
53476
52897
|
handing = false;
|
|
53477
52898
|
if (releasedWhileHanding)
|
|
53478
|
-
relayed
|
|
52899
|
+
relayed.nak();
|
|
53479
52900
|
};
|
|
53480
52901
|
const RESUBSCRIBE_DELAY_MS = Number(process.env.ENVOY_RESUBSCRIBE_DELAY_MS ?? "") || 5000;
|
|
53481
52902
|
let shuttingDown = false;
|
|
53482
|
-
const
|
|
53483
|
-
const
|
|
53484
|
-
|
|
53485
|
-
|
|
53486
|
-
|
|
53487
|
-
|
|
53488
|
-
|
|
53489
|
-
|
|
53490
|
-
return false;
|
|
53491
|
-
intentionallyClosed.add(topic);
|
|
53492
|
-
return true;
|
|
52903
|
+
const followed = new Set;
|
|
52904
|
+
const follow = (topic) => {
|
|
52905
|
+
let added = false;
|
|
52906
|
+
for (const subject of expandSubscriptionTopics([topic])) {
|
|
52907
|
+
if (followed.has(subject))
|
|
52908
|
+
continue;
|
|
52909
|
+
followed.add(subject);
|
|
52910
|
+
added = true;
|
|
53493
52911
|
}
|
|
53494
|
-
|
|
53495
|
-
subscription.unsubscribe();
|
|
53496
|
-
subscriptions.delete(topic);
|
|
53497
|
-
return true;
|
|
53498
|
-
};
|
|
53499
|
-
const lineageOf = (id) => {
|
|
53500
|
-
const lineage = continuedBy(id);
|
|
53501
|
-
return announced !== undefined && announced.from !== id && carriesSession(announced.reason) && !lineage.includes(announced.from) ? [...lineage, announced.from] : lineage;
|
|
53502
|
-
};
|
|
53503
|
-
const topicAddress = (topic) => {
|
|
53504
|
-
if (!topic.startsWith(agentSubject("")))
|
|
53505
|
-
return { addressed: undefined };
|
|
53506
|
-
const host = hostSessionID();
|
|
53507
|
-
if (host === "")
|
|
53508
|
-
return { addressed: undefined };
|
|
53509
|
-
return lineageOf(host).some((id) => topic === agentSubject(id)) ? { addressed: host } : { replaced: true };
|
|
52912
|
+
return added;
|
|
53510
52913
|
};
|
|
53511
|
-
const
|
|
53512
|
-
|
|
53513
|
-
|
|
53514
|
-
|
|
53515
|
-
|
|
53516
|
-
|
|
53517
|
-
|
|
53518
|
-
});
|
|
53519
|
-
continue;
|
|
53520
|
-
}
|
|
53521
|
-
try {
|
|
53522
|
-
await deliver(address.addressed, topic, message.subject, codec2.decode(message.data), message.reply ?? "", receivedAt);
|
|
53523
|
-
} catch {}
|
|
53524
|
-
}
|
|
53525
|
-
} catch {}
|
|
53526
|
-
if (subscriptions.get(topic) === subscription)
|
|
53527
|
-
subscriptions.delete(topic);
|
|
53528
|
-
if (shuttingDown)
|
|
53529
|
-
return;
|
|
53530
|
-
if (intentionallyClosed.delete(topic))
|
|
53531
|
-
return;
|
|
53532
|
-
const snapshot = registrationState.roleSnapshot(topic);
|
|
53533
|
-
const retry = (delayMs) => {
|
|
53534
|
-
awaitingRetry.add(topic);
|
|
53535
|
-
setTimeout(() => {
|
|
53536
|
-
awaitingRetry.delete(topic);
|
|
53537
|
-
if (shuttingDown || subscriptions.has(topic))
|
|
53538
|
-
return;
|
|
53539
|
-
if (intentionallyClosed.delete(topic))
|
|
53540
|
-
return;
|
|
53541
|
-
subscribeUnlessRoleEnds(topic, snapshot).then((wanted) => {
|
|
53542
|
-
if (wanted)
|
|
53543
|
-
triggerReplay();
|
|
53544
|
-
}, () => retry(NATS_RETRY_INTERVAL_MS));
|
|
53545
|
-
}, delayMs);
|
|
53546
|
-
};
|
|
53547
|
-
retry(RESUBSCRIBE_DELAY_MS);
|
|
52914
|
+
const unfollow = (topic) => {
|
|
52915
|
+
let dropped = false;
|
|
52916
|
+
for (const subject of expandSubscriptionTopics([topic])) {
|
|
52917
|
+
if (followed.delete(subject))
|
|
52918
|
+
dropped = true;
|
|
52919
|
+
}
|
|
52920
|
+
return dropped;
|
|
53548
52921
|
};
|
|
52922
|
+
const SUBSCRIBE_FLUSH_TIMEOUT_MS = Number(process.env.ENVOY_SUBSCRIBE_FLUSH_TIMEOUT_MS ?? "") || 1e4;
|
|
52923
|
+
const unanswered = new Set;
|
|
53549
52924
|
const within = async (promise, ms, what) => {
|
|
53550
52925
|
const expired = Promise.withResolvers();
|
|
53551
52926
|
const timer = setTimeout(() => expired.reject(new Error(`${what} timed out after ${ms} ms`)), ms);
|
|
@@ -53584,53 +52959,6 @@ ${REPLAYED_BTW_NOTE}`, "inert", identity, claim);
|
|
|
53584
52959
|
unanswered.delete(connection);
|
|
53585
52960
|
}
|
|
53586
52961
|
};
|
|
53587
|
-
const subscribe = async (topic, connect = ensureConnection) => {
|
|
53588
|
-
const subjects = expandSubscriptionTopics([topic]);
|
|
53589
|
-
const inFlight = subjects.flatMap((subject) => confirming.get(subject) ?? []);
|
|
53590
|
-
if (inFlight.length > 0)
|
|
53591
|
-
await Promise.allSettled(inFlight);
|
|
53592
|
-
const fresh = subjects.filter((candidate) => !subscriptions.has(candidate));
|
|
53593
|
-
if (fresh.length === 0)
|
|
53594
|
-
return false;
|
|
53595
|
-
const activeConnection = await connect();
|
|
53596
|
-
const opened = [];
|
|
53597
|
-
const closeOpened = () => {
|
|
53598
|
-
for (const [subject, subscription] of opened) {
|
|
53599
|
-
if (subscriptions.get(subject) === subscription)
|
|
53600
|
-
closeIntentionally(subject);
|
|
53601
|
-
}
|
|
53602
|
-
};
|
|
53603
|
-
try {
|
|
53604
|
-
for (const subject of fresh) {
|
|
53605
|
-
const subscription = activeConnection.subscribe(subject);
|
|
53606
|
-
intentionallyClosed.delete(subject);
|
|
53607
|
-
subscriptions.set(subject, subscription);
|
|
53608
|
-
opened.push([subject, subscription]);
|
|
53609
|
-
pump(subject, subscription);
|
|
53610
|
-
}
|
|
53611
|
-
} catch (error) {
|
|
53612
|
-
closeOpened();
|
|
53613
|
-
throw error;
|
|
53614
|
-
}
|
|
53615
|
-
const settled = confirmSubscribed(activeConnection, `the subscription to ${topic}`);
|
|
53616
|
-
const confirmation = settled.catch(() => {
|
|
53617
|
-
return;
|
|
53618
|
-
});
|
|
53619
|
-
for (const [subject] of opened)
|
|
53620
|
-
confirming.set(subject, confirmation);
|
|
53621
|
-
try {
|
|
53622
|
-
await settled;
|
|
53623
|
-
} catch (error) {
|
|
53624
|
-
closeOpened();
|
|
53625
|
-
throw error;
|
|
53626
|
-
} finally {
|
|
53627
|
-
for (const [subject] of opened) {
|
|
53628
|
-
if (confirming.get(subject) === confirmation)
|
|
53629
|
-
confirming.delete(subject);
|
|
53630
|
-
}
|
|
53631
|
-
}
|
|
53632
|
-
return true;
|
|
53633
|
-
};
|
|
53634
52962
|
const noteInbox = (envelope) => {
|
|
53635
52963
|
inbox.unshift({
|
|
53636
52964
|
event_id: envelope.event_id ?? "unknown",
|
|
@@ -53644,62 +52972,42 @@ ${REPLAYED_BTW_NOTE}`, "inert", identity, claim);
|
|
|
53644
52972
|
const followedSubjects = () => {
|
|
53645
52973
|
if (sessionID === "")
|
|
53646
52974
|
return [];
|
|
53647
|
-
|
|
53648
|
-
|
|
53649
|
-
|
|
53650
|
-
|
|
53651
|
-
|
|
53652
|
-
|
|
53653
|
-
|
|
53654
|
-
|
|
53655
|
-
sessionID:
|
|
53656
|
-
|
|
53657
|
-
|
|
53658
|
-
|
|
53659
|
-
|
|
53660
|
-
|
|
53661
|
-
|
|
53662
|
-
|
|
53663
|
-
|
|
53664
|
-
|
|
53665
|
-
|
|
53666
|
-
|
|
53667
|
-
eventID: rendered.envelope?.event_id,
|
|
53668
|
-
open: sessionID
|
|
53669
|
-
});
|
|
53670
|
-
return "failed";
|
|
53671
|
-
}
|
|
53672
|
-
if (replaySuppressed(rendered))
|
|
53673
|
-
return "suppressed";
|
|
53674
|
-
if (rendered.envelope !== undefined)
|
|
53675
|
-
noteInbox(rendered.envelope);
|
|
53676
|
-
const shown = replayedText(rendered.content, frame.time);
|
|
53677
|
-
if (rendered.delivery?.mode === "btw") {
|
|
53678
|
-
noteBtw(rendered.envelope?.event_id);
|
|
53679
|
-
return showReplayCard(addressed, `${shown}
|
|
53680
|
-
${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
|
|
53681
|
-
}
|
|
53682
|
-
return showReplayCard(addressed, shown, frame.envelope, "card", isHumanDispatchCard(rendered) ? () => armAskAwarenessForPersonInput(activeSessionContext, addressed) : undefined);
|
|
52975
|
+
return replayFollowedSubjects(agentSubject(sessionID), followed, registrationState.isRoleBound);
|
|
52976
|
+
};
|
|
52977
|
+
const closeRemovedSubscriptions = async (raw, storedAtMs) => {
|
|
52978
|
+
const closed = await closeReplayedRemoval({ data: raw, storedAtMs }, {
|
|
52979
|
+
sessionID,
|
|
52980
|
+
relay: relay?.sessionID === sessionID ? relay.delivery : undefined,
|
|
52981
|
+
close: unfollow,
|
|
52982
|
+
unregister: async (topics) => {
|
|
52983
|
+
await active?.client.unsubscribe({ sessionID, topics }).catch((error) => logger3.warn("envoy: a subscription removal was not taken out of the registry", {
|
|
52984
|
+
topics,
|
|
52985
|
+
error: messageFor(error)
|
|
52986
|
+
}));
|
|
52987
|
+
},
|
|
52988
|
+
followedChanged: ledgerFollowedChanged
|
|
52989
|
+
});
|
|
52990
|
+
if (closed.length === 0)
|
|
52991
|
+
return;
|
|
52992
|
+
Promise.resolve().then(registerSession).catch(() => {
|
|
52993
|
+
return;
|
|
52994
|
+
});
|
|
53683
52995
|
};
|
|
53684
52996
|
const transcriptSessionID = () => {
|
|
53685
52997
|
const host = hostSessionID();
|
|
53686
52998
|
return host !== "" && host === sessionID ? host : undefined;
|
|
53687
52999
|
};
|
|
53688
|
-
const
|
|
53000
|
+
const tellGapNotice = (notice) => {
|
|
53689
53001
|
logger3.warn(`envoy: ${notice.message}`);
|
|
53690
|
-
|
|
53691
|
-
warn: (message) => activeSessionContext?.ui.notify(`envoy: ${message}`, "warning"),
|
|
53692
|
-
card: (content) => unwritten.sendNotice(content)
|
|
53693
|
-
});
|
|
53002
|
+
unwritten.sendNotice(gapNoticeText(notice));
|
|
53694
53003
|
};
|
|
53695
|
-
const
|
|
53004
|
+
const ledger = active === undefined || !inbound ? undefined : createDeliveryLedger({
|
|
53696
53005
|
host: {
|
|
53697
53006
|
sessionID: () => shuttingDown ? undefined : transcriptSessionID(),
|
|
53698
53007
|
writeSessionID: transcriptSessionID,
|
|
53699
53008
|
followedSubjects,
|
|
53700
|
-
|
|
53701
|
-
|
|
53702
|
-
const outcome = await showReplayCard(sessionID, envoyNoticeText(failureNoticeFields(notice)), notice.envelope, btwEvents.has(notice.eventId) ? "inert" : "card");
|
|
53009
|
+
showFailureNotice: async (addressed, notice) => {
|
|
53010
|
+
const outcome = showReplayCard(addressed, envoyNoticeText(failureNoticeFields(notice)), notice.envelope, btwEvents.has(notice.eventId) ? "inert" : "card");
|
|
53703
53011
|
if (outcome === "failed")
|
|
53704
53012
|
throw new Error("the session it names is closed");
|
|
53705
53013
|
return outcome;
|
|
@@ -53711,7 +53019,6 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
|
|
|
53711
53019
|
});
|
|
53712
53020
|
activeSessionContext?.ui.notify(`envoy: message ${notice.eventId} from ${notice.sender} was not shown, nor was the notice naming it (${messageFor(error)})`, "warning");
|
|
53713
53021
|
},
|
|
53714
|
-
notify: tellReplayNotice,
|
|
53715
53022
|
log: (message, error) => logger3.warn(`envoy: ${message}`, error === undefined ? undefined : { error: messageFor(error) }),
|
|
53716
53023
|
write: (change) => {
|
|
53717
53024
|
for (const entry of change.delivered)
|
|
@@ -53719,28 +53026,21 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
|
|
|
53719
53026
|
if (change.state !== undefined)
|
|
53720
53027
|
pi.appendEntry(REPLAY_STATE_ENTRY, change.state);
|
|
53721
53028
|
}
|
|
53722
|
-
}
|
|
53723
|
-
transport: active.client,
|
|
53724
|
-
dedupe: delivered
|
|
53029
|
+
}
|
|
53725
53030
|
});
|
|
53726
|
-
const
|
|
53727
|
-
const
|
|
53728
|
-
if (
|
|
53729
|
-
|
|
53730
|
-
};
|
|
53731
|
-
const replayFollowedChanged = async () => {
|
|
53732
|
-
if (replay !== undefined && replayOpen())
|
|
53733
|
-
await replay.followedChanged();
|
|
53031
|
+
const ledgerOpen = () => !shuttingDown && sessionID !== "" && registrationState.inboundOpenSession() === sessionID;
|
|
53032
|
+
const ledgerFollowedChanged = async () => {
|
|
53033
|
+
if (ledger !== undefined && ledgerOpen())
|
|
53034
|
+
await ledger.followedChanged();
|
|
53734
53035
|
};
|
|
53735
53036
|
let relay;
|
|
53736
|
-
const relaysCoreTopic = (topic) => relay?.sessionID === sessionID && relay.delivery.relays(topic);
|
|
53737
53037
|
const deliverRelayed = async (delivery, frame) => {
|
|
53738
53038
|
const owner = relay;
|
|
53739
53039
|
if (shuttingDown || owner?.delivery !== delivery || !sessionOpen(owner.sessionID)) {
|
|
53740
53040
|
frame.nak();
|
|
53741
53041
|
return;
|
|
53742
53042
|
}
|
|
53743
|
-
await deliver(owner.sessionID, frame.subject, frame.
|
|
53043
|
+
await deliver(owner.sessionID, frame.subject, frame.data, frame);
|
|
53744
53044
|
};
|
|
53745
53045
|
const createRelay = (id, entries, ledger) => {
|
|
53746
53046
|
let persistedFollows = "";
|
|
@@ -53749,7 +53049,7 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
|
|
|
53749
53049
|
ledger,
|
|
53750
53050
|
host: {
|
|
53751
53051
|
deliver: (frame) => deliverRelayed(delivery, frame),
|
|
53752
|
-
gap:
|
|
53052
|
+
gap: tellGapNotice,
|
|
53753
53053
|
log: (message, error) => logger3.warn(`envoy: ${message}`, error === undefined ? undefined : { error: messageFor(error) })
|
|
53754
53054
|
},
|
|
53755
53055
|
publish: (reply, body) => {
|
|
@@ -53796,11 +53096,11 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
|
|
|
53796
53096
|
}
|
|
53797
53097
|
};
|
|
53798
53098
|
const openRelay = async (context, id, connect) => {
|
|
53799
|
-
if (
|
|
53099
|
+
if (ledger === undefined)
|
|
53800
53100
|
return;
|
|
53801
53101
|
if (relay?.sessionID !== id) {
|
|
53802
53102
|
closeRelay();
|
|
53803
|
-
relay = createRelay(id, context.sessionManager.getEntries(),
|
|
53103
|
+
relay = createRelay(id, context.sessionManager.getEntries(), ledger);
|
|
53804
53104
|
}
|
|
53805
53105
|
await subscribeRelay(relay, connect);
|
|
53806
53106
|
};
|
|
@@ -53843,17 +53143,10 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
|
|
|
53843
53143
|
return;
|
|
53844
53144
|
});
|
|
53845
53145
|
};
|
|
53846
|
-
const takeDeliveryAnswer = (registeredSession,
|
|
53847
|
-
if (sessionID !== registeredSession ||
|
|
53848
|
-
return;
|
|
53849
|
-
if (asked !== undefined) {
|
|
53850
|
-
asked.delivery.answered(result.delivery, topics);
|
|
53851
|
-
return;
|
|
53852
|
-
}
|
|
53853
|
-
if (replay === undefined)
|
|
53146
|
+
const takeDeliveryAnswer = (registeredSession, asked, result) => {
|
|
53147
|
+
if (sessionID !== registeredSession || relay !== asked)
|
|
53854
53148
|
return;
|
|
53855
|
-
|
|
53856
|
-
registeredWithoutRelay(replay, open?.delivery, topics);
|
|
53149
|
+
asked.delivery.answered(result.delivery);
|
|
53857
53150
|
};
|
|
53858
53151
|
const agentStream = new AgentStreamPublisher({
|
|
53859
53152
|
now: () => Date.now(),
|
|
@@ -54102,20 +53395,28 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
|
|
|
54102
53395
|
},
|
|
54103
53396
|
dial: dialNats,
|
|
54104
53397
|
connect: ensureConnection,
|
|
54105
|
-
subscribeTopic:
|
|
54106
|
-
|
|
54107
|
-
|
|
53398
|
+
subscribeTopic: async (topic) => follow(topic),
|
|
53399
|
+
closeSubjects: (held, subjects) => {
|
|
53400
|
+
for (const subject of subjects)
|
|
53401
|
+
unfollow(subject);
|
|
53402
|
+
const id = held === "" ? sessionID : held;
|
|
53403
|
+
if (subjects.length === 0 || id === "")
|
|
53404
|
+
return;
|
|
53405
|
+
active?.client.unsubscribe({ sessionID: id, topics: subjects }).catch((error) => logger3.warn("envoy: a role's notice subjects were not taken out of the registry", {
|
|
53406
|
+
topics: subjects,
|
|
53407
|
+
sessionID: id,
|
|
53408
|
+
error: messageFor(error)
|
|
53409
|
+
}));
|
|
54108
53410
|
}
|
|
54109
53411
|
});
|
|
54110
|
-
const
|
|
53412
|
+
const followUnlessRoleEnds = (topic, snapshot) => {
|
|
54111
53413
|
const roleEnded = () => snapshot.roleBound && registrationState.roleEndCount() !== snapshot.endsBefore;
|
|
54112
53414
|
if (roleEnded())
|
|
54113
53415
|
return false;
|
|
54114
|
-
|
|
53416
|
+
follow(topic);
|
|
54115
53417
|
if (!roleEnded())
|
|
54116
53418
|
return true;
|
|
54117
|
-
|
|
54118
|
-
closeIntentionally(subject);
|
|
53419
|
+
unfollow(topic);
|
|
54119
53420
|
return false;
|
|
54120
53421
|
};
|
|
54121
53422
|
const registrationsInFlight = new Map;
|
|
@@ -54150,43 +53451,45 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
|
|
|
54150
53451
|
}
|
|
54151
53452
|
await registrationState.deregister(id);
|
|
54152
53453
|
};
|
|
53454
|
+
const inboundOutage = inboundUnavailable((why) => {
|
|
53455
|
+
logger3.warn(`envoy: this session receives nothing: ${why}`);
|
|
53456
|
+
activeSessionContext?.ui.notify(`envoy: inbound messages are unavailable (${why}); registering again every heartbeat`, "warning");
|
|
53457
|
+
unwritten.sendNotice(inboundUnavailableNoticeText(why));
|
|
53458
|
+
});
|
|
54153
53459
|
const tmuxPlaces = createTmuxPlaceCache({
|
|
54154
53460
|
read: () => readTmuxPlace(process.env, defaultExec),
|
|
54155
53461
|
lifetimeMs: () => active?.settings.tmuxPlaceCacheMs ?? DEFAULT_TMUX_PLACE_CACHE_MS,
|
|
54156
53462
|
onFailure: (error) => logger3.debug("envoy: the tmux place reading failed", { error: messageFor(error) })
|
|
54157
53463
|
});
|
|
54158
|
-
const
|
|
54159
|
-
const own = agentSubject(sessionID);
|
|
54160
|
-
const topics = [
|
|
54161
|
-
...new Set([
|
|
54162
|
-
own,
|
|
54163
|
-
...[...subscriptions.keys()].filter((subject) => !registrationState.isRoleBound(subject) && !reachesPrivateStreamSubject(own, subject))
|
|
54164
|
-
])
|
|
54165
|
-
];
|
|
54166
|
-
if (asking !== undefined)
|
|
54167
|
-
asking.delivery.setFollowed(topics);
|
|
54168
|
-
return {
|
|
54169
|
-
sessionID,
|
|
54170
|
-
directory: sessionDirectory2,
|
|
54171
|
-
topics,
|
|
54172
|
-
port: 0,
|
|
54173
|
-
title: activeSessionContext?.sessionManager.getSessionName?.() ?? "",
|
|
54174
|
-
capabilities: sideTurn(activeSessionContext) === undefined ? CAPABILITIES_WITHOUT_BTW : DELIVERY_CAPABILITIES,
|
|
54175
|
-
driving: false,
|
|
54176
|
-
selfSubscribed: true,
|
|
54177
|
-
plugin: { name, version: version2 },
|
|
54178
|
-
...asking === undefined ? {} : { delivery: asking.delivery.registration() },
|
|
54179
|
-
...place === undefined ? {} : { place }
|
|
54180
|
-
};
|
|
54181
|
-
};
|
|
54182
|
-
const sendRegistration = async (send) => {
|
|
53464
|
+
const sendRegistration = (send) => {
|
|
54183
53465
|
const place = tmuxPlaces.place();
|
|
54184
53466
|
const registeringFor = sessionID;
|
|
54185
|
-
const asking = relay?.sessionID === registeringFor && relay.subscription !== undefined
|
|
54186
|
-
const
|
|
54187
|
-
|
|
54188
|
-
|
|
54189
|
-
|
|
53467
|
+
const asking = relay?.sessionID === registeringFor && relay.subscription !== undefined ? relay : undefined;
|
|
53468
|
+
const role = registrationState.heldRole();
|
|
53469
|
+
return registerWithRelay({
|
|
53470
|
+
relay: asking?.delivery,
|
|
53471
|
+
ownAgentSubject: agentSubject(registeringFor),
|
|
53472
|
+
followed,
|
|
53473
|
+
roles: role === undefined ? [] : [role],
|
|
53474
|
+
outage: inboundOutage,
|
|
53475
|
+
send: (topics, delivery) => send({
|
|
53476
|
+
sessionID: registeringFor,
|
|
53477
|
+
directory: sessionDirectory2,
|
|
53478
|
+
topics,
|
|
53479
|
+
port: 0,
|
|
53480
|
+
title: activeSessionContext?.sessionManager.getSessionName?.() ?? "",
|
|
53481
|
+
capabilities: sideTurn(activeSessionContext) === undefined ? CAPABILITIES_WITHOUT_BTW : DELIVERY_CAPABILITIES,
|
|
53482
|
+
driving: false,
|
|
53483
|
+
selfSubscribed: true,
|
|
53484
|
+
plugin: { name, version: version2 },
|
|
53485
|
+
delivery,
|
|
53486
|
+
...place === undefined ? {} : { place }
|
|
53487
|
+
}),
|
|
53488
|
+
answered: (result) => {
|
|
53489
|
+
if (asking !== undefined)
|
|
53490
|
+
takeDeliveryAnswer(registeringFor, asking, result);
|
|
53491
|
+
}
|
|
53492
|
+
});
|
|
54190
53493
|
};
|
|
54191
53494
|
const registerSession = () => trackRegistration(sessionID, sendRegistration(registrationState.refreshRegistration));
|
|
54192
53495
|
let writtenTitle;
|
|
@@ -54241,7 +53544,6 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
|
|
|
54241
53544
|
return;
|
|
54242
53545
|
writeHeartbeatTitle(context);
|
|
54243
53546
|
unwritten.handBackWithdrawn();
|
|
54244
|
-
triggerReplay();
|
|
54245
53547
|
if (healing) {
|
|
54246
53548
|
const refreshMs = requireEnvoy().settings.heartbeatMs;
|
|
54247
53549
|
if (registrationState.registrationFresherThan(sessionID, refreshMs))
|
|
@@ -54408,7 +53710,7 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
|
|
|
54408
53710
|
lastHeard = "";
|
|
54409
53711
|
}
|
|
54410
53712
|
for (const other of handle.forgetOtherAgentSessions(host)) {
|
|
54411
|
-
|
|
53713
|
+
unfollow(agentSubject(other));
|
|
54412
53714
|
leftSessions.add(other);
|
|
54413
53715
|
}
|
|
54414
53716
|
if (relay !== undefined && relay.sessionID !== host)
|
|
@@ -54419,7 +53721,6 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
|
|
|
54419
53721
|
return true;
|
|
54420
53722
|
}
|
|
54421
53723
|
let inboundFailure;
|
|
54422
|
-
let openedInbound = false;
|
|
54423
53724
|
if (inbound && registrationState.inboundOpenSession() !== host) {
|
|
54424
53725
|
try {
|
|
54425
53726
|
handle.markAgentSessionOpen(host);
|
|
@@ -54431,24 +53732,18 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
|
|
|
54431
53732
|
await recoverRegisteredInterests(handle);
|
|
54432
53733
|
}
|
|
54433
53734
|
handle.markInboundOpen(host);
|
|
54434
|
-
openedInbound = true;
|
|
54435
53735
|
} catch (error) {
|
|
54436
53736
|
inboundFailure = error;
|
|
54437
53737
|
}
|
|
54438
53738
|
}
|
|
54439
53739
|
handle.check();
|
|
54440
|
-
if (inboundFailure !== undefined && replay !== undefined)
|
|
54441
|
-
await replay.startCursors();
|
|
54442
53740
|
const registration = await trackRegistration(host, sendRegistration(handle.register)).then(() => {
|
|
54443
53741
|
return;
|
|
54444
53742
|
}, (error) => ({ error }));
|
|
54445
53743
|
handle.check();
|
|
54446
|
-
if (registration === undefined)
|
|
53744
|
+
if (registration === undefined)
|
|
54447
53745
|
handle.markEstablished(host);
|
|
54448
|
-
|
|
54449
|
-
}
|
|
54450
|
-
if (openedInbound)
|
|
54451
|
-
triggerReplay();
|
|
53746
|
+
ensureHeartbeat(context);
|
|
54452
53747
|
const decided = await registrationState.roleMoves.run((move) => settleRole(context, host, cause, registration === undefined, move)) ?? false;
|
|
54453
53748
|
handle.check();
|
|
54454
53749
|
leftSessions.delete(host);
|
|
@@ -54565,6 +53860,7 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
|
|
|
54565
53860
|
if (context === undefined || context.sessionManager.getSessionId() !== targetSessionID) {
|
|
54566
53861
|
throw new Error(`Envoy has no active session for Legion notice subscription: ${targetSessionID}`);
|
|
54567
53862
|
}
|
|
53863
|
+
requireInbound();
|
|
54568
53864
|
if (registrationState.establishedFor() !== targetSessionID) {
|
|
54569
53865
|
await establishForBridge(context);
|
|
54570
53866
|
}
|
|
@@ -54578,15 +53874,16 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
|
|
|
54578
53874
|
}
|
|
54579
53875
|
const snapshot = registrationState.roleSnapshot(topic);
|
|
54580
53876
|
try {
|
|
54581
|
-
if (!
|
|
53877
|
+
if (!followUnlessRoleEnds(topic, snapshot))
|
|
54582
53878
|
return;
|
|
53879
|
+
await registerSession();
|
|
54583
53880
|
} catch (error) {
|
|
54584
53881
|
if (registrationState.roleEndCount() === snapshot.endsBefore) {
|
|
53882
|
+
unfollow(topic);
|
|
54585
53883
|
registrationState.unmarkRoleBoundSubjects(marked);
|
|
54586
53884
|
}
|
|
54587
53885
|
throw error;
|
|
54588
53886
|
}
|
|
54589
|
-
await registerSession();
|
|
54590
53887
|
};
|
|
54591
53888
|
const claimInstance = {
|
|
54592
53889
|
claim,
|
|
@@ -54624,13 +53921,13 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
|
|
|
54624
53921
|
try {
|
|
54625
53922
|
await establish();
|
|
54626
53923
|
} catch (error) {
|
|
54627
|
-
context.ui.notify(`envoy:
|
|
53924
|
+
context.ui.notify(`envoy: this session is not registered (${messageFor(error)}); retrying in the background`, "warning");
|
|
54628
53925
|
let attempting = false;
|
|
54629
53926
|
context.setInterval(() => {
|
|
54630
53927
|
if (established || attempting)
|
|
54631
53928
|
return;
|
|
54632
53929
|
attempting = true;
|
|
54633
|
-
establish().then(() => context.ui.notify("envoy:
|
|
53930
|
+
establish().then(() => context.ui.notify("envoy: this session is registered", "warning")).catch(() => {
|
|
54634
53931
|
return;
|
|
54635
53932
|
}).finally(() => {
|
|
54636
53933
|
attempting = false;
|
|
@@ -54727,9 +54024,7 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
|
|
|
54727
54024
|
clearTimeout(timer);
|
|
54728
54025
|
connection = undefined;
|
|
54729
54026
|
activeSessionContext = undefined;
|
|
54730
|
-
|
|
54731
|
-
intentionallyClosed.clear();
|
|
54732
|
-
awaitingRetry.clear();
|
|
54027
|
+
followed.clear();
|
|
54733
54028
|
unanswered.clear();
|
|
54734
54029
|
agentStreamControl = undefined;
|
|
54735
54030
|
agentStreamControlSession = "";
|
|
@@ -55042,16 +54337,13 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
|
|
|
55042
54337
|
const { client } = requireEnvoy();
|
|
55043
54338
|
switch (operation) {
|
|
55044
54339
|
case EnvoyToolOperation.subscribe: {
|
|
54340
|
+
requireInbound();
|
|
54341
|
+
const requested = topicsFor(parameters);
|
|
54342
|
+
refuseUncapturedTopics(sessionID, agentSubject(sessionID), requested);
|
|
55045
54343
|
const added = [];
|
|
55046
54344
|
const already = [];
|
|
55047
|
-
|
|
55048
|
-
|
|
55049
|
-
try {
|
|
55050
|
-
(await subscribe(topic) ? added : already).push(topic);
|
|
55051
|
-
} catch (error) {
|
|
55052
|
-
openFailure = error;
|
|
55053
|
-
break;
|
|
55054
|
-
}
|
|
54345
|
+
for (const topic of requested) {
|
|
54346
|
+
(follow(topic) ? added : already).push(topic);
|
|
55055
54347
|
}
|
|
55056
54348
|
let warnings;
|
|
55057
54349
|
let registrationError;
|
|
@@ -55061,11 +54353,8 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
|
|
|
55061
54353
|
} catch (error) {
|
|
55062
54354
|
registrationError = messageFor(error);
|
|
55063
54355
|
}
|
|
55064
|
-
await
|
|
55065
|
-
triggerReplay();
|
|
54356
|
+
await ledgerFollowedChanged();
|
|
55066
54357
|
}
|
|
55067
|
-
if (openFailure !== undefined)
|
|
55068
|
-
throw openFailure;
|
|
55069
54358
|
const subscribed = `Subscribed: ${added.join(", ") || "(none new)"}`;
|
|
55070
54359
|
return toolSuccess(warnings === undefined || warnings.length === 0 ? subscribed : `${subscribed}
|
|
55071
54360
|
Warnings: ${warnings.join("; ")}`, {
|
|
@@ -55077,11 +54366,11 @@ Warnings: ${warnings.join("; ")}`, {
|
|
|
55077
54366
|
}
|
|
55078
54367
|
case EnvoyToolOperation.unsubscribe: {
|
|
55079
54368
|
const inbox = agentSubject(sessionID);
|
|
55080
|
-
const candidates = topicsFor(parameters, [...
|
|
54369
|
+
const candidates = topicsFor(parameters, [...followed]).filter((subject) => subject !== inbox);
|
|
55081
54370
|
const kept = candidates.filter(registrationState.isRoleBound);
|
|
55082
|
-
const removed = candidates.filter((subject) => !registrationState.isRoleBound(subject)).filter(
|
|
54371
|
+
const removed = candidates.filter((subject) => !registrationState.isRoleBound(subject)).filter((subject) => followed.delete(subject));
|
|
55083
54372
|
if (removed.length > 0)
|
|
55084
|
-
await
|
|
54373
|
+
await ledgerFollowedChanged();
|
|
55085
54374
|
const registryRemoved = removed.filter((topic) => !topic.startsWith(ROLE_TOPIC_PREFIX));
|
|
55086
54375
|
const registrationError = registryRemoved.length === 0 ? undefined : await client.unsubscribe({ sessionID, topics: registryRemoved }).then(registerSession).then(() => {
|
|
55087
54376
|
return;
|
|
@@ -55096,7 +54385,7 @@ Kept (they last while this session holds role ${registrationState.heldRole()}):
|
|
|
55096
54385
|
}
|
|
55097
54386
|
case EnvoyToolOperation.listInterests: {
|
|
55098
54387
|
const registry = await client.getInterest(sessionID);
|
|
55099
|
-
const interests = mergeInterestSources(registry.topics, [...
|
|
54388
|
+
const interests = mergeInterestSources(registry.topics, [...followed]);
|
|
55100
54389
|
return toolSuccess(JSON.stringify({ ...registry, topics: [...interests.keys()] }, null, 2), {
|
|
55101
54390
|
interests: [...interests].map(([topic, source]) => ({ topic, source }))
|
|
55102
54391
|
});
|
|
@@ -55138,7 +54427,6 @@ Not delivered: that holder is the session this subagent sends as, and the listen
|
|
|
55138
54427
|
topic,
|
|
55139
54428
|
...result.holder === undefined ? {} : { holder: result.holder },
|
|
55140
54429
|
...result.holderState === undefined ? {} : { holder_state: result.holderState },
|
|
55141
|
-
...result.unresponsive.length === 0 ? {} : { unresponsive: result.unresponsive },
|
|
55142
54430
|
...result.kept === undefined ? {} : { kept: result.kept },
|
|
55143
54431
|
...result.keptReason === undefined ? {} : { kept_reason: result.keptReason },
|
|
55144
54432
|
...undelivered ? { undelivered_echo: true } : {}
|
|
@@ -55186,7 +54474,7 @@ Not delivered: that holder is the session this subagent sends as, and the listen
|
|
|
55186
54474
|
...subagent === undefined ? {} : { subagent }
|
|
55187
54475
|
}, null, 2), {
|
|
55188
54476
|
sessionID: address,
|
|
55189
|
-
topics: [...
|
|
54477
|
+
topics: [...followed],
|
|
55190
54478
|
...subagent === undefined ? {} : { subagent }
|
|
55191
54479
|
});
|
|
55192
54480
|
}
|