@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
@@ -0,0 +1,3584 @@
1
+ import { n as createDedupeCache, s as createLoggerBackedRuntime } from "./runtime-api-C0hr1Rtn.js";
2
+ import { c as validateUrbitBaseUrl, d as formatTargetHint, f as normalizeShip, h as resolveTlonOutboundTarget, m as parseTlonTarget, p as parseChannelNest, s as normalizeUrbitHostname, u as resolveTlonAccount } from "./setup-core-BUkZJ-MU.js";
3
+ import { t as getTlonRuntime } from "./runtime-5FiW9E50.js";
4
+ import { t as tlonSetupWizard } from "./setup-surface-FxNMaluC.js";
5
+ import { fetchWithSsrFGuard, ssrfPolicyFromDangerouslyAllowPrivateNetwork } from "openclaw/plugin-sdk/ssrf-runtime";
6
+ import { normalizeLowercaseStringOrEmpty } from "openclaw/plugin-sdk/text-runtime";
7
+ import crypto, { randomBytes, randomUUID } from "node:crypto";
8
+ import { da, scot } from "@urbit/aura";
9
+ import { Readable } from "node:stream";
10
+ import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
11
+ import { mkdir, writeFile } from "node:fs/promises";
12
+ import * as path from "node:path";
13
+ import { MAX_IMAGE_BYTES, fetchRemoteMedia, saveMediaBuffer } from "openclaw/plugin-sdk/media-runtime";
14
+ import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
15
+ import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
16
+ //#region extensions/tlon/src/settings.ts
17
+ const SETTINGS_DESK = "moltbot";
18
+ const SETTINGS_BUCKET = "tlon";
19
+ /**
20
+ * Parse channelRules - handles both JSON string and object formats.
21
+ * Settings-store doesn't support nested objects, so we store as JSON string.
22
+ */
23
+ function parseChannelRules(value) {
24
+ if (!value) return;
25
+ if (typeof value === "string") try {
26
+ const parsed = JSON.parse(value);
27
+ if (isChannelRulesObject(parsed)) return parsed;
28
+ } catch {
29
+ return;
30
+ }
31
+ if (isChannelRulesObject(value)) return value;
32
+ }
33
+ /**
34
+ * Parse settings from the raw Urbit settings-store response.
35
+ * The response shape is: { [bucket]: { [key]: value } }
36
+ */
37
+ function parseSettingsResponse(raw) {
38
+ if (!raw || typeof raw !== "object") return {};
39
+ const bucket = raw[SETTINGS_BUCKET];
40
+ if (!bucket || typeof bucket !== "object") return {};
41
+ const settings = bucket;
42
+ return {
43
+ groupChannels: Array.isArray(settings.groupChannels) ? settings.groupChannels.filter((x) => typeof x === "string") : void 0,
44
+ dmAllowlist: Array.isArray(settings.dmAllowlist) ? settings.dmAllowlist.filter((x) => typeof x === "string") : void 0,
45
+ autoDiscover: typeof settings.autoDiscover === "boolean" ? settings.autoDiscover : void 0,
46
+ showModelSig: typeof settings.showModelSig === "boolean" ? settings.showModelSig : void 0,
47
+ autoAcceptDmInvites: typeof settings.autoAcceptDmInvites === "boolean" ? settings.autoAcceptDmInvites : void 0,
48
+ autoAcceptGroupInvites: typeof settings.autoAcceptGroupInvites === "boolean" ? settings.autoAcceptGroupInvites : void 0,
49
+ groupInviteAllowlist: Array.isArray(settings.groupInviteAllowlist) ? settings.groupInviteAllowlist.filter((x) => typeof x === "string") : void 0,
50
+ channelRules: parseChannelRules(settings.channelRules),
51
+ defaultAuthorizedShips: Array.isArray(settings.defaultAuthorizedShips) ? settings.defaultAuthorizedShips.filter((x) => typeof x === "string") : void 0,
52
+ ownerShip: typeof settings.ownerShip === "string" ? settings.ownerShip : void 0,
53
+ pendingApprovals: parsePendingApprovals(settings.pendingApprovals)
54
+ };
55
+ }
56
+ function isChannelRulesObject(val) {
57
+ if (!val || typeof val !== "object" || Array.isArray(val)) return false;
58
+ for (const [, rule] of Object.entries(val)) if (!rule || typeof rule !== "object") return false;
59
+ return true;
60
+ }
61
+ /**
62
+ * Parse pendingApprovals - handles both JSON string and array formats.
63
+ * Settings-store stores complex objects as JSON strings.
64
+ */
65
+ function parsePendingApprovals(value) {
66
+ if (!value) return;
67
+ let parsed = value;
68
+ if (typeof value === "string") try {
69
+ parsed = JSON.parse(value);
70
+ } catch {
71
+ return;
72
+ }
73
+ if (!Array.isArray(parsed)) return;
74
+ return parsed.filter((item) => {
75
+ if (!item || typeof item !== "object") return false;
76
+ const obj = item;
77
+ return typeof obj.id === "string" && (obj.type === "dm" || obj.type === "channel" || obj.type === "group") && typeof obj.requestingShip === "string" && typeof obj.timestamp === "number";
78
+ });
79
+ }
80
+ /**
81
+ * Parse a single settings entry update event.
82
+ */
83
+ function parseSettingsEvent(event) {
84
+ if (!event || typeof event !== "object") return null;
85
+ const evt = event;
86
+ if (evt["put-entry"]) {
87
+ const put = evt["put-entry"];
88
+ if (put.desk !== SETTINGS_DESK || put["bucket-key"] !== SETTINGS_BUCKET) return null;
89
+ return {
90
+ key: typeof put["entry-key"] === "string" ? put["entry-key"] : "",
91
+ value: put.value
92
+ };
93
+ }
94
+ if (evt["del-entry"]) {
95
+ const del = evt["del-entry"];
96
+ if (del.desk !== SETTINGS_DESK || del["bucket-key"] !== SETTINGS_BUCKET) return null;
97
+ return {
98
+ key: typeof del["entry-key"] === "string" ? del["entry-key"] : "",
99
+ value: void 0
100
+ };
101
+ }
102
+ return null;
103
+ }
104
+ /**
105
+ * Apply a single settings update to the current state.
106
+ */
107
+ function applySettingsUpdate(current, key, value) {
108
+ const next = { ...current };
109
+ switch (key) {
110
+ case "groupChannels":
111
+ next.groupChannels = Array.isArray(value) ? value.filter((x) => typeof x === "string") : void 0;
112
+ break;
113
+ case "dmAllowlist":
114
+ next.dmAllowlist = Array.isArray(value) ? value.filter((x) => typeof x === "string") : void 0;
115
+ break;
116
+ case "autoDiscover":
117
+ next.autoDiscover = typeof value === "boolean" ? value : void 0;
118
+ break;
119
+ case "showModelSig":
120
+ next.showModelSig = typeof value === "boolean" ? value : void 0;
121
+ break;
122
+ case "autoAcceptDmInvites":
123
+ next.autoAcceptDmInvites = typeof value === "boolean" ? value : void 0;
124
+ break;
125
+ case "autoAcceptGroupInvites":
126
+ next.autoAcceptGroupInvites = typeof value === "boolean" ? value : void 0;
127
+ break;
128
+ case "groupInviteAllowlist":
129
+ next.groupInviteAllowlist = Array.isArray(value) ? value.filter((x) => typeof x === "string") : void 0;
130
+ break;
131
+ case "channelRules":
132
+ next.channelRules = parseChannelRules(value);
133
+ break;
134
+ case "defaultAuthorizedShips":
135
+ next.defaultAuthorizedShips = Array.isArray(value) ? value.filter((x) => typeof x === "string") : void 0;
136
+ break;
137
+ case "ownerShip":
138
+ next.ownerShip = typeof value === "string" ? value : void 0;
139
+ break;
140
+ case "pendingApprovals":
141
+ next.pendingApprovals = parsePendingApprovals(value);
142
+ break;
143
+ }
144
+ return next;
145
+ }
146
+ /**
147
+ * Create a settings store subscription manager.
148
+ *
149
+ * Usage:
150
+ * const settings = createSettingsManager(api, logger);
151
+ * await settings.load();
152
+ * settings.subscribe((newSettings) => { ... });
153
+ */
154
+ function createSettingsManager(api, logger) {
155
+ let state = {
156
+ current: {},
157
+ loaded: false
158
+ };
159
+ const listeners = /* @__PURE__ */ new Set();
160
+ const notify = () => {
161
+ for (const listener of listeners) try {
162
+ listener(state.current);
163
+ } catch (err) {
164
+ logger?.error?.(`[settings] Listener error: ${String(err)}`);
165
+ }
166
+ };
167
+ return {
168
+ /**
169
+ * Get current settings (may be empty if not loaded yet).
170
+ */
171
+ get current() {
172
+ return state.current;
173
+ },
174
+ /**
175
+ * Whether initial settings have been loaded.
176
+ */
177
+ get loaded() {
178
+ return state.loaded;
179
+ },
180
+ /**
181
+ * Load initial settings via scry.
182
+ */
183
+ async load() {
184
+ try {
185
+ const deskData = (await api.scry("/settings/all.json"))?.all?.[SETTINGS_DESK];
186
+ state.current = parseSettingsResponse(deskData ?? {});
187
+ state.loaded = true;
188
+ logger?.log?.(`[settings] Loaded: ${JSON.stringify(state.current)}`);
189
+ return state.current;
190
+ } catch (err) {
191
+ logger?.log?.(`[settings] No settings found (using defaults): ${String(err)}`);
192
+ state.current = {};
193
+ state.loaded = true;
194
+ return state.current;
195
+ }
196
+ },
197
+ /**
198
+ * Subscribe to settings changes.
199
+ */
200
+ async startSubscription() {
201
+ await api.subscribe({
202
+ app: "settings",
203
+ path: "/desk/" + SETTINGS_DESK,
204
+ event: (event) => {
205
+ const update = parseSettingsEvent(event);
206
+ if (!update) return;
207
+ logger?.log?.(`[settings] Update: ${update.key} = ${JSON.stringify(update.value)}`);
208
+ state.current = applySettingsUpdate(state.current, update.key, update.value);
209
+ notify();
210
+ },
211
+ err: (error) => {
212
+ logger?.error?.(`[settings] Subscription error: ${String(error)}`);
213
+ },
214
+ quit: () => {
215
+ logger?.log?.("[settings] Subscription ended");
216
+ }
217
+ });
218
+ logger?.log?.("[settings] Subscribed to settings updates");
219
+ },
220
+ /**
221
+ * Register a listener for settings changes.
222
+ */
223
+ onChange(listener) {
224
+ listeners.add(listener);
225
+ return () => listeners.delete(listener);
226
+ }
227
+ };
228
+ }
229
+ //#endregion
230
+ //#region extensions/tlon/src/urbit/errors.ts
231
+ var UrbitError = class extends Error {
232
+ constructor(code, message, options) {
233
+ super(message, options);
234
+ this.name = "UrbitError";
235
+ this.code = code;
236
+ }
237
+ };
238
+ var UrbitUrlError = class extends UrbitError {
239
+ constructor(message, options) {
240
+ super("invalid_url", message, options);
241
+ this.name = "UrbitUrlError";
242
+ }
243
+ };
244
+ var UrbitHttpError = class extends UrbitError {
245
+ constructor(params) {
246
+ const suffix = params.bodyText ? ` - ${params.bodyText}` : "";
247
+ super("http_error", `${params.operation} failed: ${params.status}${suffix}`, { cause: params.cause });
248
+ this.name = "UrbitHttpError";
249
+ this.status = params.status;
250
+ this.operation = params.operation;
251
+ this.bodyText = params.bodyText;
252
+ }
253
+ };
254
+ var UrbitAuthError = class extends UrbitError {
255
+ constructor(code, message, options) {
256
+ super(code, message, options);
257
+ this.name = "UrbitAuthError";
258
+ }
259
+ };
260
+ //#endregion
261
+ //#region extensions/tlon/src/urbit/fetch.ts
262
+ async function urbitFetch(params) {
263
+ const validated = validateUrbitBaseUrl(params.baseUrl);
264
+ if (!validated.ok) throw new UrbitUrlError(validated.error);
265
+ return await fetchWithSsrFGuard({
266
+ url: new URL(params.path, validated.baseUrl).toString(),
267
+ fetchImpl: params.fetchImpl,
268
+ init: params.init,
269
+ timeoutMs: params.timeoutMs,
270
+ maxRedirects: params.maxRedirects,
271
+ signal: params.signal,
272
+ policy: params.ssrfPolicy,
273
+ lookupFn: params.lookupFn,
274
+ auditContext: params.auditContext,
275
+ pinDns: params.pinDns
276
+ });
277
+ }
278
+ //#endregion
279
+ //#region extensions/tlon/src/urbit/auth.ts
280
+ async function authenticate(url, code, options = {}) {
281
+ const { response, release } = await urbitFetch({
282
+ baseUrl: url,
283
+ path: "/~/login",
284
+ init: {
285
+ method: "POST",
286
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
287
+ body: new URLSearchParams({ password: code }).toString()
288
+ },
289
+ ssrfPolicy: options.ssrfPolicy,
290
+ lookupFn: options.lookupFn,
291
+ fetchImpl: options.fetchImpl,
292
+ timeoutMs: options.timeoutMs ?? 15e3,
293
+ maxRedirects: 3,
294
+ auditContext: "tlon-urbit-login"
295
+ });
296
+ try {
297
+ if (!response.ok) throw new UrbitAuthError("auth_failed", `Login failed with status ${response.status}`);
298
+ await response.text().catch(() => {});
299
+ const cookie = response.headers.get("set-cookie");
300
+ if (!cookie) throw new UrbitAuthError("missing_cookie", "No authentication cookie received");
301
+ return cookie;
302
+ } finally {
303
+ await release();
304
+ }
305
+ }
306
+ //#endregion
307
+ //#region extensions/tlon/src/urbit/context.ts
308
+ function resolveShipFromHostname(hostname) {
309
+ const trimmed = normalizeUrbitHostname(hostname);
310
+ if (!trimmed) return "";
311
+ if (trimmed.includes(".")) return trimmed.split(".")[0] ?? trimmed;
312
+ return trimmed;
313
+ }
314
+ function normalizeUrbitShip(ship, hostname) {
315
+ return (ship?.replace(/^~/, "") ?? resolveShipFromHostname(hostname)).trim();
316
+ }
317
+ function normalizeUrbitCookie(cookie) {
318
+ return cookie.split(";")[0] ?? cookie;
319
+ }
320
+ function getUrbitContext(url, ship) {
321
+ const validated = validateUrbitBaseUrl(url);
322
+ if (!validated.ok) throw new UrbitUrlError(validated.error);
323
+ return {
324
+ baseUrl: validated.baseUrl,
325
+ hostname: validated.hostname,
326
+ ship: normalizeUrbitShip(ship, validated.hostname)
327
+ };
328
+ }
329
+ /**
330
+ * Get the default SSRF policy for image uploads.
331
+ * Uses a restrictive policy that blocks private networks by default.
332
+ */
333
+ function getDefaultSsrFPolicy() {}
334
+ //#endregion
335
+ //#region extensions/tlon/src/urbit/story.ts
336
+ /**
337
+ * Parse inline markdown formatting (bold, italic, code, links, mentions)
338
+ */
339
+ function parseInlineMarkdown(text) {
340
+ const result = [];
341
+ let remaining = text;
342
+ while (remaining.length > 0) {
343
+ const shipMatch = remaining.match(/^(~[a-z][-a-z0-9]*)/);
344
+ if (shipMatch) {
345
+ result.push({ ship: shipMatch[1] });
346
+ remaining = remaining.slice(shipMatch[0].length);
347
+ continue;
348
+ }
349
+ const boldMatch = remaining.match(/^\*\*(.+?)\*\*|^__(.+?)__/);
350
+ if (boldMatch) {
351
+ const content = boldMatch[1] || boldMatch[2];
352
+ result.push({ bold: parseInlineMarkdown(content) });
353
+ remaining = remaining.slice(boldMatch[0].length);
354
+ continue;
355
+ }
356
+ const italicsMatch = remaining.match(/^\*([^*]+?)\*|^_([^_]+?)_(?![a-zA-Z0-9])/);
357
+ if (italicsMatch) {
358
+ const content = italicsMatch[1] || italicsMatch[2];
359
+ result.push({ italics: parseInlineMarkdown(content) });
360
+ remaining = remaining.slice(italicsMatch[0].length);
361
+ continue;
362
+ }
363
+ const strikeMatch = remaining.match(/^~~(.+?)~~/);
364
+ if (strikeMatch) {
365
+ result.push({ strike: parseInlineMarkdown(strikeMatch[1]) });
366
+ remaining = remaining.slice(strikeMatch[0].length);
367
+ continue;
368
+ }
369
+ const codeMatch = remaining.match(/^`([^`]+)`/);
370
+ if (codeMatch) {
371
+ result.push({ "inline-code": codeMatch[1] });
372
+ remaining = remaining.slice(codeMatch[0].length);
373
+ continue;
374
+ }
375
+ const linkMatch = remaining.match(/^\[([^\]]+)\]\(([^)]+)\)/);
376
+ if (linkMatch) {
377
+ result.push({ link: {
378
+ href: linkMatch[2],
379
+ content: linkMatch[1]
380
+ } });
381
+ remaining = remaining.slice(linkMatch[0].length);
382
+ continue;
383
+ }
384
+ const imageMatch = remaining.match(/^!\[([^\]]*)\]\(([^)]+)\)/);
385
+ if (imageMatch) {
386
+ result.push({ __image: {
387
+ src: imageMatch[2],
388
+ alt: imageMatch[1]
389
+ } });
390
+ remaining = remaining.slice(imageMatch[0].length);
391
+ continue;
392
+ }
393
+ const urlMatch = remaining.match(/^(https?:\/\/[^\s<>"\]]+)/);
394
+ if (urlMatch) {
395
+ result.push({ link: {
396
+ href: urlMatch[1],
397
+ content: urlMatch[1]
398
+ } });
399
+ remaining = remaining.slice(urlMatch[0].length);
400
+ continue;
401
+ }
402
+ const plainMatch = remaining.match(/^[^*_`~[#~\n:/]+/);
403
+ if (plainMatch) {
404
+ result.push(plainMatch[0]);
405
+ remaining = remaining.slice(plainMatch[0].length);
406
+ continue;
407
+ }
408
+ result.push(remaining[0]);
409
+ remaining = remaining.slice(1);
410
+ }
411
+ return mergeAdjacentStrings(result);
412
+ }
413
+ /**
414
+ * Merge adjacent string elements in an inline array
415
+ */
416
+ function mergeAdjacentStrings(inlines) {
417
+ const result = [];
418
+ for (const item of inlines) if (typeof item === "string" && typeof result[result.length - 1] === "string") result[result.length - 1] = result[result.length - 1] + item;
419
+ else result.push(item);
420
+ return result;
421
+ }
422
+ /**
423
+ * Create an image block
424
+ */
425
+ function createImageBlock(src, alt = "", height = 0, width = 0) {
426
+ return { block: { image: {
427
+ src,
428
+ height,
429
+ width,
430
+ alt
431
+ } } };
432
+ }
433
+ /**
434
+ * Check if URL looks like an image
435
+ */
436
+ function isImageUrl(url) {
437
+ return /\.(jpg|jpeg|png|gif|webp|svg|bmp|ico)(\?.*)?$/i.test(url);
438
+ }
439
+ /**
440
+ * Process inlines and extract any image markers into blocks
441
+ */
442
+ function processInlinesForImages(inlines) {
443
+ const cleanInlines = [];
444
+ const imageBlocks = [];
445
+ for (const inline of inlines) if (typeof inline === "object" && "__image" in inline) {
446
+ const img = inline.__image;
447
+ imageBlocks.push(createImageBlock(img.src, img.alt));
448
+ } else cleanInlines.push(inline);
449
+ return {
450
+ inlines: cleanInlines,
451
+ imageBlocks
452
+ };
453
+ }
454
+ /**
455
+ * Convert markdown text to Tlon story format
456
+ */
457
+ function markdownToStory(markdown) {
458
+ const story = [];
459
+ const lines = markdown.split("\n");
460
+ let i = 0;
461
+ while (i < lines.length) {
462
+ const line = lines[i];
463
+ if (line.startsWith("```")) {
464
+ const lang = line.slice(3).trim() || "plaintext";
465
+ const codeLines = [];
466
+ i++;
467
+ while (i < lines.length && !lines[i].startsWith("```")) {
468
+ codeLines.push(lines[i]);
469
+ i++;
470
+ }
471
+ story.push({ block: { code: {
472
+ code: codeLines.join("\n"),
473
+ lang
474
+ } } });
475
+ i++;
476
+ continue;
477
+ }
478
+ const headerMatch = line.match(/^(#{1,6})\s+(.+)$/);
479
+ if (headerMatch) {
480
+ const tag = `h${headerMatch[1].length}`;
481
+ story.push({ block: { header: {
482
+ tag,
483
+ content: parseInlineMarkdown(headerMatch[2])
484
+ } } });
485
+ i++;
486
+ continue;
487
+ }
488
+ if (/^(-{3,}|\*{3,})$/.test(line.trim())) {
489
+ story.push({ block: { rule: null } });
490
+ i++;
491
+ continue;
492
+ }
493
+ if (line.startsWith("> ")) {
494
+ const quoteLines = [];
495
+ while (i < lines.length && lines[i].startsWith("> ")) {
496
+ quoteLines.push(lines[i].slice(2));
497
+ i++;
498
+ }
499
+ const quoteText = quoteLines.join("\n");
500
+ story.push({ inline: [{ blockquote: parseInlineMarkdown(quoteText) }] });
501
+ continue;
502
+ }
503
+ if (line.trim() === "") {
504
+ i++;
505
+ continue;
506
+ }
507
+ const paragraphLines = [];
508
+ while (i < lines.length && lines[i].trim() !== "" && !lines[i].startsWith("#") && !lines[i].startsWith("```") && !lines[i].startsWith("> ") && !/^(-{3,}|\*{3,})$/.test(lines[i].trim())) {
509
+ paragraphLines.push(lines[i]);
510
+ i++;
511
+ }
512
+ if (paragraphLines.length > 0) {
513
+ const inlines = parseInlineMarkdown(paragraphLines.join("\n"));
514
+ const withBreaks = [];
515
+ for (const inline of inlines) if (typeof inline === "string" && inline.includes("\n")) {
516
+ const parts = inline.split("\n");
517
+ for (let j = 0; j < parts.length; j++) {
518
+ if (parts[j]) withBreaks.push(parts[j]);
519
+ if (j < parts.length - 1) withBreaks.push({ break: null });
520
+ }
521
+ } else withBreaks.push(inline);
522
+ const { inlines: cleanInlines, imageBlocks } = processInlinesForImages(withBreaks);
523
+ if (cleanInlines.length > 0) story.push({ inline: cleanInlines });
524
+ story.push(...imageBlocks);
525
+ }
526
+ }
527
+ return story;
528
+ }
529
+ //#endregion
530
+ //#region extensions/tlon/src/urbit/send.ts
531
+ async function sendDm({ api, fromShip, toShip, text }) {
532
+ return sendDmWithStory({
533
+ api,
534
+ fromShip,
535
+ toShip,
536
+ story: markdownToStory(text)
537
+ });
538
+ }
539
+ async function sendDmWithStory({ api, fromShip, toShip, story }) {
540
+ const sentAt = Date.now();
541
+ const id = `${fromShip}/${scot("ud", da.fromUnix(sentAt))}`;
542
+ const action = {
543
+ ship: toShip,
544
+ diff: {
545
+ id,
546
+ delta: { add: {
547
+ memo: {
548
+ content: story,
549
+ author: fromShip,
550
+ sent: sentAt
551
+ },
552
+ kind: null,
553
+ time: null
554
+ } }
555
+ }
556
+ };
557
+ await api.poke({
558
+ app: "chat",
559
+ mark: "chat-dm-action",
560
+ json: action
561
+ });
562
+ return {
563
+ channel: "tlon",
564
+ messageId: id
565
+ };
566
+ }
567
+ async function sendGroupMessage({ api, fromShip, hostShip, channelName, text, replyToId }) {
568
+ return sendGroupMessageWithStory({
569
+ api,
570
+ fromShip,
571
+ hostShip,
572
+ channelName,
573
+ story: markdownToStory(text),
574
+ replyToId
575
+ });
576
+ }
577
+ async function sendGroupMessageWithStory({ api, fromShip, hostShip, channelName, story, replyToId }) {
578
+ const sentAt = Date.now();
579
+ let formattedReplyId = replyToId;
580
+ if (replyToId && /^\d+$/.test(replyToId)) try {
581
+ formattedReplyId = scot("ud", BigInt(replyToId));
582
+ } catch {}
583
+ const action = { channel: {
584
+ nest: `chat/${hostShip}/${channelName}`,
585
+ action: formattedReplyId ? { post: { reply: {
586
+ id: formattedReplyId,
587
+ action: { add: {
588
+ content: story,
589
+ author: fromShip,
590
+ sent: sentAt
591
+ } }
592
+ } } } : { post: { add: {
593
+ content: story,
594
+ author: fromShip,
595
+ sent: sentAt,
596
+ kind: "/chat",
597
+ blob: null,
598
+ meta: null
599
+ } } }
600
+ } };
601
+ await api.poke({
602
+ app: "channels",
603
+ mark: "channel-action-1",
604
+ json: action
605
+ });
606
+ return {
607
+ channel: "tlon",
608
+ messageId: `${fromShip}/${sentAt}`
609
+ };
610
+ }
611
+ /**
612
+ * Build a story with text and optional media (image)
613
+ */
614
+ function buildMediaStory(text, mediaUrl) {
615
+ const story = [];
616
+ const cleanText = text?.trim() ?? "";
617
+ const cleanUrl = mediaUrl?.trim() ?? "";
618
+ if (cleanText) story.push(...markdownToStory(cleanText));
619
+ if (cleanUrl && isImageUrl(cleanUrl)) story.push(createImageBlock(cleanUrl, ""));
620
+ else if (cleanUrl) story.push({ inline: [{ link: {
621
+ href: cleanUrl,
622
+ content: cleanUrl
623
+ } }] });
624
+ return story.length > 0 ? story : [{ inline: [""] }];
625
+ }
626
+ //#endregion
627
+ //#region extensions/tlon/src/urbit/channel-ops.ts
628
+ async function putUrbitChannel(deps, params) {
629
+ return await urbitFetch({
630
+ baseUrl: deps.baseUrl,
631
+ path: `/~/channel/${deps.channelId}`,
632
+ init: {
633
+ method: "PUT",
634
+ headers: {
635
+ "Content-Type": "application/json",
636
+ Cookie: deps.cookie
637
+ },
638
+ body: JSON.stringify(params.body)
639
+ },
640
+ ssrfPolicy: deps.ssrfPolicy,
641
+ lookupFn: deps.lookupFn,
642
+ fetchImpl: deps.fetchImpl,
643
+ timeoutMs: 3e4,
644
+ auditContext: params.auditContext
645
+ });
646
+ }
647
+ async function pokeUrbitChannel(deps, params) {
648
+ const pokeId = Date.now();
649
+ const { response, release } = await putUrbitChannel(deps, {
650
+ body: [{
651
+ id: pokeId,
652
+ action: "poke",
653
+ ship: deps.ship,
654
+ app: params.app,
655
+ mark: params.mark,
656
+ json: params.json
657
+ }],
658
+ auditContext: params.auditContext
659
+ });
660
+ try {
661
+ if (!response.ok && response.status !== 204) {
662
+ const errorText = await response.text().catch(() => "");
663
+ throw new Error(`Poke failed: ${response.status}${errorText ? ` - ${errorText}` : ""}`);
664
+ }
665
+ return pokeId;
666
+ } finally {
667
+ await release();
668
+ }
669
+ }
670
+ async function scryUrbitPath(deps, params) {
671
+ const scryPath = `/~/scry${params.path}`;
672
+ const { response, release } = await urbitFetch({
673
+ baseUrl: deps.baseUrl,
674
+ path: scryPath,
675
+ init: {
676
+ method: "GET",
677
+ headers: { Cookie: deps.cookie }
678
+ },
679
+ ssrfPolicy: deps.ssrfPolicy,
680
+ lookupFn: deps.lookupFn,
681
+ fetchImpl: deps.fetchImpl,
682
+ timeoutMs: 3e4,
683
+ auditContext: params.auditContext
684
+ });
685
+ try {
686
+ if (!response.ok) throw new Error(`Scry failed: ${response.status} for path ${params.path}`);
687
+ return await response.json();
688
+ } finally {
689
+ await release();
690
+ }
691
+ }
692
+ async function createUrbitChannel(deps, params) {
693
+ const { response, release } = await putUrbitChannel(deps, params);
694
+ try {
695
+ if (!response.ok && response.status !== 204) throw new UrbitHttpError({
696
+ operation: "Channel creation",
697
+ status: response.status
698
+ });
699
+ } finally {
700
+ await release();
701
+ }
702
+ }
703
+ async function wakeUrbitChannel(deps) {
704
+ const { response, release } = await putUrbitChannel(deps, {
705
+ body: [{
706
+ id: Date.now(),
707
+ action: "poke",
708
+ ship: deps.ship,
709
+ app: "hood",
710
+ mark: "helm-hi",
711
+ json: "Opening API channel"
712
+ }],
713
+ auditContext: "tlon-urbit-channel-wake"
714
+ });
715
+ try {
716
+ if (!response.ok && response.status !== 204) throw new UrbitHttpError({
717
+ operation: "Channel activation",
718
+ status: response.status
719
+ });
720
+ } finally {
721
+ await release();
722
+ }
723
+ }
724
+ async function ensureUrbitChannelOpen(deps, params) {
725
+ await createUrbitChannel(deps, {
726
+ body: params.createBody,
727
+ auditContext: params.createAuditContext
728
+ });
729
+ await wakeUrbitChannel(deps);
730
+ }
731
+ //#endregion
732
+ //#region extensions/tlon/src/urbit/sse-client.ts
733
+ var UrbitSSEClient = class {
734
+ constructor(url, cookie, options = {}) {
735
+ this.subscriptions = [];
736
+ this.eventHandlers = /* @__PURE__ */ new Map();
737
+ this.aborted = false;
738
+ this.streamController = null;
739
+ this.reconnectAttempts = 0;
740
+ this.isConnected = false;
741
+ this.streamRelease = null;
742
+ this.lastHeardEventId = -1;
743
+ this.lastAcknowledgedEventId = -1;
744
+ this.ackThreshold = 20;
745
+ const ctx = getUrbitContext(url, options.ship);
746
+ this.url = ctx.baseUrl;
747
+ this.cookie = normalizeUrbitCookie(cookie);
748
+ this.ship = ctx.ship;
749
+ this.channelId = `${Math.floor(Date.now() / 1e3)}-${randomUUID()}`;
750
+ this.channelUrl = new URL(`/~/channel/${this.channelId}`, this.url).toString();
751
+ this.onReconnect = options.onReconnect ?? null;
752
+ this.autoReconnect = options.autoReconnect !== false;
753
+ this.maxReconnectAttempts = options.maxReconnectAttempts ?? 10;
754
+ this.reconnectDelay = options.reconnectDelay ?? 1e3;
755
+ this.maxReconnectDelay = options.maxReconnectDelay ?? 3e4;
756
+ this.logger = options.logger ?? {};
757
+ this.ssrfPolicy = options.ssrfPolicy;
758
+ this.lookupFn = options.lookupFn;
759
+ this.fetchImpl = options.fetchImpl;
760
+ }
761
+ channelRequestContext() {
762
+ return {
763
+ baseUrl: this.url,
764
+ cookie: this.cookie,
765
+ ship: this.ship,
766
+ channelId: this.channelId,
767
+ ssrfPolicy: this.ssrfPolicy,
768
+ lookupFn: this.lookupFn,
769
+ fetchImpl: this.fetchImpl
770
+ };
771
+ }
772
+ async subscribe(params) {
773
+ const subId = this.subscriptions.length + 1;
774
+ const subscription = {
775
+ id: subId,
776
+ action: "subscribe",
777
+ ship: this.ship,
778
+ app: params.app,
779
+ path: params.path
780
+ };
781
+ this.subscriptions.push(subscription);
782
+ this.eventHandlers.set(subId, {
783
+ event: params.event,
784
+ err: params.err,
785
+ quit: params.quit
786
+ });
787
+ if (this.isConnected) try {
788
+ await this.sendSubscription(subscription);
789
+ } catch (error) {
790
+ this.eventHandlers.get(subId)?.err?.(error);
791
+ }
792
+ return subId;
793
+ }
794
+ async sendSubscription(subscription) {
795
+ const { response, release } = await this.putChannelPayload([subscription], {
796
+ timeoutMs: 3e4,
797
+ auditContext: "tlon-urbit-subscribe"
798
+ });
799
+ try {
800
+ if (!response.ok && response.status !== 204) {
801
+ const errorText = await response.text().catch(() => "");
802
+ throw new Error(`Subscribe failed: ${response.status}${errorText ? ` - ${errorText}` : ""}`);
803
+ }
804
+ } finally {
805
+ await release();
806
+ }
807
+ }
808
+ async connect() {
809
+ await ensureUrbitChannelOpen(this.channelRequestContext(), {
810
+ createBody: this.subscriptions,
811
+ createAuditContext: "tlon-urbit-channel-create"
812
+ });
813
+ await this.openStream();
814
+ this.isConnected = true;
815
+ this.reconnectAttempts = 0;
816
+ }
817
+ async openStream() {
818
+ const controller = new AbortController();
819
+ const timeoutId = setTimeout(() => controller.abort(), 6e4);
820
+ this.streamController = controller;
821
+ const { response, release } = await urbitFetch({
822
+ baseUrl: this.url,
823
+ path: `/~/channel/${this.channelId}`,
824
+ init: {
825
+ method: "GET",
826
+ headers: {
827
+ Accept: "text/event-stream",
828
+ Cookie: this.cookie
829
+ }
830
+ },
831
+ ssrfPolicy: this.ssrfPolicy,
832
+ lookupFn: this.lookupFn,
833
+ fetchImpl: this.fetchImpl,
834
+ signal: controller.signal,
835
+ auditContext: "tlon-urbit-sse-stream"
836
+ });
837
+ this.streamRelease = release;
838
+ clearTimeout(timeoutId);
839
+ if (!response.ok) {
840
+ await release();
841
+ this.streamRelease = null;
842
+ throw new Error(`Stream connection failed: ${response.status}`);
843
+ }
844
+ this.processStream(response.body).catch((error) => {
845
+ if (!this.aborted) {
846
+ this.logger.error?.(`Stream error: ${String(error)}`);
847
+ for (const { err } of this.eventHandlers.values()) if (err) err(error);
848
+ }
849
+ });
850
+ }
851
+ async processStream(body) {
852
+ if (!body) return;
853
+ const stream = body instanceof ReadableStream ? Readable.fromWeb(body) : body;
854
+ let buffer = "";
855
+ try {
856
+ for await (const chunk of stream) {
857
+ if (this.aborted) break;
858
+ buffer += chunk.toString();
859
+ let eventEnd;
860
+ while ((eventEnd = buffer.indexOf("\n\n")) !== -1) {
861
+ const eventData = buffer.slice(0, eventEnd);
862
+ buffer = buffer.slice(eventEnd + 2);
863
+ this.processEvent(eventData);
864
+ }
865
+ }
866
+ } finally {
867
+ if (this.streamRelease) {
868
+ const release = this.streamRelease;
869
+ this.streamRelease = null;
870
+ await release();
871
+ }
872
+ this.streamController = null;
873
+ if (!this.aborted && this.autoReconnect) {
874
+ this.isConnected = false;
875
+ this.logger.log?.("[SSE] Stream ended, attempting reconnection...");
876
+ await this.attemptReconnect();
877
+ }
878
+ }
879
+ }
880
+ processEvent(eventData) {
881
+ const lines = eventData.split("\n");
882
+ let data = null;
883
+ let eventId = null;
884
+ for (const line of lines) {
885
+ if (line.startsWith("id: ")) eventId = Number.parseInt(line.slice(4), 10);
886
+ if (line.startsWith("data: ")) data = line.slice(6);
887
+ }
888
+ if (!data) return;
889
+ if (eventId !== null && !Number.isNaN(eventId)) {
890
+ if (eventId > this.lastHeardEventId) {
891
+ this.lastHeardEventId = eventId;
892
+ if (eventId - this.lastAcknowledgedEventId > this.ackThreshold) {
893
+ this.logger.log?.(`[SSE] Acking event ${eventId} (last acked: ${this.lastAcknowledgedEventId})`);
894
+ this.ack(eventId).catch((err) => {
895
+ this.logger.error?.(`Failed to ack event ${eventId}: ${String(err)}`);
896
+ });
897
+ }
898
+ }
899
+ }
900
+ try {
901
+ const parsed = JSON.parse(data);
902
+ if (parsed.response === "quit") {
903
+ if (parsed.id) {
904
+ const handlers = this.eventHandlers.get(parsed.id);
905
+ if (handlers?.quit) handlers.quit();
906
+ }
907
+ return;
908
+ }
909
+ if (parsed.id && this.eventHandlers.has(parsed.id)) {
910
+ const { event } = this.eventHandlers.get(parsed.id) ?? {};
911
+ if (event && parsed.json) event(parsed.json);
912
+ } else if (parsed.json) {
913
+ for (const { event } of this.eventHandlers.values()) if (event) event(parsed.json);
914
+ }
915
+ } catch (error) {
916
+ this.logger.error?.(`Error parsing SSE event: ${String(error)}`);
917
+ }
918
+ }
919
+ async poke(params) {
920
+ return await pokeUrbitChannel(this.channelRequestContext(), {
921
+ ...params,
922
+ auditContext: "tlon-urbit-poke"
923
+ });
924
+ }
925
+ async scry(path) {
926
+ return await scryUrbitPath({
927
+ baseUrl: this.url,
928
+ cookie: this.cookie,
929
+ ssrfPolicy: this.ssrfPolicy,
930
+ lookupFn: this.lookupFn,
931
+ fetchImpl: this.fetchImpl
932
+ }, {
933
+ path,
934
+ auditContext: "tlon-urbit-scry"
935
+ });
936
+ }
937
+ /**
938
+ * Update the cookie used for authentication.
939
+ * Call this when re-authenticating after session expiry.
940
+ */
941
+ updateCookie(newCookie) {
942
+ this.cookie = normalizeUrbitCookie(newCookie);
943
+ }
944
+ async ack(eventId) {
945
+ this.lastAcknowledgedEventId = eventId;
946
+ const ackData = {
947
+ id: Date.now(),
948
+ action: "ack",
949
+ "event-id": eventId
950
+ };
951
+ const { response, release } = await this.putChannelPayload([ackData], {
952
+ timeoutMs: 1e4,
953
+ auditContext: "tlon-urbit-ack"
954
+ });
955
+ try {
956
+ if (!response.ok) throw new Error(`Ack failed with status ${response.status}`);
957
+ } finally {
958
+ await release();
959
+ }
960
+ }
961
+ async attemptReconnect() {
962
+ if (this.aborted || !this.autoReconnect) {
963
+ this.logger.log?.("[SSE] Reconnection aborted or disabled");
964
+ return;
965
+ }
966
+ if (this.reconnectAttempts >= this.maxReconnectAttempts) {
967
+ this.logger.log?.(`[SSE] Max reconnection attempts (${this.maxReconnectAttempts}) reached. Waiting 10s before resetting...`);
968
+ const extendedBackoff = 1e4;
969
+ await new Promise((resolve) => setTimeout(resolve, extendedBackoff));
970
+ this.reconnectAttempts = 0;
971
+ this.logger.log?.("[SSE] Reconnection attempts reset, resuming reconnection...");
972
+ }
973
+ this.reconnectAttempts += 1;
974
+ const delay = Math.min(this.reconnectDelay * 2 ** (this.reconnectAttempts - 1), this.maxReconnectDelay);
975
+ this.logger.log?.(`[SSE] Reconnection attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts} in ${delay}ms...`);
976
+ await new Promise((resolve) => setTimeout(resolve, delay));
977
+ try {
978
+ this.channelId = `${Math.floor(Date.now() / 1e3)}-${randomUUID()}`;
979
+ this.channelUrl = new URL(`/~/channel/${this.channelId}`, this.url).toString();
980
+ if (this.onReconnect) await this.onReconnect(this);
981
+ await this.connect();
982
+ this.logger.log?.("[SSE] Reconnection successful!");
983
+ } catch (error) {
984
+ this.logger.error?.(`[SSE] Reconnection failed: ${String(error)}`);
985
+ await this.attemptReconnect();
986
+ }
987
+ }
988
+ async close() {
989
+ this.aborted = true;
990
+ this.isConnected = false;
991
+ this.streamController?.abort();
992
+ try {
993
+ const unsubscribes = this.subscriptions.map((sub) => ({
994
+ id: sub.id,
995
+ action: "unsubscribe",
996
+ subscription: sub.id
997
+ }));
998
+ {
999
+ const { response, release } = await this.putChannelPayload(unsubscribes, {
1000
+ timeoutMs: 3e4,
1001
+ auditContext: "tlon-urbit-unsubscribe"
1002
+ });
1003
+ try {
1004
+ response.body?.cancel();
1005
+ } finally {
1006
+ await release();
1007
+ }
1008
+ }
1009
+ {
1010
+ const { response, release } = await urbitFetch({
1011
+ baseUrl: this.url,
1012
+ path: `/~/channel/${this.channelId}`,
1013
+ init: {
1014
+ method: "DELETE",
1015
+ headers: { Cookie: this.cookie }
1016
+ },
1017
+ ssrfPolicy: this.ssrfPolicy,
1018
+ lookupFn: this.lookupFn,
1019
+ fetchImpl: this.fetchImpl,
1020
+ timeoutMs: 3e4,
1021
+ auditContext: "tlon-urbit-channel-close"
1022
+ });
1023
+ try {
1024
+ response.body?.cancel();
1025
+ } finally {
1026
+ await release();
1027
+ }
1028
+ }
1029
+ } catch (error) {
1030
+ this.logger.error?.(`Error closing channel: ${String(error)}`);
1031
+ }
1032
+ if (this.streamRelease) {
1033
+ const release = this.streamRelease;
1034
+ this.streamRelease = null;
1035
+ await release();
1036
+ }
1037
+ }
1038
+ async putChannelPayload(payload, params) {
1039
+ return await urbitFetch({
1040
+ baseUrl: this.url,
1041
+ path: `/~/channel/${this.channelId}`,
1042
+ init: {
1043
+ method: "PUT",
1044
+ headers: {
1045
+ "Content-Type": "application/json",
1046
+ Cookie: this.cookie
1047
+ },
1048
+ body: JSON.stringify(payload)
1049
+ },
1050
+ ssrfPolicy: this.ssrfPolicy,
1051
+ lookupFn: this.lookupFn,
1052
+ fetchImpl: this.fetchImpl,
1053
+ timeoutMs: params.timeoutMs,
1054
+ auditContext: params.auditContext
1055
+ });
1056
+ }
1057
+ };
1058
+ //#endregion
1059
+ //#region extensions/tlon/src/monitor/approval.ts
1060
+ /**
1061
+ * Approval system for managing DM, channel mention, and group invite approvals.
1062
+ *
1063
+ * When an unknown ship tries to interact with the bot, the owner receives
1064
+ * a notification and can approve or deny the request.
1065
+ */
1066
+ function normalizeLowercaseStringOrEmpty$1(value) {
1067
+ return typeof value === "string" ? value.trim().toLowerCase() : "";
1068
+ }
1069
+ /**
1070
+ * Generate a unique approval ID in the format: {type}-{timestamp}-{shortHash}
1071
+ */
1072
+ function generateApprovalId(type) {
1073
+ return `${type}-${Date.now()}-${randomBytes(3).toString("hex")}`;
1074
+ }
1075
+ /**
1076
+ * Create a pending approval object.
1077
+ */
1078
+ function createPendingApproval(params) {
1079
+ return {
1080
+ id: generateApprovalId(params.type),
1081
+ type: params.type,
1082
+ requestingShip: params.requestingShip,
1083
+ channelNest: params.channelNest,
1084
+ groupFlag: params.groupFlag,
1085
+ messagePreview: params.messagePreview,
1086
+ originalMessage: params.originalMessage,
1087
+ timestamp: Date.now()
1088
+ };
1089
+ }
1090
+ /**
1091
+ * Truncate text to a maximum length with ellipsis.
1092
+ */
1093
+ function truncate(text, maxLength) {
1094
+ if (text.length <= maxLength) return text;
1095
+ return text.slice(0, maxLength - 3) + "...";
1096
+ }
1097
+ /**
1098
+ * Format a notification message for the owner about a pending approval.
1099
+ */
1100
+ function formatApprovalRequest(approval) {
1101
+ const preview = approval.messagePreview ? `\n"${truncate(approval.messagePreview, 100)}"` : "";
1102
+ switch (approval.type) {
1103
+ case "dm": return `New DM request from ${approval.requestingShip}:${preview}\n\nReply "approve", "deny", or "block" (ID: ${approval.id})`;
1104
+ case "channel": return `${approval.requestingShip} mentioned you in ${approval.channelNest}:${preview}\n\nReply "approve", "deny", or "block"\n(ID: ${approval.id})`;
1105
+ case "group": return `Group invite from ${approval.requestingShip} to join ${approval.groupFlag}\n\nReply "approve", "deny", or "block"\n(ID: ${approval.id})`;
1106
+ }
1107
+ throw new Error("Unsupported approval type");
1108
+ }
1109
+ /**
1110
+ * Parse an owner's response to an approval request.
1111
+ * Supports formats:
1112
+ * - "approve" / "deny" / "block" (applies to most recent pending)
1113
+ * - "approve dm-1234567890-abc" / "deny dm-1234567890-abc" (specific ID)
1114
+ * - "block" permanently blocks the ship via Tlon's native blocking
1115
+ */
1116
+ function parseApprovalResponse(text) {
1117
+ const match = normalizeLowercaseStringOrEmpty$1(text).match(/^(approve|deny|block)(?:\s+(.+))?$/);
1118
+ if (!match) return null;
1119
+ return {
1120
+ action: match[1],
1121
+ id: match[2]?.trim()
1122
+ };
1123
+ }
1124
+ /**
1125
+ * Check if a message text looks like an approval response.
1126
+ * Used to determine if we should intercept the message before normal processing.
1127
+ */
1128
+ function isApprovalResponse(text) {
1129
+ const trimmed = normalizeLowercaseStringOrEmpty$1(text);
1130
+ return trimmed.startsWith("approve") || trimmed.startsWith("deny") || trimmed.startsWith("block");
1131
+ }
1132
+ /**
1133
+ * Find a pending approval by ID, or return the most recent if no ID specified.
1134
+ */
1135
+ function findPendingApproval(pendingApprovals, id) {
1136
+ if (id) return pendingApprovals.find((a) => a.id === id);
1137
+ return pendingApprovals[pendingApprovals.length - 1];
1138
+ }
1139
+ /**
1140
+ * Remove a pending approval from the list by ID.
1141
+ */
1142
+ function removePendingApproval(pendingApprovals, id) {
1143
+ return pendingApprovals.filter((a) => a.id !== id);
1144
+ }
1145
+ /**
1146
+ * Format a confirmation message after an approval action.
1147
+ */
1148
+ function formatApprovalConfirmation(approval, action) {
1149
+ if (action === "block") return `Blocked ${approval.requestingShip}. They will no longer be able to contact the bot.`;
1150
+ const actionText = action === "approve" ? "Approved" : "Denied";
1151
+ switch (approval.type) {
1152
+ case "dm":
1153
+ if (action === "approve") return `${actionText} DM access for ${approval.requestingShip}. They can now message the bot.`;
1154
+ return `${actionText} DM request from ${approval.requestingShip}.`;
1155
+ case "channel":
1156
+ if (action === "approve") return `${actionText} ${approval.requestingShip} for ${approval.channelNest}. They can now interact in this channel.`;
1157
+ return `${actionText} ${approval.requestingShip} for ${approval.channelNest}.`;
1158
+ case "group":
1159
+ if (action === "approve") return `${actionText} group invite from ${approval.requestingShip} to ${approval.groupFlag}. Joining group...`;
1160
+ return `${actionText} group invite from ${approval.requestingShip} to ${approval.groupFlag}.`;
1161
+ }
1162
+ throw new Error("Unsupported approval type");
1163
+ }
1164
+ /**
1165
+ * Parse an admin command from owner message.
1166
+ * Supports:
1167
+ * - "unblock ~ship" - unblock a specific ship
1168
+ * - "blocked" - list all blocked ships
1169
+ * - "pending" - list all pending approvals
1170
+ */
1171
+ function parseAdminCommand(text) {
1172
+ const trimmed = normalizeLowercaseStringOrEmpty$1(text);
1173
+ if (trimmed === "blocked") return { type: "blocked" };
1174
+ if (trimmed === "pending") return { type: "pending" };
1175
+ const unblockMatch = trimmed.match(/^unblock\s+(~[\w-]+)$/);
1176
+ if (unblockMatch) return {
1177
+ type: "unblock",
1178
+ ship: unblockMatch[1]
1179
+ };
1180
+ return null;
1181
+ }
1182
+ /**
1183
+ * Check if a message text looks like an admin command.
1184
+ */
1185
+ function isAdminCommand(text) {
1186
+ return parseAdminCommand(text) !== null;
1187
+ }
1188
+ /**
1189
+ * Format the list of blocked ships for display to owner.
1190
+ */
1191
+ function formatBlockedList(ships) {
1192
+ if (ships.length === 0) return "No ships are currently blocked.";
1193
+ return `Blocked ships (${ships.length}):\n${ships.map((s) => `• ${s}`).join("\n")}`;
1194
+ }
1195
+ /**
1196
+ * Format the list of pending approvals for display to owner.
1197
+ */
1198
+ function formatPendingList(approvals) {
1199
+ if (approvals.length === 0) return "No pending approval requests.";
1200
+ return `Pending approvals (${approvals.length}):\n${approvals.map((a) => `• ${a.id}: ${a.type} from ${a.requestingShip}`).join("\n")}`;
1201
+ }
1202
+ //#endregion
1203
+ //#region extensions/tlon/src/monitor/approval-runtime.ts
1204
+ function createTlonApprovalRuntime(params) {
1205
+ const { api, runtime, botShipName, getPendingApprovals, setPendingApprovals, getCurrentSettings, setCurrentSettings, getEffectiveDmAllowlist, setEffectiveDmAllowlist, getEffectiveOwnerShip, processApprovedMessage, refreshWatchedChannels } = params;
1206
+ const savePendingApprovals = async () => {
1207
+ try {
1208
+ await api.poke({
1209
+ app: "settings",
1210
+ mark: "settings-event",
1211
+ json: { "put-entry": {
1212
+ desk: "moltbot",
1213
+ "bucket-key": "tlon",
1214
+ "entry-key": "pendingApprovals",
1215
+ value: JSON.stringify(getPendingApprovals())
1216
+ } }
1217
+ });
1218
+ } catch (err) {
1219
+ runtime.error?.(`[tlon] Failed to save pending approvals: ${String(err)}`);
1220
+ }
1221
+ };
1222
+ const addToDmAllowlist = async (ship) => {
1223
+ const normalizedShip = normalizeShip(ship);
1224
+ const nextAllowlist = getEffectiveDmAllowlist().includes(normalizedShip) ? getEffectiveDmAllowlist() : [...getEffectiveDmAllowlist(), normalizedShip];
1225
+ setEffectiveDmAllowlist(nextAllowlist);
1226
+ try {
1227
+ await api.poke({
1228
+ app: "settings",
1229
+ mark: "settings-event",
1230
+ json: { "put-entry": {
1231
+ desk: "moltbot",
1232
+ "bucket-key": "tlon",
1233
+ "entry-key": "dmAllowlist",
1234
+ value: nextAllowlist
1235
+ } }
1236
+ });
1237
+ runtime.log?.(`[tlon] Added ${normalizedShip} to dmAllowlist`);
1238
+ } catch (err) {
1239
+ runtime.error?.(`[tlon] Failed to update dmAllowlist: ${String(err)}`);
1240
+ }
1241
+ };
1242
+ const addToChannelAllowlist = async (ship, channelNest) => {
1243
+ const normalizedShip = normalizeShip(ship);
1244
+ const currentSettings = getCurrentSettings();
1245
+ const channelRules = currentSettings.channelRules ?? {};
1246
+ const rule = channelRules[channelNest] ?? {
1247
+ mode: "restricted",
1248
+ allowedShips: []
1249
+ };
1250
+ const allowedShips = [...rule.allowedShips ?? []];
1251
+ if (!allowedShips.includes(normalizedShip)) allowedShips.push(normalizedShip);
1252
+ const updatedRules = {
1253
+ ...channelRules,
1254
+ [channelNest]: {
1255
+ ...rule,
1256
+ allowedShips
1257
+ }
1258
+ };
1259
+ setCurrentSettings({
1260
+ ...currentSettings,
1261
+ channelRules: updatedRules
1262
+ });
1263
+ try {
1264
+ await api.poke({
1265
+ app: "settings",
1266
+ mark: "settings-event",
1267
+ json: { "put-entry": {
1268
+ desk: "moltbot",
1269
+ "bucket-key": "tlon",
1270
+ "entry-key": "channelRules",
1271
+ value: JSON.stringify(updatedRules)
1272
+ } }
1273
+ });
1274
+ runtime.log?.(`[tlon] Added ${normalizedShip} to ${channelNest} allowlist`);
1275
+ } catch (err) {
1276
+ runtime.error?.(`[tlon] Failed to update channelRules: ${String(err)}`);
1277
+ }
1278
+ };
1279
+ const blockShip = async (ship) => {
1280
+ const normalizedShip = normalizeShip(ship);
1281
+ try {
1282
+ await api.poke({
1283
+ app: "chat",
1284
+ mark: "chat-block-ship",
1285
+ json: { ship: normalizedShip }
1286
+ });
1287
+ runtime.log?.(`[tlon] Blocked ship ${normalizedShip}`);
1288
+ } catch (err) {
1289
+ runtime.error?.(`[tlon] Failed to block ship ${normalizedShip}: ${String(err)}`);
1290
+ }
1291
+ };
1292
+ const isShipBlocked = async (ship) => {
1293
+ const normalizedShip = normalizeShip(ship);
1294
+ try {
1295
+ const blocked = await api.scry("/chat/blocked.json");
1296
+ return Array.isArray(blocked) && blocked.some((item) => normalizeShip(item) === normalizedShip);
1297
+ } catch (err) {
1298
+ runtime.log?.(`[tlon] Failed to check blocked list: ${String(err)}`);
1299
+ return false;
1300
+ }
1301
+ };
1302
+ const getBlockedShips = async () => {
1303
+ try {
1304
+ const blocked = await api.scry("/chat/blocked.json");
1305
+ return Array.isArray(blocked) ? blocked : [];
1306
+ } catch (err) {
1307
+ runtime.log?.(`[tlon] Failed to get blocked list: ${String(err)}`);
1308
+ return [];
1309
+ }
1310
+ };
1311
+ const unblockShip = async (ship) => {
1312
+ const normalizedShip = normalizeShip(ship);
1313
+ try {
1314
+ await api.poke({
1315
+ app: "chat",
1316
+ mark: "chat-unblock-ship",
1317
+ json: { ship: normalizedShip }
1318
+ });
1319
+ runtime.log?.(`[tlon] Unblocked ship ${normalizedShip}`);
1320
+ return true;
1321
+ } catch (err) {
1322
+ runtime.error?.(`[tlon] Failed to unblock ship ${normalizedShip}: ${String(err)}`);
1323
+ return false;
1324
+ }
1325
+ };
1326
+ const sendOwnerNotification = async (message) => {
1327
+ const ownerShip = getEffectiveOwnerShip();
1328
+ if (!ownerShip) {
1329
+ runtime.log?.("[tlon] No ownerShip configured, cannot send notification");
1330
+ return;
1331
+ }
1332
+ try {
1333
+ await sendDm({
1334
+ api,
1335
+ fromShip: botShipName,
1336
+ toShip: ownerShip,
1337
+ text: message
1338
+ });
1339
+ runtime.log?.(`[tlon] Sent notification to owner ${ownerShip}`);
1340
+ } catch (err) {
1341
+ runtime.error?.(`[tlon] Failed to send notification to owner: ${String(err)}`);
1342
+ }
1343
+ };
1344
+ const queueApprovalRequest = async (approval) => {
1345
+ if (await isShipBlocked(approval.requestingShip)) {
1346
+ runtime.log?.(`[tlon] Ignoring request from blocked ship ${approval.requestingShip}`);
1347
+ return;
1348
+ }
1349
+ const approvals = getPendingApprovals();
1350
+ const existingIndex = approvals.findIndex((item) => item.type === approval.type && item.requestingShip === approval.requestingShip && (approval.type !== "channel" || item.channelNest === approval.channelNest) && (approval.type !== "group" || item.groupFlag === approval.groupFlag));
1351
+ if (existingIndex !== -1) {
1352
+ const existing = approvals[existingIndex];
1353
+ if (approval.originalMessage) {
1354
+ existing.originalMessage = approval.originalMessage;
1355
+ existing.messagePreview = approval.messagePreview;
1356
+ }
1357
+ runtime.log?.(`[tlon] Updated existing approval for ${approval.requestingShip} (${approval.type}) - re-sending notification`);
1358
+ await savePendingApprovals();
1359
+ await sendOwnerNotification(formatApprovalRequest(existing));
1360
+ return;
1361
+ }
1362
+ setPendingApprovals([...approvals, approval]);
1363
+ await savePendingApprovals();
1364
+ await sendOwnerNotification(formatApprovalRequest(approval));
1365
+ runtime.log?.(`[tlon] Queued approval request: ${approval.id} (${approval.type} from ${approval.requestingShip})`);
1366
+ };
1367
+ const handleApprovalResponse = async (text) => {
1368
+ const parsed = parseApprovalResponse(text);
1369
+ if (!parsed) return false;
1370
+ const approval = findPendingApproval(getPendingApprovals(), parsed.id);
1371
+ if (!approval) {
1372
+ await sendOwnerNotification(`No pending approval found${parsed.id ? ` for ID: ${parsed.id}` : ""}`);
1373
+ return true;
1374
+ }
1375
+ if (parsed.action === "approve") {
1376
+ switch (approval.type) {
1377
+ case "dm":
1378
+ await addToDmAllowlist(approval.requestingShip);
1379
+ if (approval.originalMessage) {
1380
+ runtime.log?.(`[tlon] Processing original message from ${approval.requestingShip} after approval`);
1381
+ await processApprovedMessage(approval);
1382
+ }
1383
+ break;
1384
+ case "channel":
1385
+ if (approval.channelNest) {
1386
+ await addToChannelAllowlist(approval.requestingShip, approval.channelNest);
1387
+ if (approval.originalMessage) {
1388
+ runtime.log?.(`[tlon] Processing original message from ${approval.requestingShip} in ${approval.channelNest} after approval`);
1389
+ await processApprovedMessage(approval);
1390
+ }
1391
+ }
1392
+ break;
1393
+ case "group":
1394
+ if (approval.groupFlag) try {
1395
+ await api.poke({
1396
+ app: "groups",
1397
+ mark: "group-join",
1398
+ json: {
1399
+ flag: approval.groupFlag,
1400
+ "join-all": true
1401
+ }
1402
+ });
1403
+ runtime.log?.(`[tlon] Joined group ${approval.groupFlag} after approval`);
1404
+ setTimeout(() => {
1405
+ (async () => {
1406
+ try {
1407
+ const newCount = await refreshWatchedChannels();
1408
+ if (newCount > 0) runtime.log?.(`[tlon] Discovered ${newCount} new channel(s) after joining group`);
1409
+ } catch (err) {
1410
+ runtime.log?.(`[tlon] Channel discovery after group join failed: ${String(err)}`);
1411
+ }
1412
+ })();
1413
+ }, 2e3);
1414
+ } catch (err) {
1415
+ runtime.error?.(`[tlon] Failed to join group ${approval.groupFlag}: ${String(err)}`);
1416
+ }
1417
+ break;
1418
+ }
1419
+ await sendOwnerNotification(formatApprovalConfirmation(approval, "approve"));
1420
+ } else if (parsed.action === "block") {
1421
+ await blockShip(approval.requestingShip);
1422
+ await sendOwnerNotification(formatApprovalConfirmation(approval, "block"));
1423
+ } else await sendOwnerNotification(formatApprovalConfirmation(approval, "deny"));
1424
+ setPendingApprovals(removePendingApproval(getPendingApprovals(), approval.id));
1425
+ await savePendingApprovals();
1426
+ return true;
1427
+ };
1428
+ const handleAdminCommand = async (text) => {
1429
+ const command = parseAdminCommand(text);
1430
+ if (!command) return false;
1431
+ switch (command.type) {
1432
+ case "blocked": {
1433
+ const blockedShips = await getBlockedShips();
1434
+ await sendOwnerNotification(formatBlockedList(blockedShips));
1435
+ runtime.log?.(`[tlon] Owner requested blocked ships list (${blockedShips.length} ships)`);
1436
+ return true;
1437
+ }
1438
+ case "pending":
1439
+ await sendOwnerNotification(formatPendingList(getPendingApprovals()));
1440
+ runtime.log?.(`[tlon] Owner requested pending approvals list (${getPendingApprovals().length} pending)`);
1441
+ return true;
1442
+ case "unblock": {
1443
+ const shipToUnblock = command.ship;
1444
+ if (!await isShipBlocked(shipToUnblock)) {
1445
+ await sendOwnerNotification(`${shipToUnblock} is not blocked.`);
1446
+ return true;
1447
+ }
1448
+ await sendOwnerNotification(await unblockShip(shipToUnblock) ? `Unblocked ${shipToUnblock}.` : `Failed to unblock ${shipToUnblock}.`);
1449
+ return true;
1450
+ }
1451
+ }
1452
+ throw new Error("Unsupported Tlon admin command");
1453
+ };
1454
+ return {
1455
+ queueApprovalRequest,
1456
+ handleApprovalResponse,
1457
+ handleAdminCommand
1458
+ };
1459
+ }
1460
+ //#endregion
1461
+ //#region extensions/tlon/src/monitor/authorization.ts
1462
+ function resolveChannelAuthorization(cfg, channelNest, settings) {
1463
+ const tlonConfig = cfg.channels?.tlon;
1464
+ const fileRules = tlonConfig?.authorization?.channelRules ?? {};
1465
+ const rule = (settings?.channelRules ?? {})[channelNest] ?? fileRules[channelNest];
1466
+ const defaultShips = settings?.defaultAuthorizedShips ?? tlonConfig?.defaultAuthorizedShips ?? [];
1467
+ return {
1468
+ mode: rule?.mode ?? "restricted",
1469
+ allowedShips: rule?.allowedShips ?? defaultShips
1470
+ };
1471
+ }
1472
+ //#endregion
1473
+ //#region extensions/tlon/src/monitor/utils.ts
1474
+ function extractCites(content) {
1475
+ if (!content || !Array.isArray(content)) return [];
1476
+ const cites = [];
1477
+ for (const verse of content) if (verse?.block?.cite && typeof verse.block.cite === "object") {
1478
+ const cite = verse.block.cite;
1479
+ if (cite.chan && typeof cite.chan === "object") {
1480
+ const { nest, where } = cite.chan;
1481
+ const whereMatch = where?.match(/\/msg\/(~[a-z-]+)\/(.+)/);
1482
+ cites.push({
1483
+ type: "chan",
1484
+ nest,
1485
+ where,
1486
+ author: whereMatch?.[1],
1487
+ postId: whereMatch?.[2]
1488
+ });
1489
+ } else if (cite.group && typeof cite.group === "string") cites.push({
1490
+ type: "group",
1491
+ group: cite.group
1492
+ });
1493
+ else if (cite.desk && typeof cite.desk === "object") cites.push({
1494
+ type: "desk",
1495
+ flag: cite.desk.flag,
1496
+ where: cite.desk.where
1497
+ });
1498
+ else if (cite.bait && typeof cite.bait === "object") cites.push({
1499
+ type: "bait",
1500
+ group: cite.bait.group,
1501
+ nest: cite.bait.graph,
1502
+ where: cite.bait.where
1503
+ });
1504
+ }
1505
+ return cites;
1506
+ }
1507
+ function formatModelName(modelString) {
1508
+ if (!modelString) return "AI";
1509
+ const modelName = modelString.includes("/") ? modelString.split("/")[1] : modelString;
1510
+ const modelMappings = {
1511
+ "claude-opus-4-5": "Claude Opus 4.5",
1512
+ "claude-sonnet-4-5": "Claude Sonnet 4.5",
1513
+ "claude-sonnet-3-5": "Claude Sonnet 3.5",
1514
+ "gpt-4o": "GPT-4o",
1515
+ "gpt-4-turbo": "GPT-4 Turbo",
1516
+ "gpt-4": "GPT-4",
1517
+ "gemini-2.0-flash": "Gemini 2.0 Flash",
1518
+ "gemini-pro": "Gemini Pro"
1519
+ };
1520
+ if (modelMappings[modelName]) return modelMappings[modelName];
1521
+ return modelName.replace(/-/g, " ").split(" ").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
1522
+ }
1523
+ function isBotMentioned(messageText, botShipName, nickname) {
1524
+ if (!messageText || !botShipName) return false;
1525
+ if (/@all\b/i.test(messageText)) return true;
1526
+ const escapedShip = normalizeShip(botShipName).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1527
+ if (new RegExp(`(^|\\s)${escapedShip}(?=\\s|$)`, "i").test(messageText)) return true;
1528
+ if (nickname) {
1529
+ const escapedNickname = nickname.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1530
+ if (new RegExp(`(^|\\s)${escapedNickname}(?=\\s|$|[,!?.])`, "i").test(messageText)) return true;
1531
+ }
1532
+ return false;
1533
+ }
1534
+ /**
1535
+ * Strip bot ship mention from message text for command detection.
1536
+ * "~bot-ship /status" → "/status"
1537
+ */
1538
+ function stripBotMention(messageText, botShipName) {
1539
+ if (!messageText || !botShipName) return messageText;
1540
+ return messageText.replace(normalizeShip(botShipName), "").trim();
1541
+ }
1542
+ function isDmAllowed(senderShip, allowlist) {
1543
+ if (!allowlist || allowlist.length === 0) return false;
1544
+ const normalizedSender = normalizeShip(senderShip);
1545
+ return allowlist.map((ship) => normalizeShip(ship)).some((ship) => ship === normalizedSender);
1546
+ }
1547
+ /**
1548
+ * Check if a group invite from a ship should be auto-accepted.
1549
+ *
1550
+ * SECURITY: Fail-safe to deny. If allowlist is empty or undefined,
1551
+ * ALL invites are rejected - even if autoAcceptGroupInvites is enabled.
1552
+ * This prevents misconfigured bots from accepting malicious invites.
1553
+ */
1554
+ function isGroupInviteAllowed(inviterShip, allowlist) {
1555
+ if (!allowlist || allowlist.length === 0) return false;
1556
+ const normalizedInviter = normalizeShip(inviterShip);
1557
+ return allowlist.map((ship) => normalizeShip(ship)).some((ship) => ship === normalizedInviter);
1558
+ }
1559
+ /**
1560
+ * Resolve quoted/cited content only after the caller has passed authorization.
1561
+ * Unauthorized paths must keep raw text and must not trigger cross-channel cite fetches.
1562
+ */
1563
+ async function resolveAuthorizedMessageText(params) {
1564
+ const { rawText, content, authorizedForCites, resolveAllCites } = params;
1565
+ if (!authorizedForCites) return rawText;
1566
+ return await resolveAllCites(content) + rawText;
1567
+ }
1568
+ const asRecord = asNullableObjectRecord;
1569
+ const formatErrorMessage$1 = formatErrorMessage;
1570
+ const readString = readStringField;
1571
+ function asNullableObjectRecord(value) {
1572
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
1573
+ }
1574
+ function readStringField(record, field) {
1575
+ const value = record?.[field];
1576
+ return typeof value === "string" ? value : void 0;
1577
+ }
1578
+ function renderInlineItem(item, options) {
1579
+ if (typeof item === "string") return item;
1580
+ const record = asRecord(item);
1581
+ if (!record) return "";
1582
+ const ship = readString(record, "ship");
1583
+ if (ship) return ship;
1584
+ if ("sect" in record) {
1585
+ const sect = record.sect;
1586
+ if (typeof sect === "string") return `@${sect || "all"}`;
1587
+ if (sect === null) return "@all";
1588
+ }
1589
+ if (options?.allowBreak && "break" in record) return "\n";
1590
+ const inlineCode = readString(record, "inline-code");
1591
+ if (inlineCode) return `\`${inlineCode}\``;
1592
+ const code = readString(record, "code");
1593
+ if (code) return `\`${code}\``;
1594
+ const link = asRecord(record.link);
1595
+ const linkHref = link ? readString(link, "href") : void 0;
1596
+ if (link && linkHref) {
1597
+ const linkContent = readString(link, "content");
1598
+ return options?.linkMode === "href" ? linkHref : linkContent || linkHref;
1599
+ }
1600
+ if (Array.isArray(record.bold)) return `**${extractInlineText(record.bold)}**`;
1601
+ if (Array.isArray(record.italics)) return `*${extractInlineText(record.italics)}*`;
1602
+ if (Array.isArray(record.strike)) return `~~${extractInlineText(record.strike)}~~`;
1603
+ if (options?.allowBlockquote && Array.isArray(record.blockquote)) return `> ${extractInlineText(record.blockquote)}`;
1604
+ return "";
1605
+ }
1606
+ function extractInlineText(items) {
1607
+ return items.map((item) => renderInlineItem(item)).join("");
1608
+ }
1609
+ function extractMessageText(content) {
1610
+ if (!content || !Array.isArray(content)) return "";
1611
+ return content.map((verse) => {
1612
+ const verseRecord = asRecord(verse);
1613
+ if (!verseRecord) return "";
1614
+ if (Array.isArray(verseRecord.inline)) return verseRecord.inline.map((item) => renderInlineItem(item, {
1615
+ linkMode: "href",
1616
+ allowBreak: true,
1617
+ allowBlockquote: true
1618
+ })).join("");
1619
+ const block = asRecord(verseRecord.block);
1620
+ if (block) {
1621
+ const image = asRecord(block.image);
1622
+ if (image) {
1623
+ const imageSrc = readString(image, "src");
1624
+ if (imageSrc) {
1625
+ const altText = readString(image, "alt");
1626
+ return `\n${imageSrc}${altText ? ` (${altText})` : ""}\n`;
1627
+ }
1628
+ }
1629
+ const codeBlock = asRecord(block.code);
1630
+ if (codeBlock) return `\n\`\`\`${readString(codeBlock, "lang") ?? ""}\n${readString(codeBlock, "code") ?? ""}\n\`\`\`\n`;
1631
+ const header = asRecord(block.header);
1632
+ if (header) return `\n## ${(Array.isArray(header.content) ? header.content : []).map((item) => typeof item === "string" ? item : "").join("") || ""}\n`;
1633
+ const cite = asRecord(block.cite);
1634
+ if (cite) {
1635
+ const chanCite = asRecord(cite.chan);
1636
+ if (chanCite) {
1637
+ const nest = readString(chanCite, "nest");
1638
+ const whereMatch = readString(chanCite, "where")?.match(/\/msg\/(~[a-z-]+)\/(.+)/);
1639
+ if (whereMatch) {
1640
+ const [, author, _postId] = whereMatch;
1641
+ return `\n> [quoted: ${author} in ${nest}]\n`;
1642
+ }
1643
+ return `\n> [quoted from ${nest}]\n`;
1644
+ }
1645
+ const group = readString(cite, "group");
1646
+ if (group) return `\n> [ref: group ${group}]\n`;
1647
+ const desk = asRecord(cite.desk);
1648
+ if (desk) {
1649
+ const flag = readString(desk, "flag");
1650
+ if (flag) return `\n> [ref: ${flag}]\n`;
1651
+ }
1652
+ const bait = asRecord(cite.bait);
1653
+ if (bait) {
1654
+ const graph = readString(bait, "graph");
1655
+ const groupName = readString(bait, "group");
1656
+ if (graph && groupName) return `\n> [ref: ${graph} in ${groupName}]\n`;
1657
+ }
1658
+ return `\n> [quoted message]\n`;
1659
+ }
1660
+ }
1661
+ return "";
1662
+ }).join("\n").trim();
1663
+ }
1664
+ function isSummarizationRequest(messageText) {
1665
+ return [
1666
+ /summarize\s+(this\s+)?(channel|chat|conversation)/i,
1667
+ /what\s+did\s+i\s+miss/i,
1668
+ /catch\s+me\s+up/i,
1669
+ /channel\s+summary/i,
1670
+ /tldr/i
1671
+ ].some((pattern) => pattern.test(messageText));
1672
+ }
1673
+ //#endregion
1674
+ //#region extensions/tlon/src/monitor/cites.ts
1675
+ function createTlonCitationResolver(params) {
1676
+ const { api, runtime } = params;
1677
+ const resolveCiteContent = async (cite) => {
1678
+ if (cite.type !== "chan" || !cite.nest || !cite.postId) return null;
1679
+ try {
1680
+ const scryPath = `/channels/v4/${cite.nest}/posts/post/${cite.postId}.json`;
1681
+ runtime.log?.(`[tlon] Fetching cited post: ${scryPath}`);
1682
+ const essay = asRecord(asRecord(await api.scry(scryPath))?.essay);
1683
+ if (essay?.content) return extractMessageText(essay.content) || null;
1684
+ return null;
1685
+ } catch (err) {
1686
+ runtime.log?.(`[tlon] Failed to fetch cited post: ${String(err)}`);
1687
+ return null;
1688
+ }
1689
+ };
1690
+ const resolveAllCites = async (content) => {
1691
+ const cites = extractCites(content);
1692
+ if (cites.length === 0) return "";
1693
+ const resolved = [];
1694
+ for (const cite of cites) {
1695
+ const text = await resolveCiteContent(cite);
1696
+ if (text) resolved.push(`> ${cite.author || "unknown"} wrote: ${text}`);
1697
+ }
1698
+ return resolved.length > 0 ? `${resolved.join("\n")}\n\n` : "";
1699
+ };
1700
+ return {
1701
+ resolveCiteContent,
1702
+ resolveAllCites
1703
+ };
1704
+ }
1705
+ //#endregion
1706
+ //#region extensions/tlon/src/monitor/discovery.ts
1707
+ /**
1708
+ * Fetch groups-ui init data, returning channels and foreigns.
1709
+ * This is a single scry that provides both channel discovery and pending invites.
1710
+ */
1711
+ async function fetchInitData(api, runtime) {
1712
+ try {
1713
+ runtime.log?.("[tlon] Fetching groups-ui init data...");
1714
+ const initData = asRecord(await api.scry("/groups-ui/v6/init.json"));
1715
+ const channels = [];
1716
+ const groups = asRecord(initData?.groups);
1717
+ if (groups) for (const groupData of Object.values(groups)) {
1718
+ const groupChannels = asRecord(asRecord(groupData)?.channels);
1719
+ if (groupChannels) {
1720
+ for (const channelNest of Object.keys(groupChannels)) if (channelNest.startsWith("chat/")) channels.push(channelNest);
1721
+ }
1722
+ }
1723
+ if (channels.length > 0) runtime.log?.(`[tlon] Auto-discovered ${channels.length} chat channel(s)`);
1724
+ else runtime.log?.("[tlon] No chat channels found via auto-discovery");
1725
+ const foreignsValue = asRecord(initData?.foreigns);
1726
+ const foreigns = foreignsValue ? foreignsValue : null;
1727
+ if (foreigns) {
1728
+ const pendingCount = Object.values(foreigns).filter((f) => f.invites?.some((i) => i.valid)).length;
1729
+ if (pendingCount > 0) runtime.log?.(`[tlon] Found ${pendingCount} pending group invite(s)`);
1730
+ }
1731
+ return {
1732
+ channels,
1733
+ foreigns
1734
+ };
1735
+ } catch (error) {
1736
+ runtime.log?.(`[tlon] Init data fetch failed: ${formatErrorMessage$1(error)}`);
1737
+ return {
1738
+ channels: [],
1739
+ foreigns: null
1740
+ };
1741
+ }
1742
+ }
1743
+ async function fetchAllChannels(api, runtime) {
1744
+ const { channels } = await fetchInitData(api, runtime);
1745
+ return channels;
1746
+ }
1747
+ //#endregion
1748
+ //#region extensions/tlon/src/monitor/history.ts
1749
+ /**
1750
+ * Format a number as @ud (with dots every 3 digits from the right)
1751
+ * e.g., 170141184507799509469114119040828178432 -> 170.141.184.507.799.509.469.114.119.040.828.178.432
1752
+ */
1753
+ function formatUd(id) {
1754
+ const reversed = String(id).replace(/\./g, "").split("").toReversed();
1755
+ const chunks = [];
1756
+ for (let i = 0; i < reversed.length; i += 3) chunks.push(reversed.slice(i, i + 3).toReversed().join(""));
1757
+ return chunks.toReversed().join(".");
1758
+ }
1759
+ function createHistoryEntryFromMemo(params) {
1760
+ const { memo, seal, fallbackId } = params;
1761
+ return {
1762
+ author: typeof memo?.author === "string" ? memo.author : "unknown",
1763
+ content: extractMessageText(memo?.content || []),
1764
+ timestamp: typeof memo?.sent === "number" ? memo.sent : Date.now(),
1765
+ id: typeof seal?.id === "string" ? seal.id : typeof fallbackId === "string" ? fallbackId : void 0
1766
+ };
1767
+ }
1768
+ const messageCache = /* @__PURE__ */ new Map();
1769
+ const MAX_CACHED_MESSAGES = 100;
1770
+ function cacheMessage(channelNest, message) {
1771
+ if (!messageCache.has(channelNest)) messageCache.set(channelNest, []);
1772
+ const cache = messageCache.get(channelNest);
1773
+ if (!cache) return;
1774
+ cache.unshift(message);
1775
+ if (cache.length > MAX_CACHED_MESSAGES) cache.pop();
1776
+ }
1777
+ async function fetchChannelHistory(api, channelNest, count = 50, runtime) {
1778
+ try {
1779
+ const scryPath = `/channels/v4/${channelNest}/posts/newest/${count}/outline.json`;
1780
+ runtime?.log?.(`[tlon] Fetching history: ${scryPath}`);
1781
+ const data = await api.scry(scryPath);
1782
+ if (!data) return [];
1783
+ let posts = [];
1784
+ if (Array.isArray(data)) posts = data;
1785
+ else {
1786
+ const dataRecord = asRecord(data);
1787
+ const postMap = asRecord(dataRecord?.posts);
1788
+ if (postMap) posts = Object.values(postMap);
1789
+ else if (dataRecord) posts = Object.values(dataRecord);
1790
+ }
1791
+ const messages = posts.map((item) => {
1792
+ const itemRecord = asRecord(item);
1793
+ const replyPostSet = asRecord(asRecord(itemRecord?.["r-post"])?.set);
1794
+ const essay = asRecord(itemRecord?.essay) ?? asRecord(replyPostSet?.essay);
1795
+ const seal = asRecord(itemRecord?.seal) ?? asRecord(replyPostSet?.seal);
1796
+ return {
1797
+ author: typeof essay?.author === "string" ? essay.author : "unknown",
1798
+ content: extractMessageText(essay?.content || []),
1799
+ timestamp: typeof essay?.sent === "number" ? essay.sent : Date.now(),
1800
+ id: typeof seal?.id === "string" ? seal.id : void 0
1801
+ };
1802
+ }).filter((msg) => msg.content);
1803
+ runtime?.log?.(`[tlon] Extracted ${messages.length} messages from history`);
1804
+ return messages;
1805
+ } catch (error) {
1806
+ runtime?.log?.(`[tlon] Error fetching channel history: ${formatErrorMessage$1(error)}`);
1807
+ return [];
1808
+ }
1809
+ }
1810
+ async function getChannelHistory(api, channelNest, count = 50, runtime) {
1811
+ const cache = messageCache.get(channelNest) ?? [];
1812
+ if (cache.length >= count) {
1813
+ runtime?.log?.(`[tlon] Using cached messages (${cache.length} available)`);
1814
+ return cache.slice(0, count);
1815
+ }
1816
+ runtime?.log?.(`[tlon] Cache has ${cache.length} messages, need ${count}, fetching from scry...`);
1817
+ return await fetchChannelHistory(api, channelNest, count, runtime);
1818
+ }
1819
+ /**
1820
+ * Fetch thread/reply history for a specific parent post.
1821
+ * Used to get context when entering a thread conversation.
1822
+ */
1823
+ async function fetchThreadHistory(api, channelNest, parentId, count = 50, runtime) {
1824
+ try {
1825
+ const formattedParentId = formatUd(parentId);
1826
+ runtime?.log?.(`[tlon] Thread history - parentId: ${parentId} -> formatted: ${formattedParentId}`);
1827
+ const scryPath = `/channels/v4/${channelNest}/posts/post/id/${formattedParentId}/replies/newest/${count}.json`;
1828
+ runtime?.log?.(`[tlon] Fetching thread history: ${scryPath}`);
1829
+ const data = await api.scry(scryPath);
1830
+ if (!data) {
1831
+ runtime?.log?.(`[tlon] No thread history data returned`);
1832
+ return [];
1833
+ }
1834
+ let replies = [];
1835
+ if (Array.isArray(data)) replies = data;
1836
+ else {
1837
+ const dataRecord = asRecord(data);
1838
+ const replyValue = dataRecord?.replies;
1839
+ if (Array.isArray(replyValue)) replies = replyValue;
1840
+ else if (typeof replyValue === "object" && replyValue) replies = Object.values(replyValue);
1841
+ else if (dataRecord) replies = Object.values(dataRecord);
1842
+ }
1843
+ const messages = replies.map((item) => {
1844
+ const itemRecord = asRecord(item);
1845
+ const replySet = asRecord(asRecord(itemRecord?.["r-reply"])?.set);
1846
+ return createHistoryEntryFromMemo({
1847
+ memo: asRecord(itemRecord?.memo) ?? asRecord(replySet?.memo) ?? itemRecord,
1848
+ seal: asRecord(itemRecord?.seal) ?? asRecord(replySet?.seal),
1849
+ fallbackId: itemRecord?.id
1850
+ });
1851
+ }).filter((msg) => msg.content);
1852
+ runtime?.log?.(`[tlon] Extracted ${messages.length} thread replies from history`);
1853
+ return messages;
1854
+ } catch (error) {
1855
+ runtime?.log?.(`[tlon] Error fetching thread history: ${formatErrorMessage$1(error)}`);
1856
+ try {
1857
+ const altPath = `/channels/v4/${channelNest}/posts/post/id/${formatUd(parentId)}.json`;
1858
+ runtime?.log?.(`[tlon] Trying alternate path: ${altPath}`);
1859
+ const data = asRecord(await api.scry(altPath));
1860
+ const dataMeta = asRecord(asRecord(data?.seal)?.meta);
1861
+ const repliesValue = data?.replies;
1862
+ if (typeof dataMeta?.replyCount === "number" && dataMeta.replyCount > 0 && repliesValue) {
1863
+ const messages = (Array.isArray(repliesValue) ? repliesValue : Object.values(repliesValue)).map((reply) => {
1864
+ const replyRecord = asRecord(reply);
1865
+ return createHistoryEntryFromMemo({
1866
+ memo: asRecord(replyRecord?.memo),
1867
+ seal: asRecord(replyRecord?.seal)
1868
+ });
1869
+ }).filter((msg) => msg.content);
1870
+ runtime?.log?.(`[tlon] Extracted ${messages.length} replies from post data`);
1871
+ return messages;
1872
+ }
1873
+ } catch (altError) {
1874
+ runtime?.log?.(`[tlon] Alternate path also failed: ${formatErrorMessage$1(altError)}`);
1875
+ }
1876
+ return [];
1877
+ }
1878
+ }
1879
+ //#endregion
1880
+ //#region extensions/tlon/src/monitor/media.ts
1881
+ const MAX_IMAGES_PER_MESSAGE = 8;
1882
+ const TLON_MEDIA_DOWNLOAD_IDLE_TIMEOUT_MS = 3e4;
1883
+ /**
1884
+ * Extract image blocks from Tlon message content.
1885
+ * Returns array of image URLs found in the message.
1886
+ */
1887
+ function extractImageBlocks(content) {
1888
+ if (!content || !Array.isArray(content)) return [];
1889
+ const images = [];
1890
+ for (const verse of content) if (verse?.block?.image?.src) {
1891
+ images.push({
1892
+ url: verse.block.image.src,
1893
+ alt: verse.block.image.alt
1894
+ });
1895
+ if (images.length >= MAX_IMAGES_PER_MESSAGE) break;
1896
+ }
1897
+ return images;
1898
+ }
1899
+ /**
1900
+ * Download a media file from URL to local storage.
1901
+ * Returns the local path where the file was saved.
1902
+ */
1903
+ async function downloadMedia(url, mediaDir) {
1904
+ try {
1905
+ const parsedUrl = new URL(url);
1906
+ if (parsedUrl.protocol !== "http:" && parsedUrl.protocol !== "https:") {
1907
+ console.warn(`[tlon-media] Rejected non-http(s) URL: ${url}`);
1908
+ return null;
1909
+ }
1910
+ const fetched = await fetchRemoteMedia({
1911
+ url,
1912
+ maxBytes: MAX_IMAGE_BYTES,
1913
+ readIdleTimeoutMs: TLON_MEDIA_DOWNLOAD_IDLE_TIMEOUT_MS,
1914
+ ssrfPolicy: /* @__PURE__ */ getDefaultSsrFPolicy(),
1915
+ requestInit: { method: "GET" }
1916
+ });
1917
+ if (!mediaDir) {
1918
+ const saved = await saveMediaBuffer(fetched.buffer, fetched.contentType, "inbound", MAX_IMAGE_BYTES, fetched.fileName);
1919
+ return {
1920
+ localPath: saved.path,
1921
+ contentType: saved.contentType ?? fetched.contentType ?? "application/octet-stream",
1922
+ originalUrl: url
1923
+ };
1924
+ }
1925
+ await mkdir(mediaDir, { recursive: true });
1926
+ const ext = getExtensionFromFileName(fetched.fileName) || getExtensionFromContentType(fetched.contentType ?? "") || getExtensionFromUrl(url) || "bin";
1927
+ const localPath = path.join(mediaDir, `${randomUUID()}.${ext}`);
1928
+ await writeFile(localPath, fetched.buffer);
1929
+ return {
1930
+ localPath,
1931
+ contentType: fetched.contentType ?? "application/octet-stream",
1932
+ originalUrl: url
1933
+ };
1934
+ } catch (error) {
1935
+ console.error(`[tlon-media] Error downloading ${url}: ${formatErrorMessage(error)}`);
1936
+ return null;
1937
+ }
1938
+ }
1939
+ function getExtensionFromFileName(fileName) {
1940
+ if (!fileName) return null;
1941
+ return path.extname(fileName).replace(/^\./, "") || null;
1942
+ }
1943
+ function getExtensionFromContentType(contentType) {
1944
+ return {
1945
+ "image/jpeg": "jpg",
1946
+ "image/jpg": "jpg",
1947
+ "image/png": "png",
1948
+ "image/gif": "gif",
1949
+ "image/webp": "webp",
1950
+ "image/svg+xml": "svg",
1951
+ "video/mp4": "mp4",
1952
+ "video/webm": "webm",
1953
+ "audio/mpeg": "mp3",
1954
+ "audio/ogg": "ogg"
1955
+ }[contentType.split(";")[0].trim()] ?? null;
1956
+ }
1957
+ function getExtensionFromUrl(url) {
1958
+ try {
1959
+ const match = new URL(url).pathname.match(/\.([a-z0-9]+)$/i);
1960
+ return match ? normalizeLowercaseStringOrEmpty(match[1]) : null;
1961
+ } catch {
1962
+ return null;
1963
+ }
1964
+ }
1965
+ /**
1966
+ * Download all images from a message and return attachment metadata.
1967
+ * Format matches OpenClaw's expected attachment structure.
1968
+ */
1969
+ async function downloadMessageImages(content, mediaDir) {
1970
+ const images = extractImageBlocks(content);
1971
+ if (images.length === 0) return [];
1972
+ const attachments = [];
1973
+ for (const image of images) {
1974
+ const downloaded = await downloadMedia(image.url, mediaDir);
1975
+ if (downloaded) attachments.push({
1976
+ path: downloaded.localPath,
1977
+ contentType: downloaded.contentType
1978
+ });
1979
+ }
1980
+ return attachments;
1981
+ }
1982
+ //#endregion
1983
+ //#region extensions/tlon/src/monitor/processed-messages.ts
1984
+ function createProcessedMessageTracker(limit = 2e3) {
1985
+ const dedupe = createDedupeCache({
1986
+ ttlMs: 0,
1987
+ maxSize: limit
1988
+ });
1989
+ const inFlight = /* @__PURE__ */ new Set();
1990
+ const claim = (id) => {
1991
+ const trimmed = id?.trim();
1992
+ if (!trimmed) return { kind: "claimed" };
1993
+ if (inFlight.has(trimmed) || dedupe.peek(trimmed)) return { kind: "duplicate" };
1994
+ inFlight.add(trimmed);
1995
+ return { kind: "claimed" };
1996
+ };
1997
+ const commit = (id) => {
1998
+ const trimmed = id?.trim();
1999
+ if (!trimmed) return;
2000
+ inFlight.delete(trimmed);
2001
+ dedupe.check(trimmed);
2002
+ };
2003
+ const release = (id) => {
2004
+ const trimmed = id?.trim();
2005
+ if (!trimmed) return;
2006
+ inFlight.delete(trimmed);
2007
+ };
2008
+ const mark = (id) => {
2009
+ if (claim(id).kind === "duplicate") return false;
2010
+ commit(id);
2011
+ return true;
2012
+ };
2013
+ const has = (id) => {
2014
+ const trimmed = id?.trim();
2015
+ if (!trimmed) return false;
2016
+ return dedupe.peek(trimmed);
2017
+ };
2018
+ return {
2019
+ claim,
2020
+ commit,
2021
+ release,
2022
+ mark,
2023
+ has,
2024
+ size: () => dedupe.size()
2025
+ };
2026
+ }
2027
+ async function runWithProcessedMessageClaim(params) {
2028
+ const claim = params.tracker.claim(params.id);
2029
+ if (claim.kind === "duplicate") return claim;
2030
+ try {
2031
+ const value = await params.task();
2032
+ params.tracker.commit(params.id);
2033
+ return {
2034
+ kind: "processed",
2035
+ value
2036
+ };
2037
+ } catch (error) {
2038
+ params.tracker.release(params.id);
2039
+ throw error;
2040
+ }
2041
+ }
2042
+ //#endregion
2043
+ //#region extensions/tlon/src/monitor/settings-helpers.ts
2044
+ function buildTlonSettingsMigrations(account, currentSettings) {
2045
+ return [
2046
+ {
2047
+ key: "dmAllowlist",
2048
+ fileValue: account.dmAllowlist,
2049
+ settingsValue: currentSettings.dmAllowlist
2050
+ },
2051
+ {
2052
+ key: "groupInviteAllowlist",
2053
+ fileValue: account.groupInviteAllowlist,
2054
+ settingsValue: currentSettings.groupInviteAllowlist
2055
+ },
2056
+ {
2057
+ key: "groupChannels",
2058
+ fileValue: account.groupChannels,
2059
+ settingsValue: currentSettings.groupChannels
2060
+ },
2061
+ {
2062
+ key: "defaultAuthorizedShips",
2063
+ fileValue: account.defaultAuthorizedShips,
2064
+ settingsValue: currentSettings.defaultAuthorizedShips
2065
+ },
2066
+ {
2067
+ key: "autoDiscoverChannels",
2068
+ fileValue: account.autoDiscoverChannels,
2069
+ settingsValue: currentSettings.autoDiscoverChannels
2070
+ },
2071
+ {
2072
+ key: "autoAcceptDmInvites",
2073
+ fileValue: account.autoAcceptDmInvites,
2074
+ settingsValue: currentSettings.autoAcceptDmInvites
2075
+ },
2076
+ {
2077
+ key: "autoAcceptGroupInvites",
2078
+ fileValue: account.autoAcceptGroupInvites,
2079
+ settingsValue: currentSettings.autoAcceptGroupInvites
2080
+ },
2081
+ {
2082
+ key: "showModelSig",
2083
+ fileValue: account.showModelSignature,
2084
+ settingsValue: currentSettings.showModelSig
2085
+ }
2086
+ ];
2087
+ }
2088
+ function shouldMigrateTlonSetting(fileValue, settingsValue) {
2089
+ return (Array.isArray(fileValue) ? fileValue.length > 0 : fileValue != null) && !(settingsValue != null);
2090
+ }
2091
+ function applyTlonSettingsOverrides(params) {
2092
+ let effectiveDmAllowlist = params.account.dmAllowlist;
2093
+ let effectiveShowModelSig = params.account.showModelSignature ?? false;
2094
+ let effectiveAutoAcceptDmInvites = params.account.autoAcceptDmInvites ?? false;
2095
+ let effectiveAutoAcceptGroupInvites = params.account.autoAcceptGroupInvites ?? false;
2096
+ let effectiveGroupInviteAllowlist = params.account.groupInviteAllowlist;
2097
+ let effectiveAutoDiscoverChannels = params.account.autoDiscoverChannels ?? false;
2098
+ let effectiveOwnerShip = params.account.ownerShip ? normalizeShip(params.account.ownerShip) : null;
2099
+ let pendingApprovals = [];
2100
+ if (params.currentSettings.defaultAuthorizedShips?.length) params.log?.(`[tlon] Using defaultAuthorizedShips from settings store: ${params.currentSettings.defaultAuthorizedShips.join(", ")}`);
2101
+ if (params.currentSettings.autoDiscoverChannels !== void 0) {
2102
+ effectiveAutoDiscoverChannels = params.currentSettings.autoDiscoverChannels;
2103
+ params.log?.(`[tlon] Using autoDiscoverChannels from settings store: ${effectiveAutoDiscoverChannels}`);
2104
+ }
2105
+ if (params.currentSettings.dmAllowlist !== void 0) {
2106
+ effectiveDmAllowlist = params.currentSettings.dmAllowlist;
2107
+ params.log?.(`[tlon] Using dmAllowlist from settings store: ${effectiveDmAllowlist.join(", ")}`);
2108
+ }
2109
+ if (params.currentSettings.showModelSig !== void 0) effectiveShowModelSig = params.currentSettings.showModelSig;
2110
+ if (params.currentSettings.autoAcceptDmInvites !== void 0) {
2111
+ effectiveAutoAcceptDmInvites = params.currentSettings.autoAcceptDmInvites;
2112
+ params.log?.(`[tlon] Using autoAcceptDmInvites from settings store: ${effectiveAutoAcceptDmInvites}`);
2113
+ }
2114
+ if (params.currentSettings.autoAcceptGroupInvites !== void 0) {
2115
+ effectiveAutoAcceptGroupInvites = params.currentSettings.autoAcceptGroupInvites;
2116
+ params.log?.(`[tlon] Using autoAcceptGroupInvites from settings store: ${effectiveAutoAcceptGroupInvites}`);
2117
+ }
2118
+ if (params.currentSettings.groupInviteAllowlist !== void 0) {
2119
+ effectiveGroupInviteAllowlist = params.currentSettings.groupInviteAllowlist;
2120
+ params.log?.(`[tlon] Using groupInviteAllowlist from settings store: ${effectiveGroupInviteAllowlist.join(", ")}`);
2121
+ }
2122
+ if (params.currentSettings.ownerShip) {
2123
+ effectiveOwnerShip = normalizeShip(params.currentSettings.ownerShip);
2124
+ params.log?.(`[tlon] Using ownerShip from settings store: ${effectiveOwnerShip}`);
2125
+ }
2126
+ if (params.currentSettings.pendingApprovals?.length) {
2127
+ pendingApprovals = params.currentSettings.pendingApprovals;
2128
+ params.log?.(`[tlon] Loaded ${pendingApprovals.length} pending approval(s) from settings`);
2129
+ }
2130
+ return {
2131
+ effectiveDmAllowlist,
2132
+ effectiveShowModelSig,
2133
+ effectiveAutoAcceptDmInvites,
2134
+ effectiveAutoAcceptGroupInvites,
2135
+ effectiveGroupInviteAllowlist,
2136
+ effectiveAutoDiscoverChannels,
2137
+ effectiveOwnerShip,
2138
+ pendingApprovals,
2139
+ currentSettings: params.currentSettings
2140
+ };
2141
+ }
2142
+ function mergeUniqueStrings(base, next) {
2143
+ if (!next?.length) return [...base];
2144
+ const merged = [...base];
2145
+ for (const value of next) if (!merged.includes(value)) merged.push(value);
2146
+ return merged;
2147
+ }
2148
+ //#endregion
2149
+ //#region extensions/tlon/src/monitor/index.ts
2150
+ function readNumber(record, key) {
2151
+ const value = record?.[key];
2152
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
2153
+ }
2154
+ async function monitorTlonProvider(opts = {}) {
2155
+ const core = getTlonRuntime();
2156
+ const cfg = core.config.current();
2157
+ if (cfg.channels?.tlon?.enabled === false) return;
2158
+ const logger = core.logging.getChildLogger({ module: "tlon-auto-reply" });
2159
+ const runtime = opts.runtime ?? createLoggerBackedRuntime({ logger });
2160
+ const account = resolveTlonAccount(cfg, opts.accountId ?? void 0);
2161
+ if (!account.enabled) return;
2162
+ if (!account.configured || !account.ship || !account.url || !account.code) throw new Error("Tlon account not configured (ship/url/code required)");
2163
+ const botShipName = normalizeShip(account.ship);
2164
+ runtime.log?.(`[tlon] Starting monitor for ${botShipName}`);
2165
+ const ssrfPolicy = ssrfPolicyFromDangerouslyAllowPrivateNetwork(account.dangerouslyAllowPrivateNetwork);
2166
+ const accountUrl = account.url;
2167
+ const accountCode = account.code;
2168
+ async function authenticateWithRetry(maxAttempts = 10) {
2169
+ for (let attempt = 1;; attempt++) {
2170
+ if (opts.abortSignal?.aborted) throw new Error("Aborted while waiting to authenticate");
2171
+ try {
2172
+ runtime.log?.(`[tlon] Attempting authentication to ${accountUrl}...`);
2173
+ return await authenticate(accountUrl, accountCode, { ssrfPolicy });
2174
+ } catch (error) {
2175
+ runtime.error?.(`[tlon] Failed to authenticate (attempt ${attempt}): ${formatErrorMessage$1(error)}`);
2176
+ if (attempt >= maxAttempts) throw error;
2177
+ const delay = Math.min(3e4, 1e3 * 2 ** (attempt - 1));
2178
+ runtime.log?.(`[tlon] Retrying authentication in ${delay}ms...`);
2179
+ await new Promise((resolve, reject) => {
2180
+ const timer = setTimeout(resolve, delay);
2181
+ if (opts.abortSignal) {
2182
+ const onAbort = () => {
2183
+ clearTimeout(timer);
2184
+ reject(/* @__PURE__ */ new Error("Aborted"));
2185
+ };
2186
+ opts.abortSignal.addEventListener("abort", onAbort, { once: true });
2187
+ }
2188
+ });
2189
+ }
2190
+ }
2191
+ }
2192
+ let api = null;
2193
+ const cookie = await authenticateWithRetry();
2194
+ api = new UrbitSSEClient(account.url, cookie, {
2195
+ ship: botShipName,
2196
+ ssrfPolicy,
2197
+ logger: {
2198
+ log: (message) => runtime.log?.(message),
2199
+ error: (message) => runtime.error?.(message)
2200
+ },
2201
+ onReconnect: async (client) => {
2202
+ runtime.log?.("[tlon] Re-authenticating on SSE reconnect...");
2203
+ const newCookie = await authenticateWithRetry(5);
2204
+ client.updateCookie(newCookie);
2205
+ runtime.log?.("[tlon] Re-authentication successful");
2206
+ }
2207
+ });
2208
+ const processedTracker = createProcessedMessageTracker(2e3);
2209
+ let groupChannels = [];
2210
+ let botNickname = null;
2211
+ const settingsManager = createSettingsManager(api, {
2212
+ log: (msg) => runtime.log?.(msg),
2213
+ error: (msg) => runtime.error?.(msg)
2214
+ });
2215
+ let effectiveDmAllowlist = account.dmAllowlist;
2216
+ let effectiveShowModelSig = account.showModelSignature ?? false;
2217
+ let effectiveAutoAcceptDmInvites = account.autoAcceptDmInvites ?? false;
2218
+ let effectiveAutoAcceptGroupInvites = account.autoAcceptGroupInvites ?? false;
2219
+ let effectiveGroupInviteAllowlist = account.groupInviteAllowlist;
2220
+ let effectiveAutoDiscoverChannels = account.autoDiscoverChannels ?? false;
2221
+ let effectiveOwnerShip = account.ownerShip ? normalizeShip(account.ownerShip) : null;
2222
+ let pendingApprovals = [];
2223
+ let currentSettings = {};
2224
+ const participatedThreads = /* @__PURE__ */ new Set();
2225
+ const dmSendersBySession = /* @__PURE__ */ new Map();
2226
+ let sharedSessionWarningSent = false;
2227
+ try {
2228
+ const selfProfile = await api.scry("/contacts/v1/self.json");
2229
+ if (selfProfile && typeof selfProfile === "object") {
2230
+ botNickname = selfProfile.nickname?.value || null;
2231
+ if (botNickname) runtime.log?.(`[tlon] Bot nickname: ${botNickname}`);
2232
+ }
2233
+ } catch (error) {
2234
+ runtime.log?.(`[tlon] Could not fetch nickname: ${formatErrorMessage$1(error)}`);
2235
+ }
2236
+ let initForeigns = null;
2237
+ async function migrateConfigToSettings() {
2238
+ const migrations = buildTlonSettingsMigrations(account, currentSettings);
2239
+ for (const { key, fileValue, settingsValue } of migrations) if (shouldMigrateTlonSetting(fileValue, settingsValue)) try {
2240
+ await api.poke({
2241
+ app: "settings",
2242
+ mark: "settings-event",
2243
+ json: { "put-entry": {
2244
+ "bucket-key": "tlon",
2245
+ "entry-key": key,
2246
+ value: fileValue,
2247
+ desk: "moltbot"
2248
+ } }
2249
+ });
2250
+ runtime.log?.(`[tlon] Migrated ${key} from config to settings store`);
2251
+ } catch (err) {
2252
+ runtime.log?.(`[tlon] Failed to migrate ${key}: ${String(err)}`);
2253
+ }
2254
+ }
2255
+ try {
2256
+ currentSettings = await settingsManager.load();
2257
+ await migrateConfigToSettings();
2258
+ ({effectiveDmAllowlist, effectiveShowModelSig, effectiveAutoAcceptDmInvites, effectiveAutoAcceptGroupInvites, effectiveGroupInviteAllowlist, effectiveAutoDiscoverChannels, effectiveOwnerShip, pendingApprovals, currentSettings} = applyTlonSettingsOverrides({
2259
+ account,
2260
+ currentSettings,
2261
+ log: (message) => runtime.log?.(message)
2262
+ }));
2263
+ } catch (err) {
2264
+ runtime.log?.(`[tlon] Settings store not available, using file config: ${String(err)}`);
2265
+ }
2266
+ if (effectiveAutoDiscoverChannels) try {
2267
+ const initData = await fetchInitData(api, runtime);
2268
+ if (initData.channels.length > 0) groupChannels = initData.channels;
2269
+ initForeigns = initData.foreigns;
2270
+ } catch (error) {
2271
+ runtime.error?.(`[tlon] Auto-discovery failed: ${formatErrorMessage$1(error)}`);
2272
+ }
2273
+ if (account.groupChannels.length > 0) {
2274
+ groupChannels = mergeUniqueStrings(groupChannels, account.groupChannels);
2275
+ runtime.log?.(`[tlon] Added ${account.groupChannels.length} manual groupChannels to monitoring`);
2276
+ }
2277
+ groupChannels = mergeUniqueStrings(groupChannels, currentSettings.groupChannels);
2278
+ if (groupChannels.length > 0) runtime.log?.(`[tlon] Monitoring ${groupChannels.length} group channel(s): ${groupChannels.join(", ")}`);
2279
+ else runtime.log?.("[tlon] No group channels to monitor (DMs only)");
2280
+ function isOwner(ship) {
2281
+ if (!effectiveOwnerShip) return false;
2282
+ return normalizeShip(ship) === effectiveOwnerShip;
2283
+ }
2284
+ /**
2285
+ * Extract the DM partner ship from the 'whom' field.
2286
+ * This is the canonical source for DM routing (more reliable than essay.author).
2287
+ * Returns empty string if whom doesn't contain a valid patp-like value.
2288
+ */
2289
+ function extractDmPartnerShip(whom) {
2290
+ const normalized = normalizeShip(typeof whom === "string" ? whom : whom && typeof whom === "object" && "ship" in whom && typeof whom.ship === "string" ? whom.ship : "");
2291
+ return /^~?[a-z-]+$/i.test(normalized) ? normalized : "";
2292
+ }
2293
+ const processMessage = async (params) => {
2294
+ const { messageId, senderShip, isGroup, channelNest, hostShip: _hostShip, channelName: _channelName, timestamp, parentId, isThreadReply, messageContent } = params;
2295
+ const groupChannel = channelNest;
2296
+ let messageText = params.messageText;
2297
+ let attachments = [];
2298
+ if (messageContent) try {
2299
+ attachments = await downloadMessageImages(messageContent);
2300
+ if (attachments.length > 0) runtime.log?.(`[tlon] Downloaded ${attachments.length} image(s) from message`);
2301
+ } catch (error) {
2302
+ runtime.log?.(`[tlon] Failed to download images: ${formatErrorMessage$1(error)}`);
2303
+ }
2304
+ if (isThreadReply && parentId && groupChannel) try {
2305
+ const threadHistory = await fetchThreadHistory(api, groupChannel, parentId, 20, runtime);
2306
+ if (threadHistory.length > 0) {
2307
+ const threadContext = threadHistory.slice(-10).map((msg) => `${msg.author}: ${msg.content}`).join("\n");
2308
+ messageText = `${`[Thread conversation - ${threadHistory.length} previous replies. You are participating in this thread. Only respond if relevant or helpful - you don't need to reply to every message.]`}\n\n[Previous messages]\n${threadContext}\n\n[Current message]\n${messageText}`;
2309
+ runtime?.log?.(`[tlon] Added thread context (${threadHistory.length} replies) to message`);
2310
+ }
2311
+ } catch (error) {
2312
+ runtime?.log?.(`[tlon] Could not fetch thread context: ${formatErrorMessage$1(error)}`);
2313
+ }
2314
+ if (isGroup && groupChannel && isSummarizationRequest(messageText)) try {
2315
+ const history = await getChannelHistory(api, groupChannel, 50, runtime);
2316
+ if (history.length === 0) {
2317
+ const noHistoryMsg = "I couldn't fetch any messages for this channel. It might be empty or there might be a permissions issue.";
2318
+ if (isGroup) {
2319
+ const parsed = parseChannelNest(groupChannel);
2320
+ if (parsed) await sendGroupMessage({
2321
+ api,
2322
+ fromShip: botShipName,
2323
+ hostShip: parsed.hostShip,
2324
+ channelName: parsed.channelName,
2325
+ text: noHistoryMsg
2326
+ });
2327
+ } else await sendDm({
2328
+ api,
2329
+ fromShip: botShipName,
2330
+ toShip: senderShip,
2331
+ text: noHistoryMsg
2332
+ });
2333
+ return;
2334
+ }
2335
+ const historyText = history.map((msg) => `[${new Date(msg.timestamp).toLocaleString()}] ${msg.author}: ${msg.content}`).join("\n");
2336
+ messageText = `Please summarize this channel conversation (${history.length} recent messages):\n\n${historyText}\n\nProvide a concise summary highlighting:
2337
+ 1. Main topics discussed
2338
+ 2. Key decisions or conclusions
2339
+ 3. Action items if any
2340
+ 4. Notable participants`;
2341
+ } catch (error) {
2342
+ const errorMsg = `Sorry, I encountered an error while fetching the channel history: ${formatErrorMessage$1(error)}`;
2343
+ if (isGroup && groupChannel) {
2344
+ const parsed = parseChannelNest(groupChannel);
2345
+ if (parsed) await sendGroupMessage({
2346
+ api,
2347
+ fromShip: botShipName,
2348
+ hostShip: parsed.hostShip,
2349
+ channelName: parsed.channelName,
2350
+ text: errorMsg
2351
+ });
2352
+ } else await sendDm({
2353
+ api,
2354
+ fromShip: botShipName,
2355
+ toShip: senderShip,
2356
+ text: errorMsg
2357
+ });
2358
+ return;
2359
+ }
2360
+ const route = core.channel.routing.resolveAgentRoute({
2361
+ cfg,
2362
+ channel: "tlon",
2363
+ accountId: opts.accountId ?? void 0,
2364
+ peer: {
2365
+ kind: isGroup ? "group" : "direct",
2366
+ id: isGroup ? groupChannel ?? senderShip : senderShip
2367
+ }
2368
+ });
2369
+ if (!isGroup) {
2370
+ const sessionKey = route.sessionKey;
2371
+ if (!dmSendersBySession.has(sessionKey)) dmSendersBySession.set(sessionKey, /* @__PURE__ */ new Set());
2372
+ const senders = dmSendersBySession.get(sessionKey);
2373
+ if (senders.size > 0 && !senders.has(senderShip)) {
2374
+ runtime.log?.("[tlon] ⚠️ SECURITY: Multiple users sharing DM session. Configure \"session.dmScope: per-channel-peer\" in OpenClaw config.");
2375
+ if (!sharedSessionWarningSent && effectiveOwnerShip) {
2376
+ sharedSessionWarningSent = true;
2377
+ sendDm({
2378
+ api,
2379
+ fromShip: botShipName,
2380
+ toShip: effectiveOwnerShip,
2381
+ text: "⚠️ Security Warning: Multiple users are sharing a DM session with this bot. This can leak conversation context between users.\n\nFix: Add to your OpenClaw config:\nsession:\n dmScope: \"per-channel-peer\"\n\nDocs: https://docs.openclaw.ai/concepts/session#secure-dm-mode"
2382
+ }).catch((err) => runtime.error?.(`[tlon] Failed to send security warning to owner: ${err}`));
2383
+ }
2384
+ }
2385
+ senders.add(senderShip);
2386
+ }
2387
+ const senderRole = isOwner(senderShip) ? "owner" : "user";
2388
+ const fromLabel = isGroup ? `${senderShip} [${senderRole}] in ${channelNest}` : `${senderShip} [${senderRole}]`;
2389
+ const shouldComputeAuth = core.channel.commands.shouldComputeCommandAuthorized(messageText, cfg);
2390
+ let commandAuthorized = false;
2391
+ if (shouldComputeAuth) {
2392
+ const useAccessGroups = cfg.commands?.useAccessGroups !== false;
2393
+ const senderIsOwner = isOwner(senderShip);
2394
+ commandAuthorized = core.channel.commands.resolveCommandAuthorizedFromAuthorizers({
2395
+ useAccessGroups,
2396
+ authorizers: [{
2397
+ configured: Boolean(effectiveOwnerShip),
2398
+ allowed: senderIsOwner
2399
+ }]
2400
+ });
2401
+ if (!commandAuthorized) console.log(`[tlon] Command attempt denied: ${senderShip} is not owner (owner=${effectiveOwnerShip ?? "not configured"})`);
2402
+ }
2403
+ let bodyWithAttachments = messageText;
2404
+ if (attachments.length > 0) bodyWithAttachments = attachments.map((a) => `[media attached: ${a.path} (${a.contentType}) | ${a.path}]`).join("\n") + "\n" + messageText;
2405
+ const body = core.channel.reply.formatAgentEnvelope({
2406
+ channel: "Tlon",
2407
+ from: fromLabel,
2408
+ timestamp,
2409
+ body: bodyWithAttachments
2410
+ });
2411
+ const commandBody = isGroup ? stripBotMention(messageText, botShipName) : messageText;
2412
+ const tlonConversationId = isGroup ? groupChannel ?? channelNest ?? senderShip : senderShip;
2413
+ const rawTurnMessage = {
2414
+ messageId,
2415
+ messageText,
2416
+ timestamp
2417
+ };
2418
+ const ctxPayload = core.channel.turn.buildContext({
2419
+ channel: "tlon",
2420
+ accountId: route.accountId,
2421
+ messageId,
2422
+ timestamp,
2423
+ from: isGroup ? `tlon:group:${groupChannel}` : `tlon:${senderShip}`,
2424
+ sender: {
2425
+ id: senderShip,
2426
+ name: senderShip,
2427
+ roles: [senderRole]
2428
+ },
2429
+ conversation: {
2430
+ kind: isGroup ? "group" : "direct",
2431
+ id: tlonConversationId,
2432
+ label: fromLabel,
2433
+ routePeer: {
2434
+ kind: isGroup ? "group" : "direct",
2435
+ id: tlonConversationId
2436
+ }
2437
+ },
2438
+ route: {
2439
+ agentId: route.agentId,
2440
+ accountId: route.accountId,
2441
+ routeSessionKey: route.sessionKey
2442
+ },
2443
+ reply: {
2444
+ to: `tlon:${botShipName}`,
2445
+ originatingTo: `tlon:${isGroup ? groupChannel : botShipName}`,
2446
+ replyToId: parentId ?? void 0
2447
+ },
2448
+ message: {
2449
+ body,
2450
+ bodyForAgent: commandBody,
2451
+ rawBody: messageText,
2452
+ commandBody,
2453
+ envelopeFrom: fromLabel
2454
+ },
2455
+ extra: {
2456
+ GroupSubject: void 0,
2457
+ SenderRole: senderRole,
2458
+ CommandAuthorized: commandAuthorized,
2459
+ CommandSource: "text",
2460
+ ...attachments.length > 0 && { Attachments: attachments },
2461
+ ...parentId && { ThreadId: parentId }
2462
+ }
2463
+ });
2464
+ const dispatchStartTime = Date.now();
2465
+ const responsePrefix = core.channel.reply.resolveEffectiveMessagesConfig(cfg, route.agentId).responsePrefix;
2466
+ const humanDelay = core.channel.reply.resolveHumanDelayConfig(cfg, route.agentId);
2467
+ const storePath = core.channel.session.resolveStorePath(cfg.session?.store, { agentId: route.agentId });
2468
+ await core.channel.turn.run({
2469
+ channel: "tlon",
2470
+ accountId: route.accountId,
2471
+ raw: rawTurnMessage,
2472
+ adapter: {
2473
+ ingest: (raw) => ({
2474
+ id: raw.messageId,
2475
+ timestamp: raw.timestamp,
2476
+ rawText: raw.messageText,
2477
+ textForAgent: commandBody,
2478
+ textForCommands: commandBody,
2479
+ raw
2480
+ }),
2481
+ resolveTurn: () => ({
2482
+ cfg,
2483
+ channel: "tlon",
2484
+ accountId: route.accountId,
2485
+ agentId: route.agentId,
2486
+ routeSessionKey: route.sessionKey,
2487
+ storePath,
2488
+ ctxPayload,
2489
+ recordInboundSession: core.channel.session.recordInboundSession,
2490
+ dispatchReplyWithBufferedBlockDispatcher: core.channel.reply.dispatchReplyWithBufferedBlockDispatcher,
2491
+ delivery: {
2492
+ deliver: async (payload) => {
2493
+ let replyText = payload.text;
2494
+ if (!replyText) return;
2495
+ if (effectiveShowModelSig) {
2496
+ const extPayload = payload;
2497
+ const defaultModel = cfg.agents?.defaults?.model;
2498
+ const modelInfo = extPayload.metadata?.model || extPayload.model || (typeof defaultModel === "string" ? defaultModel : defaultModel?.primary);
2499
+ replyText = `${replyText}\n\n_[Generated by ${formatModelName(modelInfo)}]_`;
2500
+ }
2501
+ if (isGroup && groupChannel) {
2502
+ const parsed = parseChannelNest(groupChannel);
2503
+ if (!parsed) return;
2504
+ await sendGroupMessage({
2505
+ api,
2506
+ fromShip: botShipName,
2507
+ hostShip: parsed.hostShip,
2508
+ channelName: parsed.channelName,
2509
+ text: replyText,
2510
+ replyToId: parentId ?? void 0
2511
+ });
2512
+ if (parentId) {
2513
+ participatedThreads.add(parentId);
2514
+ runtime.log?.(`[tlon] Now tracking thread for future replies: ${parentId}`);
2515
+ }
2516
+ } else await sendDm({
2517
+ api,
2518
+ fromShip: botShipName,
2519
+ toShip: senderShip,
2520
+ text: replyText
2521
+ });
2522
+ },
2523
+ onError: (err, info) => {
2524
+ const dispatchDuration = Date.now() - dispatchStartTime;
2525
+ runtime.error?.(`[tlon] ${info.kind} reply failed after ${dispatchDuration}ms: ${String(err)}`);
2526
+ }
2527
+ },
2528
+ dispatcherOptions: {
2529
+ responsePrefix,
2530
+ humanDelay
2531
+ },
2532
+ record: { onRecordError: (err) => {
2533
+ runtime.error?.(`[tlon] failed updating session meta: ${String(err)}`);
2534
+ } }
2535
+ })
2536
+ }
2537
+ });
2538
+ };
2539
+ const watchedChannels = new Set(groupChannels);
2540
+ const refreshWatchedChannels = async () => {
2541
+ const discoveredChannels = await fetchAllChannels(api, runtime);
2542
+ let newCount = 0;
2543
+ for (const channelNest of discoveredChannels) if (!watchedChannels.has(channelNest)) {
2544
+ watchedChannels.add(channelNest);
2545
+ newCount++;
2546
+ }
2547
+ return newCount;
2548
+ };
2549
+ const { resolveAllCites } = createTlonCitationResolver({
2550
+ api: { scry: (path) => api.scry(path) },
2551
+ runtime
2552
+ });
2553
+ const { queueApprovalRequest, handleApprovalResponse, handleAdminCommand } = createTlonApprovalRuntime({
2554
+ api: {
2555
+ poke: (payload) => api.poke(payload),
2556
+ scry: (path) => api.scry(path)
2557
+ },
2558
+ runtime,
2559
+ botShipName,
2560
+ getPendingApprovals: () => pendingApprovals,
2561
+ setPendingApprovals: (approvals) => {
2562
+ pendingApprovals = approvals;
2563
+ },
2564
+ getCurrentSettings: () => currentSettings,
2565
+ setCurrentSettings: (settings) => {
2566
+ currentSettings = settings;
2567
+ },
2568
+ getEffectiveDmAllowlist: () => effectiveDmAllowlist,
2569
+ setEffectiveDmAllowlist: (ships) => {
2570
+ effectiveDmAllowlist = ships;
2571
+ },
2572
+ getEffectiveOwnerShip: () => effectiveOwnerShip,
2573
+ processApprovedMessage: async (approval) => {
2574
+ if (!approval.originalMessage) return;
2575
+ if (approval.type === "dm") {
2576
+ await processMessage({
2577
+ messageId: approval.originalMessage.messageId,
2578
+ senderShip: approval.requestingShip,
2579
+ messageText: approval.originalMessage.messageText,
2580
+ messageContent: approval.originalMessage.messageContent,
2581
+ isGroup: false,
2582
+ timestamp: approval.originalMessage.timestamp
2583
+ });
2584
+ return;
2585
+ }
2586
+ if (approval.type === "channel" && approval.channelNest) {
2587
+ const parsedChannel = parseChannelNest(approval.channelNest);
2588
+ await processMessage({
2589
+ messageId: approval.originalMessage.messageId,
2590
+ senderShip: approval.requestingShip,
2591
+ messageText: approval.originalMessage.messageText,
2592
+ messageContent: approval.originalMessage.messageContent,
2593
+ isGroup: true,
2594
+ channelNest: approval.channelNest,
2595
+ hostShip: parsedChannel?.hostShip,
2596
+ channelName: parsedChannel?.channelName,
2597
+ timestamp: approval.originalMessage.timestamp,
2598
+ parentId: approval.originalMessage.parentId,
2599
+ isThreadReply: approval.originalMessage.isThreadReply
2600
+ });
2601
+ }
2602
+ },
2603
+ refreshWatchedChannels
2604
+ });
2605
+ const handleChannelsFirehose = async (event) => {
2606
+ try {
2607
+ const eventRecord = asRecord(event);
2608
+ const nest = readString(eventRecord, "nest");
2609
+ if (!nest) return;
2610
+ if (!watchedChannels.has(nest)) return;
2611
+ const response = asRecord(eventRecord?.response);
2612
+ if (!response) return;
2613
+ const post = asRecord(response.post);
2614
+ const rPost = asRecord(post?.["r-post"]);
2615
+ const set = asRecord(rPost?.set);
2616
+ const reply = asRecord(rPost?.reply);
2617
+ const replySet = asRecord(asRecord(reply?.["r-reply"])?.set);
2618
+ const essay = asRecord(set?.essay);
2619
+ const memo = asRecord(replySet?.memo);
2620
+ if (!essay && !memo) return;
2621
+ const content = memo ?? essay;
2622
+ if (!content) return;
2623
+ const isThreadReply = Boolean(memo);
2624
+ const messageId = isThreadReply ? readString(reply, "id") : readString(post, "id");
2625
+ if (!messageId) return;
2626
+ if ((await runWithProcessedMessageClaim({
2627
+ tracker: processedTracker,
2628
+ id: messageId,
2629
+ task: async () => {
2630
+ const senderShip = normalizeShip(readString(content, "author") ?? "");
2631
+ if (!senderShip || senderShip === botShipName) return;
2632
+ const rawText = extractMessageText(content.content);
2633
+ if (!rawText.trim()) return;
2634
+ const contentBody = content.content;
2635
+ const sentAt = readNumber(content, "sent") ?? Date.now();
2636
+ cacheMessage(nest, {
2637
+ author: senderShip,
2638
+ content: rawText,
2639
+ timestamp: sentAt,
2640
+ id: messageId
2641
+ });
2642
+ const seal = isThreadReply ? asRecord(replySet?.seal) : asRecord(set?.seal);
2643
+ const parentId = readString(seal, "parent-id") ?? readString(seal, "parent") ?? null;
2644
+ const mentioned = isBotMentioned(rawText, botShipName, botNickname ?? void 0);
2645
+ const inParticipatedThread = isThreadReply && parentId && participatedThreads.has(parentId);
2646
+ if (!mentioned && !inParticipatedThread) return;
2647
+ if (inParticipatedThread && !mentioned) runtime.log?.(`[tlon] Responding to thread we participated in (no mention): ${parentId}`);
2648
+ if (isOwner(senderShip)) runtime.log?.(`[tlon] Owner ${senderShip} is always allowed in channels`);
2649
+ else {
2650
+ const { mode, allowedShips } = resolveChannelAuthorization(cfg, nest, currentSettings);
2651
+ if (mode === "restricted") {
2652
+ if (!allowedShips.map(normalizeShip).includes(senderShip)) {
2653
+ if (effectiveOwnerShip) await queueApprovalRequest(createPendingApproval({
2654
+ type: "channel",
2655
+ requestingShip: senderShip,
2656
+ channelNest: nest,
2657
+ messagePreview: rawText.slice(0, 100),
2658
+ originalMessage: {
2659
+ messageId: messageId ?? "",
2660
+ messageText: rawText,
2661
+ messageContent: contentBody,
2662
+ timestamp: sentAt,
2663
+ parentId: parentId ?? void 0,
2664
+ isThreadReply
2665
+ }
2666
+ }));
2667
+ else runtime.log?.(`[tlon] Access denied: ${senderShip} in ${nest} (allowed: ${allowedShips.join(", ")})`);
2668
+ return;
2669
+ }
2670
+ }
2671
+ }
2672
+ const messageText = await resolveAuthorizedMessageText({
2673
+ rawText,
2674
+ content: contentBody,
2675
+ authorizedForCites: true,
2676
+ resolveAllCites
2677
+ });
2678
+ const parsed = parseChannelNest(nest);
2679
+ await processMessage({
2680
+ messageId: messageId ?? "",
2681
+ senderShip,
2682
+ messageText,
2683
+ messageContent: contentBody,
2684
+ isGroup: true,
2685
+ channelNest: nest,
2686
+ hostShip: parsed?.hostShip,
2687
+ channelName: parsed?.channelName,
2688
+ timestamp: sentAt,
2689
+ parentId,
2690
+ isThreadReply
2691
+ });
2692
+ }
2693
+ })).kind === "duplicate") return;
2694
+ } catch (error) {
2695
+ runtime.error?.(`[tlon] Error handling channel firehose event: ${formatErrorMessage$1(error)}`);
2696
+ }
2697
+ };
2698
+ const processedDmInvites = /* @__PURE__ */ new Set();
2699
+ const handleChatFirehose = async (event) => {
2700
+ try {
2701
+ if (Array.isArray(event)) {
2702
+ for (const invite of event) {
2703
+ const ship = normalizeShip(invite.ship || "");
2704
+ if (!ship || processedDmInvites.has(ship)) continue;
2705
+ if (isOwner(ship)) {
2706
+ try {
2707
+ await api.poke({
2708
+ app: "chat",
2709
+ mark: "chat-dm-rsvp",
2710
+ json: {
2711
+ ship,
2712
+ ok: true
2713
+ }
2714
+ });
2715
+ processedDmInvites.add(ship);
2716
+ runtime.log?.(`[tlon] Auto-accepted DM invite from owner ${ship}`);
2717
+ } catch (err) {
2718
+ runtime.error?.(`[tlon] Failed to auto-accept DM from owner: ${String(err)}`);
2719
+ }
2720
+ continue;
2721
+ }
2722
+ if (effectiveAutoAcceptDmInvites && isDmAllowed(ship, effectiveDmAllowlist)) {
2723
+ try {
2724
+ await api.poke({
2725
+ app: "chat",
2726
+ mark: "chat-dm-rsvp",
2727
+ json: {
2728
+ ship,
2729
+ ok: true
2730
+ }
2731
+ });
2732
+ processedDmInvites.add(ship);
2733
+ runtime.log?.(`[tlon] Auto-accepted DM invite from ${ship}`);
2734
+ } catch (err) {
2735
+ runtime.error?.(`[tlon] Failed to auto-accept DM from ${ship}: ${String(err)}`);
2736
+ }
2737
+ continue;
2738
+ }
2739
+ if (effectiveOwnerShip && !isDmAllowed(ship, effectiveDmAllowlist)) {
2740
+ await queueApprovalRequest(createPendingApproval({
2741
+ type: "dm",
2742
+ requestingShip: ship,
2743
+ messagePreview: "(DM invite - no message yet)"
2744
+ }));
2745
+ processedDmInvites.add(ship);
2746
+ }
2747
+ }
2748
+ return;
2749
+ }
2750
+ const eventRecord = asRecord(event);
2751
+ if (!eventRecord) return;
2752
+ const whom = eventRecord.whom;
2753
+ const messageId = readString(eventRecord, "id");
2754
+ const response = asRecord(eventRecord.response);
2755
+ if (!messageId || !response) return;
2756
+ const essay = asRecord(asRecord(response.add)?.essay);
2757
+ if (!essay) return;
2758
+ if ((await runWithProcessedMessageClaim({
2759
+ tracker: processedTracker,
2760
+ id: messageId,
2761
+ task: async () => {
2762
+ const authorShip = normalizeShip(readString(essay, "author") ?? "");
2763
+ const partnerShip = extractDmPartnerShip(whom);
2764
+ const senderShip = partnerShip || authorShip;
2765
+ if (authorShip === botShipName) return;
2766
+ if (!senderShip || senderShip === botShipName) return;
2767
+ if (authorShip && partnerShip && authorShip !== partnerShip) runtime.log?.(`[tlon] DM ship mismatch (author=${authorShip}, partner=${partnerShip}) - routing to partner`);
2768
+ const rawText = extractMessageText(essay.content);
2769
+ if (!rawText.trim()) return;
2770
+ const messageText = rawText;
2771
+ if (isOwner(senderShip) && isApprovalResponse(messageText)) {
2772
+ if (await handleApprovalResponse(messageText)) {
2773
+ runtime.log?.(`[tlon] Processed approval response from owner: ${messageText}`);
2774
+ return;
2775
+ }
2776
+ }
2777
+ if (isOwner(senderShip) && isAdminCommand(messageText)) {
2778
+ if (await handleAdminCommand(messageText)) {
2779
+ runtime.log?.(`[tlon] Processed admin command from owner: ${messageText}`);
2780
+ return;
2781
+ }
2782
+ }
2783
+ if (isOwner(senderShip)) {
2784
+ const resolvedMessageText = await resolveAuthorizedMessageText({
2785
+ rawText,
2786
+ content: essay.content,
2787
+ authorizedForCites: true,
2788
+ resolveAllCites
2789
+ });
2790
+ runtime.log?.(`[tlon] Processing DM from owner ${senderShip}`);
2791
+ await processMessage({
2792
+ messageId: messageId ?? "",
2793
+ senderShip,
2794
+ messageText: resolvedMessageText,
2795
+ messageContent: essay.content,
2796
+ isGroup: false,
2797
+ timestamp: readNumber(essay, "sent") ?? Date.now()
2798
+ });
2799
+ return;
2800
+ }
2801
+ if (!isDmAllowed(senderShip, effectiveDmAllowlist)) {
2802
+ if (effectiveOwnerShip) await queueApprovalRequest(createPendingApproval({
2803
+ type: "dm",
2804
+ requestingShip: senderShip,
2805
+ messagePreview: messageText.slice(0, 100),
2806
+ originalMessage: {
2807
+ messageId: messageId ?? "",
2808
+ messageText,
2809
+ messageContent: essay.content,
2810
+ timestamp: readNumber(essay, "sent") ?? Date.now()
2811
+ }
2812
+ }));
2813
+ else runtime.log?.(`[tlon] Blocked DM from ${senderShip}: not in allowlist`);
2814
+ return;
2815
+ }
2816
+ await processMessage({
2817
+ messageText: await resolveAuthorizedMessageText({
2818
+ rawText,
2819
+ content: essay.content,
2820
+ authorizedForCites: true,
2821
+ resolveAllCites
2822
+ }),
2823
+ messageId: messageId ?? "",
2824
+ senderShip,
2825
+ messageContent: essay.content,
2826
+ isGroup: false,
2827
+ timestamp: readNumber(essay, "sent") ?? Date.now()
2828
+ });
2829
+ }
2830
+ })).kind === "duplicate") return;
2831
+ } catch (error) {
2832
+ runtime.error?.(`[tlon] Error handling chat firehose event: ${formatErrorMessage$1(error)}`);
2833
+ }
2834
+ };
2835
+ try {
2836
+ runtime.log?.("[tlon] Subscribing to firehose updates...");
2837
+ await api.subscribe({
2838
+ app: "channels",
2839
+ path: "/v2",
2840
+ event: handleChannelsFirehose,
2841
+ err: (error) => {
2842
+ runtime.error?.(`[tlon] Channels firehose error: ${String(error)}`);
2843
+ },
2844
+ quit: () => {
2845
+ runtime.log?.("[tlon] Channels firehose subscription ended");
2846
+ }
2847
+ });
2848
+ runtime.log?.("[tlon] Subscribed to channels firehose (/v2)");
2849
+ await api.subscribe({
2850
+ app: "chat",
2851
+ path: "/v3",
2852
+ event: handleChatFirehose,
2853
+ err: (error) => {
2854
+ runtime.error?.(`[tlon] Chat firehose error: ${String(error)}`);
2855
+ },
2856
+ quit: () => {
2857
+ runtime.log?.("[tlon] Chat firehose subscription ended");
2858
+ }
2859
+ });
2860
+ runtime.log?.("[tlon] Subscribed to chat firehose (/v3)");
2861
+ await api.subscribe({
2862
+ app: "contacts",
2863
+ path: "/v1/news",
2864
+ event: (event) => {
2865
+ try {
2866
+ const eventRecord = asRecord(event);
2867
+ if (eventRecord?.self) {
2868
+ const nickname = asRecord(asRecord(asRecord(eventRecord.self)?.contact)?.nickname);
2869
+ if (nickname && "value" in nickname) {
2870
+ const newNickname = readString(nickname, "value") ?? null;
2871
+ if (newNickname !== botNickname) {
2872
+ botNickname = newNickname;
2873
+ runtime.log?.(`[tlon] Nickname updated: ${botNickname}`);
2874
+ }
2875
+ }
2876
+ }
2877
+ } catch (error) {
2878
+ runtime.error?.(`[tlon] Error handling contacts event: ${formatErrorMessage$1(error)}`);
2879
+ }
2880
+ },
2881
+ err: (error) => {
2882
+ runtime.error?.(`[tlon] Contacts subscription error: ${String(error)}`);
2883
+ },
2884
+ quit: () => {
2885
+ runtime.log?.("[tlon] Contacts subscription ended");
2886
+ }
2887
+ });
2888
+ runtime.log?.("[tlon] Subscribed to contacts updates (/v1/news)");
2889
+ settingsManager.onChange((newSettings) => {
2890
+ currentSettings = newSettings;
2891
+ if (newSettings.groupChannels?.length) {
2892
+ const newChannels = newSettings.groupChannels;
2893
+ for (const ch of newChannels) if (!watchedChannels.has(ch)) {
2894
+ watchedChannels.add(ch);
2895
+ runtime.log?.(`[tlon] Settings: now watching channel ${ch}`);
2896
+ }
2897
+ }
2898
+ ({effectiveDmAllowlist, effectiveShowModelSig, effectiveAutoAcceptDmInvites, effectiveAutoAcceptGroupInvites, effectiveGroupInviteAllowlist, effectiveAutoDiscoverChannels, effectiveOwnerShip, pendingApprovals} = applyTlonSettingsOverrides({
2899
+ account,
2900
+ currentSettings: newSettings,
2901
+ log: (message) => runtime.log?.(message)
2902
+ }));
2903
+ });
2904
+ try {
2905
+ await settingsManager.startSubscription();
2906
+ } catch (err) {
2907
+ runtime.log?.(`[tlon] Settings subscription not available: ${String(err)}`);
2908
+ }
2909
+ try {
2910
+ await api.subscribe({
2911
+ app: "groups",
2912
+ path: "/groups/ui",
2913
+ event: async (event) => {
2914
+ try {
2915
+ const eventRecord = asRecord(event);
2916
+ if (eventRecord) {
2917
+ const channels = asRecord(eventRecord.channels);
2918
+ if (channels) for (const [channelNest, _channelData] of Object.entries(channels)) {
2919
+ if (!channelNest.startsWith("chat/")) continue;
2920
+ if (!watchedChannels.has(channelNest)) {
2921
+ watchedChannels.add(channelNest);
2922
+ runtime.log?.(`[tlon] Auto-detected new channel (invite accepted): ${channelNest}`);
2923
+ if (effectiveAutoAcceptGroupInvites) try {
2924
+ const currentChannels = currentSettings.groupChannels || [];
2925
+ if (!currentChannels.includes(channelNest)) {
2926
+ const updatedChannels = [...currentChannels, channelNest];
2927
+ await api.poke({
2928
+ app: "settings",
2929
+ mark: "settings-event",
2930
+ json: { "put-entry": {
2931
+ "bucket-key": "tlon",
2932
+ "entry-key": "groupChannels",
2933
+ value: updatedChannels,
2934
+ desk: "moltbot"
2935
+ } }
2936
+ });
2937
+ runtime.log?.(`[tlon] Persisted ${channelNest} to settings store`);
2938
+ }
2939
+ } catch (err) {
2940
+ runtime.error?.(`[tlon] Failed to persist channel to settings: ${String(err)}`);
2941
+ }
2942
+ }
2943
+ }
2944
+ const join = asRecord(eventRecord.join);
2945
+ if (join) {
2946
+ const joinChannels = Array.isArray(join.channels) ? join.channels : [];
2947
+ if (joinChannels.length > 0) for (const channelNest of joinChannels) {
2948
+ if (typeof channelNest !== "string") continue;
2949
+ if (!channelNest.startsWith("chat/")) continue;
2950
+ if (!watchedChannels.has(channelNest)) {
2951
+ watchedChannels.add(channelNest);
2952
+ runtime.log?.(`[tlon] Auto-detected joined channel: ${channelNest}`);
2953
+ if (effectiveAutoAcceptGroupInvites) try {
2954
+ const currentChannels = currentSettings.groupChannels || [];
2955
+ if (!currentChannels.includes(channelNest)) {
2956
+ const updatedChannels = [...currentChannels, channelNest];
2957
+ await api.poke({
2958
+ app: "settings",
2959
+ mark: "settings-event",
2960
+ json: { "put-entry": {
2961
+ "bucket-key": "tlon",
2962
+ "entry-key": "groupChannels",
2963
+ value: updatedChannels,
2964
+ desk: "moltbot"
2965
+ } }
2966
+ });
2967
+ runtime.log?.(`[tlon] Persisted ${channelNest} to settings store`);
2968
+ }
2969
+ } catch (err) {
2970
+ runtime.error?.(`[tlon] Failed to persist channel to settings: ${String(err)}`);
2971
+ }
2972
+ }
2973
+ }
2974
+ }
2975
+ }
2976
+ } catch (error) {
2977
+ runtime.error?.(`[tlon] Error handling groups-ui event: ${formatErrorMessage$1(error)}`);
2978
+ }
2979
+ },
2980
+ err: (error) => {
2981
+ runtime.error?.(`[tlon] Groups-ui subscription error: ${String(error)}`);
2982
+ },
2983
+ quit: () => {
2984
+ runtime.log?.("[tlon] Groups-ui subscription ended");
2985
+ }
2986
+ });
2987
+ runtime.log?.("[tlon] Subscribed to groups-ui for real-time channel detection");
2988
+ } catch (err) {
2989
+ runtime.log?.(`[tlon] Groups-ui subscription failed (will rely on polling): ${String(err)}`);
2990
+ }
2991
+ {
2992
+ const processedGroupInvites = /* @__PURE__ */ new Set();
2993
+ const processPendingInvites = async (foreigns) => {
2994
+ if (!foreigns || typeof foreigns !== "object") return;
2995
+ for (const [groupFlag, foreign] of Object.entries(foreigns)) {
2996
+ if (processedGroupInvites.has(groupFlag)) continue;
2997
+ if (!foreign.invites || foreign.invites.length === 0) continue;
2998
+ const validInvite = foreign.invites.find((inv) => inv.valid);
2999
+ if (!validInvite) continue;
3000
+ const inviterShip = validInvite.from;
3001
+ if (isOwner(inviterShip)) {
3002
+ try {
3003
+ await api.poke({
3004
+ app: "groups",
3005
+ mark: "group-join",
3006
+ json: {
3007
+ flag: groupFlag,
3008
+ "join-all": true
3009
+ }
3010
+ });
3011
+ processedGroupInvites.add(groupFlag);
3012
+ runtime.log?.(`[tlon] Auto-accepted group invite from owner: ${groupFlag}`);
3013
+ } catch (err) {
3014
+ runtime.error?.(`[tlon] Failed to accept group invite from owner: ${String(err)}`);
3015
+ }
3016
+ continue;
3017
+ }
3018
+ if (!effectiveAutoAcceptGroupInvites) {
3019
+ if (effectiveOwnerShip) {
3020
+ await queueApprovalRequest(createPendingApproval({
3021
+ type: "group",
3022
+ requestingShip: inviterShip,
3023
+ groupFlag
3024
+ }));
3025
+ processedGroupInvites.add(groupFlag);
3026
+ }
3027
+ continue;
3028
+ }
3029
+ if (!isGroupInviteAllowed(inviterShip, effectiveGroupInviteAllowlist)) {
3030
+ if (effectiveOwnerShip) {
3031
+ await queueApprovalRequest(createPendingApproval({
3032
+ type: "group",
3033
+ requestingShip: inviterShip,
3034
+ groupFlag
3035
+ }));
3036
+ processedGroupInvites.add(groupFlag);
3037
+ } else {
3038
+ runtime.log?.(`[tlon] Rejected group invite from ${inviterShip} (not in groupInviteAllowlist): ${groupFlag}`);
3039
+ processedGroupInvites.add(groupFlag);
3040
+ }
3041
+ continue;
3042
+ }
3043
+ try {
3044
+ await api.poke({
3045
+ app: "groups",
3046
+ mark: "group-join",
3047
+ json: {
3048
+ flag: groupFlag,
3049
+ "join-all": true
3050
+ }
3051
+ });
3052
+ processedGroupInvites.add(groupFlag);
3053
+ runtime.log?.(`[tlon] Auto-accepted group invite: ${groupFlag} (from ${validInvite.from})`);
3054
+ } catch (err) {
3055
+ runtime.error?.(`[tlon] Failed to auto-accept group ${groupFlag}: ${String(err)}`);
3056
+ }
3057
+ }
3058
+ };
3059
+ if (initForeigns) await processPendingInvites(initForeigns);
3060
+ try {
3061
+ await api.subscribe({
3062
+ app: "groups",
3063
+ path: "/v1/foreigns",
3064
+ event: (data) => {
3065
+ (async () => {
3066
+ try {
3067
+ await processPendingInvites(data);
3068
+ } catch (error) {
3069
+ runtime.error?.(`[tlon] Error handling foreigns event: ${formatErrorMessage$1(error)}`);
3070
+ }
3071
+ })();
3072
+ },
3073
+ err: (error) => {
3074
+ runtime.error?.(`[tlon] Foreigns subscription error: ${String(error)}`);
3075
+ },
3076
+ quit: () => {
3077
+ runtime.log?.("[tlon] Foreigns subscription ended");
3078
+ }
3079
+ });
3080
+ runtime.log?.("[tlon] Subscribed to foreigns (/v1/foreigns) for auto-accepting group invites");
3081
+ } catch (err) {
3082
+ runtime.log?.(`[tlon] Foreigns subscription failed: ${String(err)}`);
3083
+ }
3084
+ }
3085
+ if (effectiveAutoDiscoverChannels) {
3086
+ const discoveredChannels = await fetchAllChannels(api, runtime);
3087
+ for (const channelNest of discoveredChannels) watchedChannels.add(channelNest);
3088
+ runtime.log?.(`[tlon] Watching ${watchedChannels.size} channel(s)`);
3089
+ }
3090
+ for (const channelNest of watchedChannels) runtime.log?.(`[tlon] Watching channel: ${channelNest}`);
3091
+ runtime.log?.("[tlon] All subscriptions registered, connecting to SSE stream...");
3092
+ await api.connect();
3093
+ runtime.log?.("[tlon] Connected! Firehose subscriptions active");
3094
+ const pollInterval = setInterval(async () => {
3095
+ if (!opts.abortSignal?.aborted) try {
3096
+ if (effectiveAutoDiscoverChannels) {
3097
+ const discoveredChannels = await fetchAllChannels(api, runtime);
3098
+ for (const channelNest of discoveredChannels) if (!watchedChannels.has(channelNest)) {
3099
+ watchedChannels.add(channelNest);
3100
+ runtime.log?.(`[tlon] Now watching new channel: ${channelNest}`);
3101
+ }
3102
+ }
3103
+ } catch (error) {
3104
+ runtime.error?.(`[tlon] Channel refresh error: ${formatErrorMessage$1(error)}`);
3105
+ }
3106
+ }, 120 * 1e3);
3107
+ if (opts.abortSignal) {
3108
+ const signal = opts.abortSignal;
3109
+ await new Promise((resolve) => {
3110
+ signal.addEventListener("abort", () => {
3111
+ clearInterval(pollInterval);
3112
+ resolve(null);
3113
+ }, { once: true });
3114
+ });
3115
+ } else await new Promise(() => {});
3116
+ } finally {
3117
+ try {
3118
+ await api?.close();
3119
+ } catch (error) {
3120
+ runtime.error?.(`[tlon] Cleanup error: ${formatErrorMessage$1(error)}`);
3121
+ }
3122
+ }
3123
+ }
3124
+ //#endregion
3125
+ //#region extensions/tlon/src/tlon-api.ts
3126
+ const MEMEX_BASE_URL = "https://memex.tlon.network";
3127
+ const mimeToExt = {
3128
+ "image/gif": ".gif",
3129
+ "image/heic": ".heic",
3130
+ "image/heif": ".heif",
3131
+ "image/jpeg": ".jpg",
3132
+ "image/jpg": ".jpg",
3133
+ "image/png": ".png",
3134
+ "image/webp": ".webp"
3135
+ };
3136
+ let currentClientConfig = null;
3137
+ function configureClient(params) {
3138
+ currentClientConfig = {
3139
+ ...params,
3140
+ shipName: params.shipName.replace(/^~/, "")
3141
+ };
3142
+ }
3143
+ function requireClientConfig() {
3144
+ if (!currentClientConfig) throw new Error("Tlon client not configured");
3145
+ return currentClientConfig;
3146
+ }
3147
+ function getExtensionFromMimeType(mimeType) {
3148
+ if (!mimeType) return ".jpg";
3149
+ return mimeToExt[normalizeLowercaseStringOrEmpty(mimeType)] || ".jpg";
3150
+ }
3151
+ function hasCustomS3Creds(credentials) {
3152
+ return Boolean(credentials?.accessKeyId && credentials?.endpoint && credentials?.secretAccessKey);
3153
+ }
3154
+ function isStorageCredentials(value) {
3155
+ if (!value || typeof value !== "object") return false;
3156
+ const record = value;
3157
+ return typeof record.endpoint === "string" && typeof record.accessKeyId === "string" && typeof record.secretAccessKey === "string";
3158
+ }
3159
+ function hostnameMatchesDomainBoundary(hostname, domain) {
3160
+ return hostname === domain || hostname.endsWith(`.${domain}`);
3161
+ }
3162
+ function isHostedShipUrl(shipUrl) {
3163
+ const hostname = extractShipHostname(shipUrl);
3164
+ return hostname !== null && isHostedTlonHostname(hostname);
3165
+ }
3166
+ function extractShipHostname(shipUrl) {
3167
+ const trimmed = shipUrl.trim();
3168
+ if (!trimmed) return null;
3169
+ const normalized = /^[a-zA-Z][\w+.-]*:\/\//.test(trimmed) ? trimmed : `https://${trimmed}`;
3170
+ try {
3171
+ return new URL(normalized).hostname;
3172
+ } catch {
3173
+ return null;
3174
+ }
3175
+ }
3176
+ function isHostedTlonHostname(hostname) {
3177
+ return hostnameMatchesDomainBoundary(hostname, "tlon.network") || hostnameMatchesDomainBoundary(hostname, "test.tlon.systems");
3178
+ }
3179
+ function assertTrustedMemexUploadUrl(rawUrl, label) {
3180
+ let parsed;
3181
+ try {
3182
+ parsed = new URL(rawUrl);
3183
+ } catch {
3184
+ throw new Error(`${label} must be a valid https URL`);
3185
+ }
3186
+ if (parsed.protocol !== "https:") throw new Error(`${label} must use https`);
3187
+ if (!isHostedTlonHostname(parsed.hostname)) throw new Error(`${label} must target a trusted hosted Tlon domain`);
3188
+ if (parsed.port && parsed.port !== "443") throw new Error(`${label} must not specify a non-standard port`);
3189
+ return parsed.toString();
3190
+ }
3191
+ function assertSafeUploadResultUrl(rawUrl, label) {
3192
+ let parsed;
3193
+ try {
3194
+ parsed = new URL(rawUrl);
3195
+ } catch {
3196
+ throw new Error(`${label} must be a valid http(s) URL`);
3197
+ }
3198
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new Error(`${label} must use http or https`);
3199
+ return parsed.toString();
3200
+ }
3201
+ function prefixEndpoint(endpoint) {
3202
+ return /https?:\/\//.test(endpoint) ? endpoint : `https://${endpoint}`;
3203
+ }
3204
+ function sanitizeFileName(fileName) {
3205
+ return fileName.split(/[/\\]/).pop() || fileName;
3206
+ }
3207
+ async function getAuthCookie(config) {
3208
+ return await authenticate(config.shipUrl, await config.getCode(), { ssrfPolicy: ssrfPolicyFromDangerouslyAllowPrivateNetwork(config.dangerouslyAllowPrivateNetwork) });
3209
+ }
3210
+ async function scryJson(config, cookie, path) {
3211
+ return await scryUrbitPath({
3212
+ baseUrl: config.shipUrl,
3213
+ cookie,
3214
+ ssrfPolicy: ssrfPolicyFromDangerouslyAllowPrivateNetwork(config.dangerouslyAllowPrivateNetwork)
3215
+ }, {
3216
+ path,
3217
+ auditContext: "tlon-storage-scry"
3218
+ });
3219
+ }
3220
+ async function getStorageConfiguration(config, cookie) {
3221
+ const result = await scryJson(config, cookie, "/storage/configuration.json");
3222
+ if ("storage-update" in result && result["storage-update"]?.configuration) return result["storage-update"].configuration;
3223
+ if ("currentBucket" in result) return result;
3224
+ throw new Error("Invalid storage configuration response");
3225
+ }
3226
+ async function getStorageCredentials(config, cookie) {
3227
+ const result = await scryJson(config, cookie, "/storage/credentials.json");
3228
+ if ("storage-update" in result) return result["storage-update"]?.credentials ?? null;
3229
+ if (isStorageCredentials(result)) return result;
3230
+ return null;
3231
+ }
3232
+ async function getMemexUploadUrl(params) {
3233
+ const token = await scryJson(params.config, params.cookie, "/genuine/secret.json");
3234
+ const resolvedToken = typeof token === "string" ? token : token.secret;
3235
+ if (!resolvedToken) throw new Error("Missing genuine secret");
3236
+ const endpoint = `${MEMEX_BASE_URL}/v1/${params.config.shipName}/upload`;
3237
+ let release;
3238
+ try {
3239
+ const guarded = await fetchWithSsrFGuard({
3240
+ url: endpoint,
3241
+ init: {
3242
+ method: "PUT",
3243
+ headers: { "Content-Type": "application/json" },
3244
+ body: JSON.stringify({
3245
+ token: resolvedToken,
3246
+ contentLength: params.contentLength,
3247
+ contentType: params.contentType,
3248
+ fileName: params.fileName
3249
+ })
3250
+ },
3251
+ auditContext: "tlon-memex-upload-url",
3252
+ capture: false,
3253
+ maxRedirects: 0
3254
+ });
3255
+ release = guarded.release;
3256
+ if (!guarded.response.ok) throw new Error(`Memex upload request failed: ${guarded.response.status}`);
3257
+ const data = await guarded.response.json();
3258
+ if (!data?.url || !data.filePath) throw new Error("Invalid response from Memex");
3259
+ return {
3260
+ hostedUrl: data.filePath,
3261
+ uploadUrl: data.url
3262
+ };
3263
+ } finally {
3264
+ await release?.();
3265
+ }
3266
+ }
3267
+ async function uploadFile(params) {
3268
+ const config = requireClientConfig();
3269
+ const cookie = await getAuthCookie(config);
3270
+ const privateNetworkPolicy = ssrfPolicyFromDangerouslyAllowPrivateNetwork(config.dangerouslyAllowPrivateNetwork);
3271
+ const [storageConfig, credentials] = await Promise.all([getStorageConfiguration(config, cookie), getStorageCredentials(config, cookie)]);
3272
+ const contentType = params.contentType || params.blob.type || "application/octet-stream";
3273
+ const extension = getExtensionFromMimeType(contentType);
3274
+ const fileName = sanitizeFileName(params.fileName || `upload${extension}`);
3275
+ const fileKey = `${config.shipName}/${Date.now()}-${crypto.randomUUID()}-${fileName}`;
3276
+ if (isHostedShipUrl(config.shipUrl) && (storageConfig.service === "presigned-url" || !hasCustomS3Creds(credentials))) {
3277
+ const { hostedUrl, uploadUrl } = await getMemexUploadUrl({
3278
+ config,
3279
+ cookie,
3280
+ contentLength: params.blob.size,
3281
+ contentType,
3282
+ fileName: fileKey
3283
+ });
3284
+ const trustedUploadUrl = assertTrustedMemexUploadUrl(uploadUrl, "Memex upload URL");
3285
+ let release;
3286
+ try {
3287
+ const guarded = await fetchWithSsrFGuard({
3288
+ url: trustedUploadUrl,
3289
+ init: {
3290
+ method: "PUT",
3291
+ body: params.blob,
3292
+ headers: {
3293
+ "Cache-Control": "public, max-age=3600",
3294
+ "Content-Type": contentType
3295
+ }
3296
+ },
3297
+ auditContext: "tlon-memex-upload",
3298
+ capture: false,
3299
+ maxRedirects: 0
3300
+ });
3301
+ release = guarded.release;
3302
+ assertTrustedMemexUploadUrl(guarded.finalUrl, "Memex final upload URL");
3303
+ if (!guarded.response.ok) throw new Error(`Upload failed: ${guarded.response.status}`);
3304
+ } finally {
3305
+ await release?.();
3306
+ }
3307
+ return { url: assertTrustedMemexUploadUrl(hostedUrl, "Memex hosted URL") };
3308
+ }
3309
+ if (!hasCustomS3Creds(credentials)) throw new Error("No storage credentials configured");
3310
+ const endpoint = new URL(prefixEndpoint(credentials.endpoint));
3311
+ const client = new S3Client({
3312
+ endpoint: {
3313
+ protocol: endpoint.protocol.slice(0, -1),
3314
+ hostname: endpoint.host,
3315
+ path: endpoint.pathname || "/"
3316
+ },
3317
+ region: storageConfig.region || "us-east-1",
3318
+ credentials: {
3319
+ accessKeyId: credentials.accessKeyId,
3320
+ secretAccessKey: credentials.secretAccessKey
3321
+ },
3322
+ forcePathStyle: true
3323
+ });
3324
+ const headers = {
3325
+ "Cache-Control": "public, max-age=3600",
3326
+ "Content-Type": contentType,
3327
+ "x-amz-acl": "public-read"
3328
+ };
3329
+ const signedUrl = await getSignedUrl(client, new PutObjectCommand({
3330
+ Bucket: storageConfig.currentBucket,
3331
+ Key: fileKey,
3332
+ ContentType: headers["Content-Type"],
3333
+ CacheControl: headers["Cache-Control"],
3334
+ ACL: "public-read"
3335
+ }), {
3336
+ expiresIn: 3600,
3337
+ signableHeaders: new Set(Object.keys(headers))
3338
+ });
3339
+ let release;
3340
+ try {
3341
+ const guarded = await fetchWithSsrFGuard({
3342
+ url: signedUrl,
3343
+ init: {
3344
+ method: "PUT",
3345
+ body: params.blob,
3346
+ headers: signedUrl.includes("digitaloceanspaces.com") ? headers : void 0
3347
+ },
3348
+ auditContext: "tlon-custom-s3-upload",
3349
+ capture: false,
3350
+ maxRedirects: 0,
3351
+ policy: privateNetworkPolicy
3352
+ });
3353
+ release = guarded.release;
3354
+ if (!guarded.response.ok) throw new Error(`Upload failed: ${guarded.response.status}`);
3355
+ } finally {
3356
+ await release?.();
3357
+ }
3358
+ return { url: assertSafeUploadResultUrl(storageConfig.publicUrlBase ? new URL(fileKey, storageConfig.publicUrlBase).toString() : signedUrl.split("?")[0], "Upload result URL") };
3359
+ }
3360
+ //#endregion
3361
+ //#region extensions/tlon/src/urbit/upload.ts
3362
+ /**
3363
+ * Upload an image from a URL to Tlon storage.
3364
+ */
3365
+ /**
3366
+ * Fetch an image from a URL and upload it to Tlon storage.
3367
+ * Returns the uploaded URL, or falls back to the original URL on error.
3368
+ *
3369
+ * Note: configureClient must be called before using this function.
3370
+ */
3371
+ async function uploadImageFromUrl(imageUrl) {
3372
+ try {
3373
+ const url = new URL(imageUrl);
3374
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
3375
+ console.warn(`[tlon] Rejected non-http(s) URL: ${imageUrl}`);
3376
+ return imageUrl;
3377
+ }
3378
+ const { response, release } = await fetchWithSsrFGuard({
3379
+ url: imageUrl,
3380
+ init: { method: "GET" },
3381
+ policy: /* @__PURE__ */ getDefaultSsrFPolicy(),
3382
+ auditContext: "tlon-upload-image"
3383
+ });
3384
+ try {
3385
+ if (!response.ok) {
3386
+ console.warn(`[tlon] Failed to fetch image from ${imageUrl}: ${response.status}`);
3387
+ return imageUrl;
3388
+ }
3389
+ const contentType = response.headers.get("content-type") || "image/png";
3390
+ return (await uploadFile({
3391
+ blob: await response.blob(),
3392
+ fileName: new URL(imageUrl).pathname.split("/").pop() || `upload-${Date.now()}.png`,
3393
+ contentType
3394
+ })).url;
3395
+ } finally {
3396
+ await release();
3397
+ }
3398
+ } catch (err) {
3399
+ console.warn(`[tlon] Failed to upload image, using original URL: ${String(err)}`);
3400
+ return imageUrl;
3401
+ }
3402
+ }
3403
+ //#endregion
3404
+ //#region extensions/tlon/src/channel.runtime.ts
3405
+ async function createHttpPokeApi(params) {
3406
+ const ssrfPolicy = ssrfPolicyFromDangerouslyAllowPrivateNetwork(params.dangerouslyAllowPrivateNetwork);
3407
+ const cookie = await authenticate(params.url, params.code, { ssrfPolicy });
3408
+ const channelPath = `/~/channel/${`${Math.floor(Date.now() / 1e3)}-${crypto.randomUUID()}`}`;
3409
+ const shipName = params.ship.replace(/^~/, "");
3410
+ return {
3411
+ poke: async (pokeParams) => {
3412
+ const pokeId = Date.now();
3413
+ const pokeData = {
3414
+ id: pokeId,
3415
+ action: "poke",
3416
+ ship: shipName,
3417
+ app: pokeParams.app,
3418
+ mark: pokeParams.mark,
3419
+ json: pokeParams.json
3420
+ };
3421
+ const { response, release } = await urbitFetch({
3422
+ baseUrl: params.url,
3423
+ path: channelPath,
3424
+ init: {
3425
+ method: "PUT",
3426
+ headers: {
3427
+ "Content-Type": "application/json",
3428
+ Cookie: cookie.split(";")[0]
3429
+ },
3430
+ body: JSON.stringify([pokeData])
3431
+ },
3432
+ ssrfPolicy,
3433
+ auditContext: "tlon-poke"
3434
+ });
3435
+ try {
3436
+ if (!response.ok && response.status !== 204) {
3437
+ const errorText = await response.text();
3438
+ throw new Error(`Poke failed: ${response.status} - ${errorText}`);
3439
+ }
3440
+ return pokeId;
3441
+ } finally {
3442
+ await release();
3443
+ }
3444
+ },
3445
+ delete: async () => {}
3446
+ };
3447
+ }
3448
+ function resolveOutboundContext(params) {
3449
+ const account = resolveTlonAccount(params.cfg, params.accountId ?? void 0);
3450
+ if (!account.configured || !account.ship || !account.url || !account.code) throw new Error("Tlon account not configured");
3451
+ const parsed = parseTlonTarget(params.to);
3452
+ if (!parsed) throw new Error(`Invalid Tlon target. Use ${formatTargetHint()}`);
3453
+ return {
3454
+ account,
3455
+ parsed
3456
+ };
3457
+ }
3458
+ function resolveReplyId(replyToId, threadId) {
3459
+ return replyToId ?? threadId ? String(replyToId ?? threadId) : void 0;
3460
+ }
3461
+ async function withHttpPokeAccountApi(account, run) {
3462
+ const api = await createHttpPokeApi({
3463
+ url: account.url,
3464
+ ship: account.ship,
3465
+ code: account.code,
3466
+ dangerouslyAllowPrivateNetwork: account.dangerouslyAllowPrivateNetwork ?? void 0
3467
+ });
3468
+ try {
3469
+ return await run(api);
3470
+ } finally {
3471
+ try {
3472
+ await api.delete();
3473
+ } catch {}
3474
+ }
3475
+ }
3476
+ const tlonRuntimeOutbound = {
3477
+ deliveryMode: "direct",
3478
+ textChunkLimit: 1e4,
3479
+ resolveTarget: ({ to }) => resolveTlonOutboundTarget(to),
3480
+ sendText: async ({ cfg, to, text, accountId, replyToId, threadId }) => {
3481
+ const { account, parsed } = resolveOutboundContext({
3482
+ cfg,
3483
+ accountId,
3484
+ to
3485
+ });
3486
+ return withHttpPokeAccountApi(account, async (api) => {
3487
+ const fromShip = normalizeShip(account.ship);
3488
+ if (parsed.kind === "dm") return await sendDm({
3489
+ api,
3490
+ fromShip,
3491
+ toShip: parsed.ship,
3492
+ text
3493
+ });
3494
+ return await sendGroupMessage({
3495
+ api,
3496
+ fromShip,
3497
+ hostShip: parsed.hostShip,
3498
+ channelName: parsed.channelName,
3499
+ text,
3500
+ replyToId: resolveReplyId(replyToId, threadId)
3501
+ });
3502
+ });
3503
+ },
3504
+ sendMedia: async ({ cfg, to, text, mediaUrl, accountId, replyToId, threadId }) => {
3505
+ const { account, parsed } = resolveOutboundContext({
3506
+ cfg,
3507
+ accountId,
3508
+ to
3509
+ });
3510
+ configureClient({
3511
+ shipUrl: account.url,
3512
+ shipName: account.ship.replace(/^~/, ""),
3513
+ verbose: false,
3514
+ getCode: async () => account.code,
3515
+ dangerouslyAllowPrivateNetwork: account.dangerouslyAllowPrivateNetwork ?? void 0
3516
+ });
3517
+ const uploadedUrl = mediaUrl ? await uploadImageFromUrl(mediaUrl) : void 0;
3518
+ return withHttpPokeAccountApi(account, async (api) => {
3519
+ const fromShip = normalizeShip(account.ship);
3520
+ const story = buildMediaStory(text, uploadedUrl);
3521
+ if (parsed.kind === "dm") return await sendDmWithStory({
3522
+ api,
3523
+ fromShip,
3524
+ toShip: parsed.ship,
3525
+ story
3526
+ });
3527
+ return await sendGroupMessageWithStory({
3528
+ api,
3529
+ fromShip,
3530
+ hostShip: parsed.hostShip,
3531
+ channelName: parsed.channelName,
3532
+ story,
3533
+ replyToId: resolveReplyId(replyToId, threadId)
3534
+ });
3535
+ });
3536
+ }
3537
+ };
3538
+ async function probeTlonAccount(account) {
3539
+ try {
3540
+ const ssrfPolicy = ssrfPolicyFromDangerouslyAllowPrivateNetwork(account.dangerouslyAllowPrivateNetwork);
3541
+ const cookie = await authenticate(account.url, account.code, { ssrfPolicy });
3542
+ const { response, release } = await urbitFetch({
3543
+ baseUrl: account.url,
3544
+ path: "/~/name",
3545
+ init: {
3546
+ method: "GET",
3547
+ headers: { Cookie: cookie }
3548
+ },
3549
+ ssrfPolicy,
3550
+ timeoutMs: 3e4,
3551
+ auditContext: "tlon-probe-account"
3552
+ });
3553
+ try {
3554
+ if (!response.ok) return {
3555
+ ok: false,
3556
+ error: `Name request failed: ${response.status}`
3557
+ };
3558
+ return { ok: true };
3559
+ } finally {
3560
+ await release();
3561
+ }
3562
+ } catch (error) {
3563
+ return {
3564
+ ok: false,
3565
+ error: error?.message ?? String(error)
3566
+ };
3567
+ }
3568
+ }
3569
+ async function startTlonGatewayAccount(ctx) {
3570
+ const account = ctx.account;
3571
+ ctx.setStatus({
3572
+ accountId: account.accountId,
3573
+ ship: account.ship,
3574
+ url: account.url
3575
+ });
3576
+ ctx.log?.info(`[${account.accountId}] starting Tlon provider for ${account.ship ?? "tlon"}`);
3577
+ return monitorTlonProvider({
3578
+ runtime: ctx.runtime,
3579
+ abortSignal: ctx.abortSignal,
3580
+ accountId: account.accountId
3581
+ });
3582
+ }
3583
+ //#endregion
3584
+ export { probeTlonAccount, startTlonGatewayAccount, tlonRuntimeOutbound, tlonSetupWizard };