@openclaw/tlon 2026.2.21 → 2026.5.2-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/api.ts +16 -0
  2. package/channel-plugin-api.ts +1 -0
  3. package/doctor-contract-api.ts +1 -0
  4. package/index.ts +177 -11
  5. package/openclaw.plugin.json +194 -1
  6. package/package.json +57 -4
  7. package/runtime-api.ts +17 -0
  8. package/setup-api.ts +2 -0
  9. package/setup-entry.ts +9 -0
  10. package/src/account-fields.ts +9 -3
  11. package/src/channel.runtime.ts +248 -0
  12. package/src/channel.ts +153 -364
  13. package/src/config-schema.ts +22 -16
  14. package/src/core.test.ts +278 -0
  15. package/src/doctor-contract.ts +9 -0
  16. package/src/doctor.test.ts +40 -0
  17. package/src/doctor.ts +10 -0
  18. package/src/logger-runtime.ts +1 -0
  19. package/src/monitor/approval-runtime.ts +363 -0
  20. package/src/monitor/approval.test.ts +33 -0
  21. package/src/monitor/approval.ts +286 -0
  22. package/src/monitor/authorization.ts +30 -0
  23. package/src/monitor/cites.ts +54 -0
  24. package/src/monitor/discovery.ts +44 -54
  25. package/src/monitor/history.ts +155 -21
  26. package/src/monitor/index.ts +1290 -369
  27. package/src/monitor/media.test.ts +91 -0
  28. package/src/monitor/media.ts +172 -0
  29. package/src/monitor/processed-messages.test.ts +36 -1
  30. package/src/monitor/processed-messages.ts +62 -19
  31. package/src/monitor/settings-helpers.test.ts +113 -0
  32. package/src/monitor/settings-helpers.ts +158 -0
  33. package/src/monitor/utils.ts +311 -45
  34. package/src/runtime.ts +8 -13
  35. package/src/security.test.ts +622 -0
  36. package/src/session-route.ts +40 -0
  37. package/src/settings.ts +391 -0
  38. package/src/setup-core.ts +228 -0
  39. package/src/setup-surface.ts +103 -0
  40. package/src/targets.ts +29 -16
  41. package/src/tlon-api.test.ts +589 -0
  42. package/src/tlon-api.ts +402 -0
  43. package/src/types.ts +106 -45
  44. package/src/urbit/auth.ssrf.test.ts +3 -2
  45. package/src/urbit/auth.ts +2 -2
  46. package/src/urbit/base-url.test.ts +18 -11
  47. package/src/urbit/base-url.ts +9 -5
  48. package/src/urbit/channel-ops.ts +40 -59
  49. package/src/urbit/context.ts +13 -10
  50. package/src/urbit/errors.ts +2 -2
  51. package/src/urbit/fetch.ts +6 -3
  52. package/src/urbit/foreigns.ts +49 -0
  53. package/src/urbit/send.ts +53 -8
  54. package/src/urbit/sse-client.test.ts +184 -25
  55. package/src/urbit/sse-client.ts +123 -69
  56. package/src/urbit/story.ts +332 -0
  57. package/src/urbit/upload.test.ts +154 -0
  58. package/src/urbit/upload.ts +60 -0
  59. package/test-api.ts +1 -0
  60. package/tsconfig.json +16 -0
  61. package/src/config-schema.test.ts +0 -31
  62. package/src/onboarding.ts +0 -229
  63. package/src/urbit/channel-client.ts +0 -157
@@ -1,105 +1,74 @@
1
- import { format } from "node:util";
2
- import type { RuntimeEnv, ReplyPayload, OpenClawConfig } from "openclaw/plugin-sdk";
3
- import { createReplyPrefixOptions } from "openclaw/plugin-sdk";
1
+ import type { ReplyPayload } from "openclaw/plugin-sdk/reply-runtime";
2
+ import type { RuntimeEnv } from "openclaw/plugin-sdk/runtime";
3
+ import type { OpenClawConfig } from "../../runtime-api.js";
4
+ import { createLoggerBackedRuntime } from "../../runtime-api.js";
4
5
  import { getTlonRuntime } from "../runtime.js";
6
+ import { createSettingsManager, type TlonSettingsStore } from "../settings.js";
5
7
  import { normalizeShip, parseChannelNest } from "../targets.js";
6
8
  import { resolveTlonAccount } from "../types.js";
7
9
  import { authenticate } from "../urbit/auth.js";
8
- import { ssrfPolicyFromAllowPrivateNetwork } from "../urbit/context.js";
10
+ import { ssrfPolicyFromDangerouslyAllowPrivateNetwork } from "../urbit/context.js";
11
+ import type { DmInvite, Foreigns } from "../urbit/foreigns.js";
9
12
  import { sendDm, sendGroupMessage } from "../urbit/send.js";
10
13
  import { UrbitSSEClient } from "../urbit/sse-client.js";
11
- import { fetchAllChannels } from "./discovery.js";
12
- import { cacheMessage, getChannelHistory } from "./history.js";
13
- import { createProcessedMessageTracker } from "./processed-messages.js";
14
+ import { createTlonApprovalRuntime } from "./approval-runtime.js";
15
+ import {
16
+ createPendingApproval,
17
+ isAdminCommand,
18
+ isApprovalResponse,
19
+ type PendingApproval,
20
+ } from "./approval.js";
21
+ import { resolveChannelAuthorization } from "./authorization.js";
22
+ import { createTlonCitationResolver } from "./cites.js";
23
+ import { fetchAllChannels, fetchInitData } from "./discovery.js";
24
+ import { cacheMessage, fetchThreadHistory, getChannelHistory } from "./history.js";
25
+ import { downloadMessageImages } from "./media.js";
26
+ import {
27
+ createProcessedMessageTracker,
28
+ runWithProcessedMessageClaim,
29
+ } from "./processed-messages.js";
30
+ import {
31
+ applyTlonSettingsOverrides,
32
+ buildTlonSettingsMigrations,
33
+ mergeUniqueStrings,
34
+ shouldMigrateTlonSetting,
35
+ } from "./settings-helpers.js";
36
+ import { asRecord, formatErrorMessage, readString } from "./utils.js";
14
37
  import {
15
38
  extractMessageText,
16
39
  formatModelName,
17
40
  isBotMentioned,
18
41
  isDmAllowed,
42
+ isGroupInviteAllowed,
19
43
  isSummarizationRequest,
44
+ resolveAuthorizedMessageText,
45
+ stripBotMention,
20
46
  } from "./utils.js";
21
47
 
22
- function formatError(err: unknown): string {
23
- if (err instanceof Error) return err.message;
24
- return String(err);
25
- }
26
-
27
- export type MonitorTlonOpts = {
48
+ type MonitorTlonOpts = {
28
49
  runtime?: RuntimeEnv;
29
50
  abortSignal?: AbortSignal;
30
51
  accountId?: string | null;
31
52
  };
32
53
 
33
- type ChannelAuthorization = {
34
- mode?: "restricted" | "open";
35
- allowedShips?: string[];
36
- };
37
-
38
- type UrbitMemo = {
39
- author?: string;
40
- content?: unknown;
41
- sent?: number;
42
- };
43
-
44
- type UrbitSeal = {
45
- "parent-id"?: string;
46
- parent?: string;
47
- };
48
-
49
- type UrbitUpdate = {
50
- id?: string | number;
51
- response?: {
52
- add?: { memo?: UrbitMemo };
53
- post?: {
54
- id?: string | number;
55
- "r-post"?: {
56
- set?: { essay?: UrbitMemo; seal?: UrbitSeal };
57
- reply?: {
58
- id?: string | number;
59
- "r-reply"?: { set?: { memo?: UrbitMemo; seal?: UrbitSeal } };
60
- };
61
- };
62
- };
63
- };
64
- };
65
-
66
- function resolveChannelAuthorization(
67
- cfg: OpenClawConfig,
68
- channelNest: string,
69
- ): { mode: "restricted" | "open"; allowedShips: string[] } {
70
- const tlonConfig = cfg.channels?.tlon as
71
- | {
72
- authorization?: { channelRules?: Record<string, ChannelAuthorization> };
73
- defaultAuthorizedShips?: string[];
74
- }
75
- | undefined;
76
- const rules = tlonConfig?.authorization?.channelRules ?? {};
77
- const rule = rules[channelNest];
78
- const allowedShips = rule?.allowedShips ?? tlonConfig?.defaultAuthorizedShips ?? [];
79
- const mode = rule?.mode ?? "restricted";
80
- return { mode, allowedShips };
54
+ function readNumber(record: Record<string, unknown> | null, key: string): number | undefined {
55
+ const value = record?.[key];
56
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
81
57
  }
82
58
 
83
59
  export async function monitorTlonProvider(opts: MonitorTlonOpts = {}): Promise<void> {
84
60
  const core = getTlonRuntime();
85
- const cfg = core.config.loadConfig();
61
+ const cfg = core.config.current() as OpenClawConfig;
86
62
  if (cfg.channels?.tlon?.enabled === false) {
87
63
  return;
88
64
  }
89
65
 
90
66
  const logger = core.logging.getChildLogger({ module: "tlon-auto-reply" });
91
- const formatRuntimeMessage = (...args: Parameters<RuntimeEnv["log"]>) => format(...args);
92
- const runtime: RuntimeEnv = opts.runtime ?? {
93
- log: (...args) => {
94
- logger.info(formatRuntimeMessage(...args));
95
- },
96
- error: (...args) => {
97
- logger.error(formatRuntimeMessage(...args));
98
- },
99
- exit: (code: number): never => {
100
- throw new Error(`exit ${code}`);
101
- },
102
- };
67
+ const runtime: RuntimeEnv =
68
+ opts.runtime ??
69
+ createLoggerBackedRuntime({
70
+ logger,
71
+ });
103
72
 
104
73
  const account = resolveTlonAccount(cfg, opts.accountId ?? undefined);
105
74
  if (!account.enabled) {
@@ -112,187 +81,285 @@ export async function monitorTlonProvider(opts: MonitorTlonOpts = {}): Promise<v
112
81
  const botShipName = normalizeShip(account.ship);
113
82
  runtime.log?.(`[tlon] Starting monitor for ${botShipName}`);
114
83
 
115
- let api: UrbitSSEClient | null = null;
116
- try {
117
- const ssrfPolicy = ssrfPolicyFromAllowPrivateNetwork(account.allowPrivateNetwork);
118
- runtime.log?.(`[tlon] Attempting authentication to ${account.url}...`);
119
- const cookie = await authenticate(account.url, account.code, { ssrfPolicy });
120
- api = new UrbitSSEClient(account.url, cookie, {
121
- ship: botShipName,
122
- ssrfPolicy,
123
- logger: {
124
- log: (message) => runtime.log?.(message),
125
- error: (message) => runtime.error?.(message),
126
- },
127
- });
128
- } catch (error) {
129
- runtime.error?.(`[tlon] Failed to authenticate: ${formatError(error)}`);
130
- throw error;
131
- }
84
+ const ssrfPolicy = ssrfPolicyFromDangerouslyAllowPrivateNetwork(
85
+ account.dangerouslyAllowPrivateNetwork,
86
+ );
132
87
 
133
- const processedTracker = createProcessedMessageTracker(2000);
134
- let groupChannels: string[] = [];
88
+ // Store validated values for use in closures (TypeScript narrowing doesn't propagate)
89
+ const accountUrl = account.url;
90
+ const accountCode = account.code;
135
91
 
136
- if (account.autoDiscoverChannels !== false) {
137
- try {
138
- const discoveredChannels = await fetchAllChannels(api, runtime);
139
- if (discoveredChannels.length > 0) {
140
- groupChannels = discoveredChannels;
92
+ // Helper to authenticate with retry logic
93
+ async function authenticateWithRetry(maxAttempts = 10): Promise<string> {
94
+ for (let attempt = 1; ; attempt++) {
95
+ if (opts.abortSignal?.aborted) {
96
+ throw new Error("Aborted while waiting to authenticate");
97
+ }
98
+ try {
99
+ runtime.log?.(`[tlon] Attempting authentication to ${accountUrl}...`);
100
+ return await authenticate(accountUrl, accountCode, { ssrfPolicy });
101
+ } catch (error: unknown) {
102
+ runtime.error?.(
103
+ `[tlon] Failed to authenticate (attempt ${attempt}): ${formatErrorMessage(error)}`,
104
+ );
105
+ if (attempt >= maxAttempts) {
106
+ throw error;
107
+ }
108
+ const delay = Math.min(30000, 1000 * 2 ** (attempt - 1));
109
+ runtime.log?.(`[tlon] Retrying authentication in ${delay}ms...`);
110
+ await new Promise<void>((resolve, reject) => {
111
+ const timer = setTimeout(resolve, delay);
112
+ if (opts.abortSignal) {
113
+ const onAbort = () => {
114
+ clearTimeout(timer);
115
+ reject(new Error("Aborted"));
116
+ };
117
+ opts.abortSignal.addEventListener("abort", onAbort, { once: true });
118
+ }
119
+ });
141
120
  }
142
- } catch (error) {
143
- runtime.error?.(`[tlon] Auto-discovery failed: ${formatError(error)}`);
144
121
  }
145
122
  }
146
123
 
147
- if (groupChannels.length === 0 && account.groupChannels.length > 0) {
148
- groupChannels = account.groupChannels;
149
- runtime.log?.(`[tlon] Using manual groupChannels config: ${groupChannels.join(", ")}`);
150
- }
124
+ let api: UrbitSSEClient | null = null;
125
+ const cookie = await authenticateWithRetry();
126
+ api = new UrbitSSEClient(account.url, cookie, {
127
+ ship: botShipName,
128
+ ssrfPolicy,
129
+ logger: {
130
+ log: (message) => runtime.log?.(message),
131
+ error: (message) => runtime.error?.(message),
132
+ },
133
+ // Re-authenticate on reconnect in case the session expired
134
+ onReconnect: async (client) => {
135
+ runtime.log?.("[tlon] Re-authenticating on SSE reconnect...");
136
+ const newCookie = await authenticateWithRetry(5);
137
+ client.updateCookie(newCookie);
138
+ runtime.log?.("[tlon] Re-authentication successful");
139
+ },
140
+ });
151
141
 
152
- if (groupChannels.length > 0) {
153
- runtime.log?.(
154
- `[tlon] Monitoring ${groupChannels.length} group channel(s): ${groupChannels.join(", ")}`,
155
- );
156
- } else {
157
- runtime.log?.("[tlon] No group channels to monitor (DMs only)");
158
- }
142
+ const processedTracker = createProcessedMessageTracker(2000);
143
+ let groupChannels: string[] = [];
144
+ let botNickname: string | null = null;
159
145
 
160
- const handleIncomingDM = async (update: UrbitUpdate) => {
161
- try {
162
- const memo = update?.response?.add?.memo;
163
- if (!memo) {
164
- return;
165
- }
146
+ // Settings store manager for hot-reloading config
147
+ const settingsManager = createSettingsManager(api, {
148
+ log: (msg) => runtime.log?.(msg),
149
+ error: (msg) => runtime.error?.(msg),
150
+ });
166
151
 
167
- const messageId = update.id != null ? String(update.id) : undefined;
168
- if (!processedTracker.mark(messageId)) {
169
- return;
170
- }
152
+ // Reactive state that can be updated via settings store
153
+ let effectiveDmAllowlist: string[] = account.dmAllowlist;
154
+ let effectiveShowModelSig: boolean = account.showModelSignature ?? false;
155
+ let effectiveAutoAcceptDmInvites: boolean = account.autoAcceptDmInvites ?? false;
156
+ let effectiveAutoAcceptGroupInvites: boolean = account.autoAcceptGroupInvites ?? false;
157
+ let effectiveGroupInviteAllowlist: string[] = account.groupInviteAllowlist;
158
+ let effectiveAutoDiscoverChannels: boolean = account.autoDiscoverChannels ?? false;
159
+ let effectiveOwnerShip: string | null = account.ownerShip
160
+ ? normalizeShip(account.ownerShip)
161
+ : null;
162
+ let pendingApprovals: PendingApproval[] = [];
163
+ let currentSettings: TlonSettingsStore = {};
171
164
 
172
- const senderShip = normalizeShip(memo.author ?? "");
173
- if (!senderShip || senderShip === botShipName) {
174
- return;
175
- }
165
+ // Track threads we've participated in (by parentId) - respond without mention requirement
166
+ const participatedThreads = new Set<string>();
176
167
 
177
- const messageText = extractMessageText(memo.content);
178
- if (!messageText) {
179
- return;
180
- }
168
+ // Track DM senders per session to detect shared sessions (security warning)
169
+ const dmSendersBySession = new Map<string, Set<string>>();
170
+ let sharedSessionWarningSent = false;
181
171
 
182
- if (!isDmAllowed(senderShip, account.dmAllowlist)) {
183
- runtime.log?.(`[tlon] Blocked DM from ${senderShip}: not in allowlist`);
184
- return;
172
+ // Fetch bot's nickname from contacts
173
+ try {
174
+ const selfProfile = await api.scry("/contacts/v1/self.json");
175
+ if (selfProfile && typeof selfProfile === "object") {
176
+ const profile = selfProfile as { nickname?: { value?: string } };
177
+ botNickname = profile.nickname?.value || null;
178
+ if (botNickname) {
179
+ runtime.log?.(`[tlon] Bot nickname: ${botNickname}`);
185
180
  }
186
-
187
- await processMessage({
188
- messageId: messageId ?? "",
189
- senderShip,
190
- messageText,
191
- isGroup: false,
192
- timestamp: memo.sent || Date.now(),
193
- });
194
- } catch (error) {
195
- runtime.error?.(`[tlon] Error handling DM: ${formatError(error)}`);
196
181
  }
197
- };
182
+ } catch (error: unknown) {
183
+ runtime.log?.(`[tlon] Could not fetch nickname: ${formatErrorMessage(error)}`);
184
+ }
198
185
 
199
- const handleIncomingGroupMessage = (channelNest: string) => async (update: UrbitUpdate) => {
200
- try {
201
- const parsed = parseChannelNest(channelNest);
202
- if (!parsed) {
203
- return;
204
- }
186
+ // Store init foreigns for processing after settings are loaded
187
+ let initForeigns: Foreigns | null = null;
205
188
 
206
- const post = update?.response?.post?.["r-post"];
207
- const essay = post?.set?.essay;
208
- const memo = post?.reply?.["r-reply"]?.set?.memo;
209
- if (!essay && !memo) {
210
- return;
211
- }
189
+ // Migrate file config to settings store (seed on first run)
190
+ async function migrateConfigToSettings() {
191
+ const migrations = buildTlonSettingsMigrations(account, currentSettings);
212
192
 
213
- const content = memo || essay;
214
- if (!content) {
215
- return;
193
+ for (const { key, fileValue, settingsValue } of migrations) {
194
+ if (shouldMigrateTlonSetting(fileValue, settingsValue)) {
195
+ try {
196
+ await api!.poke({
197
+ app: "settings",
198
+ mark: "settings-event",
199
+ json: {
200
+ "put-entry": {
201
+ "bucket-key": "tlon",
202
+ "entry-key": key,
203
+ value: fileValue,
204
+ desk: "moltbot",
205
+ },
206
+ },
207
+ });
208
+ runtime.log?.(`[tlon] Migrated ${key} from config to settings store`);
209
+ } catch (err) {
210
+ runtime.log?.(`[tlon] Failed to migrate ${key}: ${String(err)}`);
211
+ }
216
212
  }
217
- const isThreadReply = Boolean(memo);
218
- const rawMessageId = isThreadReply ? post?.reply?.id : update?.response?.post?.id;
219
- const messageId = rawMessageId != null ? String(rawMessageId) : undefined;
213
+ }
214
+ }
220
215
 
221
- if (!processedTracker.mark(messageId)) {
222
- return;
223
- }
216
+ // Load settings from settings store (hot-reloadable config)
217
+ try {
218
+ currentSettings = await settingsManager.load();
224
219
 
225
- const senderShip = normalizeShip(content.author ?? "");
226
- if (!senderShip || senderShip === botShipName) {
227
- return;
228
- }
220
+ // Migrate file config to settings store if not already present
221
+ await migrateConfigToSettings();
222
+ ({
223
+ effectiveDmAllowlist,
224
+ effectiveShowModelSig,
225
+ effectiveAutoAcceptDmInvites,
226
+ effectiveAutoAcceptGroupInvites,
227
+ effectiveGroupInviteAllowlist,
228
+ effectiveAutoDiscoverChannels,
229
+ effectiveOwnerShip,
230
+ pendingApprovals,
231
+ currentSettings,
232
+ } = applyTlonSettingsOverrides({
233
+ account,
234
+ currentSettings,
235
+ log: (message) => runtime.log?.(message),
236
+ }));
237
+ } catch (err) {
238
+ runtime.log?.(`[tlon] Settings store not available, using file config: ${String(err)}`);
239
+ }
229
240
 
230
- const messageText = extractMessageText(content.content);
231
- if (!messageText) {
232
- return;
241
+ // Run channel discovery AFTER settings are loaded (so settings store value is used)
242
+ if (effectiveAutoDiscoverChannels) {
243
+ try {
244
+ const initData = await fetchInitData(api, runtime);
245
+ if (initData.channels.length > 0) {
246
+ groupChannels = initData.channels;
233
247
  }
248
+ initForeigns = initData.foreigns;
249
+ } catch (error: unknown) {
250
+ runtime.error?.(`[tlon] Auto-discovery failed: ${formatErrorMessage(error)}`);
251
+ }
252
+ }
234
253
 
235
- cacheMessage(channelNest, {
236
- author: senderShip,
237
- content: messageText,
238
- timestamp: content.sent || Date.now(),
239
- id: messageId,
240
- });
254
+ // Merge manual config with auto-discovered channels
255
+ if (account.groupChannels.length > 0) {
256
+ groupChannels = mergeUniqueStrings(groupChannels, account.groupChannels);
257
+ runtime.log?.(
258
+ `[tlon] Added ${account.groupChannels.length} manual groupChannels to monitoring`,
259
+ );
260
+ }
241
261
 
242
- const mentioned = isBotMentioned(messageText, botShipName);
243
- if (!mentioned) {
244
- return;
245
- }
262
+ // Also merge settings store groupChannels (may have been set via tlon settings command)
263
+ groupChannels = mergeUniqueStrings(groupChannels, currentSettings.groupChannels);
246
264
 
247
- const { mode, allowedShips } = resolveChannelAuthorization(cfg, channelNest);
248
- if (mode === "restricted") {
249
- if (allowedShips.length === 0) {
250
- runtime.log?.(`[tlon] Access denied: ${senderShip} in ${channelNest} (no allowlist)`);
251
- return;
252
- }
253
- const normalizedAllowed = allowedShips.map(normalizeShip);
254
- if (!normalizedAllowed.includes(senderShip)) {
255
- runtime.log?.(
256
- `[tlon] Access denied: ${senderShip} in ${channelNest} (allowed: ${allowedShips.join(", ")})`,
257
- );
258
- return;
259
- }
260
- }
265
+ if (groupChannels.length > 0) {
266
+ runtime.log?.(
267
+ `[tlon] Monitoring ${groupChannels.length} group channel(s): ${groupChannels.join(", ")}`,
268
+ );
269
+ } else {
270
+ runtime.log?.("[tlon] No group channels to monitor (DMs only)");
271
+ }
261
272
 
262
- const seal = isThreadReply
263
- ? update?.response?.post?.["r-post"]?.reply?.["r-reply"]?.set?.seal
264
- : update?.response?.post?.["r-post"]?.set?.seal;
265
-
266
- const parentId = seal?.["parent-id"] || seal?.parent || null;
267
-
268
- await processMessage({
269
- messageId: messageId ?? "",
270
- senderShip,
271
- messageText,
272
- isGroup: true,
273
- groupChannel: channelNest,
274
- groupName: `${parsed.hostShip}/${parsed.channelName}`,
275
- timestamp: content.sent || Date.now(),
276
- parentId,
277
- });
278
- } catch (error) {
279
- runtime.error?.(`[tlon] Error handling group message: ${formatError(error)}`);
273
+ // Check if a ship is the owner (always allowed to DM)
274
+ function isOwner(ship: string): boolean {
275
+ if (!effectiveOwnerShip) {
276
+ return false;
280
277
  }
281
- };
278
+ return normalizeShip(ship) === effectiveOwnerShip;
279
+ }
280
+
281
+ /**
282
+ * Extract the DM partner ship from the 'whom' field.
283
+ * This is the canonical source for DM routing (more reliable than essay.author).
284
+ * Returns empty string if whom doesn't contain a valid patp-like value.
285
+ */
286
+ function extractDmPartnerShip(whom: unknown): string {
287
+ const raw =
288
+ typeof whom === "string"
289
+ ? whom
290
+ : whom && typeof whom === "object" && "ship" in whom && typeof whom.ship === "string"
291
+ ? whom.ship
292
+ : "";
293
+ const normalized = normalizeShip(raw);
294
+ // Keep DM routing strict: accept only patp-like values.
295
+ return /^~?[a-z-]+$/i.test(normalized) ? normalized : "";
296
+ }
282
297
 
283
298
  const processMessage = async (params: {
284
299
  messageId: string;
285
300
  senderShip: string;
286
301
  messageText: string;
302
+ messageContent?: unknown; // Raw Tlon content for media extraction
287
303
  isGroup: boolean;
288
- groupChannel?: string;
289
- groupName?: string;
304
+ channelNest?: string;
305
+ hostShip?: string;
306
+ channelName?: string;
290
307
  timestamp: number;
291
308
  parentId?: string | null;
309
+ isThreadReply?: boolean;
292
310
  }) => {
293
- const { messageId, senderShip, isGroup, groupChannel, groupName, timestamp, parentId } = params;
311
+ const {
312
+ messageId,
313
+ senderShip,
314
+ isGroup,
315
+ channelNest,
316
+ hostShip: _hostShip,
317
+ channelName: _channelName,
318
+ timestamp,
319
+ parentId,
320
+ isThreadReply,
321
+ messageContent,
322
+ } = params;
323
+ const groupChannel = channelNest; // For compatibility
294
324
  let messageText = params.messageText;
295
325
 
326
+ // Download any images from the message content
327
+ let attachments: Array<{ path: string; contentType: string }> = [];
328
+ if (messageContent) {
329
+ try {
330
+ attachments = await downloadMessageImages(messageContent);
331
+ if (attachments.length > 0) {
332
+ runtime.log?.(`[tlon] Downloaded ${attachments.length} image(s) from message`);
333
+ }
334
+ } catch (error: unknown) {
335
+ runtime.log?.(`[tlon] Failed to download images: ${formatErrorMessage(error)}`);
336
+ }
337
+ }
338
+
339
+ // Fetch thread context when entering a thread for the first time
340
+ if (isThreadReply && parentId && groupChannel) {
341
+ try {
342
+ const threadHistory = await fetchThreadHistory(api, groupChannel, parentId, 20, runtime);
343
+ if (threadHistory.length > 0) {
344
+ const threadContext = threadHistory
345
+ .slice(-10) // Last 10 messages for context
346
+ .map((msg) => `${msg.author}: ${msg.content}`)
347
+ .join("\n");
348
+
349
+ // Prepend thread context to the message
350
+ // Include note about ongoing conversation for agent judgment
351
+ const contextNote = `[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.]`;
352
+ messageText = `${contextNote}\n\n[Previous messages]\n${threadContext}\n\n[Current message]\n${messageText}`;
353
+ runtime?.log?.(
354
+ `[tlon] Added thread context (${threadHistory.length} replies) to message`,
355
+ );
356
+ }
357
+ } catch (error: unknown) {
358
+ runtime?.log?.(`[tlon] Could not fetch thread context: ${formatErrorMessage(error)}`);
359
+ // Continue without thread context - not critical
360
+ }
361
+ }
362
+
296
363
  if (isGroup && groupChannel && isSummarizationRequest(messageText)) {
297
364
  try {
298
365
  const history = await getChannelHistory(api, groupChannel, 50, runtime);
@@ -334,8 +401,8 @@ export async function monitorTlonProvider(opts: MonitorTlonOpts = {}): Promise<v
334
401
  "2. Key decisions or conclusions\n" +
335
402
  "3. Action items if any\n" +
336
403
  "4. Notable participants";
337
- } catch (error) {
338
- const errorMsg = `Sorry, I encountered an error while fetching the channel history: ${formatError(error)}`;
404
+ } catch (error: unknown) {
405
+ const errorMsg = `Sorry, I encountered an error while fetching the channel history: ${formatErrorMessage(error)}`;
339
406
  if (isGroup && groupChannel) {
340
407
  const parsed = parseChannelNest(groupChannel);
341
408
  if (parsed) {
@@ -364,215 +431,1069 @@ export async function monitorTlonProvider(opts: MonitorTlonOpts = {}): Promise<v
364
431
  },
365
432
  });
366
433
 
367
- const fromLabel = isGroup ? `${senderShip} in ${groupName}` : senderShip;
434
+ // Warn if multiple users share a DM session (insecure dmScope configuration)
435
+ if (!isGroup) {
436
+ const sessionKey = route.sessionKey;
437
+ if (!dmSendersBySession.has(sessionKey)) {
438
+ dmSendersBySession.set(sessionKey, new Set());
439
+ }
440
+ const senders = dmSendersBySession.get(sessionKey)!;
441
+ if (senders.size > 0 && !senders.has(senderShip)) {
442
+ // Log warning
443
+ runtime.log?.(
444
+ `[tlon] ⚠️ SECURITY: Multiple users sharing DM session. ` +
445
+ `Configure "session.dmScope: per-channel-peer" in OpenClaw config.`,
446
+ );
447
+
448
+ // Notify owner via DM (once per monitor session)
449
+ if (!sharedSessionWarningSent && effectiveOwnerShip) {
450
+ sharedSessionWarningSent = true;
451
+ const warningMsg =
452
+ `⚠️ Security Warning: Multiple users are sharing a DM session with this bot. ` +
453
+ `This can leak conversation context between users.\n\n` +
454
+ `Fix: Add to your OpenClaw config:\n` +
455
+ `session:\n dmScope: "per-channel-peer"\n\n` +
456
+ `Docs: https://docs.openclaw.ai/concepts/session#secure-dm-mode`;
457
+
458
+ // Send async, don't block message processing
459
+ sendDm({
460
+ api,
461
+ fromShip: botShipName,
462
+ toShip: effectiveOwnerShip,
463
+ text: warningMsg,
464
+ }).catch((err) =>
465
+ runtime.error?.(`[tlon] Failed to send security warning to owner: ${err}`),
466
+ );
467
+ }
468
+ }
469
+ senders.add(senderShip);
470
+ }
471
+
472
+ const senderRole = isOwner(senderShip) ? "owner" : "user";
473
+ const fromLabel = isGroup
474
+ ? `${senderShip} [${senderRole}] in ${channelNest}`
475
+ : `${senderShip} [${senderRole}]`;
476
+
477
+ // Compute command authorization for slash commands (owner-only)
478
+ const shouldComputeAuth = core.channel.commands.shouldComputeCommandAuthorized(
479
+ messageText,
480
+ cfg,
481
+ );
482
+ let commandAuthorized = false;
483
+
484
+ if (shouldComputeAuth) {
485
+ const useAccessGroups = cfg.commands?.useAccessGroups !== false;
486
+ const senderIsOwner = isOwner(senderShip);
487
+
488
+ commandAuthorized = core.channel.commands.resolveCommandAuthorizedFromAuthorizers({
489
+ useAccessGroups,
490
+ authorizers: [{ configured: Boolean(effectiveOwnerShip), allowed: senderIsOwner }],
491
+ });
492
+
493
+ // Log when non-owner attempts a slash command (will be silently ignored by Gateway)
494
+ if (!commandAuthorized) {
495
+ console.log(
496
+ `[tlon] Command attempt denied: ${senderShip} is not owner (owner=${effectiveOwnerShip ?? "not configured"})`,
497
+ );
498
+ }
499
+ }
500
+
501
+ // Prepend attachment annotations to message body (similar to Signal format)
502
+ let bodyWithAttachments = messageText;
503
+ if (attachments.length > 0) {
504
+ const mediaLines = attachments
505
+ .map((a) => `[media attached: ${a.path} (${a.contentType}) | ${a.path}]`)
506
+ .join("\n");
507
+ bodyWithAttachments = mediaLines + "\n" + messageText;
508
+ }
509
+
368
510
  const body = core.channel.reply.formatAgentEnvelope({
369
511
  channel: "Tlon",
370
512
  from: fromLabel,
371
513
  timestamp,
372
- body: messageText,
514
+ body: bodyWithAttachments,
373
515
  });
374
516
 
375
- const ctxPayload = core.channel.reply.finalizeInboundContext({
376
- Body: body,
377
- BodyForAgent: messageText,
378
- RawBody: messageText,
379
- CommandBody: messageText,
380
- From: isGroup ? `tlon:group:${groupChannel}` : `tlon:${senderShip}`,
381
- To: `tlon:${botShipName}`,
382
- SessionKey: route.sessionKey,
383
- AccountId: route.accountId,
384
- ChatType: isGroup ? "group" : "direct",
385
- ConversationLabel: fromLabel,
386
- SenderName: senderShip,
387
- SenderId: senderShip,
388
- Provider: "tlon",
389
- Surface: "tlon",
390
- MessageSid: messageId,
391
- OriginatingChannel: "tlon",
392
- OriginatingTo: `tlon:${isGroup ? groupChannel : botShipName}`,
517
+ // Strip bot ship mention for CommandBody so "/status" is recognized as command-only
518
+ const commandBody = isGroup ? stripBotMention(messageText, botShipName) : messageText;
519
+ const tlonConversationId = isGroup ? (groupChannel ?? channelNest ?? senderShip) : senderShip;
520
+ const rawTurnMessage = {
521
+ messageId,
522
+ messageText,
523
+ timestamp,
524
+ };
525
+
526
+ const ctxPayload = core.channel.turn.buildContext({
527
+ channel: "tlon",
528
+ accountId: route.accountId,
529
+ messageId,
530
+ timestamp,
531
+ from: isGroup ? `tlon:group:${groupChannel}` : `tlon:${senderShip}`,
532
+ sender: {
533
+ id: senderShip,
534
+ name: senderShip,
535
+ roles: [senderRole],
536
+ },
537
+ conversation: {
538
+ kind: isGroup ? "group" : "direct",
539
+ id: tlonConversationId,
540
+ label: fromLabel,
541
+ routePeer: {
542
+ kind: isGroup ? "group" : "direct",
543
+ id: tlonConversationId,
544
+ },
545
+ },
546
+ route: {
547
+ agentId: route.agentId,
548
+ accountId: route.accountId,
549
+ routeSessionKey: route.sessionKey,
550
+ },
551
+ reply: {
552
+ to: `tlon:${botShipName}`,
553
+ originatingTo: `tlon:${isGroup ? groupChannel : botShipName}`,
554
+ replyToId: parentId ?? undefined,
555
+ },
556
+ message: {
557
+ body,
558
+ bodyForAgent: commandBody,
559
+ rawBody: messageText,
560
+ commandBody,
561
+ envelopeFrom: fromLabel,
562
+ },
563
+ extra: {
564
+ GroupSubject: undefined,
565
+ SenderRole: senderRole,
566
+ CommandAuthorized: commandAuthorized,
567
+ CommandSource: "text" as const,
568
+ ...(attachments.length > 0 && { Attachments: attachments }),
569
+ ...(parentId && { ThreadId: parentId }),
570
+ },
393
571
  });
394
572
 
395
573
  const dispatchStartTime = Date.now();
396
574
 
397
- const { onModelSelected, ...prefixOptions } = createReplyPrefixOptions({
575
+ const responsePrefix = core.channel.reply.resolveEffectiveMessagesConfig(
398
576
  cfg,
577
+ route.agentId,
578
+ ).responsePrefix;
579
+ const humanDelay = core.channel.reply.resolveHumanDelayConfig(cfg, route.agentId);
580
+ const storePath = core.channel.session.resolveStorePath(cfg.session?.store, {
399
581
  agentId: route.agentId,
582
+ });
583
+
584
+ await core.channel.turn.run({
400
585
  channel: "tlon",
401
586
  accountId: route.accountId,
587
+ raw: rawTurnMessage,
588
+ adapter: {
589
+ ingest: (raw) => ({
590
+ id: raw.messageId,
591
+ timestamp: raw.timestamp,
592
+ rawText: raw.messageText,
593
+ textForAgent: commandBody,
594
+ textForCommands: commandBody,
595
+ raw,
596
+ }),
597
+ resolveTurn: () => ({
598
+ cfg,
599
+ channel: "tlon",
600
+ accountId: route.accountId,
601
+ agentId: route.agentId,
602
+ routeSessionKey: route.sessionKey,
603
+ storePath,
604
+ ctxPayload,
605
+ recordInboundSession: core.channel.session.recordInboundSession,
606
+ dispatchReplyWithBufferedBlockDispatcher:
607
+ core.channel.reply.dispatchReplyWithBufferedBlockDispatcher,
608
+ delivery: {
609
+ deliver: async (payload: ReplyPayload) => {
610
+ let replyText = payload.text;
611
+ if (!replyText) {
612
+ return;
613
+ }
614
+
615
+ // Use settings store value if set, otherwise fall back to file config
616
+ const showSignature = effectiveShowModelSig;
617
+ if (showSignature) {
618
+ const extPayload = payload as {
619
+ metadata?: { model?: string };
620
+ model?: string;
621
+ };
622
+ const defaultModel = cfg.agents?.defaults?.model;
623
+ const modelInfo =
624
+ extPayload.metadata?.model ||
625
+ extPayload.model ||
626
+ (typeof defaultModel === "string" ? defaultModel : defaultModel?.primary);
627
+ replyText = `${replyText}\n\n_[Generated by ${formatModelName(modelInfo)}]_`;
628
+ }
629
+
630
+ if (isGroup && groupChannel) {
631
+ const parsed = parseChannelNest(groupChannel);
632
+ if (!parsed) {
633
+ return;
634
+ }
635
+ await sendGroupMessage({
636
+ api: api,
637
+ fromShip: botShipName,
638
+ hostShip: parsed.hostShip,
639
+ channelName: parsed.channelName,
640
+ text: replyText,
641
+ replyToId: parentId ?? undefined,
642
+ });
643
+ // Track thread participation for future replies without mention
644
+ if (parentId) {
645
+ participatedThreads.add(parentId);
646
+ runtime.log?.(`[tlon] Now tracking thread for future replies: ${parentId}`);
647
+ }
648
+ } else {
649
+ await sendDm({
650
+ api: api,
651
+ fromShip: botShipName,
652
+ toShip: senderShip,
653
+ text: replyText,
654
+ });
655
+ }
656
+ },
657
+ onError: (err, info) => {
658
+ const dispatchDuration = Date.now() - dispatchStartTime;
659
+ runtime.error?.(
660
+ `[tlon] ${info.kind} reply failed after ${dispatchDuration}ms: ${String(err)}`,
661
+ );
662
+ },
663
+ },
664
+ dispatcherOptions: {
665
+ responsePrefix,
666
+ humanDelay,
667
+ },
668
+ record: {
669
+ onRecordError: (err) => {
670
+ runtime.error?.(`[tlon] failed updating session meta: ${String(err)}`);
671
+ },
672
+ },
673
+ }),
674
+ },
402
675
  });
403
- const humanDelay = core.channel.reply.resolveHumanDelayConfig(cfg, route.agentId);
676
+ };
404
677
 
405
- await core.channel.reply.dispatchReplyWithBufferedBlockDispatcher({
406
- ctx: ctxPayload,
407
- cfg,
408
- dispatcherOptions: {
409
- ...prefixOptions,
410
- humanDelay,
411
- deliver: async (payload: ReplyPayload) => {
412
- let replyText = payload.text;
413
- if (!replyText) {
678
+ // Track which channels we're interested in for filtering firehose events
679
+ const watchedChannels = new Set<string>(groupChannels);
680
+ const _watchedDMs = new Set<string>();
681
+
682
+ const refreshWatchedChannels = async (): Promise<number> => {
683
+ const discoveredChannels = await fetchAllChannels(api, runtime);
684
+ let newCount = 0;
685
+ for (const channelNest of discoveredChannels) {
686
+ if (!watchedChannels.has(channelNest)) {
687
+ watchedChannels.add(channelNest);
688
+ newCount++;
689
+ }
690
+ }
691
+ return newCount;
692
+ };
693
+
694
+ const { resolveAllCites } = createTlonCitationResolver({
695
+ api: { scry: (path) => api.scry(path) },
696
+ runtime,
697
+ });
698
+
699
+ const { queueApprovalRequest, handleApprovalResponse, handleAdminCommand } =
700
+ createTlonApprovalRuntime({
701
+ api: {
702
+ poke: (payload) => api.poke(payload),
703
+ scry: (path) => api.scry(path),
704
+ },
705
+ runtime,
706
+ botShipName,
707
+ getPendingApprovals: () => pendingApprovals,
708
+ setPendingApprovals: (approvals) => {
709
+ pendingApprovals = approvals;
710
+ },
711
+ getCurrentSettings: () => currentSettings,
712
+ setCurrentSettings: (settings) => {
713
+ currentSettings = settings;
714
+ },
715
+ getEffectiveDmAllowlist: () => effectiveDmAllowlist,
716
+ setEffectiveDmAllowlist: (ships) => {
717
+ effectiveDmAllowlist = ships;
718
+ },
719
+ getEffectiveOwnerShip: () => effectiveOwnerShip,
720
+ processApprovedMessage: async (approval) => {
721
+ if (!approval.originalMessage) {
722
+ return;
723
+ }
724
+ if (approval.type === "dm") {
725
+ await processMessage({
726
+ messageId: approval.originalMessage.messageId,
727
+ senderShip: approval.requestingShip,
728
+ messageText: approval.originalMessage.messageText,
729
+ messageContent: approval.originalMessage.messageContent,
730
+ isGroup: false,
731
+ timestamp: approval.originalMessage.timestamp,
732
+ });
733
+ return;
734
+ }
735
+ if (approval.type === "channel" && approval.channelNest) {
736
+ const parsedChannel = parseChannelNest(approval.channelNest);
737
+ await processMessage({
738
+ messageId: approval.originalMessage.messageId,
739
+ senderShip: approval.requestingShip,
740
+ messageText: approval.originalMessage.messageText,
741
+ messageContent: approval.originalMessage.messageContent,
742
+ isGroup: true,
743
+ channelNest: approval.channelNest,
744
+ hostShip: parsedChannel?.hostShip,
745
+ channelName: parsedChannel?.channelName,
746
+ timestamp: approval.originalMessage.timestamp,
747
+ parentId: approval.originalMessage.parentId,
748
+ isThreadReply: approval.originalMessage.isThreadReply,
749
+ });
750
+ }
751
+ },
752
+ refreshWatchedChannels,
753
+ });
754
+
755
+ // Firehose handler for all channel messages (/v2)
756
+ const handleChannelsFirehose = async (event: unknown) => {
757
+ try {
758
+ const eventRecord = asRecord(event);
759
+ const nest = readString(eventRecord, "nest");
760
+ if (!nest) {
761
+ return;
762
+ }
763
+
764
+ // Only process channels we're watching
765
+ if (!watchedChannels.has(nest)) {
766
+ return;
767
+ }
768
+
769
+ const response = asRecord(eventRecord?.response);
770
+ if (!response) {
771
+ return;
772
+ }
773
+
774
+ // Handle post responses (new posts and replies)
775
+ const post = asRecord(response.post);
776
+ const rPost = asRecord(post?.["r-post"]);
777
+ const set = asRecord(rPost?.set);
778
+ const reply = asRecord(rPost?.reply);
779
+ const replyPayload = asRecord(reply?.["r-reply"]);
780
+ const replySet = asRecord(replyPayload?.set);
781
+ const essay = asRecord(set?.essay);
782
+ const memo = asRecord(replySet?.memo);
783
+ if (!essay && !memo) {
784
+ return;
785
+ }
786
+
787
+ const content = memo ?? essay;
788
+ if (!content) {
789
+ return;
790
+ }
791
+ const isThreadReply = Boolean(memo);
792
+ const messageId = isThreadReply ? readString(reply, "id") : readString(post, "id");
793
+ if (!messageId) {
794
+ return;
795
+ }
796
+
797
+ const processed = await runWithProcessedMessageClaim({
798
+ tracker: processedTracker,
799
+ id: messageId,
800
+ task: async () => {
801
+ const senderShip = normalizeShip(readString(content, "author") ?? "");
802
+ if (!senderShip || senderShip === botShipName) {
414
803
  return;
415
804
  }
416
805
 
417
- const showSignature =
418
- account.showModelSignature ?? cfg.channels?.tlon?.showModelSignature ?? false;
419
- if (showSignature) {
420
- const extPayload = payload as ReplyPayload & {
421
- metadata?: { model?: string };
422
- model?: string;
423
- };
424
- const extRoute = route as typeof route & { model?: string };
425
- const modelInfo =
426
- extPayload.metadata?.model ||
427
- extPayload.model ||
428
- extRoute.model ||
429
- cfg.agents?.defaults?.model?.primary;
430
- replyText = `${replyText}\n\n_[Generated by ${formatModelName(modelInfo)}]_`;
806
+ const rawText = extractMessageText(content.content);
807
+ if (!rawText.trim()) {
808
+ return;
431
809
  }
432
810
 
433
- if (isGroup && groupChannel) {
434
- const parsed = parseChannelNest(groupChannel);
435
- if (!parsed) {
811
+ const contentBody = content.content;
812
+ const sentAt = readNumber(content, "sent") ?? Date.now();
813
+
814
+ cacheMessage(nest, {
815
+ author: senderShip,
816
+ content: rawText,
817
+ timestamp: sentAt,
818
+ id: messageId,
819
+ });
820
+
821
+ // Get thread info early for participation check
822
+ const seal = isThreadReply ? asRecord(replySet?.seal) : asRecord(set?.seal);
823
+ const parentId = readString(seal, "parent-id") ?? readString(seal, "parent") ?? null;
824
+
825
+ // Check if we should respond:
826
+ // 1. Direct mention always triggers response
827
+ // 2. Thread replies where we've participated - respond if relevant (let agent decide)
828
+ const mentioned = isBotMentioned(rawText, botShipName, botNickname ?? undefined);
829
+ const inParticipatedThread =
830
+ isThreadReply && parentId && participatedThreads.has(parentId);
831
+
832
+ if (!mentioned && !inParticipatedThread) {
833
+ return;
834
+ }
835
+
836
+ // Log why we're responding
837
+ if (inParticipatedThread && !mentioned) {
838
+ runtime.log?.(
839
+ `[tlon] Responding to thread we participated in (no mention): ${parentId}`,
840
+ );
841
+ }
842
+
843
+ // Owner is always allowed
844
+ if (isOwner(senderShip)) {
845
+ runtime.log?.(`[tlon] Owner ${senderShip} is always allowed in channels`);
846
+ } else {
847
+ const { mode, allowedShips } = resolveChannelAuthorization(cfg, nest, currentSettings);
848
+ if (mode === "restricted") {
849
+ const normalizedAllowed = allowedShips.map(normalizeShip);
850
+ if (!normalizedAllowed.includes(senderShip)) {
851
+ // If owner is configured, queue approval request
852
+ if (effectiveOwnerShip) {
853
+ const approval = createPendingApproval({
854
+ type: "channel",
855
+ requestingShip: senderShip,
856
+ channelNest: nest,
857
+ messagePreview: rawText.slice(0, 100),
858
+ originalMessage: {
859
+ messageId: messageId ?? "",
860
+ messageText: rawText,
861
+ messageContent: contentBody,
862
+ timestamp: sentAt,
863
+ parentId: parentId ?? undefined,
864
+ isThreadReply,
865
+ },
866
+ });
867
+ await queueApprovalRequest(approval);
868
+ } else {
869
+ runtime.log?.(
870
+ `[tlon] Access denied: ${senderShip} in ${nest} (allowed: ${allowedShips.join(", ")})`,
871
+ );
872
+ }
873
+ return;
874
+ }
875
+ }
876
+ }
877
+
878
+ const messageText = await resolveAuthorizedMessageText({
879
+ rawText,
880
+ content: contentBody,
881
+ authorizedForCites: true,
882
+ resolveAllCites,
883
+ });
884
+
885
+ const parsed = parseChannelNest(nest);
886
+ await processMessage({
887
+ messageId: messageId ?? "",
888
+ senderShip,
889
+ messageText,
890
+ messageContent: contentBody, // Pass raw content for media extraction
891
+ isGroup: true,
892
+ channelNest: nest,
893
+ hostShip: parsed?.hostShip,
894
+ channelName: parsed?.channelName,
895
+ timestamp: sentAt,
896
+ parentId,
897
+ isThreadReply,
898
+ });
899
+ },
900
+ });
901
+ if (processed.kind === "duplicate") {
902
+ return;
903
+ }
904
+ } catch (error: unknown) {
905
+ runtime.error?.(`[tlon] Error handling channel firehose event: ${formatErrorMessage(error)}`);
906
+ }
907
+ };
908
+
909
+ // Firehose handler for all DM messages (/v3)
910
+ // Track which DM invites we've already processed to avoid duplicate accepts
911
+ const processedDmInvites = new Set<string>();
912
+
913
+ const handleChatFirehose = async (event: unknown) => {
914
+ try {
915
+ // Handle DM invite lists (arrays)
916
+ if (Array.isArray(event)) {
917
+ for (const invite of event as DmInvite[]) {
918
+ const ship = normalizeShip(invite.ship || "");
919
+ if (!ship || processedDmInvites.has(ship)) {
920
+ continue;
921
+ }
922
+
923
+ // Owner is always allowed
924
+ if (isOwner(ship)) {
925
+ try {
926
+ await api.poke({
927
+ app: "chat",
928
+ mark: "chat-dm-rsvp",
929
+ json: { ship, ok: true },
930
+ });
931
+ processedDmInvites.add(ship);
932
+ runtime.log?.(`[tlon] Auto-accepted DM invite from owner ${ship}`);
933
+ } catch (err) {
934
+ runtime.error?.(`[tlon] Failed to auto-accept DM from owner: ${String(err)}`);
935
+ }
936
+ continue;
937
+ }
938
+
939
+ // Auto-accept if on allowlist and auto-accept is enabled
940
+ if (effectiveAutoAcceptDmInvites && isDmAllowed(ship, effectiveDmAllowlist)) {
941
+ try {
942
+ await api.poke({
943
+ app: "chat",
944
+ mark: "chat-dm-rsvp",
945
+ json: { ship, ok: true },
946
+ });
947
+ processedDmInvites.add(ship);
948
+ runtime.log?.(`[tlon] Auto-accepted DM invite from ${ship}`);
949
+ } catch (err) {
950
+ runtime.error?.(`[tlon] Failed to auto-accept DM from ${ship}: ${String(err)}`);
951
+ }
952
+ continue;
953
+ }
954
+
955
+ // If owner is configured and ship is not on allowlist, queue approval
956
+ if (effectiveOwnerShip && !isDmAllowed(ship, effectiveDmAllowlist)) {
957
+ const approval = createPendingApproval({
958
+ type: "dm",
959
+ requestingShip: ship,
960
+ messagePreview: "(DM invite - no message yet)",
961
+ });
962
+ await queueApprovalRequest(approval);
963
+ processedDmInvites.add(ship); // Mark as processed to avoid duplicate notifications
964
+ }
965
+ }
966
+ return;
967
+ }
968
+ const eventRecord = asRecord(event);
969
+ if (!eventRecord) {
970
+ return;
971
+ }
972
+
973
+ const whom = eventRecord.whom; // DM partner ship or club ID
974
+ const messageId = readString(eventRecord, "id");
975
+ const response = asRecord(eventRecord.response);
976
+ if (!messageId || !response) {
977
+ return;
978
+ }
979
+
980
+ // Handle add events (new messages)
981
+ const essay = asRecord(asRecord(response.add)?.essay);
982
+ if (!essay) {
983
+ return;
984
+ }
985
+
986
+ const processed = await runWithProcessedMessageClaim({
987
+ tracker: processedTracker,
988
+ id: messageId,
989
+ task: async () => {
990
+ const authorShip = normalizeShip(readString(essay, "author") ?? "");
991
+ const partnerShip = extractDmPartnerShip(whom);
992
+ const senderShip = partnerShip || authorShip;
993
+
994
+ // Ignore the bot's own outbound DM events.
995
+ if (authorShip === botShipName) {
996
+ return;
997
+ }
998
+ if (!senderShip || senderShip === botShipName) {
999
+ return;
1000
+ }
1001
+
1002
+ // Log mismatch between author and partner for debugging
1003
+ if (authorShip && partnerShip && authorShip !== partnerShip) {
1004
+ runtime.log?.(
1005
+ `[tlon] DM ship mismatch (author=${authorShip}, partner=${partnerShip}) - routing to partner`,
1006
+ );
1007
+ }
1008
+
1009
+ const rawText = extractMessageText(essay.content);
1010
+ if (!rawText.trim()) {
1011
+ return;
1012
+ }
1013
+
1014
+ // Check if this is the owner sending an approval response
1015
+ const messageText = rawText;
1016
+ if (isOwner(senderShip) && isApprovalResponse(messageText)) {
1017
+ const handled = await handleApprovalResponse(messageText);
1018
+ if (handled) {
1019
+ runtime.log?.(`[tlon] Processed approval response from owner: ${messageText}`);
436
1020
  return;
437
1021
  }
438
- await sendGroupMessage({
439
- api: api,
440
- fromShip: botShipName,
441
- hostShip: parsed.hostShip,
442
- channelName: parsed.channelName,
443
- text: replyText,
444
- replyToId: parentId ?? undefined,
1022
+ }
1023
+
1024
+ // Check if this is the owner sending an admin command
1025
+ if (isOwner(senderShip) && isAdminCommand(messageText)) {
1026
+ const handled = await handleAdminCommand(messageText);
1027
+ if (handled) {
1028
+ runtime.log?.(`[tlon] Processed admin command from owner: ${messageText}`);
1029
+ return;
1030
+ }
1031
+ }
1032
+
1033
+ // Owner is always allowed to DM (bypass allowlist)
1034
+ if (isOwner(senderShip)) {
1035
+ const resolvedMessageText = await resolveAuthorizedMessageText({
1036
+ rawText,
1037
+ content: essay.content,
1038
+ authorizedForCites: true,
1039
+ resolveAllCites,
445
1040
  });
446
- } else {
447
- await sendDm({ api: api, fromShip: botShipName, toShip: senderShip, text: replyText });
1041
+ runtime.log?.(`[tlon] Processing DM from owner ${senderShip}`);
1042
+ await processMessage({
1043
+ messageId: messageId ?? "",
1044
+ senderShip,
1045
+ messageText: resolvedMessageText,
1046
+ messageContent: essay.content,
1047
+ isGroup: false,
1048
+ timestamp: readNumber(essay, "sent") ?? Date.now(),
1049
+ });
1050
+ return;
448
1051
  }
1052
+
1053
+ // For DMs from others, check allowlist
1054
+ if (!isDmAllowed(senderShip, effectiveDmAllowlist)) {
1055
+ // If owner is configured, queue approval request
1056
+ if (effectiveOwnerShip) {
1057
+ const approval = createPendingApproval({
1058
+ type: "dm",
1059
+ requestingShip: senderShip,
1060
+ messagePreview: messageText.slice(0, 100),
1061
+ originalMessage: {
1062
+ messageId: messageId ?? "",
1063
+ messageText,
1064
+ messageContent: essay.content,
1065
+ timestamp: readNumber(essay, "sent") ?? Date.now(),
1066
+ },
1067
+ });
1068
+ await queueApprovalRequest(approval);
1069
+ } else {
1070
+ runtime.log?.(`[tlon] Blocked DM from ${senderShip}: not in allowlist`);
1071
+ }
1072
+ return;
1073
+ }
1074
+
1075
+ await processMessage({
1076
+ messageText: await resolveAuthorizedMessageText({
1077
+ rawText,
1078
+ content: essay.content,
1079
+ authorizedForCites: true,
1080
+ resolveAllCites,
1081
+ }),
1082
+ messageId: messageId ?? "",
1083
+ senderShip,
1084
+ messageContent: essay.content, // Pass raw content for media extraction
1085
+ isGroup: false,
1086
+ timestamp: readNumber(essay, "sent") ?? Date.now(),
1087
+ });
449
1088
  },
450
- onError: (err, info) => {
451
- const dispatchDuration = Date.now() - dispatchStartTime;
452
- runtime.error?.(
453
- `[tlon] ${info.kind} reply failed after ${dispatchDuration}ms: ${String(err)}`,
454
- );
455
- },
1089
+ });
1090
+ if (processed.kind === "duplicate") {
1091
+ return;
1092
+ }
1093
+ } catch (error: unknown) {
1094
+ runtime.error?.(`[tlon] Error handling chat firehose event: ${formatErrorMessage(error)}`);
1095
+ }
1096
+ };
1097
+
1098
+ try {
1099
+ runtime.log?.("[tlon] Subscribing to firehose updates...");
1100
+
1101
+ // Subscribe to channels firehose (/v2)
1102
+ await api.subscribe({
1103
+ app: "channels",
1104
+ path: "/v2",
1105
+ event: handleChannelsFirehose,
1106
+ err: (error) => {
1107
+ runtime.error?.(`[tlon] Channels firehose error: ${String(error)}`);
456
1108
  },
457
- replyOptions: {
458
- onModelSelected,
1109
+ quit: () => {
1110
+ runtime.log?.("[tlon] Channels firehose subscription ended");
459
1111
  },
460
1112
  });
461
- };
1113
+ runtime.log?.("[tlon] Subscribed to channels firehose (/v2)");
462
1114
 
463
- const subscribedChannels = new Set<string>();
464
- const subscribedDMs = new Set<string>();
1115
+ // Subscribe to chat/DM firehose (/v3)
1116
+ await api.subscribe({
1117
+ app: "chat",
1118
+ path: "/v3",
1119
+ event: handleChatFirehose,
1120
+ err: (error) => {
1121
+ runtime.error?.(`[tlon] Chat firehose error: ${String(error)}`);
1122
+ },
1123
+ quit: () => {
1124
+ runtime.log?.("[tlon] Chat firehose subscription ended");
1125
+ },
1126
+ });
1127
+ runtime.log?.("[tlon] Subscribed to chat firehose (/v3)");
465
1128
 
466
- async function subscribeToChannel(channelNest: string) {
467
- if (subscribedChannels.has(channelNest)) {
468
- return;
469
- }
470
- const parsed = parseChannelNest(channelNest);
471
- if (!parsed) {
472
- runtime.error?.(`[tlon] Invalid channel format: ${channelNest}`);
473
- return;
474
- }
1129
+ // Subscribe to contacts updates to track nickname changes
1130
+ await api.subscribe({
1131
+ app: "contacts",
1132
+ path: "/v1/news",
1133
+ event: (event: unknown) => {
1134
+ try {
1135
+ const eventRecord = asRecord(event);
1136
+ // Look for self profile updates
1137
+ if (eventRecord?.self) {
1138
+ const selfUpdate = asRecord(eventRecord.self);
1139
+ const contact = asRecord(selfUpdate?.contact);
1140
+ const nickname = asRecord(contact?.nickname);
1141
+ if (nickname && "value" in nickname) {
1142
+ const newNickname = readString(nickname, "value") ?? null;
1143
+ if (newNickname !== botNickname) {
1144
+ botNickname = newNickname;
1145
+ runtime.log?.(`[tlon] Nickname updated: ${botNickname}`);
1146
+ }
1147
+ }
1148
+ }
1149
+ } catch (error: unknown) {
1150
+ runtime.error?.(`[tlon] Error handling contacts event: ${formatErrorMessage(error)}`);
1151
+ }
1152
+ },
1153
+ err: (error) => {
1154
+ runtime.error?.(`[tlon] Contacts subscription error: ${String(error)}`);
1155
+ },
1156
+ quit: () => {
1157
+ runtime.log?.("[tlon] Contacts subscription ended");
1158
+ },
1159
+ });
1160
+ runtime.log?.("[tlon] Subscribed to contacts updates (/v1/news)");
1161
+
1162
+ // Subscribe to settings store for hot-reloading config
1163
+ settingsManager.onChange((newSettings) => {
1164
+ currentSettings = newSettings;
1165
+
1166
+ // Update watched channels if settings changed
1167
+ if (newSettings.groupChannels?.length) {
1168
+ const newChannels = newSettings.groupChannels;
1169
+ for (const ch of newChannels) {
1170
+ if (!watchedChannels.has(ch)) {
1171
+ watchedChannels.add(ch);
1172
+ runtime.log?.(`[tlon] Settings: now watching channel ${ch}`);
1173
+ }
1174
+ }
1175
+ // Note: we don't remove channels from watchedChannels to avoid missing messages
1176
+ // during transitions. The authorization check handles access control.
1177
+ }
1178
+
1179
+ // Recompute effective settings from the latest snapshot so deletions
1180
+ // cleanly fall back to file config and empty arrays remain authoritative.
1181
+ ({
1182
+ effectiveDmAllowlist,
1183
+ effectiveShowModelSig,
1184
+ effectiveAutoAcceptDmInvites,
1185
+ effectiveAutoAcceptGroupInvites,
1186
+ effectiveGroupInviteAllowlist,
1187
+ effectiveAutoDiscoverChannels,
1188
+ effectiveOwnerShip,
1189
+ pendingApprovals,
1190
+ } = applyTlonSettingsOverrides({
1191
+ account,
1192
+ currentSettings: newSettings,
1193
+ log: (message) => runtime.log?.(message),
1194
+ }));
1195
+ });
475
1196
 
476
1197
  try {
477
- await api!.subscribe({
478
- app: "channels",
479
- path: `/${channelNest}`,
480
- event: (data: unknown) => {
481
- handleIncomingGroupMessage(channelNest)(data as UrbitUpdate);
482
- },
483
- err: (error) => {
484
- runtime.error?.(`[tlon] Group subscription error for ${channelNest}: ${String(error)}`);
485
- },
486
- quit: () => {
487
- runtime.log?.(`[tlon] Group subscription ended for ${channelNest}`);
488
- subscribedChannels.delete(channelNest);
489
- },
490
- });
491
- subscribedChannels.add(channelNest);
492
- runtime.log?.(`[tlon] Subscribed to group channel: ${channelNest}`);
493
- } catch (error) {
494
- runtime.error?.(`[tlon] Failed to subscribe to ${channelNest}: ${formatError(error)}`);
1198
+ await settingsManager.startSubscription();
1199
+ } catch (err) {
1200
+ // Settings subscription is optional - don't fail if it doesn't work
1201
+ runtime.log?.(`[tlon] Settings subscription not available: ${String(err)}`);
495
1202
  }
496
- }
497
1203
 
498
- async function subscribeToDM(dmShip: string) {
499
- if (subscribedDMs.has(dmShip)) {
500
- return;
501
- }
1204
+ // Subscribe to groups-ui for real-time channel additions (when invites are accepted)
502
1205
  try {
503
- await api!.subscribe({
504
- app: "chat",
505
- path: `/dm/${dmShip}`,
506
- event: (data: unknown) => {
507
- handleIncomingDM(data as UrbitUpdate);
1206
+ await api.subscribe({
1207
+ app: "groups",
1208
+ path: "/groups/ui",
1209
+ event: async (event: unknown) => {
1210
+ try {
1211
+ const eventRecord = asRecord(event);
1212
+ // Handle group/channel join events
1213
+ // Event structure: { group: { flag: "~host/group-name", ... }, channels: { ... } }
1214
+ if (eventRecord) {
1215
+ // Check for new channels being added to groups
1216
+ const channels = asRecord(eventRecord.channels);
1217
+ if (channels) {
1218
+ for (const [channelNest, _channelData] of Object.entries(channels)) {
1219
+ // Only monitor chat channels
1220
+ if (!channelNest.startsWith("chat/")) {
1221
+ continue;
1222
+ }
1223
+
1224
+ // If this is a new channel we're not watching yet, add it
1225
+ if (!watchedChannels.has(channelNest)) {
1226
+ watchedChannels.add(channelNest);
1227
+ runtime.log?.(
1228
+ `[tlon] Auto-detected new channel (invite accepted): ${channelNest}`,
1229
+ );
1230
+
1231
+ // Persist to settings store so it survives restarts
1232
+ if (effectiveAutoAcceptGroupInvites) {
1233
+ try {
1234
+ const currentChannels = currentSettings.groupChannels || [];
1235
+ if (!currentChannels.includes(channelNest)) {
1236
+ const updatedChannels = [...currentChannels, channelNest];
1237
+ // Poke settings store to persist
1238
+ await api.poke({
1239
+ app: "settings",
1240
+ mark: "settings-event",
1241
+ json: {
1242
+ "put-entry": {
1243
+ "bucket-key": "tlon",
1244
+ "entry-key": "groupChannels",
1245
+ value: updatedChannels,
1246
+ desk: "moltbot",
1247
+ },
1248
+ },
1249
+ });
1250
+ runtime.log?.(`[tlon] Persisted ${channelNest} to settings store`);
1251
+ }
1252
+ } catch (err) {
1253
+ runtime.error?.(
1254
+ `[tlon] Failed to persist channel to settings: ${String(err)}`,
1255
+ );
1256
+ }
1257
+ }
1258
+ }
1259
+ }
1260
+ }
1261
+
1262
+ // Also check for the "join" event structure
1263
+ const join = asRecord(eventRecord.join);
1264
+ if (join) {
1265
+ const joinChannels = Array.isArray(join.channels) ? join.channels : [];
1266
+ if (joinChannels.length > 0) {
1267
+ for (const channelNest of joinChannels) {
1268
+ if (typeof channelNest !== "string") {
1269
+ continue;
1270
+ }
1271
+ if (!channelNest.startsWith("chat/")) {
1272
+ continue;
1273
+ }
1274
+ if (!watchedChannels.has(channelNest)) {
1275
+ watchedChannels.add(channelNest);
1276
+ runtime.log?.(`[tlon] Auto-detected joined channel: ${channelNest}`);
1277
+
1278
+ // Persist to settings store
1279
+ if (effectiveAutoAcceptGroupInvites) {
1280
+ try {
1281
+ const currentChannels = currentSettings.groupChannels || [];
1282
+ if (!currentChannels.includes(channelNest)) {
1283
+ const updatedChannels = [...currentChannels, channelNest];
1284
+ await api.poke({
1285
+ app: "settings",
1286
+ mark: "settings-event",
1287
+ json: {
1288
+ "put-entry": {
1289
+ "bucket-key": "tlon",
1290
+ "entry-key": "groupChannels",
1291
+ value: updatedChannels,
1292
+ desk: "moltbot",
1293
+ },
1294
+ },
1295
+ });
1296
+ runtime.log?.(`[tlon] Persisted ${channelNest} to settings store`);
1297
+ }
1298
+ } catch (err) {
1299
+ runtime.error?.(
1300
+ `[tlon] Failed to persist channel to settings: ${String(err)}`,
1301
+ );
1302
+ }
1303
+ }
1304
+ }
1305
+ }
1306
+ }
1307
+ }
1308
+ }
1309
+ } catch (error: unknown) {
1310
+ runtime.error?.(`[tlon] Error handling groups-ui event: ${formatErrorMessage(error)}`);
1311
+ }
508
1312
  },
509
1313
  err: (error) => {
510
- runtime.error?.(`[tlon] DM subscription error for ${dmShip}: ${String(error)}`);
1314
+ runtime.error?.(`[tlon] Groups-ui subscription error: ${String(error)}`);
511
1315
  },
512
1316
  quit: () => {
513
- runtime.log?.(`[tlon] DM subscription ended for ${dmShip}`);
514
- subscribedDMs.delete(dmShip);
1317
+ runtime.log?.("[tlon] Groups-ui subscription ended");
515
1318
  },
516
1319
  });
517
- subscribedDMs.add(dmShip);
518
- runtime.log?.(`[tlon] Subscribed to DM with ${dmShip}`);
519
- } catch (error) {
520
- runtime.error?.(`[tlon] Failed to subscribe to DM with ${dmShip}: ${formatError(error)}`);
1320
+ runtime.log?.("[tlon] Subscribed to groups-ui for real-time channel detection");
1321
+ } catch (err) {
1322
+ // Groups-ui subscription is optional - channel discovery will still work via polling
1323
+ runtime.log?.(`[tlon] Groups-ui subscription failed (will rely on polling): ${String(err)}`);
521
1324
  }
522
- }
523
1325
 
524
- async function refreshChannelSubscriptions() {
525
- try {
526
- const dmShips = await api!.scry("/chat/dm.json");
527
- if (Array.isArray(dmShips)) {
528
- for (const dmShip of dmShips) {
529
- await subscribeToDM(dmShip);
1326
+ // Subscribe to foreigns for auto-accepting group invites
1327
+ // Always subscribe so we can hot-reload the setting via settings store
1328
+ {
1329
+ const processedGroupInvites = new Set<string>();
1330
+
1331
+ // Helper to process pending invites
1332
+ const processPendingInvites = async (foreigns: Foreigns) => {
1333
+ if (!foreigns || typeof foreigns !== "object") {
1334
+ return;
530
1335
  }
531
- }
532
1336
 
533
- if (account.autoDiscoverChannels !== false) {
534
- const discoveredChannels = await fetchAllChannels(api!, runtime);
535
- for (const channelNest of discoveredChannels) {
536
- await subscribeToChannel(channelNest);
1337
+ for (const [groupFlag, foreign] of Object.entries(foreigns)) {
1338
+ if (processedGroupInvites.has(groupFlag)) {
1339
+ continue;
1340
+ }
1341
+ if (!foreign.invites || foreign.invites.length === 0) {
1342
+ continue;
1343
+ }
1344
+
1345
+ const validInvite = foreign.invites.find((inv) => inv.valid);
1346
+ if (!validInvite) {
1347
+ continue;
1348
+ }
1349
+
1350
+ const inviterShip = validInvite.from;
1351
+ // Owner invites are always accepted
1352
+ if (isOwner(inviterShip)) {
1353
+ try {
1354
+ await api.poke({
1355
+ app: "groups",
1356
+ mark: "group-join",
1357
+ json: {
1358
+ flag: groupFlag,
1359
+ "join-all": true,
1360
+ },
1361
+ });
1362
+ processedGroupInvites.add(groupFlag);
1363
+ runtime.log?.(`[tlon] Auto-accepted group invite from owner: ${groupFlag}`);
1364
+ } catch (err) {
1365
+ runtime.error?.(`[tlon] Failed to accept group invite from owner: ${String(err)}`);
1366
+ }
1367
+ continue;
1368
+ }
1369
+
1370
+ // Skip if auto-accept is disabled
1371
+ if (!effectiveAutoAcceptGroupInvites) {
1372
+ // If owner is configured, queue approval
1373
+ if (effectiveOwnerShip) {
1374
+ const approval = createPendingApproval({
1375
+ type: "group",
1376
+ requestingShip: inviterShip,
1377
+ groupFlag,
1378
+ });
1379
+ await queueApprovalRequest(approval);
1380
+ processedGroupInvites.add(groupFlag);
1381
+ }
1382
+ continue;
1383
+ }
1384
+
1385
+ // Check if inviter is on allowlist
1386
+ const isAllowed = isGroupInviteAllowed(inviterShip, effectiveGroupInviteAllowlist);
1387
+
1388
+ if (!isAllowed) {
1389
+ // If owner is configured, queue approval
1390
+ if (effectiveOwnerShip) {
1391
+ const approval = createPendingApproval({
1392
+ type: "group",
1393
+ requestingShip: inviterShip,
1394
+ groupFlag,
1395
+ });
1396
+ await queueApprovalRequest(approval);
1397
+ processedGroupInvites.add(groupFlag);
1398
+ } else {
1399
+ runtime.log?.(
1400
+ `[tlon] Rejected group invite from ${inviterShip} (not in groupInviteAllowlist): ${groupFlag}`,
1401
+ );
1402
+ processedGroupInvites.add(groupFlag);
1403
+ }
1404
+ continue;
1405
+ }
1406
+
1407
+ // Inviter is on allowlist - accept the invite
1408
+ try {
1409
+ await api.poke({
1410
+ app: "groups",
1411
+ mark: "group-join",
1412
+ json: {
1413
+ flag: groupFlag,
1414
+ "join-all": true,
1415
+ },
1416
+ });
1417
+ processedGroupInvites.add(groupFlag);
1418
+ runtime.log?.(
1419
+ `[tlon] Auto-accepted group invite: ${groupFlag} (from ${validInvite.from})`,
1420
+ );
1421
+ } catch (err) {
1422
+ runtime.error?.(`[tlon] Failed to auto-accept group ${groupFlag}: ${String(err)}`);
1423
+ }
537
1424
  }
538
- }
539
- } catch (error) {
540
- runtime.error?.(`[tlon] Channel refresh failed: ${formatError(error)}`);
541
- }
542
- }
1425
+ };
543
1426
 
544
- try {
545
- runtime.log?.("[tlon] Subscribing to updates...");
1427
+ // Process existing pending invites from init data
1428
+ if (initForeigns) {
1429
+ await processPendingInvites(initForeigns);
1430
+ }
546
1431
 
547
- let dmShips: string[] = [];
548
- try {
549
- const dmList = await api.scry("/chat/dm.json");
550
- if (Array.isArray(dmList)) {
551
- dmShips = dmList;
552
- runtime.log?.(`[tlon] Found ${dmShips.length} DM conversation(s)`);
1432
+ try {
1433
+ await api.subscribe({
1434
+ app: "groups",
1435
+ path: "/v1/foreigns",
1436
+ event: (data: unknown) => {
1437
+ void (async () => {
1438
+ try {
1439
+ await processPendingInvites(data as Foreigns);
1440
+ } catch (error: unknown) {
1441
+ runtime.error?.(
1442
+ `[tlon] Error handling foreigns event: ${formatErrorMessage(error)}`,
1443
+ );
1444
+ }
1445
+ })();
1446
+ },
1447
+ err: (error) => {
1448
+ runtime.error?.(`[tlon] Foreigns subscription error: ${String(error)}`);
1449
+ },
1450
+ quit: () => {
1451
+ runtime.log?.("[tlon] Foreigns subscription ended");
1452
+ },
1453
+ });
1454
+ runtime.log?.(
1455
+ "[tlon] Subscribed to foreigns (/v1/foreigns) for auto-accepting group invites",
1456
+ );
1457
+ } catch (err) {
1458
+ runtime.log?.(`[tlon] Foreigns subscription failed: ${String(err)}`);
553
1459
  }
554
- } catch (error) {
555
- runtime.error?.(`[tlon] Failed to fetch DM list: ${formatError(error)}`);
556
1460
  }
557
1461
 
558
- for (const dmShip of dmShips) {
559
- await subscribeToDM(dmShip);
1462
+ // Discover channels to watch
1463
+ if (effectiveAutoDiscoverChannels) {
1464
+ const discoveredChannels = await fetchAllChannels(api, runtime);
1465
+ for (const channelNest of discoveredChannels) {
1466
+ watchedChannels.add(channelNest);
1467
+ }
1468
+ runtime.log?.(`[tlon] Watching ${watchedChannels.size} channel(s)`);
560
1469
  }
561
1470
 
562
- for (const channelNest of groupChannels) {
563
- await subscribeToChannel(channelNest);
1471
+ // Log watched channels
1472
+ for (const channelNest of watchedChannels) {
1473
+ runtime.log?.(`[tlon] Watching channel: ${channelNest}`);
564
1474
  }
565
1475
 
566
1476
  runtime.log?.("[tlon] All subscriptions registered, connecting to SSE stream...");
567
1477
  await api.connect();
568
- runtime.log?.("[tlon] Connected! All subscriptions active");
1478
+ runtime.log?.("[tlon] Connected! Firehose subscriptions active");
569
1479
 
1480
+ // Periodically refresh channel discovery
570
1481
  const pollInterval = setInterval(
571
- () => {
1482
+ async () => {
572
1483
  if (!opts.abortSignal?.aborted) {
573
- refreshChannelSubscriptions().catch((error) => {
574
- runtime.error?.(`[tlon] Channel refresh error: ${formatError(error)}`);
575
- });
1484
+ try {
1485
+ if (effectiveAutoDiscoverChannels) {
1486
+ const discoveredChannels = await fetchAllChannels(api, runtime);
1487
+ for (const channelNest of discoveredChannels) {
1488
+ if (!watchedChannels.has(channelNest)) {
1489
+ watchedChannels.add(channelNest);
1490
+ runtime.log?.(`[tlon] Now watching new channel: ${channelNest}`);
1491
+ }
1492
+ }
1493
+ }
1494
+ } catch (error: unknown) {
1495
+ runtime.error?.(`[tlon] Channel refresh error: ${formatErrorMessage(error)}`);
1496
+ }
576
1497
  }
577
1498
  },
578
1499
  2 * 60 * 1000,
@@ -596,8 +1517,8 @@ export async function monitorTlonProvider(opts: MonitorTlonOpts = {}): Promise<v
596
1517
  } finally {
597
1518
  try {
598
1519
  await api?.close();
599
- } catch (error) {
600
- runtime.error?.(`[tlon] Cleanup error: ${formatError(error)}`);
1520
+ } catch (error: unknown) {
1521
+ runtime.error?.(`[tlon] Cleanup error: ${formatErrorMessage(error)}`);
601
1522
  }
602
1523
  }
603
1524
  }