@howaboua/pi-agent-board 0.0.1 → 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.
package/src/config.ts CHANGED
@@ -91,6 +91,10 @@ export function writeBoardConfig(
91
91
  else board[field] = enabled;
92
92
  if (enabled === undefined && !existsSync(path)) return;
93
93
  document["board"] = board;
94
+ writeDocument(path, document);
95
+ }
96
+
97
+ function writeDocument(path: string, document: Record<string, unknown>) {
94
98
  mkdirSync(dirname(path), { recursive: true });
95
99
  const temporary = `${path}.${randomUUID()}.tmp`;
96
100
  try {
@@ -102,3 +106,77 @@ export function writeBoardConfig(
102
106
  rmSync(temporary, { force: true });
103
107
  }
104
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
+ }
package/src/contract.ts CHANGED
@@ -8,6 +8,7 @@ const BOARD_ACTIONS = [
8
8
  "create_channel",
9
9
  "get_channels",
10
10
  "post",
11
+ "set_status",
11
12
  "list_threads",
12
13
  "read_thread",
13
14
  "read_post",
@@ -15,6 +16,8 @@ const BOARD_ACTIONS = [
15
16
  "subscribe",
16
17
  "unsubscribe",
17
18
  ] as const;
19
+ const THREAD_STATUSES = ["open", "completed", "abandoned"] as const;
20
+ export type ThreadStatus = (typeof THREAD_STATUSES)[number];
18
21
  export const BoardParameters = Type.Object({
19
22
  action: Type.Optional(StringEnum(BOARD_ACTIONS)),
20
23
  });
@@ -30,12 +33,15 @@ const Request = Type.Object(
30
33
  thread_id: string,
31
34
  message_id: string,
32
35
  text: string,
36
+ status: Type.Optional(StringEnum(THREAD_STATUSES)),
37
+ comment: string,
33
38
  query: string,
34
39
  author: string,
35
40
  target_agent: string,
36
41
  after_message_id: string,
37
42
  board_id: string,
38
43
  cursor: string,
44
+ full: Type.Optional(Type.Boolean()),
39
45
  subscribe: Type.Optional(Type.Boolean()),
40
46
  recent_first: Type.Optional(Type.Boolean()),
41
47
  sort: Type.Optional(StringEnum(["created", "activity"])),
@@ -56,6 +62,7 @@ export type BoardAction = BoardParams["action"];
56
62
  export const MUTATIONS = new Set<BoardAction>([
57
63
  "create_channel",
58
64
  "post",
65
+ "set_status",
59
66
  "subscribe",
60
67
  "unsubscribe",
61
68
  ]);
@@ -73,6 +80,7 @@ const fields: Record<BoardAction, string[]> = {
73
80
  "thread_id",
74
81
  "agents_to_notify",
75
82
  ],
83
+ set_status: ["thread_id", "status", "comment"],
76
84
  list_threads: [
77
85
  "channel_name",
78
86
  "sort",
@@ -81,11 +89,12 @@ const fields: Record<BoardAction, string[]> = {
81
89
  ...paging,
82
90
  ...reads,
83
91
  ],
84
- read_thread: ["thread_id", "max_chars_per_post", ...paging, ...reads],
92
+ read_thread: ["thread_id", "full", "max_chars_per_post", ...paging, ...reads],
85
93
  read_post: ["message_id", "offset_chars", "limit_chars", ...reads],
86
94
  search_posts: [
87
95
  "channel_name",
88
96
  "query",
97
+ "full",
89
98
  "author",
90
99
  "after_message_id",
91
100
  "max_chars_per_post",
@@ -98,6 +107,7 @@ const fields: Record<BoardAction, string[]> = {
98
107
  const requiredFields: Partial<Record<BoardAction, string[]>> = {
99
108
  create_channel: ["channel_name"],
100
109
  post: ["text"],
110
+ set_status: ["thread_id", "status", "comment"],
101
111
  list_threads: ["channel_name"],
102
112
  read_thread: ["thread_id"],
103
113
  read_post: ["message_id"],
@@ -163,7 +173,7 @@ export const boardHelp = {
163
173
  values
164
174
  .map(
165
175
  (field) =>
166
- `${field}${requiredFields[action as BoardAction]?.includes(field) ? "" : "?"}`,
176
+ `${field === "status" ? `status=${THREAD_STATUSES.join("|")}` : field}${requiredFields[action as BoardAction]?.includes(field) ? "" : "?"}`,
167
177
  )
168
178
  .join(" "),
169
179
  ]),
@@ -172,6 +182,8 @@ export const boardHelp = {
172
182
  scope:
173
183
  "Defaults to your tree; board_id browses history, never writes. list_boards discovers saved boards",
174
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",
175
187
  subscriptions:
176
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",
177
189
  notify:
@@ -179,7 +191,9 @@ export const boardHelp = {
179
191
  agents:
180
192
  "Use spawn's boardAgent; absolute /root/... or child path relative to you, not a pane or contextAgent",
181
193
  paging:
182
- "limit default20, cap50; cursor opaque, keep query/sort unchanged. Concurrent posts may shift pages",
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",
183
197
  order:
184
198
  "Newest first; get_channels by activity, list_threads sort=created|activity. read_thread pages newest replies with root on every page",
185
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",
@@ -187,3 +201,46 @@ export const boardHelp = {
187
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",
188
202
  },
189
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
+ }
package/src/delivery.ts CHANGED
@@ -41,6 +41,15 @@ export async function initializeDelivery() {
41
41
  delivery = await loadDelivery();
42
42
  }
43
43
 
44
+ export function preparePolicyMessage(message: CodexDeveloperCustomMessage) {
45
+ return (
46
+ delivery?.withCodexDeveloperMessageDetails?.({
47
+ ...message,
48
+ details: message.details ?? {},
49
+ }) ?? message
50
+ );
51
+ }
52
+
44
53
  export function registerInferenceBriefing(
45
54
  pi: ExtensionAPI,
46
55
  handler: CodexContextBriefingHandler,
package/src/paging.ts CHANGED
@@ -37,16 +37,15 @@ export function page<T>(values: T[], params: BoardParams) {
37
37
  const { limit, offset } = window(params);
38
38
  const has_more = values.length > limit;
39
39
  const results = values.slice(0, limit);
40
- let next_cursor: string | null = null;
41
- if (has_more) {
42
- if (offset + results.length > 0xffffffff)
43
- throw new Error("Cursor exceeds board limit");
44
- const bytes = Buffer.alloc(4);
45
- bytes.writeUInt32BE(offset + results.length);
46
- next_cursor = bytes.toString("base64url");
47
- }
40
+ const next_cursor = has_more ? cursor(offset + results.length) : null;
48
41
  return { results, n_returned: results.length, has_more, next_cursor };
49
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
+ }
50
49
  export function budget(params: BoardParams, count: number) {
51
50
  return Math.min(
52
51
  params.max_chars_per_post ?? 1000,
package/src/queries.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  import { caseFold } from "unicode-case-folding";
2
- import { agentPath, type BoardParams, required } from "./contract.js";
2
+ import { type BoardParams, required } from "./contract.js";
3
3
  import {
4
4
  budget,
5
+ cursor,
5
6
  metadata,
6
7
  POST_COLUMNS,
7
8
  type PostRecord,
@@ -9,7 +10,9 @@ import {
9
10
  preview,
10
11
  window,
11
12
  } from "./paging.js";
13
+ import { searchBoard } from "./search.js";
12
14
  import type { BoardStore } from "./store.js";
15
+ import { summaryPreview } from "./summaries.js";
13
16
 
14
17
  export function queryBoard(
15
18
  store: BoardStore,
@@ -72,6 +75,28 @@ export function queryBoard(
72
75
  }
73
76
  if (params.action === "read_thread") {
74
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
+ }
75
100
  const replies = store.all<PostRecord>(
76
101
  `SELECT ${POST_COLUMNS} FROM posts WHERE board_id=? AND root=? AND id<>root ORDER BY created_at DESC,seq DESC LIMIT ? OFFSET ?`,
77
102
  board,
@@ -81,7 +106,9 @@ export function queryBoard(
81
106
  );
82
107
  const chars = budget(params, Math.min(replies.length, limit) + 1);
83
108
  return {
109
+ view: "full",
84
110
  root_post: preview(root, chars),
111
+ ...store.threadStatus(board, root.thread_id),
85
112
  ...page(
86
113
  replies.map((post) => preview(post, chars)),
87
114
  params,
@@ -107,6 +134,7 @@ export function queryBoard(
107
134
  const chars = budget(params, 2 * Math.min(roots.length, limit));
108
135
  return page(
109
136
  roots.map((root) => {
137
+ const summary = store.summaries.get(board, root.thread_id);
110
138
  const reply = store.one<PostRecord>(
111
139
  `SELECT ${POST_COLUMNS} FROM posts WHERE board_id=? AND root=? AND id<>root ORDER BY created_at DESC,seq DESC LIMIT 1`,
112
140
  board,
@@ -120,57 +148,24 @@ export function queryBoard(
120
148
  )?.n ?? 0;
121
149
  return {
122
150
  thread_id: root.message_id,
123
- root_post: preview(root, chars),
151
+ ...store.threadStatus(board, root.message_id),
152
+ ...(summary
153
+ ? { summary: summaryPreview(summary, chars) }
154
+ : { root_post: preview(root, chars) }),
124
155
  reply_count: count,
125
156
  last_activity_at:
126
157
  reply && reply.created_at > root.created_at
127
158
  ? reply.created_at
128
159
  : root.created_at,
129
- latest_reply: reply ? preview(reply, chars) : null,
160
+ ...(summary
161
+ ? {}
162
+ : { latest_reply: reply ? preview(reply, chars) : null }),
130
163
  };
131
164
  }),
132
165
  params,
133
166
  );
134
167
  }
135
- if (params.action === "search_posts") return search(store, board, params);
168
+ if (params.action === "search_posts")
169
+ return searchBoard(store, board, params);
136
170
  throw new Error(`Unsupported board read: ${params.action}`);
137
171
  }
138
-
139
- function search(store: BoardStore, board: string, params: BoardParams) {
140
- const { limit, offset } = window(params);
141
- const clauses = ["board_id=?"];
142
- const args: (string | number)[] = [board];
143
- if (params.channel_name !== undefined) {
144
- clauses.push("channel=?");
145
- args.push(params.channel_name);
146
- }
147
- if (params.author !== undefined) {
148
- clauses.push("author=?");
149
- args.push(agentPath(params.author, "/root"));
150
- }
151
- if (params.query !== undefined) {
152
- clauses.push("instr(body_search,?)>0");
153
- args.push(caseFold(params.query));
154
- }
155
- if (params.after_message_id !== undefined) {
156
- const after = store.one<{ created_at: string; seq: number }>(
157
- "SELECT created_at,seq FROM posts WHERE board_id=? AND id=?",
158
- board,
159
- params.after_message_id,
160
- );
161
- if (!after) throw new Error("Post not found in this board");
162
- clauses.push("(created_at,seq)>(?,?)");
163
- args.push(after.created_at, after.seq);
164
- }
165
- const posts = store.all<PostRecord>(
166
- `SELECT ${POST_COLUMNS} FROM posts WHERE ${clauses.join(" AND ")} ORDER BY created_at DESC,seq DESC LIMIT ? OFFSET ?`,
167
- ...args,
168
- limit + 1,
169
- offset,
170
- );
171
- const chars = budget(params, Math.min(posts.length, limit));
172
- return page(
173
- posts.map((post) => preview(post, chars)),
174
- params,
175
- );
176
- }
package/src/runtime.ts CHANGED
@@ -13,9 +13,14 @@ import {
13
13
  agentPath,
14
14
  type BoardParams,
15
15
  boardHelp,
16
+ gptBoardHelp,
16
17
  parseBoardRequest,
17
18
  } from "./contract.js";
18
- import { initializeDelivery, isMissingOptionalModule } from "./delivery.js";
19
+ import {
20
+ initializeDelivery,
21
+ isMissingOptionalModule,
22
+ preparePolicyMessage,
23
+ } from "./delivery.js";
19
24
  import {
20
25
  binding,
21
26
  members,
@@ -26,14 +31,18 @@ import {
26
31
  } from "./identity.js";
27
32
  import type { BoardAdapter } from "./integration.js";
28
33
  import { type BoardEnvelope, parseEnvelope } from "./protocol.js";
34
+ import { BoardSummarizer } from "./summarizer.js";
29
35
  import { createBoardTool } from "./tool.js";
30
36
  import { BoardTurns } from "./turns.js";
31
37
 
32
38
  export class BoardRuntime {
39
+ gptPromptMode = false;
40
+ private preparePromptMode: ((ctx: ExtensionContext) => void) | undefined;
33
41
  private readonly pi: ExtensionAPI;
34
42
  private adapter: BoardAdapter | undefined;
35
43
  private readonly turns: BoardTurns;
36
44
  private readonly awareness: BoardAwareness;
45
+ private readonly summarizer = new BoardSummarizer();
37
46
  private refreshTools: (() => void) | undefined;
38
47
  private lastSetting: { sessionId: string; enabled: boolean } | undefined;
39
48
  private configError: string | undefined;
@@ -47,6 +56,7 @@ export class BoardRuntime {
47
56
  (ctx) => this.population(ctx),
48
57
  availability,
49
58
  () => this.adapter?.briefing,
59
+ () => this.gptPromptMode,
50
60
  );
51
61
  this.turns = new BoardTurns(
52
62
  pi,
@@ -55,11 +65,14 @@ export class BoardRuntime {
55
65
  (ctx, ids) => this.awareness.markSeen(ctx, ids),
56
66
  );
57
67
  pi.on("session_start", (_event, ctx) => {
68
+ this.summarizer.cancelAll();
58
69
  this.availabilityWarning = undefined;
59
70
  setBoardDefault(ctx, true);
60
71
  return this.refresh(ctx);
61
72
  });
73
+ pi.on("session_shutdown", () => this.summarizer.cancelAll());
62
74
  pi.on("before_agent_start", async (_event, ctx) => {
75
+ this.preparePromptMode?.(ctx);
63
76
  // Reconcile resumed/offline children before tool/prompt preparation.
64
77
  const own = binding(ctx);
65
78
  if (own.upstream) {
@@ -88,11 +101,11 @@ export class BoardRuntime {
88
101
  catchup.accepted();
89
102
  if (catchup.content)
90
103
  return {
91
- message: {
104
+ message: preparePolicyMessage({
92
105
  customType: "shepherdr-board-catchup",
93
106
  content: catchup.content.trim(),
94
107
  display: true,
95
- },
108
+ }),
96
109
  };
97
110
  });
98
111
  }
@@ -116,6 +129,9 @@ export class BoardRuntime {
116
129
  setToolRefresh(refresh: () => void) {
117
130
  this.refreshTools = refresh;
118
131
  }
132
+ setPromptModePreparation(prepare: (ctx: ExtensionContext) => void) {
133
+ this.preparePromptMode = prepare;
134
+ }
119
135
  private async population(ctx: ExtensionContext) {
120
136
  const own = binding(ctx);
121
137
  if (own.upstream) {
@@ -186,7 +202,7 @@ export class BoardRuntime {
186
202
  .some((tool) => ["exec", "code", "notebook"].includes(tool));
187
203
  return {
188
204
  content: result.length
189
- ? `\n\nUnread board updates available; read if relevant to the current task: ${[
205
+ ? `\n\n${this.gptPromptMode ? "Unread board updates. Read task-relevant threads:" : "Unread board updates available; read if relevant to the current task:"} ${[
190
206
  ...new Set(result.map((post) => post.thread_id)),
191
207
  ]
192
208
  .map((thread_id) => {
@@ -220,7 +236,10 @@ export class BoardRuntime {
220
236
  if (own.enabled) active.push("board");
221
237
  this.pi.setActiveTools(active);
222
238
  this.refreshTools?.();
223
- if (!own.enabled) this.turns.active.clear();
239
+ if (!own.enabled) {
240
+ this.turns.active.clear();
241
+ this.summarizer.cancelAll();
242
+ }
224
243
  const changed =
225
244
  this.lastSetting?.sessionId !== own.sessionId ||
226
245
  this.lastSetting.enabled !== own.enabled;
@@ -246,6 +265,14 @@ export class BoardRuntime {
246
265
  const setting = own.upstream ? undefined : rootBoardSetting(ctx);
247
266
  return `Board ${own.enabled ? "on" : "off"} (${setting?.source ?? "inherited from owner"})${includeArchive ? `. ${own.boardId}\nArchive: ${own.databasePath}` : ""}${setting?.error ? `\n${setting.error}` : ""}`;
248
267
  }
268
+ summarize(ctx: ExtensionContext, thread: string) {
269
+ const own = binding(ctx);
270
+ if (own.upstream || own.sessionId !== own.rootSessionId)
271
+ throw new Error("Summarize threads in the owning parent session");
272
+ if (!own.enabled) throw new Error("Board is off; enable it with /board on");
273
+ parseBoardRequest({ action: "read_thread", thread_id: thread });
274
+ this.summarizer.start(ctx, own, thread.toLowerCase());
275
+ }
249
276
  async execute(ctx: ExtensionContext, input: unknown, requestId: string) {
250
277
  const params = parseBoardRequest(input);
251
278
  const caller = binding(ctx);
@@ -276,7 +303,9 @@ export class BoardRuntime {
276
303
  "warning",
277
304
  );
278
305
  }
279
- return value;
306
+ return params.action === "help" && this.gptPromptMode
307
+ ? gptBoardHelp(value)
308
+ : value;
280
309
  }
281
310
  async handle(
282
311
  ctx: ExtensionContext,
@@ -414,6 +443,18 @@ export class BoardRuntime {
414
443
  request.requestId,
415
444
  );
416
445
  if ("notice" in result && result.notice) {
446
+ // Replayed mutations have no notice: never start or cancel twice for a retry.
447
+ if (params.action === "set_status") {
448
+ if (params.status === "open")
449
+ this.summarizer.cancel(own.boardId, result.notice.thread_id);
450
+ else
451
+ this.summarizer.start(
452
+ ctx,
453
+ own,
454
+ result.notice.thread_id,
455
+ result.notice.message_id,
456
+ );
457
+ }
417
458
  for (let start = 0; start < result.recipients.length; start += 16) {
418
459
  await Promise.all(
419
460
  result.recipients.slice(start, start + 16).map(async (target) => {
@@ -528,6 +569,18 @@ async function createRuntime(pi: ExtensionAPI) {
528
569
  const runtime = new BoardRuntime(pi);
529
570
  const tool = createBoardTool(runtime);
530
571
  pi.registerTool(tool);
572
+ try {
573
+ const { registerGptPromptMode, prepareGptPromptMode } = await import(
574
+ "@howaboua/pi-codex-conversion/prompt-mode"
575
+ );
576
+ runtime.setPromptModePreparation((ctx) => prepareGptPromptMode(pi, ctx));
577
+ registerGptPromptMode(pi, (active) => {
578
+ runtime.gptPromptMode = active;
579
+ return [tool];
580
+ });
581
+ } catch (error) {
582
+ if (!isMissingOptionalModule(error, "prompt-mode")) throw error;
583
+ }
531
584
  registerBoardActivityRenderer(pi);
532
585
  try {
533
586
  const { adaptToolForCodeMode, registerCodeModeExtensionTools } =
@@ -538,7 +591,7 @@ async function createRuntime(pi: ExtensionAPI) {
538
591
  adaptToolForCodeMode(tool, {
539
592
  prepareInput: (input) =>
540
593
  input === undefined || input === null ? {} : input,
541
- usage: "await tools.board() // Shared discussion archive",
594
+ discovery: "help",
542
595
  }),
543
596
  ],
544
597
  { isActive: (ctx) => runtime.enabled(ctx) },
package/src/search.ts ADDED
@@ -0,0 +1,93 @@
1
+ import { caseFold } from "unicode-case-folding";
2
+ import { agentPath, type BoardParams } from "./contract.js";
3
+ import { budget, type PostRecord, page, preview, window } from "./paging.js";
4
+ import type { BoardStore } from "./store.js";
5
+ import { summaryPreview } from "./summaries.js";
6
+
7
+ /** Summaries replace their source posts, never supplement them in default search. */
8
+ export function searchBoard(
9
+ store: BoardStore,
10
+ board: string,
11
+ params: BoardParams,
12
+ ) {
13
+ const { limit, offset } = window(params);
14
+ const summarized = store.summaries.available && !params.full;
15
+ const clauses = ["board_id=?"];
16
+ const args: (string | number)[] = [board];
17
+ if (params.channel_name !== undefined) {
18
+ clauses.push("channel_name=?");
19
+ args.push(params.channel_name);
20
+ }
21
+ if (params.author !== undefined) {
22
+ clauses.push(`(author=? OR (kind='summary' AND EXISTS (
23
+ SELECT 1 FROM posts a WHERE a.board_id=c.board_id AND a.root=c.thread_id AND a.author=?)))`);
24
+ const author = agentPath(params.author, "/root");
25
+ args.push(author, author);
26
+ }
27
+ if (params.query !== undefined) {
28
+ clauses.push("instr(body_search,?)>0");
29
+ args.push(caseFold(params.query));
30
+ }
31
+ if (params.after_message_id !== undefined) {
32
+ const after = store.one<{ created_at: string; seq: number }>(
33
+ "SELECT created_at,seq FROM posts WHERE board_id=? AND id=?",
34
+ board,
35
+ params.after_message_id,
36
+ );
37
+ if (!after) throw new Error("Post not found in this board");
38
+ clauses.push("(created_at,seq)>(?,?)");
39
+ args.push(after.created_at, after.seq);
40
+ }
41
+ const rows = store.all<
42
+ | (PostRecord & { kind: "post" })
43
+ | (Omit<PostRecord, "author"> & { kind: "summary"; author: null })
44
+ >(
45
+ `WITH candidates AS (
46
+ SELECT p.board_id,p.id AS message_id,p.channel AS channel_name,p.author,p.root AS thread_id,
47
+ p.created_at,p.text,p.body_search,p.seq,'post' AS kind FROM posts p
48
+ ${summarized ? "WHERE NOT EXISTS (SELECT 1 FROM thread_summaries s WHERE s.board_id=p.board_id AND s.thread_id=p.root)" : ""}
49
+ ${
50
+ summarized
51
+ ? `UNION ALL
52
+ SELECT s.board_id,p.id,p.channel,NULL,s.thread_id,p.created_at,s.text,s.body_search,p.seq,'summary'
53
+ FROM thread_summaries s JOIN posts p ON p.board_id=s.board_id AND p.id=s.through_message_id`
54
+ : ""
55
+ }
56
+ ) SELECT * FROM candidates c WHERE ${clauses.join(" AND ")}
57
+ ORDER BY created_at DESC,seq DESC LIMIT ? OFFSET ?`,
58
+ ...args,
59
+ limit + 1,
60
+ offset,
61
+ );
62
+ const chars = budget(params, Math.min(rows.length, limit));
63
+ return page(
64
+ rows.map((row) => {
65
+ const status = store.threadStatus(board, row.thread_id);
66
+ if (row.kind === "summary") {
67
+ const summary = store.summaries.get(board, row.thread_id);
68
+ if (!summary)
69
+ throw new Error(
70
+ "Thread summary is no longer available; repeat the search",
71
+ );
72
+ return {
73
+ kind: "summary",
74
+ thread_id: row.thread_id,
75
+ channel_name: row.channel_name,
76
+ ...status,
77
+ summary: summaryPreview(summary, chars),
78
+ };
79
+ }
80
+ // Do not expose SQL-only columns as post metadata.
81
+ const post: PostRecord = {
82
+ message_id: row.message_id,
83
+ channel_name: row.channel_name,
84
+ author: row.author,
85
+ thread_id: row.thread_id,
86
+ created_at: row.created_at,
87
+ text: row.text,
88
+ };
89
+ return { kind: "post", ...preview(post, chars), ...status };
90
+ }),
91
+ params,
92
+ );
93
+ }