@openclaw/tlon 2026.7.2-beta.7 → 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,24 +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, createChannelIngressError, createChannelIngressMonitor, createMessageReceiptFromOutboundResults, waitUntilAbort } from "openclaw/plugin-sdk/channel-outbound";
7
- import { expectDefined } from "openclaw/plugin-sdk/expect-runtime";
8
- import { asFiniteNumber, normalizeLowercaseStringOrEmpty, normalizeNullableString, uniqueStrings } from "openclaw/plugin-sdk/string-coerce-runtime";
6
+ import { createMessageReceiptFromOutboundResults } from "openclaw/plugin-sdk/channel-outbound";
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";
21
- import { isRecord } from "openclaw/plugin-sdk/channel-secret-basic-runtime";
15
+ import { resolveStableChannelMessageIngress } from "openclaw/plugin-sdk/channel-ingress-runtime";
16
+ import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
22
17
  import { mkdir, writeFile } from "node:fs/promises";
23
18
  import * as path from "node:path";
24
19
  import { extensionForMime } from "openclaw/plugin-sdk/media-mime";
@@ -149,9 +144,7 @@ function applySettingsUpdate(current, key, value) {
149
144
  case "ownerShip":
150
145
  next.ownerShip = typeof value === "string" ? value : void 0;
151
146
  break;
152
- case "pendingApprovals":
153
- next.pendingApprovals = parsePendingApprovals(value);
154
- break;
147
+ case "pendingApprovals": next.pendingApprovals = parsePendingApprovals(value);
155
148
  }
156
149
  return next;
157
150
  }
@@ -274,8 +267,9 @@ var UrbitAuthError = class extends UrbitError {
274
267
  async function urbitFetch(params) {
275
268
  const validated = validateUrbitBaseUrl(params.baseUrl);
276
269
  if (!validated.ok) throw new UrbitUrlError(validated.error);
270
+ const url = new URL(params.path, validated.baseUrl).toString();
277
271
  return await fetchWithSsrFGuard({
278
- url: new URL(params.path, validated.baseUrl).toString(),
272
+ url,
279
273
  fetchImpl: params.fetchImpl,
280
274
  init: params.init,
281
275
  timeoutMs: params.timeoutMs,
@@ -289,7 +283,7 @@ async function urbitFetch(params) {
289
283
  }
290
284
  //#endregion
291
285
  //#region extensions/tlon/src/urbit/auth.ts
292
- const MAX_AUTH_BODY_DRAIN_BYTES = 64 * 1024;
286
+ const MAX_AUTH_BODY_DRAIN_BYTES = 65536;
293
287
  async function authenticate(url, code, options = {}) {
294
288
  const { response, release } = await urbitFetch({
295
289
  baseUrl: url,
@@ -345,11 +339,6 @@ function getUrbitContext(url, ship) {
345
339
  //#endregion
346
340
  //#region extensions/tlon/src/urbit/story.ts
347
341
  /**
348
- * Tlon Story Format - Rich text converter
349
- *
350
- * Converts markdown-like text to Tlon's story format.
351
- */
352
- /**
353
342
  * Parse inline markdown formatting (bold, italic, code, links, mentions)
354
343
  */
355
344
  function parseInlineMarkdown(text) {
@@ -358,41 +347,41 @@ function parseInlineMarkdown(text) {
358
347
  while (remaining.length > 0) {
359
348
  const shipMatch = remaining.match(/^(~[a-z][-a-z0-9]*)/);
360
349
  if (shipMatch) {
361
- result.push({ ship: expectDefined(shipMatch[1], "ship mention capture") });
350
+ result.push({ ship: shipMatch[1] });
362
351
  remaining = remaining.slice(shipMatch[0].length);
363
352
  continue;
364
353
  }
365
354
  const boldMatch = remaining.match(/^\*\*(.+?)\*\*|^__(.+?)__/);
366
355
  if (boldMatch) {
367
- const content = expectDefined(boldMatch[1] ?? boldMatch[2], "bold body capture");
356
+ const content = boldMatch[1] || boldMatch[2];
368
357
  result.push({ bold: parseInlineMarkdown(content) });
369
358
  remaining = remaining.slice(boldMatch[0].length);
370
359
  continue;
371
360
  }
372
361
  const italicsMatch = remaining.match(/^\*([^*]+?)\*|^_([^_]+?)_(?![a-zA-Z0-9])/);
373
362
  if (italicsMatch) {
374
- const content = expectDefined(italicsMatch[1] ?? italicsMatch[2], "italic body capture");
363
+ const content = italicsMatch[1] || italicsMatch[2];
375
364
  result.push({ italics: parseInlineMarkdown(content) });
376
365
  remaining = remaining.slice(italicsMatch[0].length);
377
366
  continue;
378
367
  }
379
368
  const strikeMatch = remaining.match(/^~~(.+?)~~/);
380
369
  if (strikeMatch) {
381
- result.push({ strike: parseInlineMarkdown(expectDefined(strikeMatch[1], "strikethrough body capture")) });
370
+ result.push({ strike: parseInlineMarkdown(strikeMatch[1]) });
382
371
  remaining = remaining.slice(strikeMatch[0].length);
383
372
  continue;
384
373
  }
385
374
  const codeMatch = remaining.match(/^`([^`]+)`/);
386
375
  if (codeMatch) {
387
- result.push({ "inline-code": expectDefined(codeMatch[1], "inline code capture") });
376
+ result.push({ "inline-code": codeMatch[1] });
388
377
  remaining = remaining.slice(codeMatch[0].length);
389
378
  continue;
390
379
  }
391
380
  const linkMatch = remaining.match(/^\[([^\]]+)\]\(([^)]+)\)/);
392
381
  if (linkMatch) {
393
382
  result.push({ link: {
394
- href: expectDefined(linkMatch[2], "link URL capture"),
395
- content: expectDefined(linkMatch[1], "link text capture")
383
+ href: linkMatch[2],
384
+ content: linkMatch[1]
396
385
  } });
397
386
  remaining = remaining.slice(linkMatch[0].length);
398
387
  continue;
@@ -400,53 +389,39 @@ function parseInlineMarkdown(text) {
400
389
  const imageMatch = remaining.match(/^!\[([^\]]*)\]\(([^)]+)\)/);
401
390
  if (imageMatch) {
402
391
  result.push({ __image: {
403
- src: expectDefined(imageMatch[2], "image URL capture"),
404
- alt: expectDefined(imageMatch[1], "image alt capture")
392
+ src: imageMatch[2],
393
+ alt: imageMatch[1]
405
394
  } });
406
395
  remaining = remaining.slice(imageMatch[0].length);
407
396
  continue;
408
397
  }
409
398
  const urlMatch = remaining.match(/^(https?:\/\/[^\s<>"\]]+)/);
410
399
  if (urlMatch) {
411
- const url = expectDefined(urlMatch[1], "plain URL capture");
412
400
  result.push({ link: {
413
- href: url,
414
- content: url
401
+ href: urlMatch[1],
402
+ content: urlMatch[1]
415
403
  } });
416
404
  remaining = remaining.slice(urlMatch[0].length);
417
405
  continue;
418
406
  }
419
407
  const plainMatch = remaining.match(/^[^*_`~[#\n:/]+/);
420
408
  if (plainMatch) {
421
- result.push(expectDefined(plainMatch[0], "plain text match"));
409
+ result.push(plainMatch[0]);
422
410
  remaining = remaining.slice(plainMatch[0].length);
423
411
  continue;
424
412
  }
425
- result.push(remaining.charAt(0));
413
+ result.push(remaining[0]);
426
414
  remaining = remaining.slice(1);
427
415
  }
428
416
  return mergeAdjacentStrings(result);
429
417
  }
430
- function headingTag(marker) {
431
- switch (marker.length) {
432
- case 1: return "h1";
433
- case 2: return "h2";
434
- case 3: return "h3";
435
- case 4: return "h4";
436
- case 5: return "h5";
437
- default: return "h6";
438
- }
439
- }
440
418
  /**
441
419
  * Merge adjacent string elements in an inline array
442
420
  */
443
421
  function mergeAdjacentStrings(inlines) {
444
422
  const result = [];
445
- for (const item of inlines) {
446
- const last = result.at(-1);
447
- if (typeof item === "string" && typeof last === "string") result.splice(-1, 1, last + item);
448
- else result.push(item);
449
- }
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);
450
425
  return result;
451
426
  }
452
427
  /**
@@ -464,12 +439,7 @@ function createImageBlock(src, alt = "", height = 0, width = 0) {
464
439
  * Check if URL looks like an image
465
440
  */
466
441
  function isImageUrl(url) {
467
- const imageExtensions = /\.(jpg|jpeg|png|gif|webp|svg|bmp|ico)$/i;
468
- let path = url.split(/[?#]/, 1)[0] ?? url;
469
- try {
470
- path = new URL(url).pathname;
471
- } catch {}
472
- return imageExtensions.test(path);
442
+ return /\.(jpg|jpeg|png|gif|webp|svg|bmp|ico)(\?.*)?$/i.test(url);
473
443
  }
474
444
  /**
475
445
  * Process inlines and extract any image markers into blocks
@@ -486,158 +456,6 @@ function processInlinesForImages(inlines) {
486
456
  imageBlocks
487
457
  };
488
458
  }
489
- function parseInlinesWithBreaks(text) {
490
- const withBreaks = [];
491
- for (const inline of parseInlineMarkdown(text)) {
492
- if (typeof inline !== "string" || !inline.includes("\n")) {
493
- withBreaks.push(inline);
494
- continue;
495
- }
496
- const parts = inline.split("\n");
497
- for (const [index, part] of parts.entries()) {
498
- if (part) withBreaks.push(part);
499
- if (index < parts.length - 1) withBreaks.push({ break: null });
500
- }
501
- }
502
- return processInlinesForImages(withBreaks);
503
- }
504
- const MARKDOWN_LIST_ITEM_PATTERN = /^([ \t]*)([-+*]|\d{1,9}[.)])(?:([ \t]+)(.*))?$/;
505
- function isMarkdownThematicBreak(text) {
506
- return /^(?:(?:\*\s*){3,}|(?:-\s*){3,}|(?:_\s*){3,})$/.test(text);
507
- }
508
- function startsListBlockSyntax(text) {
509
- return /^(`{3,}|~{3,})/.test(text) || text.startsWith(">") || /^#{1,6}(?:\s|$)/.test(text) || isMarkdownThematicBreak(text) || /^(?:[-+*]|\d{1,9}[.)])(?:\s|$)/.test(text);
510
- }
511
- function whitespaceColumns(text, startColumn = 0) {
512
- let column = startColumn;
513
- for (const char of text) column += char === " " ? 4 - column % 4 : 1;
514
- return column;
515
- }
516
- function parseMarkdownListItem(line) {
517
- const match = line.match(MARKDOWN_LIST_ITEM_PATTERN);
518
- if (!match || isMarkdownThematicBreak(line.trim())) return;
519
- const marker = expectDefined(match[2], "list marker capture");
520
- const markerType = /^\d/.test(marker) ? "ordered" : "unordered";
521
- const padding = match[3] ?? " ";
522
- const sourceBody = match[4] ?? "";
523
- let body = sourceBody;
524
- const task = body.match(/^\[([\t xX])\](?:\s+(.*))?$/);
525
- let checked;
526
- if (task) {
527
- checked = expectDefined(task[1], "task state capture").toLowerCase() === "x";
528
- body = task[2] ?? "";
529
- }
530
- const { inlines, imageBlocks } = parseInlinesWithBreaks(body);
531
- const indent = whitespaceColumns(expectDefined(match[1], "list indent capture"));
532
- const markerEnd = indent + marker.length;
533
- const contentIndent = whitespaceColumns(padding, markerEnd);
534
- return {
535
- indent,
536
- contentIndent,
537
- markerType,
538
- markerKey: markerType === "ordered" ? marker.slice(-1) : marker,
539
- ...markerType === "ordered" ? { orderedStart: Number.parseInt(marker, 10) } : {},
540
- hasSourceBody: sourceBody.length > 0,
541
- hasBlockBody: sourceBody.length > 0 && (contentIndent - markerEnd >= 5 || startsListBlockSyntax(sourceBody)),
542
- hasImages: imageBlocks.length > 0,
543
- content: inlines,
544
- ...checked === void 0 ? {} : { checked }
545
- };
546
- }
547
- function lineIndent(line) {
548
- return whitespaceColumns(line.match(/^[ \t]*/)?.[0] ?? "");
549
- }
550
- function startsTopLevelStoryBlock(line) {
551
- return /^(#{1,6})\s+(.+)$/.test(line) || line.startsWith("```") || line.startsWith("> ") || /^(-{3,}|\*{3,})$/.test(line.trim());
552
- }
553
- function listItemContent(item) {
554
- return item.checked === void 0 ? item.content : [{ task: {
555
- checked: item.checked,
556
- content: item.content
557
- } }];
558
- }
559
- function canInterruptWithListItem(item) {
560
- return item.hasSourceBody && (item.markerType === "unordered" || item.orderedStart === 1);
561
- }
562
- function parseListingBlock(lines, startIndex) {
563
- const first = parseMarkdownListItem(expectDefined(lines[startIndex], "list start line"));
564
- if (!first) return;
565
- if (first.indent >= 4 || first.markerType === "ordered" && first.orderedStart !== 1) return;
566
- function parseLevel(index, minIndent, markerKey) {
567
- const firstItem = parseMarkdownListItem(expectDefined(lines[index], "list level start"));
568
- if (!firstItem || firstItem.indent < minIndent || firstItem.indent > minIndent + 3 || firstItem.markerType === "ordered" && firstItem.orderedStart !== 1) return;
569
- const items = [];
570
- const markerType = firstItem.markerType;
571
- let allTasks = true;
572
- let cursor = index;
573
- while (cursor < lines.length) {
574
- const item = parseMarkdownListItem(expectDefined(lines[cursor], "list line index"));
575
- if (!item || item.indent < minIndent || item.indent > minIndent + 3 || item.markerKey !== markerKey) break;
576
- if (item.hasBlockBody || item.hasImages) return;
577
- allTasks &&= item.checked !== void 0;
578
- cursor++;
579
- while (cursor < lines.length) {
580
- const continuationLine = expectDefined(lines[cursor], "continuation line index");
581
- if (continuationLine.trim() === "") {
582
- let nextContentIndex = cursor + 1;
583
- while (lines[nextContentIndex]?.trim() === "") nextContentIndex++;
584
- const nextContent = lines.at(nextContentIndex);
585
- if (nextContent === void 0) break;
586
- if (parseMarkdownListItem(nextContent)) {
587
- cursor = nextContentIndex;
588
- continue;
589
- }
590
- if (lineIndent(nextContent) > item.indent) return;
591
- break;
592
- }
593
- if (parseMarkdownListItem(continuationLine)) break;
594
- if (lineIndent(continuationLine) <= item.indent && startsTopLevelStoryBlock(continuationLine)) break;
595
- return;
596
- }
597
- const childLine = lines.at(cursor);
598
- const child = childLine === void 0 ? void 0 : parseMarkdownListItem(childLine);
599
- if (child !== void 0 && child.markerKey === markerKey && child.indent >= minIndent && child.indent <= minIndent + 3 && child.indent < item.contentIndent) {
600
- items.push({ item: listItemContent(item) });
601
- continue;
602
- }
603
- if (child && child.markerKey !== markerKey && !canInterruptWithListItem(child)) return;
604
- if (child && child.indent >= item.contentIndent && !canInterruptWithListItem(child)) return;
605
- if (child && child.indent > item.indent) {
606
- if (child.indent < item.contentIndent || child.indent >= item.contentIndent + 4) return;
607
- const nested = parseLevel(cursor, item.contentIndent, child.markerKey);
608
- if (!nested) return;
609
- items.push({ list: {
610
- type: nested.type,
611
- contents: listItemContent(item),
612
- items: nested.items
613
- } });
614
- cursor = nested.nextIndex;
615
- const strandedChildLine = lines.at(cursor);
616
- const strandedChild = strandedChildLine === void 0 ? void 0 : parseMarkdownListItem(strandedChildLine);
617
- if (!(strandedChild !== void 0 && strandedChild.markerKey === markerKey && strandedChild.indent >= minIndent && strandedChild.indent <= minIndent + 3 && strandedChild.indent < item.contentIndent) && strandedChild && strandedChild.indent > item.indent) return;
618
- let trailingIndex = cursor;
619
- while (lines[trailingIndex]?.trim() === "") trailingIndex++;
620
- const trailingLine = lines.at(trailingIndex);
621
- if (trailingLine !== void 0 && !parseMarkdownListItem(trailingLine) && lineIndent(trailingLine) > item.indent) return;
622
- } else items.push({ item: listItemContent(item) });
623
- }
624
- return {
625
- type: markerType === "unordered" && allTasks && items.length > 0 ? "tasklist" : markerType,
626
- items,
627
- nextIndex: cursor
628
- };
629
- }
630
- const parsed = parseLevel(startIndex, 0, first.markerKey);
631
- if (!parsed) return;
632
- return {
633
- verses: [{ block: { listing: { list: {
634
- type: parsed.type,
635
- contents: [],
636
- items: parsed.items
637
- } } } }],
638
- nextIndex: parsed.nextIndex
639
- };
640
- }
641
459
  /**
642
460
  * Convert markdown text to Tlon story format
643
461
  */
@@ -645,19 +463,14 @@ function markdownToStory(markdown) {
645
463
  const story = [];
646
464
  const lines = markdown.split("\n");
647
465
  let i = 0;
648
- let preservedListMarkerKey;
649
466
  while (i < lines.length) {
650
- const line = expectDefined(lines[i], "Markdown line index is in bounds");
651
- const lineListItem = parseMarkdownListItem(line);
652
- if (line.trim() !== "" && preservedListMarkerKey !== void 0 && (lineListItem !== void 0 ? lineListItem.markerKey !== preservedListMarkerKey : lineIndent(line) === 0)) preservedListMarkerKey = void 0;
467
+ const line = lines[i];
653
468
  if (line.startsWith("```")) {
654
469
  const lang = line.slice(3).trim() || "plaintext";
655
470
  const codeLines = [];
656
471
  i++;
657
- while (true) {
658
- const codeLine = lines.at(i);
659
- if (codeLine === void 0 || codeLine.startsWith("```")) break;
660
- codeLines.push(codeLine);
472
+ while (i < lines.length && !lines[i].startsWith("```")) {
473
+ codeLines.push(lines[i]);
661
474
  i++;
662
475
  }
663
476
  story.push({ block: { code: {
@@ -669,10 +482,10 @@ function markdownToStory(markdown) {
669
482
  }
670
483
  const headerMatch = line.match(/^(#{1,6})\s+(.+)$/);
671
484
  if (headerMatch) {
672
- const tag = headingTag(expectDefined(headerMatch[1], "header marker capture"));
485
+ const tag = `h${headerMatch[1].length}`;
673
486
  story.push({ block: { header: {
674
487
  tag,
675
- content: parseInlineMarkdown(expectDefined(headerMatch[2], "header body capture"))
488
+ content: parseInlineMarkdown(headerMatch[2])
676
489
  } } });
677
490
  i++;
678
491
  continue;
@@ -684,10 +497,8 @@ function markdownToStory(markdown) {
684
497
  }
685
498
  if (line.startsWith("> ")) {
686
499
  const quoteLines = [];
687
- while (true) {
688
- const quoteLine = lines.at(i);
689
- if (quoteLine === void 0 || !quoteLine.startsWith("> ")) break;
690
- quoteLines.push(quoteLine.slice(2));
500
+ while (i < lines.length && lines[i].startsWith("> ")) {
501
+ quoteLines.push(lines[i].slice(2));
691
502
  i++;
692
503
  }
693
504
  const quoteText = quoteLines.join("\n");
@@ -698,33 +509,23 @@ function markdownToStory(markdown) {
698
509
  i++;
699
510
  continue;
700
511
  }
701
- const preservesLooseList = preservedListMarkerKey !== void 0 && lineListItem?.markerKey === preservedListMarkerKey;
702
- const listing = preservesLooseList ? void 0 : parseListingBlock(lines, i);
703
- if (listing) {
704
- story.push(...listing.verses);
705
- i = listing.nextIndex;
706
- preservedListMarkerKey = void 0;
707
- continue;
708
- }
709
- if (lineListItem) preservedListMarkerKey = lineListItem.markerKey;
710
- let preserveListText = preservesLooseList || MARKDOWN_LIST_ITEM_PATTERN.test(line);
711
512
  const paragraphLines = [];
712
- while (true) {
713
- const paragraphLine = lines.at(i);
714
- if (paragraphLine === void 0 || paragraphLine.trim() === "" || paragraphLine.startsWith("#") || paragraphLine.startsWith("```") || paragraphLine.startsWith("> ") || /^(-{3,}|\*{3,})$/.test(paragraphLine.trim())) break;
715
- if (!preserveListText && MARKDOWN_LIST_ITEM_PATTERN.test(paragraphLine)) {
716
- const item = parseMarkdownListItem(paragraphLine);
717
- const candidate = parseListingBlock(lines, i);
718
- if (item?.hasSourceBody === true && candidate) break;
719
- preserveListText = true;
720
- if (item) preservedListMarkerKey = item.markerKey;
721
- }
722
- 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]);
723
515
  i++;
724
516
  }
725
517
  if (paragraphLines.length > 0) {
726
- const { inlines, imageBlocks } = parseInlinesWithBreaks(paragraphLines.join("\n"));
727
- 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 });
728
529
  story.push(...imageBlocks);
729
530
  }
730
531
  }
@@ -872,7 +673,7 @@ async function putUrbitChannel(deps, params) {
872
673
  auditContext: params.auditContext
873
674
  });
874
675
  }
875
- const TLON_ERROR_BODY_LIMIT_BYTES = 16 * 1024;
676
+ const TLON_ERROR_BODY_LIMIT_BYTES = 16384;
876
677
  async function pokeUrbitChannel(deps, params) {
877
678
  const pokeId = Date.now();
878
679
  const { response, release } = await putUrbitChannel(deps, {
@@ -889,11 +690,7 @@ async function pokeUrbitChannel(deps, params) {
889
690
  try {
890
691
  if (!response.ok && response.status !== 204) {
891
692
  const errorText = await readResponseTextLimited(response, TLON_ERROR_BODY_LIMIT_BYTES).catch(() => "");
892
- throw new UrbitHttpError({
893
- operation: "Poke",
894
- status: response.status,
895
- bodyText: errorText || void 0
896
- });
693
+ throw new Error(`Poke failed: ${response.status}${errorText ? ` - ${errorText}` : ""}`);
897
694
  }
898
695
  return pokeId;
899
696
  } finally {
@@ -916,10 +713,7 @@ async function scryUrbitPath(deps, params) {
916
713
  auditContext: params.auditContext
917
714
  });
918
715
  try {
919
- if (!response.ok) throw new UrbitHttpError({
920
- operation: `Scry for path ${params.path}`,
921
- status: response.status
922
- });
716
+ if (!response.ok) throw new Error(`Scry failed: ${response.status} for path ${params.path}`);
923
717
  return await readProviderJsonResponse(response, `Tlon scry response for path ${params.path}`);
924
718
  } finally {
925
719
  await release();
@@ -966,7 +760,7 @@ async function ensureUrbitChannelOpen(deps, params) {
966
760
  }
967
761
  //#endregion
968
762
  //#region extensions/tlon/src/urbit/sse-client.ts
969
- const MAX_SSE_PAYLOAD_BYTES = 16 * 1024 * 1024;
763
+ const MAX_SSE_PAYLOAD_BYTES = 16777216;
970
764
  function parseUrbitSsePayload(data) {
971
765
  if (Buffer.byteLength(data, "utf8") > MAX_SSE_PAYLOAD_BYTES) throw new Error("Tlon Urbit SSE payload exceeds 16 MiB limit");
972
766
  try {
@@ -993,7 +787,6 @@ var UrbitSSEClient = class {
993
787
  this.lastHeardEventId = -1;
994
788
  this.lastAcknowledgedEventId = -1;
995
789
  this.ackThreshold = 20;
996
- this.reconnectAbortController = new AbortController();
997
790
  const ctx = getUrbitContext(url, options.ship);
998
791
  this.url = ctx.baseUrl;
999
792
  this.cookie = normalizeUrbitCookie(cookie);
@@ -1021,18 +814,6 @@ var UrbitSSEClient = class {
1021
814
  fetchImpl: this.fetchImpl
1022
815
  };
1023
816
  }
1024
- resetChannelIdentity() {
1025
- this.channelId = `${Math.floor(Date.now() / 1e3)}-${randomUUID()}`;
1026
- this.channelUrl = new URL(`/~/channel/${this.channelId}`, this.url).toString();
1027
- this.lastHeardEventId = -1;
1028
- this.lastAcknowledgedEventId = -1;
1029
- }
1030
- async createCurrentChannel() {
1031
- await ensureUrbitChannelOpen(this.channelRequestContext(), {
1032
- createBody: this.subscriptions,
1033
- createAuditContext: "tlon-urbit-channel-create"
1034
- });
1035
- }
1036
817
  async subscribe(params) {
1037
818
  const subId = this.subscriptions.length + 1;
1038
819
  const subscription = {
@@ -1062,7 +843,7 @@ var UrbitSSEClient = class {
1062
843
  });
1063
844
  try {
1064
845
  if (!response.ok && response.status !== 204) {
1065
- const errorText = await readResponseTextLimited(response, 16 * 1024).catch(() => "");
846
+ const errorText = await readResponseTextLimited(response, 16384).catch(() => "");
1066
847
  throw new Error(`Subscribe failed: ${response.status}${errorText ? ` - ${errorText}` : ""}`);
1067
848
  }
1068
849
  } finally {
@@ -1070,9 +851,10 @@ var UrbitSSEClient = class {
1070
851
  }
1071
852
  }
1072
853
  async connect() {
1073
- this.lastHeardEventId = -1;
1074
- this.lastAcknowledgedEventId = -1;
1075
- await this.createCurrentChannel();
854
+ await ensureUrbitChannelOpen(this.channelRequestContext(), {
855
+ createBody: this.subscriptions,
856
+ createAuditContext: "tlon-urbit-channel-create"
857
+ });
1076
858
  await this.openStream();
1077
859
  this.isConnected = true;
1078
860
  this.reconnectAttempts = 0;
@@ -1107,10 +889,7 @@ var UrbitSSEClient = class {
1107
889
  if (!response.ok) {
1108
890
  this.streamRelease = null;
1109
891
  await release();
1110
- throw new UrbitHttpError({
1111
- operation: "Stream connection",
1112
- status: response.status
1113
- });
892
+ throw new Error(`Stream connection failed: ${response.status}`);
1114
893
  }
1115
894
  this.processStream(response.body).catch((error) => {
1116
895
  if (!this.aborted) {
@@ -1135,12 +914,12 @@ var UrbitSSEClient = class {
1135
914
  buffer += text;
1136
915
  bufferBytes = nextBytes;
1137
916
  };
1138
- const consumeText = async (text) => {
917
+ const consumeText = (text) => {
1139
918
  let offset = 0;
1140
919
  if (pendingDelimiterNewline && text.length > 0) {
1141
920
  pendingDelimiterNewline = false;
1142
921
  if (text.startsWith("\n")) {
1143
- await this.processEvent(buffer);
922
+ this.processEvent(buffer);
1144
923
  buffer = "";
1145
924
  bufferBytes = 0;
1146
925
  offset = 1;
@@ -1155,7 +934,7 @@ var UrbitSSEClient = class {
1155
934
  return;
1156
935
  }
1157
936
  appendPending(text.slice(offset, eventEnd));
1158
- await this.processEvent(buffer);
937
+ this.processEvent(buffer);
1159
938
  buffer = "";
1160
939
  bufferBytes = 0;
1161
940
  offset = eventEnd + 2;
@@ -1165,11 +944,11 @@ var UrbitSSEClient = class {
1165
944
  for await (const chunk of stream) {
1166
945
  if (this.aborted) break;
1167
946
  if (typeof chunk === "string") {
1168
- await consumeText(decoder.decode());
1169
- await consumeText(chunk);
1170
- } else await consumeText(decoder.decode(chunk, { stream: true }));
947
+ consumeText(decoder.decode());
948
+ consumeText(chunk);
949
+ } else consumeText(decoder.decode(chunk, { stream: true }));
1171
950
  }
1172
- await consumeText(decoder.decode());
951
+ consumeText(decoder.decode());
1173
952
  } finally {
1174
953
  if (this.streamRelease) {
1175
954
  const release = this.streamRelease;
@@ -1184,7 +963,7 @@ var UrbitSSEClient = class {
1184
963
  }
1185
964
  }
1186
965
  }
1187
- async processEvent(eventData) {
966
+ processEvent(eventData) {
1188
967
  const lines = eventData.split("\n");
1189
968
  let data = null;
1190
969
  let eventId = null;
@@ -1193,33 +972,35 @@ var UrbitSSEClient = class {
1193
972
  if (line.startsWith("data: ")) data = line.slice(6);
1194
973
  }
1195
974
  if (!data) return;
1196
- 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
+ }
1197
986
  try {
1198
- 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
+ }
1199
1001
  } catch (error) {
1200
1002
  this.logger.error?.(`Error parsing SSE event: ${String(error)}`);
1201
- await this.acknowledgeHandledEventIfNeeded(eventId);
1202
- return;
1203
1003
  }
1204
- if (parsed.response === "quit") {
1205
- if (parsed.id) {
1206
- const handlers = this.eventHandlers.get(parsed.id);
1207
- if (handlers?.quit) handlers.quit();
1208
- }
1209
- } else if (parsed.id && this.eventHandlers.has(parsed.id)) {
1210
- const { event } = this.eventHandlers.get(parsed.id) ?? {};
1211
- if (event && parsed.json) await event(parsed.json);
1212
- } else if (parsed.json) {
1213
- for (const { event } of this.eventHandlers.values()) if (event) await event(parsed.json);
1214
- }
1215
- await this.acknowledgeHandledEventIfNeeded(eventId);
1216
- }
1217
- async acknowledgeHandledEventIfNeeded(eventId) {
1218
- if (eventId === null || eventId <= this.lastAcknowledgedEventId) return;
1219
- this.lastHeardEventId = Math.max(this.lastHeardEventId, eventId);
1220
- if (this.lastHeardEventId - this.lastAcknowledgedEventId <= this.ackThreshold) return;
1221
- this.logger.log?.(`[SSE] Acking event ${this.lastHeardEventId} (last acked: ${this.lastAcknowledgedEventId})`);
1222
- await this.ack(this.lastHeardEventId);
1223
1004
  }
1224
1005
  async poke(params) {
1225
1006
  return await pokeUrbitChannel(this.channelRequestContext(), {
@@ -1247,6 +1028,7 @@ var UrbitSSEClient = class {
1247
1028
  this.cookie = normalizeUrbitCookie(newCookie);
1248
1029
  }
1249
1030
  async ack(eventId) {
1031
+ this.lastAcknowledgedEventId = eventId;
1250
1032
  const ackData = {
1251
1033
  id: Date.now(),
1252
1034
  action: "ack",
@@ -1258,7 +1040,6 @@ var UrbitSSEClient = class {
1258
1040
  });
1259
1041
  try {
1260
1042
  if (!response.ok) throw new Error(`Ack failed with status ${response.status}`);
1261
- this.lastAcknowledgedEventId = eventId;
1262
1043
  } finally {
1263
1044
  await release();
1264
1045
  }
@@ -1270,40 +1051,34 @@ var UrbitSSEClient = class {
1270
1051
  }
1271
1052
  if (this.reconnectAttempts >= this.maxReconnectAttempts) {
1272
1053
  this.logger.log?.(`[SSE] Max reconnection attempts (${this.maxReconnectAttempts}) reached. Waiting 10s before resetting...`);
1273
- if (!await this.waitForReconnectDelay(1e4) || this.aborted) return;
1054
+ const extendedBackoff = 1e4;
1055
+ await new Promise((resolve) => {
1056
+ setTimeout(resolve, extendedBackoff);
1057
+ });
1274
1058
  this.reconnectAttempts = 0;
1275
1059
  this.logger.log?.("[SSE] Reconnection attempts reset, resuming reconnection...");
1276
1060
  }
1277
1061
  this.reconnectAttempts += 1;
1278
1062
  const delay = Math.min(this.reconnectDelay * 2 ** (this.reconnectAttempts - 1), this.maxReconnectDelay);
1279
1063
  this.logger.log?.(`[SSE] Reconnection attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts} in ${delay}ms...`);
1280
- if (!await this.waitForReconnectDelay(delay) || this.aborted || !this.autoReconnect) return;
1064
+ await new Promise((resolve) => {
1065
+ setTimeout(resolve, delay);
1066
+ });
1281
1067
  try {
1068
+ this.channelId = `${Math.floor(Date.now() / 1e3)}-${randomUUID()}`;
1069
+ this.channelUrl = new URL(`/~/channel/${this.channelId}`, this.url).toString();
1282
1070
  if (this.onReconnect) await this.onReconnect(this);
1283
- try {
1284
- await this.openStream();
1285
- } catch (error) {
1286
- if (!(error instanceof UrbitHttpError) || error.status !== 404) throw error;
1287
- this.resetChannelIdentity();
1288
- await this.createCurrentChannel();
1289
- await this.openStream();
1290
- }
1291
- this.isConnected = true;
1292
- this.reconnectAttempts = 0;
1071
+ await this.connect();
1293
1072
  this.logger.log?.("[SSE] Reconnection successful!");
1294
1073
  } catch (error) {
1295
1074
  this.logger.error?.(`[SSE] Reconnection failed: ${String(error)}`);
1296
1075
  await this.attemptReconnect();
1297
1076
  }
1298
1077
  }
1299
- stopReceiving() {
1078
+ async close() {
1300
1079
  this.aborted = true;
1301
1080
  this.isConnected = false;
1302
- this.reconnectAbortController.abort();
1303
1081
  this.streamController?.abort();
1304
- }
1305
- async close() {
1306
- this.stopReceiving();
1307
1082
  try {
1308
1083
  const unsubscribes = this.subscriptions.map((sub) => ({
1309
1084
  id: sub.id,
@@ -1350,15 +1125,6 @@ var UrbitSSEClient = class {
1350
1125
  await release();
1351
1126
  }
1352
1127
  }
1353
- async waitForReconnectDelay(delayMs) {
1354
- try {
1355
- await sleepWithAbort(delayMs, this.reconnectAbortController.signal);
1356
- return true;
1357
- } catch (error) {
1358
- if (this.reconnectAbortController.signal.aborted) return false;
1359
- throw error;
1360
- }
1361
- }
1362
1128
  async putChannelPayload(payload, params) {
1363
1129
  return await urbitFetch({
1364
1130
  baseUrl: this.url,
@@ -1496,7 +1262,7 @@ function parseAdminCommand(text) {
1496
1262
  const unblockMatch = trimmed.match(/^unblock\s+(~[\w-]+)$/);
1497
1263
  if (unblockMatch) return {
1498
1264
  type: "unblock",
1499
- ship: expectDefined(unblockMatch[1], "unblock ship capture")
1265
+ ship: unblockMatch[1]
1500
1266
  };
1501
1267
  return null;
1502
1268
  }
@@ -1670,7 +1436,7 @@ function createTlonApprovalRuntime(params) {
1670
1436
  const approvals = getPendingApprovals();
1671
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));
1672
1438
  if (existingIndex !== -1) {
1673
- const existing = expectDefined(approvals[existingIndex], "located pending approval index");
1439
+ const existing = approvals[existingIndex];
1674
1440
  if (approval.originalMessage) {
1675
1441
  existing.originalMessage = approval.originalMessage;
1676
1442
  existing.messagePreview = approval.messagePreview;
@@ -1711,31 +1477,29 @@ function createTlonApprovalRuntime(params) {
1711
1477
  }
1712
1478
  }
1713
1479
  break;
1714
- case "group":
1715
- if (approval.groupFlag) try {
1716
- await api.poke({
1717
- app: "groups",
1718
- mark: "group-join",
1719
- json: {
1720
- flag: approval.groupFlag,
1721
- "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)}`);
1722
1497
  }
1723
- });
1724
- runtime.log?.(`[tlon] Joined group ${approval.groupFlag} after approval`);
1725
- setTimeout(() => {
1726
- (async () => {
1727
- try {
1728
- const newCount = await refreshWatchedChannels();
1729
- if (newCount > 0) runtime.log?.(`[tlon] Discovered ${newCount} new channel(s) after joining group`);
1730
- } catch (err) {
1731
- runtime.log?.(`[tlon] Channel discovery after group join failed: ${String(err)}`);
1732
- }
1733
- })();
1734
- }, 2e3);
1735
- } catch (err) {
1736
- runtime.error?.(`[tlon] Failed to join group ${approval.groupFlag}: ${String(err)}`);
1737
- }
1738
- break;
1498
+ })();
1499
+ }, 2e3);
1500
+ } catch (err) {
1501
+ runtime.error?.(`[tlon] Failed to join group ${approval.groupFlag}: ${String(err)}`);
1502
+ }
1739
1503
  }
1740
1504
  await sendOwnerNotification(formatApprovalConfirmation(approval, "approve"));
1741
1505
  } else if (parsed.action === "block") {
@@ -1828,8 +1592,8 @@ function extractCites(content) {
1828
1592
  }
1829
1593
  function formatModelName(modelString) {
1830
1594
  if (!modelString) return "AI";
1831
- const modelName = modelString.includes("/") ? expectDefined(modelString.split("/").at(1), "provider/model second segment") : modelString;
1832
- const mappedName = {
1595
+ const modelName = modelString.includes("/") ? modelString.split("/")[1] : modelString;
1596
+ const modelMappings = {
1833
1597
  "claude-opus-4-5": "Claude Opus 4.5",
1834
1598
  "claude-sonnet-4-5": "Claude Sonnet 4.5",
1835
1599
  "claude-sonnet-3-5": "Claude Sonnet 3.5",
@@ -1838,8 +1602,8 @@ function formatModelName(modelString) {
1838
1602
  "gpt-4": "GPT-4",
1839
1603
  "gemini-2.0-flash": "Gemini 2.0 Flash",
1840
1604
  "gemini-pro": "Gemini Pro"
1841
- }[modelName];
1842
- if (mappedName !== void 0) return mappedName;
1605
+ };
1606
+ if (modelMappings[modelName]) return modelMappings[modelName];
1843
1607
  return modelName.replace(/-/g, " ").split(" ").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
1844
1608
  }
1845
1609
  function isBotMentioned(messageText, botShipName, nickname) {
@@ -1900,37 +1664,10 @@ async function resolveTlonCommandAuthorizationWithIngress(params) {
1900
1664
  command: {}
1901
1665
  });
1902
1666
  }
1903
- function resolveTlonGroupMentionDecision(params) {
1904
- const implicitMentions = resolveChannelImplicitMentions({
1905
- cfg: params.cfg,
1906
- channel: "tlon",
1907
- accountId: params.accountId
1908
- });
1909
- return resolveInboundMentionDecision({
1910
- facts: {
1911
- canDetectMention: true,
1912
- wasMentioned: params.wasMentioned,
1913
- implicitMentionKinds: implicitMentionKindWhen("bot_thread_participant", params.botParticipatedInThread)
1914
- },
1915
- policy: {
1916
- isGroup: true,
1917
- requireMention: true,
1918
- implicitMentions,
1919
- allowTextCommands: false,
1920
- hasControlCommand: false,
1921
- commandAuthorized: false
1922
- }
1923
- });
1924
- }
1925
1667
  function isGroupInviteAllowed(inviterShip, allowlist) {
1668
+ if (!allowlist || allowlist.length === 0) return false;
1926
1669
  const normalizedInviter = normalizeShip(inviterShip);
1927
- return resolveAllowlistMatchByCandidates({
1928
- allowList: (allowlist ?? []).map((ship) => normalizeShip(ship)),
1929
- candidates: [{
1930
- value: normalizedInviter,
1931
- source: "ship"
1932
- }]
1933
- }).allowed;
1670
+ return allowlist.map((ship) => normalizeShip(ship)).some((ship) => ship === normalizedInviter);
1934
1671
  }
1935
1672
  async function resolveAuthorizedMessageText(params) {
1936
1673
  const { rawText, content, authorizedForCites, resolveAllCites } = params;
@@ -2051,7 +1788,8 @@ function createTlonCitationResolver(params) {
2051
1788
  try {
2052
1789
  const scryPath = `/channels/v4/${cite.nest}/posts/post/${cite.postId}.json`;
2053
1790
  runtime.log?.(`[tlon] Fetching cited post: ${scryPath}`);
2054
- const essay = asRecord(asRecord(await api.scry(scryPath))?.essay);
1791
+ const data = asRecord(await api.scry(scryPath));
1792
+ const essay = asRecord(data?.essay);
2055
1793
  if (essay?.content) return extractMessageText(essay.content) || null;
2056
1794
  return null;
2057
1795
  } catch (err) {
@@ -2087,7 +1825,8 @@ async function fetchInitData(api, runtime) {
2087
1825
  const channels = [];
2088
1826
  const groups = asRecord(initData?.groups);
2089
1827
  if (groups) for (const groupData of Object.values(groups)) {
2090
- const groupChannels = asRecord(asRecord(groupData)?.channels);
1828
+ const typedGroupData = asRecord(groupData);
1829
+ const groupChannels = asRecord(typedGroupData?.channels);
2091
1830
  if (groupChannels) {
2092
1831
  for (const channelNest of Object.keys(groupChannels)) if (channelNest.startsWith("chat/")) channels.push(channelNest);
2093
1832
  }
@@ -2162,7 +1901,8 @@ async function fetchChannelHistory(api, channelNest, count = 50, runtime) {
2162
1901
  }
2163
1902
  const messages = posts.map((item) => {
2164
1903
  const itemRecord = asRecord(item);
2165
- const replyPostSet = asRecord(asRecord(itemRecord?.["r-post"])?.set);
1904
+ const replyPost = asRecord(itemRecord?.["r-post"]);
1905
+ const replyPostSet = asRecord(replyPost?.set);
2166
1906
  const essay = asRecord(itemRecord?.essay) ?? asRecord(replyPostSet?.essay);
2167
1907
  const seal = asRecord(itemRecord?.seal) ?? asRecord(replyPostSet?.seal);
2168
1908
  return {
@@ -2214,7 +1954,8 @@ async function fetchThreadHistory(api, channelNest, parentId, count = 50, runtim
2214
1954
  }
2215
1955
  const messages = replies.map((item) => {
2216
1956
  const itemRecord = asRecord(item);
2217
- const replySet = asRecord(asRecord(itemRecord?.["r-reply"])?.set);
1957
+ const replyRecord = asRecord(itemRecord?.["r-reply"]);
1958
+ const replySet = asRecord(replyRecord?.set);
2218
1959
  return createHistoryEntryFromMemo({
2219
1960
  memo: asRecord(itemRecord?.memo) ?? asRecord(replySet?.memo) ?? itemRecord,
2220
1961
  seal: asRecord(itemRecord?.seal) ?? asRecord(replySet?.seal),
@@ -2229,7 +1970,8 @@ async function fetchThreadHistory(api, channelNest, parentId, count = 50, runtim
2229
1970
  const altPath = `/channels/v4/${channelNest}/posts/post/id/${formatUd(parentId)}.json`;
2230
1971
  runtime?.log?.(`[tlon] Trying alternate path: ${altPath}`);
2231
1972
  const data = asRecord(await api.scry(altPath));
2232
- const dataMeta = asRecord(asRecord(data?.seal)?.meta);
1973
+ const dataSeal = asRecord(data?.seal);
1974
+ const dataMeta = asRecord(dataSeal?.meta);
2233
1975
  const repliesValue = data?.replies;
2234
1976
  if (typeof dataMeta?.replyCount === "number" && dataMeta.replyCount > 0 && repliesValue) {
2235
1977
  const messages = (Array.isArray(repliesValue) ? repliesValue : Object.values(repliesValue)).map((reply) => {
@@ -2249,133 +1991,6 @@ async function fetchThreadHistory(api, channelNest, parentId, count = 50, runtim
2249
1991
  }
2250
1992
  }
2251
1993
  //#endregion
2252
- //#region extensions/tlon/src/monitor/ingress.ts
2253
- const TLON_INGRESS_PAYLOAD_VERSION = 1;
2254
- const TLON_INGRESS_POLL_INTERVAL_MS = 1e3;
2255
- const TlonIngressPermanentError = createChannelIngressError("TlonIngressPermanentError", { withReason: true });
2256
- var TlonIngressShutdownError = class extends Error {
2257
- constructor() {
2258
- super("Tlon ingress stopped before dispatch adoption.");
2259
- this.name = "TlonIngressShutdownError";
2260
- }
2261
- };
2262
- function inspectChannelsEvent(event) {
2263
- const envelope = isRecord(event) ? event : null;
2264
- const nest = normalizeNullableString(envelope?.nest);
2265
- const response = isRecord(envelope?.response) ? envelope.response : null;
2266
- const post = isRecord(response?.post) ? response.post : null;
2267
- const rPost = isRecord(post?.["r-post"]) ? post["r-post"] : null;
2268
- const set = isRecord(rPost?.set) ? rPost.set : null;
2269
- const reply = isRecord(rPost?.reply) ? rPost.reply : null;
2270
- const rReply = isRecord(reply?.["r-reply"]) ? reply["r-reply"] : null;
2271
- const replySet = isRecord(rReply?.set) ? rReply.set : null;
2272
- if (!nest || !isRecord(set?.essay) && !isRecord(replySet?.memo)) return null;
2273
- const eventId = normalizeNullableString(isRecord(replySet?.memo) ? reply?.id : post?.id);
2274
- return eventId ? {
2275
- eventId,
2276
- laneKey: `group:${nest}`
2277
- } : null;
2278
- }
2279
- function inspectChatEvent(event) {
2280
- const envelope = isRecord(event) ? event : null;
2281
- const response = isRecord(envelope?.response) ? envelope.response : null;
2282
- const add = isRecord(response?.add) ? response.add : null;
2283
- const essay = isRecord(add?.essay) ? add.essay : null;
2284
- const eventId = normalizeNullableString(envelope?.id);
2285
- if (!essay || !eventId) return null;
2286
- const whom = isRecord(envelope?.whom) ? normalizeNullableString(envelope.whom.ship) : null;
2287
- const peer = normalizeNullableString(envelope?.whom) ?? whom ?? normalizeNullableString(essay.author);
2288
- return {
2289
- eventId,
2290
- laneKey: peer ? `direct:${peer}` : `event:${eventId}`
2291
- };
2292
- }
2293
- function inspectTlonIngressEvent(source, event) {
2294
- return source === "channels" ? inspectChannelsEvent(event) : inspectChatEvent(event);
2295
- }
2296
- function decodeTlonIngressPayload(payload, claimedId) {
2297
- if (payload.source !== "channels" && payload.source !== "chat" || typeof payload.rawEvent !== "string") throw new TlonIngressPermanentError("invalid-event", `Tlon ingress row ${claimedId} has an invalid payload.`);
2298
- return {
2299
- version: payload.version,
2300
- body: {
2301
- receivedAt: payload.receivedAt,
2302
- source: payload.source,
2303
- rawEvent: payload.rawEvent
2304
- }
2305
- };
2306
- }
2307
- function deserializeTlonIngressEvent(body, claimedId) {
2308
- let event;
2309
- try {
2310
- event = JSON.parse(body.rawEvent);
2311
- } catch (error) {
2312
- throw new TlonIngressPermanentError("invalid-event", `Tlon ingress row ${claimedId} contains invalid JSON.`, { cause: error });
2313
- }
2314
- return {
2315
- source: body.source,
2316
- event
2317
- };
2318
- }
2319
- function resolveTlonIngressNonRetryableFailure(error) {
2320
- if (error instanceof TlonIngressPermanentError) return {
2321
- reason: error.reason,
2322
- message: error.message
2323
- };
2324
- for (const candidate of collectErrorGraphCandidates(error, (current) => [current.cause])) if (candidate instanceof UrbitAuthError || candidate instanceof UrbitHttpError && (candidate.status === 401 || candidate.status === 403)) return {
2325
- reason: "tlon-auth",
2326
- message: formatErrorMessage(candidate)
2327
- };
2328
- return null;
2329
- }
2330
- function createTlonIngressMonitor(options) {
2331
- const monitor = createChannelIngressMonitor({
2332
- queue: options.queue ?? (() => getTlonRuntime().state.openChannelIngressQueue({ accountId: options.accountId })),
2333
- inspect: (raw) => inspectTlonIngressEvent(raw.source, raw.event),
2334
- payload: {
2335
- version: TLON_INGRESS_PAYLOAD_VERSION,
2336
- serialize: (raw, { receivedAt }) => ({
2337
- receivedAt,
2338
- source: raw.source,
2339
- rawEvent: JSON.stringify(raw.event)
2340
- }),
2341
- deserialize: (body, { claim }) => deserializeTlonIngressEvent(body, claim.id),
2342
- encode: ({ body }) => ({
2343
- version: TLON_INGRESS_PAYLOAD_VERSION,
2344
- ...body
2345
- }),
2346
- decode: (payload, { claim }) => decodeTlonIngressPayload(payload, claim.id),
2347
- 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.`)
2348
- },
2349
- deliver: (raw, lifecycle) => options.dispatch(raw.source, raw.event, lifecycle),
2350
- pollIntervalMs: options.pollIntervalMs ?? TLON_INGRESS_POLL_INTERVAL_MS,
2351
- retention: {
2352
- completedTtlMs: void 0,
2353
- completedMaxEntries: 2e3,
2354
- failedMaxEntries: 2e3
2355
- },
2356
- appendRetryDelaysMs: [0],
2357
- drain: {
2358
- resolveNonRetryableFailure: resolveTlonIngressNonRetryableFailure,
2359
- ...options.adoptionStallTimeoutMs === void 0 ? {} : { adoptionStallTimeoutMs: options.adoptionStallTimeoutMs },
2360
- onLog: (message) => options.runtime.log?.(`tlon ${message}`)
2361
- },
2362
- ...options.abortSignal ? { abortSignal: options.abortSignal } : {},
2363
- createStoppedError: () => new TlonIngressShutdownError(),
2364
- onError: (error) => options.runtime.error?.(`tlon ingress drain failed: ${formatErrorMessage(error)}`)
2365
- });
2366
- return {
2367
- receive: async ({ source, event }) => {
2368
- return { kind: (await monitor.admit({
2369
- source,
2370
- event
2371
- })).kind === "durable" ? "accepted" : "ignored" };
2372
- },
2373
- start: monitor.start,
2374
- stop: monitor.stop,
2375
- waitForIdle: monitor.waitForIdle
2376
- };
2377
- }
2378
- //#endregion
2379
1994
  //#region extensions/tlon/src/media-fetch-timeouts.ts
2380
1995
  const TLON_MEDIA_FETCH_TIMEOUTS = {
2381
1996
  responseHeaderTimeoutMs: 12e4,
@@ -2384,18 +1999,6 @@ const TLON_MEDIA_FETCH_TIMEOUTS = {
2384
1999
  //#endregion
2385
2000
  //#region extensions/tlon/src/monitor/media.ts
2386
2001
  const MAX_IMAGES_PER_MESSAGE = 8;
2387
- /** Keeps Tlon's shipped path-duplicating prompt bytes paired with ordered facts. */
2388
- function buildTlonInboundMediaPrompt(messageText, attachments) {
2389
- const media = attachments.map((attachment) => ({ ...attachment }));
2390
- if (media.length === 0) return {
2391
- body: messageText,
2392
- media
2393
- };
2394
- return {
2395
- body: `${media.map((attachment) => `[media attached: ${attachment.path} (${attachment.contentType}) | ${attachment.path}]`).join("\n")}\n${messageText}`,
2396
- media
2397
- };
2398
- }
2399
2002
  /**
2400
2003
  * Extract image blocks from Tlon message content.
2401
2004
  * Returns array of image URLs found in the message.
@@ -2486,6 +2089,66 @@ async function downloadMessageImages(content, mediaDir) {
2486
2089
  return attachments;
2487
2090
  }
2488
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
2489
2152
  //#region extensions/tlon/src/monitor/settings-helpers.ts
2490
2153
  function buildTlonSettingsMigrations(account, currentSettings) {
2491
2154
  return [
@@ -2589,37 +2252,6 @@ function mergeUniqueStrings(base, next) {
2589
2252
  return uniqueStrings([...base, ...next ?? []]);
2590
2253
  }
2591
2254
  //#endregion
2592
- //#region extensions/tlon/src/monitor/tracking.ts
2593
- const TLON_PARTICIPATED_THREAD_LIMIT = 2e3;
2594
- function createParticipatedThreadTracker(limit = TLON_PARTICIPATED_THREAD_LIMIT) {
2595
- const cache = createDedupeCache({
2596
- ttlMs: 0,
2597
- maxSize: limit
2598
- });
2599
- return {
2600
- add: (parentId) => {
2601
- cache.check(parentId);
2602
- },
2603
- has: (parentId) => {
2604
- if (!cache.peek(parentId)) return false;
2605
- cache.check(parentId);
2606
- return true;
2607
- }
2608
- };
2609
- }
2610
- function createActiveSnapshotTracker() {
2611
- const processed = /* @__PURE__ */ new Set();
2612
- return {
2613
- beginSnapshot: (keys) => {
2614
- const active = new Set(keys);
2615
- for (const key of processed) if (!active.has(key)) processed.delete(key);
2616
- return active;
2617
- },
2618
- has: (key) => processed.has(key),
2619
- add: (key) => processed.add(key)
2620
- };
2621
- }
2622
- //#endregion
2623
2255
  //#region extensions/tlon/src/monitor/index.ts
2624
2256
  function readNumber(record, key) {
2625
2257
  return asFiniteNumber(record?.[key]);
@@ -2670,6 +2302,7 @@ async function monitorTlonProvider(opts = {}) {
2670
2302
  runtime.log?.("[tlon] Re-authentication successful");
2671
2303
  }
2672
2304
  });
2305
+ const processedTracker = createProcessedMessageTracker(2e3);
2673
2306
  let groupChannels = [];
2674
2307
  let botNickname = null;
2675
2308
  const settingsManager = createSettingsManager(api, {
@@ -2685,7 +2318,7 @@ async function monitorTlonProvider(opts = {}) {
2685
2318
  let effectiveOwnerShip = account.ownerShip ? normalizeShip(account.ownerShip) : null;
2686
2319
  let pendingApprovals = [];
2687
2320
  let currentSettings = {};
2688
- const participatedThreads = createParticipatedThreadTracker();
2321
+ const participatedThreads = /* @__PURE__ */ new Set();
2689
2322
  const dmSendersBySession = /* @__PURE__ */ new Map();
2690
2323
  let sharedSessionWarningSent = false;
2691
2324
  try {
@@ -2751,11 +2384,12 @@ async function monitorTlonProvider(opts = {}) {
2751
2384
  * Returns empty string if whom doesn't contain a valid patp-like value.
2752
2385
  */
2753
2386
  function extractDmPartnerShip(whom) {
2754
- 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);
2755
2389
  return /^~?[a-z-]+$/i.test(normalized) ? normalized : "";
2756
2390
  }
2757
2391
  const processMessage = async (params) => {
2758
- 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;
2759
2393
  const groupChannel = channelNest;
2760
2394
  let messageText = params.messageText;
2761
2395
  let attachments = [];
@@ -2853,22 +2487,21 @@ async function monitorTlonProvider(opts = {}) {
2853
2487
  const shouldComputeAuth = core.channel.commands.shouldComputeCommandAuthorized(messageText, cfg);
2854
2488
  let commandAuthorized = false;
2855
2489
  if (shouldComputeAuth) {
2490
+ const useAccessGroups = cfg.commands?.useAccessGroups !== false;
2856
2491
  commandAuthorized = (await resolveTlonCommandAuthorizationWithIngress({
2857
2492
  senderShip,
2858
2493
  ownerShip: effectiveOwnerShip,
2859
- useAccessGroups: true
2494
+ useAccessGroups
2860
2495
  })).commandAccess.authorized;
2861
2496
  if (!commandAuthorized) console.log(`[tlon] Command attempt denied: ${senderShip} is not owner (owner=${effectiveOwnerShip ?? "not configured"})`);
2862
2497
  }
2863
- const promptMedia = buildTlonInboundMediaPrompt(messageText, attachments);
2864
- const body = createChannelInboundEnvelopeBuilder({
2865
- cfg,
2866
- route
2867
- })({
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({
2868
2501
  channel: "Tlon",
2869
2502
  from: fromLabel,
2870
2503
  timestamp,
2871
- body: promptMedia.body
2504
+ body: bodyWithAttachments
2872
2505
  });
2873
2506
  const commandBody = isGroup ? stripBotMention(messageText, botShipName) : messageText;
2874
2507
  const tlonConversationId = isGroup ? groupChannel ?? channelNest ?? senderShip : senderShip;
@@ -2890,7 +2523,6 @@ async function monitorTlonProvider(opts = {}) {
2890
2523
  },
2891
2524
  route: {
2892
2525
  agentId: route.agentId,
2893
- dmScope: route.dmScope,
2894
2526
  accountId: route.accountId,
2895
2527
  routeSessionKey: route.sessionKey
2896
2528
  },
@@ -2916,7 +2548,8 @@ async function monitorTlonProvider(opts = {}) {
2916
2548
  });
2917
2549
  const dispatchStartTime = Date.now();
2918
2550
  const responsePrefix = core.channel.reply.resolveEffectiveMessagesConfig(cfg, route.agentId).responsePrefix;
2919
- 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 });
2920
2553
  const deliveryTarget = isGroup ? groupChannel : senderShip;
2921
2554
  const prepareReplyPayload = (payload) => {
2922
2555
  const replyText = payload.text;
@@ -2935,20 +2568,16 @@ async function monitorTlonProvider(opts = {}) {
2935
2568
  participatedThreads.add(parentId);
2936
2569
  runtime.log?.(`[tlon] Now tracking thread for future replies: ${parentId}`);
2937
2570
  };
2938
- const replyOptions = {
2939
- ...turnAdoptionLifecycle ? bindIngressLifecycleToReplyOptions(turnAdoptionLifecycle) : {},
2940
- ...promptMedia.media.length > 0 ? { media: promptMedia.media } : {}
2941
- };
2942
- await core.channel.inbound.dispatch({
2571
+ await core.channel.inbound.dispatchReply({
2943
2572
  channel: "tlon",
2944
2573
  accountId: route.accountId,
2945
2574
  cfg,
2946
- route: {
2947
- agentId: route.agentId,
2948
- dmScope: route.dmScope,
2949
- sessionKey: route.sessionKey
2950
- },
2575
+ agentId: route.agentId,
2576
+ routeSessionKey: route.sessionKey,
2577
+ storePath,
2951
2578
  ctxPayload,
2579
+ recordInboundSession: core.channel.session.recordInboundSession,
2580
+ dispatchReplyWithBufferedBlockDispatcher: core.channel.reply.dispatchReplyWithBufferedBlockDispatcher,
2952
2581
  delivery: {
2953
2582
  preparePayload: prepareReplyPayload,
2954
2583
  durable: deliveryTarget ? () => ({
@@ -2995,7 +2624,6 @@ async function monitorTlonProvider(opts = {}) {
2995
2624
  responsePrefix,
2996
2625
  humanDelay
2997
2626
  },
2998
- ...turnAdoptionLifecycle || promptMedia.media.length > 0 ? { replyOptions } : {},
2999
2627
  record: { onRecordError: (err) => {
3000
2628
  runtime.error?.(`[tlon] failed updating session meta: ${String(err)}`);
3001
2629
  } }
@@ -3067,7 +2695,7 @@ async function monitorTlonProvider(opts = {}) {
3067
2695
  },
3068
2696
  refreshWatchedChannels
3069
2697
  });
3070
- const handleChannelsFirehose = async (event, turnAdoptionLifecycle) => {
2698
+ const handleChannelsFirehose = async (event) => {
3071
2699
  try {
3072
2700
  const eventRecord = asRecord(event);
3073
2701
  const nest = readString(eventRecord, "nest");
@@ -3079,7 +2707,8 @@ async function monitorTlonProvider(opts = {}) {
3079
2707
  const rPost = asRecord(post?.["r-post"]);
3080
2708
  const set = asRecord(rPost?.set);
3081
2709
  const reply = asRecord(rPost?.reply);
3082
- const replySet = asRecord(asRecord(reply?.["r-reply"])?.set);
2710
+ const replyPayload = asRecord(reply?.["r-reply"]);
2711
+ const replySet = asRecord(replyPayload?.set);
3083
2712
  const essay = asRecord(set?.essay);
3084
2713
  const memo = asRecord(replySet?.memo);
3085
2714
  if (!essay && !memo) return;
@@ -3088,89 +2717,87 @@ async function monitorTlonProvider(opts = {}) {
3088
2717
  const isThreadReply = Boolean(memo);
3089
2718
  const messageId = isThreadReply ? readString(reply, "id") : readString(post, "id");
3090
2719
  if (!messageId) return;
3091
- const senderShip = normalizeShip(readString(content, "author") ?? "");
3092
- if (!senderShip || senderShip === botShipName) return;
3093
- const rawText = extractMessageText(content.content);
3094
- if (!rawText.trim()) return;
3095
- const contentBody = content.content;
3096
- const sentAt = readNumber(content, "sent") ?? Date.now();
3097
- cacheMessage(nest, {
3098
- author: senderShip,
3099
- content: rawText,
3100
- timestamp: sentAt,
3101
- id: messageId
3102
- });
3103
- const seal = isThreadReply ? asRecord(replySet?.seal) : asRecord(set?.seal);
3104
- const parentId = readString(seal, "parent-id") ?? readString(seal, "parent") ?? null;
3105
- const mentioned = isBotMentioned(rawText, botShipName, botNickname ?? void 0);
3106
- const inParticipatedThread = isThreadReply && parentId && participatedThreads.has(parentId);
3107
- const mentionDecision = resolveTlonGroupMentionDecision({
3108
- cfg,
3109
- accountId: account.accountId,
3110
- wasMentioned: mentioned,
3111
- botParticipatedInThread: Boolean(inParticipatedThread)
3112
- });
3113
- if (mentionDecision.shouldSkip) return;
3114
- if (mentionDecision.implicitMention && !mentioned) runtime.log?.(`[tlon] Responding to thread we participated in (no mention): ${parentId}`);
3115
- if (isOwner(senderShip)) runtime.log?.(`[tlon] Owner ${senderShip} is always allowed in channels`);
3116
- else {
3117
- const { mode, allowedShips } = resolveChannelAuthorization(cfg, nest, currentSettings);
3118
- if (mode === "restricted") {
3119
- if (!allowedShips.map(normalizeShip).includes(senderShip)) {
3120
- if (effectiveOwnerShip) {
3121
- const approval = createPendingApproval({
3122
- type: "channel",
3123
- requestingShip: senderShip,
3124
- channelNest: nest,
3125
- messagePreview: sliceUtf16Safe(rawText, 0, 100),
3126
- originalMessage: {
3127
- messageId: messageId ?? "",
3128
- messageText: rawText,
3129
- messageContent: contentBody,
3130
- timestamp: sentAt,
3131
- parentId: parentId ?? void 0,
3132
- isThreadReply
3133
- }
3134
- });
3135
- await queueApprovalRequest(approval);
3136
- } else runtime.log?.(`[tlon] Access denied: ${senderShip} in ${nest} (allowed: ${allowedShips.join(", ")})`);
3137
- 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
+ }
3138
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
+ });
3139
2788
  }
3140
- }
3141
- const messageText = await resolveAuthorizedMessageText({
3142
- rawText,
3143
- content: contentBody,
3144
- authorizedForCites: true,
3145
- resolveAllCites
3146
- });
3147
- const parsed = parseChannelNest(nest);
3148
- await processMessage({
3149
- messageId: messageId ?? "",
3150
- senderShip,
3151
- messageText,
3152
- messageContent: contentBody,
3153
- isGroup: true,
3154
- channelNest: nest,
3155
- hostShip: parsed?.hostShip,
3156
- channelName: parsed?.channelName,
3157
- timestamp: sentAt,
3158
- parentId,
3159
- isThreadReply,
3160
- turnAdoptionLifecycle
3161
2789
  });
3162
2790
  } catch (error) {
3163
2791
  runtime.error?.(`[tlon] Error handling channel firehose event: ${formatErrorMessage$1(error)}`);
3164
- throw error;
3165
2792
  }
3166
2793
  };
3167
- const processedDmInvites = createActiveSnapshotTracker();
3168
- const handleChatFirehose = async (event, turnAdoptionLifecycle) => {
2794
+ const processedDmInvites = /* @__PURE__ */ new Set();
2795
+ const handleChatFirehose = async (event) => {
3169
2796
  try {
3170
2797
  if (Array.isArray(event)) {
3171
- const ships = processedDmInvites.beginSnapshot(event.map((invite) => normalizeShip(invite.ship || "")).filter(Boolean));
3172
- for (const ship of ships) {
3173
- if (processedDmInvites.has(ship)) continue;
2798
+ for (const invite of event) {
2799
+ const ship = normalizeShip(invite.ship || "");
2800
+ if (!ship || processedDmInvites.has(ship)) continue;
3174
2801
  if (isOwner(ship)) {
3175
2802
  try {
3176
2803
  await api.poke({
@@ -3188,8 +2815,7 @@ async function monitorTlonProvider(opts = {}) {
3188
2815
  }
3189
2816
  continue;
3190
2817
  }
3191
- const allowed = await isDmAllowedWithIngress(ship, effectiveDmAllowlist);
3192
- if (effectiveAutoAcceptDmInvites && allowed) {
2818
+ if (effectiveAutoAcceptDmInvites && await isDmAllowedWithIngress(ship, effectiveDmAllowlist)) {
3193
2819
  try {
3194
2820
  await api.poke({
3195
2821
  app: "chat",
@@ -3206,7 +2832,7 @@ async function monitorTlonProvider(opts = {}) {
3206
2832
  }
3207
2833
  continue;
3208
2834
  }
3209
- if (effectiveOwnerShip && !allowed) {
2835
+ if (effectiveOwnerShip && !await isDmAllowedWithIngress(ship, effectiveDmAllowlist)) {
3210
2836
  const approval = createPendingApproval({
3211
2837
  type: "dm",
3212
2838
  requestingShip: ship,
@@ -3226,104 +2852,92 @@ async function monitorTlonProvider(opts = {}) {
3226
2852
  if (!messageId || !response) return;
3227
2853
  const essay = asRecord(asRecord(response.add)?.essay);
3228
2854
  if (!essay) return;
3229
- const authorShip = normalizeShip(readString(essay, "author") ?? "");
3230
- const partnerShip = extractDmPartnerShip(whom);
3231
- const senderShip = partnerShip || authorShip;
3232
- if (authorShip === botShipName) return;
3233
- if (!senderShip || senderShip === botShipName) return;
3234
- if (authorShip && partnerShip && authorShip !== partnerShip) runtime.log?.(`[tlon] DM ship mismatch (author=${authorShip}, partner=${partnerShip}) - routing to partner`);
3235
- const rawText = extractMessageText(essay.content);
3236
- if (!rawText.trim()) return;
3237
- const messageText = rawText;
3238
- if (isOwner(senderShip) && isApprovalResponse(messageText)) {
3239
- if (await handleApprovalResponse(messageText)) {
3240
- runtime.log?.(`[tlon] Processed approval response from owner: ${messageText}`);
3241
- return;
3242
- }
3243
- }
3244
- if (isOwner(senderShip) && isAdminCommand(messageText)) {
3245
- if (await handleAdminCommand(messageText)) {
3246
- runtime.log?.(`[tlon] Processed admin command from owner: ${messageText}`);
3247
- return;
3248
- }
3249
- }
3250
- if (isOwner(senderShip)) {
3251
- const resolvedMessageText = await resolveAuthorizedMessageText({
3252
- rawText,
3253
- content: essay.content,
3254
- authorizedForCites: true,
3255
- resolveAllCites
3256
- });
3257
- runtime.log?.(`[tlon] Processing DM from owner ${senderShip}`);
3258
- await processMessage({
3259
- messageId: messageId ?? "",
3260
- senderShip,
3261
- messageText: resolvedMessageText,
3262
- messageContent: essay.content,
3263
- isGroup: false,
3264
- timestamp: readNumber(essay, "sent") ?? Date.now(),
3265
- turnAdoptionLifecycle
3266
- });
3267
- return;
3268
- }
3269
- if (!await isDmAllowedWithIngress(senderShip, effectiveDmAllowlist)) {
3270
- if (effectiveOwnerShip) {
3271
- const approval = createPendingApproval({
3272
- type: "dm",
3273
- requestingShip: senderShip,
3274
- messagePreview: sliceUtf16Safe(messageText, 0, 100),
3275
- 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({
3276
2889
  messageId: messageId ?? "",
3277
- messageText,
2890
+ senderShip,
2891
+ messageText: resolvedMessageText,
3278
2892
  messageContent: essay.content,
2893
+ isGroup: false,
3279
2894
  timestamp: readNumber(essay, "sent") ?? Date.now()
3280
- }
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()
3281
2927
  });
3282
- await queueApprovalRequest(approval);
3283
- } else runtime.log?.(`[tlon] Blocked DM from ${senderShip}: not in allowlist`);
3284
- return;
3285
- }
3286
- await processMessage({
3287
- messageText: await resolveAuthorizedMessageText({
3288
- rawText,
3289
- content: essay.content,
3290
- authorizedForCites: true,
3291
- resolveAllCites
3292
- }),
3293
- messageId: messageId ?? "",
3294
- senderShip,
3295
- messageContent: essay.content,
3296
- isGroup: false,
3297
- timestamp: readNumber(essay, "sent") ?? Date.now(),
3298
- turnAdoptionLifecycle
2928
+ }
3299
2929
  });
3300
2930
  } catch (error) {
3301
2931
  runtime.error?.(`[tlon] Error handling chat firehose event: ${formatErrorMessage$1(error)}`);
3302
- throw error;
3303
2932
  }
3304
2933
  };
3305
- const ingress = createTlonIngressMonitor({
3306
- accountId: account.accountId,
3307
- runtime,
3308
- abortSignal: opts.abortSignal,
3309
- dispatch: async (source, event, turnAdoptionLifecycle) => {
3310
- if (source === "channels") {
3311
- await handleChannelsFirehose(event, turnAdoptionLifecycle);
3312
- return;
3313
- }
3314
- await handleChatFirehose(event, turnAdoptionLifecycle);
3315
- }
3316
- });
3317
2934
  try {
3318
2935
  runtime.log?.("[tlon] Subscribing to firehose updates...");
3319
2936
  await api.subscribe({
3320
2937
  app: "channels",
3321
2938
  path: "/v2",
3322
- event: async (event) => {
3323
- if ((await ingress.receive({
3324
- source: "channels",
3325
- event
3326
- })).kind === "ignored") await handleChannelsFirehose(event);
2939
+ event: (event) => {
2940
+ handleChannelsFirehose(event);
3327
2941
  },
3328
2942
  err: (error) => {
3329
2943
  runtime.error?.(`[tlon] Channels firehose error: ${String(error)}`);
@@ -3336,11 +2950,8 @@ async function monitorTlonProvider(opts = {}) {
3336
2950
  await api.subscribe({
3337
2951
  app: "chat",
3338
2952
  path: "/v3",
3339
- event: async (event) => {
3340
- if ((await ingress.receive({
3341
- source: "chat",
3342
- event
3343
- })).kind === "ignored") await handleChatFirehose(event);
2953
+ event: (event) => {
2954
+ handleChatFirehose(event);
3344
2955
  },
3345
2956
  err: (error) => {
3346
2957
  runtime.error?.(`[tlon] Chat firehose error: ${String(error)}`);
@@ -3357,7 +2968,9 @@ async function monitorTlonProvider(opts = {}) {
3357
2968
  try {
3358
2969
  const eventRecord = asRecord(event);
3359
2970
  if (eventRecord?.self) {
3360
- 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);
3361
2974
  if (nickname && "value" in nickname) {
3362
2975
  const newNickname = readString(nickname, "value") ?? null;
3363
2976
  if (newNickname !== botNickname) {
@@ -3586,7 +3199,6 @@ async function monitorTlonProvider(opts = {}) {
3586
3199
  for (const channelNest of watchedChannels) runtime.log?.(`[tlon] Watching channel: ${channelNest}`);
3587
3200
  runtime.log?.("[tlon] All subscriptions registered, connecting to SSE stream...");
3588
3201
  await api.connect();
3589
- ingress.start();
3590
3202
  runtime.log?.("[tlon] Connected! Firehose subscriptions active");
3591
3203
  const pollInterval = setInterval(() => {
3592
3204
  (async () => {
@@ -3602,13 +3214,17 @@ async function monitorTlonProvider(opts = {}) {
3602
3214
  runtime.error?.(`[tlon] Channel refresh error: ${formatErrorMessage$1(error)}`);
3603
3215
  }
3604
3216
  })();
3605
- }, 120 * 1e3);
3606
- await waitUntilAbort(opts.abortSignal, () => {
3607
- clearInterval(pollInterval);
3608
- });
3217
+ }, 12e4);
3218
+ if (opts.abortSignal) {
3219
+ const signal = opts.abortSignal;
3220
+ await new Promise((resolve) => {
3221
+ signal.addEventListener("abort", () => {
3222
+ clearInterval(pollInterval);
3223
+ resolve(null);
3224
+ }, { once: true });
3225
+ });
3226
+ } else await new Promise(() => {});
3609
3227
  } finally {
3610
- api?.stopReceiving();
3611
- await ingress.stop();
3612
3228
  try {
3613
3229
  await api?.close();
3614
3230
  } catch (error) {
@@ -3620,20 +3236,8 @@ async function monitorTlonProvider(opts = {}) {
3620
3236
  //#region extensions/tlon/src/tlon-api.ts
3621
3237
  const MEMEX_BASE_URL = "https://memex.tlon.network";
3622
3238
  /** Max bytes to read from the Memex upload JSON response. */
3623
- const MEMEX_UPLOAD_RESPONSE_MAX_BYTES = 64 * 1024;
3624
- /** Total deadline for the Memex upload URL lookup, including DNS and response reading. */
3625
- const TLON_MEMEX_UPLOAD_URL_TIMEOUT_MS = 3e4;
3626
- /** Total deadline for Memex and custom S3 PUTs, including DNS and the full upload. */
3627
- const TLON_UPLOAD_TIMEOUT_MS = 3e5;
3239
+ const MEMEX_UPLOAD_RESPONSE_MAX_BYTES = 65536;
3628
3240
  let currentClientConfig = null;
3629
- async function releaseUploadResponse(guarded) {
3630
- if (!guarded) return;
3631
- try {
3632
- if (!guarded.response.bodyUsed) await guarded.response.body?.cancel();
3633
- } catch {} finally {
3634
- await guarded.release();
3635
- }
3636
- }
3637
3241
  function configureClient(params) {
3638
3242
  currentClientConfig = {
3639
3243
  ...params,
@@ -3733,9 +3337,9 @@ async function getMemexUploadUrl(params) {
3733
3337
  const resolvedToken = typeof token === "string" ? token : token.secret;
3734
3338
  if (!resolvedToken) throw new Error("Missing genuine secret");
3735
3339
  const endpoint = `${MEMEX_BASE_URL}/v1/${params.config.shipName}/upload`;
3736
- let guarded;
3340
+ let release;
3737
3341
  try {
3738
- guarded = await fetchWithSsrFGuard({
3342
+ const guarded = await fetchWithSsrFGuard({
3739
3343
  url: endpoint,
3740
3344
  init: {
3741
3345
  method: "PUT",
@@ -3749,9 +3353,9 @@ async function getMemexUploadUrl(params) {
3749
3353
  },
3750
3354
  auditContext: "tlon-memex-upload-url",
3751
3355
  capture: false,
3752
- maxRedirects: 0,
3753
- timeoutMs: TLON_MEMEX_UPLOAD_URL_TIMEOUT_MS
3356
+ maxRedirects: 0
3754
3357
  });
3358
+ release = guarded.release;
3755
3359
  if (!guarded.response.ok) throw new Error(`Memex upload request failed: ${guarded.response.status}`);
3756
3360
  const data = await readProviderJsonResponse(guarded.response, "Memex upload", { maxBytes: MEMEX_UPLOAD_RESPONSE_MAX_BYTES });
3757
3361
  if (!data?.url || !data.filePath) throw new Error("Invalid response from Memex");
@@ -3760,7 +3364,7 @@ async function getMemexUploadUrl(params) {
3760
3364
  uploadUrl: data.url
3761
3365
  };
3762
3366
  } finally {
3763
- await releaseUploadResponse(guarded);
3367
+ await release?.();
3764
3368
  }
3765
3369
  }
3766
3370
  async function uploadFile(params) {
@@ -3781,9 +3385,9 @@ async function uploadFile(params) {
3781
3385
  fileName: fileKey
3782
3386
  });
3783
3387
  const trustedUploadUrl = assertTrustedMemexUploadUrl(uploadUrl, "Memex upload URL");
3784
- let guarded;
3388
+ let release;
3785
3389
  try {
3786
- guarded = await fetchWithSsrFGuard({
3390
+ const guarded = await fetchWithSsrFGuard({
3787
3391
  url: trustedUploadUrl,
3788
3392
  init: {
3789
3393
  method: "PUT",
@@ -3795,19 +3399,24 @@ async function uploadFile(params) {
3795
3399
  },
3796
3400
  auditContext: "tlon-memex-upload",
3797
3401
  capture: false,
3798
- maxRedirects: 0,
3799
- timeoutMs: TLON_UPLOAD_TIMEOUT_MS
3402
+ maxRedirects: 0
3800
3403
  });
3404
+ release = guarded.release;
3801
3405
  assertTrustedMemexUploadUrl(guarded.finalUrl, "Memex final upload URL");
3802
3406
  if (!guarded.response.ok) throw new Error(`Upload failed: ${guarded.response.status}`);
3803
3407
  } finally {
3804
- await releaseUploadResponse(guarded);
3408
+ await release?.();
3805
3409
  }
3806
3410
  return { url: assertTrustedMemexUploadUrl(hostedUrl, "Memex hosted URL") };
3807
3411
  }
3808
3412
  if (!hasCustomS3Creds(credentials)) throw new Error("No storage credentials configured");
3413
+ const endpoint = new URL(prefixEndpoint(credentials.endpoint));
3809
3414
  const client = new S3Client({
3810
- endpoint: prefixEndpoint(credentials.endpoint),
3415
+ endpoint: {
3416
+ protocol: endpoint.protocol.slice(0, -1),
3417
+ hostname: endpoint.host,
3418
+ path: endpoint.pathname || "/"
3419
+ },
3811
3420
  region: storageConfig.region || "us-east-1",
3812
3421
  credentials: {
3813
3422
  accessKeyId: credentials.accessKeyId,
@@ -3820,16 +3429,20 @@ async function uploadFile(params) {
3820
3429
  "Content-Type": contentType,
3821
3430
  "x-amz-acl": "public-read"
3822
3431
  };
3823
- const signedUrl = await getSignedUrl(client, new PutObjectCommand({
3432
+ const command = new PutObjectCommand({
3824
3433
  Bucket: storageConfig.currentBucket,
3825
3434
  Key: fileKey,
3826
3435
  ContentType: headers["Content-Type"],
3827
3436
  CacheControl: headers["Cache-Control"],
3828
3437
  ACL: "public-read"
3829
- }), { expiresIn: 3600 });
3830
- let guarded;
3438
+ });
3439
+ const signedUrl = await getSignedUrl(client, command, {
3440
+ expiresIn: 3600,
3441
+ signableHeaders: new Set(Object.keys(headers))
3442
+ });
3443
+ let release;
3831
3444
  try {
3832
- guarded = await fetchWithSsrFGuard({
3445
+ const guarded = await fetchWithSsrFGuard({
3833
3446
  url: signedUrl,
3834
3447
  init: {
3835
3448
  method: "PUT",
@@ -3839,14 +3452,14 @@ async function uploadFile(params) {
3839
3452
  auditContext: "tlon-custom-s3-upload",
3840
3453
  capture: false,
3841
3454
  maxRedirects: 0,
3842
- policy: privateNetworkPolicy,
3843
- timeoutMs: TLON_UPLOAD_TIMEOUT_MS
3455
+ policy: privateNetworkPolicy
3844
3456
  });
3457
+ release = guarded.release;
3845
3458
  if (!guarded.response.ok) throw new Error(`Upload failed: ${guarded.response.status}`);
3846
3459
  } finally {
3847
- await releaseUploadResponse(guarded);
3460
+ await release?.();
3848
3461
  }
3849
- 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") };
3850
3463
  }
3851
3464
  //#endregion
3852
3465
  //#region extensions/tlon/src/urbit/upload.ts
@@ -3909,7 +3522,7 @@ async function createHttpPokeApi(params) {
3909
3522
  method: "PUT",
3910
3523
  headers: {
3911
3524
  "Content-Type": "application/json",
3912
- Cookie: expectDefined(cookie.split(";").at(0), "cookie first segment")
3525
+ Cookie: cookie.split(";")[0]
3913
3526
  },
3914
3527
  body: JSON.stringify([pokeData])
3915
3528
  },
@@ -3918,7 +3531,7 @@ async function createHttpPokeApi(params) {
3918
3531
  });
3919
3532
  try {
3920
3533
  if (!response.ok && response.status !== 204) {
3921
- const errorText = await readResponseTextLimited(response, 16 * 1024);
3534
+ const errorText = await readResponseTextLimited(response, 16384);
3922
3535
  throw new Error(`Poke failed: ${response.status} - ${errorText}`);
3923
3536
  }
3924
3537
  return pokeId;
@@ -4028,8 +3641,8 @@ const tlonRuntimeOutbound = {
4028
3641
  });
4029
3642
  }
4030
3643
  };
4031
- async function probeTlonAccount(account, timeoutMs) {
4032
- return await runChannelProbe(timeoutMs, async () => {
3644
+ async function probeTlonAccount(account) {
3645
+ try {
4033
3646
  const ssrfPolicy = ssrfPolicyFromDangerouslyAllowPrivateNetwork(account.dangerouslyAllowPrivateNetwork);
4034
3647
  const cookie = await authenticate(account.url, account.code, { ssrfPolicy });
4035
3648
  const { response, release } = await urbitFetch({
@@ -4050,13 +3663,14 @@ async function probeTlonAccount(account, timeoutMs) {
4050
3663
  };
4051
3664
  return { ok: true };
4052
3665
  } finally {
4053
- if (!response.bodyUsed) await response.body?.cancel().catch(() => void 0);
4054
3666
  await release();
4055
3667
  }
4056
- }, (error) => ({
4057
- ok: false,
4058
- error: error?.message ?? String(error)
4059
- }));
3668
+ } catch (error) {
3669
+ return {
3670
+ ok: false,
3671
+ error: error?.message ?? String(error)
3672
+ };
3673
+ }
4060
3674
  }
4061
3675
  async function startTlonGatewayAccount(ctx) {
4062
3676
  const account = ctx.account;