@openclaw/tlon 2026.9.5 → 2026.9.7

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,16 +1,17 @@
1
- import { n as createDedupeCache, o as createLoggerBackedRuntime } from "./runtime-api-BXVe40nS.mjs";
2
- import { c as normalizeUrbitHostname, d as resolveTlonAccount, f as formatTargetHint, h as parseTlonTarget, l as validateUrbitBaseUrl, m as parseChannelNest, p as normalizeShip } from "./setup-core-Ny4-ZMK0.mjs";
1
+ import { i as __reExport, r as __exportAll } from "./doctor-contract-BiiG6XQ7.mjs";
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
4
  import { t as getTlonRuntime } from "./runtime-Ck3lNvST.mjs";
4
- import { t as tlonSetupWizard } from "./setup-surface-C4uWCLAo.mjs";
5
+ import { t as tlonSetupWizard } from "./setup-surface-BemXwGis.mjs";
5
6
  import { fetchWithSsrFGuard, ssrfPolicyFromDangerouslyAllowPrivateNetwork } from "openclaw/plugin-sdk/ssrf-runtime";
6
7
  import { bindIngressLifecycleToReplyOptions, createChannelIngressError, createChannelIngressMonitor, createMessageReceiptFromOutboundResults, waitUntilAbort } from "openclaw/plugin-sdk/channel-outbound";
7
8
  import { expectDefined } from "openclaw/plugin-sdk/expect-runtime";
8
9
  import { asFiniteNumber, asNullableRecord, filterStringEntries, normalizeLowercaseStringOrEmpty, normalizeNullableString, readStringField, uniqueStrings } from "openclaw/plugin-sdk/string-coerce-runtime";
9
10
  import crypto, { randomBytes, randomUUID } from "node:crypto";
10
11
  import { readProviderJsonResponse, readResponseTextLimited } from "openclaw/plugin-sdk/provider-http";
11
- import { runChannelProbe, sliceUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
12
+ import { escapeRegExp, runChannelProbe, sliceUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
12
13
  import { resolveHumanDelayConfig } from "openclaw/plugin-sdk/agent-runtime";
13
- import { createChannelInboundEnvelopeBuilder, formatAgentEnvelope, formatInboundMediaUnavailableText, implicitMentionKindWhen, resolveEnvelopeFormatOptions, resolveInboundMentionDecision } from "openclaw/plugin-sdk/channel-inbound";
14
+ import { createChannelInboundEnvelopeBuilder, formatAgentEnvelope, formatInboundMediaUnavailableText, resolveEnvelopeFormatOptions } from "openclaw/plugin-sdk/channel-inbound";
14
15
  import { collectErrorGraphCandidates, formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
15
16
  import { retryAsync } from "openclaw/plugin-sdk/retry-runtime";
16
17
  import { sleepWithAbort } from "openclaw/plugin-sdk/runtime-env";
@@ -18,24 +19,14 @@ import { da, scot } from "@urbit/aura";
18
19
  import { Readable } from "node:stream";
19
20
  import { resolveTimerTimeoutMs } from "openclaw/plugin-sdk/number-runtime";
20
21
  import { resolveAllowlistMatchByCandidates } from "openclaw/plugin-sdk/allow-from";
21
- import { resolveChannelImplicitMentions, resolveStableChannelMessageIngress } from "openclaw/plugin-sdk/channel-ingress-runtime";
22
22
  import { isRecord } from "openclaw/plugin-sdk/channel-secret-basic-runtime";
23
23
  import { MAX_IMAGE_BYTES, readRemoteMediaBuffer, saveRemoteMedia } from "openclaw/plugin-sdk/media-runtime";
24
+ import { resolveChannelImplicitMentions } from "openclaw/plugin-sdk/channel-ingress-runtime";
24
25
  import { bufferToBlobPart } from "openclaw/plugin-sdk/blob-runtime";
25
26
  import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
26
27
  import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
27
28
  import { extensionForMime } from "openclaw/plugin-sdk/media-mime";
28
29
  //#region extensions/tlon/src/settings.ts
29
- /**
30
- * Settings Store integration for hot-reloading Tlon plugin config.
31
- *
32
- * Settings are stored in Urbit's %settings agent under:
33
- * desk: "moltbot"
34
- * bucket: "tlon"
35
- *
36
- * This allows config changes via poke from any Landscape client
37
- * without requiring a gateway restart.
38
- */
39
30
  const SETTINGS_DESK = "moltbot";
40
31
  const SETTINGS_BUCKET = "tlon";
41
32
  /**
@@ -99,124 +90,59 @@ function parsePendingApprovals(value) {
99
90
  return typeof obj.id === "string" && (obj.type === "dm" || obj.type === "channel" || obj.type === "group") && typeof obj.requestingShip === "string" && typeof obj.timestamp === "number";
100
91
  });
101
92
  }
102
- /**
103
- * Parse a single settings entry update event.
104
- */
105
93
  function parseSettingsEvent(event) {
106
94
  if (!event || typeof event !== "object") return null;
107
95
  const evt = event;
108
- if (evt["put-entry"]) {
109
- const put = evt["put-entry"];
110
- if (put.desk !== SETTINGS_DESK || put["bucket-key"] !== SETTINGS_BUCKET) return null;
111
- return {
112
- key: typeof put["entry-key"] === "string" ? put["entry-key"] : "",
113
- value: put.value
114
- };
115
- }
116
- if (evt["del-entry"]) {
117
- const del = evt["del-entry"];
118
- if (del.desk !== SETTINGS_DESK || del["bucket-key"] !== SETTINGS_BUCKET) return null;
119
- return {
120
- key: typeof del["entry-key"] === "string" ? del["entry-key"] : "",
121
- value: void 0
122
- };
123
- }
124
- return null;
96
+ const operation = evt["put-entry"] ? "put-entry" : "del-entry";
97
+ const entry = evt[operation];
98
+ if (!entry || entry.desk !== SETTINGS_DESK || entry["bucket-key"] !== SETTINGS_BUCKET) return null;
99
+ return {
100
+ key: typeof entry["entry-key"] === "string" ? entry["entry-key"] : "",
101
+ value: operation === "put-entry" ? entry.value : void 0
102
+ };
125
103
  }
126
- /**
127
- * Apply a single settings update to the current state.
128
- */
129
104
  function applySettingsUpdate(current, key, value) {
130
- const next = { ...current };
131
- switch (key) {
132
- case "groupChannels":
133
- next.groupChannels = Array.isArray(value) ? filterStringEntries(value) : void 0;
134
- break;
135
- case "dmAllowlist":
136
- next.dmAllowlist = Array.isArray(value) ? filterStringEntries(value) : void 0;
137
- break;
138
- case "autoDiscoverChannels":
139
- next.autoDiscoverChannels = typeof value === "boolean" ? value : void 0;
140
- break;
141
- case "showModelSig":
142
- next.showModelSig = typeof value === "boolean" ? value : void 0;
143
- break;
144
- case "autoAcceptDmInvites":
145
- next.autoAcceptDmInvites = typeof value === "boolean" ? value : void 0;
146
- break;
147
- case "autoAcceptGroupInvites":
148
- next.autoAcceptGroupInvites = typeof value === "boolean" ? value : void 0;
149
- break;
150
- case "groupInviteAllowlist":
151
- next.groupInviteAllowlist = Array.isArray(value) ? filterStringEntries(value) : void 0;
152
- break;
153
- case "channelRules":
154
- next.channelRules = parseChannelRules(value);
155
- break;
156
- case "defaultAuthorizedShips":
157
- next.defaultAuthorizedShips = Array.isArray(value) ? filterStringEntries(value) : void 0;
158
- break;
159
- case "ownerShip":
160
- next.ownerShip = typeof value === "string" ? value : void 0;
161
- break;
162
- case "pendingApprovals": next.pendingApprovals = parsePendingApprovals(value);
163
- }
164
- return next;
105
+ const parsed = parseSettingsResponse({ [SETTINGS_BUCKET]: { [key]: value } });
106
+ return Object.hasOwn(parsed, key) ? {
107
+ ...current,
108
+ [key]: parsed[key]
109
+ } : { ...current };
110
+ }
111
+ async function putTlonSetting(api, key, value) {
112
+ await api.poke({
113
+ app: "settings",
114
+ mark: "settings-event",
115
+ json: { "put-entry": {
116
+ desk: SETTINGS_DESK,
117
+ "bucket-key": SETTINGS_BUCKET,
118
+ "entry-key": key,
119
+ value
120
+ } }
121
+ });
165
122
  }
166
- /**
167
- * Create a settings store subscription manager.
168
- *
169
- * Usage:
170
- * const settings = createSettingsManager(api, logger);
171
- * await settings.load();
172
- * settings.subscribe((newSettings) => { ... });
173
- */
174
123
  function createSettingsManager(api, logger) {
175
- const state = {
176
- current: {},
177
- loaded: false
178
- };
124
+ let current = {};
179
125
  const listeners = /* @__PURE__ */ new Set();
180
126
  const notify = () => {
181
127
  for (const listener of listeners) try {
182
- listener(state.current);
128
+ listener(current);
183
129
  } catch (err) {
184
130
  logger?.error?.(`[settings] Listener error: ${String(err)}`);
185
131
  }
186
132
  };
187
133
  return {
188
- /**
189
- * Get current settings (may be empty if not loaded yet).
190
- */
191
- get current() {
192
- return state.current;
193
- },
194
- /**
195
- * Whether initial settings have been loaded.
196
- */
197
- get loaded() {
198
- return state.loaded;
199
- },
200
- /**
201
- * Load initial settings via scry.
202
- */
203
134
  async load() {
204
135
  try {
205
136
  const deskData = (await api.scry("/settings/all.json"))?.all?.[SETTINGS_DESK];
206
- state.current = parseSettingsResponse(deskData ?? {});
207
- state.loaded = true;
208
- logger?.log?.(`[settings] Loaded: ${JSON.stringify(state.current)}`);
209
- return state.current;
137
+ current = parseSettingsResponse(deskData ?? {});
138
+ logger?.log?.(`[settings] Loaded: ${JSON.stringify(current)}`);
139
+ return current;
210
140
  } catch (err) {
211
141
  logger?.log?.(`[settings] No settings found (using defaults): ${String(err)}`);
212
- state.current = {};
213
- state.loaded = true;
214
- return state.current;
142
+ current = {};
143
+ return current;
215
144
  }
216
145
  },
217
- /**
218
- * Subscribe to settings changes.
219
- */
220
146
  async startSubscription() {
221
147
  await api.subscribe({
222
148
  app: "settings",
@@ -225,7 +151,7 @@ function createSettingsManager(api, logger) {
225
151
  const update = parseSettingsEvent(event);
226
152
  if (!update) return;
227
153
  logger?.log?.(`[settings] Update: ${update.key} = ${JSON.stringify(update.value)}`);
228
- state.current = applySettingsUpdate(state.current, update.key, update.value);
154
+ current = applySettingsUpdate(current, update.key, update.value);
229
155
  notify();
230
156
  },
231
157
  err: (error) => {
@@ -237,9 +163,6 @@ function createSettingsManager(api, logger) {
237
163
  });
238
164
  logger?.log?.("[settings] Subscribed to settings updates");
239
165
  },
240
- /**
241
- * Register a listener for settings changes.
242
- */
243
166
  onChange(listener) {
244
167
  listeners.add(listener);
245
168
  return () => listeners.delete(listener);
@@ -364,97 +287,83 @@ function getUrbitContext(url, ship) {
364
287
  *
365
288
  * Converts markdown-like text to Tlon's story format.
366
289
  */
367
- /**
368
- * Parse inline markdown formatting (bold, italic, code, links, mentions)
369
- */
290
+ const INLINE_MARKDOWN_RULES = [
291
+ {
292
+ pattern: /^(~[a-z][-a-z0-9]*)/,
293
+ render: (match) => ({ ship: expectDefined(match[1], "ship mention capture") })
294
+ },
295
+ {
296
+ pattern: /^\*\*(.+?)\*\*|^__(.+?)__/,
297
+ render: (match) => ({ bold: parseInlineMarkdown(expectDefined(match[1] ?? match[2], "bold body capture")) })
298
+ },
299
+ {
300
+ pattern: /^\*([^*]+?)\*|^_([^_]+?)_(?![a-zA-Z0-9])/,
301
+ render: (match) => ({ italics: parseInlineMarkdown(expectDefined(match[1] ?? match[2], "italic body capture")) })
302
+ },
303
+ {
304
+ pattern: /^~~(.+?)~~/,
305
+ render: (match) => ({ strike: parseInlineMarkdown(expectDefined(match[1], "strikethrough body capture")) })
306
+ },
307
+ {
308
+ pattern: /^`([^`]+)`/,
309
+ render: (match) => ({ "inline-code": expectDefined(match[1], "inline code capture") })
310
+ },
311
+ {
312
+ pattern: /^\[([^\]]+)\]\(([^)]+)\)/,
313
+ render: (match) => ({ link: {
314
+ href: expectDefined(match[2], "link URL capture"),
315
+ content: expectDefined(match[1], "link text capture")
316
+ } })
317
+ },
318
+ {
319
+ pattern: /^!\[([^\]]*)\]\(([^)]+)\)/,
320
+ render: (match) => ({ imageBlock: {
321
+ src: expectDefined(match[2], "image URL capture"),
322
+ alt: expectDefined(match[1], "image alt capture")
323
+ } })
324
+ },
325
+ {
326
+ pattern: /^(https?:\/\/[^\s<>"\]]+)/,
327
+ render: (match) => {
328
+ const url = expectDefined(match[1], "plain URL capture");
329
+ return { link: {
330
+ href: url,
331
+ content: url
332
+ } };
333
+ }
334
+ },
335
+ {
336
+ pattern: /^[^*_`~[#\n:/]+/,
337
+ render: (match) => expectDefined(match[0], "plain text match")
338
+ }
339
+ ];
370
340
  function parseInlineMarkdown(text) {
371
341
  const result = [];
372
342
  let remaining = text;
373
343
  while (remaining.length > 0) {
374
- const shipMatch = remaining.match(/^(~[a-z][-a-z0-9]*)/);
375
- if (shipMatch) {
376
- result.push({ ship: expectDefined(shipMatch[1], "ship mention capture") });
377
- remaining = remaining.slice(shipMatch[0].length);
378
- continue;
379
- }
380
- const boldMatch = remaining.match(/^\*\*(.+?)\*\*|^__(.+?)__/);
381
- if (boldMatch) {
382
- const content = expectDefined(boldMatch[1] ?? boldMatch[2], "bold body capture");
383
- result.push({ bold: parseInlineMarkdown(content) });
384
- remaining = remaining.slice(boldMatch[0].length);
385
- continue;
386
- }
387
- const italicsMatch = remaining.match(/^\*([^*]+?)\*|^_([^_]+?)_(?![a-zA-Z0-9])/);
388
- if (italicsMatch) {
389
- const content = expectDefined(italicsMatch[1] ?? italicsMatch[2], "italic body capture");
390
- result.push({ italics: parseInlineMarkdown(content) });
391
- remaining = remaining.slice(italicsMatch[0].length);
392
- continue;
393
- }
394
- const strikeMatch = remaining.match(/^~~(.+?)~~/);
395
- if (strikeMatch) {
396
- result.push({ strike: parseInlineMarkdown(expectDefined(strikeMatch[1], "strikethrough body capture")) });
397
- remaining = remaining.slice(strikeMatch[0].length);
398
- continue;
399
- }
400
- const codeMatch = remaining.match(/^`([^`]+)`/);
401
- if (codeMatch) {
402
- result.push({ "inline-code": expectDefined(codeMatch[1], "inline code capture") });
403
- remaining = remaining.slice(codeMatch[0].length);
404
- continue;
405
- }
406
- const linkMatch = remaining.match(/^\[([^\]]+)\]\(([^)]+)\)/);
407
- if (linkMatch) {
408
- result.push({ link: {
409
- href: expectDefined(linkMatch[2], "link URL capture"),
410
- content: expectDefined(linkMatch[1], "link text capture")
411
- } });
412
- remaining = remaining.slice(linkMatch[0].length);
413
- continue;
414
- }
415
- const imageMatch = remaining.match(/^!\[([^\]]*)\]\(([^)]+)\)/);
416
- if (imageMatch) {
417
- result.push({ imageBlock: {
418
- src: expectDefined(imageMatch[2], "image URL capture"),
419
- alt: expectDefined(imageMatch[1], "image alt capture")
420
- } });
421
- remaining = remaining.slice(imageMatch[0].length);
422
- continue;
423
- }
424
- const urlMatch = remaining.match(/^(https?:\/\/[^\s<>"\]]+)/);
425
- if (urlMatch) {
426
- const url = expectDefined(urlMatch[1], "plain URL capture");
427
- result.push({ link: {
428
- href: url,
429
- content: url
430
- } });
431
- remaining = remaining.slice(urlMatch[0].length);
432
- continue;
433
- }
434
- const plainMatch = remaining.match(/^[^*_`~[#\n:/]+/);
435
- if (plainMatch) {
436
- result.push(expectDefined(plainMatch[0], "plain text match"));
437
- remaining = remaining.slice(plainMatch[0].length);
438
- continue;
344
+ let consumed = 1;
345
+ let inline = remaining.charAt(0);
346
+ for (const rule of INLINE_MARKDOWN_RULES) {
347
+ const match = remaining.match(rule.pattern);
348
+ if (match) {
349
+ inline = rule.render(match);
350
+ consumed = match[0].length;
351
+ break;
352
+ }
439
353
  }
440
- result.push(remaining.charAt(0));
441
- remaining = remaining.slice(1);
354
+ result.push(inline);
355
+ remaining = remaining.slice(consumed);
442
356
  }
443
357
  return mergeAdjacentStrings(result);
444
358
  }
445
- function headingTag(marker) {
446
- switch (marker.length) {
447
- case 1: return "h1";
448
- case 2: return "h2";
449
- case 3: return "h3";
450
- case 4: return "h4";
451
- case 5: return "h5";
452
- default: return "h6";
453
- }
454
- }
455
- /**
456
- * Merge adjacent string elements in an inline array
457
- */
359
+ const HEADING_TAGS = [
360
+ "h1",
361
+ "h2",
362
+ "h3",
363
+ "h4",
364
+ "h5",
365
+ "h6"
366
+ ];
458
367
  function mergeAdjacentStrings(inlines) {
459
368
  const result = [];
460
369
  for (const item of inlines) {
@@ -464,9 +373,6 @@ function mergeAdjacentStrings(inlines) {
464
373
  }
465
374
  return result;
466
375
  }
467
- /**
468
- * Create an image block
469
- */
470
376
  function createImageBlock(src, alt = "", height = 0, width = 0) {
471
377
  return { block: { image: {
472
378
  src,
@@ -475,9 +381,6 @@ function createImageBlock(src, alt = "", height = 0, width = 0) {
475
381
  alt
476
382
  } } };
477
383
  }
478
- /**
479
- * Check if URL looks like an image
480
- */
481
384
  function isImageUrl(url) {
482
385
  const imageExtensions = /\.(jpg|jpeg|png|gif|webp|svg|bmp|ico)$/i;
483
386
  let path = url.split(/[?#]/, 1)[0] ?? url;
@@ -653,9 +556,6 @@ function parseListingBlock(lines, startIndex) {
653
556
  nextIndex: parsed.nextIndex
654
557
  };
655
558
  }
656
- /**
657
- * Convert markdown text to Tlon story format
658
- */
659
559
  function markdownToStory(markdown) {
660
560
  const story = [];
661
561
  const lines = markdown.split("\n");
@@ -684,7 +584,7 @@ function markdownToStory(markdown) {
684
584
  }
685
585
  const headerMatch = line.match(/^(#{1,6})\s+(.+)$/);
686
586
  if (headerMatch) {
687
- const tag = headingTag(expectDefined(headerMatch[1], "header marker capture"));
587
+ const tag = HEADING_TAGS[expectDefined(headerMatch[1], "header marker capture").length - 1] ?? "h6";
688
588
  story.push({ block: { header: {
689
589
  tag,
690
590
  content: parseInlineMarkdown(expectDefined(headerMatch[2], "header body capture"))
@@ -758,11 +658,9 @@ function createTlonSendReceipt(params) {
758
658
  kind: params.kind
759
659
  });
760
660
  }
761
- async function sendDm({ api, fromShip, toShip, text }) {
661
+ async function sendDm({ text, ...params }) {
762
662
  return sendDmWithStory({
763
- api,
764
- fromShip,
765
- toShip,
663
+ ...params,
766
664
  story: markdownToStory(text),
767
665
  kind: "text"
768
666
  });
@@ -800,14 +698,10 @@ async function sendDmWithStory({ api, fromShip, toShip, story, kind = "unknown"
800
698
  })
801
699
  };
802
700
  }
803
- async function sendGroupMessage({ api, fromShip, hostShip, channelName, text, replyToId }) {
701
+ async function sendGroupMessage({ text, ...params }) {
804
702
  return sendGroupMessageWithStory({
805
- api,
806
- fromShip,
807
- hostShip,
808
- channelName,
703
+ ...params,
809
704
  story: markdownToStory(text),
810
- replyToId,
811
705
  kind: "text"
812
706
  });
813
707
  }
@@ -851,9 +745,6 @@ async function sendGroupMessageWithStory({ api, fromShip, hostShip, channelName,
851
745
  })
852
746
  };
853
747
  }
854
- /**
855
- * Build a story with text and optional media (image)
856
- */
857
748
  function buildMediaStory(text, mediaUrl) {
858
749
  const story = [];
859
750
  const cleanText = text?.trim() ?? "";
@@ -1389,21 +1280,9 @@ var UrbitSSEClient = class {
1389
1280
  };
1390
1281
  //#endregion
1391
1282
  //#region extensions/tlon/src/monitor/approval.ts
1392
- /**
1393
- * Approval system for managing DM, channel mention, and group invite approvals.
1394
- *
1395
- * When an unknown ship tries to interact with the bot, the owner receives
1396
- * a notification and can approve or deny the request.
1397
- */
1398
- /**
1399
- * Generate a unique approval ID in the format: {type}-{timestamp}-{shortHash}
1400
- */
1401
1283
  function generateApprovalId(type) {
1402
1284
  return `${type}-${Date.now()}-${randomBytes(3).toString("hex")}`;
1403
1285
  }
1404
- /**
1405
- * Create a pending approval object.
1406
- */
1407
1286
  function createPendingApproval(params) {
1408
1287
  return {
1409
1288
  id: generateApprovalId(params.type),
@@ -1416,16 +1295,10 @@ function createPendingApproval(params) {
1416
1295
  timestamp: Date.now()
1417
1296
  };
1418
1297
  }
1419
- /**
1420
- * Truncate text to a maximum length with ellipsis.
1421
- */
1422
1298
  function truncate(text, maxLength) {
1423
1299
  if (text.length <= maxLength) return text;
1424
1300
  return sliceUtf16Safe(text, 0, maxLength - 3) + "...";
1425
1301
  }
1426
- /**
1427
- * Format a notification message for the owner about a pending approval.
1428
- */
1429
1302
  function formatApprovalRequest(approval) {
1430
1303
  const preview = approval.messagePreview ? `\n"${truncate(approval.messagePreview, 100)}"` : "";
1431
1304
  switch (approval.type) {
@@ -1450,30 +1323,13 @@ function parseApprovalResponse(text) {
1450
1323
  id: match[2]?.trim()
1451
1324
  };
1452
1325
  }
1453
- /**
1454
- * Check if a message text looks like an approval response.
1455
- * Used to determine if we should intercept the message before normal processing.
1456
- */
1457
- function isApprovalResponse(text) {
1458
- const trimmed = normalizeLowercaseStringOrEmpty(text);
1459
- return trimmed.startsWith("approve") || trimmed.startsWith("deny") || trimmed.startsWith("block");
1460
- }
1461
- /**
1462
- * Find a pending approval by ID, or return the most recent if no ID specified.
1463
- */
1464
1326
  function findPendingApproval(pendingApprovals, id) {
1465
1327
  if (id) return pendingApprovals.find((a) => a.id === id);
1466
1328
  return pendingApprovals[pendingApprovals.length - 1];
1467
1329
  }
1468
- /**
1469
- * Remove a pending approval from the list by ID.
1470
- */
1471
1330
  function removePendingApproval(pendingApprovals, id) {
1472
1331
  return pendingApprovals.filter((a) => a.id !== id);
1473
1332
  }
1474
- /**
1475
- * Format a confirmation message after an approval action.
1476
- */
1477
1333
  function formatApprovalConfirmation(approval, action) {
1478
1334
  if (action === "block") return `Blocked ${approval.requestingShip}. They will no longer be able to contact the bot.`;
1479
1335
  const actionText = action === "approve" ? "Approved" : "Denied";
@@ -1508,22 +1364,10 @@ function parseAdminCommand(text) {
1508
1364
  };
1509
1365
  return null;
1510
1366
  }
1511
- /**
1512
- * Check if a message text looks like an admin command.
1513
- */
1514
- function isAdminCommand(text) {
1515
- return parseAdminCommand(text) !== null;
1516
- }
1517
- /**
1518
- * Format the list of blocked ships for display to owner.
1519
- */
1520
1367
  function formatBlockedList(ships) {
1521
1368
  if (ships.length === 0) return "No ships are currently blocked.";
1522
1369
  return `Blocked ships (${ships.length}):\n${ships.map((s) => `• ${s}`).join("\n")}`;
1523
1370
  }
1524
- /**
1525
- * Format the list of pending approvals for display to owner.
1526
- */
1527
1371
  function formatPendingList(approvals) {
1528
1372
  if (approvals.length === 0) return "No pending approval requests.";
1529
1373
  return `Pending approvals (${approvals.length}):\n${approvals.map((a) => `• ${a.id}: ${a.type} from ${a.requestingShip}`).join("\n")}`;
@@ -1532,18 +1376,11 @@ function formatPendingList(approvals) {
1532
1376
  //#region extensions/tlon/src/monitor/approval-runtime.ts
1533
1377
  function createTlonApprovalRuntime(params) {
1534
1378
  const { api, runtime, botShipName, getPendingApprovals, setPendingApprovals, getCurrentSettings, setCurrentSettings, getEffectiveDmAllowlist, setEffectiveDmAllowlist, getEffectiveOwnerShip, processApprovedMessage, refreshWatchedChannels } = params;
1379
+ let approvalOverflowNoticeSent = false;
1380
+ let approvalOverflowNoticeAttempts = 0;
1535
1381
  const savePendingApprovals = async (required = false) => {
1536
1382
  try {
1537
- await api.poke({
1538
- app: "settings",
1539
- mark: "settings-event",
1540
- json: { "put-entry": {
1541
- desk: "moltbot",
1542
- "bucket-key": "tlon",
1543
- "entry-key": "pendingApprovals",
1544
- value: JSON.stringify(getPendingApprovals())
1545
- } }
1546
- });
1383
+ await putTlonSetting(api, "pendingApprovals", JSON.stringify(getPendingApprovals()));
1547
1384
  } catch (err) {
1548
1385
  runtime.error?.(`[tlon] Failed to save pending approvals: ${String(err)}`);
1549
1386
  if (required) throw err;
@@ -1554,16 +1391,7 @@ function createTlonApprovalRuntime(params) {
1554
1391
  const nextAllowlist = getEffectiveDmAllowlist().includes(normalizedShip) ? getEffectiveDmAllowlist() : [...getEffectiveDmAllowlist(), normalizedShip];
1555
1392
  setEffectiveDmAllowlist(nextAllowlist);
1556
1393
  try {
1557
- await api.poke({
1558
- app: "settings",
1559
- mark: "settings-event",
1560
- json: { "put-entry": {
1561
- desk: "moltbot",
1562
- "bucket-key": "tlon",
1563
- "entry-key": "dmAllowlist",
1564
- value: nextAllowlist
1565
- } }
1566
- });
1394
+ await putTlonSetting(api, "dmAllowlist", nextAllowlist);
1567
1395
  runtime.log?.(`[tlon] Added ${normalizedShip} to dmAllowlist`);
1568
1396
  } catch (err) {
1569
1397
  runtime.error?.(`[tlon] Failed to update dmAllowlist: ${String(err)}`);
@@ -1591,16 +1419,7 @@ function createTlonApprovalRuntime(params) {
1591
1419
  channelRules: updatedRules
1592
1420
  });
1593
1421
  try {
1594
- await api.poke({
1595
- app: "settings",
1596
- mark: "settings-event",
1597
- json: { "put-entry": {
1598
- desk: "moltbot",
1599
- "bucket-key": "tlon",
1600
- "entry-key": "channelRules",
1601
- value: JSON.stringify(updatedRules)
1602
- } }
1603
- });
1422
+ await putTlonSetting(api, "channelRules", JSON.stringify(updatedRules));
1604
1423
  runtime.log?.(`[tlon] Added ${normalizedShip} to ${channelNest} allowlist`);
1605
1424
  } catch (err) {
1606
1425
  runtime.error?.(`[tlon] Failed to update channelRules: ${String(err)}`);
@@ -1657,7 +1476,7 @@ function createTlonApprovalRuntime(params) {
1657
1476
  const ownerShip = getEffectiveOwnerShip();
1658
1477
  if (!ownerShip) {
1659
1478
  runtime.log?.("[tlon] No ownerShip configured, cannot send notification");
1660
- return;
1479
+ return false;
1661
1480
  }
1662
1481
  try {
1663
1482
  await sendDm({
@@ -1667,19 +1486,20 @@ function createTlonApprovalRuntime(params) {
1667
1486
  text: message
1668
1487
  });
1669
1488
  runtime.log?.(`[tlon] Sent notification to owner ${ownerShip}`);
1489
+ return true;
1670
1490
  } catch (err) {
1671
1491
  runtime.error?.(`[tlon] Failed to send notification to owner: ${String(err)}`);
1492
+ return false;
1672
1493
  }
1673
1494
  };
1674
1495
  const queueApprovalRequest = async (approval) => {
1675
1496
  if (await isShipBlocked(approval.requestingShip)) {
1676
1497
  runtime.log?.(`[tlon] Ignoring request from blocked ship ${approval.requestingShip}`);
1677
- return;
1498
+ return false;
1678
1499
  }
1679
1500
  const approvals = getPendingApprovals();
1680
- const existingIndex = approvals.findIndex((item) => item.type === approval.type && item.requestingShip === approval.requestingShip && (approval.type !== "channel" || item.channelNest === approval.channelNest) && (approval.type !== "group" || item.groupFlag === approval.groupFlag));
1681
- if (existingIndex !== -1) {
1682
- const existing = expectDefined(approvals[existingIndex], "located pending approval index");
1501
+ const existing = approvals.find((item) => item.type === approval.type && item.requestingShip === approval.requestingShip && (approval.type !== "channel" || item.channelNest === approval.channelNest) && (approval.type !== "group" || item.groupFlag === approval.groupFlag));
1502
+ if (existing) {
1683
1503
  if (approval.originalMessage) {
1684
1504
  existing.originalMessage = approval.originalMessage;
1685
1505
  existing.messagePreview = approval.messagePreview;
@@ -1687,12 +1507,23 @@ function createTlonApprovalRuntime(params) {
1687
1507
  runtime.log?.(`[tlon] Updated existing approval for ${approval.requestingShip} (${approval.type}) - re-sending notification`);
1688
1508
  await savePendingApprovals(true);
1689
1509
  await sendOwnerNotification(formatApprovalRequest(existing));
1690
- return;
1510
+ return true;
1691
1511
  }
1512
+ if (approvals.length >= 100) {
1513
+ runtime.log?.(`[tlon] Pending approval limit reached; ignoring ${approval.type} request from ${approval.requestingShip}`);
1514
+ if (!approvalOverflowNoticeSent && approvalOverflowNoticeAttempts < 3) {
1515
+ approvalOverflowNoticeAttempts += 1;
1516
+ approvalOverflowNoticeSent = await sendOwnerNotification(`Pending approval queue is full (${approvals.length}). Resolve existing requests with approve, deny, or block before asking rejected requesters to retry.`);
1517
+ }
1518
+ return false;
1519
+ }
1520
+ approvalOverflowNoticeSent = false;
1521
+ approvalOverflowNoticeAttempts = 0;
1692
1522
  setPendingApprovals([...approvals, approval]);
1693
1523
  await savePendingApprovals(true);
1694
1524
  await sendOwnerNotification(formatApprovalRequest(approval));
1695
1525
  runtime.log?.(`[tlon] Queued approval request: ${approval.id} (${approval.type} from ${approval.requestingShip})`);
1526
+ return true;
1696
1527
  };
1697
1528
  const handleApprovalResponse = async (text) => {
1698
1529
  const parsed = parseApprovalResponse(text);
@@ -1791,11 +1622,16 @@ function createTlonApprovalRuntime(params) {
1791
1622
  function resolveChannelAuthorization(cfg, channelNest, settings) {
1792
1623
  const tlonConfig = cfg.channels?.tlon;
1793
1624
  const fileRules = tlonConfig?.authorization?.channelRules ?? {};
1794
- const rule = (settings?.channelRules ?? {})[channelNest] ?? fileRules[channelNest];
1625
+ const settingsRules = settings?.channelRules ?? {};
1626
+ const fileRule = fileRules[channelNest];
1627
+ const settingsRule = settingsRules[channelNest];
1628
+ const rule = settingsRule ?? fileRule;
1795
1629
  const defaultShips = settings?.defaultAuthorizedShips ?? tlonConfig?.defaultAuthorizedShips ?? [];
1630
+ const requireMentionInBotThreads = typeof settingsRule?.requireMentionInBotThreads === "boolean" ? settingsRule.requireMentionInBotThreads : fileRule?.requireMentionInBotThreads;
1796
1631
  return {
1797
1632
  mode: rule?.mode ?? "restricted",
1798
- allowedShips: rule?.allowedShips ?? defaultShips
1633
+ allowedShips: rule?.allowedShips ?? defaultShips,
1634
+ requireMentionInBotThreads: typeof requireMentionInBotThreads === "boolean" ? requireMentionInBotThreads : void 0
1799
1635
  };
1800
1636
  }
1801
1637
  //#endregion
@@ -1861,10 +1697,11 @@ function formatModelName(modelString) {
1861
1697
  function isBotMentioned(messageText, botShipName, nickname) {
1862
1698
  if (!messageText || !botShipName) return false;
1863
1699
  if (/@all\b/i.test(messageText)) return true;
1864
- const escapedShip = normalizeShip(botShipName).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1700
+ const normalizedBotShip = normalizeShip(botShipName);
1701
+ const escapedShip = escapeRegExp(normalizedBotShip);
1865
1702
  if (new RegExp(`(^|\\s)${escapedShip}(?=\\s|$)`, "i").test(messageText)) return true;
1866
1703
  if (nickname) {
1867
- const escapedNickname = nickname.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1704
+ const escapedNickname = escapeRegExp(nickname);
1868
1705
  if (new RegExp(`(^|\\s)${escapedNickname}(?=\\s|$|[,!?.])`, "i").test(messageText)) return true;
1869
1706
  }
1870
1707
  return false;
@@ -1873,6 +1710,11 @@ function stripBotMention(messageText, botShipName) {
1873
1710
  if (!messageText || !botShipName) return messageText;
1874
1711
  return messageText.replace(normalizeShip(botShipName), "").trim();
1875
1712
  }
1713
+ function extractDmPartnerShip(whom) {
1714
+ const raw = typeof whom === "string" ? whom : whom && typeof whom === "object" && "ship" in whom && typeof whom.ship === "string" ? whom.ship : "";
1715
+ const normalized = normalizeShip(raw);
1716
+ return /^~?[a-z-]+$/i.test(normalized) ? normalized : "";
1717
+ }
1876
1718
  const tlonIngressIdentity = {
1877
1719
  key: "sender-ship",
1878
1720
  normalize: normalizeShip,
@@ -1892,7 +1734,7 @@ async function isDmAllowedWithIngress(senderShip, allowlist) {
1892
1734
  })).senderAccess.allowed;
1893
1735
  }
1894
1736
  async function resolveTlonMessageIngress(params) {
1895
- return await resolveStableChannelMessageIngress({
1737
+ return await getTlonRuntime().channel.inbound.ingress.resolveStable({
1896
1738
  channelId: "tlon",
1897
1739
  accountId: params.accountId ?? "default",
1898
1740
  identity: tlonIngressIdentity,
@@ -1907,7 +1749,7 @@ async function resolveTlonMessageIngress(params) {
1907
1749
  }
1908
1750
  async function resolveTlonCommandAuthorizationWithIngress(params) {
1909
1751
  const normalizedOwner = params.ownerShip ? normalizeShip(params.ownerShip) : null;
1910
- return await resolveStableChannelMessageIngress({
1752
+ return await getTlonRuntime().channel.inbound.ingress.resolveStable({
1911
1753
  channelId: "tlon",
1912
1754
  accountId: "default",
1913
1755
  identity: tlonIngressIdentity,
@@ -1927,28 +1769,6 @@ async function resolveTlonCommandAuthorizationWithIngress(params) {
1927
1769
  command: {}
1928
1770
  });
1929
1771
  }
1930
- function resolveTlonGroupMentionDecision(params) {
1931
- const implicitMentions = resolveChannelImplicitMentions({
1932
- cfg: params.cfg,
1933
- channel: "tlon",
1934
- accountId: params.accountId
1935
- });
1936
- return resolveInboundMentionDecision({
1937
- facts: {
1938
- canDetectMention: true,
1939
- wasMentioned: params.wasMentioned,
1940
- implicitMentionKinds: implicitMentionKindWhen("bot_thread_participant", params.botParticipatedInThread)
1941
- },
1942
- policy: {
1943
- isGroup: true,
1944
- requireMention: true,
1945
- implicitMentions,
1946
- allowTextCommands: false,
1947
- hasControlCommand: false,
1948
- commandAuthorized: false
1949
- }
1950
- });
1951
- }
1952
1772
  function isGroupInviteAllowed(inviterShip, allowlist) {
1953
1773
  const normalizedInviter = normalizeShip(inviterShip);
1954
1774
  return resolveAllowlistMatchByCandidates({
@@ -2215,14 +2035,10 @@ async function fetchChannelHistory(api, channelNest, count = 50, runtime) {
2215
2035
  const itemRecord = asNullableRecord(item);
2216
2036
  const replyPost = asNullableRecord(itemRecord?.["r-post"]);
2217
2037
  const replyPostSet = asNullableRecord(replyPost?.set);
2218
- const essay = asNullableRecord(itemRecord?.essay) ?? asNullableRecord(replyPostSet?.essay);
2219
- const seal = asNullableRecord(itemRecord?.seal) ?? asNullableRecord(replyPostSet?.seal);
2220
- return {
2221
- author: typeof essay?.author === "string" ? essay.author : "unknown",
2222
- content: extractMessageText(essay?.content || []),
2223
- timestamp: typeof essay?.sent === "number" ? essay.sent : Date.now(),
2224
- id: typeof seal?.id === "string" ? seal.id : void 0
2225
- };
2038
+ return createHistoryEntryFromMemo({
2039
+ memo: asNullableRecord(itemRecord?.essay) ?? asNullableRecord(replyPostSet?.essay),
2040
+ seal: asNullableRecord(itemRecord?.seal) ?? asNullableRecord(replyPostSet?.seal)
2041
+ });
2226
2042
  }).filter((msg) => msg.content);
2227
2043
  runtime?.log?.(`[tlon] Extracted ${messages.length} messages from history`);
2228
2044
  return messages;
@@ -2251,6 +2067,17 @@ function createChannelHistoryCache() {
2251
2067
  }
2252
2068
  };
2253
2069
  }
2070
+ async function fetchThreadRootAuthor(api, channelNest, parentId, runtime) {
2071
+ if (!/^chat\/~?[a-z-]+\/[a-z0-9-]+$/i.test(channelNest) || !/^\d+(?:\.\d{3})*$/.test(parentId)) return null;
2072
+ try {
2073
+ const data = asNullableRecord(await api.scry(`/channels/v4/${channelNest}/posts/post/id/${formatUd(parentId)}.json`));
2074
+ const essay = asNullableRecord(data?.essay);
2075
+ return typeof essay?.author === "string" ? essay.author : null;
2076
+ } catch (error) {
2077
+ runtime?.log?.(`[tlon] Could not identify thread root author: ${formatErrorMessage(error)}`);
2078
+ return null;
2079
+ }
2080
+ }
2254
2081
  /**
2255
2082
  * Fetch thread/reply history for a specific parent post.
2256
2083
  * Used to get context when entering a thread conversation.
@@ -2478,10 +2305,6 @@ function extractImageBlocks(content) {
2478
2305
  unavailableCount
2479
2306
  };
2480
2307
  }
2481
- /**
2482
- * Download a media file from URL to local storage.
2483
- * Returns the local path where the file was saved.
2484
- */
2485
2308
  async function downloadMedia(url, maxBytes) {
2486
2309
  try {
2487
2310
  const parsedUrl = new URL(url);
@@ -2497,7 +2320,7 @@ async function downloadMedia(url, maxBytes) {
2497
2320
  requestInit: { method: "GET" }
2498
2321
  });
2499
2322
  return {
2500
- localPath: saved.path,
2323
+ path: saved.path,
2501
2324
  contentType: saved.contentType ?? "application/octet-stream"
2502
2325
  };
2503
2326
  } catch (error) {
@@ -2515,10 +2338,7 @@ async function downloadMessageImages(content, maxBytes) {
2515
2338
  let unavailableCount = overCapCount;
2516
2339
  for (const image of images) {
2517
2340
  const downloaded = await downloadMedia(image.url, maxBytes);
2518
- if (downloaded) attachments.push({
2519
- path: downloaded.localPath,
2520
- contentType: downloaded.contentType
2521
- });
2341
+ if (downloaded) attachments.push(downloaded);
2522
2342
  else unavailableCount++;
2523
2343
  }
2524
2344
  return {
@@ -2527,50 +2347,107 @@ async function downloadMessageImages(content, maxBytes) {
2527
2347
  };
2528
2348
  }
2529
2349
  //#endregion
2530
- //#region extensions/tlon/src/monitor/settings-helpers.ts
2531
- function buildTlonSettingsMigrations(account, currentSettings) {
2532
- return [
2533
- {
2534
- key: "dmAllowlist",
2535
- fileValue: account.dmAllowlist,
2536
- settingsValue: currentSettings.dmAllowlist
2537
- },
2538
- {
2539
- key: "groupInviteAllowlist",
2540
- fileValue: account.groupInviteAllowlist,
2541
- settingsValue: currentSettings.groupInviteAllowlist
2542
- },
2543
- {
2544
- key: "groupChannels",
2545
- fileValue: account.groupChannels,
2546
- settingsValue: currentSettings.groupChannels
2547
- },
2548
- {
2549
- key: "defaultAuthorizedShips",
2550
- fileValue: account.defaultAuthorizedShips,
2551
- settingsValue: currentSettings.defaultAuthorizedShips
2552
- },
2553
- {
2554
- key: "autoDiscoverChannels",
2555
- fileValue: account.autoDiscoverChannels,
2556
- settingsValue: currentSettings.autoDiscoverChannels
2557
- },
2558
- {
2559
- key: "autoAcceptDmInvites",
2560
- fileValue: account.autoAcceptDmInvites,
2561
- settingsValue: currentSettings.autoAcceptDmInvites
2562
- },
2563
- {
2564
- key: "autoAcceptGroupInvites",
2565
- fileValue: account.autoAcceptGroupInvites,
2566
- settingsValue: currentSettings.autoAcceptGroupInvites
2350
+ //#region src/channels/mention-gating.ts
2351
+ function resolveBotThreadMentionPolicy(params) {
2352
+ if (!params.isBotOwnedThread || params.requireMentionInBotThreads === void 0) return {
2353
+ requireMention: params.requireMention,
2354
+ implicitMentionKinds: params.implicitMentionKinds
2355
+ };
2356
+ return {
2357
+ requireMention: params.requireMentionInBotThreads,
2358
+ implicitMentionKinds: params.requireMentionInBotThreads ? params.implicitMentionKinds?.filter((kind) => kind === "native") : params.implicitMentionKinds
2359
+ };
2360
+ }
2361
+ //#endregion
2362
+ //#region \0openclaw:bundled-sdk:openclaw/plugin-sdk/channel-mention-gating
2363
+ var channel_mention_gating_exports = /* @__PURE__ */ __exportAll({ resolveBotThreadMentionPolicy: () => resolveBotThreadMentionPolicy });
2364
+ import * as import_openclaw_plugin_sdk_channel_mention_gating from "openclaw/plugin-sdk/channel-mention-gating";
2365
+ __reExport(channel_mention_gating_exports, import_openclaw_plugin_sdk_channel_mention_gating);
2366
+ //#endregion
2367
+ //#region extensions/tlon/src/monitor/mentions.ts
2368
+ function resolveTlonGroupMentionDecision(params) {
2369
+ const implicitMentions = resolveChannelImplicitMentions({
2370
+ cfg: params.cfg,
2371
+ channel: "tlon",
2372
+ accountId: params.accountId
2373
+ });
2374
+ const threadPolicy = resolveBotThreadMentionPolicy({
2375
+ isBotOwnedThread: params.isBotOwnedThread === true,
2376
+ requireMentionInBotThreads: params.requireMentionInBotThreads,
2377
+ requireMention: true,
2378
+ implicitMentionKinds: (0, channel_mention_gating_exports.implicitMentionKindWhen)("bot_thread_participant", params.botParticipatedInThread)
2379
+ });
2380
+ return (0, channel_mention_gating_exports.resolveInboundMentionDecision)({
2381
+ facts: {
2382
+ canDetectMention: true,
2383
+ wasMentioned: params.wasMentioned,
2384
+ implicitMentionKinds: threadPolicy.implicitMentionKinds
2567
2385
  },
2568
- {
2569
- key: "showModelSig",
2570
- fileValue: account.showModelSignature,
2571
- settingsValue: currentSettings.showModelSig
2386
+ policy: {
2387
+ isGroup: true,
2388
+ requireMention: threadPolicy.requireMention,
2389
+ implicitMentions,
2390
+ allowTextCommands: false,
2391
+ hasControlCommand: false,
2392
+ commandAuthorized: false
2572
2393
  }
2573
- ];
2394
+ });
2395
+ }
2396
+ async function prepareTlonGroupAdmission(params) {
2397
+ const { cfg, account, channelNest, botShipName, runtime } = params;
2398
+ const parentId = readStringField(params.messageSeal, "parent-id") ?? readStringField(params.messageSeal, "parent") ?? null;
2399
+ const mentioned = isBotMentioned(params.rawText, botShipName, params.botNickname ?? void 0);
2400
+ const configuredThreadMention = resolveChannelAuthorization(cfg, channelNest, params.getSettings()).requireMentionInBotThreads ?? account.requireMentionInBotThreads;
2401
+ const botParticipatedInThread = Boolean(params.isThreadReply && parentId && params.hasParticipatedInThread(parentId));
2402
+ const threadRootAuthor = !mentioned && params.isThreadReply && parentId && (configuredThreadMention !== void 0 || botParticipatedInThread) ? await fetchThreadRootAuthor(params.api, channelNest, parentId, runtime) : null;
2403
+ const isBotOwnedThread = Boolean(threadRootAuthor && normalizeShip(threadRootAuthor) === botShipName);
2404
+ const resolveCurrentAdmission = () => {
2405
+ const authorization = resolveChannelAuthorization(cfg, channelNest, params.getSettings());
2406
+ return {
2407
+ ...authorization,
2408
+ senderAllowed: params.isOwner(params.senderShip) || authorization.mode === "open" || authorization.allowedShips.some((ship) => normalizeShip(ship) === params.senderShip),
2409
+ mentionDecision: resolveTlonGroupMentionDecision({
2410
+ cfg,
2411
+ accountId: account.accountId,
2412
+ wasMentioned: mentioned,
2413
+ botParticipatedInThread,
2414
+ isBotOwnedThread,
2415
+ requireMentionInBotThreads: authorization.requireMentionInBotThreads ?? account.requireMentionInBotThreads
2416
+ })
2417
+ };
2418
+ };
2419
+ const admission = resolveCurrentAdmission();
2420
+ const { mentionDecision } = admission;
2421
+ if (mentionDecision.implicitMention && !mentioned && !mentionDecision.shouldSkip) runtime.log?.(`[tlon] Responding to thread we participated in (no mention): ${parentId}`);
2422
+ return {
2423
+ ...admission,
2424
+ parentId,
2425
+ isAdmissionAllowed: () => {
2426
+ const current = resolveCurrentAdmission();
2427
+ return current.senderAllowed && !current.mentionDecision.shouldSkip;
2428
+ }
2429
+ };
2430
+ }
2431
+ //#endregion
2432
+ //#region extensions/tlon/src/monitor/settings-helpers.ts
2433
+ function buildTlonSettingsMigrations(account, currentSettings) {
2434
+ return [...[
2435
+ "dmAllowlist",
2436
+ "groupInviteAllowlist",
2437
+ "groupChannels",
2438
+ "defaultAuthorizedShips",
2439
+ "autoDiscoverChannels",
2440
+ "autoAcceptDmInvites",
2441
+ "autoAcceptGroupInvites"
2442
+ ].map((key) => ({
2443
+ key,
2444
+ fileValue: account[key],
2445
+ settingsValue: currentSettings[key]
2446
+ })), {
2447
+ key: "showModelSig",
2448
+ fileValue: account.showModelSignature,
2449
+ settingsValue: currentSettings.showModelSig
2450
+ }];
2574
2451
  }
2575
2452
  function shouldMigrateTlonSetting(fileValue, settingsValue) {
2576
2453
  return (Array.isArray(fileValue) ? fileValue.length > 0 : fileValue != null) && !(settingsValue != null);
@@ -2657,7 +2534,8 @@ function createActiveSnapshotTracker() {
2657
2534
  return active;
2658
2535
  },
2659
2536
  has: (key) => processed.has(key),
2660
- add: (key) => processed.add(key)
2537
+ add: (key) => processed.add(key),
2538
+ addIfAccepted: (key, accepted) => accepted && processed.add(key)
2661
2539
  };
2662
2540
  }
2663
2541
  //#endregion
@@ -2699,9 +2577,8 @@ async function monitorTlonProvider(opts = {}) {
2699
2577
  sleep: (delayMs) => sleepWithAbort(delayMs, opts.abortSignal)
2700
2578
  });
2701
2579
  }
2702
- let api = null;
2703
2580
  const cookie = await authenticateWithRetry();
2704
- api = new UrbitSSEClient(account.url, cookie, {
2581
+ const api = new UrbitSSEClient(account.url, cookie, {
2705
2582
  ship: botShipName,
2706
2583
  ssrfPolicy,
2707
2584
  logger: {
@@ -2747,16 +2624,7 @@ async function monitorTlonProvider(opts = {}) {
2747
2624
  async function migrateConfigToSettings() {
2748
2625
  const migrations = buildTlonSettingsMigrations(account, currentSettings);
2749
2626
  for (const { key, fileValue, settingsValue } of migrations) if (shouldMigrateTlonSetting(fileValue, settingsValue)) try {
2750
- await api.poke({
2751
- app: "settings",
2752
- mark: "settings-event",
2753
- json: { "put-entry": {
2754
- "bucket-key": "tlon",
2755
- "entry-key": key,
2756
- value: fileValue,
2757
- desk: "moltbot"
2758
- } }
2759
- });
2627
+ await putTlonSetting(api, key, fileValue);
2760
2628
  runtime.log?.(`[tlon] Migrated ${key} from config to settings store`);
2761
2629
  } catch (err) {
2762
2630
  runtime.log?.(`[tlon] Failed to migrate ${key}: ${String(err)}`);
@@ -2791,19 +2659,8 @@ async function monitorTlonProvider(opts = {}) {
2791
2659
  if (!effectiveOwnerShip) return false;
2792
2660
  return normalizeShip(ship) === effectiveOwnerShip;
2793
2661
  }
2794
- /**
2795
- * Extract the DM partner ship from the 'whom' field.
2796
- * This is the canonical source for DM routing (more reliable than essay.author).
2797
- * Returns empty string if whom doesn't contain a valid patp-like value.
2798
- */
2799
- function extractDmPartnerShip(whom) {
2800
- const raw = typeof whom === "string" ? whom : whom && typeof whom === "object" && "ship" in whom && typeof whom.ship === "string" ? whom.ship : "";
2801
- const normalized = normalizeShip(raw);
2802
- return /^~?[a-z-]+$/i.test(normalized) ? normalized : "";
2803
- }
2804
2662
  const processMessage = async (params) => {
2805
- const { messageId, senderShip, isGroup, channelNest, hostShip: _hostShip, channelName: _channelName, timestamp, parentId, isThreadReply, messageContent, turnAdoptionLifecycle, resolveChannelIngress } = params;
2806
- const groupChannel = channelNest;
2663
+ const { messageId, senderShip, isGroup, channelNest, timestamp, parentId, isThreadReply, isAdmissionAllowed, messageContent, turnAdoptionLifecycle, resolveChannelIngress } = params;
2807
2664
  let messageText = params.messageText;
2808
2665
  let attachments = [];
2809
2666
  let unavailableMediaCount = 0;
@@ -2813,8 +2670,8 @@ async function monitorTlonProvider(opts = {}) {
2813
2670
  } catch (error) {
2814
2671
  runtime.log?.(`[tlon] Failed to download images: ${formatErrorMessage(error)}`);
2815
2672
  }
2816
- if (isThreadReply && parentId && groupChannel) try {
2817
- const threadHistory = await fetchThreadHistory(api, groupChannel, parentId, 20, runtime);
2673
+ if (isThreadReply && parentId && channelNest) try {
2674
+ const threadHistory = await fetchThreadHistory(api, channelNest, parentId, 20, runtime);
2818
2675
  if (threadHistory.length > 0) {
2819
2676
  const threadContext = threadHistory.slice(-10).map((msg) => `${msg.author}: ${msg.content}`).join("\n");
2820
2677
  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}`;
@@ -2823,23 +2680,16 @@ async function monitorTlonProvider(opts = {}) {
2823
2680
  } catch (error) {
2824
2681
  runtime?.log?.(`[tlon] Could not fetch thread context: ${formatErrorMessage(error)}`);
2825
2682
  }
2826
- if (isGroup && groupChannel && isSummarizationRequest(messageText)) try {
2827
- const history = await channelHistory.getChannelHistory(api, groupChannel, 50, runtime);
2683
+ if (isGroup && channelNest && isSummarizationRequest(messageText)) try {
2684
+ const history = await channelHistory.getChannelHistory(api, channelNest, 50, runtime);
2828
2685
  if (history.length === 0) {
2829
2686
  const noHistoryMsg = "I couldn't fetch any messages for this channel. It might be empty or there might be a permissions issue.";
2830
- if (isGroup) {
2831
- const parsed = parseChannelNest(groupChannel);
2832
- if (parsed) await sendGroupMessage({
2833
- api,
2834
- fromShip: botShipName,
2835
- hostShip: parsed.hostShip,
2836
- channelName: parsed.channelName,
2837
- text: noHistoryMsg
2838
- });
2839
- } else await sendDm({
2687
+ const parsed = parseChannelNest(channelNest);
2688
+ if (parsed && isAdmissionAllowed?.() !== false) await sendGroupMessage({
2840
2689
  api,
2841
2690
  fromShip: botShipName,
2842
- toShip: senderShip,
2691
+ hostShip: parsed.hostShip,
2692
+ channelName: parsed.channelName,
2843
2693
  text: noHistoryMsg
2844
2694
  });
2845
2695
  return;
@@ -2852,19 +2702,12 @@ async function monitorTlonProvider(opts = {}) {
2852
2702
  4. Notable participants`;
2853
2703
  } catch (error) {
2854
2704
  const errorMsg = `Sorry, I encountered an error while fetching the channel history: ${formatErrorMessage(error)}`;
2855
- if (isGroup && groupChannel) {
2856
- const parsed = parseChannelNest(groupChannel);
2857
- if (parsed) await sendGroupMessage({
2858
- api,
2859
- fromShip: botShipName,
2860
- hostShip: parsed.hostShip,
2861
- channelName: parsed.channelName,
2862
- text: errorMsg
2863
- });
2864
- } else await sendDm({
2705
+ const parsed = parseChannelNest(channelNest);
2706
+ if (parsed && isAdmissionAllowed?.() !== false) await sendGroupMessage({
2865
2707
  api,
2866
2708
  fromShip: botShipName,
2867
- toShip: senderShip,
2709
+ hostShip: parsed.hostShip,
2710
+ channelName: parsed.channelName,
2868
2711
  text: errorMsg
2869
2712
  });
2870
2713
  return;
@@ -2875,7 +2718,7 @@ async function monitorTlonProvider(opts = {}) {
2875
2718
  accountId: opts.accountId ?? void 0,
2876
2719
  peer: {
2877
2720
  kind: isGroup ? "group" : "direct",
2878
- id: isGroup ? groupChannel ?? senderShip : senderShip
2721
+ id: isGroup ? channelNest ?? senderShip : senderShip
2879
2722
  }
2880
2723
  });
2881
2724
  const channelIngress = await resolveChannelIngress({
@@ -2933,13 +2776,13 @@ async function monitorTlonProvider(opts = {}) {
2933
2776
  body: commandBody,
2934
2777
  notice: `[tlon ${unavailableMediaCount > 1 ? `${unavailableMediaCount} attachments` : "attachment"} unavailable]`
2935
2778
  }) : commandBody;
2936
- const tlonConversationId = isGroup ? groupChannel ?? channelNest ?? senderShip : senderShip;
2779
+ const tlonConversationId = isGroup ? channelNest ?? senderShip : senderShip;
2937
2780
  const ctxPayload = core.channel.inbound.buildContext({
2938
2781
  channel: "tlon",
2939
2782
  accountId: route.accountId,
2940
2783
  messageId,
2941
2784
  timestamp,
2942
- from: isGroup ? `tlon:group:${groupChannel}` : `tlon:${senderShip}`,
2785
+ from: isGroup ? `tlon:group:${channelNest}` : `tlon:${senderShip}`,
2943
2786
  sender: {
2944
2787
  id: senderShip,
2945
2788
  name: senderShip,
@@ -2958,7 +2801,7 @@ async function monitorTlonProvider(opts = {}) {
2958
2801
  },
2959
2802
  reply: {
2960
2803
  to: `tlon:${botShipName}`,
2961
- originatingTo: `tlon:${isGroup ? groupChannel : botShipName}`,
2804
+ originatingTo: `tlon:${isGroup ? channelNest : botShipName}`,
2962
2805
  replyToId: parentId ?? void 0
2963
2806
  },
2964
2807
  message: {
@@ -2979,7 +2822,7 @@ async function monitorTlonProvider(opts = {}) {
2979
2822
  });
2980
2823
  const dispatchStartTime = Date.now();
2981
2824
  const humanDelay = resolveHumanDelayConfig(cfg, route.agentId);
2982
- const deliveryTarget = isGroup ? groupChannel : senderShip;
2825
+ const deliveryTarget = isGroup ? channelNest : senderShip;
2983
2826
  const prepareReplyPayload = (payload) => {
2984
2827
  const replyText = payload.text;
2985
2828
  if (!replyText) return payload;
@@ -2993,7 +2836,7 @@ async function monitorTlonProvider(opts = {}) {
2993
2836
  };
2994
2837
  };
2995
2838
  const rememberThreadParticipation = (result) => {
2996
- if (!isGroup || !groupChannel || !parentId || result?.visibleReplySent === false) return;
2839
+ if (!isGroup || !channelNest || !parentId || result?.visibleReplySent === false) return;
2997
2840
  participatedThreads.add(parentId);
2998
2841
  runtime.log?.(`[tlon] Now tracking thread for future replies: ${parentId}`);
2999
2842
  };
@@ -3001,6 +2844,7 @@ async function monitorTlonProvider(opts = {}) {
3001
2844
  ...turnAdoptionLifecycle ? bindIngressLifecycleToReplyOptions(turnAdoptionLifecycle) : {},
3002
2845
  ...promptMedia.media.length > 0 ? { media: promptMedia.media } : {}
3003
2846
  };
2847
+ if (isAdmissionAllowed?.() === false) return;
3004
2848
  await core.channel.inbound.dispatch({
3005
2849
  channel: "tlon",
3006
2850
  accountId: route.accountId,
@@ -3022,8 +2866,8 @@ async function monitorTlonProvider(opts = {}) {
3022
2866
  deliver: async (payload) => {
3023
2867
  const replyText = payload.text;
3024
2868
  if (!replyText) return { visibleReplySent: false };
3025
- if (isGroup && groupChannel) {
3026
- const parsed = parseChannelNest(groupChannel);
2869
+ if (isGroup && channelNest) {
2870
+ const parsed = parseChannelNest(channelNest);
3027
2871
  if (!parsed) return { visibleReplySent: false };
3028
2872
  await sendGroupMessage({
3029
2873
  api,
@@ -3072,14 +2916,11 @@ async function monitorTlonProvider(opts = {}) {
3072
2916
  return newCount;
3073
2917
  };
3074
2918
  const { resolveAllCites } = createTlonCitationResolver({
3075
- api: { scry: (path) => api.scry(path) },
2919
+ api,
3076
2920
  runtime
3077
2921
  });
3078
2922
  const { queueApprovalRequest, handleApprovalResponse, handleAdminCommand } = createTlonApprovalRuntime({
3079
- api: {
3080
- poke: (payload) => api.poke(payload),
3081
- scry: (path) => api.scry(path)
3082
- },
2923
+ api,
3083
2924
  runtime,
3084
2925
  botShipName,
3085
2926
  getPendingApprovals: () => pendingApprovals,
@@ -3096,56 +2937,34 @@ async function monitorTlonProvider(opts = {}) {
3096
2937
  },
3097
2938
  getEffectiveOwnerShip: () => effectiveOwnerShip,
3098
2939
  processApprovedMessage: async (approval) => {
3099
- if (!approval.originalMessage) return;
3100
- if (approval.type === "dm") {
3101
- await processMessage({
3102
- messageId: approval.originalMessage.messageId,
3103
- senderShip: approval.requestingShip,
3104
- messageText: approval.originalMessage.messageText,
3105
- messageContent: approval.originalMessage.messageContent,
3106
- isGroup: false,
3107
- timestamp: approval.originalMessage.timestamp,
3108
- resolveChannelIngress: async (contextBinding) => await resolveTlonMessageIngress({
3109
- senderShip: approval.requestingShip,
3110
- accountId: account.accountId,
3111
- conversation: {
3112
- kind: "direct",
3113
- id: approval.requestingShip
3114
- },
3115
- allowFrom: [approval.requestingShip],
3116
- dmPolicy: "allowlist",
3117
- contextBinding
3118
- })
3119
- });
3120
- return;
3121
- }
3122
- if (approval.type === "channel" && approval.channelNest) {
3123
- const parsedChannel = parseChannelNest(approval.channelNest);
3124
- await processMessage({
3125
- messageId: approval.originalMessage.messageId,
3126
- senderShip: approval.requestingShip,
3127
- messageText: approval.originalMessage.messageText,
3128
- messageContent: approval.originalMessage.messageContent,
3129
- isGroup: true,
3130
- channelNest: approval.channelNest,
3131
- hostShip: parsedChannel?.hostShip,
3132
- channelName: parsedChannel?.channelName,
3133
- timestamp: approval.originalMessage.timestamp,
2940
+ if (!approval.originalMessage || approval.type === "group") return;
2941
+ const isGroup = approval.type === "channel";
2942
+ const conversationId = isGroup ? approval.channelNest ?? "" : approval.requestingShip;
2943
+ if (isGroup && !conversationId) return;
2944
+ await processMessage({
2945
+ messageId: approval.originalMessage.messageId,
2946
+ senderShip: approval.requestingShip,
2947
+ messageText: approval.originalMessage.messageText,
2948
+ messageContent: approval.originalMessage.messageContent,
2949
+ timestamp: approval.originalMessage.timestamp,
2950
+ isGroup,
2951
+ ...isGroup ? {
2952
+ channelNest: conversationId,
3134
2953
  parentId: approval.originalMessage.parentId,
3135
- isThreadReply: approval.originalMessage.isThreadReply,
3136
- resolveChannelIngress: async (contextBinding) => await resolveTlonMessageIngress({
3137
- senderShip: approval.requestingShip,
3138
- accountId: account.accountId,
3139
- conversation: {
3140
- kind: "group",
3141
- id: approval.channelNest
3142
- },
3143
- allowFrom: [approval.requestingShip],
3144
- groupPolicy: "allowlist",
3145
- contextBinding
3146
- })
3147
- });
3148
- }
2954
+ isThreadReply: approval.originalMessage.isThreadReply
2955
+ } : {},
2956
+ resolveChannelIngress: async (contextBinding) => await resolveTlonMessageIngress({
2957
+ senderShip: approval.requestingShip,
2958
+ accountId: account.accountId,
2959
+ conversation: {
2960
+ kind: isGroup ? "group" : "direct",
2961
+ id: conversationId
2962
+ },
2963
+ allowFrom: [approval.requestingShip],
2964
+ ...isGroup ? { groupPolicy: "allowlist" } : { dmPolicy: "allowlist" },
2965
+ contextBinding
2966
+ })
2967
+ });
3149
2968
  },
3150
2969
  refreshWatchedChannels
3151
2970
  });
@@ -3165,7 +2984,6 @@ async function monitorTlonProvider(opts = {}) {
3165
2984
  const replySet = asNullableRecord(replyPayload?.set);
3166
2985
  const essay = asNullableRecord(set?.essay);
3167
2986
  const memo = asNullableRecord(replySet?.memo);
3168
- if (!essay && !memo) return;
3169
2987
  const content = memo ?? essay;
3170
2988
  if (!content) return;
3171
2989
  const isThreadReply = Boolean(memo);
@@ -3183,41 +3001,42 @@ async function monitorTlonProvider(opts = {}) {
3183
3001
  timestamp: sentAt,
3184
3002
  id: messageId
3185
3003
  });
3186
- const seal = isThreadReply ? asNullableRecord(replySet?.seal) : asNullableRecord(set?.seal);
3187
- const parentId = readStringField(seal, "parent-id") ?? readStringField(seal, "parent") ?? null;
3188
- const mentioned = isBotMentioned(rawText, botShipName, botNickname ?? void 0);
3189
- const inParticipatedThread = isThreadReply && parentId && participatedThreads.has(parentId);
3190
- const mentionDecision = resolveTlonGroupMentionDecision({
3004
+ const { allowedShips, senderAllowed, mentionDecision, parentId, isAdmissionAllowed } = await prepareTlonGroupAdmission({
3191
3005
  cfg,
3192
- accountId: account.accountId,
3193
- wasMentioned: mentioned,
3194
- botParticipatedInThread: Boolean(inParticipatedThread)
3006
+ account,
3007
+ api,
3008
+ channelNest: nest,
3009
+ senderShip,
3010
+ isOwner,
3011
+ botShipName,
3012
+ botNickname,
3013
+ rawText,
3014
+ messageSeal: isThreadReply ? asNullableRecord(replySet?.seal) : asNullableRecord(set?.seal),
3015
+ isThreadReply,
3016
+ hasParticipatedInThread: participatedThreads.has,
3017
+ getSettings: () => currentSettings,
3018
+ runtime
3195
3019
  });
3196
3020
  if (mentionDecision.shouldSkip) return;
3197
- if (mentionDecision.implicitMention && !mentioned) runtime.log?.(`[tlon] Responding to thread we participated in (no mention): ${parentId}`);
3198
- const { mode, allowedShips } = resolveChannelAuthorization(cfg, nest, currentSettings);
3199
- if (isOwner(senderShip)) runtime.log?.(`[tlon] Owner ${senderShip} is always allowed in channels`);
3200
- else if (mode === "restricted") {
3201
- if (!allowedShips.map(normalizeShip).includes(senderShip)) {
3202
- if (effectiveOwnerShip) {
3203
- const approval = createPendingApproval({
3204
- type: "channel",
3205
- requestingShip: senderShip,
3206
- channelNest: nest,
3207
- messagePreview: sliceUtf16Safe(rawText, 0, 100),
3208
- originalMessage: {
3209
- messageId: messageId ?? "",
3210
- messageText: rawText,
3211
- messageContent: contentBody,
3212
- timestamp: sentAt,
3213
- parentId: parentId ?? void 0,
3214
- isThreadReply
3215
- }
3216
- });
3217
- await queueApprovalRequest(approval);
3218
- } else runtime.log?.(`[tlon] Access denied: ${senderShip} in ${nest} (allowed: ${allowedShips.join(", ")})`);
3219
- return;
3220
- }
3021
+ if (!senderAllowed) {
3022
+ if (effectiveOwnerShip) {
3023
+ const approval = createPendingApproval({
3024
+ type: "channel",
3025
+ requestingShip: senderShip,
3026
+ channelNest: nest,
3027
+ messagePreview: sliceUtf16Safe(rawText, 0, 100),
3028
+ originalMessage: {
3029
+ messageId,
3030
+ messageText: rawText,
3031
+ messageContent: contentBody,
3032
+ timestamp: sentAt,
3033
+ parentId: parentId ?? void 0,
3034
+ isThreadReply
3035
+ }
3036
+ });
3037
+ await queueApprovalRequest(approval);
3038
+ } else runtime.log?.(`[tlon] Access denied: ${senderShip} in ${nest} (allowed: ${allowedShips.join(", ")})`);
3039
+ return;
3221
3040
  }
3222
3041
  const messageText = await resolveAuthorizedMessageText({
3223
3042
  rawText,
@@ -3225,31 +3044,32 @@ async function monitorTlonProvider(opts = {}) {
3225
3044
  authorizedForCites: true,
3226
3045
  resolveAllCites
3227
3046
  });
3228
- const parsed = parseChannelNest(nest);
3229
3047
  await processMessage({
3230
- messageId: messageId ?? "",
3048
+ messageId,
3231
3049
  senderShip,
3232
3050
  messageText,
3233
3051
  messageContent: contentBody,
3234
3052
  isGroup: true,
3235
3053
  channelNest: nest,
3236
- hostShip: parsed?.hostShip,
3237
- channelName: parsed?.channelName,
3238
3054
  timestamp: sentAt,
3239
3055
  parentId,
3240
3056
  isThreadReply,
3241
3057
  turnAdoptionLifecycle,
3242
- resolveChannelIngress: async (contextBinding) => await resolveTlonMessageIngress({
3243
- senderShip,
3244
- accountId: account.accountId,
3245
- conversation: {
3246
- kind: "group",
3247
- id: nest
3248
- },
3249
- allowFrom: [...allowedShips.map(normalizeShip), ...effectiveOwnerShip ? [normalizeShip(effectiveOwnerShip)] : []],
3250
- groupPolicy: mode === "restricted" ? "allowlist" : "open",
3251
- contextBinding
3252
- })
3058
+ isAdmissionAllowed,
3059
+ resolveChannelIngress: async (contextBinding) => {
3060
+ const { mode, allowedShips: currentAllowedShips } = resolveChannelAuthorization(cfg, nest, currentSettings);
3061
+ return await resolveTlonMessageIngress({
3062
+ senderShip,
3063
+ accountId: account.accountId,
3064
+ conversation: {
3065
+ kind: "group",
3066
+ id: nest
3067
+ },
3068
+ allowFrom: [...currentAllowedShips.map(normalizeShip), ...effectiveOwnerShip ? [normalizeShip(effectiveOwnerShip)] : []],
3069
+ groupPolicy: mode === "restricted" ? "allowlist" : "open",
3070
+ contextBinding
3071
+ });
3072
+ }
3253
3073
  });
3254
3074
  } catch (error) {
3255
3075
  runtime.error?.(`[tlon] Error handling channel firehose event: ${formatErrorMessage(error)}`);
@@ -3289,8 +3109,7 @@ async function monitorTlonProvider(opts = {}) {
3289
3109
  requestingShip: ship,
3290
3110
  messagePreview: "(DM invite - no message yet)"
3291
3111
  });
3292
- await queueApprovalRequest(approval);
3293
- processedDmInvites.add(ship);
3112
+ processedDmInvites.addIfAccepted(ship, await queueApprovalRequest(approval));
3294
3113
  }
3295
3114
  }
3296
3115
  return;
@@ -3312,48 +3131,15 @@ async function monitorTlonProvider(opts = {}) {
3312
3131
  const rawText = extractMessageText(essay.content);
3313
3132
  if (!rawText.trim()) return;
3314
3133
  const messageText = rawText;
3315
- if (isOwner(senderShip) && isApprovalResponse(messageText)) {
3316
- if (await handleApprovalResponse(messageText)) {
3317
- runtime.log?.(`[tlon] Processed approval response from owner: ${messageText}`);
3318
- return;
3319
- }
3320
- }
3321
- if (isOwner(senderShip) && isAdminCommand(messageText)) {
3322
- if (await handleAdminCommand(messageText)) {
3323
- runtime.log?.(`[tlon] Processed admin command from owner: ${messageText}`);
3324
- return;
3325
- }
3134
+ if (isOwner(senderShip) && await handleApprovalResponse(messageText)) {
3135
+ runtime.log?.(`[tlon] Processed approval response from owner: ${messageText}`);
3136
+ return;
3326
3137
  }
3327
- if (isOwner(senderShip)) {
3328
- const resolvedMessageText = await resolveAuthorizedMessageText({
3329
- rawText,
3330
- content: essay.content,
3331
- authorizedForCites: true,
3332
- resolveAllCites
3333
- });
3334
- runtime.log?.(`[tlon] Processing DM from owner ${senderShip}`);
3335
- await processMessage({
3336
- messageId: messageId ?? "",
3337
- senderShip,
3338
- messageText: resolvedMessageText,
3339
- messageContent: essay.content,
3340
- isGroup: false,
3341
- timestamp: asFiniteNumber(essay?.sent) ?? Date.now(),
3342
- turnAdoptionLifecycle,
3343
- resolveChannelIngress: async (contextBinding) => await resolveTlonMessageIngress({
3344
- senderShip,
3345
- accountId: account.accountId,
3346
- conversation: {
3347
- kind: "direct",
3348
- id: senderShip
3349
- },
3350
- allowFrom: [senderShip],
3351
- dmPolicy: "allowlist",
3352
- contextBinding
3353
- })
3354
- });
3138
+ if (isOwner(senderShip) && await handleAdminCommand(messageText)) {
3139
+ runtime.log?.(`[tlon] Processed admin command from owner: ${messageText}`);
3355
3140
  return;
3356
3141
  }
3142
+ const ownerDm = isOwner(senderShip);
3357
3143
  const resolveChannelIngress = async (contextBinding) => await resolveTlonMessageIngress({
3358
3144
  senderShip,
3359
3145
  accountId: account.accountId,
@@ -3361,18 +3147,18 @@ async function monitorTlonProvider(opts = {}) {
3361
3147
  kind: "direct",
3362
3148
  id: senderShip
3363
3149
  },
3364
- allowFrom: effectiveDmAllowlist ?? [],
3150
+ allowFrom: ownerDm ? [senderShip] : effectiveDmAllowlist,
3365
3151
  dmPolicy: "allowlist",
3366
3152
  contextBinding
3367
3153
  });
3368
- if (!(await resolveChannelIngress()).senderAccess.allowed) {
3154
+ if (!ownerDm && !(await resolveChannelIngress()).senderAccess.allowed) {
3369
3155
  if (effectiveOwnerShip) {
3370
3156
  const approval = createPendingApproval({
3371
3157
  type: "dm",
3372
3158
  requestingShip: senderShip,
3373
3159
  messagePreview: sliceUtf16Safe(messageText, 0, 100),
3374
3160
  originalMessage: {
3375
- messageId: messageId ?? "",
3161
+ messageId,
3376
3162
  messageText,
3377
3163
  messageContent: essay.content,
3378
3164
  timestamp: asFiniteNumber(essay?.sent) ?? Date.now()
@@ -3382,14 +3168,16 @@ async function monitorTlonProvider(opts = {}) {
3382
3168
  } else runtime.log?.(`[tlon] Blocked DM from ${senderShip}: not in allowlist`);
3383
3169
  return;
3384
3170
  }
3171
+ const resolvedMessageText = await resolveAuthorizedMessageText({
3172
+ rawText,
3173
+ content: essay.content,
3174
+ authorizedForCites: true,
3175
+ resolveAllCites
3176
+ });
3177
+ if (ownerDm) runtime.log?.(`[tlon] Processing DM from owner ${senderShip}`);
3385
3178
  await processMessage({
3386
- messageText: await resolveAuthorizedMessageText({
3387
- rawText,
3388
- content: essay.content,
3389
- authorizedForCites: true,
3390
- resolveAllCites
3391
- }),
3392
- messageId: messageId ?? "",
3179
+ messageText: resolvedMessageText,
3180
+ messageId,
3393
3181
  senderShip,
3394
3182
  messageContent: essay.content,
3395
3183
  isGroup: false,
@@ -3416,40 +3204,35 @@ async function monitorTlonProvider(opts = {}) {
3416
3204
  });
3417
3205
  try {
3418
3206
  runtime.log?.("[tlon] Subscribing to firehose updates...");
3419
- await api.subscribe({
3420
- app: "channels",
3421
- path: "/v2",
3422
- event: async (event) => {
3423
- if ((await ingress.receive({
3424
- source: "channels",
3425
- event
3426
- })).kind === "ignored") await handleChannelsFirehose(event);
3427
- },
3428
- err: (error) => {
3429
- runtime.error?.(`[tlon] Channels firehose error: ${String(error)}`);
3430
- },
3431
- quit: () => {
3432
- runtime.log?.("[tlon] Channels firehose subscription ended");
3433
- }
3434
- });
3435
- runtime.log?.("[tlon] Subscribed to channels firehose (/v2)");
3436
- await api.subscribe({
3437
- app: "chat",
3438
- path: "/v3",
3439
- event: async (event) => {
3440
- if ((await ingress.receive({
3441
- source: "chat",
3442
- event
3443
- })).kind === "ignored") await handleChatFirehose(event);
3444
- },
3445
- err: (error) => {
3446
- runtime.error?.(`[tlon] Chat firehose error: ${String(error)}`);
3447
- },
3448
- quit: () => {
3449
- runtime.log?.("[tlon] Chat firehose subscription ended");
3450
- }
3451
- });
3452
- runtime.log?.("[tlon] Subscribed to chat firehose (/v3)");
3207
+ for (const [source, path, label, handleEvent] of [[
3208
+ "channels",
3209
+ "/v2",
3210
+ "Channels",
3211
+ handleChannelsFirehose
3212
+ ], [
3213
+ "chat",
3214
+ "/v3",
3215
+ "Chat",
3216
+ handleChatFirehose
3217
+ ]]) {
3218
+ await api.subscribe({
3219
+ app: source,
3220
+ path,
3221
+ event: async (event) => {
3222
+ if ((await ingress.receive({
3223
+ source,
3224
+ event
3225
+ })).kind === "ignored") await handleEvent(event);
3226
+ },
3227
+ err: (error) => {
3228
+ runtime.error?.(`[tlon] ${label} firehose error: ${String(error)}`);
3229
+ },
3230
+ quit: () => {
3231
+ runtime.log?.(`[tlon] ${label} firehose subscription ended`);
3232
+ }
3233
+ });
3234
+ runtime.log?.(`[tlon] Subscribed to ${source} firehose (${path})`);
3235
+ }
3453
3236
  await api.subscribe({
3454
3237
  app: "contacts",
3455
3238
  path: "/v1/news",
@@ -3520,16 +3303,7 @@ async function monitorTlonProvider(opts = {}) {
3520
3303
  const unpersistedChannels = discoveredChannels.filter((channel) => !currentChannels.includes(channel));
3521
3304
  if (unpersistedChannels.length === 0) return;
3522
3305
  const updatedChannels = mergeUniqueStrings(currentChannels, unpersistedChannels);
3523
- await api.poke({
3524
- app: "settings",
3525
- mark: "settings-event",
3526
- json: { "put-entry": {
3527
- "bucket-key": "tlon",
3528
- "entry-key": "groupChannels",
3529
- value: updatedChannels,
3530
- desk: "moltbot"
3531
- } }
3532
- });
3306
+ await putTlonSetting(api, "groupChannels", updatedChannels);
3533
3307
  currentSettings = {
3534
3308
  ...currentSettings,
3535
3309
  groupChannels: updatedChannels
@@ -3552,7 +3326,7 @@ async function monitorTlonProvider(opts = {}) {
3552
3326
  runtime.log?.(`[tlon] Groups-ui subscription failed (will rely on polling): ${String(err)}`);
3553
3327
  }
3554
3328
  {
3555
- const processedGroupInvites = /* @__PURE__ */ new Set();
3329
+ const processedGroupInvites = createActiveSnapshotTracker();
3556
3330
  const processPendingInvites = async (foreigns, propagateWriteFailures = false) => {
3557
3331
  if (!foreigns || typeof foreigns !== "object") return;
3558
3332
  let firstWriteError;
@@ -3587,8 +3361,7 @@ async function monitorTlonProvider(opts = {}) {
3587
3361
  requestingShip: inviterShip,
3588
3362
  groupFlag
3589
3363
  });
3590
- await queueApprovalRequest(approval);
3591
- processedGroupInvites.add(groupFlag);
3364
+ processedGroupInvites.addIfAccepted(groupFlag, await queueApprovalRequest(approval));
3592
3365
  continue;
3593
3366
  }
3594
3367
  if (effectiveAutoAcceptGroupInvites) {
@@ -3656,10 +3429,10 @@ async function monitorTlonProvider(opts = {}) {
3656
3429
  clearInterval(pollInterval);
3657
3430
  });
3658
3431
  } finally {
3659
- api?.stopReceiving();
3432
+ api.stopReceiving();
3660
3433
  await ingress.stop();
3661
3434
  try {
3662
- await api?.close();
3435
+ await api.close();
3663
3436
  } catch (error) {
3664
3437
  runtime.error?.(`[tlon] Cleanup error: ${formatErrorMessage(error)}`);
3665
3438
  }
@@ -3682,9 +3455,6 @@ async function releaseUploadResponse(guarded) {
3682
3455
  await guarded.release();
3683
3456
  }
3684
3457
  }
3685
- function getExtensionFromMimeType(mimeType) {
3686
- return extensionForMime(mimeType) || ".jpg";
3687
- }
3688
3458
  function hasCustomS3Creds(credentials) {
3689
3459
  return Boolean(credentials?.accessKeyId && credentials?.endpoint && credentials?.secretAccessKey);
3690
3460
  }
@@ -3741,12 +3511,6 @@ function prefixEndpoint(endpoint) {
3741
3511
  function sanitizeFileName(fileName) {
3742
3512
  return fileName.split(/[/\\]/).pop() || fileName;
3743
3513
  }
3744
- async function getAuthCookie(config) {
3745
- return await authenticate(config.shipUrl, await config.getCode(), {
3746
- ssrfPolicy: ssrfPolicyFromDangerouslyAllowPrivateNetwork(config.dangerouslyAllowPrivateNetwork),
3747
- beforeRequest: config.assertDirectAdapterHandoff
3748
- });
3749
- }
3750
3514
  async function scryJson(config, cookie, path) {
3751
3515
  return await scryUrbitPath({
3752
3516
  baseUrl: config.shipUrl,
@@ -3811,11 +3575,14 @@ async function uploadFile(params, clientConfig) {
3811
3575
  ...clientConfig,
3812
3576
  shipName: clientConfig.shipName.replace(/^~/, "")
3813
3577
  };
3814
- const cookie = await getAuthCookie(config);
3578
+ const cookie = await authenticate(config.shipUrl, await config.getCode(), {
3579
+ ssrfPolicy: ssrfPolicyFromDangerouslyAllowPrivateNetwork(config.dangerouslyAllowPrivateNetwork),
3580
+ beforeRequest: config.assertDirectAdapterHandoff
3581
+ });
3815
3582
  const privateNetworkPolicy = ssrfPolicyFromDangerouslyAllowPrivateNetwork(config.dangerouslyAllowPrivateNetwork);
3816
3583
  const [storageConfig, credentials] = await Promise.all([getStorageConfiguration(config, cookie), getStorageCredentials(config, cookie)]);
3817
3584
  const contentType = params.contentType || params.blob.type || "application/octet-stream";
3818
- const extension = getExtensionFromMimeType(contentType);
3585
+ const extension = extensionForMime(contentType) || ".jpg";
3819
3586
  const fileName = sanitizeFileName(params.fileName || `upload${extension}`);
3820
3587
  const fileKey = `${config.shipName}/${Date.now()}-${crypto.randomUUID()}-${fileName}`;
3821
3588
  if (isHostedShipUrl(config.shipUrl) && (storageConfig.service === "presigned-url" || !hasCustomS3Creds(credentials))) {