@openclaw/tlon 2026.10.10 → 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
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-DnIfSMDp.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
4
  import { t as getTlonRuntime } from "./runtime-ReERXJF_.mjs";
5
- import { t as tlonSetupWizard } from "./setup-surface-CTiMlwQy.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";
@@ -153,33 +153,24 @@ function redactUrbitErrorText(text) {
153
153
  return redactToolPayloadText(text).replace(URBIT_COOKIE_REFLECTION_RE, "***");
154
154
  }
155
155
  // extensions/tlon/src/urbit/errors.ts
156
- var UrbitError = class extends Error {
157
- constructor(code, message, options) {
158
- super(message, options);
159
- this.name = "UrbitError";
160
- this.code = code;
161
- }
162
- };
163
- var UrbitUrlError = class extends UrbitError {
164
- constructor(message, options) {
165
- super("invalid_url", message, options);
156
+ var UrbitUrlError = class extends Error {
157
+ constructor(message) {
158
+ super(message);
166
159
  this.name = "UrbitUrlError";
167
160
  }
168
161
  };
169
- var UrbitHttpError = class extends UrbitError {
162
+ var UrbitHttpError = class extends Error {
170
163
  constructor(params) {
171
164
  const bodyText = params.bodyText ? redactUrbitErrorText(params.bodyText) : void 0;
172
165
  const suffix = bodyText ? ` - ${bodyText}` : "";
173
- super("http_error", `${params.operation} failed: ${params.status}${suffix}`, { cause: params.cause });
166
+ super(`${params.operation} failed: ${params.status}${suffix}`);
174
167
  this.name = "UrbitHttpError";
175
168
  this.status = params.status;
176
- this.operation = params.operation;
177
- this.bodyText = bodyText;
178
169
  }
179
170
  };
180
- var UrbitAuthError = class extends UrbitError {
181
- constructor(code, message, options) {
182
- super(code, message, options);
171
+ var UrbitAuthError = class extends Error {
172
+ constructor(message) {
173
+ super(message);
183
174
  this.name = "UrbitAuthError";
184
175
  }
185
176
  };
@@ -190,14 +181,12 @@ async function urbitFetch(params) {
190
181
  const url = new URL(params.path, validated.baseUrl).toString();
191
182
  const guarded = await fetchWithSsrFGuard({
192
183
  url,
193
- fetchImpl: params.fetchImpl,
194
184
  beforeRequest: params.beforeRequest,
195
185
  init: params.init,
196
186
  timeoutMs: params.timeoutMs,
197
187
  maxRedirects: params.maxRedirects,
198
188
  signal: params.signal,
199
189
  policy: params.ssrfPolicy,
200
- lookupFn: params.lookupFn,
201
190
  auditContext: params.auditContext
202
191
  });
203
192
  return {
@@ -220,18 +209,16 @@ async function authenticate(url, code, options = {}) {
220
209
  body: new URLSearchParams({ password: code }).toString()
221
210
  },
222
211
  ssrfPolicy: options.ssrfPolicy,
223
- lookupFn: options.lookupFn,
224
- fetchImpl: options.fetchImpl,
225
212
  beforeRequest: options.beforeRequest,
226
213
  timeoutMs: 15e3,
227
214
  maxRedirects: 3,
228
215
  auditContext: "tlon-urbit-login"
229
216
  });
230
217
  try {
231
- 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}`);
232
219
  await readResponseTextLimited(response, MAX_AUTH_BODY_DRAIN_BYTES).catch(() => void 0);
233
220
  const cookie = response.headers.get("set-cookie");
234
- if (!cookie) throw new UrbitAuthError("missing_cookie", "No authentication cookie received");
221
+ if (!cookie) throw new UrbitAuthError("No authentication cookie received");
235
222
  return cookie;
236
223
  } finally {
237
224
  await release();
@@ -246,7 +233,6 @@ function getUrbitContext(url, ship) {
246
233
  if (!validated.ok) throw new UrbitUrlError(validated.error);
247
234
  return {
248
235
  baseUrl: validated.baseUrl,
249
- hostname: validated.hostname,
250
236
  ship: (ship?.replace(/^~/, "") ?? validated.hostname.split(".")[0] ?? validated.hostname).trim()
251
237
  };
252
238
  }
@@ -418,9 +404,6 @@ const MARKDOWN_LIST_ITEM_PATTERN = /^([ \t]*)([-+*]|\d{1,9}[.)])(?:([ \t]+)(.*))
418
404
  function isMarkdownThematicBreak(text) {
419
405
  return /^(?:(?:\*\s*){3,}|(?:-\s*){3,}|(?:_\s*){3,})$/.test(text);
420
406
  }
421
- function startsListBlockSyntax(text) {
422
- return /^(`{3,}|~{3,})/.test(text) || text.startsWith(">") || /^#{1,6}(?:\s|$)/.test(text) || isMarkdownThematicBreak(text) || /^(?:[-+*]|\d{1,9}[.)])(?:\s|$)/.test(text);
423
- }
424
407
  function whitespaceColumns(text, startColumn = 0) {
425
408
  let column = startColumn;
426
409
  for (const char of text) column += char === " " ? 4 - column % 4 : 1;
@@ -451,7 +434,7 @@ function parseMarkdownListItem(line) {
451
434
  markerKey: markerType === "ordered" ? marker.slice(-1) : marker,
452
435
  ...markerType === "ordered" ? { orderedStart: Number.parseInt(marker, 10) } : {},
453
436
  hasSourceBody: sourceBody.length > 0,
454
- 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)),
455
438
  hasImages: imageBlocks.length > 0,
456
439
  content: inlines,
457
440
  ...checked === void 0 ? {} : { checked }
@@ -472,19 +455,16 @@ function listItemContent(item) {
472
455
  function canInterruptWithListItem(item) {
473
456
  return item.hasSourceBody && (item.markerType === "unordered" || item.orderedStart === 1);
474
457
  }
475
- function parseListingBlock(lines, startIndex) {
476
- const first = parseMarkdownListItem(expectDefined(lines[startIndex], "list start line"));
477
- if (!first) return;
478
- if (first.indent >= 4 || first.markerType === "ordered" && first.orderedStart !== 1) return;
479
- function parseLevel(index, minIndent, markerKey) {
480
- const firstItem = parseMarkdownListItem(expectDefined(lines[index], "list level start"));
481
- 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) {
482
461
  const items = [];
462
+ const markerKey = firstItem.markerKey;
483
463
  const markerType = firstItem.markerType;
484
464
  let allTasks = true;
485
465
  let cursor = index;
486
466
  while (cursor < lines.length) {
487
- const item = parseMarkdownListItem(expectDefined(lines[cursor], "list line index"));
467
+ const item = cursor === index ? firstItem : parseMarkdownListItem(expectDefined(lines[cursor], "list line index"));
488
468
  if (!item || item.indent < minIndent || item.indent > minIndent + 3 || item.markerKey !== markerKey) break;
489
469
  if (item.hasBlockBody || item.hasImages) return;
490
470
  allTasks &&= item.checked !== void 0;
@@ -517,7 +497,7 @@ function parseListingBlock(lines, startIndex) {
517
497
  if (child && child.indent >= item.contentIndent && !canInterruptWithListItem(child)) return;
518
498
  if (child && child.indent > item.indent) {
519
499
  if (child.indent < item.contentIndent || child.indent >= item.contentIndent + 4) return;
520
- const nested = parseLevel(cursor, item.contentIndent, child.markerKey);
500
+ const nested = parseLevel(cursor, item.contentIndent, child);
521
501
  if (!nested) return;
522
502
  items.push({ list: {
523
503
  type: nested.type,
@@ -540,7 +520,7 @@ function parseListingBlock(lines, startIndex) {
540
520
  nextIndex: cursor
541
521
  };
542
522
  }
543
- const parsed = parseLevel(startIndex, 0, first.markerKey);
523
+ const parsed = parseLevel(startIndex, 0, first);
544
524
  if (!parsed) return;
545
525
  return {
546
526
  verses: [{ block: { listing: { list: {
@@ -615,7 +595,7 @@ function markdownToStory(markdown) {
615
595
  continue;
616
596
  }
617
597
  const preservesLooseList = preservedListMarkerKey !== void 0 && lineListItem?.markerKey === preservedListMarkerKey;
618
- const listing = preservesLooseList ? void 0 : parseListingBlock(lines, i);
598
+ const listing = preservesLooseList ? void 0 : parseListingBlock(lines, i, lineListItem);
619
599
  if (listing) {
620
600
  story.push(...listing.verses);
621
601
  i = listing.nextIndex;
@@ -630,7 +610,7 @@ function markdownToStory(markdown) {
630
610
  if (paragraphLine === void 0 || paragraphLine.trim() === "" || startsTopLevelStoryBlock(paragraphLine)) break;
631
611
  if (!preserveListText && MARKDOWN_LIST_ITEM_PATTERN.test(paragraphLine)) {
632
612
  const item = parseMarkdownListItem(paragraphLine);
633
- const candidate = parseListingBlock(lines, i);
613
+ const candidate = parseListingBlock(lines, i, item);
634
614
  if (item?.hasSourceBody === true && candidate) break;
635
615
  preserveListText = true;
636
616
  if (item) preservedListMarkerKey = item.markerKey;
@@ -768,8 +748,6 @@ async function putUrbitChannel(deps, params) {
768
748
  body: JSON.stringify(params.body)
769
749
  },
770
750
  ssrfPolicy: deps.ssrfPolicy,
771
- lookupFn: deps.lookupFn,
772
- fetchImpl: deps.fetchImpl,
773
751
  timeoutMs: params.timeoutMs,
774
752
  auditContext: params.auditContext,
775
753
  beforeRequest: params.beforeRequest
@@ -788,7 +766,8 @@ async function pokeUrbitChannel(deps, params) {
788
766
  json: params.json
789
767
  }],
790
768
  auditContext: params.auditContext,
791
- timeoutMs: 3e4
769
+ timeoutMs: params.timeoutMs,
770
+ beforeRequest: params.beforeRequest
792
771
  });
793
772
  try {
794
773
  if (!response.ok && response.status !== 204) {
@@ -814,8 +793,6 @@ async function scryUrbitPath(deps, params) {
814
793
  headers: { Cookie: deps.cookie }
815
794
  },
816
795
  ssrfPolicy: deps.ssrfPolicy,
817
- lookupFn: deps.lookupFn,
818
- fetchImpl: deps.fetchImpl,
819
796
  beforeRequest: deps.beforeRequest,
820
797
  timeoutMs: 3e4,
821
798
  auditContext: params.auditContext
@@ -868,6 +845,7 @@ async function ensureUrbitChannelOpen(deps, params) {
868
845
  // extensions/tlon/src/urbit/sse-client.ts
869
846
  const MAX_SSE_PAYLOAD_BYTES = 16777216;
870
847
  const MAX_RECONNECT_ATTEMPTS = 10;
848
+ const SSE_STALL_TIMEOUT_MS = 6e4;
871
849
  function parseUrbitSsePayload(data) {
872
850
  if (Buffer.byteLength(data, "utf8") > MAX_SSE_PAYLOAD_BYTES) throw new Error("Tlon Urbit SSE payload exceeds 16 MiB limit");
873
851
  try {
@@ -903,8 +881,6 @@ var UrbitSSEClient = class {
903
881
  this.onReconnect = options.onReconnect ?? null;
904
882
  this.logger = options.logger ?? {};
905
883
  this.ssrfPolicy = options.ssrfPolicy;
906
- this.lookupFn = options.lookupFn;
907
- this.fetchImpl = options.fetchImpl;
908
884
  }
909
885
  channelRequestContext() {
910
886
  return {
@@ -912,9 +888,7 @@ var UrbitSSEClient = class {
912
888
  cookie: this.cookie,
913
889
  ship: this.ship,
914
890
  channelId: this.channelId,
915
- ssrfPolicy: this.ssrfPolicy,
916
- lookupFn: this.lookupFn,
917
- fetchImpl: this.fetchImpl
891
+ ssrfPolicy: this.ssrfPolicy
918
892
  };
919
893
  }
920
894
  resetChannelIdentity() {
@@ -992,8 +966,6 @@ var UrbitSSEClient = class {
992
966
  }
993
967
  },
994
968
  ssrfPolicy: this.ssrfPolicy,
995
- lookupFn: this.lookupFn,
996
- fetchImpl: this.fetchImpl,
997
969
  signal: AbortSignal.any([controller.signal, this.reconnectAbortController.signal]),
998
970
  beforeRequest: () => this.reconnectAbortController.signal.throwIfAborted(),
999
971
  auditContext: "tlon-urbit-sse-stream"
@@ -1026,6 +998,17 @@ var UrbitSSEClient = class {
1026
998
  async processStream(body) {
1027
999
  if (!body) return;
1028
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();
1029
1012
  const decoder = new TextDecoder();
1030
1013
  let buffer = "";
1031
1014
  let bufferBytes = 0;
@@ -1073,13 +1056,16 @@ var UrbitSSEClient = class {
1073
1056
  try {
1074
1057
  for await (const chunk of stream) {
1075
1058
  if (this.aborted) break;
1059
+ watchdog.disarm();
1076
1060
  if (typeof chunk === "string") {
1077
1061
  await consumeText(decoder.decode());
1078
1062
  await consumeText(chunk);
1079
1063
  } else await consumeText(decoder.decode(chunk, { stream: true }));
1064
+ watchdog.arm();
1080
1065
  }
1081
1066
  await consumeText(decoder.decode());
1082
1067
  } finally {
1068
+ watchdog.stop();
1083
1069
  if (this.streamRelease) {
1084
1070
  const release = this.streamRelease;
1085
1071
  this.streamRelease = null;
@@ -1131,17 +1117,20 @@ var UrbitSSEClient = class {
1131
1117
  if (eventId === null || eventId <= this.lastAcknowledgedEventId) return;
1132
1118
  this.lastHeardEventId = Math.max(this.lastHeardEventId, eventId);
1133
1119
  if (this.lastHeardEventId - this.lastAcknowledgedEventId <= this.ackThreshold) return;
1134
- this.logger.log?.(`[SSE] Acking event ${this.lastHeardEventId} (last acked: ${this.lastAcknowledgedEventId})`);
1135
1120
  await this.ack(this.lastHeardEventId);
1136
1121
  }
1137
1122
  async poke(params) {
1138
1123
  return await pokeUrbitChannel(this.channelRequestContext(), {
1139
1124
  ...params,
1140
- auditContext: "tlon-urbit-poke"
1125
+ auditContext: "tlon-urbit-poke",
1126
+ timeoutMs: 3e4
1141
1127
  });
1142
1128
  }
1143
- async scry(path) {
1144
- return await scryUrbitPath(this.channelRequestContext(), {
1129
+ async scry(path, beforeRequest) {
1130
+ return await scryUrbitPath({
1131
+ ...this.channelRequestContext(),
1132
+ beforeRequest
1133
+ }, {
1145
1134
  path,
1146
1135
  auditContext: "tlon-urbit-scry"
1147
1136
  });
@@ -1210,33 +1199,17 @@ var UrbitSSEClient = class {
1210
1199
  async close() {
1211
1200
  this.stopReceiving();
1212
1201
  try {
1213
- const unsubscribes = this.subscriptions.map((sub) => ({
1214
- id: sub.id,
1215
- action: "unsubscribe",
1216
- subscription: sub.id
1217
- }));
1218
- {
1219
- const { release } = await putUrbitChannel(this.channelRequestContext(), {
1220
- body: unsubscribes,
1221
- timeoutMs: 3e4,
1222
- auditContext: "tlon-urbit-unsubscribe"
1223
- });
1224
- await release();
1225
- }
1226
- {
1227
- const { release } = await urbitFetch({
1228
- baseUrl: this.url,
1229
- path: `/~/channel/${this.channelId}`,
1230
- init: {
1231
- method: "DELETE",
1232
- headers: { Cookie: this.cookie }
1233
- },
1234
- ssrfPolicy: this.ssrfPolicy,
1235
- lookupFn: this.lookupFn,
1236
- fetchImpl: this.fetchImpl,
1237
- timeoutMs: 3e4,
1238
- 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
1239
1211
  });
1212
+ } finally {
1240
1213
  await release();
1241
1214
  }
1242
1215
  } catch (error) {
@@ -1259,12 +1232,10 @@ var UrbitSSEClient = class {
1259
1232
  }
1260
1233
  };
1261
1234
  // extensions/tlon/src/monitor/approval.ts
1262
- function generateApprovalId(type) {
1263
- return `${type}-${Date.now()}-${randomBytes(3).toString("hex")}`;
1264
- }
1265
1235
  function createPendingApproval(params) {
1236
+ const timestamp = Date.now();
1266
1237
  return {
1267
- id: generateApprovalId(params.type),
1238
+ id: `${params.type}-${timestamp}-${randomBytes(3).toString("hex")}`,
1268
1239
  type: params.type,
1269
1240
  requestingShip: params.requestingShip,
1270
1241
  ...params.clubId !== void 0 ? { clubId: params.clubId } : {},
@@ -1273,24 +1244,27 @@ function createPendingApproval(params) {
1273
1244
  groupFlag: params.groupFlag,
1274
1245
  messagePreview: params.messagePreview != null ? sliceUtf16Safe(params.messagePreview, 0, 100) : void 0,
1275
1246
  originalMessage: params.originalMessage,
1276
- timestamp: Date.now()
1247
+ timestamp
1277
1248
  };
1278
1249
  }
1279
1250
  function truncate(text, maxLength) {
1280
1251
  if (text.length <= maxLength) return text;
1281
1252
  return sliceUtf16Safe(text, 0, maxLength - 3) + "...";
1282
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
+ }
1283
1257
  function formatApprovalRequest(approval) {
1284
1258
  const preview = approval.messagePreview ? `\n"${truncate(approval.messagePreview, 100)}"` : "";
1285
1259
  switch (approval.type) {
1286
1260
  case "dm":
1287
1261
  if (approval.clubId !== void 0) {
1288
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.`;
1289
- return `New group DM message claiming to be from ${approval.requestingShip} (unverified; group DM ${approval.clubId}):${preview}\n\nApproving adds ${approval.requestingShip} to the DM allowlist. ${replayLine}\nReply "approve", "deny", or "block" (ID: ${approval.id})`;
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);
1290
1264
  }
1291
- return `New DM request from ${approval.requestingShip}:${preview}\n\nReply "approve", "deny", or "block" (ID: ${approval.id})`;
1292
- case "channel": return `${approval.requestingShip} mentioned you in ${approval.channelNest}:${preview}\n\nReply "approve", "deny", or "block"\n(ID: ${approval.id})`;
1293
- case "group": return `Group invite from ${approval.requestingShip} to join ${approval.groupFlag}\n\nReply "approve", "deny", or "block"\n(ID: ${approval.id})`;
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);
1294
1268
  }
1295
1269
  throw new Error("Unsupported approval type");
1296
1270
  }
@@ -1303,8 +1277,7 @@ function parseApprovalResponse(text) {
1303
1277
  };
1304
1278
  }
1305
1279
  function findPendingApproval(pendingApprovals, id) {
1306
- if (id) return pendingApprovals.find((a) => a.id === id);
1307
- return pendingApprovals[pendingApprovals.length - 1];
1280
+ return id ? pendingApprovals.find((approval) => approval.id === id) : pendingApprovals.length === 1 ? pendingApprovals[0] : void 0;
1308
1281
  }
1309
1282
  function removePendingApproval(pendingApprovals, id) {
1310
1283
  return pendingApprovals.filter((a) => a.id !== id);
@@ -1484,7 +1457,7 @@ function createTlonApprovalRuntime(params) {
1484
1457
  runtime.log?.(`[tlon] Pending approval limit reached; ignoring ${approval.type} request from ${approval.requestingShip}`);
1485
1458
  if (!approvalOverflowNoticeSent && approvalOverflowNoticeAttempts < 3) {
1486
1459
  approvalOverflowNoticeAttempts += 1;
1487
- approvalOverflowNoticeSent = await sendOwnerNotification(`Pending approval queue is full (${approvals.length}). Resolve existing requests with approve, deny, or block before asking rejected requesters to retry.`);
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.`);
1488
1461
  }
1489
1462
  return false;
1490
1463
  }
@@ -1501,7 +1474,7 @@ function createTlonApprovalRuntime(params) {
1501
1474
  if (!parsed) return false;
1502
1475
  const approval = findPendingApproval(state.pendingApprovals, parsed.id);
1503
1476
  if (!approval) {
1504
- 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.");
1505
1478
  return true;
1506
1479
  }
1507
1480
  if (parsed.action === "approve") switch (approval.type) {
@@ -1703,7 +1676,8 @@ function isGroupInviteAllowed(inviterShip, allowlist) {
1703
1676
  }]
1704
1677
  }).allowed;
1705
1678
  }
1706
- function renderInlineItem(item, topLevel = false) {
1679
+ const MAX_INLINE_DEPTH = 100;
1680
+ function renderInlineItem(item, topLevel = false, depth = 0) {
1707
1681
  if (typeof item === "string") return item;
1708
1682
  const record = asNullableRecord(item);
1709
1683
  if (!record) return "";
@@ -1723,14 +1697,21 @@ function renderInlineItem(item, topLevel = false) {
1723
1697
  const linkContent = readStringField(link, "content");
1724
1698
  return topLevel ? linkHref : linkContent || linkHref;
1725
1699
  }
1726
- if (Array.isArray(record.bold)) return `**${extractInlineText(record.bold)}**`;
1727
- if (Array.isArray(record.italics)) return `*${extractInlineText(record.italics)}*`;
1728
- if (Array.isArray(record.strike)) return `~~${extractInlineText(record.strike)}~~`;
1729
- if (topLevel && Array.isArray(record.blockquote)) return `> ${extractInlineText(record.blockquote)}`;
1730
- return "";
1731
- }
1732
- function extractInlineText(items) {
1733
- return items.map((item) => renderInlineItem(item)).join("");
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("");
1734
1715
  }
1735
1716
  function extractMessageText(content) {
1736
1717
  if (!Array.isArray(content)) return "";
@@ -1817,6 +1798,8 @@ function formatSummarizationHistoryText(history, cfg) {
1817
1798
  // extensions/tlon/src/monitor/cites.ts
1818
1799
  const CITE_PATH_SEGMENT_RE = /^[A-Za-z0-9._~-]+$/;
1819
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 {};
1820
1803
  function isSafeCitePathSegment(segment) {
1821
1804
  if (segment === "." || segment === "..") return false;
1822
1805
  return CITE_PATH_SEGMENT_RE.test(segment);
@@ -1836,7 +1819,7 @@ function buildCitedPostScryPath(nest, postId) {
1836
1819
  if (new URL(scryPath, CITE_PATH_NORMALIZATION_BASE).pathname !== scryPath) return null;
1837
1820
  return scryPath;
1838
1821
  }
1839
- async function resolveTlonCitations(content, api, runtime) {
1822
+ async function resolveTlonCitations(content, canExpandNest, api, runtime) {
1840
1823
  if (!Array.isArray(content)) return "";
1841
1824
  const resolved = [];
1842
1825
  for (const verse of content) {
@@ -1846,6 +1829,10 @@ async function resolveTlonCitations(content, api, runtime) {
1846
1829
  const whereMatch = readStringField(chan, "where")?.match(/\/msg\/(~[a-z-]+)\/(.+)/);
1847
1830
  const postId = whereMatch?.[2];
1848
1831
  if (!nest || !postId) continue;
1832
+ if (!canExpandNest(nest)) {
1833
+ runtime.log?.(CITATION_SCOPE_SKIP_LOG);
1834
+ continue;
1835
+ }
1849
1836
  const scryPath = buildCitedPostScryPath(nest, postId);
1850
1837
  if (!scryPath) {
1851
1838
  runtime.log?.("[tlon] Skipping cited post: citation does not name a channel post");
@@ -1853,11 +1840,21 @@ async function resolveTlonCitations(content, api, runtime) {
1853
1840
  }
1854
1841
  try {
1855
1842
  runtime.log?.(`[tlon] Fetching cited post: ${scryPath}`);
1856
- 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
+ }
1857
1850
  const essay = asNullableRecord(data?.essay);
1858
1851
  const text = essay?.content ? extractMessageText(essay.content) : "";
1859
1852
  if (text) resolved.push(`> ${whereMatch?.[1] || "unknown"} wrote: ${text}`);
1860
1853
  } catch (err) {
1854
+ if (err instanceof CitationScopeChangedError) {
1855
+ runtime.log?.(CITATION_SCOPE_SKIP_LOG);
1856
+ continue;
1857
+ }
1861
1858
  runtime.log?.(`[tlon] Failed to fetch cited post: ${String(err)}`);
1862
1859
  }
1863
1860
  }
@@ -1905,18 +1902,17 @@ function formatUd(id) {
1905
1902
  return chunks.toReversed().join(".");
1906
1903
  }
1907
1904
  function createHistoryEntryFromMemo(params) {
1908
- const { memo, seal, fallbackId } = params;
1905
+ const { memo } = params;
1909
1906
  return {
1910
1907
  author: typeof memo?.author === "string" ? memo.author : "unknown",
1911
1908
  content: extractMessageText(memo?.content || []),
1912
- timestamp: typeof memo?.sent === "number" ? memo.sent : Date.now(),
1913
- id: typeof seal?.id === "string" ? seal.id : typeof fallbackId === "string" ? fallbackId : void 0
1909
+ timestamp: typeof memo?.sent === "number" ? memo.sent : Date.now()
1914
1910
  };
1915
1911
  }
1916
1912
  const MAX_CACHED_MESSAGES = 100;
1917
- async function fetchChannelHistory(api, channelNest, count = 50, runtime) {
1913
+ async function fetchChannelHistory(api, channelNest, runtime) {
1918
1914
  try {
1919
- const scryPath = `/channels/v4/${channelNest}/posts/newest/${count}/outline.json`;
1915
+ const scryPath = `/channels/v4/${channelNest}/posts/newest/50/outline.json`;
1920
1916
  runtime?.log?.(`[tlon] Fetching history: ${scryPath}`);
1921
1917
  const data = await api.scry(scryPath);
1922
1918
  if (!data) return [];
@@ -1925,10 +1921,7 @@ async function fetchChannelHistory(api, channelNest, count = 50, runtime) {
1925
1921
  const itemRecord = asNullableRecord(item);
1926
1922
  const replyPost = asNullableRecord(itemRecord?.["r-post"]);
1927
1923
  const replyPostSet = asNullableRecord(replyPost?.set);
1928
- return createHistoryEntryFromMemo({
1929
- memo: asNullableRecord(itemRecord?.essay) ?? asNullableRecord(replyPostSet?.essay),
1930
- seal: asNullableRecord(itemRecord?.seal) ?? asNullableRecord(replyPostSet?.seal)
1931
- });
1924
+ return createHistoryEntryFromMemo({ memo: asNullableRecord(itemRecord?.essay) ?? asNullableRecord(replyPostSet?.essay) });
1932
1925
  }).filter((msg) => msg.content);
1933
1926
  runtime?.log?.(`[tlon] Extracted ${messages.length} messages from history`);
1934
1927
  return messages;
@@ -1946,14 +1939,14 @@ function createChannelHistoryCache() {
1946
1939
  if (cache.length > MAX_CACHED_MESSAGES) cache.pop();
1947
1940
  messageCache.set(channelNest, cache);
1948
1941
  },
1949
- async getChannelHistory(api, channelNest, count = 50, runtime) {
1942
+ async getChannelHistory(api, channelNest, runtime) {
1950
1943
  const cache = messageCache.get(channelNest) ?? [];
1951
- if (cache.length >= count) {
1944
+ if (cache.length >= 50) {
1952
1945
  runtime?.log?.(`[tlon] Using cached messages (${cache.length} available)`);
1953
- return cache.slice(0, count);
1946
+ return cache.slice(0, 50);
1954
1947
  }
1955
- runtime?.log?.(`[tlon] Cache has ${cache.length} messages, need ${count}, fetching from scry...`);
1956
- 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);
1957
1950
  }
1958
1951
  };
1959
1952
  }
@@ -1968,11 +1961,11 @@ async function fetchThreadRootAuthor(api, channelNest, parentId, runtime) {
1968
1961
  return null;
1969
1962
  }
1970
1963
  }
1971
- async function fetchThreadHistory(api, channelNest, parentId, count = 50, runtime) {
1964
+ async function fetchThreadHistory(api, channelNest, parentId, runtime) {
1972
1965
  try {
1973
1966
  const formattedParentId = formatUd(parentId);
1974
1967
  runtime?.log?.(`[tlon] Thread history - parentId: ${parentId} -> formatted: ${formattedParentId}`);
1975
- 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`;
1976
1969
  runtime?.log?.(`[tlon] Fetching thread history: ${scryPath}`);
1977
1970
  const data = await api.scry(scryPath);
1978
1971
  if (!data) {
@@ -1992,11 +1985,7 @@ async function fetchThreadHistory(api, channelNest, parentId, count = 50, runtim
1992
1985
  const itemRecord = asNullableRecord(item);
1993
1986
  const replyRecord = asNullableRecord(itemRecord?.["r-reply"]);
1994
1987
  const replySet = asNullableRecord(replyRecord?.set);
1995
- return createHistoryEntryFromMemo({
1996
- memo: asNullableRecord(itemRecord?.memo) ?? asNullableRecord(replySet?.memo) ?? itemRecord,
1997
- seal: asNullableRecord(itemRecord?.seal) ?? asNullableRecord(replySet?.seal),
1998
- fallbackId: itemRecord?.id
1999
- });
1988
+ return createHistoryEntryFromMemo({ memo: asNullableRecord(itemRecord?.memo) ?? asNullableRecord(replySet?.memo) ?? itemRecord });
2000
1989
  }).filter((msg) => msg.content);
2001
1990
  runtime?.log?.(`[tlon] Extracted ${messages.length} thread replies from history`);
2002
1991
  return messages;
@@ -2012,10 +2001,7 @@ async function fetchThreadHistory(api, channelNest, parentId, count = 50, runtim
2012
2001
  if (typeof dataMeta?.replyCount === "number" && dataMeta.replyCount > 0 && repliesValue) {
2013
2002
  const messages = (Array.isArray(repliesValue) ? repliesValue : Object.values(repliesValue)).map((reply) => {
2014
2003
  const replyRecord = asNullableRecord(reply);
2015
- return createHistoryEntryFromMemo({
2016
- memo: asNullableRecord(replyRecord?.memo),
2017
- seal: asNullableRecord(replyRecord?.seal)
2018
- });
2004
+ return createHistoryEntryFromMemo({ memo: asNullableRecord(replyRecord?.memo) });
2019
2005
  }).filter((msg) => msg.content);
2020
2006
  runtime?.log?.(`[tlon] Extracted ${messages.length} replies from post data`);
2021
2007
  return messages;
@@ -2028,41 +2014,50 @@ async function fetchThreadHistory(api, channelNest, parentId, count = 50, runtim
2028
2014
  }
2029
2015
  // extensions/tlon/src/monitor/ingress.ts
2030
2016
  const TLON_INGRESS_PAYLOAD_VERSION = 1;
2031
- const TLON_INGRESS_POLL_INTERVAL_MS = 1e3;
2032
2017
  const TlonIngressPermanentError = createChannelIngressError("TlonIngressPermanentError", { withReason: true });
2033
- 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) {
2034
2033
  const envelope = asNullableRecord(event);
2035
- const nest = normalizeNullableString(envelope?.nest);
2036
- const response = asNullableRecord(envelope?.response);
2037
- const post = asNullableRecord(response?.post);
2034
+ const nest = readStringField(envelope, "nest");
2035
+ const post = asNullableRecord(asNullableRecord(envelope?.response)?.post);
2038
2036
  const rPost = asNullableRecord(post?.["r-post"]);
2039
2037
  const set = asNullableRecord(rPost?.set);
2040
2038
  const reply = asNullableRecord(rPost?.reply);
2041
- const rReply = asNullableRecord(reply?.["r-reply"]);
2042
- const replySet = asNullableRecord(rReply?.set);
2043
- if (!nest || !asNullableRecord(set?.essay) && !asNullableRecord(replySet?.memo)) return null;
2044
- const eventId = normalizeNullableString(asNullableRecord(replySet?.memo) ? reply?.id : post?.id);
2045
- return eventId ? {
2046
- eventId,
2047
- laneKey: `group:${nest}`
2048
- } : null;
2049
- }
2050
- function inspectChatEvent(event) {
2051
- const envelope = asNullableRecord(event);
2052
- const response = asNullableRecord(envelope?.response);
2053
- const add = asNullableRecord(response?.add);
2054
- const essay = asNullableRecord(add?.essay);
2055
- const eventId = normalizeNullableString(envelope?.id);
2056
- if (!essay || !eventId) return null;
2057
- const whom = normalizeNullableString(asNullableRecord(envelope?.whom)?.ship);
2058
- 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;
2059
2044
  return {
2060
- eventId,
2061
- laneKey: peer ? `direct:${peer}` : `event:${eventId}`
2045
+ nest,
2046
+ messageId,
2047
+ content,
2048
+ isThreadReply: Boolean(memo),
2049
+ messageSet: memo ? replySet : set
2062
2050
  };
2063
2051
  }
2064
- function inspectTlonIngressEvent(source, event) {
2065
- 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;
2066
2061
  }
2067
2062
  function decodeTlonIngressPayload(payload, claimedId) {
2068
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.`);
@@ -2100,14 +2095,33 @@ function resolveTlonIngressNonRetryableFailure(error) {
2100
2095
  }
2101
2096
  function createTlonIngressMonitor(options) {
2102
2097
  const monitor = createChannelIngressMonitor({
2103
- queue: options.queue ?? (() => getTlonRuntime().state.openChannelIngressQueue({ accountId: options.accountId })),
2104
- 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
+ },
2105
2119
  payload: {
2106
2120
  version: TLON_INGRESS_PAYLOAD_VERSION,
2107
2121
  serialize: (raw, { receivedAt }) => ({
2108
2122
  receivedAt,
2109
2123
  source: raw.source,
2110
- rawEvent: JSON.stringify(raw.event)
2124
+ rawEvent: serializeTlonIngressEvent(raw.event)
2111
2125
  }),
2112
2126
  deserialize: (body, { claim }) => deserializeTlonIngressEvent(body, claim.id),
2113
2127
  encode: ({ body }) => ({
@@ -2118,7 +2132,7 @@ function createTlonIngressMonitor(options) {
2118
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.`)
2119
2133
  },
2120
2134
  deliver: (raw, lifecycle) => options.dispatch(raw.source, raw.event, lifecycle),
2121
- pollIntervalMs: options.pollIntervalMs ?? TLON_INGRESS_POLL_INTERVAL_MS,
2135
+ pollIntervalMs: 1e3,
2122
2136
  retention: {
2123
2137
  completedTtlMs: void 0,
2124
2138
  completedMaxEntries: 2e3,
@@ -2127,7 +2141,6 @@ function createTlonIngressMonitor(options) {
2127
2141
  appendRetryDelaysMs: [0],
2128
2142
  drain: {
2129
2143
  resolveNonRetryableFailure: resolveTlonIngressNonRetryableFailure,
2130
- ...options.adoptionStallTimeoutMs === void 0 ? {} : { adoptionStallTimeoutMs: options.adoptionStallTimeoutMs },
2131
2144
  onLog: (message) => options.runtime.log?.(`tlon ${message}`)
2132
2145
  },
2133
2146
  ...options.abortSignal ? { abortSignal: options.abortSignal } : {},
@@ -2136,10 +2149,18 @@ function createTlonIngressMonitor(options) {
2136
2149
  });
2137
2150
  return {
2138
2151
  receive: async ({ source, event }) => {
2139
- return { kind: (await monitor.admit({
2140
- source,
2141
- event
2142
- })).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
+ }
2143
2164
  },
2144
2165
  start: monitor.start,
2145
2166
  stop: monitor.stop,
@@ -2154,8 +2175,7 @@ const TLON_MEDIA_FETCH_TIMEOUTS = {
2154
2175
  // extensions/tlon/src/monitor/media.ts
2155
2176
  const MAX_IMAGES_PER_MESSAGE = 8;
2156
2177
  /** Keeps Tlon's shipped path-duplicating prompt bytes paired with ordered facts. */
2157
- function buildTlonInboundMediaPrompt(messageText, attachments) {
2158
- const media = attachments.map((attachment) => ({ ...attachment }));
2178
+ function buildTlonInboundMediaPrompt(messageText, media) {
2159
2179
  if (media.length === 0) return {
2160
2180
  body: messageText,
2161
2181
  media
@@ -2165,31 +2185,25 @@ function buildTlonInboundMediaPrompt(messageText, attachments) {
2165
2185
  media
2166
2186
  };
2167
2187
  }
2168
- function extractImageBlocks(content) {
2169
- if (!Array.isArray(content)) return {
2170
- images: [],
2171
- unavailableCount: 0
2172
- };
2188
+ async function downloadMessageImages(content, maxBytes) {
2173
2189
  const images = [];
2190
+ const attachments = [];
2174
2191
  let unavailableCount = 0;
2175
- for (const verse of content) if (verse?.block?.image?.src) {
2176
- if (images.length >= MAX_IMAGES_PER_MESSAGE) {
2177
- unavailableCount++;
2178
- 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);
2179
2199
  }
2180
- images.push(verse.block.image.src);
2181
2200
  }
2182
- return {
2183
- images,
2184
- unavailableCount
2185
- };
2186
- }
2187
- async function downloadMedia(url, maxBytes) {
2188
- try {
2201
+ for (const url of images) try {
2189
2202
  const parsedUrl = new URL(url);
2190
2203
  if (parsedUrl.protocol !== "http:" && parsedUrl.protocol !== "https:") {
2191
- console.warn(`[tlon-media] Rejected non-http(s) URL: ${url}`);
2192
- return null;
2204
+ console.warn("[tlon-media] Rejected non-http(s) media URL");
2205
+ unavailableCount++;
2206
+ continue;
2193
2207
  }
2194
2208
  const saved = await saveRemoteMedia({
2195
2209
  url,
@@ -2198,23 +2212,13 @@ async function downloadMedia(url, maxBytes) {
2198
2212
  ssrfPolicy: void 0,
2199
2213
  requestInit: { method: "GET" }
2200
2214
  });
2201
- return {
2215
+ attachments.push({
2202
2216
  path: saved.path,
2203
2217
  contentType: saved.contentType ?? "application/octet-stream"
2204
- };
2205
- } catch (error) {
2206
- console.error(`[tlon-media] Error downloading ${url}: ${formatErrorMessage(error)}`);
2207
- return null;
2208
- }
2209
- }
2210
- async function downloadMessageImages(content, maxBytes) {
2211
- const { images, unavailableCount: overCapCount } = extractImageBlocks(content);
2212
- const attachments = [];
2213
- let unavailableCount = overCapCount;
2214
- for (const url of images) {
2215
- const downloaded = await downloadMedia(url, maxBytes);
2216
- if (downloaded) attachments.push(downloaded);
2217
- else unavailableCount++;
2218
+ });
2219
+ } catch {
2220
+ console.error("[tlon-media] Error downloading inbound media");
2221
+ unavailableCount++;
2218
2222
  }
2219
2223
  return {
2220
2224
  attachments,
@@ -2237,34 +2241,6 @@ var channel_mention_gating_exports = /* @__PURE__ */ __exportAll({ resolveBotThr
2237
2241
  import * as import_openclaw_plugin_sdk_channel_mention_gating from "openclaw/plugin-sdk/channel-mention-gating";
2238
2242
  __reExport(channel_mention_gating_exports, import_openclaw_plugin_sdk_channel_mention_gating);
2239
2243
  // extensions/tlon/src/monitor/mentions.ts
2240
- function resolveTlonGroupMentionDecision(params) {
2241
- const implicitMentions = resolveChannelImplicitMentions({
2242
- cfg: params.cfg,
2243
- channel: "tlon",
2244
- accountId: params.accountId
2245
- });
2246
- const threadPolicy = resolveBotThreadMentionPolicy({
2247
- isBotOwnedThread: params.isBotOwnedThread === true,
2248
- requireMentionInBotThreads: params.requireMentionInBotThreads,
2249
- requireMention: true,
2250
- implicitMentionKinds: (0, channel_mention_gating_exports.implicitMentionKindWhen)("bot_thread_participant", params.botParticipatedInThread)
2251
- });
2252
- return (0, channel_mention_gating_exports.resolveInboundMentionDecision)({
2253
- facts: {
2254
- canDetectMention: true,
2255
- wasMentioned: params.wasMentioned,
2256
- implicitMentionKinds: threadPolicy.implicitMentionKinds
2257
- },
2258
- policy: {
2259
- isGroup: true,
2260
- requireMention: threadPolicy.requireMention,
2261
- implicitMentions,
2262
- allowTextCommands: false,
2263
- hasControlCommand: false,
2264
- commandAuthorized: false
2265
- }
2266
- });
2267
- }
2268
2244
  async function prepareTlonGroupAdmission(params) {
2269
2245
  const { cfg, account, channelNest, botShipName, runtime } = params;
2270
2246
  const parentId = readStringField(params.messageSeal, "parent-id") ?? readStringField(params.messageSeal, "parent") ?? null;
@@ -2275,17 +2251,37 @@ async function prepareTlonGroupAdmission(params) {
2275
2251
  const isBotOwnedThread = Boolean(threadRootAuthor && normalizeShip(threadRootAuthor) === botShipName);
2276
2252
  const resolveCurrentAdmission = () => {
2277
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
+ });
2278
2281
  return {
2279
2282
  ...authorization,
2280
- senderAllowed: params.isOwner(params.senderShip) || authorization.mode === "open" || authorization.allowedShips.some((ship) => normalizeShip(ship) === params.senderShip),
2281
- mentionDecision: resolveTlonGroupMentionDecision({
2282
- cfg,
2283
- accountId: account.accountId,
2284
- wasMentioned: mentioned,
2285
- botParticipatedInThread,
2286
- isBotOwnedThread,
2287
- requireMentionInBotThreads: authorization.requireMentionInBotThreads ?? account.requireMentionInBotThreads
2288
- })
2283
+ senderAllowed,
2284
+ mentionDecision: decision
2289
2285
  };
2290
2286
  };
2291
2287
  const admission = resolveCurrentAdmission();
@@ -2345,6 +2341,7 @@ function applyTlonSettingsOverrides(params) {
2345
2341
  effectiveAutoAcceptDmInvites: settings.autoAcceptDmInvites ?? account.autoAcceptDmInvites ?? false,
2346
2342
  effectiveAutoAcceptGroupInvites: settings.autoAcceptGroupInvites ?? account.autoAcceptGroupInvites ?? false,
2347
2343
  effectiveGroupInviteAllowlist: settings.groupInviteAllowlist ?? account.groupInviteAllowlist,
2344
+ explicitChannels: mergeUniqueStrings(account.groupChannels, settings.groupChannels),
2348
2345
  effectiveAutoDiscoverChannels: settings.autoDiscoverChannels ?? account.autoDiscoverChannels ?? false,
2349
2346
  effectiveOwnerShip,
2350
2347
  pendingApprovals: settings.pendingApprovals?.length ? settings.pendingApprovals : [],
@@ -2354,12 +2351,26 @@ function applyTlonSettingsOverrides(params) {
2354
2351
  function mergeUniqueStrings(base, next) {
2355
2352
  return uniqueStrings([...base, ...next ?? []]);
2356
2353
  }
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
+ }
2357
2369
  // extensions/tlon/src/monitor/tracking.ts
2358
- const TLON_PARTICIPATED_THREAD_LIMIT = 2e3;
2359
- function createParticipatedThreadTracker(limit = TLON_PARTICIPATED_THREAD_LIMIT) {
2370
+ function createParticipatedThreadTracker() {
2360
2371
  const cache = createDedupeCache({
2361
2372
  ttlMs: 0,
2362
- maxSize: limit
2373
+ maxSize: 2e3
2363
2374
  });
2364
2375
  return {
2365
2376
  add: (parentId) => {
@@ -2397,7 +2408,7 @@ async function monitorTlonProvider(opts) {
2397
2408
  if (cfg.channels?.tlon?.enabled === false) return;
2398
2409
  const logger = core.logging.getChildLogger({ module: "tlon-auto-reply" });
2399
2410
  const runtime = opts.runtime ?? createLoggerBackedRuntime({ logger });
2400
- const account = resolveTlonAccount(cfg, opts.accountId ?? void 0);
2411
+ const account = resolveTlonAccount(cfg, opts.accountId);
2401
2412
  if (!account.enabled) return;
2402
2413
  if (!account.configured || !account.ship || !account.url || !account.code) throw new Error("Tlon account not configured (ship/url/code required)");
2403
2414
  const botShipName = normalizeShip(account.ship);
@@ -2453,6 +2464,7 @@ async function monitorTlonProvider(opts) {
2453
2464
  account,
2454
2465
  currentSettings: {}
2455
2466
  });
2467
+ const installSettings = createTlonSettingsInstaller(settingsState, account, (message) => runtime.log?.(message));
2456
2468
  const participatedThreads = createParticipatedThreadTracker();
2457
2469
  const channelHistory = createChannelHistoryCache();
2458
2470
  const dmSendersBySession = /* @__PURE__ */ new Map();
@@ -2467,29 +2479,19 @@ async function monitorTlonProvider(opts) {
2467
2479
  runtime.log?.(`[tlon] Could not fetch nickname: ${formatErrorMessage(error)}`);
2468
2480
  }
2469
2481
  let initForeigns = null;
2470
- try {
2471
- settingsState.currentSettings = await settingsManager.load();
2472
- const migrations = buildTlonSettingsMigrations(account, settingsState.currentSettings);
2473
- for (const { key, fileValue, settingsValue } of migrations) if (shouldMigrateTlonSetting(fileValue, settingsValue)) try {
2474
- await putTlonSetting(api, key, fileValue);
2475
- runtime.log?.(`[tlon] Migrated ${key} from config to settings store`);
2476
- } catch (err) {
2477
- runtime.log?.(`[tlon] Failed to migrate ${key}: ${String(err)}`);
2478
- }
2479
- Object.assign(settingsState, applyTlonSettingsOverrides({
2480
- account,
2481
- currentSettings: settingsState.currentSettings,
2482
- log: (message) => runtime.log?.(message)
2483
- }));
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`);
2484
2487
  } catch (err) {
2485
- runtime.log?.(`[tlon] Settings store not available, using file config: ${String(err)}`);
2488
+ runtime.log?.(`[tlon] Failed to migrate ${key}: ${String(err)}`);
2486
2489
  }
2487
- if (settingsState.effectiveAutoDiscoverChannels) try {
2490
+ installSettings(settingsState.currentSettings);
2491
+ if (settingsState.effectiveAutoDiscoverChannels) {
2488
2492
  const initData = await fetchInitData(api, runtime);
2489
2493
  if (initData.channels.length > 0) groupChannels = initData.channels;
2490
2494
  initForeigns = initData.foreigns;
2491
- } catch (error) {
2492
- runtime.error?.(`[tlon] Auto-discovery failed: ${formatErrorMessage(error)}`);
2493
2495
  }
2494
2496
  if (account.groupChannels.length > 0) {
2495
2497
  groupChannels = mergeUniqueStrings(groupChannels, account.groupChannels);
@@ -2515,21 +2517,17 @@ async function monitorTlonProvider(opts) {
2515
2517
  const senderId = clubId === void 0 ? senderShip : clubSenderId(clubId, senderShip);
2516
2518
  let attachments = [];
2517
2519
  let unavailableMediaCount = 0;
2518
- if (messageContent) try {
2520
+ if (messageContent) {
2519
2521
  ({attachments, unavailableCount: unavailableMediaCount} = await downloadMessageImages(messageContent, account.mediaMaxBytes));
2520
2522
  if (attachments.length > 0) runtime.log?.(`[tlon] Downloaded ${attachments.length} image(s) from message`);
2521
- } catch (error) {
2522
- runtime.log?.(`[tlon] Failed to download images: ${formatErrorMessage(error)}`);
2523
2523
  }
2524
- if (isThreadReply && parentId && channelNest) try {
2525
- const threadHistory = await fetchThreadHistory(api, channelNest, parentId, 20, runtime);
2524
+ if (isThreadReply && parentId && channelNest) {
2525
+ const threadHistory = await fetchThreadHistory(api, channelNest, parentId, runtime);
2526
2526
  if (threadHistory.length > 0) {
2527
2527
  const threadContext = threadHistory.slice(-10).map((msg) => `${msg.author}: ${msg.content}`).join("\n");
2528
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}`;
2529
2529
  runtime?.log?.(`[tlon] Added thread context (${threadHistory.length} replies) to message`);
2530
2530
  }
2531
- } catch (error) {
2532
- runtime?.log?.(`[tlon] Could not fetch thread context: ${formatErrorMessage(error)}`);
2533
2531
  }
2534
2532
  const groupTarget = isGroup && channelNest ? parseChannelNest(channelNest) : null;
2535
2533
  const groupSendContext = groupTarget && {
@@ -2538,7 +2536,7 @@ async function monitorTlonProvider(opts) {
2538
2536
  ...groupTarget
2539
2537
  };
2540
2538
  if (isGroup && channelNest && isSummarizationRequest(messageText)) try {
2541
- const history = await channelHistory.getChannelHistory(api, channelNest, 50, runtime);
2539
+ const history = await channelHistory.getChannelHistory(api, channelNest, runtime);
2542
2540
  if (history.length === 0) {
2543
2541
  const noHistoryMsg = "I couldn't fetch any messages for this channel. It might be empty or there might be a permissions issue.";
2544
2542
  if (groupSendContext && isAdmissionAllowed?.() !== false) await sendGroupMessage({
@@ -2564,7 +2562,7 @@ async function monitorTlonProvider(opts) {
2564
2562
  const route = core.channel.routing.resolveAgentRoute({
2565
2563
  cfg,
2566
2564
  channel: "tlon",
2567
- accountId: opts.accountId ?? void 0,
2565
+ accountId: opts.accountId,
2568
2566
  peer: {
2569
2567
  kind: isGroup ? "group" : "direct",
2570
2568
  id: isGroup ? channelNest ?? senderShip : senderShip
@@ -2624,7 +2622,6 @@ async function monitorTlonProvider(opts) {
2624
2622
  body: commandBody,
2625
2623
  notice: `[tlon ${unavailableMediaCount > 1 ? `${unavailableMediaCount} attachments` : "attachment"} unavailable]`
2626
2624
  }) : commandBody;
2627
- const tlonConversationId = isGroup ? channelNest ?? senderShip : senderShip;
2628
2625
  const ctxPayload = core.channel.inbound.buildContext({
2629
2626
  channel: "tlon",
2630
2627
  accountId: route.accountId,
@@ -2638,7 +2635,7 @@ async function monitorTlonProvider(opts) {
2638
2635
  },
2639
2636
  conversation: {
2640
2637
  kind: isGroup ? "group" : "direct",
2641
- id: tlonConversationId,
2638
+ id: isGroup ? channelNest ?? senderShip : senderShip,
2642
2639
  label: fromLabel
2643
2640
  },
2644
2641
  route: {
@@ -2665,6 +2662,7 @@ async function monitorTlonProvider(opts) {
2665
2662
  CommandAuthorized: commandAuthorized,
2666
2663
  CommandSource: "text",
2667
2664
  ...attachments.length > 0 && { Attachments: attachments },
2665
+ ...isGroup && { ReplyThreading: { implicitCurrentMessage: "deny" } },
2668
2666
  ...parentId && { ThreadId: parentId }
2669
2667
  }
2670
2668
  });
@@ -2713,7 +2711,7 @@ async function monitorTlonProvider(opts) {
2713
2711
  await sendGroupMessage({
2714
2712
  ...groupSendContext,
2715
2713
  text: replyText,
2716
- replyToId: parentId ?? void 0
2714
+ replyToId: parentId
2717
2715
  });
2718
2716
  return {
2719
2717
  visibleReplySent: true,
@@ -2735,8 +2733,7 @@ async function monitorTlonProvider(opts) {
2735
2733
  }
2736
2734
  },
2737
2735
  onError: (err, info) => {
2738
- const dispatchDuration = Date.now() - dispatchStartTime;
2739
- 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)}`);
2740
2737
  }
2741
2738
  },
2742
2739
  dispatcherOptions: { humanDelay },
@@ -2747,6 +2744,7 @@ async function monitorTlonProvider(opts) {
2747
2744
  });
2748
2745
  };
2749
2746
  const watchedChannels = new Set(groupChannels);
2747
+ const canExpandCitedNest = (nest) => settingsState.effectiveAutoDiscoverChannels || settingsState.explicitChannels.includes(nest);
2750
2748
  const addWatchedChannels = (channels, logPrefix) => {
2751
2749
  const previousCount = watchedChannels.size;
2752
2750
  for (const channelNest of channels) if (!watchedChannels.has(channelNest)) {
@@ -2804,36 +2802,24 @@ async function monitorTlonProvider(opts) {
2804
2802
  });
2805
2803
  const handleChannelsFirehose = async (event, turnAdoptionLifecycle) => {
2806
2804
  try {
2807
- const eventRecord = asNullableRecord(event);
2808
- const nest = readStringField(eventRecord, "nest");
2809
- if (!nest) return;
2810
- if (!watchedChannels.has(nest)) return;
2811
- const response = asNullableRecord(eventRecord?.response);
2812
- if (!response) return;
2813
- const post = asNullableRecord(response.post);
2814
- const rPost = asNullableRecord(post?.["r-post"]);
2815
- const set = asNullableRecord(rPost?.set);
2816
- const reply = asNullableRecord(rPost?.reply);
2817
- const replyPayload = asNullableRecord(reply?.["r-reply"]);
2818
- const replySet = asNullableRecord(replyPayload?.set);
2819
- const essay = asNullableRecord(set?.essay);
2820
- const memo = asNullableRecord(replySet?.memo);
2821
- const content = memo ?? essay;
2822
- if (!content) return;
2823
- const isThreadReply = Boolean(memo);
2824
- const messageId = isThreadReply ? readStringField(reply, "id") : readStringField(post, "id");
2825
- if (!messageId) return;
2805
+ const message = decodeTlonChannelsEvent(event);
2806
+ if (!message || !watchedChannels.has(message.nest)) return;
2807
+ const { nest, messageId, content, isThreadReply, messageSet } = message;
2826
2808
  const senderShip = normalizeShip(readStringField(content, "author") ?? "");
2827
2809
  if (!senderShip || senderShip === botShipName) return;
2828
- 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
+ }
2829
2817
  if (!rawText.trim()) return;
2830
- const contentBody = content.content;
2831
2818
  const sentAt = asFiniteNumber(content?.sent) ?? Date.now();
2832
2819
  channelHistory.cacheMessage(nest, {
2833
2820
  author: senderShip,
2834
2821
  content: rawText,
2835
- timestamp: sentAt,
2836
- id: messageId
2822
+ timestamp: sentAt
2837
2823
  });
2838
2824
  const { allowedShips, senderAllowed, mentionDecision, parentId, isAdmissionAllowed } = await prepareTlonGroupAdmission({
2839
2825
  cfg,
@@ -2845,7 +2831,7 @@ async function monitorTlonProvider(opts) {
2845
2831
  botShipName,
2846
2832
  botNickname,
2847
2833
  rawText,
2848
- messageSeal: isThreadReply ? asNullableRecord(replySet?.seal) : asNullableRecord(set?.seal),
2834
+ messageSeal: asNullableRecord(messageSet?.seal),
2849
2835
  isThreadReply,
2850
2836
  hasParticipatedInThread: participatedThreads.has,
2851
2837
  getSettings: () => settingsState.currentSettings,
@@ -2858,11 +2844,11 @@ async function monitorTlonProvider(opts) {
2858
2844
  type: "channel",
2859
2845
  requestingShip: senderShip,
2860
2846
  channelNest: nest,
2861
- messagePreview: sliceUtf16Safe(rawText, 0, 100),
2847
+ messagePreview: rawText,
2862
2848
  originalMessage: {
2863
2849
  messageId,
2864
2850
  messageText: rawText,
2865
- messageContent: contentBody,
2851
+ messageContent: content.content,
2866
2852
  timestamp: sentAt,
2867
2853
  parentId: parentId ?? void 0,
2868
2854
  isThreadReply
@@ -2872,12 +2858,12 @@ async function monitorTlonProvider(opts) {
2872
2858
  } else runtime.log?.(`[tlon] Access denied: ${senderShip} in ${nest} (allowed: ${allowedShips.join(", ")})`);
2873
2859
  return;
2874
2860
  }
2875
- const messageText = await resolveTlonCitations(contentBody, api, runtime) + rawText;
2861
+ const messageText = await resolveTlonCitations(content.content, canExpandCitedNest, api, runtime) + rawText;
2876
2862
  await processMessage({
2877
2863
  messageId,
2878
2864
  senderShip,
2879
2865
  messageText,
2880
- messageContent: contentBody,
2866
+ messageContent: content.content,
2881
2867
  isGroup: true,
2882
2868
  channelNest: nest,
2883
2869
  timestamp: sentAt,
@@ -2915,21 +2901,16 @@ async function monitorTlonProvider(opts) {
2915
2901
  const ownerInvite = isOwner(ship);
2916
2902
  const allowed = ownerInvite || await isDmAllowedWithIngress(ship, settingsState.effectiveDmAllowlist);
2917
2903
  if (ownerInvite || settingsState.effectiveAutoAcceptDmInvites && allowed) {
2918
- try {
2919
- await api.poke({
2920
- app: "chat",
2921
- mark: "chat-dm-rsvp",
2922
- json: {
2923
- ship,
2924
- ok: true
2925
- }
2926
- });
2927
- processedDmInvites.add(ship);
2928
- runtime.log?.(ownerInvite ? `[tlon] Auto-accepted DM invite from owner ${ship}` : `[tlon] Auto-accepted DM invite from ${ship}`);
2929
- } catch (err) {
2930
- runtime.error?.(ownerInvite ? `[tlon] Failed to auto-accept DM from owner: ${String(err)}` : `[tlon] Failed to auto-accept DM from ${ship}: ${String(err)}`);
2931
- throw err;
2932
- }
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}`);
2933
2914
  continue;
2934
2915
  }
2935
2916
  if (settingsState.effectiveOwnerShip && !allowed) {
@@ -2943,14 +2924,9 @@ async function monitorTlonProvider(opts) {
2943
2924
  }
2944
2925
  return;
2945
2926
  }
2946
- const eventRecord = asNullableRecord(event);
2947
- if (!eventRecord) return;
2948
- const whom = eventRecord.whom;
2949
- const messageId = readStringField(eventRecord, "id");
2950
- const response = asNullableRecord(eventRecord.response);
2951
- if (!messageId || !response) return;
2952
- const essay = asNullableRecord(asNullableRecord(response.add)?.essay);
2953
- if (!essay) return;
2927
+ const message = decodeTlonChatEvent(event);
2928
+ if (!message) return;
2929
+ const { whom, messageId, essay } = message;
2954
2930
  const authorShip = normalizeShip(readStringField(essay, "author") ?? "");
2955
2931
  const partnerShip = extractDmPartnerShip(whom);
2956
2932
  const senderShip = partnerShip || authorShip;
@@ -2960,16 +2936,21 @@ async function monitorTlonProvider(opts) {
2960
2936
  if (authorShip === botShipName) return;
2961
2937
  if (!senderShip || senderShip === botShipName) return;
2962
2938
  if (authorShip && partnerShip && authorShip !== partnerShip) runtime.log?.(`[tlon] DM ship mismatch (author=${authorShip}, partner=${partnerShip}) - routing to partner`);
2963
- 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
+ }
2964
2946
  if (!rawText.trim()) return;
2965
- const messageText = rawText;
2966
2947
  const ownerDm = !isClubMessage && isOwner(senderShip);
2967
- if (ownerDm && await handleApprovalResponse(messageText)) {
2968
- runtime.log?.(`[tlon] Processed approval response from owner: ${messageText}`);
2948
+ if (ownerDm && await handleApprovalResponse(rawText)) {
2949
+ runtime.log?.("[tlon] Processed approval response from owner");
2969
2950
  return;
2970
2951
  }
2971
- if (ownerDm && await handleAdminCommand(messageText)) {
2972
- runtime.log?.(`[tlon] Processed admin command from owner: ${messageText}`);
2952
+ if (ownerDm && await handleAdminCommand(rawText)) {
2953
+ runtime.log?.("[tlon] Processed admin command from owner");
2973
2954
  return;
2974
2955
  }
2975
2956
  const resolveChannelIngress = async (contextBinding) => await resolveTlonMessageIngress({
@@ -2992,11 +2973,11 @@ async function monitorTlonProvider(opts) {
2992
2973
  const approval = createPendingApproval({
2993
2974
  type: "dm",
2994
2975
  requestingShip: senderShip,
2995
- messagePreview: sliceUtf16Safe(messageText, 0, 100),
2976
+ messagePreview: rawText,
2996
2977
  ...isClubMessage ? { clubId } : { verifiedDirect: true },
2997
2978
  ...isClubMessage && isOwner(senderShip) ? {} : { originalMessage: {
2998
2979
  messageId,
2999
- messageText,
2980
+ messageText: rawText,
3000
2981
  messageContent: essay.content,
3001
2982
  timestamp: asFiniteNumber(essay?.sent) ?? Date.now()
3002
2983
  } }
@@ -3005,10 +2986,10 @@ async function monitorTlonProvider(opts) {
3005
2986
  } else runtime.log?.(`[tlon] Blocked DM from ${senderShip}: not in allowlist`);
3006
2987
  return;
3007
2988
  }
3008
- 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;
3009
2990
  if (ownerDm) runtime.log?.(`[tlon] Processing DM from owner ${senderShip}`);
3010
2991
  await processMessage({
3011
- messageText: resolvedMessageText,
2992
+ messageText: agentText,
3012
2993
  messageId,
3013
2994
  senderShip,
3014
2995
  clubId,
@@ -3035,6 +3016,14 @@ async function monitorTlonProvider(opts) {
3035
3016
  await handleChatFirehose(event, turnAdoptionLifecycle);
3036
3017
  }
3037
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
+ });
3038
3027
  try {
3039
3028
  runtime.log?.("[tlon] Subscribing to firehose updates...");
3040
3029
  for (const [source, path, label, handleEvent] of [[
@@ -3057,12 +3046,7 @@ async function monitorTlonProvider(opts) {
3057
3046
  event
3058
3047
  })).kind === "ignored") await handleEvent(event);
3059
3048
  },
3060
- err: (error) => {
3061
- runtime.error?.(`[tlon] ${label} firehose error: ${String(error)}`);
3062
- },
3063
- quit: () => {
3064
- runtime.log?.(`[tlon] ${label} firehose subscription ended`);
3065
- }
3049
+ ...subscriptionLogHandlers(`${label} firehose`, `${label} firehose subscription`)
3066
3050
  });
3067
3051
  runtime.log?.(`[tlon] Subscribed to ${source} firehose (${path})`);
3068
3052
  }
@@ -3088,23 +3072,13 @@ async function monitorTlonProvider(opts) {
3088
3072
  runtime.error?.(`[tlon] Error handling contacts event: ${formatErrorMessage(error)}`);
3089
3073
  }
3090
3074
  },
3091
- err: (error) => {
3092
- runtime.error?.(`[tlon] Contacts subscription error: ${String(error)}`);
3093
- },
3094
- quit: () => {
3095
- runtime.log?.("[tlon] Contacts subscription ended");
3096
- }
3075
+ ...subscriptionLogHandlers("Contacts subscription", "Contacts subscription")
3097
3076
  });
3098
3077
  runtime.log?.("[tlon] Subscribed to contacts updates (/v1/news)");
3099
3078
  try {
3100
3079
  await settingsManager.startSubscription((newSettings) => {
3101
- settingsState.currentSettings = newSettings;
3102
3080
  addWatchedChannels(newSettings.groupChannels ?? [], "[tlon] Settings: now watching channel ");
3103
- Object.assign(settingsState, applyTlonSettingsOverrides({
3104
- account,
3105
- currentSettings: newSettings,
3106
- log: (message) => runtime.log?.(message)
3107
- }));
3081
+ installSettings(newSettings);
3108
3082
  });
3109
3083
  } catch (err) {
3110
3084
  runtime.log?.(`[tlon] Settings subscription not available: ${String(err)}`);
@@ -3122,27 +3096,23 @@ async function monitorTlonProvider(opts) {
3122
3096
  const discoveredChannels = mergeUniqueStrings(Object.keys(asNullableRecord(eventRecord.channels) ?? {}), joinedChannels.filter((channel) => typeof channel === "string")).filter((channel) => channel.startsWith("chat/"));
3123
3097
  addWatchedChannels(discoveredChannels, "[tlon] Auto-detected new channel: ");
3124
3098
  if (!settingsState.effectiveAutoAcceptGroupInvites) return;
3125
- const currentChannels = settingsState.currentSettings.groupChannels ?? [];
3099
+ const settingsSnapshot = settingsState.currentSettings;
3100
+ const currentChannels = settingsSnapshot.groupChannels ?? [];
3126
3101
  const unpersistedChannels = discoveredChannels.filter((channel) => !currentChannels.includes(channel));
3127
3102
  if (unpersistedChannels.length === 0) return;
3128
3103
  const updatedChannels = mergeUniqueStrings(currentChannels, unpersistedChannels);
3129
3104
  await putTlonSetting(api, "groupChannels", updatedChannels);
3130
- settingsState.currentSettings = {
3131
- ...settingsState.currentSettings,
3105
+ if (settingsState.currentSettings === settingsSnapshot) installSettings({
3106
+ ...settingsSnapshot,
3132
3107
  groupChannels: updatedChannels
3133
- };
3108
+ }, true);
3134
3109
  runtime.log?.(`[tlon] Persisted ${unpersistedChannels.join(", ")} to settings store`);
3135
3110
  } catch (error) {
3136
3111
  runtime.error?.(`[tlon] Error handling groups-ui event: ${formatErrorMessage(error)}`);
3137
3112
  throw error;
3138
3113
  }
3139
3114
  },
3140
- err: (error) => {
3141
- runtime.error?.(`[tlon] Groups-ui subscription error: ${String(error)}`);
3142
- },
3143
- quit: () => {
3144
- runtime.log?.("[tlon] Groups-ui subscription ended");
3145
- }
3115
+ ...subscriptionLogHandlers("Groups-ui subscription", "Groups-ui subscription")
3146
3116
  });
3147
3117
  runtime.log?.("[tlon] Subscribed to groups-ui for real-time channel detection");
3148
3118
  } catch (err) {
@@ -3213,12 +3183,7 @@ async function monitorTlonProvider(opts) {
3213
3183
  throw error;
3214
3184
  }
3215
3185
  },
3216
- err: (error) => {
3217
- runtime.error?.(`[tlon] Foreigns subscription error: ${String(error)}`);
3218
- },
3219
- quit: () => {
3220
- runtime.log?.("[tlon] Foreigns subscription ended");
3221
- }
3186
+ ...subscriptionLogHandlers("Foreigns subscription", "Foreigns subscription")
3222
3187
  });
3223
3188
  runtime.log?.("[tlon] Subscribed to foreigns (/v1/foreigns) for auto-accepting group invites");
3224
3189
  } catch (err) {
@@ -3242,13 +3207,9 @@ async function monitorTlonProvider(opts) {
3242
3207
  everyMs: 12e4,
3243
3208
  run: async () => {
3244
3209
  if (!settingsState.effectiveAutoDiscoverChannels) return;
3245
- try {
3246
- const { channels: discoveredChannels } = await fetchInitData(api, runtime);
3247
- if (discoveryScheduler.signal.aborted) return;
3248
- addWatchedChannels(discoveredChannels, "[tlon] Now watching new channel: ");
3249
- } catch (error) {
3250
- runtime.error?.(`[tlon] Channel refresh error: ${formatErrorMessage(error)}`);
3251
- }
3210
+ const { channels: discoveredChannels } = await fetchInitData(api, runtime);
3211
+ if (discoveryScheduler.signal.aborted) return;
3212
+ addWatchedChannels(discoveredChannels, "[tlon] Now watching new channel: ");
3252
3213
  }
3253
3214
  });
3254
3215
  await waitUntilAbort(opts.abortSignal);
@@ -3332,6 +3293,12 @@ function prefixEndpoint(endpoint) {
3332
3293
  function sanitizeFileName(fileName) {
3333
3294
  return fileName.split(/[/\\]/).pop() || fileName;
3334
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
+ }
3335
3302
  async function scryJson(config, cookie, path) {
3336
3303
  return await scryUrbitPath({
3337
3304
  baseUrl: config.shipUrl,
@@ -3343,54 +3310,6 @@ async function scryJson(config, cookie, path) {
3343
3310
  auditContext: "tlon-storage-scry"
3344
3311
  });
3345
3312
  }
3346
- async function getStorageConfiguration(config, cookie) {
3347
- const result = await scryJson(config, cookie, "/storage/configuration.json");
3348
- if ("storage-update" in result && result["storage-update"]?.configuration) return result["storage-update"].configuration;
3349
- if ("currentBucket" in result) return result;
3350
- throw new Error("Invalid storage configuration response");
3351
- }
3352
- async function getStorageCredentials(config, cookie) {
3353
- const result = await scryJson(config, cookie, "/storage/credentials.json");
3354
- if ("storage-update" in result) return result["storage-update"]?.credentials ?? null;
3355
- if (isStorageCredentials(result)) return result;
3356
- return null;
3357
- }
3358
- async function getMemexUploadUrl(params) {
3359
- const token = await scryJson(params.config, params.cookie, "/genuine/secret.json");
3360
- const resolvedToken = typeof token === "string" ? token : token.secret;
3361
- if (!resolvedToken) throw new Error("Missing genuine secret");
3362
- const endpoint = `${MEMEX_BASE_URL}/v1/${params.config.shipName}/upload`;
3363
- let guarded;
3364
- try {
3365
- guarded = await fetchWithSsrFGuard({
3366
- url: endpoint,
3367
- init: {
3368
- method: "PUT",
3369
- headers: { "Content-Type": "application/json" },
3370
- body: JSON.stringify({
3371
- token: resolvedToken,
3372
- contentLength: params.contentLength,
3373
- contentType: params.contentType,
3374
- fileName: params.fileName
3375
- })
3376
- },
3377
- auditContext: "tlon-memex-upload-url",
3378
- capture: false,
3379
- maxRedirects: 0,
3380
- timeoutMs: TLON_MEMEX_UPLOAD_URL_TIMEOUT_MS,
3381
- beforeRequest: params.config.assertDirectAdapterHandoff
3382
- });
3383
- if (!guarded.response.ok) throw new Error(`Memex upload request failed: ${guarded.response.status}`);
3384
- const data = await readProviderJsonResponse(guarded.response, "Memex upload", { maxBytes: MEMEX_UPLOAD_RESPONSE_MAX_BYTES });
3385
- if (!data?.url || !data.filePath) throw new Error("Invalid response from Memex");
3386
- return {
3387
- hostedUrl: data.filePath,
3388
- uploadUrl: data.url
3389
- };
3390
- } finally {
3391
- await releaseUploadResponse(guarded);
3392
- }
3393
- }
3394
3313
  async function uploadFile(params, clientConfig) {
3395
3314
  const config = {
3396
3315
  ...clientConfig,
@@ -3401,7 +3320,19 @@ async function uploadFile(params, clientConfig) {
3401
3320
  beforeRequest: config.assertDirectAdapterHandoff
3402
3321
  });
3403
3322
  const privateNetworkPolicy = ssrfPolicyFromDangerouslyAllowPrivateNetwork(config.dangerouslyAllowPrivateNetwork);
3404
- 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()]);
3405
3336
  const contentType = params.contentType || params.blob.type || "application/octet-stream";
3406
3337
  const extension = extensionForMime(contentType) || ".jpg";
3407
3338
  const fileName = sanitizeFileName(params.fileName || `upload${extension}`);
@@ -3430,14 +3361,45 @@ async function uploadFile(params, clientConfig) {
3430
3361
  await releaseUploadResponse(guarded);
3431
3362
  }
3432
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
+ }
3433
3401
  if (useMemex) {
3434
- const { hostedUrl, uploadUrl } = await getMemexUploadUrl({
3435
- config,
3436
- cookie,
3437
- contentLength: params.blob.size,
3438
- contentType,
3439
- fileName: fileKey
3440
- });
3402
+ const { hostedUrl, uploadUrl } = await getMemexUploadUrl();
3441
3403
  await uploadBlob(assertTrustedMemexUploadUrl(uploadUrl, "Memex upload URL"), {
3442
3404
  "Cache-Control": "public, max-age=3600",
3443
3405
  "Content-Type": contentType
@@ -3468,7 +3430,7 @@ async function uploadFile(params, clientConfig) {
3468
3430
  });
3469
3431
  const signedUrl = await getSignedUrl(client, command, { expiresIn: 3600 });
3470
3432
  await uploadBlob(signedUrl, signedUrl.includes("digitaloceanspaces.com") ? headers : void 0);
3471
- 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") };
3472
3434
  }
3473
3435
  // extensions/tlon/src/urbit/upload.ts
3474
3436
  /**
@@ -3502,7 +3464,7 @@ async function uploadImageFromUrl(imageUrl, clientConfig, maxBytes) {
3502
3464
  const contentType = fetched.contentType || "image/png";
3503
3465
  return (await uploadFile({
3504
3466
  blob: new Blob([bufferToBlobPart(fetched.buffer)], { type: contentType }),
3505
- fileName: url.pathname.split("/").pop() || `upload-${Date.now()}.png`,
3467
+ fileName: fetched.fileName?.trim() || url.pathname.split("/").pop()?.trim() || `upload-${Date.now()}.png`,
3506
3468
  contentType
3507
3469
  }, {
3508
3470
  ...clientConfig,
@@ -3517,75 +3479,23 @@ async function uploadImageFromUrl(imageUrl, clientConfig, maxBytes) {
3517
3479
  }
3518
3480
  }
3519
3481
  // extensions/tlon/src/channel.runtime.ts
3520
- async function createHttpPokeApi(params) {
3521
- const ssrfPolicy = ssrfPolicyFromDangerouslyAllowPrivateNetwork(params.dangerouslyAllowPrivateNetwork);
3522
- const cookie = await authenticate(params.url, params.code, {
3523
- ssrfPolicy,
3524
- beforeRequest: params.assertDirectAdapterHandoff
3525
- });
3526
- const channelId = `${Math.floor(Date.now() / 1e3)}-${crypto.randomUUID()}`;
3527
- const shipName = params.ship.replace(/^~/, "");
3528
- return { poke: async (pokeParams) => {
3529
- const pokeId = Date.now();
3530
- const pokeData = {
3531
- id: pokeId,
3532
- action: "poke",
3533
- ship: shipName,
3534
- app: pokeParams.app,
3535
- mark: pokeParams.mark,
3536
- json: pokeParams.json
3537
- };
3538
- params.assertDirectAdapterHandoff?.();
3539
- await params.onPlatformSendDispatch?.();
3540
- const { response, release } = await putUrbitChannel({
3541
- baseUrl: params.url,
3542
- channelId,
3543
- ship: shipName,
3544
- cookie: normalizeUrbitCookie(cookie),
3545
- ssrfPolicy
3546
- }, {
3547
- body: [pokeData],
3548
- auditContext: "tlon-poke",
3549
- beforeRequest: params.assertDirectAdapterHandoff
3550
- });
3551
- try {
3552
- if (!response.ok && response.status !== 204) {
3553
- const errorText = await readResponseTextLimited(response, 16384);
3554
- throw new Error(`Poke failed: ${response.status} - ${redactUrbitErrorText(errorText)}`);
3555
- }
3556
- return pokeId;
3557
- } finally {
3558
- await release();
3559
- }
3560
- } };
3561
- }
3562
- function resolveOutboundContext(params) {
3563
- const account = resolveTlonAccount(params.cfg, params.accountId ?? void 0);
3564
- if (!account.configured || !account.ship || !account.url || !account.code) {
3565
- const missingFields = [
3566
- account.ship ? void 0 : "ship",
3567
- account.url ? void 0 : "url",
3568
- account.code ? void 0 : "code"
3569
- ].filter((field) => field !== void 0);
3570
- throw new Error(`Tlon account ${account.accountId} not configured (missing ${missingFields.join(", ")})`);
3571
- }
3572
- const parsed = parseTlonTarget(params.to);
3573
- if (!parsed) throw new Error(`Invalid Tlon target. Use ${formatTargetHint()}`);
3574
- return {
3575
- account,
3576
- parsed
3577
- };
3578
- }
3579
3482
  function resolveReplyId(replyToId, threadId) {
3580
3483
  return replyToId ?? threadId ? String(replyToId ?? threadId) : void 0;
3581
3484
  }
3582
3485
  async function sendTlonOutbound(params, kind) {
3583
3486
  const { cfg, to, text, accountId, replyToId, threadId, assertDirectAdapterHandoff } = params;
3584
- const { account, parsed } = resolveOutboundContext({
3585
- cfg,
3586
- accountId,
3587
- to
3588
- });
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;
3589
3499
  let uploadedUrl;
3590
3500
  if (kind === "media") {
3591
3501
  const { mediaUrl } = params;
@@ -3597,14 +3507,30 @@ async function sendTlonOutbound(params, kind) {
3597
3507
  assertDirectAdapterHandoff
3598
3508
  }, account.mediaMaxBytes) : void 0;
3599
3509
  }
3600
- const api = await createHttpPokeApi({
3601
- url: account.url,
3602
- ship: account.ship,
3603
- code: account.code,
3604
- dangerouslyAllowPrivateNetwork: account.dangerouslyAllowPrivateNetwork ?? void 0,
3605
- assertDirectAdapterHandoff,
3606
- 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
3607
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
+ } };
3608
3534
  const fromShip = normalizeShip(account.ship);
3609
3535
  const story = kind === "media" ? buildMediaStory(text, uploadedUrl) : markdownToStory(text);
3610
3536
  if (parsed.kind === "dm") return await sendDmWithStory({