@openclaw/tlon 2026.7.2-beta.3 → 2026.7.2-beta.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api.js +1 -1
- package/dist/{channel-B_FSYQLm.js → channel-Ds41J7__.js} +5 -4
- package/dist/channel-plugin-api.js +1 -1
- package/dist/{channel.runtime-CbQv5emM.js → channel.runtime-B9OMPklT.js} +652 -308
- package/dist/setup-api.js +2 -2
- package/dist/{setup-core-BgykzCYT.js → setup-core-DUM2q1dE.js} +90 -19
- package/dist/{setup-surface-j5Hrbts7.js → setup-surface-1WtsAw4R.js} +1 -1
- package/package.json +79 -33
- package/npm-shrinkwrap.json +0 -544
|
@@ -1,23 +1,23 @@
|
|
|
1
1
|
import { n as createDedupeCache, o as createLoggerBackedRuntime } from "./runtime-api-BXVe40nS.js";
|
|
2
|
-
import { c as
|
|
2
|
+
import { c as normalizeUrbitHostname, d as resolveTlonAccount, f as formatTargetHint, g as resolveTlonOutboundTarget, h as parseTlonTarget, l as validateUrbitBaseUrl, m as parseChannelNest, p as normalizeShip } from "./setup-core-DUM2q1dE.js";
|
|
3
3
|
import { t as getTlonRuntime } from "./runtime-Ck3lNvST.js";
|
|
4
|
-
import { t as tlonSetupWizard } from "./setup-surface-
|
|
4
|
+
import { t as tlonSetupWizard } from "./setup-surface-1WtsAw4R.js";
|
|
5
5
|
import { fetchWithSsrFGuard, ssrfPolicyFromDangerouslyAllowPrivateNetwork } from "openclaw/plugin-sdk/ssrf-runtime";
|
|
6
|
-
import { createMessageReceiptFromOutboundResults } from "openclaw/plugin-sdk/channel-outbound";
|
|
6
|
+
import { bindIngressLifecycleToReplyOptions, createChannelIngressMonitor, createMessageReceiptFromOutboundResults } from "openclaw/plugin-sdk/channel-outbound";
|
|
7
7
|
import { expectDefined } from "openclaw/plugin-sdk/expect-runtime";
|
|
8
8
|
import { asFiniteNumber, normalizeLowercaseStringOrEmpty, uniqueStrings } from "openclaw/plugin-sdk/string-coerce-runtime";
|
|
9
9
|
import crypto, { randomBytes, randomUUID } from "node:crypto";
|
|
10
10
|
import { readProviderJsonResponse, readResponseTextLimited } from "openclaw/plugin-sdk/provider-http";
|
|
11
|
+
import { runChannelProbe, sliceUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
|
|
11
12
|
import { resolveHumanDelayConfig } from "openclaw/plugin-sdk/agent-runtime";
|
|
12
13
|
import { createChannelInboundEnvelopeBuilder, implicitMentionKindWhen, resolveInboundMentionDecision } from "openclaw/plugin-sdk/channel-inbound";
|
|
13
14
|
import { sleepWithAbort } from "openclaw/plugin-sdk/runtime-env";
|
|
14
|
-
import { sliceUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
|
|
15
15
|
import { da, scot } from "@urbit/aura";
|
|
16
16
|
import { Readable } from "node:stream";
|
|
17
17
|
import { resolveTimerTimeoutMs } from "openclaw/plugin-sdk/number-runtime";
|
|
18
18
|
import { resolveAllowlistMatchByCandidates } from "openclaw/plugin-sdk/allow-from";
|
|
19
19
|
import { resolveChannelImplicitMentions, resolveStableChannelMessageIngress } from "openclaw/plugin-sdk/channel-ingress-runtime";
|
|
20
|
-
import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
|
|
20
|
+
import { collectErrorGraphCandidates, formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
|
|
21
21
|
import { mkdir, writeFile } from "node:fs/promises";
|
|
22
22
|
import * as path from "node:path";
|
|
23
23
|
import { extensionForMime } from "openclaw/plugin-sdk/media-mime";
|
|
@@ -288,6 +288,7 @@ async function urbitFetch(params) {
|
|
|
288
288
|
}
|
|
289
289
|
//#endregion
|
|
290
290
|
//#region extensions/tlon/src/urbit/auth.ts
|
|
291
|
+
const MAX_AUTH_BODY_DRAIN_BYTES = 64 * 1024;
|
|
291
292
|
async function authenticate(url, code, options = {}) {
|
|
292
293
|
const { response, release } = await urbitFetch({
|
|
293
294
|
baseUrl: url,
|
|
@@ -305,8 +306,11 @@ async function authenticate(url, code, options = {}) {
|
|
|
305
306
|
auditContext: "tlon-urbit-login"
|
|
306
307
|
});
|
|
307
308
|
try {
|
|
308
|
-
if (!response.ok)
|
|
309
|
-
|
|
309
|
+
if (!response.ok) {
|
|
310
|
+
await response.body?.cancel().catch(() => void 0);
|
|
311
|
+
throw new UrbitAuthError("auth_failed", `Login failed with status ${response.status}`);
|
|
312
|
+
}
|
|
313
|
+
await readResponseTextLimited(response, MAX_AUTH_BODY_DRAIN_BYTES).catch(() => void 0);
|
|
310
314
|
const cookie = response.headers.get("set-cookie");
|
|
311
315
|
if (!cookie) throw new UrbitAuthError("missing_cookie", "No authentication cookie received");
|
|
312
316
|
return cookie;
|
|
@@ -481,6 +485,158 @@ function processInlinesForImages(inlines) {
|
|
|
481
485
|
imageBlocks
|
|
482
486
|
};
|
|
483
487
|
}
|
|
488
|
+
function parseInlinesWithBreaks(text) {
|
|
489
|
+
const withBreaks = [];
|
|
490
|
+
for (const inline of parseInlineMarkdown(text)) {
|
|
491
|
+
if (typeof inline !== "string" || !inline.includes("\n")) {
|
|
492
|
+
withBreaks.push(inline);
|
|
493
|
+
continue;
|
|
494
|
+
}
|
|
495
|
+
const parts = inline.split("\n");
|
|
496
|
+
for (const [index, part] of parts.entries()) {
|
|
497
|
+
if (part) withBreaks.push(part);
|
|
498
|
+
if (index < parts.length - 1) withBreaks.push({ break: null });
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
return processInlinesForImages(withBreaks);
|
|
502
|
+
}
|
|
503
|
+
const MARKDOWN_LIST_ITEM_PATTERN = /^([ \t]*)([-+*]|\d{1,9}[.)])(?:([ \t]+)(.*))?$/;
|
|
504
|
+
function isMarkdownThematicBreak(text) {
|
|
505
|
+
return /^(?:(?:\*\s*){3,}|(?:-\s*){3,}|(?:_\s*){3,})$/.test(text);
|
|
506
|
+
}
|
|
507
|
+
function startsListBlockSyntax(text) {
|
|
508
|
+
return /^(`{3,}|~{3,})/.test(text) || text.startsWith(">") || /^#{1,6}(?:\s|$)/.test(text) || isMarkdownThematicBreak(text) || /^(?:[-+*]|\d{1,9}[.)])(?:\s|$)/.test(text);
|
|
509
|
+
}
|
|
510
|
+
function whitespaceColumns(text, startColumn = 0) {
|
|
511
|
+
let column = startColumn;
|
|
512
|
+
for (const char of text) column += char === " " ? 4 - column % 4 : 1;
|
|
513
|
+
return column;
|
|
514
|
+
}
|
|
515
|
+
function parseMarkdownListItem(line) {
|
|
516
|
+
const match = line.match(MARKDOWN_LIST_ITEM_PATTERN);
|
|
517
|
+
if (!match || isMarkdownThematicBreak(line.trim())) return;
|
|
518
|
+
const marker = expectDefined(match[2], "list marker capture");
|
|
519
|
+
const markerType = /^\d/.test(marker) ? "ordered" : "unordered";
|
|
520
|
+
const padding = match[3] ?? " ";
|
|
521
|
+
const sourceBody = match[4] ?? "";
|
|
522
|
+
let body = sourceBody;
|
|
523
|
+
const task = body.match(/^\[([\t xX])\](?:\s+(.*))?$/);
|
|
524
|
+
let checked;
|
|
525
|
+
if (task) {
|
|
526
|
+
checked = expectDefined(task[1], "task state capture").toLowerCase() === "x";
|
|
527
|
+
body = task[2] ?? "";
|
|
528
|
+
}
|
|
529
|
+
const { inlines, imageBlocks } = parseInlinesWithBreaks(body);
|
|
530
|
+
const indent = whitespaceColumns(expectDefined(match[1], "list indent capture"));
|
|
531
|
+
const markerEnd = indent + marker.length;
|
|
532
|
+
const contentIndent = whitespaceColumns(padding, markerEnd);
|
|
533
|
+
return {
|
|
534
|
+
indent,
|
|
535
|
+
contentIndent,
|
|
536
|
+
markerType,
|
|
537
|
+
markerKey: markerType === "ordered" ? marker.slice(-1) : marker,
|
|
538
|
+
...markerType === "ordered" ? { orderedStart: Number.parseInt(marker, 10) } : {},
|
|
539
|
+
hasSourceBody: sourceBody.length > 0,
|
|
540
|
+
hasBlockBody: sourceBody.length > 0 && (contentIndent - markerEnd >= 5 || startsListBlockSyntax(sourceBody)),
|
|
541
|
+
hasImages: imageBlocks.length > 0,
|
|
542
|
+
content: inlines,
|
|
543
|
+
...checked === void 0 ? {} : { checked }
|
|
544
|
+
};
|
|
545
|
+
}
|
|
546
|
+
function lineIndent(line) {
|
|
547
|
+
return whitespaceColumns(line.match(/^[ \t]*/)?.[0] ?? "");
|
|
548
|
+
}
|
|
549
|
+
function startsTopLevelStoryBlock(line) {
|
|
550
|
+
return /^(#{1,6})\s+(.+)$/.test(line) || line.startsWith("```") || line.startsWith("> ") || /^(-{3,}|\*{3,})$/.test(line.trim());
|
|
551
|
+
}
|
|
552
|
+
function listItemContent(item) {
|
|
553
|
+
return item.checked === void 0 ? item.content : [{ task: {
|
|
554
|
+
checked: item.checked,
|
|
555
|
+
content: item.content
|
|
556
|
+
} }];
|
|
557
|
+
}
|
|
558
|
+
function canInterruptWithListItem(item) {
|
|
559
|
+
return item.hasSourceBody && (item.markerType === "unordered" || item.orderedStart === 1);
|
|
560
|
+
}
|
|
561
|
+
function parseListingBlock(lines, startIndex) {
|
|
562
|
+
const first = parseMarkdownListItem(expectDefined(lines[startIndex], "list start line"));
|
|
563
|
+
if (!first) return;
|
|
564
|
+
if (first.indent >= 4 || first.markerType === "ordered" && first.orderedStart !== 1) return;
|
|
565
|
+
function parseLevel(index, minIndent, markerKey) {
|
|
566
|
+
const firstItem = parseMarkdownListItem(expectDefined(lines[index], "list level start"));
|
|
567
|
+
if (!firstItem || firstItem.indent < minIndent || firstItem.indent > minIndent + 3 || firstItem.markerType === "ordered" && firstItem.orderedStart !== 1) return;
|
|
568
|
+
const items = [];
|
|
569
|
+
const markerType = firstItem.markerType;
|
|
570
|
+
let allTasks = true;
|
|
571
|
+
let cursor = index;
|
|
572
|
+
while (cursor < lines.length) {
|
|
573
|
+
const item = parseMarkdownListItem(expectDefined(lines[cursor], "list line index"));
|
|
574
|
+
if (!item || item.indent < minIndent || item.indent > minIndent + 3 || item.markerKey !== markerKey) break;
|
|
575
|
+
if (item.hasBlockBody || item.hasImages) return;
|
|
576
|
+
allTasks &&= item.checked !== void 0;
|
|
577
|
+
cursor++;
|
|
578
|
+
while (cursor < lines.length) {
|
|
579
|
+
const continuationLine = expectDefined(lines[cursor], "continuation line index");
|
|
580
|
+
if (continuationLine.trim() === "") {
|
|
581
|
+
let nextContentIndex = cursor + 1;
|
|
582
|
+
while (lines[nextContentIndex]?.trim() === "") nextContentIndex++;
|
|
583
|
+
const nextContent = lines.at(nextContentIndex);
|
|
584
|
+
if (nextContent === void 0) break;
|
|
585
|
+
if (parseMarkdownListItem(nextContent)) {
|
|
586
|
+
cursor = nextContentIndex;
|
|
587
|
+
continue;
|
|
588
|
+
}
|
|
589
|
+
if (lineIndent(nextContent) > item.indent) return;
|
|
590
|
+
break;
|
|
591
|
+
}
|
|
592
|
+
if (parseMarkdownListItem(continuationLine)) break;
|
|
593
|
+
if (lineIndent(continuationLine) <= item.indent && startsTopLevelStoryBlock(continuationLine)) break;
|
|
594
|
+
return;
|
|
595
|
+
}
|
|
596
|
+
const childLine = lines.at(cursor);
|
|
597
|
+
const child = childLine === void 0 ? void 0 : parseMarkdownListItem(childLine);
|
|
598
|
+
if (child !== void 0 && child.markerKey === markerKey && child.indent >= minIndent && child.indent <= minIndent + 3 && child.indent < item.contentIndent) {
|
|
599
|
+
items.push({ item: listItemContent(item) });
|
|
600
|
+
continue;
|
|
601
|
+
}
|
|
602
|
+
if (child && child.markerKey !== markerKey && !canInterruptWithListItem(child)) return;
|
|
603
|
+
if (child && child.indent >= item.contentIndent && !canInterruptWithListItem(child)) return;
|
|
604
|
+
if (child && child.indent > item.indent) {
|
|
605
|
+
if (child.indent < item.contentIndent || child.indent >= item.contentIndent + 4) return;
|
|
606
|
+
const nested = parseLevel(cursor, item.contentIndent, child.markerKey);
|
|
607
|
+
if (!nested) return;
|
|
608
|
+
items.push({ list: {
|
|
609
|
+
type: nested.type,
|
|
610
|
+
contents: listItemContent(item),
|
|
611
|
+
items: nested.items
|
|
612
|
+
} });
|
|
613
|
+
cursor = nested.nextIndex;
|
|
614
|
+
const strandedChildLine = lines.at(cursor);
|
|
615
|
+
const strandedChild = strandedChildLine === void 0 ? void 0 : parseMarkdownListItem(strandedChildLine);
|
|
616
|
+
if (!(strandedChild !== void 0 && strandedChild.markerKey === markerKey && strandedChild.indent >= minIndent && strandedChild.indent <= minIndent + 3 && strandedChild.indent < item.contentIndent) && strandedChild && strandedChild.indent > item.indent) return;
|
|
617
|
+
let trailingIndex = cursor;
|
|
618
|
+
while (lines[trailingIndex]?.trim() === "") trailingIndex++;
|
|
619
|
+
const trailingLine = lines.at(trailingIndex);
|
|
620
|
+
if (trailingLine !== void 0 && !parseMarkdownListItem(trailingLine) && lineIndent(trailingLine) > item.indent) return;
|
|
621
|
+
} else items.push({ item: listItemContent(item) });
|
|
622
|
+
}
|
|
623
|
+
return {
|
|
624
|
+
type: markerType === "unordered" && allTasks && items.length > 0 ? "tasklist" : markerType,
|
|
625
|
+
items,
|
|
626
|
+
nextIndex: cursor
|
|
627
|
+
};
|
|
628
|
+
}
|
|
629
|
+
const parsed = parseLevel(startIndex, 0, first.markerKey);
|
|
630
|
+
if (!parsed) return;
|
|
631
|
+
return {
|
|
632
|
+
verses: [{ block: { listing: { list: {
|
|
633
|
+
type: parsed.type,
|
|
634
|
+
contents: [],
|
|
635
|
+
items: parsed.items
|
|
636
|
+
} } } }],
|
|
637
|
+
nextIndex: parsed.nextIndex
|
|
638
|
+
};
|
|
639
|
+
}
|
|
484
640
|
/**
|
|
485
641
|
* Convert markdown text to Tlon story format
|
|
486
642
|
*/
|
|
@@ -488,8 +644,11 @@ function markdownToStory(markdown) {
|
|
|
488
644
|
const story = [];
|
|
489
645
|
const lines = markdown.split("\n");
|
|
490
646
|
let i = 0;
|
|
647
|
+
let preservedListMarkerKey;
|
|
491
648
|
while (i < lines.length) {
|
|
492
649
|
const line = expectDefined(lines[i], "Markdown line index is in bounds");
|
|
650
|
+
const lineListItem = parseMarkdownListItem(line);
|
|
651
|
+
if (line.trim() !== "" && preservedListMarkerKey !== void 0 && (lineListItem !== void 0 ? lineListItem.markerKey !== preservedListMarkerKey : lineIndent(line) === 0)) preservedListMarkerKey = void 0;
|
|
493
652
|
if (line.startsWith("```")) {
|
|
494
653
|
const lang = line.slice(3).trim() || "plaintext";
|
|
495
654
|
const codeLines = [];
|
|
@@ -538,25 +697,33 @@ function markdownToStory(markdown) {
|
|
|
538
697
|
i++;
|
|
539
698
|
continue;
|
|
540
699
|
}
|
|
700
|
+
const preservesLooseList = preservedListMarkerKey !== void 0 && lineListItem?.markerKey === preservedListMarkerKey;
|
|
701
|
+
const listing = preservesLooseList ? void 0 : parseListingBlock(lines, i);
|
|
702
|
+
if (listing) {
|
|
703
|
+
story.push(...listing.verses);
|
|
704
|
+
i = listing.nextIndex;
|
|
705
|
+
preservedListMarkerKey = void 0;
|
|
706
|
+
continue;
|
|
707
|
+
}
|
|
708
|
+
if (lineListItem) preservedListMarkerKey = lineListItem.markerKey;
|
|
709
|
+
let preserveListText = preservesLooseList || MARKDOWN_LIST_ITEM_PATTERN.test(line);
|
|
541
710
|
const paragraphLines = [];
|
|
542
711
|
while (true) {
|
|
543
712
|
const paragraphLine = lines.at(i);
|
|
544
713
|
if (paragraphLine === void 0 || paragraphLine.trim() === "" || paragraphLine.startsWith("#") || paragraphLine.startsWith("```") || paragraphLine.startsWith("> ") || /^(-{3,}|\*{3,})$/.test(paragraphLine.trim())) break;
|
|
714
|
+
if (!preserveListText && MARKDOWN_LIST_ITEM_PATTERN.test(paragraphLine)) {
|
|
715
|
+
const item = parseMarkdownListItem(paragraphLine);
|
|
716
|
+
const candidate = parseListingBlock(lines, i);
|
|
717
|
+
if (item?.hasSourceBody === true && candidate) break;
|
|
718
|
+
preserveListText = true;
|
|
719
|
+
if (item) preservedListMarkerKey = item.markerKey;
|
|
720
|
+
}
|
|
545
721
|
paragraphLines.push(paragraphLine);
|
|
546
722
|
i++;
|
|
547
723
|
}
|
|
548
724
|
if (paragraphLines.length > 0) {
|
|
549
|
-
const inlines =
|
|
550
|
-
|
|
551
|
-
for (const inline of inlines) if (typeof inline === "string" && inline.includes("\n")) {
|
|
552
|
-
const parts = inline.split("\n");
|
|
553
|
-
for (const [j, part] of parts.entries()) {
|
|
554
|
-
if (part) withBreaks.push(part);
|
|
555
|
-
if (j < parts.length - 1) withBreaks.push({ break: null });
|
|
556
|
-
}
|
|
557
|
-
} else withBreaks.push(inline);
|
|
558
|
-
const { inlines: cleanInlines, imageBlocks } = processInlinesForImages(withBreaks);
|
|
559
|
-
if (cleanInlines.length > 0) story.push({ inline: cleanInlines });
|
|
725
|
+
const { inlines, imageBlocks } = parseInlinesWithBreaks(paragraphLines.join("\n"));
|
|
726
|
+
if (inlines.length > 0) story.push({ inline: inlines });
|
|
560
727
|
story.push(...imageBlocks);
|
|
561
728
|
}
|
|
562
729
|
}
|
|
@@ -721,7 +888,11 @@ async function pokeUrbitChannel(deps, params) {
|
|
|
721
888
|
try {
|
|
722
889
|
if (!response.ok && response.status !== 204) {
|
|
723
890
|
const errorText = await readResponseTextLimited(response, TLON_ERROR_BODY_LIMIT_BYTES).catch(() => "");
|
|
724
|
-
throw new
|
|
891
|
+
throw new UrbitHttpError({
|
|
892
|
+
operation: "Poke",
|
|
893
|
+
status: response.status,
|
|
894
|
+
bodyText: errorText || void 0
|
|
895
|
+
});
|
|
725
896
|
}
|
|
726
897
|
return pokeId;
|
|
727
898
|
} finally {
|
|
@@ -744,7 +915,10 @@ async function scryUrbitPath(deps, params) {
|
|
|
744
915
|
auditContext: params.auditContext
|
|
745
916
|
});
|
|
746
917
|
try {
|
|
747
|
-
if (!response.ok) throw new
|
|
918
|
+
if (!response.ok) throw new UrbitHttpError({
|
|
919
|
+
operation: `Scry for path ${params.path}`,
|
|
920
|
+
status: response.status
|
|
921
|
+
});
|
|
748
922
|
return await readProviderJsonResponse(response, `Tlon scry response for path ${params.path}`);
|
|
749
923
|
} finally {
|
|
750
924
|
await release();
|
|
@@ -845,6 +1019,18 @@ var UrbitSSEClient = class {
|
|
|
845
1019
|
fetchImpl: this.fetchImpl
|
|
846
1020
|
};
|
|
847
1021
|
}
|
|
1022
|
+
resetChannelIdentity() {
|
|
1023
|
+
this.channelId = `${Math.floor(Date.now() / 1e3)}-${randomUUID()}`;
|
|
1024
|
+
this.channelUrl = new URL(`/~/channel/${this.channelId}`, this.url).toString();
|
|
1025
|
+
this.lastHeardEventId = -1;
|
|
1026
|
+
this.lastAcknowledgedEventId = -1;
|
|
1027
|
+
}
|
|
1028
|
+
async createCurrentChannel() {
|
|
1029
|
+
await ensureUrbitChannelOpen(this.channelRequestContext(), {
|
|
1030
|
+
createBody: this.subscriptions,
|
|
1031
|
+
createAuditContext: "tlon-urbit-channel-create"
|
|
1032
|
+
});
|
|
1033
|
+
}
|
|
848
1034
|
async subscribe(params) {
|
|
849
1035
|
const subId = this.subscriptions.length + 1;
|
|
850
1036
|
const subscription = {
|
|
@@ -882,10 +1068,9 @@ var UrbitSSEClient = class {
|
|
|
882
1068
|
}
|
|
883
1069
|
}
|
|
884
1070
|
async connect() {
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
});
|
|
1071
|
+
this.lastHeardEventId = -1;
|
|
1072
|
+
this.lastAcknowledgedEventId = -1;
|
|
1073
|
+
await this.createCurrentChannel();
|
|
889
1074
|
await this.openStream();
|
|
890
1075
|
this.isConnected = true;
|
|
891
1076
|
this.reconnectAttempts = 0;
|
|
@@ -920,7 +1105,10 @@ var UrbitSSEClient = class {
|
|
|
920
1105
|
if (!response.ok) {
|
|
921
1106
|
this.streamRelease = null;
|
|
922
1107
|
await release();
|
|
923
|
-
throw new
|
|
1108
|
+
throw new UrbitHttpError({
|
|
1109
|
+
operation: "Stream connection",
|
|
1110
|
+
status: response.status
|
|
1111
|
+
});
|
|
924
1112
|
}
|
|
925
1113
|
this.processStream(response.body).catch((error) => {
|
|
926
1114
|
if (!this.aborted) {
|
|
@@ -945,12 +1133,12 @@ var UrbitSSEClient = class {
|
|
|
945
1133
|
buffer += text;
|
|
946
1134
|
bufferBytes = nextBytes;
|
|
947
1135
|
};
|
|
948
|
-
const consumeText = (text) => {
|
|
1136
|
+
const consumeText = async (text) => {
|
|
949
1137
|
let offset = 0;
|
|
950
1138
|
if (pendingDelimiterNewline && text.length > 0) {
|
|
951
1139
|
pendingDelimiterNewline = false;
|
|
952
1140
|
if (text.startsWith("\n")) {
|
|
953
|
-
this.processEvent(buffer);
|
|
1141
|
+
await this.processEvent(buffer);
|
|
954
1142
|
buffer = "";
|
|
955
1143
|
bufferBytes = 0;
|
|
956
1144
|
offset = 1;
|
|
@@ -965,7 +1153,7 @@ var UrbitSSEClient = class {
|
|
|
965
1153
|
return;
|
|
966
1154
|
}
|
|
967
1155
|
appendPending(text.slice(offset, eventEnd));
|
|
968
|
-
this.processEvent(buffer);
|
|
1156
|
+
await this.processEvent(buffer);
|
|
969
1157
|
buffer = "";
|
|
970
1158
|
bufferBytes = 0;
|
|
971
1159
|
offset = eventEnd + 2;
|
|
@@ -975,11 +1163,11 @@ var UrbitSSEClient = class {
|
|
|
975
1163
|
for await (const chunk of stream) {
|
|
976
1164
|
if (this.aborted) break;
|
|
977
1165
|
if (typeof chunk === "string") {
|
|
978
|
-
consumeText(decoder.decode());
|
|
979
|
-
consumeText(chunk);
|
|
980
|
-
} else consumeText(decoder.decode(chunk, { stream: true }));
|
|
1166
|
+
await consumeText(decoder.decode());
|
|
1167
|
+
await consumeText(chunk);
|
|
1168
|
+
} else await consumeText(decoder.decode(chunk, { stream: true }));
|
|
981
1169
|
}
|
|
982
|
-
consumeText(decoder.decode());
|
|
1170
|
+
await consumeText(decoder.decode());
|
|
983
1171
|
} finally {
|
|
984
1172
|
if (this.streamRelease) {
|
|
985
1173
|
const release = this.streamRelease;
|
|
@@ -994,7 +1182,7 @@ var UrbitSSEClient = class {
|
|
|
994
1182
|
}
|
|
995
1183
|
}
|
|
996
1184
|
}
|
|
997
|
-
processEvent(eventData) {
|
|
1185
|
+
async processEvent(eventData) {
|
|
998
1186
|
const lines = eventData.split("\n");
|
|
999
1187
|
let data = null;
|
|
1000
1188
|
let eventId = null;
|
|
@@ -1003,35 +1191,33 @@ var UrbitSSEClient = class {
|
|
|
1003
1191
|
if (line.startsWith("data: ")) data = line.slice(6);
|
|
1004
1192
|
}
|
|
1005
1193
|
if (!data) return;
|
|
1006
|
-
|
|
1007
|
-
if (eventId > this.lastHeardEventId) {
|
|
1008
|
-
this.lastHeardEventId = eventId;
|
|
1009
|
-
if (eventId - this.lastAcknowledgedEventId > this.ackThreshold) {
|
|
1010
|
-
this.logger.log?.(`[SSE] Acking event ${eventId} (last acked: ${this.lastAcknowledgedEventId})`);
|
|
1011
|
-
this.ack(eventId).catch((err) => {
|
|
1012
|
-
this.logger.error?.(`Failed to ack event ${eventId}: ${String(err)}`);
|
|
1013
|
-
});
|
|
1014
|
-
}
|
|
1015
|
-
}
|
|
1016
|
-
}
|
|
1194
|
+
let parsed;
|
|
1017
1195
|
try {
|
|
1018
|
-
|
|
1019
|
-
if (parsed.response === "quit") {
|
|
1020
|
-
if (parsed.id) {
|
|
1021
|
-
const handlers = this.eventHandlers.get(parsed.id);
|
|
1022
|
-
if (handlers?.quit) handlers.quit();
|
|
1023
|
-
}
|
|
1024
|
-
return;
|
|
1025
|
-
}
|
|
1026
|
-
if (parsed.id && this.eventHandlers.has(parsed.id)) {
|
|
1027
|
-
const { event } = this.eventHandlers.get(parsed.id) ?? {};
|
|
1028
|
-
if (event && parsed.json) event(parsed.json);
|
|
1029
|
-
} else if (parsed.json) {
|
|
1030
|
-
for (const { event } of this.eventHandlers.values()) if (event) event(parsed.json);
|
|
1031
|
-
}
|
|
1196
|
+
parsed = parseUrbitSsePayload(data);
|
|
1032
1197
|
} catch (error) {
|
|
1033
1198
|
this.logger.error?.(`Error parsing SSE event: ${String(error)}`);
|
|
1199
|
+
await this.acknowledgeHandledEventIfNeeded(eventId);
|
|
1200
|
+
return;
|
|
1201
|
+
}
|
|
1202
|
+
if (parsed.response === "quit") {
|
|
1203
|
+
if (parsed.id) {
|
|
1204
|
+
const handlers = this.eventHandlers.get(parsed.id);
|
|
1205
|
+
if (handlers?.quit) handlers.quit();
|
|
1206
|
+
}
|
|
1207
|
+
} else if (parsed.id && this.eventHandlers.has(parsed.id)) {
|
|
1208
|
+
const { event } = this.eventHandlers.get(parsed.id) ?? {};
|
|
1209
|
+
if (event && parsed.json) await event(parsed.json);
|
|
1210
|
+
} else if (parsed.json) {
|
|
1211
|
+
for (const { event } of this.eventHandlers.values()) if (event) await event(parsed.json);
|
|
1034
1212
|
}
|
|
1213
|
+
await this.acknowledgeHandledEventIfNeeded(eventId);
|
|
1214
|
+
}
|
|
1215
|
+
async acknowledgeHandledEventIfNeeded(eventId) {
|
|
1216
|
+
if (eventId === null || eventId <= this.lastAcknowledgedEventId) return;
|
|
1217
|
+
this.lastHeardEventId = Math.max(this.lastHeardEventId, eventId);
|
|
1218
|
+
if (this.lastHeardEventId - this.lastAcknowledgedEventId <= this.ackThreshold) return;
|
|
1219
|
+
this.logger.log?.(`[SSE] Acking event ${this.lastHeardEventId} (last acked: ${this.lastAcknowledgedEventId})`);
|
|
1220
|
+
await this.ack(this.lastHeardEventId);
|
|
1035
1221
|
}
|
|
1036
1222
|
async poke(params) {
|
|
1037
1223
|
return await pokeUrbitChannel(this.channelRequestContext(), {
|
|
@@ -1059,7 +1245,6 @@ var UrbitSSEClient = class {
|
|
|
1059
1245
|
this.cookie = normalizeUrbitCookie(newCookie);
|
|
1060
1246
|
}
|
|
1061
1247
|
async ack(eventId) {
|
|
1062
|
-
this.lastAcknowledgedEventId = eventId;
|
|
1063
1248
|
const ackData = {
|
|
1064
1249
|
id: Date.now(),
|
|
1065
1250
|
action: "ack",
|
|
@@ -1071,6 +1256,7 @@ var UrbitSSEClient = class {
|
|
|
1071
1256
|
});
|
|
1072
1257
|
try {
|
|
1073
1258
|
if (!response.ok) throw new Error(`Ack failed with status ${response.status}`);
|
|
1259
|
+
this.lastAcknowledgedEventId = eventId;
|
|
1074
1260
|
} finally {
|
|
1075
1261
|
await release();
|
|
1076
1262
|
}
|
|
@@ -1095,21 +1281,32 @@ var UrbitSSEClient = class {
|
|
|
1095
1281
|
await new Promise((resolve) => {
|
|
1096
1282
|
setTimeout(resolve, delay);
|
|
1097
1283
|
});
|
|
1284
|
+
if (this.aborted || !this.autoReconnect) return;
|
|
1098
1285
|
try {
|
|
1099
|
-
this.channelId = `${Math.floor(Date.now() / 1e3)}-${randomUUID()}`;
|
|
1100
|
-
this.channelUrl = new URL(`/~/channel/${this.channelId}`, this.url).toString();
|
|
1101
1286
|
if (this.onReconnect) await this.onReconnect(this);
|
|
1102
|
-
|
|
1287
|
+
try {
|
|
1288
|
+
await this.openStream();
|
|
1289
|
+
} catch (error) {
|
|
1290
|
+
if (!(error instanceof UrbitHttpError) || error.status !== 404) throw error;
|
|
1291
|
+
this.resetChannelIdentity();
|
|
1292
|
+
await this.createCurrentChannel();
|
|
1293
|
+
await this.openStream();
|
|
1294
|
+
}
|
|
1295
|
+
this.isConnected = true;
|
|
1296
|
+
this.reconnectAttempts = 0;
|
|
1103
1297
|
this.logger.log?.("[SSE] Reconnection successful!");
|
|
1104
1298
|
} catch (error) {
|
|
1105
1299
|
this.logger.error?.(`[SSE] Reconnection failed: ${String(error)}`);
|
|
1106
1300
|
await this.attemptReconnect();
|
|
1107
1301
|
}
|
|
1108
1302
|
}
|
|
1109
|
-
|
|
1303
|
+
stopReceiving() {
|
|
1110
1304
|
this.aborted = true;
|
|
1111
1305
|
this.isConnected = false;
|
|
1112
1306
|
this.streamController?.abort();
|
|
1307
|
+
}
|
|
1308
|
+
async close() {
|
|
1309
|
+
this.stopReceiving();
|
|
1113
1310
|
try {
|
|
1114
1311
|
const unsubscribes = this.subscriptions.map((sub) => ({
|
|
1115
1312
|
id: sub.id,
|
|
@@ -1122,7 +1319,7 @@ var UrbitSSEClient = class {
|
|
|
1122
1319
|
auditContext: "tlon-urbit-unsubscribe"
|
|
1123
1320
|
});
|
|
1124
1321
|
try {
|
|
1125
|
-
response.body?.cancel();
|
|
1322
|
+
response.body?.cancel().catch(() => void 0);
|
|
1126
1323
|
} finally {
|
|
1127
1324
|
await release();
|
|
1128
1325
|
}
|
|
@@ -1142,7 +1339,7 @@ var UrbitSSEClient = class {
|
|
|
1142
1339
|
auditContext: "tlon-urbit-channel-close"
|
|
1143
1340
|
});
|
|
1144
1341
|
try {
|
|
1145
|
-
response.body?.cancel();
|
|
1342
|
+
response.body?.cancel().catch(() => void 0);
|
|
1146
1343
|
} finally {
|
|
1147
1344
|
await release();
|
|
1148
1345
|
}
|
|
@@ -2046,6 +2243,149 @@ async function fetchThreadHistory(api, channelNest, parentId, count = 50, runtim
|
|
|
2046
2243
|
}
|
|
2047
2244
|
}
|
|
2048
2245
|
//#endregion
|
|
2246
|
+
//#region extensions/tlon/src/monitor/ingress.ts
|
|
2247
|
+
const TLON_INGRESS_PAYLOAD_VERSION = 1;
|
|
2248
|
+
const TLON_INGRESS_POLL_INTERVAL_MS = 1e3;
|
|
2249
|
+
const TLON_INGRESS_PRUNE_INTERVAL_MS = 3600 * 1e3;
|
|
2250
|
+
const TLON_INGRESS_FAILED_TTL_MS = 720 * 60 * 60 * 1e3;
|
|
2251
|
+
const TLON_INGRESS_TOMBSTONE_MAX_ENTRIES = 2e3;
|
|
2252
|
+
var TlonIngressPermanentError = class extends Error {
|
|
2253
|
+
constructor(reason, message, options) {
|
|
2254
|
+
super(message, options);
|
|
2255
|
+
this.reason = reason;
|
|
2256
|
+
this.name = "TlonIngressPermanentError";
|
|
2257
|
+
}
|
|
2258
|
+
};
|
|
2259
|
+
var TlonIngressShutdownError = class extends Error {
|
|
2260
|
+
constructor() {
|
|
2261
|
+
super("Tlon ingress stopped before dispatch adoption.");
|
|
2262
|
+
this.name = "TlonIngressShutdownError";
|
|
2263
|
+
}
|
|
2264
|
+
};
|
|
2265
|
+
function isRecord(value) {
|
|
2266
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2267
|
+
}
|
|
2268
|
+
function nonEmptyString(value) {
|
|
2269
|
+
return typeof value === "string" && value.trim() ? value.trim() : null;
|
|
2270
|
+
}
|
|
2271
|
+
function inspectChannelsEvent(event) {
|
|
2272
|
+
const envelope = isRecord(event) ? event : null;
|
|
2273
|
+
const nest = nonEmptyString(envelope?.nest);
|
|
2274
|
+
const response = isRecord(envelope?.response) ? envelope.response : null;
|
|
2275
|
+
const post = isRecord(response?.post) ? response.post : null;
|
|
2276
|
+
const rPost = isRecord(post?.["r-post"]) ? post["r-post"] : null;
|
|
2277
|
+
const set = isRecord(rPost?.set) ? rPost.set : null;
|
|
2278
|
+
const reply = isRecord(rPost?.reply) ? rPost.reply : null;
|
|
2279
|
+
const rReply = isRecord(reply?.["r-reply"]) ? reply["r-reply"] : null;
|
|
2280
|
+
const replySet = isRecord(rReply?.set) ? rReply.set : null;
|
|
2281
|
+
if (!nest || !isRecord(set?.essay) && !isRecord(replySet?.memo)) return null;
|
|
2282
|
+
const eventId = nonEmptyString(isRecord(replySet?.memo) ? reply?.id : post?.id);
|
|
2283
|
+
return eventId ? {
|
|
2284
|
+
eventId,
|
|
2285
|
+
laneKey: `group:${nest}`
|
|
2286
|
+
} : null;
|
|
2287
|
+
}
|
|
2288
|
+
function inspectChatEvent(event) {
|
|
2289
|
+
const envelope = isRecord(event) ? event : null;
|
|
2290
|
+
const response = isRecord(envelope?.response) ? envelope.response : null;
|
|
2291
|
+
const add = isRecord(response?.add) ? response.add : null;
|
|
2292
|
+
const essay = isRecord(add?.essay) ? add.essay : null;
|
|
2293
|
+
const eventId = nonEmptyString(envelope?.id);
|
|
2294
|
+
if (!essay || !eventId) return null;
|
|
2295
|
+
const whom = isRecord(envelope?.whom) ? nonEmptyString(envelope.whom.ship) : null;
|
|
2296
|
+
const peer = nonEmptyString(envelope?.whom) ?? whom ?? nonEmptyString(essay.author);
|
|
2297
|
+
return {
|
|
2298
|
+
eventId,
|
|
2299
|
+
laneKey: peer ? `direct:${peer}` : `event:${eventId}`
|
|
2300
|
+
};
|
|
2301
|
+
}
|
|
2302
|
+
function inspectTlonIngressEvent(source, event) {
|
|
2303
|
+
return source === "channels" ? inspectChannelsEvent(event) : inspectChatEvent(event);
|
|
2304
|
+
}
|
|
2305
|
+
function decodeTlonIngressPayload(payload, claimedId) {
|
|
2306
|
+
if (payload.source !== "channels" && payload.source !== "chat" || typeof payload.rawEvent !== "string") throw new TlonIngressPermanentError("invalid-event", `Tlon ingress row ${claimedId} has an invalid payload.`);
|
|
2307
|
+
return {
|
|
2308
|
+
version: payload.version,
|
|
2309
|
+
body: {
|
|
2310
|
+
receivedAt: payload.receivedAt,
|
|
2311
|
+
source: payload.source,
|
|
2312
|
+
rawEvent: payload.rawEvent
|
|
2313
|
+
}
|
|
2314
|
+
};
|
|
2315
|
+
}
|
|
2316
|
+
function deserializeTlonIngressEvent(body, claimedId) {
|
|
2317
|
+
let event;
|
|
2318
|
+
try {
|
|
2319
|
+
event = JSON.parse(body.rawEvent);
|
|
2320
|
+
} catch (error) {
|
|
2321
|
+
throw new TlonIngressPermanentError("invalid-event", `Tlon ingress row ${claimedId} contains invalid JSON.`, { cause: error });
|
|
2322
|
+
}
|
|
2323
|
+
return {
|
|
2324
|
+
source: body.source,
|
|
2325
|
+
event
|
|
2326
|
+
};
|
|
2327
|
+
}
|
|
2328
|
+
function resolveTlonIngressNonRetryableFailure(error) {
|
|
2329
|
+
if (error instanceof TlonIngressPermanentError) return {
|
|
2330
|
+
reason: error.reason,
|
|
2331
|
+
message: error.message
|
|
2332
|
+
};
|
|
2333
|
+
for (const candidate of collectErrorGraphCandidates(error, (current) => [current.cause])) if (candidate instanceof UrbitAuthError || candidate instanceof UrbitHttpError && (candidate.status === 401 || candidate.status === 403)) return {
|
|
2334
|
+
reason: "tlon-auth",
|
|
2335
|
+
message: formatErrorMessage(candidate)
|
|
2336
|
+
};
|
|
2337
|
+
return null;
|
|
2338
|
+
}
|
|
2339
|
+
function createTlonIngressMonitor(options) {
|
|
2340
|
+
const monitor = createChannelIngressMonitor({
|
|
2341
|
+
queue: options.queue ?? (() => getTlonRuntime().state.openChannelIngressQueue({ accountId: options.accountId })),
|
|
2342
|
+
inspect: (raw) => inspectTlonIngressEvent(raw.source, raw.event),
|
|
2343
|
+
payload: {
|
|
2344
|
+
version: TLON_INGRESS_PAYLOAD_VERSION,
|
|
2345
|
+
serialize: (raw, { receivedAt }) => ({
|
|
2346
|
+
receivedAt,
|
|
2347
|
+
source: raw.source,
|
|
2348
|
+
rawEvent: JSON.stringify(raw.event)
|
|
2349
|
+
}),
|
|
2350
|
+
deserialize: (body, { claim }) => deserializeTlonIngressEvent(body, claim.id),
|
|
2351
|
+
encode: ({ body }) => ({
|
|
2352
|
+
version: TLON_INGRESS_PAYLOAD_VERSION,
|
|
2353
|
+
...body
|
|
2354
|
+
}),
|
|
2355
|
+
decode: (payload, { claim }) => decodeTlonIngressPayload(payload, claim.id),
|
|
2356
|
+
createClaimError: (kind, claim) => new TlonIngressPermanentError("invalid-event", kind === "invalid-version" ? `Tlon ingress row ${claim.id} has an invalid payload.` : `Tlon ingress row ${claim.id} has invalid message identity.`)
|
|
2357
|
+
},
|
|
2358
|
+
deliver: (raw, lifecycle) => options.dispatch(raw.source, raw.event, lifecycle),
|
|
2359
|
+
pollIntervalMs: options.pollIntervalMs ?? TLON_INGRESS_POLL_INTERVAL_MS,
|
|
2360
|
+
retention: {
|
|
2361
|
+
pruneIntervalMs: TLON_INGRESS_PRUNE_INTERVAL_MS,
|
|
2362
|
+
completedMaxEntries: TLON_INGRESS_TOMBSTONE_MAX_ENTRIES,
|
|
2363
|
+
failedTtlMs: TLON_INGRESS_FAILED_TTL_MS,
|
|
2364
|
+
failedMaxEntries: TLON_INGRESS_TOMBSTONE_MAX_ENTRIES
|
|
2365
|
+
},
|
|
2366
|
+
appendRetryDelaysMs: [0],
|
|
2367
|
+
drain: {
|
|
2368
|
+
resolveNonRetryableFailure: resolveTlonIngressNonRetryableFailure,
|
|
2369
|
+
...options.adoptionStallTimeoutMs === void 0 ? {} : { adoptionStallTimeoutMs: options.adoptionStallTimeoutMs },
|
|
2370
|
+
onLog: (message) => options.runtime.log?.(`tlon ${message}`)
|
|
2371
|
+
},
|
|
2372
|
+
...options.abortSignal ? { abortSignal: options.abortSignal } : {},
|
|
2373
|
+
createStoppedError: () => new TlonIngressShutdownError(),
|
|
2374
|
+
onError: (error) => options.runtime.error?.(`tlon ingress drain failed: ${formatErrorMessage(error)}`)
|
|
2375
|
+
});
|
|
2376
|
+
return {
|
|
2377
|
+
receive: async ({ source, event }) => {
|
|
2378
|
+
return { kind: (await monitor.admit({
|
|
2379
|
+
source,
|
|
2380
|
+
event
|
|
2381
|
+
})).kind === "durable" ? "accepted" : "ignored" };
|
|
2382
|
+
},
|
|
2383
|
+
start: monitor.start,
|
|
2384
|
+
stop: monitor.stop,
|
|
2385
|
+
waitForIdle: monitor.waitForIdle
|
|
2386
|
+
};
|
|
2387
|
+
}
|
|
2388
|
+
//#endregion
|
|
2049
2389
|
//#region extensions/tlon/src/media-fetch-timeouts.ts
|
|
2050
2390
|
const TLON_MEDIA_FETCH_TIMEOUTS = {
|
|
2051
2391
|
responseHeaderTimeoutMs: 12e4,
|
|
@@ -2054,6 +2394,18 @@ const TLON_MEDIA_FETCH_TIMEOUTS = {
|
|
|
2054
2394
|
//#endregion
|
|
2055
2395
|
//#region extensions/tlon/src/monitor/media.ts
|
|
2056
2396
|
const MAX_IMAGES_PER_MESSAGE = 8;
|
|
2397
|
+
/** Keeps Tlon's shipped path-duplicating prompt bytes paired with ordered facts. */
|
|
2398
|
+
function buildTlonInboundMediaPrompt(messageText, attachments) {
|
|
2399
|
+
const media = attachments.map((attachment) => ({ ...attachment }));
|
|
2400
|
+
if (media.length === 0) return {
|
|
2401
|
+
body: messageText,
|
|
2402
|
+
media
|
|
2403
|
+
};
|
|
2404
|
+
return {
|
|
2405
|
+
body: `${media.map((attachment) => `[media attached: ${attachment.path} (${attachment.contentType}) | ${attachment.path}]`).join("\n")}\n${messageText}`,
|
|
2406
|
+
media
|
|
2407
|
+
};
|
|
2408
|
+
}
|
|
2057
2409
|
/**
|
|
2058
2410
|
* Extract image blocks from Tlon message content.
|
|
2059
2411
|
* Returns array of image URLs found in the message.
|
|
@@ -2144,66 +2496,6 @@ async function downloadMessageImages(content, mediaDir) {
|
|
|
2144
2496
|
return attachments;
|
|
2145
2497
|
}
|
|
2146
2498
|
//#endregion
|
|
2147
|
-
//#region extensions/tlon/src/monitor/processed-messages.ts
|
|
2148
|
-
function createProcessedMessageTracker(limit = 2e3) {
|
|
2149
|
-
const dedupe = createDedupeCache({
|
|
2150
|
-
ttlMs: 0,
|
|
2151
|
-
maxSize: limit
|
|
2152
|
-
});
|
|
2153
|
-
const inFlight = /* @__PURE__ */ new Set();
|
|
2154
|
-
const claim = (id) => {
|
|
2155
|
-
const trimmed = id?.trim();
|
|
2156
|
-
if (!trimmed) return { kind: "claimed" };
|
|
2157
|
-
if (inFlight.has(trimmed) || dedupe.peek(trimmed)) return { kind: "duplicate" };
|
|
2158
|
-
inFlight.add(trimmed);
|
|
2159
|
-
return { kind: "claimed" };
|
|
2160
|
-
};
|
|
2161
|
-
const commit = (id) => {
|
|
2162
|
-
const trimmed = id?.trim();
|
|
2163
|
-
if (!trimmed) return;
|
|
2164
|
-
inFlight.delete(trimmed);
|
|
2165
|
-
dedupe.check(trimmed);
|
|
2166
|
-
};
|
|
2167
|
-
const release = (id) => {
|
|
2168
|
-
const trimmed = id?.trim();
|
|
2169
|
-
if (!trimmed) return;
|
|
2170
|
-
inFlight.delete(trimmed);
|
|
2171
|
-
};
|
|
2172
|
-
const mark = (id) => {
|
|
2173
|
-
if (claim(id).kind === "duplicate") return false;
|
|
2174
|
-
commit(id);
|
|
2175
|
-
return true;
|
|
2176
|
-
};
|
|
2177
|
-
const has = (id) => {
|
|
2178
|
-
const trimmed = id?.trim();
|
|
2179
|
-
if (!trimmed) return false;
|
|
2180
|
-
return dedupe.peek(trimmed);
|
|
2181
|
-
};
|
|
2182
|
-
return {
|
|
2183
|
-
claim,
|
|
2184
|
-
commit,
|
|
2185
|
-
release,
|
|
2186
|
-
mark,
|
|
2187
|
-
has,
|
|
2188
|
-
size: () => dedupe.size()
|
|
2189
|
-
};
|
|
2190
|
-
}
|
|
2191
|
-
async function runWithProcessedMessageClaim(params) {
|
|
2192
|
-
const claim = params.tracker.claim(params.id);
|
|
2193
|
-
if (claim.kind === "duplicate") return claim;
|
|
2194
|
-
try {
|
|
2195
|
-
const value = await params.task();
|
|
2196
|
-
params.tracker.commit(params.id);
|
|
2197
|
-
return {
|
|
2198
|
-
kind: "processed",
|
|
2199
|
-
value
|
|
2200
|
-
};
|
|
2201
|
-
} catch (error) {
|
|
2202
|
-
params.tracker.release(params.id);
|
|
2203
|
-
throw error;
|
|
2204
|
-
}
|
|
2205
|
-
}
|
|
2206
|
-
//#endregion
|
|
2207
2499
|
//#region extensions/tlon/src/monitor/settings-helpers.ts
|
|
2208
2500
|
function buildTlonSettingsMigrations(account, currentSettings) {
|
|
2209
2501
|
return [
|
|
@@ -2307,6 +2599,37 @@ function mergeUniqueStrings(base, next) {
|
|
|
2307
2599
|
return uniqueStrings([...base, ...next ?? []]);
|
|
2308
2600
|
}
|
|
2309
2601
|
//#endregion
|
|
2602
|
+
//#region extensions/tlon/src/monitor/tracking.ts
|
|
2603
|
+
const TLON_PARTICIPATED_THREAD_LIMIT = 2e3;
|
|
2604
|
+
function createParticipatedThreadTracker(limit = TLON_PARTICIPATED_THREAD_LIMIT) {
|
|
2605
|
+
const cache = createDedupeCache({
|
|
2606
|
+
ttlMs: 0,
|
|
2607
|
+
maxSize: limit
|
|
2608
|
+
});
|
|
2609
|
+
return {
|
|
2610
|
+
add: (parentId) => {
|
|
2611
|
+
cache.check(parentId);
|
|
2612
|
+
},
|
|
2613
|
+
has: (parentId) => {
|
|
2614
|
+
if (!cache.peek(parentId)) return false;
|
|
2615
|
+
cache.check(parentId);
|
|
2616
|
+
return true;
|
|
2617
|
+
}
|
|
2618
|
+
};
|
|
2619
|
+
}
|
|
2620
|
+
function createActiveSnapshotTracker() {
|
|
2621
|
+
const processed = /* @__PURE__ */ new Set();
|
|
2622
|
+
return {
|
|
2623
|
+
beginSnapshot: (keys) => {
|
|
2624
|
+
const active = new Set(keys);
|
|
2625
|
+
for (const key of processed) if (!active.has(key)) processed.delete(key);
|
|
2626
|
+
return active;
|
|
2627
|
+
},
|
|
2628
|
+
has: (key) => processed.has(key),
|
|
2629
|
+
add: (key) => processed.add(key)
|
|
2630
|
+
};
|
|
2631
|
+
}
|
|
2632
|
+
//#endregion
|
|
2310
2633
|
//#region extensions/tlon/src/monitor/index.ts
|
|
2311
2634
|
function readNumber(record, key) {
|
|
2312
2635
|
return asFiniteNumber(record?.[key]);
|
|
@@ -2357,7 +2680,6 @@ async function monitorTlonProvider(opts = {}) {
|
|
|
2357
2680
|
runtime.log?.("[tlon] Re-authentication successful");
|
|
2358
2681
|
}
|
|
2359
2682
|
});
|
|
2360
|
-
const processedTracker = createProcessedMessageTracker(2e3);
|
|
2361
2683
|
let groupChannels = [];
|
|
2362
2684
|
let botNickname = null;
|
|
2363
2685
|
const settingsManager = createSettingsManager(api, {
|
|
@@ -2373,7 +2695,7 @@ async function monitorTlonProvider(opts = {}) {
|
|
|
2373
2695
|
let effectiveOwnerShip = account.ownerShip ? normalizeShip(account.ownerShip) : null;
|
|
2374
2696
|
let pendingApprovals = [];
|
|
2375
2697
|
let currentSettings = {};
|
|
2376
|
-
const participatedThreads =
|
|
2698
|
+
const participatedThreads = createParticipatedThreadTracker();
|
|
2377
2699
|
const dmSendersBySession = /* @__PURE__ */ new Map();
|
|
2378
2700
|
let sharedSessionWarningSent = false;
|
|
2379
2701
|
try {
|
|
@@ -2443,7 +2765,7 @@ async function monitorTlonProvider(opts = {}) {
|
|
|
2443
2765
|
return /^~?[a-z-]+$/i.test(normalized) ? normalized : "";
|
|
2444
2766
|
}
|
|
2445
2767
|
const processMessage = async (params) => {
|
|
2446
|
-
const { messageId, senderShip, isGroup, channelNest, hostShip: _hostShip, channelName: _channelName, timestamp, parentId, isThreadReply, messageContent } = params;
|
|
2768
|
+
const { messageId, senderShip, isGroup, channelNest, hostShip: _hostShip, channelName: _channelName, timestamp, parentId, isThreadReply, messageContent, turnAdoptionLifecycle } = params;
|
|
2447
2769
|
const groupChannel = channelNest;
|
|
2448
2770
|
let messageText = params.messageText;
|
|
2449
2771
|
let attachments = [];
|
|
@@ -2541,16 +2863,14 @@ async function monitorTlonProvider(opts = {}) {
|
|
|
2541
2863
|
const shouldComputeAuth = core.channel.commands.shouldComputeCommandAuthorized(messageText, cfg);
|
|
2542
2864
|
let commandAuthorized = false;
|
|
2543
2865
|
if (shouldComputeAuth) {
|
|
2544
|
-
const useAccessGroups = cfg.commands?.useAccessGroups !== false;
|
|
2545
2866
|
commandAuthorized = (await resolveTlonCommandAuthorizationWithIngress({
|
|
2546
2867
|
senderShip,
|
|
2547
2868
|
ownerShip: effectiveOwnerShip,
|
|
2548
|
-
useAccessGroups
|
|
2869
|
+
useAccessGroups: true
|
|
2549
2870
|
})).commandAccess.authorized;
|
|
2550
2871
|
if (!commandAuthorized) console.log(`[tlon] Command attempt denied: ${senderShip} is not owner (owner=${effectiveOwnerShip ?? "not configured"})`);
|
|
2551
2872
|
}
|
|
2552
|
-
|
|
2553
|
-
if (attachments.length > 0) bodyWithAttachments = attachments.map((a) => `[media attached: ${a.path} (${a.contentType}) | ${a.path}]`).join("\n") + "\n" + messageText;
|
|
2873
|
+
const promptMedia = buildTlonInboundMediaPrompt(messageText, attachments);
|
|
2554
2874
|
const body = createChannelInboundEnvelopeBuilder({
|
|
2555
2875
|
cfg,
|
|
2556
2876
|
route
|
|
@@ -2558,7 +2878,7 @@ async function monitorTlonProvider(opts = {}) {
|
|
|
2558
2878
|
channel: "Tlon",
|
|
2559
2879
|
from: fromLabel,
|
|
2560
2880
|
timestamp,
|
|
2561
|
-
body:
|
|
2881
|
+
body: promptMedia.body
|
|
2562
2882
|
});
|
|
2563
2883
|
const commandBody = isGroup ? stripBotMention(messageText, botShipName) : messageText;
|
|
2564
2884
|
const tlonConversationId = isGroup ? groupChannel ?? channelNest ?? senderShip : senderShip;
|
|
@@ -2625,6 +2945,10 @@ async function monitorTlonProvider(opts = {}) {
|
|
|
2625
2945
|
participatedThreads.add(parentId);
|
|
2626
2946
|
runtime.log?.(`[tlon] Now tracking thread for future replies: ${parentId}`);
|
|
2627
2947
|
};
|
|
2948
|
+
const replyOptions = {
|
|
2949
|
+
...turnAdoptionLifecycle ? bindIngressLifecycleToReplyOptions(turnAdoptionLifecycle) : {},
|
|
2950
|
+
...promptMedia.media.length > 0 ? { media: promptMedia.media } : {}
|
|
2951
|
+
};
|
|
2628
2952
|
await core.channel.inbound.dispatch({
|
|
2629
2953
|
channel: "tlon",
|
|
2630
2954
|
accountId: route.accountId,
|
|
@@ -2681,6 +3005,7 @@ async function monitorTlonProvider(opts = {}) {
|
|
|
2681
3005
|
responsePrefix,
|
|
2682
3006
|
humanDelay
|
|
2683
3007
|
},
|
|
3008
|
+
...turnAdoptionLifecycle || promptMedia.media.length > 0 ? { replyOptions } : {},
|
|
2684
3009
|
record: { onRecordError: (err) => {
|
|
2685
3010
|
runtime.error?.(`[tlon] failed updating session meta: ${String(err)}`);
|
|
2686
3011
|
} }
|
|
@@ -2752,7 +3077,7 @@ async function monitorTlonProvider(opts = {}) {
|
|
|
2752
3077
|
},
|
|
2753
3078
|
refreshWatchedChannels
|
|
2754
3079
|
});
|
|
2755
|
-
const handleChannelsFirehose = async (event) => {
|
|
3080
|
+
const handleChannelsFirehose = async (event, turnAdoptionLifecycle) => {
|
|
2756
3081
|
try {
|
|
2757
3082
|
const eventRecord = asRecord(event);
|
|
2758
3083
|
const nest = readString(eventRecord, "nest");
|
|
@@ -2773,93 +3098,89 @@ async function monitorTlonProvider(opts = {}) {
|
|
|
2773
3098
|
const isThreadReply = Boolean(memo);
|
|
2774
3099
|
const messageId = isThreadReply ? readString(reply, "id") : readString(post, "id");
|
|
2775
3100
|
if (!messageId) return;
|
|
2776
|
-
|
|
2777
|
-
|
|
2778
|
-
|
|
2779
|
-
|
|
2780
|
-
|
|
2781
|
-
|
|
2782
|
-
|
|
2783
|
-
|
|
2784
|
-
|
|
2785
|
-
|
|
2786
|
-
|
|
2787
|
-
|
|
2788
|
-
|
|
2789
|
-
|
|
2790
|
-
|
|
2791
|
-
|
|
2792
|
-
|
|
2793
|
-
|
|
2794
|
-
|
|
2795
|
-
|
|
2796
|
-
|
|
2797
|
-
|
|
2798
|
-
|
|
2799
|
-
|
|
2800
|
-
|
|
2801
|
-
|
|
2802
|
-
|
|
2803
|
-
|
|
2804
|
-
if (
|
|
2805
|
-
|
|
2806
|
-
|
|
2807
|
-
|
|
2808
|
-
|
|
2809
|
-
|
|
2810
|
-
|
|
2811
|
-
|
|
2812
|
-
|
|
2813
|
-
|
|
2814
|
-
|
|
2815
|
-
|
|
2816
|
-
|
|
2817
|
-
|
|
2818
|
-
|
|
2819
|
-
|
|
2820
|
-
|
|
2821
|
-
|
|
2822
|
-
|
|
2823
|
-
});
|
|
2824
|
-
await queueApprovalRequest(approval);
|
|
2825
|
-
} else runtime.log?.(`[tlon] Access denied: ${senderShip} in ${nest} (allowed: ${allowedShips.join(", ")})`);
|
|
2826
|
-
return;
|
|
2827
|
-
}
|
|
2828
|
-
}
|
|
3101
|
+
const senderShip = normalizeShip(readString(content, "author") ?? "");
|
|
3102
|
+
if (!senderShip || senderShip === botShipName) return;
|
|
3103
|
+
const rawText = extractMessageText(content.content);
|
|
3104
|
+
if (!rawText.trim()) return;
|
|
3105
|
+
const contentBody = content.content;
|
|
3106
|
+
const sentAt = readNumber(content, "sent") ?? Date.now();
|
|
3107
|
+
cacheMessage(nest, {
|
|
3108
|
+
author: senderShip,
|
|
3109
|
+
content: rawText,
|
|
3110
|
+
timestamp: sentAt,
|
|
3111
|
+
id: messageId
|
|
3112
|
+
});
|
|
3113
|
+
const seal = isThreadReply ? asRecord(replySet?.seal) : asRecord(set?.seal);
|
|
3114
|
+
const parentId = readString(seal, "parent-id") ?? readString(seal, "parent") ?? null;
|
|
3115
|
+
const mentioned = isBotMentioned(rawText, botShipName, botNickname ?? void 0);
|
|
3116
|
+
const inParticipatedThread = isThreadReply && parentId && participatedThreads.has(parentId);
|
|
3117
|
+
const mentionDecision = resolveTlonGroupMentionDecision({
|
|
3118
|
+
cfg,
|
|
3119
|
+
accountId: account.accountId,
|
|
3120
|
+
wasMentioned: mentioned,
|
|
3121
|
+
botParticipatedInThread: Boolean(inParticipatedThread)
|
|
3122
|
+
});
|
|
3123
|
+
if (mentionDecision.shouldSkip) return;
|
|
3124
|
+
if (mentionDecision.implicitMention && !mentioned) runtime.log?.(`[tlon] Responding to thread we participated in (no mention): ${parentId}`);
|
|
3125
|
+
if (isOwner(senderShip)) runtime.log?.(`[tlon] Owner ${senderShip} is always allowed in channels`);
|
|
3126
|
+
else {
|
|
3127
|
+
const { mode, allowedShips } = resolveChannelAuthorization(cfg, nest, currentSettings);
|
|
3128
|
+
if (mode === "restricted") {
|
|
3129
|
+
if (!allowedShips.map(normalizeShip).includes(senderShip)) {
|
|
3130
|
+
if (effectiveOwnerShip) {
|
|
3131
|
+
const approval = createPendingApproval({
|
|
3132
|
+
type: "channel",
|
|
3133
|
+
requestingShip: senderShip,
|
|
3134
|
+
channelNest: nest,
|
|
3135
|
+
messagePreview: sliceUtf16Safe(rawText, 0, 100),
|
|
3136
|
+
originalMessage: {
|
|
3137
|
+
messageId: messageId ?? "",
|
|
3138
|
+
messageText: rawText,
|
|
3139
|
+
messageContent: contentBody,
|
|
3140
|
+
timestamp: sentAt,
|
|
3141
|
+
parentId: parentId ?? void 0,
|
|
3142
|
+
isThreadReply
|
|
3143
|
+
}
|
|
3144
|
+
});
|
|
3145
|
+
await queueApprovalRequest(approval);
|
|
3146
|
+
} else runtime.log?.(`[tlon] Access denied: ${senderShip} in ${nest} (allowed: ${allowedShips.join(", ")})`);
|
|
3147
|
+
return;
|
|
2829
3148
|
}
|
|
2830
|
-
const messageText = await resolveAuthorizedMessageText({
|
|
2831
|
-
rawText,
|
|
2832
|
-
content: contentBody,
|
|
2833
|
-
authorizedForCites: true,
|
|
2834
|
-
resolveAllCites
|
|
2835
|
-
});
|
|
2836
|
-
const parsed = parseChannelNest(nest);
|
|
2837
|
-
await processMessage({
|
|
2838
|
-
messageId: messageId ?? "",
|
|
2839
|
-
senderShip,
|
|
2840
|
-
messageText,
|
|
2841
|
-
messageContent: contentBody,
|
|
2842
|
-
isGroup: true,
|
|
2843
|
-
channelNest: nest,
|
|
2844
|
-
hostShip: parsed?.hostShip,
|
|
2845
|
-
channelName: parsed?.channelName,
|
|
2846
|
-
timestamp: sentAt,
|
|
2847
|
-
parentId,
|
|
2848
|
-
isThreadReply
|
|
2849
|
-
});
|
|
2850
3149
|
}
|
|
3150
|
+
}
|
|
3151
|
+
const messageText = await resolveAuthorizedMessageText({
|
|
3152
|
+
rawText,
|
|
3153
|
+
content: contentBody,
|
|
3154
|
+
authorizedForCites: true,
|
|
3155
|
+
resolveAllCites
|
|
3156
|
+
});
|
|
3157
|
+
const parsed = parseChannelNest(nest);
|
|
3158
|
+
await processMessage({
|
|
3159
|
+
messageId: messageId ?? "",
|
|
3160
|
+
senderShip,
|
|
3161
|
+
messageText,
|
|
3162
|
+
messageContent: contentBody,
|
|
3163
|
+
isGroup: true,
|
|
3164
|
+
channelNest: nest,
|
|
3165
|
+
hostShip: parsed?.hostShip,
|
|
3166
|
+
channelName: parsed?.channelName,
|
|
3167
|
+
timestamp: sentAt,
|
|
3168
|
+
parentId,
|
|
3169
|
+
isThreadReply,
|
|
3170
|
+
turnAdoptionLifecycle
|
|
2851
3171
|
});
|
|
2852
3172
|
} catch (error) {
|
|
2853
3173
|
runtime.error?.(`[tlon] Error handling channel firehose event: ${formatErrorMessage$1(error)}`);
|
|
3174
|
+
throw error;
|
|
2854
3175
|
}
|
|
2855
3176
|
};
|
|
2856
|
-
const processedDmInvites =
|
|
2857
|
-
const handleChatFirehose = async (event) => {
|
|
3177
|
+
const processedDmInvites = createActiveSnapshotTracker();
|
|
3178
|
+
const handleChatFirehose = async (event, turnAdoptionLifecycle) => {
|
|
2858
3179
|
try {
|
|
2859
3180
|
if (Array.isArray(event)) {
|
|
2860
|
-
|
|
2861
|
-
|
|
2862
|
-
if (
|
|
3181
|
+
const ships = processedDmInvites.beginSnapshot(event.map((invite) => normalizeShip(invite.ship || "")).filter(Boolean));
|
|
3182
|
+
for (const ship of ships) {
|
|
3183
|
+
if (processedDmInvites.has(ship)) continue;
|
|
2863
3184
|
if (isOwner(ship)) {
|
|
2864
3185
|
try {
|
|
2865
3186
|
await api.poke({
|
|
@@ -2877,7 +3198,8 @@ async function monitorTlonProvider(opts = {}) {
|
|
|
2877
3198
|
}
|
|
2878
3199
|
continue;
|
|
2879
3200
|
}
|
|
2880
|
-
|
|
3201
|
+
const allowed = await isDmAllowedWithIngress(ship, effectiveDmAllowlist);
|
|
3202
|
+
if (effectiveAutoAcceptDmInvites && allowed) {
|
|
2881
3203
|
try {
|
|
2882
3204
|
await api.poke({
|
|
2883
3205
|
app: "chat",
|
|
@@ -2894,7 +3216,7 @@ async function monitorTlonProvider(opts = {}) {
|
|
|
2894
3216
|
}
|
|
2895
3217
|
continue;
|
|
2896
3218
|
}
|
|
2897
|
-
if (effectiveOwnerShip && !
|
|
3219
|
+
if (effectiveOwnerShip && !allowed) {
|
|
2898
3220
|
const approval = createPendingApproval({
|
|
2899
3221
|
type: "dm",
|
|
2900
3222
|
requestingShip: ship,
|
|
@@ -2914,92 +3236,104 @@ async function monitorTlonProvider(opts = {}) {
|
|
|
2914
3236
|
if (!messageId || !response) return;
|
|
2915
3237
|
const essay = asRecord(asRecord(response.add)?.essay);
|
|
2916
3238
|
if (!essay) return;
|
|
2917
|
-
|
|
2918
|
-
|
|
2919
|
-
|
|
2920
|
-
|
|
2921
|
-
|
|
2922
|
-
|
|
2923
|
-
|
|
2924
|
-
|
|
2925
|
-
|
|
2926
|
-
|
|
2927
|
-
|
|
2928
|
-
|
|
2929
|
-
|
|
2930
|
-
|
|
2931
|
-
|
|
2932
|
-
|
|
2933
|
-
|
|
2934
|
-
|
|
2935
|
-
|
|
2936
|
-
|
|
2937
|
-
|
|
2938
|
-
|
|
2939
|
-
|
|
2940
|
-
|
|
2941
|
-
|
|
2942
|
-
|
|
2943
|
-
|
|
2944
|
-
|
|
2945
|
-
|
|
2946
|
-
|
|
2947
|
-
|
|
2948
|
-
|
|
2949
|
-
|
|
2950
|
-
|
|
3239
|
+
const authorShip = normalizeShip(readString(essay, "author") ?? "");
|
|
3240
|
+
const partnerShip = extractDmPartnerShip(whom);
|
|
3241
|
+
const senderShip = partnerShip || authorShip;
|
|
3242
|
+
if (authorShip === botShipName) return;
|
|
3243
|
+
if (!senderShip || senderShip === botShipName) return;
|
|
3244
|
+
if (authorShip && partnerShip && authorShip !== partnerShip) runtime.log?.(`[tlon] DM ship mismatch (author=${authorShip}, partner=${partnerShip}) - routing to partner`);
|
|
3245
|
+
const rawText = extractMessageText(essay.content);
|
|
3246
|
+
if (!rawText.trim()) return;
|
|
3247
|
+
const messageText = rawText;
|
|
3248
|
+
if (isOwner(senderShip) && isApprovalResponse(messageText)) {
|
|
3249
|
+
if (await handleApprovalResponse(messageText)) {
|
|
3250
|
+
runtime.log?.(`[tlon] Processed approval response from owner: ${messageText}`);
|
|
3251
|
+
return;
|
|
3252
|
+
}
|
|
3253
|
+
}
|
|
3254
|
+
if (isOwner(senderShip) && isAdminCommand(messageText)) {
|
|
3255
|
+
if (await handleAdminCommand(messageText)) {
|
|
3256
|
+
runtime.log?.(`[tlon] Processed admin command from owner: ${messageText}`);
|
|
3257
|
+
return;
|
|
3258
|
+
}
|
|
3259
|
+
}
|
|
3260
|
+
if (isOwner(senderShip)) {
|
|
3261
|
+
const resolvedMessageText = await resolveAuthorizedMessageText({
|
|
3262
|
+
rawText,
|
|
3263
|
+
content: essay.content,
|
|
3264
|
+
authorizedForCites: true,
|
|
3265
|
+
resolveAllCites
|
|
3266
|
+
});
|
|
3267
|
+
runtime.log?.(`[tlon] Processing DM from owner ${senderShip}`);
|
|
3268
|
+
await processMessage({
|
|
3269
|
+
messageId: messageId ?? "",
|
|
3270
|
+
senderShip,
|
|
3271
|
+
messageText: resolvedMessageText,
|
|
3272
|
+
messageContent: essay.content,
|
|
3273
|
+
isGroup: false,
|
|
3274
|
+
timestamp: readNumber(essay, "sent") ?? Date.now(),
|
|
3275
|
+
turnAdoptionLifecycle
|
|
3276
|
+
});
|
|
3277
|
+
return;
|
|
3278
|
+
}
|
|
3279
|
+
if (!await isDmAllowedWithIngress(senderShip, effectiveDmAllowlist)) {
|
|
3280
|
+
if (effectiveOwnerShip) {
|
|
3281
|
+
const approval = createPendingApproval({
|
|
3282
|
+
type: "dm",
|
|
3283
|
+
requestingShip: senderShip,
|
|
3284
|
+
messagePreview: sliceUtf16Safe(messageText, 0, 100),
|
|
3285
|
+
originalMessage: {
|
|
2951
3286
|
messageId: messageId ?? "",
|
|
2952
|
-
|
|
2953
|
-
messageText: resolvedMessageText,
|
|
3287
|
+
messageText,
|
|
2954
3288
|
messageContent: essay.content,
|
|
2955
|
-
isGroup: false,
|
|
2956
3289
|
timestamp: readNumber(essay, "sent") ?? Date.now()
|
|
2957
|
-
}
|
|
2958
|
-
return;
|
|
2959
|
-
}
|
|
2960
|
-
if (!await isDmAllowedWithIngress(senderShip, effectiveDmAllowlist)) {
|
|
2961
|
-
if (effectiveOwnerShip) {
|
|
2962
|
-
const approval = createPendingApproval({
|
|
2963
|
-
type: "dm",
|
|
2964
|
-
requestingShip: senderShip,
|
|
2965
|
-
messagePreview: sliceUtf16Safe(messageText, 0, 100),
|
|
2966
|
-
originalMessage: {
|
|
2967
|
-
messageId: messageId ?? "",
|
|
2968
|
-
messageText,
|
|
2969
|
-
messageContent: essay.content,
|
|
2970
|
-
timestamp: readNumber(essay, "sent") ?? Date.now()
|
|
2971
|
-
}
|
|
2972
|
-
});
|
|
2973
|
-
await queueApprovalRequest(approval);
|
|
2974
|
-
} else runtime.log?.(`[tlon] Blocked DM from ${senderShip}: not in allowlist`);
|
|
2975
|
-
return;
|
|
2976
|
-
}
|
|
2977
|
-
await processMessage({
|
|
2978
|
-
messageText: await resolveAuthorizedMessageText({
|
|
2979
|
-
rawText,
|
|
2980
|
-
content: essay.content,
|
|
2981
|
-
authorizedForCites: true,
|
|
2982
|
-
resolveAllCites
|
|
2983
|
-
}),
|
|
2984
|
-
messageId: messageId ?? "",
|
|
2985
|
-
senderShip,
|
|
2986
|
-
messageContent: essay.content,
|
|
2987
|
-
isGroup: false,
|
|
2988
|
-
timestamp: readNumber(essay, "sent") ?? Date.now()
|
|
3290
|
+
}
|
|
2989
3291
|
});
|
|
2990
|
-
|
|
3292
|
+
await queueApprovalRequest(approval);
|
|
3293
|
+
} else runtime.log?.(`[tlon] Blocked DM from ${senderShip}: not in allowlist`);
|
|
3294
|
+
return;
|
|
3295
|
+
}
|
|
3296
|
+
await processMessage({
|
|
3297
|
+
messageText: await resolveAuthorizedMessageText({
|
|
3298
|
+
rawText,
|
|
3299
|
+
content: essay.content,
|
|
3300
|
+
authorizedForCites: true,
|
|
3301
|
+
resolveAllCites
|
|
3302
|
+
}),
|
|
3303
|
+
messageId: messageId ?? "",
|
|
3304
|
+
senderShip,
|
|
3305
|
+
messageContent: essay.content,
|
|
3306
|
+
isGroup: false,
|
|
3307
|
+
timestamp: readNumber(essay, "sent") ?? Date.now(),
|
|
3308
|
+
turnAdoptionLifecycle
|
|
2991
3309
|
});
|
|
2992
3310
|
} catch (error) {
|
|
2993
3311
|
runtime.error?.(`[tlon] Error handling chat firehose event: ${formatErrorMessage$1(error)}`);
|
|
3312
|
+
throw error;
|
|
2994
3313
|
}
|
|
2995
3314
|
};
|
|
3315
|
+
const ingress = createTlonIngressMonitor({
|
|
3316
|
+
accountId: account.accountId,
|
|
3317
|
+
runtime,
|
|
3318
|
+
abortSignal: opts.abortSignal,
|
|
3319
|
+
dispatch: async (source, event, turnAdoptionLifecycle) => {
|
|
3320
|
+
if (source === "channels") {
|
|
3321
|
+
await handleChannelsFirehose(event, turnAdoptionLifecycle);
|
|
3322
|
+
return;
|
|
3323
|
+
}
|
|
3324
|
+
await handleChatFirehose(event, turnAdoptionLifecycle);
|
|
3325
|
+
}
|
|
3326
|
+
});
|
|
2996
3327
|
try {
|
|
2997
3328
|
runtime.log?.("[tlon] Subscribing to firehose updates...");
|
|
2998
3329
|
await api.subscribe({
|
|
2999
3330
|
app: "channels",
|
|
3000
3331
|
path: "/v2",
|
|
3001
|
-
event: (event) => {
|
|
3002
|
-
|
|
3332
|
+
event: async (event) => {
|
|
3333
|
+
if ((await ingress.receive({
|
|
3334
|
+
source: "channels",
|
|
3335
|
+
event
|
|
3336
|
+
})).kind === "ignored") await handleChannelsFirehose(event);
|
|
3003
3337
|
},
|
|
3004
3338
|
err: (error) => {
|
|
3005
3339
|
runtime.error?.(`[tlon] Channels firehose error: ${String(error)}`);
|
|
@@ -3012,8 +3346,11 @@ async function monitorTlonProvider(opts = {}) {
|
|
|
3012
3346
|
await api.subscribe({
|
|
3013
3347
|
app: "chat",
|
|
3014
3348
|
path: "/v3",
|
|
3015
|
-
event: (event) => {
|
|
3016
|
-
|
|
3349
|
+
event: async (event) => {
|
|
3350
|
+
if ((await ingress.receive({
|
|
3351
|
+
source: "chat",
|
|
3352
|
+
event
|
|
3353
|
+
})).kind === "ignored") await handleChatFirehose(event);
|
|
3017
3354
|
},
|
|
3018
3355
|
err: (error) => {
|
|
3019
3356
|
runtime.error?.(`[tlon] Chat firehose error: ${String(error)}`);
|
|
@@ -3259,6 +3596,7 @@ async function monitorTlonProvider(opts = {}) {
|
|
|
3259
3596
|
for (const channelNest of watchedChannels) runtime.log?.(`[tlon] Watching channel: ${channelNest}`);
|
|
3260
3597
|
runtime.log?.("[tlon] All subscriptions registered, connecting to SSE stream...");
|
|
3261
3598
|
await api.connect();
|
|
3599
|
+
ingress.start();
|
|
3262
3600
|
runtime.log?.("[tlon] Connected! Firehose subscriptions active");
|
|
3263
3601
|
const pollInterval = setInterval(() => {
|
|
3264
3602
|
(async () => {
|
|
@@ -3285,6 +3623,8 @@ async function monitorTlonProvider(opts = {}) {
|
|
|
3285
3623
|
});
|
|
3286
3624
|
} else await new Promise(() => {});
|
|
3287
3625
|
} finally {
|
|
3626
|
+
api?.stopReceiving();
|
|
3627
|
+
await ingress.stop();
|
|
3288
3628
|
try {
|
|
3289
3629
|
await api?.close();
|
|
3290
3630
|
} catch (error) {
|
|
@@ -3302,6 +3642,14 @@ const TLON_MEMEX_UPLOAD_URL_TIMEOUT_MS = 3e4;
|
|
|
3302
3642
|
/** Total deadline for Memex and custom S3 PUTs, including DNS and the full upload. */
|
|
3303
3643
|
const TLON_UPLOAD_TIMEOUT_MS = 3e5;
|
|
3304
3644
|
let currentClientConfig = null;
|
|
3645
|
+
async function releaseUploadResponse(guarded) {
|
|
3646
|
+
if (!guarded) return;
|
|
3647
|
+
try {
|
|
3648
|
+
if (!guarded.response.bodyUsed) await guarded.response.body?.cancel();
|
|
3649
|
+
} catch {} finally {
|
|
3650
|
+
await guarded.release();
|
|
3651
|
+
}
|
|
3652
|
+
}
|
|
3305
3653
|
function configureClient(params) {
|
|
3306
3654
|
currentClientConfig = {
|
|
3307
3655
|
...params,
|
|
@@ -3401,9 +3749,9 @@ async function getMemexUploadUrl(params) {
|
|
|
3401
3749
|
const resolvedToken = typeof token === "string" ? token : token.secret;
|
|
3402
3750
|
if (!resolvedToken) throw new Error("Missing genuine secret");
|
|
3403
3751
|
const endpoint = `${MEMEX_BASE_URL}/v1/${params.config.shipName}/upload`;
|
|
3404
|
-
let
|
|
3752
|
+
let guarded;
|
|
3405
3753
|
try {
|
|
3406
|
-
|
|
3754
|
+
guarded = await fetchWithSsrFGuard({
|
|
3407
3755
|
url: endpoint,
|
|
3408
3756
|
init: {
|
|
3409
3757
|
method: "PUT",
|
|
@@ -3420,7 +3768,6 @@ async function getMemexUploadUrl(params) {
|
|
|
3420
3768
|
maxRedirects: 0,
|
|
3421
3769
|
timeoutMs: TLON_MEMEX_UPLOAD_URL_TIMEOUT_MS
|
|
3422
3770
|
});
|
|
3423
|
-
release = guarded.release;
|
|
3424
3771
|
if (!guarded.response.ok) throw new Error(`Memex upload request failed: ${guarded.response.status}`);
|
|
3425
3772
|
const data = await readProviderJsonResponse(guarded.response, "Memex upload", { maxBytes: MEMEX_UPLOAD_RESPONSE_MAX_BYTES });
|
|
3426
3773
|
if (!data?.url || !data.filePath) throw new Error("Invalid response from Memex");
|
|
@@ -3429,7 +3776,7 @@ async function getMemexUploadUrl(params) {
|
|
|
3429
3776
|
uploadUrl: data.url
|
|
3430
3777
|
};
|
|
3431
3778
|
} finally {
|
|
3432
|
-
await
|
|
3779
|
+
await releaseUploadResponse(guarded);
|
|
3433
3780
|
}
|
|
3434
3781
|
}
|
|
3435
3782
|
async function uploadFile(params) {
|
|
@@ -3450,9 +3797,9 @@ async function uploadFile(params) {
|
|
|
3450
3797
|
fileName: fileKey
|
|
3451
3798
|
});
|
|
3452
3799
|
const trustedUploadUrl = assertTrustedMemexUploadUrl(uploadUrl, "Memex upload URL");
|
|
3453
|
-
let
|
|
3800
|
+
let guarded;
|
|
3454
3801
|
try {
|
|
3455
|
-
|
|
3802
|
+
guarded = await fetchWithSsrFGuard({
|
|
3456
3803
|
url: trustedUploadUrl,
|
|
3457
3804
|
init: {
|
|
3458
3805
|
method: "PUT",
|
|
@@ -3467,11 +3814,10 @@ async function uploadFile(params) {
|
|
|
3467
3814
|
maxRedirects: 0,
|
|
3468
3815
|
timeoutMs: TLON_UPLOAD_TIMEOUT_MS
|
|
3469
3816
|
});
|
|
3470
|
-
release = guarded.release;
|
|
3471
3817
|
assertTrustedMemexUploadUrl(guarded.finalUrl, "Memex final upload URL");
|
|
3472
3818
|
if (!guarded.response.ok) throw new Error(`Upload failed: ${guarded.response.status}`);
|
|
3473
3819
|
} finally {
|
|
3474
|
-
await
|
|
3820
|
+
await releaseUploadResponse(guarded);
|
|
3475
3821
|
}
|
|
3476
3822
|
return { url: assertTrustedMemexUploadUrl(hostedUrl, "Memex hosted URL") };
|
|
3477
3823
|
}
|
|
@@ -3497,9 +3843,9 @@ async function uploadFile(params) {
|
|
|
3497
3843
|
CacheControl: headers["Cache-Control"],
|
|
3498
3844
|
ACL: "public-read"
|
|
3499
3845
|
}), { expiresIn: 3600 });
|
|
3500
|
-
let
|
|
3846
|
+
let guarded;
|
|
3501
3847
|
try {
|
|
3502
|
-
|
|
3848
|
+
guarded = await fetchWithSsrFGuard({
|
|
3503
3849
|
url: signedUrl,
|
|
3504
3850
|
init: {
|
|
3505
3851
|
method: "PUT",
|
|
@@ -3512,10 +3858,9 @@ async function uploadFile(params) {
|
|
|
3512
3858
|
policy: privateNetworkPolicy,
|
|
3513
3859
|
timeoutMs: TLON_UPLOAD_TIMEOUT_MS
|
|
3514
3860
|
});
|
|
3515
|
-
release = guarded.release;
|
|
3516
3861
|
if (!guarded.response.ok) throw new Error(`Upload failed: ${guarded.response.status}`);
|
|
3517
3862
|
} finally {
|
|
3518
|
-
await
|
|
3863
|
+
await releaseUploadResponse(guarded);
|
|
3519
3864
|
}
|
|
3520
3865
|
return { url: assertSafeUploadResultUrl(storageConfig.publicUrlBase ? new URL(fileKey, storageConfig.publicUrlBase).toString() : expectDefined(signedUrl.split("?").at(0), "signed URL base segment"), "Upload result URL") };
|
|
3521
3866
|
}
|
|
@@ -3699,8 +4044,8 @@ const tlonRuntimeOutbound = {
|
|
|
3699
4044
|
});
|
|
3700
4045
|
}
|
|
3701
4046
|
};
|
|
3702
|
-
async function probeTlonAccount(account) {
|
|
3703
|
-
|
|
4047
|
+
async function probeTlonAccount(account, timeoutMs) {
|
|
4048
|
+
return await runChannelProbe(timeoutMs, async () => {
|
|
3704
4049
|
const ssrfPolicy = ssrfPolicyFromDangerouslyAllowPrivateNetwork(account.dangerouslyAllowPrivateNetwork);
|
|
3705
4050
|
const cookie = await authenticate(account.url, account.code, { ssrfPolicy });
|
|
3706
4051
|
const { response, release } = await urbitFetch({
|
|
@@ -3721,14 +4066,13 @@ async function probeTlonAccount(account) {
|
|
|
3721
4066
|
};
|
|
3722
4067
|
return { ok: true };
|
|
3723
4068
|
} finally {
|
|
4069
|
+
if (!response.bodyUsed) await response.body?.cancel().catch(() => void 0);
|
|
3724
4070
|
await release();
|
|
3725
4071
|
}
|
|
3726
|
-
}
|
|
3727
|
-
|
|
3728
|
-
|
|
3729
|
-
|
|
3730
|
-
};
|
|
3731
|
-
}
|
|
4072
|
+
}, (error) => ({
|
|
4073
|
+
ok: false,
|
|
4074
|
+
error: error?.message ?? String(error)
|
|
4075
|
+
}));
|
|
3732
4076
|
}
|
|
3733
4077
|
async function startTlonGatewayAccount(ctx) {
|
|
3734
4078
|
const account = ctx.account;
|