@openclaw/tlon 2026.11.3 → 2026.11.5-beta.2

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,20 +1,20 @@
1
1
  import { i as __reExport, r as __exportAll } from "./doctor-contract-bInPRAQZ.mjs";
2
2
  import { createDedupeCache, createLoggerBackedRuntime } from "../runtime-api.js";
3
- import { c as resolveTlonAccount, d as parseChannelNest, f as parseTlonTarget, l as formatTargetHint, o as validateUrbitBaseUrl, u as normalizeShip } from "./setup-core-kO8u8noA.mjs";
3
+ import { c as resolveTlonAccount, d as parseChannelNest, f as parseTlonTarget, l as formatTargetHint, o as validateUrbitBaseUrl, u as normalizeShip } from "./setup-core-Cfw9JPWJ.mjs";
4
4
  import { t as getTlonRuntime } from "./runtime-Ck3lNvST.mjs";
5
- import { t as tlonSetupWizard } from "./setup-surface-Byac6RoF.mjs";
5
+ import { t as tlonSetupWizard } from "./setup-surface-C0_CutPR.mjs";
6
6
  import { fetchWithSsrFGuard, ssrfPolicyFromDangerouslyAllowPrivateNetwork } from "openclaw/plugin-sdk/ssrf-runtime";
7
7
  import { bindIngressLifecycleToReplyOptions, createArmableStallWatchdog, createChannelIngressError, createChannelIngressMonitor, createMessageReceiptFromOutboundResults, waitUntilAbort } from "openclaw/plugin-sdk/channel-outbound";
8
- import { expectDefined } from "openclaw/plugin-sdk/expect-runtime";
9
8
  import { asBoolean, asFiniteNumber, asNullableRecord, filterStringEntries, normalizeLowercaseStringOrEmpty, normalizeNullableString, readStringField, uniqueStrings } from "openclaw/plugin-sdk/string-coerce-runtime";
9
+ import { expectDefined } from "openclaw/plugin-sdk/expect-runtime";
10
10
  import crypto, { randomBytes, randomUUID } from "node:crypto";
11
- import { readProviderJsonResponse, readResponseTextLimited } from "openclaw/plugin-sdk/provider-http";
12
11
  import { escapeRegExp, runChannelProbe, sliceUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
13
12
  import { resolveHumanDelayConfig } from "openclaw/plugin-sdk/agent-runtime";
14
13
  import { createChannelInboundEnvelopeBuilderAsync, formatAgentEnvelope, formatInboundMediaUnavailableText, resolveEnvelopeFormatOptions } from "openclaw/plugin-sdk/channel-inbound";
15
14
  import { collectErrorGraphCandidates, formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
16
15
  import { retryAsync } from "openclaw/plugin-sdk/retry-runtime";
17
16
  import { sleepWithAbort } from "openclaw/plugin-sdk/runtime-env";
17
+ import { readProviderJsonResponse, readResponseTextLimited } from "openclaw/plugin-sdk/provider-http";
18
18
  import { redactToolPayloadText } from "openclaw/plugin-sdk/logging-core";
19
19
  import { da, scot } from "@urbit/aura";
20
20
  import { Readable } from "node:stream";
@@ -155,33 +155,24 @@ function redactUrbitErrorText(text) {
155
155
  }
156
156
  //#endregion
157
157
  //#region extensions/tlon/src/urbit/errors.ts
158
- var UrbitError = class extends Error {
159
- constructor(code, message, options) {
160
- super(message, options);
161
- this.name = "UrbitError";
162
- this.code = code;
163
- }
164
- };
165
- var UrbitUrlError = class extends UrbitError {
166
- constructor(message, options) {
167
- super("invalid_url", message, options);
158
+ var UrbitUrlError = class extends Error {
159
+ constructor(message) {
160
+ super(message);
168
161
  this.name = "UrbitUrlError";
169
162
  }
170
163
  };
171
- var UrbitHttpError = class extends UrbitError {
164
+ var UrbitHttpError = class extends Error {
172
165
  constructor(params) {
173
166
  const bodyText = params.bodyText ? redactUrbitErrorText(params.bodyText) : void 0;
174
167
  const suffix = bodyText ? ` - ${bodyText}` : "";
175
- super("http_error", `${params.operation} failed: ${params.status}${suffix}`, { cause: params.cause });
168
+ super(`${params.operation} failed: ${params.status}${suffix}`);
176
169
  this.name = "UrbitHttpError";
177
170
  this.status = params.status;
178
- this.operation = params.operation;
179
- this.bodyText = bodyText;
180
171
  }
181
172
  };
182
- var UrbitAuthError = class extends UrbitError {
183
- constructor(code, message, options) {
184
- super(code, message, options);
173
+ var UrbitAuthError = class extends Error {
174
+ constructor(message) {
175
+ super(message);
185
176
  this.name = "UrbitAuthError";
186
177
  }
187
178
  };
@@ -193,14 +184,12 @@ async function urbitFetch(params) {
193
184
  const url = new URL(params.path, validated.baseUrl).toString();
194
185
  const guarded = await fetchWithSsrFGuard({
195
186
  url,
196
- fetchImpl: params.fetchImpl,
197
187
  beforeRequest: params.beforeRequest,
198
188
  init: params.init,
199
189
  timeoutMs: params.timeoutMs,
200
190
  maxRedirects: params.maxRedirects,
201
191
  signal: params.signal,
202
192
  policy: params.ssrfPolicy,
203
- lookupFn: params.lookupFn,
204
193
  auditContext: params.auditContext
205
194
  });
206
195
  return {
@@ -224,18 +213,16 @@ async function authenticate(url, code, options = {}) {
224
213
  body: new URLSearchParams({ password: code }).toString()
225
214
  },
226
215
  ssrfPolicy: options.ssrfPolicy,
227
- lookupFn: options.lookupFn,
228
- fetchImpl: options.fetchImpl,
229
216
  beforeRequest: options.beforeRequest,
230
217
  timeoutMs: 15e3,
231
218
  maxRedirects: 3,
232
219
  auditContext: "tlon-urbit-login"
233
220
  });
234
221
  try {
235
- if (!response.ok) throw new UrbitAuthError("auth_failed", `Login failed with status ${response.status}`);
222
+ if (!response.ok) throw new UrbitAuthError(`Login failed with status ${response.status}`);
236
223
  await readResponseTextLimited(response, MAX_AUTH_BODY_DRAIN_BYTES).catch(() => void 0);
237
224
  const cookie = response.headers.get("set-cookie");
238
- if (!cookie) throw new UrbitAuthError("missing_cookie", "No authentication cookie received");
225
+ if (!cookie) throw new UrbitAuthError("No authentication cookie received");
239
226
  return cookie;
240
227
  } finally {
241
228
  await release();
@@ -251,7 +238,6 @@ function getUrbitContext(url, ship) {
251
238
  if (!validated.ok) throw new UrbitUrlError(validated.error);
252
239
  return {
253
240
  baseUrl: validated.baseUrl,
254
- hostname: validated.hostname,
255
241
  ship: (ship?.replace(/^~/, "") ?? validated.hostname.split(".")[0] ?? validated.hostname).trim()
256
242
  };
257
243
  }
@@ -424,9 +410,6 @@ const MARKDOWN_LIST_ITEM_PATTERN = /^([ \t]*)([-+*]|\d{1,9}[.)])(?:([ \t]+)(.*))
424
410
  function isMarkdownThematicBreak(text) {
425
411
  return /^(?:(?:\*\s*){3,}|(?:-\s*){3,}|(?:_\s*){3,})$/.test(text);
426
412
  }
427
- function startsListBlockSyntax(text) {
428
- return /^(`{3,}|~{3,})/.test(text) || text.startsWith(">") || /^#{1,6}(?:\s|$)/.test(text) || isMarkdownThematicBreak(text) || /^(?:[-+*]|\d{1,9}[.)])(?:\s|$)/.test(text);
429
- }
430
413
  function whitespaceColumns(text, startColumn = 0) {
431
414
  let column = startColumn;
432
415
  for (const char of text) column += char === " " ? 4 - column % 4 : 1;
@@ -457,7 +440,7 @@ function parseMarkdownListItem(line) {
457
440
  markerKey: markerType === "ordered" ? marker.slice(-1) : marker,
458
441
  ...markerType === "ordered" ? { orderedStart: Number.parseInt(marker, 10) } : {},
459
442
  hasSourceBody: sourceBody.length > 0,
460
- hasBlockBody: sourceBody.length > 0 && (contentIndent - markerEnd >= 5 || startsListBlockSyntax(sourceBody)),
443
+ hasBlockBody: sourceBody.length > 0 && (contentIndent - markerEnd >= 5 || /^(`{3,}|~{3,})/.test(sourceBody) || sourceBody.startsWith(">") || /^#{1,6}(?:\s|$)/.test(sourceBody) || isMarkdownThematicBreak(sourceBody) || /^(?:[-+*]|\d{1,9}[.)])(?:\s|$)/.test(sourceBody)),
461
444
  hasImages: imageBlocks.length > 0,
462
445
  content: inlines,
463
446
  ...checked === void 0 ? {} : { checked }
@@ -478,19 +461,16 @@ function listItemContent(item) {
478
461
  function canInterruptWithListItem(item) {
479
462
  return item.hasSourceBody && (item.markerType === "unordered" || item.orderedStart === 1);
480
463
  }
481
- function parseListingBlock(lines, startIndex) {
482
- const first = parseMarkdownListItem(expectDefined(lines[startIndex], "list start line"));
483
- if (!first) return;
484
- if (first.indent >= 4 || first.markerType === "ordered" && first.orderedStart !== 1) return;
485
- function parseLevel(index, minIndent, markerKey) {
486
- const firstItem = parseMarkdownListItem(expectDefined(lines[index], "list level start"));
487
- if (!firstItem || firstItem.indent < minIndent || firstItem.indent > minIndent + 3 || firstItem.markerType === "ordered" && firstItem.orderedStart !== 1) return;
464
+ function parseListingBlock(lines, startIndex, first) {
465
+ if (!first || first.indent >= 4 || first.markerType === "ordered" && first.orderedStart !== 1) return;
466
+ function parseLevel(index, minIndent, firstItem) {
488
467
  const items = [];
468
+ const markerKey = firstItem.markerKey;
489
469
  const markerType = firstItem.markerType;
490
470
  let allTasks = true;
491
471
  let cursor = index;
492
472
  while (cursor < lines.length) {
493
- const item = parseMarkdownListItem(expectDefined(lines[cursor], "list line index"));
473
+ const item = cursor === index ? firstItem : parseMarkdownListItem(expectDefined(lines[cursor], "list line index"));
494
474
  if (!item || item.indent < minIndent || item.indent > minIndent + 3 || item.markerKey !== markerKey) break;
495
475
  if (item.hasBlockBody || item.hasImages) return;
496
476
  allTasks &&= item.checked !== void 0;
@@ -523,7 +503,7 @@ function parseListingBlock(lines, startIndex) {
523
503
  if (child && child.indent >= item.contentIndent && !canInterruptWithListItem(child)) return;
524
504
  if (child && child.indent > item.indent) {
525
505
  if (child.indent < item.contentIndent || child.indent >= item.contentIndent + 4) return;
526
- const nested = parseLevel(cursor, item.contentIndent, child.markerKey);
506
+ const nested = parseLevel(cursor, item.contentIndent, child);
527
507
  if (!nested) return;
528
508
  items.push({ list: {
529
509
  type: nested.type,
@@ -546,7 +526,7 @@ function parseListingBlock(lines, startIndex) {
546
526
  nextIndex: cursor
547
527
  };
548
528
  }
549
- const parsed = parseLevel(startIndex, 0, first.markerKey);
529
+ const parsed = parseLevel(startIndex, 0, first);
550
530
  if (!parsed) return;
551
531
  return {
552
532
  verses: [{ block: { listing: { list: {
@@ -621,7 +601,7 @@ function markdownToStory(markdown) {
621
601
  continue;
622
602
  }
623
603
  const preservesLooseList = preservedListMarkerKey !== void 0 && lineListItem?.markerKey === preservedListMarkerKey;
624
- const listing = preservesLooseList ? void 0 : parseListingBlock(lines, i);
604
+ const listing = preservesLooseList ? void 0 : parseListingBlock(lines, i, lineListItem);
625
605
  if (listing) {
626
606
  story.push(...listing.verses);
627
607
  i = listing.nextIndex;
@@ -636,7 +616,7 @@ function markdownToStory(markdown) {
636
616
  if (paragraphLine === void 0 || paragraphLine.trim() === "" || startsTopLevelStoryBlock(paragraphLine)) break;
637
617
  if (!preserveListText && MARKDOWN_LIST_ITEM_PATTERN.test(paragraphLine)) {
638
618
  const item = parseMarkdownListItem(paragraphLine);
639
- const candidate = parseListingBlock(lines, i);
619
+ const candidate = parseListingBlock(lines, i, item);
640
620
  if (item?.hasSourceBody === true && candidate) break;
641
621
  preserveListText = true;
642
622
  if (item) preservedListMarkerKey = item.markerKey;
@@ -776,8 +756,6 @@ async function putUrbitChannel(deps, params) {
776
756
  body: JSON.stringify(params.body)
777
757
  },
778
758
  ssrfPolicy: deps.ssrfPolicy,
779
- lookupFn: deps.lookupFn,
780
- fetchImpl: deps.fetchImpl,
781
759
  timeoutMs: params.timeoutMs,
782
760
  auditContext: params.auditContext,
783
761
  beforeRequest: params.beforeRequest
@@ -796,7 +774,8 @@ async function pokeUrbitChannel(deps, params) {
796
774
  json: params.json
797
775
  }],
798
776
  auditContext: params.auditContext,
799
- timeoutMs: 3e4
777
+ timeoutMs: params.timeoutMs,
778
+ beforeRequest: params.beforeRequest
800
779
  });
801
780
  try {
802
781
  if (!response.ok && response.status !== 204) {
@@ -822,8 +801,6 @@ async function scryUrbitPath(deps, params) {
822
801
  headers: { Cookie: deps.cookie }
823
802
  },
824
803
  ssrfPolicy: deps.ssrfPolicy,
825
- lookupFn: deps.lookupFn,
826
- fetchImpl: deps.fetchImpl,
827
804
  beforeRequest: deps.beforeRequest,
828
805
  timeoutMs: 3e4,
829
806
  auditContext: params.auditContext
@@ -913,8 +890,6 @@ var UrbitSSEClient = class {
913
890
  this.onReconnect = options.onReconnect ?? null;
914
891
  this.logger = options.logger ?? {};
915
892
  this.ssrfPolicy = options.ssrfPolicy;
916
- this.lookupFn = options.lookupFn;
917
- this.fetchImpl = options.fetchImpl;
918
893
  }
919
894
  channelRequestContext() {
920
895
  return {
@@ -922,9 +897,7 @@ var UrbitSSEClient = class {
922
897
  cookie: this.cookie,
923
898
  ship: this.ship,
924
899
  channelId: this.channelId,
925
- ssrfPolicy: this.ssrfPolicy,
926
- lookupFn: this.lookupFn,
927
- fetchImpl: this.fetchImpl
900
+ ssrfPolicy: this.ssrfPolicy
928
901
  };
929
902
  }
930
903
  resetChannelIdentity() {
@@ -1002,8 +975,6 @@ var UrbitSSEClient = class {
1002
975
  }
1003
976
  },
1004
977
  ssrfPolicy: this.ssrfPolicy,
1005
- lookupFn: this.lookupFn,
1006
- fetchImpl: this.fetchImpl,
1007
978
  signal: AbortSignal.any([controller.signal, this.reconnectAbortController.signal]),
1008
979
  beforeRequest: () => this.reconnectAbortController.signal.throwIfAborted(),
1009
980
  auditContext: "tlon-urbit-sse-stream"
@@ -1155,17 +1126,20 @@ var UrbitSSEClient = class {
1155
1126
  if (eventId === null || eventId <= this.lastAcknowledgedEventId) return;
1156
1127
  this.lastHeardEventId = Math.max(this.lastHeardEventId, eventId);
1157
1128
  if (this.lastHeardEventId - this.lastAcknowledgedEventId <= this.ackThreshold) return;
1158
- this.logger.log?.(`[SSE] Acking event ${this.lastHeardEventId} (last acked: ${this.lastAcknowledgedEventId})`);
1159
1129
  await this.ack(this.lastHeardEventId);
1160
1130
  }
1161
1131
  async poke(params) {
1162
1132
  return await pokeUrbitChannel(this.channelRequestContext(), {
1163
1133
  ...params,
1164
- auditContext: "tlon-urbit-poke"
1134
+ auditContext: "tlon-urbit-poke",
1135
+ timeoutMs: 3e4
1165
1136
  });
1166
1137
  }
1167
- async scry(path) {
1168
- return await scryUrbitPath(this.channelRequestContext(), {
1138
+ async scry(path, beforeRequest) {
1139
+ return await scryUrbitPath({
1140
+ ...this.channelRequestContext(),
1141
+ beforeRequest
1142
+ }, {
1169
1143
  path,
1170
1144
  auditContext: "tlon-urbit-scry"
1171
1145
  });
@@ -1234,33 +1208,17 @@ var UrbitSSEClient = class {
1234
1208
  async close() {
1235
1209
  this.stopReceiving();
1236
1210
  try {
1237
- const unsubscribes = this.subscriptions.map((sub) => ({
1238
- id: sub.id,
1239
- action: "unsubscribe",
1240
- subscription: sub.id
1241
- }));
1242
- {
1243
- const { release } = await putUrbitChannel(this.channelRequestContext(), {
1244
- body: unsubscribes,
1245
- timeoutMs: 3e4,
1246
- auditContext: "tlon-urbit-unsubscribe"
1247
- });
1248
- await release();
1249
- }
1250
- {
1251
- const { release } = await urbitFetch({
1252
- baseUrl: this.url,
1253
- path: `/~/channel/${this.channelId}`,
1254
- init: {
1255
- method: "DELETE",
1256
- headers: { Cookie: this.cookie }
1257
- },
1258
- ssrfPolicy: this.ssrfPolicy,
1259
- lookupFn: this.lookupFn,
1260
- fetchImpl: this.fetchImpl,
1261
- timeoutMs: 3e4,
1262
- auditContext: "tlon-urbit-channel-close"
1211
+ const { response, release } = await putUrbitChannel(this.channelRequestContext(), {
1212
+ body: [{ action: "delete" }],
1213
+ timeoutMs: 3e4,
1214
+ auditContext: "tlon-urbit-channel-close"
1215
+ });
1216
+ try {
1217
+ if (!response.ok) throw new UrbitHttpError({
1218
+ operation: "Channel close",
1219
+ status: response.status
1263
1220
  });
1221
+ } finally {
1264
1222
  await release();
1265
1223
  }
1266
1224
  } catch (error) {
@@ -1284,12 +1242,10 @@ var UrbitSSEClient = class {
1284
1242
  };
1285
1243
  //#endregion
1286
1244
  //#region extensions/tlon/src/monitor/approval.ts
1287
- function generateApprovalId(type) {
1288
- return `${type}-${Date.now()}-${randomBytes(3).toString("hex")}`;
1289
- }
1290
1245
  function createPendingApproval(params) {
1246
+ const timestamp = Date.now();
1291
1247
  return {
1292
- id: generateApprovalId(params.type),
1248
+ id: `${params.type}-${timestamp}-${randomBytes(3).toString("hex")}`,
1293
1249
  type: params.type,
1294
1250
  requestingShip: params.requestingShip,
1295
1251
  ...params.clubId !== void 0 ? { clubId: params.clubId } : {},
@@ -1298,7 +1254,7 @@ function createPendingApproval(params) {
1298
1254
  groupFlag: params.groupFlag,
1299
1255
  messagePreview: params.messagePreview != null ? sliceUtf16Safe(params.messagePreview, 0, 100) : void 0,
1300
1256
  originalMessage: params.originalMessage,
1301
- timestamp: Date.now()
1257
+ timestamp
1302
1258
  };
1303
1259
  }
1304
1260
  function truncate(text, maxLength) {
@@ -1770,14 +1726,6 @@ function renderInlineItem(item, topLevel = false, depth = 0) {
1770
1726
  function extractInlineText(items, depth = 0) {
1771
1727
  return items.map((item) => renderInlineItem(item, false, depth)).join("");
1772
1728
  }
1773
- function extractMessageTextSafely(content, runtime) {
1774
- try {
1775
- return extractMessageText(content);
1776
- } catch (error) {
1777
- runtime.log?.(`[tlon] Failed to extract message text: ${formatErrorMessage(error)}`);
1778
- return "";
1779
- }
1780
- }
1781
1729
  function extractMessageText(content) {
1782
1730
  if (!Array.isArray(content)) return "";
1783
1731
  return content.map((verse) => {
@@ -1864,6 +1812,8 @@ function formatSummarizationHistoryText(history, cfg) {
1864
1812
  //#region extensions/tlon/src/monitor/cites.ts
1865
1813
  const CITE_PATH_SEGMENT_RE = /^[A-Za-z0-9._~-]+$/;
1866
1814
  const CITE_PATH_NORMALIZATION_BASE = "https://tlon.invalid";
1815
+ const CITATION_SCOPE_SKIP_LOG = "[tlon] Skipping cited post: citation is outside explicit channel scope";
1816
+ var CitationScopeChangedError = class extends Error {};
1867
1817
  function isSafeCitePathSegment(segment) {
1868
1818
  if (segment === "." || segment === "..") return false;
1869
1819
  return CITE_PATH_SEGMENT_RE.test(segment);
@@ -1883,7 +1833,7 @@ function buildCitedPostScryPath(nest, postId) {
1883
1833
  if (new URL(scryPath, CITE_PATH_NORMALIZATION_BASE).pathname !== scryPath) return null;
1884
1834
  return scryPath;
1885
1835
  }
1886
- async function resolveTlonCitations(content, api, runtime) {
1836
+ async function resolveTlonCitations(content, canExpandNest, api, runtime) {
1887
1837
  if (!Array.isArray(content)) return "";
1888
1838
  const resolved = [];
1889
1839
  for (const verse of content) {
@@ -1893,6 +1843,10 @@ async function resolveTlonCitations(content, api, runtime) {
1893
1843
  const whereMatch = readStringField(chan, "where")?.match(/\/msg\/(~[a-z-]+)\/(.+)/);
1894
1844
  const postId = whereMatch?.[2];
1895
1845
  if (!nest || !postId) continue;
1846
+ if (!canExpandNest(nest)) {
1847
+ runtime.log?.(CITATION_SCOPE_SKIP_LOG);
1848
+ continue;
1849
+ }
1896
1850
  const scryPath = buildCitedPostScryPath(nest, postId);
1897
1851
  if (!scryPath) {
1898
1852
  runtime.log?.("[tlon] Skipping cited post: citation does not name a channel post");
@@ -1900,11 +1854,21 @@ async function resolveTlonCitations(content, api, runtime) {
1900
1854
  }
1901
1855
  try {
1902
1856
  runtime.log?.(`[tlon] Fetching cited post: ${scryPath}`);
1903
- const data = asNullableRecord(await api.scry(scryPath));
1857
+ const data = asNullableRecord(await api.scry(scryPath, () => {
1858
+ if (!canExpandNest(nest)) throw new CitationScopeChangedError();
1859
+ }));
1860
+ if (!canExpandNest(nest)) {
1861
+ runtime.log?.(CITATION_SCOPE_SKIP_LOG);
1862
+ continue;
1863
+ }
1904
1864
  const essay = asNullableRecord(data?.essay);
1905
1865
  const text = essay?.content ? extractMessageText(essay.content) : "";
1906
1866
  if (text) resolved.push(`> ${whereMatch?.[1] || "unknown"} wrote: ${text}`);
1907
1867
  } catch (err) {
1868
+ if (err instanceof CitationScopeChangedError) {
1869
+ runtime.log?.(CITATION_SCOPE_SKIP_LOG);
1870
+ continue;
1871
+ }
1908
1872
  runtime.log?.(`[tlon] Failed to fetch cited post: ${String(err)}`);
1909
1873
  }
1910
1874
  }
@@ -1954,18 +1918,17 @@ function formatUd(id) {
1954
1918
  return chunks.toReversed().join(".");
1955
1919
  }
1956
1920
  function createHistoryEntryFromMemo(params) {
1957
- const { memo, seal, fallbackId } = params;
1921
+ const { memo } = params;
1958
1922
  return {
1959
1923
  author: typeof memo?.author === "string" ? memo.author : "unknown",
1960
1924
  content: extractMessageText(memo?.content || []),
1961
- timestamp: typeof memo?.sent === "number" ? memo.sent : Date.now(),
1962
- id: typeof seal?.id === "string" ? seal.id : typeof fallbackId === "string" ? fallbackId : void 0
1925
+ timestamp: typeof memo?.sent === "number" ? memo.sent : Date.now()
1963
1926
  };
1964
1927
  }
1965
1928
  const MAX_CACHED_MESSAGES = 100;
1966
- async function fetchChannelHistory(api, channelNest, count = 50, runtime) {
1929
+ async function fetchChannelHistory(api, channelNest, runtime) {
1967
1930
  try {
1968
- const scryPath = `/channels/v4/${channelNest}/posts/newest/${count}/outline.json`;
1931
+ const scryPath = `/channels/v4/${channelNest}/posts/newest/50/outline.json`;
1969
1932
  runtime?.log?.(`[tlon] Fetching history: ${scryPath}`);
1970
1933
  const data = await api.scry(scryPath);
1971
1934
  if (!data) return [];
@@ -1974,10 +1937,7 @@ async function fetchChannelHistory(api, channelNest, count = 50, runtime) {
1974
1937
  const itemRecord = asNullableRecord(item);
1975
1938
  const replyPost = asNullableRecord(itemRecord?.["r-post"]);
1976
1939
  const replyPostSet = asNullableRecord(replyPost?.set);
1977
- return createHistoryEntryFromMemo({
1978
- memo: asNullableRecord(itemRecord?.essay) ?? asNullableRecord(replyPostSet?.essay),
1979
- seal: asNullableRecord(itemRecord?.seal) ?? asNullableRecord(replyPostSet?.seal)
1980
- });
1940
+ return createHistoryEntryFromMemo({ memo: asNullableRecord(itemRecord?.essay) ?? asNullableRecord(replyPostSet?.essay) });
1981
1941
  }).filter((msg) => msg.content);
1982
1942
  runtime?.log?.(`[tlon] Extracted ${messages.length} messages from history`);
1983
1943
  return messages;
@@ -1995,14 +1955,14 @@ function createChannelHistoryCache() {
1995
1955
  if (cache.length > MAX_CACHED_MESSAGES) cache.pop();
1996
1956
  messageCache.set(channelNest, cache);
1997
1957
  },
1998
- async getChannelHistory(api, channelNest, count = 50, runtime) {
1958
+ async getChannelHistory(api, channelNest, runtime) {
1999
1959
  const cache = messageCache.get(channelNest) ?? [];
2000
- if (cache.length >= count) {
1960
+ if (cache.length >= 50) {
2001
1961
  runtime?.log?.(`[tlon] Using cached messages (${cache.length} available)`);
2002
- return cache.slice(0, count);
1962
+ return cache.slice(0, 50);
2003
1963
  }
2004
- runtime?.log?.(`[tlon] Cache has ${cache.length} messages, need ${count}, fetching from scry...`);
2005
- return await fetchChannelHistory(api, channelNest, count, runtime);
1964
+ runtime?.log?.(`[tlon] Cache has ${cache.length} messages, need 50, fetching from scry...`);
1965
+ return await fetchChannelHistory(api, channelNest, runtime);
2006
1966
  }
2007
1967
  };
2008
1968
  }
@@ -2017,11 +1977,11 @@ async function fetchThreadRootAuthor(api, channelNest, parentId, runtime) {
2017
1977
  return null;
2018
1978
  }
2019
1979
  }
2020
- async function fetchThreadHistory(api, channelNest, parentId, count = 50, runtime) {
1980
+ async function fetchThreadHistory(api, channelNest, parentId, runtime) {
2021
1981
  try {
2022
1982
  const formattedParentId = formatUd(parentId);
2023
1983
  runtime?.log?.(`[tlon] Thread history - parentId: ${parentId} -> formatted: ${formattedParentId}`);
2024
- const scryPath = `/channels/v4/${channelNest}/posts/post/id/${formattedParentId}/replies/newest/${count}.json`;
1984
+ const scryPath = `/channels/v4/${channelNest}/posts/post/id/${formattedParentId}/replies/newest/20.json`;
2025
1985
  runtime?.log?.(`[tlon] Fetching thread history: ${scryPath}`);
2026
1986
  const data = await api.scry(scryPath);
2027
1987
  if (!data) {
@@ -2041,11 +2001,7 @@ async function fetchThreadHistory(api, channelNest, parentId, count = 50, runtim
2041
2001
  const itemRecord = asNullableRecord(item);
2042
2002
  const replyRecord = asNullableRecord(itemRecord?.["r-reply"]);
2043
2003
  const replySet = asNullableRecord(replyRecord?.set);
2044
- return createHistoryEntryFromMemo({
2045
- memo: asNullableRecord(itemRecord?.memo) ?? asNullableRecord(replySet?.memo) ?? itemRecord,
2046
- seal: asNullableRecord(itemRecord?.seal) ?? asNullableRecord(replySet?.seal),
2047
- fallbackId: itemRecord?.id
2048
- });
2004
+ return createHistoryEntryFromMemo({ memo: asNullableRecord(itemRecord?.memo) ?? asNullableRecord(replySet?.memo) ?? itemRecord });
2049
2005
  }).filter((msg) => msg.content);
2050
2006
  runtime?.log?.(`[tlon] Extracted ${messages.length} thread replies from history`);
2051
2007
  return messages;
@@ -2061,10 +2017,7 @@ async function fetchThreadHistory(api, channelNest, parentId, count = 50, runtim
2061
2017
  if (typeof dataMeta?.replyCount === "number" && dataMeta.replyCount > 0 && repliesValue) {
2062
2018
  const messages = (Array.isArray(repliesValue) ? repliesValue : Object.values(repliesValue)).map((reply) => {
2063
2019
  const replyRecord = asNullableRecord(reply);
2064
- return createHistoryEntryFromMemo({
2065
- memo: asNullableRecord(replyRecord?.memo),
2066
- seal: asNullableRecord(replyRecord?.seal)
2067
- });
2020
+ return createHistoryEntryFromMemo({ memo: asNullableRecord(replyRecord?.memo) });
2068
2021
  }).filter((msg) => msg.content);
2069
2022
  runtime?.log?.(`[tlon] Extracted ${messages.length} replies from post data`);
2070
2023
  return messages;
@@ -2078,7 +2031,6 @@ async function fetchThreadHistory(api, channelNest, parentId, count = 50, runtim
2078
2031
  //#endregion
2079
2032
  //#region extensions/tlon/src/monitor/ingress.ts
2080
2033
  const TLON_INGRESS_PAYLOAD_VERSION = 1;
2081
- const TLON_INGRESS_POLL_INTERVAL_MS = 1e3;
2082
2034
  const TlonIngressPermanentError = createChannelIngressError("TlonIngressPermanentError", { withReason: true });
2083
2035
  var TlonIngressUnserializableEventError = class extends Error {
2084
2036
  constructor(cause) {
@@ -2094,39 +2046,35 @@ function serializeTlonIngressEvent(event) {
2094
2046
  throw error;
2095
2047
  }
2096
2048
  }
2097
- function inspectChannelsEvent(event) {
2049
+ function decodeTlonChannelsEvent(event) {
2098
2050
  const envelope = asNullableRecord(event);
2099
- const nest = normalizeNullableString(envelope?.nest);
2100
- const response = asNullableRecord(envelope?.response);
2101
- const post = asNullableRecord(response?.post);
2051
+ const nest = readStringField(envelope, "nest");
2052
+ const post = asNullableRecord(asNullableRecord(envelope?.response)?.post);
2102
2053
  const rPost = asNullableRecord(post?.["r-post"]);
2103
2054
  const set = asNullableRecord(rPost?.set);
2104
2055
  const reply = asNullableRecord(rPost?.reply);
2105
- const rReply = asNullableRecord(reply?.["r-reply"]);
2106
- const replySet = asNullableRecord(rReply?.set);
2107
- if (!nest || !asNullableRecord(set?.essay) && !asNullableRecord(replySet?.memo)) return null;
2108
- const eventId = normalizeNullableString(asNullableRecord(replySet?.memo) ? reply?.id : post?.id);
2109
- return eventId ? {
2110
- eventId,
2111
- laneKey: `group:${nest}`
2112
- } : null;
2113
- }
2114
- function inspectChatEvent(event) {
2115
- const envelope = asNullableRecord(event);
2116
- const response = asNullableRecord(envelope?.response);
2117
- const add = asNullableRecord(response?.add);
2118
- const essay = asNullableRecord(add?.essay);
2119
- const eventId = normalizeNullableString(envelope?.id);
2120
- if (!essay || !eventId) return null;
2121
- const whom = normalizeNullableString(asNullableRecord(envelope?.whom)?.ship);
2122
- const peer = normalizeNullableString(envelope?.whom) ?? whom ?? normalizeNullableString(essay.author);
2056
+ const replySet = asNullableRecord(asNullableRecord(reply?.["r-reply"])?.set);
2057
+ const memo = asNullableRecord(replySet?.memo);
2058
+ const content = memo ?? asNullableRecord(set?.essay);
2059
+ const messageId = readStringField(memo ? reply : post, "id");
2060
+ if (!nest || !messageId || !content) return null;
2123
2061
  return {
2124
- eventId,
2125
- laneKey: peer ? `direct:${peer}` : `event:${eventId}`
2062
+ nest,
2063
+ messageId,
2064
+ content,
2065
+ isThreadReply: Boolean(memo),
2066
+ messageSet: memo ? replySet : set
2126
2067
  };
2127
2068
  }
2128
- function inspectTlonIngressEvent(source, event) {
2129
- return source === "channels" ? inspectChannelsEvent(event) : inspectChatEvent(event);
2069
+ function decodeTlonChatEvent(event) {
2070
+ const envelope = asNullableRecord(event);
2071
+ const messageId = readStringField(envelope, "id");
2072
+ const essay = asNullableRecord(asNullableRecord(asNullableRecord(envelope?.response)?.add)?.essay);
2073
+ return envelope && messageId && essay ? {
2074
+ messageId,
2075
+ whom: envelope.whom,
2076
+ essay
2077
+ } : null;
2130
2078
  }
2131
2079
  function decodeTlonIngressPayload(payload, claimedId) {
2132
2080
  if (payload.source !== "channels" && payload.source !== "chat" || typeof payload.rawEvent !== "string") throw new TlonIngressPermanentError("invalid-event", `Tlon ingress row ${claimedId} has an invalid payload.`);
@@ -2164,8 +2112,27 @@ function resolveTlonIngressNonRetryableFailure(error) {
2164
2112
  }
2165
2113
  function createTlonIngressMonitor(options) {
2166
2114
  const monitor = createChannelIngressMonitor({
2167
- queue: options.queue ?? (() => getTlonRuntime().state.openChannelIngressQueue({ accountId: options.accountId })),
2168
- inspect: (raw) => inspectTlonIngressEvent(raw.source, raw.event),
2115
+ queue: () => getTlonRuntime().state.openChannelIngressQueue({ accountId: options.accountId }),
2116
+ inspect: ({ source, event }) => {
2117
+ if (source === "channels") {
2118
+ const message = decodeTlonChannelsEvent(event);
2119
+ const eventId = normalizeNullableString(message?.messageId);
2120
+ const nest = normalizeNullableString(message?.nest);
2121
+ return eventId && nest ? {
2122
+ eventId,
2123
+ laneKey: `group:${nest}`
2124
+ } : null;
2125
+ }
2126
+ const message = decodeTlonChatEvent(event);
2127
+ const eventId = normalizeNullableString(message?.messageId);
2128
+ if (!message || !eventId) return null;
2129
+ const whom = normalizeNullableString(asNullableRecord(message.whom)?.ship);
2130
+ const peer = normalizeNullableString(message.whom) ?? whom ?? normalizeNullableString(message.essay.author);
2131
+ return {
2132
+ eventId,
2133
+ laneKey: peer ? `direct:${peer}` : `event:${eventId}`
2134
+ };
2135
+ },
2169
2136
  payload: {
2170
2137
  version: TLON_INGRESS_PAYLOAD_VERSION,
2171
2138
  serialize: (raw, { receivedAt }) => ({
@@ -2182,7 +2149,7 @@ function createTlonIngressMonitor(options) {
2182
2149
  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.`)
2183
2150
  },
2184
2151
  deliver: (raw, lifecycle) => options.dispatch(raw.source, raw.event, lifecycle),
2185
- pollIntervalMs: options.pollIntervalMs ?? TLON_INGRESS_POLL_INTERVAL_MS,
2152
+ pollIntervalMs: 1e3,
2186
2153
  retention: {
2187
2154
  completedTtlMs: void 0,
2188
2155
  completedMaxEntries: 2e3,
@@ -2191,7 +2158,6 @@ function createTlonIngressMonitor(options) {
2191
2158
  appendRetryDelaysMs: [0],
2192
2159
  drain: {
2193
2160
  resolveNonRetryableFailure: resolveTlonIngressNonRetryableFailure,
2194
- ...options.adoptionStallTimeoutMs === void 0 ? {} : { adoptionStallTimeoutMs: options.adoptionStallTimeoutMs },
2195
2161
  onLog: (message) => options.runtime.log?.(`tlon ${message}`)
2196
2162
  },
2197
2163
  ...options.abortSignal ? { abortSignal: options.abortSignal } : {},
@@ -2228,8 +2194,7 @@ const TLON_MEDIA_FETCH_TIMEOUTS = {
2228
2194
  //#region extensions/tlon/src/monitor/media.ts
2229
2195
  const MAX_IMAGES_PER_MESSAGE = 8;
2230
2196
  /** Keeps Tlon's shipped path-duplicating prompt bytes paired with ordered facts. */
2231
- function buildTlonInboundMediaPrompt(messageText, attachments) {
2232
- const media = attachments.map((attachment) => ({ ...attachment }));
2197
+ function buildTlonInboundMediaPrompt(messageText, media) {
2233
2198
  if (media.length === 0) return {
2234
2199
  body: messageText,
2235
2200
  media
@@ -2239,31 +2204,25 @@ function buildTlonInboundMediaPrompt(messageText, attachments) {
2239
2204
  media
2240
2205
  };
2241
2206
  }
2242
- function extractImageBlocks(content) {
2243
- if (!Array.isArray(content)) return {
2244
- images: [],
2245
- unavailableCount: 0
2246
- };
2207
+ async function downloadMessageImages(content, maxBytes) {
2247
2208
  const images = [];
2209
+ const attachments = [];
2248
2210
  let unavailableCount = 0;
2249
- for (const verse of content) if (verse?.block?.image?.src) {
2250
- if (images.length >= MAX_IMAGES_PER_MESSAGE) {
2251
- unavailableCount++;
2252
- continue;
2211
+ if (Array.isArray(content)) {
2212
+ for (const verse of content) if (verse?.block?.image?.src) {
2213
+ if (images.length >= MAX_IMAGES_PER_MESSAGE) {
2214
+ unavailableCount++;
2215
+ continue;
2216
+ }
2217
+ images.push(verse.block.image.src);
2253
2218
  }
2254
- images.push(verse.block.image.src);
2255
2219
  }
2256
- return {
2257
- images,
2258
- unavailableCount
2259
- };
2260
- }
2261
- async function downloadMedia(url, maxBytes) {
2262
- try {
2220
+ for (const url of images) try {
2263
2221
  const parsedUrl = new URL(url);
2264
2222
  if (parsedUrl.protocol !== "http:" && parsedUrl.protocol !== "https:") {
2265
- console.warn(`[tlon-media] Rejected non-http(s) URL: ${url}`);
2266
- return null;
2223
+ console.warn("[tlon-media] Rejected non-http(s) media URL");
2224
+ unavailableCount++;
2225
+ continue;
2267
2226
  }
2268
2227
  const saved = await saveRemoteMedia({
2269
2228
  url,
@@ -2272,23 +2231,13 @@ async function downloadMedia(url, maxBytes) {
2272
2231
  ssrfPolicy: void 0,
2273
2232
  requestInit: { method: "GET" }
2274
2233
  });
2275
- return {
2234
+ attachments.push({
2276
2235
  path: saved.path,
2277
2236
  contentType: saved.contentType ?? "application/octet-stream"
2278
- };
2279
- } catch (error) {
2280
- console.error(`[tlon-media] Error downloading ${url}: ${formatErrorMessage(error)}`);
2281
- return null;
2282
- }
2283
- }
2284
- async function downloadMessageImages(content, maxBytes) {
2285
- const { images, unavailableCount: overCapCount } = extractImageBlocks(content);
2286
- const attachments = [];
2287
- let unavailableCount = overCapCount;
2288
- for (const url of images) {
2289
- const downloaded = await downloadMedia(url, maxBytes);
2290
- if (downloaded) attachments.push(downloaded);
2291
- else unavailableCount++;
2237
+ });
2238
+ } catch {
2239
+ console.error("[tlon-media] Error downloading inbound media");
2240
+ unavailableCount++;
2292
2241
  }
2293
2242
  return {
2294
2243
  attachments,
@@ -2314,34 +2263,6 @@ import * as import_openclaw_plugin_sdk_channel_mention_gating from "openclaw/plu
2314
2263
  __reExport(channel_mention_gating_exports, import_openclaw_plugin_sdk_channel_mention_gating);
2315
2264
  //#endregion
2316
2265
  //#region extensions/tlon/src/monitor/mentions.ts
2317
- function resolveTlonGroupMentionDecision(params) {
2318
- const implicitMentions = resolveChannelImplicitMentions({
2319
- cfg: params.cfg,
2320
- channel: "tlon",
2321
- accountId: params.accountId
2322
- });
2323
- const threadPolicy = resolveBotThreadMentionPolicy({
2324
- isBotOwnedThread: params.isBotOwnedThread === true,
2325
- requireMentionInBotThreads: params.requireMentionInBotThreads,
2326
- requireMention: true,
2327
- implicitMentionKinds: (0, channel_mention_gating_exports.implicitMentionKindWhen)("bot_thread_participant", params.botParticipatedInThread)
2328
- });
2329
- return (0, channel_mention_gating_exports.resolveInboundMentionDecision)({
2330
- facts: {
2331
- canDetectMention: true,
2332
- wasMentioned: params.wasMentioned,
2333
- implicitMentionKinds: threadPolicy.implicitMentionKinds
2334
- },
2335
- policy: {
2336
- isGroup: true,
2337
- requireMention: threadPolicy.requireMention,
2338
- implicitMentions,
2339
- allowTextCommands: false,
2340
- hasControlCommand: false,
2341
- commandAuthorized: false
2342
- }
2343
- });
2344
- }
2345
2266
  async function prepareTlonGroupAdmission(params) {
2346
2267
  const { cfg, account, channelNest, botShipName, runtime } = params;
2347
2268
  const parentId = readStringField(params.messageSeal, "parent-id") ?? readStringField(params.messageSeal, "parent") ?? null;
@@ -2352,17 +2273,37 @@ async function prepareTlonGroupAdmission(params) {
2352
2273
  const isBotOwnedThread = Boolean(threadRootAuthor && normalizeShip(threadRootAuthor) === botShipName);
2353
2274
  const resolveCurrentAdmission = () => {
2354
2275
  const authorization = resolveChannelAuthorization(cfg, channelNest, params.getSettings());
2276
+ const senderAllowed = params.isOwner(params.senderShip) || authorization.mode === "open" || authorization.allowedShips.some((ship) => normalizeShip(ship) === params.senderShip);
2277
+ const implicitMentions = resolveChannelImplicitMentions({
2278
+ cfg,
2279
+ channel: "tlon",
2280
+ accountId: account.accountId
2281
+ });
2282
+ const threadPolicy = resolveBotThreadMentionPolicy({
2283
+ isBotOwnedThread,
2284
+ requireMentionInBotThreads: authorization.requireMentionInBotThreads ?? account.requireMentionInBotThreads,
2285
+ requireMention: true,
2286
+ implicitMentionKinds: (0, channel_mention_gating_exports.implicitMentionKindWhen)("bot_thread_participant", botParticipatedInThread)
2287
+ });
2288
+ const decision = (0, channel_mention_gating_exports.resolveInboundMentionDecision)({
2289
+ facts: {
2290
+ canDetectMention: true,
2291
+ wasMentioned: mentioned,
2292
+ implicitMentionKinds: threadPolicy.implicitMentionKinds
2293
+ },
2294
+ policy: {
2295
+ isGroup: true,
2296
+ requireMention: threadPolicy.requireMention,
2297
+ implicitMentions,
2298
+ allowTextCommands: false,
2299
+ hasControlCommand: false,
2300
+ commandAuthorized: false
2301
+ }
2302
+ });
2355
2303
  return {
2356
2304
  ...authorization,
2357
- senderAllowed: params.isOwner(params.senderShip) || authorization.mode === "open" || authorization.allowedShips.some((ship) => normalizeShip(ship) === params.senderShip),
2358
- mentionDecision: resolveTlonGroupMentionDecision({
2359
- cfg,
2360
- accountId: account.accountId,
2361
- wasMentioned: mentioned,
2362
- botParticipatedInThread,
2363
- isBotOwnedThread,
2364
- requireMentionInBotThreads: authorization.requireMentionInBotThreads ?? account.requireMentionInBotThreads
2365
- })
2305
+ senderAllowed,
2306
+ mentionDecision: decision
2366
2307
  };
2367
2308
  };
2368
2309
  const admission = resolveCurrentAdmission();
@@ -2423,6 +2364,7 @@ function applyTlonSettingsOverrides(params) {
2423
2364
  effectiveAutoAcceptDmInvites: settings.autoAcceptDmInvites ?? account.autoAcceptDmInvites ?? false,
2424
2365
  effectiveAutoAcceptGroupInvites: settings.autoAcceptGroupInvites ?? account.autoAcceptGroupInvites ?? false,
2425
2366
  effectiveGroupInviteAllowlist: settings.groupInviteAllowlist ?? account.groupInviteAllowlist,
2367
+ explicitChannels: mergeUniqueStrings(account.groupChannels, settings.groupChannels),
2426
2368
  effectiveAutoDiscoverChannels: settings.autoDiscoverChannels ?? account.autoDiscoverChannels ?? false,
2427
2369
  effectiveOwnerShip,
2428
2370
  pendingApprovals: settings.pendingApprovals?.length ? settings.pendingApprovals : [],
@@ -2432,13 +2374,27 @@ function applyTlonSettingsOverrides(params) {
2432
2374
  function mergeUniqueStrings(base, next) {
2433
2375
  return uniqueStrings([...base, ...next ?? []]);
2434
2376
  }
2377
+ function createTlonSettingsInstaller(state, account, log) {
2378
+ return (currentSettings, preserveApprovalState = false) => {
2379
+ const pendingApprovals = state.pendingApprovals;
2380
+ const effectiveDmAllowlist = state.effectiveDmAllowlist;
2381
+ Object.assign(state, applyTlonSettingsOverrides({
2382
+ account,
2383
+ currentSettings,
2384
+ log
2385
+ }));
2386
+ if (preserveApprovalState) {
2387
+ state.pendingApprovals = pendingApprovals;
2388
+ state.effectiveDmAllowlist = effectiveDmAllowlist;
2389
+ }
2390
+ };
2391
+ }
2435
2392
  //#endregion
2436
2393
  //#region extensions/tlon/src/monitor/tracking.ts
2437
- const TLON_PARTICIPATED_THREAD_LIMIT = 2e3;
2438
- function createParticipatedThreadTracker(limit = TLON_PARTICIPATED_THREAD_LIMIT) {
2394
+ function createParticipatedThreadTracker() {
2439
2395
  const cache = createDedupeCache({
2440
2396
  ttlMs: 0,
2441
- maxSize: limit
2397
+ maxSize: 2e3
2442
2398
  });
2443
2399
  return {
2444
2400
  add: (parentId) => {
@@ -2477,7 +2433,7 @@ async function monitorTlonProvider(opts) {
2477
2433
  if (cfg.channels?.tlon?.enabled === false) return;
2478
2434
  const logger = core.logging.getChildLogger({ module: "tlon-auto-reply" });
2479
2435
  const runtime = opts.runtime ?? createLoggerBackedRuntime({ logger });
2480
- const account = resolveTlonAccount(cfg, opts.accountId ?? void 0);
2436
+ const account = resolveTlonAccount(cfg, opts.accountId);
2481
2437
  if (!account.enabled) return;
2482
2438
  if (!account.configured || !account.ship || !account.url || !account.code) throw new Error("Tlon account not configured (ship/url/code required)");
2483
2439
  const botShipName = normalizeShip(account.ship);
@@ -2533,6 +2489,7 @@ async function monitorTlonProvider(opts) {
2533
2489
  account,
2534
2490
  currentSettings: {}
2535
2491
  });
2492
+ const installSettings = createTlonSettingsInstaller(settingsState, account, (message) => runtime.log?.(message));
2536
2493
  const participatedThreads = createParticipatedThreadTracker();
2537
2494
  const channelHistory = createChannelHistoryCache();
2538
2495
  const dmSendersBySession = /* @__PURE__ */ new Map();
@@ -2547,29 +2504,19 @@ async function monitorTlonProvider(opts) {
2547
2504
  runtime.log?.(`[tlon] Could not fetch nickname: ${formatErrorMessage(error)}`);
2548
2505
  }
2549
2506
  let initForeigns = null;
2550
- try {
2551
- settingsState.currentSettings = await settingsManager.load();
2552
- const migrations = buildTlonSettingsMigrations(account, settingsState.currentSettings);
2553
- for (const { key, fileValue, settingsValue } of migrations) if (shouldMigrateTlonSetting(fileValue, settingsValue)) try {
2554
- await putTlonSetting(api, key, fileValue);
2555
- runtime.log?.(`[tlon] Migrated ${key} from config to settings store`);
2556
- } catch (err) {
2557
- runtime.log?.(`[tlon] Failed to migrate ${key}: ${String(err)}`);
2558
- }
2559
- Object.assign(settingsState, applyTlonSettingsOverrides({
2560
- account,
2561
- currentSettings: settingsState.currentSettings,
2562
- log: (message) => runtime.log?.(message)
2563
- }));
2507
+ settingsState.currentSettings = await settingsManager.load();
2508
+ const migrations = buildTlonSettingsMigrations(account, settingsState.currentSettings);
2509
+ for (const { key, fileValue, settingsValue } of migrations) if (shouldMigrateTlonSetting(fileValue, settingsValue)) try {
2510
+ await putTlonSetting(api, key, fileValue);
2511
+ runtime.log?.(`[tlon] Migrated ${key} from config to settings store`);
2564
2512
  } catch (err) {
2565
- runtime.log?.(`[tlon] Settings store not available, using file config: ${String(err)}`);
2513
+ runtime.log?.(`[tlon] Failed to migrate ${key}: ${String(err)}`);
2566
2514
  }
2567
- if (settingsState.effectiveAutoDiscoverChannels) try {
2515
+ installSettings(settingsState.currentSettings);
2516
+ if (settingsState.effectiveAutoDiscoverChannels) {
2568
2517
  const initData = await fetchInitData(api, runtime);
2569
2518
  if (initData.channels.length > 0) groupChannels = initData.channels;
2570
2519
  initForeigns = initData.foreigns;
2571
- } catch (error) {
2572
- runtime.error?.(`[tlon] Auto-discovery failed: ${formatErrorMessage(error)}`);
2573
2520
  }
2574
2521
  if (account.groupChannels.length > 0) {
2575
2522
  groupChannels = mergeUniqueStrings(groupChannels, account.groupChannels);
@@ -2595,21 +2542,17 @@ async function monitorTlonProvider(opts) {
2595
2542
  const senderId = clubId === void 0 ? senderShip : clubSenderId(clubId, senderShip);
2596
2543
  let attachments = [];
2597
2544
  let unavailableMediaCount = 0;
2598
- if (messageContent) try {
2545
+ if (messageContent) {
2599
2546
  ({attachments, unavailableCount: unavailableMediaCount} = await downloadMessageImages(messageContent, account.mediaMaxBytes));
2600
2547
  if (attachments.length > 0) runtime.log?.(`[tlon] Downloaded ${attachments.length} image(s) from message`);
2601
- } catch (error) {
2602
- runtime.log?.(`[tlon] Failed to download images: ${formatErrorMessage(error)}`);
2603
2548
  }
2604
- if (isThreadReply && parentId && channelNest) try {
2605
- const threadHistory = await fetchThreadHistory(api, channelNest, parentId, 20, runtime);
2549
+ if (isThreadReply && parentId && channelNest) {
2550
+ const threadHistory = await fetchThreadHistory(api, channelNest, parentId, runtime);
2606
2551
  if (threadHistory.length > 0) {
2607
2552
  const threadContext = threadHistory.slice(-10).map((msg) => `${msg.author}: ${msg.content}`).join("\n");
2608
2553
  messageText = `${`[Thread conversation - ${threadHistory.length} previous replies. You are participating in this thread. Only respond if relevant or helpful - you don't need to reply to every message.]`}\n\n[Previous messages]\n${threadContext}\n\n[Current message]\n${messageText}`;
2609
2554
  runtime?.log?.(`[tlon] Added thread context (${threadHistory.length} replies) to message`);
2610
2555
  }
2611
- } catch (error) {
2612
- runtime?.log?.(`[tlon] Could not fetch thread context: ${formatErrorMessage(error)}`);
2613
2556
  }
2614
2557
  const groupTarget = isGroup && channelNest ? parseChannelNest(channelNest) : null;
2615
2558
  const groupSendContext = groupTarget && {
@@ -2618,7 +2561,7 @@ async function monitorTlonProvider(opts) {
2618
2561
  ...groupTarget
2619
2562
  };
2620
2563
  if (isGroup && channelNest && isSummarizationRequest(messageText)) try {
2621
- const history = await channelHistory.getChannelHistory(api, channelNest, 50, runtime);
2564
+ const history = await channelHistory.getChannelHistory(api, channelNest, runtime);
2622
2565
  if (history.length === 0) {
2623
2566
  const noHistoryMsg = "I couldn't fetch any messages for this channel. It might be empty or there might be a permissions issue.";
2624
2567
  if (groupSendContext && isAdmissionAllowed?.() !== false) await sendGroupMessage({
@@ -2644,7 +2587,7 @@ async function monitorTlonProvider(opts) {
2644
2587
  const route = core.channel.routing.resolveAgentRoute({
2645
2588
  cfg,
2646
2589
  channel: "tlon",
2647
- accountId: opts.accountId ?? void 0,
2590
+ accountId: opts.accountId,
2648
2591
  peer: {
2649
2592
  kind: isGroup ? "group" : "direct",
2650
2593
  id: isGroup ? channelNest ?? senderShip : senderShip
@@ -2704,7 +2647,6 @@ async function monitorTlonProvider(opts) {
2704
2647
  body: commandBody,
2705
2648
  notice: `[tlon ${unavailableMediaCount > 1 ? `${unavailableMediaCount} attachments` : "attachment"} unavailable]`
2706
2649
  }) : commandBody;
2707
- const tlonConversationId = isGroup ? channelNest ?? senderShip : senderShip;
2708
2650
  const ctxPayload = core.channel.inbound.buildContext({
2709
2651
  channel: "tlon",
2710
2652
  accountId: route.accountId,
@@ -2718,7 +2660,7 @@ async function monitorTlonProvider(opts) {
2718
2660
  },
2719
2661
  conversation: {
2720
2662
  kind: isGroup ? "group" : "direct",
2721
- id: tlonConversationId,
2663
+ id: isGroup ? channelNest ?? senderShip : senderShip,
2722
2664
  label: fromLabel
2723
2665
  },
2724
2666
  route: {
@@ -2745,6 +2687,7 @@ async function monitorTlonProvider(opts) {
2745
2687
  CommandAuthorized: commandAuthorized,
2746
2688
  CommandSource: "text",
2747
2689
  ...attachments.length > 0 && { Attachments: attachments },
2690
+ ...isGroup && { ReplyThreading: { implicitCurrentMessage: "deny" } },
2748
2691
  ...parentId && { ThreadId: parentId }
2749
2692
  }
2750
2693
  });
@@ -2793,7 +2736,7 @@ async function monitorTlonProvider(opts) {
2793
2736
  await sendGroupMessage({
2794
2737
  ...groupSendContext,
2795
2738
  text: replyText,
2796
- replyToId: parentId ?? void 0
2739
+ replyToId: parentId
2797
2740
  });
2798
2741
  return {
2799
2742
  visibleReplySent: true,
@@ -2815,8 +2758,7 @@ async function monitorTlonProvider(opts) {
2815
2758
  }
2816
2759
  },
2817
2760
  onError: (err, info) => {
2818
- const dispatchDuration = Date.now() - dispatchStartTime;
2819
- runtime.error?.(`[tlon] ${info.kind} reply failed after ${dispatchDuration}ms: ${String(err)}`);
2761
+ runtime.error?.(`[tlon] ${info.kind} reply failed after ${Date.now() - dispatchStartTime}ms: ${String(err)}`);
2820
2762
  }
2821
2763
  },
2822
2764
  dispatcherOptions: { humanDelay },
@@ -2827,6 +2769,7 @@ async function monitorTlonProvider(opts) {
2827
2769
  });
2828
2770
  };
2829
2771
  const watchedChannels = new Set(groupChannels);
2772
+ const canExpandCitedNest = (nest) => settingsState.effectiveAutoDiscoverChannels || settingsState.explicitChannels.includes(nest);
2830
2773
  const addWatchedChannels = (channels, logPrefix) => {
2831
2774
  const previousCount = watchedChannels.size;
2832
2775
  for (const channelNest of channels) if (!watchedChannels.has(channelNest)) {
@@ -2884,36 +2827,24 @@ async function monitorTlonProvider(opts) {
2884
2827
  });
2885
2828
  const handleChannelsFirehose = async (event, turnAdoptionLifecycle) => {
2886
2829
  try {
2887
- const eventRecord = asNullableRecord(event);
2888
- const nest = readStringField(eventRecord, "nest");
2889
- if (!nest) return;
2890
- if (!watchedChannels.has(nest)) return;
2891
- const response = asNullableRecord(eventRecord?.response);
2892
- if (!response) return;
2893
- const post = asNullableRecord(response.post);
2894
- const rPost = asNullableRecord(post?.["r-post"]);
2895
- const set = asNullableRecord(rPost?.set);
2896
- const reply = asNullableRecord(rPost?.reply);
2897
- const replyPayload = asNullableRecord(reply?.["r-reply"]);
2898
- const replySet = asNullableRecord(replyPayload?.set);
2899
- const essay = asNullableRecord(set?.essay);
2900
- const memo = asNullableRecord(replySet?.memo);
2901
- const content = memo ?? essay;
2902
- if (!content) return;
2903
- const isThreadReply = Boolean(memo);
2904
- const messageId = isThreadReply ? readStringField(reply, "id") : readStringField(post, "id");
2905
- if (!messageId) return;
2830
+ const message = decodeTlonChannelsEvent(event);
2831
+ if (!message || !watchedChannels.has(message.nest)) return;
2832
+ const { nest, messageId, content, isThreadReply, messageSet } = message;
2906
2833
  const senderShip = normalizeShip(readStringField(content, "author") ?? "");
2907
2834
  if (!senderShip || senderShip === botShipName) return;
2908
- const rawText = extractMessageTextSafely(content.content, runtime);
2835
+ let rawText;
2836
+ try {
2837
+ rawText = extractMessageText(content.content);
2838
+ } catch (error) {
2839
+ runtime.log?.(`[tlon] Failed to extract message text: ${formatErrorMessage(error)}`);
2840
+ return;
2841
+ }
2909
2842
  if (!rawText.trim()) return;
2910
- const contentBody = content.content;
2911
2843
  const sentAt = asFiniteNumber(content?.sent) ?? Date.now();
2912
2844
  channelHistory.cacheMessage(nest, {
2913
2845
  author: senderShip,
2914
2846
  content: rawText,
2915
- timestamp: sentAt,
2916
- id: messageId
2847
+ timestamp: sentAt
2917
2848
  });
2918
2849
  const { allowedShips, senderAllowed, mentionDecision, parentId, isAdmissionAllowed } = await prepareTlonGroupAdmission({
2919
2850
  cfg,
@@ -2925,7 +2856,7 @@ async function monitorTlonProvider(opts) {
2925
2856
  botShipName,
2926
2857
  botNickname,
2927
2858
  rawText,
2928
- messageSeal: isThreadReply ? asNullableRecord(replySet?.seal) : asNullableRecord(set?.seal),
2859
+ messageSeal: asNullableRecord(messageSet?.seal),
2929
2860
  isThreadReply,
2930
2861
  hasParticipatedInThread: participatedThreads.has,
2931
2862
  getSettings: () => settingsState.currentSettings,
@@ -2938,11 +2869,11 @@ async function monitorTlonProvider(opts) {
2938
2869
  type: "channel",
2939
2870
  requestingShip: senderShip,
2940
2871
  channelNest: nest,
2941
- messagePreview: sliceUtf16Safe(rawText, 0, 100),
2872
+ messagePreview: rawText,
2942
2873
  originalMessage: {
2943
2874
  messageId,
2944
2875
  messageText: rawText,
2945
- messageContent: contentBody,
2876
+ messageContent: content.content,
2946
2877
  timestamp: sentAt,
2947
2878
  parentId: parentId ?? void 0,
2948
2879
  isThreadReply
@@ -2952,12 +2883,12 @@ async function monitorTlonProvider(opts) {
2952
2883
  } else runtime.log?.(`[tlon] Access denied: ${senderShip} in ${nest} (allowed: ${allowedShips.join(", ")})`);
2953
2884
  return;
2954
2885
  }
2955
- const messageText = await resolveTlonCitations(contentBody, api, runtime) + rawText;
2886
+ const messageText = await resolveTlonCitations(content.content, canExpandCitedNest, api, runtime) + rawText;
2956
2887
  await processMessage({
2957
2888
  messageId,
2958
2889
  senderShip,
2959
2890
  messageText,
2960
- messageContent: contentBody,
2891
+ messageContent: content.content,
2961
2892
  isGroup: true,
2962
2893
  channelNest: nest,
2963
2894
  timestamp: sentAt,
@@ -2995,21 +2926,16 @@ async function monitorTlonProvider(opts) {
2995
2926
  const ownerInvite = isOwner(ship);
2996
2927
  const allowed = ownerInvite || await isDmAllowedWithIngress(ship, settingsState.effectiveDmAllowlist);
2997
2928
  if (ownerInvite || settingsState.effectiveAutoAcceptDmInvites && allowed) {
2998
- try {
2999
- await api.poke({
3000
- app: "chat",
3001
- mark: "chat-dm-rsvp",
3002
- json: {
3003
- ship,
3004
- ok: true
3005
- }
3006
- });
3007
- processedDmInvites.add(ship);
3008
- runtime.log?.(ownerInvite ? `[tlon] Auto-accepted DM invite from owner ${ship}` : `[tlon] Auto-accepted DM invite from ${ship}`);
3009
- } catch (err) {
3010
- runtime.error?.(ownerInvite ? `[tlon] Failed to auto-accept DM from owner: ${String(err)}` : `[tlon] Failed to auto-accept DM from ${ship}: ${String(err)}`);
3011
- throw err;
3012
- }
2929
+ await api.poke({
2930
+ app: "chat",
2931
+ mark: "chat-dm-rsvp",
2932
+ json: {
2933
+ ship,
2934
+ ok: true
2935
+ }
2936
+ });
2937
+ processedDmInvites.add(ship);
2938
+ runtime.log?.(ownerInvite ? `[tlon] Auto-accepted DM invite from owner ${ship}` : `[tlon] Auto-accepted DM invite from ${ship}`);
3013
2939
  continue;
3014
2940
  }
3015
2941
  if (settingsState.effectiveOwnerShip && !allowed) {
@@ -3023,14 +2949,9 @@ async function monitorTlonProvider(opts) {
3023
2949
  }
3024
2950
  return;
3025
2951
  }
3026
- const eventRecord = asNullableRecord(event);
3027
- if (!eventRecord) return;
3028
- const whom = eventRecord.whom;
3029
- const messageId = readStringField(eventRecord, "id");
3030
- const response = asNullableRecord(eventRecord.response);
3031
- if (!messageId || !response) return;
3032
- const essay = asNullableRecord(asNullableRecord(response.add)?.essay);
3033
- if (!essay) return;
2952
+ const message = decodeTlonChatEvent(event);
2953
+ if (!message) return;
2954
+ const { whom, messageId, essay } = message;
3034
2955
  const authorShip = normalizeShip(readStringField(essay, "author") ?? "");
3035
2956
  const partnerShip = extractDmPartnerShip(whom);
3036
2957
  const senderShip = partnerShip || authorShip;
@@ -3040,16 +2961,21 @@ async function monitorTlonProvider(opts) {
3040
2961
  if (authorShip === botShipName) return;
3041
2962
  if (!senderShip || senderShip === botShipName) return;
3042
2963
  if (authorShip && partnerShip && authorShip !== partnerShip) runtime.log?.(`[tlon] DM ship mismatch (author=${authorShip}, partner=${partnerShip}) - routing to partner`);
3043
- const rawText = extractMessageTextSafely(essay.content, runtime);
2964
+ let rawText;
2965
+ try {
2966
+ rawText = extractMessageText(essay.content);
2967
+ } catch (error) {
2968
+ runtime.log?.(`[tlon] Failed to extract message text: ${formatErrorMessage(error)}`);
2969
+ return;
2970
+ }
3044
2971
  if (!rawText.trim()) return;
3045
- const messageText = rawText;
3046
2972
  const ownerDm = !isClubMessage && isOwner(senderShip);
3047
- if (ownerDm && await handleApprovalResponse(messageText)) {
3048
- runtime.log?.(`[tlon] Processed approval response from owner: ${messageText}`);
2973
+ if (ownerDm && await handleApprovalResponse(rawText)) {
2974
+ runtime.log?.("[tlon] Processed approval response from owner");
3049
2975
  return;
3050
2976
  }
3051
- if (ownerDm && await handleAdminCommand(messageText)) {
3052
- runtime.log?.(`[tlon] Processed admin command from owner: ${messageText}`);
2977
+ if (ownerDm && await handleAdminCommand(rawText)) {
2978
+ runtime.log?.("[tlon] Processed admin command from owner");
3053
2979
  return;
3054
2980
  }
3055
2981
  const resolveChannelIngress = async (contextBinding) => await resolveTlonMessageIngress({
@@ -3072,11 +2998,11 @@ async function monitorTlonProvider(opts) {
3072
2998
  const approval = createPendingApproval({
3073
2999
  type: "dm",
3074
3000
  requestingShip: senderShip,
3075
- messagePreview: sliceUtf16Safe(messageText, 0, 100),
3001
+ messagePreview: rawText,
3076
3002
  ...isClubMessage ? { clubId } : { verifiedDirect: true },
3077
3003
  ...isClubMessage && isOwner(senderShip) ? {} : { originalMessage: {
3078
3004
  messageId,
3079
- messageText,
3005
+ messageText: rawText,
3080
3006
  messageContent: essay.content,
3081
3007
  timestamp: asFiniteNumber(essay?.sent) ?? Date.now()
3082
3008
  } }
@@ -3085,10 +3011,10 @@ async function monitorTlonProvider(opts) {
3085
3011
  } else runtime.log?.(`[tlon] Blocked DM from ${senderShip}: not in allowlist`);
3086
3012
  return;
3087
3013
  }
3088
- const resolvedMessageText = await resolveTlonCitations(essay.content, api, runtime) + rawText;
3014
+ const can = (nest) => !isClubMessage && isOwner(senderShip) || canExpandCitedNest(nest), agentText = await resolveTlonCitations(essay.content, can, api, runtime) + rawText;
3089
3015
  if (ownerDm) runtime.log?.(`[tlon] Processing DM from owner ${senderShip}`);
3090
3016
  await processMessage({
3091
- messageText: resolvedMessageText,
3017
+ messageText: agentText,
3092
3018
  messageId,
3093
3019
  senderShip,
3094
3020
  clubId,
@@ -3115,6 +3041,14 @@ async function monitorTlonProvider(opts) {
3115
3041
  await handleChatFirehose(event, turnAdoptionLifecycle);
3116
3042
  }
3117
3043
  });
3044
+ const subscriptionLogHandlers = (errorLabel, endedLabel) => ({
3045
+ err: (error) => {
3046
+ runtime.error?.(`[tlon] ${errorLabel} error: ${String(error)}`);
3047
+ },
3048
+ quit: () => {
3049
+ runtime.log?.(`[tlon] ${endedLabel} ended`);
3050
+ }
3051
+ });
3118
3052
  try {
3119
3053
  runtime.log?.("[tlon] Subscribing to firehose updates...");
3120
3054
  for (const [source, path, label, handleEvent] of [[
@@ -3137,12 +3071,7 @@ async function monitorTlonProvider(opts) {
3137
3071
  event
3138
3072
  })).kind === "ignored") await handleEvent(event);
3139
3073
  },
3140
- err: (error) => {
3141
- runtime.error?.(`[tlon] ${label} firehose error: ${String(error)}`);
3142
- },
3143
- quit: () => {
3144
- runtime.log?.(`[tlon] ${label} firehose subscription ended`);
3145
- }
3074
+ ...subscriptionLogHandlers(`${label} firehose`, `${label} firehose subscription`)
3146
3075
  });
3147
3076
  runtime.log?.(`[tlon] Subscribed to ${source} firehose (${path})`);
3148
3077
  }
@@ -3168,23 +3097,13 @@ async function monitorTlonProvider(opts) {
3168
3097
  runtime.error?.(`[tlon] Error handling contacts event: ${formatErrorMessage(error)}`);
3169
3098
  }
3170
3099
  },
3171
- err: (error) => {
3172
- runtime.error?.(`[tlon] Contacts subscription error: ${String(error)}`);
3173
- },
3174
- quit: () => {
3175
- runtime.log?.("[tlon] Contacts subscription ended");
3176
- }
3100
+ ...subscriptionLogHandlers("Contacts subscription", "Contacts subscription")
3177
3101
  });
3178
3102
  runtime.log?.("[tlon] Subscribed to contacts updates (/v1/news)");
3179
3103
  try {
3180
3104
  await settingsManager.startSubscription((newSettings) => {
3181
- settingsState.currentSettings = newSettings;
3182
3105
  addWatchedChannels(newSettings.groupChannels ?? [], "[tlon] Settings: now watching channel ");
3183
- Object.assign(settingsState, applyTlonSettingsOverrides({
3184
- account,
3185
- currentSettings: newSettings,
3186
- log: (message) => runtime.log?.(message)
3187
- }));
3106
+ installSettings(newSettings);
3188
3107
  });
3189
3108
  } catch (err) {
3190
3109
  runtime.log?.(`[tlon] Settings subscription not available: ${String(err)}`);
@@ -3202,27 +3121,23 @@ async function monitorTlonProvider(opts) {
3202
3121
  const discoveredChannels = mergeUniqueStrings(Object.keys(asNullableRecord(eventRecord.channels) ?? {}), joinedChannels.filter((channel) => typeof channel === "string")).filter((channel) => channel.startsWith("chat/"));
3203
3122
  addWatchedChannels(discoveredChannels, "[tlon] Auto-detected new channel: ");
3204
3123
  if (!settingsState.effectiveAutoAcceptGroupInvites) return;
3205
- const currentChannels = settingsState.currentSettings.groupChannels ?? [];
3124
+ const settingsSnapshot = settingsState.currentSettings;
3125
+ const currentChannels = settingsSnapshot.groupChannels ?? [];
3206
3126
  const unpersistedChannels = discoveredChannels.filter((channel) => !currentChannels.includes(channel));
3207
3127
  if (unpersistedChannels.length === 0) return;
3208
3128
  const updatedChannels = mergeUniqueStrings(currentChannels, unpersistedChannels);
3209
3129
  await putTlonSetting(api, "groupChannels", updatedChannels);
3210
- settingsState.currentSettings = {
3211
- ...settingsState.currentSettings,
3130
+ if (settingsState.currentSettings === settingsSnapshot) installSettings({
3131
+ ...settingsSnapshot,
3212
3132
  groupChannels: updatedChannels
3213
- };
3133
+ }, true);
3214
3134
  runtime.log?.(`[tlon] Persisted ${unpersistedChannels.join(", ")} to settings store`);
3215
3135
  } catch (error) {
3216
3136
  runtime.error?.(`[tlon] Error handling groups-ui event: ${formatErrorMessage(error)}`);
3217
3137
  throw error;
3218
3138
  }
3219
3139
  },
3220
- err: (error) => {
3221
- runtime.error?.(`[tlon] Groups-ui subscription error: ${String(error)}`);
3222
- },
3223
- quit: () => {
3224
- runtime.log?.("[tlon] Groups-ui subscription ended");
3225
- }
3140
+ ...subscriptionLogHandlers("Groups-ui subscription", "Groups-ui subscription")
3226
3141
  });
3227
3142
  runtime.log?.("[tlon] Subscribed to groups-ui for real-time channel detection");
3228
3143
  } catch (err) {
@@ -3293,12 +3208,7 @@ async function monitorTlonProvider(opts) {
3293
3208
  throw error;
3294
3209
  }
3295
3210
  },
3296
- err: (error) => {
3297
- runtime.error?.(`[tlon] Foreigns subscription error: ${String(error)}`);
3298
- },
3299
- quit: () => {
3300
- runtime.log?.("[tlon] Foreigns subscription ended");
3301
- }
3211
+ ...subscriptionLogHandlers("Foreigns subscription", "Foreigns subscription")
3302
3212
  });
3303
3213
  runtime.log?.("[tlon] Subscribed to foreigns (/v1/foreigns) for auto-accepting group invites");
3304
3214
  } catch (err) {
@@ -3322,13 +3232,9 @@ async function monitorTlonProvider(opts) {
3322
3232
  everyMs: 12e4,
3323
3233
  run: async () => {
3324
3234
  if (!settingsState.effectiveAutoDiscoverChannels) return;
3325
- try {
3326
- const { channels: discoveredChannels } = await fetchInitData(api, runtime);
3327
- if (discoveryScheduler.signal.aborted) return;
3328
- addWatchedChannels(discoveredChannels, "[tlon] Now watching new channel: ");
3329
- } catch (error) {
3330
- runtime.error?.(`[tlon] Channel refresh error: ${formatErrorMessage(error)}`);
3331
- }
3235
+ const { channels: discoveredChannels } = await fetchInitData(api, runtime);
3236
+ if (discoveryScheduler.signal.aborted) return;
3237
+ addWatchedChannels(discoveredChannels, "[tlon] Now watching new channel: ");
3332
3238
  }
3333
3239
  });
3334
3240
  await waitUntilAbort(opts.abortSignal);
@@ -3413,6 +3319,12 @@ function prefixEndpoint(endpoint) {
3413
3319
  function sanitizeFileName(fileName) {
3414
3320
  return fileName.split(/[/\\]/).pop() || fileName;
3415
3321
  }
3322
+ /** Join a storage object key onto publicUrlBase without treating #/? as URL delimiters. */
3323
+ function buildCustomS3PublicUrl(publicUrlBase, fileKey) {
3324
+ const base = publicUrlBase.endsWith("/") ? publicUrlBase : `${publicUrlBase}/`;
3325
+ const encodedKey = fileKey.split("/").map((segment) => encodeURIComponent(segment)).join("/");
3326
+ return new URL(encodedKey, base).toString();
3327
+ }
3416
3328
  async function scryJson(config, cookie, path) {
3417
3329
  return await scryUrbitPath({
3418
3330
  baseUrl: config.shipUrl,
@@ -3424,54 +3336,6 @@ async function scryJson(config, cookie, path) {
3424
3336
  auditContext: "tlon-storage-scry"
3425
3337
  });
3426
3338
  }
3427
- async function getStorageConfiguration(config, cookie) {
3428
- const result = await scryJson(config, cookie, "/storage/configuration.json");
3429
- if ("storage-update" in result && result["storage-update"]?.configuration) return result["storage-update"].configuration;
3430
- if ("currentBucket" in result) return result;
3431
- throw new Error("Invalid storage configuration response");
3432
- }
3433
- async function getStorageCredentials(config, cookie) {
3434
- const result = await scryJson(config, cookie, "/storage/credentials.json");
3435
- if ("storage-update" in result) return result["storage-update"]?.credentials ?? null;
3436
- if (isStorageCredentials(result)) return result;
3437
- return null;
3438
- }
3439
- async function getMemexUploadUrl(params) {
3440
- const token = await scryJson(params.config, params.cookie, "/genuine/secret.json");
3441
- const resolvedToken = typeof token === "string" ? token : token.secret;
3442
- if (!resolvedToken) throw new Error("Missing genuine secret");
3443
- const endpoint = `${MEMEX_BASE_URL}/v1/${params.config.shipName}/upload`;
3444
- let guarded;
3445
- try {
3446
- guarded = await fetchWithSsrFGuard({
3447
- url: endpoint,
3448
- init: {
3449
- method: "PUT",
3450
- headers: { "Content-Type": "application/json" },
3451
- body: JSON.stringify({
3452
- token: resolvedToken,
3453
- contentLength: params.contentLength,
3454
- contentType: params.contentType,
3455
- fileName: params.fileName
3456
- })
3457
- },
3458
- auditContext: "tlon-memex-upload-url",
3459
- capture: false,
3460
- maxRedirects: 0,
3461
- timeoutMs: TLON_MEMEX_UPLOAD_URL_TIMEOUT_MS,
3462
- beforeRequest: params.config.assertDirectAdapterHandoff
3463
- });
3464
- if (!guarded.response.ok) throw new Error(`Memex upload request failed: ${guarded.response.status}`);
3465
- const data = await readProviderJsonResponse(guarded.response, "Memex upload", { maxBytes: MEMEX_UPLOAD_RESPONSE_MAX_BYTES });
3466
- if (!data?.url || !data.filePath) throw new Error("Invalid response from Memex");
3467
- return {
3468
- hostedUrl: data.filePath,
3469
- uploadUrl: data.url
3470
- };
3471
- } finally {
3472
- await releaseUploadResponse(guarded);
3473
- }
3474
- }
3475
3339
  async function uploadFile(params, clientConfig) {
3476
3340
  const config = {
3477
3341
  ...clientConfig,
@@ -3482,7 +3346,19 @@ async function uploadFile(params, clientConfig) {
3482
3346
  beforeRequest: config.assertDirectAdapterHandoff
3483
3347
  });
3484
3348
  const privateNetworkPolicy = ssrfPolicyFromDangerouslyAllowPrivateNetwork(config.dangerouslyAllowPrivateNetwork);
3485
- const [storageConfig, credentials] = await Promise.all([getStorageConfiguration(config, cookie), getStorageCredentials(config, cookie)]);
3349
+ async function getStorageConfiguration() {
3350
+ const result = await scryJson(config, cookie, "/storage/configuration.json");
3351
+ if ("storage-update" in result && result["storage-update"]?.configuration) return result["storage-update"].configuration;
3352
+ if ("currentBucket" in result) return result;
3353
+ throw new Error("Invalid storage configuration response");
3354
+ }
3355
+ async function getStorageCredentials() {
3356
+ const result = await scryJson(config, cookie, "/storage/credentials.json");
3357
+ if ("storage-update" in result) return result["storage-update"]?.credentials ?? null;
3358
+ if (isStorageCredentials(result)) return result;
3359
+ return null;
3360
+ }
3361
+ const [storageConfig, credentials] = await Promise.all([getStorageConfiguration(), getStorageCredentials()]);
3486
3362
  const contentType = params.contentType || params.blob.type || "application/octet-stream";
3487
3363
  const extension = extensionForMime(contentType) || ".jpg";
3488
3364
  const fileName = sanitizeFileName(params.fileName || `upload${extension}`);
@@ -3511,14 +3387,45 @@ async function uploadFile(params, clientConfig) {
3511
3387
  await releaseUploadResponse(guarded);
3512
3388
  }
3513
3389
  };
3390
+ async function getMemexUploadUrl() {
3391
+ const contentLength = params.blob.size;
3392
+ const token = await scryJson(config, cookie, "/genuine/secret.json");
3393
+ const resolvedToken = typeof token === "string" ? token : token.secret;
3394
+ if (!resolvedToken) throw new Error("Missing genuine secret");
3395
+ const endpoint = `${MEMEX_BASE_URL}/v1/${config.shipName}/upload`;
3396
+ let guarded;
3397
+ try {
3398
+ guarded = await fetchWithSsrFGuard({
3399
+ url: endpoint,
3400
+ init: {
3401
+ method: "PUT",
3402
+ headers: { "Content-Type": "application/json" },
3403
+ body: JSON.stringify({
3404
+ token: resolvedToken,
3405
+ contentLength,
3406
+ contentType,
3407
+ fileName: fileKey
3408
+ })
3409
+ },
3410
+ auditContext: "tlon-memex-upload-url",
3411
+ capture: false,
3412
+ maxRedirects: 0,
3413
+ timeoutMs: TLON_MEMEX_UPLOAD_URL_TIMEOUT_MS,
3414
+ beforeRequest: config.assertDirectAdapterHandoff
3415
+ });
3416
+ if (!guarded.response.ok) throw new Error(`Memex upload request failed: ${guarded.response.status}`);
3417
+ const data = await readProviderJsonResponse(guarded.response, "Memex upload", { maxBytes: MEMEX_UPLOAD_RESPONSE_MAX_BYTES });
3418
+ if (!data?.url || !data.filePath) throw new Error("Invalid response from Memex");
3419
+ return {
3420
+ hostedUrl: data.filePath,
3421
+ uploadUrl: data.url
3422
+ };
3423
+ } finally {
3424
+ await releaseUploadResponse(guarded);
3425
+ }
3426
+ }
3514
3427
  if (useMemex) {
3515
- const { hostedUrl, uploadUrl } = await getMemexUploadUrl({
3516
- config,
3517
- cookie,
3518
- contentLength: params.blob.size,
3519
- contentType,
3520
- fileName: fileKey
3521
- });
3428
+ const { hostedUrl, uploadUrl } = await getMemexUploadUrl();
3522
3429
  await uploadBlob(assertTrustedMemexUploadUrl(uploadUrl, "Memex upload URL"), {
3523
3430
  "Cache-Control": "public, max-age=3600",
3524
3431
  "Content-Type": contentType
@@ -3549,7 +3456,7 @@ async function uploadFile(params, clientConfig) {
3549
3456
  });
3550
3457
  const signedUrl = await getSignedUrl(client, command, { expiresIn: 3600 });
3551
3458
  await uploadBlob(signedUrl, signedUrl.includes("digitaloceanspaces.com") ? headers : void 0);
3552
- return { url: assertSafeUploadResultUrl(storageConfig.publicUrlBase ? new URL(fileKey, storageConfig.publicUrlBase).toString() : expectDefined(signedUrl.split("?").at(0), "signed URL base segment"), "Upload result URL") };
3459
+ return { url: assertSafeUploadResultUrl(storageConfig.publicUrlBase ? buildCustomS3PublicUrl(storageConfig.publicUrlBase, fileKey) : expectDefined(signedUrl.split("?").at(0), "signed URL base segment"), "Upload result URL") };
3553
3460
  }
3554
3461
  //#endregion
3555
3462
  //#region extensions/tlon/src/urbit/upload.ts
@@ -3584,7 +3491,7 @@ async function uploadImageFromUrl(imageUrl, clientConfig, maxBytes) {
3584
3491
  const contentType = fetched.contentType || "image/png";
3585
3492
  return (await uploadFile({
3586
3493
  blob: new Blob([bufferToBlobPart(fetched.buffer)], { type: contentType }),
3587
- fileName: url.pathname.split("/").pop() || `upload-${Date.now()}.png`,
3494
+ fileName: fetched.fileName?.trim() || url.pathname.split("/").pop()?.trim() || `upload-${Date.now()}.png`,
3588
3495
  contentType
3589
3496
  }, {
3590
3497
  ...clientConfig,
@@ -3600,75 +3507,23 @@ async function uploadImageFromUrl(imageUrl, clientConfig, maxBytes) {
3600
3507
  }
3601
3508
  //#endregion
3602
3509
  //#region extensions/tlon/src/channel.runtime.ts
3603
- async function createHttpPokeApi(params) {
3604
- const ssrfPolicy = ssrfPolicyFromDangerouslyAllowPrivateNetwork(params.dangerouslyAllowPrivateNetwork);
3605
- const cookie = await authenticate(params.url, params.code, {
3606
- ssrfPolicy,
3607
- beforeRequest: params.assertDirectAdapterHandoff
3608
- });
3609
- const channelId = `${Math.floor(Date.now() / 1e3)}-${crypto.randomUUID()}`;
3610
- const shipName = params.ship.replace(/^~/, "");
3611
- return { poke: async (pokeParams) => {
3612
- const pokeId = Date.now();
3613
- const pokeData = {
3614
- id: pokeId,
3615
- action: "poke",
3616
- ship: shipName,
3617
- app: pokeParams.app,
3618
- mark: pokeParams.mark,
3619
- json: pokeParams.json
3620
- };
3621
- params.assertDirectAdapterHandoff?.();
3622
- await params.onPlatformSendDispatch?.();
3623
- const { response, release } = await putUrbitChannel({
3624
- baseUrl: params.url,
3625
- channelId,
3626
- ship: shipName,
3627
- cookie: normalizeUrbitCookie(cookie),
3628
- ssrfPolicy
3629
- }, {
3630
- body: [pokeData],
3631
- auditContext: "tlon-poke",
3632
- beforeRequest: params.assertDirectAdapterHandoff
3633
- });
3634
- try {
3635
- if (!response.ok && response.status !== 204) {
3636
- const errorText = await readResponseTextLimited(response, 16384);
3637
- throw new Error(`Poke failed: ${response.status} - ${redactUrbitErrorText(errorText)}`);
3638
- }
3639
- return pokeId;
3640
- } finally {
3641
- await release();
3642
- }
3643
- } };
3644
- }
3645
- function resolveOutboundContext(params) {
3646
- const account = resolveTlonAccount(params.cfg, params.accountId ?? void 0);
3647
- if (!account.configured || !account.ship || !account.url || !account.code) {
3648
- const missingFields = [
3649
- account.ship ? void 0 : "ship",
3650
- account.url ? void 0 : "url",
3651
- account.code ? void 0 : "code"
3652
- ].filter((field) => field !== void 0);
3653
- throw new Error(`Tlon account ${account.accountId} not configured (missing ${missingFields.join(", ")})`);
3654
- }
3655
- const parsed = parseTlonTarget(params.to);
3656
- if (!parsed) throw new Error(`Invalid Tlon target. Use ${formatTargetHint()}`);
3657
- return {
3658
- account,
3659
- parsed
3660
- };
3661
- }
3662
3510
  function resolveReplyId(replyToId, threadId) {
3663
3511
  return replyToId ?? threadId ? String(replyToId ?? threadId) : void 0;
3664
3512
  }
3665
3513
  async function sendTlonOutbound(params, kind) {
3666
3514
  const { cfg, to, text, accountId, replyToId, threadId, assertDirectAdapterHandoff } = params;
3667
- const { account, parsed } = resolveOutboundContext({
3668
- cfg,
3669
- accountId,
3670
- to
3671
- });
3515
+ const resolvedAccount = resolveTlonAccount(cfg, accountId);
3516
+ if (!resolvedAccount.configured || !resolvedAccount.ship || !resolvedAccount.url || !resolvedAccount.code) {
3517
+ const missingFields = [
3518
+ resolvedAccount.ship ? void 0 : "ship",
3519
+ resolvedAccount.url ? void 0 : "url",
3520
+ resolvedAccount.code ? void 0 : "code"
3521
+ ].filter((field) => field !== void 0);
3522
+ throw new Error(`Tlon account ${resolvedAccount.accountId} not configured (missing ${missingFields.join(", ")})`);
3523
+ }
3524
+ const parsed = parseTlonTarget(to);
3525
+ if (!parsed) throw new Error(`Invalid Tlon target. Use ${formatTargetHint()}`);
3526
+ const account = resolvedAccount;
3672
3527
  let uploadedUrl;
3673
3528
  if (kind === "media") {
3674
3529
  const { mediaUrl } = params;
@@ -3680,14 +3535,30 @@ async function sendTlonOutbound(params, kind) {
3680
3535
  assertDirectAdapterHandoff
3681
3536
  }, account.mediaMaxBytes) : void 0;
3682
3537
  }
3683
- const api = await createHttpPokeApi({
3684
- url: account.url,
3685
- ship: account.ship,
3686
- code: account.code,
3687
- dangerouslyAllowPrivateNetwork: account.dangerouslyAllowPrivateNetwork ?? void 0,
3688
- assertDirectAdapterHandoff,
3689
- onPlatformSendDispatch: params.onPlatformSendDispatch
3538
+ const { url, ship, code, dangerouslyAllowPrivateNetwork } = account;
3539
+ const onPlatformSendDispatch = params.onPlatformSendDispatch;
3540
+ const ssrfPolicy = ssrfPolicyFromDangerouslyAllowPrivateNetwork(dangerouslyAllowPrivateNetwork ?? void 0);
3541
+ const cookie = await authenticate(url, code, {
3542
+ ssrfPolicy,
3543
+ beforeRequest: assertDirectAdapterHandoff
3690
3544
  });
3545
+ const channelId = `${Math.floor(Date.now() / 1e3)}-${crypto.randomUUID()}`;
3546
+ const shipName = ship.replace(/^~/, "");
3547
+ const api = { poke: async (pokeParams) => {
3548
+ assertDirectAdapterHandoff?.();
3549
+ await onPlatformSendDispatch?.();
3550
+ return await pokeUrbitChannel({
3551
+ baseUrl: url,
3552
+ channelId,
3553
+ ship: shipName,
3554
+ cookie: normalizeUrbitCookie(cookie),
3555
+ ssrfPolicy
3556
+ }, {
3557
+ ...pokeParams,
3558
+ auditContext: "tlon-poke",
3559
+ beforeRequest: assertDirectAdapterHandoff
3560
+ });
3561
+ } };
3691
3562
  const fromShip = normalizeShip(account.ship);
3692
3563
  const story = kind === "media" ? buildMediaStory(text, uploadedUrl) : markdownToStory(text);
3693
3564
  if (parsed.kind === "dm") return await sendDmWithStory({