@openclaw/tlon 2026.9.7 → 2026.10.1-beta.1

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,12 +1,12 @@
1
- import { i as __reExport, r as __exportAll } from "./doctor-contract-BiiG6XQ7.mjs";
1
+ import { i as __reExport, r as __exportAll } from "./doctor-contract-bInPRAQZ.mjs";
2
2
  import { createDedupeCache, createLoggerBackedRuntime } from "../runtime-api.js";
3
- import { d as normalizeShip, f as parseChannelNest, l as resolveTlonAccount, o as normalizeUrbitHostname, p as parseTlonTarget, s as validateUrbitBaseUrl, u as formatTargetHint } from "./setup-core-Bktn6kgm.mjs";
3
+ import { c as resolveTlonAccount, d as parseChannelNest, f as parseTlonTarget, l as formatTargetHint, o as validateUrbitBaseUrl, u as normalizeShip } from "./setup-core-CDShPwjB.mjs";
4
4
  import { t as getTlonRuntime } from "./runtime-Ck3lNvST.mjs";
5
- import { t as tlonSetupWizard } from "./setup-surface-BemXwGis.mjs";
5
+ import { t as tlonSetupWizard } from "./setup-surface-o-30U28J.mjs";
6
6
  import { fetchWithSsrFGuard, ssrfPolicyFromDangerouslyAllowPrivateNetwork } from "openclaw/plugin-sdk/ssrf-runtime";
7
7
  import { bindIngressLifecycleToReplyOptions, createChannelIngressError, createChannelIngressMonitor, createMessageReceiptFromOutboundResults, waitUntilAbort } from "openclaw/plugin-sdk/channel-outbound";
8
8
  import { expectDefined } from "openclaw/plugin-sdk/expect-runtime";
9
- import { asFiniteNumber, asNullableRecord, filterStringEntries, normalizeLowercaseStringOrEmpty, normalizeNullableString, readStringField, uniqueStrings } from "openclaw/plugin-sdk/string-coerce-runtime";
9
+ import { asBoolean, asFiniteNumber, asNullableRecord, filterStringEntries, normalizeLowercaseStringOrEmpty, normalizeNullableString, readStringField, uniqueStrings } from "openclaw/plugin-sdk/string-coerce-runtime";
10
10
  import crypto, { randomBytes, randomUUID } from "node:crypto";
11
11
  import { readProviderJsonResponse, readResponseTextLimited } from "openclaw/plugin-sdk/provider-http";
12
12
  import { escapeRegExp, runChannelProbe, sliceUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
@@ -19,7 +19,6 @@ import { da, scot } from "@urbit/aura";
19
19
  import { Readable } from "node:stream";
20
20
  import { resolveTimerTimeoutMs } from "openclaw/plugin-sdk/number-runtime";
21
21
  import { resolveAllowlistMatchByCandidates } from "openclaw/plugin-sdk/allow-from";
22
- import { isRecord } from "openclaw/plugin-sdk/channel-secret-basic-runtime";
23
22
  import { MAX_IMAGE_BYTES, readRemoteMediaBuffer, saveRemoteMedia } from "openclaw/plugin-sdk/media-runtime";
24
23
  import { resolveChannelImplicitMentions } from "openclaw/plugin-sdk/channel-ingress-runtime";
25
24
  import { bufferToBlobPart } from "openclaw/plugin-sdk/blob-runtime";
@@ -29,19 +28,17 @@ import { extensionForMime } from "openclaw/plugin-sdk/media-mime";
29
28
  //#region extensions/tlon/src/settings.ts
30
29
  const SETTINGS_DESK = "moltbot";
31
30
  const SETTINGS_BUCKET = "tlon";
32
- /**
33
- * Parse channelRules - handles both JSON string and object formats.
34
- * Settings-store doesn't support nested objects, so we store as JSON string.
35
- */
36
- function parseChannelRules(value) {
37
- if (!value) return;
38
- if (typeof value === "string") try {
39
- const parsed = JSON.parse(value);
40
- if (isChannelRulesObject(parsed)) return parsed;
31
+ function parseJsonSetting(value) {
32
+ if (typeof value !== "string") return value;
33
+ try {
34
+ return JSON.parse(value);
41
35
  } catch {
42
36
  return;
43
37
  }
44
- if (isChannelRulesObject(value)) return value;
38
+ }
39
+ function parseChannelRules(value) {
40
+ const parsed = parseJsonSetting(value);
41
+ return isChannelRulesObject(parsed) ? parsed : void 0;
45
42
  }
46
43
  /**
47
44
  * Parse settings from the raw Urbit settings-store response.
@@ -55,10 +52,10 @@ function parseSettingsResponse(raw) {
55
52
  return {
56
53
  groupChannels: Array.isArray(settings.groupChannels) ? filterStringEntries(settings.groupChannels) : void 0,
57
54
  dmAllowlist: Array.isArray(settings.dmAllowlist) ? filterStringEntries(settings.dmAllowlist) : void 0,
58
- autoDiscoverChannels: typeof settings.autoDiscoverChannels === "boolean" ? settings.autoDiscoverChannels : void 0,
59
- showModelSig: typeof settings.showModelSig === "boolean" ? settings.showModelSig : void 0,
60
- autoAcceptDmInvites: typeof settings.autoAcceptDmInvites === "boolean" ? settings.autoAcceptDmInvites : void 0,
61
- autoAcceptGroupInvites: typeof settings.autoAcceptGroupInvites === "boolean" ? settings.autoAcceptGroupInvites : void 0,
55
+ autoDiscoverChannels: asBoolean(settings.autoDiscoverChannels),
56
+ showModelSig: asBoolean(settings.showModelSig),
57
+ autoAcceptDmInvites: asBoolean(settings.autoAcceptDmInvites),
58
+ autoAcceptGroupInvites: asBoolean(settings.autoAcceptGroupInvites),
62
59
  groupInviteAllowlist: Array.isArray(settings.groupInviteAllowlist) ? filterStringEntries(settings.groupInviteAllowlist) : void 0,
63
60
  channelRules: parseChannelRules(settings.channelRules),
64
61
  defaultAuthorizedShips: Array.isArray(settings.defaultAuthorizedShips) ? filterStringEntries(settings.defaultAuthorizedShips) : void 0,
@@ -71,18 +68,8 @@ function isChannelRulesObject(val) {
71
68
  for (const [, rule] of Object.entries(val)) if (!rule || typeof rule !== "object") return false;
72
69
  return true;
73
70
  }
74
- /**
75
- * Parse pendingApprovals - handles both JSON string and array formats.
76
- * Settings-store stores complex objects as JSON strings.
77
- */
78
71
  function parsePendingApprovals(value) {
79
- if (!value) return;
80
- let parsed = value;
81
- if (typeof value === "string") try {
82
- parsed = JSON.parse(value);
83
- } catch {
84
- return;
85
- }
72
+ const parsed = parseJsonSetting(value);
86
73
  if (!Array.isArray(parsed)) return;
87
74
  return parsed.filter((item) => {
88
75
  if (!item || typeof item !== "object") return false;
@@ -122,14 +109,6 @@ async function putTlonSetting(api, key, value) {
122
109
  }
123
110
  function createSettingsManager(api, logger) {
124
111
  let current = {};
125
- const listeners = /* @__PURE__ */ new Set();
126
- const notify = () => {
127
- for (const listener of listeners) try {
128
- listener(current);
129
- } catch (err) {
130
- logger?.error?.(`[settings] Listener error: ${String(err)}`);
131
- }
132
- };
133
112
  return {
134
113
  async load() {
135
114
  try {
@@ -143,7 +122,7 @@ function createSettingsManager(api, logger) {
143
122
  return current;
144
123
  }
145
124
  },
146
- async startSubscription() {
125
+ async startSubscription(onChange) {
147
126
  await api.subscribe({
148
127
  app: "settings",
149
128
  path: "/desk/moltbot",
@@ -152,7 +131,11 @@ function createSettingsManager(api, logger) {
152
131
  if (!update) return;
153
132
  logger?.log?.(`[settings] Update: ${update.key} = ${JSON.stringify(update.value)}`);
154
133
  current = applySettingsUpdate(current, update.key, update.value);
155
- notify();
134
+ try {
135
+ onChange(current);
136
+ } catch (err) {
137
+ logger?.error?.(`[settings] Listener error: ${String(err)}`);
138
+ }
156
139
  },
157
140
  err: (error) => {
158
141
  logger?.error?.(`[settings] Subscription error: ${String(error)}`);
@@ -162,10 +145,6 @@ function createSettingsManager(api, logger) {
162
145
  }
163
146
  });
164
147
  logger?.log?.("[settings] Subscribed to settings updates");
165
- },
166
- onChange(listener) {
167
- listeners.add(listener);
168
- return () => listeners.delete(listener);
169
148
  }
170
149
  };
171
150
  }
@@ -216,8 +195,7 @@ async function urbitFetch(params) {
216
195
  signal: params.signal,
217
196
  policy: params.ssrfPolicy,
218
197
  lookupFn: params.lookupFn,
219
- auditContext: params.auditContext,
220
- pinDns: params.pinDns
198
+ auditContext: params.auditContext
221
199
  });
222
200
  return {
223
201
  ...guarded,
@@ -243,7 +221,7 @@ async function authenticate(url, code, options = {}) {
243
221
  lookupFn: options.lookupFn,
244
222
  fetchImpl: options.fetchImpl,
245
223
  beforeRequest: options.beforeRequest,
246
- timeoutMs: options.timeoutMs ?? 15e3,
224
+ timeoutMs: 15e3,
247
225
  maxRedirects: 3,
248
226
  auditContext: "tlon-urbit-login"
249
227
  });
@@ -259,15 +237,6 @@ async function authenticate(url, code, options = {}) {
259
237
  }
260
238
  //#endregion
261
239
  //#region extensions/tlon/src/urbit/context.ts
262
- function resolveShipFromHostname(hostname) {
263
- const trimmed = normalizeUrbitHostname(hostname);
264
- if (!trimmed) return "";
265
- if (trimmed.includes(".")) return trimmed.split(".")[0] ?? trimmed;
266
- return trimmed;
267
- }
268
- function normalizeUrbitShip(ship, hostname) {
269
- return (ship?.replace(/^~/, "") ?? resolveShipFromHostname(hostname)).trim();
270
- }
271
240
  function normalizeUrbitCookie(cookie) {
272
241
  return cookie.split(";")[0] ?? cookie;
273
242
  }
@@ -277,16 +246,11 @@ function getUrbitContext(url, ship) {
277
246
  return {
278
247
  baseUrl: validated.baseUrl,
279
248
  hostname: validated.hostname,
280
- ship: normalizeUrbitShip(ship, validated.hostname)
249
+ ship: (ship?.replace(/^~/, "") ?? validated.hostname.split(".")[0] ?? validated.hostname).trim()
281
250
  };
282
251
  }
283
252
  //#endregion
284
253
  //#region extensions/tlon/src/urbit/story.ts
285
- /**
286
- * Tlon Story Format - Rich text converter
287
- *
288
- * Converts markdown-like text to Tlon's story format.
289
- */
290
254
  const INLINE_MARKDOWN_RULES = [
291
255
  {
292
256
  pattern: /^(~[a-z][-a-z0-9]*)/,
@@ -373,11 +337,11 @@ function mergeAdjacentStrings(inlines) {
373
337
  }
374
338
  return result;
375
339
  }
376
- function createImageBlock(src, alt = "", height = 0, width = 0) {
340
+ function createImageBlock(src, alt = "") {
377
341
  return { block: { image: {
378
342
  src,
379
- height,
380
- width,
343
+ height: 0,
344
+ width: 0,
381
345
  alt
382
346
  } } };
383
347
  }
@@ -389,24 +353,14 @@ function isImageUrl(url) {
389
353
  } catch {}
390
354
  return imageExtensions.test(path);
391
355
  }
392
- /**
393
- * Process inlines and extract any image markers into blocks
394
- */
395
- function processInlinesForImages(inlines) {
396
- const cleanInlines = [];
397
- const imageBlocks = [];
398
- for (const inline of inlines) if (typeof inline === "object" && "imageBlock" in inline) {
399
- const img = inline.imageBlock;
400
- imageBlocks.push(createImageBlock(img.src, img.alt));
401
- } else cleanInlines.push(inline);
402
- return {
403
- inlines: cleanInlines,
404
- imageBlocks
405
- };
406
- }
407
356
  function parseInlinesWithBreaks(text) {
408
357
  const withBreaks = [];
358
+ const imageBlocks = [];
409
359
  for (const inline of parseInlineMarkdown(text)) {
360
+ if (typeof inline === "object" && "imageBlock" in inline) {
361
+ imageBlocks.push(createImageBlock(inline.imageBlock.src, inline.imageBlock.alt));
362
+ continue;
363
+ }
410
364
  if (typeof inline !== "string" || !inline.includes("\n")) {
411
365
  withBreaks.push(inline);
412
366
  continue;
@@ -417,7 +371,10 @@ function parseInlinesWithBreaks(text) {
417
371
  if (index < parts.length - 1) withBreaks.push({ break: null });
418
372
  }
419
373
  }
420
- return processInlinesForImages(withBreaks);
374
+ return {
375
+ inlines: withBreaks,
376
+ imageBlocks
377
+ };
421
378
  }
422
379
  const MARKDOWN_LIST_ITEM_PATTERN = /^([ \t]*)([-+*]|\d{1,9}[.)])(?:([ \t]+)(.*))?$/;
423
380
  function isMarkdownThematicBreak(text) {
@@ -711,19 +668,18 @@ async function sendGroupMessageWithStory({ api, fromShip, hostShip, channelName,
711
668
  if (replyToId && /^\d+$/.test(replyToId)) try {
712
669
  formattedReplyId = scot("ud", BigInt(replyToId));
713
670
  } catch {}
671
+ const memo = {
672
+ content: story,
673
+ author: fromShip,
674
+ sent: sentAt
675
+ };
714
676
  const action = { channel: {
715
677
  nest: `chat/${hostShip}/${channelName}`,
716
- action: formattedReplyId ? { post: { reply: {
678
+ action: { post: formattedReplyId ? { reply: {
717
679
  id: formattedReplyId,
718
- action: { add: {
719
- content: story,
720
- author: fromShip,
721
- sent: sentAt
722
- } }
723
- } } } : { post: { add: {
724
- content: story,
725
- author: fromShip,
726
- sent: sentAt,
680
+ action: { add: memo }
681
+ } } : { add: {
682
+ ...memo,
727
683
  kind: "/chat",
728
684
  blob: null,
729
685
  meta: null
@@ -774,8 +730,9 @@ async function putUrbitChannel(deps, params) {
774
730
  ssrfPolicy: deps.ssrfPolicy,
775
731
  lookupFn: deps.lookupFn,
776
732
  fetchImpl: deps.fetchImpl,
777
- timeoutMs: 3e4,
778
- auditContext: params.auditContext
733
+ timeoutMs: params.timeoutMs,
734
+ auditContext: params.auditContext,
735
+ beforeRequest: params.beforeRequest
779
736
  });
780
737
  }
781
738
  const TLON_ERROR_BODY_LIMIT_BYTES = 16384;
@@ -790,7 +747,8 @@ async function pokeUrbitChannel(deps, params) {
790
747
  mark: params.mark,
791
748
  json: params.json
792
749
  }],
793
- auditContext: params.auditContext
750
+ auditContext: params.auditContext,
751
+ timeoutMs: 3e4
794
752
  });
795
753
  try {
796
754
  if (!response.ok && response.status !== 204) {
@@ -832,19 +790,27 @@ async function scryUrbitPath(deps, params) {
832
790
  await release();
833
791
  }
834
792
  }
835
- async function createUrbitChannel(deps, params) {
836
- const { response, release } = await putUrbitChannel(deps, params);
793
+ async function openUrbitChannelStep(deps, params) {
794
+ const { response, release } = await putUrbitChannel(deps, {
795
+ ...params,
796
+ timeoutMs: 3e4
797
+ });
837
798
  try {
838
799
  if (!response.ok && response.status !== 204) throw new UrbitHttpError({
839
- operation: "Channel creation",
800
+ operation: params.operation,
840
801
  status: response.status
841
802
  });
842
803
  } finally {
843
804
  await release();
844
805
  }
845
806
  }
846
- async function wakeUrbitChannel(deps) {
847
- const { response, release } = await putUrbitChannel(deps, {
807
+ async function ensureUrbitChannelOpen(deps, params) {
808
+ await openUrbitChannelStep(deps, {
809
+ body: params.createBody,
810
+ auditContext: params.createAuditContext,
811
+ operation: "Channel creation"
812
+ });
813
+ await openUrbitChannelStep(deps, {
848
814
  body: [{
849
815
  id: Date.now(),
850
816
  action: "poke",
@@ -853,23 +819,9 @@ async function wakeUrbitChannel(deps) {
853
819
  mark: "helm-hi",
854
820
  json: "Opening API channel"
855
821
  }],
856
- auditContext: "tlon-urbit-channel-wake"
822
+ auditContext: "tlon-urbit-channel-wake",
823
+ operation: "Channel activation"
857
824
  });
858
- try {
859
- if (!response.ok && response.status !== 204) throw new UrbitHttpError({
860
- operation: "Channel activation",
861
- status: response.status
862
- });
863
- } finally {
864
- await release();
865
- }
866
- }
867
- async function ensureUrbitChannelOpen(deps, params) {
868
- await createUrbitChannel(deps, {
869
- body: params.createBody,
870
- auditContext: params.createAuditContext
871
- });
872
- await wakeUrbitChannel(deps);
873
825
  }
874
826
  //#endregion
875
827
  //#region extensions/tlon/src/urbit/sse-client.ts
@@ -906,7 +858,6 @@ var UrbitSSEClient = class {
906
858
  this.cookie = normalizeUrbitCookie(cookie);
907
859
  this.ship = ctx.ship;
908
860
  this.channelId = `${Math.floor(Date.now() / 1e3)}-${randomUUID()}`;
909
- this.channelUrl = new URL(`/~/channel/${this.channelId}`, this.url).toString();
910
861
  this.onReconnect = options.onReconnect ?? null;
911
862
  this.autoReconnect = options.autoReconnect !== false;
912
863
  this.maxReconnectAttempts = options.maxReconnectAttempts ?? 10;
@@ -930,7 +881,6 @@ var UrbitSSEClient = class {
930
881
  }
931
882
  resetChannelIdentity() {
932
883
  this.channelId = `${Math.floor(Date.now() / 1e3)}-${randomUUID()}`;
933
- this.channelUrl = new URL(`/~/channel/${this.channelId}`, this.url).toString();
934
884
  this.lastHeardEventId = -1;
935
885
  this.lastAcknowledgedEventId = -1;
936
886
  }
@@ -963,7 +913,8 @@ var UrbitSSEClient = class {
963
913
  return subId;
964
914
  }
965
915
  async sendSubscription(subscription) {
966
- const { response, release } = await this.putChannelPayload([subscription], {
916
+ const { response, release } = await putUrbitChannel(this.channelRequestContext(), {
917
+ body: [subscription],
967
918
  timeoutMs: 3e4,
968
919
  auditContext: "tlon-urbit-subscribe"
969
920
  });
@@ -1146,10 +1097,6 @@ var UrbitSSEClient = class {
1146
1097
  auditContext: "tlon-urbit-scry"
1147
1098
  });
1148
1099
  }
1149
- /**
1150
- * Update the cookie used for authentication.
1151
- * Call this when re-authenticating after session expiry.
1152
- */
1153
1100
  updateCookie(newCookie) {
1154
1101
  this.cookie = normalizeUrbitCookie(newCookie);
1155
1102
  }
@@ -1159,7 +1106,8 @@ var UrbitSSEClient = class {
1159
1106
  action: "ack",
1160
1107
  "event-id": eventId
1161
1108
  };
1162
- const { response, release } = await this.putChannelPayload([ackData], {
1109
+ const { response, release } = await putUrbitChannel(this.channelRequestContext(), {
1110
+ body: [ackData],
1163
1111
  timeoutMs: 1e4,
1164
1112
  auditContext: "tlon-urbit-ack"
1165
1113
  });
@@ -1218,7 +1166,8 @@ var UrbitSSEClient = class {
1218
1166
  subscription: sub.id
1219
1167
  }));
1220
1168
  {
1221
- const { release } = await this.putChannelPayload(unsubscribes, {
1169
+ const { release } = await putUrbitChannel(this.channelRequestContext(), {
1170
+ body: unsubscribes,
1222
1171
  timeoutMs: 3e4,
1223
1172
  auditContext: "tlon-urbit-unsubscribe"
1224
1173
  });
@@ -1258,25 +1207,6 @@ var UrbitSSEClient = class {
1258
1207
  throw error;
1259
1208
  }
1260
1209
  }
1261
- async putChannelPayload(payload, params) {
1262
- return await urbitFetch({
1263
- baseUrl: this.url,
1264
- path: `/~/channel/${this.channelId}`,
1265
- init: {
1266
- method: "PUT",
1267
- headers: {
1268
- "Content-Type": "application/json",
1269
- Cookie: this.cookie
1270
- },
1271
- body: JSON.stringify(payload)
1272
- },
1273
- ssrfPolicy: this.ssrfPolicy,
1274
- lookupFn: this.lookupFn,
1275
- fetchImpl: this.fetchImpl,
1276
- timeoutMs: params.timeoutMs,
1277
- auditContext: params.auditContext
1278
- });
1279
- }
1280
1210
  };
1281
1211
  //#endregion
1282
1212
  //#region extensions/tlon/src/monitor/approval.ts
@@ -1308,13 +1238,6 @@ function formatApprovalRequest(approval) {
1308
1238
  }
1309
1239
  throw new Error("Unsupported approval type");
1310
1240
  }
1311
- /**
1312
- * Parse an owner's response to an approval request.
1313
- * Supports formats:
1314
- * - "approve" / "deny" / "block" (applies to most recent pending)
1315
- * - "approve dm-1234567890-abc" / "deny dm-1234567890-abc" (specific ID)
1316
- * - "block" permanently blocks the ship via Tlon's native blocking
1317
- */
1318
1241
  function parseApprovalResponse(text) {
1319
1242
  const match = normalizeLowercaseStringOrEmpty(text).match(/^(approve|deny|block)(?:\s+(.+))?$/);
1320
1243
  if (!match) return null;
@@ -1346,13 +1269,6 @@ function formatApprovalConfirmation(approval, action) {
1346
1269
  }
1347
1270
  throw new Error("Unsupported approval type");
1348
1271
  }
1349
- /**
1350
- * Parse an admin command from owner message.
1351
- * Supports:
1352
- * - "unblock ~ship" - unblock a specific ship
1353
- * - "blocked" - list all blocked ships
1354
- * - "pending" - list all pending approvals
1355
- */
1356
1272
  function parseAdminCommand(text) {
1357
1273
  const trimmed = normalizeLowercaseStringOrEmpty(text);
1358
1274
  if (trimmed === "blocked") return { type: "blocked" };
@@ -1636,52 +1552,10 @@ function resolveChannelAuthorization(cfg, channelNest, settings) {
1636
1552
  }
1637
1553
  //#endregion
1638
1554
  //#region extensions/tlon/src/monitor/utils.ts
1639
- function extractCites(content) {
1640
- if (!content || !Array.isArray(content)) return [];
1641
- const cites = [];
1642
- for (const verse of content) {
1643
- const verseRecord = asNullableRecord(verse);
1644
- const block = asNullableRecord(verseRecord?.block);
1645
- const cite = asNullableRecord(block?.cite);
1646
- if (cite) {
1647
- const chan = asNullableRecord(cite.chan);
1648
- const group = readStringField(cite, "group");
1649
- const desk = asNullableRecord(cite.desk);
1650
- const bait = asNullableRecord(cite.bait);
1651
- if (chan) {
1652
- const nest = readStringField(chan, "nest");
1653
- const where = readStringField(chan, "where");
1654
- const whereMatch = where?.match(/\/msg\/(~[a-z-]+)\/(.+)/);
1655
- cites.push({
1656
- type: "chan",
1657
- nest,
1658
- where,
1659
- author: whereMatch?.[1],
1660
- postId: whereMatch?.[2]
1661
- });
1662
- } else if (group) cites.push({
1663
- type: "group",
1664
- group
1665
- });
1666
- else if (desk) cites.push({
1667
- type: "desk",
1668
- flag: readStringField(desk, "flag"),
1669
- where: readStringField(desk, "where")
1670
- });
1671
- else if (bait) cites.push({
1672
- type: "bait",
1673
- group: readStringField(bait, "group"),
1674
- nest: readStringField(bait, "graph"),
1675
- where: readStringField(bait, "where")
1676
- });
1677
- }
1678
- }
1679
- return cites;
1680
- }
1681
1555
  function formatModelName(modelString) {
1682
1556
  if (!modelString) return "AI";
1683
1557
  const modelName = modelString.includes("/") ? expectDefined(modelString.split("/").at(1), "provider/model second segment") : modelString;
1684
- const mappedName = {
1558
+ const modelMappings = {
1685
1559
  "claude-opus-4-5": "Claude Opus 4.5",
1686
1560
  "claude-sonnet-4-5": "Claude Sonnet 4.5",
1687
1561
  "claude-sonnet-3-5": "Claude Sonnet 3.5",
@@ -1690,7 +1564,8 @@ function formatModelName(modelString) {
1690
1564
  "gpt-4": "GPT-4",
1691
1565
  "gemini-2.0-flash": "Gemini 2.0 Flash",
1692
1566
  "gemini-pro": "Gemini Pro"
1693
- }[modelName];
1567
+ };
1568
+ const mappedName = Object.hasOwn(modelMappings, modelName) ? modelMappings[modelName] : void 0;
1694
1569
  if (mappedName !== void 0) return mappedName;
1695
1570
  return modelName.replace(/-/g, " ").split(" ").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
1696
1571
  }
@@ -1729,8 +1604,7 @@ async function isDmAllowedWithIngress(senderShip, allowlist) {
1729
1604
  conversation: {
1730
1605
  kind: "direct",
1731
1606
  id: "direct"
1732
- },
1733
- dmPolicy: "allowlist"
1607
+ }
1734
1608
  })).senderAccess.allowed;
1735
1609
  }
1736
1610
  async function resolveTlonMessageIngress(params) {
@@ -1741,7 +1615,7 @@ async function resolveTlonMessageIngress(params) {
1741
1615
  subject: { stableId: params.senderShip },
1742
1616
  conversation: params.conversation,
1743
1617
  contextBinding: params.contextBinding,
1744
- dmPolicy: params.dmPolicy ?? "allowlist",
1618
+ dmPolicy: "allowlist",
1745
1619
  groupPolicy: params.groupPolicy ?? "open",
1746
1620
  allowFrom: params.allowFrom,
1747
1621
  groupAllowFrom: params.allowFrom
@@ -1753,7 +1627,7 @@ async function resolveTlonCommandAuthorizationWithIngress(params) {
1753
1627
  channelId: "tlon",
1754
1628
  accountId: "default",
1755
1629
  identity: tlonIngressIdentity,
1756
- useAccessGroups: params.useAccessGroups,
1630
+ useAccessGroups: true,
1757
1631
  subject: { stableId: params.senderShip },
1758
1632
  conversation: {
1759
1633
  kind: "direct",
@@ -1779,12 +1653,7 @@ function isGroupInviteAllowed(inviterShip, allowlist) {
1779
1653
  }]
1780
1654
  }).allowed;
1781
1655
  }
1782
- async function resolveAuthorizedMessageText(params) {
1783
- const { rawText, content, authorizedForCites, resolveAllCites } = params;
1784
- if (!authorizedForCites) return rawText;
1785
- return await resolveAllCites(content) + rawText;
1786
- }
1787
- function renderInlineItem(item, options) {
1656
+ function renderInlineItem(item, topLevel = false) {
1788
1657
  if (typeof item === "string") return item;
1789
1658
  const record = asNullableRecord(item);
1790
1659
  if (!record) return "";
@@ -1795,21 +1664,19 @@ function renderInlineItem(item, options) {
1795
1664
  if (typeof sect === "string") return `@${sect || "all"}`;
1796
1665
  if (sect === null) return "@all";
1797
1666
  }
1798
- if (options?.allowBreak && "break" in record) return "\n";
1799
- const inlineCode = readStringField(record, "inline-code");
1800
- if (inlineCode) return `\`${inlineCode}\``;
1801
- const code = readStringField(record, "code");
1667
+ if (topLevel && "break" in record) return "\n";
1668
+ const code = readStringField(record, "inline-code") || readStringField(record, "code");
1802
1669
  if (code) return `\`${code}\``;
1803
1670
  const link = asNullableRecord(record.link);
1804
1671
  const linkHref = link ? readStringField(link, "href") : void 0;
1805
1672
  if (link && linkHref) {
1806
1673
  const linkContent = readStringField(link, "content");
1807
- return options?.linkMode === "href" ? linkHref : linkContent || linkHref;
1674
+ return topLevel ? linkHref : linkContent || linkHref;
1808
1675
  }
1809
1676
  if (Array.isArray(record.bold)) return `**${extractInlineText(record.bold)}**`;
1810
1677
  if (Array.isArray(record.italics)) return `*${extractInlineText(record.italics)}*`;
1811
1678
  if (Array.isArray(record.strike)) return `~~${extractInlineText(record.strike)}~~`;
1812
- if (options?.allowBlockquote && Array.isArray(record.blockquote)) return `> ${extractInlineText(record.blockquote)}`;
1679
+ if (topLevel && Array.isArray(record.blockquote)) return `> ${extractInlineText(record.blockquote)}`;
1813
1680
  return "";
1814
1681
  }
1815
1682
  function extractInlineText(items) {
@@ -1820,11 +1687,7 @@ function extractMessageText(content) {
1820
1687
  return content.map((verse) => {
1821
1688
  const verseRecord = asNullableRecord(verse);
1822
1689
  if (!verseRecord) return "";
1823
- if (Array.isArray(verseRecord.inline)) return verseRecord.inline.map((item) => renderInlineItem(item, {
1824
- linkMode: "href",
1825
- allowBreak: true,
1826
- allowBlockquote: true
1827
- })).join("");
1690
+ if (Array.isArray(verseRecord.inline)) return verseRecord.inline.map((item) => renderInlineItem(item, true)).join("");
1828
1691
  const block = asNullableRecord(verseRecord.block);
1829
1692
  if (block) {
1830
1693
  const image = asNullableRecord(block.image);
@@ -1919,9 +1782,8 @@ function buildCitedPostScryPath(nest, postId) {
1919
1782
  }
1920
1783
  function createTlonCitationResolver(params) {
1921
1784
  const { api, runtime } = params;
1922
- const resolveCiteContent = async (cite) => {
1923
- if (cite.type !== "chan" || !cite.nest || !cite.postId) return null;
1924
- const scryPath = buildCitedPostScryPath(cite.nest, cite.postId);
1785
+ const resolveCiteContent = async (nest, postId) => {
1786
+ const scryPath = buildCitedPostScryPath(nest, postId);
1925
1787
  if (!scryPath) {
1926
1788
  runtime.log?.("[tlon] Skipping cited post: citation does not name a channel post");
1927
1789
  return null;
@@ -1938,19 +1800,21 @@ function createTlonCitationResolver(params) {
1938
1800
  }
1939
1801
  };
1940
1802
  const resolveAllCites = async (content) => {
1941
- const cites = extractCites(content);
1942
- if (cites.length === 0) return "";
1803
+ if (!Array.isArray(content)) return "";
1943
1804
  const resolved = [];
1944
- for (const cite of cites) {
1945
- const text = await resolveCiteContent(cite);
1946
- if (text) resolved.push(`> ${cite.author || "unknown"} wrote: ${text}`);
1805
+ for (const verse of content) {
1806
+ const block = asNullableRecord(asNullableRecord(verse)?.block);
1807
+ const chan = asNullableRecord(asNullableRecord(block?.cite)?.chan);
1808
+ const nest = readStringField(chan, "nest");
1809
+ const whereMatch = readStringField(chan, "where")?.match(/\/msg\/(~[a-z-]+)\/(.+)/);
1810
+ const postId = whereMatch?.[2];
1811
+ if (!nest || !postId) continue;
1812
+ const text = await resolveCiteContent(nest, postId);
1813
+ if (text) resolved.push(`> ${whereMatch?.[1] || "unknown"} wrote: ${text}`);
1947
1814
  }
1948
1815
  return resolved.length > 0 ? `${resolved.join("\n")}\n\n` : "";
1949
1816
  };
1950
- return {
1951
- resolveCiteContent,
1952
- resolveAllCites
1953
- };
1817
+ return { resolveAllCites };
1954
1818
  }
1955
1819
  //#endregion
1956
1820
  //#region extensions/tlon/src/monitor/discovery.ts
@@ -1962,15 +1826,7 @@ async function fetchInitData(api, runtime) {
1962
1826
  try {
1963
1827
  runtime.log?.("[tlon] Fetching groups-ui init data...");
1964
1828
  const initData = asNullableRecord(await api.scry("/groups-ui/v6/init.json"));
1965
- const channels = [];
1966
- const groups = asNullableRecord(initData?.groups);
1967
- if (groups) for (const groupData of Object.values(groups)) {
1968
- const typedGroupData = asNullableRecord(groupData);
1969
- const groupChannels = asNullableRecord(typedGroupData?.channels);
1970
- if (groupChannels) {
1971
- for (const channelNest of Object.keys(groupChannels)) if (channelNest.startsWith("chat/")) channels.push(channelNest);
1972
- }
1973
- }
1829
+ const channels = Object.values(asNullableRecord(initData?.groups) ?? {}).flatMap((group) => Object.keys(asNullableRecord(asNullableRecord(group)?.channels) ?? {}).filter((nest) => nest.startsWith("chat/")));
1974
1830
  if (channels.length > 0) runtime.log?.(`[tlon] Auto-discovered ${channels.length} chat channel(s)`);
1975
1831
  else runtime.log?.("[tlon] No chat channels found via auto-discovery");
1976
1832
  const foreignsValue = asNullableRecord(initData?.foreigns);
@@ -1991,10 +1847,6 @@ async function fetchInitData(api, runtime) {
1991
1847
  };
1992
1848
  }
1993
1849
  }
1994
- async function fetchAllChannels(api, runtime) {
1995
- const { channels } = await fetchInitData(api, runtime);
1996
- return channels;
1997
- }
1998
1850
  //#endregion
1999
1851
  //#region extensions/tlon/src/monitor/history.ts
2000
1852
  /**
@@ -2002,9 +1854,9 @@ async function fetchAllChannels(api, runtime) {
2002
1854
  * e.g., 170141184507799509469114119040828178432 -> 170.141.184.507.799.509.469.114.119.040.828.178.432
2003
1855
  */
2004
1856
  function formatUd(id) {
2005
- const reversed = String(id).replace(/\./g, "").split("").toReversed();
1857
+ const str = String(id).replace(/\./g, "");
2006
1858
  const chunks = [];
2007
- for (let i = 0; i < reversed.length; i += 3) chunks.push(reversed.slice(i, i + 3).toReversed().join(""));
1859
+ for (let end = str.length; end > 0; end -= 3) chunks.push(str.slice(Math.max(0, end - 3), end));
2008
1860
  return chunks.toReversed().join(".");
2009
1861
  }
2010
1862
  function createHistoryEntryFromMemo(params) {
@@ -2023,15 +1875,8 @@ async function fetchChannelHistory(api, channelNest, count = 50, runtime) {
2023
1875
  runtime?.log?.(`[tlon] Fetching history: ${scryPath}`);
2024
1876
  const data = await api.scry(scryPath);
2025
1877
  if (!data) return [];
2026
- let posts = [];
2027
- if (Array.isArray(data)) posts = data;
2028
- else {
2029
- const dataRecord = asNullableRecord(data);
2030
- const postMap = asNullableRecord(dataRecord?.posts);
2031
- if (postMap) posts = Object.values(postMap);
2032
- else if (dataRecord) posts = Object.values(dataRecord);
2033
- }
2034
- const messages = posts.map((item) => {
1878
+ const dataRecord = asNullableRecord(data);
1879
+ const messages = (Array.isArray(data) ? data : Object.values(asNullableRecord(dataRecord?.posts) ?? dataRecord ?? {})).map((item) => {
2035
1880
  const itemRecord = asNullableRecord(item);
2036
1881
  const replyPost = asNullableRecord(itemRecord?.["r-post"]);
2037
1882
  const replyPostSet = asNullableRecord(replyPost?.set);
@@ -2146,30 +1991,30 @@ const TLON_INGRESS_PAYLOAD_VERSION = 1;
2146
1991
  const TLON_INGRESS_POLL_INTERVAL_MS = 1e3;
2147
1992
  const TlonIngressPermanentError = createChannelIngressError("TlonIngressPermanentError", { withReason: true });
2148
1993
  function inspectChannelsEvent(event) {
2149
- const envelope = isRecord(event) ? event : null;
1994
+ const envelope = asNullableRecord(event);
2150
1995
  const nest = normalizeNullableString(envelope?.nest);
2151
- const response = isRecord(envelope?.response) ? envelope.response : null;
2152
- const post = isRecord(response?.post) ? response.post : null;
2153
- const rPost = isRecord(post?.["r-post"]) ? post["r-post"] : null;
2154
- const set = isRecord(rPost?.set) ? rPost.set : null;
2155
- const reply = isRecord(rPost?.reply) ? rPost.reply : null;
2156
- const rReply = isRecord(reply?.["r-reply"]) ? reply["r-reply"] : null;
2157
- const replySet = isRecord(rReply?.set) ? rReply.set : null;
2158
- if (!nest || !isRecord(set?.essay) && !isRecord(replySet?.memo)) return null;
2159
- const eventId = normalizeNullableString(isRecord(replySet?.memo) ? reply?.id : post?.id);
1996
+ const response = asNullableRecord(envelope?.response);
1997
+ const post = asNullableRecord(response?.post);
1998
+ const rPost = asNullableRecord(post?.["r-post"]);
1999
+ const set = asNullableRecord(rPost?.set);
2000
+ const reply = asNullableRecord(rPost?.reply);
2001
+ const rReply = asNullableRecord(reply?.["r-reply"]);
2002
+ const replySet = asNullableRecord(rReply?.set);
2003
+ if (!nest || !asNullableRecord(set?.essay) && !asNullableRecord(replySet?.memo)) return null;
2004
+ const eventId = normalizeNullableString(asNullableRecord(replySet?.memo) ? reply?.id : post?.id);
2160
2005
  return eventId ? {
2161
2006
  eventId,
2162
2007
  laneKey: `group:${nest}`
2163
2008
  } : null;
2164
2009
  }
2165
2010
  function inspectChatEvent(event) {
2166
- const envelope = isRecord(event) ? event : null;
2167
- const response = isRecord(envelope?.response) ? envelope.response : null;
2168
- const add = isRecord(response?.add) ? response.add : null;
2169
- const essay = isRecord(add?.essay) ? add.essay : null;
2011
+ const envelope = asNullableRecord(event);
2012
+ const response = asNullableRecord(envelope?.response);
2013
+ const add = asNullableRecord(response?.add);
2014
+ const essay = asNullableRecord(add?.essay);
2170
2015
  const eventId = normalizeNullableString(envelope?.id);
2171
2016
  if (!essay || !eventId) return null;
2172
- const whom = isRecord(envelope?.whom) ? normalizeNullableString(envelope.whom.ship) : null;
2017
+ const whom = normalizeNullableString(asNullableRecord(envelope?.whom)?.ship);
2173
2018
  const peer = normalizeNullableString(envelope?.whom) ?? whom ?? normalizeNullableString(essay.author);
2174
2019
  return {
2175
2020
  eventId,
@@ -2453,54 +2298,31 @@ function shouldMigrateTlonSetting(fileValue, settingsValue) {
2453
2298
  return (Array.isArray(fileValue) ? fileValue.length > 0 : fileValue != null) && !(settingsValue != null);
2454
2299
  }
2455
2300
  function applyTlonSettingsOverrides(params) {
2456
- let effectiveDmAllowlist = params.account.dmAllowlist;
2457
- let effectiveShowModelSig = params.account.showModelSignature ?? false;
2458
- let effectiveAutoAcceptDmInvites = params.account.autoAcceptDmInvites ?? false;
2459
- let effectiveAutoAcceptGroupInvites = params.account.autoAcceptGroupInvites ?? false;
2460
- let effectiveGroupInviteAllowlist = params.account.groupInviteAllowlist;
2461
- let effectiveAutoDiscoverChannels = params.account.autoDiscoverChannels ?? false;
2462
- let effectiveOwnerShip = params.account.ownerShip ? normalizeShip(params.account.ownerShip) : null;
2463
- let pendingApprovals = [];
2464
- if (params.currentSettings.defaultAuthorizedShips?.length) params.log?.(`[tlon] Using defaultAuthorizedShips from settings store: ${params.currentSettings.defaultAuthorizedShips.join(", ")}`);
2465
- if (params.currentSettings.autoDiscoverChannels !== void 0) {
2466
- effectiveAutoDiscoverChannels = params.currentSettings.autoDiscoverChannels;
2467
- params.log?.(`[tlon] Using autoDiscoverChannels from settings store: ${effectiveAutoDiscoverChannels}`);
2468
- }
2469
- if (params.currentSettings.dmAllowlist !== void 0) {
2470
- effectiveDmAllowlist = params.currentSettings.dmAllowlist;
2471
- params.log?.(`[tlon] Using dmAllowlist from settings store: ${effectiveDmAllowlist.join(", ")}`);
2472
- }
2473
- if (params.currentSettings.showModelSig !== void 0) effectiveShowModelSig = params.currentSettings.showModelSig;
2474
- if (params.currentSettings.autoAcceptDmInvites !== void 0) {
2475
- effectiveAutoAcceptDmInvites = params.currentSettings.autoAcceptDmInvites;
2476
- params.log?.(`[tlon] Using autoAcceptDmInvites from settings store: ${effectiveAutoAcceptDmInvites}`);
2477
- }
2478
- if (params.currentSettings.autoAcceptGroupInvites !== void 0) {
2479
- effectiveAutoAcceptGroupInvites = params.currentSettings.autoAcceptGroupInvites;
2480
- params.log?.(`[tlon] Using autoAcceptGroupInvites from settings store: ${effectiveAutoAcceptGroupInvites}`);
2481
- }
2482
- if (params.currentSettings.groupInviteAllowlist !== void 0) {
2483
- effectiveGroupInviteAllowlist = params.currentSettings.groupInviteAllowlist;
2484
- params.log?.(`[tlon] Using groupInviteAllowlist from settings store: ${effectiveGroupInviteAllowlist.join(", ")}`);
2485
- }
2486
- if (params.currentSettings.ownerShip) {
2487
- effectiveOwnerShip = normalizeShip(params.currentSettings.ownerShip);
2488
- params.log?.(`[tlon] Using ownerShip from settings store: ${effectiveOwnerShip}`);
2489
- }
2490
- if (params.currentSettings.pendingApprovals?.length) {
2491
- pendingApprovals = params.currentSettings.pendingApprovals;
2492
- params.log?.(`[tlon] Loaded ${pendingApprovals.length} pending approval(s) from settings`);
2493
- }
2301
+ const { account, currentSettings: settings, log } = params;
2302
+ if (settings.defaultAuthorizedShips?.length) log?.(`[tlon] Using defaultAuthorizedShips from settings store: ${settings.defaultAuthorizedShips.join(", ")}`);
2303
+ for (const key of [
2304
+ "autoDiscoverChannels",
2305
+ "dmAllowlist",
2306
+ "autoAcceptDmInvites",
2307
+ "autoAcceptGroupInvites",
2308
+ "groupInviteAllowlist"
2309
+ ]) {
2310
+ const value = settings[key];
2311
+ if (value !== void 0) log?.(`[tlon] Using ${key} from settings store: ${Array.isArray(value) ? value.join(", ") : value}`);
2312
+ }
2313
+ const effectiveOwnerShip = settings.ownerShip ? normalizeShip(settings.ownerShip) : account.ownerShip ? normalizeShip(account.ownerShip) : null;
2314
+ if (settings.ownerShip) log?.(`[tlon] Using ownerShip from settings store: ${effectiveOwnerShip}`);
2315
+ if (settings.pendingApprovals?.length) log?.(`[tlon] Loaded ${settings.pendingApprovals.length} pending approval(s) from settings`);
2494
2316
  return {
2495
- effectiveDmAllowlist,
2496
- effectiveShowModelSig,
2497
- effectiveAutoAcceptDmInvites,
2498
- effectiveAutoAcceptGroupInvites,
2499
- effectiveGroupInviteAllowlist,
2500
- effectiveAutoDiscoverChannels,
2317
+ effectiveDmAllowlist: settings.dmAllowlist ?? account.dmAllowlist,
2318
+ effectiveShowModelSig: settings.showModelSig ?? account.showModelSignature ?? false,
2319
+ effectiveAutoAcceptDmInvites: settings.autoAcceptDmInvites ?? account.autoAcceptDmInvites ?? false,
2320
+ effectiveAutoAcceptGroupInvites: settings.autoAcceptGroupInvites ?? account.autoAcceptGroupInvites ?? false,
2321
+ effectiveGroupInviteAllowlist: settings.groupInviteAllowlist ?? account.groupInviteAllowlist,
2322
+ effectiveAutoDiscoverChannels: settings.autoDiscoverChannels ?? account.autoDiscoverChannels ?? false,
2501
2323
  effectiveOwnerShip,
2502
- pendingApprovals,
2503
- currentSettings: params.currentSettings
2324
+ pendingApprovals: settings.pendingApprovals?.length ? settings.pendingApprovals : [],
2325
+ currentSettings: settings
2504
2326
  };
2505
2327
  }
2506
2328
  function mergeUniqueStrings(base, next) {
@@ -2540,7 +2362,8 @@ function createActiveSnapshotTracker() {
2540
2362
  }
2541
2363
  //#endregion
2542
2364
  //#region extensions/tlon/src/monitor/index.ts
2543
- async function monitorTlonProvider(opts = {}) {
2365
+ async function monitorTlonProvider(opts) {
2366
+ const discoveryScheduler = opts.scheduler.scope();
2544
2367
  const core = getTlonRuntime();
2545
2368
  const cfg = core.config.current();
2546
2369
  if (cfg.channels?.tlon?.enabled === false) return;
@@ -2756,8 +2579,7 @@ async function monitorTlonProvider(opts = {}) {
2756
2579
  if (shouldComputeAuth) {
2757
2580
  commandAuthorized = (await resolveTlonCommandAuthorizationWithIngress({
2758
2581
  senderShip,
2759
- ownerShip: effectiveOwnerShip,
2760
- useAccessGroups: true
2582
+ ownerShip: effectiveOwnerShip
2761
2583
  })).commandAccess.authorized;
2762
2584
  if (!commandAuthorized) console.log(`[tlon] Command attempt denied: ${senderShip} is not owner (owner=${effectiveOwnerShip ?? "not configured"})`);
2763
2585
  }
@@ -2825,8 +2647,7 @@ async function monitorTlonProvider(opts = {}) {
2825
2647
  const deliveryTarget = isGroup ? channelNest : senderShip;
2826
2648
  const prepareReplyPayload = (payload) => {
2827
2649
  const replyText = payload.text;
2828
- if (!replyText) return payload;
2829
- if (!effectiveShowModelSig) return payload;
2650
+ if (!replyText || !effectiveShowModelSig) return payload;
2830
2651
  const extPayload = payload;
2831
2652
  const defaultModel = cfg.agents?.defaults?.model;
2832
2653
  const modelInfo = extPayload.metadata?.model || extPayload.model || (typeof defaultModel === "string" ? defaultModel : defaultModel?.primary);
@@ -2906,14 +2727,17 @@ async function monitorTlonProvider(opts = {}) {
2906
2727
  });
2907
2728
  };
2908
2729
  const watchedChannels = new Set(groupChannels);
2909
- const refreshWatchedChannels = async () => {
2910
- const discoveredChannels = await fetchAllChannels(api, runtime);
2911
- let newCount = 0;
2912
- for (const channelNest of discoveredChannels) if (!watchedChannels.has(channelNest)) {
2730
+ const addWatchedChannels = (channels, logPrefix) => {
2731
+ const previousCount = watchedChannels.size;
2732
+ for (const channelNest of channels) if (!watchedChannels.has(channelNest)) {
2913
2733
  watchedChannels.add(channelNest);
2914
- newCount++;
2734
+ if (logPrefix) runtime.log?.(`${logPrefix}${channelNest}`);
2915
2735
  }
2916
- return newCount;
2736
+ return watchedChannels.size - previousCount;
2737
+ };
2738
+ const refreshWatchedChannels = async () => {
2739
+ const { channels: discoveredChannels } = await fetchInitData(api, runtime);
2740
+ return addWatchedChannels(discoveredChannels);
2917
2741
  };
2918
2742
  const { resolveAllCites } = createTlonCitationResolver({
2919
2743
  api,
@@ -2961,7 +2785,7 @@ async function monitorTlonProvider(opts = {}) {
2961
2785
  id: conversationId
2962
2786
  },
2963
2787
  allowFrom: [approval.requestingShip],
2964
- ...isGroup ? { groupPolicy: "allowlist" } : { dmPolicy: "allowlist" },
2788
+ ...isGroup ? { groupPolicy: "allowlist" } : {},
2965
2789
  contextBinding
2966
2790
  })
2967
2791
  });
@@ -3038,12 +2862,7 @@ async function monitorTlonProvider(opts = {}) {
3038
2862
  } else runtime.log?.(`[tlon] Access denied: ${senderShip} in ${nest} (allowed: ${allowedShips.join(", ")})`);
3039
2863
  return;
3040
2864
  }
3041
- const messageText = await resolveAuthorizedMessageText({
3042
- rawText,
3043
- content: contentBody,
3044
- authorizedForCites: true,
3045
- resolveAllCites
3046
- });
2865
+ const messageText = await resolveAllCites(contentBody) + rawText;
3047
2866
  await processMessage({
3048
2867
  messageId,
3049
2868
  senderShip,
@@ -3148,7 +2967,6 @@ async function monitorTlonProvider(opts = {}) {
3148
2967
  id: senderShip
3149
2968
  },
3150
2969
  allowFrom: ownerDm ? [senderShip] : effectiveDmAllowlist,
3151
- dmPolicy: "allowlist",
3152
2970
  contextBinding
3153
2971
  });
3154
2972
  if (!ownerDm && !(await resolveChannelIngress()).senderAccess.allowed) {
@@ -3168,12 +2986,7 @@ async function monitorTlonProvider(opts = {}) {
3168
2986
  } else runtime.log?.(`[tlon] Blocked DM from ${senderShip}: not in allowlist`);
3169
2987
  return;
3170
2988
  }
3171
- const resolvedMessageText = await resolveAuthorizedMessageText({
3172
- rawText,
3173
- content: essay.content,
3174
- authorizedForCites: true,
3175
- resolveAllCites
3176
- });
2989
+ const resolvedMessageText = await resolveAllCites(essay.content) + rawText;
3177
2990
  if (ownerDm) runtime.log?.(`[tlon] Processing DM from owner ${senderShip}`);
3178
2991
  await processMessage({
3179
2992
  messageText: resolvedMessageText,
@@ -3263,23 +3076,16 @@ async function monitorTlonProvider(opts = {}) {
3263
3076
  }
3264
3077
  });
3265
3078
  runtime.log?.("[tlon] Subscribed to contacts updates (/v1/news)");
3266
- settingsManager.onChange((newSettings) => {
3267
- currentSettings = newSettings;
3268
- if (newSettings.groupChannels?.length) {
3269
- const newChannels = newSettings.groupChannels;
3270
- for (const ch of newChannels) if (!watchedChannels.has(ch)) {
3271
- watchedChannels.add(ch);
3272
- runtime.log?.(`[tlon] Settings: now watching channel ${ch}`);
3273
- }
3274
- }
3275
- ({effectiveDmAllowlist, effectiveShowModelSig, effectiveAutoAcceptDmInvites, effectiveAutoAcceptGroupInvites, effectiveGroupInviteAllowlist, effectiveAutoDiscoverChannels, effectiveOwnerShip, pendingApprovals} = applyTlonSettingsOverrides({
3276
- account,
3277
- currentSettings: newSettings,
3278
- log: (message) => runtime.log?.(message)
3279
- }));
3280
- });
3281
3079
  try {
3282
- await settingsManager.startSubscription();
3080
+ await settingsManager.startSubscription((newSettings) => {
3081
+ currentSettings = newSettings;
3082
+ addWatchedChannels(newSettings.groupChannels ?? [], "[tlon] Settings: now watching channel ");
3083
+ ({effectiveDmAllowlist, effectiveShowModelSig, effectiveAutoAcceptDmInvites, effectiveAutoAcceptGroupInvites, effectiveGroupInviteAllowlist, effectiveAutoDiscoverChannels, effectiveOwnerShip, pendingApprovals} = applyTlonSettingsOverrides({
3084
+ account,
3085
+ currentSettings: newSettings,
3086
+ log: (message) => runtime.log?.(message)
3087
+ }));
3088
+ });
3283
3089
  } catch (err) {
3284
3090
  runtime.log?.(`[tlon] Settings subscription not available: ${String(err)}`);
3285
3091
  }
@@ -3294,10 +3100,7 @@ async function monitorTlonProvider(opts = {}) {
3294
3100
  const join = asNullableRecord(eventRecord.join);
3295
3101
  const joinedChannels = Array.isArray(join?.channels) ? join.channels : [];
3296
3102
  const discoveredChannels = mergeUniqueStrings(Object.keys(asNullableRecord(eventRecord.channels) ?? {}), joinedChannels.filter((channel) => typeof channel === "string")).filter((channel) => channel.startsWith("chat/"));
3297
- for (const channelNest of discoveredChannels) if (!watchedChannels.has(channelNest)) {
3298
- watchedChannels.add(channelNest);
3299
- runtime.log?.(`[tlon] Auto-detected new channel: ${channelNest}`);
3300
- }
3103
+ addWatchedChannels(discoveredChannels, "[tlon] Auto-detected new channel: ");
3301
3104
  if (!effectiveAutoAcceptGroupInvites) return;
3302
3105
  const currentChannels = currentSettings.groupChannels ?? [];
3303
3106
  const unpersistedChannels = discoveredChannels.filter((channel) => !currentChannels.includes(channel));
@@ -3326,15 +3129,17 @@ async function monitorTlonProvider(opts = {}) {
3326
3129
  runtime.log?.(`[tlon] Groups-ui subscription failed (will rely on polling): ${String(err)}`);
3327
3130
  }
3328
3131
  {
3329
- const processedGroupInvites = createActiveSnapshotTracker();
3132
+ const processedGroupInvites = /* @__PURE__ */ new Set();
3330
3133
  const processPendingInvites = async (foreigns, propagateWriteFailures = false) => {
3331
3134
  if (!foreigns || typeof foreigns !== "object") return;
3332
3135
  let firstWriteError;
3333
3136
  for (const [groupFlag, foreign] of Object.entries(foreigns)) {
3137
+ const validInvite = foreign.invites?.find((invite) => invite.valid);
3138
+ if (foreign.progress === "done" || !validInvite) {
3139
+ processedGroupInvites.delete(groupFlag);
3140
+ continue;
3141
+ }
3334
3142
  if (processedGroupInvites.has(groupFlag)) continue;
3335
- if (!foreign.invites || foreign.invites.length === 0) continue;
3336
- const validInvite = foreign.invites.find((inv) => inv.valid);
3337
- if (!validInvite) continue;
3338
3143
  const inviterShip = validInvite.from;
3339
3144
  const ownerInvite = isOwner(inviterShip);
3340
3145
  if (ownerInvite || effectiveAutoAcceptGroupInvites && isGroupInviteAllowed(inviterShip, effectiveGroupInviteAllowlist)) {
@@ -3361,7 +3166,7 @@ async function monitorTlonProvider(opts = {}) {
3361
3166
  requestingShip: inviterShip,
3362
3167
  groupFlag
3363
3168
  });
3364
- processedGroupInvites.addIfAccepted(groupFlag, await queueApprovalRequest(approval));
3169
+ if (await queueApprovalRequest(approval)) processedGroupInvites.add(groupFlag);
3365
3170
  continue;
3366
3171
  }
3367
3172
  if (effectiveAutoAcceptGroupInvites) {
@@ -3401,35 +3206,36 @@ async function monitorTlonProvider(opts = {}) {
3401
3206
  }
3402
3207
  }
3403
3208
  if (effectiveAutoDiscoverChannels) {
3404
- const discoveredChannels = await fetchAllChannels(api, runtime);
3405
- for (const channelNest of discoveredChannels) watchedChannels.add(channelNest);
3209
+ const { channels: discoveredChannels } = await fetchInitData(api, runtime);
3210
+ addWatchedChannels(discoveredChannels);
3406
3211
  runtime.log?.(`[tlon] Watching ${watchedChannels.size} channel(s)`);
3407
3212
  }
3408
3213
  for (const channelNest of watchedChannels) runtime.log?.(`[tlon] Watching channel: ${channelNest}`);
3409
3214
  runtime.log?.("[tlon] All subscriptions registered, connecting to SSE stream...");
3410
3215
  await api.connect();
3216
+ if (discoveryScheduler.signal.aborted) return;
3411
3217
  ingress.start();
3412
3218
  runtime.log?.("[tlon] Connected! Firehose subscriptions active");
3413
- const pollInterval = setInterval(() => {
3414
- (async () => {
3415
- if (!opts.abortSignal?.aborted) try {
3416
- if (effectiveAutoDiscoverChannels) {
3417
- const discoveredChannels = await fetchAllChannels(api, runtime);
3418
- for (const channelNest of discoveredChannels) if (!watchedChannels.has(channelNest)) {
3419
- watchedChannels.add(channelNest);
3420
- runtime.log?.(`[tlon] Now watching new channel: ${channelNest}`);
3421
- }
3422
- }
3219
+ discoveryScheduler.schedule({
3220
+ id: "channel-discovery",
3221
+ delayMs: 12e4,
3222
+ everyMs: 12e4,
3223
+ run: async () => {
3224
+ if (!effectiveAutoDiscoverChannels) return;
3225
+ try {
3226
+ const { channels: discoveredChannels } = await fetchInitData(api, runtime);
3227
+ if (discoveryScheduler.signal.aborted) return;
3228
+ addWatchedChannels(discoveredChannels, "[tlon] Now watching new channel: ");
3423
3229
  } catch (error) {
3424
3230
  runtime.error?.(`[tlon] Channel refresh error: ${formatErrorMessage(error)}`);
3425
3231
  }
3426
- })();
3427
- }, 12e4);
3428
- await waitUntilAbort(opts.abortSignal, () => {
3429
- clearInterval(pollInterval);
3232
+ }
3430
3233
  });
3234
+ await waitUntilAbort(opts.abortSignal);
3431
3235
  } finally {
3236
+ discoveryScheduler.beginClose();
3432
3237
  api.stopReceiving();
3238
+ await discoveryScheduler.stop();
3433
3239
  await ingress.stop();
3434
3240
  try {
3435
3241
  await api.close();
@@ -3467,17 +3273,13 @@ function hostnameMatchesDomainBoundary(hostname, domain) {
3467
3273
  return hostname === domain || hostname.endsWith(`.${domain}`);
3468
3274
  }
3469
3275
  function isHostedShipUrl(shipUrl) {
3470
- const hostname = extractShipHostname(shipUrl);
3471
- return hostname !== null && isHostedTlonHostname(hostname);
3472
- }
3473
- function extractShipHostname(shipUrl) {
3474
3276
  const trimmed = shipUrl.trim();
3475
- if (!trimmed) return null;
3277
+ if (!trimmed) return false;
3476
3278
  const normalized = /^[a-zA-Z][\w+.-]*:\/\//.test(trimmed) ? trimmed : `https://${trimmed}`;
3477
3279
  try {
3478
- return new URL(normalized).hostname;
3280
+ return isHostedTlonHostname(new URL(normalized).hostname);
3479
3281
  } catch {
3480
- return null;
3282
+ return false;
3481
3283
  }
3482
3284
  }
3483
3285
  function isHostedTlonHostname(hostname) {
@@ -3585,38 +3387,42 @@ async function uploadFile(params, clientConfig) {
3585
3387
  const extension = extensionForMime(contentType) || ".jpg";
3586
3388
  const fileName = sanitizeFileName(params.fileName || `upload${extension}`);
3587
3389
  const fileKey = `${config.shipName}/${Date.now()}-${crypto.randomUUID()}-${fileName}`;
3588
- if (isHostedShipUrl(config.shipUrl) && (storageConfig.service === "presigned-url" || !hasCustomS3Creds(credentials))) {
3589
- const { hostedUrl, uploadUrl } = await getMemexUploadUrl({
3590
- config,
3591
- cookie,
3592
- contentLength: params.blob.size,
3593
- contentType,
3594
- fileName: fileKey
3595
- });
3596
- const trustedUploadUrl = assertTrustedMemexUploadUrl(uploadUrl, "Memex upload URL");
3390
+ const useMemex = isHostedShipUrl(config.shipUrl) && (storageConfig.service === "presigned-url" || !hasCustomS3Creds(credentials));
3391
+ const uploadBlob = async (url, headers) => {
3597
3392
  let guarded;
3598
3393
  try {
3599
3394
  guarded = await fetchWithSsrFGuard({
3600
- url: trustedUploadUrl,
3395
+ url,
3601
3396
  init: {
3602
3397
  method: "PUT",
3603
3398
  body: params.blob,
3604
- headers: {
3605
- "Cache-Control": "public, max-age=3600",
3606
- "Content-Type": contentType
3607
- }
3399
+ headers
3608
3400
  },
3609
- auditContext: "tlon-memex-upload",
3401
+ auditContext: useMemex ? "tlon-memex-upload" : "tlon-custom-s3-upload",
3610
3402
  capture: false,
3611
3403
  maxRedirects: 0,
3404
+ ...useMemex ? {} : { policy: privateNetworkPolicy },
3612
3405
  timeoutMs: TLON_UPLOAD_TIMEOUT_MS,
3613
3406
  beforeRequest: config.assertDirectAdapterHandoff
3614
3407
  });
3615
- assertTrustedMemexUploadUrl(guarded.finalUrl, "Memex final upload URL");
3408
+ if (useMemex) assertTrustedMemexUploadUrl(guarded.finalUrl, "Memex final upload URL");
3616
3409
  if (!guarded.response.ok) throw new Error(`Upload failed: ${guarded.response.status}`);
3617
3410
  } finally {
3618
3411
  await releaseUploadResponse(guarded);
3619
3412
  }
3413
+ };
3414
+ if (useMemex) {
3415
+ const { hostedUrl, uploadUrl } = await getMemexUploadUrl({
3416
+ config,
3417
+ cookie,
3418
+ contentLength: params.blob.size,
3419
+ contentType,
3420
+ fileName: fileKey
3421
+ });
3422
+ await uploadBlob(assertTrustedMemexUploadUrl(uploadUrl, "Memex upload URL"), {
3423
+ "Cache-Control": "public, max-age=3600",
3424
+ "Content-Type": contentType
3425
+ });
3620
3426
  return { url: assertTrustedMemexUploadUrl(hostedUrl, "Memex hosted URL") };
3621
3427
  }
3622
3428
  if (!hasCustomS3Creds(credentials)) throw new Error("No storage credentials configured");
@@ -3642,34 +3448,12 @@ async function uploadFile(params, clientConfig) {
3642
3448
  ACL: "public-read"
3643
3449
  });
3644
3450
  const signedUrl = await getSignedUrl(client, command, { expiresIn: 3600 });
3645
- let guarded;
3646
- try {
3647
- guarded = await fetchWithSsrFGuard({
3648
- url: signedUrl,
3649
- init: {
3650
- method: "PUT",
3651
- body: params.blob,
3652
- headers: signedUrl.includes("digitaloceanspaces.com") ? headers : void 0
3653
- },
3654
- auditContext: "tlon-custom-s3-upload",
3655
- capture: false,
3656
- maxRedirects: 0,
3657
- policy: privateNetworkPolicy,
3658
- timeoutMs: TLON_UPLOAD_TIMEOUT_MS,
3659
- beforeRequest: config.assertDirectAdapterHandoff
3660
- });
3661
- if (!guarded.response.ok) throw new Error(`Upload failed: ${guarded.response.status}`);
3662
- } finally {
3663
- await releaseUploadResponse(guarded);
3664
- }
3451
+ await uploadBlob(signedUrl, signedUrl.includes("digitaloceanspaces.com") ? headers : void 0);
3665
3452
  return { url: assertSafeUploadResultUrl(storageConfig.publicUrlBase ? new URL(fileKey, storageConfig.publicUrlBase).toString() : expectDefined(signedUrl.split("?").at(0), "signed URL base segment"), "Upload result URL") };
3666
3453
  }
3667
3454
  //#endregion
3668
3455
  //#region extensions/tlon/src/urbit/upload.ts
3669
3456
  /**
3670
- * Upload an image from a URL to Tlon storage.
3671
- */
3672
- /**
3673
3457
  * Fetch an image from a URL and upload it to Tlon storage.
3674
3458
  * Falls back to the original URL on error, but only after a bounded download when a cap is set.
3675
3459
  */
@@ -3700,7 +3484,7 @@ async function uploadImageFromUrl(imageUrl, clientConfig, maxBytes) {
3700
3484
  const contentType = fetched.contentType || "image/png";
3701
3485
  return (await uploadFile({
3702
3486
  blob: new Blob([bufferToBlobPart(fetched.buffer)], { type: contentType }),
3703
- fileName: new URL(imageUrl).pathname.split("/").pop() || `upload-${Date.now()}.png`,
3487
+ fileName: url.pathname.split("/").pop() || `upload-${Date.now()}.png`,
3704
3488
  contentType
3705
3489
  }, {
3706
3490
  ...clientConfig,
@@ -3722,7 +3506,7 @@ async function createHttpPokeApi(params) {
3722
3506
  ssrfPolicy,
3723
3507
  beforeRequest: params.assertDirectAdapterHandoff
3724
3508
  });
3725
- const channelPath = `/~/channel/${`${Math.floor(Date.now() / 1e3)}-${crypto.randomUUID()}`}`;
3509
+ const channelId = `${Math.floor(Date.now() / 1e3)}-${crypto.randomUUID()}`;
3726
3510
  const shipName = params.ship.replace(/^~/, "");
3727
3511
  return { poke: async (pokeParams) => {
3728
3512
  const pokeId = Date.now();
@@ -3736,18 +3520,14 @@ async function createHttpPokeApi(params) {
3736
3520
  };
3737
3521
  params.assertDirectAdapterHandoff?.();
3738
3522
  await params.onPlatformSendDispatch?.();
3739
- const { response, release } = await urbitFetch({
3523
+ const { response, release } = await putUrbitChannel({
3740
3524
  baseUrl: params.url,
3741
- path: channelPath,
3742
- init: {
3743
- method: "PUT",
3744
- headers: {
3745
- "Content-Type": "application/json",
3746
- Cookie: expectDefined(cookie.split(";").at(0), "cookie first segment")
3747
- },
3748
- body: JSON.stringify([pokeData])
3749
- },
3750
- ssrfPolicy,
3525
+ channelId,
3526
+ ship: shipName,
3527
+ cookie: normalizeUrbitCookie(cookie),
3528
+ ssrfPolicy
3529
+ }, {
3530
+ body: [pokeData],
3751
3531
  auditContext: "tlon-poke",
3752
3532
  beforeRequest: params.assertDirectAdapterHandoff
3753
3533
  });
@@ -3870,6 +3650,7 @@ async function startTlonGatewayAccount(ctx) {
3870
3650
  });
3871
3651
  ctx.log?.info(`[${account.accountId}] starting Tlon provider for ${account.ship ?? "tlon"}`);
3872
3652
  return monitorTlonProvider({
3653
+ scheduler: ctx.scheduler,
3873
3654
  runtime: ctx.runtime,
3874
3655
  abortSignal: ctx.abortSignal,
3875
3656
  accountId: account.accountId