@howaboua/pi-agent-board 0.0.4 → 0.0.6

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 (64) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +3 -1
  3. package/dist/viewer/archive.js +24 -17
  4. package/dist/viewer/web/posts.js +0 -1
  5. package/index.ts +5 -69
  6. package/package.json +15 -14
  7. package/runtime.ts +2 -0
  8. package/scripts/build-viewer.mjs +9 -0
  9. package/src/board/AGENTS.md +12 -0
  10. package/src/{archive.ts → board/archive.ts} +17 -7
  11. package/src/{awareness.ts → board/awareness.ts} +6 -11
  12. package/src/board/briefing.ts +25 -0
  13. package/src/{contract.ts → board/contract.ts} +39 -29
  14. package/src/board/feature.ts +91 -0
  15. package/src/{identity.ts → board/identity.ts} +121 -37
  16. package/src/{integration.ts → board/integration.ts} +1 -0
  17. package/src/board/protocol.ts +117 -0
  18. package/src/{queries.ts → board/queries.ts} +9 -11
  19. package/src/{response.ts → board/response.ts} +7 -1
  20. package/src/board/runtime/activation.ts +50 -0
  21. package/src/{runtime → board/runtime}/coordinator.ts +76 -43
  22. package/src/board/runtime/engine.ts +40 -0
  23. package/src/board/runtime/index.ts +63 -0
  24. package/src/{runtime → board/runtime}/owner.ts +44 -15
  25. package/src/{runtime → board/runtime}/routing.ts +19 -4
  26. package/src/{runtime → board/runtime}/turns.ts +9 -1
  27. package/src/{search.ts → board/search.ts} +11 -9
  28. package/src/board/settings/panel.ts +193 -0
  29. package/src/{store.ts → board/store.ts} +45 -9
  30. package/src/{summarizer.ts → board/summarizer.ts} +3 -2
  31. package/src/{tool.ts → board/tool.ts} +5 -0
  32. package/src/board/viewer/AGENTS.md +1 -0
  33. package/src/{viewer → board/viewer}/archive.ts +24 -17
  34. package/src/{viewer → board/viewer}/index.ts +5 -1
  35. package/src/{viewer → board/viewer}/web/posts.js +0 -1
  36. package/src/guidance.ts +121 -0
  37. package/src/settings-navigation.ts +11 -0
  38. package/src/timestamps.ts +3 -0
  39. package/tsconfig.json +6 -2
  40. package/tsconfig.viewer.json +11 -0
  41. package/changelog.ts +0 -337
  42. package/src/briefing.ts +0 -32
  43. package/src/protocol.ts +0 -78
  44. package/src/runtime/index.ts +0 -113
  45. package/src/settings/panel.ts +0 -87
  46. /package/src/{activity.ts → board/activity.ts} +0 -0
  47. /package/src/{config.ts → board/config.ts} +0 -0
  48. /package/src/{consolidation.ts → board/consolidation.ts} +0 -0
  49. /package/src/{context-briefing.ts → board/context-briefing.ts} +0 -0
  50. /package/src/{delivery.ts → board/delivery.ts} +0 -0
  51. /package/src/{paging.ts → board/paging.ts} +0 -0
  52. /package/src/{runtime → board/runtime}/catchup.ts +0 -0
  53. /package/src/{summaries.ts → board/summaries.ts} +0 -0
  54. /package/src/{viewer → board/viewer}/config.ts +0 -0
  55. /package/src/{viewer → board/viewer}/contracts.ts +0 -0
  56. /package/src/{viewer → board/viewer}/server.ts +0 -0
  57. /package/src/{viewer → board/viewer}/source.ts +0 -0
  58. /package/src/{viewer → board/viewer}/web/app.js +0 -0
  59. /package/src/{viewer → board/viewer}/web/index.html +0 -0
  60. /package/src/{viewer → board/viewer}/web/navigation.js +0 -0
  61. /package/src/{viewer → board/viewer}/web/render.js +0 -0
  62. /package/src/{viewer → board/viewer}/web/session.js +0 -0
  63. /package/src/{viewer → board/viewer}/web/style.css +0 -0
  64. /package/src/{viewer → board/viewer}/web/updates.js +0 -0
@@ -0,0 +1,91 @@
1
+ import type {
2
+ ExtensionAPI,
3
+ ExtensionContext,
4
+ } from "@earendil-works/pi-coding-agent";
5
+ import type { CommsFeature } from "../guidance.js";
6
+ import type { OpenSettings } from "../settings-navigation.js";
7
+ import { binding } from "./identity.js";
8
+ import { acquireBoard } from "./runtime/index.js";
9
+
10
+ export async function createBoardFeature(
11
+ pi: ExtensionAPI,
12
+ openSettings?: OpenSettings,
13
+ ): Promise<CommsFeature> {
14
+ const board = await acquireBoard(pi);
15
+ const open = async (ctx: ExtensionContext) => {
16
+ const { openBoardSettings } = await import("./settings/panel.js");
17
+ return openBoardSettings(pi, ctx, board, Boolean(openSettings));
18
+ };
19
+ pi.registerCommand("board", {
20
+ description: `${openSettings ? "Board settings" : "Board viewer; settings"}; status, on|off [session|folder|global]`,
21
+ getArgumentCompletions(prefix) {
22
+ const commands = ["settings", "status", "on", "off"];
23
+ const scopes = ["session", "folder", "global"];
24
+ const options = prefix.includes(" ")
25
+ ? ["on", "off"].flatMap((command) =>
26
+ scopes.map((scope) => `${command} ${scope}`),
27
+ )
28
+ : commands;
29
+ return options
30
+ .filter((value) => value.startsWith(prefix))
31
+ .map((value) => ({ label: value, value }));
32
+ },
33
+ async handler(args, ctx) {
34
+ if (args.trim() === "settings" || (!args.trim() && openSettings)) {
35
+ if (openSettings) return openSettings(ctx, "board");
36
+ await open(ctx);
37
+ return;
38
+ }
39
+ const [command = "", scope = "session", ...extra] = args
40
+ .trim()
41
+ .split(/\s+/);
42
+ if (
43
+ (command === "on" || command === "off") &&
44
+ (scope === "session" || scope === "folder" || scope === "global") &&
45
+ !extra.length
46
+ ) {
47
+ try {
48
+ await board.setSetting(ctx, scope, command === "on");
49
+ ctx.ui.notify(board.status(ctx), "info");
50
+ } catch (error) {
51
+ ctx.ui.notify(
52
+ error instanceof Error ? error.message : String(error),
53
+ "error",
54
+ );
55
+ }
56
+ return;
57
+ }
58
+ if (args.trim() === "status") {
59
+ ctx.ui.notify(board.status(ctx), "info");
60
+ return;
61
+ }
62
+ if (command) {
63
+ ctx.ui.notify(
64
+ "Use /board, /board settings, /board status or /board on|off [session|folder|global]",
65
+ "warning",
66
+ );
67
+ return;
68
+ }
69
+ const { openBoardViewer } = await import("./viewer/index.js");
70
+ await openBoardViewer(pi, ctx, (context, sessionName) => {
71
+ const own = binding(context);
72
+ if (own.upstream)
73
+ throw new Error(
74
+ "Open /board in the owning root session to view this shared board",
75
+ );
76
+ return {
77
+ sessionId: own.sessionId,
78
+ sessionName: sessionName ?? null,
79
+ boardId: own.boardId,
80
+ folder: own.ownerFolder,
81
+ databasePath: own.databasePath,
82
+ };
83
+ });
84
+ },
85
+ });
86
+ return {
87
+ enabled: (ctx) => board.enabled(ctx),
88
+ gptPromptMode: () => board.gptPromptMode,
89
+ openSettings: open,
90
+ };
91
+ }
@@ -1,55 +1,77 @@
1
1
  import { resolve } from "node:path";
2
- import { Type } from "@earendil-works/pi-ai";
3
2
  import type {
4
3
  ExtensionAPI,
5
4
  ExtensionContext,
6
5
  } from "@earendil-works/pi-coding-agent";
7
- import type { Static } from "typebox";
8
- import { Check } from "typebox/value";
6
+ import {
7
+ bool,
8
+ compile,
9
+ lit,
10
+ nul,
11
+ obj,
12
+ opt,
13
+ type Static,
14
+ str,
15
+ union,
16
+ } from "@earendil-works/pi-schema";
9
17
  import { readBoardConfig } from "./config.js";
10
18
 
11
- const uuid = Type.String({ pattern: "^[a-f0-9-]{36}$" });
12
- export const BindingSchema = Type.Object(
19
+ const nativeId = str({ pattern: "^[a-zA-Z0-9_.-]+$" });
20
+ export const BindingSchema = obj(
13
21
  {
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 })),
22
+ protocol: lit(1),
23
+ boardId: nativeId,
24
+ rootSessionId: nativeId,
25
+ sessionId: nativeId,
26
+ agentName: str({
27
+ pattern: "^/[a-zA-Z0-9_.-]+(?:/[a-zA-Z0-9_-]+)*$",
28
+ }),
29
+ legacyAgentName: opt(str({ pattern: "^/root(?:/[a-zA-Z0-9_-]+)*$" })),
30
+ parentSessionId: opt(nativeId),
31
+ ownerFolder: str({ minLength: 1 }),
32
+ databasePath: str({ minLength: 1 }),
33
+ enabled: bool(),
34
+ upstream: opt(str({ minLength: 1 })),
23
35
  },
24
- { additionalProperties: false },
36
+ { open: false },
25
37
  );
26
38
  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>;
39
+ const ChildSchema = obj(
40
+ {
41
+ parentSessionId: nativeId,
42
+ binding: BindingSchema,
43
+ machine: str(),
44
+ sessionFile: str({ minLength: 1 }),
45
+ },
46
+ { open: true },
47
+ );
48
+ type BoardChild = Static<typeof ChildSchema>;
34
49
  const BINDING = "shepherdr-board-binding";
35
50
  const MEMBER = "shepherdr-board-member";
36
51
  const CHILD = "shepherdr-board-child";
37
52
  const SETTING = "shepherdr-board-setting";
38
53
  const defaults = new WeakMap<ExtensionContext["sessionManager"], boolean>();
54
+ const bindingSchemaValidator = compile(BindingSchema);
55
+ const childSchemaValidator = compile(ChildSchema);
56
+
39
57
  export function setBoardDefault(ctx: ExtensionContext, enabled: boolean) {
40
58
  defaults.set(ctx.sessionManager, enabled);
41
59
  }
42
60
  const REMOVED = "shepherdr-board-removed";
43
- const SettingSchema = Type.Object({
44
- sessionId: uuid,
45
- enabled: Type.Union([Type.Boolean(), Type.Null()]),
46
- });
61
+ const SettingSchema = obj(
62
+ {
63
+ sessionId: nativeId,
64
+ enabled: union([bool(), nul()]),
65
+ },
66
+ { open: true },
67
+ );
68
+ const settingSchemaValidator = compile(SettingSchema);
47
69
 
48
70
  function sessionBoardSetting(ctx: ExtensionContext): boolean | undefined {
49
71
  let enabled: boolean | undefined;
50
72
  for (const entry of ctx.sessionManager.getEntries()) {
51
73
  if (entry.type !== "custom" || entry.customType !== SETTING) continue;
52
- if (!Check(SettingSchema, entry.data))
74
+ if (!settingSchemaValidator.check(entry.data))
53
75
  throw new Error("Invalid saved board setting");
54
76
  const value = entry.data as Static<typeof SettingSchema>;
55
77
  if (value.sessionId === ctx.sessionManager.getSessionId())
@@ -95,12 +117,24 @@ export function rootBoardSetting(ctx: ExtensionContext) {
95
117
  }
96
118
 
97
119
  export function parseBinding(value: unknown): BoardBinding {
98
- if (!Check(BindingSchema, value))
120
+ if (!bindingSchemaValidator.check(value))
99
121
  throw new Error("Invalid Shepherdr board binding");
100
- return value as BoardBinding;
122
+ const saved = value as BoardBinding;
123
+ assertSessionIdentity(saved.sessionId, saved.rootSessionId);
124
+ const agentName = `/${saved.sessionId}`;
125
+ if (saved.agentName !== agentName && !/^\/root(?:\/|$)/.test(saved.agentName))
126
+ throw new Error("Board agent reference does not match its native session");
127
+ return {
128
+ ...saved,
129
+ agentName,
130
+ ...(saved.agentName !== agentName && !saved.legacyAgentName
131
+ ? { legacyAgentName: saved.agentName }
132
+ : {}),
133
+ };
101
134
  }
102
135
  export function binding(ctx: ExtensionContext): BoardBinding {
103
136
  const sessionId = ctx.sessionManager.getSessionId();
137
+ assertSessionIdentity(sessionId);
104
138
  let saved: BoardBinding | undefined;
105
139
  for (const entry of ctx.sessionManager.getEntries()) {
106
140
  if (entry.type !== "custom" || entry.customType !== BINDING) continue;
@@ -115,7 +149,7 @@ export function binding(ctx: ExtensionContext): BoardBinding {
115
149
  sessionId,
116
150
  rootSessionId: sessionId,
117
151
  boardId: sessionId,
118
- agentName: "/root",
152
+ agentName: `/${sessionId}`,
119
153
  ownerFolder,
120
154
  databasePath: resolve(ownerFolder, ".pi", "agent-message-board.sqlite"),
121
155
  enabled: false,
@@ -123,24 +157,41 @@ export function binding(ctx: ExtensionContext): BoardBinding {
123
157
  enabled: rootBoardSetting(ctx).enabled,
124
158
  };
125
159
  }
160
+ function assertSessionIdentity(...ids: string[]) {
161
+ if (ids.includes("root"))
162
+ throw new Error(
163
+ "Pi session ID root conflicts with the legacy /root reference; start a session with another ID",
164
+ );
165
+ }
126
166
  export function saveBinding(pi: ExtensionAPI, value: BoardBinding) {
127
167
  pi.appendEntry(BINDING, value);
128
168
  }
129
169
  export function members(ctx: ExtensionContext): BoardBinding[] {
130
170
  const own = binding(ctx);
131
- const found = new Map([[own.agentName, own]]);
171
+ const found = new Map([[own.sessionId, own]]);
132
172
  for (const entry of ctx.sessionManager.getEntries()) {
133
173
  if (entry.type === "custom" && entry.customType === REMOVED) {
134
174
  const value = parseBinding(entry.data);
135
- if (value.boardId === own.boardId) found.delete(value.agentName);
175
+ if (value.boardId === own.boardId) found.delete(value.sessionId);
136
176
  continue;
137
177
  }
138
178
  if (entry.type !== "custom" || entry.customType !== MEMBER) continue;
139
179
  const value = parseBinding(entry.data);
140
180
  if (value.rootSessionId === own.sessionId && value.boardId === own.boardId)
141
- found.set(value.agentName, value);
181
+ found.set(value.sessionId, value);
142
182
  }
143
- return [...found.values()];
183
+ const directory = [...found.values()];
184
+ return directory.map((member) => {
185
+ if (member.parentSessionId || !member.legacyAgentName) return member;
186
+ const path = member.legacyAgentName;
187
+ const parent = directory.find(
188
+ (entry) =>
189
+ (entry.legacyAgentName ??
190
+ (entry.sessionId === own.rootSessionId ? "/root" : undefined)) ===
191
+ path.slice(0, path.lastIndexOf("/")),
192
+ );
193
+ return parent ? { ...member, parentSessionId: parent.sessionId } : member;
194
+ });
144
195
  }
145
196
  export function saveMember(pi: ExtensionAPI, value: BoardBinding) {
146
197
  pi.appendEntry(MEMBER, value);
@@ -151,18 +202,21 @@ export function children(ctx: ExtensionContext): BoardChild[] {
151
202
  for (const entry of ctx.sessionManager.getEntries()) {
152
203
  if (entry.type === "custom" && entry.customType === REMOVED) {
153
204
  const value = parseBinding(entry.data);
154
- if (value.boardId === own.boardId) found.delete(value.agentName);
205
+ if (value.boardId === own.boardId) found.delete(value.sessionId);
155
206
  continue;
156
207
  }
157
208
  if (entry.type !== "custom" || entry.customType !== CHILD) continue;
158
- if (!Check(ChildSchema, entry.data))
209
+ if (!childSchemaValidator.check(entry.data))
159
210
  throw new Error("Invalid saved board child route");
160
211
  const value = entry.data as BoardChild;
161
212
  if (
162
213
  value.parentSessionId === own.sessionId &&
163
214
  value.binding.boardId === own.boardId
164
215
  )
165
- found.set(value.binding.agentName, value);
216
+ found.set(value.binding.sessionId, {
217
+ ...value,
218
+ binding: parseBinding(value.binding),
219
+ });
166
220
  }
167
221
  return [...found.values()];
168
222
  }
@@ -172,3 +226,33 @@ export function saveChild(pi: ExtensionAPI, value: BoardChild) {
172
226
  export function removeMember(pi: ExtensionAPI, value: BoardBinding) {
173
227
  pi.appendEntry(REMOVED, value);
174
228
  }
229
+
230
+ /** Legacy names are aliases from native-session records, never access grants. */
231
+ export function boardAliases(
232
+ ctx: ExtensionContext,
233
+ boardId = binding(ctx).boardId,
234
+ ): [string, string][] {
235
+ const own = binding(ctx);
236
+ const aliases = new Map<string, string>();
237
+ if (own.boardId === boardId && own.sessionId === own.rootSessionId)
238
+ aliases.set("/root", own.agentName);
239
+ for (const entry of ctx.sessionManager.getEntries()) {
240
+ if (entry.type !== "custom") continue;
241
+ let member: BoardBinding;
242
+ if ([BINDING, MEMBER, REMOVED].includes(entry.customType))
243
+ member = parseBinding(entry.data);
244
+ else if (
245
+ entry.customType === CHILD &&
246
+ childSchemaValidator.check(entry.data)
247
+ )
248
+ member = parseBinding((entry.data as BoardChild).binding);
249
+ else continue;
250
+ if (member.boardId === boardId && member.legacyAgentName) {
251
+ const previous = aliases.get(member.legacyAgentName);
252
+ if (previous && previous !== member.agentName)
253
+ throw new Error("Ambiguous saved board agent reference");
254
+ aliases.set(member.legacyAgentName, member.agentName);
255
+ }
256
+ }
257
+ return [...aliases];
258
+ }
@@ -44,6 +44,7 @@ export {
44
44
  children,
45
45
  members,
46
46
  parseBinding,
47
+ parseBinding as canonicalBoardBinding,
47
48
  removeMember,
48
49
  rootBoardSetting,
49
50
  saveBinding,
@@ -0,0 +1,117 @@
1
+ import {
2
+ arr,
3
+ bool,
4
+ compile,
5
+ int,
6
+ lit,
7
+ nul,
8
+ obj,
9
+ opt,
10
+ type Static,
11
+ str,
12
+ union,
13
+ unknown,
14
+ } from "@earendil-works/pi-schema";
15
+ import { BindingSchema } from "./identity.js";
16
+
17
+ const NoticeSchema = obj(
18
+ {
19
+ message_id: str(),
20
+ channel_name: str(),
21
+ author: str(),
22
+ thread_id: str(),
23
+ created_at: str(),
24
+ text_preview: str({ maxLength: 300 }),
25
+ n_chars: int({ minimum: 0 }),
26
+ truncated: bool(),
27
+ },
28
+ { open: false },
29
+ );
30
+ const Protocol = union([
31
+ obj(
32
+ {
33
+ operation: lit("board-catchup"),
34
+ caller: BindingSchema,
35
+ seen: arr(str()),
36
+ },
37
+ { open: true },
38
+ ),
39
+ obj(
40
+ {
41
+ operation: lit("board-bind"),
42
+ binding: BindingSchema,
43
+ },
44
+ { open: true },
45
+ ),
46
+ obj(
47
+ {
48
+ operation: lit("board-register"),
49
+ caller: BindingSchema,
50
+ member: BindingSchema,
51
+ },
52
+ { open: true },
53
+ ),
54
+ obj(
55
+ {
56
+ operation: lit("board-unregister"),
57
+ caller: BindingSchema,
58
+ member: BindingSchema,
59
+ },
60
+ { open: true },
61
+ ),
62
+ obj(
63
+ {
64
+ operation: lit("board-enabled"),
65
+ boardId: str(),
66
+ enabled: bool(),
67
+ },
68
+ { open: true },
69
+ ),
70
+ obj(
71
+ {
72
+ operation: lit("board-active"),
73
+ caller: BindingSchema,
74
+ turnId: union([str(), nul()]),
75
+ previousTurnId: opt(str()),
76
+ },
77
+ { open: true },
78
+ ),
79
+ obj(
80
+ {
81
+ operation: lit("board-call"),
82
+ caller: BindingSchema,
83
+ params: unknown(),
84
+ requestId: str(),
85
+ },
86
+ { open: true },
87
+ ),
88
+ obj(
89
+ {
90
+ operation: lit("board-notify"),
91
+ boardId: str(),
92
+ target: str(),
93
+ route: opt(arr(str())),
94
+ sessionId: str(),
95
+ turnId: str(),
96
+ notice: NoticeSchema,
97
+ },
98
+ { open: true },
99
+ ),
100
+ ]);
101
+ export type BoardEnvelope = Static<typeof Protocol>;
102
+ const protocolValidator = compile(Protocol);
103
+
104
+ export function parseEnvelope(value: unknown): BoardEnvelope {
105
+ if (!protocolValidator.check(value))
106
+ throw new Error("Invalid board host request");
107
+ return value as BoardEnvelope;
108
+ }
109
+ export function isBoardEnvelope(value: unknown): boolean {
110
+ return (
111
+ !!value &&
112
+ typeof value === "object" &&
113
+ "operation" in value &&
114
+ typeof value.operation === "string" &&
115
+ value.operation.startsWith("board-")
116
+ );
117
+ }
@@ -32,10 +32,10 @@ export function queryBoard(
32
32
  message_count: number;
33
33
  }>(
34
34
  `SELECT b.board_id,b.owner_folder,b.created_at,
35
- 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,
35
+ COALESCE((SELECT created_at FROM posts p WHERE p.board_id=b.board_id ORDER BY seq DESC LIMIT 1),(SELECT created_at FROM channels c WHERE c.board_id=b.board_id ORDER BY substr(created_at,1,16) DESC,name DESC LIMIT 1),b.created_at) AS last_activity_at,
36
36
  (SELECT COUNT(*) FROM channels c WHERE c.board_id=b.board_id) AS channel_count,
37
37
  (SELECT COUNT(*) FROM posts p WHERE p.board_id=b.board_id) AS message_count
38
- FROM boards b ORDER BY last_activity_at DESC,board_id DESC LIMIT ? OFFSET ?`,
38
+ FROM boards b ORDER BY substr(last_activity_at,1,16) DESC,(SELECT MAX(seq) FROM posts p WHERE p.board_id=b.board_id) DESC,board_id DESC LIMIT ? OFFSET ?`,
39
39
  limit + 1,
40
40
  offset,
41
41
  );
@@ -47,7 +47,8 @@ export function queryBoard(
47
47
  if (params.action === "get_channels") {
48
48
  const rows = store.all<{ name: string }>(
49
49
  `SELECT name FROM channels c WHERE board_id=? AND instr(name_search,?)>0 ORDER BY
50
- 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 ?`,
50
+ COALESCE((SELECT substr(created_at,1,16) FROM posts p WHERE p.board_id=c.board_id AND p.channel=c.name ORDER BY seq DESC LIMIT 1),substr(c.created_at,1,16)) ${order},
51
+ (SELECT MAX(seq) FROM posts p WHERE p.board_id=c.board_id AND p.channel=c.name) ${order},name ${order} LIMIT ? OFFSET ?`,
51
52
  board,
52
53
  caseFold(params.query ?? ""),
53
54
  limit + 1,
@@ -97,7 +98,7 @@ export function queryBoard(
97
98
  };
98
99
  }
99
100
  const replies = store.all<PostRecord>(
100
- `SELECT ${POST_COLUMNS} FROM posts WHERE board_id=? AND root=? AND id<>root ORDER BY created_at DESC,seq DESC LIMIT ? OFFSET ?`,
101
+ `SELECT ${POST_COLUMNS} FROM posts WHERE board_id=? AND root=? AND id<>root ORDER BY seq DESC LIMIT ? OFFSET ?`,
101
102
  board,
102
103
  root.message_id,
103
104
  limit + 1,
@@ -121,8 +122,8 @@ export function queryBoard(
121
122
  );
122
123
  const sort =
123
124
  params.sort === "activity"
124
- ? "(SELECT MAX(created_at) FROM posts r WHERE r.board_id=p.board_id AND r.root=p.id)"
125
- : "p.created_at";
125
+ ? "(SELECT MAX(seq) FROM posts r WHERE r.board_id=p.board_id AND r.root=p.id)"
126
+ : "p.seq";
126
127
  const roots = store.all<PostRecord>(
127
128
  `SELECT ${POST_COLUMNS} FROM posts p WHERE board_id=? AND channel=? AND id=root ORDER BY ${sort} ${order},seq ${order} LIMIT ? OFFSET ?`,
128
129
  board,
@@ -135,7 +136,7 @@ export function queryBoard(
135
136
  roots.map((root) => {
136
137
  const summary = store.summaries.get(board, root.thread_id);
137
138
  const reply = store.one<PostRecord>(
138
- `SELECT ${POST_COLUMNS} FROM posts WHERE board_id=? AND root=? AND id<>root ORDER BY created_at DESC,seq DESC LIMIT 1`,
139
+ `SELECT ${POST_COLUMNS} FROM posts WHERE board_id=? AND root=? AND id<>root ORDER BY seq DESC LIMIT 1`,
139
140
  board,
140
141
  root.message_id,
141
142
  );
@@ -152,10 +153,7 @@ export function queryBoard(
152
153
  ? { summary: summaryPreview(summary, chars) }
153
154
  : { root_post: preview(root, chars) }),
154
155
  reply_count: count,
155
- last_activity_at:
156
- reply && reply.created_at > root.created_at
157
- ? reply.created_at
158
- : root.created_at,
156
+ last_activity_at: reply?.created_at ?? root.created_at,
159
157
  ...(summary
160
158
  ? {}
161
159
  : { latest_reply: reply ? preview(reply, chars) : null }),
@@ -1,10 +1,16 @@
1
+ import { minuteTimestamp } from "../timestamps.js";
1
2
  import type { BoardParams } from "./contract.js";
2
3
 
3
4
  // Includes UTF-8 text, JSON escaping and metadata, in every tool mode.
4
5
  const MAX_RESPONSE_BYTES = 8000;
5
6
 
6
7
  export function serializeBoardResult(value: unknown): string {
7
- const text = JSON.stringify(value);
8
+ const text = JSON.stringify(value, (key, entry) =>
9
+ (key === "created_at" || key === "last_activity_at") &&
10
+ typeof entry === "string"
11
+ ? minuteTimestamp(entry)
12
+ : entry,
13
+ );
8
14
  if (Buffer.byteLength(text) > MAX_RESPONSE_BYTES)
9
15
  throw new Error(
10
16
  "Result exceeds the output budget. Reduce limit or max_chars_per_post; use read_post with a smaller limit_chars for long posts.",
@@ -0,0 +1,50 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { initializeDelivery, isMissingOptionalModule } from "../delivery.js";
3
+ import { createBoardTool } from "../tool.js";
4
+ import type { BoardRuntime } from "./coordinator.js";
5
+
6
+ export async function activateBoard(pi: ExtensionAPI, runtime: BoardRuntime) {
7
+ await initializeDelivery();
8
+ const tool = createBoardTool(runtime);
9
+ pi.registerTool(tool);
10
+ try {
11
+ const { registerGptPromptMode, prepareGptPromptMode } = await import(
12
+ "@howaboua/pi-codex-conversion/prompt-mode"
13
+ );
14
+ runtime.setPromptModePreparation((ctx) => prepareGptPromptMode(pi, ctx));
15
+ registerGptPromptMode(pi, (active) => {
16
+ runtime.gptPromptMode = active;
17
+ return [tool];
18
+ });
19
+ } catch (error) {
20
+ if (!isMissingOptionalModule(error, "prompt-mode")) throw error;
21
+ }
22
+ try {
23
+ const { adaptToolForCodeMode, registerCodeModeExtensionTools } =
24
+ await import("@howaboua/pi-codex-conversion/code-mode");
25
+ const registration = registerCodeModeExtensionTools(
26
+ pi,
27
+ () => [
28
+ adaptToolForCodeMode(tool, {
29
+ prepareInput: (input) =>
30
+ input === undefined || input === null ? {} : input,
31
+ discovery: "help",
32
+ }),
33
+ ],
34
+ { isActive: (ctx) => runtime.enabled(ctx) },
35
+ );
36
+ runtime.setToolRefresh(() => registration.refresh());
37
+ pi.on("session_shutdown", () => registration.unregister());
38
+ } catch (error) {
39
+ if (!isMissingOptionalModule(error, "code-mode")) throw error;
40
+ if (
41
+ error instanceof Error &&
42
+ "code" in error &&
43
+ error.code === "ERR_PACKAGE_PATH_NOT_EXPORTED"
44
+ )
45
+ throw new Error(
46
+ "Update Codex Conversion to use its Code and Notebook board tools",
47
+ { cause: error },
48
+ );
49
+ }
50
+ }