@howaboua/pi-agent-comms 0.0.0-stage → 0.0.1-dev.14.1.g7d1d3da173aa

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.
Files changed (141) hide show
  1. package/INTEGRATION.md +31 -0
  2. package/LICENSE +21 -0
  3. package/PCC-INTEGRATION.md +17 -0
  4. package/README.md +53 -2
  5. package/dist/viewer/archive.js +249 -0
  6. package/dist/viewer/config.js +85 -0
  7. package/dist/viewer/contracts.js +1 -0
  8. package/dist/viewer/server.js +177 -0
  9. package/dist/viewer/source.js +29 -0
  10. package/dist/viewer/web/app.js +88 -0
  11. package/dist/viewer/web/index.html +41 -0
  12. package/dist/viewer/web/navigation.js +72 -0
  13. package/dist/viewer/web/posts.js +105 -0
  14. package/dist/viewer/web/render.js +147 -0
  15. package/dist/viewer/web/session.js +86 -0
  16. package/dist/viewer/web/style.css +517 -0
  17. package/dist/viewer/web/updates.js +106 -0
  18. package/docs/BOARD-CHANGELOG.md +49 -0
  19. package/docs/BOARD.md +124 -0
  20. package/docs/NOTES-CHANGELOG.md +127 -0
  21. package/docs/NOTES.md +122 -0
  22. package/index.ts +21 -0
  23. package/package.json +75 -5
  24. package/src/board/AGENTS.md +12 -0
  25. package/src/board/activity.ts +274 -0
  26. package/src/board/archive.ts +118 -0
  27. package/src/board/awareness.ts +179 -0
  28. package/src/board/briefing.ts +25 -0
  29. package/src/board/config.ts +192 -0
  30. package/src/board/consolidation.ts +32 -0
  31. package/src/board/context-briefing.ts +245 -0
  32. package/src/board/contract.ts +254 -0
  33. package/src/board/delivery.ts +85 -0
  34. package/src/board/feature.ts +91 -0
  35. package/src/board/identity.ts +238 -0
  36. package/src/board/integration.ts +55 -0
  37. package/src/board/paging.ts +54 -0
  38. package/src/board/protocol.ts +78 -0
  39. package/src/board/queries.ts +168 -0
  40. package/src/board/response.ts +82 -0
  41. package/src/board/runtime/activation.ts +50 -0
  42. package/src/board/runtime/catchup.ts +96 -0
  43. package/src/board/runtime/coordinator.ts +311 -0
  44. package/src/board/runtime/engine.ts +40 -0
  45. package/src/board/runtime/index.ts +63 -0
  46. package/src/board/runtime/owner.ts +168 -0
  47. package/src/board/runtime/routing.ts +152 -0
  48. package/src/board/runtime/turns.ts +109 -0
  49. package/src/board/search.ts +95 -0
  50. package/src/board/settings/panel.ts +193 -0
  51. package/src/board/store.ts +427 -0
  52. package/src/board/summaries.ts +124 -0
  53. package/src/board/summarizer.ts +201 -0
  54. package/src/board/tool.ts +27 -0
  55. package/src/board/viewer/AGENTS.md +1 -0
  56. package/src/board/viewer/archive.ts +308 -0
  57. package/src/board/viewer/config.ts +111 -0
  58. package/src/board/viewer/contracts.ts +98 -0
  59. package/src/board/viewer/index.ts +162 -0
  60. package/src/board/viewer/server.ts +204 -0
  61. package/src/board/viewer/source.ts +33 -0
  62. package/src/board/viewer/web/app.js +88 -0
  63. package/src/board/viewer/web/index.html +41 -0
  64. package/src/board/viewer/web/navigation.js +72 -0
  65. package/src/board/viewer/web/posts.js +105 -0
  66. package/src/board/viewer/web/render.js +147 -0
  67. package/src/board/viewer/web/session.js +86 -0
  68. package/src/board/viewer/web/style.css +517 -0
  69. package/src/board/viewer/web/updates.js +106 -0
  70. package/src/guidance.ts +121 -0
  71. package/src/notes/AGENTS.md +27 -0
  72. package/src/notes/activation.ts +150 -0
  73. package/src/notes/agent-identity.ts +221 -0
  74. package/src/notes/attachment-sharing.ts +165 -0
  75. package/src/notes/attachment-snapshot.ts +113 -0
  76. package/src/notes/binding-startup.ts +30 -0
  77. package/src/notes/bridge.ts +130 -0
  78. package/src/notes/compaction-projection.ts +88 -0
  79. package/src/notes/context-owner.ts +99 -0
  80. package/src/notes/context-sharing.ts +178 -0
  81. package/src/notes/extension-hooks.ts +200 -0
  82. package/src/notes/extension-sharing.ts +133 -0
  83. package/src/notes/feature.ts +168 -0
  84. package/src/notes/fresh-checkpoint.ts +143 -0
  85. package/src/notes/fresh-notes.ts +323 -0
  86. package/src/notes/history-search-protocol.ts +39 -0
  87. package/src/notes/history-search-pruning.mjs +120 -0
  88. package/src/notes/history-search-worker.mjs +258 -0
  89. package/src/notes/history-search.ts +269 -0
  90. package/src/notes/history-windows.ts +221 -0
  91. package/src/notes/history.ts +158 -0
  92. package/src/notes/idle-admission.ts +201 -0
  93. package/src/notes/index.ts +125 -0
  94. package/src/notes/integrations.ts +174 -0
  95. package/src/notes/lifecycle.ts +308 -0
  96. package/src/notes/model-role-config.ts +79 -0
  97. package/src/notes/model-role-screen.ts +74 -0
  98. package/src/notes/model-roles.ts +225 -0
  99. package/src/notes/note-query.ts +148 -0
  100. package/src/notes/note-result.ts +88 -0
  101. package/src/notes/note-save-marker.ts +128 -0
  102. package/src/notes/notes-lookup.ts +115 -0
  103. package/src/notes/notes.ts +302 -0
  104. package/src/notes/query-executor.ts +242 -0
  105. package/src/notes/query-input.ts +126 -0
  106. package/src/notes/remote.ts +376 -0
  107. package/src/notes/rollover.ts +224 -0
  108. package/src/notes/saved-session-access.ts +117 -0
  109. package/src/notes/saved-session-index.mjs +83 -0
  110. package/src/notes/saved-session.mjs +241 -0
  111. package/src/notes/saved-session.ts +51 -0
  112. package/src/notes/saved-sharing-records.ts +135 -0
  113. package/src/notes/session-pruning-content.ts +237 -0
  114. package/src/notes/session-pruning-plan.ts +243 -0
  115. package/src/notes/session-pruning-policy.ts +20 -0
  116. package/src/notes/session-pruning-screen.ts +204 -0
  117. package/src/notes/session-pruning-source.ts +44 -0
  118. package/src/notes/session-pruning-transaction.ts +141 -0
  119. package/src/notes/session-pruning.ts +155 -0
  120. package/src/notes/settings-command.ts +95 -0
  121. package/src/notes/settings-controls.ts +199 -0
  122. package/src/notes/settings-screen.ts +113 -0
  123. package/src/notes/settings.ts +287 -0
  124. package/src/notes/shared-notes.ts +411 -0
  125. package/src/notes/shared-session-reader.ts +143 -0
  126. package/src/notes/sharing-service.ts +282 -0
  127. package/src/notes/sqlite.mjs +33 -0
  128. package/src/notes/store.ts +283 -0
  129. package/src/notes/task-boundary.ts +37 -0
  130. package/src/notes/tool-contracts.ts +312 -0
  131. package/src/notes/tools.ts +148 -0
  132. package/src/notes/tree-archive-manifest.mjs +27 -0
  133. package/src/notes/tree-archive.ts +129 -0
  134. package/src/notes/tree-checkpoint.ts +170 -0
  135. package/src/notes/tree-handoff-read.ts +192 -0
  136. package/src/notes/window-checkpoint.ts +105 -0
  137. package/src/notes/window-message.ts +185 -0
  138. package/src/notes/windows.ts +272 -0
  139. package/src/settings-navigation.ts +11 -0
  140. package/src/timestamps.ts +3 -0
  141. package/tsconfig.json +9 -0
@@ -0,0 +1,427 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { chmodSync, existsSync, mkdirSync } from "node:fs";
3
+ import { dirname } from "node:path";
4
+ import { DatabaseSync, type SQLInputValue } from "node:sqlite";
5
+ import { caseFold } from "unicode-case-folding";
6
+ import { minuteTimestamp } from "../timestamps.js";
7
+ import {
8
+ agentPath,
9
+ type BoardParams,
10
+ MUTATIONS,
11
+ required,
12
+ type ThreadStatus,
13
+ } from "./contract.js";
14
+ import { metadata, POST_COLUMNS, type PostRecord, preview } from "./paging.js";
15
+ import { queryBoard } from "./queries.js";
16
+ import { serializeBoardResult } from "./response.js";
17
+ import { ThreadSummaries } from "./summaries.js";
18
+
19
+ export interface BoardScope {
20
+ boardId: string;
21
+ rootSessionId: string;
22
+ ownerFolder: string;
23
+ agentName: string;
24
+ legacyAgentName?: string;
25
+ callerSessionId: string;
26
+ members: readonly string[];
27
+ }
28
+ const SCHEMA = `
29
+ CREATE TABLE boards (board_id TEXT PRIMARY KEY, root_session_id TEXT NOT NULL, owner_folder TEXT NOT NULL, created_at TEXT NOT NULL);
30
+ CREATE TABLE channels (board_id TEXT NOT NULL, name TEXT NOT NULL, name_search TEXT NOT NULL, created_at TEXT NOT NULL, author TEXT NOT NULL, PRIMARY KEY(board_id,name));
31
+ CREATE TABLE posts (seq INTEGER PRIMARY KEY AUTOINCREMENT,board_id TEXT NOT NULL,id TEXT NOT NULL,channel TEXT NOT NULL,root TEXT NOT NULL,author TEXT NOT NULL,created_at TEXT NOT NULL,text TEXT NOT NULL,body_search TEXT NOT NULL,request_id TEXT NOT NULL,request TEXT NOT NULL,UNIQUE(board_id,id),UNIQUE(board_id,request_id));
32
+ CREATE INDEX posts_channel ON posts(board_id,channel,created_at,seq);
33
+ CREATE INDEX posts_root ON posts(board_id,root,created_at,seq);
34
+ CREATE INDEX posts_order ON posts(board_id,created_at,seq);
35
+ CREATE TABLE subscriptions (board_id TEXT NOT NULL,target TEXT NOT NULL,agent TEXT NOT NULL,enabled INTEGER NOT NULL,PRIMARY KEY(board_id,target,agent));
36
+ PRAGMA user_version=1;`;
37
+ const THREAD_STATUS_SCHEMA = `CREATE TABLE IF NOT EXISTS thread_statuses (
38
+ board_id TEXT NOT NULL, thread_id TEXT NOT NULL,
39
+ status TEXT NOT NULL CHECK(status IN ('open','completed','abandoned')),
40
+ message_id TEXT NOT NULL, PRIMARY KEY(board_id,thread_id));`;
41
+
42
+ /** One transaction/connection per call. Reads never create a file, schema or board. */
43
+ export class BoardStore {
44
+ readonly db: DatabaseSync;
45
+ readonly summaries: ThreadSummaries;
46
+ private readonly hasThreadStatuses: boolean;
47
+ private readonly aliases: Map<string, string>;
48
+ constructor(path: string, write: boolean, aliases: [string, string][] = []) {
49
+ this.aliases = new Map(aliases);
50
+ const fresh = !existsSync(path);
51
+ if (write && fresh) mkdirSync(dirname(path), { recursive: true });
52
+ this.db = new DatabaseSync(path, { readOnly: !write });
53
+ try {
54
+ this.db.exec("PRAGMA busy_timeout=5000");
55
+ if (write) {
56
+ if (fresh) chmodSync(path, 0o600);
57
+ this.db.exec("PRAGMA journal_mode=WAL; BEGIN IMMEDIATE");
58
+ }
59
+ const version = this.one<{ user_version: number }>(
60
+ "PRAGMA user_version",
61
+ )?.user_version;
62
+ if (
63
+ version === 0 &&
64
+ write &&
65
+ this.all("SELECT name FROM sqlite_master WHERE type='table'").length ===
66
+ 0
67
+ )
68
+ this.db.exec(SCHEMA);
69
+ else if (version !== 1)
70
+ throw new Error("Unsupported Shepherdr board archive schema");
71
+ if (write) this.db.exec(THREAD_STATUS_SCHEMA);
72
+ this.hasThreadStatuses = !!this.one(
73
+ "SELECT 1 FROM sqlite_master WHERE type='table' AND name='thread_statuses'",
74
+ );
75
+ this.summaries = new ThreadSummaries(this.db, write);
76
+ if (write) this.db.exec("COMMIT");
77
+ } catch (error) {
78
+ this.db.close();
79
+ throw error;
80
+ }
81
+ }
82
+ canonicalAgent(value: string) {
83
+ return this.aliases.get(value) ?? value;
84
+ }
85
+ agentIdentities(value: string) {
86
+ const canonical = this.canonicalAgent(value);
87
+ return [
88
+ canonical,
89
+ ...[...this.aliases]
90
+ .filter(([, native]) => native === canonical)
91
+ .map(([legacy]) => legacy),
92
+ ];
93
+ }
94
+ one<T>(sql: string, ...args: SQLInputValue[]): T | undefined {
95
+ return this.db.prepare(sql).get(...args) as T | undefined;
96
+ }
97
+ all<T>(sql: string, ...args: SQLInputValue[]): T[] {
98
+ return this.db.prepare(sql).all(...args) as T[];
99
+ }
100
+ run(sql: string, ...args: SQLInputValue[]) {
101
+ return this.db.prepare(sql).run(...args);
102
+ }
103
+ post(board: string, id: string): PostRecord {
104
+ const post = this.one<PostRecord>(
105
+ `SELECT ${POST_COLUMNS} FROM posts WHERE board_id=? AND id=?`,
106
+ board,
107
+ id,
108
+ );
109
+ if (!post) throw new Error("Post not found in this board");
110
+ return post;
111
+ }
112
+ root(board: string, id: string): PostRecord {
113
+ const post = this.post(board, id);
114
+ if (post.thread_id !== id)
115
+ throw new Error("thread_id must identify a first post");
116
+ return post;
117
+ }
118
+ threadStatus(
119
+ board: string,
120
+ thread: string,
121
+ ): {
122
+ status: ThreadStatus;
123
+ status_message_id: string | null;
124
+ } {
125
+ return (
126
+ (this.hasThreadStatuses
127
+ ? this.one<{ status: ThreadStatus; status_message_id: string }>(
128
+ "SELECT status,message_id AS status_message_id FROM thread_statuses WHERE board_id=? AND thread_id=?",
129
+ board,
130
+ thread,
131
+ )
132
+ : undefined) ?? { status: "open", status_message_id: null }
133
+ );
134
+ }
135
+ channel(board: string, name: string) {
136
+ const channel = this.one<{
137
+ channel_name: string;
138
+ created_at: string;
139
+ created_by: string;
140
+ message_count: number;
141
+ last_message_id: string | null;
142
+ }>(
143
+ `SELECT name AS channel_name,created_at,author AS created_by,
144
+ (SELECT COUNT(*) FROM posts p WHERE p.board_id=c.board_id AND p.channel=c.name) AS message_count,
145
+ (SELECT id FROM posts p WHERE p.board_id=c.board_id AND p.channel=c.name ORDER BY seq DESC LIMIT 1) AS last_message_id
146
+ FROM channels c WHERE board_id=? AND name=?`,
147
+ board,
148
+ name,
149
+ );
150
+ if (!channel) throw new Error("Channel not found in this board");
151
+ return channel;
152
+ }
153
+ execute(scope: BoardScope, params: BoardParams, requestId: string) {
154
+ const write = MUTATIONS.has(params.action);
155
+ this.db.exec(write ? "BEGIN IMMEDIATE" : "BEGIN");
156
+ try {
157
+ const result = write
158
+ ? this.mutate(scope, params, requestId)
159
+ : { value: queryBoard(this, scope.boardId, params), recipients: [] };
160
+ if (write) serializeBoardResult(result.value);
161
+ this.db.exec("COMMIT");
162
+ return result;
163
+ } catch (error) {
164
+ this.db.exec("ROLLBACK");
165
+ throw error;
166
+ }
167
+ }
168
+ close() {
169
+ this.db.close();
170
+ }
171
+ private ensureBoard(scope: BoardScope, now: string) {
172
+ this.run(
173
+ "INSERT OR IGNORE INTO boards VALUES(?,?,?,?)",
174
+ scope.boardId,
175
+ scope.rootSessionId,
176
+ scope.ownerFolder,
177
+ now,
178
+ );
179
+ }
180
+ private insertChannel(scope: BoardScope, name: string, now: string) {
181
+ if (
182
+ this.one(
183
+ "SELECT 1 FROM channels WHERE board_id=? AND name=?",
184
+ scope.boardId,
185
+ name,
186
+ )
187
+ )
188
+ throw new Error("Channel already exists");
189
+ this.run(
190
+ "INSERT INTO channels VALUES(?,?,?,?,?)",
191
+ scope.boardId,
192
+ name,
193
+ caseFold(name),
194
+ now,
195
+ scope.agentName,
196
+ );
197
+ }
198
+ private subscription(
199
+ board: string,
200
+ target: string,
201
+ agent: string,
202
+ enabled: boolean,
203
+ implicit = false,
204
+ ) {
205
+ if (
206
+ implicit &&
207
+ this.one(
208
+ "SELECT 1 FROM subscriptions WHERE board_id=? AND target=? AND agent IN (SELECT value FROM json_each(?))",
209
+ board,
210
+ target,
211
+ JSON.stringify(this.agentIdentities(agent)),
212
+ )
213
+ )
214
+ return;
215
+ this.run(
216
+ implicit
217
+ ? "INSERT OR IGNORE INTO subscriptions VALUES(?,?,?,1)"
218
+ : "INSERT INTO subscriptions VALUES(?,?,?,?) ON CONFLICT(board_id,target,agent) DO UPDATE SET enabled=excluded.enabled",
219
+ ...[board, target, agent, ...(implicit ? [] : [enabled ? 1 : 0])],
220
+ );
221
+ }
222
+ private resolve(scope: BoardScope, value: string) {
223
+ const path = this.canonicalAgent(
224
+ agentPath(value, scope.legacyAgentName ?? scope.agentName),
225
+ );
226
+ if (!scope.members.includes(path))
227
+ throw new Error(`Agent not bound to this tree: ${path}`);
228
+ return path;
229
+ }
230
+ private mutate(scope: BoardScope, params: BoardParams, requestId: string) {
231
+ const board = scope.boardId;
232
+ if (params.action === "post" || params.action === "set_status")
233
+ return this.publish(scope, params, requestId);
234
+ if (params.action === "create_channel") {
235
+ const name = required(params.channel_name, "channel_name");
236
+ const now = minuteTimestamp();
237
+ this.ensureBoard(scope, now);
238
+ this.insertChannel(scope, name, now);
239
+ if (params.subscribe !== false)
240
+ this.subscription(board, `channel:${name}`, scope.agentName, true);
241
+ return { value: this.channel(board, name), recipients: [] };
242
+ }
243
+ const target_agent =
244
+ params.target_agent === undefined
245
+ ? scope.agentName
246
+ : this.resolve(scope, params.target_agent);
247
+ const root =
248
+ params.thread_id === undefined
249
+ ? undefined
250
+ : this.root(board, params.thread_id);
251
+ const channel = this.channel(
252
+ board,
253
+ root?.channel_name ?? required(params.channel_name, "channel_name"),
254
+ );
255
+ const thread_id = root?.thread_id ?? null;
256
+ const target = root
257
+ ? `thread:${root.thread_id}`
258
+ : `channel:${channel.channel_name}`;
259
+ const last = root
260
+ ? (this.one<{ id: string }>(
261
+ "SELECT id FROM posts WHERE board_id=? AND root=? ORDER BY seq DESC LIMIT 1",
262
+ board,
263
+ root.thread_id,
264
+ )?.id ?? null)
265
+ : channel.last_message_id;
266
+ const enabled = params.action === "subscribe";
267
+ this.subscription(board, target, target_agent, enabled);
268
+ return {
269
+ value: {
270
+ channel_name: channel.channel_name,
271
+ thread_id,
272
+ target_agent,
273
+ enabled,
274
+ last_message_id: last,
275
+ },
276
+ recipients: [],
277
+ };
278
+ }
279
+ private publish(scope: BoardScope, params: BoardParams, requestId: string) {
280
+ const board = scope.boardId;
281
+ const request = JSON.stringify(
282
+ Object.fromEntries(
283
+ Object.entries({
284
+ ...params,
285
+ agents_to_notify: params.agents_to_notify ?? [],
286
+ }).sort(([a], [b]) => a.localeCompare(b)),
287
+ ),
288
+ );
289
+ const key = `${scope.callerSessionId}:${requestId}`;
290
+ if (!requestId || Buffer.byteLength(key) > 1024)
291
+ throw new Error("Invalid post invocation ID");
292
+ const previous = this.one<{ id: string; request: string }>(
293
+ "SELECT id,request FROM posts WHERE board_id=? AND request_id=?",
294
+ board,
295
+ key,
296
+ );
297
+ if (previous) {
298
+ if (previous.request !== request)
299
+ throw new Error("Invocation ID already used for a different post");
300
+ return {
301
+ value: {
302
+ ...metadata(this.post(board, previous.id)),
303
+ ...(params.action === "set_status" ? { status: params.status } : {}),
304
+ },
305
+ recipients: [],
306
+ };
307
+ }
308
+ const recipients = new Set(
309
+ (params.agents_to_notify ?? []).map((name) => this.resolve(scope, name)),
310
+ );
311
+ const now = minuteTimestamp();
312
+ const id = randomUUID();
313
+ let channel: string;
314
+ let root: string = id;
315
+ if (params.thread_id !== undefined) {
316
+ const post = this.root(board, params.thread_id);
317
+ channel = post.channel_name;
318
+ root = post.thread_id;
319
+ if (
320
+ params.action === "post" &&
321
+ this.threadStatus(board, root).status !== "open"
322
+ )
323
+ throw new Error(
324
+ "Thread is closed. The parent session must reopen it before replies.",
325
+ );
326
+ } else if (params.new_channel_name !== undefined) {
327
+ channel = params.new_channel_name;
328
+ this.ensureBoard(scope, now);
329
+ this.insertChannel(scope, channel, now);
330
+ this.subscription(board, `channel:${channel}`, scope.agentName, true);
331
+ } else
332
+ channel = this.channel(
333
+ board,
334
+ required(params.channel_name, "channel_name"),
335
+ ).channel_name;
336
+ const target = root === id ? `channel:${channel}` : `thread:${root}`;
337
+ for (const { agent } of this.all<{ agent: string }>(
338
+ `SELECT s.agent FROM subscriptions s WHERE s.board_id=? AND s.target=? AND s.enabled=1`,
339
+ board,
340
+ target,
341
+ )) {
342
+ const canonical = this.canonicalAgent(agent);
343
+ const override = this.one<{ enabled: number }>(
344
+ "SELECT enabled FROM subscriptions WHERE board_id=? AND target=? AND agent=?",
345
+ board,
346
+ target,
347
+ canonical,
348
+ );
349
+ if (!override || override.enabled) recipients.add(canonical);
350
+ }
351
+ recipients.delete(scope.agentName);
352
+ const post: PostRecord = {
353
+ message_id: id,
354
+ channel_name: channel,
355
+ author: scope.agentName,
356
+ thread_id: root,
357
+ created_at: now,
358
+ text:
359
+ params.action === "set_status"
360
+ ? required(params.comment, "comment")
361
+ : required(params.text, "text"),
362
+ };
363
+ this.run(
364
+ "INSERT INTO posts(board_id,id,channel,root,author,created_at,text,body_search,request_id,request) VALUES(?,?,?,?,?,?,?,?,?,?)",
365
+ board,
366
+ id,
367
+ channel,
368
+ root,
369
+ scope.agentName,
370
+ now,
371
+ post.text,
372
+ caseFold(post.text),
373
+ key,
374
+ request,
375
+ );
376
+ if (params.action === "set_status") {
377
+ this.run(
378
+ `INSERT INTO thread_statuses(board_id,thread_id,status,message_id) VALUES(?,?,?,?)
379
+ ON CONFLICT(board_id,thread_id) DO UPDATE SET status=excluded.status,message_id=excluded.message_id`,
380
+ board,
381
+ root,
382
+ required(params.status, "status"),
383
+ id,
384
+ );
385
+ this.summaries.discard(board, root);
386
+ }
387
+ this.subscription(board, `thread:${root}`, scope.agentName, true, true);
388
+ return {
389
+ value: {
390
+ ...metadata(post),
391
+ ...(params.action === "set_status" ? { status: params.status } : {}),
392
+ },
393
+ notice: preview(post, 150),
394
+ recipients: [...recipients],
395
+ };
396
+ }
397
+ }
398
+
399
+ export function validateMutation(params: BoardParams) {
400
+ if (
401
+ params.action === "create_channel" ||
402
+ params.new_channel_name !== undefined
403
+ ) {
404
+ const name = required(
405
+ params.new_channel_name ?? params.channel_name,
406
+ "channel_name",
407
+ );
408
+ if (
409
+ !name ||
410
+ !name.isWellFormed() ||
411
+ Buffer.byteLength(name) > 128 ||
412
+ name.trim() !== name ||
413
+ /\p{Cc}/u.test(name)
414
+ )
415
+ throw new Error(
416
+ "Channel must be 1-128 UTF-8 bytes without edge whitespace/control characters",
417
+ );
418
+ }
419
+ if (params.action === "post" || params.action === "set_status") {
420
+ const field = params.action === "set_status" ? "comment" : "text";
421
+ const text = required(params[field], field);
422
+ if (!text || !text.isWellFormed() || Buffer.byteLength(text) > 65536)
423
+ throw new Error(
424
+ `${params.action === "post" ? "Post" : "Comment"} must be 1-65536 UTF-8 bytes`,
425
+ );
426
+ }
427
+ }
@@ -0,0 +1,124 @@
1
+ import type { DatabaseSync } from "node:sqlite";
2
+ import { caseFold } from "unicode-case-folding";
3
+
4
+ export interface ThreadSummary {
5
+ thread_id: string;
6
+ status_message_id: string;
7
+ through_message_id: string;
8
+ created_at: string;
9
+ provider: string;
10
+ model: string;
11
+ reasoning: string;
12
+ text: string;
13
+ }
14
+
15
+ /** Derived closure snapshots, separate from posts and their activity/subscriptions. */
16
+ export class ThreadSummaries {
17
+ readonly available: boolean;
18
+ private readonly db: DatabaseSync;
19
+ constructor(db: DatabaseSync, write: boolean) {
20
+ this.db = db;
21
+ if (write)
22
+ db.exec(`CREATE TABLE IF NOT EXISTS thread_summaries (
23
+ board_id TEXT NOT NULL, thread_id TEXT NOT NULL,
24
+ status_message_id TEXT NOT NULL, through_message_id TEXT NOT NULL,
25
+ created_at TEXT NOT NULL, provider TEXT NOT NULL, model TEXT NOT NULL,
26
+ reasoning TEXT NOT NULL, text TEXT NOT NULL, body_search TEXT NOT NULL,
27
+ PRIMARY KEY(board_id,thread_id));`);
28
+ this.available = !!db
29
+ .prepare(
30
+ "SELECT 1 FROM sqlite_master WHERE type='table' AND name='thread_summaries'",
31
+ )
32
+ .get();
33
+ }
34
+ get(
35
+ board: string,
36
+ thread: string,
37
+ ): (ThreadSummary & { has_newer_posts: boolean }) | undefined {
38
+ if (!this.available) return undefined;
39
+ const row = this.db
40
+ .prepare(
41
+ `SELECT thread_id,status_message_id,through_message_id,created_at,provider,model,reasoning,text,
42
+ EXISTS(SELECT 1 FROM posts p WHERE p.board_id=s.board_id AND p.root=s.thread_id
43
+ AND p.seq>(SELECT seq FROM posts WHERE board_id=s.board_id AND id=s.through_message_id)) AS has_newer_posts
44
+ FROM thread_summaries s WHERE board_id=? AND thread_id=?`,
45
+ )
46
+ .get(board, thread) as
47
+ | (ThreadSummary & { has_newer_posts: number })
48
+ | undefined;
49
+ return row
50
+ ? { ...row, has_newer_posts: row.has_newer_posts === 1 }
51
+ : undefined;
52
+ }
53
+ /** A late completion cannot restore a reopened/reclosed or changed snapshot. */
54
+ save(board: string, summary: ThreadSummary): boolean {
55
+ if (
56
+ !summary.text.trim() ||
57
+ !summary.text.isWellFormed() ||
58
+ Buffer.byteLength(summary.text) > 65536
59
+ )
60
+ throw new Error("Summary must be 1-65536 UTF-8 bytes of nonempty text");
61
+ if (
62
+ ![summary.provider, summary.model, summary.reasoning].every((value) =>
63
+ value.trim(),
64
+ )
65
+ )
66
+ throw new Error("Summary model metadata is required");
67
+ const result = this.db
68
+ .prepare(`INSERT INTO thread_summaries
69
+ (board_id,thread_id,status_message_id,through_message_id,created_at,provider,model,reasoning,text,body_search)
70
+ SELECT ?,?,?,?,?,?,?,?,?,? WHERE EXISTS (
71
+ SELECT 1 FROM thread_statuses s WHERE s.board_id=? AND s.thread_id=?
72
+ AND s.status<>'open' AND s.message_id=?
73
+ AND (SELECT id FROM posts WHERE board_id=s.board_id AND root=s.thread_id ORDER BY seq DESC LIMIT 1)=?
74
+ )
75
+ ON CONFLICT(board_id,thread_id) DO UPDATE SET
76
+ status_message_id=excluded.status_message_id,through_message_id=excluded.through_message_id,
77
+ created_at=excluded.created_at,provider=excluded.provider,model=excluded.model,
78
+ reasoning=excluded.reasoning,text=excluded.text,body_search=excluded.body_search`)
79
+ .run(
80
+ board,
81
+ summary.thread_id,
82
+ summary.status_message_id,
83
+ summary.through_message_id,
84
+ summary.created_at,
85
+ summary.provider,
86
+ summary.model,
87
+ summary.reasoning,
88
+ summary.text,
89
+ caseFold(summary.text),
90
+ board,
91
+ summary.thread_id,
92
+ summary.status_message_id,
93
+ summary.through_message_id,
94
+ );
95
+ return result.changes === 1;
96
+ }
97
+ discard(board: string, thread: string): void {
98
+ if (this.available)
99
+ this.db
100
+ .prepare(
101
+ "DELETE FROM thread_summaries WHERE board_id=? AND thread_id=?",
102
+ )
103
+ .run(board, thread);
104
+ }
105
+ }
106
+
107
+ export function summaryPreview(
108
+ {
109
+ text,
110
+ provider: _provider,
111
+ model: _model,
112
+ reasoning: _reasoning,
113
+ ...metadata
114
+ }: ThreadSummary & { has_newer_posts: boolean },
115
+ chars: number,
116
+ ) {
117
+ const points = Array.from(text);
118
+ return {
119
+ ...metadata,
120
+ text_preview: points.slice(0, chars).join(""),
121
+ n_chars: points.length,
122
+ truncated: points.length > chars,
123
+ };
124
+ }