@openclaw/tlon 2026.7.2-beta.2 → 2026.7.2-beta.4
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-plugin-api.js +1 -1
- package/dist/{channel-B3c5Sud6.js → channel-wkzrI--y.js} +10 -5
- package/dist/{channel.runtime-BtBrqXGq.js → channel.runtime-CDkEY-wR.js} +690 -305
- package/dist/setup-api.js +2 -2
- package/dist/{setup-core-BgykzCYT.js → setup-core-CrZ1Pk4C.js} +82 -4
- package/dist/{setup-surface-j5Hrbts7.js → setup-surface-3Assi5YZ.js} +1 -1
- package/npm-shrinkwrap.json +184 -184
- package/openclaw.plugin.json +49 -1
- package/package.json +79 -32
|
@@ -1,20 +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-CrZ1Pk4C.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-3Assi5YZ.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 { resolveHumanDelayConfig } from "openclaw/plugin-sdk/agent-runtime";
|
|
12
|
+
import { createChannelInboundEnvelopeBuilder, implicitMentionKindWhen, resolveInboundMentionDecision } from "openclaw/plugin-sdk/channel-inbound";
|
|
11
13
|
import { sleepWithAbort } from "openclaw/plugin-sdk/runtime-env";
|
|
12
14
|
import { sliceUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
|
|
13
15
|
import { da, scot } from "@urbit/aura";
|
|
14
16
|
import { Readable } from "node:stream";
|
|
15
17
|
import { resolveTimerTimeoutMs } from "openclaw/plugin-sdk/number-runtime";
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
18
|
+
import { resolveAllowlistMatchByCandidates } from "openclaw/plugin-sdk/allow-from";
|
|
19
|
+
import { resolveChannelImplicitMentions, resolveStableChannelMessageIngress } from "openclaw/plugin-sdk/channel-ingress-runtime";
|
|
20
|
+
import { collectErrorGraphCandidates, formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
|
|
18
21
|
import { mkdir, writeFile } from "node:fs/promises";
|
|
19
22
|
import * as path from "node:path";
|
|
20
23
|
import { extensionForMime } from "openclaw/plugin-sdk/media-mime";
|
|
@@ -285,6 +288,7 @@ async function urbitFetch(params) {
|
|
|
285
288
|
}
|
|
286
289
|
//#endregion
|
|
287
290
|
//#region extensions/tlon/src/urbit/auth.ts
|
|
291
|
+
const MAX_AUTH_BODY_DRAIN_BYTES = 64 * 1024;
|
|
288
292
|
async function authenticate(url, code, options = {}) {
|
|
289
293
|
const { response, release } = await urbitFetch({
|
|
290
294
|
baseUrl: url,
|
|
@@ -302,8 +306,11 @@ async function authenticate(url, code, options = {}) {
|
|
|
302
306
|
auditContext: "tlon-urbit-login"
|
|
303
307
|
});
|
|
304
308
|
try {
|
|
305
|
-
if (!response.ok)
|
|
306
|
-
|
|
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);
|
|
307
314
|
const cookie = response.headers.get("set-cookie");
|
|
308
315
|
if (!cookie) throw new UrbitAuthError("missing_cookie", "No authentication cookie received");
|
|
309
316
|
return cookie;
|
|
@@ -478,6 +485,158 @@ function processInlinesForImages(inlines) {
|
|
|
478
485
|
imageBlocks
|
|
479
486
|
};
|
|
480
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
|
+
}
|
|
481
640
|
/**
|
|
482
641
|
* Convert markdown text to Tlon story format
|
|
483
642
|
*/
|
|
@@ -485,8 +644,11 @@ function markdownToStory(markdown) {
|
|
|
485
644
|
const story = [];
|
|
486
645
|
const lines = markdown.split("\n");
|
|
487
646
|
let i = 0;
|
|
647
|
+
let preservedListMarkerKey;
|
|
488
648
|
while (i < lines.length) {
|
|
489
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;
|
|
490
652
|
if (line.startsWith("```")) {
|
|
491
653
|
const lang = line.slice(3).trim() || "plaintext";
|
|
492
654
|
const codeLines = [];
|
|
@@ -535,25 +697,33 @@ function markdownToStory(markdown) {
|
|
|
535
697
|
i++;
|
|
536
698
|
continue;
|
|
537
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);
|
|
538
710
|
const paragraphLines = [];
|
|
539
711
|
while (true) {
|
|
540
712
|
const paragraphLine = lines.at(i);
|
|
541
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
|
+
}
|
|
542
721
|
paragraphLines.push(paragraphLine);
|
|
543
722
|
i++;
|
|
544
723
|
}
|
|
545
724
|
if (paragraphLines.length > 0) {
|
|
546
|
-
const inlines =
|
|
547
|
-
|
|
548
|
-
for (const inline of inlines) if (typeof inline === "string" && inline.includes("\n")) {
|
|
549
|
-
const parts = inline.split("\n");
|
|
550
|
-
for (const [j, part] of parts.entries()) {
|
|
551
|
-
if (part) withBreaks.push(part);
|
|
552
|
-
if (j < parts.length - 1) withBreaks.push({ break: null });
|
|
553
|
-
}
|
|
554
|
-
} else withBreaks.push(inline);
|
|
555
|
-
const { inlines: cleanInlines, imageBlocks } = processInlinesForImages(withBreaks);
|
|
556
|
-
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 });
|
|
557
727
|
story.push(...imageBlocks);
|
|
558
728
|
}
|
|
559
729
|
}
|
|
@@ -718,7 +888,11 @@ async function pokeUrbitChannel(deps, params) {
|
|
|
718
888
|
try {
|
|
719
889
|
if (!response.ok && response.status !== 204) {
|
|
720
890
|
const errorText = await readResponseTextLimited(response, TLON_ERROR_BODY_LIMIT_BYTES).catch(() => "");
|
|
721
|
-
throw new
|
|
891
|
+
throw new UrbitHttpError({
|
|
892
|
+
operation: "Poke",
|
|
893
|
+
status: response.status,
|
|
894
|
+
bodyText: errorText || void 0
|
|
895
|
+
});
|
|
722
896
|
}
|
|
723
897
|
return pokeId;
|
|
724
898
|
} finally {
|
|
@@ -741,7 +915,10 @@ async function scryUrbitPath(deps, params) {
|
|
|
741
915
|
auditContext: params.auditContext
|
|
742
916
|
});
|
|
743
917
|
try {
|
|
744
|
-
if (!response.ok) throw new
|
|
918
|
+
if (!response.ok) throw new UrbitHttpError({
|
|
919
|
+
operation: `Scry for path ${params.path}`,
|
|
920
|
+
status: response.status
|
|
921
|
+
});
|
|
745
922
|
return await readProviderJsonResponse(response, `Tlon scry response for path ${params.path}`);
|
|
746
923
|
} finally {
|
|
747
924
|
await release();
|
|
@@ -842,6 +1019,18 @@ var UrbitSSEClient = class {
|
|
|
842
1019
|
fetchImpl: this.fetchImpl
|
|
843
1020
|
};
|
|
844
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
|
+
}
|
|
845
1034
|
async subscribe(params) {
|
|
846
1035
|
const subId = this.subscriptions.length + 1;
|
|
847
1036
|
const subscription = {
|
|
@@ -879,10 +1068,9 @@ var UrbitSSEClient = class {
|
|
|
879
1068
|
}
|
|
880
1069
|
}
|
|
881
1070
|
async connect() {
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
});
|
|
1071
|
+
this.lastHeardEventId = -1;
|
|
1072
|
+
this.lastAcknowledgedEventId = -1;
|
|
1073
|
+
await this.createCurrentChannel();
|
|
886
1074
|
await this.openStream();
|
|
887
1075
|
this.isConnected = true;
|
|
888
1076
|
this.reconnectAttempts = 0;
|
|
@@ -917,7 +1105,10 @@ var UrbitSSEClient = class {
|
|
|
917
1105
|
if (!response.ok) {
|
|
918
1106
|
this.streamRelease = null;
|
|
919
1107
|
await release();
|
|
920
|
-
throw new
|
|
1108
|
+
throw new UrbitHttpError({
|
|
1109
|
+
operation: "Stream connection",
|
|
1110
|
+
status: response.status
|
|
1111
|
+
});
|
|
921
1112
|
}
|
|
922
1113
|
this.processStream(response.body).catch((error) => {
|
|
923
1114
|
if (!this.aborted) {
|
|
@@ -942,12 +1133,12 @@ var UrbitSSEClient = class {
|
|
|
942
1133
|
buffer += text;
|
|
943
1134
|
bufferBytes = nextBytes;
|
|
944
1135
|
};
|
|
945
|
-
const consumeText = (text) => {
|
|
1136
|
+
const consumeText = async (text) => {
|
|
946
1137
|
let offset = 0;
|
|
947
1138
|
if (pendingDelimiterNewline && text.length > 0) {
|
|
948
1139
|
pendingDelimiterNewline = false;
|
|
949
1140
|
if (text.startsWith("\n")) {
|
|
950
|
-
this.processEvent(buffer);
|
|
1141
|
+
await this.processEvent(buffer);
|
|
951
1142
|
buffer = "";
|
|
952
1143
|
bufferBytes = 0;
|
|
953
1144
|
offset = 1;
|
|
@@ -962,7 +1153,7 @@ var UrbitSSEClient = class {
|
|
|
962
1153
|
return;
|
|
963
1154
|
}
|
|
964
1155
|
appendPending(text.slice(offset, eventEnd));
|
|
965
|
-
this.processEvent(buffer);
|
|
1156
|
+
await this.processEvent(buffer);
|
|
966
1157
|
buffer = "";
|
|
967
1158
|
bufferBytes = 0;
|
|
968
1159
|
offset = eventEnd + 2;
|
|
@@ -972,11 +1163,11 @@ var UrbitSSEClient = class {
|
|
|
972
1163
|
for await (const chunk of stream) {
|
|
973
1164
|
if (this.aborted) break;
|
|
974
1165
|
if (typeof chunk === "string") {
|
|
975
|
-
consumeText(decoder.decode());
|
|
976
|
-
consumeText(chunk);
|
|
977
|
-
} 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 }));
|
|
978
1169
|
}
|
|
979
|
-
consumeText(decoder.decode());
|
|
1170
|
+
await consumeText(decoder.decode());
|
|
980
1171
|
} finally {
|
|
981
1172
|
if (this.streamRelease) {
|
|
982
1173
|
const release = this.streamRelease;
|
|
@@ -991,7 +1182,7 @@ var UrbitSSEClient = class {
|
|
|
991
1182
|
}
|
|
992
1183
|
}
|
|
993
1184
|
}
|
|
994
|
-
processEvent(eventData) {
|
|
1185
|
+
async processEvent(eventData) {
|
|
995
1186
|
const lines = eventData.split("\n");
|
|
996
1187
|
let data = null;
|
|
997
1188
|
let eventId = null;
|
|
@@ -1000,35 +1191,33 @@ var UrbitSSEClient = class {
|
|
|
1000
1191
|
if (line.startsWith("data: ")) data = line.slice(6);
|
|
1001
1192
|
}
|
|
1002
1193
|
if (!data) return;
|
|
1003
|
-
|
|
1004
|
-
if (eventId > this.lastHeardEventId) {
|
|
1005
|
-
this.lastHeardEventId = eventId;
|
|
1006
|
-
if (eventId - this.lastAcknowledgedEventId > this.ackThreshold) {
|
|
1007
|
-
this.logger.log?.(`[SSE] Acking event ${eventId} (last acked: ${this.lastAcknowledgedEventId})`);
|
|
1008
|
-
this.ack(eventId).catch((err) => {
|
|
1009
|
-
this.logger.error?.(`Failed to ack event ${eventId}: ${String(err)}`);
|
|
1010
|
-
});
|
|
1011
|
-
}
|
|
1012
|
-
}
|
|
1013
|
-
}
|
|
1194
|
+
let parsed;
|
|
1014
1195
|
try {
|
|
1015
|
-
|
|
1016
|
-
if (parsed.response === "quit") {
|
|
1017
|
-
if (parsed.id) {
|
|
1018
|
-
const handlers = this.eventHandlers.get(parsed.id);
|
|
1019
|
-
if (handlers?.quit) handlers.quit();
|
|
1020
|
-
}
|
|
1021
|
-
return;
|
|
1022
|
-
}
|
|
1023
|
-
if (parsed.id && this.eventHandlers.has(parsed.id)) {
|
|
1024
|
-
const { event } = this.eventHandlers.get(parsed.id) ?? {};
|
|
1025
|
-
if (event && parsed.json) event(parsed.json);
|
|
1026
|
-
} else if (parsed.json) {
|
|
1027
|
-
for (const { event } of this.eventHandlers.values()) if (event) event(parsed.json);
|
|
1028
|
-
}
|
|
1196
|
+
parsed = parseUrbitSsePayload(data);
|
|
1029
1197
|
} catch (error) {
|
|
1030
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);
|
|
1031
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);
|
|
1032
1221
|
}
|
|
1033
1222
|
async poke(params) {
|
|
1034
1223
|
return await pokeUrbitChannel(this.channelRequestContext(), {
|
|
@@ -1056,7 +1245,6 @@ var UrbitSSEClient = class {
|
|
|
1056
1245
|
this.cookie = normalizeUrbitCookie(newCookie);
|
|
1057
1246
|
}
|
|
1058
1247
|
async ack(eventId) {
|
|
1059
|
-
this.lastAcknowledgedEventId = eventId;
|
|
1060
1248
|
const ackData = {
|
|
1061
1249
|
id: Date.now(),
|
|
1062
1250
|
action: "ack",
|
|
@@ -1068,6 +1256,7 @@ var UrbitSSEClient = class {
|
|
|
1068
1256
|
});
|
|
1069
1257
|
try {
|
|
1070
1258
|
if (!response.ok) throw new Error(`Ack failed with status ${response.status}`);
|
|
1259
|
+
this.lastAcknowledgedEventId = eventId;
|
|
1071
1260
|
} finally {
|
|
1072
1261
|
await release();
|
|
1073
1262
|
}
|
|
@@ -1092,21 +1281,32 @@ var UrbitSSEClient = class {
|
|
|
1092
1281
|
await new Promise((resolve) => {
|
|
1093
1282
|
setTimeout(resolve, delay);
|
|
1094
1283
|
});
|
|
1284
|
+
if (this.aborted || !this.autoReconnect) return;
|
|
1095
1285
|
try {
|
|
1096
|
-
this.channelId = `${Math.floor(Date.now() / 1e3)}-${randomUUID()}`;
|
|
1097
|
-
this.channelUrl = new URL(`/~/channel/${this.channelId}`, this.url).toString();
|
|
1098
1286
|
if (this.onReconnect) await this.onReconnect(this);
|
|
1099
|
-
|
|
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;
|
|
1100
1297
|
this.logger.log?.("[SSE] Reconnection successful!");
|
|
1101
1298
|
} catch (error) {
|
|
1102
1299
|
this.logger.error?.(`[SSE] Reconnection failed: ${String(error)}`);
|
|
1103
1300
|
await this.attemptReconnect();
|
|
1104
1301
|
}
|
|
1105
1302
|
}
|
|
1106
|
-
|
|
1303
|
+
stopReceiving() {
|
|
1107
1304
|
this.aborted = true;
|
|
1108
1305
|
this.isConnected = false;
|
|
1109
1306
|
this.streamController?.abort();
|
|
1307
|
+
}
|
|
1308
|
+
async close() {
|
|
1309
|
+
this.stopReceiving();
|
|
1110
1310
|
try {
|
|
1111
1311
|
const unsubscribes = this.subscriptions.map((sub) => ({
|
|
1112
1312
|
id: sub.id,
|
|
@@ -1119,7 +1319,7 @@ var UrbitSSEClient = class {
|
|
|
1119
1319
|
auditContext: "tlon-urbit-unsubscribe"
|
|
1120
1320
|
});
|
|
1121
1321
|
try {
|
|
1122
|
-
response.body?.cancel();
|
|
1322
|
+
response.body?.cancel().catch(() => void 0);
|
|
1123
1323
|
} finally {
|
|
1124
1324
|
await release();
|
|
1125
1325
|
}
|
|
@@ -1139,7 +1339,7 @@ var UrbitSSEClient = class {
|
|
|
1139
1339
|
auditContext: "tlon-urbit-channel-close"
|
|
1140
1340
|
});
|
|
1141
1341
|
try {
|
|
1142
|
-
response.body?.cancel();
|
|
1342
|
+
response.body?.cancel().catch(() => void 0);
|
|
1143
1343
|
} finally {
|
|
1144
1344
|
await release();
|
|
1145
1345
|
}
|
|
@@ -1694,10 +1894,37 @@ async function resolveTlonCommandAuthorizationWithIngress(params) {
|
|
|
1694
1894
|
command: {}
|
|
1695
1895
|
});
|
|
1696
1896
|
}
|
|
1897
|
+
function resolveTlonGroupMentionDecision(params) {
|
|
1898
|
+
const implicitMentions = resolveChannelImplicitMentions({
|
|
1899
|
+
cfg: params.cfg,
|
|
1900
|
+
channel: "tlon",
|
|
1901
|
+
accountId: params.accountId
|
|
1902
|
+
});
|
|
1903
|
+
return resolveInboundMentionDecision({
|
|
1904
|
+
facts: {
|
|
1905
|
+
canDetectMention: true,
|
|
1906
|
+
wasMentioned: params.wasMentioned,
|
|
1907
|
+
implicitMentionKinds: implicitMentionKindWhen("bot_thread_participant", params.botParticipatedInThread)
|
|
1908
|
+
},
|
|
1909
|
+
policy: {
|
|
1910
|
+
isGroup: true,
|
|
1911
|
+
requireMention: true,
|
|
1912
|
+
implicitMentions,
|
|
1913
|
+
allowTextCommands: false,
|
|
1914
|
+
hasControlCommand: false,
|
|
1915
|
+
commandAuthorized: false
|
|
1916
|
+
}
|
|
1917
|
+
});
|
|
1918
|
+
}
|
|
1697
1919
|
function isGroupInviteAllowed(inviterShip, allowlist) {
|
|
1698
|
-
if (!allowlist || allowlist.length === 0) return false;
|
|
1699
1920
|
const normalizedInviter = normalizeShip(inviterShip);
|
|
1700
|
-
return
|
|
1921
|
+
return resolveAllowlistMatchByCandidates({
|
|
1922
|
+
allowList: (allowlist ?? []).map((ship) => normalizeShip(ship)),
|
|
1923
|
+
candidates: [{
|
|
1924
|
+
value: normalizedInviter,
|
|
1925
|
+
source: "ship"
|
|
1926
|
+
}]
|
|
1927
|
+
}).allowed;
|
|
1701
1928
|
}
|
|
1702
1929
|
async function resolveAuthorizedMessageText(params) {
|
|
1703
1930
|
const { rawText, content, authorizedForCites, resolveAllCites } = params;
|
|
@@ -2016,6 +2243,149 @@ async function fetchThreadHistory(api, channelNest, parentId, count = 50, runtim
|
|
|
2016
2243
|
}
|
|
2017
2244
|
}
|
|
2018
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
|
|
2019
2389
|
//#region extensions/tlon/src/media-fetch-timeouts.ts
|
|
2020
2390
|
const TLON_MEDIA_FETCH_TIMEOUTS = {
|
|
2021
2391
|
responseHeaderTimeoutMs: 12e4,
|
|
@@ -2024,6 +2394,18 @@ const TLON_MEDIA_FETCH_TIMEOUTS = {
|
|
|
2024
2394
|
//#endregion
|
|
2025
2395
|
//#region extensions/tlon/src/monitor/media.ts
|
|
2026
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
|
+
}
|
|
2027
2409
|
/**
|
|
2028
2410
|
* Extract image blocks from Tlon message content.
|
|
2029
2411
|
* Returns array of image URLs found in the message.
|
|
@@ -2114,66 +2496,6 @@ async function downloadMessageImages(content, mediaDir) {
|
|
|
2114
2496
|
return attachments;
|
|
2115
2497
|
}
|
|
2116
2498
|
//#endregion
|
|
2117
|
-
//#region extensions/tlon/src/monitor/processed-messages.ts
|
|
2118
|
-
function createProcessedMessageTracker(limit = 2e3) {
|
|
2119
|
-
const dedupe = createDedupeCache({
|
|
2120
|
-
ttlMs: 0,
|
|
2121
|
-
maxSize: limit
|
|
2122
|
-
});
|
|
2123
|
-
const inFlight = /* @__PURE__ */ new Set();
|
|
2124
|
-
const claim = (id) => {
|
|
2125
|
-
const trimmed = id?.trim();
|
|
2126
|
-
if (!trimmed) return { kind: "claimed" };
|
|
2127
|
-
if (inFlight.has(trimmed) || dedupe.peek(trimmed)) return { kind: "duplicate" };
|
|
2128
|
-
inFlight.add(trimmed);
|
|
2129
|
-
return { kind: "claimed" };
|
|
2130
|
-
};
|
|
2131
|
-
const commit = (id) => {
|
|
2132
|
-
const trimmed = id?.trim();
|
|
2133
|
-
if (!trimmed) return;
|
|
2134
|
-
inFlight.delete(trimmed);
|
|
2135
|
-
dedupe.check(trimmed);
|
|
2136
|
-
};
|
|
2137
|
-
const release = (id) => {
|
|
2138
|
-
const trimmed = id?.trim();
|
|
2139
|
-
if (!trimmed) return;
|
|
2140
|
-
inFlight.delete(trimmed);
|
|
2141
|
-
};
|
|
2142
|
-
const mark = (id) => {
|
|
2143
|
-
if (claim(id).kind === "duplicate") return false;
|
|
2144
|
-
commit(id);
|
|
2145
|
-
return true;
|
|
2146
|
-
};
|
|
2147
|
-
const has = (id) => {
|
|
2148
|
-
const trimmed = id?.trim();
|
|
2149
|
-
if (!trimmed) return false;
|
|
2150
|
-
return dedupe.peek(trimmed);
|
|
2151
|
-
};
|
|
2152
|
-
return {
|
|
2153
|
-
claim,
|
|
2154
|
-
commit,
|
|
2155
|
-
release,
|
|
2156
|
-
mark,
|
|
2157
|
-
has,
|
|
2158
|
-
size: () => dedupe.size()
|
|
2159
|
-
};
|
|
2160
|
-
}
|
|
2161
|
-
async function runWithProcessedMessageClaim(params) {
|
|
2162
|
-
const claim = params.tracker.claim(params.id);
|
|
2163
|
-
if (claim.kind === "duplicate") return claim;
|
|
2164
|
-
try {
|
|
2165
|
-
const value = await params.task();
|
|
2166
|
-
params.tracker.commit(params.id);
|
|
2167
|
-
return {
|
|
2168
|
-
kind: "processed",
|
|
2169
|
-
value
|
|
2170
|
-
};
|
|
2171
|
-
} catch (error) {
|
|
2172
|
-
params.tracker.release(params.id);
|
|
2173
|
-
throw error;
|
|
2174
|
-
}
|
|
2175
|
-
}
|
|
2176
|
-
//#endregion
|
|
2177
2499
|
//#region extensions/tlon/src/monitor/settings-helpers.ts
|
|
2178
2500
|
function buildTlonSettingsMigrations(account, currentSettings) {
|
|
2179
2501
|
return [
|
|
@@ -2277,6 +2599,37 @@ function mergeUniqueStrings(base, next) {
|
|
|
2277
2599
|
return uniqueStrings([...base, ...next ?? []]);
|
|
2278
2600
|
}
|
|
2279
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
|
|
2280
2633
|
//#region extensions/tlon/src/monitor/index.ts
|
|
2281
2634
|
function readNumber(record, key) {
|
|
2282
2635
|
return asFiniteNumber(record?.[key]);
|
|
@@ -2327,7 +2680,6 @@ async function monitorTlonProvider(opts = {}) {
|
|
|
2327
2680
|
runtime.log?.("[tlon] Re-authentication successful");
|
|
2328
2681
|
}
|
|
2329
2682
|
});
|
|
2330
|
-
const processedTracker = createProcessedMessageTracker(2e3);
|
|
2331
2683
|
let groupChannels = [];
|
|
2332
2684
|
let botNickname = null;
|
|
2333
2685
|
const settingsManager = createSettingsManager(api, {
|
|
@@ -2343,7 +2695,7 @@ async function monitorTlonProvider(opts = {}) {
|
|
|
2343
2695
|
let effectiveOwnerShip = account.ownerShip ? normalizeShip(account.ownerShip) : null;
|
|
2344
2696
|
let pendingApprovals = [];
|
|
2345
2697
|
let currentSettings = {};
|
|
2346
|
-
const participatedThreads =
|
|
2698
|
+
const participatedThreads = createParticipatedThreadTracker();
|
|
2347
2699
|
const dmSendersBySession = /* @__PURE__ */ new Map();
|
|
2348
2700
|
let sharedSessionWarningSent = false;
|
|
2349
2701
|
try {
|
|
@@ -2413,7 +2765,7 @@ async function monitorTlonProvider(opts = {}) {
|
|
|
2413
2765
|
return /^~?[a-z-]+$/i.test(normalized) ? normalized : "";
|
|
2414
2766
|
}
|
|
2415
2767
|
const processMessage = async (params) => {
|
|
2416
|
-
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;
|
|
2417
2769
|
const groupChannel = channelNest;
|
|
2418
2770
|
let messageText = params.messageText;
|
|
2419
2771
|
let attachments = [];
|
|
@@ -2511,21 +2863,22 @@ async function monitorTlonProvider(opts = {}) {
|
|
|
2511
2863
|
const shouldComputeAuth = core.channel.commands.shouldComputeCommandAuthorized(messageText, cfg);
|
|
2512
2864
|
let commandAuthorized = false;
|
|
2513
2865
|
if (shouldComputeAuth) {
|
|
2514
|
-
const useAccessGroups = cfg.commands?.useAccessGroups !== false;
|
|
2515
2866
|
commandAuthorized = (await resolveTlonCommandAuthorizationWithIngress({
|
|
2516
2867
|
senderShip,
|
|
2517
2868
|
ownerShip: effectiveOwnerShip,
|
|
2518
|
-
useAccessGroups
|
|
2869
|
+
useAccessGroups: true
|
|
2519
2870
|
})).commandAccess.authorized;
|
|
2520
2871
|
if (!commandAuthorized) console.log(`[tlon] Command attempt denied: ${senderShip} is not owner (owner=${effectiveOwnerShip ?? "not configured"})`);
|
|
2521
2872
|
}
|
|
2522
|
-
|
|
2523
|
-
|
|
2524
|
-
|
|
2873
|
+
const promptMedia = buildTlonInboundMediaPrompt(messageText, attachments);
|
|
2874
|
+
const body = createChannelInboundEnvelopeBuilder({
|
|
2875
|
+
cfg,
|
|
2876
|
+
route
|
|
2877
|
+
})({
|
|
2525
2878
|
channel: "Tlon",
|
|
2526
2879
|
from: fromLabel,
|
|
2527
2880
|
timestamp,
|
|
2528
|
-
body:
|
|
2881
|
+
body: promptMedia.body
|
|
2529
2882
|
});
|
|
2530
2883
|
const commandBody = isGroup ? stripBotMention(messageText, botShipName) : messageText;
|
|
2531
2884
|
const tlonConversationId = isGroup ? groupChannel ?? channelNest ?? senderShip : senderShip;
|
|
@@ -2547,6 +2900,7 @@ async function monitorTlonProvider(opts = {}) {
|
|
|
2547
2900
|
},
|
|
2548
2901
|
route: {
|
|
2549
2902
|
agentId: route.agentId,
|
|
2903
|
+
dmScope: route.dmScope,
|
|
2550
2904
|
accountId: route.accountId,
|
|
2551
2905
|
routeSessionKey: route.sessionKey
|
|
2552
2906
|
},
|
|
@@ -2572,8 +2926,7 @@ async function monitorTlonProvider(opts = {}) {
|
|
|
2572
2926
|
});
|
|
2573
2927
|
const dispatchStartTime = Date.now();
|
|
2574
2928
|
const responsePrefix = core.channel.reply.resolveEffectiveMessagesConfig(cfg, route.agentId).responsePrefix;
|
|
2575
|
-
const humanDelay =
|
|
2576
|
-
const storePath = core.channel.session.resolveStorePath(cfg.session?.store, { agentId: route.agentId });
|
|
2929
|
+
const humanDelay = resolveHumanDelayConfig(cfg, route.agentId);
|
|
2577
2930
|
const deliveryTarget = isGroup ? groupChannel : senderShip;
|
|
2578
2931
|
const prepareReplyPayload = (payload) => {
|
|
2579
2932
|
const replyText = payload.text;
|
|
@@ -2592,16 +2945,20 @@ async function monitorTlonProvider(opts = {}) {
|
|
|
2592
2945
|
participatedThreads.add(parentId);
|
|
2593
2946
|
runtime.log?.(`[tlon] Now tracking thread for future replies: ${parentId}`);
|
|
2594
2947
|
};
|
|
2595
|
-
|
|
2948
|
+
const replyOptions = {
|
|
2949
|
+
...turnAdoptionLifecycle ? bindIngressLifecycleToReplyOptions(turnAdoptionLifecycle) : {},
|
|
2950
|
+
...promptMedia.media.length > 0 ? { media: promptMedia.media } : {}
|
|
2951
|
+
};
|
|
2952
|
+
await core.channel.inbound.dispatch({
|
|
2596
2953
|
channel: "tlon",
|
|
2597
2954
|
accountId: route.accountId,
|
|
2598
2955
|
cfg,
|
|
2599
|
-
|
|
2600
|
-
|
|
2601
|
-
|
|
2956
|
+
route: {
|
|
2957
|
+
agentId: route.agentId,
|
|
2958
|
+
dmScope: route.dmScope,
|
|
2959
|
+
sessionKey: route.sessionKey
|
|
2960
|
+
},
|
|
2602
2961
|
ctxPayload,
|
|
2603
|
-
recordInboundSession: core.channel.session.recordInboundSession,
|
|
2604
|
-
dispatchReplyWithBufferedBlockDispatcher: core.channel.reply.dispatchReplyWithBufferedBlockDispatcher,
|
|
2605
2962
|
delivery: {
|
|
2606
2963
|
preparePayload: prepareReplyPayload,
|
|
2607
2964
|
durable: deliveryTarget ? () => ({
|
|
@@ -2648,6 +3005,7 @@ async function monitorTlonProvider(opts = {}) {
|
|
|
2648
3005
|
responsePrefix,
|
|
2649
3006
|
humanDelay
|
|
2650
3007
|
},
|
|
3008
|
+
...turnAdoptionLifecycle || promptMedia.media.length > 0 ? { replyOptions } : {},
|
|
2651
3009
|
record: { onRecordError: (err) => {
|
|
2652
3010
|
runtime.error?.(`[tlon] failed updating session meta: ${String(err)}`);
|
|
2653
3011
|
} }
|
|
@@ -2719,7 +3077,7 @@ async function monitorTlonProvider(opts = {}) {
|
|
|
2719
3077
|
},
|
|
2720
3078
|
refreshWatchedChannels
|
|
2721
3079
|
});
|
|
2722
|
-
const handleChannelsFirehose = async (event) => {
|
|
3080
|
+
const handleChannelsFirehose = async (event, turnAdoptionLifecycle) => {
|
|
2723
3081
|
try {
|
|
2724
3082
|
const eventRecord = asRecord(event);
|
|
2725
3083
|
const nest = readString(eventRecord, "nest");
|
|
@@ -2740,87 +3098,89 @@ async function monitorTlonProvider(opts = {}) {
|
|
|
2740
3098
|
const isThreadReply = Boolean(memo);
|
|
2741
3099
|
const messageId = isThreadReply ? readString(reply, "id") : readString(post, "id");
|
|
2742
3100
|
if (!messageId) return;
|
|
2743
|
-
|
|
2744
|
-
|
|
2745
|
-
|
|
2746
|
-
|
|
2747
|
-
|
|
2748
|
-
|
|
2749
|
-
|
|
2750
|
-
|
|
2751
|
-
|
|
2752
|
-
|
|
2753
|
-
|
|
2754
|
-
|
|
2755
|
-
|
|
2756
|
-
|
|
2757
|
-
|
|
2758
|
-
|
|
2759
|
-
|
|
2760
|
-
|
|
2761
|
-
|
|
2762
|
-
|
|
2763
|
-
|
|
2764
|
-
|
|
2765
|
-
|
|
2766
|
-
|
|
2767
|
-
|
|
2768
|
-
|
|
2769
|
-
|
|
2770
|
-
|
|
2771
|
-
|
|
2772
|
-
|
|
2773
|
-
|
|
2774
|
-
|
|
2775
|
-
|
|
2776
|
-
|
|
2777
|
-
|
|
2778
|
-
|
|
2779
|
-
|
|
2780
|
-
|
|
2781
|
-
|
|
2782
|
-
|
|
2783
|
-
|
|
2784
|
-
|
|
2785
|
-
|
|
2786
|
-
|
|
2787
|
-
|
|
2788
|
-
|
|
2789
|
-
|
|
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;
|
|
2790
3148
|
}
|
|
2791
|
-
const messageText = await resolveAuthorizedMessageText({
|
|
2792
|
-
rawText,
|
|
2793
|
-
content: contentBody,
|
|
2794
|
-
authorizedForCites: true,
|
|
2795
|
-
resolveAllCites
|
|
2796
|
-
});
|
|
2797
|
-
const parsed = parseChannelNest(nest);
|
|
2798
|
-
await processMessage({
|
|
2799
|
-
messageId: messageId ?? "",
|
|
2800
|
-
senderShip,
|
|
2801
|
-
messageText,
|
|
2802
|
-
messageContent: contentBody,
|
|
2803
|
-
isGroup: true,
|
|
2804
|
-
channelNest: nest,
|
|
2805
|
-
hostShip: parsed?.hostShip,
|
|
2806
|
-
channelName: parsed?.channelName,
|
|
2807
|
-
timestamp: sentAt,
|
|
2808
|
-
parentId,
|
|
2809
|
-
isThreadReply
|
|
2810
|
-
});
|
|
2811
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
|
|
2812
3171
|
});
|
|
2813
3172
|
} catch (error) {
|
|
2814
3173
|
runtime.error?.(`[tlon] Error handling channel firehose event: ${formatErrorMessage$1(error)}`);
|
|
3174
|
+
throw error;
|
|
2815
3175
|
}
|
|
2816
3176
|
};
|
|
2817
|
-
const processedDmInvites =
|
|
2818
|
-
const handleChatFirehose = async (event) => {
|
|
3177
|
+
const processedDmInvites = createActiveSnapshotTracker();
|
|
3178
|
+
const handleChatFirehose = async (event, turnAdoptionLifecycle) => {
|
|
2819
3179
|
try {
|
|
2820
3180
|
if (Array.isArray(event)) {
|
|
2821
|
-
|
|
2822
|
-
|
|
2823
|
-
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;
|
|
2824
3184
|
if (isOwner(ship)) {
|
|
2825
3185
|
try {
|
|
2826
3186
|
await api.poke({
|
|
@@ -2838,7 +3198,8 @@ async function monitorTlonProvider(opts = {}) {
|
|
|
2838
3198
|
}
|
|
2839
3199
|
continue;
|
|
2840
3200
|
}
|
|
2841
|
-
|
|
3201
|
+
const allowed = await isDmAllowedWithIngress(ship, effectiveDmAllowlist);
|
|
3202
|
+
if (effectiveAutoAcceptDmInvites && allowed) {
|
|
2842
3203
|
try {
|
|
2843
3204
|
await api.poke({
|
|
2844
3205
|
app: "chat",
|
|
@@ -2855,7 +3216,7 @@ async function monitorTlonProvider(opts = {}) {
|
|
|
2855
3216
|
}
|
|
2856
3217
|
continue;
|
|
2857
3218
|
}
|
|
2858
|
-
if (effectiveOwnerShip && !
|
|
3219
|
+
if (effectiveOwnerShip && !allowed) {
|
|
2859
3220
|
const approval = createPendingApproval({
|
|
2860
3221
|
type: "dm",
|
|
2861
3222
|
requestingShip: ship,
|
|
@@ -2875,92 +3236,104 @@ async function monitorTlonProvider(opts = {}) {
|
|
|
2875
3236
|
if (!messageId || !response) return;
|
|
2876
3237
|
const essay = asRecord(asRecord(response.add)?.essay);
|
|
2877
3238
|
if (!essay) return;
|
|
2878
|
-
|
|
2879
|
-
|
|
2880
|
-
|
|
2881
|
-
|
|
2882
|
-
|
|
2883
|
-
|
|
2884
|
-
|
|
2885
|
-
|
|
2886
|
-
|
|
2887
|
-
|
|
2888
|
-
|
|
2889
|
-
|
|
2890
|
-
|
|
2891
|
-
|
|
2892
|
-
|
|
2893
|
-
|
|
2894
|
-
|
|
2895
|
-
|
|
2896
|
-
|
|
2897
|
-
|
|
2898
|
-
|
|
2899
|
-
|
|
2900
|
-
|
|
2901
|
-
|
|
2902
|
-
|
|
2903
|
-
|
|
2904
|
-
|
|
2905
|
-
|
|
2906
|
-
|
|
2907
|
-
|
|
2908
|
-
|
|
2909
|
-
|
|
2910
|
-
|
|
2911
|
-
|
|
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: {
|
|
2912
3286
|
messageId: messageId ?? "",
|
|
2913
|
-
|
|
2914
|
-
messageText: resolvedMessageText,
|
|
3287
|
+
messageText,
|
|
2915
3288
|
messageContent: essay.content,
|
|
2916
|
-
isGroup: false,
|
|
2917
3289
|
timestamp: readNumber(essay, "sent") ?? Date.now()
|
|
2918
|
-
}
|
|
2919
|
-
return;
|
|
2920
|
-
}
|
|
2921
|
-
if (!await isDmAllowedWithIngress(senderShip, effectiveDmAllowlist)) {
|
|
2922
|
-
if (effectiveOwnerShip) {
|
|
2923
|
-
const approval = createPendingApproval({
|
|
2924
|
-
type: "dm",
|
|
2925
|
-
requestingShip: senderShip,
|
|
2926
|
-
messagePreview: sliceUtf16Safe(messageText, 0, 100),
|
|
2927
|
-
originalMessage: {
|
|
2928
|
-
messageId: messageId ?? "",
|
|
2929
|
-
messageText,
|
|
2930
|
-
messageContent: essay.content,
|
|
2931
|
-
timestamp: readNumber(essay, "sent") ?? Date.now()
|
|
2932
|
-
}
|
|
2933
|
-
});
|
|
2934
|
-
await queueApprovalRequest(approval);
|
|
2935
|
-
} else runtime.log?.(`[tlon] Blocked DM from ${senderShip}: not in allowlist`);
|
|
2936
|
-
return;
|
|
2937
|
-
}
|
|
2938
|
-
await processMessage({
|
|
2939
|
-
messageText: await resolveAuthorizedMessageText({
|
|
2940
|
-
rawText,
|
|
2941
|
-
content: essay.content,
|
|
2942
|
-
authorizedForCites: true,
|
|
2943
|
-
resolveAllCites
|
|
2944
|
-
}),
|
|
2945
|
-
messageId: messageId ?? "",
|
|
2946
|
-
senderShip,
|
|
2947
|
-
messageContent: essay.content,
|
|
2948
|
-
isGroup: false,
|
|
2949
|
-
timestamp: readNumber(essay, "sent") ?? Date.now()
|
|
3290
|
+
}
|
|
2950
3291
|
});
|
|
2951
|
-
|
|
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
|
|
2952
3309
|
});
|
|
2953
3310
|
} catch (error) {
|
|
2954
3311
|
runtime.error?.(`[tlon] Error handling chat firehose event: ${formatErrorMessage$1(error)}`);
|
|
3312
|
+
throw error;
|
|
2955
3313
|
}
|
|
2956
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
|
+
});
|
|
2957
3327
|
try {
|
|
2958
3328
|
runtime.log?.("[tlon] Subscribing to firehose updates...");
|
|
2959
3329
|
await api.subscribe({
|
|
2960
3330
|
app: "channels",
|
|
2961
3331
|
path: "/v2",
|
|
2962
|
-
event: (event) => {
|
|
2963
|
-
|
|
3332
|
+
event: async (event) => {
|
|
3333
|
+
if ((await ingress.receive({
|
|
3334
|
+
source: "channels",
|
|
3335
|
+
event
|
|
3336
|
+
})).kind === "ignored") await handleChannelsFirehose(event);
|
|
2964
3337
|
},
|
|
2965
3338
|
err: (error) => {
|
|
2966
3339
|
runtime.error?.(`[tlon] Channels firehose error: ${String(error)}`);
|
|
@@ -2973,8 +3346,11 @@ async function monitorTlonProvider(opts = {}) {
|
|
|
2973
3346
|
await api.subscribe({
|
|
2974
3347
|
app: "chat",
|
|
2975
3348
|
path: "/v3",
|
|
2976
|
-
event: (event) => {
|
|
2977
|
-
|
|
3349
|
+
event: async (event) => {
|
|
3350
|
+
if ((await ingress.receive({
|
|
3351
|
+
source: "chat",
|
|
3352
|
+
event
|
|
3353
|
+
})).kind === "ignored") await handleChatFirehose(event);
|
|
2978
3354
|
},
|
|
2979
3355
|
err: (error) => {
|
|
2980
3356
|
runtime.error?.(`[tlon] Chat firehose error: ${String(error)}`);
|
|
@@ -3220,6 +3596,7 @@ async function monitorTlonProvider(opts = {}) {
|
|
|
3220
3596
|
for (const channelNest of watchedChannels) runtime.log?.(`[tlon] Watching channel: ${channelNest}`);
|
|
3221
3597
|
runtime.log?.("[tlon] All subscriptions registered, connecting to SSE stream...");
|
|
3222
3598
|
await api.connect();
|
|
3599
|
+
ingress.start();
|
|
3223
3600
|
runtime.log?.("[tlon] Connected! Firehose subscriptions active");
|
|
3224
3601
|
const pollInterval = setInterval(() => {
|
|
3225
3602
|
(async () => {
|
|
@@ -3246,6 +3623,8 @@ async function monitorTlonProvider(opts = {}) {
|
|
|
3246
3623
|
});
|
|
3247
3624
|
} else await new Promise(() => {});
|
|
3248
3625
|
} finally {
|
|
3626
|
+
api?.stopReceiving();
|
|
3627
|
+
await ingress.stop();
|
|
3249
3628
|
try {
|
|
3250
3629
|
await api?.close();
|
|
3251
3630
|
} catch (error) {
|
|
@@ -3263,6 +3642,14 @@ const TLON_MEMEX_UPLOAD_URL_TIMEOUT_MS = 3e4;
|
|
|
3263
3642
|
/** Total deadline for Memex and custom S3 PUTs, including DNS and the full upload. */
|
|
3264
3643
|
const TLON_UPLOAD_TIMEOUT_MS = 3e5;
|
|
3265
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
|
+
}
|
|
3266
3653
|
function configureClient(params) {
|
|
3267
3654
|
currentClientConfig = {
|
|
3268
3655
|
...params,
|
|
@@ -3362,9 +3749,9 @@ async function getMemexUploadUrl(params) {
|
|
|
3362
3749
|
const resolvedToken = typeof token === "string" ? token : token.secret;
|
|
3363
3750
|
if (!resolvedToken) throw new Error("Missing genuine secret");
|
|
3364
3751
|
const endpoint = `${MEMEX_BASE_URL}/v1/${params.config.shipName}/upload`;
|
|
3365
|
-
let
|
|
3752
|
+
let guarded;
|
|
3366
3753
|
try {
|
|
3367
|
-
|
|
3754
|
+
guarded = await fetchWithSsrFGuard({
|
|
3368
3755
|
url: endpoint,
|
|
3369
3756
|
init: {
|
|
3370
3757
|
method: "PUT",
|
|
@@ -3381,7 +3768,6 @@ async function getMemexUploadUrl(params) {
|
|
|
3381
3768
|
maxRedirects: 0,
|
|
3382
3769
|
timeoutMs: TLON_MEMEX_UPLOAD_URL_TIMEOUT_MS
|
|
3383
3770
|
});
|
|
3384
|
-
release = guarded.release;
|
|
3385
3771
|
if (!guarded.response.ok) throw new Error(`Memex upload request failed: ${guarded.response.status}`);
|
|
3386
3772
|
const data = await readProviderJsonResponse(guarded.response, "Memex upload", { maxBytes: MEMEX_UPLOAD_RESPONSE_MAX_BYTES });
|
|
3387
3773
|
if (!data?.url || !data.filePath) throw new Error("Invalid response from Memex");
|
|
@@ -3390,7 +3776,7 @@ async function getMemexUploadUrl(params) {
|
|
|
3390
3776
|
uploadUrl: data.url
|
|
3391
3777
|
};
|
|
3392
3778
|
} finally {
|
|
3393
|
-
await
|
|
3779
|
+
await releaseUploadResponse(guarded);
|
|
3394
3780
|
}
|
|
3395
3781
|
}
|
|
3396
3782
|
async function uploadFile(params) {
|
|
@@ -3411,9 +3797,9 @@ async function uploadFile(params) {
|
|
|
3411
3797
|
fileName: fileKey
|
|
3412
3798
|
});
|
|
3413
3799
|
const trustedUploadUrl = assertTrustedMemexUploadUrl(uploadUrl, "Memex upload URL");
|
|
3414
|
-
let
|
|
3800
|
+
let guarded;
|
|
3415
3801
|
try {
|
|
3416
|
-
|
|
3802
|
+
guarded = await fetchWithSsrFGuard({
|
|
3417
3803
|
url: trustedUploadUrl,
|
|
3418
3804
|
init: {
|
|
3419
3805
|
method: "PUT",
|
|
@@ -3428,11 +3814,10 @@ async function uploadFile(params) {
|
|
|
3428
3814
|
maxRedirects: 0,
|
|
3429
3815
|
timeoutMs: TLON_UPLOAD_TIMEOUT_MS
|
|
3430
3816
|
});
|
|
3431
|
-
release = guarded.release;
|
|
3432
3817
|
assertTrustedMemexUploadUrl(guarded.finalUrl, "Memex final upload URL");
|
|
3433
3818
|
if (!guarded.response.ok) throw new Error(`Upload failed: ${guarded.response.status}`);
|
|
3434
3819
|
} finally {
|
|
3435
|
-
await
|
|
3820
|
+
await releaseUploadResponse(guarded);
|
|
3436
3821
|
}
|
|
3437
3822
|
return { url: assertTrustedMemexUploadUrl(hostedUrl, "Memex hosted URL") };
|
|
3438
3823
|
}
|
|
@@ -3458,9 +3843,9 @@ async function uploadFile(params) {
|
|
|
3458
3843
|
CacheControl: headers["Cache-Control"],
|
|
3459
3844
|
ACL: "public-read"
|
|
3460
3845
|
}), { expiresIn: 3600 });
|
|
3461
|
-
let
|
|
3846
|
+
let guarded;
|
|
3462
3847
|
try {
|
|
3463
|
-
|
|
3848
|
+
guarded = await fetchWithSsrFGuard({
|
|
3464
3849
|
url: signedUrl,
|
|
3465
3850
|
init: {
|
|
3466
3851
|
method: "PUT",
|
|
@@ -3473,10 +3858,9 @@ async function uploadFile(params) {
|
|
|
3473
3858
|
policy: privateNetworkPolicy,
|
|
3474
3859
|
timeoutMs: TLON_UPLOAD_TIMEOUT_MS
|
|
3475
3860
|
});
|
|
3476
|
-
release = guarded.release;
|
|
3477
3861
|
if (!guarded.response.ok) throw new Error(`Upload failed: ${guarded.response.status}`);
|
|
3478
3862
|
} finally {
|
|
3479
|
-
await
|
|
3863
|
+
await releaseUploadResponse(guarded);
|
|
3480
3864
|
}
|
|
3481
3865
|
return { url: assertSafeUploadResultUrl(storageConfig.publicUrlBase ? new URL(fileKey, storageConfig.publicUrlBase).toString() : expectDefined(signedUrl.split("?").at(0), "signed URL base segment"), "Upload result URL") };
|
|
3482
3866
|
}
|
|
@@ -3682,6 +4066,7 @@ async function probeTlonAccount(account) {
|
|
|
3682
4066
|
};
|
|
3683
4067
|
return { ok: true };
|
|
3684
4068
|
} finally {
|
|
4069
|
+
if (!response.bodyUsed) await response.body?.cancel().catch(() => void 0);
|
|
3685
4070
|
await release();
|
|
3686
4071
|
}
|
|
3687
4072
|
} catch (error) {
|