@openclaw/tlon 2026.5.2 → 2026.5.3-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/dist/api.js +4 -0
  2. package/dist/channel-B4LtNGeZ.js +221 -0
  3. package/dist/channel-plugin-api.js +2 -0
  4. package/dist/channel.runtime-v-_0sHkJ.js +3584 -0
  5. package/dist/doctor-contract-W99wMbar.js +7 -0
  6. package/dist/doctor-contract-api.js +2 -0
  7. package/dist/index.js +18 -0
  8. package/dist/runtime-5FiW9E50.js +8 -0
  9. package/dist/runtime-api-C0hr1Rtn.js +4 -0
  10. package/dist/runtime-api.js +2 -0
  11. package/dist/setup-api.js +3 -0
  12. package/dist/setup-core-BUkZJ-MU.js +386 -0
  13. package/dist/setup-entry.js +11 -0
  14. package/dist/setup-surface-FxNMaluC.js +72 -0
  15. package/dist/test-api.js +2 -0
  16. package/package.json +15 -6
  17. package/api.ts +0 -16
  18. package/channel-plugin-api.ts +0 -1
  19. package/doctor-contract-api.ts +0 -1
  20. package/index.ts +0 -183
  21. package/runtime-api.ts +0 -17
  22. package/setup-api.ts +0 -2
  23. package/setup-entry.ts +0 -9
  24. package/src/account-fields.ts +0 -31
  25. package/src/channel.runtime.ts +0 -248
  26. package/src/channel.ts +0 -173
  27. package/src/config-schema.ts +0 -53
  28. package/src/core.test.ts +0 -278
  29. package/src/doctor-contract.ts +0 -9
  30. package/src/doctor.test.ts +0 -40
  31. package/src/doctor.ts +0 -10
  32. package/src/logger-runtime.ts +0 -1
  33. package/src/monitor/approval-runtime.ts +0 -363
  34. package/src/monitor/approval.test.ts +0 -33
  35. package/src/monitor/approval.ts +0 -286
  36. package/src/monitor/authorization.ts +0 -30
  37. package/src/monitor/cites.ts +0 -54
  38. package/src/monitor/discovery.ts +0 -68
  39. package/src/monitor/history.ts +0 -226
  40. package/src/monitor/index.ts +0 -1524
  41. package/src/monitor/media.test.ts +0 -91
  42. package/src/monitor/media.ts +0 -172
  43. package/src/monitor/processed-messages.test.ts +0 -58
  44. package/src/monitor/processed-messages.ts +0 -89
  45. package/src/monitor/settings-helpers.test.ts +0 -113
  46. package/src/monitor/settings-helpers.ts +0 -158
  47. package/src/monitor/utils.ts +0 -372
  48. package/src/runtime.ts +0 -9
  49. package/src/security.test.ts +0 -622
  50. package/src/session-route.ts +0 -40
  51. package/src/settings.ts +0 -391
  52. package/src/setup-core.ts +0 -228
  53. package/src/setup-surface.ts +0 -103
  54. package/src/targets.ts +0 -102
  55. package/src/tlon-api.test.ts +0 -589
  56. package/src/tlon-api.ts +0 -402
  57. package/src/types.ts +0 -160
  58. package/src/urbit/auth.ssrf.test.ts +0 -45
  59. package/src/urbit/auth.ts +0 -48
  60. package/src/urbit/base-url.test.ts +0 -48
  61. package/src/urbit/base-url.ts +0 -61
  62. package/src/urbit/channel-ops.ts +0 -145
  63. package/src/urbit/context.ts +0 -50
  64. package/src/urbit/errors.ts +0 -51
  65. package/src/urbit/fetch.ts +0 -42
  66. package/src/urbit/foreigns.ts +0 -49
  67. package/src/urbit/send.test.ts +0 -38
  68. package/src/urbit/send.ts +0 -176
  69. package/src/urbit/sse-client.test.ts +0 -203
  70. package/src/urbit/sse-client.ts +0 -484
  71. package/src/urbit/story.ts +0 -332
  72. package/src/urbit/upload.test.ts +0 -154
  73. package/src/urbit/upload.ts +0 -60
  74. package/test-api.ts +0 -1
  75. package/tsconfig.json +0 -16
@@ -1,1524 +0,0 @@
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";
5
- import { getTlonRuntime } from "../runtime.js";
6
- import { createSettingsManager, type TlonSettingsStore } from "../settings.js";
7
- import { normalizeShip, parseChannelNest } from "../targets.js";
8
- import { resolveTlonAccount } from "../types.js";
9
- import { authenticate } from "../urbit/auth.js";
10
- import { ssrfPolicyFromDangerouslyAllowPrivateNetwork } from "../urbit/context.js";
11
- import type { DmInvite, Foreigns } from "../urbit/foreigns.js";
12
- import { sendDm, sendGroupMessage } from "../urbit/send.js";
13
- import { UrbitSSEClient } from "../urbit/sse-client.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";
37
- import {
38
- extractMessageText,
39
- formatModelName,
40
- isBotMentioned,
41
- isDmAllowed,
42
- isGroupInviteAllowed,
43
- isSummarizationRequest,
44
- resolveAuthorizedMessageText,
45
- stripBotMention,
46
- } from "./utils.js";
47
-
48
- type MonitorTlonOpts = {
49
- runtime?: RuntimeEnv;
50
- abortSignal?: AbortSignal;
51
- accountId?: string | null;
52
- };
53
-
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;
57
- }
58
-
59
- export async function monitorTlonProvider(opts: MonitorTlonOpts = {}): Promise<void> {
60
- const core = getTlonRuntime();
61
- const cfg = core.config.current() as OpenClawConfig;
62
- if (cfg.channels?.tlon?.enabled === false) {
63
- return;
64
- }
65
-
66
- const logger = core.logging.getChildLogger({ module: "tlon-auto-reply" });
67
- const runtime: RuntimeEnv =
68
- opts.runtime ??
69
- createLoggerBackedRuntime({
70
- logger,
71
- });
72
-
73
- const account = resolveTlonAccount(cfg, opts.accountId ?? undefined);
74
- if (!account.enabled) {
75
- return;
76
- }
77
- if (!account.configured || !account.ship || !account.url || !account.code) {
78
- throw new Error("Tlon account not configured (ship/url/code required)");
79
- }
80
-
81
- const botShipName = normalizeShip(account.ship);
82
- runtime.log?.(`[tlon] Starting monitor for ${botShipName}`);
83
-
84
- const ssrfPolicy = ssrfPolicyFromDangerouslyAllowPrivateNetwork(
85
- account.dangerouslyAllowPrivateNetwork,
86
- );
87
-
88
- // Store validated values for use in closures (TypeScript narrowing doesn't propagate)
89
- const accountUrl = account.url;
90
- const accountCode = account.code;
91
-
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
- });
120
- }
121
- }
122
- }
123
-
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
- });
141
-
142
- const processedTracker = createProcessedMessageTracker(2000);
143
- let groupChannels: string[] = [];
144
- let botNickname: string | null = null;
145
-
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
- });
151
-
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 = {};
164
-
165
- // Track threads we've participated in (by parentId) - respond without mention requirement
166
- const participatedThreads = new Set<string>();
167
-
168
- // Track DM senders per session to detect shared sessions (security warning)
169
- const dmSendersBySession = new Map<string, Set<string>>();
170
- let sharedSessionWarningSent = false;
171
-
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}`);
180
- }
181
- }
182
- } catch (error: unknown) {
183
- runtime.log?.(`[tlon] Could not fetch nickname: ${formatErrorMessage(error)}`);
184
- }
185
-
186
- // Store init foreigns for processing after settings are loaded
187
- let initForeigns: Foreigns | null = null;
188
-
189
- // Migrate file config to settings store (seed on first run)
190
- async function migrateConfigToSettings() {
191
- const migrations = buildTlonSettingsMigrations(account, currentSettings);
192
-
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
- }
212
- }
213
- }
214
- }
215
-
216
- // Load settings from settings store (hot-reloadable config)
217
- try {
218
- currentSettings = await settingsManager.load();
219
-
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
- }
240
-
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;
247
- }
248
- initForeigns = initData.foreigns;
249
- } catch (error: unknown) {
250
- runtime.error?.(`[tlon] Auto-discovery failed: ${formatErrorMessage(error)}`);
251
- }
252
- }
253
-
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
- }
261
-
262
- // Also merge settings store groupChannels (may have been set via tlon settings command)
263
- groupChannels = mergeUniqueStrings(groupChannels, currentSettings.groupChannels);
264
-
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
- }
272
-
273
- // Check if a ship is the owner (always allowed to DM)
274
- function isOwner(ship: string): boolean {
275
- if (!effectiveOwnerShip) {
276
- return false;
277
- }
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
- }
297
-
298
- const processMessage = async (params: {
299
- messageId: string;
300
- senderShip: string;
301
- messageText: string;
302
- messageContent?: unknown; // Raw Tlon content for media extraction
303
- isGroup: boolean;
304
- channelNest?: string;
305
- hostShip?: string;
306
- channelName?: string;
307
- timestamp: number;
308
- parentId?: string | null;
309
- isThreadReply?: boolean;
310
- }) => {
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
324
- let messageText = params.messageText;
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
-
363
- if (isGroup && groupChannel && isSummarizationRequest(messageText)) {
364
- try {
365
- const history = await getChannelHistory(api, groupChannel, 50, runtime);
366
- if (history.length === 0) {
367
- const noHistoryMsg =
368
- "I couldn't fetch any messages for this channel. It might be empty or there might be a permissions issue.";
369
- if (isGroup) {
370
- const parsed = parseChannelNest(groupChannel);
371
- if (parsed) {
372
- await sendGroupMessage({
373
- api: api,
374
- fromShip: botShipName,
375
- hostShip: parsed.hostShip,
376
- channelName: parsed.channelName,
377
- text: noHistoryMsg,
378
- });
379
- }
380
- } else {
381
- await sendDm({
382
- api: api,
383
- fromShip: botShipName,
384
- toShip: senderShip,
385
- text: noHistoryMsg,
386
- });
387
- }
388
- return;
389
- }
390
-
391
- const historyText = history
392
- .map(
393
- (msg) => `[${new Date(msg.timestamp).toLocaleString()}] ${msg.author}: ${msg.content}`,
394
- )
395
- .join("\n");
396
-
397
- messageText =
398
- `Please summarize this channel conversation (${history.length} recent messages):\n\n${historyText}\n\n` +
399
- "Provide a concise summary highlighting:\n" +
400
- "1. Main topics discussed\n" +
401
- "2. Key decisions or conclusions\n" +
402
- "3. Action items if any\n" +
403
- "4. Notable participants";
404
- } catch (error: unknown) {
405
- const errorMsg = `Sorry, I encountered an error while fetching the channel history: ${formatErrorMessage(error)}`;
406
- if (isGroup && groupChannel) {
407
- const parsed = parseChannelNest(groupChannel);
408
- if (parsed) {
409
- await sendGroupMessage({
410
- api: api,
411
- fromShip: botShipName,
412
- hostShip: parsed.hostShip,
413
- channelName: parsed.channelName,
414
- text: errorMsg,
415
- });
416
- }
417
- } else {
418
- await sendDm({ api: api, fromShip: botShipName, toShip: senderShip, text: errorMsg });
419
- }
420
- return;
421
- }
422
- }
423
-
424
- const route = core.channel.routing.resolveAgentRoute({
425
- cfg,
426
- channel: "tlon",
427
- accountId: opts.accountId ?? undefined,
428
- peer: {
429
- kind: isGroup ? "group" : "direct",
430
- id: isGroup ? (groupChannel ?? senderShip) : senderShip,
431
- },
432
- });
433
-
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
-
510
- const body = core.channel.reply.formatAgentEnvelope({
511
- channel: "Tlon",
512
- from: fromLabel,
513
- timestamp,
514
- body: bodyWithAttachments,
515
- });
516
-
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
- },
571
- });
572
-
573
- const dispatchStartTime = Date.now();
574
-
575
- const responsePrefix = core.channel.reply.resolveEffectiveMessagesConfig(
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, {
581
- agentId: route.agentId,
582
- });
583
-
584
- await core.channel.turn.run({
585
- channel: "tlon",
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
- },
675
- });
676
- };
677
-
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) {
803
- return;
804
- }
805
-
806
- const rawText = extractMessageText(content.content);
807
- if (!rawText.trim()) {
808
- return;
809
- }
810
-
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}`);
1020
- return;
1021
- }
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,
1040
- });
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;
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
- });
1088
- },
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)}`);
1108
- },
1109
- quit: () => {
1110
- runtime.log?.("[tlon] Channels firehose subscription ended");
1111
- },
1112
- });
1113
- runtime.log?.("[tlon] Subscribed to channels firehose (/v2)");
1114
-
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)");
1128
-
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
- });
1196
-
1197
- try {
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)}`);
1202
- }
1203
-
1204
- // Subscribe to groups-ui for real-time channel additions (when invites are accepted)
1205
- try {
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
- }
1312
- },
1313
- err: (error) => {
1314
- runtime.error?.(`[tlon] Groups-ui subscription error: ${String(error)}`);
1315
- },
1316
- quit: () => {
1317
- runtime.log?.("[tlon] Groups-ui subscription ended");
1318
- },
1319
- });
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)}`);
1324
- }
1325
-
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;
1335
- }
1336
-
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
- }
1424
- }
1425
- };
1426
-
1427
- // Process existing pending invites from init data
1428
- if (initForeigns) {
1429
- await processPendingInvites(initForeigns);
1430
- }
1431
-
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)}`);
1459
- }
1460
- }
1461
-
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)`);
1469
- }
1470
-
1471
- // Log watched channels
1472
- for (const channelNest of watchedChannels) {
1473
- runtime.log?.(`[tlon] Watching channel: ${channelNest}`);
1474
- }
1475
-
1476
- runtime.log?.("[tlon] All subscriptions registered, connecting to SSE stream...");
1477
- await api.connect();
1478
- runtime.log?.("[tlon] Connected! Firehose subscriptions active");
1479
-
1480
- // Periodically refresh channel discovery
1481
- const pollInterval = setInterval(
1482
- async () => {
1483
- if (!opts.abortSignal?.aborted) {
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
- }
1497
- }
1498
- },
1499
- 2 * 60 * 1000,
1500
- );
1501
-
1502
- if (opts.abortSignal) {
1503
- const signal = opts.abortSignal;
1504
- await new Promise((resolve) => {
1505
- signal.addEventListener(
1506
- "abort",
1507
- () => {
1508
- clearInterval(pollInterval);
1509
- resolve(null);
1510
- },
1511
- { once: true },
1512
- );
1513
- });
1514
- } else {
1515
- await new Promise(() => {});
1516
- }
1517
- } finally {
1518
- try {
1519
- await api?.close();
1520
- } catch (error: unknown) {
1521
- runtime.error?.(`[tlon] Cleanup error: ${formatErrorMessage(error)}`);
1522
- }
1523
- }
1524
- }