@openclaw/tlon 2026.7.2-beta.5 → 2026.8.1-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,23 +1,25 @@
1
1
  import { n as createDedupeCache, o as createLoggerBackedRuntime } from "./runtime-api-BXVe40nS.js";
2
- import { c as normalizeUrbitHostname, d as resolveTlonAccount, f as formatTargetHint, g as resolveTlonOutboundTarget, h as parseTlonTarget, l as validateUrbitBaseUrl, m as parseChannelNest, p as normalizeShip } from "./setup-core-DUM2q1dE.js";
2
+ import { c as normalizeUrbitHostname, d as resolveTlonAccount, f as formatTargetHint, g as resolveTlonOutboundTarget, h as parseTlonTarget, l as validateUrbitBaseUrl, m as parseChannelNest, p as normalizeShip } from "./setup-core-QCmS9Gmh.js";
3
3
  import { t as getTlonRuntime } from "./runtime-Ck3lNvST.js";
4
- import { t as tlonSetupWizard } from "./setup-surface-1WtsAw4R.js";
4
+ import { t as tlonSetupWizard } from "./setup-surface-UgXzT7Tg.js";
5
5
  import { fetchWithSsrFGuard, ssrfPolicyFromDangerouslyAllowPrivateNetwork } from "openclaw/plugin-sdk/ssrf-runtime";
6
- import { bindIngressLifecycleToReplyOptions, createChannelIngressMonitor, createMessageReceiptFromOutboundResults } from "openclaw/plugin-sdk/channel-outbound";
6
+ import { bindIngressLifecycleToReplyOptions, createChannelIngressError, createChannelIngressMonitor, createMessageReceiptFromOutboundResults, waitUntilAbort } from "openclaw/plugin-sdk/channel-outbound";
7
+ import { chunkTextForOutbound } from "openclaw/plugin-sdk/text-chunking";
7
8
  import { expectDefined } from "openclaw/plugin-sdk/expect-runtime";
8
- import { asFiniteNumber, normalizeLowercaseStringOrEmpty, uniqueStrings } from "openclaw/plugin-sdk/string-coerce-runtime";
9
+ import { asFiniteNumber, asNullableRecord, filterStringEntries, normalizeLowercaseStringOrEmpty, normalizeNullableString, readStringField, uniqueStrings } from "openclaw/plugin-sdk/string-coerce-runtime";
9
10
  import crypto, { randomBytes, randomUUID } from "node:crypto";
10
11
  import { readProviderJsonResponse, readResponseTextLimited } from "openclaw/plugin-sdk/provider-http";
11
12
  import { runChannelProbe, sliceUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
12
13
  import { resolveHumanDelayConfig } from "openclaw/plugin-sdk/agent-runtime";
13
- import { createChannelInboundEnvelopeBuilder, implicitMentionKindWhen, resolveInboundMentionDecision } from "openclaw/plugin-sdk/channel-inbound";
14
+ import { createChannelInboundEnvelopeBuilder, formatAgentEnvelope, formatInboundMediaUnavailableText, implicitMentionKindWhen, resolveEnvelopeFormatOptions, resolveInboundMentionDecision } from "openclaw/plugin-sdk/channel-inbound";
15
+ import { collectErrorGraphCandidates, formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
14
16
  import { sleepWithAbort } from "openclaw/plugin-sdk/runtime-env";
15
17
  import { da, scot } from "@urbit/aura";
16
18
  import { Readable } from "node:stream";
17
19
  import { resolveTimerTimeoutMs } from "openclaw/plugin-sdk/number-runtime";
18
20
  import { resolveAllowlistMatchByCandidates } from "openclaw/plugin-sdk/allow-from";
19
21
  import { resolveChannelImplicitMentions, resolveStableChannelMessageIngress } from "openclaw/plugin-sdk/channel-ingress-runtime";
20
- import { collectErrorGraphCandidates, formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
22
+ import { isRecord } from "openclaw/plugin-sdk/channel-secret-basic-runtime";
21
23
  import { mkdir, writeFile } from "node:fs/promises";
22
24
  import * as path from "node:path";
23
25
  import { extensionForMime } from "openclaw/plugin-sdk/media-mime";
@@ -25,6 +27,16 @@ import { MAX_IMAGE_BYTES, readRemoteMediaBuffer, saveRemoteMedia } from "opencla
25
27
  import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
26
28
  import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
27
29
  //#region extensions/tlon/src/settings.ts
30
+ /**
31
+ * Settings Store integration for hot-reloading Tlon plugin config.
32
+ *
33
+ * Settings are stored in Urbit's %settings agent under:
34
+ * desk: "moltbot"
35
+ * bucket: "tlon"
36
+ *
37
+ * This allows config changes via poke from any Landscape client
38
+ * without requiring a gateway restart.
39
+ */
28
40
  const SETTINGS_DESK = "moltbot";
29
41
  const SETTINGS_BUCKET = "tlon";
30
42
  /**
@@ -51,15 +63,15 @@ function parseSettingsResponse(raw) {
51
63
  if (!bucket || typeof bucket !== "object") return {};
52
64
  const settings = bucket;
53
65
  return {
54
- groupChannels: Array.isArray(settings.groupChannels) ? settings.groupChannels.filter((x) => typeof x === "string") : void 0,
55
- dmAllowlist: Array.isArray(settings.dmAllowlist) ? settings.dmAllowlist.filter((x) => typeof x === "string") : void 0,
56
- autoDiscover: typeof settings.autoDiscover === "boolean" ? settings.autoDiscover : void 0,
66
+ groupChannels: Array.isArray(settings.groupChannels) ? filterStringEntries(settings.groupChannels) : void 0,
67
+ dmAllowlist: Array.isArray(settings.dmAllowlist) ? filterStringEntries(settings.dmAllowlist) : void 0,
68
+ autoDiscoverChannels: typeof settings.autoDiscoverChannels === "boolean" ? settings.autoDiscoverChannels : void 0,
57
69
  showModelSig: typeof settings.showModelSig === "boolean" ? settings.showModelSig : void 0,
58
70
  autoAcceptDmInvites: typeof settings.autoAcceptDmInvites === "boolean" ? settings.autoAcceptDmInvites : void 0,
59
71
  autoAcceptGroupInvites: typeof settings.autoAcceptGroupInvites === "boolean" ? settings.autoAcceptGroupInvites : void 0,
60
- groupInviteAllowlist: Array.isArray(settings.groupInviteAllowlist) ? settings.groupInviteAllowlist.filter((x) => typeof x === "string") : void 0,
72
+ groupInviteAllowlist: Array.isArray(settings.groupInviteAllowlist) ? filterStringEntries(settings.groupInviteAllowlist) : void 0,
61
73
  channelRules: parseChannelRules(settings.channelRules),
62
- defaultAuthorizedShips: Array.isArray(settings.defaultAuthorizedShips) ? settings.defaultAuthorizedShips.filter((x) => typeof x === "string") : void 0,
74
+ defaultAuthorizedShips: Array.isArray(settings.defaultAuthorizedShips) ? filterStringEntries(settings.defaultAuthorizedShips) : void 0,
63
75
  ownerShip: typeof settings.ownerShip === "string" ? settings.ownerShip : void 0,
64
76
  pendingApprovals: parsePendingApprovals(settings.pendingApprovals)
65
77
  };
@@ -119,13 +131,13 @@ function applySettingsUpdate(current, key, value) {
119
131
  const next = { ...current };
120
132
  switch (key) {
121
133
  case "groupChannels":
122
- next.groupChannels = Array.isArray(value) ? value.filter((x) => typeof x === "string") : void 0;
134
+ next.groupChannels = Array.isArray(value) ? filterStringEntries(value) : void 0;
123
135
  break;
124
136
  case "dmAllowlist":
125
- next.dmAllowlist = Array.isArray(value) ? value.filter((x) => typeof x === "string") : void 0;
137
+ next.dmAllowlist = Array.isArray(value) ? filterStringEntries(value) : void 0;
126
138
  break;
127
- case "autoDiscover":
128
- next.autoDiscover = typeof value === "boolean" ? value : void 0;
139
+ case "autoDiscoverChannels":
140
+ next.autoDiscoverChannels = typeof value === "boolean" ? value : void 0;
129
141
  break;
130
142
  case "showModelSig":
131
143
  next.showModelSig = typeof value === "boolean" ? value : void 0;
@@ -137,13 +149,13 @@ function applySettingsUpdate(current, key, value) {
137
149
  next.autoAcceptGroupInvites = typeof value === "boolean" ? value : void 0;
138
150
  break;
139
151
  case "groupInviteAllowlist":
140
- next.groupInviteAllowlist = Array.isArray(value) ? value.filter((x) => typeof x === "string") : void 0;
152
+ next.groupInviteAllowlist = Array.isArray(value) ? filterStringEntries(value) : void 0;
141
153
  break;
142
154
  case "channelRules":
143
155
  next.channelRules = parseChannelRules(value);
144
156
  break;
145
157
  case "defaultAuthorizedShips":
146
- next.defaultAuthorizedShips = Array.isArray(value) ? value.filter((x) => typeof x === "string") : void 0;
158
+ next.defaultAuthorizedShips = Array.isArray(value) ? filterStringEntries(value) : void 0;
147
159
  break;
148
160
  case "ownerShip":
149
161
  next.ownerShip = typeof value === "string" ? value : void 0;
@@ -273,7 +285,7 @@ var UrbitAuthError = class extends UrbitError {
273
285
  async function urbitFetch(params) {
274
286
  const validated = validateUrbitBaseUrl(params.baseUrl);
275
287
  if (!validated.ok) throw new UrbitUrlError(validated.error);
276
- return await fetchWithSsrFGuard({
288
+ const guarded = await fetchWithSsrFGuard({
277
289
  url: new URL(params.path, validated.baseUrl).toString(),
278
290
  fetchImpl: params.fetchImpl,
279
291
  init: params.init,
@@ -285,6 +297,13 @@ async function urbitFetch(params) {
285
297
  auditContext: params.auditContext,
286
298
  pinDns: params.pinDns
287
299
  });
300
+ return {
301
+ ...guarded,
302
+ release: async () => {
303
+ if (!guarded.response.bodyUsed) guarded.response.body?.cancel().catch(() => void 0);
304
+ await guarded.release();
305
+ }
306
+ };
288
307
  }
289
308
  //#endregion
290
309
  //#region extensions/tlon/src/urbit/auth.ts
@@ -306,10 +325,7 @@ async function authenticate(url, code, options = {}) {
306
325
  auditContext: "tlon-urbit-login"
307
326
  });
308
327
  try {
309
- if (!response.ok) {
310
- await response.body?.cancel().catch(() => void 0);
311
- throw new UrbitAuthError("auth_failed", `Login failed with status ${response.status}`);
312
- }
328
+ if (!response.ok) throw new UrbitAuthError("auth_failed", `Login failed with status ${response.status}`);
313
329
  await readResponseTextLimited(response, MAX_AUTH_BODY_DRAIN_BYTES).catch(() => void 0);
314
330
  const cookie = response.headers.get("set-cookie");
315
331
  if (!cookie) throw new UrbitAuthError("missing_cookie", "No authentication cookie received");
@@ -992,6 +1008,7 @@ var UrbitSSEClient = class {
992
1008
  this.lastHeardEventId = -1;
993
1009
  this.lastAcknowledgedEventId = -1;
994
1010
  this.ackThreshold = 20;
1011
+ this.reconnectAbortController = new AbortController();
995
1012
  const ctx = getUrbitContext(url, options.ship);
996
1013
  this.url = ctx.baseUrl;
997
1014
  this.cookie = normalizeUrbitCookie(cookie);
@@ -1268,20 +1285,14 @@ var UrbitSSEClient = class {
1268
1285
  }
1269
1286
  if (this.reconnectAttempts >= this.maxReconnectAttempts) {
1270
1287
  this.logger.log?.(`[SSE] Max reconnection attempts (${this.maxReconnectAttempts}) reached. Waiting 10s before resetting...`);
1271
- const extendedBackoff = 1e4;
1272
- await new Promise((resolve) => {
1273
- setTimeout(resolve, extendedBackoff);
1274
- });
1288
+ if (!await this.waitForReconnectDelay(1e4) || this.aborted) return;
1275
1289
  this.reconnectAttempts = 0;
1276
1290
  this.logger.log?.("[SSE] Reconnection attempts reset, resuming reconnection...");
1277
1291
  }
1278
1292
  this.reconnectAttempts += 1;
1279
1293
  const delay = Math.min(this.reconnectDelay * 2 ** (this.reconnectAttempts - 1), this.maxReconnectDelay);
1280
1294
  this.logger.log?.(`[SSE] Reconnection attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts} in ${delay}ms...`);
1281
- await new Promise((resolve) => {
1282
- setTimeout(resolve, delay);
1283
- });
1284
- if (this.aborted || !this.autoReconnect) return;
1295
+ if (!await this.waitForReconnectDelay(delay) || this.aborted || !this.autoReconnect) return;
1285
1296
  try {
1286
1297
  if (this.onReconnect) await this.onReconnect(this);
1287
1298
  try {
@@ -1303,6 +1314,7 @@ var UrbitSSEClient = class {
1303
1314
  stopReceiving() {
1304
1315
  this.aborted = true;
1305
1316
  this.isConnected = false;
1317
+ this.reconnectAbortController.abort();
1306
1318
  this.streamController?.abort();
1307
1319
  }
1308
1320
  async close() {
@@ -1314,18 +1326,14 @@ var UrbitSSEClient = class {
1314
1326
  subscription: sub.id
1315
1327
  }));
1316
1328
  {
1317
- const { response, release } = await this.putChannelPayload(unsubscribes, {
1329
+ const { release } = await this.putChannelPayload(unsubscribes, {
1318
1330
  timeoutMs: 3e4,
1319
1331
  auditContext: "tlon-urbit-unsubscribe"
1320
1332
  });
1321
- try {
1322
- response.body?.cancel().catch(() => void 0);
1323
- } finally {
1324
- await release();
1325
- }
1333
+ await release();
1326
1334
  }
1327
1335
  {
1328
- const { response, release } = await urbitFetch({
1336
+ const { release } = await urbitFetch({
1329
1337
  baseUrl: this.url,
1330
1338
  path: `/~/channel/${this.channelId}`,
1331
1339
  init: {
@@ -1338,11 +1346,7 @@ var UrbitSSEClient = class {
1338
1346
  timeoutMs: 3e4,
1339
1347
  auditContext: "tlon-urbit-channel-close"
1340
1348
  });
1341
- try {
1342
- response.body?.cancel().catch(() => void 0);
1343
- } finally {
1344
- await release();
1345
- }
1349
+ await release();
1346
1350
  }
1347
1351
  } catch (error) {
1348
1352
  this.logger.error?.(`Error closing channel: ${String(error)}`);
@@ -1353,6 +1357,15 @@ var UrbitSSEClient = class {
1353
1357
  await release();
1354
1358
  }
1355
1359
  }
1360
+ async waitForReconnectDelay(delayMs) {
1361
+ try {
1362
+ await sleepWithAbort(delayMs, this.reconnectAbortController.signal);
1363
+ return true;
1364
+ } catch (error) {
1365
+ if (this.reconnectAbortController.signal.aborted) return false;
1366
+ throw error;
1367
+ }
1368
+ }
1356
1369
  async putChannelPayload(payload, params) {
1357
1370
  return await urbitFetch({
1358
1371
  baseUrl: this.url,
@@ -1859,19 +1872,30 @@ const tlonIngressIdentity = {
1859
1872
  entryIdPrefix: "tlon-entry"
1860
1873
  };
1861
1874
  async function isDmAllowedWithIngress(senderShip, allowlist) {
1862
- return (await resolveStableChannelMessageIngress({
1863
- channelId: "tlon",
1864
- accountId: "default",
1865
- identity: tlonIngressIdentity,
1866
- subject: { stableId: senderShip },
1875
+ return (await resolveTlonMessageIngress({
1876
+ senderShip,
1877
+ allowFrom: allowlist ?? [],
1867
1878
  conversation: {
1868
1879
  kind: "direct",
1869
1880
  id: "direct"
1870
1881
  },
1871
- dmPolicy: "allowlist",
1872
- allowFrom: allowlist ?? []
1882
+ dmPolicy: "allowlist"
1873
1883
  })).senderAccess.allowed;
1874
1884
  }
1885
+ async function resolveTlonMessageIngress(params) {
1886
+ return await resolveStableChannelMessageIngress({
1887
+ channelId: "tlon",
1888
+ accountId: params.accountId ?? "default",
1889
+ identity: tlonIngressIdentity,
1890
+ subject: { stableId: params.senderShip },
1891
+ conversation: params.conversation,
1892
+ contextBinding: params.contextBinding,
1893
+ dmPolicy: params.dmPolicy ?? "allowlist",
1894
+ groupPolicy: params.groupPolicy ?? "open",
1895
+ allowFrom: params.allowFrom,
1896
+ groupAllowFrom: params.allowFrom
1897
+ });
1898
+ }
1875
1899
  async function resolveTlonCommandAuthorizationWithIngress(params) {
1876
1900
  const normalizedOwner = params.ownerShip ? normalizeShip(params.ownerShip) : null;
1877
1901
  return await resolveStableChannelMessageIngress({
@@ -1931,21 +1955,11 @@ async function resolveAuthorizedMessageText(params) {
1931
1955
  if (!authorizedForCites) return rawText;
1932
1956
  return await resolveAllCites(content) + rawText;
1933
1957
  }
1934
- const asRecord = asNullableObjectRecord;
1935
- const formatErrorMessage$1 = formatErrorMessage;
1936
- const readString = readStringField;
1937
- function asNullableObjectRecord(value) {
1938
- return value && typeof value === "object" && !Array.isArray(value) ? value : null;
1939
- }
1940
- function readStringField(record, field) {
1941
- const value = record?.[field];
1942
- return typeof value === "string" ? value : void 0;
1943
- }
1944
1958
  function renderInlineItem(item, options) {
1945
1959
  if (typeof item === "string") return item;
1946
- const record = asRecord(item);
1960
+ const record = asNullableRecord(item);
1947
1961
  if (!record) return "";
1948
- const ship = readString(record, "ship");
1962
+ const ship = readStringField(record, "ship");
1949
1963
  if (ship) return ship;
1950
1964
  if ("sect" in record) {
1951
1965
  const sect = record.sect;
@@ -1953,14 +1967,14 @@ function renderInlineItem(item, options) {
1953
1967
  if (sect === null) return "@all";
1954
1968
  }
1955
1969
  if (options?.allowBreak && "break" in record) return "\n";
1956
- const inlineCode = readString(record, "inline-code");
1970
+ const inlineCode = readStringField(record, "inline-code");
1957
1971
  if (inlineCode) return `\`${inlineCode}\``;
1958
- const code = readString(record, "code");
1972
+ const code = readStringField(record, "code");
1959
1973
  if (code) return `\`${code}\``;
1960
- const link = asRecord(record.link);
1961
- const linkHref = link ? readString(link, "href") : void 0;
1974
+ const link = asNullableRecord(record.link);
1975
+ const linkHref = link ? readStringField(link, "href") : void 0;
1962
1976
  if (link && linkHref) {
1963
- const linkContent = readString(link, "content");
1977
+ const linkContent = readStringField(link, "content");
1964
1978
  return options?.linkMode === "href" ? linkHref : linkContent || linkHref;
1965
1979
  }
1966
1980
  if (Array.isArray(record.bold)) return `**${extractInlineText(record.bold)}**`;
@@ -1975,50 +1989,50 @@ function extractInlineText(items) {
1975
1989
  function extractMessageText(content) {
1976
1990
  if (!content || !Array.isArray(content)) return "";
1977
1991
  return content.map((verse) => {
1978
- const verseRecord = asRecord(verse);
1992
+ const verseRecord = asNullableRecord(verse);
1979
1993
  if (!verseRecord) return "";
1980
1994
  if (Array.isArray(verseRecord.inline)) return verseRecord.inline.map((item) => renderInlineItem(item, {
1981
1995
  linkMode: "href",
1982
1996
  allowBreak: true,
1983
1997
  allowBlockquote: true
1984
1998
  })).join("");
1985
- const block = asRecord(verseRecord.block);
1999
+ const block = asNullableRecord(verseRecord.block);
1986
2000
  if (block) {
1987
- const image = asRecord(block.image);
2001
+ const image = asNullableRecord(block.image);
1988
2002
  if (image) {
1989
- const imageSrc = readString(image, "src");
2003
+ const imageSrc = readStringField(image, "src");
1990
2004
  if (imageSrc) {
1991
- const altText = readString(image, "alt");
2005
+ const altText = readStringField(image, "alt");
1992
2006
  return `\n${imageSrc}${altText ? ` (${altText})` : ""}\n`;
1993
2007
  }
1994
2008
  }
1995
- const codeBlock = asRecord(block.code);
1996
- if (codeBlock) return `\n\`\`\`${readString(codeBlock, "lang") ?? ""}\n${readString(codeBlock, "code") ?? ""}\n\`\`\`\n`;
1997
- const header = asRecord(block.header);
2009
+ const codeBlock = asNullableRecord(block.code);
2010
+ if (codeBlock) return `\n\`\`\`${readStringField(codeBlock, "lang") ?? ""}\n${readStringField(codeBlock, "code") ?? ""}\n\`\`\`\n`;
2011
+ const header = asNullableRecord(block.header);
1998
2012
  if (header) return `\n## ${(Array.isArray(header.content) ? header.content : []).map((item) => typeof item === "string" ? item : "").join("") || ""}\n`;
1999
- const cite = asRecord(block.cite);
2013
+ const cite = asNullableRecord(block.cite);
2000
2014
  if (cite) {
2001
- const chanCite = asRecord(cite.chan);
2015
+ const chanCite = asNullableRecord(cite.chan);
2002
2016
  if (chanCite) {
2003
- const nest = readString(chanCite, "nest");
2004
- const whereMatch = readString(chanCite, "where")?.match(/\/msg\/(~[a-z-]+)\/(.+)/);
2017
+ const nest = readStringField(chanCite, "nest");
2018
+ const whereMatch = readStringField(chanCite, "where")?.match(/\/msg\/(~[a-z-]+)\/(.+)/);
2005
2019
  if (whereMatch) {
2006
2020
  const [, author, _postId] = whereMatch;
2007
2021
  return `\n> [quoted: ${author} in ${nest}]\n`;
2008
2022
  }
2009
2023
  return `\n> [quoted from ${nest}]\n`;
2010
2024
  }
2011
- const group = readString(cite, "group");
2025
+ const group = readStringField(cite, "group");
2012
2026
  if (group) return `\n> [ref: group ${group}]\n`;
2013
- const desk = asRecord(cite.desk);
2027
+ const desk = asNullableRecord(cite.desk);
2014
2028
  if (desk) {
2015
- const flag = readString(desk, "flag");
2029
+ const flag = readStringField(desk, "flag");
2016
2030
  if (flag) return `\n> [ref: ${flag}]\n`;
2017
2031
  }
2018
- const bait = asRecord(cite.bait);
2032
+ const bait = asNullableRecord(cite.bait);
2019
2033
  if (bait) {
2020
- const graph = readString(bait, "graph");
2021
- const groupName = readString(bait, "group");
2034
+ const graph = readStringField(bait, "graph");
2035
+ const groupName = readStringField(bait, "group");
2022
2036
  if (graph && groupName) return `\n> [ref: ${graph} in ${groupName}]\n`;
2023
2037
  }
2024
2038
  return `\n> [quoted message]\n`;
@@ -2036,6 +2050,21 @@ function isSummarizationRequest(messageText) {
2036
2050
  /tldr/i
2037
2051
  ].some((pattern) => pattern.test(messageText));
2038
2052
  }
2053
+ /**
2054
+ * Formats channel history for a summarization request. Each entry is rendered
2055
+ * through the shared inbound envelope so timestamps honor the configured user
2056
+ * timezone instead of the host process zone (matches Mattermost/Feishu).
2057
+ */
2058
+ function formatSummarizationHistoryText(history, cfg) {
2059
+ const envelopeOptions = resolveEnvelopeFormatOptions(cfg);
2060
+ return history.map((msg) => formatAgentEnvelope({
2061
+ channel: "Tlon",
2062
+ from: msg.author,
2063
+ timestamp: msg.timestamp,
2064
+ body: msg.content,
2065
+ envelope: envelopeOptions
2066
+ })).join("\n");
2067
+ }
2039
2068
  //#endregion
2040
2069
  //#region extensions/tlon/src/monitor/cites.ts
2041
2070
  function createTlonCitationResolver(params) {
@@ -2045,7 +2074,7 @@ function createTlonCitationResolver(params) {
2045
2074
  try {
2046
2075
  const scryPath = `/channels/v4/${cite.nest}/posts/post/${cite.postId}.json`;
2047
2076
  runtime.log?.(`[tlon] Fetching cited post: ${scryPath}`);
2048
- const essay = asRecord(asRecord(await api.scry(scryPath))?.essay);
2077
+ const essay = asNullableRecord(asNullableRecord(await api.scry(scryPath))?.essay);
2049
2078
  if (essay?.content) return extractMessageText(essay.content) || null;
2050
2079
  return null;
2051
2080
  } catch (err) {
@@ -2077,18 +2106,18 @@ function createTlonCitationResolver(params) {
2077
2106
  async function fetchInitData(api, runtime) {
2078
2107
  try {
2079
2108
  runtime.log?.("[tlon] Fetching groups-ui init data...");
2080
- const initData = asRecord(await api.scry("/groups-ui/v6/init.json"));
2109
+ const initData = asNullableRecord(await api.scry("/groups-ui/v6/init.json"));
2081
2110
  const channels = [];
2082
- const groups = asRecord(initData?.groups);
2111
+ const groups = asNullableRecord(initData?.groups);
2083
2112
  if (groups) for (const groupData of Object.values(groups)) {
2084
- const groupChannels = asRecord(asRecord(groupData)?.channels);
2113
+ const groupChannels = asNullableRecord(asNullableRecord(groupData)?.channels);
2085
2114
  if (groupChannels) {
2086
2115
  for (const channelNest of Object.keys(groupChannels)) if (channelNest.startsWith("chat/")) channels.push(channelNest);
2087
2116
  }
2088
2117
  }
2089
2118
  if (channels.length > 0) runtime.log?.(`[tlon] Auto-discovered ${channels.length} chat channel(s)`);
2090
2119
  else runtime.log?.("[tlon] No chat channels found via auto-discovery");
2091
- const foreignsValue = asRecord(initData?.foreigns);
2120
+ const foreignsValue = asNullableRecord(initData?.foreigns);
2092
2121
  const foreigns = foreignsValue ? foreignsValue : null;
2093
2122
  if (foreigns) {
2094
2123
  const pendingCount = Object.values(foreigns).filter((f) => f.invites?.some((i) => i.valid)).length;
@@ -2099,7 +2128,7 @@ async function fetchInitData(api, runtime) {
2099
2128
  foreigns
2100
2129
  };
2101
2130
  } catch (error) {
2102
- runtime.log?.(`[tlon] Init data fetch failed: ${formatErrorMessage$1(error)}`);
2131
+ runtime.log?.(`[tlon] Init data fetch failed: ${formatErrorMessage(error)}`);
2103
2132
  return {
2104
2133
  channels: [],
2105
2134
  foreigns: null
@@ -2149,16 +2178,16 @@ async function fetchChannelHistory(api, channelNest, count = 50, runtime) {
2149
2178
  let posts = [];
2150
2179
  if (Array.isArray(data)) posts = data;
2151
2180
  else {
2152
- const dataRecord = asRecord(data);
2153
- const postMap = asRecord(dataRecord?.posts);
2181
+ const dataRecord = asNullableRecord(data);
2182
+ const postMap = asNullableRecord(dataRecord?.posts);
2154
2183
  if (postMap) posts = Object.values(postMap);
2155
2184
  else if (dataRecord) posts = Object.values(dataRecord);
2156
2185
  }
2157
2186
  const messages = posts.map((item) => {
2158
- const itemRecord = asRecord(item);
2159
- const replyPostSet = asRecord(asRecord(itemRecord?.["r-post"])?.set);
2160
- const essay = asRecord(itemRecord?.essay) ?? asRecord(replyPostSet?.essay);
2161
- const seal = asRecord(itemRecord?.seal) ?? asRecord(replyPostSet?.seal);
2187
+ const itemRecord = asNullableRecord(item);
2188
+ const replyPostSet = asNullableRecord(asNullableRecord(itemRecord?.["r-post"])?.set);
2189
+ const essay = asNullableRecord(itemRecord?.essay) ?? asNullableRecord(replyPostSet?.essay);
2190
+ const seal = asNullableRecord(itemRecord?.seal) ?? asNullableRecord(replyPostSet?.seal);
2162
2191
  return {
2163
2192
  author: typeof essay?.author === "string" ? essay.author : "unknown",
2164
2193
  content: extractMessageText(essay?.content || []),
@@ -2169,7 +2198,7 @@ async function fetchChannelHistory(api, channelNest, count = 50, runtime) {
2169
2198
  runtime?.log?.(`[tlon] Extracted ${messages.length} messages from history`);
2170
2199
  return messages;
2171
2200
  } catch (error) {
2172
- runtime?.log?.(`[tlon] Error fetching channel history: ${formatErrorMessage$1(error)}`);
2201
+ runtime?.log?.(`[tlon] Error fetching channel history: ${formatErrorMessage(error)}`);
2173
2202
  return [];
2174
2203
  }
2175
2204
  }
@@ -2200,44 +2229,44 @@ async function fetchThreadHistory(api, channelNest, parentId, count = 50, runtim
2200
2229
  let replies = [];
2201
2230
  if (Array.isArray(data)) replies = data;
2202
2231
  else {
2203
- const dataRecord = asRecord(data);
2232
+ const dataRecord = asNullableRecord(data);
2204
2233
  const replyValue = dataRecord?.replies;
2205
2234
  if (Array.isArray(replyValue)) replies = replyValue;
2206
2235
  else if (typeof replyValue === "object" && replyValue) replies = Object.values(replyValue);
2207
2236
  else if (dataRecord) replies = Object.values(dataRecord);
2208
2237
  }
2209
2238
  const messages = replies.map((item) => {
2210
- const itemRecord = asRecord(item);
2211
- const replySet = asRecord(asRecord(itemRecord?.["r-reply"])?.set);
2239
+ const itemRecord = asNullableRecord(item);
2240
+ const replySet = asNullableRecord(asNullableRecord(itemRecord?.["r-reply"])?.set);
2212
2241
  return createHistoryEntryFromMemo({
2213
- memo: asRecord(itemRecord?.memo) ?? asRecord(replySet?.memo) ?? itemRecord,
2214
- seal: asRecord(itemRecord?.seal) ?? asRecord(replySet?.seal),
2242
+ memo: asNullableRecord(itemRecord?.memo) ?? asNullableRecord(replySet?.memo) ?? itemRecord,
2243
+ seal: asNullableRecord(itemRecord?.seal) ?? asNullableRecord(replySet?.seal),
2215
2244
  fallbackId: itemRecord?.id
2216
2245
  });
2217
2246
  }).filter((msg) => msg.content);
2218
2247
  runtime?.log?.(`[tlon] Extracted ${messages.length} thread replies from history`);
2219
2248
  return messages;
2220
2249
  } catch (error) {
2221
- runtime?.log?.(`[tlon] Error fetching thread history: ${formatErrorMessage$1(error)}`);
2250
+ runtime?.log?.(`[tlon] Error fetching thread history: ${formatErrorMessage(error)}`);
2222
2251
  try {
2223
2252
  const altPath = `/channels/v4/${channelNest}/posts/post/id/${formatUd(parentId)}.json`;
2224
2253
  runtime?.log?.(`[tlon] Trying alternate path: ${altPath}`);
2225
- const data = asRecord(await api.scry(altPath));
2226
- const dataMeta = asRecord(asRecord(data?.seal)?.meta);
2254
+ const data = asNullableRecord(await api.scry(altPath));
2255
+ const dataMeta = asNullableRecord(asNullableRecord(data?.seal)?.meta);
2227
2256
  const repliesValue = data?.replies;
2228
2257
  if (typeof dataMeta?.replyCount === "number" && dataMeta.replyCount > 0 && repliesValue) {
2229
2258
  const messages = (Array.isArray(repliesValue) ? repliesValue : Object.values(repliesValue)).map((reply) => {
2230
- const replyRecord = asRecord(reply);
2259
+ const replyRecord = asNullableRecord(reply);
2231
2260
  return createHistoryEntryFromMemo({
2232
- memo: asRecord(replyRecord?.memo),
2233
- seal: asRecord(replyRecord?.seal)
2261
+ memo: asNullableRecord(replyRecord?.memo),
2262
+ seal: asNullableRecord(replyRecord?.seal)
2234
2263
  });
2235
2264
  }).filter((msg) => msg.content);
2236
2265
  runtime?.log?.(`[tlon] Extracted ${messages.length} replies from post data`);
2237
2266
  return messages;
2238
2267
  }
2239
2268
  } catch (altError) {
2240
- runtime?.log?.(`[tlon] Alternate path also failed: ${formatErrorMessage$1(altError)}`);
2269
+ runtime?.log?.(`[tlon] Alternate path also failed: ${formatErrorMessage(altError)}`);
2241
2270
  }
2242
2271
  return [];
2243
2272
  }
@@ -2246,31 +2275,10 @@ async function fetchThreadHistory(api, channelNest, parentId, count = 50, runtim
2246
2275
  //#region extensions/tlon/src/monitor/ingress.ts
2247
2276
  const TLON_INGRESS_PAYLOAD_VERSION = 1;
2248
2277
  const TLON_INGRESS_POLL_INTERVAL_MS = 1e3;
2249
- const TLON_INGRESS_PRUNE_INTERVAL_MS = 3600 * 1e3;
2250
- const TLON_INGRESS_FAILED_TTL_MS = 720 * 60 * 60 * 1e3;
2251
- const TLON_INGRESS_TOMBSTONE_MAX_ENTRIES = 2e3;
2252
- var TlonIngressPermanentError = class extends Error {
2253
- constructor(reason, message, options) {
2254
- super(message, options);
2255
- this.reason = reason;
2256
- this.name = "TlonIngressPermanentError";
2257
- }
2258
- };
2259
- var TlonIngressShutdownError = class extends Error {
2260
- constructor() {
2261
- super("Tlon ingress stopped before dispatch adoption.");
2262
- this.name = "TlonIngressShutdownError";
2263
- }
2264
- };
2265
- function isRecord(value) {
2266
- return typeof value === "object" && value !== null && !Array.isArray(value);
2267
- }
2268
- function nonEmptyString(value) {
2269
- return typeof value === "string" && value.trim() ? value.trim() : null;
2270
- }
2278
+ const TlonIngressPermanentError = createChannelIngressError("TlonIngressPermanentError", { withReason: true });
2271
2279
  function inspectChannelsEvent(event) {
2272
2280
  const envelope = isRecord(event) ? event : null;
2273
- const nest = nonEmptyString(envelope?.nest);
2281
+ const nest = normalizeNullableString(envelope?.nest);
2274
2282
  const response = isRecord(envelope?.response) ? envelope.response : null;
2275
2283
  const post = isRecord(response?.post) ? response.post : null;
2276
2284
  const rPost = isRecord(post?.["r-post"]) ? post["r-post"] : null;
@@ -2279,7 +2287,7 @@ function inspectChannelsEvent(event) {
2279
2287
  const rReply = isRecord(reply?.["r-reply"]) ? reply["r-reply"] : null;
2280
2288
  const replySet = isRecord(rReply?.set) ? rReply.set : null;
2281
2289
  if (!nest || !isRecord(set?.essay) && !isRecord(replySet?.memo)) return null;
2282
- const eventId = nonEmptyString(isRecord(replySet?.memo) ? reply?.id : post?.id);
2290
+ const eventId = normalizeNullableString(isRecord(replySet?.memo) ? reply?.id : post?.id);
2283
2291
  return eventId ? {
2284
2292
  eventId,
2285
2293
  laneKey: `group:${nest}`
@@ -2290,10 +2298,10 @@ function inspectChatEvent(event) {
2290
2298
  const response = isRecord(envelope?.response) ? envelope.response : null;
2291
2299
  const add = isRecord(response?.add) ? response.add : null;
2292
2300
  const essay = isRecord(add?.essay) ? add.essay : null;
2293
- const eventId = nonEmptyString(envelope?.id);
2301
+ const eventId = normalizeNullableString(envelope?.id);
2294
2302
  if (!essay || !eventId) return null;
2295
- const whom = isRecord(envelope?.whom) ? nonEmptyString(envelope.whom.ship) : null;
2296
- const peer = nonEmptyString(envelope?.whom) ?? whom ?? nonEmptyString(essay.author);
2303
+ const whom = isRecord(envelope?.whom) ? normalizeNullableString(envelope.whom.ship) : null;
2304
+ const peer = normalizeNullableString(envelope?.whom) ?? whom ?? normalizeNullableString(essay.author);
2297
2305
  return {
2298
2306
  eventId,
2299
2307
  laneKey: peer ? `direct:${peer}` : `event:${eventId}`
@@ -2358,10 +2366,9 @@ function createTlonIngressMonitor(options) {
2358
2366
  deliver: (raw, lifecycle) => options.dispatch(raw.source, raw.event, lifecycle),
2359
2367
  pollIntervalMs: options.pollIntervalMs ?? TLON_INGRESS_POLL_INTERVAL_MS,
2360
2368
  retention: {
2361
- pruneIntervalMs: TLON_INGRESS_PRUNE_INTERVAL_MS,
2362
- completedMaxEntries: TLON_INGRESS_TOMBSTONE_MAX_ENTRIES,
2363
- failedTtlMs: TLON_INGRESS_FAILED_TTL_MS,
2364
- failedMaxEntries: TLON_INGRESS_TOMBSTONE_MAX_ENTRIES
2369
+ completedTtlMs: void 0,
2370
+ completedMaxEntries: 2e3,
2371
+ failedMaxEntries: 2e3
2365
2372
  },
2366
2373
  appendRetryDelaysMs: [0],
2367
2374
  drain: {
@@ -2370,7 +2377,7 @@ function createTlonIngressMonitor(options) {
2370
2377
  onLog: (message) => options.runtime.log?.(`tlon ${message}`)
2371
2378
  },
2372
2379
  ...options.abortSignal ? { abortSignal: options.abortSignal } : {},
2373
- createStoppedError: () => new TlonIngressShutdownError(),
2380
+ createStoppedError: () => /* @__PURE__ */ new Error("Tlon ingress stopped before dispatch adoption."),
2374
2381
  onError: (error) => options.runtime.error?.(`tlon ingress drain failed: ${formatErrorMessage(error)}`)
2375
2382
  });
2376
2383
  return {
@@ -2408,19 +2415,26 @@ function buildTlonInboundMediaPrompt(messageText, attachments) {
2408
2415
  }
2409
2416
  /**
2410
2417
  * Extract image blocks from Tlon message content.
2411
- * Returns array of image URLs found in the message.
2418
+ * Returns up to the download cap plus the number omitted by that cap.
2412
2419
  */
2413
2420
  function extractImageBlocks(content) {
2414
- if (!content || !Array.isArray(content)) return [];
2421
+ if (!content || !Array.isArray(content)) return {
2422
+ images: [],
2423
+ unavailableCount: 0
2424
+ };
2415
2425
  const images = [];
2426
+ let unavailableCount = 0;
2416
2427
  for (const verse of content) if (verse?.block?.image?.src) {
2417
- images.push({
2418
- url: verse.block.image.src,
2419
- alt: verse.block.image.alt
2420
- });
2421
- if (images.length >= MAX_IMAGES_PER_MESSAGE) break;
2428
+ if (images.length >= MAX_IMAGES_PER_MESSAGE) {
2429
+ unavailableCount++;
2430
+ continue;
2431
+ }
2432
+ images.push({ url: verse.block.image.src });
2422
2433
  }
2423
- return images;
2434
+ return {
2435
+ images,
2436
+ unavailableCount
2437
+ };
2424
2438
  }
2425
2439
  /**
2426
2440
  * Download a media file from URL to local storage.
@@ -2444,8 +2458,7 @@ async function downloadMedia(url, mediaDir) {
2444
2458
  const saved = await saveRemoteMedia(fetchOptions);
2445
2459
  return {
2446
2460
  localPath: saved.path,
2447
- contentType: saved.contentType ?? "application/octet-stream",
2448
- originalUrl: url
2461
+ contentType: saved.contentType ?? "application/octet-stream"
2449
2462
  };
2450
2463
  }
2451
2464
  const fetched = await readRemoteMediaBuffer(fetchOptions);
@@ -2455,8 +2468,7 @@ async function downloadMedia(url, mediaDir) {
2455
2468
  await writeFile(localPath, fetched.buffer);
2456
2469
  return {
2457
2470
  localPath,
2458
- contentType: fetched.contentType ?? "application/octet-stream",
2459
- originalUrl: url
2471
+ contentType: fetched.contentType ?? "application/octet-stream"
2460
2472
  };
2461
2473
  } catch (error) {
2462
2474
  console.error(`[tlon-media] Error downloading ${url}: ${formatErrorMessage(error)}`);
@@ -2483,17 +2495,21 @@ function getExtensionFromUrl(url) {
2483
2495
  * Format matches OpenClaw's expected attachment structure.
2484
2496
  */
2485
2497
  async function downloadMessageImages(content, mediaDir) {
2486
- const images = extractImageBlocks(content);
2487
- if (images.length === 0) return [];
2498
+ const { images, unavailableCount: overCapCount } = extractImageBlocks(content);
2488
2499
  const attachments = [];
2500
+ let unavailableCount = overCapCount;
2489
2501
  for (const image of images) {
2490
2502
  const downloaded = await downloadMedia(image.url, mediaDir);
2491
2503
  if (downloaded) attachments.push({
2492
2504
  path: downloaded.localPath,
2493
2505
  contentType: downloaded.contentType
2494
2506
  });
2507
+ else unavailableCount++;
2495
2508
  }
2496
- return attachments;
2509
+ return {
2510
+ attachments,
2511
+ unavailableCount
2512
+ };
2497
2513
  }
2498
2514
  //#endregion
2499
2515
  //#region extensions/tlon/src/monitor/settings-helpers.ts
@@ -2631,9 +2647,6 @@ function createActiveSnapshotTracker() {
2631
2647
  }
2632
2648
  //#endregion
2633
2649
  //#region extensions/tlon/src/monitor/index.ts
2634
- function readNumber(record, key) {
2635
- return asFiniteNumber(record?.[key]);
2636
- }
2637
2650
  async function monitorTlonProvider(opts = {}) {
2638
2651
  const core = getTlonRuntime();
2639
2652
  const cfg = core.config.current();
@@ -2655,7 +2668,7 @@ async function monitorTlonProvider(opts = {}) {
2655
2668
  runtime.log?.(`[tlon] Attempting authentication to ${accountUrl}...`);
2656
2669
  return await authenticate(accountUrl, accountCode, { ssrfPolicy });
2657
2670
  } catch (error) {
2658
- runtime.error?.(`[tlon] Failed to authenticate (attempt ${attempt}): ${formatErrorMessage$1(error)}`);
2671
+ runtime.error?.(`[tlon] Failed to authenticate (attempt ${attempt}): ${formatErrorMessage(error)}`);
2659
2672
  if (attempt >= maxAttempts) throw error;
2660
2673
  const delay = Math.min(3e4, 1e3 * 2 ** (attempt - 1));
2661
2674
  runtime.log?.(`[tlon] Retrying authentication in ${delay}ms...`);
@@ -2705,7 +2718,7 @@ async function monitorTlonProvider(opts = {}) {
2705
2718
  if (botNickname) runtime.log?.(`[tlon] Bot nickname: ${botNickname}`);
2706
2719
  }
2707
2720
  } catch (error) {
2708
- runtime.log?.(`[tlon] Could not fetch nickname: ${formatErrorMessage$1(error)}`);
2721
+ runtime.log?.(`[tlon] Could not fetch nickname: ${formatErrorMessage(error)}`);
2709
2722
  }
2710
2723
  let initForeigns = null;
2711
2724
  async function migrateConfigToSettings() {
@@ -2742,7 +2755,7 @@ async function monitorTlonProvider(opts = {}) {
2742
2755
  if (initData.channels.length > 0) groupChannels = initData.channels;
2743
2756
  initForeigns = initData.foreigns;
2744
2757
  } catch (error) {
2745
- runtime.error?.(`[tlon] Auto-discovery failed: ${formatErrorMessage$1(error)}`);
2758
+ runtime.error?.(`[tlon] Auto-discovery failed: ${formatErrorMessage(error)}`);
2746
2759
  }
2747
2760
  if (account.groupChannels.length > 0) {
2748
2761
  groupChannels = mergeUniqueStrings(groupChannels, account.groupChannels);
@@ -2765,15 +2778,16 @@ async function monitorTlonProvider(opts = {}) {
2765
2778
  return /^~?[a-z-]+$/i.test(normalized) ? normalized : "";
2766
2779
  }
2767
2780
  const processMessage = async (params) => {
2768
- const { messageId, senderShip, isGroup, channelNest, hostShip: _hostShip, channelName: _channelName, timestamp, parentId, isThreadReply, messageContent, turnAdoptionLifecycle } = params;
2781
+ const { messageId, senderShip, isGroup, channelNest, hostShip: _hostShip, channelName: _channelName, timestamp, parentId, isThreadReply, messageContent, turnAdoptionLifecycle, resolveChannelIngress } = params;
2769
2782
  const groupChannel = channelNest;
2770
2783
  let messageText = params.messageText;
2771
2784
  let attachments = [];
2785
+ let unavailableMediaCount = 0;
2772
2786
  if (messageContent) try {
2773
- attachments = await downloadMessageImages(messageContent);
2787
+ ({attachments, unavailableCount: unavailableMediaCount} = await downloadMessageImages(messageContent));
2774
2788
  if (attachments.length > 0) runtime.log?.(`[tlon] Downloaded ${attachments.length} image(s) from message`);
2775
2789
  } catch (error) {
2776
- runtime.log?.(`[tlon] Failed to download images: ${formatErrorMessage$1(error)}`);
2790
+ runtime.log?.(`[tlon] Failed to download images: ${formatErrorMessage(error)}`);
2777
2791
  }
2778
2792
  if (isThreadReply && parentId && groupChannel) try {
2779
2793
  const threadHistory = await fetchThreadHistory(api, groupChannel, parentId, 20, runtime);
@@ -2783,7 +2797,7 @@ async function monitorTlonProvider(opts = {}) {
2783
2797
  runtime?.log?.(`[tlon] Added thread context (${threadHistory.length} replies) to message`);
2784
2798
  }
2785
2799
  } catch (error) {
2786
- runtime?.log?.(`[tlon] Could not fetch thread context: ${formatErrorMessage$1(error)}`);
2800
+ runtime?.log?.(`[tlon] Could not fetch thread context: ${formatErrorMessage(error)}`);
2787
2801
  }
2788
2802
  if (isGroup && groupChannel && isSummarizationRequest(messageText)) try {
2789
2803
  const history = await getChannelHistory(api, groupChannel, 50, runtime);
@@ -2806,14 +2820,14 @@ async function monitorTlonProvider(opts = {}) {
2806
2820
  });
2807
2821
  return;
2808
2822
  }
2809
- const historyText = history.map((msg) => `[${new Date(msg.timestamp).toLocaleString()}] ${msg.author}: ${msg.content}`).join("\n");
2823
+ const historyText = formatSummarizationHistoryText(history, cfg);
2810
2824
  messageText = `Please summarize this channel conversation (${history.length} recent messages):\n\n${historyText}\n\nProvide a concise summary highlighting:
2811
2825
  1. Main topics discussed
2812
2826
  2. Key decisions or conclusions
2813
2827
  3. Action items if any
2814
2828
  4. Notable participants`;
2815
2829
  } catch (error) {
2816
- const errorMsg = `Sorry, I encountered an error while fetching the channel history: ${formatErrorMessage$1(error)}`;
2830
+ const errorMsg = `Sorry, I encountered an error while fetching the channel history: ${formatErrorMessage(error)}`;
2817
2831
  if (isGroup && groupChannel) {
2818
2832
  const parsed = parseChannelNest(groupChannel);
2819
2833
  if (parsed) await sendGroupMessage({
@@ -2840,6 +2854,16 @@ async function monitorTlonProvider(opts = {}) {
2840
2854
  id: isGroup ? groupChannel ?? senderShip : senderShip
2841
2855
  }
2842
2856
  });
2857
+ const channelIngress = await resolveChannelIngress({
2858
+ agentId: route.agentId,
2859
+ sessionKey: route.sessionKey,
2860
+ messageId,
2861
+ inboundEventKind: "user_request"
2862
+ });
2863
+ if (!channelIngress.senderAccess.allowed) {
2864
+ runtime.log?.(`[tlon] Authorization changed before dispatch for ${senderShip}`);
2865
+ return;
2866
+ }
2843
2867
  if (!isGroup) {
2844
2868
  const sessionKey = route.sessionKey;
2845
2869
  if (!dmSendersBySession.has(sessionKey)) dmSendersBySession.set(sessionKey, /* @__PURE__ */ new Set());
@@ -2853,7 +2877,7 @@ async function monitorTlonProvider(opts = {}) {
2853
2877
  fromShip: botShipName,
2854
2878
  toShip: effectiveOwnerShip,
2855
2879
  text: "⚠️ Security Warning: Multiple users are sharing a DM session with this bot. This can leak conversation context between users.\n\nFix: Add to your OpenClaw config:\nsession:\n dmScope: \"per-channel-peer\"\n\nDocs: https://docs.openclaw.ai/concepts/session#secure-dm-mode"
2856
- }).catch((err) => runtime.error?.(`[tlon] Failed to send security warning to owner: ${formatErrorMessage$1(err)}`));
2880
+ }).catch((err) => runtime.error?.(`[tlon] Failed to send security warning to owner: ${formatErrorMessage(err)}`));
2857
2881
  }
2858
2882
  }
2859
2883
  senders.add(senderShip);
@@ -2881,6 +2905,10 @@ async function monitorTlonProvider(opts = {}) {
2881
2905
  body: promptMedia.body
2882
2906
  });
2883
2907
  const commandBody = isGroup ? stripBotMention(messageText, botShipName) : messageText;
2908
+ const bodyForAgent = unavailableMediaCount > 0 ? formatInboundMediaUnavailableText({
2909
+ body: commandBody,
2910
+ notice: `[tlon ${unavailableMediaCount > 1 ? `${unavailableMediaCount} attachments` : "attachment"} unavailable]`
2911
+ }) : commandBody;
2884
2912
  const tlonConversationId = isGroup ? groupChannel ?? channelNest ?? senderShip : senderShip;
2885
2913
  const ctxPayload = core.channel.inbound.buildContext({
2886
2914
  channel: "tlon",
@@ -2911,10 +2939,11 @@ async function monitorTlonProvider(opts = {}) {
2911
2939
  },
2912
2940
  message: {
2913
2941
  body,
2914
- bodyForAgent: commandBody,
2942
+ bodyForAgent,
2915
2943
  rawBody: messageText,
2916
2944
  commandBody
2917
2945
  },
2946
+ channelIngress,
2918
2947
  extra: {
2919
2948
  GroupSubject: void 0,
2920
2949
  SenderRole: senderRole,
@@ -3054,7 +3083,18 @@ async function monitorTlonProvider(opts = {}) {
3054
3083
  messageText: approval.originalMessage.messageText,
3055
3084
  messageContent: approval.originalMessage.messageContent,
3056
3085
  isGroup: false,
3057
- timestamp: approval.originalMessage.timestamp
3086
+ timestamp: approval.originalMessage.timestamp,
3087
+ resolveChannelIngress: async (contextBinding) => await resolveTlonMessageIngress({
3088
+ senderShip: approval.requestingShip,
3089
+ accountId: account.accountId,
3090
+ conversation: {
3091
+ kind: "direct",
3092
+ id: approval.requestingShip
3093
+ },
3094
+ allowFrom: [approval.requestingShip],
3095
+ dmPolicy: "allowlist",
3096
+ contextBinding
3097
+ })
3058
3098
  });
3059
3099
  return;
3060
3100
  }
@@ -3071,7 +3111,18 @@ async function monitorTlonProvider(opts = {}) {
3071
3111
  channelName: parsedChannel?.channelName,
3072
3112
  timestamp: approval.originalMessage.timestamp,
3073
3113
  parentId: approval.originalMessage.parentId,
3074
- isThreadReply: approval.originalMessage.isThreadReply
3114
+ isThreadReply: approval.originalMessage.isThreadReply,
3115
+ resolveChannelIngress: async (contextBinding) => await resolveTlonMessageIngress({
3116
+ senderShip: approval.requestingShip,
3117
+ accountId: account.accountId,
3118
+ conversation: {
3119
+ kind: "group",
3120
+ id: approval.channelNest
3121
+ },
3122
+ allowFrom: [approval.requestingShip],
3123
+ groupPolicy: "allowlist",
3124
+ contextBinding
3125
+ })
3075
3126
  });
3076
3127
  }
3077
3128
  },
@@ -3079,39 +3130,39 @@ async function monitorTlonProvider(opts = {}) {
3079
3130
  });
3080
3131
  const handleChannelsFirehose = async (event, turnAdoptionLifecycle) => {
3081
3132
  try {
3082
- const eventRecord = asRecord(event);
3083
- const nest = readString(eventRecord, "nest");
3133
+ const eventRecord = asNullableRecord(event);
3134
+ const nest = readStringField(eventRecord, "nest");
3084
3135
  if (!nest) return;
3085
3136
  if (!watchedChannels.has(nest)) return;
3086
- const response = asRecord(eventRecord?.response);
3137
+ const response = asNullableRecord(eventRecord?.response);
3087
3138
  if (!response) return;
3088
- const post = asRecord(response.post);
3089
- const rPost = asRecord(post?.["r-post"]);
3090
- const set = asRecord(rPost?.set);
3091
- const reply = asRecord(rPost?.reply);
3092
- const replySet = asRecord(asRecord(reply?.["r-reply"])?.set);
3093
- const essay = asRecord(set?.essay);
3094
- const memo = asRecord(replySet?.memo);
3139
+ const post = asNullableRecord(response.post);
3140
+ const rPost = asNullableRecord(post?.["r-post"]);
3141
+ const set = asNullableRecord(rPost?.set);
3142
+ const reply = asNullableRecord(rPost?.reply);
3143
+ const replySet = asNullableRecord(asNullableRecord(reply?.["r-reply"])?.set);
3144
+ const essay = asNullableRecord(set?.essay);
3145
+ const memo = asNullableRecord(replySet?.memo);
3095
3146
  if (!essay && !memo) return;
3096
3147
  const content = memo ?? essay;
3097
3148
  if (!content) return;
3098
3149
  const isThreadReply = Boolean(memo);
3099
- const messageId = isThreadReply ? readString(reply, "id") : readString(post, "id");
3150
+ const messageId = isThreadReply ? readStringField(reply, "id") : readStringField(post, "id");
3100
3151
  if (!messageId) return;
3101
- const senderShip = normalizeShip(readString(content, "author") ?? "");
3152
+ const senderShip = normalizeShip(readStringField(content, "author") ?? "");
3102
3153
  if (!senderShip || senderShip === botShipName) return;
3103
3154
  const rawText = extractMessageText(content.content);
3104
3155
  if (!rawText.trim()) return;
3105
3156
  const contentBody = content.content;
3106
- const sentAt = readNumber(content, "sent") ?? Date.now();
3157
+ const sentAt = asFiniteNumber(content?.sent) ?? Date.now();
3107
3158
  cacheMessage(nest, {
3108
3159
  author: senderShip,
3109
3160
  content: rawText,
3110
3161
  timestamp: sentAt,
3111
3162
  id: messageId
3112
3163
  });
3113
- const seal = isThreadReply ? asRecord(replySet?.seal) : asRecord(set?.seal);
3114
- const parentId = readString(seal, "parent-id") ?? readString(seal, "parent") ?? null;
3164
+ const seal = isThreadReply ? asNullableRecord(replySet?.seal) : asNullableRecord(set?.seal);
3165
+ const parentId = readStringField(seal, "parent-id") ?? readStringField(seal, "parent") ?? null;
3115
3166
  const mentioned = isBotMentioned(rawText, botShipName, botNickname ?? void 0);
3116
3167
  const inParticipatedThread = isThreadReply && parentId && participatedThreads.has(parentId);
3117
3168
  const mentionDecision = resolveTlonGroupMentionDecision({
@@ -3122,30 +3173,28 @@ async function monitorTlonProvider(opts = {}) {
3122
3173
  });
3123
3174
  if (mentionDecision.shouldSkip) return;
3124
3175
  if (mentionDecision.implicitMention && !mentioned) runtime.log?.(`[tlon] Responding to thread we participated in (no mention): ${parentId}`);
3176
+ const { mode, allowedShips } = resolveChannelAuthorization(cfg, nest, currentSettings);
3125
3177
  if (isOwner(senderShip)) runtime.log?.(`[tlon] Owner ${senderShip} is always allowed in channels`);
3126
- else {
3127
- const { mode, allowedShips } = resolveChannelAuthorization(cfg, nest, currentSettings);
3128
- if (mode === "restricted") {
3129
- if (!allowedShips.map(normalizeShip).includes(senderShip)) {
3130
- if (effectiveOwnerShip) {
3131
- const approval = createPendingApproval({
3132
- type: "channel",
3133
- requestingShip: senderShip,
3134
- channelNest: nest,
3135
- messagePreview: sliceUtf16Safe(rawText, 0, 100),
3136
- originalMessage: {
3137
- messageId: messageId ?? "",
3138
- messageText: rawText,
3139
- messageContent: contentBody,
3140
- timestamp: sentAt,
3141
- parentId: parentId ?? void 0,
3142
- isThreadReply
3143
- }
3144
- });
3145
- await queueApprovalRequest(approval);
3146
- } else runtime.log?.(`[tlon] Access denied: ${senderShip} in ${nest} (allowed: ${allowedShips.join(", ")})`);
3147
- return;
3148
- }
3178
+ else if (mode === "restricted") {
3179
+ if (!allowedShips.map(normalizeShip).includes(senderShip)) {
3180
+ if (effectiveOwnerShip) {
3181
+ const approval = createPendingApproval({
3182
+ type: "channel",
3183
+ requestingShip: senderShip,
3184
+ channelNest: nest,
3185
+ messagePreview: sliceUtf16Safe(rawText, 0, 100),
3186
+ originalMessage: {
3187
+ messageId: messageId ?? "",
3188
+ messageText: rawText,
3189
+ messageContent: contentBody,
3190
+ timestamp: sentAt,
3191
+ parentId: parentId ?? void 0,
3192
+ isThreadReply
3193
+ }
3194
+ });
3195
+ await queueApprovalRequest(approval);
3196
+ } else runtime.log?.(`[tlon] Access denied: ${senderShip} in ${nest} (allowed: ${allowedShips.join(", ")})`);
3197
+ return;
3149
3198
  }
3150
3199
  }
3151
3200
  const messageText = await resolveAuthorizedMessageText({
@@ -3167,10 +3216,21 @@ async function monitorTlonProvider(opts = {}) {
3167
3216
  timestamp: sentAt,
3168
3217
  parentId,
3169
3218
  isThreadReply,
3170
- turnAdoptionLifecycle
3219
+ turnAdoptionLifecycle,
3220
+ resolveChannelIngress: async (contextBinding) => await resolveTlonMessageIngress({
3221
+ senderShip,
3222
+ accountId: account.accountId,
3223
+ conversation: {
3224
+ kind: "group",
3225
+ id: nest
3226
+ },
3227
+ allowFrom: [...allowedShips.map(normalizeShip), ...effectiveOwnerShip ? [normalizeShip(effectiveOwnerShip)] : []],
3228
+ groupPolicy: mode === "restricted" ? "allowlist" : "open",
3229
+ contextBinding
3230
+ })
3171
3231
  });
3172
3232
  } catch (error) {
3173
- runtime.error?.(`[tlon] Error handling channel firehose event: ${formatErrorMessage$1(error)}`);
3233
+ runtime.error?.(`[tlon] Error handling channel firehose event: ${formatErrorMessage(error)}`);
3174
3234
  throw error;
3175
3235
  }
3176
3236
  };
@@ -3228,15 +3288,15 @@ async function monitorTlonProvider(opts = {}) {
3228
3288
  }
3229
3289
  return;
3230
3290
  }
3231
- const eventRecord = asRecord(event);
3291
+ const eventRecord = asNullableRecord(event);
3232
3292
  if (!eventRecord) return;
3233
3293
  const whom = eventRecord.whom;
3234
- const messageId = readString(eventRecord, "id");
3235
- const response = asRecord(eventRecord.response);
3294
+ const messageId = readStringField(eventRecord, "id");
3295
+ const response = asNullableRecord(eventRecord.response);
3236
3296
  if (!messageId || !response) return;
3237
- const essay = asRecord(asRecord(response.add)?.essay);
3297
+ const essay = asNullableRecord(asNullableRecord(response.add)?.essay);
3238
3298
  if (!essay) return;
3239
- const authorShip = normalizeShip(readString(essay, "author") ?? "");
3299
+ const authorShip = normalizeShip(readStringField(essay, "author") ?? "");
3240
3300
  const partnerShip = extractDmPartnerShip(whom);
3241
3301
  const senderShip = partnerShip || authorShip;
3242
3302
  if (authorShip === botShipName) return;
@@ -3271,12 +3331,34 @@ async function monitorTlonProvider(opts = {}) {
3271
3331
  messageText: resolvedMessageText,
3272
3332
  messageContent: essay.content,
3273
3333
  isGroup: false,
3274
- timestamp: readNumber(essay, "sent") ?? Date.now(),
3275
- turnAdoptionLifecycle
3334
+ timestamp: asFiniteNumber(essay?.sent) ?? Date.now(),
3335
+ turnAdoptionLifecycle,
3336
+ resolveChannelIngress: async (contextBinding) => await resolveTlonMessageIngress({
3337
+ senderShip,
3338
+ accountId: account.accountId,
3339
+ conversation: {
3340
+ kind: "direct",
3341
+ id: senderShip
3342
+ },
3343
+ allowFrom: [senderShip],
3344
+ dmPolicy: "allowlist",
3345
+ contextBinding
3346
+ })
3276
3347
  });
3277
3348
  return;
3278
3349
  }
3279
- if (!await isDmAllowedWithIngress(senderShip, effectiveDmAllowlist)) {
3350
+ const resolveChannelIngress = async (contextBinding) => await resolveTlonMessageIngress({
3351
+ senderShip,
3352
+ accountId: account.accountId,
3353
+ conversation: {
3354
+ kind: "direct",
3355
+ id: senderShip
3356
+ },
3357
+ allowFrom: effectiveDmAllowlist ?? [],
3358
+ dmPolicy: "allowlist",
3359
+ contextBinding
3360
+ });
3361
+ if (!(await resolveChannelIngress()).senderAccess.allowed) {
3280
3362
  if (effectiveOwnerShip) {
3281
3363
  const approval = createPendingApproval({
3282
3364
  type: "dm",
@@ -3286,7 +3368,7 @@ async function monitorTlonProvider(opts = {}) {
3286
3368
  messageId: messageId ?? "",
3287
3369
  messageText,
3288
3370
  messageContent: essay.content,
3289
- timestamp: readNumber(essay, "sent") ?? Date.now()
3371
+ timestamp: asFiniteNumber(essay?.sent) ?? Date.now()
3290
3372
  }
3291
3373
  });
3292
3374
  await queueApprovalRequest(approval);
@@ -3304,11 +3386,12 @@ async function monitorTlonProvider(opts = {}) {
3304
3386
  senderShip,
3305
3387
  messageContent: essay.content,
3306
3388
  isGroup: false,
3307
- timestamp: readNumber(essay, "sent") ?? Date.now(),
3308
- turnAdoptionLifecycle
3389
+ timestamp: asFiniteNumber(essay?.sent) ?? Date.now(),
3390
+ turnAdoptionLifecycle,
3391
+ resolveChannelIngress
3309
3392
  });
3310
3393
  } catch (error) {
3311
- runtime.error?.(`[tlon] Error handling chat firehose event: ${formatErrorMessage$1(error)}`);
3394
+ runtime.error?.(`[tlon] Error handling chat firehose event: ${formatErrorMessage(error)}`);
3312
3395
  throw error;
3313
3396
  }
3314
3397
  };
@@ -3365,11 +3448,11 @@ async function monitorTlonProvider(opts = {}) {
3365
3448
  path: "/v1/news",
3366
3449
  event: (event) => {
3367
3450
  try {
3368
- const eventRecord = asRecord(event);
3451
+ const eventRecord = asNullableRecord(event);
3369
3452
  if (eventRecord?.self) {
3370
- const nickname = asRecord(asRecord(asRecord(eventRecord.self)?.contact)?.nickname);
3453
+ const nickname = asNullableRecord(asNullableRecord(asNullableRecord(eventRecord.self)?.contact)?.nickname);
3371
3454
  if (nickname && "value" in nickname) {
3372
- const newNickname = readString(nickname, "value") ?? null;
3455
+ const newNickname = readStringField(nickname, "value") ?? null;
3373
3456
  if (newNickname !== botNickname) {
3374
3457
  botNickname = newNickname;
3375
3458
  runtime.log?.(`[tlon] Nickname updated: ${botNickname}`);
@@ -3377,7 +3460,7 @@ async function monitorTlonProvider(opts = {}) {
3377
3460
  }
3378
3461
  }
3379
3462
  } catch (error) {
3380
- runtime.error?.(`[tlon] Error handling contacts event: ${formatErrorMessage$1(error)}`);
3463
+ runtime.error?.(`[tlon] Error handling contacts event: ${formatErrorMessage(error)}`);
3381
3464
  }
3382
3465
  },
3383
3466
  err: (error) => {
@@ -3415,9 +3498,9 @@ async function monitorTlonProvider(opts = {}) {
3415
3498
  event: (event) => {
3416
3499
  (async () => {
3417
3500
  try {
3418
- const eventRecord = asRecord(event);
3501
+ const eventRecord = asNullableRecord(event);
3419
3502
  if (eventRecord) {
3420
- const channels = asRecord(eventRecord.channels);
3503
+ const channels = asNullableRecord(eventRecord.channels);
3421
3504
  if (channels) for (const [channelNest, _channelData] of Object.entries(channels)) {
3422
3505
  if (!channelNest.startsWith("chat/")) continue;
3423
3506
  if (!watchedChannels.has(channelNest)) {
@@ -3444,7 +3527,7 @@ async function monitorTlonProvider(opts = {}) {
3444
3527
  }
3445
3528
  }
3446
3529
  }
3447
- const join = asRecord(eventRecord.join);
3530
+ const join = asNullableRecord(eventRecord.join);
3448
3531
  if (join) {
3449
3532
  const joinChannels = Array.isArray(join.channels) ? join.channels : [];
3450
3533
  if (joinChannels.length > 0) for (const channelNest of joinChannels) {
@@ -3477,7 +3560,7 @@ async function monitorTlonProvider(opts = {}) {
3477
3560
  }
3478
3561
  }
3479
3562
  } catch (error) {
3480
- runtime.error?.(`[tlon] Error handling groups-ui event: ${formatErrorMessage$1(error)}`);
3563
+ runtime.error?.(`[tlon] Error handling groups-ui event: ${formatErrorMessage(error)}`);
3481
3564
  }
3482
3565
  })();
3483
3566
  },
@@ -3572,7 +3655,7 @@ async function monitorTlonProvider(opts = {}) {
3572
3655
  try {
3573
3656
  await processPendingInvites(data);
3574
3657
  } catch (error) {
3575
- runtime.error?.(`[tlon] Error handling foreigns event: ${formatErrorMessage$1(error)}`);
3658
+ runtime.error?.(`[tlon] Error handling foreigns event: ${formatErrorMessage(error)}`);
3576
3659
  }
3577
3660
  })();
3578
3661
  },
@@ -3609,26 +3692,20 @@ async function monitorTlonProvider(opts = {}) {
3609
3692
  }
3610
3693
  }
3611
3694
  } catch (error) {
3612
- runtime.error?.(`[tlon] Channel refresh error: ${formatErrorMessage$1(error)}`);
3695
+ runtime.error?.(`[tlon] Channel refresh error: ${formatErrorMessage(error)}`);
3613
3696
  }
3614
3697
  })();
3615
3698
  }, 120 * 1e3);
3616
- if (opts.abortSignal) {
3617
- const signal = opts.abortSignal;
3618
- await new Promise((resolve) => {
3619
- signal.addEventListener("abort", () => {
3620
- clearInterval(pollInterval);
3621
- resolve(null);
3622
- }, { once: true });
3623
- });
3624
- } else await new Promise(() => {});
3699
+ await waitUntilAbort(opts.abortSignal, () => {
3700
+ clearInterval(pollInterval);
3701
+ });
3625
3702
  } finally {
3626
3703
  api?.stopReceiving();
3627
3704
  await ingress.stop();
3628
3705
  try {
3629
3706
  await api?.close();
3630
3707
  } catch (error) {
3631
- runtime.error?.(`[tlon] Cleanup error: ${formatErrorMessage$1(error)}`);
3708
+ runtime.error?.(`[tlon] Cleanup error: ${formatErrorMessage(error)}`);
3632
3709
  }
3633
3710
  }
3634
3711
  }
@@ -3975,6 +4052,8 @@ async function withHttpPokeAccountApi(account, run) {
3975
4052
  }
3976
4053
  const tlonRuntimeOutbound = {
3977
4054
  deliveryMode: "direct",
4055
+ chunker: chunkTextForOutbound,
4056
+ chunkerMode: "markdown",
3978
4057
  textChunkLimit: 1e4,
3979
4058
  resolveTarget: ({ to }) => resolveTlonOutboundTarget(to),
3980
4059
  deliveryCapabilities: { durableFinal: {
@@ -4066,7 +4145,6 @@ async function probeTlonAccount(account, timeoutMs) {
4066
4145
  };
4067
4146
  return { ok: true };
4068
4147
  } finally {
4069
- if (!response.bodyUsed) await response.body?.cancel().catch(() => void 0);
4070
4148
  await release();
4071
4149
  }
4072
4150
  }, (error) => ({