@botharness/core 1.6.0 → 1.6.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.
package/cli/index.mjs CHANGED
@@ -4641,6 +4641,8 @@ function isLanAddress(address) {
4641
4641
  }
4642
4642
  //#endregion
4643
4643
  //#region apps/mobile/src/host/route.ts
4644
+ const isLoopbackHostname = (hostname) => hostname === "localhost" || hostname === "[::1]" || /^127\.\d+\.\d+\.\d+$/u.test(hostname);
4645
+ const isTailscaleHostname = (hostname) => hostname.endsWith(".ts.net") || /^100\.(?:6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.\d+\.\d+$/u.test(hostname);
4644
4646
  function checkRoute(input) {
4645
4647
  let url;
4646
4648
  try {
@@ -4652,8 +4654,8 @@ function checkRoute(input) {
4652
4654
  };
4653
4655
  }
4654
4656
  const name = url.hostname;
4655
- const loopback = name === "localhost" || name === "[::1]" || /^127\.\d+\.\d+\.\d+$/u.test(name);
4656
- const tailnet = name.endsWith(".ts.net") || /^100\.(?:6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.\d+\.\d+$/u.test(name);
4657
+ const loopback = isLoopbackHostname(name);
4658
+ const tailnet = isTailscaleHostname(name);
4657
4659
  const connect = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.deepseekbot\.dev$/u.test(name);
4658
4660
  if (!(isLanAddress(name) && url.protocol === "http:" && url.port !== "" || loopback && (url.protocol === "http:" || url.protocol === "https:") || (tailnet || connect && url.port === "") && url.protocol === "https:") || url.username || url.password || url.search || url.hash || url.pathname !== "/" && url.pathname !== "") return {
4659
4661
  ok: false,
@@ -4682,16 +4684,17 @@ function isLanRoute(route) {
4682
4684
  return false;
4683
4685
  }
4684
4686
  }
4685
- function isEncryptedRoute(route, encryption) {
4686
- if (isConnectRoute(route) || isLanRoute(route)) return true;
4687
- if (encryption?.loopback !== "encrypted") return false;
4687
+ function isLoopbackRoute(route) {
4688
4688
  try {
4689
- const hostname = new URL(route).hostname;
4690
- return hostname === "localhost" || hostname === "[::1]" || /^127\.\d+\.\d+\.\d+$/u.test(hostname);
4689
+ return isLoopbackHostname(new URL(route).hostname);
4691
4690
  } catch {
4692
4691
  return false;
4693
4692
  }
4694
4693
  }
4694
+ function isEncryptedRoute(route, encryption) {
4695
+ if (isConnectRoute(route) || isLanRoute(route)) return true;
4696
+ return encryption?.loopback === "encrypted" && isLoopbackRoute(route);
4697
+ }
4695
4698
  //#endregion
4696
4699
  //#region apps/mobile/src/host/encrypted-carrier.ts
4697
4700
  var ConnectRefused = class extends Error {
@@ -16425,6 +16428,58 @@ const BOT_HARNESS_SCHEMA_PLAN = defineSchemaPlan([
16425
16428
  migrate(database) {
16426
16429
  database.exec(MESSAGE_SEARCH_INDEX_SQL);
16427
16430
  }
16431
+ },
16432
+ {
16433
+ generation: 113,
16434
+ module: "messaging",
16435
+ description: "Fence grant-backed reception evidence from older Bridge-only readers",
16436
+ migrate(database) {
16437
+ database.exec(`CREATE INDEX messaging_paths_authority
16438
+ ON messaging_source_paths(bot_slug, source_event_id, json_extract(body, '$.kind'));
16439
+ CREATE VIEW messaging_bridge_sources AS SELECT DISTINCT source_event_id
16440
+ FROM messaging_source_paths WHERE json_extract(body, '$.kind') IS NOT 'grant';`);
16441
+ }
16442
+ },
16443
+ {
16444
+ generation: 114,
16445
+ module: "messaging",
16446
+ description: "Index canonical pending attention candidates without scanning ordinary history",
16447
+ migrate(database) {
16448
+ database.exec(`
16449
+ CREATE INDEX source_events_attention_question ON source_events (message_id, source_event_id)
16450
+ WHERE source_kind = 'bot-message'
16451
+ AND json_extract(payload_json, '$.userQuestionRequest') IS NOT NULL;
16452
+ CREATE INDEX source_events_attention_approval ON source_events (message_id, source_event_id)
16453
+ WHERE source_kind = 'bot-message'
16454
+ AND json_extract(payload_json, '$.toolApprovalRequest') IS NOT NULL;
16455
+ CREATE INDEX source_events_attention_private ON source_events (message_id, source_event_id)
16456
+ WHERE source_kind = 'bot-message'
16457
+ AND json_extract(payload_json, '$.privateInputRequest') IS NOT NULL;
16458
+ CREATE INDEX source_events_attention_grant ON source_events (message_id, source_event_id)
16459
+ WHERE source_kind = 'bot-message'
16460
+ AND json_extract(payload_json, '$.grantRequest') = 1;
16461
+ CREATE INDEX source_events_attention_rejection ON source_events (message_id, source_event_id)
16462
+ WHERE source_kind = 'system-message'
16463
+ AND json_extract(payload_json, '$.toolAutoApproval.outcome') = 'rejected';
16464
+ `);
16465
+ }
16466
+ },
16467
+ {
16468
+ generation: 115,
16469
+ module: "bot-lan",
16470
+ description: "Record explicit Host-key-bound LAN Bot collaboration admissions",
16471
+ migrate(database) {
16472
+ database.exec(`
16473
+ CREATE TABLE bot_lan_admissions (
16474
+ host_id TEXT PRIMARY KEY,
16475
+ public_key TEXT NOT NULL,
16476
+ admission_id TEXT NOT NULL UNIQUE,
16477
+ name TEXT NOT NULL,
16478
+ admitted_at TEXT NOT NULL,
16479
+ revoked_at TEXT
16480
+ );
16481
+ `);
16482
+ }
16428
16483
  }
16429
16484
  ]);
16430
16485
  //#endregion
@@ -28417,6 +28472,8 @@ function createPersonaBotRegistry(options) {
28417
28472
  if (typeof parsed === "object" && parsed !== null && "appearance" in parsed && !isUsableAvatarAppearance(parsed.appearance, parsed.avatar)) delete parsed.appearance;
28418
28473
  if (typeof parsed === "object" && parsed !== null && "banner" in parsed && !isBotBanner(parsed.banner)) delete parsed.banner;
28419
28474
  if (typeof parsed === "object" && parsed !== null && "primaryColor" in parsed && !isBotPrimaryColor(parsed.primaryColor)) delete parsed.primaryColor;
28475
+ if (typeof parsed === "object" && parsed !== null && "modelPlan" in parsed && !isPersonaBotModelPlan(parsed.modelPlan)) delete parsed.modelPlan;
28476
+ if (typeof parsed === "object" && parsed !== null && "modelPlanRevision" in parsed && (typeof parsed.modelPlanRevision !== "number" || !Number.isSafeInteger(parsed.modelPlanRevision) || parsed.modelPlanRevision < 0)) delete parsed.modelPlanRevision;
28420
28477
  if (!isPersonaBotRecord(parsed, slug)) throw new Error("Invalid PersonaBot Registry record");
28421
28478
  return recordSnapshot(parsed);
28422
28479
  };
@@ -28428,6 +28485,8 @@ function createPersonaBotRegistry(options) {
28428
28485
  });
28429
28486
  };
28430
28487
  const write = (record) => {
28488
+ const slug = record.slug;
28489
+ if (!isPersonaBotRecord(record, slug)) throw new Error(`Refusing to persist an invalid PersonaBot Registry record: ${slug}`);
28431
28490
  port.transaction((database) => {
28432
28491
  database.prepare(`INSERT INTO persona_bots (slug, body) VALUES (?, ?)
28433
28492
  ON CONFLICT (slug) DO UPDATE SET body = excluded.body`).run(record.slug, JSON.stringify(recordSnapshot(record)));
@@ -29984,6 +30043,11 @@ const purgeFactSchema = object$2({
29984
30043
  kind: literal("bot"),
29985
30044
  slug: identity
29986
30045
  }).strict(),
30046
+ object$2({
30047
+ kind: literal("remote-bot"),
30048
+ hostId: identity,
30049
+ slug: identity
30050
+ }).strict(),
29987
30051
  object$2({
29988
30052
  kind: literal("bridged"),
29989
30053
  source: identity
@@ -30063,6 +30127,53 @@ const DEFAULT_GROUP_WAKE_POLICY = {
30063
30127
  intervalSeconds: 30,
30064
30128
  revision: 0
30065
30129
  };
30130
+ function isBotNetworkScope(value) {
30131
+ if (typeof value !== "object" || value === null) return false;
30132
+ const record = value;
30133
+ const id = (field) => typeof record[field] === "string" && /^[a-zA-Z0-9_-]{1,128}$/u.test(record[field]);
30134
+ return record["kind"] === "tailnet" ? id("localNodeId") && id("remoteNodeId") : record["kind"] === "connect" ? id("accountId") && id("localHostId") && id("remoteHostId") : record["kind"] === "lan" && id("localAdmissionId") && id("remoteAdmissionId");
30135
+ }
30136
+ function isBotNetworkMembership(value) {
30137
+ if (isBotNetworkScope(value)) return true;
30138
+ if (typeof value !== "object" || value === null) return false;
30139
+ const record = value;
30140
+ const scopes = record["scopes"];
30141
+ return record["kind"] === "scopes" && Array.isArray(scopes) && scopes.length >= 2 && scopes.length <= 3 && scopes.every(isBotNetworkScope) && new Set(scopes.map((scope) => scope.kind)).size === scopes.length;
30142
+ }
30143
+ function botNetworkScopes(membership) {
30144
+ return membership.kind === "scopes" ? membership.scopes : [membership];
30145
+ }
30146
+ function mergeBotNetworkMembership(previous, next) {
30147
+ const scopes = /* @__PURE__ */ new Map();
30148
+ for (const scope of previous === void 0 ? [] : botNetworkScopes(previous)) scopes.set(scope.kind, scope);
30149
+ for (const scope of botNetworkScopes(next)) scopes.set(scope.kind, scope);
30150
+ return scopes.size === 1 ? [...scopes.values()][0] : {
30151
+ kind: "scopes",
30152
+ scopes: [...scopes.values()]
30153
+ };
30154
+ }
30155
+ function remoteBotDmRecord(localBotSlug, remoteBot, at) {
30156
+ if (!isValidSlug(localBotSlug) || !isValidSlug(remoteBot.botSlug) || !/^[a-zA-Z0-9_-]{1,128}$/u.test(remoteBot.hostId) || remoteBot.displayName.length > 128 || remoteBot.membership !== void 0 && (!isBotNetworkMembership(remoteBot.membership) || remoteBot.hostKey === void 0) || remoteBot.hostKey !== void 0 && !/^[0-9a-f]{64}$/u.test(remoteBot.hostKey)) throw new Error("Invalid remote Bot participant");
30157
+ return {
30158
+ id: `dm-remote-${createHash("sha256").update(JSON.stringify([
30159
+ localBotSlug,
30160
+ remoteBot.hostId,
30161
+ remoteBot.botSlug
30162
+ ])).digest("hex").slice(0, 32)}`,
30163
+ type: "dm",
30164
+ name: remoteBot.displayName,
30165
+ members: [localBotSlug],
30166
+ remoteBot: {
30167
+ hostId: remoteBot.hostId,
30168
+ botSlug: remoteBot.botSlug,
30169
+ displayName: remoteBot.displayName,
30170
+ ...remoteBot.hostKey === void 0 ? {} : { hostKey: remoteBot.hostKey },
30171
+ ...remoteBot.membership === void 0 ? {} : { membership: { ...remoteBot.membership } }
30172
+ },
30173
+ createdAt: at,
30174
+ updatedAt: at
30175
+ };
30176
+ }
30066
30177
  function isGroupAvatar(value) {
30067
30178
  if (typeof value !== "string" || value.length > 131072) return false;
30068
30179
  const match = /^data:image\/(png|jpeg|webp);base64,([A-Za-z0-9+/]+={0,2})$/.exec(value);
@@ -30102,7 +30213,7 @@ function botDmChannelId(firstBotSlug, secondBotSlug) {
30102
30213
  return `dm-bots-${createHash("sha256").update(JSON.stringify(pair)).digest("hex").slice(0, 32)}`;
30103
30214
  }
30104
30215
  function isBotDmChannel(channel) {
30105
- return channel.type === "dm" && channel.botSlug === void 0 && channel.members.length === 2;
30216
+ return channel.type === "dm" && channel.botSlug === void 0 && (channel.remoteBot === void 0 ? channel.members.length === 2 : channel.members.length === 1);
30106
30217
  }
30107
30218
  function slugifyChannelName(name) {
30108
30219
  return name.trim().toLowerCase().replace(/[^a-z0-9]+/gu, "-").replace(/^-+|-+$/gu, "").slice(0, 64).replace(/-+$/gu, "");
@@ -30118,6 +30229,7 @@ function isChannelMessageAuthor(value) {
30118
30229
  case "human":
30119
30230
  case "system": return true;
30120
30231
  case "bot": return typeof author["slug"] === "string" && author["slug"].length > 0;
30232
+ case "remote-bot": return typeof author["hostId"] === "string" && /^[a-zA-Z0-9_-]{1,128}$/u.test(author["hostId"]) && typeof author["slug"] === "string" && isValidSlug(author["slug"]);
30121
30233
  case "bridged": return typeof author["source"] === "string" && author["source"].length > 0;
30122
30234
  default: return false;
30123
30235
  }
@@ -30138,6 +30250,12 @@ function isChannelRecord(value, id) {
30138
30250
  if (!Array.isArray(members) || !members.every((entry) => typeof entry === "string")) return false;
30139
30251
  const botSlug = record["botSlug"];
30140
30252
  if (botSlug !== void 0 && typeof botSlug !== "string") return false;
30253
+ const remote = record["remoteBot"];
30254
+ if (remote !== void 0) {
30255
+ if (record["type"] !== "dm" || botSlug !== void 0 || members.length !== 1 || typeof remote !== "object" || remote === null) return false;
30256
+ const peer = remote;
30257
+ if (typeof peer["hostId"] !== "string" || !/^[a-zA-Z0-9_-]{1,128}$/u.test(peer["hostId"]) || typeof peer["botSlug"] !== "string" || !isValidSlug(peer["botSlug"]) || typeof peer["displayName"] !== "string" || peer["displayName"].length > 128 || peer["membership"] !== void 0 && (!isBotNetworkMembership(peer["membership"]) || peer["hostKey"] === void 0) || peer["hostKey"] !== void 0 && (typeof peer["hostKey"] !== "string" || !/^[0-9a-f]{64}$/u.test(peer["hostKey"]))) return false;
30258
+ }
30141
30259
  const ownerBotSlug = record["ownerBotSlug"];
30142
30260
  if (ownerBotSlug !== void 0) {
30143
30261
  if (record["type"] !== "group" || typeof ownerBotSlug !== "string" || !members.includes(ownerBotSlug)) return false;
@@ -30314,7 +30432,7 @@ function isChannelMessage(value) {
30314
30432
  if (botCausation !== void 0) {
30315
30433
  if (typeof botCausation !== "object" || botCausation === null) return false;
30316
30434
  const causal = botCausation;
30317
- if (typeof causal["rootSourceEventId"] !== "string" || typeof causal["parentSourceEventId"] !== "string" || !Number.isSafeInteger(causal["hop"]) || causal["hop"] < 1 || message["author"]?.kind !== "bot") return false;
30435
+ if (typeof causal["rootSourceEventId"] !== "string" || typeof causal["parentSourceEventId"] !== "string" || !Number.isSafeInteger(causal["hop"]) || causal["hop"] < 1 || !["bot", "remote-bot"].includes(message["author"]?.kind)) return false;
30318
30436
  }
30319
30437
  const attachments = message["attachments"];
30320
30438
  if (attachments !== void 0 && (!Array.isArray(attachments) || attachments.length > 10 || !attachments.every(isChannelAttachmentRef))) return false;
@@ -32548,13 +32666,17 @@ async function runPhoneRouteCommand(command, rest, values, connect) {
32548
32666
  //#endregion
32549
32667
  //#region packages/core/src/bots/cli-devices.ts
32550
32668
  const DEVICES_COMMANDS = [
32669
+ {
32670
+ command: "bot-lan",
32671
+ description: "list nearby Hosts; admit <host-id> <public-key> or revoke <host-id> with --confirm"
32672
+ },
32551
32673
  {
32552
32674
  command: "device-requests",
32553
32675
  description: "list pending exact-key device approval requests"
32554
32676
  },
32555
32677
  {
32556
32678
  command: "device-lan",
32557
- description: "enable --confirm or disable encrypted phone access on the local network"
32679
+ description: "enable --confirm or disable encrypted LAN access and nearby Host discovery"
32558
32680
  },
32559
32681
  {
32560
32682
  command: "device-approve-key",
@@ -32586,12 +32708,28 @@ async function runDevicesCommand(command, rest, values, connect, write = (path,
32586
32708
  flag: "wx",
32587
32709
  mode: 384
32588
32710
  }), exists = existsSync) {
32711
+ if (command === "bot-lan") {
32712
+ const [action, hostId, publicKey] = rest;
32713
+ if (!(action === "list" ? rest.length === 1 : action === "revoke" ? rest.length === 2 : action === "admit" && rest.length === 3 && /^[a-f0-9]{64}$/u.test(publicKey ?? "")) || values.out !== void 0 || action !== "list" && !/^[a-zA-Z0-9_-]{1,128}$/u.test(hostId ?? "")) throw new CliLiveError("usage", "bot-lan takes list, admit <host-id> <public-key> --confirm, or revoke <host-id> --confirm.");
32714
+ if (action !== "list" && values.confirm !== true) throw new CliLiveError("confirm-required", "Compare the Host identity before changing LAN Bot access. Pass --confirm.");
32715
+ const response = await (await connect()).http(`${DEVICES$1}/lan-bots`, action === "list" ? void 0 : {
32716
+ action,
32717
+ hostId,
32718
+ ...action === "admit" ? { publicKey } : {},
32719
+ confirm: true
32720
+ });
32721
+ try {
32722
+ const parsed = JSON.parse(new TextDecoder().decode(response.bytes));
32723
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
32724
+ } catch {}
32725
+ throw new CliLiveError("host-protocol-error", "The Host did not return a JSON object.");
32726
+ }
32589
32727
  const takes = command === "device-approve-key" ? 2 : command === "device-offer-status" || command === "device-revoke" || command === "device-lan" ? 1 : 0;
32590
32728
  if (rest.length !== takes) throw new CliLiveError("usage", takes === 0 ? `${command} takes no arguments.` : command === "device-approve-key" ? "device-approve-key takes <receipt> <public-key> --confirm." : `${command} takes exactly one ${command === "device-revoke" ? "<device-id>" : "<receipt>"}.`);
32591
32729
  if (values.out !== void 0 && command !== "device-offer") throw new CliLiveError("usage", "--out requires device-offer.");
32592
32730
  if (command === "device-lan") {
32593
32731
  if (rest[0] !== "enable" && rest[0] !== "disable") throw new CliLiveError("usage", "device-lan takes enable --confirm or disable.");
32594
- if (rest[0] === "enable" && values.confirm !== true) throw new CliLiveError("confirm-required", "LAN access opens an encrypted phone entry on this network. Pass --confirm.");
32732
+ if (rest[0] === "enable" && values.confirm !== true) throw new CliLiveError("confirm-required", "LAN access opens an encrypted device entry and advertises this Host nearby. Pass --confirm.");
32595
32733
  }
32596
32734
  if (command === "device-offer") {
32597
32735
  if (values.out === void 0) throw new CliLiveError("out-required", "device-offer writes the pairing link only to a file. Pass --out with a new absolute path, or show the QR code from Bot settings → Devices.");
@@ -32624,7 +32762,8 @@ async function runDevicesCommand(command, rest, values, connect, write = (path,
32624
32762
  devices: snapshot["devices"],
32625
32763
  ...pendingKeys === void 0 ? {} : { pendingKeys },
32626
32764
  routes: snapshot["routes"],
32627
- ...snapshot["lan"] === void 0 ? {} : { lan: snapshot["lan"] }
32765
+ ...snapshot["lan"] === void 0 ? {} : { lan: snapshot["lan"] },
32766
+ ...snapshot["lanBots"] === void 0 ? {} : { lanBots: snapshot["lanBots"] }
32628
32767
  };
32629
32768
  }
32630
32769
  if (command === "device-lan") return decode((await host.http(`${DEVICES$1}/lan`, {
@@ -36919,7 +37058,8 @@ async function runBotToolCommand(command, rest, values, io, connect) {
36919
37058
  slug: rest[0].trim(),
36920
37059
  tool: rest[1].trim(),
36921
37060
  args,
36922
- ...values.session === void 0 ? {} : { sessionId: values.session }
37061
+ ...values.session === void 0 ? {} : { sessionId: values.session },
37062
+ ...values["cause-event"] === void 0 ? {} : { sourceEventId: values["cause-event"] }
36923
37063
  });
36924
37064
  }
36925
37065
  //#endregion
@@ -40275,18 +40415,25 @@ function encodeCursor(channelId, message) {
40275
40415
  id: message.id
40276
40416
  })).toString("base64url");
40277
40417
  }
40278
- function cursorIndex(channelId, messages, cursor) {
40279
- if (cursor.length > 2048) return -1;
40418
+ function timelineCursorAnchor(channelId, cursor) {
40419
+ if (cursor.length > 2048) return void 0;
40280
40420
  try {
40281
40421
  const value = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
40282
- if (typeof value !== "object" || value === null) return -1;
40422
+ if (typeof value !== "object" || value === null) return void 0;
40283
40423
  const decoded = value;
40284
- if (decoded.v !== 1 || decoded.channelId !== channelId || typeof decoded.id !== "string" || typeof decoded.at !== "string") return -1;
40285
- return messages.findIndex((message) => message.id === decoded.id && message.at === decoded.at);
40424
+ if (decoded.v !== 1 || decoded.channelId !== channelId || typeof decoded.id !== "string" || typeof decoded.at !== "string") return void 0;
40425
+ return {
40426
+ id: decoded.id,
40427
+ at: decoded.at
40428
+ };
40286
40429
  } catch {
40287
- return -1;
40430
+ return;
40288
40431
  }
40289
40432
  }
40433
+ function cursorIndex(channelId, messages, cursor) {
40434
+ const anchor = timelineCursorAnchor(channelId, cursor);
40435
+ return anchor === void 0 ? -1 : messages.findIndex((message) => message.id === anchor.id && message.at === anchor.at);
40436
+ }
40290
40437
  function pageChannelJournal(channelId, messages, request) {
40291
40438
  const { through, before } = request;
40292
40439
  if (!Number.isSafeInteger(through) || through < 0 || through > messages.length) return void 0;
@@ -41947,6 +42094,7 @@ const LIVE_OPTIONS = {
41947
42094
  conversation: { type: "string" },
41948
42095
  out: { type: "string" },
41949
42096
  "args-stdin": { type: "boolean" },
42097
+ "cause-event": { type: "string" },
41950
42098
  session: { type: "string" },
41951
42099
  turns: { type: "string" },
41952
42100
  offset: { type: "string" },
@@ -47272,7 +47420,7 @@ function sameIntent(left, right) {
47272
47420
  });
47273
47421
  }
47274
47422
  function sourceKind(message) {
47275
- return message.author.kind === "human" ? "human-message" : message.author.kind === "bot" ? "bot-message" : "system-message";
47423
+ return message.author.kind === "human" ? "human-message" : message.author.kind === "bot" || message.author.kind === "remote-bot" ? "bot-message" : "system-message";
47276
47424
  }
47277
47425
  function rawMessage(message) {
47278
47426
  const result = { ...message };
@@ -47354,6 +47502,20 @@ function createSqliteChannelStore(options) {
47354
47502
  options.warn?.("Channel record notification failed: " + String(error));
47355
47503
  }
47356
47504
  };
47505
+ const remoteHostKey = (db, host) => {
47506
+ const rows = db.prepare(`SELECT DISTINCT json_extract(record_json, '$.remoteBot.hostKey') AS host_key
47507
+ FROM channel_records WHERE json_extract(record_json, '$.remoteBot.hostId') = ?
47508
+ AND json_extract(record_json, '$.remoteBot.hostKey') IS NOT NULL`).all(host);
47509
+ if (rows.length > 1) throw new Error("network-host-key-conflict");
47510
+ const key = rows[0]?.host_key;
47511
+ if (key !== void 0 && (typeof key !== "string" || !/^[0-9a-f]{64}$/u.test(key))) throw new Error("network-host-key-invalid");
47512
+ return key;
47513
+ };
47514
+ const assertHostKey = (db, host, key) => {
47515
+ if (!/^[0-9a-f]{64}$/u.test(key)) throw new Error("network-host-key-invalid");
47516
+ const known = remoteHostKey(db, host);
47517
+ if (known !== void 0 && known !== key) throw new Error("network-host-key-conflict");
47518
+ };
47357
47519
  const writeRecord = (record) => {
47358
47520
  database.transaction((db) => {
47359
47521
  db.prepare(`INSERT INTO channel_records (channel_id, record_json) VALUES (?, ?)
@@ -47377,7 +47539,9 @@ function createSqliteChannelStore(options) {
47377
47539
  });
47378
47540
  };
47379
47541
  let reactionTable = false;
47380
- const channelReactions = (channelId, messageId) => {
47542
+ const channelReactions = (channelId, messageIds) => {
47543
+ const selected = typeof messageIds === "string" ? [messageIds] : messageIds;
47544
+ if (selected?.length === 0) return /* @__PURE__ */ new Map();
47381
47545
  reactionTable ||= database.read((db) => db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'channel_reactions'").get() !== void 0);
47382
47546
  if (!reactionTable) return /* @__PURE__ */ new Map();
47383
47547
  const rows = database.read((db) => db.prepare(`SELECT r.message_id, r.emoji, r.actor_kind, r.actor_id,
@@ -47385,8 +47549,8 @@ function createSqliteChannelStore(options) {
47385
47549
  WHERE f.channel_id = r.channel_id AND f.message_id = r.message_id
47386
47550
  AND f.emoji = r.emoji) AS first_at
47387
47551
  FROM channel_reactions r
47388
- WHERE r.channel_id = ?${messageId === void 0 ? "" : " AND r.message_id = ?"}
47389
- ORDER BY r.message_id, first_at, r.emoji, r.reacted_at, r.actor_kind, r.actor_id`).all(...messageId === void 0 ? [channelId] : [channelId, messageId]));
47552
+ WHERE r.channel_id = ?${selected === void 0 ? "" : ` AND r.message_id IN (${selected.map(() => "?").join(", ")})`}
47553
+ ORDER BY r.message_id, first_at, r.emoji, r.reacted_at, r.actor_kind, r.actor_id`).all(channelId, ...selected ?? []));
47390
47554
  const result = /* @__PURE__ */ new Map();
47391
47555
  for (const row of rows) {
47392
47556
  let reactions = result.get(row.message_id);
@@ -47476,6 +47640,26 @@ function createSqliteChannelStore(options) {
47476
47640
  return recipients.length === 0 ? void 0 : recipients;
47477
47641
  };
47478
47642
  const projectMessageAttachments = (sourceEventId, message) => projectAttachmentFiles(attachmentMigration.project(sourceEventId, message), options.attachments);
47643
+ const placementMessage = (row, id) => parseMessage(row.payload_json, row.body, row.message_id, id) ?? {
47644
+ id: row.message_id,
47645
+ at: row.created_at,
47646
+ author: { kind: "system" },
47647
+ body: "This message was written by a newer version and cannot be shown."
47648
+ };
47649
+ const projectPlacement = (row, id, members, reactionsById) => {
47650
+ const message = attachmentMigration.project(row.source_event_id, placementMessage(row, id));
47651
+ const deliveries = admissionStatuses(row.source_event_id);
47652
+ const humanReceipts = humanReceiptsFor(message, row.revision, members);
47653
+ const reactions = reactionsById.get(row.message_id);
47654
+ return {
47655
+ ...message,
47656
+ ...noticeOrigin(message, row, id),
47657
+ channelRevision: row.revision,
47658
+ ...deliveries === void 0 ? {} : { deliveries },
47659
+ ...humanReceipts === void 0 ? {} : { humanReceipts },
47660
+ ...reactions === void 0 ? {} : { reactions }
47661
+ };
47662
+ };
47479
47663
  const allMessages = (id) => {
47480
47664
  if (!isValidChannelId(id)) return [];
47481
47665
  const rows = database.read((db) => db.prepare(`
@@ -47487,26 +47671,7 @@ function createSqliteChannelStore(options) {
47487
47671
  `).all(id));
47488
47672
  const members = humanMembers(id);
47489
47673
  const reactionsById = channelReactions(id);
47490
- return rows.flatMap((row) => {
47491
- const original = parseMessage(row.payload_json, row.body, row.message_id, id) ?? {
47492
- id: row.message_id,
47493
- at: row.created_at,
47494
- author: { kind: "system" },
47495
- body: "This message was written by a newer version and cannot be shown."
47496
- };
47497
- const message = attachmentMigration.project(row.source_event_id, original);
47498
- const deliveries = admissionStatuses(row.source_event_id);
47499
- const humanReceipts = humanReceiptsFor(message, row.revision, members);
47500
- const reactions = reactionsById.get(row.message_id);
47501
- return [{
47502
- ...message,
47503
- ...noticeOrigin(message, row, id),
47504
- channelRevision: row.revision,
47505
- ...deliveries === void 0 ? {} : { deliveries },
47506
- ...humanReceipts === void 0 ? {} : { humanReceipts },
47507
- ...reactions === void 0 ? {} : { reactions }
47508
- }];
47509
- });
47674
+ return rows.map((row) => projectPlacement(row, id, members, reactionsById));
47510
47675
  };
47511
47676
  const projectPostPreview = (message) => {
47512
47677
  const post = message.botChannelPost;
@@ -47530,6 +47695,86 @@ function createSqliteChannelStore(options) {
47530
47695
  ...projectPostPreview(message),
47531
47696
  ...message.grantRequest ? { grantRequestResolved: isGrantRequestResolved(messages, message.id) } : {}
47532
47697
  }, new Map(messages.map((item) => [item.id, item]))), options.attachments);
47698
+ const timelinePage = (id, request = {}, visibleFrom = 0, members) => {
47699
+ if (!isValidChannelId(id)) return pageChannelTimeline(id, [], request);
47700
+ const limit = Math.max(1, Math.min(request.limit ?? 50, 200));
47701
+ const older = Math.max(0, Math.min(request.olderLimit ?? 20, 200));
47702
+ const newer = Math.max(0, Math.min(request.newerLimit ?? 20, 200));
47703
+ if ((request.direction === "around" ? [older, newer] : [limit]).some(Number.isNaN)) return void 0;
47704
+ let anchor;
47705
+ if (request.direction === "around" || request.direction === "older" || request.direction === "newer") {
47706
+ const cursor = request.direction === "around" || request.cursor === void 0 ? void 0 : timelineCursorAnchor(id, request.cursor);
47707
+ const anchorId = request.direction === "around" ? request.around : cursor?.id;
47708
+ if (anchorId === void 0) return void 0;
47709
+ anchor = database.read((db) => db.prepare(`
47710
+ SELECT p.revision, p.source_event_id, p.message_id, e.payload_json, e.body, e.created_at,
47711
+ e.channel_id AS home_channel_id
47712
+ FROM channel_placements p
47713
+ JOIN source_events e ON e.source_event_id = p.source_event_id
47714
+ WHERE p.channel_id = ? AND p.message_id = ? AND p.revision >= ?
47715
+ `).get(id, anchorId, visibleFrom));
47716
+ if (anchor === void 0 || cursor !== void 0 && placementMessage(anchor, id).at !== cursor.at) return void 0;
47717
+ }
47718
+ const readSide = (direction, count) => database.read((db) => db.prepare(`
47719
+ SELECT p.revision, p.source_event_id, p.message_id, e.payload_json, e.body, e.created_at,
47720
+ e.channel_id AS home_channel_id
47721
+ FROM channel_placements p
47722
+ JOIN source_events e ON e.source_event_id = p.source_event_id
47723
+ WHERE p.channel_id = ? AND p.revision >= ?
47724
+ ${anchor === void 0 ? "" : `AND p.revision ${direction === "older" ? "<" : ">"} ?`}
47725
+ ORDER BY p.revision ${direction === "older" ? "DESC" : "ASC"} LIMIT ?
47726
+ `).all(id, visibleFrom, ...anchor === void 0 ? [] : [anchor.revision], Math.ceil(count) + 1));
47727
+ const rows = anchor === void 0 ? readSide("older", limit).reverse() : request.direction === "older" ? [...readSide("older", limit).reverse(), anchor] : request.direction === "newer" ? [anchor, ...readSide("newer", limit)] : [
47728
+ ...readSide("older", older).reverse(),
47729
+ anchor,
47730
+ ...readSide("newer", newer)
47731
+ ];
47732
+ const page = pageChannelTimeline(id, rows.map((row) => placementMessage(row, id)), request);
47733
+ if (page === void 0 || page.entries.length === 0) return page;
47734
+ const selectedIds = new Set(page.entries.map((message) => message.id));
47735
+ const reactions = channelReactions(id, [...selectedIds]);
47736
+ const recipients = members ?? humanMembers(id);
47737
+ const selected = rows.filter((row) => selectedIds.has(row.message_id)).map((row) => projectPlacement(row, id, recipients, reactions));
47738
+ const dependencies = [...selected];
47739
+ const replyIds = [...new Set(selected.flatMap((message) => message.replyTo === void 0 || selectedIds.has(message.replyTo) ? [] : [message.replyTo]))];
47740
+ if (replyIds.length > 0) {
47741
+ const replies = database.read((db) => db.prepare(`
47742
+ SELECT p.revision, p.source_event_id, p.message_id, e.payload_json, e.body, e.created_at,
47743
+ e.channel_id AS home_channel_id
47744
+ FROM channel_placements p
47745
+ JOIN source_events e ON e.source_event_id = p.source_event_id
47746
+ WHERE p.channel_id = ? AND p.revision >= ?
47747
+ AND p.message_id IN (${replyIds.map(() => "?").join(", ")})
47748
+ `).all(id, visibleFrom, ...replyIds));
47749
+ dependencies.push(...replies.map((row) => attachmentMigration.project(row.source_event_id, placementMessage(row, id))));
47750
+ }
47751
+ const grantIds = selected.filter((message) => message.grantRequest).map((message) => message.id);
47752
+ if (grantIds.length > 0) dependencies.push(...database.read((db) => {
47753
+ const resolved = /* @__PURE__ */ new Map();
47754
+ for (const row of db.prepare(`
47755
+ SELECT p.message_id, e.payload_json, e.body
47756
+ FROM channel_placements p
47757
+ JOIN source_events e ON e.source_event_id = p.source_event_id
47758
+ WHERE p.channel_id = ? AND p.revision >= ?
47759
+ AND CASE WHEN json_valid(e.payload_json) THEN
47760
+ json_extract(e.payload_json, '$.author.kind') = 'human'
47761
+ AND json_extract(e.payload_json, '$.replyTo') = json_extract(e.payload_json, '$.grantRequestResolution.requestMessageId')
47762
+ AND json_extract(e.payload_json, '$.grantRequestResolution.requestMessageId') IN (${grantIds.map(() => "?").join(", ")})
47763
+ ELSE 0 END
47764
+ `).iterate(id, visibleFrom, ...grantIds)) {
47765
+ const candidate = row;
47766
+ const message = parseMessage(candidate.payload_json, candidate.body, candidate.message_id, id);
47767
+ const requestId = message?.grantRequestResolution?.requestMessageId;
47768
+ if (message !== void 0 && requestId !== void 0 && isGrantRequestResolved([message], requestId)) resolved.set(requestId, message);
47769
+ if (resolved.size === grantIds.length) break;
47770
+ }
47771
+ return [...resolved.values()];
47772
+ }));
47773
+ return {
47774
+ ...page,
47775
+ entries: selected.map((message) => project(dependencies, message))
47776
+ };
47777
+ };
47533
47778
  const revisionOf = (id) => {
47534
47779
  if (!isValidChannelId(id)) return 0;
47535
47780
  return database.read((db) => db.prepare("SELECT COALESCE(MAX(revision), 0) AS revision FROM channel_placements WHERE channel_id = ?").get(id)).revision;
@@ -47562,19 +47807,21 @@ function createSqliteChannelStore(options) {
47562
47807
  const senderSlug = message.author.kind === "bot" ? message.author.slug : void 0;
47563
47808
  if (channel.type === "group" && senderSlug !== void 0 && !channel.members.includes(senderSlug)) throw new Error("Only a joined Bot may author this Group Channel");
47564
47809
  if (channel.type === "group" && senderSlug !== void 0 && mentions.length > 0 && message.botCausation === void 0) throw new Error("Bot Group mentions require trusted causation");
47565
- const botDm = isBotDmChannel(channel) && senderSlug !== void 0;
47566
- if (isBotDmChannel(channel) && (senderSlug === void 0 || !channel.members.includes(senderSlug))) throw new Error("Only a Bot DM participant may author this Channel");
47810
+ const remoteSender = message.author.kind === "remote-bot";
47811
+ if (message.author.kind === "remote-bot" && (channel.remoteBot?.hostId !== message.author.hostId || channel.remoteBot?.botSlug !== message.author.slug || !isBotDmChannel(channel))) throw new Error("Remote Bot does not own this DM");
47812
+ const botDm = isBotDmChannel(channel) && (senderSlug !== void 0 || remoteSender);
47813
+ if (isBotDmChannel(channel) && !remoteSender && (senderSlug === void 0 || !channel.members.includes(senderSlug))) throw new Error("Only a Bot DM participant may author this Channel");
47567
47814
  if (botDm && message.botCausation === void 0) throw new Error("Bot DM send requires trusted causation");
47568
47815
  const senderDm = botDm && senderSlug !== void 0 ? readRecord(dmChannelId(senderSlug)) : void 0;
47569
- if (botDm && (senderDm?.type !== "dm" || senderDm.botSlug !== senderSlug)) throw new Error("Sender Human DM is unavailable for the Bot action notice");
47816
+ if (botDm && !remoteSender && (senderDm?.type !== "dm" || senderDm.botSlug !== senderSlug)) throw new Error("Sender Human DM is unavailable for the Bot action notice");
47570
47817
  const cause = botDm && senderSlug !== void 0 && message.botCausation !== void 0 ? causeChannel(message.botCausation.parentSourceEventId, senderSlug, id) : void 0;
47571
47818
  const noticeChannel = !botDm || cause === "target" ? void 0 : cause ?? senderDm;
47572
47819
  const recipient = botDm ? channel.members.find((slug) => slug !== senderSlug) : void 0;
47573
- if (botDm && recipient === void 0) throw new Error("Bot DM has no recipient");
47820
+ if (botDm && recipient === void 0 && channel.remoteBot === void 0) throw new Error("Bot DM has no recipient");
47574
47821
  const durable = rawMessage(message);
47575
47822
  const revision = previous.length + 1;
47576
47823
  const sourceEventId = randomUUID();
47577
- const action = noticeChannel !== void 0 && recipient !== void 0 && senderSlug !== void 0 ? {
47824
+ const action = noticeChannel !== void 0 && (recipient !== void 0 || channel.remoteBot !== void 0) && senderSlug !== void 0 ? {
47578
47825
  id: `bot-dm-action-${durable.id}`,
47579
47826
  at: durable.at,
47580
47827
  author: {
@@ -47582,11 +47829,14 @@ function createSqliteChannelStore(options) {
47582
47829
  slug: senderSlug
47583
47830
  },
47584
47831
  body: "",
47585
- botDmAction: {
47832
+ ...channel.remoteBot !== void 0 ? { botChannelPost: {
47833
+ channelId: id,
47834
+ messageId: durable.id
47835
+ } } : { botDmAction: {
47586
47836
  channelId: id,
47587
47837
  messageId: durable.id,
47588
47838
  recipientBotSlug: recipient
47589
- }
47839
+ } }
47590
47840
  } : void 0;
47591
47841
  const actionRevision = noticeChannel === void 0 ? void 0 : allMessages(noticeChannel.id).length + 1;
47592
47842
  const humanDm = senderSlug === void 0 ? void 0 : readRecord(dmChannelId(senderSlug));
@@ -47914,6 +48164,62 @@ function createSqliteChannelStore(options) {
47914
48164
  writeRecord(record);
47915
48165
  return record;
47916
48166
  },
48167
+ remoteHostKey(host) {
48168
+ return database.read((db) => remoteHostKey(db, host));
48169
+ },
48170
+ trustRemoteHostKey(host, key, membership) {
48171
+ if (membership !== void 0 && !isBotNetworkMembership(membership)) throw new Error("network-membership-invalid");
48172
+ database.transaction((db) => {
48173
+ assertHostKey(db, host, key);
48174
+ if (db.prepare(`UPDATE channel_records
48175
+ SET record_json = json_set(record_json, '$.remoteBot.hostKey', ?)
48176
+ WHERE json_extract(record_json, '$.remoteBot.hostId') = ?`).run(key, host).changes === 0) throw new Error("network-channel-required");
48177
+ if (membership !== void 0) {
48178
+ const rows = db.prepare(`SELECT channel_id, record_json FROM channel_records
48179
+ WHERE json_extract(record_json, '$.remoteBot.hostId') = ?`).all(host);
48180
+ for (const row of rows) {
48181
+ if (typeof row.channel_id !== "string" || typeof row.record_json !== "string") throw new Error("network-channel-invalid");
48182
+ const record = parseRecord$1(row.record_json, row.channel_id);
48183
+ if (record?.remoteBot === void 0) throw new Error("network-channel-invalid");
48184
+ const merged = mergeBotNetworkMembership(record.remoteBot.membership, membership);
48185
+ db.prepare(`UPDATE channel_records SET record_json = json_set(record_json,
48186
+ '$.remoteBot.membership', json(?)) WHERE channel_id = ?`).run(JSON.stringify(merged), row.channel_id);
48187
+ }
48188
+ }
48189
+ }, ["channel"]);
48190
+ publishRecordChanged();
48191
+ },
48192
+ getOrCreateRemoteBotDm(localBotSlug, remote) {
48193
+ const candidate = remoteBotDmRecord(localBotSlug, remote, now().toISOString());
48194
+ if (!isBotActive(localBotSlug)) throw new Error("Remote Bot DM recipient is not active");
48195
+ const result = database.transaction((db) => {
48196
+ if (remote.hostKey !== void 0) assertHostKey(db, remote.hostId, remote.hostKey);
48197
+ const row = db.prepare("SELECT record_json FROM channel_records WHERE channel_id = ?").get(candidate.id);
48198
+ const existing = typeof row?.record_json === "string" ? parseRecord$1(row.record_json, candidate.id) : void 0;
48199
+ if (existing !== void 0 && existing.deletedAt === void 0 && (existing.remoteBot?.hostId !== remote.hostId || existing.remoteBot.botSlug !== remote.botSlug || existing.members.length !== 1 || existing.members[0] !== localBotSlug || !isBotDmChannel(existing))) throw new Error("Remote Bot DM identity collision");
48200
+ const record = existing?.deletedAt === void 0 && existing !== void 0 ? existing : candidate;
48201
+ const key = remote.hostKey ?? remoteHostKey(db, remote.hostId);
48202
+ const pinned = key === void 0 ? record : {
48203
+ ...record,
48204
+ remoteBot: {
48205
+ ...record.remoteBot,
48206
+ hostKey: key
48207
+ }
48208
+ };
48209
+ const updated = remote.membership === void 0 ? pinned : {
48210
+ ...pinned,
48211
+ remoteBot: {
48212
+ ...pinned.remoteBot,
48213
+ membership: mergeBotNetworkMembership(pinned.remoteBot?.membership, remote.membership)
48214
+ }
48215
+ };
48216
+ db.prepare(`INSERT INTO channel_records (channel_id, record_json) VALUES (?, ?)
48217
+ ON CONFLICT(channel_id) DO UPDATE SET record_json = excluded.record_json`).run(updated.id, JSON.stringify(updated));
48218
+ return updated;
48219
+ }, ["channel"]);
48220
+ publishRecordChanged();
48221
+ return result;
48222
+ },
47917
48223
  getOrCreateBotDm(firstBotSlug, secondBotSlug, name) {
47918
48224
  if (!isValidSlug(firstBotSlug) || !isValidSlug(secondBotSlug) || firstBotSlug === secondBotSlug) return void 0;
47919
48225
  const id = botDmChannelId(firstBotSlug, secondBotSlug);
@@ -48596,12 +48902,61 @@ function createSqliteChannelStore(options) {
48596
48902
  `).get(LOCAL_HUMAN_ID, id))?.message_id;
48597
48903
  },
48598
48904
  latestMessage(id) {
48599
- const messages = allMessages(id);
48600
- const latest = messages.findLast((message) => !isChannelNotice(message));
48601
- return latest === void 0 ? void 0 : project(messages, latest);
48905
+ if (!isValidChannelId(id)) return void 0;
48906
+ const latest = database.read((db) => {
48907
+ for (const row of db.prepare(`
48908
+ SELECT p.revision, p.source_event_id, p.message_id, e.payload_json, e.body, e.created_at,
48909
+ e.channel_id AS home_channel_id
48910
+ FROM channel_placements p
48911
+ JOIN source_events e ON e.source_event_id = p.source_event_id
48912
+ WHERE p.channel_id = ? ORDER BY p.revision DESC
48913
+ `).iterate(id)) {
48914
+ const placement = row;
48915
+ if (!isChannelNotice(placementMessage(placement, id))) return placement;
48916
+ }
48917
+ });
48918
+ if (latest === void 0) return void 0;
48919
+ const message = projectPlacement(latest, id, humanMembers(id), channelReactions(id, latest.message_id));
48920
+ const dependencies = [message];
48921
+ const replyTo = message.replyTo;
48922
+ if (replyTo !== void 0) {
48923
+ const target = database.read((db) => db.prepare(`
48924
+ SELECT p.message_id, e.payload_json, e.body, e.created_at
48925
+ FROM channel_placements p
48926
+ JOIN source_events e ON e.source_event_id = p.source_event_id
48927
+ WHERE p.channel_id = ? AND p.message_id = ?
48928
+ `).get(id, replyTo));
48929
+ if (target !== void 0) dependencies.push(placementMessage(target, id));
48930
+ }
48931
+ if (message.grantRequest) {
48932
+ const resolution = database.read((db) => {
48933
+ for (const row of db.prepare(`
48934
+ SELECT p.message_id, e.payload_json, e.body
48935
+ FROM channel_placements p
48936
+ JOIN source_events e ON e.source_event_id = p.source_event_id
48937
+ WHERE p.channel_id = ?
48938
+ AND CASE WHEN json_valid(e.payload_json) THEN
48939
+ json_extract(e.payload_json, '$.author.kind') = 'human'
48940
+ AND json_extract(e.payload_json, '$.replyTo') = ?
48941
+ AND json_extract(e.payload_json, '$.grantRequestResolution.requestMessageId') = ?
48942
+ ELSE 0 END
48943
+ `).iterate(id, message.id, message.id)) {
48944
+ const candidate = row;
48945
+ const parsed = parseMessage(candidate.payload_json, candidate.body, candidate.message_id, id);
48946
+ if (parsed !== void 0 && isGrantRequestResolved([parsed], message.id)) return parsed;
48947
+ }
48948
+ });
48949
+ if (resolution !== void 0) dependencies.push(resolution);
48950
+ }
48951
+ return project(dependencies, message);
48602
48952
  },
48603
48953
  hasMessage(id, messageId) {
48604
- return allMessages(id).some((message) => message.id === messageId);
48954
+ if (!isValidChannelId(id)) return false;
48955
+ return database.read((db) => db.prepare(`
48956
+ SELECT 1 FROM channel_placements p
48957
+ JOIN source_events e ON e.source_event_id = p.source_event_id
48958
+ WHERE p.channel_id = ? AND p.message_id = ?
48959
+ `).get(id, messageId)) !== void 0;
48605
48960
  },
48606
48961
  message(id, messageId) {
48607
48962
  const messages = allMessages(id);
@@ -48889,12 +49244,7 @@ function createSqliteChannelStore(options) {
48889
49244
  };
48890
49245
  },
48891
49246
  readTimeline(id, request) {
48892
- const messages = allMessages(id);
48893
- const page = pageChannelTimeline(id, messages, request);
48894
- return page === void 0 ? void 0 : {
48895
- ...page,
48896
- entries: page.entries.map((message) => project(messages, message))
48897
- };
49247
+ return timelinePage(id, request);
48898
49248
  },
48899
49249
  searchHumanMessages(id, request) {
48900
49250
  const channel = readRecord(id);
@@ -48978,14 +49328,10 @@ function createSqliteChannelStore(options) {
48978
49328
  readHumanTimeline(id, request) {
48979
49329
  const channel = readRecord(id);
48980
49330
  if (channel === void 0) return void 0;
48981
- const member = humanMembers(id).find((entry) => entry.human_id === LOCAL_HUMAN_ID);
49331
+ const members = humanMembers(id);
49332
+ const member = members.find((entry) => entry.human_id === LOCAL_HUMAN_ID);
48982
49333
  if (channel.type === "group" && member === void 0) return void 0;
48983
- const messages = allMessages(id).filter((message) => (message.channelRevision ?? 0) >= (member?.visible_from_revision ?? 0));
48984
- const page = pageChannelTimeline(id, messages, request);
48985
- return page === void 0 ? void 0 : {
48986
- ...page,
48987
- entries: page.entries.map((message) => project(messages, message))
48988
- };
49334
+ return timelinePage(id, request, member?.visible_from_revision ?? 0, members);
48989
49335
  },
48990
49336
  readHumanJournalPage(id, request) {
48991
49337
  const channel = readRecord(id);
@@ -74641,6 +74987,39 @@ async function runAgentCli(command, rest, values, io) {
74641
74987
  return refuse(write ? "agent-write-uncertain" : "agent-protocol-error", "The scoped CLI result could not be confirmed.");
74642
74988
  }
74643
74989
  //#endregion
74990
+ //#region packages/core/src/devices/bot-network-wire.ts
74991
+ const keySchema = string().regex(/^[0-9a-f]{64}$/u);
74992
+ const hostId = string().regex(/^[a-zA-Z0-9_-]{1,128}$/u);
74993
+ const slug = string().max(64).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/u);
74994
+ object$2({
74995
+ hostId,
74996
+ publicKey: keySchema,
74997
+ contacts: array(object$2({
74998
+ hostId,
74999
+ botSlug: slug,
75000
+ displayName: string().max(128),
75001
+ description: string().max(1e3).optional(),
75002
+ device: object$2({
75003
+ model: string().max(128).nullable(),
75004
+ platform: string().max(128).nullable()
75005
+ }),
75006
+ capabilities: array(string().max(48)).max(8)
75007
+ })).max(50),
75008
+ next: number().int().positive().optional()
75009
+ });
75010
+ object$2({
75011
+ id: string().min(1).max(128),
75012
+ at: datetime(),
75013
+ senderBotSlug: slug,
75014
+ recipientBotSlug: slug,
75015
+ body: string().min(1).max(2e4),
75016
+ causation: object$2({
75017
+ rootSourceEventId: string().min(1).max(128),
75018
+ parentSourceEventId: string().min(1).max(128),
75019
+ hop: number().int().positive().max(1e3)
75020
+ })
75021
+ }).strict();
75022
+ //#endregion
74644
75023
  //#region packages/core/src/devices/http.ts
74645
75024
  const PAIRING_LINK_SCHEME = "deepseekbot";
74646
75025
  function pairingLink(payload) {