@openclaw/tlon 2026.10.10-beta.5 → 2026.11.5-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,20 +1,20 @@
1
- import { i as __reExport, r as __exportAll } from "./doctor-contract-bInPRAQZ.mjs";
1
+ import { i as __reExport, r as __exportAll } from "./doctor-contract-CfYeTj9o.mjs";
2
2
  import { createDedupeCache, createLoggerBackedRuntime } from "../runtime-api.js";
3
- import { c as resolveTlonAccount, d as parseChannelNest, f as parseTlonTarget, l as formatTargetHint, o as validateUrbitBaseUrl, u as normalizeShip } from "./setup-core-kO8u8noA.mjs";
4
- import { t as getTlonRuntime } from "./runtime-Ck3lNvST.mjs";
5
- import { t as tlonSetupWizard } from "./setup-surface-Byac6RoF.mjs";
3
+ import { c as resolveTlonAccount, d as parseChannelNest, f as parseTlonTarget, l as formatTargetHint, o as validateUrbitBaseUrl, u as normalizeShip } from "./setup-core-BjuM9rjU.mjs";
4
+ import { t as getTlonRuntime } from "./runtime-ReERXJF_.mjs";
5
+ import { t as tlonSetupWizard } from "./setup-surface-CsTGExtf.mjs";
6
6
  import { fetchWithSsrFGuard, ssrfPolicyFromDangerouslyAllowPrivateNetwork } from "openclaw/plugin-sdk/ssrf-runtime";
7
- import { bindIngressLifecycleToReplyOptions, createChannelIngressError, createChannelIngressMonitor, createMessageReceiptFromOutboundResults, waitUntilAbort } from "openclaw/plugin-sdk/channel-outbound";
8
- import { expectDefined } from "openclaw/plugin-sdk/expect-runtime";
7
+ import { bindIngressLifecycleToReplyOptions, createArmableStallWatchdog, createChannelIngressError, createChannelIngressMonitor, createMessageReceiptFromOutboundResults, waitUntilAbort } from "openclaw/plugin-sdk/channel-outbound";
9
8
  import { asBoolean, asFiniteNumber, asNullableRecord, filterStringEntries, normalizeLowercaseStringOrEmpty, normalizeNullableString, readStringField, uniqueStrings } from "openclaw/plugin-sdk/string-coerce-runtime";
9
+ import { expectDefined } from "openclaw/plugin-sdk/expect-runtime";
10
10
  import crypto, { randomBytes, randomUUID } from "node:crypto";
11
- import { readProviderJsonResponse, readResponseTextLimited } from "openclaw/plugin-sdk/provider-http";
12
11
  import { escapeRegExp, runChannelProbe, sliceUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
13
12
  import { resolveHumanDelayConfig } from "openclaw/plugin-sdk/agent-runtime";
14
13
  import { createChannelInboundEnvelopeBuilderAsync, formatAgentEnvelope, formatInboundMediaUnavailableText, resolveEnvelopeFormatOptions } from "openclaw/plugin-sdk/channel-inbound";
15
14
  import { collectErrorGraphCandidates, formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
16
15
  import { retryAsync } from "openclaw/plugin-sdk/retry-runtime";
17
16
  import { sleepWithAbort } from "openclaw/plugin-sdk/runtime-env";
17
+ import { readProviderJsonResponse, readResponseTextLimited } from "openclaw/plugin-sdk/provider-http";
18
18
  import { redactToolPayloadText } from "openclaw/plugin-sdk/logging-core";
19
19
  import { da, scot } from "@urbit/aura";
20
20
  import { Readable } from "node:stream";
@@ -25,7 +25,7 @@ import { bufferToBlobPart } from "openclaw/plugin-sdk/blob-runtime";
25
25
  import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
26
26
  import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
27
27
  import { extensionForMime } from "openclaw/plugin-sdk/media-mime";
28
- //#region extensions/tlon/src/settings.ts
28
+ // extensions/tlon/src/settings.ts
29
29
  const SETTINGS_DESK = "moltbot";
30
30
  const SETTINGS_BUCKET = "tlon";
31
31
  function parseJsonSetting(value) {
@@ -147,60 +147,46 @@ function createSettingsManager(api, logger) {
147
147
  }
148
148
  };
149
149
  }
150
- //#endregion
151
- //#region extensions/tlon/src/urbit/redact.ts
150
+ // extensions/tlon/src/urbit/redact.ts
152
151
  const URBIT_COOKIE_REFLECTION_RE = /\burbauth-[a-z0-9~-]+=[^\s"'(),;]+/gi;
153
152
  function redactUrbitErrorText(text) {
154
153
  return redactToolPayloadText(text).replace(URBIT_COOKIE_REFLECTION_RE, "***");
155
154
  }
156
- //#endregion
157
- //#region extensions/tlon/src/urbit/errors.ts
158
- var UrbitError = class extends Error {
159
- constructor(code, message, options) {
160
- super(message, options);
161
- this.name = "UrbitError";
162
- this.code = code;
163
- }
164
- };
165
- var UrbitUrlError = class extends UrbitError {
166
- constructor(message, options) {
167
- super("invalid_url", message, options);
155
+ // extensions/tlon/src/urbit/errors.ts
156
+ var UrbitUrlError = class extends Error {
157
+ constructor(message) {
158
+ super(message);
168
159
  this.name = "UrbitUrlError";
169
160
  }
170
161
  };
171
- var UrbitHttpError = class extends UrbitError {
162
+ var UrbitHttpError = class extends Error {
172
163
  constructor(params) {
173
164
  const bodyText = params.bodyText ? redactUrbitErrorText(params.bodyText) : void 0;
174
165
  const suffix = bodyText ? ` - ${bodyText}` : "";
175
- super("http_error", `${params.operation} failed: ${params.status}${suffix}`, { cause: params.cause });
166
+ super(`${params.operation} failed: ${params.status}${suffix}`);
176
167
  this.name = "UrbitHttpError";
177
168
  this.status = params.status;
178
- this.operation = params.operation;
179
- this.bodyText = bodyText;
180
169
  }
181
170
  };
182
- var UrbitAuthError = class extends UrbitError {
183
- constructor(code, message, options) {
184
- super(code, message, options);
171
+ var UrbitAuthError = class extends Error {
172
+ constructor(message) {
173
+ super(message);
185
174
  this.name = "UrbitAuthError";
186
175
  }
187
176
  };
188
- //#endregion
189
- //#region extensions/tlon/src/urbit/fetch.ts
177
+ // extensions/tlon/src/urbit/fetch.ts
190
178
  async function urbitFetch(params) {
191
179
  const validated = validateUrbitBaseUrl(params.baseUrl);
192
180
  if (!validated.ok) throw new UrbitUrlError(validated.error);
193
181
  const url = new URL(params.path, validated.baseUrl).toString();
194
182
  const guarded = await fetchWithSsrFGuard({
195
183
  url,
196
- fetchImpl: params.fetchImpl,
197
184
  beforeRequest: params.beforeRequest,
198
185
  init: params.init,
199
186
  timeoutMs: params.timeoutMs,
200
187
  maxRedirects: params.maxRedirects,
201
188
  signal: params.signal,
202
189
  policy: params.ssrfPolicy,
203
- lookupFn: params.lookupFn,
204
190
  auditContext: params.auditContext
205
191
  });
206
192
  return {
@@ -211,8 +197,7 @@ async function urbitFetch(params) {
211
197
  }
212
198
  };
213
199
  }
214
- //#endregion
215
- //#region extensions/tlon/src/urbit/auth.ts
200
+ // extensions/tlon/src/urbit/auth.ts
216
201
  const MAX_AUTH_BODY_DRAIN_BYTES = 65536;
217
202
  async function authenticate(url, code, options = {}) {
218
203
  const { response, release } = await urbitFetch({
@@ -224,25 +209,22 @@ async function authenticate(url, code, options = {}) {
224
209
  body: new URLSearchParams({ password: code }).toString()
225
210
  },
226
211
  ssrfPolicy: options.ssrfPolicy,
227
- lookupFn: options.lookupFn,
228
- fetchImpl: options.fetchImpl,
229
212
  beforeRequest: options.beforeRequest,
230
213
  timeoutMs: 15e3,
231
214
  maxRedirects: 3,
232
215
  auditContext: "tlon-urbit-login"
233
216
  });
234
217
  try {
235
- if (!response.ok) throw new UrbitAuthError("auth_failed", `Login failed with status ${response.status}`);
218
+ if (!response.ok) throw new UrbitAuthError(`Login failed with status ${response.status}`);
236
219
  await readResponseTextLimited(response, MAX_AUTH_BODY_DRAIN_BYTES).catch(() => void 0);
237
220
  const cookie = response.headers.get("set-cookie");
238
- if (!cookie) throw new UrbitAuthError("missing_cookie", "No authentication cookie received");
221
+ if (!cookie) throw new UrbitAuthError("No authentication cookie received");
239
222
  return cookie;
240
223
  } finally {
241
224
  await release();
242
225
  }
243
226
  }
244
- //#endregion
245
- //#region extensions/tlon/src/urbit/context.ts
227
+ // extensions/tlon/src/urbit/context.ts
246
228
  function normalizeUrbitCookie(cookie) {
247
229
  return cookie.split(";")[0] ?? cookie;
248
230
  }
@@ -251,12 +233,10 @@ function getUrbitContext(url, ship) {
251
233
  if (!validated.ok) throw new UrbitUrlError(validated.error);
252
234
  return {
253
235
  baseUrl: validated.baseUrl,
254
- hostname: validated.hostname,
255
236
  ship: (ship?.replace(/^~/, "") ?? validated.hostname.split(".")[0] ?? validated.hostname).trim()
256
237
  };
257
238
  }
258
- //#endregion
259
- //#region extensions/tlon/src/urbit/story.ts
239
+ // extensions/tlon/src/urbit/story.ts
260
240
  function matchMarkdownDestination(text, image) {
261
241
  const prefix = (image ? /^!\[([^\]]*)\]\(/ : /^\[([^\]]+)\]\(/).exec(text);
262
242
  if (!prefix) return null;
@@ -424,9 +404,6 @@ const MARKDOWN_LIST_ITEM_PATTERN = /^([ \t]*)([-+*]|\d{1,9}[.)])(?:([ \t]+)(.*))
424
404
  function isMarkdownThematicBreak(text) {
425
405
  return /^(?:(?:\*\s*){3,}|(?:-\s*){3,}|(?:_\s*){3,})$/.test(text);
426
406
  }
427
- function startsListBlockSyntax(text) {
428
- return /^(`{3,}|~{3,})/.test(text) || text.startsWith(">") || /^#{1,6}(?:\s|$)/.test(text) || isMarkdownThematicBreak(text) || /^(?:[-+*]|\d{1,9}[.)])(?:\s|$)/.test(text);
429
- }
430
407
  function whitespaceColumns(text, startColumn = 0) {
431
408
  let column = startColumn;
432
409
  for (const char of text) column += char === " " ? 4 - column % 4 : 1;
@@ -457,7 +434,7 @@ function parseMarkdownListItem(line) {
457
434
  markerKey: markerType === "ordered" ? marker.slice(-1) : marker,
458
435
  ...markerType === "ordered" ? { orderedStart: Number.parseInt(marker, 10) } : {},
459
436
  hasSourceBody: sourceBody.length > 0,
460
- hasBlockBody: sourceBody.length > 0 && (contentIndent - markerEnd >= 5 || startsListBlockSyntax(sourceBody)),
437
+ hasBlockBody: sourceBody.length > 0 && (contentIndent - markerEnd >= 5 || /^(`{3,}|~{3,})/.test(sourceBody) || sourceBody.startsWith(">") || /^#{1,6}(?:\s|$)/.test(sourceBody) || isMarkdownThematicBreak(sourceBody) || /^(?:[-+*]|\d{1,9}[.)])(?:\s|$)/.test(sourceBody)),
461
438
  hasImages: imageBlocks.length > 0,
462
439
  content: inlines,
463
440
  ...checked === void 0 ? {} : { checked }
@@ -478,19 +455,16 @@ function listItemContent(item) {
478
455
  function canInterruptWithListItem(item) {
479
456
  return item.hasSourceBody && (item.markerType === "unordered" || item.orderedStart === 1);
480
457
  }
481
- function parseListingBlock(lines, startIndex) {
482
- const first = parseMarkdownListItem(expectDefined(lines[startIndex], "list start line"));
483
- if (!first) return;
484
- if (first.indent >= 4 || first.markerType === "ordered" && first.orderedStart !== 1) return;
485
- function parseLevel(index, minIndent, markerKey) {
486
- const firstItem = parseMarkdownListItem(expectDefined(lines[index], "list level start"));
487
- if (!firstItem || firstItem.indent < minIndent || firstItem.indent > minIndent + 3 || firstItem.markerType === "ordered" && firstItem.orderedStart !== 1) return;
458
+ function parseListingBlock(lines, startIndex, first) {
459
+ if (!first || first.indent >= 4 || first.markerType === "ordered" && first.orderedStart !== 1) return;
460
+ function parseLevel(index, minIndent, firstItem) {
488
461
  const items = [];
462
+ const markerKey = firstItem.markerKey;
489
463
  const markerType = firstItem.markerType;
490
464
  let allTasks = true;
491
465
  let cursor = index;
492
466
  while (cursor < lines.length) {
493
- const item = parseMarkdownListItem(expectDefined(lines[cursor], "list line index"));
467
+ const item = cursor === index ? firstItem : parseMarkdownListItem(expectDefined(lines[cursor], "list line index"));
494
468
  if (!item || item.indent < minIndent || item.indent > minIndent + 3 || item.markerKey !== markerKey) break;
495
469
  if (item.hasBlockBody || item.hasImages) return;
496
470
  allTasks &&= item.checked !== void 0;
@@ -523,7 +497,7 @@ function parseListingBlock(lines, startIndex) {
523
497
  if (child && child.indent >= item.contentIndent && !canInterruptWithListItem(child)) return;
524
498
  if (child && child.indent > item.indent) {
525
499
  if (child.indent < item.contentIndent || child.indent >= item.contentIndent + 4) return;
526
- const nested = parseLevel(cursor, item.contentIndent, child.markerKey);
500
+ const nested = parseLevel(cursor, item.contentIndent, child);
527
501
  if (!nested) return;
528
502
  items.push({ list: {
529
503
  type: nested.type,
@@ -546,7 +520,7 @@ function parseListingBlock(lines, startIndex) {
546
520
  nextIndex: cursor
547
521
  };
548
522
  }
549
- const parsed = parseLevel(startIndex, 0, first.markerKey);
523
+ const parsed = parseLevel(startIndex, 0, first);
550
524
  if (!parsed) return;
551
525
  return {
552
526
  verses: [{ block: { listing: { list: {
@@ -621,7 +595,7 @@ function markdownToStory(markdown) {
621
595
  continue;
622
596
  }
623
597
  const preservesLooseList = preservedListMarkerKey !== void 0 && lineListItem?.markerKey === preservedListMarkerKey;
624
- const listing = preservesLooseList ? void 0 : parseListingBlock(lines, i);
598
+ const listing = preservesLooseList ? void 0 : parseListingBlock(lines, i, lineListItem);
625
599
  if (listing) {
626
600
  story.push(...listing.verses);
627
601
  i = listing.nextIndex;
@@ -636,7 +610,7 @@ function markdownToStory(markdown) {
636
610
  if (paragraphLine === void 0 || paragraphLine.trim() === "" || startsTopLevelStoryBlock(paragraphLine)) break;
637
611
  if (!preserveListText && MARKDOWN_LIST_ITEM_PATTERN.test(paragraphLine)) {
638
612
  const item = parseMarkdownListItem(paragraphLine);
639
- const candidate = parseListingBlock(lines, i);
613
+ const candidate = parseListingBlock(lines, i, item);
640
614
  if (item?.hasSourceBody === true && candidate) break;
641
615
  preserveListText = true;
642
616
  if (item) preservedListMarkerKey = item.markerKey;
@@ -652,8 +626,7 @@ function markdownToStory(markdown) {
652
626
  }
653
627
  return story;
654
628
  }
655
- //#endregion
656
- //#region extensions/tlon/src/urbit/send.ts
629
+ // extensions/tlon/src/urbit/send.ts
657
630
  function createTlonSendReceipt(params) {
658
631
  return createMessageReceiptFromOutboundResults({
659
632
  results: [{
@@ -761,8 +734,7 @@ function buildMediaStory(text, mediaUrl) {
761
734
  } }] });
762
735
  return story.length > 0 ? story : [{ inline: [""] }];
763
736
  }
764
- //#endregion
765
- //#region extensions/tlon/src/urbit/channel-ops.ts
737
+ // extensions/tlon/src/urbit/channel-ops.ts
766
738
  async function putUrbitChannel(deps, params) {
767
739
  return await urbitFetch({
768
740
  baseUrl: deps.baseUrl,
@@ -776,8 +748,6 @@ async function putUrbitChannel(deps, params) {
776
748
  body: JSON.stringify(params.body)
777
749
  },
778
750
  ssrfPolicy: deps.ssrfPolicy,
779
- lookupFn: deps.lookupFn,
780
- fetchImpl: deps.fetchImpl,
781
751
  timeoutMs: params.timeoutMs,
782
752
  auditContext: params.auditContext,
783
753
  beforeRequest: params.beforeRequest
@@ -796,7 +766,8 @@ async function pokeUrbitChannel(deps, params) {
796
766
  json: params.json
797
767
  }],
798
768
  auditContext: params.auditContext,
799
- timeoutMs: 3e4
769
+ timeoutMs: params.timeoutMs,
770
+ beforeRequest: params.beforeRequest
800
771
  });
801
772
  try {
802
773
  if (!response.ok && response.status !== 204) {
@@ -822,8 +793,6 @@ async function scryUrbitPath(deps, params) {
822
793
  headers: { Cookie: deps.cookie }
823
794
  },
824
795
  ssrfPolicy: deps.ssrfPolicy,
825
- lookupFn: deps.lookupFn,
826
- fetchImpl: deps.fetchImpl,
827
796
  beforeRequest: deps.beforeRequest,
828
797
  timeoutMs: 3e4,
829
798
  auditContext: params.auditContext
@@ -873,10 +842,10 @@ async function ensureUrbitChannelOpen(deps, params) {
873
842
  beforeRequest: params.beforeRequest
874
843
  });
875
844
  }
876
- //#endregion
877
- //#region extensions/tlon/src/urbit/sse-client.ts
845
+ // extensions/tlon/src/urbit/sse-client.ts
878
846
  const MAX_SSE_PAYLOAD_BYTES = 16777216;
879
847
  const MAX_RECONNECT_ATTEMPTS = 10;
848
+ const SSE_STALL_TIMEOUT_MS = 6e4;
880
849
  function parseUrbitSsePayload(data) {
881
850
  if (Buffer.byteLength(data, "utf8") > MAX_SSE_PAYLOAD_BYTES) throw new Error("Tlon Urbit SSE payload exceeds 16 MiB limit");
882
851
  try {
@@ -912,8 +881,6 @@ var UrbitSSEClient = class {
912
881
  this.onReconnect = options.onReconnect ?? null;
913
882
  this.logger = options.logger ?? {};
914
883
  this.ssrfPolicy = options.ssrfPolicy;
915
- this.lookupFn = options.lookupFn;
916
- this.fetchImpl = options.fetchImpl;
917
884
  }
918
885
  channelRequestContext() {
919
886
  return {
@@ -921,9 +888,7 @@ var UrbitSSEClient = class {
921
888
  cookie: this.cookie,
922
889
  ship: this.ship,
923
890
  channelId: this.channelId,
924
- ssrfPolicy: this.ssrfPolicy,
925
- lookupFn: this.lookupFn,
926
- fetchImpl: this.fetchImpl
891
+ ssrfPolicy: this.ssrfPolicy
927
892
  };
928
893
  }
929
894
  resetChannelIdentity() {
@@ -1001,8 +966,6 @@ var UrbitSSEClient = class {
1001
966
  }
1002
967
  },
1003
968
  ssrfPolicy: this.ssrfPolicy,
1004
- lookupFn: this.lookupFn,
1005
- fetchImpl: this.fetchImpl,
1006
969
  signal: AbortSignal.any([controller.signal, this.reconnectAbortController.signal]),
1007
970
  beforeRequest: () => this.reconnectAbortController.signal.throwIfAborted(),
1008
971
  auditContext: "tlon-urbit-sse-stream"
@@ -1035,6 +998,17 @@ var UrbitSSEClient = class {
1035
998
  async processStream(body) {
1036
999
  if (!body) return;
1037
1000
  const stream = body instanceof ReadableStream ? Readable.fromWeb(body) : body;
1001
+ const streamController = this.streamController;
1002
+ const watchdog = createArmableStallWatchdog({
1003
+ label: "tlon-sse",
1004
+ timeoutMs: SSE_STALL_TIMEOUT_MS,
1005
+ onTimeout: ({ idleMs }) => {
1006
+ const error = /* @__PURE__ */ new Error(`Tlon Urbit SSE stream stalled: no data for ${Math.round(idleMs / 1e3)}s`);
1007
+ streamController?.abort(error);
1008
+ if (stream instanceof Readable) stream.destroy(error);
1009
+ }
1010
+ });
1011
+ watchdog.arm();
1038
1012
  const decoder = new TextDecoder();
1039
1013
  let buffer = "";
1040
1014
  let bufferBytes = 0;
@@ -1082,13 +1056,16 @@ var UrbitSSEClient = class {
1082
1056
  try {
1083
1057
  for await (const chunk of stream) {
1084
1058
  if (this.aborted) break;
1059
+ watchdog.disarm();
1085
1060
  if (typeof chunk === "string") {
1086
1061
  await consumeText(decoder.decode());
1087
1062
  await consumeText(chunk);
1088
1063
  } else await consumeText(decoder.decode(chunk, { stream: true }));
1064
+ watchdog.arm();
1089
1065
  }
1090
1066
  await consumeText(decoder.decode());
1091
1067
  } finally {
1068
+ watchdog.stop();
1092
1069
  if (this.streamRelease) {
1093
1070
  const release = this.streamRelease;
1094
1071
  this.streamRelease = null;
@@ -1140,17 +1117,20 @@ var UrbitSSEClient = class {
1140
1117
  if (eventId === null || eventId <= this.lastAcknowledgedEventId) return;
1141
1118
  this.lastHeardEventId = Math.max(this.lastHeardEventId, eventId);
1142
1119
  if (this.lastHeardEventId - this.lastAcknowledgedEventId <= this.ackThreshold) return;
1143
- this.logger.log?.(`[SSE] Acking event ${this.lastHeardEventId} (last acked: ${this.lastAcknowledgedEventId})`);
1144
1120
  await this.ack(this.lastHeardEventId);
1145
1121
  }
1146
1122
  async poke(params) {
1147
1123
  return await pokeUrbitChannel(this.channelRequestContext(), {
1148
1124
  ...params,
1149
- auditContext: "tlon-urbit-poke"
1125
+ auditContext: "tlon-urbit-poke",
1126
+ timeoutMs: 3e4
1150
1127
  });
1151
1128
  }
1152
- async scry(path) {
1153
- return await scryUrbitPath(this.channelRequestContext(), {
1129
+ async scry(path, beforeRequest) {
1130
+ return await scryUrbitPath({
1131
+ ...this.channelRequestContext(),
1132
+ beforeRequest
1133
+ }, {
1154
1134
  path,
1155
1135
  auditContext: "tlon-urbit-scry"
1156
1136
  });
@@ -1219,33 +1199,17 @@ var UrbitSSEClient = class {
1219
1199
  async close() {
1220
1200
  this.stopReceiving();
1221
1201
  try {
1222
- const unsubscribes = this.subscriptions.map((sub) => ({
1223
- id: sub.id,
1224
- action: "unsubscribe",
1225
- subscription: sub.id
1226
- }));
1227
- {
1228
- const { release } = await putUrbitChannel(this.channelRequestContext(), {
1229
- body: unsubscribes,
1230
- timeoutMs: 3e4,
1231
- auditContext: "tlon-urbit-unsubscribe"
1232
- });
1233
- await release();
1234
- }
1235
- {
1236
- const { release } = await urbitFetch({
1237
- baseUrl: this.url,
1238
- path: `/~/channel/${this.channelId}`,
1239
- init: {
1240
- method: "DELETE",
1241
- headers: { Cookie: this.cookie }
1242
- },
1243
- ssrfPolicy: this.ssrfPolicy,
1244
- lookupFn: this.lookupFn,
1245
- fetchImpl: this.fetchImpl,
1246
- timeoutMs: 3e4,
1247
- auditContext: "tlon-urbit-channel-close"
1202
+ const { response, release } = await putUrbitChannel(this.channelRequestContext(), {
1203
+ body: [{ action: "delete" }],
1204
+ timeoutMs: 3e4,
1205
+ auditContext: "tlon-urbit-channel-close"
1206
+ });
1207
+ try {
1208
+ if (!response.ok) throw new UrbitHttpError({
1209
+ operation: "Channel close",
1210
+ status: response.status
1248
1211
  });
1212
+ } finally {
1249
1213
  await release();
1250
1214
  }
1251
1215
  } catch (error) {
@@ -1267,14 +1231,11 @@ var UrbitSSEClient = class {
1267
1231
  }
1268
1232
  }
1269
1233
  };
1270
- //#endregion
1271
- //#region extensions/tlon/src/monitor/approval.ts
1272
- function generateApprovalId(type) {
1273
- return `${type}-${Date.now()}-${randomBytes(3).toString("hex")}`;
1274
- }
1234
+ // extensions/tlon/src/monitor/approval.ts
1275
1235
  function createPendingApproval(params) {
1236
+ const timestamp = Date.now();
1276
1237
  return {
1277
- id: generateApprovalId(params.type),
1238
+ id: `${params.type}-${timestamp}-${randomBytes(3).toString("hex")}`,
1278
1239
  type: params.type,
1279
1240
  requestingShip: params.requestingShip,
1280
1241
  ...params.clubId !== void 0 ? { clubId: params.clubId } : {},
@@ -1283,24 +1244,27 @@ function createPendingApproval(params) {
1283
1244
  groupFlag: params.groupFlag,
1284
1245
  messagePreview: params.messagePreview != null ? sliceUtf16Safe(params.messagePreview, 0, 100) : void 0,
1285
1246
  originalMessage: params.originalMessage,
1286
- timestamp: Date.now()
1247
+ timestamp
1287
1248
  };
1288
1249
  }
1289
1250
  function truncate(text, maxLength) {
1290
1251
  if (text.length <= maxLength) return text;
1291
1252
  return sliceUtf16Safe(text, 0, maxLength - 3) + "...";
1292
1253
  }
1254
+ function formatApprovalInstructions(id) {
1255
+ return `Reply "approve", "deny", or "block" if this is the only pending request. If multiple are pending, reply "approve ${id}", "deny ${id}", or "block ${id}".`;
1256
+ }
1293
1257
  function formatApprovalRequest(approval) {
1294
1258
  const preview = approval.messagePreview ? `\n"${truncate(approval.messagePreview, 100)}"` : "";
1295
1259
  switch (approval.type) {
1296
1260
  case "dm":
1297
1261
  if (approval.clubId !== void 0) {
1298
1262
  const replayLine = approval.originalMessage ? `The message is answered as an unverified group DM sender, never as ${approval.requestingShip}.` : `The message is not kept, so it will not be answered; have ${approval.requestingShip} send it again in a normal direct message to get a reply.`;
1299
- return `New group DM message claiming to be from ${approval.requestingShip} (unverified; group DM ${approval.clubId}):${preview}\n\nApproving adds ${approval.requestingShip} to the DM allowlist. ${replayLine}\nReply "approve", "deny", or "block" (ID: ${approval.id})`;
1263
+ return `New group DM message claiming to be from ${approval.requestingShip} (unverified; group DM ${approval.clubId}):${preview}\n\nApproving adds ${approval.requestingShip} to the DM allowlist. ${replayLine}\n` + formatApprovalInstructions(approval.id);
1300
1264
  }
1301
- return `New DM request from ${approval.requestingShip}:${preview}\n\nReply "approve", "deny", or "block" (ID: ${approval.id})`;
1302
- case "channel": return `${approval.requestingShip} mentioned you in ${approval.channelNest}:${preview}\n\nReply "approve", "deny", or "block"\n(ID: ${approval.id})`;
1303
- case "group": return `Group invite from ${approval.requestingShip} to join ${approval.groupFlag}\n\nReply "approve", "deny", or "block"\n(ID: ${approval.id})`;
1265
+ return `New DM request from ${approval.requestingShip}:${preview}\n\n` + formatApprovalInstructions(approval.id);
1266
+ case "channel": return `${approval.requestingShip} mentioned you in ${approval.channelNest}:${preview}\n\n` + formatApprovalInstructions(approval.id);
1267
+ case "group": return `Group invite from ${approval.requestingShip} to join ${approval.groupFlag}\n\n` + formatApprovalInstructions(approval.id);
1304
1268
  }
1305
1269
  throw new Error("Unsupported approval type");
1306
1270
  }
@@ -1313,8 +1277,7 @@ function parseApprovalResponse(text) {
1313
1277
  };
1314
1278
  }
1315
1279
  function findPendingApproval(pendingApprovals, id) {
1316
- if (id) return pendingApprovals.find((a) => a.id === id);
1317
- return pendingApprovals[pendingApprovals.length - 1];
1280
+ return id ? pendingApprovals.find((approval) => approval.id === id) : pendingApprovals.length === 1 ? pendingApprovals[0] : void 0;
1318
1281
  }
1319
1282
  function removePendingApproval(pendingApprovals, id) {
1320
1283
  return pendingApprovals.filter((a) => a.id !== id);
@@ -1364,8 +1327,7 @@ function formatPendingList(approvals) {
1364
1327
  if (approvals.length === 0) return "No pending approval requests.";
1365
1328
  return `Pending approvals (${approvals.length}):\n${approvals.map((a) => `• ${a.id}: ${a.type} from ${a.requestingShip}`).join("\n")}`;
1366
1329
  }
1367
- //#endregion
1368
- //#region extensions/tlon/src/monitor/approval-runtime.ts
1330
+ // extensions/tlon/src/monitor/approval-runtime.ts
1369
1331
  function createTlonApprovalRuntime(params) {
1370
1332
  const { api, runtime, botShipName, state, processApprovedMessage, refreshWatchedChannels } = params;
1371
1333
  let approvalOverflowNoticeSent = false;
@@ -1495,7 +1457,7 @@ function createTlonApprovalRuntime(params) {
1495
1457
  runtime.log?.(`[tlon] Pending approval limit reached; ignoring ${approval.type} request from ${approval.requestingShip}`);
1496
1458
  if (!approvalOverflowNoticeSent && approvalOverflowNoticeAttempts < 3) {
1497
1459
  approvalOverflowNoticeAttempts += 1;
1498
- approvalOverflowNoticeSent = await sendOwnerNotification(`Pending approval queue is full (${approvals.length}). Resolve existing requests with approve, deny, or block before asking rejected requesters to retry.`);
1460
+ approvalOverflowNoticeSent = await sendOwnerNotification(`Pending approval queue is full (${approvals.length}). Resolve existing requests by replying with approve, deny, or block followed by the request ID before asking rejected requesters to retry.`);
1499
1461
  }
1500
1462
  return false;
1501
1463
  }
@@ -1512,7 +1474,7 @@ function createTlonApprovalRuntime(params) {
1512
1474
  if (!parsed) return false;
1513
1475
  const approval = findPendingApproval(state.pendingApprovals, parsed.id);
1514
1476
  if (!approval) {
1515
- await sendOwnerNotification(`No pending approval found${parsed.id ? ` for ID: ${parsed.id}` : ""}`);
1477
+ await sendOwnerNotification(parsed.id ? `No pending approval found for ID: ${parsed.id}` : state.pendingApprovals.length > 1 ? `Multiple approvals are pending. Include an approval ID with your decision.\n\n${formatPendingList(state.pendingApprovals)}` : "No pending approval found.");
1516
1478
  return true;
1517
1479
  }
1518
1480
  if (parsed.action === "approve") switch (approval.type) {
@@ -1596,8 +1558,7 @@ function createTlonApprovalRuntime(params) {
1596
1558
  handleAdminCommand
1597
1559
  };
1598
1560
  }
1599
- //#endregion
1600
- //#region extensions/tlon/src/monitor/authorization.ts
1561
+ // extensions/tlon/src/monitor/authorization.ts
1601
1562
  function resolveChannelAuthorization(cfg, channelNest, settings) {
1602
1563
  const tlonConfig = cfg.channels?.tlon;
1603
1564
  const fileRules = tlonConfig?.authorization?.channelRules ?? {};
@@ -1613,8 +1574,7 @@ function resolveChannelAuthorization(cfg, channelNest, settings) {
1613
1574
  requireMentionInBotThreads: typeof requireMentionInBotThreads === "boolean" ? requireMentionInBotThreads : void 0
1614
1575
  };
1615
1576
  }
1616
- //#endregion
1617
- //#region extensions/tlon/src/monitor/utils.ts
1577
+ // extensions/tlon/src/monitor/utils.ts
1618
1578
  function formatModelName(modelString) {
1619
1579
  if (!modelString) return "AI";
1620
1580
  const modelName = modelString.includes("/") ? expectDefined(modelString.split("/").at(1), "provider/model second segment") : modelString;
@@ -1716,7 +1676,8 @@ function isGroupInviteAllowed(inviterShip, allowlist) {
1716
1676
  }]
1717
1677
  }).allowed;
1718
1678
  }
1719
- function renderInlineItem(item, topLevel = false) {
1679
+ const MAX_INLINE_DEPTH = 100;
1680
+ function renderInlineItem(item, topLevel = false, depth = 0) {
1720
1681
  if (typeof item === "string") return item;
1721
1682
  const record = asNullableRecord(item);
1722
1683
  if (!record) return "";
@@ -1736,14 +1697,21 @@ function renderInlineItem(item, topLevel = false) {
1736
1697
  const linkContent = readStringField(link, "content");
1737
1698
  return topLevel ? linkHref : linkContent || linkHref;
1738
1699
  }
1739
- if (Array.isArray(record.bold)) return `**${extractInlineText(record.bold)}**`;
1740
- if (Array.isArray(record.italics)) return `*${extractInlineText(record.italics)}*`;
1741
- if (Array.isArray(record.strike)) return `~~${extractInlineText(record.strike)}~~`;
1742
- if (topLevel && Array.isArray(record.blockquote)) return `> ${extractInlineText(record.blockquote)}`;
1743
- return "";
1744
- }
1745
- function extractInlineText(items) {
1746
- return items.map((item) => renderInlineItem(item)).join("");
1700
+ const bold = Array.isArray(record.bold) ? record.bold : void 0;
1701
+ const italics = Array.isArray(record.italics) ? record.italics : void 0;
1702
+ const strike = Array.isArray(record.strike) ? record.strike : void 0;
1703
+ const blockquote = topLevel && Array.isArray(record.blockquote) ? record.blockquote : void 0;
1704
+ const nested = bold ?? italics ?? strike ?? blockquote;
1705
+ if (!nested) return "";
1706
+ if (depth >= MAX_INLINE_DEPTH) return "";
1707
+ const inner = extractInlineText(nested, depth + 1);
1708
+ if (bold) return `**${inner}**`;
1709
+ if (italics) return `*${inner}*`;
1710
+ if (strike) return `~~${inner}~~`;
1711
+ return `> ${inner}`;
1712
+ }
1713
+ function extractInlineText(items, depth = 0) {
1714
+ return items.map((item) => renderInlineItem(item, false, depth)).join("");
1747
1715
  }
1748
1716
  function extractMessageText(content) {
1749
1717
  if (!Array.isArray(content)) return "";
@@ -1827,10 +1795,11 @@ function formatSummarizationHistoryText(history, cfg) {
1827
1795
  envelope: envelopeOptions
1828
1796
  })).join("\n");
1829
1797
  }
1830
- //#endregion
1831
- //#region extensions/tlon/src/monitor/cites.ts
1798
+ // extensions/tlon/src/monitor/cites.ts
1832
1799
  const CITE_PATH_SEGMENT_RE = /^[A-Za-z0-9._~-]+$/;
1833
1800
  const CITE_PATH_NORMALIZATION_BASE = "https://tlon.invalid";
1801
+ const CITATION_SCOPE_SKIP_LOG = "[tlon] Skipping cited post: citation is outside explicit channel scope";
1802
+ var CitationScopeChangedError = class extends Error {};
1834
1803
  function isSafeCitePathSegment(segment) {
1835
1804
  if (segment === "." || segment === "..") return false;
1836
1805
  return CITE_PATH_SEGMENT_RE.test(segment);
@@ -1850,7 +1819,7 @@ function buildCitedPostScryPath(nest, postId) {
1850
1819
  if (new URL(scryPath, CITE_PATH_NORMALIZATION_BASE).pathname !== scryPath) return null;
1851
1820
  return scryPath;
1852
1821
  }
1853
- async function resolveTlonCitations(content, api, runtime) {
1822
+ async function resolveTlonCitations(content, canExpandNest, api, runtime) {
1854
1823
  if (!Array.isArray(content)) return "";
1855
1824
  const resolved = [];
1856
1825
  for (const verse of content) {
@@ -1860,6 +1829,10 @@ async function resolveTlonCitations(content, api, runtime) {
1860
1829
  const whereMatch = readStringField(chan, "where")?.match(/\/msg\/(~[a-z-]+)\/(.+)/);
1861
1830
  const postId = whereMatch?.[2];
1862
1831
  if (!nest || !postId) continue;
1832
+ if (!canExpandNest(nest)) {
1833
+ runtime.log?.(CITATION_SCOPE_SKIP_LOG);
1834
+ continue;
1835
+ }
1863
1836
  const scryPath = buildCitedPostScryPath(nest, postId);
1864
1837
  if (!scryPath) {
1865
1838
  runtime.log?.("[tlon] Skipping cited post: citation does not name a channel post");
@@ -1867,18 +1840,27 @@ async function resolveTlonCitations(content, api, runtime) {
1867
1840
  }
1868
1841
  try {
1869
1842
  runtime.log?.(`[tlon] Fetching cited post: ${scryPath}`);
1870
- const data = asNullableRecord(await api.scry(scryPath));
1843
+ const data = asNullableRecord(await api.scry(scryPath, () => {
1844
+ if (!canExpandNest(nest)) throw new CitationScopeChangedError();
1845
+ }));
1846
+ if (!canExpandNest(nest)) {
1847
+ runtime.log?.(CITATION_SCOPE_SKIP_LOG);
1848
+ continue;
1849
+ }
1871
1850
  const essay = asNullableRecord(data?.essay);
1872
1851
  const text = essay?.content ? extractMessageText(essay.content) : "";
1873
1852
  if (text) resolved.push(`> ${whereMatch?.[1] || "unknown"} wrote: ${text}`);
1874
1853
  } catch (err) {
1854
+ if (err instanceof CitationScopeChangedError) {
1855
+ runtime.log?.(CITATION_SCOPE_SKIP_LOG);
1856
+ continue;
1857
+ }
1875
1858
  runtime.log?.(`[tlon] Failed to fetch cited post: ${String(err)}`);
1876
1859
  }
1877
1860
  }
1878
1861
  return resolved.length > 0 ? `${resolved.join("\n")}\n\n` : "";
1879
1862
  }
1880
- //#endregion
1881
- //#region extensions/tlon/src/monitor/discovery.ts
1863
+ // extensions/tlon/src/monitor/discovery.ts
1882
1864
  /**
1883
1865
  * Fetch groups-ui init data, returning channels and foreigns.
1884
1866
  * This is a single scry that provides both channel discovery and pending invites.
@@ -1908,8 +1890,7 @@ async function fetchInitData(api, runtime) {
1908
1890
  };
1909
1891
  }
1910
1892
  }
1911
- //#endregion
1912
- //#region extensions/tlon/src/monitor/history.ts
1893
+ // extensions/tlon/src/monitor/history.ts
1913
1894
  /**
1914
1895
  * Format a number as @ud (with dots every 3 digits from the right)
1915
1896
  * e.g., 170141184507799509469114119040828178432 -> 170.141.184.507.799.509.469.114.119.040.828.178.432
@@ -1921,18 +1902,17 @@ function formatUd(id) {
1921
1902
  return chunks.toReversed().join(".");
1922
1903
  }
1923
1904
  function createHistoryEntryFromMemo(params) {
1924
- const { memo, seal, fallbackId } = params;
1905
+ const { memo } = params;
1925
1906
  return {
1926
1907
  author: typeof memo?.author === "string" ? memo.author : "unknown",
1927
1908
  content: extractMessageText(memo?.content || []),
1928
- timestamp: typeof memo?.sent === "number" ? memo.sent : Date.now(),
1929
- id: typeof seal?.id === "string" ? seal.id : typeof fallbackId === "string" ? fallbackId : void 0
1909
+ timestamp: typeof memo?.sent === "number" ? memo.sent : Date.now()
1930
1910
  };
1931
1911
  }
1932
1912
  const MAX_CACHED_MESSAGES = 100;
1933
- async function fetchChannelHistory(api, channelNest, count = 50, runtime) {
1913
+ async function fetchChannelHistory(api, channelNest, runtime) {
1934
1914
  try {
1935
- const scryPath = `/channels/v4/${channelNest}/posts/newest/${count}/outline.json`;
1915
+ const scryPath = `/channels/v4/${channelNest}/posts/newest/50/outline.json`;
1936
1916
  runtime?.log?.(`[tlon] Fetching history: ${scryPath}`);
1937
1917
  const data = await api.scry(scryPath);
1938
1918
  if (!data) return [];
@@ -1941,10 +1921,7 @@ async function fetchChannelHistory(api, channelNest, count = 50, runtime) {
1941
1921
  const itemRecord = asNullableRecord(item);
1942
1922
  const replyPost = asNullableRecord(itemRecord?.["r-post"]);
1943
1923
  const replyPostSet = asNullableRecord(replyPost?.set);
1944
- return createHistoryEntryFromMemo({
1945
- memo: asNullableRecord(itemRecord?.essay) ?? asNullableRecord(replyPostSet?.essay),
1946
- seal: asNullableRecord(itemRecord?.seal) ?? asNullableRecord(replyPostSet?.seal)
1947
- });
1924
+ return createHistoryEntryFromMemo({ memo: asNullableRecord(itemRecord?.essay) ?? asNullableRecord(replyPostSet?.essay) });
1948
1925
  }).filter((msg) => msg.content);
1949
1926
  runtime?.log?.(`[tlon] Extracted ${messages.length} messages from history`);
1950
1927
  return messages;
@@ -1962,14 +1939,14 @@ function createChannelHistoryCache() {
1962
1939
  if (cache.length > MAX_CACHED_MESSAGES) cache.pop();
1963
1940
  messageCache.set(channelNest, cache);
1964
1941
  },
1965
- async getChannelHistory(api, channelNest, count = 50, runtime) {
1942
+ async getChannelHistory(api, channelNest, runtime) {
1966
1943
  const cache = messageCache.get(channelNest) ?? [];
1967
- if (cache.length >= count) {
1944
+ if (cache.length >= 50) {
1968
1945
  runtime?.log?.(`[tlon] Using cached messages (${cache.length} available)`);
1969
- return cache.slice(0, count);
1946
+ return cache.slice(0, 50);
1970
1947
  }
1971
- runtime?.log?.(`[tlon] Cache has ${cache.length} messages, need ${count}, fetching from scry...`);
1972
- return await fetchChannelHistory(api, channelNest, count, runtime);
1948
+ runtime?.log?.(`[tlon] Cache has ${cache.length} messages, need 50, fetching from scry...`);
1949
+ return await fetchChannelHistory(api, channelNest, runtime);
1973
1950
  }
1974
1951
  };
1975
1952
  }
@@ -1984,11 +1961,11 @@ async function fetchThreadRootAuthor(api, channelNest, parentId, runtime) {
1984
1961
  return null;
1985
1962
  }
1986
1963
  }
1987
- async function fetchThreadHistory(api, channelNest, parentId, count = 50, runtime) {
1964
+ async function fetchThreadHistory(api, channelNest, parentId, runtime) {
1988
1965
  try {
1989
1966
  const formattedParentId = formatUd(parentId);
1990
1967
  runtime?.log?.(`[tlon] Thread history - parentId: ${parentId} -> formatted: ${formattedParentId}`);
1991
- const scryPath = `/channels/v4/${channelNest}/posts/post/id/${formattedParentId}/replies/newest/${count}.json`;
1968
+ const scryPath = `/channels/v4/${channelNest}/posts/post/id/${formattedParentId}/replies/newest/20.json`;
1992
1969
  runtime?.log?.(`[tlon] Fetching thread history: ${scryPath}`);
1993
1970
  const data = await api.scry(scryPath);
1994
1971
  if (!data) {
@@ -2008,11 +1985,7 @@ async function fetchThreadHistory(api, channelNest, parentId, count = 50, runtim
2008
1985
  const itemRecord = asNullableRecord(item);
2009
1986
  const replyRecord = asNullableRecord(itemRecord?.["r-reply"]);
2010
1987
  const replySet = asNullableRecord(replyRecord?.set);
2011
- return createHistoryEntryFromMemo({
2012
- memo: asNullableRecord(itemRecord?.memo) ?? asNullableRecord(replySet?.memo) ?? itemRecord,
2013
- seal: asNullableRecord(itemRecord?.seal) ?? asNullableRecord(replySet?.seal),
2014
- fallbackId: itemRecord?.id
2015
- });
1988
+ return createHistoryEntryFromMemo({ memo: asNullableRecord(itemRecord?.memo) ?? asNullableRecord(replySet?.memo) ?? itemRecord });
2016
1989
  }).filter((msg) => msg.content);
2017
1990
  runtime?.log?.(`[tlon] Extracted ${messages.length} thread replies from history`);
2018
1991
  return messages;
@@ -2028,10 +2001,7 @@ async function fetchThreadHistory(api, channelNest, parentId, count = 50, runtim
2028
2001
  if (typeof dataMeta?.replyCount === "number" && dataMeta.replyCount > 0 && repliesValue) {
2029
2002
  const messages = (Array.isArray(repliesValue) ? repliesValue : Object.values(repliesValue)).map((reply) => {
2030
2003
  const replyRecord = asNullableRecord(reply);
2031
- return createHistoryEntryFromMemo({
2032
- memo: asNullableRecord(replyRecord?.memo),
2033
- seal: asNullableRecord(replyRecord?.seal)
2034
- });
2004
+ return createHistoryEntryFromMemo({ memo: asNullableRecord(replyRecord?.memo) });
2035
2005
  }).filter((msg) => msg.content);
2036
2006
  runtime?.log?.(`[tlon] Extracted ${messages.length} replies from post data`);
2037
2007
  return messages;
@@ -2042,44 +2012,52 @@ async function fetchThreadHistory(api, channelNest, parentId, count = 50, runtim
2042
2012
  return [];
2043
2013
  }
2044
2014
  }
2045
- //#endregion
2046
- //#region extensions/tlon/src/monitor/ingress.ts
2015
+ // extensions/tlon/src/monitor/ingress.ts
2047
2016
  const TLON_INGRESS_PAYLOAD_VERSION = 1;
2048
- const TLON_INGRESS_POLL_INTERVAL_MS = 1e3;
2049
2017
  const TlonIngressPermanentError = createChannelIngressError("TlonIngressPermanentError", { withReason: true });
2050
- function inspectChannelsEvent(event) {
2018
+ var TlonIngressUnserializableEventError = class extends Error {
2019
+ constructor(cause) {
2020
+ super("Tlon firehose event is too deeply nested to store.", { cause });
2021
+ this.name = "TlonIngressUnserializableEventError";
2022
+ }
2023
+ };
2024
+ function serializeTlonIngressEvent(event) {
2025
+ try {
2026
+ return JSON.stringify(event);
2027
+ } catch (error) {
2028
+ if (error instanceof RangeError) throw new TlonIngressUnserializableEventError(error);
2029
+ throw error;
2030
+ }
2031
+ }
2032
+ function decodeTlonChannelsEvent(event) {
2051
2033
  const envelope = asNullableRecord(event);
2052
- const nest = normalizeNullableString(envelope?.nest);
2053
- const response = asNullableRecord(envelope?.response);
2054
- const post = asNullableRecord(response?.post);
2034
+ const nest = readStringField(envelope, "nest");
2035
+ const post = asNullableRecord(asNullableRecord(envelope?.response)?.post);
2055
2036
  const rPost = asNullableRecord(post?.["r-post"]);
2056
2037
  const set = asNullableRecord(rPost?.set);
2057
2038
  const reply = asNullableRecord(rPost?.reply);
2058
- const rReply = asNullableRecord(reply?.["r-reply"]);
2059
- const replySet = asNullableRecord(rReply?.set);
2060
- if (!nest || !asNullableRecord(set?.essay) && !asNullableRecord(replySet?.memo)) return null;
2061
- const eventId = normalizeNullableString(asNullableRecord(replySet?.memo) ? reply?.id : post?.id);
2062
- return eventId ? {
2063
- eventId,
2064
- laneKey: `group:${nest}`
2065
- } : null;
2066
- }
2067
- function inspectChatEvent(event) {
2068
- const envelope = asNullableRecord(event);
2069
- const response = asNullableRecord(envelope?.response);
2070
- const add = asNullableRecord(response?.add);
2071
- const essay = asNullableRecord(add?.essay);
2072
- const eventId = normalizeNullableString(envelope?.id);
2073
- if (!essay || !eventId) return null;
2074
- const whom = normalizeNullableString(asNullableRecord(envelope?.whom)?.ship);
2075
- const peer = normalizeNullableString(envelope?.whom) ?? whom ?? normalizeNullableString(essay.author);
2039
+ const replySet = asNullableRecord(asNullableRecord(reply?.["r-reply"])?.set);
2040
+ const memo = asNullableRecord(replySet?.memo);
2041
+ const content = memo ?? asNullableRecord(set?.essay);
2042
+ const messageId = readStringField(memo ? reply : post, "id");
2043
+ if (!nest || !messageId || !content) return null;
2076
2044
  return {
2077
- eventId,
2078
- laneKey: peer ? `direct:${peer}` : `event:${eventId}`
2045
+ nest,
2046
+ messageId,
2047
+ content,
2048
+ isThreadReply: Boolean(memo),
2049
+ messageSet: memo ? replySet : set
2079
2050
  };
2080
2051
  }
2081
- function inspectTlonIngressEvent(source, event) {
2082
- return source === "channels" ? inspectChannelsEvent(event) : inspectChatEvent(event);
2052
+ function decodeTlonChatEvent(event) {
2053
+ const envelope = asNullableRecord(event);
2054
+ const messageId = readStringField(envelope, "id");
2055
+ const essay = asNullableRecord(asNullableRecord(asNullableRecord(envelope?.response)?.add)?.essay);
2056
+ return envelope && messageId && essay ? {
2057
+ messageId,
2058
+ whom: envelope.whom,
2059
+ essay
2060
+ } : null;
2083
2061
  }
2084
2062
  function decodeTlonIngressPayload(payload, claimedId) {
2085
2063
  if (payload.source !== "channels" && payload.source !== "chat" || typeof payload.rawEvent !== "string") throw new TlonIngressPermanentError("invalid-event", `Tlon ingress row ${claimedId} has an invalid payload.`);
@@ -2117,14 +2095,33 @@ function resolveTlonIngressNonRetryableFailure(error) {
2117
2095
  }
2118
2096
  function createTlonIngressMonitor(options) {
2119
2097
  const monitor = createChannelIngressMonitor({
2120
- queue: options.queue ?? (() => getTlonRuntime().state.openChannelIngressQueue({ accountId: options.accountId })),
2121
- inspect: (raw) => inspectTlonIngressEvent(raw.source, raw.event),
2098
+ queue: () => getTlonRuntime().state.openChannelIngressQueue({ accountId: options.accountId }),
2099
+ inspect: ({ source, event }) => {
2100
+ if (source === "channels") {
2101
+ const message = decodeTlonChannelsEvent(event);
2102
+ const eventId = normalizeNullableString(message?.messageId);
2103
+ const nest = normalizeNullableString(message?.nest);
2104
+ return eventId && nest ? {
2105
+ eventId,
2106
+ laneKey: `group:${nest}`
2107
+ } : null;
2108
+ }
2109
+ const message = decodeTlonChatEvent(event);
2110
+ const eventId = normalizeNullableString(message?.messageId);
2111
+ if (!message || !eventId) return null;
2112
+ const whom = normalizeNullableString(asNullableRecord(message.whom)?.ship);
2113
+ const peer = normalizeNullableString(message.whom) ?? whom ?? normalizeNullableString(message.essay.author);
2114
+ return {
2115
+ eventId,
2116
+ laneKey: peer ? `direct:${peer}` : `event:${eventId}`
2117
+ };
2118
+ },
2122
2119
  payload: {
2123
2120
  version: TLON_INGRESS_PAYLOAD_VERSION,
2124
2121
  serialize: (raw, { receivedAt }) => ({
2125
2122
  receivedAt,
2126
2123
  source: raw.source,
2127
- rawEvent: JSON.stringify(raw.event)
2124
+ rawEvent: serializeTlonIngressEvent(raw.event)
2128
2125
  }),
2129
2126
  deserialize: (body, { claim }) => deserializeTlonIngressEvent(body, claim.id),
2130
2127
  encode: ({ body }) => ({
@@ -2135,7 +2132,7 @@ function createTlonIngressMonitor(options) {
2135
2132
  createClaimError: (kind, claim) => new TlonIngressPermanentError("invalid-event", kind === "invalid-version" ? `Tlon ingress row ${claim.id} has an invalid payload.` : `Tlon ingress row ${claim.id} has invalid message identity.`)
2136
2133
  },
2137
2134
  deliver: (raw, lifecycle) => options.dispatch(raw.source, raw.event, lifecycle),
2138
- pollIntervalMs: options.pollIntervalMs ?? TLON_INGRESS_POLL_INTERVAL_MS,
2135
+ pollIntervalMs: 1e3,
2139
2136
  retention: {
2140
2137
  completedTtlMs: void 0,
2141
2138
  completedMaxEntries: 2e3,
@@ -2144,7 +2141,6 @@ function createTlonIngressMonitor(options) {
2144
2141
  appendRetryDelaysMs: [0],
2145
2142
  drain: {
2146
2143
  resolveNonRetryableFailure: resolveTlonIngressNonRetryableFailure,
2147
- ...options.adoptionStallTimeoutMs === void 0 ? {} : { adoptionStallTimeoutMs: options.adoptionStallTimeoutMs },
2148
2144
  onLog: (message) => options.runtime.log?.(`tlon ${message}`)
2149
2145
  },
2150
2146
  ...options.abortSignal ? { abortSignal: options.abortSignal } : {},
@@ -2153,28 +2149,33 @@ function createTlonIngressMonitor(options) {
2153
2149
  });
2154
2150
  return {
2155
2151
  receive: async ({ source, event }) => {
2156
- return { kind: (await monitor.admit({
2157
- source,
2158
- event
2159
- })).kind === "durable" ? "accepted" : "ignored" };
2152
+ try {
2153
+ return { kind: (await monitor.admit({
2154
+ source,
2155
+ event
2156
+ })).kind === "durable" ? "accepted" : "ignored" };
2157
+ } catch (error) {
2158
+ if (error instanceof TlonIngressUnserializableEventError) {
2159
+ options.runtime.log?.(`tlon dropped ${source} event: ${error.message}`);
2160
+ return { kind: "dropped" };
2161
+ }
2162
+ throw error;
2163
+ }
2160
2164
  },
2161
2165
  start: monitor.start,
2162
2166
  stop: monitor.stop,
2163
2167
  waitForIdle: monitor.waitForIdle
2164
2168
  };
2165
2169
  }
2166
- //#endregion
2167
- //#region extensions/tlon/src/media-fetch-timeouts.ts
2170
+ // extensions/tlon/src/media-fetch-timeouts.ts
2168
2171
  const TLON_MEDIA_FETCH_TIMEOUTS = {
2169
2172
  responseHeaderTimeoutMs: 12e4,
2170
2173
  readIdleTimeoutMs: 3e4
2171
2174
  };
2172
- //#endregion
2173
- //#region extensions/tlon/src/monitor/media.ts
2175
+ // extensions/tlon/src/monitor/media.ts
2174
2176
  const MAX_IMAGES_PER_MESSAGE = 8;
2175
2177
  /** Keeps Tlon's shipped path-duplicating prompt bytes paired with ordered facts. */
2176
- function buildTlonInboundMediaPrompt(messageText, attachments) {
2177
- const media = attachments.map((attachment) => ({ ...attachment }));
2178
+ function buildTlonInboundMediaPrompt(messageText, media) {
2178
2179
  if (media.length === 0) return {
2179
2180
  body: messageText,
2180
2181
  media
@@ -2184,31 +2185,25 @@ function buildTlonInboundMediaPrompt(messageText, attachments) {
2184
2185
  media
2185
2186
  };
2186
2187
  }
2187
- function extractImageBlocks(content) {
2188
- if (!Array.isArray(content)) return {
2189
- images: [],
2190
- unavailableCount: 0
2191
- };
2188
+ async function downloadMessageImages(content, maxBytes) {
2192
2189
  const images = [];
2190
+ const attachments = [];
2193
2191
  let unavailableCount = 0;
2194
- for (const verse of content) if (verse?.block?.image?.src) {
2195
- if (images.length >= MAX_IMAGES_PER_MESSAGE) {
2196
- unavailableCount++;
2197
- continue;
2192
+ if (Array.isArray(content)) {
2193
+ for (const verse of content) if (verse?.block?.image?.src) {
2194
+ if (images.length >= MAX_IMAGES_PER_MESSAGE) {
2195
+ unavailableCount++;
2196
+ continue;
2197
+ }
2198
+ images.push(verse.block.image.src);
2198
2199
  }
2199
- images.push(verse.block.image.src);
2200
2200
  }
2201
- return {
2202
- images,
2203
- unavailableCount
2204
- };
2205
- }
2206
- async function downloadMedia(url, maxBytes) {
2207
- try {
2201
+ for (const url of images) try {
2208
2202
  const parsedUrl = new URL(url);
2209
2203
  if (parsedUrl.protocol !== "http:" && parsedUrl.protocol !== "https:") {
2210
- console.warn(`[tlon-media] Rejected non-http(s) URL: ${url}`);
2211
- return null;
2204
+ console.warn("[tlon-media] Rejected non-http(s) media URL");
2205
+ unavailableCount++;
2206
+ continue;
2212
2207
  }
2213
2208
  const saved = await saveRemoteMedia({
2214
2209
  url,
@@ -2217,31 +2212,20 @@ async function downloadMedia(url, maxBytes) {
2217
2212
  ssrfPolicy: void 0,
2218
2213
  requestInit: { method: "GET" }
2219
2214
  });
2220
- return {
2215
+ attachments.push({
2221
2216
  path: saved.path,
2222
2217
  contentType: saved.contentType ?? "application/octet-stream"
2223
- };
2224
- } catch (error) {
2225
- console.error(`[tlon-media] Error downloading ${url}: ${formatErrorMessage(error)}`);
2226
- return null;
2227
- }
2228
- }
2229
- async function downloadMessageImages(content, maxBytes) {
2230
- const { images, unavailableCount: overCapCount } = extractImageBlocks(content);
2231
- const attachments = [];
2232
- let unavailableCount = overCapCount;
2233
- for (const url of images) {
2234
- const downloaded = await downloadMedia(url, maxBytes);
2235
- if (downloaded) attachments.push(downloaded);
2236
- else unavailableCount++;
2218
+ });
2219
+ } catch {
2220
+ console.error("[tlon-media] Error downloading inbound media");
2221
+ unavailableCount++;
2237
2222
  }
2238
2223
  return {
2239
2224
  attachments,
2240
2225
  unavailableCount
2241
2226
  };
2242
2227
  }
2243
- //#endregion
2244
- //#region src/channels/mention-gating.ts
2228
+ // src/channels/mention-gating.ts
2245
2229
  function resolveBotThreadMentionPolicy(params) {
2246
2230
  if (!params.isBotOwnedThread || params.requireMentionInBotThreads === void 0) return {
2247
2231
  requireMention: params.requireMention,
@@ -2252,41 +2236,11 @@ function resolveBotThreadMentionPolicy(params) {
2252
2236
  implicitMentionKinds: params.requireMentionInBotThreads ? params.implicitMentionKinds?.filter((kind) => kind === "native") : params.implicitMentionKinds
2253
2237
  };
2254
2238
  }
2255
- //#endregion
2256
- //#region \0openclaw:bundled-sdk:openclaw/plugin-sdk/channel-mention-gating
2239
+ // \0openclaw:bundled-sdk:openclaw/plugin-sdk/channel-mention-gating
2257
2240
  var channel_mention_gating_exports = /* @__PURE__ */ __exportAll({ resolveBotThreadMentionPolicy: () => resolveBotThreadMentionPolicy });
2258
2241
  import * as import_openclaw_plugin_sdk_channel_mention_gating from "openclaw/plugin-sdk/channel-mention-gating";
2259
2242
  __reExport(channel_mention_gating_exports, import_openclaw_plugin_sdk_channel_mention_gating);
2260
- //#endregion
2261
- //#region extensions/tlon/src/monitor/mentions.ts
2262
- function resolveTlonGroupMentionDecision(params) {
2263
- const implicitMentions = resolveChannelImplicitMentions({
2264
- cfg: params.cfg,
2265
- channel: "tlon",
2266
- accountId: params.accountId
2267
- });
2268
- const threadPolicy = resolveBotThreadMentionPolicy({
2269
- isBotOwnedThread: params.isBotOwnedThread === true,
2270
- requireMentionInBotThreads: params.requireMentionInBotThreads,
2271
- requireMention: true,
2272
- implicitMentionKinds: (0, channel_mention_gating_exports.implicitMentionKindWhen)("bot_thread_participant", params.botParticipatedInThread)
2273
- });
2274
- return (0, channel_mention_gating_exports.resolveInboundMentionDecision)({
2275
- facts: {
2276
- canDetectMention: true,
2277
- wasMentioned: params.wasMentioned,
2278
- implicitMentionKinds: threadPolicy.implicitMentionKinds
2279
- },
2280
- policy: {
2281
- isGroup: true,
2282
- requireMention: threadPolicy.requireMention,
2283
- implicitMentions,
2284
- allowTextCommands: false,
2285
- hasControlCommand: false,
2286
- commandAuthorized: false
2287
- }
2288
- });
2289
- }
2243
+ // extensions/tlon/src/monitor/mentions.ts
2290
2244
  async function prepareTlonGroupAdmission(params) {
2291
2245
  const { cfg, account, channelNest, botShipName, runtime } = params;
2292
2246
  const parentId = readStringField(params.messageSeal, "parent-id") ?? readStringField(params.messageSeal, "parent") ?? null;
@@ -2297,17 +2251,37 @@ async function prepareTlonGroupAdmission(params) {
2297
2251
  const isBotOwnedThread = Boolean(threadRootAuthor && normalizeShip(threadRootAuthor) === botShipName);
2298
2252
  const resolveCurrentAdmission = () => {
2299
2253
  const authorization = resolveChannelAuthorization(cfg, channelNest, params.getSettings());
2254
+ const senderAllowed = params.isOwner(params.senderShip) || authorization.mode === "open" || authorization.allowedShips.some((ship) => normalizeShip(ship) === params.senderShip);
2255
+ const implicitMentions = resolveChannelImplicitMentions({
2256
+ cfg,
2257
+ channel: "tlon",
2258
+ accountId: account.accountId
2259
+ });
2260
+ const threadPolicy = resolveBotThreadMentionPolicy({
2261
+ isBotOwnedThread,
2262
+ requireMentionInBotThreads: authorization.requireMentionInBotThreads ?? account.requireMentionInBotThreads,
2263
+ requireMention: true,
2264
+ implicitMentionKinds: (0, channel_mention_gating_exports.implicitMentionKindWhen)("bot_thread_participant", botParticipatedInThread)
2265
+ });
2266
+ const decision = (0, channel_mention_gating_exports.resolveInboundMentionDecision)({
2267
+ facts: {
2268
+ canDetectMention: true,
2269
+ wasMentioned: mentioned,
2270
+ implicitMentionKinds: threadPolicy.implicitMentionKinds
2271
+ },
2272
+ policy: {
2273
+ isGroup: true,
2274
+ requireMention: threadPolicy.requireMention,
2275
+ implicitMentions,
2276
+ allowTextCommands: false,
2277
+ hasControlCommand: false,
2278
+ commandAuthorized: false
2279
+ }
2280
+ });
2300
2281
  return {
2301
2282
  ...authorization,
2302
- senderAllowed: params.isOwner(params.senderShip) || authorization.mode === "open" || authorization.allowedShips.some((ship) => normalizeShip(ship) === params.senderShip),
2303
- mentionDecision: resolveTlonGroupMentionDecision({
2304
- cfg,
2305
- accountId: account.accountId,
2306
- wasMentioned: mentioned,
2307
- botParticipatedInThread,
2308
- isBotOwnedThread,
2309
- requireMentionInBotThreads: authorization.requireMentionInBotThreads ?? account.requireMentionInBotThreads
2310
- })
2283
+ senderAllowed,
2284
+ mentionDecision: decision
2311
2285
  };
2312
2286
  };
2313
2287
  const admission = resolveCurrentAdmission();
@@ -2322,8 +2296,7 @@ async function prepareTlonGroupAdmission(params) {
2322
2296
  }
2323
2297
  };
2324
2298
  }
2325
- //#endregion
2326
- //#region extensions/tlon/src/monitor/settings-helpers.ts
2299
+ // extensions/tlon/src/monitor/settings-helpers.ts
2327
2300
  function buildTlonSettingsMigrations(account, currentSettings) {
2328
2301
  return [...[
2329
2302
  "dmAllowlist",
@@ -2368,6 +2341,7 @@ function applyTlonSettingsOverrides(params) {
2368
2341
  effectiveAutoAcceptDmInvites: settings.autoAcceptDmInvites ?? account.autoAcceptDmInvites ?? false,
2369
2342
  effectiveAutoAcceptGroupInvites: settings.autoAcceptGroupInvites ?? account.autoAcceptGroupInvites ?? false,
2370
2343
  effectiveGroupInviteAllowlist: settings.groupInviteAllowlist ?? account.groupInviteAllowlist,
2344
+ explicitChannels: mergeUniqueStrings(account.groupChannels, settings.groupChannels),
2371
2345
  effectiveAutoDiscoverChannels: settings.autoDiscoverChannels ?? account.autoDiscoverChannels ?? false,
2372
2346
  effectiveOwnerShip,
2373
2347
  pendingApprovals: settings.pendingApprovals?.length ? settings.pendingApprovals : [],
@@ -2377,13 +2351,26 @@ function applyTlonSettingsOverrides(params) {
2377
2351
  function mergeUniqueStrings(base, next) {
2378
2352
  return uniqueStrings([...base, ...next ?? []]);
2379
2353
  }
2380
- //#endregion
2381
- //#region extensions/tlon/src/monitor/tracking.ts
2382
- const TLON_PARTICIPATED_THREAD_LIMIT = 2e3;
2383
- function createParticipatedThreadTracker(limit = TLON_PARTICIPATED_THREAD_LIMIT) {
2354
+ function createTlonSettingsInstaller(state, account, log) {
2355
+ return (currentSettings, preserveApprovalState = false) => {
2356
+ const pendingApprovals = state.pendingApprovals;
2357
+ const effectiveDmAllowlist = state.effectiveDmAllowlist;
2358
+ Object.assign(state, applyTlonSettingsOverrides({
2359
+ account,
2360
+ currentSettings,
2361
+ log
2362
+ }));
2363
+ if (preserveApprovalState) {
2364
+ state.pendingApprovals = pendingApprovals;
2365
+ state.effectiveDmAllowlist = effectiveDmAllowlist;
2366
+ }
2367
+ };
2368
+ }
2369
+ // extensions/tlon/src/monitor/tracking.ts
2370
+ function createParticipatedThreadTracker() {
2384
2371
  const cache = createDedupeCache({
2385
2372
  ttlMs: 0,
2386
- maxSize: limit
2373
+ maxSize: 2e3
2387
2374
  });
2388
2375
  return {
2389
2376
  add: (parentId) => {
@@ -2409,8 +2396,7 @@ function createActiveSnapshotTracker() {
2409
2396
  addIfAccepted: (key, accepted) => accepted && processed.add(key)
2410
2397
  };
2411
2398
  }
2412
- //#endregion
2413
- //#region extensions/tlon/src/monitor/index.ts
2399
+ // extensions/tlon/src/monitor/index.ts
2414
2400
  /** Identity for an unverified group DM (club) author claim; never matches a bare ship. */
2415
2401
  function clubSenderId(clubId, claimedShip) {
2416
2402
  return `club:${clubId}:${claimedShip}`;
@@ -2422,7 +2408,7 @@ async function monitorTlonProvider(opts) {
2422
2408
  if (cfg.channels?.tlon?.enabled === false) return;
2423
2409
  const logger = core.logging.getChildLogger({ module: "tlon-auto-reply" });
2424
2410
  const runtime = opts.runtime ?? createLoggerBackedRuntime({ logger });
2425
- const account = resolveTlonAccount(cfg, opts.accountId ?? void 0);
2411
+ const account = resolveTlonAccount(cfg, opts.accountId);
2426
2412
  if (!account.enabled) return;
2427
2413
  if (!account.configured || !account.ship || !account.url || !account.code) throw new Error("Tlon account not configured (ship/url/code required)");
2428
2414
  const botShipName = normalizeShip(account.ship);
@@ -2478,6 +2464,7 @@ async function monitorTlonProvider(opts) {
2478
2464
  account,
2479
2465
  currentSettings: {}
2480
2466
  });
2467
+ const installSettings = createTlonSettingsInstaller(settingsState, account, (message) => runtime.log?.(message));
2481
2468
  const participatedThreads = createParticipatedThreadTracker();
2482
2469
  const channelHistory = createChannelHistoryCache();
2483
2470
  const dmSendersBySession = /* @__PURE__ */ new Map();
@@ -2492,29 +2479,19 @@ async function monitorTlonProvider(opts) {
2492
2479
  runtime.log?.(`[tlon] Could not fetch nickname: ${formatErrorMessage(error)}`);
2493
2480
  }
2494
2481
  let initForeigns = null;
2495
- try {
2496
- settingsState.currentSettings = await settingsManager.load();
2497
- const migrations = buildTlonSettingsMigrations(account, settingsState.currentSettings);
2498
- for (const { key, fileValue, settingsValue } of migrations) if (shouldMigrateTlonSetting(fileValue, settingsValue)) try {
2499
- await putTlonSetting(api, key, fileValue);
2500
- runtime.log?.(`[tlon] Migrated ${key} from config to settings store`);
2501
- } catch (err) {
2502
- runtime.log?.(`[tlon] Failed to migrate ${key}: ${String(err)}`);
2503
- }
2504
- Object.assign(settingsState, applyTlonSettingsOverrides({
2505
- account,
2506
- currentSettings: settingsState.currentSettings,
2507
- log: (message) => runtime.log?.(message)
2508
- }));
2482
+ settingsState.currentSettings = await settingsManager.load();
2483
+ const migrations = buildTlonSettingsMigrations(account, settingsState.currentSettings);
2484
+ for (const { key, fileValue, settingsValue } of migrations) if (shouldMigrateTlonSetting(fileValue, settingsValue)) try {
2485
+ await putTlonSetting(api, key, fileValue);
2486
+ runtime.log?.(`[tlon] Migrated ${key} from config to settings store`);
2509
2487
  } catch (err) {
2510
- runtime.log?.(`[tlon] Settings store not available, using file config: ${String(err)}`);
2488
+ runtime.log?.(`[tlon] Failed to migrate ${key}: ${String(err)}`);
2511
2489
  }
2512
- if (settingsState.effectiveAutoDiscoverChannels) try {
2490
+ installSettings(settingsState.currentSettings);
2491
+ if (settingsState.effectiveAutoDiscoverChannels) {
2513
2492
  const initData = await fetchInitData(api, runtime);
2514
2493
  if (initData.channels.length > 0) groupChannels = initData.channels;
2515
2494
  initForeigns = initData.foreigns;
2516
- } catch (error) {
2517
- runtime.error?.(`[tlon] Auto-discovery failed: ${formatErrorMessage(error)}`);
2518
2495
  }
2519
2496
  if (account.groupChannels.length > 0) {
2520
2497
  groupChannels = mergeUniqueStrings(groupChannels, account.groupChannels);
@@ -2540,21 +2517,17 @@ async function monitorTlonProvider(opts) {
2540
2517
  const senderId = clubId === void 0 ? senderShip : clubSenderId(clubId, senderShip);
2541
2518
  let attachments = [];
2542
2519
  let unavailableMediaCount = 0;
2543
- if (messageContent) try {
2520
+ if (messageContent) {
2544
2521
  ({attachments, unavailableCount: unavailableMediaCount} = await downloadMessageImages(messageContent, account.mediaMaxBytes));
2545
2522
  if (attachments.length > 0) runtime.log?.(`[tlon] Downloaded ${attachments.length} image(s) from message`);
2546
- } catch (error) {
2547
- runtime.log?.(`[tlon] Failed to download images: ${formatErrorMessage(error)}`);
2548
2523
  }
2549
- if (isThreadReply && parentId && channelNest) try {
2550
- const threadHistory = await fetchThreadHistory(api, channelNest, parentId, 20, runtime);
2524
+ if (isThreadReply && parentId && channelNest) {
2525
+ const threadHistory = await fetchThreadHistory(api, channelNest, parentId, runtime);
2551
2526
  if (threadHistory.length > 0) {
2552
2527
  const threadContext = threadHistory.slice(-10).map((msg) => `${msg.author}: ${msg.content}`).join("\n");
2553
2528
  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}`;
2554
2529
  runtime?.log?.(`[tlon] Added thread context (${threadHistory.length} replies) to message`);
2555
2530
  }
2556
- } catch (error) {
2557
- runtime?.log?.(`[tlon] Could not fetch thread context: ${formatErrorMessage(error)}`);
2558
2531
  }
2559
2532
  const groupTarget = isGroup && channelNest ? parseChannelNest(channelNest) : null;
2560
2533
  const groupSendContext = groupTarget && {
@@ -2563,7 +2536,7 @@ async function monitorTlonProvider(opts) {
2563
2536
  ...groupTarget
2564
2537
  };
2565
2538
  if (isGroup && channelNest && isSummarizationRequest(messageText)) try {
2566
- const history = await channelHistory.getChannelHistory(api, channelNest, 50, runtime);
2539
+ const history = await channelHistory.getChannelHistory(api, channelNest, runtime);
2567
2540
  if (history.length === 0) {
2568
2541
  const noHistoryMsg = "I couldn't fetch any messages for this channel. It might be empty or there might be a permissions issue.";
2569
2542
  if (groupSendContext && isAdmissionAllowed?.() !== false) await sendGroupMessage({
@@ -2589,7 +2562,7 @@ async function monitorTlonProvider(opts) {
2589
2562
  const route = core.channel.routing.resolveAgentRoute({
2590
2563
  cfg,
2591
2564
  channel: "tlon",
2592
- accountId: opts.accountId ?? void 0,
2565
+ accountId: opts.accountId,
2593
2566
  peer: {
2594
2567
  kind: isGroup ? "group" : "direct",
2595
2568
  id: isGroup ? channelNest ?? senderShip : senderShip
@@ -2649,7 +2622,6 @@ async function monitorTlonProvider(opts) {
2649
2622
  body: commandBody,
2650
2623
  notice: `[tlon ${unavailableMediaCount > 1 ? `${unavailableMediaCount} attachments` : "attachment"} unavailable]`
2651
2624
  }) : commandBody;
2652
- const tlonConversationId = isGroup ? channelNest ?? senderShip : senderShip;
2653
2625
  const ctxPayload = core.channel.inbound.buildContext({
2654
2626
  channel: "tlon",
2655
2627
  accountId: route.accountId,
@@ -2663,7 +2635,7 @@ async function monitorTlonProvider(opts) {
2663
2635
  },
2664
2636
  conversation: {
2665
2637
  kind: isGroup ? "group" : "direct",
2666
- id: tlonConversationId,
2638
+ id: isGroup ? channelNest ?? senderShip : senderShip,
2667
2639
  label: fromLabel
2668
2640
  },
2669
2641
  route: {
@@ -2690,6 +2662,7 @@ async function monitorTlonProvider(opts) {
2690
2662
  CommandAuthorized: commandAuthorized,
2691
2663
  CommandSource: "text",
2692
2664
  ...attachments.length > 0 && { Attachments: attachments },
2665
+ ...isGroup && { ReplyThreading: { implicitCurrentMessage: "deny" } },
2693
2666
  ...parentId && { ThreadId: parentId }
2694
2667
  }
2695
2668
  });
@@ -2738,7 +2711,7 @@ async function monitorTlonProvider(opts) {
2738
2711
  await sendGroupMessage({
2739
2712
  ...groupSendContext,
2740
2713
  text: replyText,
2741
- replyToId: parentId ?? void 0
2714
+ replyToId: parentId
2742
2715
  });
2743
2716
  return {
2744
2717
  visibleReplySent: true,
@@ -2760,8 +2733,7 @@ async function monitorTlonProvider(opts) {
2760
2733
  }
2761
2734
  },
2762
2735
  onError: (err, info) => {
2763
- const dispatchDuration = Date.now() - dispatchStartTime;
2764
- runtime.error?.(`[tlon] ${info.kind} reply failed after ${dispatchDuration}ms: ${String(err)}`);
2736
+ runtime.error?.(`[tlon] ${info.kind} reply failed after ${Date.now() - dispatchStartTime}ms: ${String(err)}`);
2765
2737
  }
2766
2738
  },
2767
2739
  dispatcherOptions: { humanDelay },
@@ -2772,6 +2744,7 @@ async function monitorTlonProvider(opts) {
2772
2744
  });
2773
2745
  };
2774
2746
  const watchedChannels = new Set(groupChannels);
2747
+ const canExpandCitedNest = (nest) => settingsState.effectiveAutoDiscoverChannels || settingsState.explicitChannels.includes(nest);
2775
2748
  const addWatchedChannels = (channels, logPrefix) => {
2776
2749
  const previousCount = watchedChannels.size;
2777
2750
  for (const channelNest of channels) if (!watchedChannels.has(channelNest)) {
@@ -2829,36 +2802,24 @@ async function monitorTlonProvider(opts) {
2829
2802
  });
2830
2803
  const handleChannelsFirehose = async (event, turnAdoptionLifecycle) => {
2831
2804
  try {
2832
- const eventRecord = asNullableRecord(event);
2833
- const nest = readStringField(eventRecord, "nest");
2834
- if (!nest) return;
2835
- if (!watchedChannels.has(nest)) return;
2836
- const response = asNullableRecord(eventRecord?.response);
2837
- if (!response) return;
2838
- const post = asNullableRecord(response.post);
2839
- const rPost = asNullableRecord(post?.["r-post"]);
2840
- const set = asNullableRecord(rPost?.set);
2841
- const reply = asNullableRecord(rPost?.reply);
2842
- const replyPayload = asNullableRecord(reply?.["r-reply"]);
2843
- const replySet = asNullableRecord(replyPayload?.set);
2844
- const essay = asNullableRecord(set?.essay);
2845
- const memo = asNullableRecord(replySet?.memo);
2846
- const content = memo ?? essay;
2847
- if (!content) return;
2848
- const isThreadReply = Boolean(memo);
2849
- const messageId = isThreadReply ? readStringField(reply, "id") : readStringField(post, "id");
2850
- if (!messageId) return;
2805
+ const message = decodeTlonChannelsEvent(event);
2806
+ if (!message || !watchedChannels.has(message.nest)) return;
2807
+ const { nest, messageId, content, isThreadReply, messageSet } = message;
2851
2808
  const senderShip = normalizeShip(readStringField(content, "author") ?? "");
2852
2809
  if (!senderShip || senderShip === botShipName) return;
2853
- const rawText = extractMessageText(content.content);
2810
+ let rawText;
2811
+ try {
2812
+ rawText = extractMessageText(content.content);
2813
+ } catch (error) {
2814
+ runtime.log?.(`[tlon] Failed to extract message text: ${formatErrorMessage(error)}`);
2815
+ return;
2816
+ }
2854
2817
  if (!rawText.trim()) return;
2855
- const contentBody = content.content;
2856
2818
  const sentAt = asFiniteNumber(content?.sent) ?? Date.now();
2857
2819
  channelHistory.cacheMessage(nest, {
2858
2820
  author: senderShip,
2859
2821
  content: rawText,
2860
- timestamp: sentAt,
2861
- id: messageId
2822
+ timestamp: sentAt
2862
2823
  });
2863
2824
  const { allowedShips, senderAllowed, mentionDecision, parentId, isAdmissionAllowed } = await prepareTlonGroupAdmission({
2864
2825
  cfg,
@@ -2870,7 +2831,7 @@ async function monitorTlonProvider(opts) {
2870
2831
  botShipName,
2871
2832
  botNickname,
2872
2833
  rawText,
2873
- messageSeal: isThreadReply ? asNullableRecord(replySet?.seal) : asNullableRecord(set?.seal),
2834
+ messageSeal: asNullableRecord(messageSet?.seal),
2874
2835
  isThreadReply,
2875
2836
  hasParticipatedInThread: participatedThreads.has,
2876
2837
  getSettings: () => settingsState.currentSettings,
@@ -2883,11 +2844,11 @@ async function monitorTlonProvider(opts) {
2883
2844
  type: "channel",
2884
2845
  requestingShip: senderShip,
2885
2846
  channelNest: nest,
2886
- messagePreview: sliceUtf16Safe(rawText, 0, 100),
2847
+ messagePreview: rawText,
2887
2848
  originalMessage: {
2888
2849
  messageId,
2889
2850
  messageText: rawText,
2890
- messageContent: contentBody,
2851
+ messageContent: content.content,
2891
2852
  timestamp: sentAt,
2892
2853
  parentId: parentId ?? void 0,
2893
2854
  isThreadReply
@@ -2897,12 +2858,12 @@ async function monitorTlonProvider(opts) {
2897
2858
  } else runtime.log?.(`[tlon] Access denied: ${senderShip} in ${nest} (allowed: ${allowedShips.join(", ")})`);
2898
2859
  return;
2899
2860
  }
2900
- const messageText = await resolveTlonCitations(contentBody, api, runtime) + rawText;
2861
+ const messageText = await resolveTlonCitations(content.content, canExpandCitedNest, api, runtime) + rawText;
2901
2862
  await processMessage({
2902
2863
  messageId,
2903
2864
  senderShip,
2904
2865
  messageText,
2905
- messageContent: contentBody,
2866
+ messageContent: content.content,
2906
2867
  isGroup: true,
2907
2868
  channelNest: nest,
2908
2869
  timestamp: sentAt,
@@ -2940,21 +2901,16 @@ async function monitorTlonProvider(opts) {
2940
2901
  const ownerInvite = isOwner(ship);
2941
2902
  const allowed = ownerInvite || await isDmAllowedWithIngress(ship, settingsState.effectiveDmAllowlist);
2942
2903
  if (ownerInvite || settingsState.effectiveAutoAcceptDmInvites && allowed) {
2943
- try {
2944
- await api.poke({
2945
- app: "chat",
2946
- mark: "chat-dm-rsvp",
2947
- json: {
2948
- ship,
2949
- ok: true
2950
- }
2951
- });
2952
- processedDmInvites.add(ship);
2953
- runtime.log?.(ownerInvite ? `[tlon] Auto-accepted DM invite from owner ${ship}` : `[tlon] Auto-accepted DM invite from ${ship}`);
2954
- } catch (err) {
2955
- runtime.error?.(ownerInvite ? `[tlon] Failed to auto-accept DM from owner: ${String(err)}` : `[tlon] Failed to auto-accept DM from ${ship}: ${String(err)}`);
2956
- throw err;
2957
- }
2904
+ await api.poke({
2905
+ app: "chat",
2906
+ mark: "chat-dm-rsvp",
2907
+ json: {
2908
+ ship,
2909
+ ok: true
2910
+ }
2911
+ });
2912
+ processedDmInvites.add(ship);
2913
+ runtime.log?.(ownerInvite ? `[tlon] Auto-accepted DM invite from owner ${ship}` : `[tlon] Auto-accepted DM invite from ${ship}`);
2958
2914
  continue;
2959
2915
  }
2960
2916
  if (settingsState.effectiveOwnerShip && !allowed) {
@@ -2968,14 +2924,9 @@ async function monitorTlonProvider(opts) {
2968
2924
  }
2969
2925
  return;
2970
2926
  }
2971
- const eventRecord = asNullableRecord(event);
2972
- if (!eventRecord) return;
2973
- const whom = eventRecord.whom;
2974
- const messageId = readStringField(eventRecord, "id");
2975
- const response = asNullableRecord(eventRecord.response);
2976
- if (!messageId || !response) return;
2977
- const essay = asNullableRecord(asNullableRecord(response.add)?.essay);
2978
- if (!essay) return;
2927
+ const message = decodeTlonChatEvent(event);
2928
+ if (!message) return;
2929
+ const { whom, messageId, essay } = message;
2979
2930
  const authorShip = normalizeShip(readStringField(essay, "author") ?? "");
2980
2931
  const partnerShip = extractDmPartnerShip(whom);
2981
2932
  const senderShip = partnerShip || authorShip;
@@ -2985,16 +2936,21 @@ async function monitorTlonProvider(opts) {
2985
2936
  if (authorShip === botShipName) return;
2986
2937
  if (!senderShip || senderShip === botShipName) return;
2987
2938
  if (authorShip && partnerShip && authorShip !== partnerShip) runtime.log?.(`[tlon] DM ship mismatch (author=${authorShip}, partner=${partnerShip}) - routing to partner`);
2988
- const rawText = extractMessageText(essay.content);
2939
+ let rawText;
2940
+ try {
2941
+ rawText = extractMessageText(essay.content);
2942
+ } catch (error) {
2943
+ runtime.log?.(`[tlon] Failed to extract message text: ${formatErrorMessage(error)}`);
2944
+ return;
2945
+ }
2989
2946
  if (!rawText.trim()) return;
2990
- const messageText = rawText;
2991
2947
  const ownerDm = !isClubMessage && isOwner(senderShip);
2992
- if (ownerDm && await handleApprovalResponse(messageText)) {
2993
- runtime.log?.(`[tlon] Processed approval response from owner: ${messageText}`);
2948
+ if (ownerDm && await handleApprovalResponse(rawText)) {
2949
+ runtime.log?.("[tlon] Processed approval response from owner");
2994
2950
  return;
2995
2951
  }
2996
- if (ownerDm && await handleAdminCommand(messageText)) {
2997
- runtime.log?.(`[tlon] Processed admin command from owner: ${messageText}`);
2952
+ if (ownerDm && await handleAdminCommand(rawText)) {
2953
+ runtime.log?.("[tlon] Processed admin command from owner");
2998
2954
  return;
2999
2955
  }
3000
2956
  const resolveChannelIngress = async (contextBinding) => await resolveTlonMessageIngress({
@@ -3017,11 +2973,11 @@ async function monitorTlonProvider(opts) {
3017
2973
  const approval = createPendingApproval({
3018
2974
  type: "dm",
3019
2975
  requestingShip: senderShip,
3020
- messagePreview: sliceUtf16Safe(messageText, 0, 100),
2976
+ messagePreview: rawText,
3021
2977
  ...isClubMessage ? { clubId } : { verifiedDirect: true },
3022
2978
  ...isClubMessage && isOwner(senderShip) ? {} : { originalMessage: {
3023
2979
  messageId,
3024
- messageText,
2980
+ messageText: rawText,
3025
2981
  messageContent: essay.content,
3026
2982
  timestamp: asFiniteNumber(essay?.sent) ?? Date.now()
3027
2983
  } }
@@ -3030,10 +2986,10 @@ async function monitorTlonProvider(opts) {
3030
2986
  } else runtime.log?.(`[tlon] Blocked DM from ${senderShip}: not in allowlist`);
3031
2987
  return;
3032
2988
  }
3033
- const resolvedMessageText = await resolveTlonCitations(essay.content, api, runtime) + rawText;
2989
+ const can = (nest) => !isClubMessage && isOwner(senderShip) || canExpandCitedNest(nest), agentText = await resolveTlonCitations(essay.content, can, api, runtime) + rawText;
3034
2990
  if (ownerDm) runtime.log?.(`[tlon] Processing DM from owner ${senderShip}`);
3035
2991
  await processMessage({
3036
- messageText: resolvedMessageText,
2992
+ messageText: agentText,
3037
2993
  messageId,
3038
2994
  senderShip,
3039
2995
  clubId,
@@ -3060,6 +3016,14 @@ async function monitorTlonProvider(opts) {
3060
3016
  await handleChatFirehose(event, turnAdoptionLifecycle);
3061
3017
  }
3062
3018
  });
3019
+ const subscriptionLogHandlers = (errorLabel, endedLabel) => ({
3020
+ err: (error) => {
3021
+ runtime.error?.(`[tlon] ${errorLabel} error: ${String(error)}`);
3022
+ },
3023
+ quit: () => {
3024
+ runtime.log?.(`[tlon] ${endedLabel} ended`);
3025
+ }
3026
+ });
3063
3027
  try {
3064
3028
  runtime.log?.("[tlon] Subscribing to firehose updates...");
3065
3029
  for (const [source, path, label, handleEvent] of [[
@@ -3082,12 +3046,7 @@ async function monitorTlonProvider(opts) {
3082
3046
  event
3083
3047
  })).kind === "ignored") await handleEvent(event);
3084
3048
  },
3085
- err: (error) => {
3086
- runtime.error?.(`[tlon] ${label} firehose error: ${String(error)}`);
3087
- },
3088
- quit: () => {
3089
- runtime.log?.(`[tlon] ${label} firehose subscription ended`);
3090
- }
3049
+ ...subscriptionLogHandlers(`${label} firehose`, `${label} firehose subscription`)
3091
3050
  });
3092
3051
  runtime.log?.(`[tlon] Subscribed to ${source} firehose (${path})`);
3093
3052
  }
@@ -3113,23 +3072,13 @@ async function monitorTlonProvider(opts) {
3113
3072
  runtime.error?.(`[tlon] Error handling contacts event: ${formatErrorMessage(error)}`);
3114
3073
  }
3115
3074
  },
3116
- err: (error) => {
3117
- runtime.error?.(`[tlon] Contacts subscription error: ${String(error)}`);
3118
- },
3119
- quit: () => {
3120
- runtime.log?.("[tlon] Contacts subscription ended");
3121
- }
3075
+ ...subscriptionLogHandlers("Contacts subscription", "Contacts subscription")
3122
3076
  });
3123
3077
  runtime.log?.("[tlon] Subscribed to contacts updates (/v1/news)");
3124
3078
  try {
3125
3079
  await settingsManager.startSubscription((newSettings) => {
3126
- settingsState.currentSettings = newSettings;
3127
3080
  addWatchedChannels(newSettings.groupChannels ?? [], "[tlon] Settings: now watching channel ");
3128
- Object.assign(settingsState, applyTlonSettingsOverrides({
3129
- account,
3130
- currentSettings: newSettings,
3131
- log: (message) => runtime.log?.(message)
3132
- }));
3081
+ installSettings(newSettings);
3133
3082
  });
3134
3083
  } catch (err) {
3135
3084
  runtime.log?.(`[tlon] Settings subscription not available: ${String(err)}`);
@@ -3147,27 +3096,23 @@ async function monitorTlonProvider(opts) {
3147
3096
  const discoveredChannels = mergeUniqueStrings(Object.keys(asNullableRecord(eventRecord.channels) ?? {}), joinedChannels.filter((channel) => typeof channel === "string")).filter((channel) => channel.startsWith("chat/"));
3148
3097
  addWatchedChannels(discoveredChannels, "[tlon] Auto-detected new channel: ");
3149
3098
  if (!settingsState.effectiveAutoAcceptGroupInvites) return;
3150
- const currentChannels = settingsState.currentSettings.groupChannels ?? [];
3099
+ const settingsSnapshot = settingsState.currentSettings;
3100
+ const currentChannels = settingsSnapshot.groupChannels ?? [];
3151
3101
  const unpersistedChannels = discoveredChannels.filter((channel) => !currentChannels.includes(channel));
3152
3102
  if (unpersistedChannels.length === 0) return;
3153
3103
  const updatedChannels = mergeUniqueStrings(currentChannels, unpersistedChannels);
3154
3104
  await putTlonSetting(api, "groupChannels", updatedChannels);
3155
- settingsState.currentSettings = {
3156
- ...settingsState.currentSettings,
3105
+ if (settingsState.currentSettings === settingsSnapshot) installSettings({
3106
+ ...settingsSnapshot,
3157
3107
  groupChannels: updatedChannels
3158
- };
3108
+ }, true);
3159
3109
  runtime.log?.(`[tlon] Persisted ${unpersistedChannels.join(", ")} to settings store`);
3160
3110
  } catch (error) {
3161
3111
  runtime.error?.(`[tlon] Error handling groups-ui event: ${formatErrorMessage(error)}`);
3162
3112
  throw error;
3163
3113
  }
3164
3114
  },
3165
- err: (error) => {
3166
- runtime.error?.(`[tlon] Groups-ui subscription error: ${String(error)}`);
3167
- },
3168
- quit: () => {
3169
- runtime.log?.("[tlon] Groups-ui subscription ended");
3170
- }
3115
+ ...subscriptionLogHandlers("Groups-ui subscription", "Groups-ui subscription")
3171
3116
  });
3172
3117
  runtime.log?.("[tlon] Subscribed to groups-ui for real-time channel detection");
3173
3118
  } catch (err) {
@@ -3238,12 +3183,7 @@ async function monitorTlonProvider(opts) {
3238
3183
  throw error;
3239
3184
  }
3240
3185
  },
3241
- err: (error) => {
3242
- runtime.error?.(`[tlon] Foreigns subscription error: ${String(error)}`);
3243
- },
3244
- quit: () => {
3245
- runtime.log?.("[tlon] Foreigns subscription ended");
3246
- }
3186
+ ...subscriptionLogHandlers("Foreigns subscription", "Foreigns subscription")
3247
3187
  });
3248
3188
  runtime.log?.("[tlon] Subscribed to foreigns (/v1/foreigns) for auto-accepting group invites");
3249
3189
  } catch (err) {
@@ -3267,13 +3207,9 @@ async function monitorTlonProvider(opts) {
3267
3207
  everyMs: 12e4,
3268
3208
  run: async () => {
3269
3209
  if (!settingsState.effectiveAutoDiscoverChannels) return;
3270
- try {
3271
- const { channels: discoveredChannels } = await fetchInitData(api, runtime);
3272
- if (discoveryScheduler.signal.aborted) return;
3273
- addWatchedChannels(discoveredChannels, "[tlon] Now watching new channel: ");
3274
- } catch (error) {
3275
- runtime.error?.(`[tlon] Channel refresh error: ${formatErrorMessage(error)}`);
3276
- }
3210
+ const { channels: discoveredChannels } = await fetchInitData(api, runtime);
3211
+ if (discoveryScheduler.signal.aborted) return;
3212
+ addWatchedChannels(discoveredChannels, "[tlon] Now watching new channel: ");
3277
3213
  }
3278
3214
  });
3279
3215
  await waitUntilAbort(opts.abortSignal);
@@ -3289,8 +3225,7 @@ async function monitorTlonProvider(opts) {
3289
3225
  }
3290
3226
  }
3291
3227
  }
3292
- //#endregion
3293
- //#region extensions/tlon/src/tlon-api.ts
3228
+ // extensions/tlon/src/tlon-api.ts
3294
3229
  const MEMEX_BASE_URL = "https://memex.tlon.network";
3295
3230
  /** Max bytes to read from the Memex upload JSON response. */
3296
3231
  const MEMEX_UPLOAD_RESPONSE_MAX_BYTES = 65536;
@@ -3358,6 +3293,12 @@ function prefixEndpoint(endpoint) {
3358
3293
  function sanitizeFileName(fileName) {
3359
3294
  return fileName.split(/[/\\]/).pop() || fileName;
3360
3295
  }
3296
+ /** Join a storage object key onto publicUrlBase without treating #/? as URL delimiters. */
3297
+ function buildCustomS3PublicUrl(publicUrlBase, fileKey) {
3298
+ const base = publicUrlBase.endsWith("/") ? publicUrlBase : `${publicUrlBase}/`;
3299
+ const encodedKey = fileKey.split("/").map((segment) => encodeURIComponent(segment)).join("/");
3300
+ return new URL(encodedKey, base).toString();
3301
+ }
3361
3302
  async function scryJson(config, cookie, path) {
3362
3303
  return await scryUrbitPath({
3363
3304
  baseUrl: config.shipUrl,
@@ -3369,54 +3310,6 @@ async function scryJson(config, cookie, path) {
3369
3310
  auditContext: "tlon-storage-scry"
3370
3311
  });
3371
3312
  }
3372
- async function getStorageConfiguration(config, cookie) {
3373
- const result = await scryJson(config, cookie, "/storage/configuration.json");
3374
- if ("storage-update" in result && result["storage-update"]?.configuration) return result["storage-update"].configuration;
3375
- if ("currentBucket" in result) return result;
3376
- throw new Error("Invalid storage configuration response");
3377
- }
3378
- async function getStorageCredentials(config, cookie) {
3379
- const result = await scryJson(config, cookie, "/storage/credentials.json");
3380
- if ("storage-update" in result) return result["storage-update"]?.credentials ?? null;
3381
- if (isStorageCredentials(result)) return result;
3382
- return null;
3383
- }
3384
- async function getMemexUploadUrl(params) {
3385
- const token = await scryJson(params.config, params.cookie, "/genuine/secret.json");
3386
- const resolvedToken = typeof token === "string" ? token : token.secret;
3387
- if (!resolvedToken) throw new Error("Missing genuine secret");
3388
- const endpoint = `${MEMEX_BASE_URL}/v1/${params.config.shipName}/upload`;
3389
- let guarded;
3390
- try {
3391
- guarded = await fetchWithSsrFGuard({
3392
- url: endpoint,
3393
- init: {
3394
- method: "PUT",
3395
- headers: { "Content-Type": "application/json" },
3396
- body: JSON.stringify({
3397
- token: resolvedToken,
3398
- contentLength: params.contentLength,
3399
- contentType: params.contentType,
3400
- fileName: params.fileName
3401
- })
3402
- },
3403
- auditContext: "tlon-memex-upload-url",
3404
- capture: false,
3405
- maxRedirects: 0,
3406
- timeoutMs: TLON_MEMEX_UPLOAD_URL_TIMEOUT_MS,
3407
- beforeRequest: params.config.assertDirectAdapterHandoff
3408
- });
3409
- if (!guarded.response.ok) throw new Error(`Memex upload request failed: ${guarded.response.status}`);
3410
- const data = await readProviderJsonResponse(guarded.response, "Memex upload", { maxBytes: MEMEX_UPLOAD_RESPONSE_MAX_BYTES });
3411
- if (!data?.url || !data.filePath) throw new Error("Invalid response from Memex");
3412
- return {
3413
- hostedUrl: data.filePath,
3414
- uploadUrl: data.url
3415
- };
3416
- } finally {
3417
- await releaseUploadResponse(guarded);
3418
- }
3419
- }
3420
3313
  async function uploadFile(params, clientConfig) {
3421
3314
  const config = {
3422
3315
  ...clientConfig,
@@ -3427,7 +3320,19 @@ async function uploadFile(params, clientConfig) {
3427
3320
  beforeRequest: config.assertDirectAdapterHandoff
3428
3321
  });
3429
3322
  const privateNetworkPolicy = ssrfPolicyFromDangerouslyAllowPrivateNetwork(config.dangerouslyAllowPrivateNetwork);
3430
- const [storageConfig, credentials] = await Promise.all([getStorageConfiguration(config, cookie), getStorageCredentials(config, cookie)]);
3323
+ async function getStorageConfiguration() {
3324
+ const result = await scryJson(config, cookie, "/storage/configuration.json");
3325
+ if ("storage-update" in result && result["storage-update"]?.configuration) return result["storage-update"].configuration;
3326
+ if ("currentBucket" in result) return result;
3327
+ throw new Error("Invalid storage configuration response");
3328
+ }
3329
+ async function getStorageCredentials() {
3330
+ const result = await scryJson(config, cookie, "/storage/credentials.json");
3331
+ if ("storage-update" in result) return result["storage-update"]?.credentials ?? null;
3332
+ if (isStorageCredentials(result)) return result;
3333
+ return null;
3334
+ }
3335
+ const [storageConfig, credentials] = await Promise.all([getStorageConfiguration(), getStorageCredentials()]);
3431
3336
  const contentType = params.contentType || params.blob.type || "application/octet-stream";
3432
3337
  const extension = extensionForMime(contentType) || ".jpg";
3433
3338
  const fileName = sanitizeFileName(params.fileName || `upload${extension}`);
@@ -3456,14 +3361,45 @@ async function uploadFile(params, clientConfig) {
3456
3361
  await releaseUploadResponse(guarded);
3457
3362
  }
3458
3363
  };
3364
+ async function getMemexUploadUrl() {
3365
+ const contentLength = params.blob.size;
3366
+ const token = await scryJson(config, cookie, "/genuine/secret.json");
3367
+ const resolvedToken = typeof token === "string" ? token : token.secret;
3368
+ if (!resolvedToken) throw new Error("Missing genuine secret");
3369
+ const endpoint = `${MEMEX_BASE_URL}/v1/${config.shipName}/upload`;
3370
+ let guarded;
3371
+ try {
3372
+ guarded = await fetchWithSsrFGuard({
3373
+ url: endpoint,
3374
+ init: {
3375
+ method: "PUT",
3376
+ headers: { "Content-Type": "application/json" },
3377
+ body: JSON.stringify({
3378
+ token: resolvedToken,
3379
+ contentLength,
3380
+ contentType,
3381
+ fileName: fileKey
3382
+ })
3383
+ },
3384
+ auditContext: "tlon-memex-upload-url",
3385
+ capture: false,
3386
+ maxRedirects: 0,
3387
+ timeoutMs: TLON_MEMEX_UPLOAD_URL_TIMEOUT_MS,
3388
+ beforeRequest: config.assertDirectAdapterHandoff
3389
+ });
3390
+ if (!guarded.response.ok) throw new Error(`Memex upload request failed: ${guarded.response.status}`);
3391
+ const data = await readProviderJsonResponse(guarded.response, "Memex upload", { maxBytes: MEMEX_UPLOAD_RESPONSE_MAX_BYTES });
3392
+ if (!data?.url || !data.filePath) throw new Error("Invalid response from Memex");
3393
+ return {
3394
+ hostedUrl: data.filePath,
3395
+ uploadUrl: data.url
3396
+ };
3397
+ } finally {
3398
+ await releaseUploadResponse(guarded);
3399
+ }
3400
+ }
3459
3401
  if (useMemex) {
3460
- const { hostedUrl, uploadUrl } = await getMemexUploadUrl({
3461
- config,
3462
- cookie,
3463
- contentLength: params.blob.size,
3464
- contentType,
3465
- fileName: fileKey
3466
- });
3402
+ const { hostedUrl, uploadUrl } = await getMemexUploadUrl();
3467
3403
  await uploadBlob(assertTrustedMemexUploadUrl(uploadUrl, "Memex upload URL"), {
3468
3404
  "Cache-Control": "public, max-age=3600",
3469
3405
  "Content-Type": contentType
@@ -3494,10 +3430,9 @@ async function uploadFile(params, clientConfig) {
3494
3430
  });
3495
3431
  const signedUrl = await getSignedUrl(client, command, { expiresIn: 3600 });
3496
3432
  await uploadBlob(signedUrl, signedUrl.includes("digitaloceanspaces.com") ? headers : void 0);
3497
- return { url: assertSafeUploadResultUrl(storageConfig.publicUrlBase ? new URL(fileKey, storageConfig.publicUrlBase).toString() : expectDefined(signedUrl.split("?").at(0), "signed URL base segment"), "Upload result URL") };
3433
+ return { url: assertSafeUploadResultUrl(storageConfig.publicUrlBase ? buildCustomS3PublicUrl(storageConfig.publicUrlBase, fileKey) : expectDefined(signedUrl.split("?").at(0), "signed URL base segment"), "Upload result URL") };
3498
3434
  }
3499
- //#endregion
3500
- //#region extensions/tlon/src/urbit/upload.ts
3435
+ // extensions/tlon/src/urbit/upload.ts
3501
3436
  /**
3502
3437
  * Fetch an image from a URL and upload it to Tlon storage.
3503
3438
  * Falls back to the original URL on error, but only after a bounded download when a cap is set.
@@ -3529,7 +3464,7 @@ async function uploadImageFromUrl(imageUrl, clientConfig, maxBytes) {
3529
3464
  const contentType = fetched.contentType || "image/png";
3530
3465
  return (await uploadFile({
3531
3466
  blob: new Blob([bufferToBlobPart(fetched.buffer)], { type: contentType }),
3532
- fileName: url.pathname.split("/").pop() || `upload-${Date.now()}.png`,
3467
+ fileName: fetched.fileName?.trim() || url.pathname.split("/").pop()?.trim() || `upload-${Date.now()}.png`,
3533
3468
  contentType
3534
3469
  }, {
3535
3470
  ...clientConfig,
@@ -3543,77 +3478,24 @@ async function uploadImageFromUrl(imageUrl, clientConfig, maxBytes) {
3543
3478
  return imageUrl;
3544
3479
  }
3545
3480
  }
3546
- //#endregion
3547
- //#region extensions/tlon/src/channel.runtime.ts
3548
- async function createHttpPokeApi(params) {
3549
- const ssrfPolicy = ssrfPolicyFromDangerouslyAllowPrivateNetwork(params.dangerouslyAllowPrivateNetwork);
3550
- const cookie = await authenticate(params.url, params.code, {
3551
- ssrfPolicy,
3552
- beforeRequest: params.assertDirectAdapterHandoff
3553
- });
3554
- const channelId = `${Math.floor(Date.now() / 1e3)}-${crypto.randomUUID()}`;
3555
- const shipName = params.ship.replace(/^~/, "");
3556
- return { poke: async (pokeParams) => {
3557
- const pokeId = Date.now();
3558
- const pokeData = {
3559
- id: pokeId,
3560
- action: "poke",
3561
- ship: shipName,
3562
- app: pokeParams.app,
3563
- mark: pokeParams.mark,
3564
- json: pokeParams.json
3565
- };
3566
- params.assertDirectAdapterHandoff?.();
3567
- await params.onPlatformSendDispatch?.();
3568
- const { response, release } = await putUrbitChannel({
3569
- baseUrl: params.url,
3570
- channelId,
3571
- ship: shipName,
3572
- cookie: normalizeUrbitCookie(cookie),
3573
- ssrfPolicy
3574
- }, {
3575
- body: [pokeData],
3576
- auditContext: "tlon-poke",
3577
- beforeRequest: params.assertDirectAdapterHandoff
3578
- });
3579
- try {
3580
- if (!response.ok && response.status !== 204) {
3581
- const errorText = await readResponseTextLimited(response, 16384);
3582
- throw new Error(`Poke failed: ${response.status} - ${redactUrbitErrorText(errorText)}`);
3583
- }
3584
- return pokeId;
3585
- } finally {
3586
- await release();
3587
- }
3588
- } };
3589
- }
3590
- function resolveOutboundContext(params) {
3591
- const account = resolveTlonAccount(params.cfg, params.accountId ?? void 0);
3592
- if (!account.configured || !account.ship || !account.url || !account.code) {
3593
- const missingFields = [
3594
- account.ship ? void 0 : "ship",
3595
- account.url ? void 0 : "url",
3596
- account.code ? void 0 : "code"
3597
- ].filter((field) => field !== void 0);
3598
- throw new Error(`Tlon account ${account.accountId} not configured (missing ${missingFields.join(", ")})`);
3599
- }
3600
- const parsed = parseTlonTarget(params.to);
3601
- if (!parsed) throw new Error(`Invalid Tlon target. Use ${formatTargetHint()}`);
3602
- return {
3603
- account,
3604
- parsed
3605
- };
3606
- }
3481
+ // extensions/tlon/src/channel.runtime.ts
3607
3482
  function resolveReplyId(replyToId, threadId) {
3608
3483
  return replyToId ?? threadId ? String(replyToId ?? threadId) : void 0;
3609
3484
  }
3610
3485
  async function sendTlonOutbound(params, kind) {
3611
3486
  const { cfg, to, text, accountId, replyToId, threadId, assertDirectAdapterHandoff } = params;
3612
- const { account, parsed } = resolveOutboundContext({
3613
- cfg,
3614
- accountId,
3615
- to
3616
- });
3487
+ const resolvedAccount = resolveTlonAccount(cfg, accountId);
3488
+ if (!resolvedAccount.configured || !resolvedAccount.ship || !resolvedAccount.url || !resolvedAccount.code) {
3489
+ const missingFields = [
3490
+ resolvedAccount.ship ? void 0 : "ship",
3491
+ resolvedAccount.url ? void 0 : "url",
3492
+ resolvedAccount.code ? void 0 : "code"
3493
+ ].filter((field) => field !== void 0);
3494
+ throw new Error(`Tlon account ${resolvedAccount.accountId} not configured (missing ${missingFields.join(", ")})`);
3495
+ }
3496
+ const parsed = parseTlonTarget(to);
3497
+ if (!parsed) throw new Error(`Invalid Tlon target. Use ${formatTargetHint()}`);
3498
+ const account = resolvedAccount;
3617
3499
  let uploadedUrl;
3618
3500
  if (kind === "media") {
3619
3501
  const { mediaUrl } = params;
@@ -3625,14 +3507,30 @@ async function sendTlonOutbound(params, kind) {
3625
3507
  assertDirectAdapterHandoff
3626
3508
  }, account.mediaMaxBytes) : void 0;
3627
3509
  }
3628
- const api = await createHttpPokeApi({
3629
- url: account.url,
3630
- ship: account.ship,
3631
- code: account.code,
3632
- dangerouslyAllowPrivateNetwork: account.dangerouslyAllowPrivateNetwork ?? void 0,
3633
- assertDirectAdapterHandoff,
3634
- onPlatformSendDispatch: params.onPlatformSendDispatch
3510
+ const { url, ship, code, dangerouslyAllowPrivateNetwork } = account;
3511
+ const onPlatformSendDispatch = params.onPlatformSendDispatch;
3512
+ const ssrfPolicy = ssrfPolicyFromDangerouslyAllowPrivateNetwork(dangerouslyAllowPrivateNetwork ?? void 0);
3513
+ const cookie = await authenticate(url, code, {
3514
+ ssrfPolicy,
3515
+ beforeRequest: assertDirectAdapterHandoff
3635
3516
  });
3517
+ const channelId = `${Math.floor(Date.now() / 1e3)}-${crypto.randomUUID()}`;
3518
+ const shipName = ship.replace(/^~/, "");
3519
+ const api = { poke: async (pokeParams) => {
3520
+ assertDirectAdapterHandoff?.();
3521
+ await onPlatformSendDispatch?.();
3522
+ return await pokeUrbitChannel({
3523
+ baseUrl: url,
3524
+ channelId,
3525
+ ship: shipName,
3526
+ cookie: normalizeUrbitCookie(cookie),
3527
+ ssrfPolicy
3528
+ }, {
3529
+ ...pokeParams,
3530
+ auditContext: "tlon-poke",
3531
+ beforeRequest: assertDirectAdapterHandoff
3532
+ });
3533
+ } };
3636
3534
  const fromShip = normalizeShip(account.ship);
3637
3535
  const story = kind === "media" ? buildMediaStory(text, uploadedUrl) : markdownToStory(text);
3638
3536
  if (parsed.kind === "dm") return await sendDmWithStory({
@@ -3700,5 +3598,4 @@ async function startTlonGatewayAccount(ctx) {
3700
3598
  accountId: account.accountId
3701
3599
  });
3702
3600
  }
3703
- //#endregion
3704
3601
  export { probeTlonAccount, startTlonGatewayAccount, tlonRuntimeOutbound, tlonSetupWizard };