@howaboua/pi-agent-board 0.0.4 → 0.0.5

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/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # @howaboua/pi-agent-board
2
2
 
3
+ ## 0.0.5
4
+
5
+ - Requires Pi 1.5 or newer.
6
+ - Board agents now use Pi session IDs without changing identity on attachment. Existing authors, subscriptions and archives remain accessible.
7
+ - Removed custom changelog suppression. Updates use Pi's native notices and `collapseChangelog`.
8
+
3
9
  ## 0.0.4
4
10
 
5
11
  - - Board and connected extension briefings now refresh after Notes context-window rollover.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@howaboua/pi-agent-board",
3
- "version": "0.0.4",
3
+ "version": "0.0.5",
4
4
  "description": "Standalone agent message boards and a read-only browser viewer for Pi",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -17,7 +17,6 @@
17
17
  "INTEGRATION.md",
18
18
  "LICENSE",
19
19
  "tsconfig.json",
20
- "changelog.ts",
21
20
  "CHANGELOG.md"
22
21
  ],
23
22
  "main": "index.ts",
@@ -28,7 +27,6 @@
28
27
  },
29
28
  "pi": {
30
29
  "extensions": [
31
- "./changelog.ts",
32
30
  "./index.ts"
33
31
  ]
34
32
  },
@@ -50,9 +48,9 @@
50
48
  },
51
49
  "peerDependencies": {
52
50
  "@earendil-works/pi-ai": ">=1.1.0",
53
- "@earendil-works/pi-coding-agent": ">=1.1.0",
51
+ "@earendil-works/pi-coding-agent": ">=1.5.0",
54
52
  "@earendil-works/pi-tui": ">=1.1.0",
55
- "@howaboua/pi-codex-conversion": ">=4.0.5",
53
+ "@howaboua/pi-codex-conversion": ">=4.0.8",
56
54
  "typebox": "*"
57
55
  },
58
56
  "peerDependenciesMeta": {
@@ -64,6 +62,6 @@
64
62
  "access": "public"
65
63
  },
66
64
  "devDependencies": {
67
- "@howaboua/pi-codex-conversion": "4.0.5"
65
+ "@howaboua/pi-codex-conversion": "4.0.8"
68
66
  }
69
67
  }
package/src/archive.ts CHANGED
@@ -8,22 +8,27 @@ import { boundedBoardRead, checkMutationBudget } from "./response.js";
8
8
  export async function readSubscribedUpdates(
9
9
  caller: BoardBinding,
10
10
  seen: string[],
11
+ aliases: [string, string][] = [],
11
12
  ) {
12
13
  if (!existsSync(caller.databasePath)) return [];
13
14
  const { BoardStore } = await import("./store.js");
14
- const store = new BoardStore(caller.databasePath, false);
15
+ const store = new BoardStore(caller.databasePath, false, aliases);
15
16
  try {
17
+ const identities = JSON.stringify(store.agentIdentities(caller.agentName));
16
18
  return store.all<{ message_id: string; thread_id: string }>(
17
19
  `SELECT p.id AS message_id,p.root AS thread_id FROM posts p
18
- WHERE p.board_id=? AND p.author<>? AND NOT EXISTS
20
+ WHERE p.board_id=? AND p.author NOT IN (SELECT value FROM json_each(?)) AND NOT EXISTS
19
21
  (SELECT 1 FROM json_each(?) WHERE value=p.id) AND EXISTS
20
22
  (SELECT 1 FROM subscriptions s WHERE s.board_id=p.board_id
21
- AND s.agent=? AND s.enabled=1 AND s.target=CASE WHEN p.id=p.root
22
- THEN 'channel:'||p.channel ELSE 'thread:'||p.root END)
23
+ AND s.agent IN (SELECT value FROM json_each(?)) AND s.enabled=1
24
+ AND (s.agent=? OR NOT EXISTS (SELECT 1 FROM subscriptions n WHERE n.board_id=s.board_id AND n.target=s.target AND n.agent=?))
25
+ AND s.target=CASE WHEN p.id=p.root THEN 'channel:'||p.channel ELSE 'thread:'||p.root END)
23
26
  ORDER BY p.seq ASC LIMIT 50`,
24
27
  caller.boardId,
25
- caller.agentName,
28
+ identities,
26
29
  JSON.stringify(seen),
30
+ identities,
31
+ caller.agentName,
27
32
  caller.agentName,
28
33
  );
29
34
  } finally {
@@ -36,6 +41,7 @@ export async function executeArchive(
36
41
  memberNames: readonly string[],
37
42
  params: BoardParams,
38
43
  requestId: string,
44
+ aliases: [string, string][] = [],
39
45
  ) {
40
46
  if (
41
47
  params.action === "set_status" &&
@@ -65,7 +71,8 @@ export async function executeArchive(
65
71
  ...(params.agents_to_notify ?? []),
66
72
  ...(params.target_agent === undefined ? [] : [params.target_agent]),
67
73
  ]) {
68
- const target = agentPath(value, caller.agentName);
74
+ const path = agentPath(value, caller.legacyAgentName ?? caller.agentName);
75
+ const target = new Map(aliases).get(path) ?? path;
69
76
  if (!memberNames.includes(target))
70
77
  throw new Error(`Agent not bound to this tree: ${target}`);
71
78
  }
@@ -87,7 +94,7 @@ export async function executeArchive(
87
94
  return { value: page([], params), recipients: [] };
88
95
  throw new Error("This board has no channels or posts yet");
89
96
  }
90
- const store = new storage.BoardStore(caller.databasePath, write);
97
+ const store = new storage.BoardStore(caller.databasePath, write, aliases);
91
98
  try {
92
99
  const scope = {
93
100
  boardId: caller.boardId,
@@ -95,6 +102,9 @@ export async function executeArchive(
95
102
  ownerFolder: caller.ownerFolder,
96
103
  callerSessionId: caller.sessionId,
97
104
  agentName: caller.agentName,
105
+ ...(caller.legacyAgentName
106
+ ? { legacyAgentName: caller.legacyAgentName }
107
+ : {}),
98
108
  members: memberNames,
99
109
  };
100
110
  return write
package/src/awareness.ts CHANGED
@@ -88,7 +88,8 @@ export class BoardAwareness {
88
88
  ids?: unknown;
89
89
  };
90
90
  return data?.boardId === own.boardId &&
91
- data.agentName === own.agentName &&
91
+ (data.agentName === own.agentName ||
92
+ data.agentName === own.legacyAgentName) &&
92
93
  Array.isArray(data.ids)
93
94
  ? data.ids.filter((id): id is string => typeof id === "string")
94
95
  : [];
package/src/contract.ts CHANGED
@@ -1,7 +1,10 @@
1
- import { StringEnum, Type } from "@earendil-works/pi-ai";
2
- import type { Static } from "typebox";
1
+ import { type Static, Type } from "typebox";
3
2
  import { Check } from "typebox/value";
4
3
 
4
+ function StringEnum<T extends readonly string[]>(values: T) {
5
+ return Type.Unsafe<T[number]>({ type: "string", enum: values });
6
+ }
7
+
5
8
  const BOARD_ACTIONS = [
6
9
  "help",
7
10
  "list_boards",
@@ -134,7 +137,6 @@ export function parseBoardRequest(value: unknown): BoardParams {
134
137
  "thread_id",
135
138
  "message_id",
136
139
  "after_message_id",
137
- "board_id",
138
140
  ] as const) {
139
141
  const id = request[field];
140
142
  if (
@@ -146,6 +148,11 @@ export function parseBoardRequest(value: unknown): BoardParams {
146
148
  throw new Error(`${field} must be a UUID`);
147
149
  if (id !== undefined) request[field] = id.toLowerCase();
148
150
  }
151
+ if (
152
+ request.board_id !== undefined &&
153
+ !/^[a-zA-Z0-9_.-]+$/.test(request.board_id)
154
+ )
155
+ throw new Error("Invalid board_id");
149
156
  if (request.action === "post")
150
157
  exactlyOne(request, ["channel_name", "new_channel_name", "thread_id"]);
151
158
  if (request.action === "subscribe" || request.action === "unsubscribe")
@@ -162,7 +169,7 @@ export function required(value: string | undefined, field: string): string {
162
169
  }
163
170
  export function agentPath(value: string, caller: string): string {
164
171
  const path = value.startsWith("/") ? value : `${caller}/${value}`;
165
- if (!/^\/root(?:\/[a-zA-Z0-9_-]+)*$/.test(path))
172
+ if (!/^\/[a-zA-Z0-9_.-]+(?:\/[a-zA-Z0-9_-]+)*$/.test(path))
166
173
  throw new Error("Invalid agent path");
167
174
  return path;
168
175
  }
@@ -189,7 +196,7 @@ export const boardHelp = {
189
196
  notify:
190
197
  "agents_to_notify is one-time, excludes author; only running turns, no waking or offline notices",
191
198
  agents:
192
- "Use spawn's boardAgent; absolute /root/... or child path relative to you, not a pane or contextAgent",
199
+ "Agent reference /<Pi session ID>; saved legacy references remain valid",
193
200
  paging:
194
201
  "limit default20, cap50; cursor opaque, keep query/sort/full unchanged. Concurrent changes may shift pages",
195
202
  summaries:
@@ -222,8 +229,7 @@ export function gptBoardHelp(value: unknown): unknown {
222
229
  "EXACTLY one: channel_name|thread_id; channel=first posts, thread=replies; target_agent=you by default; posting→subscribe author UNLESS explicitly unsubscribed",
223
230
  notify:
224
231
  "agents_to_notify=once, excludes author; running turns ONLY; NO waking/offline notices",
225
- agents:
226
- "spawn's boardAgent: absolute /root/... OR relative child path; NOT pane/contextAgent",
232
+ agents: "Agent=/<Pi session ID>; legacy references accepted",
227
233
  paging:
228
234
  "limit default20 cap50; opaque cursor→unchanged query/sort/full; concurrent changes MAY shift pages",
229
235
  summaries:
package/src/identity.ts CHANGED
@@ -1,21 +1,26 @@
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";
6
+ import { type Static, Type } from "typebox";
8
7
  import { Check } from "typebox/value";
9
8
  import { readBoardConfig } from "./config.js";
10
9
 
11
- const uuid = Type.String({ pattern: "^[a-f0-9-]{36}$" });
10
+ const nativeId = Type.String({ pattern: "^[a-zA-Z0-9_.-]+$" });
12
11
  export const BindingSchema = Type.Object(
13
12
  {
14
13
  protocol: Type.Literal(1),
15
- boardId: uuid,
16
- rootSessionId: uuid,
17
- sessionId: uuid,
18
- agentName: Type.String({ pattern: "^/root(?:/[a-zA-Z0-9_-]+)*$" }),
14
+ boardId: nativeId,
15
+ rootSessionId: nativeId,
16
+ sessionId: nativeId,
17
+ agentName: Type.String({
18
+ pattern: "^/[a-zA-Z0-9_.-]+(?:/[a-zA-Z0-9_-]+)*$",
19
+ }),
20
+ legacyAgentName: Type.Optional(
21
+ Type.String({ pattern: "^/root(?:/[a-zA-Z0-9_-]+)*$" }),
22
+ ),
23
+ parentSessionId: Type.Optional(nativeId),
19
24
  ownerFolder: Type.String({ minLength: 1 }),
20
25
  databasePath: Type.String({ minLength: 1 }),
21
26
  enabled: Type.Boolean(),
@@ -25,7 +30,7 @@ export const BindingSchema = Type.Object(
25
30
  );
26
31
  export type BoardBinding = Static<typeof BindingSchema>;
27
32
  const ChildSchema = Type.Object({
28
- parentSessionId: uuid,
33
+ parentSessionId: nativeId,
29
34
  binding: BindingSchema,
30
35
  machine: Type.String(),
31
36
  sessionFile: Type.String({ minLength: 1 }),
@@ -41,7 +46,7 @@ export function setBoardDefault(ctx: ExtensionContext, enabled: boolean) {
41
46
  }
42
47
  const REMOVED = "shepherdr-board-removed";
43
48
  const SettingSchema = Type.Object({
44
- sessionId: uuid,
49
+ sessionId: nativeId,
45
50
  enabled: Type.Union([Type.Boolean(), Type.Null()]),
46
51
  });
47
52
 
@@ -97,10 +102,22 @@ export function rootBoardSetting(ctx: ExtensionContext) {
97
102
  export function parseBinding(value: unknown): BoardBinding {
98
103
  if (!Check(BindingSchema, value))
99
104
  throw new Error("Invalid Shepherdr board binding");
100
- return value as BoardBinding;
105
+ const saved = value as BoardBinding;
106
+ assertSessionIdentity(saved.sessionId, saved.rootSessionId);
107
+ const agentName = `/${saved.sessionId}`;
108
+ if (saved.agentName !== agentName && !/^\/root(?:\/|$)/.test(saved.agentName))
109
+ throw new Error("Board agent reference does not match its native session");
110
+ return {
111
+ ...saved,
112
+ agentName,
113
+ ...(saved.agentName !== agentName && !saved.legacyAgentName
114
+ ? { legacyAgentName: saved.agentName }
115
+ : {}),
116
+ };
101
117
  }
102
118
  export function binding(ctx: ExtensionContext): BoardBinding {
103
119
  const sessionId = ctx.sessionManager.getSessionId();
120
+ assertSessionIdentity(sessionId);
104
121
  let saved: BoardBinding | undefined;
105
122
  for (const entry of ctx.sessionManager.getEntries()) {
106
123
  if (entry.type !== "custom" || entry.customType !== BINDING) continue;
@@ -115,7 +132,7 @@ export function binding(ctx: ExtensionContext): BoardBinding {
115
132
  sessionId,
116
133
  rootSessionId: sessionId,
117
134
  boardId: sessionId,
118
- agentName: "/root",
135
+ agentName: `/${sessionId}`,
119
136
  ownerFolder,
120
137
  databasePath: resolve(ownerFolder, ".pi", "agent-message-board.sqlite"),
121
138
  enabled: false,
@@ -123,24 +140,41 @@ export function binding(ctx: ExtensionContext): BoardBinding {
123
140
  enabled: rootBoardSetting(ctx).enabled,
124
141
  };
125
142
  }
143
+ function assertSessionIdentity(...ids: string[]) {
144
+ if (ids.includes("root"))
145
+ throw new Error(
146
+ "Pi session ID root conflicts with the legacy /root reference; start a session with another ID",
147
+ );
148
+ }
126
149
  export function saveBinding(pi: ExtensionAPI, value: BoardBinding) {
127
150
  pi.appendEntry(BINDING, value);
128
151
  }
129
152
  export function members(ctx: ExtensionContext): BoardBinding[] {
130
153
  const own = binding(ctx);
131
- const found = new Map([[own.agentName, own]]);
154
+ const found = new Map([[own.sessionId, own]]);
132
155
  for (const entry of ctx.sessionManager.getEntries()) {
133
156
  if (entry.type === "custom" && entry.customType === REMOVED) {
134
157
  const value = parseBinding(entry.data);
135
- if (value.boardId === own.boardId) found.delete(value.agentName);
158
+ if (value.boardId === own.boardId) found.delete(value.sessionId);
136
159
  continue;
137
160
  }
138
161
  if (entry.type !== "custom" || entry.customType !== MEMBER) continue;
139
162
  const value = parseBinding(entry.data);
140
163
  if (value.rootSessionId === own.sessionId && value.boardId === own.boardId)
141
- found.set(value.agentName, value);
164
+ found.set(value.sessionId, value);
142
165
  }
143
- return [...found.values()];
166
+ const directory = [...found.values()];
167
+ return directory.map((member) => {
168
+ if (member.parentSessionId || !member.legacyAgentName) return member;
169
+ const path = member.legacyAgentName;
170
+ const parent = directory.find(
171
+ (entry) =>
172
+ (entry.legacyAgentName ??
173
+ (entry.sessionId === own.rootSessionId ? "/root" : undefined)) ===
174
+ path.slice(0, path.lastIndexOf("/")),
175
+ );
176
+ return parent ? { ...member, parentSessionId: parent.sessionId } : member;
177
+ });
144
178
  }
145
179
  export function saveMember(pi: ExtensionAPI, value: BoardBinding) {
146
180
  pi.appendEntry(MEMBER, value);
@@ -151,7 +185,7 @@ export function children(ctx: ExtensionContext): BoardChild[] {
151
185
  for (const entry of ctx.sessionManager.getEntries()) {
152
186
  if (entry.type === "custom" && entry.customType === REMOVED) {
153
187
  const value = parseBinding(entry.data);
154
- if (value.boardId === own.boardId) found.delete(value.agentName);
188
+ if (value.boardId === own.boardId) found.delete(value.sessionId);
155
189
  continue;
156
190
  }
157
191
  if (entry.type !== "custom" || entry.customType !== CHILD) continue;
@@ -162,7 +196,10 @@ export function children(ctx: ExtensionContext): BoardChild[] {
162
196
  value.parentSessionId === own.sessionId &&
163
197
  value.binding.boardId === own.boardId
164
198
  )
165
- found.set(value.binding.agentName, value);
199
+ found.set(value.binding.sessionId, {
200
+ ...value,
201
+ binding: parseBinding(value.binding),
202
+ });
166
203
  }
167
204
  return [...found.values()];
168
205
  }
@@ -172,3 +209,30 @@ export function saveChild(pi: ExtensionAPI, value: BoardChild) {
172
209
  export function removeMember(pi: ExtensionAPI, value: BoardBinding) {
173
210
  pi.appendEntry(REMOVED, value);
174
211
  }
212
+
213
+ /** Legacy names are aliases from native-session records, never access grants. */
214
+ export function boardAliases(
215
+ ctx: ExtensionContext,
216
+ boardId = binding(ctx).boardId,
217
+ ): [string, string][] {
218
+ const own = binding(ctx);
219
+ const aliases = new Map<string, string>();
220
+ if (own.boardId === boardId && own.sessionId === own.rootSessionId)
221
+ aliases.set("/root", own.agentName);
222
+ for (const entry of ctx.sessionManager.getEntries()) {
223
+ if (entry.type !== "custom") continue;
224
+ let member: BoardBinding;
225
+ if ([BINDING, MEMBER, REMOVED].includes(entry.customType))
226
+ member = parseBinding(entry.data);
227
+ else if (entry.customType === CHILD && Check(ChildSchema, entry.data))
228
+ member = parseBinding((entry.data as BoardChild).binding);
229
+ else continue;
230
+ if (member.boardId === boardId && member.legacyAgentName) {
231
+ const previous = aliases.get(member.legacyAgentName);
232
+ if (previous && previous !== member.agentName)
233
+ throw new Error("Ambiguous saved board agent reference");
234
+ aliases.set(member.legacyAgentName, member.agentName);
235
+ }
236
+ }
237
+ return [...aliases];
238
+ }
@@ -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,
package/src/protocol.ts CHANGED
@@ -1,5 +1,4 @@
1
- import { Type } from "@earendil-works/pi-ai";
2
- import type { Static } from "typebox";
1
+ import { type Static, Type } from "typebox";
3
2
  import { Check } from "typebox/value";
4
3
  import { BindingSchema } from "./identity.js";
5
4
 
@@ -57,6 +56,7 @@ const Protocol = Type.Union([
57
56
  operation: Type.Literal("board-notify"),
58
57
  boardId: Type.String(),
59
58
  target: Type.String(),
59
+ route: Type.Optional(Type.Array(Type.String())),
60
60
  sessionId: Type.String(),
61
61
  turnId: Type.String(),
62
62
  notice: NoticeSchema,
@@ -6,7 +6,7 @@ import {
6
6
  boardHelp,
7
7
  parseBoardRequest,
8
8
  } from "../contract.js";
9
- import { binding, members } from "../identity.js";
9
+ import { binding, boardAliases, members } from "../identity.js";
10
10
  import type { BoardAdapter } from "../integration.js";
11
11
  import type { BoardEnvelope } from "../protocol.js";
12
12
  import type { BoardSummarizer } from "../summarizer.js";
@@ -68,7 +68,9 @@ export class BoardOwner {
68
68
  return true;
69
69
  }
70
70
  if (request.operation === "board-catchup")
71
- return own.enabled ? readSubscribedUpdates(caller, request.seen) : [];
71
+ return own.enabled
72
+ ? readSubscribedUpdates(caller, request.seen, boardAliases(ctx))
73
+ : [];
72
74
  if (request.operation !== "board-call")
73
75
  throw new Error("Invalid board owner operation");
74
76
  const params = parseBoardRequest(request.params);
@@ -80,7 +82,7 @@ export class BoardOwner {
80
82
  : {
81
83
  ...boardHelp.rules,
82
84
  agents:
83
- "Absolute /root/... or child path relative to you; notices require registered members",
85
+ "Agent reference /<Pi session ID>; notices require registered members",
84
86
  },
85
87
  enabled: own.enabled,
86
88
  };
@@ -89,13 +91,20 @@ export class BoardOwner {
89
91
  const prepared: BoardParams =
90
92
  params.author === undefined
91
93
  ? params
92
- : { ...params, author: agentPath(params.author, caller.agentName) };
94
+ : {
95
+ ...params,
96
+ author: agentPath(
97
+ params.author,
98
+ caller.legacyAgentName ?? caller.agentName,
99
+ ),
100
+ };
93
101
  const active = new Map(this.turns.active);
94
102
  const result = await executeArchive(
95
103
  { ...caller, enabled: own.enabled },
96
104
  directory.map((member) => member.agentName),
97
105
  prepared,
98
106
  request.requestId,
107
+ boardAliases(ctx, params.board_id),
99
108
  );
100
109
  if ("notice" in result && result.notice) {
101
110
  // Replayed mutations have no notice: never start or cancel twice for a retry.
@@ -115,6 +124,21 @@ export class BoardOwner {
115
124
  result.recipients.slice(start, start + 16).map(async (target) => {
116
125
  const turn = active.get(target);
117
126
  if (!turn) return;
127
+ const route: string[] = [];
128
+ let member = directory.find(
129
+ (entry) => entry.sessionId === turn.sessionId,
130
+ );
131
+ while (
132
+ member &&
133
+ member.sessionId !== own.sessionId &&
134
+ route.length < directory.length
135
+ ) {
136
+ route.unshift(member.sessionId);
137
+ member = directory.find(
138
+ (entry) => entry.sessionId === member?.parentSessionId,
139
+ );
140
+ }
141
+ if (member?.sessionId !== own.sessionId) return;
118
142
  try {
119
143
  await this.notify(
120
144
  ctx,
@@ -122,6 +146,7 @@ export class BoardOwner {
122
146
  operation: "board-notify",
123
147
  boardId: own.boardId,
124
148
  target,
149
+ route,
125
150
  ...turn,
126
151
  notice: result.notice,
127
152
  },
@@ -2,7 +2,7 @@ import type {
2
2
  ExtensionAPI,
3
3
  ExtensionContext,
4
4
  } from "@earendil-works/pi-coding-agent";
5
- import { binding, saveBinding } from "../identity.js";
5
+ import { binding, parseBinding, saveBinding } from "../identity.js";
6
6
  import type { BoardAdapter } from "../integration.js";
7
7
  import { type BoardEnvelope, parseEnvelope } from "../protocol.js";
8
8
  import type { BoardOwner } from "./owner.js";
@@ -40,6 +40,15 @@ export class BoardRouting {
40
40
  const request = parseEnvelope(value);
41
41
  const own = binding(ctx);
42
42
  if (request.operation === "board-bind") {
43
+ parseBinding(request.binding);
44
+ if (own.sessionId === request.binding.sessionId)
45
+ throw new Error(
46
+ "Child and controller have the same Pi session ID; start the child with a different ID",
47
+ );
48
+ if (request.binding.agentName !== `/${request.binding.sessionId}`)
49
+ throw new Error(
50
+ "Restart the controller with updated extensions before spawning shared-board agents",
51
+ );
43
52
  if (
44
53
  !ctx.isIdle() ||
45
54
  ctx.sessionManager
@@ -55,7 +64,13 @@ export class BoardRouting {
55
64
  throw new Error(
56
65
  "Bind board identity only in a fresh idle child before its first task",
57
66
  );
58
- const adopted = { ...request.binding, sessionId: own.sessionId };
67
+ const { legacyAgentName: _legacy, ...proposed } = request.binding;
68
+ const adopted = {
69
+ ...proposed,
70
+ sessionId: own.sessionId,
71
+ agentName: own.agentName,
72
+ parentSessionId: request.binding.sessionId,
73
+ };
59
74
  saveBinding(this.pi, adopted);
60
75
  await this.refresh(ctx);
61
76
  return adopted;
package/src/search.ts CHANGED
@@ -19,10 +19,12 @@ export function searchBoard(
19
19
  args.push(params.channel_name);
20
20
  }
21
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);
22
+ clauses.push(`(author IN (SELECT value FROM json_each(?)) 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 IN (SELECT value FROM json_each(?)))))`);
24
+ const authors = JSON.stringify(
25
+ store.agentIdentities(agentPath(params.author, "/root")),
26
+ );
27
+ args.push(authors, authors);
26
28
  }
27
29
  if (params.query !== undefined) {
28
30
  clauses.push("instr(body_search,?)>0");
package/src/store.ts CHANGED
@@ -20,6 +20,7 @@ export interface BoardScope {
20
20
  rootSessionId: string;
21
21
  ownerFolder: string;
22
22
  agentName: string;
23
+ legacyAgentName?: string;
23
24
  callerSessionId: string;
24
25
  members: readonly string[];
25
26
  }
@@ -42,7 +43,9 @@ export class BoardStore {
42
43
  readonly db: DatabaseSync;
43
44
  readonly summaries: ThreadSummaries;
44
45
  private readonly hasThreadStatuses: boolean;
45
- constructor(path: string, write: boolean) {
46
+ private readonly aliases: Map<string, string>;
47
+ constructor(path: string, write: boolean, aliases: [string, string][] = []) {
48
+ this.aliases = new Map(aliases);
46
49
  const fresh = !existsSync(path);
47
50
  if (write && fresh) mkdirSync(dirname(path), { recursive: true });
48
51
  this.db = new DatabaseSync(path, { readOnly: !write });
@@ -75,6 +78,18 @@ export class BoardStore {
75
78
  throw error;
76
79
  }
77
80
  }
81
+ canonicalAgent(value: string) {
82
+ return this.aliases.get(value) ?? value;
83
+ }
84
+ agentIdentities(value: string) {
85
+ const canonical = this.canonicalAgent(value);
86
+ return [
87
+ canonical,
88
+ ...[...this.aliases]
89
+ .filter(([, native]) => native === canonical)
90
+ .map(([legacy]) => legacy),
91
+ ];
92
+ }
78
93
  one<T>(sql: string, ...args: SQLInputValue[]): T | undefined {
79
94
  return this.db.prepare(sql).get(...args) as T | undefined;
80
95
  }
@@ -186,6 +201,16 @@ export class BoardStore {
186
201
  enabled: boolean,
187
202
  implicit = false,
188
203
  ) {
204
+ if (
205
+ implicit &&
206
+ this.one(
207
+ "SELECT 1 FROM subscriptions WHERE board_id=? AND target=? AND agent IN (SELECT value FROM json_each(?))",
208
+ board,
209
+ target,
210
+ JSON.stringify(this.agentIdentities(agent)),
211
+ )
212
+ )
213
+ return;
189
214
  this.run(
190
215
  implicit
191
216
  ? "INSERT OR IGNORE INTO subscriptions VALUES(?,?,?,1)"
@@ -194,7 +219,9 @@ export class BoardStore {
194
219
  );
195
220
  }
196
221
  private resolve(scope: BoardScope, value: string) {
197
- const path = agentPath(value, scope.agentName);
222
+ const path = this.canonicalAgent(
223
+ agentPath(value, scope.legacyAgentName ?? scope.agentName),
224
+ );
198
225
  if (!scope.members.includes(path))
199
226
  throw new Error(`Agent not bound to this tree: ${path}`);
200
227
  return path;
@@ -307,11 +334,19 @@ export class BoardStore {
307
334
  ).channel_name;
308
335
  const target = root === id ? `channel:${channel}` : `thread:${root}`;
309
336
  for (const { agent } of this.all<{ agent: string }>(
310
- "SELECT agent FROM subscriptions WHERE board_id=? AND target=? AND enabled=1",
337
+ `SELECT s.agent FROM subscriptions s WHERE s.board_id=? AND s.target=? AND s.enabled=1`,
311
338
  board,
312
339
  target,
313
- ))
314
- recipients.add(agent);
340
+ )) {
341
+ const canonical = this.canonicalAgent(agent);
342
+ const override = this.one<{ enabled: number }>(
343
+ "SELECT enabled FROM subscriptions WHERE board_id=? AND target=? AND agent=?",
344
+ board,
345
+ target,
346
+ canonical,
347
+ );
348
+ if (!override || override.enabled) recipients.add(canonical);
349
+ }
315
350
  recipients.delete(scope.agentName);
316
351
  const post: PostRecord = {
317
352
  message_id: id,
package/changelog.ts DELETED
@@ -1,337 +0,0 @@
1
- // Generated extension packages copy this file during changelog:extensions.
2
-
3
- import { randomUUID } from "node:crypto";
4
- import { readFileSync } from "node:fs";
5
- import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
6
- import { dirname, join } from "node:path";
7
- import { fileURLToPath } from "node:url";
8
- import {
9
- DynamicBorder,
10
- type ExtensionAPI,
11
- getAgentDir,
12
- getMarkdownTheme,
13
- } from "@earendil-works/pi-coding-agent";
14
- import { Container, Markdown, Spacer, Text } from "@earendil-works/pi-tui";
15
-
16
- const ENTRY_TYPE = "@howaboua/pi-stuff/changelog";
17
- const REGISTRATION_CHANNEL = "@howaboua/pi-stuff/changelog/register/v1";
18
- const STATE_FILENAME = "howaboua-pi-stuff-changelog.json";
19
- const SUPPRESS_KEY = "suppress";
20
- const LOCK_STALE_MS = 30_000;
21
- const LOCK_TIMEOUT_MS = 2_000;
22
-
23
- interface PackageMetadata {
24
- name: string;
25
- version: string;
26
- }
27
-
28
- interface PackageRegistration extends PackageMetadata {
29
- changelogPath: string;
30
- }
31
-
32
- interface RegistrationEvent {
33
- accept: () => void;
34
- registration: PackageRegistration;
35
- }
36
-
37
- interface ChangelogEntry {
38
- content: string;
39
- version: string;
40
- }
41
-
42
- interface ChangelogEntryData {
43
- markdown: string;
44
- }
45
-
46
- type ChangelogState = Record<string, boolean | string>;
47
-
48
- function packageRegistration(): PackageRegistration {
49
- const packageDirectory = fileURLToPath(new URL(".", import.meta.url));
50
- const metadata = JSON.parse(
51
- readFileSync(join(packageDirectory, "package.json"), "utf8"),
52
- ) as Partial<PackageMetadata>;
53
- if (typeof metadata.name !== "string" || typeof metadata.version !== "string")
54
- throw new Error(`Invalid package metadata in ${packageDirectory}`);
55
- return {
56
- name: metadata.name,
57
- version: metadata.version,
58
- changelogPath: join(packageDirectory, "CHANGELOG.md"),
59
- };
60
- }
61
-
62
- function isRegistrationEvent(value: unknown): value is RegistrationEvent {
63
- if (!value || typeof value !== "object") return false;
64
- const event = value as Partial<RegistrationEvent>;
65
- return (
66
- typeof event.accept === "function" &&
67
- typeof event.registration?.name === "string" &&
68
- typeof event.registration.version === "string" &&
69
- typeof event.registration.changelogPath === "string"
70
- );
71
- }
72
-
73
- function parseChangelog(markdown: string): ChangelogEntry[] {
74
- const entries: ChangelogEntry[] = [];
75
- let currentLines: string[] = [];
76
- let currentVersion: string | undefined;
77
-
78
- for (const line of markdown.split("\n")) {
79
- const version = line.match(/^##\s+\[?(\d+\.\d+\.\d+)\]?(?:\s.*)?$/)?.[1];
80
- if (version) {
81
- if (currentVersion)
82
- entries.push({
83
- content: currentLines.join("\n").trim(),
84
- version: currentVersion,
85
- });
86
- currentVersion = version;
87
- currentLines = [line];
88
- } else if (currentVersion) {
89
- currentLines.push(line);
90
- }
91
- }
92
-
93
- if (currentVersion)
94
- entries.push({
95
- content: currentLines.join("\n").trim(),
96
- version: currentVersion,
97
- });
98
- return entries;
99
- }
100
-
101
- function compareVersions(left: string, right: string): number {
102
- const leftParts = left.split(".").map(Number);
103
- const rightParts = right.split(".").map(Number);
104
- for (let index = 0; index < 3; index++) {
105
- const difference = (leftParts[index] ?? 0) - (rightParts[index] ?? 0);
106
- if (difference !== 0) return difference;
107
- }
108
- return 0;
109
- }
110
-
111
- function isStableVersion(version: string): boolean {
112
- return /^\d+\.\d+\.\d+$/.test(version);
113
- }
114
-
115
- function statePath(): string {
116
- return join(getAgentDir(), STATE_FILENAME);
117
- }
118
-
119
- async function readState(path: string): Promise<ChangelogState> {
120
- let text: string;
121
- try {
122
- text = await readFile(path, "utf8");
123
- } catch (error) {
124
- if ((error as NodeJS.ErrnoException).code === "ENOENT") return {};
125
- throw error;
126
- }
127
- const parsed = JSON.parse(text) as unknown;
128
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
129
- throw new Error(`${path} must contain a JSON object`);
130
- for (const [name, value] of Object.entries(parsed)) {
131
- if (name === SUPPRESS_KEY) {
132
- if (typeof value !== "boolean")
133
- throw new Error(`${path} ${SUPPRESS_KEY} must be a boolean`);
134
- } else if (typeof value !== "string") {
135
- throw new Error(`${path} version for ${name} must be a string`);
136
- }
137
- }
138
- return parsed as ChangelogState;
139
- }
140
-
141
- async function acquireLock(path: string): Promise<() => Promise<void>> {
142
- const deadline = Date.now() + LOCK_TIMEOUT_MS;
143
- while (true) {
144
- try {
145
- await mkdir(path);
146
- return () => rm(path, { force: true, recursive: true });
147
- } catch (error) {
148
- if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
149
- const info = await stat(path).catch(() => undefined);
150
- if (info && Date.now() - info.mtimeMs > LOCK_STALE_MS) {
151
- await rm(path, { force: true, recursive: true });
152
- continue;
153
- }
154
- if (Date.now() >= deadline)
155
- throw new Error(`Timed out waiting for ${path}`);
156
- await new Promise((resolve) => setTimeout(resolve, 20));
157
- }
158
- }
159
- }
160
-
161
- async function writeState(path: string, state: ChangelogState): Promise<void> {
162
- await mkdir(dirname(path), { mode: 0o700, recursive: true });
163
- const temporaryPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
164
- try {
165
- const ordered = Object.fromEntries(
166
- Object.entries(state).sort(([left], [right]) =>
167
- left.localeCompare(right),
168
- ),
169
- );
170
- await writeFile(temporaryPath, `${JSON.stringify(ordered, null, 2)}\n`, {
171
- encoding: "utf8",
172
- mode: 0o600,
173
- });
174
- await rename(temporaryPath, path);
175
- } catch (error) {
176
- await rm(temporaryPath, { force: true });
177
- throw error;
178
- }
179
- }
180
-
181
- function packageMarkdown(
182
- registration: PackageRegistration,
183
- entries: ChangelogEntry[],
184
- ): string {
185
- const body = (entry: ChangelogEntry) =>
186
- entry.content
187
- .replace(/^##[^\n]*\n*/, "")
188
- .replace(/^###\s+(?:Changes|Minor Changes|Patch Changes)\s*\n*/gim, "")
189
- .replace(/^###\s+(.+)$/gm, "**$1**");
190
- if (entries.length === 1) {
191
- const [entry] = entries;
192
- if (!entry) return "";
193
- return `## ${registration.name} ${entry.version}\n\n${body(entry)}`;
194
- }
195
- return [
196
- `## ${registration.name}`,
197
- ...entries.map((entry) => `**${entry.version}**\n\n${body(entry)}`),
198
- ].join("\n\n");
199
- }
200
-
201
- async function claimUpdates(
202
- registrations: Iterable<PackageRegistration>,
203
- ): Promise<{ errors: string[]; markdown?: string }> {
204
- const stableRegistrations = [...registrations]
205
- .filter((registration) => isStableVersion(registration.version))
206
- .sort((left, right) => left.name.localeCompare(right.name));
207
- if (stableRegistrations.length === 0) return { errors: [] };
208
- const path = statePath();
209
- await mkdir(dirname(path), { mode: 0o700, recursive: true });
210
- const release = await acquireLock(`${path}.lock`);
211
- try {
212
- const state = await readState(path);
213
- const errors: string[] = [];
214
- const sections: string[] = [];
215
- let changed = false;
216
- if (state[SUPPRESS_KEY] === true) {
217
- for (const registration of stableRegistrations) {
218
- const seenVersion = state[registration.name];
219
- if (
220
- typeof seenVersion !== "string" ||
221
- compareVersions(registration.version, seenVersion) > 0
222
- ) {
223
- state[registration.name] = registration.version;
224
- changed = true;
225
- }
226
- }
227
- if (changed) await writeState(path, state);
228
- return { errors };
229
- }
230
- for (const registration of stableRegistrations) {
231
- const seenVersion = state[registration.name];
232
- if (
233
- typeof seenVersion === "string" &&
234
- compareVersions(registration.version, seenVersion) <= 0
235
- )
236
- continue;
237
- try {
238
- const entries = parseChangelog(
239
- await readFile(registration.changelogPath, "utf8"),
240
- ).filter(
241
- (entry) =>
242
- compareVersions(entry.version, registration.version) <= 0 &&
243
- (typeof seenVersion === "string"
244
- ? compareVersions(entry.version, seenVersion) > 0
245
- : entry.version === registration.version),
246
- );
247
- if (entries.length === 0) {
248
- errors.push(
249
- `No ${registration.version} changelog entry found for ${registration.name}`,
250
- );
251
- continue;
252
- }
253
- sections.push(packageMarkdown(registration, entries));
254
- state[registration.name] = registration.version;
255
- changed = true;
256
- } catch (error) {
257
- errors.push(
258
- `Could not read the ${registration.name} changelog: ${error instanceof Error ? error.message : String(error)}`,
259
- );
260
- }
261
- }
262
- if (changed) await writeState(path, state);
263
- return {
264
- errors,
265
- ...(sections.length > 0 ? { markdown: sections.join("\n\n") } : {}),
266
- };
267
- } finally {
268
- await release();
269
- }
270
- }
271
-
272
- function registerCoordinator(
273
- pi: ExtensionAPI,
274
- registration: PackageRegistration,
275
- ): void {
276
- let accepted = false;
277
- pi.events.emit(REGISTRATION_CHANNEL, {
278
- registration,
279
- accept: () => {
280
- accepted = true;
281
- },
282
- } satisfies RegistrationEvent);
283
- if (accepted) return;
284
-
285
- const registrations = new Map([[registration.name, registration]]);
286
- pi.events.on(REGISTRATION_CHANNEL, (value) => {
287
- if (!isRegistrationEvent(value)) return;
288
- registrations.set(value.registration.name, value.registration);
289
- value.accept();
290
- });
291
- pi.registerEntryRenderer<ChangelogEntryData>(
292
- ENTRY_TYPE,
293
- (entry, _options, theme) => {
294
- if (!entry.data) return undefined;
295
- const container = new Container();
296
- container.addChild(new DynamicBorder());
297
- container.addChild(
298
- new Text(theme.bold(theme.fg("accent", "What's New")), 1, 0),
299
- );
300
- container.addChild(new Spacer(1));
301
- container.addChild(
302
- new Markdown(entry.data.markdown.trim(), 1, 0, getMarkdownTheme()),
303
- );
304
- container.addChild(new Spacer(1));
305
- container.addChild(new DynamicBorder());
306
- return container;
307
- },
308
- );
309
- pi.on("session_start", async (event, ctx) => {
310
- if (event.reason === "reload" || ctx.mode !== "tui") return;
311
- if (
312
- ctx.sessionManager
313
- .getEntries()
314
- .some((entry) =>
315
- ["branch_summary", "compaction", "message"].includes(entry.type),
316
- )
317
- )
318
- return;
319
- try {
320
- const update = await claimUpdates(registrations.values());
321
- if (update.markdown)
322
- pi.appendEntry<ChangelogEntryData>(ENTRY_TYPE, {
323
- markdown: update.markdown,
324
- });
325
- for (const error of update.errors) ctx.ui.notify(error, "warning");
326
- } catch (error) {
327
- ctx.ui.notify(
328
- `Could not update Howaboua changelog state: ${error instanceof Error ? error.message : String(error)}`,
329
- "warning",
330
- );
331
- }
332
- });
333
- }
334
-
335
- export default function howabouaPackageChangelog(pi: ExtensionAPI): void {
336
- registerCoordinator(pi, packageRegistration());
337
- }