@howaboua/pi-agent-board 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/INTEGRATION.md +31 -0
  3. package/LICENSE +21 -0
  4. package/README.md +112 -2
  5. package/changelog.ts +337 -0
  6. package/dist/viewer/archive.js +242 -0
  7. package/dist/viewer/config.js +85 -0
  8. package/dist/viewer/contracts.js +1 -0
  9. package/dist/viewer/server.js +172 -0
  10. package/dist/viewer/source.js +29 -0
  11. package/dist/viewer/web/app.js +515 -0
  12. package/dist/viewer/web/index.html +41 -0
  13. package/dist/viewer/web/style.css +517 -0
  14. package/index.ts +122 -0
  15. package/package.json +68 -5
  16. package/src/activity.ts +274 -0
  17. package/src/archive.ts +108 -0
  18. package/src/awareness.ts +184 -0
  19. package/src/briefing.ts +24 -0
  20. package/src/config.ts +182 -0
  21. package/src/context-briefing.ts +227 -0
  22. package/src/contract.ts +246 -0
  23. package/src/delivery.ts +85 -0
  24. package/src/identity.ts +174 -0
  25. package/src/integration.ts +54 -0
  26. package/src/paging.ts +54 -0
  27. package/src/protocol.ts +78 -0
  28. package/src/queries.ts +171 -0
  29. package/src/response.ts +56 -0
  30. package/src/runtime.ts +614 -0
  31. package/src/search.ts +93 -0
  32. package/src/store.ts +391 -0
  33. package/src/summaries.ts +118 -0
  34. package/src/summarizer.ts +199 -0
  35. package/src/tool.ts +22 -0
  36. package/src/turns.ts +101 -0
  37. package/src/viewer/archive.ts +301 -0
  38. package/src/viewer/config.ts +111 -0
  39. package/src/viewer/contracts.ts +98 -0
  40. package/src/viewer/index.ts +158 -0
  41. package/src/viewer/server.ts +199 -0
  42. package/src/viewer/source.ts +33 -0
  43. package/src/viewer/web/app.js +515 -0
  44. package/src/viewer/web/index.html +41 -0
  45. package/src/viewer/web/style.css +517 -0
  46. package/tsconfig.json +5 -0
@@ -0,0 +1,85 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import type {
3
+ CodexContextBriefingHandler,
4
+ CodexDeveloperCustomMessage,
5
+ CodexDeveloperMessageOptions,
6
+ } from "@howaboua/pi-codex-conversion/developer-messages";
7
+
8
+ type Delivery =
9
+ typeof import("@howaboua/pi-codex-conversion/developer-messages");
10
+ let optionalDelivery: Promise<Delivery | undefined> | undefined;
11
+
12
+ function loadDelivery() {
13
+ return (optionalDelivery ??= import(
14
+ "@howaboua/pi-codex-conversion/developer-messages"
15
+ ).catch((error) => {
16
+ if (isMissingOptionalModule(error, "developer-messages")) return undefined;
17
+ throw error;
18
+ }));
19
+ }
20
+
21
+ export function isMissingOptionalModule(error: unknown, subpath: string) {
22
+ if (!(error instanceof Error) || !("code" in error)) return false;
23
+ const name = "@howaboua/pi-codex-conversion";
24
+ if (error.code === "ERR_PACKAGE_PATH_NOT_EXPORTED")
25
+ return (
26
+ error.message.includes(name) && error.message.includes(`./${subpath}`)
27
+ );
28
+ if (
29
+ error.code !== "ERR_MODULE_NOT_FOUND" &&
30
+ error.code !== "MODULE_NOT_FOUND"
31
+ )
32
+ return false;
33
+ const missing = error.message.match(
34
+ /Cannot find (?:package|module) ['"]([^'"]+)['"]/,
35
+ )?.[1];
36
+ return missing === name || missing === `${name}/${subpath}`;
37
+ }
38
+
39
+ let delivery: Delivery | undefined;
40
+ export async function initializeDelivery() {
41
+ delivery = await loadDelivery();
42
+ }
43
+
44
+ export function preparePolicyMessage(message: CodexDeveloperCustomMessage) {
45
+ return (
46
+ delivery?.withCodexDeveloperMessageDetails?.({
47
+ ...message,
48
+ details: message.details ?? {},
49
+ }) ?? message
50
+ );
51
+ }
52
+
53
+ export function registerInferenceBriefing(
54
+ pi: ExtensionAPI,
55
+ handler: CodexContextBriefingHandler,
56
+ ) {
57
+ let unregister: (() => void) | undefined;
58
+ const ready = loadDelivery().then((api) => {
59
+ delivery = api;
60
+ unregister = api?.registerCodexContextBriefing?.(pi, handler);
61
+ });
62
+ pi.on("session_shutdown", () => unregister?.());
63
+ return {
64
+ ready,
65
+ hosted: () => delivery?.hasCodexContextBriefingHost?.(pi) ?? false,
66
+ get outdated() {
67
+ return Boolean(delivery && !delivery.registerCodexContextBriefing);
68
+ },
69
+ };
70
+ }
71
+
72
+ export function sendPolicyMessage(
73
+ pi: ExtensionAPI,
74
+ message: CodexDeveloperCustomMessage,
75
+ options: CodexDeveloperMessageOptions,
76
+ ) {
77
+ if (delivery?.trySendCodexDeveloperCustomMessage?.(pi, message, options))
78
+ return;
79
+ pi.sendMessage(
80
+ message,
81
+ options.deliverAs === "nextTurn"
82
+ ? { ...options, deliverAs: "steer" }
83
+ : options,
84
+ );
85
+ }
@@ -0,0 +1,174 @@
1
+ import { resolve } from "node:path";
2
+ import { Type } from "@earendil-works/pi-ai";
3
+ import type {
4
+ ExtensionAPI,
5
+ ExtensionContext,
6
+ } from "@earendil-works/pi-coding-agent";
7
+ import type { Static } from "typebox";
8
+ import { Check } from "typebox/value";
9
+ import { readBoardConfig } from "./config.js";
10
+
11
+ const uuid = Type.String({ pattern: "^[a-f0-9-]{36}$" });
12
+ export const BindingSchema = Type.Object(
13
+ {
14
+ protocol: Type.Literal(1),
15
+ boardId: uuid,
16
+ rootSessionId: uuid,
17
+ sessionId: uuid,
18
+ agentName: Type.String({ pattern: "^/root(?:/[a-zA-Z0-9_-]+)*$" }),
19
+ ownerFolder: Type.String({ minLength: 1 }),
20
+ databasePath: Type.String({ minLength: 1 }),
21
+ enabled: Type.Boolean(),
22
+ upstream: Type.Optional(Type.String({ minLength: 1 })),
23
+ },
24
+ { additionalProperties: false },
25
+ );
26
+ export type BoardBinding = Static<typeof BindingSchema>;
27
+ const ChildSchema = Type.Object({
28
+ parentSessionId: uuid,
29
+ binding: BindingSchema,
30
+ machine: Type.String(),
31
+ sessionFile: Type.String({ minLength: 1 }),
32
+ });
33
+ export type BoardChild = Static<typeof ChildSchema>;
34
+ const BINDING = "shepherdr-board-binding";
35
+ const MEMBER = "shepherdr-board-member";
36
+ const CHILD = "shepherdr-board-child";
37
+ const SETTING = "shepherdr-board-setting";
38
+ const defaults = new WeakMap<ExtensionContext["sessionManager"], boolean>();
39
+ export function setBoardDefault(ctx: ExtensionContext, enabled: boolean) {
40
+ defaults.set(ctx.sessionManager, enabled);
41
+ }
42
+ const REMOVED = "shepherdr-board-removed";
43
+ const SettingSchema = Type.Object({
44
+ sessionId: uuid,
45
+ enabled: Type.Union([Type.Boolean(), Type.Null()]),
46
+ });
47
+
48
+ function sessionBoardSetting(ctx: ExtensionContext): boolean | undefined {
49
+ let enabled: boolean | undefined;
50
+ for (const entry of ctx.sessionManager.getEntries()) {
51
+ if (entry.type !== "custom" || entry.customType !== SETTING) continue;
52
+ if (!Check(SettingSchema, entry.data))
53
+ throw new Error("Invalid saved board setting");
54
+ const value = entry.data as Static<typeof SettingSchema>;
55
+ if (value.sessionId === ctx.sessionManager.getSessionId())
56
+ enabled = value.enabled ?? undefined;
57
+ }
58
+ return enabled;
59
+ }
60
+
61
+ export function saveBoardSetting(
62
+ pi: ExtensionAPI,
63
+ ctx: ExtensionContext,
64
+ enabled: boolean | undefined,
65
+ ) {
66
+ pi.appendEntry(SETTING, {
67
+ sessionId: ctx.sessionManager.getSessionId(),
68
+ enabled: enabled ?? null,
69
+ });
70
+ }
71
+
72
+ export function rootBoardSetting(ctx: ExtensionContext) {
73
+ try {
74
+ const config = readBoardConfig(
75
+ resolve(ctx.sessionManager.getCwd()),
76
+ defaults.get(ctx.sessionManager),
77
+ );
78
+ const session = sessionBoardSetting(ctx);
79
+ return {
80
+ enabled: session ?? config.folder ?? config.global,
81
+ source:
82
+ session !== undefined
83
+ ? "session"
84
+ : config.folder !== undefined
85
+ ? "folder"
86
+ : "global default",
87
+ };
88
+ } catch (error) {
89
+ return {
90
+ enabled: false,
91
+ source: "invalid configuration",
92
+ error: String(error),
93
+ };
94
+ }
95
+ }
96
+
97
+ export function parseBinding(value: unknown): BoardBinding {
98
+ if (!Check(BindingSchema, value))
99
+ throw new Error("Invalid Shepherdr board binding");
100
+ return value as BoardBinding;
101
+ }
102
+ export function binding(ctx: ExtensionContext): BoardBinding {
103
+ const sessionId = ctx.sessionManager.getSessionId();
104
+ let saved: BoardBinding | undefined;
105
+ for (const entry of ctx.sessionManager.getEntries()) {
106
+ if (entry.type !== "custom" || entry.customType !== BINDING) continue;
107
+ const candidate = parseBinding(entry.data);
108
+ if (candidate.sessionId === sessionId) saved = candidate;
109
+ }
110
+ const ownerFolder = resolve(ctx.sessionManager.getCwd());
111
+ if (saved?.upstream) return saved;
112
+ return {
113
+ ...(saved ?? {
114
+ protocol: 1,
115
+ sessionId,
116
+ rootSessionId: sessionId,
117
+ boardId: sessionId,
118
+ agentName: "/root",
119
+ ownerFolder,
120
+ databasePath: resolve(ownerFolder, ".pi", "agent-message-board.sqlite"),
121
+ enabled: false,
122
+ }),
123
+ enabled: rootBoardSetting(ctx).enabled,
124
+ };
125
+ }
126
+ export function saveBinding(pi: ExtensionAPI, value: BoardBinding) {
127
+ pi.appendEntry(BINDING, value);
128
+ }
129
+ export function members(ctx: ExtensionContext): BoardBinding[] {
130
+ const own = binding(ctx);
131
+ const found = new Map([[own.agentName, own]]);
132
+ for (const entry of ctx.sessionManager.getEntries()) {
133
+ if (entry.type === "custom" && entry.customType === REMOVED) {
134
+ const value = parseBinding(entry.data);
135
+ if (value.boardId === own.boardId) found.delete(value.agentName);
136
+ continue;
137
+ }
138
+ if (entry.type !== "custom" || entry.customType !== MEMBER) continue;
139
+ const value = parseBinding(entry.data);
140
+ if (value.rootSessionId === own.sessionId && value.boardId === own.boardId)
141
+ found.set(value.agentName, value);
142
+ }
143
+ return [...found.values()];
144
+ }
145
+ export function saveMember(pi: ExtensionAPI, value: BoardBinding) {
146
+ pi.appendEntry(MEMBER, value);
147
+ }
148
+ export function children(ctx: ExtensionContext): BoardChild[] {
149
+ const own = binding(ctx);
150
+ const found = new Map<string, BoardChild>();
151
+ for (const entry of ctx.sessionManager.getEntries()) {
152
+ if (entry.type === "custom" && entry.customType === REMOVED) {
153
+ const value = parseBinding(entry.data);
154
+ if (value.boardId === own.boardId) found.delete(value.agentName);
155
+ continue;
156
+ }
157
+ if (entry.type !== "custom" || entry.customType !== CHILD) continue;
158
+ if (!Check(ChildSchema, entry.data))
159
+ throw new Error("Invalid saved board child route");
160
+ const value = entry.data as BoardChild;
161
+ if (
162
+ value.parentSessionId === own.sessionId &&
163
+ value.binding.boardId === own.boardId
164
+ )
165
+ found.set(value.binding.agentName, value);
166
+ }
167
+ return [...found.values()];
168
+ }
169
+ export function saveChild(pi: ExtensionAPI, value: BoardChild) {
170
+ pi.appendEntry(CHILD, value);
171
+ }
172
+ export function removeMember(pi: ExtensionAPI, value: BoardBinding) {
173
+ pi.appendEntry(REMOVED, value);
174
+ }
@@ -0,0 +1,54 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import type { BoardBinding } from "./identity.js";
3
+ import type { BoardEnvelope } from "./protocol.js";
4
+
5
+ /** Optional membership transport. The runtime owns storage, settings and delivery. */
6
+ export interface BoardAdapter {
7
+ briefing?(
8
+ member: boolean,
9
+ population: "empty" | "populated" | "unavailable",
10
+ ): string;
11
+ request(
12
+ route: string,
13
+ request: BoardEnvelope,
14
+ signal?: AbortSignal,
15
+ ): Promise<unknown>;
16
+ commitDirectory(
17
+ own: BoardBinding,
18
+ directory: BoardBinding[],
19
+ caller: BoardBinding,
20
+ request: Extract<
21
+ BoardEnvelope,
22
+ { operation: "board-register" | "board-unregister" }
23
+ >,
24
+ ): unknown;
25
+ routeNotice(
26
+ ctx: ExtensionContext,
27
+ request: Extract<BoardEnvelope, { operation: "board-notify" }>,
28
+ signal?: AbortSignal,
29
+ ): Promise<unknown>;
30
+ propagateEnabled(ctx: ExtensionContext, enabled: boolean): Promise<void>;
31
+ }
32
+
33
+ export type { BoardScope } from "./config.js";
34
+ export {
35
+ contextBriefingWindow,
36
+ hasContextRollover,
37
+ recordContextBriefing,
38
+ registerContextBriefing,
39
+ } from "./context-briefing.js";
40
+ export type { BoardBinding } from "./identity.js";
41
+ export {
42
+ BindingSchema,
43
+ binding,
44
+ children,
45
+ members,
46
+ parseBinding,
47
+ removeMember,
48
+ rootBoardSetting,
49
+ saveBinding,
50
+ saveChild,
51
+ saveMember,
52
+ } from "./identity.js";
53
+ export type { BoardEnvelope } from "./protocol.js";
54
+ export { isBoardEnvelope } from "./protocol.js";
package/src/paging.ts ADDED
@@ -0,0 +1,54 @@
1
+ import type { BoardParams } from "./contract.js";
2
+
3
+ export interface PostRecord {
4
+ message_id: string;
5
+ channel_name: string;
6
+ author: string;
7
+ thread_id: string;
8
+ created_at: string;
9
+ text: string;
10
+ }
11
+ export const POST_COLUMNS =
12
+ "id AS message_id,channel AS channel_name,author,root AS thread_id,created_at,text";
13
+ export function metadata({ text: _text, ...value }: PostRecord) {
14
+ return value;
15
+ }
16
+ export function preview(post: PostRecord, chars: number) {
17
+ const text = Array.from(post.text);
18
+ return {
19
+ ...metadata(post),
20
+ text_preview: text.slice(0, chars).join(""),
21
+ n_chars: text.length,
22
+ truncated: text.length > chars,
23
+ };
24
+ }
25
+ export function window(params: BoardParams) {
26
+ const limit = Math.min(params.limit ?? 20, 50);
27
+ let offset = 0;
28
+ if (params.cursor !== undefined) {
29
+ const bytes = Buffer.from(params.cursor, "base64url");
30
+ if (bytes.length !== 4 || bytes.toString("base64url") !== params.cursor)
31
+ throw new Error("Invalid cursor");
32
+ offset = bytes.readUInt32BE();
33
+ }
34
+ return { limit, offset };
35
+ }
36
+ export function page<T>(values: T[], params: BoardParams) {
37
+ const { limit, offset } = window(params);
38
+ const has_more = values.length > limit;
39
+ const results = values.slice(0, limit);
40
+ const next_cursor = has_more ? cursor(offset + results.length) : null;
41
+ return { results, n_returned: results.length, has_more, next_cursor };
42
+ }
43
+ export function cursor(offset: number) {
44
+ if (offset > 0xffffffff) throw new Error("Cursor exceeds board limit");
45
+ const bytes = Buffer.alloc(4);
46
+ bytes.writeUInt32BE(offset);
47
+ return bytes.toString("base64url");
48
+ }
49
+ export function budget(params: BoardParams, count: number) {
50
+ return Math.min(
51
+ params.max_chars_per_post ?? 1000,
52
+ Math.floor(20000 / Math.max(1, count)),
53
+ );
54
+ }
@@ -0,0 +1,78 @@
1
+ import { Type } from "@earendil-works/pi-ai";
2
+ import type { Static } from "typebox";
3
+ import { Check } from "typebox/value";
4
+ import { BindingSchema } from "./identity.js";
5
+
6
+ const NoticeSchema = Type.Object(
7
+ {
8
+ message_id: Type.String(),
9
+ channel_name: Type.String(),
10
+ author: Type.String(),
11
+ thread_id: Type.String(),
12
+ created_at: Type.String(),
13
+ text_preview: Type.String({ maxLength: 300 }),
14
+ n_chars: Type.Integer({ minimum: 0 }),
15
+ truncated: Type.Boolean(),
16
+ },
17
+ { additionalProperties: false },
18
+ );
19
+ const Protocol = Type.Union([
20
+ Type.Object({
21
+ operation: Type.Literal("board-catchup"),
22
+ caller: BindingSchema,
23
+ seen: Type.Array(Type.String()),
24
+ }),
25
+ Type.Object({
26
+ operation: Type.Literal("board-bind"),
27
+ binding: BindingSchema,
28
+ }),
29
+ Type.Object({
30
+ operation: Type.Literal("board-register"),
31
+ caller: BindingSchema,
32
+ member: BindingSchema,
33
+ }),
34
+ Type.Object({
35
+ operation: Type.Literal("board-unregister"),
36
+ caller: BindingSchema,
37
+ member: BindingSchema,
38
+ }),
39
+ Type.Object({
40
+ operation: Type.Literal("board-enabled"),
41
+ boardId: Type.String(),
42
+ enabled: Type.Boolean(),
43
+ }),
44
+ Type.Object({
45
+ operation: Type.Literal("board-active"),
46
+ caller: BindingSchema,
47
+ turnId: Type.Union([Type.String(), Type.Null()]),
48
+ previousTurnId: Type.Optional(Type.String()),
49
+ }),
50
+ Type.Object({
51
+ operation: Type.Literal("board-call"),
52
+ caller: BindingSchema,
53
+ params: Type.Unknown(),
54
+ requestId: Type.String(),
55
+ }),
56
+ Type.Object({
57
+ operation: Type.Literal("board-notify"),
58
+ boardId: Type.String(),
59
+ target: Type.String(),
60
+ sessionId: Type.String(),
61
+ turnId: Type.String(),
62
+ notice: NoticeSchema,
63
+ }),
64
+ ]);
65
+ export type BoardEnvelope = Static<typeof Protocol>;
66
+ export function parseEnvelope(value: unknown): BoardEnvelope {
67
+ if (!Check(Protocol, value)) throw new Error("Invalid board host request");
68
+ return value as BoardEnvelope;
69
+ }
70
+ export function isBoardEnvelope(value: unknown): boolean {
71
+ return (
72
+ !!value &&
73
+ typeof value === "object" &&
74
+ "operation" in value &&
75
+ typeof value.operation === "string" &&
76
+ value.operation.startsWith("board-")
77
+ );
78
+ }
package/src/queries.ts ADDED
@@ -0,0 +1,171 @@
1
+ import { caseFold } from "unicode-case-folding";
2
+ import { type BoardParams, required } from "./contract.js";
3
+ import {
4
+ budget,
5
+ cursor,
6
+ metadata,
7
+ POST_COLUMNS,
8
+ type PostRecord,
9
+ page,
10
+ preview,
11
+ window,
12
+ } from "./paging.js";
13
+ import { searchBoard } from "./search.js";
14
+ import type { BoardStore } from "./store.js";
15
+ import { summaryPreview } from "./summaries.js";
16
+
17
+ export function queryBoard(
18
+ store: BoardStore,
19
+ ownBoard: string,
20
+ params: BoardParams,
21
+ ): Record<string, unknown> {
22
+ const board = params.board_id ?? ownBoard;
23
+ const { limit, offset } = window(params);
24
+ const order = params.recent_first === false ? "ASC" : "DESC";
25
+ if (params.action === "list_boards") {
26
+ const rows = store.all<{
27
+ board_id: string;
28
+ root_session_id: string;
29
+ owner_folder: string;
30
+ created_at: string;
31
+ last_activity_at: string;
32
+ channel_count: number;
33
+ message_count: number;
34
+ }>(
35
+ `SELECT b.*,
36
+ COALESCE((SELECT MAX(created_at) FROM posts p WHERE p.board_id=b.board_id),(SELECT MAX(created_at) FROM channels c WHERE c.board_id=b.board_id),b.created_at) AS last_activity_at,
37
+ (SELECT COUNT(*) FROM channels c WHERE c.board_id=b.board_id) AS channel_count,
38
+ (SELECT COUNT(*) FROM posts p WHERE p.board_id=b.board_id) AS message_count
39
+ FROM boards b ORDER BY last_activity_at DESC,board_id DESC LIMIT ? OFFSET ?`,
40
+ limit + 1,
41
+ offset,
42
+ );
43
+ return page(
44
+ rows.map((row) => ({ ...row, current: row.board_id === ownBoard })),
45
+ params,
46
+ );
47
+ }
48
+ if (params.action === "get_channels") {
49
+ const rows = store.all<{ name: string }>(
50
+ `SELECT name FROM channels c WHERE board_id=? AND instr(name_search,?)>0 ORDER BY
51
+ COALESCE((SELECT MAX(created_at) FROM posts p WHERE p.board_id=c.board_id AND p.channel=c.name),c.created_at) ${order},name ${order} LIMIT ? OFFSET ?`,
52
+ board,
53
+ caseFold(params.query ?? ""),
54
+ limit + 1,
55
+ offset,
56
+ );
57
+ return page(
58
+ rows.map(({ name }) => store.channel(board, name)),
59
+ params,
60
+ );
61
+ }
62
+ if (params.action === "read_post") {
63
+ const post = store.post(board, required(params.message_id, "message_id"));
64
+ const chars = Array.from(post.text);
65
+ const offset = Math.min(params.offset_chars ?? 0, chars.length);
66
+ const text = chars
67
+ .slice(offset, offset + Math.min(params.limit_chars ?? 20000, 20000))
68
+ .join("");
69
+ return {
70
+ ...metadata(post),
71
+ text,
72
+ n_chars: chars.length,
73
+ next_offset_chars: offset + Array.from(text).length,
74
+ };
75
+ }
76
+ if (params.action === "read_thread") {
77
+ const root = store.root(board, required(params.thread_id, "thread_id"));
78
+ const summary = params.full
79
+ ? undefined
80
+ : store.summaries.get(board, root.thread_id);
81
+ if (summary) {
82
+ const points = Array.from(summary.text);
83
+ const start = Math.min(offset, points.length);
84
+ const text = points.slice(start, start + budget(params, 1)).join("");
85
+ const next = start + Array.from(text).length;
86
+ return {
87
+ view: "summary",
88
+ root_post: metadata(root),
89
+ ...store.threadStatus(board, root.thread_id),
90
+ summary: {
91
+ ...summaryPreview(summary, 0),
92
+ text_preview: text,
93
+ offset_chars: start,
94
+ truncated: next < points.length,
95
+ },
96
+ has_more: next < points.length,
97
+ next_cursor: next < points.length ? cursor(next) : null,
98
+ };
99
+ }
100
+ const replies = store.all<PostRecord>(
101
+ `SELECT ${POST_COLUMNS} FROM posts WHERE board_id=? AND root=? AND id<>root ORDER BY created_at DESC,seq DESC LIMIT ? OFFSET ?`,
102
+ board,
103
+ root.message_id,
104
+ limit + 1,
105
+ offset,
106
+ );
107
+ const chars = budget(params, Math.min(replies.length, limit) + 1);
108
+ return {
109
+ view: "full",
110
+ root_post: preview(root, chars),
111
+ ...store.threadStatus(board, root.thread_id),
112
+ ...page(
113
+ replies.map((post) => preview(post, chars)),
114
+ params,
115
+ ),
116
+ };
117
+ }
118
+ if (params.action === "list_threads") {
119
+ const channel = store.channel(
120
+ board,
121
+ required(params.channel_name, "channel_name"),
122
+ );
123
+ const sort =
124
+ params.sort === "activity"
125
+ ? "(SELECT MAX(created_at) FROM posts r WHERE r.board_id=p.board_id AND r.root=p.id)"
126
+ : "p.created_at";
127
+ const roots = store.all<PostRecord>(
128
+ `SELECT ${POST_COLUMNS} FROM posts p WHERE board_id=? AND channel=? AND id=root ORDER BY ${sort} ${order},seq ${order} LIMIT ? OFFSET ?`,
129
+ board,
130
+ channel.channel_name,
131
+ limit + 1,
132
+ offset,
133
+ );
134
+ const chars = budget(params, 2 * Math.min(roots.length, limit));
135
+ return page(
136
+ roots.map((root) => {
137
+ const summary = store.summaries.get(board, root.thread_id);
138
+ const reply = store.one<PostRecord>(
139
+ `SELECT ${POST_COLUMNS} FROM posts WHERE board_id=? AND root=? AND id<>root ORDER BY created_at DESC,seq DESC LIMIT 1`,
140
+ board,
141
+ root.message_id,
142
+ );
143
+ const count =
144
+ store.one<{ n: number }>(
145
+ "SELECT COUNT(*) AS n FROM posts WHERE board_id=? AND root=? AND id<>root",
146
+ board,
147
+ root.message_id,
148
+ )?.n ?? 0;
149
+ return {
150
+ thread_id: root.message_id,
151
+ ...store.threadStatus(board, root.message_id),
152
+ ...(summary
153
+ ? { summary: summaryPreview(summary, chars) }
154
+ : { root_post: preview(root, chars) }),
155
+ reply_count: count,
156
+ last_activity_at:
157
+ reply && reply.created_at > root.created_at
158
+ ? reply.created_at
159
+ : root.created_at,
160
+ ...(summary
161
+ ? {}
162
+ : { latest_reply: reply ? preview(reply, chars) : null }),
163
+ };
164
+ }),
165
+ params,
166
+ );
167
+ }
168
+ if (params.action === "search_posts")
169
+ return searchBoard(store, board, params);
170
+ throw new Error(`Unsupported board read: ${params.action}`);
171
+ }
@@ -0,0 +1,56 @@
1
+ import type { BoardParams } from "./contract.js";
2
+
3
+ // Includes UTF-8 text, JSON escaping and metadata, in every tool mode.
4
+ const MAX_RESPONSE_BYTES = 8000;
5
+
6
+ export function serializeBoardResult(value: unknown): string {
7
+ const text = JSON.stringify(value);
8
+ if (Buffer.byteLength(text) > MAX_RESPONSE_BYTES)
9
+ throw new Error(
10
+ "Result exceeds the output budget. Reduce limit or max_chars_per_post; use read_post with a smaller limit_chars for long posts.",
11
+ );
12
+ return text;
13
+ }
14
+
15
+ export function checkMutationBudget(caller: string, params: BoardParams) {
16
+ // Native acknowledgement reserve, checked before opening or creating storage.
17
+ const target = params.target_agent ?? "";
18
+ if (
19
+ 2048 + Buffer.byteLength(caller) + Buffer.byteLength(target) >
20
+ MAX_RESPONSE_BYTES
21
+ )
22
+ throw new Error(
23
+ "Output budget is too small to acknowledge a message-board mutation; no change was made.",
24
+ );
25
+ }
26
+
27
+ export function boundedBoardRead<T extends { value: unknown }>(
28
+ params: BoardParams,
29
+ fetch: (request: BoardParams) => T,
30
+ ): T {
31
+ const limit = Math.min(params.limit ?? 20, 50);
32
+ const chars = Math.min(params.max_chars_per_post ?? 1000, 20000);
33
+ const postChars = Math.min(params.limit_chars ?? 20000, 20000);
34
+ const previews = ["list_threads", "search_posts", "read_thread"].includes(
35
+ params.action,
36
+ );
37
+ const post = params.action === "read_post";
38
+ const largest = post ? postChars : previews ? Math.max(limit, chars) : limit;
39
+ for (let scale = 1; ; scale *= 2) {
40
+ const reduced = (value: number) => Math.max(1, Math.floor(value / scale));
41
+ // Reissue the original cursor/offset so continuation matches the reduced page.
42
+ const result = fetch({
43
+ ...params,
44
+ ...(post
45
+ ? { limit_chars: reduced(postChars) }
46
+ : { limit: reduced(limit) }),
47
+ ...(previews ? { max_chars_per_post: reduced(chars) } : {}),
48
+ });
49
+ if (Buffer.byteLength(JSON.stringify(result.value)) <= MAX_RESPONSE_BYTES)
50
+ return result;
51
+ if (Math.floor(largest / scale) <= 1)
52
+ throw new Error(
53
+ "The output budget is too small for this result's metadata.",
54
+ );
55
+ }
56
+ }