@howaboua/pi-shepherdr 0.2.9 → 0.2.11

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.
@@ -0,0 +1,413 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import type {
3
+ ExtensionAPI,
4
+ ExtensionContext,
5
+ } from "@earendil-works/pi-coding-agent";
6
+ import type { AgentFleet, ConnectedMachine } from "../fleet.js";
7
+ import { sessionPath } from "../herdr.js";
8
+ import {
9
+ requestContext,
10
+ sessionContextPath,
11
+ } from "../remote/shepherdr-context.mjs";
12
+ import { executeArchive } from "./archive.js";
13
+ import {
14
+ type BoardScope,
15
+ readBoardConfig,
16
+ writeBoardConfig,
17
+ } from "./config.js";
18
+ import {
19
+ agentPath,
20
+ type BoardParams,
21
+ boardHelp,
22
+ parseBoardRequest,
23
+ } from "./contract.js";
24
+ import {
25
+ binding,
26
+ children,
27
+ members,
28
+ parseBinding,
29
+ rootBoardSetting,
30
+ saveBinding,
31
+ saveBoardSetting,
32
+ saveChild,
33
+ saveMember,
34
+ sessionBoardSetting,
35
+ } from "./identity.js";
36
+ import { type BoardEnvelope, parseEnvelope } from "./protocol.js";
37
+ import { BoardTurns } from "./turns.js";
38
+
39
+ export class AgentBoard {
40
+ private readonly pi: ExtensionAPI;
41
+ private readonly fleet: AgentFleet;
42
+ private readonly turns: BoardTurns;
43
+ private refreshTools: (() => void) | undefined;
44
+ private lastSetting: { sessionId: string; enabled: boolean } | undefined;
45
+ private configError: string | undefined;
46
+ constructor(pi: ExtensionAPI, fleet: AgentFleet) {
47
+ this.pi = pi;
48
+ this.fleet = fleet;
49
+ this.turns = new BoardTurns(pi, (ctx, request) =>
50
+ this.toOwner(ctx, request),
51
+ );
52
+ pi.on("session_start", (_event, ctx) => this.refresh(ctx));
53
+ pi.on("before_agent_start", async (_event, ctx) => {
54
+ // Reconcile resumed/offline children before tool/prompt preparation.
55
+ const own = binding(ctx);
56
+ if (own.upstream) {
57
+ try {
58
+ const result = await this.toOwner(ctx, {
59
+ operation: "board-call",
60
+ caller: own,
61
+ params: { action: "help" },
62
+ requestId: "status",
63
+ });
64
+ if (
65
+ typeof result === "object" &&
66
+ result !== null &&
67
+ "enabled" in result &&
68
+ typeof result.enabled === "boolean" &&
69
+ result.enabled !== own.enabled
70
+ )
71
+ saveBinding(pi, { ...own, enabled: result.enabled });
72
+ } catch (error) {
73
+ if (own.enabled)
74
+ ctx.ui.notify(
75
+ `Board owner unavailable: ${String(error)}`,
76
+ "warning",
77
+ );
78
+ }
79
+ }
80
+ await this.refresh(ctx);
81
+ });
82
+ }
83
+ setToolRefresh(refresh: () => void) {
84
+ this.refreshTools = refresh;
85
+ }
86
+ enabled(ctx: ExtensionContext | undefined) {
87
+ return ctx ? binding(ctx).enabled : false;
88
+ }
89
+ private async refresh(ctx: ExtensionContext) {
90
+ const own = binding(ctx);
91
+ const setting = own.upstream ? undefined : rootBoardSetting(ctx);
92
+ if (setting?.error && setting.error !== this.configError)
93
+ ctx.ui.notify(`Board disabled: ${setting.error}`, "error");
94
+ this.configError = setting?.error;
95
+ const active = this.pi.getActiveTools().filter((name) => name !== "board");
96
+ if (own.enabled) active.push("board");
97
+ this.pi.setActiveTools(active);
98
+ this.refreshTools?.();
99
+ if (!own.enabled) this.turns.active.clear();
100
+ const changed =
101
+ this.lastSetting?.sessionId !== own.sessionId ||
102
+ this.lastSetting.enabled !== own.enabled;
103
+ this.lastSetting = { sessionId: own.sessionId, enabled: own.enabled };
104
+ if (changed && !own.upstream) await this.propagateEnabled(ctx, own.enabled);
105
+ }
106
+ settings(ctx: ExtensionContext) {
107
+ const own = binding(ctx);
108
+ if (own.upstream)
109
+ throw new Error("Change the board setting in the owning root session");
110
+ return {
111
+ ...readBoardConfig(own.ownerFolder),
112
+ session: sessionBoardSetting(ctx),
113
+ };
114
+ }
115
+ async setSetting(
116
+ ctx: ExtensionContext,
117
+ scope: BoardScope,
118
+ enabled: boolean | undefined,
119
+ ) {
120
+ if (!ctx.isIdle())
121
+ throw new Error("Change the board setting after this session settles");
122
+ const own = binding(ctx);
123
+ if (own.upstream)
124
+ throw new Error("Change the board setting in the owning root session");
125
+ if (scope === "session") saveBoardSetting(this.pi, ctx, enabled);
126
+ else writeBoardConfig(own.ownerFolder, scope, enabled);
127
+ await this.refresh(ctx);
128
+ }
129
+ status(ctx: ExtensionContext) {
130
+ const own = binding(ctx);
131
+ const setting = own.upstream ? undefined : rootBoardSetting(ctx);
132
+ return `Board ${own.enabled ? "on" : "off"} (${setting?.source ?? "inherited from owner"}). ${own.boardId}\nArchive: ${own.databasePath}${setting?.error ? `\n${setting.error}` : ""}`;
133
+ }
134
+ async execute(ctx: ExtensionContext, input: unknown, requestId: string) {
135
+ const params = parseBoardRequest(input);
136
+ const caller = binding(ctx);
137
+ if (!caller.upstream) {
138
+ const setting = rootBoardSetting(ctx);
139
+ if (setting.error) throw new Error(setting.error);
140
+ }
141
+ if (!caller.enabled)
142
+ throw new Error(
143
+ "Board is off; the user can enable it with /herdr board on",
144
+ );
145
+ return this.toOwner(ctx, {
146
+ operation: "board-call",
147
+ caller,
148
+ params,
149
+ requestId,
150
+ });
151
+ }
152
+ async prepare(
153
+ ctx: ExtensionContext,
154
+ runtime: ConnectedMachine,
155
+ name: string,
156
+ args: readonly string[],
157
+ ) {
158
+ const own = binding(ctx);
159
+ if (!own.enabled) return undefined;
160
+ if (
161
+ args.some((arg) =>
162
+ /^(?:--(?:session(?:-id)?|continue|resume|no-session|fork)(?:=|$)|-[cr]$)/.test(
163
+ arg,
164
+ ),
165
+ )
166
+ )
167
+ throw new Error(
168
+ "Board child binding requires a fresh saved Pi session; use assign for existing agents",
169
+ );
170
+ const file = ctx.sessionManager.getSessionFile();
171
+ if (!file)
172
+ throw new Error(
173
+ "Board child binding requires a saved controller session",
174
+ );
175
+ const segment =
176
+ name.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 64) || "agent";
177
+ const agentName = `${own.agentName}/${segment}-${randomUUID()}`;
178
+ const upstream = runtime.local
179
+ ? sessionContextPath(file)
180
+ : runtime.client.contextRelayPath();
181
+ // Persist only session identity/routes, never an empty archive or board.
182
+ saveBinding(this.pi, own);
183
+ return {
184
+ accept: async (agent: Parameters<typeof sessionPath>[0]) => {
185
+ const sessionFile = sessionPath(agent);
186
+ if (!sessionFile)
187
+ throw new Error("Spawned agent has no native Pi session path");
188
+ const prepared = { ...own, agentName, upstream };
189
+ const result = await runtime.client.requestContext(
190
+ sessionContextPath(sessionFile),
191
+ { operation: "board-bind", binding: prepared },
192
+ );
193
+ const adopted = parseBinding(result);
194
+ if (
195
+ adopted.boardId !== own.boardId ||
196
+ adopted.databasePath !== own.databasePath ||
197
+ adopted.agentName !== agentName ||
198
+ adopted.rootSessionId !== own.rootSessionId ||
199
+ adopted.upstream !== upstream ||
200
+ adopted.sessionId === own.sessionId
201
+ )
202
+ throw new Error("Spawned agent did not adopt its board binding");
203
+ if (ctx.sessionManager.getSessionId() !== own.sessionId)
204
+ throw new Error("Controller session changed during board binding");
205
+ await this.toOwner(ctx, {
206
+ operation: "board-register",
207
+ caller: own,
208
+ member: adopted,
209
+ });
210
+ saveChild(this.pi, {
211
+ parentSessionId: own.sessionId,
212
+ binding: adopted,
213
+ machine: runtime.machine,
214
+ sessionFile,
215
+ });
216
+ return adopted.agentName;
217
+ },
218
+ };
219
+ }
220
+ async handle(
221
+ ctx: ExtensionContext,
222
+ value: unknown,
223
+ signal?: AbortSignal,
224
+ ): Promise<unknown> {
225
+ const request = parseEnvelope(value);
226
+ const own = binding(ctx);
227
+ if (request.operation === "board-bind") {
228
+ if (
229
+ !ctx.isIdle() ||
230
+ ctx.sessionManager
231
+ .getEntries()
232
+ .some(
233
+ (entry) =>
234
+ (entry.type === "message" &&
235
+ ["user", "assistant"].includes(entry.message.role)) ||
236
+ (entry.type === "custom" &&
237
+ entry.customType === "shepherdr-board-binding"),
238
+ )
239
+ )
240
+ throw new Error(
241
+ "Bind board identity only in a fresh idle child before its first task",
242
+ );
243
+ const adopted = { ...request.binding, sessionId: own.sessionId };
244
+ saveBinding(this.pi, adopted);
245
+ await this.refresh(ctx);
246
+ return adopted;
247
+ }
248
+ if (request.operation === "board-enabled") {
249
+ if (!own.upstream || request.boardId !== own.boardId)
250
+ throw new Error("Invalid board setting route");
251
+ saveBinding(this.pi, { ...own, enabled: request.enabled });
252
+ await this.refresh(ctx);
253
+ await this.propagateEnabled(ctx, request.enabled);
254
+ return true;
255
+ }
256
+ if (request.operation === "board-notify") {
257
+ if (!own.enabled || request.boardId !== own.boardId) return false;
258
+ if (request.target === own.agentName) return this.turns.deliver(request);
259
+ return this.routeNotice(ctx, request, signal);
260
+ }
261
+ return this.toOwner(ctx, request, signal);
262
+ }
263
+ private async toOwner(
264
+ ctx: ExtensionContext,
265
+ request: BoardEnvelope,
266
+ signal?: AbortSignal,
267
+ ): Promise<unknown> {
268
+ const own = binding(ctx);
269
+ if (own.upstream) {
270
+ try {
271
+ return await requestContext(own.upstream, request, signal);
272
+ } catch (error) {
273
+ if (
274
+ error instanceof Error &&
275
+ error.message.startsWith("Shared context response was lost")
276
+ )
277
+ throw new Error(
278
+ "Board response lost; a mutation may have completed. Read the channel/thread before retrying",
279
+ { cause: error },
280
+ );
281
+ if (
282
+ error instanceof Error &&
283
+ error.message.startsWith("Shared context owner is unavailable")
284
+ )
285
+ throw new Error(
286
+ "Board owner unavailable; resume its Pi session and reconnect its machine",
287
+ { cause: error },
288
+ );
289
+ throw error;
290
+ }
291
+ }
292
+ if (!("caller" in request)) throw new Error("Invalid board owner request");
293
+ const directory = members(ctx);
294
+ const caller = directory.find(
295
+ (member) =>
296
+ member.sessionId === request.caller.sessionId &&
297
+ member.agentName === request.caller.agentName,
298
+ );
299
+ if (
300
+ !caller ||
301
+ request.caller.boardId !== own.boardId ||
302
+ request.caller.databasePath !== own.databasePath
303
+ )
304
+ throw new Error("Caller not bound to this board");
305
+ if (request.operation === "board-register") {
306
+ const member = request.member;
307
+ if (
308
+ member.boardId !== own.boardId ||
309
+ member.databasePath !== own.databasePath ||
310
+ member.rootSessionId !== own.rootSessionId ||
311
+ !member.agentName.startsWith(`${caller.agentName}/`)
312
+ )
313
+ throw new Error("Invalid board member registration");
314
+ if (
315
+ directory.some(
316
+ (entry) =>
317
+ entry.agentName === member.agentName ||
318
+ entry.sessionId === member.sessionId,
319
+ )
320
+ )
321
+ throw new Error("Board member already bound");
322
+ saveMember(this.pi, member);
323
+ return true;
324
+ }
325
+ if (request.operation === "board-active") {
326
+ if (own.enabled) this.turns.register(caller, request);
327
+ return true;
328
+ }
329
+ if (request.operation !== "board-call")
330
+ throw new Error("Invalid board owner operation");
331
+ const params = parseBoardRequest(request.params);
332
+ if (params.action === "help") return { ...boardHelp, enabled: own.enabled };
333
+ if (!own.enabled)
334
+ throw new Error(
335
+ "Board is off; the user can enable it with /herdr board on",
336
+ );
337
+ const prepared: BoardParams =
338
+ params.author === undefined
339
+ ? params
340
+ : { ...params, author: agentPath(params.author, caller.agentName) };
341
+ const active = new Map(this.turns.active);
342
+ const result = await executeArchive(
343
+ { ...caller, enabled: own.enabled },
344
+ directory.map((member) => member.agentName),
345
+ prepared,
346
+ request.requestId,
347
+ );
348
+ if ("notice" in result && result.notice) {
349
+ for (let start = 0; start < result.recipients.length; start += 16) {
350
+ await Promise.all(
351
+ result.recipients.slice(start, start + 16).map(async (target) => {
352
+ const turn = active.get(target);
353
+ if (!turn) return;
354
+ try {
355
+ await this.handle(
356
+ ctx,
357
+ {
358
+ operation: "board-notify",
359
+ boardId: own.boardId,
360
+ target,
361
+ ...turn,
362
+ notice: result.notice,
363
+ },
364
+ AbortSignal.timeout(750),
365
+ );
366
+ } catch {
367
+ /* Committed posts succeed even when a running turn stops accepting. */
368
+ }
369
+ }),
370
+ );
371
+ }
372
+ }
373
+ return result.value;
374
+ }
375
+ private async routeNotice(
376
+ ctx: ExtensionContext,
377
+ request: Extract<BoardEnvelope, { operation: "board-notify" }>,
378
+ signal?: AbortSignal,
379
+ ) {
380
+ const child = children(ctx).find(
381
+ (entry) =>
382
+ request.target === entry.binding.agentName ||
383
+ request.target.startsWith(`${entry.binding.agentName}/`),
384
+ );
385
+ if (!child) return false;
386
+ return this.fleet
387
+ .connected(child.machine)
388
+ .client.requestContext(
389
+ sessionContextPath(child.sessionFile),
390
+ request,
391
+ signal,
392
+ );
393
+ }
394
+ private async propagateEnabled(ctx: ExtensionContext, enabled: boolean) {
395
+ await Promise.all(
396
+ children(ctx).map(async (child) => {
397
+ try {
398
+ await this.fleet.connected(child.machine).client.requestContext(
399
+ sessionContextPath(child.sessionFile),
400
+ {
401
+ operation: "board-enabled",
402
+ boardId: binding(ctx).boardId,
403
+ enabled,
404
+ },
405
+ AbortSignal.timeout(750),
406
+ );
407
+ } catch {
408
+ /* Resumed children reconcile with their owner before the next user turn. */
409
+ }
410
+ }),
411
+ );
412
+ }
413
+ }
@@ -0,0 +1,155 @@
1
+ import { resolve } from "node:path";
2
+ import { Type } from "@earendil-works/pi-ai";
3
+ import type {
4
+ ExtensionAPI,
5
+ ExtensionContext,
6
+ } from "@earendil-works/pi-coding-agent";
7
+ import type { Static } from "typebox";
8
+ import { Check } from "typebox/value";
9
+ import { readBoardConfig } from "./config.js";
10
+
11
+ const uuid = Type.String({ pattern: "^[a-f0-9-]{36}$" });
12
+ export const BindingSchema = Type.Object(
13
+ {
14
+ protocol: Type.Literal(1),
15
+ boardId: uuid,
16
+ rootSessionId: uuid,
17
+ sessionId: uuid,
18
+ agentName: Type.String({ pattern: "^/root(?:/[a-zA-Z0-9_-]+)*$" }),
19
+ ownerFolder: Type.String({ minLength: 1 }),
20
+ databasePath: Type.String({ minLength: 1 }),
21
+ enabled: Type.Boolean(),
22
+ upstream: Type.Optional(Type.String({ minLength: 1 })),
23
+ },
24
+ { additionalProperties: false },
25
+ );
26
+ export type BoardBinding = Static<typeof BindingSchema>;
27
+ const ChildSchema = Type.Object({
28
+ parentSessionId: uuid,
29
+ binding: BindingSchema,
30
+ machine: Type.String(),
31
+ sessionFile: Type.String({ minLength: 1 }),
32
+ });
33
+ export type BoardChild = Static<typeof ChildSchema>;
34
+ const BINDING = "shepherdr-board-binding";
35
+ const MEMBER = "shepherdr-board-member";
36
+ const CHILD = "shepherdr-board-child";
37
+ const SETTING = "shepherdr-board-setting";
38
+ const SettingSchema = Type.Object({
39
+ sessionId: uuid,
40
+ enabled: Type.Union([Type.Boolean(), Type.Null()]),
41
+ });
42
+
43
+ export function sessionBoardSetting(
44
+ ctx: ExtensionContext,
45
+ ): boolean | undefined {
46
+ let enabled: boolean | undefined;
47
+ for (const entry of ctx.sessionManager.getEntries()) {
48
+ if (entry.type !== "custom" || entry.customType !== SETTING) continue;
49
+ if (!Check(SettingSchema, entry.data))
50
+ throw new Error("Invalid saved board setting");
51
+ const value = entry.data as Static<typeof SettingSchema>;
52
+ if (value.sessionId === ctx.sessionManager.getSessionId())
53
+ enabled = value.enabled ?? undefined;
54
+ }
55
+ return enabled;
56
+ }
57
+
58
+ export function saveBoardSetting(
59
+ pi: ExtensionAPI,
60
+ ctx: ExtensionContext,
61
+ enabled: boolean | undefined,
62
+ ) {
63
+ pi.appendEntry(SETTING, {
64
+ sessionId: ctx.sessionManager.getSessionId(),
65
+ enabled: enabled ?? null,
66
+ });
67
+ }
68
+
69
+ export function rootBoardSetting(ctx: ExtensionContext) {
70
+ try {
71
+ const config = readBoardConfig(resolve(ctx.sessionManager.getCwd()));
72
+ const session = sessionBoardSetting(ctx);
73
+ return {
74
+ enabled: session ?? config.folder ?? config.global,
75
+ source:
76
+ session !== undefined
77
+ ? "session"
78
+ : config.folder !== undefined
79
+ ? "folder"
80
+ : "global default",
81
+ };
82
+ } catch (error) {
83
+ return {
84
+ enabled: false,
85
+ source: "invalid configuration",
86
+ error: String(error),
87
+ };
88
+ }
89
+ }
90
+
91
+ export function parseBinding(value: unknown): BoardBinding {
92
+ if (!Check(BindingSchema, value))
93
+ throw new Error("Invalid Shepherdr board binding");
94
+ return value as BoardBinding;
95
+ }
96
+ export function binding(ctx: ExtensionContext): BoardBinding {
97
+ const sessionId = ctx.sessionManager.getSessionId();
98
+ let saved: BoardBinding | undefined;
99
+ for (const entry of ctx.sessionManager.getEntries()) {
100
+ if (entry.type !== "custom" || entry.customType !== BINDING) continue;
101
+ const candidate = parseBinding(entry.data);
102
+ if (candidate.sessionId === sessionId) saved = candidate;
103
+ }
104
+ const ownerFolder = resolve(ctx.sessionManager.getCwd());
105
+ if (saved?.upstream) return saved;
106
+ return {
107
+ ...(saved ?? {
108
+ protocol: 1,
109
+ sessionId,
110
+ rootSessionId: sessionId,
111
+ boardId: sessionId,
112
+ agentName: "/root",
113
+ ownerFolder,
114
+ databasePath: resolve(ownerFolder, ".pi", "agent-message-board.sqlite"),
115
+ enabled: false,
116
+ }),
117
+ enabled: rootBoardSetting(ctx).enabled,
118
+ };
119
+ }
120
+ export function saveBinding(pi: ExtensionAPI, value: BoardBinding) {
121
+ pi.appendEntry(BINDING, value);
122
+ }
123
+ export function members(ctx: ExtensionContext): BoardBinding[] {
124
+ const own = binding(ctx);
125
+ const found = new Map([[own.agentName, own]]);
126
+ for (const entry of ctx.sessionManager.getEntries()) {
127
+ if (entry.type !== "custom" || entry.customType !== MEMBER) continue;
128
+ const value = parseBinding(entry.data);
129
+ if (value.rootSessionId === own.sessionId && value.boardId === own.boardId)
130
+ found.set(value.agentName, value);
131
+ }
132
+ return [...found.values()];
133
+ }
134
+ export function saveMember(pi: ExtensionAPI, value: BoardBinding) {
135
+ pi.appendEntry(MEMBER, value);
136
+ }
137
+ export function children(ctx: ExtensionContext): BoardChild[] {
138
+ const own = binding(ctx);
139
+ const found = new Map<string, BoardChild>();
140
+ for (const entry of ctx.sessionManager.getEntries()) {
141
+ if (entry.type !== "custom" || entry.customType !== CHILD) continue;
142
+ if (!Check(ChildSchema, entry.data))
143
+ throw new Error("Invalid saved board child route");
144
+ const value = entry.data as BoardChild;
145
+ if (
146
+ value.parentSessionId === own.sessionId &&
147
+ value.binding.boardId === own.boardId
148
+ )
149
+ found.set(value.binding.agentName, value);
150
+ }
151
+ return [...found.values()];
152
+ }
153
+ export function saveChild(pi: ExtensionAPI, value: BoardChild) {
154
+ pi.appendEntry(CHILD, value);
155
+ }
@@ -0,0 +1,55 @@
1
+ import type { BoardParams } from "./contract.js";
2
+
3
+ export interface PostRecord {
4
+ message_id: string;
5
+ channel_name: string;
6
+ author: string;
7
+ thread_id: string;
8
+ created_at: string;
9
+ text: string;
10
+ }
11
+ export const POST_COLUMNS =
12
+ "id AS message_id,channel AS channel_name,author,root AS thread_id,created_at,text";
13
+ export function metadata({ text: _text, ...value }: PostRecord) {
14
+ return value;
15
+ }
16
+ export function preview(post: PostRecord, chars: number) {
17
+ const text = Array.from(post.text);
18
+ return {
19
+ ...metadata(post),
20
+ text_preview: text.slice(0, chars).join(""),
21
+ n_chars: text.length,
22
+ truncated: text.length > chars,
23
+ };
24
+ }
25
+ export function window(params: BoardParams) {
26
+ const limit = Math.min(params.limit ?? 20, 50);
27
+ let offset = 0;
28
+ if (params.cursor !== undefined) {
29
+ const bytes = Buffer.from(params.cursor, "base64url");
30
+ if (bytes.length !== 4 || bytes.toString("base64url") !== params.cursor)
31
+ throw new Error("Invalid cursor");
32
+ offset = bytes.readUInt32BE();
33
+ }
34
+ return { limit, offset };
35
+ }
36
+ export function page<T>(values: T[], params: BoardParams) {
37
+ const { limit, offset } = window(params);
38
+ const has_more = values.length > limit;
39
+ const results = values.slice(0, limit);
40
+ 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
+ }
48
+ return { results, n_returned: results.length, has_more, next_cursor };
49
+ }
50
+ export function budget(params: BoardParams, count: number) {
51
+ return Math.min(
52
+ params.max_chars_per_post ?? 1000,
53
+ Math.floor(20000 / Math.max(1, count)),
54
+ );
55
+ }
@@ -0,0 +1,68 @@
1
+ import { Type } from "@earendil-works/pi-ai";
2
+ import type { Static } from "typebox";
3
+ import { Check } from "typebox/value";
4
+ import { BindingSchema } from "./identity.js";
5
+
6
+ const NoticeSchema = Type.Object(
7
+ {
8
+ message_id: Type.String(),
9
+ channel_name: Type.String(),
10
+ author: Type.String(),
11
+ thread_id: Type.String(),
12
+ created_at: Type.String(),
13
+ text_preview: Type.String({ maxLength: 300 }),
14
+ n_chars: Type.Integer({ minimum: 0 }),
15
+ truncated: Type.Boolean(),
16
+ },
17
+ { additionalProperties: false },
18
+ );
19
+ const Protocol = Type.Union([
20
+ Type.Object({
21
+ operation: Type.Literal("board-bind"),
22
+ binding: BindingSchema,
23
+ }),
24
+ Type.Object({
25
+ operation: Type.Literal("board-register"),
26
+ caller: BindingSchema,
27
+ member: BindingSchema,
28
+ }),
29
+ Type.Object({
30
+ operation: Type.Literal("board-enabled"),
31
+ boardId: Type.String(),
32
+ enabled: Type.Boolean(),
33
+ }),
34
+ Type.Object({
35
+ operation: Type.Literal("board-active"),
36
+ caller: BindingSchema,
37
+ turnId: Type.Union([Type.String(), Type.Null()]),
38
+ previousTurnId: Type.Optional(Type.String()),
39
+ }),
40
+ Type.Object({
41
+ operation: Type.Literal("board-call"),
42
+ caller: BindingSchema,
43
+ params: Type.Unknown(),
44
+ requestId: Type.String(),
45
+ }),
46
+ Type.Object({
47
+ operation: Type.Literal("board-notify"),
48
+ boardId: Type.String(),
49
+ target: Type.String(),
50
+ sessionId: Type.String(),
51
+ turnId: Type.String(),
52
+ notice: NoticeSchema,
53
+ }),
54
+ ]);
55
+ export type BoardEnvelope = Static<typeof Protocol>;
56
+ export function parseEnvelope(value: unknown): BoardEnvelope {
57
+ if (!Check(Protocol, value)) throw new Error("Invalid board host request");
58
+ return value as BoardEnvelope;
59
+ }
60
+ export function isBoardEnvelope(value: unknown): boolean {
61
+ return (
62
+ !!value &&
63
+ typeof value === "object" &&
64
+ "operation" in value &&
65
+ typeof value.operation === "string" &&
66
+ value.operation.startsWith("board-")
67
+ );
68
+ }