@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
package/src/config.ts ADDED
@@ -0,0 +1,182 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import {
3
+ existsSync,
4
+ mkdirSync,
5
+ readFileSync,
6
+ realpathSync,
7
+ renameSync,
8
+ rmSync,
9
+ writeFileSync,
10
+ } from "node:fs";
11
+ import { dirname, resolve } from "node:path";
12
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
13
+
14
+ const CONFIG_FILE = "pi-shepherdr.json";
15
+ export type BoardScope = "session" | "folder" | "global";
16
+
17
+ function object(value: unknown): value is Record<string, unknown> {
18
+ return typeof value === "object" && value !== null && !Array.isArray(value);
19
+ }
20
+
21
+ function readDocument(path: string): Record<string, unknown> {
22
+ if (!existsSync(path)) return {};
23
+ try {
24
+ const value: unknown = JSON.parse(readFileSync(path, "utf8"));
25
+ if (!object(value)) throw new Error("configuration must be an object");
26
+ if (value["board"] !== undefined && !object(value["board"]))
27
+ throw new Error("board must be an object");
28
+ return value;
29
+ } catch (error) {
30
+ throw new Error(`Could not read ${path}: ${String(error)}`, {
31
+ cause: error,
32
+ });
33
+ }
34
+ }
35
+
36
+ function readEnabled(path: string, scope: "folder" | "global") {
37
+ const document = readDocument(path);
38
+ const board = object(document["board"]) ? document["board"] : {};
39
+ const field = scope === "global" ? "enabledGlobally" : "enabled";
40
+ const wrongField = scope === "global" ? "enabled" : "enabledGlobally";
41
+ if (wrongField in board)
42
+ throw new Error(`${path}: use board.${field} for ${scope} enablement`);
43
+ const value = board[field];
44
+ if (value !== undefined && typeof value !== "boolean")
45
+ throw new Error(`${path}: board.${field} must be a boolean`);
46
+ return value;
47
+ }
48
+
49
+ function boardConfigPaths(folder: string) {
50
+ // Keep aliases on one write target so atomic saves do not replace symlinks.
51
+ function configPath(directory: string) {
52
+ const path = resolve(directory, CONFIG_FILE);
53
+ return existsSync(path) ? realpathSync(path) : path;
54
+ }
55
+ const global = configPath(getAgentDir());
56
+ const local = configPath(resolve(folder, ".pi"));
57
+ return {
58
+ global,
59
+ // The global config is never also a folder config.
60
+ folder: local === global ? undefined : local,
61
+ };
62
+ }
63
+
64
+ export function readBoardConfig(folder: string, defaultEnabled = false) {
65
+ const paths = boardConfigPaths(folder);
66
+ const global = readEnabled(paths.global, "global");
67
+ return {
68
+ paths,
69
+ folder: paths.folder ? readEnabled(paths.folder, "folder") : undefined,
70
+ global: global ?? defaultEnabled,
71
+ };
72
+ }
73
+
74
+ export function writeBoardConfig(
75
+ folder: string,
76
+ scope: "folder" | "global",
77
+ enabled: boolean | undefined,
78
+ ) {
79
+ if (scope === "global" && enabled === undefined)
80
+ throw new Error("Global enablement must be on or off");
81
+ const path = boardConfigPaths(folder)[scope];
82
+ if (!path)
83
+ throw new Error(
84
+ "This folder's config is the global config; use a session override instead",
85
+ );
86
+ readEnabled(path, scope);
87
+ const document = readDocument(path);
88
+ const board = object(document["board"]) ? { ...document["board"] } : {};
89
+ const field = scope === "global" ? "enabledGlobally" : "enabled";
90
+ if (enabled === undefined) delete board[field];
91
+ else board[field] = enabled;
92
+ if (enabled === undefined && !existsSync(path)) return;
93
+ document["board"] = board;
94
+ writeDocument(path, document);
95
+ }
96
+
97
+ function writeDocument(path: string, document: Record<string, unknown>) {
98
+ mkdirSync(dirname(path), { recursive: true });
99
+ const temporary = `${path}.${randomUUID()}.tmp`;
100
+ try {
101
+ writeFileSync(temporary, `${JSON.stringify(document, null, 2)}\n`, {
102
+ mode: 0o600,
103
+ });
104
+ renameSync(temporary, path);
105
+ } finally {
106
+ rmSync(temporary, { force: true });
107
+ }
108
+ }
109
+
110
+ export type BoardSummarySelection = "luna" | "custom";
111
+ export type BoardSummaryModel = {
112
+ provider: string;
113
+ model: string;
114
+ reasoning: "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
115
+ };
116
+
117
+ const LUNA_SUMMARY_MODEL: BoardSummaryModel = {
118
+ provider: "openai-codex",
119
+ model: "gpt-6-luna",
120
+ reasoning: "high",
121
+ };
122
+
123
+ export function readBoardSummaryConfig(folder: string) {
124
+ const path = boardConfigPaths(folder).global;
125
+ const document = readDocument(path);
126
+ const board = object(document["board"]) ? document["board"] : {};
127
+ const summary = board["summary"];
128
+ if (summary !== undefined && !object(summary))
129
+ throw new Error(`${path}: board.summary must be an object`);
130
+ const selection = summary?.["selection"] ?? "luna";
131
+ if (selection !== "luna" && selection !== "custom")
132
+ throw new Error(`${path}: board.summary.selection must be luna or custom`);
133
+ return { path, selection, custom: summary?.["custom"] };
134
+ }
135
+
136
+ function customSummaryModel(value: unknown, path: string): BoardSummaryModel {
137
+ const instruction = `Edit board.summary.custom in ${path}: set provider, model and reasoning (off|minimal|low|medium|high|xhigh|max)`;
138
+ if (!object(value)) throw new Error(instruction);
139
+ const { provider, model, reasoning } = value;
140
+ if (
141
+ typeof provider !== "string" ||
142
+ !provider.trim() ||
143
+ typeof model !== "string" ||
144
+ !model.trim() ||
145
+ (reasoning !== "off" &&
146
+ reasoning !== "minimal" &&
147
+ reasoning !== "low" &&
148
+ reasoning !== "medium" &&
149
+ reasoning !== "high" &&
150
+ reasoning !== "xhigh" &&
151
+ reasoning !== "max")
152
+ )
153
+ throw new Error(instruction);
154
+ return { provider, model, reasoning };
155
+ }
156
+
157
+ export function resolveBoardSummaryModel(folder: string): BoardSummaryModel {
158
+ const config = readBoardSummaryConfig(folder);
159
+ return config.selection === "luna"
160
+ ? { ...LUNA_SUMMARY_MODEL }
161
+ : customSummaryModel(config.custom, config.path);
162
+ }
163
+
164
+ export function writeBoardSummarySelection(
165
+ folder: string,
166
+ selection: BoardSummarySelection,
167
+ ) {
168
+ const config = readBoardSummaryConfig(folder);
169
+ const document = readDocument(config.path);
170
+ const board = object(document["board"]) ? { ...document["board"] } : {};
171
+ const summary = object(board["summary"]) ? { ...board["summary"] } : {};
172
+ summary["luna"] = {
173
+ ...(object(summary["luna"]) ? summary["luna"] : {}),
174
+ ...LUNA_SUMMARY_MODEL,
175
+ };
176
+ if (summary["custom"] === undefined)
177
+ summary["custom"] = { provider: "", model: "", reasoning: "high" };
178
+ summary["selection"] = selection;
179
+ board["summary"] = summary;
180
+ document["board"] = board;
181
+ writeDocument(config.path, document);
182
+ }
@@ -0,0 +1,227 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import {
3
+ buildSessionContext,
4
+ type ExtensionAPI,
5
+ type ExtensionContext,
6
+ } from "@earendil-works/pi-coding-agent";
7
+ import type {
8
+ CODEX_CONTEXT_BRIEFING_TYPE,
9
+ CodexContextBriefing,
10
+ CodexContextBriefingHandler,
11
+ } from "@howaboua/pi-codex-conversion/developer-messages";
12
+ import { registerInferenceBriefing } from "./delivery.js";
13
+
14
+ // Conversion projects this durable protocol in inference, compaction and native replay.
15
+ const BRIEFING: typeof CODEX_CONTEXT_BRIEFING_TYPE = "codex-context-briefing";
16
+
17
+ export function registerContextBriefing(
18
+ pi: ExtensionAPI,
19
+ name: string,
20
+ relevant: (ctx: ExtensionContext) => boolean,
21
+ record: CodexContextBriefingHandler,
22
+ ) {
23
+ const hosted = registerInferenceBriefing(pi, record);
24
+ const warned = new Set<string>();
25
+ pi.on("context_with_system", async (event, ctx) => {
26
+ await hosted.ready;
27
+ if (hosted.hosted()) return;
28
+ if (
29
+ hosted.outdated &&
30
+ relevant(ctx) &&
31
+ !warned.has(ctx.sessionManager.getSessionId())
32
+ ) {
33
+ warned.add(ctx.sessionManager.getSessionId());
34
+ ctx.ui.notify(
35
+ `Update Codex Conversion and reload to preserve ${name} briefings through its context rollover and native replay. Native Pi briefings and other agent tools remain available.`,
36
+ "warning",
37
+ );
38
+ }
39
+ try {
40
+ await record(ctx, undefined, event.messages);
41
+ return { messages: projectNative(ctx, event.messages) };
42
+ } catch (error) {
43
+ ctx.abort();
44
+ throw error;
45
+ }
46
+ });
47
+ }
48
+
49
+ export function contextBriefingWindow(
50
+ ctx: ExtensionContext,
51
+ windowId?: string,
52
+ ) {
53
+ const branch = ctx.sessionManager.getBranch();
54
+ const compaction = branch.findLastIndex(
55
+ (entry) =>
56
+ entry.type === "compaction" &&
57
+ !(
58
+ entry.details &&
59
+ typeof entry.details === "object" &&
60
+ "strategy" in entry.details &&
61
+ entry.details.strategy === "codex-context-window"
62
+ ),
63
+ );
64
+ const boundary = branch.findLastIndex(
65
+ (entry) =>
66
+ entry.type === "custom_message" &&
67
+ entry.customType === "codex-context-window" &&
68
+ entry.details &&
69
+ typeof entry.details === "object" &&
70
+ "contextManagement" in entry.details &&
71
+ entry.details.contextManagement &&
72
+ typeof entry.details.contextManagement === "object" &&
73
+ "kind" in entry.details.contextManagement &&
74
+ entry.details.contextManagement.kind === "window",
75
+ );
76
+ return compaction > boundary
77
+ ? branch[compaction]!.id
78
+ : (windowId ?? ctx.sessionManager.getSessionId());
79
+ }
80
+
81
+ export function hasContextRollover(ctx: ExtensionContext): boolean {
82
+ return ctx.sessionManager.getBranch().some((entry) => {
83
+ if (entry.type === "compaction") return true;
84
+ if (
85
+ entry.type !== "custom_message" ||
86
+ entry.customType !== "codex-context-window" ||
87
+ !entry.details ||
88
+ typeof entry.details !== "object" ||
89
+ !("contextManagement" in entry.details)
90
+ )
91
+ return false;
92
+ const window = entry.details.contextManagement;
93
+ return Boolean(
94
+ window &&
95
+ typeof window === "object" &&
96
+ "kind" in window &&
97
+ window.kind === "window" &&
98
+ "windowNumber" in window &&
99
+ typeof window.windowNumber === "number" &&
100
+ window.windowNumber > 0,
101
+ );
102
+ });
103
+ }
104
+
105
+ export async function recordContextBriefing(
106
+ pi: ExtensionAPI,
107
+ ctx: ExtensionContext,
108
+ owner: string,
109
+ key: string,
110
+ content: () => Promise<string | undefined>,
111
+ ) {
112
+ const saved = ctx.sessionManager
113
+ .getEntries()
114
+ .findLast(
115
+ (entry) =>
116
+ entry.type === "custom" &&
117
+ entry.customType === BRIEFING &&
118
+ readBriefing(entry.data).owner === owner &&
119
+ readBriefing(entry.data).key === key,
120
+ );
121
+ if (saved?.type === "custom") {
122
+ // Tree may select an ancestor before its metadata child. Reuse immutable bytes/ID.
123
+ if (
124
+ !ctx.sessionManager
125
+ .getBranch()
126
+ .some(
127
+ (entry) =>
128
+ entry.type === "custom" &&
129
+ entry.customType === BRIEFING &&
130
+ readBriefing(entry.data).owner === owner &&
131
+ readBriefing(entry.data).key === key,
132
+ )
133
+ )
134
+ pi.appendEntry(BRIEFING, readBriefing(saved.data));
135
+ return;
136
+ }
137
+ const value = await content();
138
+ if (value === undefined) return;
139
+ pi.appendEntry(BRIEFING, {
140
+ protocol: 1,
141
+ id: randomUUID(),
142
+ owner,
143
+ key,
144
+ content: value,
145
+ } satisfies CodexContextBriefing);
146
+ }
147
+
148
+ function projectNative(
149
+ ctx: ExtensionContext,
150
+ messages: NativeMessage[],
151
+ ): NativeMessage[] {
152
+ const entries = ctx.sessionManager.getBranch().map((entry) => {
153
+ if (entry.type !== "custom" || entry.customType !== BRIEFING) return entry;
154
+ const briefing = readBriefing(entry.data);
155
+ return {
156
+ ...entry,
157
+ type: "custom_message" as const,
158
+ content: briefing.content,
159
+ display: false,
160
+ details: briefing,
161
+ };
162
+ });
163
+ const reconstructed = buildSessionContext(entries).messages;
164
+ const positions = new Map<string, number[]>();
165
+ messages.forEach((message, index) => {
166
+ const key = messageKey(message);
167
+ const indices = positions.get(key) ?? [];
168
+ indices.push(index);
169
+ positions.set(key, indices);
170
+ });
171
+ const insertions = new Map<number, NativeMessage[]>();
172
+ let pending: NativeMessage[] = [];
173
+ let last = messages[0]?.role === "system" ? 0 : -1;
174
+ const insert = (index: number) => {
175
+ if (!pending.length) return;
176
+ const position =
177
+ messages[0]?.role === "system" ? Math.max(1, index) : index;
178
+ insertions.set(position, [...(insertions.get(position) ?? []), ...pending]);
179
+ pending = [];
180
+ };
181
+ for (const message of reconstructed) {
182
+ const index = positions.get(messageKey(message))?.shift();
183
+ if (index !== undefined) {
184
+ insert(index);
185
+ last = index;
186
+ } else if (message.role === "custom" && message.customType === BRIEFING) {
187
+ pending.push(message);
188
+ }
189
+ }
190
+ insert(last + 1);
191
+ return messages
192
+ .flatMap((message, index) => [...(insertions.get(index) ?? []), message])
193
+ .concat(insertions.get(messages.length) ?? []);
194
+ }
195
+
196
+ type NativeMessage = ReturnType<typeof buildSessionContext>["messages"][number];
197
+ function messageKey(message: NativeMessage) {
198
+ return JSON.stringify([
199
+ message.role,
200
+ message.timestamp,
201
+ message.role === "custom"
202
+ ? message.customType === BRIEFING
203
+ ? readBriefing(message.details).id
204
+ : message.customType
205
+ : message.role === "toolResult"
206
+ ? message.toolCallId
207
+ : undefined,
208
+ ]);
209
+ }
210
+ function readBriefing(value: unknown): CodexContextBriefing {
211
+ if (
212
+ !value ||
213
+ typeof value !== "object" ||
214
+ !("protocol" in value) ||
215
+ value.protocol !== 1 ||
216
+ !("id" in value) ||
217
+ typeof value.id !== "string" ||
218
+ !("owner" in value) ||
219
+ typeof value.owner !== "string" ||
220
+ !("key" in value) ||
221
+ typeof value.key !== "string" ||
222
+ !("content" in value) ||
223
+ typeof value.content !== "string"
224
+ )
225
+ throw new Error("Invalid saved context briefing");
226
+ return value as CodexContextBriefing;
227
+ }
@@ -0,0 +1,246 @@
1
+ import { StringEnum, Type } from "@earendil-works/pi-ai";
2
+ import type { Static } from "typebox";
3
+ import { Check } from "typebox/value";
4
+
5
+ const BOARD_ACTIONS = [
6
+ "help",
7
+ "list_boards",
8
+ "create_channel",
9
+ "get_channels",
10
+ "post",
11
+ "set_status",
12
+ "list_threads",
13
+ "read_thread",
14
+ "read_post",
15
+ "search_posts",
16
+ "subscribe",
17
+ "unsubscribe",
18
+ ] as const;
19
+ const THREAD_STATUSES = ["open", "completed", "abandoned"] as const;
20
+ export type ThreadStatus = (typeof THREAD_STATUSES)[number];
21
+ export const BoardParameters = Type.Object({
22
+ action: Type.Optional(StringEnum(BOARD_ACTIONS)),
23
+ });
24
+ const positive = Type.Optional(
25
+ Type.Integer({ minimum: 1, maximum: 0xffffffff }),
26
+ );
27
+ const string = Type.Optional(Type.String());
28
+ const Request = Type.Object(
29
+ {
30
+ action: StringEnum(BOARD_ACTIONS),
31
+ channel_name: string,
32
+ new_channel_name: string,
33
+ thread_id: string,
34
+ message_id: string,
35
+ text: string,
36
+ status: Type.Optional(StringEnum(THREAD_STATUSES)),
37
+ comment: string,
38
+ query: string,
39
+ author: string,
40
+ target_agent: string,
41
+ after_message_id: string,
42
+ board_id: string,
43
+ cursor: string,
44
+ full: Type.Optional(Type.Boolean()),
45
+ subscribe: Type.Optional(Type.Boolean()),
46
+ recent_first: Type.Optional(Type.Boolean()),
47
+ sort: Type.Optional(StringEnum(["created", "activity"])),
48
+ limit: positive,
49
+ max_chars_per_post: positive,
50
+ limit_chars: positive,
51
+ offset_chars: Type.Optional(
52
+ Type.Integer({ minimum: 0, maximum: 0xffffffff }),
53
+ ),
54
+ agents_to_notify: Type.Optional(
55
+ Type.Array(Type.String(), { maxItems: 256 }),
56
+ ),
57
+ },
58
+ { additionalProperties: false },
59
+ );
60
+ export type BoardParams = Static<typeof Request>;
61
+ export type BoardAction = BoardParams["action"];
62
+ export const MUTATIONS = new Set<BoardAction>([
63
+ "create_channel",
64
+ "post",
65
+ "set_status",
66
+ "subscribe",
67
+ "unsubscribe",
68
+ ]);
69
+ const paging = ["limit", "cursor"];
70
+ const reads = ["board_id"];
71
+ const fields: Record<BoardAction, string[]> = {
72
+ help: [],
73
+ list_boards: paging,
74
+ create_channel: ["channel_name", "subscribe"],
75
+ get_channels: ["query", "recent_first", ...paging, ...reads],
76
+ post: [
77
+ "text",
78
+ "channel_name",
79
+ "new_channel_name",
80
+ "thread_id",
81
+ "agents_to_notify",
82
+ ],
83
+ set_status: ["thread_id", "status", "comment"],
84
+ list_threads: [
85
+ "channel_name",
86
+ "sort",
87
+ "recent_first",
88
+ "max_chars_per_post",
89
+ ...paging,
90
+ ...reads,
91
+ ],
92
+ read_thread: ["thread_id", "full", "max_chars_per_post", ...paging, ...reads],
93
+ read_post: ["message_id", "offset_chars", "limit_chars", ...reads],
94
+ search_posts: [
95
+ "channel_name",
96
+ "query",
97
+ "full",
98
+ "author",
99
+ "after_message_id",
100
+ "max_chars_per_post",
101
+ ...paging,
102
+ ...reads,
103
+ ],
104
+ subscribe: ["channel_name", "thread_id", "target_agent"],
105
+ unsubscribe: ["channel_name", "thread_id", "target_agent"],
106
+ };
107
+ const requiredFields: Partial<Record<BoardAction, string[]>> = {
108
+ create_channel: ["channel_name"],
109
+ post: ["text"],
110
+ set_status: ["thread_id", "status", "comment"],
111
+ list_threads: ["channel_name"],
112
+ read_thread: ["thread_id"],
113
+ read_post: ["message_id"],
114
+ };
115
+ export function parseBoardRequest(value: unknown): BoardParams {
116
+ if (
117
+ value === undefined ||
118
+ (typeof value === "object" &&
119
+ value !== null &&
120
+ !Array.isArray(value) &&
121
+ Object.keys(value).length === 0)
122
+ )
123
+ return { action: "help" };
124
+ if (!Check(Request, value))
125
+ throw new Error("Invalid board request; call board help");
126
+ const request = { ...(value as BoardParams) };
127
+ const allowed = new Set(["action", ...fields[request.action]]);
128
+ if (Object.keys(request).some((field) => !allowed.has(field)))
129
+ throw new Error(`Unknown ${request.action} field; board_id is read-only`);
130
+ for (const field of requiredFields[request.action] ?? []) {
131
+ if (!(field in request)) throw new Error(`${field} is required`);
132
+ }
133
+ for (const field of [
134
+ "thread_id",
135
+ "message_id",
136
+ "after_message_id",
137
+ "board_id",
138
+ ] as const) {
139
+ const id = request[field];
140
+ if (
141
+ id !== undefined &&
142
+ !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(
143
+ id,
144
+ )
145
+ )
146
+ throw new Error(`${field} must be a UUID`);
147
+ if (id !== undefined) request[field] = id.toLowerCase();
148
+ }
149
+ if (request.action === "post")
150
+ exactlyOne(request, ["channel_name", "new_channel_name", "thread_id"]);
151
+ if (request.action === "subscribe" || request.action === "unsubscribe")
152
+ exactlyOne(request, ["channel_name", "thread_id"]);
153
+ return request;
154
+ }
155
+ function exactlyOne(value: BoardParams, keys: (keyof BoardParams)[]) {
156
+ if (keys.filter((key) => value[key] !== undefined).length !== 1)
157
+ throw new Error(`Provide exactly one of ${keys.join(", ")}`);
158
+ }
159
+ export function required(value: string | undefined, field: string): string {
160
+ if (value === undefined) throw new Error(`${field} is required`);
161
+ return value;
162
+ }
163
+ export function agentPath(value: string, caller: string): string {
164
+ const path = value.startsWith("/") ? value : `${caller}/${value}`;
165
+ if (!/^\/root(?:\/[a-zA-Z0-9_-]+)*$/.test(path))
166
+ throw new Error("Invalid agent path");
167
+ return path;
168
+ }
169
+ export const boardHelp = {
170
+ actions: Object.fromEntries(
171
+ Object.entries(fields).map(([action, values]) => [
172
+ action,
173
+ values
174
+ .map(
175
+ (field) =>
176
+ `${field === "status" ? `status=${THREAD_STATUSES.join("|")}` : field}${requiredFields[action as BoardAction]?.includes(field) ? "" : "?"}`,
177
+ )
178
+ .join(" "),
179
+ ]),
180
+ ),
181
+ rules: {
182
+ scope:
183
+ "Defaults to your tree; board_id browses history, never writes. list_boards discovers saved boards",
184
+ post: "text required; exactly one of channel_name, new_channel_name, thread_id. Thread ID is the first post ID. New channel subscribes author to first posts",
185
+ set_status:
186
+ "Parent session only. Mark completed when the user confirms it's done, or abandoned when they drop it—not merely when agents finish. Closed threads reject replies; reopen first",
187
+ subscriptions:
188
+ "Exactly one of channel_name/thread_id; channel covers first posts, thread covers replies. target_agent defaults to you. Posting subscribes author to thread unless explicitly unsubscribed",
189
+ notify:
190
+ "agents_to_notify is one-time, excludes author; only running turns, no waking or offline notices",
191
+ agents:
192
+ "Use spawn's boardAgent; absolute /root/... or child path relative to you, not a pane or contextAgent",
193
+ paging:
194
+ "limit default20, cap50; cursor opaque, keep query/sort/full unchanged. Concurrent changes may shift pages",
195
+ summaries:
196
+ "Closing starts background summarization. Summarized threads return/search only summaries. full=true reads/searches original posts. Summary author filters match participants; read_post always reads originals",
197
+ order:
198
+ "Newest first; get_channels by activity, list_threads sort=created|activity. read_thread pages newest replies with root on every page",
199
+ text: "Case-insensitive substring search; max_chars_per_post default1000. read_post offsets count Unicode characters, limit_chars default20000. Continue at next_offset_chars<n_chars",
200
+ budget:
201
+ "Post cap64KiB, channel1-128 UTF-8 bytes without edge whitespace/control characters. Results cap8000 serialized UTF-8 bytes; reads may reduce limits, continue with returned cursor/offset",
202
+ },
203
+ };
204
+
205
+ // Select only owned guidance. Routing metadata and adapter-provided prose stay intact.
206
+ export function gptBoardHelp(value: unknown): unknown {
207
+ if (
208
+ !value ||
209
+ typeof value !== "object" ||
210
+ !("rules" in value) ||
211
+ !value.rules ||
212
+ typeof value.rules !== "object"
213
+ )
214
+ return value;
215
+ const compact: typeof boardHelp.rules = {
216
+ scope:
217
+ "Default: your tree. board_id browses saved history only, never writes. Discover via list_boards",
218
+ post: "text required. Exactly one: channel_name, new_channel_name, thread_id. Thread ID=first post ID. New channel subscribes author to first posts",
219
+ set_status: boardHelp.rules.set_status,
220
+ subscriptions:
221
+ "Exactly one: channel_name/thread_id. Channel=first posts, thread=replies. target_agent defaults to you. Posting subscribes author to thread unless explicitly unsubscribed",
222
+ notify:
223
+ "agents_to_notify: one-time, excludes author. Running turns only, no waking/offline notices",
224
+ agents:
225
+ "Use spawn's boardAgent, absolute /root/... or relative child path. Never pane/contextAgent",
226
+ paging:
227
+ "limit default20 cap50. Opaque cursor, unchanged query/sort/full. Concurrent changes may shift pages",
228
+ summaries: boardHelp.rules.summaries,
229
+ order:
230
+ "Newest first. get_channels: activity. list_threads sort=created|activity. read_thread: newest replies, root repeated each page",
231
+ text: "Case-insensitive substring search. max_chars_per_post default1000. read_post: Unicode-character offsets, limit_chars default20000. Continue at next_offset_chars<n_chars",
232
+ budget:
233
+ "Post cap64KiB. Channel: 1-128 UTF-8 bytes, no edge whitespace/control characters. Results cap8000 serialized UTF-8 bytes. Reads may reduce limits; continue returned cursor/offset",
234
+ };
235
+ return {
236
+ ...value,
237
+ rules: Object.fromEntries(
238
+ Object.entries(value.rules).map(([key, text]) => [
239
+ key,
240
+ text === boardHelp.rules[key as keyof typeof compact]
241
+ ? compact[key as keyof typeof compact]
242
+ : text,
243
+ ]),
244
+ ),
245
+ };
246
+ }