@openclaw/tlon 2026.7.2-beta.5 → 2026.7.33

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.
@@ -1,23 +1,19 @@
1
- import { n as createDedupeCache, o as createLoggerBackedRuntime } from "./runtime-api-BXVe40nS.js";
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
- import { t as getTlonRuntime } from "./runtime-Ck3lNvST.js";
4
- import { t as tlonSetupWizard } from "./setup-surface-1WtsAw4R.js";
1
+ import { n as createDedupeCache, s as createLoggerBackedRuntime } from "./runtime-api-C5wXFh-q.mjs";
2
+ import { c as validateUrbitBaseUrl, d as formatTargetHint, f as normalizeShip, h as resolveTlonOutboundTarget, m as parseTlonTarget, p as parseChannelNest, s as normalizeUrbitHostname, u as resolveTlonAccount } from "./setup-core-C373Z5Vo.mjs";
3
+ import { t as getTlonRuntime } from "./runtime-Ck3lNvST.mjs";
4
+ import { t as tlonSetupWizard } from "./setup-surface-UPZjU2y6.mjs";
5
5
  import { fetchWithSsrFGuard, ssrfPolicyFromDangerouslyAllowPrivateNetwork } from "openclaw/plugin-sdk/ssrf-runtime";
6
- import { bindIngressLifecycleToReplyOptions, createChannelIngressMonitor, createMessageReceiptFromOutboundResults } from "openclaw/plugin-sdk/channel-outbound";
7
- import { expectDefined } from "openclaw/plugin-sdk/expect-runtime";
6
+ import { createMessageReceiptFromOutboundResults } from "openclaw/plugin-sdk/channel-outbound";
8
7
  import { asFiniteNumber, normalizeLowercaseStringOrEmpty, uniqueStrings } from "openclaw/plugin-sdk/string-coerce-runtime";
9
8
  import crypto, { randomBytes, randomUUID } from "node:crypto";
10
- import { readProviderJsonResponse, readResponseTextLimited } from "openclaw/plugin-sdk/provider-http";
11
- import { runChannelProbe, sliceUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
12
- import { resolveHumanDelayConfig } from "openclaw/plugin-sdk/agent-runtime";
13
- import { createChannelInboundEnvelopeBuilder, implicitMentionKindWhen, resolveInboundMentionDecision } from "openclaw/plugin-sdk/channel-inbound";
14
9
  import { sleepWithAbort } from "openclaw/plugin-sdk/runtime-env";
10
+ import { sliceUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
11
+ import { readProviderJsonResponse, readResponseTextLimited } from "openclaw/plugin-sdk/provider-http";
15
12
  import { da, scot } from "@urbit/aura";
16
13
  import { Readable } from "node:stream";
17
14
  import { resolveTimerTimeoutMs } from "openclaw/plugin-sdk/number-runtime";
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";
15
+ import { resolveStableChannelMessageIngress } from "openclaw/plugin-sdk/channel-ingress-runtime";
16
+ import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
21
17
  import { mkdir, writeFile } from "node:fs/promises";
22
18
  import * as path from "node:path";
23
19
  import { extensionForMime } from "openclaw/plugin-sdk/media-mime";
@@ -148,9 +144,7 @@ function applySettingsUpdate(current, key, value) {
148
144
  case "ownerShip":
149
145
  next.ownerShip = typeof value === "string" ? value : void 0;
150
146
  break;
151
- case "pendingApprovals":
152
- next.pendingApprovals = parsePendingApprovals(value);
153
- break;
147
+ case "pendingApprovals": next.pendingApprovals = parsePendingApprovals(value);
154
148
  }
155
149
  return next;
156
150
  }
@@ -273,8 +267,9 @@ var UrbitAuthError = class extends UrbitError {
273
267
  async function urbitFetch(params) {
274
268
  const validated = validateUrbitBaseUrl(params.baseUrl);
275
269
  if (!validated.ok) throw new UrbitUrlError(validated.error);
270
+ const url = new URL(params.path, validated.baseUrl).toString();
276
271
  return await fetchWithSsrFGuard({
277
- url: new URL(params.path, validated.baseUrl).toString(),
272
+ url,
278
273
  fetchImpl: params.fetchImpl,
279
274
  init: params.init,
280
275
  timeoutMs: params.timeoutMs,
@@ -288,7 +283,7 @@ async function urbitFetch(params) {
288
283
  }
289
284
  //#endregion
290
285
  //#region extensions/tlon/src/urbit/auth.ts
291
- const MAX_AUTH_BODY_DRAIN_BYTES = 64 * 1024;
286
+ const MAX_AUTH_BODY_DRAIN_BYTES = 65536;
292
287
  async function authenticate(url, code, options = {}) {
293
288
  const { response, release } = await urbitFetch({
294
289
  baseUrl: url,
@@ -344,11 +339,6 @@ function getUrbitContext(url, ship) {
344
339
  //#endregion
345
340
  //#region extensions/tlon/src/urbit/story.ts
346
341
  /**
347
- * Tlon Story Format - Rich text converter
348
- *
349
- * Converts markdown-like text to Tlon's story format.
350
- */
351
- /**
352
342
  * Parse inline markdown formatting (bold, italic, code, links, mentions)
353
343
  */
354
344
  function parseInlineMarkdown(text) {
@@ -357,41 +347,41 @@ function parseInlineMarkdown(text) {
357
347
  while (remaining.length > 0) {
358
348
  const shipMatch = remaining.match(/^(~[a-z][-a-z0-9]*)/);
359
349
  if (shipMatch) {
360
- result.push({ ship: expectDefined(shipMatch[1], "ship mention capture") });
350
+ result.push({ ship: shipMatch[1] });
361
351
  remaining = remaining.slice(shipMatch[0].length);
362
352
  continue;
363
353
  }
364
354
  const boldMatch = remaining.match(/^\*\*(.+?)\*\*|^__(.+?)__/);
365
355
  if (boldMatch) {
366
- const content = expectDefined(boldMatch[1] ?? boldMatch[2], "bold body capture");
356
+ const content = boldMatch[1] || boldMatch[2];
367
357
  result.push({ bold: parseInlineMarkdown(content) });
368
358
  remaining = remaining.slice(boldMatch[0].length);
369
359
  continue;
370
360
  }
371
361
  const italicsMatch = remaining.match(/^\*([^*]+?)\*|^_([^_]+?)_(?![a-zA-Z0-9])/);
372
362
  if (italicsMatch) {
373
- const content = expectDefined(italicsMatch[1] ?? italicsMatch[2], "italic body capture");
363
+ const content = italicsMatch[1] || italicsMatch[2];
374
364
  result.push({ italics: parseInlineMarkdown(content) });
375
365
  remaining = remaining.slice(italicsMatch[0].length);
376
366
  continue;
377
367
  }
378
368
  const strikeMatch = remaining.match(/^~~(.+?)~~/);
379
369
  if (strikeMatch) {
380
- result.push({ strike: parseInlineMarkdown(expectDefined(strikeMatch[1], "strikethrough body capture")) });
370
+ result.push({ strike: parseInlineMarkdown(strikeMatch[1]) });
381
371
  remaining = remaining.slice(strikeMatch[0].length);
382
372
  continue;
383
373
  }
384
374
  const codeMatch = remaining.match(/^`([^`]+)`/);
385
375
  if (codeMatch) {
386
- result.push({ "inline-code": expectDefined(codeMatch[1], "inline code capture") });
376
+ result.push({ "inline-code": codeMatch[1] });
387
377
  remaining = remaining.slice(codeMatch[0].length);
388
378
  continue;
389
379
  }
390
380
  const linkMatch = remaining.match(/^\[([^\]]+)\]\(([^)]+)\)/);
391
381
  if (linkMatch) {
392
382
  result.push({ link: {
393
- href: expectDefined(linkMatch[2], "link URL capture"),
394
- content: expectDefined(linkMatch[1], "link text capture")
383
+ href: linkMatch[2],
384
+ content: linkMatch[1]
395
385
  } });
396
386
  remaining = remaining.slice(linkMatch[0].length);
397
387
  continue;
@@ -399,53 +389,39 @@ function parseInlineMarkdown(text) {
399
389
  const imageMatch = remaining.match(/^!\[([^\]]*)\]\(([^)]+)\)/);
400
390
  if (imageMatch) {
401
391
  result.push({ __image: {
402
- src: expectDefined(imageMatch[2], "image URL capture"),
403
- alt: expectDefined(imageMatch[1], "image alt capture")
392
+ src: imageMatch[2],
393
+ alt: imageMatch[1]
404
394
  } });
405
395
  remaining = remaining.slice(imageMatch[0].length);
406
396
  continue;
407
397
  }
408
398
  const urlMatch = remaining.match(/^(https?:\/\/[^\s<>"\]]+)/);
409
399
  if (urlMatch) {
410
- const url = expectDefined(urlMatch[1], "plain URL capture");
411
400
  result.push({ link: {
412
- href: url,
413
- content: url
401
+ href: urlMatch[1],
402
+ content: urlMatch[1]
414
403
  } });
415
404
  remaining = remaining.slice(urlMatch[0].length);
416
405
  continue;
417
406
  }
418
407
  const plainMatch = remaining.match(/^[^*_`~[#\n:/]+/);
419
408
  if (plainMatch) {
420
- result.push(expectDefined(plainMatch[0], "plain text match"));
409
+ result.push(plainMatch[0]);
421
410
  remaining = remaining.slice(plainMatch[0].length);
422
411
  continue;
423
412
  }
424
- result.push(remaining.charAt(0));
413
+ result.push(remaining[0]);
425
414
  remaining = remaining.slice(1);
426
415
  }
427
416
  return mergeAdjacentStrings(result);
428
417
  }
429
- function headingTag(marker) {
430
- switch (marker.length) {
431
- case 1: return "h1";
432
- case 2: return "h2";
433
- case 3: return "h3";
434
- case 4: return "h4";
435
- case 5: return "h5";
436
- default: return "h6";
437
- }
438
- }
439
418
  /**
440
419
  * Merge adjacent string elements in an inline array
441
420
  */
442
421
  function mergeAdjacentStrings(inlines) {
443
422
  const result = [];
444
- for (const item of inlines) {
445
- const last = result.at(-1);
446
- if (typeof item === "string" && typeof last === "string") result.splice(-1, 1, last + item);
447
- else result.push(item);
448
- }
423
+ for (const item of inlines) if (typeof item === "string" && typeof result[result.length - 1] === "string") result[result.length - 1] = result[result.length - 1] + item;
424
+ else result.push(item);
449
425
  return result;
450
426
  }
451
427
  /**
@@ -463,12 +439,7 @@ function createImageBlock(src, alt = "", height = 0, width = 0) {
463
439
  * Check if URL looks like an image
464
440
  */
465
441
  function isImageUrl(url) {
466
- const imageExtensions = /\.(jpg|jpeg|png|gif|webp|svg|bmp|ico)$/i;
467
- let path = url.split(/[?#]/, 1)[0] ?? url;
468
- try {
469
- path = new URL(url).pathname;
470
- } catch {}
471
- return imageExtensions.test(path);
442
+ return /\.(jpg|jpeg|png|gif|webp|svg|bmp|ico)(\?.*)?$/i.test(url);
472
443
  }
473
444
  /**
474
445
  * Process inlines and extract any image markers into blocks
@@ -485,158 +456,6 @@ function processInlinesForImages(inlines) {
485
456
  imageBlocks
486
457
  };
487
458
  }
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
- }
640
459
  /**
641
460
  * Convert markdown text to Tlon story format
642
461
  */
@@ -644,19 +463,14 @@ function markdownToStory(markdown) {
644
463
  const story = [];
645
464
  const lines = markdown.split("\n");
646
465
  let i = 0;
647
- let preservedListMarkerKey;
648
466
  while (i < lines.length) {
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;
467
+ const line = lines[i];
652
468
  if (line.startsWith("```")) {
653
469
  const lang = line.slice(3).trim() || "plaintext";
654
470
  const codeLines = [];
655
471
  i++;
656
- while (true) {
657
- const codeLine = lines.at(i);
658
- if (codeLine === void 0 || codeLine.startsWith("```")) break;
659
- codeLines.push(codeLine);
472
+ while (i < lines.length && !lines[i].startsWith("```")) {
473
+ codeLines.push(lines[i]);
660
474
  i++;
661
475
  }
662
476
  story.push({ block: { code: {
@@ -668,10 +482,10 @@ function markdownToStory(markdown) {
668
482
  }
669
483
  const headerMatch = line.match(/^(#{1,6})\s+(.+)$/);
670
484
  if (headerMatch) {
671
- const tag = headingTag(expectDefined(headerMatch[1], "header marker capture"));
485
+ const tag = `h${headerMatch[1].length}`;
672
486
  story.push({ block: { header: {
673
487
  tag,
674
- content: parseInlineMarkdown(expectDefined(headerMatch[2], "header body capture"))
488
+ content: parseInlineMarkdown(headerMatch[2])
675
489
  } } });
676
490
  i++;
677
491
  continue;
@@ -683,10 +497,8 @@ function markdownToStory(markdown) {
683
497
  }
684
498
  if (line.startsWith("> ")) {
685
499
  const quoteLines = [];
686
- while (true) {
687
- const quoteLine = lines.at(i);
688
- if (quoteLine === void 0 || !quoteLine.startsWith("> ")) break;
689
- quoteLines.push(quoteLine.slice(2));
500
+ while (i < lines.length && lines[i].startsWith("> ")) {
501
+ quoteLines.push(lines[i].slice(2));
690
502
  i++;
691
503
  }
692
504
  const quoteText = quoteLines.join("\n");
@@ -697,33 +509,23 @@ function markdownToStory(markdown) {
697
509
  i++;
698
510
  continue;
699
511
  }
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);
710
512
  const paragraphLines = [];
711
- while (true) {
712
- const paragraphLine = lines.at(i);
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
- }
721
- paragraphLines.push(paragraphLine);
513
+ while (i < lines.length && lines[i].trim() !== "" && !lines[i].startsWith("#") && !lines[i].startsWith("```") && !lines[i].startsWith("> ") && !/^(-{3,}|\*{3,})$/.test(lines[i].trim())) {
514
+ paragraphLines.push(lines[i]);
722
515
  i++;
723
516
  }
724
517
  if (paragraphLines.length > 0) {
725
- const { inlines, imageBlocks } = parseInlinesWithBreaks(paragraphLines.join("\n"));
726
- if (inlines.length > 0) story.push({ inline: inlines });
518
+ const inlines = parseInlineMarkdown(paragraphLines.join("\n"));
519
+ const withBreaks = [];
520
+ for (const inline of inlines) if (typeof inline === "string" && inline.includes("\n")) {
521
+ const parts = inline.split("\n");
522
+ for (let j = 0; j < parts.length; j++) {
523
+ if (parts[j]) withBreaks.push(parts[j]);
524
+ if (j < parts.length - 1) withBreaks.push({ break: null });
525
+ }
526
+ } else withBreaks.push(inline);
527
+ const { inlines: cleanInlines, imageBlocks } = processInlinesForImages(withBreaks);
528
+ if (cleanInlines.length > 0) story.push({ inline: cleanInlines });
727
529
  story.push(...imageBlocks);
728
530
  }
729
531
  }
@@ -871,7 +673,7 @@ async function putUrbitChannel(deps, params) {
871
673
  auditContext: params.auditContext
872
674
  });
873
675
  }
874
- const TLON_ERROR_BODY_LIMIT_BYTES = 16 * 1024;
676
+ const TLON_ERROR_BODY_LIMIT_BYTES = 16384;
875
677
  async function pokeUrbitChannel(deps, params) {
876
678
  const pokeId = Date.now();
877
679
  const { response, release } = await putUrbitChannel(deps, {
@@ -888,11 +690,7 @@ async function pokeUrbitChannel(deps, params) {
888
690
  try {
889
691
  if (!response.ok && response.status !== 204) {
890
692
  const errorText = await readResponseTextLimited(response, TLON_ERROR_BODY_LIMIT_BYTES).catch(() => "");
891
- throw new UrbitHttpError({
892
- operation: "Poke",
893
- status: response.status,
894
- bodyText: errorText || void 0
895
- });
693
+ throw new Error(`Poke failed: ${response.status}${errorText ? ` - ${errorText}` : ""}`);
896
694
  }
897
695
  return pokeId;
898
696
  } finally {
@@ -915,10 +713,7 @@ async function scryUrbitPath(deps, params) {
915
713
  auditContext: params.auditContext
916
714
  });
917
715
  try {
918
- if (!response.ok) throw new UrbitHttpError({
919
- operation: `Scry for path ${params.path}`,
920
- status: response.status
921
- });
716
+ if (!response.ok) throw new Error(`Scry failed: ${response.status} for path ${params.path}`);
922
717
  return await readProviderJsonResponse(response, `Tlon scry response for path ${params.path}`);
923
718
  } finally {
924
719
  await release();
@@ -965,7 +760,7 @@ async function ensureUrbitChannelOpen(deps, params) {
965
760
  }
966
761
  //#endregion
967
762
  //#region extensions/tlon/src/urbit/sse-client.ts
968
- const MAX_SSE_PAYLOAD_BYTES = 16 * 1024 * 1024;
763
+ const MAX_SSE_PAYLOAD_BYTES = 16777216;
969
764
  function parseUrbitSsePayload(data) {
970
765
  if (Buffer.byteLength(data, "utf8") > MAX_SSE_PAYLOAD_BYTES) throw new Error("Tlon Urbit SSE payload exceeds 16 MiB limit");
971
766
  try {
@@ -1019,18 +814,6 @@ var UrbitSSEClient = class {
1019
814
  fetchImpl: this.fetchImpl
1020
815
  };
1021
816
  }
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
- }
1034
817
  async subscribe(params) {
1035
818
  const subId = this.subscriptions.length + 1;
1036
819
  const subscription = {
@@ -1060,7 +843,7 @@ var UrbitSSEClient = class {
1060
843
  });
1061
844
  try {
1062
845
  if (!response.ok && response.status !== 204) {
1063
- const errorText = await readResponseTextLimited(response, 16 * 1024).catch(() => "");
846
+ const errorText = await readResponseTextLimited(response, 16384).catch(() => "");
1064
847
  throw new Error(`Subscribe failed: ${response.status}${errorText ? ` - ${errorText}` : ""}`);
1065
848
  }
1066
849
  } finally {
@@ -1068,9 +851,10 @@ var UrbitSSEClient = class {
1068
851
  }
1069
852
  }
1070
853
  async connect() {
1071
- this.lastHeardEventId = -1;
1072
- this.lastAcknowledgedEventId = -1;
1073
- await this.createCurrentChannel();
854
+ await ensureUrbitChannelOpen(this.channelRequestContext(), {
855
+ createBody: this.subscriptions,
856
+ createAuditContext: "tlon-urbit-channel-create"
857
+ });
1074
858
  await this.openStream();
1075
859
  this.isConnected = true;
1076
860
  this.reconnectAttempts = 0;
@@ -1105,10 +889,7 @@ var UrbitSSEClient = class {
1105
889
  if (!response.ok) {
1106
890
  this.streamRelease = null;
1107
891
  await release();
1108
- throw new UrbitHttpError({
1109
- operation: "Stream connection",
1110
- status: response.status
1111
- });
892
+ throw new Error(`Stream connection failed: ${response.status}`);
1112
893
  }
1113
894
  this.processStream(response.body).catch((error) => {
1114
895
  if (!this.aborted) {
@@ -1133,12 +914,12 @@ var UrbitSSEClient = class {
1133
914
  buffer += text;
1134
915
  bufferBytes = nextBytes;
1135
916
  };
1136
- const consumeText = async (text) => {
917
+ const consumeText = (text) => {
1137
918
  let offset = 0;
1138
919
  if (pendingDelimiterNewline && text.length > 0) {
1139
920
  pendingDelimiterNewline = false;
1140
921
  if (text.startsWith("\n")) {
1141
- await this.processEvent(buffer);
922
+ this.processEvent(buffer);
1142
923
  buffer = "";
1143
924
  bufferBytes = 0;
1144
925
  offset = 1;
@@ -1153,7 +934,7 @@ var UrbitSSEClient = class {
1153
934
  return;
1154
935
  }
1155
936
  appendPending(text.slice(offset, eventEnd));
1156
- await this.processEvent(buffer);
937
+ this.processEvent(buffer);
1157
938
  buffer = "";
1158
939
  bufferBytes = 0;
1159
940
  offset = eventEnd + 2;
@@ -1163,11 +944,11 @@ var UrbitSSEClient = class {
1163
944
  for await (const chunk of stream) {
1164
945
  if (this.aborted) break;
1165
946
  if (typeof chunk === "string") {
1166
- await consumeText(decoder.decode());
1167
- await consumeText(chunk);
1168
- } else await consumeText(decoder.decode(chunk, { stream: true }));
947
+ consumeText(decoder.decode());
948
+ consumeText(chunk);
949
+ } else consumeText(decoder.decode(chunk, { stream: true }));
1169
950
  }
1170
- await consumeText(decoder.decode());
951
+ consumeText(decoder.decode());
1171
952
  } finally {
1172
953
  if (this.streamRelease) {
1173
954
  const release = this.streamRelease;
@@ -1182,7 +963,7 @@ var UrbitSSEClient = class {
1182
963
  }
1183
964
  }
1184
965
  }
1185
- async processEvent(eventData) {
966
+ processEvent(eventData) {
1186
967
  const lines = eventData.split("\n");
1187
968
  let data = null;
1188
969
  let eventId = null;
@@ -1191,33 +972,35 @@ var UrbitSSEClient = class {
1191
972
  if (line.startsWith("data: ")) data = line.slice(6);
1192
973
  }
1193
974
  if (!data) return;
1194
- let parsed;
975
+ if (eventId !== null && !Number.isNaN(eventId)) {
976
+ if (eventId > this.lastHeardEventId) {
977
+ this.lastHeardEventId = eventId;
978
+ if (eventId - this.lastAcknowledgedEventId > this.ackThreshold) {
979
+ this.logger.log?.(`[SSE] Acking event ${eventId} (last acked: ${this.lastAcknowledgedEventId})`);
980
+ this.ack(eventId).catch((err) => {
981
+ this.logger.error?.(`Failed to ack event ${eventId}: ${String(err)}`);
982
+ });
983
+ }
984
+ }
985
+ }
1195
986
  try {
1196
- parsed = parseUrbitSsePayload(data);
987
+ const parsed = parseUrbitSsePayload(data);
988
+ if (parsed.response === "quit") {
989
+ if (parsed.id) {
990
+ const handlers = this.eventHandlers.get(parsed.id);
991
+ if (handlers?.quit) handlers.quit();
992
+ }
993
+ return;
994
+ }
995
+ if (parsed.id && this.eventHandlers.has(parsed.id)) {
996
+ const { event } = this.eventHandlers.get(parsed.id) ?? {};
997
+ if (event && parsed.json) event(parsed.json);
998
+ } else if (parsed.json) {
999
+ for (const { event } of this.eventHandlers.values()) if (event) event(parsed.json);
1000
+ }
1197
1001
  } catch (error) {
1198
1002
  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);
1212
1003
  }
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);
1221
1004
  }
1222
1005
  async poke(params) {
1223
1006
  return await pokeUrbitChannel(this.channelRequestContext(), {
@@ -1245,6 +1028,7 @@ var UrbitSSEClient = class {
1245
1028
  this.cookie = normalizeUrbitCookie(newCookie);
1246
1029
  }
1247
1030
  async ack(eventId) {
1031
+ this.lastAcknowledgedEventId = eventId;
1248
1032
  const ackData = {
1249
1033
  id: Date.now(),
1250
1034
  action: "ack",
@@ -1256,7 +1040,6 @@ var UrbitSSEClient = class {
1256
1040
  });
1257
1041
  try {
1258
1042
  if (!response.ok) throw new Error(`Ack failed with status ${response.status}`);
1259
- this.lastAcknowledgedEventId = eventId;
1260
1043
  } finally {
1261
1044
  await release();
1262
1045
  }
@@ -1281,32 +1064,21 @@ var UrbitSSEClient = class {
1281
1064
  await new Promise((resolve) => {
1282
1065
  setTimeout(resolve, delay);
1283
1066
  });
1284
- if (this.aborted || !this.autoReconnect) return;
1285
1067
  try {
1068
+ this.channelId = `${Math.floor(Date.now() / 1e3)}-${randomUUID()}`;
1069
+ this.channelUrl = new URL(`/~/channel/${this.channelId}`, this.url).toString();
1286
1070
  if (this.onReconnect) await this.onReconnect(this);
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;
1071
+ await this.connect();
1297
1072
  this.logger.log?.("[SSE] Reconnection successful!");
1298
1073
  } catch (error) {
1299
1074
  this.logger.error?.(`[SSE] Reconnection failed: ${String(error)}`);
1300
1075
  await this.attemptReconnect();
1301
1076
  }
1302
1077
  }
1303
- stopReceiving() {
1078
+ async close() {
1304
1079
  this.aborted = true;
1305
1080
  this.isConnected = false;
1306
1081
  this.streamController?.abort();
1307
- }
1308
- async close() {
1309
- this.stopReceiving();
1310
1082
  try {
1311
1083
  const unsubscribes = this.subscriptions.map((sub) => ({
1312
1084
  id: sub.id,
@@ -1490,7 +1262,7 @@ function parseAdminCommand(text) {
1490
1262
  const unblockMatch = trimmed.match(/^unblock\s+(~[\w-]+)$/);
1491
1263
  if (unblockMatch) return {
1492
1264
  type: "unblock",
1493
- ship: expectDefined(unblockMatch[1], "unblock ship capture")
1265
+ ship: unblockMatch[1]
1494
1266
  };
1495
1267
  return null;
1496
1268
  }
@@ -1664,7 +1436,7 @@ function createTlonApprovalRuntime(params) {
1664
1436
  const approvals = getPendingApprovals();
1665
1437
  const existingIndex = approvals.findIndex((item) => item.type === approval.type && item.requestingShip === approval.requestingShip && (approval.type !== "channel" || item.channelNest === approval.channelNest) && (approval.type !== "group" || item.groupFlag === approval.groupFlag));
1666
1438
  if (existingIndex !== -1) {
1667
- const existing = expectDefined(approvals[existingIndex], "located pending approval index");
1439
+ const existing = approvals[existingIndex];
1668
1440
  if (approval.originalMessage) {
1669
1441
  existing.originalMessage = approval.originalMessage;
1670
1442
  existing.messagePreview = approval.messagePreview;
@@ -1705,31 +1477,29 @@ function createTlonApprovalRuntime(params) {
1705
1477
  }
1706
1478
  }
1707
1479
  break;
1708
- case "group":
1709
- if (approval.groupFlag) try {
1710
- await api.poke({
1711
- app: "groups",
1712
- mark: "group-join",
1713
- json: {
1714
- flag: approval.groupFlag,
1715
- "join-all": true
1480
+ case "group": if (approval.groupFlag) try {
1481
+ await api.poke({
1482
+ app: "groups",
1483
+ mark: "group-join",
1484
+ json: {
1485
+ flag: approval.groupFlag,
1486
+ "join-all": true
1487
+ }
1488
+ });
1489
+ runtime.log?.(`[tlon] Joined group ${approval.groupFlag} after approval`);
1490
+ setTimeout(() => {
1491
+ (async () => {
1492
+ try {
1493
+ const newCount = await refreshWatchedChannels();
1494
+ if (newCount > 0) runtime.log?.(`[tlon] Discovered ${newCount} new channel(s) after joining group`);
1495
+ } catch (err) {
1496
+ runtime.log?.(`[tlon] Channel discovery after group join failed: ${String(err)}`);
1716
1497
  }
1717
- });
1718
- runtime.log?.(`[tlon] Joined group ${approval.groupFlag} after approval`);
1719
- setTimeout(() => {
1720
- (async () => {
1721
- try {
1722
- const newCount = await refreshWatchedChannels();
1723
- if (newCount > 0) runtime.log?.(`[tlon] Discovered ${newCount} new channel(s) after joining group`);
1724
- } catch (err) {
1725
- runtime.log?.(`[tlon] Channel discovery after group join failed: ${String(err)}`);
1726
- }
1727
- })();
1728
- }, 2e3);
1729
- } catch (err) {
1730
- runtime.error?.(`[tlon] Failed to join group ${approval.groupFlag}: ${String(err)}`);
1731
- }
1732
- break;
1498
+ })();
1499
+ }, 2e3);
1500
+ } catch (err) {
1501
+ runtime.error?.(`[tlon] Failed to join group ${approval.groupFlag}: ${String(err)}`);
1502
+ }
1733
1503
  }
1734
1504
  await sendOwnerNotification(formatApprovalConfirmation(approval, "approve"));
1735
1505
  } else if (parsed.action === "block") {
@@ -1822,8 +1592,8 @@ function extractCites(content) {
1822
1592
  }
1823
1593
  function formatModelName(modelString) {
1824
1594
  if (!modelString) return "AI";
1825
- const modelName = modelString.includes("/") ? expectDefined(modelString.split("/").at(1), "provider/model second segment") : modelString;
1826
- const mappedName = {
1595
+ const modelName = modelString.includes("/") ? modelString.split("/")[1] : modelString;
1596
+ const modelMappings = {
1827
1597
  "claude-opus-4-5": "Claude Opus 4.5",
1828
1598
  "claude-sonnet-4-5": "Claude Sonnet 4.5",
1829
1599
  "claude-sonnet-3-5": "Claude Sonnet 3.5",
@@ -1832,8 +1602,8 @@ function formatModelName(modelString) {
1832
1602
  "gpt-4": "GPT-4",
1833
1603
  "gemini-2.0-flash": "Gemini 2.0 Flash",
1834
1604
  "gemini-pro": "Gemini Pro"
1835
- }[modelName];
1836
- if (mappedName !== void 0) return mappedName;
1605
+ };
1606
+ if (modelMappings[modelName]) return modelMappings[modelName];
1837
1607
  return modelName.replace(/-/g, " ").split(" ").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
1838
1608
  }
1839
1609
  function isBotMentioned(messageText, botShipName, nickname) {
@@ -1894,37 +1664,10 @@ async function resolveTlonCommandAuthorizationWithIngress(params) {
1894
1664
  command: {}
1895
1665
  });
1896
1666
  }
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
- }
1919
1667
  function isGroupInviteAllowed(inviterShip, allowlist) {
1668
+ if (!allowlist || allowlist.length === 0) return false;
1920
1669
  const normalizedInviter = normalizeShip(inviterShip);
1921
- return resolveAllowlistMatchByCandidates({
1922
- allowList: (allowlist ?? []).map((ship) => normalizeShip(ship)),
1923
- candidates: [{
1924
- value: normalizedInviter,
1925
- source: "ship"
1926
- }]
1927
- }).allowed;
1670
+ return allowlist.map((ship) => normalizeShip(ship)).some((ship) => ship === normalizedInviter);
1928
1671
  }
1929
1672
  async function resolveAuthorizedMessageText(params) {
1930
1673
  const { rawText, content, authorizedForCites, resolveAllCites } = params;
@@ -2045,7 +1788,8 @@ function createTlonCitationResolver(params) {
2045
1788
  try {
2046
1789
  const scryPath = `/channels/v4/${cite.nest}/posts/post/${cite.postId}.json`;
2047
1790
  runtime.log?.(`[tlon] Fetching cited post: ${scryPath}`);
2048
- const essay = asRecord(asRecord(await api.scry(scryPath))?.essay);
1791
+ const data = asRecord(await api.scry(scryPath));
1792
+ const essay = asRecord(data?.essay);
2049
1793
  if (essay?.content) return extractMessageText(essay.content) || null;
2050
1794
  return null;
2051
1795
  } catch (err) {
@@ -2081,7 +1825,8 @@ async function fetchInitData(api, runtime) {
2081
1825
  const channels = [];
2082
1826
  const groups = asRecord(initData?.groups);
2083
1827
  if (groups) for (const groupData of Object.values(groups)) {
2084
- const groupChannels = asRecord(asRecord(groupData)?.channels);
1828
+ const typedGroupData = asRecord(groupData);
1829
+ const groupChannels = asRecord(typedGroupData?.channels);
2085
1830
  if (groupChannels) {
2086
1831
  for (const channelNest of Object.keys(groupChannels)) if (channelNest.startsWith("chat/")) channels.push(channelNest);
2087
1832
  }
@@ -2156,7 +1901,8 @@ async function fetchChannelHistory(api, channelNest, count = 50, runtime) {
2156
1901
  }
2157
1902
  const messages = posts.map((item) => {
2158
1903
  const itemRecord = asRecord(item);
2159
- const replyPostSet = asRecord(asRecord(itemRecord?.["r-post"])?.set);
1904
+ const replyPost = asRecord(itemRecord?.["r-post"]);
1905
+ const replyPostSet = asRecord(replyPost?.set);
2160
1906
  const essay = asRecord(itemRecord?.essay) ?? asRecord(replyPostSet?.essay);
2161
1907
  const seal = asRecord(itemRecord?.seal) ?? asRecord(replyPostSet?.seal);
2162
1908
  return {
@@ -2208,7 +1954,8 @@ async function fetchThreadHistory(api, channelNest, parentId, count = 50, runtim
2208
1954
  }
2209
1955
  const messages = replies.map((item) => {
2210
1956
  const itemRecord = asRecord(item);
2211
- const replySet = asRecord(asRecord(itemRecord?.["r-reply"])?.set);
1957
+ const replyRecord = asRecord(itemRecord?.["r-reply"]);
1958
+ const replySet = asRecord(replyRecord?.set);
2212
1959
  return createHistoryEntryFromMemo({
2213
1960
  memo: asRecord(itemRecord?.memo) ?? asRecord(replySet?.memo) ?? itemRecord,
2214
1961
  seal: asRecord(itemRecord?.seal) ?? asRecord(replySet?.seal),
@@ -2223,7 +1970,8 @@ async function fetchThreadHistory(api, channelNest, parentId, count = 50, runtim
2223
1970
  const altPath = `/channels/v4/${channelNest}/posts/post/id/${formatUd(parentId)}.json`;
2224
1971
  runtime?.log?.(`[tlon] Trying alternate path: ${altPath}`);
2225
1972
  const data = asRecord(await api.scry(altPath));
2226
- const dataMeta = asRecord(asRecord(data?.seal)?.meta);
1973
+ const dataSeal = asRecord(data?.seal);
1974
+ const dataMeta = asRecord(dataSeal?.meta);
2227
1975
  const repliesValue = data?.replies;
2228
1976
  if (typeof dataMeta?.replyCount === "number" && dataMeta.replyCount > 0 && repliesValue) {
2229
1977
  const messages = (Array.isArray(repliesValue) ? repliesValue : Object.values(repliesValue)).map((reply) => {
@@ -2243,149 +1991,6 @@ async function fetchThreadHistory(api, channelNest, parentId, count = 50, runtim
2243
1991
  }
2244
1992
  }
2245
1993
  //#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
2389
1994
  //#region extensions/tlon/src/media-fetch-timeouts.ts
2390
1995
  const TLON_MEDIA_FETCH_TIMEOUTS = {
2391
1996
  responseHeaderTimeoutMs: 12e4,
@@ -2394,18 +1999,6 @@ const TLON_MEDIA_FETCH_TIMEOUTS = {
2394
1999
  //#endregion
2395
2000
  //#region extensions/tlon/src/monitor/media.ts
2396
2001
  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
- }
2409
2002
  /**
2410
2003
  * Extract image blocks from Tlon message content.
2411
2004
  * Returns array of image URLs found in the message.
@@ -2496,6 +2089,66 @@ async function downloadMessageImages(content, mediaDir) {
2496
2089
  return attachments;
2497
2090
  }
2498
2091
  //#endregion
2092
+ //#region extensions/tlon/src/monitor/processed-messages.ts
2093
+ function createProcessedMessageTracker(limit = 2e3) {
2094
+ const dedupe = createDedupeCache({
2095
+ ttlMs: 0,
2096
+ maxSize: limit
2097
+ });
2098
+ const inFlight = /* @__PURE__ */ new Set();
2099
+ const claim = (id) => {
2100
+ const trimmed = id?.trim();
2101
+ if (!trimmed) return { kind: "claimed" };
2102
+ if (inFlight.has(trimmed) || dedupe.peek(trimmed)) return { kind: "duplicate" };
2103
+ inFlight.add(trimmed);
2104
+ return { kind: "claimed" };
2105
+ };
2106
+ const commit = (id) => {
2107
+ const trimmed = id?.trim();
2108
+ if (!trimmed) return;
2109
+ inFlight.delete(trimmed);
2110
+ dedupe.check(trimmed);
2111
+ };
2112
+ const release = (id) => {
2113
+ const trimmed = id?.trim();
2114
+ if (!trimmed) return;
2115
+ inFlight.delete(trimmed);
2116
+ };
2117
+ const mark = (id) => {
2118
+ if (claim(id).kind === "duplicate") return false;
2119
+ commit(id);
2120
+ return true;
2121
+ };
2122
+ const has = (id) => {
2123
+ const trimmed = id?.trim();
2124
+ if (!trimmed) return false;
2125
+ return dedupe.peek(trimmed);
2126
+ };
2127
+ return {
2128
+ claim,
2129
+ commit,
2130
+ release,
2131
+ mark,
2132
+ has,
2133
+ size: () => dedupe.size()
2134
+ };
2135
+ }
2136
+ async function runWithProcessedMessageClaim(params) {
2137
+ const claim = params.tracker.claim(params.id);
2138
+ if (claim.kind === "duplicate") return claim;
2139
+ try {
2140
+ const value = await params.task();
2141
+ params.tracker.commit(params.id);
2142
+ return {
2143
+ kind: "processed",
2144
+ value
2145
+ };
2146
+ } catch (error) {
2147
+ params.tracker.release(params.id);
2148
+ throw error;
2149
+ }
2150
+ }
2151
+ //#endregion
2499
2152
  //#region extensions/tlon/src/monitor/settings-helpers.ts
2500
2153
  function buildTlonSettingsMigrations(account, currentSettings) {
2501
2154
  return [
@@ -2599,37 +2252,6 @@ function mergeUniqueStrings(base, next) {
2599
2252
  return uniqueStrings([...base, ...next ?? []]);
2600
2253
  }
2601
2254
  //#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
2633
2255
  //#region extensions/tlon/src/monitor/index.ts
2634
2256
  function readNumber(record, key) {
2635
2257
  return asFiniteNumber(record?.[key]);
@@ -2680,6 +2302,7 @@ async function monitorTlonProvider(opts = {}) {
2680
2302
  runtime.log?.("[tlon] Re-authentication successful");
2681
2303
  }
2682
2304
  });
2305
+ const processedTracker = createProcessedMessageTracker(2e3);
2683
2306
  let groupChannels = [];
2684
2307
  let botNickname = null;
2685
2308
  const settingsManager = createSettingsManager(api, {
@@ -2695,7 +2318,7 @@ async function monitorTlonProvider(opts = {}) {
2695
2318
  let effectiveOwnerShip = account.ownerShip ? normalizeShip(account.ownerShip) : null;
2696
2319
  let pendingApprovals = [];
2697
2320
  let currentSettings = {};
2698
- const participatedThreads = createParticipatedThreadTracker();
2321
+ const participatedThreads = /* @__PURE__ */ new Set();
2699
2322
  const dmSendersBySession = /* @__PURE__ */ new Map();
2700
2323
  let sharedSessionWarningSent = false;
2701
2324
  try {
@@ -2761,11 +2384,12 @@ async function monitorTlonProvider(opts = {}) {
2761
2384
  * Returns empty string if whom doesn't contain a valid patp-like value.
2762
2385
  */
2763
2386
  function extractDmPartnerShip(whom) {
2764
- const normalized = normalizeShip(typeof whom === "string" ? whom : whom && typeof whom === "object" && "ship" in whom && typeof whom.ship === "string" ? whom.ship : "");
2387
+ const raw = typeof whom === "string" ? whom : whom && typeof whom === "object" && "ship" in whom && typeof whom.ship === "string" ? whom.ship : "";
2388
+ const normalized = normalizeShip(raw);
2765
2389
  return /^~?[a-z-]+$/i.test(normalized) ? normalized : "";
2766
2390
  }
2767
2391
  const processMessage = async (params) => {
2768
- const { messageId, senderShip, isGroup, channelNest, hostShip: _hostShip, channelName: _channelName, timestamp, parentId, isThreadReply, messageContent, turnAdoptionLifecycle } = params;
2392
+ const { messageId, senderShip, isGroup, channelNest, hostShip: _hostShip, channelName: _channelName, timestamp, parentId, isThreadReply, messageContent } = params;
2769
2393
  const groupChannel = channelNest;
2770
2394
  let messageText = params.messageText;
2771
2395
  let attachments = [];
@@ -2863,22 +2487,21 @@ async function monitorTlonProvider(opts = {}) {
2863
2487
  const shouldComputeAuth = core.channel.commands.shouldComputeCommandAuthorized(messageText, cfg);
2864
2488
  let commandAuthorized = false;
2865
2489
  if (shouldComputeAuth) {
2490
+ const useAccessGroups = cfg.commands?.useAccessGroups !== false;
2866
2491
  commandAuthorized = (await resolveTlonCommandAuthorizationWithIngress({
2867
2492
  senderShip,
2868
2493
  ownerShip: effectiveOwnerShip,
2869
- useAccessGroups: true
2494
+ useAccessGroups
2870
2495
  })).commandAccess.authorized;
2871
2496
  if (!commandAuthorized) console.log(`[tlon] Command attempt denied: ${senderShip} is not owner (owner=${effectiveOwnerShip ?? "not configured"})`);
2872
2497
  }
2873
- const promptMedia = buildTlonInboundMediaPrompt(messageText, attachments);
2874
- const body = createChannelInboundEnvelopeBuilder({
2875
- cfg,
2876
- route
2877
- })({
2498
+ let bodyWithAttachments = messageText;
2499
+ if (attachments.length > 0) bodyWithAttachments = attachments.map((a) => `[media attached: ${a.path} (${a.contentType}) | ${a.path}]`).join("\n") + "\n" + messageText;
2500
+ const body = core.channel.reply.formatAgentEnvelope({
2878
2501
  channel: "Tlon",
2879
2502
  from: fromLabel,
2880
2503
  timestamp,
2881
- body: promptMedia.body
2504
+ body: bodyWithAttachments
2882
2505
  });
2883
2506
  const commandBody = isGroup ? stripBotMention(messageText, botShipName) : messageText;
2884
2507
  const tlonConversationId = isGroup ? groupChannel ?? channelNest ?? senderShip : senderShip;
@@ -2900,7 +2523,6 @@ async function monitorTlonProvider(opts = {}) {
2900
2523
  },
2901
2524
  route: {
2902
2525
  agentId: route.agentId,
2903
- dmScope: route.dmScope,
2904
2526
  accountId: route.accountId,
2905
2527
  routeSessionKey: route.sessionKey
2906
2528
  },
@@ -2926,7 +2548,8 @@ async function monitorTlonProvider(opts = {}) {
2926
2548
  });
2927
2549
  const dispatchStartTime = Date.now();
2928
2550
  const responsePrefix = core.channel.reply.resolveEffectiveMessagesConfig(cfg, route.agentId).responsePrefix;
2929
- const humanDelay = resolveHumanDelayConfig(cfg, route.agentId);
2551
+ const humanDelay = core.channel.reply.resolveHumanDelayConfig(cfg, route.agentId);
2552
+ const storePath = core.channel.session.resolveStorePath(cfg.session?.store, { agentId: route.agentId });
2930
2553
  const deliveryTarget = isGroup ? groupChannel : senderShip;
2931
2554
  const prepareReplyPayload = (payload) => {
2932
2555
  const replyText = payload.text;
@@ -2945,20 +2568,16 @@ async function monitorTlonProvider(opts = {}) {
2945
2568
  participatedThreads.add(parentId);
2946
2569
  runtime.log?.(`[tlon] Now tracking thread for future replies: ${parentId}`);
2947
2570
  };
2948
- const replyOptions = {
2949
- ...turnAdoptionLifecycle ? bindIngressLifecycleToReplyOptions(turnAdoptionLifecycle) : {},
2950
- ...promptMedia.media.length > 0 ? { media: promptMedia.media } : {}
2951
- };
2952
- await core.channel.inbound.dispatch({
2571
+ await core.channel.inbound.dispatchReply({
2953
2572
  channel: "tlon",
2954
2573
  accountId: route.accountId,
2955
2574
  cfg,
2956
- route: {
2957
- agentId: route.agentId,
2958
- dmScope: route.dmScope,
2959
- sessionKey: route.sessionKey
2960
- },
2575
+ agentId: route.agentId,
2576
+ routeSessionKey: route.sessionKey,
2577
+ storePath,
2961
2578
  ctxPayload,
2579
+ recordInboundSession: core.channel.session.recordInboundSession,
2580
+ dispatchReplyWithBufferedBlockDispatcher: core.channel.reply.dispatchReplyWithBufferedBlockDispatcher,
2962
2581
  delivery: {
2963
2582
  preparePayload: prepareReplyPayload,
2964
2583
  durable: deliveryTarget ? () => ({
@@ -3005,7 +2624,6 @@ async function monitorTlonProvider(opts = {}) {
3005
2624
  responsePrefix,
3006
2625
  humanDelay
3007
2626
  },
3008
- ...turnAdoptionLifecycle || promptMedia.media.length > 0 ? { replyOptions } : {},
3009
2627
  record: { onRecordError: (err) => {
3010
2628
  runtime.error?.(`[tlon] failed updating session meta: ${String(err)}`);
3011
2629
  } }
@@ -3077,7 +2695,7 @@ async function monitorTlonProvider(opts = {}) {
3077
2695
  },
3078
2696
  refreshWatchedChannels
3079
2697
  });
3080
- const handleChannelsFirehose = async (event, turnAdoptionLifecycle) => {
2698
+ const handleChannelsFirehose = async (event) => {
3081
2699
  try {
3082
2700
  const eventRecord = asRecord(event);
3083
2701
  const nest = readString(eventRecord, "nest");
@@ -3089,7 +2707,8 @@ async function monitorTlonProvider(opts = {}) {
3089
2707
  const rPost = asRecord(post?.["r-post"]);
3090
2708
  const set = asRecord(rPost?.set);
3091
2709
  const reply = asRecord(rPost?.reply);
3092
- const replySet = asRecord(asRecord(reply?.["r-reply"])?.set);
2710
+ const replyPayload = asRecord(reply?.["r-reply"]);
2711
+ const replySet = asRecord(replyPayload?.set);
3093
2712
  const essay = asRecord(set?.essay);
3094
2713
  const memo = asRecord(replySet?.memo);
3095
2714
  if (!essay && !memo) return;
@@ -3098,89 +2717,87 @@ async function monitorTlonProvider(opts = {}) {
3098
2717
  const isThreadReply = Boolean(memo);
3099
2718
  const messageId = isThreadReply ? readString(reply, "id") : readString(post, "id");
3100
2719
  if (!messageId) return;
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;
2720
+ await runWithProcessedMessageClaim({
2721
+ tracker: processedTracker,
2722
+ id: messageId,
2723
+ task: async () => {
2724
+ const senderShip = normalizeShip(readString(content, "author") ?? "");
2725
+ if (!senderShip || senderShip === botShipName) return;
2726
+ const rawText = extractMessageText(content.content);
2727
+ if (!rawText.trim()) return;
2728
+ const contentBody = content.content;
2729
+ const sentAt = readNumber(content, "sent") ?? Date.now();
2730
+ cacheMessage(nest, {
2731
+ author: senderShip,
2732
+ content: rawText,
2733
+ timestamp: sentAt,
2734
+ id: messageId
2735
+ });
2736
+ const seal = isThreadReply ? asRecord(replySet?.seal) : asRecord(set?.seal);
2737
+ const parentId = readString(seal, "parent-id") ?? readString(seal, "parent") ?? null;
2738
+ const mentioned = isBotMentioned(rawText, botShipName, botNickname ?? void 0);
2739
+ const inParticipatedThread = isThreadReply && parentId && participatedThreads.has(parentId);
2740
+ if (!mentioned && !inParticipatedThread) return;
2741
+ if (inParticipatedThread && !mentioned) runtime.log?.(`[tlon] Responding to thread we participated in (no mention): ${parentId}`);
2742
+ if (isOwner(senderShip)) runtime.log?.(`[tlon] Owner ${senderShip} is always allowed in channels`);
2743
+ else {
2744
+ const { mode, allowedShips } = resolveChannelAuthorization(cfg, nest, currentSettings);
2745
+ if (mode === "restricted") {
2746
+ if (!allowedShips.map(normalizeShip).includes(senderShip)) {
2747
+ if (effectiveOwnerShip) {
2748
+ const approval = createPendingApproval({
2749
+ type: "channel",
2750
+ requestingShip: senderShip,
2751
+ channelNest: nest,
2752
+ messagePreview: sliceUtf16Safe(rawText, 0, 100),
2753
+ originalMessage: {
2754
+ messageId: messageId ?? "",
2755
+ messageText: rawText,
2756
+ messageContent: contentBody,
2757
+ timestamp: sentAt,
2758
+ parentId: parentId ?? void 0,
2759
+ isThreadReply
2760
+ }
2761
+ });
2762
+ await queueApprovalRequest(approval);
2763
+ } else runtime.log?.(`[tlon] Access denied: ${senderShip} in ${nest} (allowed: ${allowedShips.join(", ")})`);
2764
+ return;
2765
+ }
2766
+ }
3148
2767
  }
2768
+ const messageText = await resolveAuthorizedMessageText({
2769
+ rawText,
2770
+ content: contentBody,
2771
+ authorizedForCites: true,
2772
+ resolveAllCites
2773
+ });
2774
+ const parsed = parseChannelNest(nest);
2775
+ await processMessage({
2776
+ messageId: messageId ?? "",
2777
+ senderShip,
2778
+ messageText,
2779
+ messageContent: contentBody,
2780
+ isGroup: true,
2781
+ channelNest: nest,
2782
+ hostShip: parsed?.hostShip,
2783
+ channelName: parsed?.channelName,
2784
+ timestamp: sentAt,
2785
+ parentId,
2786
+ isThreadReply
2787
+ });
3149
2788
  }
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
3171
2789
  });
3172
2790
  } catch (error) {
3173
2791
  runtime.error?.(`[tlon] Error handling channel firehose event: ${formatErrorMessage$1(error)}`);
3174
- throw error;
3175
2792
  }
3176
2793
  };
3177
- const processedDmInvites = createActiveSnapshotTracker();
3178
- const handleChatFirehose = async (event, turnAdoptionLifecycle) => {
2794
+ const processedDmInvites = /* @__PURE__ */ new Set();
2795
+ const handleChatFirehose = async (event) => {
3179
2796
  try {
3180
2797
  if (Array.isArray(event)) {
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;
2798
+ for (const invite of event) {
2799
+ const ship = normalizeShip(invite.ship || "");
2800
+ if (!ship || processedDmInvites.has(ship)) continue;
3184
2801
  if (isOwner(ship)) {
3185
2802
  try {
3186
2803
  await api.poke({
@@ -3198,8 +2815,7 @@ async function monitorTlonProvider(opts = {}) {
3198
2815
  }
3199
2816
  continue;
3200
2817
  }
3201
- const allowed = await isDmAllowedWithIngress(ship, effectiveDmAllowlist);
3202
- if (effectiveAutoAcceptDmInvites && allowed) {
2818
+ if (effectiveAutoAcceptDmInvites && await isDmAllowedWithIngress(ship, effectiveDmAllowlist)) {
3203
2819
  try {
3204
2820
  await api.poke({
3205
2821
  app: "chat",
@@ -3216,7 +2832,7 @@ async function monitorTlonProvider(opts = {}) {
3216
2832
  }
3217
2833
  continue;
3218
2834
  }
3219
- if (effectiveOwnerShip && !allowed) {
2835
+ if (effectiveOwnerShip && !await isDmAllowedWithIngress(ship, effectiveDmAllowlist)) {
3220
2836
  const approval = createPendingApproval({
3221
2837
  type: "dm",
3222
2838
  requestingShip: ship,
@@ -3236,104 +2852,92 @@ async function monitorTlonProvider(opts = {}) {
3236
2852
  if (!messageId || !response) return;
3237
2853
  const essay = asRecord(asRecord(response.add)?.essay);
3238
2854
  if (!essay) return;
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: {
2855
+ await runWithProcessedMessageClaim({
2856
+ tracker: processedTracker,
2857
+ id: messageId,
2858
+ task: async () => {
2859
+ const authorShip = normalizeShip(readString(essay, "author") ?? "");
2860
+ const partnerShip = extractDmPartnerShip(whom);
2861
+ const senderShip = partnerShip || authorShip;
2862
+ if (authorShip === botShipName) return;
2863
+ if (!senderShip || senderShip === botShipName) return;
2864
+ if (authorShip && partnerShip && authorShip !== partnerShip) runtime.log?.(`[tlon] DM ship mismatch (author=${authorShip}, partner=${partnerShip}) - routing to partner`);
2865
+ const rawText = extractMessageText(essay.content);
2866
+ if (!rawText.trim()) return;
2867
+ const messageText = rawText;
2868
+ if (isOwner(senderShip) && isApprovalResponse(messageText)) {
2869
+ if (await handleApprovalResponse(messageText)) {
2870
+ runtime.log?.(`[tlon] Processed approval response from owner: ${messageText}`);
2871
+ return;
2872
+ }
2873
+ }
2874
+ if (isOwner(senderShip) && isAdminCommand(messageText)) {
2875
+ if (await handleAdminCommand(messageText)) {
2876
+ runtime.log?.(`[tlon] Processed admin command from owner: ${messageText}`);
2877
+ return;
2878
+ }
2879
+ }
2880
+ if (isOwner(senderShip)) {
2881
+ const resolvedMessageText = await resolveAuthorizedMessageText({
2882
+ rawText,
2883
+ content: essay.content,
2884
+ authorizedForCites: true,
2885
+ resolveAllCites
2886
+ });
2887
+ runtime.log?.(`[tlon] Processing DM from owner ${senderShip}`);
2888
+ await processMessage({
3286
2889
  messageId: messageId ?? "",
3287
- messageText,
2890
+ senderShip,
2891
+ messageText: resolvedMessageText,
3288
2892
  messageContent: essay.content,
2893
+ isGroup: false,
3289
2894
  timestamp: readNumber(essay, "sent") ?? Date.now()
3290
- }
2895
+ });
2896
+ return;
2897
+ }
2898
+ if (!await isDmAllowedWithIngress(senderShip, effectiveDmAllowlist)) {
2899
+ if (effectiveOwnerShip) {
2900
+ const approval = createPendingApproval({
2901
+ type: "dm",
2902
+ requestingShip: senderShip,
2903
+ messagePreview: sliceUtf16Safe(messageText, 0, 100),
2904
+ originalMessage: {
2905
+ messageId: messageId ?? "",
2906
+ messageText,
2907
+ messageContent: essay.content,
2908
+ timestamp: readNumber(essay, "sent") ?? Date.now()
2909
+ }
2910
+ });
2911
+ await queueApprovalRequest(approval);
2912
+ } else runtime.log?.(`[tlon] Blocked DM from ${senderShip}: not in allowlist`);
2913
+ return;
2914
+ }
2915
+ await processMessage({
2916
+ messageText: await resolveAuthorizedMessageText({
2917
+ rawText,
2918
+ content: essay.content,
2919
+ authorizedForCites: true,
2920
+ resolveAllCites
2921
+ }),
2922
+ messageId: messageId ?? "",
2923
+ senderShip,
2924
+ messageContent: essay.content,
2925
+ isGroup: false,
2926
+ timestamp: readNumber(essay, "sent") ?? Date.now()
3291
2927
  });
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
2928
+ }
3309
2929
  });
3310
2930
  } catch (error) {
3311
2931
  runtime.error?.(`[tlon] Error handling chat firehose event: ${formatErrorMessage$1(error)}`);
3312
- throw error;
3313
2932
  }
3314
2933
  };
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
- });
3327
2934
  try {
3328
2935
  runtime.log?.("[tlon] Subscribing to firehose updates...");
3329
2936
  await api.subscribe({
3330
2937
  app: "channels",
3331
2938
  path: "/v2",
3332
- event: async (event) => {
3333
- if ((await ingress.receive({
3334
- source: "channels",
3335
- event
3336
- })).kind === "ignored") await handleChannelsFirehose(event);
2939
+ event: (event) => {
2940
+ handleChannelsFirehose(event);
3337
2941
  },
3338
2942
  err: (error) => {
3339
2943
  runtime.error?.(`[tlon] Channels firehose error: ${String(error)}`);
@@ -3346,11 +2950,8 @@ async function monitorTlonProvider(opts = {}) {
3346
2950
  await api.subscribe({
3347
2951
  app: "chat",
3348
2952
  path: "/v3",
3349
- event: async (event) => {
3350
- if ((await ingress.receive({
3351
- source: "chat",
3352
- event
3353
- })).kind === "ignored") await handleChatFirehose(event);
2953
+ event: (event) => {
2954
+ handleChatFirehose(event);
3354
2955
  },
3355
2956
  err: (error) => {
3356
2957
  runtime.error?.(`[tlon] Chat firehose error: ${String(error)}`);
@@ -3367,7 +2968,9 @@ async function monitorTlonProvider(opts = {}) {
3367
2968
  try {
3368
2969
  const eventRecord = asRecord(event);
3369
2970
  if (eventRecord?.self) {
3370
- const nickname = asRecord(asRecord(asRecord(eventRecord.self)?.contact)?.nickname);
2971
+ const selfUpdate = asRecord(eventRecord.self);
2972
+ const contact = asRecord(selfUpdate?.contact);
2973
+ const nickname = asRecord(contact?.nickname);
3371
2974
  if (nickname && "value" in nickname) {
3372
2975
  const newNickname = readString(nickname, "value") ?? null;
3373
2976
  if (newNickname !== botNickname) {
@@ -3596,7 +3199,6 @@ async function monitorTlonProvider(opts = {}) {
3596
3199
  for (const channelNest of watchedChannels) runtime.log?.(`[tlon] Watching channel: ${channelNest}`);
3597
3200
  runtime.log?.("[tlon] All subscriptions registered, connecting to SSE stream...");
3598
3201
  await api.connect();
3599
- ingress.start();
3600
3202
  runtime.log?.("[tlon] Connected! Firehose subscriptions active");
3601
3203
  const pollInterval = setInterval(() => {
3602
3204
  (async () => {
@@ -3612,7 +3214,7 @@ async function monitorTlonProvider(opts = {}) {
3612
3214
  runtime.error?.(`[tlon] Channel refresh error: ${formatErrorMessage$1(error)}`);
3613
3215
  }
3614
3216
  })();
3615
- }, 120 * 1e3);
3217
+ }, 12e4);
3616
3218
  if (opts.abortSignal) {
3617
3219
  const signal = opts.abortSignal;
3618
3220
  await new Promise((resolve) => {
@@ -3623,8 +3225,6 @@ async function monitorTlonProvider(opts = {}) {
3623
3225
  });
3624
3226
  } else await new Promise(() => {});
3625
3227
  } finally {
3626
- api?.stopReceiving();
3627
- await ingress.stop();
3628
3228
  try {
3629
3229
  await api?.close();
3630
3230
  } catch (error) {
@@ -3636,20 +3236,8 @@ async function monitorTlonProvider(opts = {}) {
3636
3236
  //#region extensions/tlon/src/tlon-api.ts
3637
3237
  const MEMEX_BASE_URL = "https://memex.tlon.network";
3638
3238
  /** Max bytes to read from the Memex upload JSON response. */
3639
- const MEMEX_UPLOAD_RESPONSE_MAX_BYTES = 64 * 1024;
3640
- /** Total deadline for the Memex upload URL lookup, including DNS and response reading. */
3641
- const TLON_MEMEX_UPLOAD_URL_TIMEOUT_MS = 3e4;
3642
- /** Total deadline for Memex and custom S3 PUTs, including DNS and the full upload. */
3643
- const TLON_UPLOAD_TIMEOUT_MS = 3e5;
3239
+ const MEMEX_UPLOAD_RESPONSE_MAX_BYTES = 65536;
3644
3240
  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
- }
3653
3241
  function configureClient(params) {
3654
3242
  currentClientConfig = {
3655
3243
  ...params,
@@ -3749,9 +3337,9 @@ async function getMemexUploadUrl(params) {
3749
3337
  const resolvedToken = typeof token === "string" ? token : token.secret;
3750
3338
  if (!resolvedToken) throw new Error("Missing genuine secret");
3751
3339
  const endpoint = `${MEMEX_BASE_URL}/v1/${params.config.shipName}/upload`;
3752
- let guarded;
3340
+ let release;
3753
3341
  try {
3754
- guarded = await fetchWithSsrFGuard({
3342
+ const guarded = await fetchWithSsrFGuard({
3755
3343
  url: endpoint,
3756
3344
  init: {
3757
3345
  method: "PUT",
@@ -3765,9 +3353,9 @@ async function getMemexUploadUrl(params) {
3765
3353
  },
3766
3354
  auditContext: "tlon-memex-upload-url",
3767
3355
  capture: false,
3768
- maxRedirects: 0,
3769
- timeoutMs: TLON_MEMEX_UPLOAD_URL_TIMEOUT_MS
3356
+ maxRedirects: 0
3770
3357
  });
3358
+ release = guarded.release;
3771
3359
  if (!guarded.response.ok) throw new Error(`Memex upload request failed: ${guarded.response.status}`);
3772
3360
  const data = await readProviderJsonResponse(guarded.response, "Memex upload", { maxBytes: MEMEX_UPLOAD_RESPONSE_MAX_BYTES });
3773
3361
  if (!data?.url || !data.filePath) throw new Error("Invalid response from Memex");
@@ -3776,7 +3364,7 @@ async function getMemexUploadUrl(params) {
3776
3364
  uploadUrl: data.url
3777
3365
  };
3778
3366
  } finally {
3779
- await releaseUploadResponse(guarded);
3367
+ await release?.();
3780
3368
  }
3781
3369
  }
3782
3370
  async function uploadFile(params) {
@@ -3797,9 +3385,9 @@ async function uploadFile(params) {
3797
3385
  fileName: fileKey
3798
3386
  });
3799
3387
  const trustedUploadUrl = assertTrustedMemexUploadUrl(uploadUrl, "Memex upload URL");
3800
- let guarded;
3388
+ let release;
3801
3389
  try {
3802
- guarded = await fetchWithSsrFGuard({
3390
+ const guarded = await fetchWithSsrFGuard({
3803
3391
  url: trustedUploadUrl,
3804
3392
  init: {
3805
3393
  method: "PUT",
@@ -3811,19 +3399,24 @@ async function uploadFile(params) {
3811
3399
  },
3812
3400
  auditContext: "tlon-memex-upload",
3813
3401
  capture: false,
3814
- maxRedirects: 0,
3815
- timeoutMs: TLON_UPLOAD_TIMEOUT_MS
3402
+ maxRedirects: 0
3816
3403
  });
3404
+ release = guarded.release;
3817
3405
  assertTrustedMemexUploadUrl(guarded.finalUrl, "Memex final upload URL");
3818
3406
  if (!guarded.response.ok) throw new Error(`Upload failed: ${guarded.response.status}`);
3819
3407
  } finally {
3820
- await releaseUploadResponse(guarded);
3408
+ await release?.();
3821
3409
  }
3822
3410
  return { url: assertTrustedMemexUploadUrl(hostedUrl, "Memex hosted URL") };
3823
3411
  }
3824
3412
  if (!hasCustomS3Creds(credentials)) throw new Error("No storage credentials configured");
3413
+ const endpoint = new URL(prefixEndpoint(credentials.endpoint));
3825
3414
  const client = new S3Client({
3826
- endpoint: prefixEndpoint(credentials.endpoint),
3415
+ endpoint: {
3416
+ protocol: endpoint.protocol.slice(0, -1),
3417
+ hostname: endpoint.host,
3418
+ path: endpoint.pathname || "/"
3419
+ },
3827
3420
  region: storageConfig.region || "us-east-1",
3828
3421
  credentials: {
3829
3422
  accessKeyId: credentials.accessKeyId,
@@ -3836,16 +3429,20 @@ async function uploadFile(params) {
3836
3429
  "Content-Type": contentType,
3837
3430
  "x-amz-acl": "public-read"
3838
3431
  };
3839
- const signedUrl = await getSignedUrl(client, new PutObjectCommand({
3432
+ const command = new PutObjectCommand({
3840
3433
  Bucket: storageConfig.currentBucket,
3841
3434
  Key: fileKey,
3842
3435
  ContentType: headers["Content-Type"],
3843
3436
  CacheControl: headers["Cache-Control"],
3844
3437
  ACL: "public-read"
3845
- }), { expiresIn: 3600 });
3846
- let guarded;
3438
+ });
3439
+ const signedUrl = await getSignedUrl(client, command, {
3440
+ expiresIn: 3600,
3441
+ signableHeaders: new Set(Object.keys(headers))
3442
+ });
3443
+ let release;
3847
3444
  try {
3848
- guarded = await fetchWithSsrFGuard({
3445
+ const guarded = await fetchWithSsrFGuard({
3849
3446
  url: signedUrl,
3850
3447
  init: {
3851
3448
  method: "PUT",
@@ -3855,14 +3452,14 @@ async function uploadFile(params) {
3855
3452
  auditContext: "tlon-custom-s3-upload",
3856
3453
  capture: false,
3857
3454
  maxRedirects: 0,
3858
- policy: privateNetworkPolicy,
3859
- timeoutMs: TLON_UPLOAD_TIMEOUT_MS
3455
+ policy: privateNetworkPolicy
3860
3456
  });
3457
+ release = guarded.release;
3861
3458
  if (!guarded.response.ok) throw new Error(`Upload failed: ${guarded.response.status}`);
3862
3459
  } finally {
3863
- await releaseUploadResponse(guarded);
3460
+ await release?.();
3864
3461
  }
3865
- return { url: assertSafeUploadResultUrl(storageConfig.publicUrlBase ? new URL(fileKey, storageConfig.publicUrlBase).toString() : expectDefined(signedUrl.split("?").at(0), "signed URL base segment"), "Upload result URL") };
3462
+ return { url: assertSafeUploadResultUrl(storageConfig.publicUrlBase ? new URL(fileKey, storageConfig.publicUrlBase).toString() : signedUrl.split("?")[0], "Upload result URL") };
3866
3463
  }
3867
3464
  //#endregion
3868
3465
  //#region extensions/tlon/src/urbit/upload.ts
@@ -3925,7 +3522,7 @@ async function createHttpPokeApi(params) {
3925
3522
  method: "PUT",
3926
3523
  headers: {
3927
3524
  "Content-Type": "application/json",
3928
- Cookie: expectDefined(cookie.split(";").at(0), "cookie first segment")
3525
+ Cookie: cookie.split(";")[0]
3929
3526
  },
3930
3527
  body: JSON.stringify([pokeData])
3931
3528
  },
@@ -3934,7 +3531,7 @@ async function createHttpPokeApi(params) {
3934
3531
  });
3935
3532
  try {
3936
3533
  if (!response.ok && response.status !== 204) {
3937
- const errorText = await readResponseTextLimited(response, 16 * 1024);
3534
+ const errorText = await readResponseTextLimited(response, 16384);
3938
3535
  throw new Error(`Poke failed: ${response.status} - ${errorText}`);
3939
3536
  }
3940
3537
  return pokeId;
@@ -4044,8 +3641,8 @@ const tlonRuntimeOutbound = {
4044
3641
  });
4045
3642
  }
4046
3643
  };
4047
- async function probeTlonAccount(account, timeoutMs) {
4048
- return await runChannelProbe(timeoutMs, async () => {
3644
+ async function probeTlonAccount(account) {
3645
+ try {
4049
3646
  const ssrfPolicy = ssrfPolicyFromDangerouslyAllowPrivateNetwork(account.dangerouslyAllowPrivateNetwork);
4050
3647
  const cookie = await authenticate(account.url, account.code, { ssrfPolicy });
4051
3648
  const { response, release } = await urbitFetch({
@@ -4066,13 +3663,14 @@ async function probeTlonAccount(account, timeoutMs) {
4066
3663
  };
4067
3664
  return { ok: true };
4068
3665
  } finally {
4069
- if (!response.bodyUsed) await response.body?.cancel().catch(() => void 0);
4070
3666
  await release();
4071
3667
  }
4072
- }, (error) => ({
4073
- ok: false,
4074
- error: error?.message ?? String(error)
4075
- }));
3668
+ } catch (error) {
3669
+ return {
3670
+ ok: false,
3671
+ error: error?.message ?? String(error)
3672
+ };
3673
+ }
4076
3674
  }
4077
3675
  async function startTlonGatewayAccount(ctx) {
4078
3676
  const account = ctx.account;