@goodfish/jarvy 0.10.0 → 0.11.0

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.
@@ -281,6 +281,22 @@ function threadView(entry, member) {
281
281
  root: entry.root ? { senderId: entry.root.senderId, content: clipMarked(entry.root.content, 300), quotes: entry.root.quotes } : null
282
282
  };
283
283
  }
284
+ function threadItemView({ chat, info, root }) {
285
+ return {
286
+ id: chat.id,
287
+ title: chat.title,
288
+ status: chat.status ?? "open",
289
+ parentId: chat.parentId,
290
+ createdAt: chat.createdAt,
291
+ replies: info.replies,
292
+ lastReplyAt: info.lastReplyAt,
293
+ root: root ? { senderId: root.senderId, content: clipMarked(root.content, 300), quotes: root.quotes } : null,
294
+ unread: chat.unread,
295
+ mentions: chat.mentions,
296
+ alerts: chat.alerts,
297
+ following: chat.following
298
+ };
299
+ }
284
300
  function messageView(message) {
285
301
  return {
286
302
  id: message.id,
@@ -684,7 +700,7 @@ var tooLarge = () => new ChatError(413, "File is too large", "file_too_large", {
684
700
  function chatRoutes({ chats, bots }) {
685
701
  const routes = new Hono5();
686
702
  const view = (chat) => chatView(chat, (id) => chats.member(id));
687
- routes.get("/", (c) => c.json({ chats: chats.list(c.get("actorId")).map(view) }));
703
+ routes.get("/", (c) => c.json({ chats: chats.list(c.get("actorId")).map(view), followed: chats.threads.followedSummary(c.get("actorId")) }));
688
704
  routes.post("/", jsonBody, async (c) => {
689
705
  const chat = chats.createDm(c.get("actorId"), await readJson(c));
690
706
  return c.json(view(chat), 201);
@@ -772,8 +788,8 @@ async function* idle(body, signal) {
772
788
  timer = setTimeout(() => reject(new HTTPException8(408, { message: "Upload stalled" })), UPLOAD_IDLE_MS);
773
789
  });
774
790
  try {
775
- const { done, value: value2 } = await Promise.race([reader.read(), stalled]);
776
- if (done) return;
791
+ const { done: done2, value: value2 } = await Promise.race([reader.read(), stalled]);
792
+ if (done2) return;
777
793
  yield value2;
778
794
  } finally {
779
795
  clearTimeout(timer);
@@ -842,13 +858,14 @@ function eventStream(c, authenticated, open2) {
842
858
  start(controller) {
843
859
  let ended = false;
844
860
  const encoder = new TextEncoder();
845
- const send = (event, data) => {
861
+ const send = (event, data, id) => {
846
862
  if (ended) return;
847
863
  if ((controller.desiredSize ?? 0) <= 0) {
848
864
  disconnect();
849
865
  return;
850
866
  }
851
- controller.enqueue(encoder.encode(`event: ${event}
867
+ controller.enqueue(encoder.encode(`${id ? `id: ${id}
868
+ ` : ""}event: ${event}
852
869
  data: ${JSON.stringify(data)}
853
870
 
854
871
  `));
@@ -894,19 +911,66 @@ function eventRoutes({ events, account, chats, bots }) {
894
911
  const routes = new Hono7();
895
912
  routes.get("/events", (c) => {
896
913
  const actorId = c.get("actorId"), token = c.get("sessionToken");
897
- return eventStream(c, () => account.authenticated(token), ({ send, close, signedIn }) => ({
898
- unsubscribe: events.subscribe(signedIn((change) => {
899
- if (change.kind === "chat" && chats.get(actorId, change.id)) send("chat", { chatId: change.id });
900
- if (change.kind === "sections" && change.ownerId === actorId) send("sections", {});
901
- if (change.kind === "inbox" && change.memberId === actorId) send("inbox", {});
902
- if (change.kind === "bot" && bots.owns(change.id)) send("bot", { botId: change.id, status: botStatusView(change.status) });
903
- if (change.kind === "bots") send("bots", {});
904
- }), close),
905
- ready: () => send("ready", {})
906
- }));
914
+ const after2 = c.req.header("Last-Event-ID") ?? c.req.query("after");
915
+ const view = (chat) => chatView(chat, (id) => chats.member(id));
916
+ const live = (chatId, followed) => {
917
+ const chat = chats.get(actorId, chatId);
918
+ if (!chat) return null;
919
+ if (chat.type !== "thread") return { chat: view(chat) };
920
+ const parent = chat.parentId ? chats.get(actorId, chat.parentId) : null;
921
+ return { chat: view(chat), ...parent ? { parent: view(parent) } : {}, ...followed || chat.following ? { followed: chats.threads.followedSummary(actorId) } : {} };
922
+ };
923
+ const render = (change) => {
924
+ switch (change.kind) {
925
+ case "message":
926
+ case "message.updated": {
927
+ const message = chats.message(actorId, change.messageId), chat = message ? live(change.chatId, false) : null;
928
+ return message && chat ? [change.kind, { ...chat, message: messageView(message) }] : null;
929
+ }
930
+ // A thread's title, status or summary, or a new one: whether it is followed may have changed too.
931
+ case "chat": {
932
+ const chat = live(change.id, true);
933
+ return chat ? ["chat", chat] : null;
934
+ }
935
+ // Gone with its threads: its owner's pages drop it.
936
+ case "chat.removed":
937
+ return change.ownerId === actorId ? ["chat.removed", { chatId: change.id, followed: chats.threads.followedSummary(actorId) }] : null;
938
+ case "sections":
939
+ return change.ownerId === actorId ? ["sections", {}] : null;
940
+ case "bot": {
941
+ if (!bots.owns(change.id)) return null;
942
+ const done2 = change.status.status === "idle" || change.status.status === "stop";
943
+ return ["bot", { botId: change.id, status: botStatusView(change.status), ...done2 ? { bot: bots.describe(change.id) } : {} }];
944
+ }
945
+ // The agent Bot created, changed or deleted Bots (A48): the page reloads them and its chats.
946
+ case "bots":
947
+ return ["bots", {}];
948
+ }
949
+ };
950
+ return eventStream(c, () => account.authenticated(token), ({ send, close, signedIn }) => {
951
+ const emit = (change, seq2) => {
952
+ const event = render(change);
953
+ if (event) send(event[0], event[1], `${events.run}.${seq2}`);
954
+ };
955
+ return {
956
+ unsubscribe: events.subscribe(signedIn(emit), close),
957
+ ready: () => {
958
+ const [run2 = "", seq2 = ""] = after2?.split(".") ?? [];
959
+ const missed = after2 ? events.since(run2, Number(seq2)) : null;
960
+ for (const { change, seq: seq3 } of once(missed ?? [])) emit(change, seq3);
961
+ send("ready", { resumed: missed !== null }, `${events.run}.${events.seq}`);
962
+ }
963
+ };
964
+ });
907
965
  });
908
966
  return routes;
909
967
  }
968
+ function once(entries2) {
969
+ const key = (change) => change.kind === "message" || change.kind === "message.updated" ? `m:${change.messageId}` : change.kind === "chat" || change.kind === "chat.removed" ? `${change.kind}:${change.id}` : change.kind === "bot" ? `b:${change.id}` : change.kind;
970
+ const fresh = new Set(entries2.flatMap(({ change }) => change.kind === "message" ? [change.messageId] : []));
971
+ const last = new Map(entries2.map(({ change }, index) => [key(change), index]));
972
+ return entries2.filter(({ change }, index) => change.kind === "message" || (change.kind === "message.updated" ? !fresh.has(change.messageId) && last.get(key(change)) === index : last.get(key(change)) === index));
973
+ }
910
974
 
911
975
  // src/server/api/routes/channels.ts
912
976
  import { Hono as Hono8 } from "hono";
@@ -963,7 +1027,12 @@ function channelRoutes({ chats }) {
963
1027
  return c.json(chat(actor, chats.threads.open(actor, c.req.param("id")).id));
964
1028
  });
965
1029
  routes.get("/chats/:id/threads", (c) => c.json({ threads: chats.threads.list(c.get("actorId"), c.req.param("id")).map((entry) => threadView(entry, (id) => chats.member(id))) }));
966
- routes.get("/threads", (c) => c.json({ threads: chats.threads.followed(c.get("actorId")).map((entry) => threadView(entry, (id) => chats.member(id))) }));
1030
+ routes.get("/threads", (c) => {
1031
+ const page2 = chats.threads.followedPage(c.get("actorId"), { filter: c.req.query("filter"), sort: c.req.query("sort"), cursor: c.req.query("cursor"), limit: c.req.query("limit") });
1032
+ const result = { threads: page2.entries.map(threadItemView), next: page2.next };
1033
+ return c.json(result);
1034
+ });
1035
+ routes.get("/threads/:id", (c) => c.json(threadItemView(chats.threads.entry(c.get("actorId"), c.req.param("id")))));
967
1036
  routes.put("/chats/:id/follow", jsonBody, async (c) => {
968
1037
  const actor = c.get("actorId"), id = c.req.param("id");
969
1038
  chats.threads.setFollowing(actor, id, (await readJson(c)).following);
@@ -2664,6 +2733,158 @@ import { randomUUID as randomUUID10 } from "node:crypto";
2664
2733
 
2665
2734
  // src/server/infra/storage/channel-repository.ts
2666
2735
  import { randomUUID as randomUUID8 } from "node:crypto";
2736
+
2737
+ // src/server/shared/delivery.ts
2738
+ var CATEGORY = {
2739
+ message: "message",
2740
+ reaction: "activity",
2741
+ note: "activity",
2742
+ onboard: "system",
2743
+ change: "system",
2744
+ task: "system",
2745
+ followed: "system"
2746
+ };
2747
+
2748
+ // src/server/infra/storage/inbox-repository.ts
2749
+ var HANDED_TO_BOT = "EXISTS(SELECT 1 FROM inbox i JOIN bots b ON b.id=i.member_id WHERE i.member_id=:member AND i.category='message' AND i.message_id=m.id)";
2750
+ var InboxRepository = class {
2751
+ constructor(db, chats) {
2752
+ this.db = db;
2753
+ this.chats = chats;
2754
+ }
2755
+ /** Writes rows inside the caller's transaction. The category comes from the kind, and the CHECKs refuse a chat row
2756
+ * without its chat or a system row with one. */
2757
+ write(entries2) {
2758
+ const insert = this.db.prepare(`INSERT INTO inbox(member_id,category,kind,reason,urgency,chat_id,message_id,actor_id,payload,created_at)
2759
+ VALUES(?,?,?,?,?,?,?,?,?,?)`);
2760
+ for (const { delivery, chatId, messageId, actorId, payload, createdAt } of entries2)
2761
+ insert.run(
2762
+ delivery.member.id,
2763
+ CATEGORY[delivery.kind],
2764
+ delivery.kind,
2765
+ delivery.reason,
2766
+ delivery.urgency,
2767
+ chatId,
2768
+ messageId,
2769
+ actorId,
2770
+ payload === null ? null : JSON.stringify(payload),
2771
+ createdAt
2772
+ );
2773
+ }
2774
+ /** A mark removed before it was told takes its row back. */
2775
+ withdrawReaction(messageId, actorId, emoji) {
2776
+ this.db.prepare(`DELETE FROM inbox WHERE message_id=? AND actor_id=? AND kind='reaction' AND state='pending' AND json_extract(payload,'$.emoji')=?`).run(messageId, actorId, emoji);
2777
+ }
2778
+ /** A task deleted before its Bot was told it is due takes its pending notice with it (A58): there is nothing left to
2779
+ * run, and the row would otherwise be carried into every later run. */
2780
+ cancelTaskNotice(taskId) {
2781
+ this.db.prepare(`DELETE FROM inbox WHERE category='system' AND kind='task' AND state='pending' AND json_extract(payload,'$.task')=?`).run(taskId);
2782
+ }
2783
+ /** A deleted member's rows go with it. */
2784
+ forget(memberId) {
2785
+ this.db.prepare("DELETE FROM inbox WHERE member_id=?").run(memberId);
2786
+ }
2787
+ // A Bot's messages, claimed by its runs.
2788
+ /** Bots with deliveries still waiting at startup, each with the most urgent of them (A41). */
2789
+ waitingBots(ownerId) {
2790
+ return this.db.prepare(`SELECT i.member_id AS botId,CASE WHEN SUM(i.urgency='interrupt')>0 THEN 'interrupt' ELSE 'queue' END AS urgency
2791
+ FROM inbox i JOIN bots b ON b.id=i.member_id WHERE b.owner_id=? AND b.deleted_at IS NULL AND i.state='pending' AND i.urgency IN ('interrupt','queue')
2792
+ GROUP BY i.member_id ORDER BY i.member_id`).all(ownerId);
2793
+ }
2794
+ hasPendingMessages(botId) {
2795
+ return !!this.db.prepare("SELECT 1 FROM inbox WHERE member_id=? AND category='message' AND state='pending' LIMIT 1").get(botId);
2796
+ }
2797
+ /** Inside a claim: messages in chats the Bot can no longer read are cancelled, the rest are listed in order. Each
2798
+ * pending message is looked up by its id, not checked against every message the Bot can read. */
2799
+ pendingMessages(botId) {
2800
+ this.db.prepare(`UPDATE inbox SET state='cancelled' WHERE member_id=? AND category='message' AND state='pending' AND NOT EXISTS
2801
+ (SELECT 1 FROM messages m JOIN chats c ON c.id=m.chat_id
2802
+ JOIN chat_members cm ON cm.chat_id=COALESCE(c.parent_id,c.id) AND cm.member_id=? AND cm.can_read=1 WHERE m.id=inbox.message_id)`).run(botId, botId);
2803
+ return this.db.prepare(`SELECT chat_id AS chatId,message_id AS messageId FROM inbox
2804
+ WHERE member_id=? AND category='message' AND state='pending' ORDER BY id`).all(botId);
2805
+ }
2806
+ claimMessages(botId, runId) {
2807
+ this.db.prepare("UPDATE inbox SET state='claimed',run_id=? WHERE member_id=? AND category='message' AND state='pending'").run(runId, botId);
2808
+ }
2809
+ /** The run ended: its messages take its outcome. */
2810
+ settleRun(runId, state) {
2811
+ this.db.prepare("UPDATE inbox SET state=? WHERE run_id=?").run(state, runId);
2812
+ }
2813
+ /** A run that never reached the model gives its messages back. */
2814
+ releaseRun(runId) {
2815
+ this.db.prepare("UPDATE inbox SET state='pending',run_id=NULL WHERE run_id=? AND state='claimed'").run(runId);
2816
+ }
2817
+ /** At start, inside the caller's transaction and before the runs are marked: claimed rows go back to pending, rows of
2818
+ * runs that reached the model are unknown. */
2819
+ recover() {
2820
+ this.db.exec(`UPDATE inbox SET state='pending',run_id=NULL WHERE run_id IN (SELECT id FROM bot_runs WHERE state='claimed');
2821
+ UPDATE inbox SET state='unknown' WHERE run_id IN (SELECT id FROM bot_runs WHERE state='submitted');`);
2822
+ }
2823
+ // A Bot's other deliveries, told once.
2824
+ /** Not told yet, oldest first: activity in chats the Bot can still read, and its system notices. */
2825
+ notices(botId) {
2826
+ const rows3 = this.db.prepare(`SELECT n.id,n.kind,n.urgency,n.chat_id AS chatId,c.title AS chatTitle,c.type AS chatType,n.message_id AS messageId,
2827
+ n.actor_id AS actorId,n.payload,n.created_at AS createdAt
2828
+ FROM inbox n LEFT JOIN chats c ON c.id=n.chat_id WHERE n.member_id=? AND n.category<>'message' AND n.state='pending' ORDER BY n.id`).all(botId);
2829
+ return rows3.filter((row) => row.chatId === null || this.chats.canAccess(botId, row.chatId)).map((row) => ({
2830
+ id: row.id,
2831
+ kind: row.kind,
2832
+ urgency: row.urgency,
2833
+ createdAt: row.createdAt,
2834
+ actor: row.actorId ? this.chats.member(row.actorId) : null,
2835
+ payload: row.payload === null ? null : JSON.parse(row.payload),
2836
+ messageId: row.messageId,
2837
+ chat: row.chatId === null ? null : { id: row.chatId, type: row.chatType, title: row.chatTitle ?? "" }
2838
+ }));
2839
+ }
2840
+ /** These notices reached the Bot (steered into its run, or in a batch it was given). A new notice version told
2841
+ * here does not count as read (A67): the text is what a compaction loses. */
2842
+ tell(botId, ids) {
2843
+ const now = Date.now();
2844
+ for (const id of ids) this.db.prepare("UPDATE inbox SET state='told',told_at=? WHERE id=? AND member_id=? AND state='pending'").run(now, id, botId);
2845
+ }
2846
+ // A person's rows: what their chat list shows.
2847
+ /** What a person's chat row shows (A41): unread interrupt messages, and the newest queued activity. */
2848
+ rowState(memberId, chatId) {
2849
+ const counts = this.db.prepare(`SELECT count(*) AS n,COALESCE(SUM(reason IN ('mention','reply')),0) AS at FROM inbox
2850
+ WHERE member_id=? AND chat_id=? AND category='message' AND urgency='interrupt' AND state='pending'`).get(memberId, chatId);
2851
+ const row = this.db.prepare(`SELECT i.kind,i.chat_id AS chatId,c.type AS chatType,c.title,i.actor_id AS actorId,i.payload,i.created_at AS createdAt
2852
+ FROM inbox i JOIN chats c ON c.id=i.chat_id
2853
+ WHERE i.member_id=? AND i.category='activity' AND i.urgency='queue' AND i.state='pending' AND (i.chat_id=? OR c.parent_id=?) ORDER BY i.id DESC LIMIT 1`).get(memberId, chatId, chatId);
2854
+ if (!row) return { alerts: counts.n, atMe: counts.at > 0, hint: null };
2855
+ const payload = row.payload ? JSON.parse(row.payload) : {};
2856
+ const detail = row.kind === "reaction" ? payload.emoji ?? "" : String(payload.version ?? "");
2857
+ return { alerts: counts.n, atMe: counts.at > 0, hint: {
2858
+ kind: row.kind,
2859
+ chatId: row.chatId,
2860
+ chatType: row.chatType,
2861
+ title: row.title,
2862
+ actor: row.actorId && this.chats.member(row.actorId)?.name || "",
2863
+ detail,
2864
+ createdAt: row.createdAt
2865
+ } };
2866
+ }
2867
+ /** A person read up to `sequence` in a chat: the messages delivered to them there are told. */
2868
+ readUpTo(memberId, chatId, sequence) {
2869
+ this.db.prepare(`UPDATE inbox SET state='told',told_at=? WHERE member_id=? AND category='message' AND state='pending'
2870
+ AND chat_id=? AND message_id IN (SELECT id FROM messages WHERE chat_id=? AND sequence<=?)`).run(Date.now(), memberId, chatId, chatId, sequence);
2871
+ }
2872
+ /** A person opened a chat: its queued activity (and its threads', for a channel) counts as seen. */
2873
+ seenIn(memberId, chatId) {
2874
+ this.db.prepare(`UPDATE inbox SET state='told',told_at=? WHERE member_id=? AND category='activity' AND state='pending'
2875
+ AND chat_id IN (SELECT id FROM chats WHERE id=? OR parent_id=?)`).run(Date.now(), memberId, chatId, chatId);
2876
+ }
2877
+ };
2878
+
2879
+ // src/server/infra/storage/unread.ts
2880
+ var unreadIn = (chat) => `FROM messages m WHERE m.chat_id=${chat} AND m.sender_id<>:member
2881
+ AND m.sequence>COALESCE((SELECT read_sequence FROM chat_states WHERE chat_id=${chat} AND member_id=:member),0)
2882
+ AND NOT ${HANDED_TO_BOT}
2883
+ AND NOT (m.echo_of IS NOT NULL AND EXISTS(SELECT 1 FROM chat_states f WHERE f.chat_id=m.echo_of AND f.member_id=:member AND f.following=1))`;
2884
+ var mentionsIn = (chat) => `${unreadIn(chat)} AND ((SELECT type FROM chats WHERE id=${chat})='dm'
2885
+ OR EXISTS(SELECT 1 FROM message_mentions mm WHERE mm.message_id=m.id AND mm.member_id=:member))`;
2886
+
2887
+ // src/server/infra/storage/channel-repository.ts
2667
2888
  var SECTION_COLUMNS = "id,name,position,created_at AS createdAt,updated_at AS updatedAt";
2668
2889
  var ChannelRepository = class {
2669
2890
  constructor(db, chats) {
@@ -2830,21 +3051,17 @@ var ChannelRepository = class {
2830
3051
  JOIN chat_members cm ON cm.chat_id=COALESCE(c.parent_id,c.id) AND cm.member_id=:member AND cm.can_read=1
2831
3052
  ORDER BY c.updated_at DESC,c.id`).all({ member: memberId }).map((row) => row.id);
2832
3053
  }
2833
- /** Chats a member belongs to: DMs, channels, and the threads it follows. */
2834
- memberChats(memberId) {
2835
- return this.db.prepare(`SELECT c.id,c.type,c.title,c.updated_at FROM chats c JOIN chat_members cm ON cm.chat_id=c.id
2836
- WHERE cm.member_id=:member AND cm.can_read=1
2837
- UNION SELECT c.id,c.type,c.title,c.updated_at FROM chats c JOIN chat_states s ON s.chat_id=c.id AND s.member_id=:member AND s.following=1
2838
- JOIN chat_members cm ON cm.chat_id=c.parent_id AND cm.member_id=:member AND cm.can_read=1 WHERE c.type='thread'
2839
- ORDER BY 4 DESC,1`).all({ member: memberId });
2840
- }
2841
- /** For a Bot's batch (A37): its unread counts. New notice / summary versions are delivered (A41). */
3054
+ /** For a Bot's batch and `messages.read unread=true` (A37, A70): its chats with unread, most recently active first —
3055
+ * DMs, channels, and the threads it follows while they are open. A finished thread stays out of this overview,
3056
+ * whatever is unread in it. One statement, by the rule a chat's own count follows. */
2842
3057
  digest(botId) {
2843
- const unread = [];
2844
- for (const chat of this.memberChats(botId)) {
2845
- const count2 = this.chats.unread(botId, chat.id).unread;
2846
- if (count2) unread.push({ chatId: chat.id, title: chat.title, type: chat.type, count: count2 });
2847
- }
3058
+ const count2 = `(SELECT count(*) ${unreadIn("c.id")}) AS count`;
3059
+ const unread = this.db.prepare(`SELECT chatId,type,title,count FROM (
3060
+ SELECT c.id AS chatId,c.type,c.title,c.updated_at AS at,${count2} FROM chats c JOIN chat_members cm ON cm.chat_id=c.id
3061
+ WHERE cm.member_id=:member AND cm.can_read=1
3062
+ UNION ALL SELECT c.id,c.type,c.title,c.updated_at,${count2} FROM chats c JOIN chat_states s ON s.chat_id=c.id AND s.member_id=:member AND s.following=1
3063
+ JOIN chat_members cm ON cm.chat_id=c.parent_id AND cm.member_id=:member AND cm.can_read=1 WHERE c.type='thread' AND c.status IS NOT 'done')
3064
+ WHERE count>0 ORDER BY at DESC,chatId`).all({ member: botId });
2848
3065
  return { unread };
2849
3066
  }
2850
3067
  };
@@ -2863,6 +3080,9 @@ function threadTitle(content2, names, file = "") {
2863
3080
  }
2864
3081
  return (rest.trim() || line || file).slice(0, 60);
2865
3082
  }
3083
+ var FOLLOWED = `FROM chats c JOIN chat_states s ON s.chat_id=c.id AND s.member_id=:member AND s.following=1
3084
+ JOIN chat_members cm ON cm.chat_id=c.parent_id AND cm.member_id=:member AND cm.can_read=1
3085
+ WHERE c.type='thread' AND EXISTS(SELECT 1 FROM messages WHERE chat_id=c.id)`;
2866
3086
  var ThreadRepository = class {
2867
3087
  constructor(db, chats) {
2868
3088
  this.db = db;
@@ -2918,14 +3138,19 @@ var ThreadRepository = class {
2918
3138
  }
2919
3139
  /** Threads the member follows in channels it can still read (with at least one reply). */
2920
3140
  followed(memberId) {
2921
- return this.db.prepare(`SELECT c.id FROM chats c JOIN chat_states s ON s.chat_id=c.id AND s.member_id=:member AND s.following=1
2922
- JOIN chat_members cm ON cm.chat_id=c.parent_id AND cm.member_id=:member AND cm.can_read=1
2923
- WHERE c.type='thread' AND EXISTS(SELECT 1 FROM messages WHERE chat_id=c.id) ORDER BY c.updated_at DESC,c.id`).all({ member: memberId }).map((row) => row.id);
3141
+ return this.db.prepare(`SELECT c.id ${FOLLOWED} ORDER BY c.updated_at DESC,c.id`).all({ member: memberId }).map((row) => row.id);
3142
+ }
3143
+ /** The same threads with what orders, filters and counts them (A69): status, creation, last reply, and the member's
3144
+ * unread and @ counts by the rule a chat's own count follows, in one statement however many there are. */
3145
+ followedKeys(memberId) {
3146
+ return this.db.prepare(`SELECT c.id,c.status,c.created_at AS createdAt,
3147
+ (SELECT created_at FROM messages WHERE chat_id=c.id ORDER BY sequence DESC LIMIT 1) AS lastReplyAt,
3148
+ (SELECT count(*) ${unreadIn("c.id")}) AS unread,(SELECT count(*) ${mentionsIn("c.id")}) AS mentions ${FOLLOWED}`).all({ member: memberId });
2924
3149
  }
2925
3150
  /** The thread under a channel message, for the "N 条回复" line. */
2926
3151
  info(rootMessageId) {
2927
3152
  return this.db.prepare(`SELECT c.id,c.title,c.status,(SELECT count(*) FROM messages WHERE chat_id=c.id) AS replies,
2928
- (SELECT MAX(created_at) FROM messages WHERE chat_id=c.id) AS lastReplyAt FROM chats c WHERE c.root_message_id=?`).get(rootMessageId) ?? null;
3153
+ (SELECT created_at FROM messages WHERE chat_id=c.id ORDER BY sequence DESC LIMIT 1) AS lastReplyAt FROM chats c WHERE c.root_message_id=?`).get(rootMessageId) ?? null;
2929
3154
  }
2930
3155
  assertThread(actorId, threadId, write2 = false) {
2931
3156
  this.chats.assertAccess(actorId, threadId, write2);
@@ -3002,141 +3227,6 @@ var QuoteRepository = class {
3002
3227
  }
3003
3228
  };
3004
3229
 
3005
- // src/server/shared/delivery.ts
3006
- var CATEGORY = {
3007
- message: "message",
3008
- reaction: "activity",
3009
- note: "activity",
3010
- onboard: "system",
3011
- change: "system",
3012
- task: "system"
3013
- };
3014
-
3015
- // src/server/infra/storage/inbox-repository.ts
3016
- var HANDED_TO_BOT = "EXISTS(SELECT 1 FROM inbox i JOIN bots b ON b.id=i.member_id WHERE i.member_id=:member AND i.category='message' AND i.message_id=m.id)";
3017
- var InboxRepository = class {
3018
- constructor(db, chats) {
3019
- this.db = db;
3020
- this.chats = chats;
3021
- }
3022
- /** Writes rows inside the caller's transaction. The category comes from the kind, and the CHECKs refuse a chat row
3023
- * without its chat or a system row with one. */
3024
- write(entries2) {
3025
- const insert = this.db.prepare(`INSERT INTO inbox(member_id,category,kind,reason,urgency,chat_id,message_id,actor_id,payload,created_at)
3026
- VALUES(?,?,?,?,?,?,?,?,?,?)`);
3027
- for (const { delivery, chatId, messageId, actorId, payload, createdAt } of entries2)
3028
- insert.run(
3029
- delivery.member.id,
3030
- CATEGORY[delivery.kind],
3031
- delivery.kind,
3032
- delivery.reason,
3033
- delivery.urgency,
3034
- chatId,
3035
- messageId,
3036
- actorId,
3037
- payload === null ? null : JSON.stringify(payload),
3038
- createdAt
3039
- );
3040
- }
3041
- /** A mark removed before it was told takes its row back. */
3042
- withdrawReaction(messageId, actorId, emoji) {
3043
- this.db.prepare(`DELETE FROM inbox WHERE message_id=? AND actor_id=? AND kind='reaction' AND state='pending' AND json_extract(payload,'$.emoji')=?`).run(messageId, actorId, emoji);
3044
- }
3045
- /** A deleted member's rows go with it. */
3046
- forget(memberId) {
3047
- this.db.prepare("DELETE FROM inbox WHERE member_id=?").run(memberId);
3048
- }
3049
- // A Bot's messages, claimed by its runs.
3050
- /** Bots with deliveries still waiting at startup, each with the most urgent of them (A41). */
3051
- waitingBots(ownerId) {
3052
- return this.db.prepare(`SELECT i.member_id AS botId,CASE WHEN SUM(i.urgency='interrupt')>0 THEN 'interrupt' ELSE 'queue' END AS urgency
3053
- FROM inbox i JOIN bots b ON b.id=i.member_id WHERE b.owner_id=? AND b.deleted_at IS NULL AND i.state='pending' AND i.urgency IN ('interrupt','queue')
3054
- GROUP BY i.member_id ORDER BY i.member_id`).all(ownerId);
3055
- }
3056
- hasPendingMessages(botId) {
3057
- return !!this.db.prepare("SELECT 1 FROM inbox WHERE member_id=? AND category='message' AND state='pending' LIMIT 1").get(botId);
3058
- }
3059
- /** Inside a claim: messages in chats the Bot can no longer read are cancelled, the rest are listed in order. */
3060
- pendingMessages(botId) {
3061
- this.db.prepare(`UPDATE inbox SET state='cancelled' WHERE member_id=? AND category='message' AND state='pending' AND message_id NOT IN
3062
- (SELECT m.id FROM messages m JOIN chats c ON c.id=m.chat_id
3063
- JOIN chat_members cm ON cm.chat_id=COALESCE(c.parent_id,c.id) AND cm.member_id=? AND cm.can_read=1)`).run(botId, botId);
3064
- return this.db.prepare(`SELECT chat_id AS chatId,message_id AS messageId FROM inbox
3065
- WHERE member_id=? AND category='message' AND state='pending' ORDER BY id`).all(botId);
3066
- }
3067
- claimMessages(botId, runId) {
3068
- this.db.prepare("UPDATE inbox SET state='claimed',run_id=? WHERE member_id=? AND category='message' AND state='pending'").run(runId, botId);
3069
- }
3070
- /** The run ended: its messages take its outcome. */
3071
- settleRun(runId, state) {
3072
- this.db.prepare("UPDATE inbox SET state=? WHERE run_id=?").run(state, runId);
3073
- }
3074
- /** A run that never reached the model gives its messages back. */
3075
- releaseRun(runId) {
3076
- this.db.prepare("UPDATE inbox SET state='pending',run_id=NULL WHERE run_id=? AND state='claimed'").run(runId);
3077
- }
3078
- /** At start, inside the caller's transaction and before the runs are marked: claimed rows go back to pending, rows of
3079
- * runs that reached the model are unknown. */
3080
- recover() {
3081
- this.db.exec(`UPDATE inbox SET state='pending',run_id=NULL WHERE run_id IN (SELECT id FROM bot_runs WHERE state='claimed');
3082
- UPDATE inbox SET state='unknown' WHERE run_id IN (SELECT id FROM bot_runs WHERE state='submitted');`);
3083
- }
3084
- // A Bot's other deliveries, told once.
3085
- /** Not told yet, oldest first: activity in chats the Bot can still read, and its system notices. */
3086
- notices(botId) {
3087
- const rows3 = this.db.prepare(`SELECT n.id,n.kind,n.urgency,n.chat_id AS chatId,c.title AS chatTitle,c.type AS chatType,n.message_id AS messageId,
3088
- n.actor_id AS actorId,n.payload,n.created_at AS createdAt
3089
- FROM inbox n LEFT JOIN chats c ON c.id=n.chat_id WHERE n.member_id=? AND n.category<>'message' AND n.state='pending' ORDER BY n.id`).all(botId);
3090
- return rows3.filter((row) => row.chatId === null || this.chats.canAccess(botId, row.chatId)).map((row) => ({
3091
- id: row.id,
3092
- kind: row.kind,
3093
- urgency: row.urgency,
3094
- createdAt: row.createdAt,
3095
- actor: row.actorId ? this.chats.member(row.actorId) : null,
3096
- payload: row.payload === null ? null : JSON.parse(row.payload),
3097
- messageId: row.messageId,
3098
- chat: row.chatId === null ? null : { id: row.chatId, type: row.chatType, title: row.chatTitle ?? "" }
3099
- }));
3100
- }
3101
- /** These notices reached the Bot (steered into its run, or in a batch it was given). A new notice version told
3102
- * here does not count as read (A67): the text is what a compaction loses. */
3103
- tell(botId, ids) {
3104
- const now = Date.now();
3105
- for (const id of ids) this.db.prepare("UPDATE inbox SET state='told',told_at=? WHERE id=? AND member_id=? AND state='pending'").run(now, id, botId);
3106
- }
3107
- // A person's rows: what their chat list shows.
3108
- /** What a person's chat row shows (A41): unread interrupt messages, and the newest queued activity. */
3109
- rowState(memberId, chatId) {
3110
- const counts = this.db.prepare(`SELECT count(*) AS n,COALESCE(SUM(reason IN ('mention','reply')),0) AS at FROM inbox
3111
- WHERE member_id=? AND chat_id=? AND category='message' AND urgency='interrupt' AND state='pending'`).get(memberId, chatId);
3112
- const row = this.db.prepare(`SELECT i.kind,i.chat_id AS chatId,c.type AS chatType,c.title,i.actor_id AS actorId,i.payload,i.created_at AS createdAt
3113
- FROM inbox i JOIN chats c ON c.id=i.chat_id
3114
- WHERE i.member_id=? AND i.category='activity' AND i.urgency='queue' AND i.state='pending' AND (i.chat_id=? OR c.parent_id=?) ORDER BY i.id DESC LIMIT 1`).get(memberId, chatId, chatId);
3115
- if (!row) return { alerts: counts.n, atMe: counts.at > 0, hint: null };
3116
- const payload = row.payload ? JSON.parse(row.payload) : {};
3117
- const detail = row.kind === "reaction" ? payload.emoji ?? "" : String(payload.version ?? "");
3118
- return { alerts: counts.n, atMe: counts.at > 0, hint: {
3119
- kind: row.kind,
3120
- chatId: row.chatId,
3121
- chatType: row.chatType,
3122
- title: row.title,
3123
- actor: row.actorId && this.chats.member(row.actorId)?.name || "",
3124
- detail,
3125
- createdAt: row.createdAt
3126
- } };
3127
- }
3128
- /** A person read up to `sequence` in a chat: the messages delivered to them there are told. */
3129
- readUpTo(memberId, chatId, sequence) {
3130
- this.db.prepare(`UPDATE inbox SET state='told',told_at=? WHERE member_id=? AND category='message' AND state='pending'
3131
- AND chat_id=? AND message_id IN (SELECT id FROM messages WHERE chat_id=? AND sequence<=?)`).run(Date.now(), memberId, chatId, chatId, sequence);
3132
- }
3133
- /** A person opened a chat: its queued activity (and its threads', for a channel) counts as seen. */
3134
- seenIn(memberId, chatId) {
3135
- this.db.prepare(`UPDATE inbox SET state='told',told_at=? WHERE member_id=? AND category='activity' AND state='pending'
3136
- AND chat_id IN (SELECT id FROM chats WHERE id=? OR parent_id=?)`).run(Date.now(), memberId, chatId, chatId);
3137
- }
3138
- };
3139
-
3140
3230
  // src/server/infra/storage/chat-repository.ts
3141
3231
  var MESSAGE_COLUMNS = "id,chat_id AS chatId,sequence,sender_id AS senderId,content,created_at AS createdAt,history_id AS historyId,tool_call_id AS toolCallId,question,echo_of AS echoOf,reply_to AS replyTo,folded_at AS foldedAt";
3142
3232
  var CHAT_COLUMNS = `c.id,c.type,c.title,c.owner_id AS ownerId,c.created_at AS createdAt,c.updated_at AS updatedAt,
@@ -3145,10 +3235,6 @@ var CHAT_COLUMNS = `c.id,c.type,c.title,c.owner_id AS ownerId,c.created_at AS cr
3145
3235
  (SELECT id FROM messages WHERE chat_id=c.id ORDER BY sequence DESC LIMIT 1) AS lastMessageId,
3146
3236
  (SELECT COALESCE(a.username,b.name) FROM messages m LEFT JOIN account a ON a.member_id=m.sender_id LEFT JOIN bots b ON b.id=m.sender_id
3147
3237
  WHERE m.chat_id=c.id ORDER BY m.sequence DESC LIMIT 1) AS lastSender`;
3148
- var UNREAD = `FROM messages m WHERE m.chat_id=:chat AND m.sender_id<>:member
3149
- AND m.sequence>COALESCE((SELECT read_sequence FROM chat_states WHERE chat_id=:chat AND member_id=:member),0)
3150
- AND NOT ${HANDED_TO_BOT}
3151
- AND NOT (m.echo_of IS NOT NULL AND EXISTS(SELECT 1 FROM chat_states f WHERE f.chat_id=m.echo_of AND f.member_id=:member AND f.following=1))`;
3152
3238
  var ChatRepository = class {
3153
3239
  constructor(db) {
3154
3240
  this.db = db;
@@ -3186,9 +3272,8 @@ var ChatRepository = class {
3186
3272
  const read4 = this.db.prepare("SELECT read_sequence AS n FROM chat_states WHERE chat_id=? AND member_id=?").get(chatId, memberId);
3187
3273
  return { unread: 0, mentions: 0, readSequence: read4?.n ?? 0 };
3188
3274
  }
3189
- const unread = this.db.prepare(`SELECT count(*) AS n ${UNREAD}`).get(params).n;
3190
- const mentions = this.db.prepare(`SELECT count(*) AS n ${UNREAD} AND ((SELECT type FROM chats WHERE id=:chat)='dm'
3191
- OR EXISTS(SELECT 1 FROM message_mentions mm WHERE mm.message_id=m.id AND mm.member_id=:member))`).get(params).n;
3275
+ const unread = this.db.prepare(`SELECT count(*) AS n ${unreadIn(":chat")}`).get(params).n;
3276
+ const mentions = this.db.prepare(`SELECT count(*) AS n ${mentionsIn(":chat")}`).get(params).n;
3192
3277
  const read3 = this.db.prepare("SELECT read_sequence AS n FROM chat_states WHERE chat_id=? AND member_id=?").get(chatId, memberId);
3193
3278
  return { unread, mentions, readSequence: read3?.n ?? 0 };
3194
3279
  }
@@ -3287,7 +3372,7 @@ var ChatRepository = class {
3287
3372
  unreadMessages(memberId, chatId, limit) {
3288
3373
  this.assertAccess(memberId, chatId);
3289
3374
  if (this.db.prepare("SELECT type FROM chats WHERE id=?").get(chatId).type === "thread" && !this.threads.isFollowing(memberId, chatId)) return [];
3290
- const rows3 = this.db.prepare(`SELECT ${MESSAGE_COLUMNS.split(",").map((column) => `m.${column}`).join(",")} ${UNREAD} ORDER BY m.sequence LIMIT :limit`).all({ chat: chatId, member: memberId, limit });
3375
+ const rows3 = this.db.prepare(`SELECT ${MESSAGE_COLUMNS.split(",").map((column) => `m.${column}`).join(",")} ${unreadIn(":chat")} ORDER BY m.sequence LIMIT :limit`).all({ chat: chatId, member: memberId, limit });
3291
3376
  return rows3.map((row) => this.messageFromRow(row));
3292
3377
  }
3293
3378
  /** Search every chat the member can read: its DMs and channels and their threads (newest first). `within` keeps
@@ -4052,10 +4137,15 @@ var TaskRepository = class {
4052
4137
  this.db.prepare("UPDATE tasks SET state=?,next_run_at=?,updated_at=? WHERE id=? AND bot_id=?").run(state, next, now, id, botId);
4053
4138
  return this.get(botId, id);
4054
4139
  }
4055
- /** Gone from the lists and from the scheduler; the row stays for the record. */
4140
+ /** Gone from the lists and from the scheduler; the row stays for the record, and a notice of a run that is still
4141
+ * waiting to be told goes with it (A58). */
4056
4142
  remove(botId, id) {
4057
4143
  const now = Date.now();
4058
- return Number(this.db.prepare("UPDATE tasks SET deleted_at=?,next_run_at=NULL,updated_at=? WHERE id=? AND bot_id=? AND deleted_at IS NULL").run(now, now, id, botId).changes) > 0;
4144
+ return transaction(this.db, () => {
4145
+ if (!Number(this.db.prepare("UPDATE tasks SET deleted_at=?,next_run_at=NULL,updated_at=? WHERE id=? AND bot_id=? AND deleted_at IS NULL").run(now, now, id, botId).changes)) return false;
4146
+ this.inbox.cancelTaskNotice(id);
4147
+ return true;
4148
+ });
4059
4149
  }
4060
4150
  /** The soonest time any task runs; the scheduler sleeps until then. Null when nothing is scheduled. */
4061
4151
  soonest() {
@@ -4567,8 +4657,8 @@ function capabilities(model) {
4567
4657
  function thinkingOptions(model) {
4568
4658
  return { levels: getSupportedThinkingLevels(capabilities(model)) };
4569
4659
  }
4570
- function resolveThinking(model, choice) {
4571
- return clampThinkingLevel(capabilities(model), choice === "auto" ? PI_DEFAULT_THINKING : choice);
4660
+ function resolveThinking(model, choice2) {
4661
+ return clampThinkingLevel(capabilities(model), choice2 === "auto" ? PI_DEFAULT_THINKING : choice2);
4572
4662
  }
4573
4663
 
4574
4664
  // src/server/infra/pi/autoconfig.ts
@@ -4642,10 +4732,10 @@ function matched(row, api, alternatives, reseller) {
4642
4732
  alternatives: alternatives.filter((item) => item !== row).slice(0, 8).map(source)
4643
4733
  };
4644
4734
  }
4645
- function autoconfigure(providers, modelId, api, choice) {
4735
+ function autoconfigure(providers, modelId, api, choice2) {
4646
4736
  const all = rows(providers), hits = candidates(all, modelId);
4647
- if (choice) {
4648
- const row = all.find((item) => item.provider === choice.provider && item.model.id === choice.modelId);
4737
+ if (choice2) {
4738
+ const row = all.find((item) => item.provider === choice2.provider && item.model.id === choice2.modelId);
4649
4739
  if (row) return matched(row, api, hits, row.official < 2);
4650
4740
  }
4651
4741
  if (!hits.length) {
@@ -4832,14 +4922,14 @@ var ModelService = class {
4832
4922
  const text4 = (value2) => typeof value2 === "string" && value2.trim() && value2.length <= 200 ? value2.trim() : null;
4833
4923
  const modelId = text4(input.modelId), api = text4(input.api);
4834
4924
  if (!modelId || !api) throw new RuntimeFault("autoconfig_model", "Enter the model ID.", 400);
4835
- let choice;
4925
+ let choice2;
4836
4926
  if (input.choice !== void 0) {
4837
4927
  const raw = input.choice;
4838
4928
  const provider = text4(raw?.provider), chosen = text4(raw?.modelId);
4839
4929
  if (!provider || !chosen) throw new RuntimeFault("autoconfig_source", "The setup source isn't valid.", 400);
4840
- choice = { provider, modelId: chosen };
4930
+ choice2 = { provider, modelId: chosen };
4841
4931
  }
4842
- return autoconfigure(this.models.providers(), modelId, api, choice);
4932
+ return autoconfigure(this.models.providers(), modelId, api, choice2);
4843
4933
  }
4844
4934
  options() {
4845
4935
  return this.list().filter((connection) => connection.models.length).map((connection) => ({
@@ -4978,20 +5068,12 @@ var Member = class {
4978
5068
  }
4979
5069
  };
4980
5070
  var User = class extends Member {
4981
- constructor(id, post, chatChanged, inboxChanged = () => {
4982
- }) {
5071
+ constructor(id, post) {
4983
5072
  super(id);
4984
5073
  this.post = post;
4985
- this.chatChanged = chatChanged;
4986
- this.inboxChanged = inboxChanged;
4987
5074
  }
4988
5075
  kind = "user";
4989
- deliver(urgency) {
4990
- this.inboxChanged(urgency);
4991
- }
4992
- /** A chat this person can see was saved. */
4993
- changed(chatId) {
4994
- this.chatChanged(chatId);
5076
+ deliver() {
4995
5077
  }
4996
5078
  send(chatId, message) {
4997
5079
  return this.post(this.id, chatId, message);
@@ -5065,7 +5147,9 @@ var POLICY = {
5065
5147
  change: { agent: "digest", owner: "digest", move: "interrupt" },
5066
5148
  // A task that is due wakes its Bot but never interrupts it, and is not steered into a running turn: it waits for
5067
5149
  // the turn to end (A58).
5068
- task: { schedule: "queue" }
5150
+ task: { schedule: "queue" },
5151
+ // After a compaction, the open threads a Bot follows ride along with its next batch, without waking it (A73).
5152
+ followed: { compaction: "digest" }
5069
5153
  };
5070
5154
  function urgencyOf(kind, reason) {
5071
5155
  return POLICY[kind][reason];
@@ -5154,7 +5238,7 @@ var Chat = class {
5154
5238
  const saved = await this.messages.append(sender, message, deliveries, mentions);
5155
5239
  if (!saved.duplicate) {
5156
5240
  this.members.notify(saved.message, deliveries.message);
5157
- if (saved.echo && deliveries.echo.length) this.members.notify(saved.echo, deliveries.echo);
5241
+ if (saved.echo) this.members.notify(saved.echo, deliveries.echo);
5158
5242
  }
5159
5243
  return saved.message;
5160
5244
  }
@@ -5347,7 +5431,7 @@ var ChatQuestions = class {
5347
5431
  return new Promise((resolve5, reject) => {
5348
5432
  const stop = () => {
5349
5433
  this.waiting.delete(message.id);
5350
- if (this.repository.settleQuestion(message.id, "ignored", null)) this.changed(message.chatId);
5434
+ if (this.repository.settleQuestion(message.id, "ignored", null)) this.changed(message.chatId, message.id);
5351
5435
  reject(signal.reason ?? new DOMException("Aborted", "AbortError"));
5352
5436
  };
5353
5437
  if (signal?.aborted) {
@@ -5373,7 +5457,7 @@ var ChatQuestions = class {
5373
5457
  const question = message.question, waiter = this.waiting.get(messageId);
5374
5458
  if (question.state !== "pending") throw new ChatError(409, "The question is already settled", "question_closed");
5375
5459
  if (!waiter) {
5376
- if (this.repository.settleQuestion(messageId, "ignored", null)) this.changed(chatId);
5460
+ if (this.repository.settleQuestion(messageId, "ignored", null)) this.changed(chatId, messageId);
5377
5461
  throw new ChatError(409, "The question is no longer waiting for an answer", "question_expired");
5378
5462
  }
5379
5463
  const dismissed = input.action === "dismiss";
@@ -5382,7 +5466,7 @@ var ChatQuestions = class {
5382
5466
  if (!this.repository.settleQuestion(messageId, dismissed ? "dismissed" : "answered", answer)) throw new ChatError(409, "The question is already settled", "question_closed");
5383
5467
  this.waiting.delete(messageId);
5384
5468
  waiter(answer ? resultOf(question, answer) : { status: "dismissed" });
5385
- this.changed(chatId);
5469
+ this.changed(chatId, messageId);
5386
5470
  return this.repository.message(actorId, messageId);
5387
5471
  }
5388
5472
  };
@@ -5511,9 +5595,12 @@ var ChatChannels = class {
5511
5595
  });
5512
5596
  return this.store.unreadNotes(memberId, [...chatIds, ...parents]);
5513
5597
  }
5598
+ /** A person's read position is a change to their row, on their other pages too (A72); a Bot's is its own business. */
5514
5599
  markRead(actorId, chatId, sequence) {
5515
5600
  if (!Number.isSafeInteger(sequence) || sequence < 0) throw new ChatError(400, "Invalid read position");
5516
- return this.store.markRead(actorId, chatId, sequence);
5601
+ const read3 = this.store.markRead(actorId, chatId, sequence);
5602
+ if (this.repository.member(actorId)?.kind === "user") this.saved(chatId);
5603
+ return read3;
5517
5604
  }
5518
5605
  digest(botId) {
5519
5606
  return this.store.digest(botId);
@@ -5536,11 +5623,23 @@ var ChatChannels = class {
5536
5623
  }
5537
5624
  };
5538
5625
 
5626
+ // src/contract/threads.ts
5627
+ var THREAD_FILTERS = ["all", "unread", "open", "done"];
5628
+ var THREAD_SORTS = ["updated", "created", "status"];
5629
+ var THREAD_PAGE = 30;
5630
+ function threadKey(thread, sort) {
5631
+ const latest = thread.lastReplyAt ?? thread.createdAt;
5632
+ return sort === "created" ? [0, -thread.createdAt, thread.id] : sort === "status" ? [thread.status === "done" ? 1 : 0, -latest, thread.id] : [0, -latest, thread.id];
5633
+ }
5634
+ function compareKeys(a, b) {
5635
+ return a[0] - b[0] || a[1] - b[1] || (a[2] < b[2] ? -1 : a[2] > b[2] ? 1 : 0);
5636
+ }
5637
+
5539
5638
  // src/server/service/chat/threads.ts
5540
5639
  var ChatThreads = class {
5541
- constructor(repository, saved) {
5640
+ constructor(repository, changed) {
5542
5641
  this.repository = repository;
5543
- this.saved = saved;
5642
+ this.changed = changed;
5544
5643
  }
5545
5644
  get store() {
5546
5645
  return this.repository.threads;
@@ -5551,7 +5650,8 @@ var ChatThreads = class {
5551
5650
  const names = this.repository.channels.directory(this.repository.channels.ownerOf(actorId)).map((member) => member.name);
5552
5651
  const id = this.store.open(actorId, rootMessageId, names);
5553
5652
  const chat = this.repository.getChat(actorId, id);
5554
- this.saved(chat.parentId);
5653
+ this.changed({ kind: "message.updated", chatId: chat.parentId, messageId: chat.rootMessageId });
5654
+ this.changed({ kind: "chat", id });
5555
5655
  return chat;
5556
5656
  }
5557
5657
  entry(actorId, threadId) {
@@ -5563,8 +5663,42 @@ var ChatThreads = class {
5563
5663
  list(actorId, channelId) {
5564
5664
  return this.store.list(actorId, channelId).map((id) => this.entry(actorId, id));
5565
5665
  }
5566
- followed(actorId) {
5567
- return this.store.followed(actorId).map((id) => this.entry(actorId, id));
5666
+ /** The threads the member follows as chats, for a Bot's chat list. */
5667
+ followedChats(actorId) {
5668
+ return this.store.followed(actorId).map((id) => this.repository.getChat(actorId, id));
5669
+ }
5670
+ /** 「我关注的线程」 a page at a time (A69): filtered and ordered here, so every page is cut from the same list. The
5671
+ * cursor is the last row's sort key, so a thread that moves while you scroll is neither repeated nor skipped. */
5672
+ followedPage(actorId, query) {
5673
+ const filter = choice(query.filter, THREAD_FILTERS, "all", "filter"), sort = choice(query.sort, THREAD_SORTS, "updated", "sort");
5674
+ const limit = query.limit === void 0 ? THREAD_PAGE : Number(query.limit);
5675
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw new ChatError(400, "Invalid limit");
5676
+ const after2 = query.cursor === void 0 ? null : cursorKey(query.cursor);
5677
+ const rows3 = this.store.followedKeys(actorId).filter((row) => filter === "all" || (filter === "unread" ? row.unread > 0 : row.status === filter)).map((row) => ({ id: row.id, key: threadKey(row, sort) })).sort((a, b) => compareKeys(a.key, b.key)).filter((row) => !after2 || compareKeys(row.key, after2) > 0);
5678
+ const page2 = rows3.slice(0, limit);
5679
+ return { entries: page2.map((row) => this.entry(actorId, row.id)), next: rows3.length > limit ? Buffer.from(JSON.stringify(page2.at(-1).key)).toString("base64url") : null };
5680
+ }
5681
+ /** The followed threads in numbers (A69), sent with the chat list for the sidebar and the page's tabs. */
5682
+ followedSummary(actorId) {
5683
+ const summary = { total: 0, open: 0, done: 0, unreadThreads: 0, unread: 0, mentions: 0 };
5684
+ for (const row of this.store.followedKeys(actorId)) {
5685
+ summary.total++;
5686
+ summary[row.status]++;
5687
+ summary.unread += row.unread;
5688
+ summary.mentions += row.mentions;
5689
+ if (row.unread > 0) summary.unreadThreads++;
5690
+ }
5691
+ return summary;
5692
+ }
5693
+ /** The open threads a member follows, most recently active first, up to `limit`, and how many there are (A73): what a
5694
+ * Bot is reminded of after a compaction. Finished threads are left out, as from a Bot's unread (A70). */
5695
+ openFollowed(actorId, limit) {
5696
+ const open2 = this.store.followedKeys(actorId).filter((row) => row.status === "open").sort((a, b) => b.lastReplyAt - a.lastReplyAt || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
5697
+ const threads = open2.slice(0, limit).flatMap((row) => {
5698
+ const chat = this.repository.getChat(actorId, row.id), channel2 = chat?.parentId ? this.repository.getChat(actorId, chat.parentId) : null;
5699
+ return chat && channel2 ? [{ id: chat.id, title: chat.title, channel: { id: channel2.id, title: channel2.title }, lastReplyAt: row.lastReplyAt, unread: row.unread }] : [];
5700
+ });
5701
+ return { total: open2.length, threads };
5568
5702
  }
5569
5703
  update(actorId, threadId, input) {
5570
5704
  const title = input.title;
@@ -5572,16 +5706,32 @@ var ChatThreads = class {
5572
5706
  if (input.status !== void 0 && input.status !== "open" && input.status !== "done") throw new ChatError(400, "Invalid thread status");
5573
5707
  this.store.update(actorId, threadId, { title: title === void 0 ? void 0 : title.trim(), status: input.status });
5574
5708
  const chat = this.repository.getChat(actorId, threadId);
5575
- this.saved(threadId);
5576
- this.saved(chat.parentId);
5709
+ this.changed({ kind: "chat", id: threadId });
5710
+ this.changed({ kind: "message.updated", chatId: chat.parentId, messageId: chat.rootMessageId });
5577
5711
  return chat;
5578
5712
  }
5579
5713
  setFollowing(actorId, threadId, following) {
5580
5714
  if (typeof following !== "boolean") throw new ChatError(400, "Invalid following");
5581
5715
  this.store.setFollowing(actorId, threadId, following);
5716
+ if (this.repository.member(actorId)?.kind === "user") this.changed({ kind: "chat", id: threadId });
5582
5717
  return this.repository.getChat(actorId, threadId);
5583
5718
  }
5584
5719
  };
5720
+ function choice(value2, allowed, fallback, what) {
5721
+ if (value2 === void 0) return fallback;
5722
+ if (!allowed.includes(value2)) throw new ChatError(400, `Invalid ${what}`);
5723
+ return value2;
5724
+ }
5725
+ function cursorKey(cursor2) {
5726
+ let key;
5727
+ try {
5728
+ key = JSON.parse(Buffer.from(cursor2, "base64url").toString());
5729
+ } catch {
5730
+ key = null;
5731
+ }
5732
+ if (!Array.isArray(key) || key.length !== 3 || !Number.isFinite(key[0]) || !Number.isFinite(key[1]) || typeof key[2] !== "string") throw new ChatError(400, "Invalid cursor");
5733
+ return key;
5734
+ }
5585
5735
 
5586
5736
  // src/server/service/chat/quotes.ts
5587
5737
  var MAX_QUOTES = 10;
@@ -5640,9 +5790,9 @@ var ChatService = class {
5640
5790
  this.deliveries = deliveries;
5641
5791
  this.notifications = notifications;
5642
5792
  this.attachments = new ChatAttachments(repository, files);
5643
- this.threads = new ChatThreads(repository, (chatId) => this.notifySaved(chatId));
5644
- this.questions = new ChatQuestions(repository, (chatId) => this.notifySaved(chatId));
5645
- this.channels = new ChatChannels(repository, (chatId) => this.notifySaved(chatId), (ownerId) => {
5793
+ this.threads = new ChatThreads(repository, (change) => this.notify(change));
5794
+ this.questions = new ChatQuestions(repository, (chatId, messageId) => this.notify({ kind: "message.updated", chatId, messageId }));
5795
+ this.channels = new ChatChannels(repository, (id) => this.notify({ kind: "chat", id }), (ownerId) => {
5646
5796
  try {
5647
5797
  this.notifications.sections?.(ownerId);
5648
5798
  } catch {
@@ -5676,7 +5826,7 @@ var ChatService = class {
5676
5826
  const actor = directory.find((member) => member.id === actorId), target3 = directory.find((member) => member.id === targetId);
5677
5827
  if (!actor || !target3) throw new ChatError(404, "Member not found");
5678
5828
  const chat = this.repository.openDirect(actorId, targetId, owner, `${actor.name} \xB7 ${target3.name}`);
5679
- this.notifySaved(chat.id);
5829
+ this.notify({ kind: "chat", id: chat.id });
5680
5830
  return chat;
5681
5831
  }
5682
5832
  /** A Bot's DMs with other Bots, for its owner (read-only). */
@@ -5692,7 +5842,7 @@ var ChatService = class {
5692
5842
  subscribe(actorId, chatId, subscribed) {
5693
5843
  if (typeof subscribed !== "boolean") throw new ChatError(400, "Invalid subscribed");
5694
5844
  this.repository.channels.setSubscribed(actorId, chatId, subscribed);
5695
- this.notifySaved(chatId);
5845
+ this.notify({ kind: "chat", id: chatId });
5696
5846
  return this.repository.getChat(actorId, chatId);
5697
5847
  }
5698
5848
  /** Notices waiting for a Bot (A39). */
@@ -5718,7 +5868,7 @@ var ChatService = class {
5718
5868
  const author = this.repository.canAccess(marked.sender.id, marked.chatId) ? marked.sender : void 0;
5719
5869
  const deliveries = apply ? plan("reaction", reactionTargets({ actorId, author })) : [];
5720
5870
  const { chatId, added } = this.repository.interactions.react(actorId, messageId, value2, apply, deliveries);
5721
- this.notifySaved(chatId);
5871
+ this.notify({ kind: "message.updated", chatId, messageId });
5722
5872
  if (added) this.deliveries.dispatch(deliveries);
5723
5873
  return this.repository.message(actorId, messageId);
5724
5874
  }
@@ -5728,7 +5878,7 @@ var ChatService = class {
5728
5878
  const message = this.repository.message(actorId, messageId);
5729
5879
  if (!message) throw new ChatError(404, "Message not found");
5730
5880
  this.repository.interactions.setFolded(messageId, folded);
5731
- this.notifySaved(message.chatId);
5881
+ this.notify({ kind: "message.updated", chatId: message.chatId, messageId });
5732
5882
  return this.repository.message(actorId, messageId);
5733
5883
  }
5734
5884
  mute(actorId, chatId, muted) {
@@ -5790,12 +5940,12 @@ var ChatService = class {
5790
5940
  }
5791
5941
  instance(actorId, chatId) {
5792
5942
  this.repository.assertAccess(actorId, chatId);
5793
- const parentId = this.repository.getChat(actorId, chatId)?.parentId ?? null;
5943
+ const chat = this.repository.getChat(actorId, chatId), parentId = chat?.parentId ?? null, rootId = chat?.rootMessageId ?? null;
5794
5944
  return new Chat(chatId, {
5795
5945
  info: new ChatInfo(chatId, actorId, this.repository),
5796
5946
  members: new ChatMembers(chatId, actorId, this.repository, (message, deliveries) => {
5797
- this.notifySaved(chatId);
5798
- if (parentId) this.notifySaved(parentId);
5947
+ this.notify({ kind: "message", chatId: message.chatId, messageId: message.id });
5948
+ if (message.chatId === chatId && parentId && rootId) this.notify({ kind: "message.updated", chatId: parentId, messageId: rootId });
5799
5949
  this.deliveries.dispatch(deliveries, message);
5800
5950
  }),
5801
5951
  messages: new ChatMessages(chatId, actorId, this.repository, this.attachments)
@@ -5833,17 +5983,18 @@ var ChatService = class {
5833
5983
  if (!query.trim() || query.length > 500 || !Number.isInteger(limit) || limit < 1 || limit > 100) throw new ChatError(400, "Invalid search query or limit");
5834
5984
  return this.repository.search(actorId, chatId, query, limit, sender);
5835
5985
  }
5836
- notifySaved(chatId) {
5986
+ notify(change) {
5837
5987
  try {
5838
- this.notifications.saved?.(chatId);
5988
+ this.notifications.changed?.(change);
5839
5989
  } catch {
5840
- console.error("[chat] committed-message notification failed", { chatId });
5990
+ console.error("[chat] change notification failed", change);
5841
5991
  }
5842
5992
  }
5843
5993
  async delete(actorId, chatId) {
5844
5994
  const chat = this.repository.getChat(actorId, chatId);
5845
5995
  if (!chat || chat.ownerId !== actorId) return false;
5846
5996
  await this.instance(actorId, chatId).delete();
5997
+ this.notify({ kind: "chat.removed", id: chatId, ownerId: actorId });
5847
5998
  await this.attachments.clean();
5848
5999
  return true;
5849
6000
  }
@@ -5916,11 +6067,32 @@ function byteSize(bytes) {
5916
6067
  }
5917
6068
 
5918
6069
  // src/server/service/events.ts
6070
+ import { randomUUID as randomUUID16 } from "node:crypto";
6071
+ var KEEP_MS = 10 * 6e4;
6072
+ var KEEP_MAX = 5e3;
5919
6073
  var Changes = class {
6074
+ /** This run's changes: a number from before a restart says nothing. */
6075
+ run = randomUUID16().slice(0, 8);
6076
+ last = 0;
6077
+ kept = [];
5920
6078
  listeners = /* @__PURE__ */ new Set();
5921
6079
  closers = /* @__PURE__ */ new Set();
6080
+ get seq() {
6081
+ return this.last;
6082
+ }
5922
6083
  publish(change) {
5923
- for (const listener of this.listeners) listener(change);
6084
+ const entry = { seq: ++this.last, at: Date.now(), change };
6085
+ this.kept.push(entry);
6086
+ let old = 0;
6087
+ while (old < this.kept.length && (this.kept[old].at < entry.at - KEEP_MS || this.kept.length - old > KEEP_MAX)) old++;
6088
+ if (old) this.kept.splice(0, old);
6089
+ for (const listener of this.listeners) listener(change, entry.seq);
6090
+ }
6091
+ /** The changes after `seq` of `run`, oldest first; null when some of them are no longer kept, or are from another run. */
6092
+ since(run2, seq2) {
6093
+ if (run2 !== this.run || !Number.isSafeInteger(seq2) || seq2 < 0 || seq2 > this.last) return null;
6094
+ if (seq2 + 1 < (this.kept[0]?.seq ?? this.last + 1)) return null;
6095
+ return this.kept.filter((entry) => entry.seq > seq2);
5924
6096
  }
5925
6097
  subscribe(listener, close) {
5926
6098
  this.listeners.add(listener);
@@ -7580,7 +7752,7 @@ var Computers = class {
7580
7752
  };
7581
7753
 
7582
7754
  // src/server/service/bot/machines.ts
7583
- import { randomUUID as randomUUID16 } from "node:crypto";
7755
+ import { randomUUID as randomUUID17 } from "node:crypto";
7584
7756
  import { dirname as dirname6, join as join12, posix } from "node:path";
7585
7757
 
7586
7758
  // src/server/infra/env/ssh.ts
@@ -7807,7 +7979,7 @@ var SshMachines = class {
7807
7979
  async prepareKey() {
7808
7980
  const now = Date.now();
7809
7981
  for (const [keyId2, key2] of this.prepared) if (key2.until < now) this.prepared.delete(keyId2);
7810
- const id = randomUUID16(), key = await this.wrap(() => generateKey(this.runtime, keyComment(id)));
7982
+ const id = randomUUID17(), key = await this.wrap(() => generateKey(this.runtime, keyComment(id)));
7811
7983
  this.prepared.set(id, { id, ...key, until: now + PREPARED_MS });
7812
7984
  return { keyId: id, publicKey: key.publicKey };
7813
7985
  }
@@ -7823,7 +7995,7 @@ var SshMachines = class {
7823
7995
  if (!password && (!prepared || prepared.until < Date.now())) throw new ChatError(409, "That key is no longer kept; show a new one and add it to the machine", "ssh_key_expired");
7824
7996
  if (!input.hostKeys.keys.length) throw new ChatError(400, "The host keys are missing; scan the machine first");
7825
7997
  directoryIn("/", input.directory);
7826
- const id = prepared && !password ? prepared.id : randomUUID16(), comment = keyComment(id);
7998
+ const id = prepared && !password ? prepared.id : randomUUID17(), comment = keyComment(id);
7827
7999
  const record3 = await this.wrap(async () => {
7828
8000
  const key = prepared && !password ? prepared : await generateKey(this.runtime, comment);
7829
8001
  const access = { ...where2, runtime: this.runtime, alias: alias(id), hostKeys: input.hostKeys.keys, privateKey: key.privateKey };
@@ -8672,7 +8844,7 @@ var ToolContext = class {
8672
8844
  };
8673
8845
 
8674
8846
  // src/server/service/bot/history-read.ts
8675
- import { randomUUID as randomUUID17 } from "node:crypto";
8847
+ import { randomUUID as randomUUID18 } from "node:crypto";
8676
8848
  import { Type as Type2 } from "typebox";
8677
8849
 
8678
8850
  // src/server/service/bot/history-format.ts
@@ -8752,7 +8924,7 @@ async function readHistory(memory, workspace, input, signal) {
8752
8924
  const rendered = formatHistory(result, format);
8753
8925
  signal?.throwIfAborted();
8754
8926
  if (!input.to_file) return rendered;
8755
- const name3 = `history-${randomUUID17()}.${format === "json" ? "json" : "md"}`;
8927
+ const name3 = `history-${randomUUID18()}.${format === "json" ? "json" : "md"}`;
8756
8928
  return workspace.writeTempFile(name3, rendered, signal);
8757
8929
  }
8758
8930
 
@@ -8779,6 +8951,7 @@ import { Type as Type4 } from "typebox";
8779
8951
 
8780
8952
  // src/server/service/bot/chat-views.ts
8781
8953
  var iso = (time2) => new Date(time2).toISOString();
8954
+ var done = (chat) => chat.type === "thread" && chat.status === "done";
8782
8955
  var name2 = (chats) => (memberId) => chats.member(memberId)?.name ?? memberId;
8783
8956
  function chatRows(chats, botId) {
8784
8957
  const sections = new Map(chats.channels.sections(botId).map((section) => [section.id, section.name]));
@@ -8790,13 +8963,14 @@ function chatRows(chats, botId) {
8790
8963
  ...chat.sectionId ? { section: sections.get(chat.sectionId) } : {},
8791
8964
  ...chat.topic ? { topic: chat.topic } : {},
8792
8965
  ...chat.type === "thread" ? { parent: chat.parentId, status: chat.status } : {},
8793
- unread: chat.unread,
8794
- ...chat.mentions && chat.type !== "dm" ? { mentions: chat.mentions } : {},
8966
+ // A finished thread stays out of a Bot's unread (A70): its batches and `messages.read unread=true` leave it out too.
8967
+ unread: done(chat) ? 0 : chat.unread,
8968
+ ...chat.mentions && chat.type !== "dm" && !done(chat) ? { mentions: chat.mentions } : {},
8795
8969
  ...chat.subscribed ? { subscribed: true } : {},
8796
8970
  ...chat.note ? { noticeVersion: chat.note.version } : {},
8797
8971
  updatedAt: iso(chat.updatedAt)
8798
8972
  });
8799
- return [...chats.list(botId).map(row), ...chats.threads.followed(botId).map((entry) => row(entry.chat))];
8973
+ return [...chats.list(botId).map(row), ...chats.threads.followedChats(botId).map(row)];
8800
8974
  }
8801
8975
  function chatDetail(chats, botId, chat) {
8802
8976
  const section = chat.sectionId ? chats.channels.sections(botId).find((item) => item.id === chat.sectionId)?.name : void 0;
@@ -8927,7 +9101,7 @@ var chatTools = [
8927
9101
  ),
8928
9102
  tool(
8929
9103
  "chats.list",
8930
- "List the chats you are in: DMs, channels and the threads you follow. Each has its type, title (DMs also give the other member's name in with), channel group (section), topic, your unread count and whether you subscribe; threads also give their channel and status.",
9104
+ "List the chats you are in: DMs, channels and the threads you follow. Each has its type, title (DMs also give the other member's name in with), channel group (section), topic, your unread count (none for threads that are done) and whether you subscribe; threads also give their channel and status.",
8931
9105
  None,
8932
9106
  (_args, context2) => chatRows(context2.chats, context2.bot)
8933
9107
  ),
@@ -9035,7 +9209,7 @@ var chatTools = [
9035
9209
  ),
9036
9210
  tool(
9037
9211
  "threads.follow",
9038
- "Follow or unfollow a thread. Followed threads appear in chats.list, and their new replies count as unread for you without interrupting you (use chats.subscribe to get them live). Posting in a thread or being @-mentioned in it follows it for you.",
9212
+ "Follow or unfollow a thread. Followed threads appear in chats.list, and their new replies count as unread for you without interrupting you (use chats.subscribe to get them live). Posting in a thread or being @-mentioned in it follows it for you. Unfollow one that no longer concerns you while it is still open; a thread that is done drops out of your unread by itself.",
9039
9213
  Type4.Object({ chatId: Type4.String({ description: "Thread ID" }), following: Type4.Boolean() }, { additionalProperties: false }),
9040
9214
  (input, context2) => {
9041
9215
  const chat = context2.chats.threads.setFollowing(context2.bot, input.chatId, input.following);
@@ -9088,7 +9262,7 @@ async function page(context2, chatId, messages, limit, signal) {
9088
9262
  var messageTools = [
9089
9263
  tool(
9090
9264
  "messages.read",
9091
- "Read messages; their files are listed by id, name, type and size, for files.get and files.view. Three ways: \u2460 chatId + after: read on from that sequence number (from the start by default); \u2461 around with a message ID: that message and context messages on each side (5 by default), to see the context; this doesn't move your read position; \u2462 unread=true: your unread messages, in one chat with chatId, or in every chat (grouped by chat) without it. \u2460 and \u2462 move your read position to the last message read; hasMore=true means there is more, so call again.",
9265
+ "Read messages; their files are listed by id, name, type and size, for files.get and files.view. Three ways: \u2460 chatId + after: read on from that sequence number (from the start by default); \u2461 around with a message ID: that message and context messages on each side (5 by default), to see the context; this doesn't move your read position; \u2462 unread=true: your unread messages, in one chat with chatId, or without it in every chat with unread (grouped by chat, the most recently active first, up to limit messages in all; threads that are done are left out). \u2460 and \u2462 move your read position to the last message read; hasMore=true means there is more, so call again.",
9092
9266
  Type5.Object({
9093
9267
  chatId: Type5.Optional(Type5.String()),
9094
9268
  after: Type5.Optional(Type5.Integer({ minimum: 0 })),
@@ -9108,9 +9282,18 @@ var messageTools = [
9108
9282
  }
9109
9283
  if (input.unread && input.chatId === void 0) {
9110
9284
  const found = [];
9111
- for (const chat2 of [...chats.list(bot), ...chats.threads.followed(bot).map((entry) => entry.chat)].filter((item) => item.unread > 0))
9112
- found.push({ chatId: chat2.id, type: chat2.type, title: chat2.title, ...await page(context2, chat2.id, chats.unreadMessages(bot, chat2.id, limit + 1), limit, signal) });
9113
- return { chats: found };
9285
+ let left = limit, more = false;
9286
+ for (const chat2 of chats.channels.digest(bot).unread) {
9287
+ if (!left) {
9288
+ more = true;
9289
+ break;
9290
+ }
9291
+ const read3 = await page(context2, chat2.chatId, chats.unreadMessages(bot, chat2.chatId, left + 1), left, signal);
9292
+ found.push({ chatId: chat2.chatId, type: chat2.type, title: chat2.title, ...read3 });
9293
+ left -= read3.messages.length;
9294
+ more = !!read3.hasMore;
9295
+ }
9296
+ return { chats: found, ...more ? { hasMore: true } : {} };
9114
9297
  }
9115
9298
  if (input.chatId === void 0) throw new ChatError(400, "chatId is required unless unread=true");
9116
9299
  const chat = context2.chat(input.chatId);
@@ -9598,9 +9781,9 @@ var agentTools = [
9598
9781
  // src/server/service/bot/tools.ts
9599
9782
  var EVERY_BOT = [...historyTools, ...chatTools, ...messageTools, ...fileTools, ...environmentTools2, ...secretTools, ...taskTools];
9600
9783
  var Gateway = Type11.Object({
9601
- action: Type11.Union([Type11.Literal("list"), Type11.Literal("describe"), Type11.Literal("call")]),
9784
+ action: Type11.Unsafe({ type: "string", enum: ["list", "describe", "call"] }),
9602
9785
  tool: Type11.Optional(Type11.String()),
9603
- args: Type11.Optional(Type11.Record(Type11.String(), Type11.Unknown()))
9786
+ args: Type11.Optional(Type11.Unsafe({ type: "object" }))
9604
9787
  }, { additionalProperties: false });
9605
9788
  var Tools = class {
9606
9789
  send;
@@ -9684,6 +9867,13 @@ function instructionsLine(change) {
9684
9867
  function noticeTail(notices, chats, members) {
9685
9868
  for (const notice of notices) {
9686
9869
  if (notice.kind === "task") continue;
9870
+ if (notice.kind === "followed") {
9871
+ for (const thread of notice.threads) {
9872
+ remember(chats, thread.channel.id, `<chat${attribute("id", thread.channel.id)}${attribute("type", "channel")}${attribute("title", thread.channel.title)}/>`);
9873
+ remember(chats, thread.id, `<chat${attribute("id", thread.id)}${attribute("type", "thread")}${attribute("title", thread.title)}${attribute("parent", thread.channel.id)}${attribute("status", "open")}/>`);
9874
+ }
9875
+ continue;
9876
+ }
9687
9877
  remember(members, notice.actor.id, `<member${attribute("id", notice.actor.id)}${attribute("name", notice.actor.name)}${attribute("kind", notice.actor.kind)}/>`);
9688
9878
  if (notice.kind === "onboard" || notice.kind === "change") continue;
9689
9879
  if (!chats.has(notice.chat.id)) chats.set(notice.chat.id, `<chat${attribute("id", notice.chat.id)}${attribute("type", notice.chat.type)}${notice.chat.title ? attribute("title", notice.chat.title) : ""}/>`);
@@ -9696,8 +9886,9 @@ function noticeTail(notices, chats, members) {
9696
9886
  const changes = changed.map((notice) => `<change${attribute("by", notice.actor.id)}${attribute("what", notice.what)}${attribute("at", iso2(notice.createdAt))}${notice.value === null ? "/>" : `>${escape(notice.value)}</change>`}`);
9697
9887
  const agent = changed.find((notice) => notice.actor.kind === "bot")?.actor, byOwner = changed.some((notice) => notice.actor.kind === "user");
9698
9888
  const onboard = notices.flatMap((notice) => notice.kind !== "onboard" ? [] : [`<onboard${attribute("by", notice.actor.id)}${attribute("at", iso2(notice.createdAt))}><note>${escape(welcome(notice.actor.name, notice.language))}</note></onboard>`]).slice(-1);
9889
+ const followed = notices.flatMap((notice) => notice.kind !== "followed" ? [] : [`<followed${attribute("total", String(notice.total))}>` + notice.threads.map((thread) => `<thread${attribute("chat", thread.id)}${attribute("at", iso2(thread.lastReplyAt))}${thread.unread ? attribute("unread", String(thread.unread)) : ""}/>`).join("") + `<note>Your conversation was compacted. These are the open threads you follow, most recently active first` + (notice.total > notice.threads.length ? ` (${notice.threads.length} of ${notice.total}; chats.list lists them all)` : "") + ". Before you act in one, read its summary with chats.info and what you missed with messages.read. Unfollow a thread that no longer concerns you with threads.follow; one that is done leaves this list by itself.</note></followed>"]).slice(-1);
9699
9890
  const tasks = notices.flatMap((notice) => notice.kind !== "task" ? [] : [`<task${attribute("id", notice.task.id)}${attribute("name", notice.task.name)}${attribute("schedule", notice.task.schedule)}${attribute("due", iso2(notice.due))}>${escape(notice.task.instruction)}</task>`]);
9700
- return (tasks.length ? `<tasks>${tasks.join("")}<note>These are your scheduled tasks, not messages from anyone. Do what each says, then send what is worth sending, to your owner unless the task says where; if nothing is, do nothing.</note></tasks>` : "") + (updates.length ? `<updates>${updates.join("")}</updates>` : "") + (marks.length ? `<notices>${marks.join("")}<note>These are reactions to your messages. Act on them if you need to; no reply is required.</note></notices>` : "") + (changes.length ? `<changes>${changes.join("")}` + (agent ? `<note>The agent Bot changed your settings, and the changes already apply. A change to your name, description or persona is a change to your instructions too. If something is unclear, ask it in a DM (messages.send with to: "${escape(agent.name)}").</note>` : "") + (byOwner ? "<note>Your owner changed where you work, and it already applies: environment is where your file and command tools run now, and access is what environments.switch can take you to. If you were in the middle of something, carry on where you are now.</note>" : "") + "</changes>" : "") + onboard.join("");
9891
+ return (tasks.length ? `<tasks>${tasks.join("")}<note>These are your scheduled tasks, not messages from anyone. Do what each says, then send what is worth sending, to your owner unless the task says where; if nothing is, do nothing.</note></tasks>` : "") + (updates.length ? `<updates>${updates.join("")}</updates>` : "") + (marks.length ? `<notices>${marks.join("")}<note>These are reactions to your messages. Act on them if you need to; no reply is required.</note></notices>` : "") + (changes.length ? `<changes>${changes.join("")}` + (agent ? `<note>The agent Bot changed your settings, and the changes already apply. A change to your name, description or persona is a change to your instructions too. If something is unclear, ask it in a DM (messages.send with to: "${escape(agent.name)}").</note>` : "") + (byOwner ? "<note>Your owner changed where you work, and it already applies: environment is where your file and command tools run now, and access is what environments.switch can take you to. If you were in the middle of something, carry on where you are now.</note>" : "") + "</changes>" : "") + onboard.join("") + followed.join("");
9701
9892
  }
9702
9893
  function encodeChatBatch(botId, messages, digest, notices, prompt) {
9703
9894
  if (!messages.length) throw new Error("Empty chat batch");
@@ -9725,6 +9916,7 @@ function encodeChatBatch(botId, messages, digest, notices, prompt) {
9725
9916
  }
9726
9917
 
9727
9918
  // src/server/service/bot/inbox.ts
9919
+ var FOLLOWED_SHOWN = 15;
9728
9920
  var BotInbox = class {
9729
9921
  /** `where` is the work environment the Bot is in now, named at the end of each batch (A50). */
9730
9922
  constructor(botId, repository, chats, files, tasks, where2) {
@@ -9755,45 +9947,63 @@ var BotInbox = class {
9755
9947
  * unread); `notices` are told once the batch is submitted. */
9756
9948
  async prepare(batch, prompt) {
9757
9949
  if (!batch.inputs.length) {
9758
- const pending2 = this.notices(prompt);
9759
- return pending2 && { xml: pending2.xml, notices: pending2.ids };
9950
+ const pending = this.notices(prompt);
9951
+ return pending && { xml: pending.xml, notices: pending.ids };
9760
9952
  }
9761
9953
  const inputs = await this.files.envelope(this.botId, batch.inputs.map((input) => input.messageId));
9762
9954
  for (const input of batch.inputs) if (!this.chats.get(this.botId, input.chatId)) throw new RuntimeFault("chat_access_changed", "Chat access has changed.");
9763
9955
  const unreadNotes = this.chats.channels.unreadNotes(this.botId, [...new Set(batch.inputs.map((input) => input.chatId))]);
9764
9956
  const digest = { ...this.chats.channels.digest(this.botId), ...unreadNotes.length ? { unreadNotes } : {}, ...this.where ? { environment: this.where() } : {} };
9765
- const pending = this.envelope(this.chats.notices(this.botId));
9766
- return { xml: encodeChatBatch(this.botId, inputs, digest, pending.length ? pending : void 0, prompt), notices: pending.map((notice) => notice.id) };
9767
- }
9768
- /** Inbox rows as the envelope shape; the steered and the batch tails share it. Chat activity names its chat; system
9957
+ const tail = this.convert(this.chats.notices(this.botId));
9958
+ this.tell(tail.stale);
9959
+ return { xml: encodeChatBatch(this.botId, inputs, digest, tail.kept.length ? tail.kept : void 0, prompt), notices: tail.kept.map((notice) => notice.id) };
9960
+ }
9961
+ /** Inbox rows as the envelope shape (`kept`); the steered and the batch tails share it. `stale`: the ids of rows with
9962
+ * nothing left to say, which are told and dropped — a task deleted before its Bot was told it is due (A58), no open
9963
+ * thread to list after a compaction, or an earlier compaction's list, which the latest one stands for (A73). */
9964
+ convert(notices) {
9965
+ let latest;
9966
+ for (const notice of notices) if (notice.kind === "followed") latest = notice.id;
9967
+ const kept = [], stale = [];
9968
+ for (const notice of notices) {
9969
+ const shaped = notice.kind === "followed" && notice.id !== latest ? null : this.shape(notice);
9970
+ if (shaped) kept.push(shaped);
9971
+ else stale.push(notice.id);
9972
+ }
9973
+ return { kept, stale };
9974
+ }
9975
+ /** One row as the envelope shape, or null when it has nothing left to say. Chat activity names its chat; system
9769
9976
  * notices have none (A61). */
9770
- envelope(notices) {
9771
- return notices.flatMap((notice) => {
9772
- const { id, createdAt } = notice;
9773
- switch (notice.kind) {
9774
- case "note":
9775
- return [{ kind: "note", id, chat: notice.chat, actor: notice.actor, version: notice.payload.version, createdAt }];
9776
- case "onboard":
9777
- return [{ kind: "onboard", id, actor: notice.actor, language: welcomeLanguage(notice.payload.language), createdAt }];
9778
- case "change":
9779
- return [{ kind: "change", id, actor: notice.actor, what: notice.payload.what, value: notice.payload.value, createdAt }];
9780
- case "task": {
9781
- const task = this.tasks.get(this.botId, notice.payload.task);
9782
- return task ? [{
9783
- kind: "task",
9784
- id,
9785
- task: { id: task.id, name: task.name, instruction: task.instruction, schedule: describeSchedule(task.schedule) },
9786
- due: notice.payload.due,
9787
- createdAt
9788
- }] : [];
9789
- }
9790
- case "reaction": {
9791
- const marked = this.chats.message(this.botId, notice.messageId);
9792
- const text4 = marked ? previewQuotes(marked.content, marked.quotes).slice(0, 120) : "";
9793
- return [{ kind: "reaction", id, chat: notice.chat, message: { id: notice.messageId, text: text4 }, actor: notice.actor, emoji: notice.payload.emoji, createdAt }];
9794
- }
9977
+ shape(notice) {
9978
+ const { id, createdAt } = notice;
9979
+ switch (notice.kind) {
9980
+ case "note":
9981
+ return { kind: "note", id, chat: notice.chat, actor: notice.actor, version: notice.payload.version, createdAt };
9982
+ case "onboard":
9983
+ return { kind: "onboard", id, actor: notice.actor, language: welcomeLanguage(notice.payload.language), createdAt };
9984
+ case "change":
9985
+ return { kind: "change", id, actor: notice.actor, what: notice.payload.what, value: notice.payload.value, createdAt };
9986
+ case "task": {
9987
+ const task = this.tasks.get(this.botId, notice.payload.task);
9988
+ return task ? {
9989
+ kind: "task",
9990
+ id,
9991
+ task: { id: task.id, name: task.name, instruction: task.instruction, schedule: describeSchedule(task.schedule) },
9992
+ due: notice.payload.due,
9993
+ createdAt
9994
+ } : null;
9795
9995
  }
9796
- });
9996
+ case "reaction": {
9997
+ const marked = this.chats.message(this.botId, notice.messageId);
9998
+ const text4 = marked ? previewQuotes(marked.content, marked.quotes).slice(0, 120) : "";
9999
+ return { kind: "reaction", id, chat: notice.chat, message: { id: notice.messageId, text: text4 }, actor: notice.actor, emoji: notice.payload.emoji, createdAt };
10000
+ }
10001
+ // Its conversation was compacted (A73): the open threads it follows, as they are now.
10002
+ case "followed": {
10003
+ const open2 = this.chats.threads.openFollowed(this.botId, FOLLOWED_SHOWN);
10004
+ return open2.total ? { kind: "followed", id, total: open2.total, threads: open2.threads, createdAt } : null;
10005
+ }
10006
+ }
9797
10007
  }
9798
10008
  /** The batch went to the model: each delivery in its tail is told once. */
9799
10009
  acknowledge(notices) {
@@ -9804,8 +10014,14 @@ var BotInbox = class {
9804
10014
  notices(prompt, steer = false) {
9805
10015
  const pending = this.chats.notices(this.botId).filter((notice) => !steer || notice.kind !== "task");
9806
10016
  if (!pending.length) return null;
10017
+ const { kept, stale } = this.convert(pending);
10018
+ if (!kept.length && !prompt) {
10019
+ this.tell(stale);
10020
+ return null;
10021
+ }
10022
+ this.tell(stale);
9807
10023
  const unreadNotes = this.chats.channels.unreadNotes(this.botId, pending.flatMap((notice) => notice.chat ? [notice.chat.id] : []));
9808
- return { xml: encodeNoticeBatch(this.botId, this.envelope(pending), this.where?.(), prompt, unreadNotes), ids: pending.map((notice) => notice.id) };
10024
+ return { xml: encodeNoticeBatch(this.botId, kept, this.where?.(), prompt, unreadNotes), ids: kept.map((notice) => notice.id) };
9809
10025
  }
9810
10026
  /** These notices reached the model. */
9811
10027
  tell(ids) {
@@ -10537,7 +10753,11 @@ var BotService = class {
10537
10753
  environment: () => this.environments.current(id, record3.workspacePath),
10538
10754
  secrets: this.deps.secrets.forBot(id),
10539
10755
  catalog: this.deps.catalog,
10540
- onCompacted: () => chats.channels.clearNotesSeen(id)
10756
+ onCompacted: () => {
10757
+ chats.channels.clearNotesSeen(id);
10758
+ const to = chats.member(id);
10759
+ if (to) this.deps.deliveries.notify({ to, kind: "followed", reason: "compaction", actorId: null, payloads: [null] });
10760
+ }
10541
10761
  }));
10542
10762
  const workspace = new Workspace(record3.workspacePath, () => this.environments.current(id, record3.workspacePath), () => {
10543
10763
  const place = this.environments.default(id, record3.workspacePath);
@@ -11064,20 +11284,15 @@ var Application = class _Application {
11064
11284
  this.release = release;
11065
11285
  this.deliveries = new Deliveries(store.chats.inbox, {
11066
11286
  bot: (id, urgency) => this.bots.deliver(id, urgency),
11067
- user: (id, urgency) => {
11068
- if (id === this.user.id) this.user.deliver(urgency);
11287
+ user: (id) => {
11288
+ if (id === this.user.id) this.user.deliver();
11069
11289
  }
11070
11290
  });
11071
11291
  this.chats = new ChatService(store.chats, this.deliveries, new AttachmentFiles(dataDir), {
11072
- saved: (id) => this.user.changed(id),
11292
+ changed: (change) => this.events.publish(change),
11073
11293
  sections: (ownerId) => this.events.publish({ kind: "sections", ownerId })
11074
11294
  });
11075
- this.user = new User(
11076
- store.account.userMemberId(),
11077
- (actor, chat, draft) => this.chats.send(actor, chat, { ...draft }),
11078
- (id) => this.events.publish({ kind: "chat", id }),
11079
- () => this.events.publish({ kind: "inbox", memberId: this.user.id })
11080
- );
11295
+ this.user = new User(store.account.userMemberId(), (actor, chat, draft) => this.chats.send(actor, chat, { ...draft }));
11081
11296
  this.files = new ChatFiles(this.chats);
11082
11297
  store.runtime.recover();
11083
11298
  this.secrets = new SecretService(store, this.chats);
@@ -11253,7 +11468,7 @@ async function stopServer(dir, waitMs = 3e4) {
11253
11468
  rmSync3(pidPath(dir), { force: true });
11254
11469
  return "stopped";
11255
11470
  }
11256
- await new Promise((done) => setTimeout(done, 200));
11471
+ await new Promise((done2) => setTimeout(done2, 200));
11257
11472
  }
11258
11473
  return "still_running";
11259
11474
  }
@@ -11270,7 +11485,7 @@ function secretPrompt(label) {
11270
11485
  process.stdout.write(label);
11271
11486
  return new Promise((resolve5, reject) => {
11272
11487
  let value2 = "";
11273
- const done = (result, error) => {
11488
+ const done2 = (result, error) => {
11274
11489
  process.stdin.off("data", onData);
11275
11490
  process.stdin.setRawMode(false);
11276
11491
  process.stdin.pause();
@@ -11281,11 +11496,11 @@ function secretPrompt(label) {
11281
11496
  const onData = (buffer) => {
11282
11497
  for (const char of buffer.toString("utf8")) {
11283
11498
  if (char === "\r" || char === "\n") {
11284
- done(value2);
11499
+ done2(value2);
11285
11500
  return;
11286
11501
  }
11287
11502
  if (char === "" || char === "") {
11288
- done(void 0, new Error("Setup cancelled"));
11503
+ done2(void 0, new Error("Setup cancelled"));
11289
11504
  return;
11290
11505
  }
11291
11506
  if (char === "\x7F" || char === "\b") {