@openclaw/tlon 2026.10.10 → 2026.10.34

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,10 +1,11 @@
1
- import { i as __reExport, r as __exportAll } from "./doctor-contract-CfYeTj9o.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 { c as resolveTlonAccount, d as parseChannelNest, f as parseTlonTarget, l as formatTargetHint, o as validateUrbitBaseUrl, u as normalizeShip } from "./setup-core-DnIfSMDp.mjs";
4
- import { t as getTlonRuntime } from "./runtime-ReERXJF_.mjs";
5
- import { t as tlonSetupWizard } from "./setup-surface-CTiMlwQy.mjs";
3
+ import { c as resolveTlonAccount, d as normalizeShip, f as parseChannelNest, l as TLON_CLUB_ID_RE, o as validateUrbitBaseUrl, p as parseTlonTarget, u as formatTargetHint } from "./setup-core-DQLcZhhT.mjs";
4
+ import { n as TlonClubPolicySchema, r as TlonClubRulesSchema } from "./channel-DUrG5iQ1.mjs";
5
+ import { t as getTlonRuntime } from "./runtime-Ck3lNvST.mjs";
6
+ import { t as tlonSetupWizard } from "./setup-surface-BNYZOF4n.mjs";
6
7
  import { fetchWithSsrFGuard, ssrfPolicyFromDangerouslyAllowPrivateNetwork } from "openclaw/plugin-sdk/ssrf-runtime";
7
- import { bindIngressLifecycleToReplyOptions, createChannelIngressError, createChannelIngressMonitor, createMessageReceiptFromOutboundResults, waitUntilAbort } from "openclaw/plugin-sdk/channel-outbound";
8
+ import { bindIngressLifecycleToReplyOptions, createArmableStallWatchdog, createChannelIngressError, createChannelIngressMonitor, createMessageReceiptFromOutboundResults, waitUntilAbort } from "openclaw/plugin-sdk/channel-outbound";
8
9
  import { expectDefined } from "openclaw/plugin-sdk/expect-runtime";
9
10
  import { asBoolean, asFiniteNumber, asNullableRecord, filterStringEntries, normalizeLowercaseStringOrEmpty, normalizeNullableString, readStringField, uniqueStrings } from "openclaw/plugin-sdk/string-coerce-runtime";
10
11
  import crypto, { randomBytes, randomUUID } from "node:crypto";
@@ -25,7 +26,7 @@ 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
- // extensions/tlon/src/settings.ts
29
+ //#region extensions/tlon/src/settings.ts
29
30
  const SETTINGS_DESK = "moltbot";
30
31
  const SETTINGS_BUCKET = "tlon";
31
32
  function parseJsonSetting(value) {
@@ -52,6 +53,8 @@ function parseSettingsResponse(raw) {
52
53
  return {
53
54
  groupChannels: Array.isArray(settings.groupChannels) ? filterStringEntries(settings.groupChannels) : void 0,
54
55
  dmAllowlist: Array.isArray(settings.dmAllowlist) ? filterStringEntries(settings.dmAllowlist) : void 0,
56
+ clubPolicy: TlonClubPolicySchema.safeParse(settings.clubPolicy).data,
57
+ clubRules: TlonClubRulesSchema.safeParse(parseJsonSetting(settings.clubRules)).data,
55
58
  autoDiscoverChannels: asBoolean(settings.autoDiscoverChannels),
56
59
  showModelSig: asBoolean(settings.showModelSig),
57
60
  autoAcceptDmInvites: asBoolean(settings.autoAcceptDmInvites),
@@ -73,14 +76,15 @@ function parsePendingApprovals(value) {
73
76
  return parsed.filter((item) => {
74
77
  if (!item || typeof item !== "object") return false;
75
78
  const obj = item;
76
- return typeof obj.id === "string" && (obj.type === "dm" || obj.type === "channel" || obj.type === "group") && typeof obj.requestingShip === "string" && typeof obj.timestamp === "number" && (obj.clubId === void 0 || typeof obj.clubId === "string") && (obj.verifiedDirect === void 0 || typeof obj.verifiedDirect === "boolean");
79
+ return typeof obj.id === "string" && (obj.type === "dm" || obj.type === "channel" || obj.type === "group" || obj.type === "club" && typeof obj.clubId === "string" && TLON_CLUB_ID_RE.test(obj.clubId) && (obj.clubMode === "once" || obj.clubMode === "message")) && typeof obj.requestingShip === "string" && typeof obj.timestamp === "number" && (obj.clubId === void 0 || typeof obj.clubId === "string") && (obj.verifiedDirect === void 0 || typeof obj.verifiedDirect === "boolean");
77
80
  });
78
81
  }
79
82
  function parseSettingsEvent(event) {
80
- if (!event || typeof event !== "object") return null;
81
- const evt = event;
83
+ const record = asNullableRecord(event);
84
+ if (!record) return null;
85
+ const evt = asNullableRecord(record["settings-event"]) ?? record;
82
86
  const operation = evt["put-entry"] ? "put-entry" : "del-entry";
83
- const entry = evt[operation];
87
+ const entry = asNullableRecord(evt[operation]);
84
88
  if (!entry || entry.desk !== SETTINGS_DESK || entry["bucket-key"] !== SETTINGS_BUCKET) return null;
85
89
  return {
86
90
  key: typeof entry["entry-key"] === "string" ? entry["entry-key"] : "",
@@ -147,12 +151,14 @@ function createSettingsManager(api, logger) {
147
151
  }
148
152
  };
149
153
  }
150
- // extensions/tlon/src/urbit/redact.ts
154
+ //#endregion
155
+ //#region extensions/tlon/src/urbit/redact.ts
151
156
  const URBIT_COOKIE_REFLECTION_RE = /\burbauth-[a-z0-9~-]+=[^\s"'(),;]+/gi;
152
157
  function redactUrbitErrorText(text) {
153
158
  return redactToolPayloadText(text).replace(URBIT_COOKIE_REFLECTION_RE, "***");
154
159
  }
155
- // extensions/tlon/src/urbit/errors.ts
160
+ //#endregion
161
+ //#region extensions/tlon/src/urbit/errors.ts
156
162
  var UrbitError = class extends Error {
157
163
  constructor(code, message, options) {
158
164
  super(message, options);
@@ -183,7 +189,8 @@ var UrbitAuthError = class extends UrbitError {
183
189
  this.name = "UrbitAuthError";
184
190
  }
185
191
  };
186
- // extensions/tlon/src/urbit/fetch.ts
192
+ //#endregion
193
+ //#region extensions/tlon/src/urbit/fetch.ts
187
194
  async function urbitFetch(params) {
188
195
  const validated = validateUrbitBaseUrl(params.baseUrl);
189
196
  if (!validated.ok) throw new UrbitUrlError(validated.error);
@@ -208,7 +215,8 @@ async function urbitFetch(params) {
208
215
  }
209
216
  };
210
217
  }
211
- // extensions/tlon/src/urbit/auth.ts
218
+ //#endregion
219
+ //#region extensions/tlon/src/urbit/auth.ts
212
220
  const MAX_AUTH_BODY_DRAIN_BYTES = 65536;
213
221
  async function authenticate(url, code, options = {}) {
214
222
  const { response, release } = await urbitFetch({
@@ -237,7 +245,8 @@ async function authenticate(url, code, options = {}) {
237
245
  await release();
238
246
  }
239
247
  }
240
- // extensions/tlon/src/urbit/context.ts
248
+ //#endregion
249
+ //#region extensions/tlon/src/urbit/context.ts
241
250
  function normalizeUrbitCookie(cookie) {
242
251
  return cookie.split(";")[0] ?? cookie;
243
252
  }
@@ -250,7 +259,8 @@ function getUrbitContext(url, ship) {
250
259
  ship: (ship?.replace(/^~/, "") ?? validated.hostname.split(".")[0] ?? validated.hostname).trim()
251
260
  };
252
261
  }
253
- // extensions/tlon/src/urbit/story.ts
262
+ //#endregion
263
+ //#region extensions/tlon/src/urbit/story.ts
254
264
  function matchMarkdownDestination(text, image) {
255
265
  const prefix = (image ? /^!\[([^\]]*)\]\(/ : /^\[([^\]]+)\]\(/).exec(text);
256
266
  if (!prefix) return null;
@@ -646,7 +656,8 @@ function markdownToStory(markdown) {
646
656
  }
647
657
  return story;
648
658
  }
649
- // extensions/tlon/src/urbit/send.ts
659
+ //#endregion
660
+ //#region extensions/tlon/src/urbit/send.ts
650
661
  function createTlonSendReceipt(params) {
651
662
  return createMessageReceiptFromOutboundResults({
652
663
  results: [{
@@ -665,35 +676,67 @@ async function sendDm({ text, ...params }) {
665
676
  kind: "text"
666
677
  });
667
678
  }
668
- async function sendDmWithStory({ api, fromShip, toShip, story, kind = "unknown" }) {
679
+ async function sendDmWithStory({ toShip, ...params }) {
680
+ return sendChatWithStory({
681
+ ...params,
682
+ target: {
683
+ kind: "dm",
684
+ ship: toShip
685
+ }
686
+ });
687
+ }
688
+ async function sendClubMessage({ text, ...params }) {
689
+ return sendClubMessageWithStory({
690
+ ...params,
691
+ story: markdownToStory(text),
692
+ kind: "text"
693
+ });
694
+ }
695
+ async function sendClubMessageWithStory({ clubId, ...params }) {
696
+ return sendChatWithStory({
697
+ ...params,
698
+ target: {
699
+ kind: "club",
700
+ clubId
701
+ }
702
+ });
703
+ }
704
+ async function sendChatWithStory({ api, fromShip, target, story, kind = "unknown" }) {
669
705
  const sentAt = Date.now();
670
706
  const id = `${fromShip}/${scot("ud", da.fromUnix(sentAt))}`;
671
- const action = {
672
- ship: toShip,
673
- diff: {
674
- id,
675
- delta: { add: {
676
- memo: {
677
- content: story,
678
- author: fromShip,
679
- sent: sentAt
680
- },
681
- kind: null,
682
- time: null
683
- } }
684
- }
707
+ const diff = {
708
+ id,
709
+ delta: { add: {
710
+ memo: {
711
+ content: story,
712
+ author: fromShip,
713
+ sent: sentAt
714
+ },
715
+ kind: null,
716
+ time: null
717
+ } }
685
718
  };
719
+ const conversationId = target.kind === "dm" ? target.ship : `club:${target.clubId}`;
686
720
  await api.poke({
687
721
  app: "chat",
688
- mark: "chat-dm-action",
689
- json: action
722
+ mark: target.kind === "dm" ? "chat-dm-action" : "chat-club-action",
723
+ json: target.kind === "dm" ? {
724
+ ship: target.ship,
725
+ diff
726
+ } : {
727
+ id: target.clubId,
728
+ diff: {
729
+ uid: "0v0",
730
+ delta: { writ: diff }
731
+ }
732
+ }
690
733
  });
691
734
  return {
692
735
  channel: "tlon",
693
736
  messageId: id,
694
737
  receipt: createTlonSendReceipt({
695
738
  messageId: id,
696
- conversationId: toShip,
739
+ conversationId,
697
740
  kind
698
741
  })
699
742
  };
@@ -754,7 +797,8 @@ function buildMediaStory(text, mediaUrl) {
754
797
  } }] });
755
798
  return story.length > 0 ? story : [{ inline: [""] }];
756
799
  }
757
- // extensions/tlon/src/urbit/channel-ops.ts
800
+ //#endregion
801
+ //#region extensions/tlon/src/urbit/channel-ops.ts
758
802
  async function putUrbitChannel(deps, params) {
759
803
  return await urbitFetch({
760
804
  baseUrl: deps.baseUrl,
@@ -865,9 +909,11 @@ async function ensureUrbitChannelOpen(deps, params) {
865
909
  beforeRequest: params.beforeRequest
866
910
  });
867
911
  }
868
- // extensions/tlon/src/urbit/sse-client.ts
912
+ //#endregion
913
+ //#region extensions/tlon/src/urbit/sse-client.ts
869
914
  const MAX_SSE_PAYLOAD_BYTES = 16777216;
870
915
  const MAX_RECONNECT_ATTEMPTS = 10;
916
+ const SSE_STALL_TIMEOUT_MS = 6e4;
871
917
  function parseUrbitSsePayload(data) {
872
918
  if (Buffer.byteLength(data, "utf8") > MAX_SSE_PAYLOAD_BYTES) throw new Error("Tlon Urbit SSE payload exceeds 16 MiB limit");
873
919
  try {
@@ -1026,6 +1072,17 @@ var UrbitSSEClient = class {
1026
1072
  async processStream(body) {
1027
1073
  if (!body) return;
1028
1074
  const stream = body instanceof ReadableStream ? Readable.fromWeb(body) : body;
1075
+ const streamController = this.streamController;
1076
+ const watchdog = createArmableStallWatchdog({
1077
+ label: "tlon-sse",
1078
+ timeoutMs: SSE_STALL_TIMEOUT_MS,
1079
+ onTimeout: ({ idleMs }) => {
1080
+ const error = /* @__PURE__ */ new Error(`Tlon Urbit SSE stream stalled: no data for ${Math.round(idleMs / 1e3)}s`);
1081
+ streamController?.abort(error);
1082
+ if (stream instanceof Readable) stream.destroy(error);
1083
+ }
1084
+ });
1085
+ watchdog.arm();
1029
1086
  const decoder = new TextDecoder();
1030
1087
  let buffer = "";
1031
1088
  let bufferBytes = 0;
@@ -1073,13 +1130,16 @@ var UrbitSSEClient = class {
1073
1130
  try {
1074
1131
  for await (const chunk of stream) {
1075
1132
  if (this.aborted) break;
1133
+ watchdog.disarm();
1076
1134
  if (typeof chunk === "string") {
1077
1135
  await consumeText(decoder.decode());
1078
1136
  await consumeText(chunk);
1079
1137
  } else await consumeText(decoder.decode(chunk, { stream: true }));
1138
+ watchdog.arm();
1080
1139
  }
1081
1140
  await consumeText(decoder.decode());
1082
1141
  } finally {
1142
+ watchdog.stop();
1083
1143
  if (this.streamRelease) {
1084
1144
  const release = this.streamRelease;
1085
1145
  this.streamRelease = null;
@@ -1140,8 +1200,11 @@ var UrbitSSEClient = class {
1140
1200
  auditContext: "tlon-urbit-poke"
1141
1201
  });
1142
1202
  }
1143
- async scry(path) {
1144
- return await scryUrbitPath(this.channelRequestContext(), {
1203
+ async scry(path, beforeRequest) {
1204
+ return await scryUrbitPath({
1205
+ ...this.channelRequestContext(),
1206
+ beforeRequest
1207
+ }, {
1145
1208
  path,
1146
1209
  auditContext: "tlon-urbit-scry"
1147
1210
  });
@@ -1258,7 +1321,8 @@ var UrbitSSEClient = class {
1258
1321
  }
1259
1322
  }
1260
1323
  };
1261
- // extensions/tlon/src/monitor/approval.ts
1324
+ //#endregion
1325
+ //#region extensions/tlon/src/monitor/approval.ts
1262
1326
  function generateApprovalId(type) {
1263
1327
  return `${type}-${Date.now()}-${randomBytes(3).toString("hex")}`;
1264
1328
  }
@@ -1268,6 +1332,7 @@ function createPendingApproval(params) {
1268
1332
  type: params.type,
1269
1333
  requestingShip: params.requestingShip,
1270
1334
  ...params.clubId !== void 0 ? { clubId: params.clubId } : {},
1335
+ ...params.clubMode !== void 0 ? { clubMode: params.clubMode } : {},
1271
1336
  ...params.verifiedDirect === true ? { verifiedDirect: true } : {},
1272
1337
  channelNest: params.channelNest,
1273
1338
  groupFlag: params.groupFlag,
@@ -1280,17 +1345,22 @@ function truncate(text, maxLength) {
1280
1345
  if (text.length <= maxLength) return text;
1281
1346
  return sliceUtf16Safe(text, 0, maxLength - 3) + "...";
1282
1347
  }
1348
+ function formatApprovalInstructions(id) {
1349
+ return `Reply "approve", "deny", or "block" if this is the only pending request. If multiple are pending, reply "approve ${id}", "deny ${id}", or "block ${id}".`;
1350
+ }
1283
1351
  function formatApprovalRequest(approval) {
1284
1352
  const preview = approval.messagePreview ? `\n"${truncate(approval.messagePreview, 100)}"` : "";
1285
1353
  switch (approval.type) {
1354
+ case "club":
1286
1355
  case "dm":
1287
1356
  if (approval.clubId !== void 0) {
1288
- const replayLine = approval.originalMessage ? `The message is answered as an unverified group DM sender, never as ${approval.requestingShip}.` : `The message is not kept, so it will not be answered; have ${approval.requestingShip} send it again in a normal direct message to get a reply.`;
1289
- return `New group DM message claiming to be from ${approval.requestingShip} (unverified; group DM ${approval.clubId}):${preview}\n\nApproving adds ${approval.requestingShip} to the DM allowlist. ${replayLine}\nReply "approve", "deny", or "block" (ID: ${approval.id})`;
1357
+ const permission = approval.type === "club" && approval.clubMode === "once" ? "Approving enables this club for automatic replies, including future messages." : "Approving permits this saved message only; it does not enable future messages.";
1358
+ const replayLine = approval.originalMessage ? "The reply goes to the club, using its own conversation." : "No message was saved; approval only dismisses this request.";
1359
+ return `Group DM ${approval.clubId}: claimed author ${approval.requestingShip} (unverified).${preview}\n\n${permission} Tlon does not authenticate club authors or participants. Input delivered under this club ID can use the agent's normal permitted tools.\n${replayLine} No direct-DM access or owner authority is granted. ` + (approval.type === "club" ? "Deny or block disables this club; no ship is blocked.\n" : "Blocking only dismisses this legacy request; no ship is blocked.\n") + formatApprovalInstructions(approval.id);
1290
1360
  }
1291
- return `New DM request from ${approval.requestingShip}:${preview}\n\nReply "approve", "deny", or "block" (ID: ${approval.id})`;
1292
- case "channel": return `${approval.requestingShip} mentioned you in ${approval.channelNest}:${preview}\n\nReply "approve", "deny", or "block"\n(ID: ${approval.id})`;
1293
- case "group": return `Group invite from ${approval.requestingShip} to join ${approval.groupFlag}\n\nReply "approve", "deny", or "block"\n(ID: ${approval.id})`;
1361
+ return `New DM request from ${approval.requestingShip}:${preview}\n\n` + formatApprovalInstructions(approval.id);
1362
+ case "channel": return `${approval.requestingShip} mentioned you in ${approval.channelNest}:${preview}\n\n` + formatApprovalInstructions(approval.id);
1363
+ case "group": return `Group invite from ${approval.requestingShip} to join ${approval.groupFlag}\n\n` + formatApprovalInstructions(approval.id);
1294
1364
  }
1295
1365
  throw new Error("Unsupported approval type");
1296
1366
  }
@@ -1303,8 +1373,7 @@ function parseApprovalResponse(text) {
1303
1373
  };
1304
1374
  }
1305
1375
  function findPendingApproval(pendingApprovals, id) {
1306
- if (id) return pendingApprovals.find((a) => a.id === id);
1307
- return pendingApprovals[pendingApprovals.length - 1];
1376
+ return id ? pendingApprovals.find((approval) => approval.id === id) : pendingApprovals.length === 1 ? pendingApprovals[0] : void 0;
1308
1377
  }
1309
1378
  function removePendingApproval(pendingApprovals, id) {
1310
1379
  return pendingApprovals.filter((a) => a.id !== id);
@@ -1317,9 +1386,15 @@ function requiresResendAfterApproval(approval) {
1317
1386
  return approval.type === "dm" && approval.originalMessage !== void 0 && approval.clubId === void 0 && approval.verifiedDirect !== true;
1318
1387
  }
1319
1388
  function formatApprovalConfirmation(approval, action) {
1389
+ if (approval.clubId !== void 0) {
1390
+ if (approval.type !== "club") return `Resolved legacy group DM request ${approval.id}. No standing club or direct-DM access was granted; no ship was blocked.`;
1391
+ if (action !== "approve") return `Disabled group DM ${approval.clubId}. No ship was blocked. Set its clubRules entry to "allow" to enable it again.`;
1392
+ return approval.clubMode === "once" ? `Enabled group DM ${approval.clubId} for automatic replies from unverified input. No direct-DM access or owner authority was granted.` : `Approved this group DM message only. No standing club or direct-DM access was granted.`;
1393
+ }
1320
1394
  if (action === "block") return `Blocked ${approval.requestingShip}. They will no longer be able to contact the bot.`;
1321
1395
  const actionText = action === "approve" ? "Approved" : "Denied";
1322
1396
  switch (approval.type) {
1397
+ case "club":
1323
1398
  case "dm":
1324
1399
  if (action === "approve") {
1325
1400
  if (requiresResendAfterApproval(approval)) return `${actionText} DM access for ${approval.requestingShip}. They can now message the bot.\nTheir earlier message was saved before this version and its sender cannot be verified, so it was not processed. Ask ${approval.requestingShip} to send it again.`;
@@ -1352,9 +1427,10 @@ function formatBlockedList(ships) {
1352
1427
  }
1353
1428
  function formatPendingList(approvals) {
1354
1429
  if (approvals.length === 0) return "No pending approval requests.";
1355
- return `Pending approvals (${approvals.length}):\n${approvals.map((a) => `• ${a.id}: ${a.type} from ${a.requestingShip}`).join("\n")}`;
1430
+ return `Pending approvals (${approvals.length}):\n${approvals.map((a) => a.clubId !== void 0 ? `• ${a.id}: group DM ${a.clubId} (unverified)` : `• ${a.id}: ${a.type} from ${a.requestingShip}`).join("\n")}`;
1356
1431
  }
1357
- // extensions/tlon/src/monitor/approval-runtime.ts
1432
+ //#endregion
1433
+ //#region extensions/tlon/src/monitor/approval-runtime.ts
1358
1434
  function createTlonApprovalRuntime(params) {
1359
1435
  const { api, runtime, botShipName, state, processApprovedMessage, refreshWatchedChannels } = params;
1360
1436
  let approvalOverflowNoticeSent = false;
@@ -1406,6 +1482,18 @@ function createTlonApprovalRuntime(params) {
1406
1482
  runtime.error?.(`[tlon] Failed to update channelRules: ${String(err)}`);
1407
1483
  }
1408
1484
  };
1485
+ const setClubRule = async (clubId, rule) => {
1486
+ const clubRules = {
1487
+ ...state.effectiveClubRules,
1488
+ [clubId]: rule
1489
+ };
1490
+ await putTlonSetting(api, "clubRules", JSON.stringify(clubRules));
1491
+ state.effectiveClubRules = clubRules;
1492
+ state.currentSettings = {
1493
+ ...state.currentSettings,
1494
+ clubRules
1495
+ };
1496
+ };
1409
1497
  const setShipBlocked = async (ship, blocked) => {
1410
1498
  const normalizedShip = normalizeShip(ship);
1411
1499
  const action = blocked ? "block" : "unblock";
@@ -1461,14 +1549,18 @@ function createTlonApprovalRuntime(params) {
1461
1549
  return false;
1462
1550
  }
1463
1551
  };
1464
- const queueApprovalRequest = async (approval) => {
1465
- if (await isShipBlocked(approval.requestingShip)) {
1552
+ const queueApprovalRequestUnqueued = async (approval) => {
1553
+ if (approval.clubId === void 0 && await isShipBlocked(approval.requestingShip)) {
1466
1554
  runtime.log?.(`[tlon] Ignoring request from blocked ship ${approval.requestingShip}`);
1467
1555
  return false;
1468
1556
  }
1469
1557
  const approvals = state.pendingApprovals;
1470
- const existing = approvals.find((item) => item.type === approval.type && item.requestingShip === approval.requestingShip && item.clubId === approval.clubId && (approval.type !== "channel" || item.channelNest === approval.channelNest) && (approval.type !== "group" || item.groupFlag === approval.groupFlag));
1558
+ const existing = approvals.find((item) => {
1559
+ if (approval.type === "club") return item.type === "club" && item.clubId === approval.clubId && item.clubMode === approval.clubMode && (approval.clubMode === "once" || item.originalMessage?.messageId === approval.originalMessage?.messageId);
1560
+ return item.type === approval.type && item.requestingShip === approval.requestingShip && item.clubId === approval.clubId && (approval.type !== "channel" || item.channelNest === approval.channelNest) && (approval.type !== "group" || item.groupFlag === approval.groupFlag);
1561
+ });
1471
1562
  if (existing) {
1563
+ if (approval.type === "club") return true;
1472
1564
  if (approval.originalMessage) {
1473
1565
  existing.originalMessage = approval.originalMessage;
1474
1566
  existing.messagePreview = approval.messagePreview;
@@ -1484,29 +1576,52 @@ function createTlonApprovalRuntime(params) {
1484
1576
  runtime.log?.(`[tlon] Pending approval limit reached; ignoring ${approval.type} request from ${approval.requestingShip}`);
1485
1577
  if (!approvalOverflowNoticeSent && approvalOverflowNoticeAttempts < 3) {
1486
1578
  approvalOverflowNoticeAttempts += 1;
1487
- approvalOverflowNoticeSent = await sendOwnerNotification(`Pending approval queue is full (${approvals.length}). Resolve existing requests with approve, deny, or block before asking rejected requesters to retry.`);
1579
+ approvalOverflowNoticeSent = await sendOwnerNotification(`Pending approval queue is full (${approvals.length}). Resolve existing requests by replying with approve, deny, or block followed by the request ID before asking rejected requesters to retry.`);
1488
1580
  }
1489
1581
  return false;
1490
1582
  }
1491
1583
  approvalOverflowNoticeSent = false;
1492
1584
  approvalOverflowNoticeAttempts = 0;
1493
- state.pendingApprovals = [...approvals, approval];
1494
- await savePendingApprovals(true);
1585
+ const nextApprovals = [...approvals, approval];
1586
+ await putTlonSetting(api, "pendingApprovals", JSON.stringify(nextApprovals));
1587
+ state.pendingApprovals = nextApprovals;
1495
1588
  await sendOwnerNotification(formatApprovalRequest(approval));
1496
1589
  runtime.log?.(`[tlon] Queued approval request: ${approval.id} (${approval.type} from ${approval.requestingShip})`);
1497
1590
  return true;
1498
1591
  };
1592
+ let pendingRequestWrite = Promise.resolve();
1593
+ const queueApprovalRequest = (approval) => {
1594
+ const result = pendingRequestWrite.then(() => queueApprovalRequestUnqueued(approval));
1595
+ pendingRequestWrite = result.then(() => {}, () => {});
1596
+ return result;
1597
+ };
1499
1598
  const handleApprovalResponse = async (text) => {
1500
1599
  const parsed = parseApprovalResponse(text);
1501
1600
  if (!parsed) return false;
1502
1601
  const approval = findPendingApproval(state.pendingApprovals, parsed.id);
1503
1602
  if (!approval) {
1504
- await sendOwnerNotification(`No pending approval found${parsed.id ? ` for ID: ${parsed.id}` : ""}`);
1603
+ await sendOwnerNotification(parsed.id ? `No pending approval found for ID: ${parsed.id}` : state.pendingApprovals.length > 1 ? `Multiple approvals are pending. Include an approval ID with your decision.\n\n${formatPendingList(state.pendingApprovals)}` : "No pending approval found.");
1604
+ return true;
1605
+ }
1606
+ if (approval.clubId !== void 0 && (state.effectiveClubPolicy === "disabled" || state.effectiveClubRules[approval.clubId] === "deny")) {
1607
+ await sendOwnerNotification(`Group DM ${approval.clubId} is disabled. No message was processed.`);
1608
+ state.pendingApprovals = removePendingApproval(state.pendingApprovals, approval.id);
1609
+ await savePendingApprovals();
1505
1610
  return true;
1506
1611
  }
1507
1612
  if (parsed.action === "approve") switch (approval.type) {
1613
+ case "club":
1614
+ if (approval.clubId && approval.clubMode === "once" && state.effectiveClubPolicy === "approve-once") await setClubRule(approval.clubId, "allow");
1615
+ else if (approval.clubMode === "once") {
1616
+ await sendOwnerNotification("The club policy changed. Send a new club message to request approval under the current policy.");
1617
+ state.pendingApprovals = removePendingApproval(state.pendingApprovals, approval.id);
1618
+ await savePendingApprovals();
1619
+ return true;
1620
+ }
1621
+ if (approval.originalMessage) await processApprovedMessage(approval);
1622
+ break;
1508
1623
  case "dm":
1509
- await addToDmAllowlist(approval.requestingShip);
1624
+ if (approval.clubId === void 0) await addToDmAllowlist(approval.requestingShip);
1510
1625
  if (requiresResendAfterApproval(approval)) runtime.log?.(`[tlon] Not replaying pre-upgrade DM request from ${approval.requestingShip}: sender provenance unknown; owner told to request a resend`);
1511
1626
  else if (approval.originalMessage) {
1512
1627
  runtime.log?.(`[tlon] Processing original message from ${approval.requestingShip} after approval`);
@@ -1546,7 +1661,8 @@ function createTlonApprovalRuntime(params) {
1546
1661
  runtime.error?.(`[tlon] Failed to join group ${approval.groupFlag}: ${String(err)}`);
1547
1662
  }
1548
1663
  }
1549
- else if (parsed.action === "block") await setShipBlocked(approval.requestingShip, true);
1664
+ else if (approval.type === "club" && approval.clubId) await setClubRule(approval.clubId, "deny");
1665
+ else if (parsed.action === "block" && approval.clubId === void 0) await setShipBlocked(approval.requestingShip, true);
1550
1666
  await sendOwnerNotification(formatApprovalConfirmation(approval, parsed.action));
1551
1667
  state.pendingApprovals = removePendingApproval(state.pendingApprovals, approval.id);
1552
1668
  await savePendingApprovals();
@@ -1585,7 +1701,8 @@ function createTlonApprovalRuntime(params) {
1585
1701
  handleAdminCommand
1586
1702
  };
1587
1703
  }
1588
- // extensions/tlon/src/monitor/authorization.ts
1704
+ //#endregion
1705
+ //#region extensions/tlon/src/monitor/authorization.ts
1589
1706
  function resolveChannelAuthorization(cfg, channelNest, settings) {
1590
1707
  const tlonConfig = cfg.channels?.tlon;
1591
1708
  const fileRules = tlonConfig?.authorization?.channelRules ?? {};
@@ -1601,7 +1718,8 @@ function resolveChannelAuthorization(cfg, channelNest, settings) {
1601
1718
  requireMentionInBotThreads: typeof requireMentionInBotThreads === "boolean" ? requireMentionInBotThreads : void 0
1602
1719
  };
1603
1720
  }
1604
- // extensions/tlon/src/monitor/utils.ts
1721
+ //#endregion
1722
+ //#region extensions/tlon/src/monitor/utils.ts
1605
1723
  function formatModelName(modelString) {
1606
1724
  if (!modelString) return "AI";
1607
1725
  const modelName = modelString.includes("/") ? expectDefined(modelString.split("/").at(1), "provider/model second segment") : modelString;
@@ -1703,7 +1821,8 @@ function isGroupInviteAllowed(inviterShip, allowlist) {
1703
1821
  }]
1704
1822
  }).allowed;
1705
1823
  }
1706
- function renderInlineItem(item, topLevel = false) {
1824
+ const MAX_INLINE_DEPTH = 100;
1825
+ function renderInlineItem(item, topLevel = false, depth = 0) {
1707
1826
  if (typeof item === "string") return item;
1708
1827
  const record = asNullableRecord(item);
1709
1828
  if (!record) return "";
@@ -1723,14 +1842,29 @@ function renderInlineItem(item, topLevel = false) {
1723
1842
  const linkContent = readStringField(link, "content");
1724
1843
  return topLevel ? linkHref : linkContent || linkHref;
1725
1844
  }
1726
- if (Array.isArray(record.bold)) return `**${extractInlineText(record.bold)}**`;
1727
- if (Array.isArray(record.italics)) return `*${extractInlineText(record.italics)}*`;
1728
- if (Array.isArray(record.strike)) return `~~${extractInlineText(record.strike)}~~`;
1729
- if (topLevel && Array.isArray(record.blockquote)) return `> ${extractInlineText(record.blockquote)}`;
1730
- return "";
1731
- }
1732
- function extractInlineText(items) {
1733
- return items.map((item) => renderInlineItem(item)).join("");
1845
+ const bold = Array.isArray(record.bold) ? record.bold : void 0;
1846
+ const italics = Array.isArray(record.italics) ? record.italics : void 0;
1847
+ const strike = Array.isArray(record.strike) ? record.strike : void 0;
1848
+ const blockquote = topLevel && Array.isArray(record.blockquote) ? record.blockquote : void 0;
1849
+ const nested = bold ?? italics ?? strike ?? blockquote;
1850
+ if (!nested) return "";
1851
+ if (depth >= MAX_INLINE_DEPTH) return "";
1852
+ const inner = extractInlineText(nested, depth + 1);
1853
+ if (bold) return `**${inner}**`;
1854
+ if (italics) return `*${inner}*`;
1855
+ if (strike) return `~~${inner}~~`;
1856
+ return `> ${inner}`;
1857
+ }
1858
+ function extractInlineText(items, depth = 0) {
1859
+ return items.map((item) => renderInlineItem(item, false, depth)).join("");
1860
+ }
1861
+ function extractMessageTextSafely(content, runtime) {
1862
+ try {
1863
+ return extractMessageText(content);
1864
+ } catch (error) {
1865
+ runtime.log?.(`[tlon] Failed to extract message text: ${formatErrorMessage(error)}`);
1866
+ return "";
1867
+ }
1734
1868
  }
1735
1869
  function extractMessageText(content) {
1736
1870
  if (!Array.isArray(content)) return "";
@@ -1814,9 +1948,12 @@ function formatSummarizationHistoryText(history, cfg) {
1814
1948
  envelope: envelopeOptions
1815
1949
  })).join("\n");
1816
1950
  }
1817
- // extensions/tlon/src/monitor/cites.ts
1951
+ //#endregion
1952
+ //#region extensions/tlon/src/monitor/cites.ts
1818
1953
  const CITE_PATH_SEGMENT_RE = /^[A-Za-z0-9._~-]+$/;
1819
1954
  const CITE_PATH_NORMALIZATION_BASE = "https://tlon.invalid";
1955
+ const CITATION_SCOPE_SKIP_LOG = "[tlon] Skipping cited post: citation is outside explicit channel scope";
1956
+ var CitationScopeChangedError = class extends Error {};
1820
1957
  function isSafeCitePathSegment(segment) {
1821
1958
  if (segment === "." || segment === "..") return false;
1822
1959
  return CITE_PATH_SEGMENT_RE.test(segment);
@@ -1836,7 +1973,7 @@ function buildCitedPostScryPath(nest, postId) {
1836
1973
  if (new URL(scryPath, CITE_PATH_NORMALIZATION_BASE).pathname !== scryPath) return null;
1837
1974
  return scryPath;
1838
1975
  }
1839
- async function resolveTlonCitations(content, api, runtime) {
1976
+ async function resolveTlonCitations(content, canExpandNest, api, runtime) {
1840
1977
  if (!Array.isArray(content)) return "";
1841
1978
  const resolved = [];
1842
1979
  for (const verse of content) {
@@ -1846,6 +1983,10 @@ async function resolveTlonCitations(content, api, runtime) {
1846
1983
  const whereMatch = readStringField(chan, "where")?.match(/\/msg\/(~[a-z-]+)\/(.+)/);
1847
1984
  const postId = whereMatch?.[2];
1848
1985
  if (!nest || !postId) continue;
1986
+ if (!canExpandNest(nest)) {
1987
+ runtime.log?.(CITATION_SCOPE_SKIP_LOG);
1988
+ continue;
1989
+ }
1849
1990
  const scryPath = buildCitedPostScryPath(nest, postId);
1850
1991
  if (!scryPath) {
1851
1992
  runtime.log?.("[tlon] Skipping cited post: citation does not name a channel post");
@@ -1853,17 +1994,28 @@ async function resolveTlonCitations(content, api, runtime) {
1853
1994
  }
1854
1995
  try {
1855
1996
  runtime.log?.(`[tlon] Fetching cited post: ${scryPath}`);
1856
- const data = asNullableRecord(await api.scry(scryPath));
1997
+ const data = asNullableRecord(await api.scry(scryPath, () => {
1998
+ if (!canExpandNest(nest)) throw new CitationScopeChangedError();
1999
+ }));
2000
+ if (!canExpandNest(nest)) {
2001
+ runtime.log?.(CITATION_SCOPE_SKIP_LOG);
2002
+ continue;
2003
+ }
1857
2004
  const essay = asNullableRecord(data?.essay);
1858
2005
  const text = essay?.content ? extractMessageText(essay.content) : "";
1859
2006
  if (text) resolved.push(`> ${whereMatch?.[1] || "unknown"} wrote: ${text}`);
1860
2007
  } catch (err) {
2008
+ if (err instanceof CitationScopeChangedError) {
2009
+ runtime.log?.(CITATION_SCOPE_SKIP_LOG);
2010
+ continue;
2011
+ }
1861
2012
  runtime.log?.(`[tlon] Failed to fetch cited post: ${String(err)}`);
1862
2013
  }
1863
2014
  }
1864
2015
  return resolved.length > 0 ? `${resolved.join("\n")}\n\n` : "";
1865
2016
  }
1866
- // extensions/tlon/src/monitor/discovery.ts
2017
+ //#endregion
2018
+ //#region extensions/tlon/src/monitor/discovery.ts
1867
2019
  /**
1868
2020
  * Fetch groups-ui init data, returning channels and foreigns.
1869
2021
  * This is a single scry that provides both channel discovery and pending invites.
@@ -1893,7 +2045,8 @@ async function fetchInitData(api, runtime) {
1893
2045
  };
1894
2046
  }
1895
2047
  }
1896
- // extensions/tlon/src/monitor/history.ts
2048
+ //#endregion
2049
+ //#region extensions/tlon/src/monitor/history.ts
1897
2050
  /**
1898
2051
  * Format a number as @ud (with dots every 3 digits from the right)
1899
2052
  * e.g., 170141184507799509469114119040828178432 -> 170.141.184.507.799.509.469.114.119.040.828.178.432
@@ -2026,10 +2179,25 @@ async function fetchThreadHistory(api, channelNest, parentId, count = 50, runtim
2026
2179
  return [];
2027
2180
  }
2028
2181
  }
2029
- // extensions/tlon/src/monitor/ingress.ts
2182
+ //#endregion
2183
+ //#region extensions/tlon/src/monitor/ingress.ts
2030
2184
  const TLON_INGRESS_PAYLOAD_VERSION = 1;
2031
2185
  const TLON_INGRESS_POLL_INTERVAL_MS = 1e3;
2032
2186
  const TlonIngressPermanentError = createChannelIngressError("TlonIngressPermanentError", { withReason: true });
2187
+ var TlonIngressUnserializableEventError = class extends Error {
2188
+ constructor(cause) {
2189
+ super("Tlon firehose event is too deeply nested to store.", { cause });
2190
+ this.name = "TlonIngressUnserializableEventError";
2191
+ }
2192
+ };
2193
+ function serializeTlonIngressEvent(event) {
2194
+ try {
2195
+ return JSON.stringify(event);
2196
+ } catch (error) {
2197
+ if (error instanceof RangeError) throw new TlonIngressUnserializableEventError(error);
2198
+ throw error;
2199
+ }
2200
+ }
2033
2201
  function inspectChannelsEvent(event) {
2034
2202
  const envelope = asNullableRecord(event);
2035
2203
  const nest = normalizeNullableString(envelope?.nest);
@@ -2107,7 +2275,7 @@ function createTlonIngressMonitor(options) {
2107
2275
  serialize: (raw, { receivedAt }) => ({
2108
2276
  receivedAt,
2109
2277
  source: raw.source,
2110
- rawEvent: JSON.stringify(raw.event)
2278
+ rawEvent: serializeTlonIngressEvent(raw.event)
2111
2279
  }),
2112
2280
  deserialize: (body, { claim }) => deserializeTlonIngressEvent(body, claim.id),
2113
2281
  encode: ({ body }) => ({
@@ -2136,22 +2304,32 @@ function createTlonIngressMonitor(options) {
2136
2304
  });
2137
2305
  return {
2138
2306
  receive: async ({ source, event }) => {
2139
- return { kind: (await monitor.admit({
2140
- source,
2141
- event
2142
- })).kind === "durable" ? "accepted" : "ignored" };
2307
+ try {
2308
+ return { kind: (await monitor.admit({
2309
+ source,
2310
+ event
2311
+ })).kind === "durable" ? "accepted" : "ignored" };
2312
+ } catch (error) {
2313
+ if (error instanceof TlonIngressUnserializableEventError) {
2314
+ options.runtime.log?.(`tlon dropped ${source} event: ${error.message}`);
2315
+ return { kind: "dropped" };
2316
+ }
2317
+ throw error;
2318
+ }
2143
2319
  },
2144
2320
  start: monitor.start,
2145
2321
  stop: monitor.stop,
2146
2322
  waitForIdle: monitor.waitForIdle
2147
2323
  };
2148
2324
  }
2149
- // extensions/tlon/src/media-fetch-timeouts.ts
2325
+ //#endregion
2326
+ //#region extensions/tlon/src/media-fetch-timeouts.ts
2150
2327
  const TLON_MEDIA_FETCH_TIMEOUTS = {
2151
2328
  responseHeaderTimeoutMs: 12e4,
2152
2329
  readIdleTimeoutMs: 3e4
2153
2330
  };
2154
- // extensions/tlon/src/monitor/media.ts
2331
+ //#endregion
2332
+ //#region extensions/tlon/src/monitor/media.ts
2155
2333
  const MAX_IMAGES_PER_MESSAGE = 8;
2156
2334
  /** Keeps Tlon's shipped path-duplicating prompt bytes paired with ordered facts. */
2157
2335
  function buildTlonInboundMediaPrompt(messageText, attachments) {
@@ -2221,7 +2399,8 @@ async function downloadMessageImages(content, maxBytes) {
2221
2399
  unavailableCount
2222
2400
  };
2223
2401
  }
2224
- // src/channels/mention-gating.ts
2402
+ //#endregion
2403
+ //#region src/channels/mention-gating.ts
2225
2404
  function resolveBotThreadMentionPolicy(params) {
2226
2405
  if (!params.isBotOwnedThread || params.requireMentionInBotThreads === void 0) return {
2227
2406
  requireMention: params.requireMention,
@@ -2232,11 +2411,13 @@ function resolveBotThreadMentionPolicy(params) {
2232
2411
  implicitMentionKinds: params.requireMentionInBotThreads ? params.implicitMentionKinds?.filter((kind) => kind === "native") : params.implicitMentionKinds
2233
2412
  };
2234
2413
  }
2235
- // \0openclaw:bundled-sdk:openclaw/plugin-sdk/channel-mention-gating
2414
+ //#endregion
2415
+ //#region \0openclaw:bundled-sdk:openclaw/plugin-sdk/channel-mention-gating
2236
2416
  var channel_mention_gating_exports = /* @__PURE__ */ __exportAll({ resolveBotThreadMentionPolicy: () => resolveBotThreadMentionPolicy });
2237
2417
  import * as import_openclaw_plugin_sdk_channel_mention_gating from "openclaw/plugin-sdk/channel-mention-gating";
2238
2418
  __reExport(channel_mention_gating_exports, import_openclaw_plugin_sdk_channel_mention_gating);
2239
- // extensions/tlon/src/monitor/mentions.ts
2419
+ //#endregion
2420
+ //#region extensions/tlon/src/monitor/mentions.ts
2240
2421
  function resolveTlonGroupMentionDecision(params) {
2241
2422
  const implicitMentions = resolveChannelImplicitMentions({
2242
2423
  cfg: params.cfg,
@@ -2300,10 +2481,14 @@ async function prepareTlonGroupAdmission(params) {
2300
2481
  }
2301
2482
  };
2302
2483
  }
2303
- // extensions/tlon/src/monitor/settings-helpers.ts
2484
+ //#endregion
2485
+ //#region extensions/tlon/src/monitor/settings-helpers.ts
2304
2486
  function buildTlonSettingsMigrations(account, currentSettings) {
2487
+ const configuredClubRules = Object.keys(account.clubRules).length > 0 ? JSON.stringify(account.clubRules) : void 0;
2305
2488
  return [...[
2306
2489
  "dmAllowlist",
2490
+ "clubPolicy",
2491
+ "clubRules",
2307
2492
  "groupInviteAllowlist",
2308
2493
  "groupChannels",
2309
2494
  "defaultAuthorizedShips",
@@ -2312,7 +2497,7 @@ function buildTlonSettingsMigrations(account, currentSettings) {
2312
2497
  "autoAcceptGroupInvites"
2313
2498
  ].map((key) => ({
2314
2499
  key,
2315
- fileValue: account[key],
2500
+ fileValue: key === "clubRules" ? configuredClubRules : account[key],
2316
2501
  settingsValue: currentSettings[key]
2317
2502
  })), {
2318
2503
  key: "showModelSig",
@@ -2341,10 +2526,13 @@ function applyTlonSettingsOverrides(params) {
2341
2526
  if (settings.pendingApprovals?.length) log?.(`[tlon] Loaded ${settings.pendingApprovals.length} pending approval(s) from settings`);
2342
2527
  return {
2343
2528
  effectiveDmAllowlist: settings.dmAllowlist ?? account.dmAllowlist,
2529
+ effectiveClubPolicy: settings.clubPolicy ?? account.clubPolicy ?? "approve-once",
2530
+ effectiveClubRules: settings.clubRules ?? account.clubRules,
2344
2531
  effectiveShowModelSig: settings.showModelSig ?? account.showModelSignature ?? false,
2345
2532
  effectiveAutoAcceptDmInvites: settings.autoAcceptDmInvites ?? account.autoAcceptDmInvites ?? false,
2346
2533
  effectiveAutoAcceptGroupInvites: settings.autoAcceptGroupInvites ?? account.autoAcceptGroupInvites ?? false,
2347
2534
  effectiveGroupInviteAllowlist: settings.groupInviteAllowlist ?? account.groupInviteAllowlist,
2535
+ explicitChannels: mergeUniqueStrings(account.groupChannels, settings.groupChannels),
2348
2536
  effectiveAutoDiscoverChannels: settings.autoDiscoverChannels ?? account.autoDiscoverChannels ?? false,
2349
2537
  effectiveOwnerShip,
2350
2538
  pendingApprovals: settings.pendingApprovals?.length ? settings.pendingApprovals : [],
@@ -2354,7 +2542,25 @@ function applyTlonSettingsOverrides(params) {
2354
2542
  function mergeUniqueStrings(base, next) {
2355
2543
  return uniqueStrings([...base, ...next ?? []]);
2356
2544
  }
2357
- // extensions/tlon/src/monitor/tracking.ts
2545
+ function createTlonSettingsInstaller(state, account, log) {
2546
+ return (currentSettings, preserveApprovalState = false) => {
2547
+ const pendingApprovals = state.pendingApprovals;
2548
+ const effectiveDmAllowlist = state.effectiveDmAllowlist;
2549
+ const effectiveClubRules = state.effectiveClubRules;
2550
+ Object.assign(state, applyTlonSettingsOverrides({
2551
+ account,
2552
+ currentSettings,
2553
+ log
2554
+ }));
2555
+ if (preserveApprovalState) {
2556
+ state.pendingApprovals = pendingApprovals;
2557
+ state.effectiveDmAllowlist = effectiveDmAllowlist;
2558
+ state.effectiveClubRules = effectiveClubRules;
2559
+ }
2560
+ };
2561
+ }
2562
+ //#endregion
2563
+ //#region extensions/tlon/src/monitor/tracking.ts
2358
2564
  const TLON_PARTICIPATED_THREAD_LIMIT = 2e3;
2359
2565
  function createParticipatedThreadTracker(limit = TLON_PARTICIPATED_THREAD_LIMIT) {
2360
2566
  const cache = createDedupeCache({
@@ -2385,7 +2591,8 @@ function createActiveSnapshotTracker() {
2385
2591
  addIfAccepted: (key, accepted) => accepted && processed.add(key)
2386
2592
  };
2387
2593
  }
2388
- // extensions/tlon/src/monitor/index.ts
2594
+ //#endregion
2595
+ //#region extensions/tlon/src/monitor/index.ts
2389
2596
  /** Identity for an unverified group DM (club) author claim; never matches a bare ship. */
2390
2597
  function clubSenderId(clubId, claimedShip) {
2391
2598
  return `club:${clubId}:${claimedShip}`;
@@ -2453,6 +2660,7 @@ async function monitorTlonProvider(opts) {
2453
2660
  account,
2454
2661
  currentSettings: {}
2455
2662
  });
2663
+ const installSettings = createTlonSettingsInstaller(settingsState, account, (message) => runtime.log?.(message));
2456
2664
  const participatedThreads = createParticipatedThreadTracker();
2457
2665
  const channelHistory = createChannelHistoryCache();
2458
2666
  const dmSendersBySession = /* @__PURE__ */ new Map();
@@ -2476,14 +2684,11 @@ async function monitorTlonProvider(opts) {
2476
2684
  } catch (err) {
2477
2685
  runtime.log?.(`[tlon] Failed to migrate ${key}: ${String(err)}`);
2478
2686
  }
2479
- Object.assign(settingsState, applyTlonSettingsOverrides({
2480
- account,
2481
- currentSettings: settingsState.currentSettings,
2482
- log: (message) => runtime.log?.(message)
2483
- }));
2687
+ installSettings(settingsState.currentSettings);
2484
2688
  } catch (err) {
2485
2689
  runtime.log?.(`[tlon] Settings store not available, using file config: ${String(err)}`);
2486
2690
  }
2691
+ runtime.log?.("[tlon] Group DMs require club enablement; dmAllowlist applies only to verified 1:1 DMs. Approve an enablement request or configure clubRules.");
2487
2692
  if (settingsState.effectiveAutoDiscoverChannels) try {
2488
2693
  const initData = await fetchInitData(api, runtime);
2489
2694
  if (initData.channels.length > 0) groupChannels = initData.channels;
@@ -2502,17 +2707,13 @@ async function monitorTlonProvider(opts) {
2502
2707
  if (!settingsState.effectiveOwnerShip) return false;
2503
2708
  return normalizeShip(ship) === settingsState.effectiveOwnerShip;
2504
2709
  }
2505
- /** DM ingress allowlist for one chat event; club claims only match as their club-scoped id. */
2506
- function resolveChatAllowFrom(params) {
2507
- if (params.ownerDm) return [params.senderShip];
2508
- if (!params.isClubMessage) return settingsState.effectiveDmAllowlist;
2509
- return settingsState.effectiveDmAllowlist.some((ship) => normalizeShip(ship) === params.senderShip) ? [params.senderId] : [];
2510
- }
2511
2710
  const processMessage = async (params) => {
2512
2711
  const { messageId, senderShip, isGroup, channelNest, timestamp, parentId, isThreadReply, isAdmissionAllowed, messageContent, turnAdoptionLifecycle, resolveChannelIngress } = params;
2513
2712
  let messageText = params.messageText;
2514
2713
  const clubId = params.clubId;
2515
2714
  const senderId = clubId === void 0 ? senderShip : clubSenderId(clubId, senderShip);
2715
+ const groupConversation = isGroup || clubId !== void 0;
2716
+ const conversationId = isGroup ? channelNest ?? senderShip : clubId !== void 0 ? `club:${clubId}` : senderShip;
2516
2717
  let attachments = [];
2517
2718
  let unavailableMediaCount = 0;
2518
2719
  if (messageContent) try {
@@ -2566,8 +2767,8 @@ async function monitorTlonProvider(opts) {
2566
2767
  channel: "tlon",
2567
2768
  accountId: opts.accountId ?? void 0,
2568
2769
  peer: {
2569
- kind: isGroup ? "group" : "direct",
2570
- id: isGroup ? channelNest ?? senderShip : senderShip
2770
+ kind: groupConversation ? "group" : "direct",
2771
+ id: conversationId
2571
2772
  }
2572
2773
  });
2573
2774
  const channelIngress = await resolveChannelIngress({
@@ -2580,7 +2781,7 @@ async function monitorTlonProvider(opts) {
2580
2781
  runtime.log?.(`[tlon] Authorization changed before dispatch for ${senderShip}`);
2581
2782
  return;
2582
2783
  }
2583
- if (!isGroup) {
2784
+ if (!groupConversation) {
2584
2785
  const sessionKey = route.sessionKey;
2585
2786
  if (!dmSendersBySession.has(sessionKey)) dmSendersBySession.set(sessionKey, /* @__PURE__ */ new Set());
2586
2787
  const senders = dmSendersBySession.get(sessionKey);
@@ -2602,7 +2803,7 @@ async function monitorTlonProvider(opts) {
2602
2803
  const fromLabel = isGroup ? `${senderShip} [${senderRole}] in ${channelNest}` : clubId !== void 0 ? `${senderShip} (unverified) [${senderRole}] in group DM ${clubId}` : `${senderShip} [${senderRole}]`;
2603
2804
  const shouldComputeAuth = core.channel.commands.shouldComputeCommandAuthorized(messageText, cfg);
2604
2805
  let commandAuthorized = false;
2605
- if (shouldComputeAuth) {
2806
+ if (shouldComputeAuth && clubId === void 0) {
2606
2807
  commandAuthorized = (await resolveTlonCommandAuthorizationWithIngress({
2607
2808
  senderShip: senderId,
2608
2809
  ownerShip: settingsState.effectiveOwnerShip
@@ -2624,21 +2825,20 @@ async function monitorTlonProvider(opts) {
2624
2825
  body: commandBody,
2625
2826
  notice: `[tlon ${unavailableMediaCount > 1 ? `${unavailableMediaCount} attachments` : "attachment"} unavailable]`
2626
2827
  }) : commandBody;
2627
- const tlonConversationId = isGroup ? channelNest ?? senderShip : senderShip;
2628
2828
  const ctxPayload = core.channel.inbound.buildContext({
2629
2829
  channel: "tlon",
2630
2830
  accountId: route.accountId,
2631
2831
  messageId,
2632
2832
  timestamp,
2633
- from: isGroup ? `tlon:group:${channelNest}` : `tlon:${senderId}`,
2833
+ from: isGroup ? `tlon:group:${channelNest}` : clubId !== void 0 ? `tlon:club:${clubId}` : `tlon:${senderId}`,
2634
2834
  sender: {
2635
2835
  id: senderId,
2636
2836
  name: clubId === void 0 ? senderShip : senderId,
2637
2837
  roles: [senderRole]
2638
2838
  },
2639
2839
  conversation: {
2640
- kind: isGroup ? "group" : "direct",
2641
- id: tlonConversationId,
2840
+ kind: groupConversation ? "group" : "direct",
2841
+ id: conversationId,
2642
2842
  label: fromLabel
2643
2843
  },
2644
2844
  route: {
@@ -2649,7 +2849,7 @@ async function monitorTlonProvider(opts) {
2649
2849
  },
2650
2850
  reply: {
2651
2851
  to: `tlon:${botShipName}`,
2652
- originatingTo: `tlon:${isGroup ? channelNest : botShipName}`,
2852
+ originatingTo: `tlon:${groupConversation ? conversationId : botShipName}`,
2653
2853
  replyToId: parentId ?? void 0
2654
2854
  },
2655
2855
  message: {
@@ -2665,12 +2865,13 @@ async function monitorTlonProvider(opts) {
2665
2865
  CommandAuthorized: commandAuthorized,
2666
2866
  CommandSource: "text",
2667
2867
  ...attachments.length > 0 && { Attachments: attachments },
2868
+ ...groupConversation && { ReplyThreading: { implicitCurrentMessage: "deny" } },
2668
2869
  ...parentId && { ThreadId: parentId }
2669
2870
  }
2670
2871
  });
2671
2872
  const dispatchStartTime = Date.now();
2672
2873
  const humanDelay = resolveHumanDelayConfig(cfg, route.agentId);
2673
- const deliveryTarget = isGroup ? channelNest : senderShip;
2874
+ const deliveryTarget = conversationId;
2674
2875
  const prepareReplyPayload = (payload) => {
2675
2876
  const replyText = payload.text;
2676
2877
  if (!replyText || !settingsState.effectiveShowModelSig) return payload;
@@ -2720,7 +2921,13 @@ async function monitorTlonProvider(opts) {
2720
2921
  replyToId: parentId ?? void 0
2721
2922
  };
2722
2923
  }
2723
- await sendDm({
2924
+ if (clubId !== void 0) await sendClubMessage({
2925
+ api,
2926
+ fromShip: botShipName,
2927
+ clubId,
2928
+ text: replyText
2929
+ });
2930
+ else await sendDm({
2724
2931
  api,
2725
2932
  fromShip: botShipName,
2726
2933
  toShip: senderShip,
@@ -2747,6 +2954,7 @@ async function monitorTlonProvider(opts) {
2747
2954
  });
2748
2955
  };
2749
2956
  const watchedChannels = new Set(groupChannels);
2957
+ const canExpandCitedNest = (nest) => settingsState.effectiveAutoDiscoverChannels || settingsState.explicitChannels.includes(nest);
2750
2958
  const addWatchedChannels = (channels, logPrefix) => {
2751
2959
  const previousCount = watchedChannels.size;
2752
2960
  for (const channelNest of channels) if (!watchedChannels.has(channelNest)) {
@@ -2763,7 +2971,7 @@ async function monitorTlonProvider(opts) {
2763
2971
  processApprovedMessage: async (approval) => {
2764
2972
  if (!approval.originalMessage || approval.type === "group") return;
2765
2973
  const isGroup = approval.type === "channel";
2766
- const conversationId = isGroup ? approval.channelNest ?? "" : approval.requestingShip;
2974
+ const conversationId = isGroup ? approval.channelNest ?? "" : approval.clubId !== void 0 ? `club:${approval.clubId}` : approval.requestingShip;
2767
2975
  if (isGroup && !conversationId) return;
2768
2976
  const clubId = !isGroup ? approval.clubId : void 0;
2769
2977
  if (!isGroup && clubId === void 0 && approval.verifiedDirect !== true) {
@@ -2788,11 +2996,11 @@ async function monitorTlonProvider(opts) {
2788
2996
  senderShip: replaySenderId,
2789
2997
  accountId: account.accountId,
2790
2998
  conversation: {
2791
- kind: isGroup ? "group" : "direct",
2999
+ kind: isGroup || clubId !== void 0 ? "group" : "direct",
2792
3000
  id: conversationId
2793
3001
  },
2794
3002
  allowFrom: [replaySenderId],
2795
- ...isGroup ? { groupPolicy: "allowlist" } : {},
3003
+ ...isGroup || clubId !== void 0 ? { groupPolicy: "allowlist" } : {},
2796
3004
  contextBinding
2797
3005
  })
2798
3006
  });
@@ -2825,7 +3033,7 @@ async function monitorTlonProvider(opts) {
2825
3033
  if (!messageId) return;
2826
3034
  const senderShip = normalizeShip(readStringField(content, "author") ?? "");
2827
3035
  if (!senderShip || senderShip === botShipName) return;
2828
- const rawText = extractMessageText(content.content);
3036
+ const rawText = extractMessageTextSafely(content.content, runtime);
2829
3037
  if (!rawText.trim()) return;
2830
3038
  const contentBody = content.content;
2831
3039
  const sentAt = asFiniteNumber(content?.sent) ?? Date.now();
@@ -2872,7 +3080,7 @@ async function monitorTlonProvider(opts) {
2872
3080
  } else runtime.log?.(`[tlon] Access denied: ${senderShip} in ${nest} (allowed: ${allowedShips.join(", ")})`);
2873
3081
  return;
2874
3082
  }
2875
- const messageText = await resolveTlonCitations(contentBody, api, runtime) + rawText;
3083
+ const messageText = await resolveTlonCitations(contentBody, canExpandCitedNest, api, runtime) + rawText;
2876
3084
  await processMessage({
2877
3085
  messageId,
2878
3086
  senderShip,
@@ -2954,22 +3162,71 @@ async function monitorTlonProvider(opts) {
2954
3162
  const authorShip = normalizeShip(readStringField(essay, "author") ?? "");
2955
3163
  const partnerShip = extractDmPartnerShip(whom);
2956
3164
  const senderShip = partnerShip || authorShip;
2957
- const clubId = partnerShip ? void 0 : typeof whom === "string" && whom ? whom : "unknown";
2958
- const isClubMessage = clubId !== void 0;
2959
- const senderId = isClubMessage ? clubSenderId(clubId, senderShip) : senderShip;
3165
+ const clubId = partnerShip ? void 0 : typeof whom === "string" && TLON_CLUB_ID_RE.test(whom) ? whom : void 0;
3166
+ if (!partnerShip && clubId === void 0) {
3167
+ runtime.log?.("[tlon] Dropped chat event without a valid DM peer or club ID");
3168
+ return;
3169
+ }
3170
+ const senderId = clubId !== void 0 ? clubSenderId(clubId, senderShip) : senderShip;
2960
3171
  if (authorShip === botShipName) return;
2961
3172
  if (!senderShip || senderShip === botShipName) return;
2962
3173
  if (authorShip && partnerShip && authorShip !== partnerShip) runtime.log?.(`[tlon] DM ship mismatch (author=${authorShip}, partner=${partnerShip}) - routing to partner`);
2963
- const rawText = extractMessageText(essay.content);
3174
+ const rawText = extractMessageTextSafely(essay.content, runtime);
2964
3175
  if (!rawText.trim()) return;
2965
- const messageText = rawText;
2966
- const ownerDm = !isClubMessage && isOwner(senderShip);
2967
- if (ownerDm && await handleApprovalResponse(messageText)) {
2968
- runtime.log?.(`[tlon] Processed approval response from owner: ${messageText}`);
3176
+ if (clubId !== void 0) {
3177
+ const policy = settingsState.effectiveClubPolicy;
3178
+ const rule = settingsState.effectiveClubRules[clubId];
3179
+ if (policy === "disabled" || rule === "deny") {
3180
+ runtime.log?.(`[tlon] Dropped disabled group DM ${clubId}`);
3181
+ return;
3182
+ }
3183
+ if (policy === "approve-each" || rule !== "allow") {
3184
+ if (settingsState.effectiveOwnerShip) await queueApprovalRequest(createPendingApproval({
3185
+ type: "club",
3186
+ clubId,
3187
+ clubMode: policy === "approve-each" ? "message" : "once",
3188
+ requestingShip: senderShip,
3189
+ messagePreview: rawText,
3190
+ originalMessage: {
3191
+ messageId,
3192
+ messageText: rawText,
3193
+ messageContent: essay.content,
3194
+ timestamp: asFiniteNumber(essay.sent) ?? Date.now()
3195
+ }
3196
+ }));
3197
+ else runtime.log?.(`[tlon] Group DM ${clubId} needs enablement: set channels.tlon.clubRules["${clubId}"] to "allow", or configure ownerShip for approval`);
3198
+ return;
3199
+ }
3200
+ await processMessage({
3201
+ messageId,
3202
+ senderShip,
3203
+ clubId,
3204
+ messageText: await resolveTlonCitations(essay.content, canExpandCitedNest, api, runtime) + rawText,
3205
+ messageContent: essay.content,
3206
+ timestamp: asFiniteNumber(essay.sent) ?? Date.now(),
3207
+ isGroup: false,
3208
+ turnAdoptionLifecycle,
3209
+ resolveChannelIngress: async (contextBinding) => resolveTlonMessageIngress({
3210
+ senderShip: senderId,
3211
+ accountId: account.accountId,
3212
+ conversation: {
3213
+ kind: "group",
3214
+ id: `club:${clubId}`
3215
+ },
3216
+ allowFrom: [],
3217
+ groupPolicy: "open",
3218
+ contextBinding
3219
+ })
3220
+ });
2969
3221
  return;
2970
3222
  }
2971
- if (ownerDm && await handleAdminCommand(messageText)) {
2972
- runtime.log?.(`[tlon] Processed admin command from owner: ${messageText}`);
3223
+ const ownerDm = isOwner(senderShip);
3224
+ if (ownerDm && await handleApprovalResponse(rawText)) {
3225
+ runtime.log?.("[tlon] Processed approval response from owner");
3226
+ return;
3227
+ }
3228
+ if (ownerDm && await handleAdminCommand(rawText)) {
3229
+ runtime.log?.("[tlon] Processed admin command from owner");
2973
3230
  return;
2974
3231
  }
2975
3232
  const resolveChannelIngress = async (contextBinding) => await resolveTlonMessageIngress({
@@ -2979,12 +3236,7 @@ async function monitorTlonProvider(opts) {
2979
3236
  kind: "direct",
2980
3237
  id: senderShip
2981
3238
  },
2982
- allowFrom: resolveChatAllowFrom({
2983
- ownerDm,
2984
- isClubMessage,
2985
- senderShip,
2986
- senderId
2987
- }),
3239
+ allowFrom: ownerDm ? [senderShip] : settingsState.effectiveDmAllowlist,
2988
3240
  contextBinding
2989
3241
  });
2990
3242
  if (!ownerDm && !(await resolveChannelIngress()).senderAccess.allowed) {
@@ -2992,20 +3244,21 @@ async function monitorTlonProvider(opts) {
2992
3244
  const approval = createPendingApproval({
2993
3245
  type: "dm",
2994
3246
  requestingShip: senderShip,
2995
- messagePreview: sliceUtf16Safe(messageText, 0, 100),
2996
- ...isClubMessage ? { clubId } : { verifiedDirect: true },
2997
- ...isClubMessage && isOwner(senderShip) ? {} : { originalMessage: {
3247
+ messagePreview: rawText,
3248
+ verifiedDirect: true,
3249
+ originalMessage: {
2998
3250
  messageId,
2999
- messageText,
3251
+ messageText: rawText,
3000
3252
  messageContent: essay.content,
3001
- timestamp: asFiniteNumber(essay?.sent) ?? Date.now()
3002
- } }
3253
+ timestamp: asFiniteNumber(essay.sent) ?? Date.now()
3254
+ }
3003
3255
  });
3004
3256
  await queueApprovalRequest(approval);
3005
3257
  } else runtime.log?.(`[tlon] Blocked DM from ${senderShip}: not in allowlist`);
3006
3258
  return;
3007
3259
  }
3008
- const resolvedMessageText = await resolveTlonCitations(essay.content, api, runtime) + rawText;
3260
+ const canExpandDmCitedNest = (nest) => isOwner(senderShip) || canExpandCitedNest(nest);
3261
+ const resolvedMessageText = await resolveTlonCitations(essay.content, canExpandDmCitedNest, api, runtime) + rawText;
3009
3262
  if (ownerDm) runtime.log?.(`[tlon] Processing DM from owner ${senderShip}`);
3010
3263
  await processMessage({
3011
3264
  messageText: resolvedMessageText,
@@ -3100,11 +3353,7 @@ async function monitorTlonProvider(opts) {
3100
3353
  await settingsManager.startSubscription((newSettings) => {
3101
3354
  settingsState.currentSettings = newSettings;
3102
3355
  addWatchedChannels(newSettings.groupChannels ?? [], "[tlon] Settings: now watching channel ");
3103
- Object.assign(settingsState, applyTlonSettingsOverrides({
3104
- account,
3105
- currentSettings: newSettings,
3106
- log: (message) => runtime.log?.(message)
3107
- }));
3356
+ installSettings(newSettings);
3108
3357
  });
3109
3358
  } catch (err) {
3110
3359
  runtime.log?.(`[tlon] Settings subscription not available: ${String(err)}`);
@@ -3122,15 +3371,16 @@ async function monitorTlonProvider(opts) {
3122
3371
  const discoveredChannels = mergeUniqueStrings(Object.keys(asNullableRecord(eventRecord.channels) ?? {}), joinedChannels.filter((channel) => typeof channel === "string")).filter((channel) => channel.startsWith("chat/"));
3123
3372
  addWatchedChannels(discoveredChannels, "[tlon] Auto-detected new channel: ");
3124
3373
  if (!settingsState.effectiveAutoAcceptGroupInvites) return;
3125
- const currentChannels = settingsState.currentSettings.groupChannels ?? [];
3374
+ const settingsSnapshot = settingsState.currentSettings;
3375
+ const currentChannels = settingsSnapshot.groupChannels ?? [];
3126
3376
  const unpersistedChannels = discoveredChannels.filter((channel) => !currentChannels.includes(channel));
3127
3377
  if (unpersistedChannels.length === 0) return;
3128
3378
  const updatedChannels = mergeUniqueStrings(currentChannels, unpersistedChannels);
3129
3379
  await putTlonSetting(api, "groupChannels", updatedChannels);
3130
- settingsState.currentSettings = {
3131
- ...settingsState.currentSettings,
3380
+ if (settingsState.currentSettings === settingsSnapshot) installSettings({
3381
+ ...settingsSnapshot,
3132
3382
  groupChannels: updatedChannels
3133
- };
3383
+ }, true);
3134
3384
  runtime.log?.(`[tlon] Persisted ${unpersistedChannels.join(", ")} to settings store`);
3135
3385
  } catch (error) {
3136
3386
  runtime.error?.(`[tlon] Error handling groups-ui event: ${formatErrorMessage(error)}`);
@@ -3264,7 +3514,8 @@ async function monitorTlonProvider(opts) {
3264
3514
  }
3265
3515
  }
3266
3516
  }
3267
- // extensions/tlon/src/tlon-api.ts
3517
+ //#endregion
3518
+ //#region extensions/tlon/src/tlon-api.ts
3268
3519
  const MEMEX_BASE_URL = "https://memex.tlon.network";
3269
3520
  /** Max bytes to read from the Memex upload JSON response. */
3270
3521
  const MEMEX_UPLOAD_RESPONSE_MAX_BYTES = 65536;
@@ -3470,7 +3721,8 @@ async function uploadFile(params, clientConfig) {
3470
3721
  await uploadBlob(signedUrl, signedUrl.includes("digitaloceanspaces.com") ? headers : void 0);
3471
3722
  return { url: assertSafeUploadResultUrl(storageConfig.publicUrlBase ? new URL(fileKey, storageConfig.publicUrlBase).toString() : expectDefined(signedUrl.split("?").at(0), "signed URL base segment"), "Upload result URL") };
3472
3723
  }
3473
- // extensions/tlon/src/urbit/upload.ts
3724
+ //#endregion
3725
+ //#region extensions/tlon/src/urbit/upload.ts
3474
3726
  /**
3475
3727
  * Fetch an image from a URL and upload it to Tlon storage.
3476
3728
  * Falls back to the original URL on error, but only after a bounded download when a cap is set.
@@ -3516,7 +3768,8 @@ async function uploadImageFromUrl(imageUrl, clientConfig, maxBytes) {
3516
3768
  return imageUrl;
3517
3769
  }
3518
3770
  }
3519
- // extensions/tlon/src/channel.runtime.ts
3771
+ //#endregion
3772
+ //#region extensions/tlon/src/channel.runtime.ts
3520
3773
  async function createHttpPokeApi(params) {
3521
3774
  const ssrfPolicy = ssrfPolicyFromDangerouslyAllowPrivateNetwork(params.dangerouslyAllowPrivateNetwork);
3522
3775
  const cookie = await authenticate(params.url, params.code, {
@@ -3614,6 +3867,13 @@ async function sendTlonOutbound(params, kind) {
3614
3867
  story,
3615
3868
  kind
3616
3869
  });
3870
+ if (parsed.kind === "club") return await sendClubMessageWithStory({
3871
+ api,
3872
+ fromShip,
3873
+ clubId: parsed.clubId,
3874
+ story,
3875
+ kind
3876
+ });
3617
3877
  return await sendGroupMessageWithStory({
3618
3878
  api,
3619
3879
  fromShip,
@@ -3672,4 +3932,5 @@ async function startTlonGatewayAccount(ctx) {
3672
3932
  accountId: account.accountId
3673
3933
  });
3674
3934
  }
3935
+ //#endregion
3675
3936
  export { probeTlonAccount, startTlonGatewayAccount, tlonRuntimeOutbound, tlonSetupWizard };