@howaboua/pi-shepherdr 0.2.15 → 0.2.16

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 (51) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +40 -33
  3. package/index.ts +16 -26
  4. package/package.json +11 -11
  5. package/src/agents-contract.ts +11 -1
  6. package/src/agents-discovery.ts +21 -7
  7. package/src/agents-focus.ts +242 -0
  8. package/src/agents-spawn.ts +23 -0
  9. package/src/agents-tool.ts +34 -5
  10. package/src/attachment-protocol.ts +7 -3
  11. package/src/attachment-target.ts +3 -1
  12. package/src/attachment.ts +3 -1
  13. package/src/board/host.ts +98 -366
  14. package/src/board/membership.ts +14 -8
  15. package/src/command-config.ts +51 -0
  16. package/src/control-panel-actions.ts +0 -20
  17. package/src/control-panel-items.ts +8 -36
  18. package/src/control-panel-view.ts +2 -11
  19. package/src/control-panel.ts +2 -11
  20. package/src/controller.ts +5 -5
  21. package/src/delivery.ts +0 -33
  22. package/src/herdr-client.ts +39 -6
  23. package/src/messages.ts +61 -61
  24. package/src/monitor-events.ts +24 -2
  25. package/src/monitor-questions.ts +12 -3
  26. package/src/monitor.ts +2 -2
  27. package/src/peer-channel.ts +39 -0
  28. package/src/peer-commands.ts +173 -0
  29. package/src/peer-inbox.ts +218 -55
  30. package/src/remote/shepherdr-channel.mjs +225 -0
  31. package/src/remote/shepherdr-checkpoints.mjs +5 -3
  32. package/src/remote/shepherdr-peer.mjs +151 -22
  33. package/src/remote/shepherdr.mjs +56 -8
  34. package/src/remote-client.ts +115 -11
  35. package/src/settlement.ts +1 -0
  36. package/src/shared-context.ts +104 -1
  37. package/src/types.ts +23 -0
  38. package/src/voice-handoff.ts +177 -0
  39. package/src/board/archive.ts +0 -77
  40. package/src/board/awareness.ts +0 -115
  41. package/src/board/config.ts +0 -121
  42. package/src/board/contract.ts +0 -181
  43. package/src/board/identity.ts +0 -169
  44. package/src/board/paging.ts +0 -55
  45. package/src/board/protocol.ts +0 -73
  46. package/src/board/queries.ts +0 -176
  47. package/src/board/response.ts +0 -56
  48. package/src/board/store.ts +0 -327
  49. package/src/board/tool.ts +0 -23
  50. package/src/board/turns.ts +0 -100
  51. package/src/context-briefing.ts +0 -226
@@ -1,73 +0,0 @@
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-unregister"),
31
- caller: BindingSchema,
32
- member: BindingSchema,
33
- }),
34
- Type.Object({
35
- operation: Type.Literal("board-enabled"),
36
- boardId: Type.String(),
37
- enabled: Type.Boolean(),
38
- }),
39
- Type.Object({
40
- operation: Type.Literal("board-active"),
41
- caller: BindingSchema,
42
- turnId: Type.Union([Type.String(), Type.Null()]),
43
- previousTurnId: Type.Optional(Type.String()),
44
- }),
45
- Type.Object({
46
- operation: Type.Literal("board-call"),
47
- caller: BindingSchema,
48
- params: Type.Unknown(),
49
- requestId: Type.String(),
50
- }),
51
- Type.Object({
52
- operation: Type.Literal("board-notify"),
53
- boardId: Type.String(),
54
- target: Type.String(),
55
- sessionId: Type.String(),
56
- turnId: Type.String(),
57
- notice: NoticeSchema,
58
- }),
59
- ]);
60
- export type BoardEnvelope = Static<typeof Protocol>;
61
- export function parseEnvelope(value: unknown): BoardEnvelope {
62
- if (!Check(Protocol, value)) throw new Error("Invalid board host request");
63
- return value as BoardEnvelope;
64
- }
65
- export function isBoardEnvelope(value: unknown): boolean {
66
- return (
67
- !!value &&
68
- typeof value === "object" &&
69
- "operation" in value &&
70
- typeof value.operation === "string" &&
71
- value.operation.startsWith("board-")
72
- );
73
- }
@@ -1,176 +0,0 @@
1
- import { caseFold } from "unicode-case-folding";
2
- import { agentPath, type BoardParams, required } from "./contract.js";
3
- import {
4
- budget,
5
- metadata,
6
- POST_COLUMNS,
7
- type PostRecord,
8
- page,
9
- preview,
10
- window,
11
- } from "./paging.js";
12
- import type { BoardStore } from "./store.js";
13
-
14
- export function queryBoard(
15
- store: BoardStore,
16
- ownBoard: string,
17
- params: BoardParams,
18
- ): Record<string, unknown> {
19
- const board = params.board_id ?? ownBoard;
20
- const { limit, offset } = window(params);
21
- const order = params.recent_first === false ? "ASC" : "DESC";
22
- if (params.action === "list_boards") {
23
- const rows = store.all<{
24
- board_id: string;
25
- root_session_id: string;
26
- owner_folder: string;
27
- created_at: string;
28
- last_activity_at: string;
29
- channel_count: number;
30
- message_count: number;
31
- }>(
32
- `SELECT b.*,
33
- 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,
34
- (SELECT COUNT(*) FROM channels c WHERE c.board_id=b.board_id) AS channel_count,
35
- (SELECT COUNT(*) FROM posts p WHERE p.board_id=b.board_id) AS message_count
36
- FROM boards b ORDER BY last_activity_at DESC,board_id DESC LIMIT ? OFFSET ?`,
37
- limit + 1,
38
- offset,
39
- );
40
- return page(
41
- rows.map((row) => ({ ...row, current: row.board_id === ownBoard })),
42
- params,
43
- );
44
- }
45
- if (params.action === "get_channels") {
46
- const rows = store.all<{ name: string }>(
47
- `SELECT name FROM channels c WHERE board_id=? AND instr(name_search,?)>0 ORDER BY
48
- 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 ?`,
49
- board,
50
- caseFold(params.query ?? ""),
51
- limit + 1,
52
- offset,
53
- );
54
- return page(
55
- rows.map(({ name }) => store.channel(board, name)),
56
- params,
57
- );
58
- }
59
- if (params.action === "read_post") {
60
- const post = store.post(board, required(params.message_id, "message_id"));
61
- const chars = Array.from(post.text);
62
- const offset = Math.min(params.offset_chars ?? 0, chars.length);
63
- const text = chars
64
- .slice(offset, offset + Math.min(params.limit_chars ?? 20000, 20000))
65
- .join("");
66
- return {
67
- ...metadata(post),
68
- text,
69
- n_chars: chars.length,
70
- next_offset_chars: offset + Array.from(text).length,
71
- };
72
- }
73
- if (params.action === "read_thread") {
74
- const root = store.root(board, required(params.thread_id, "thread_id"));
75
- const replies = store.all<PostRecord>(
76
- `SELECT ${POST_COLUMNS} FROM posts WHERE board_id=? AND root=? AND id<>root ORDER BY created_at DESC,seq DESC LIMIT ? OFFSET ?`,
77
- board,
78
- root.message_id,
79
- limit + 1,
80
- offset,
81
- );
82
- const chars = budget(params, Math.min(replies.length, limit) + 1);
83
- return {
84
- root_post: preview(root, chars),
85
- ...page(
86
- replies.map((post) => preview(post, chars)),
87
- params,
88
- ),
89
- };
90
- }
91
- if (params.action === "list_threads") {
92
- const channel = store.channel(
93
- board,
94
- required(params.channel_name, "channel_name"),
95
- );
96
- const sort =
97
- params.sort === "activity"
98
- ? "(SELECT MAX(created_at) FROM posts r WHERE r.board_id=p.board_id AND r.root=p.id)"
99
- : "p.created_at";
100
- const roots = store.all<PostRecord>(
101
- `SELECT ${POST_COLUMNS} FROM posts p WHERE board_id=? AND channel=? AND id=root ORDER BY ${sort} ${order},seq ${order} LIMIT ? OFFSET ?`,
102
- board,
103
- channel.channel_name,
104
- limit + 1,
105
- offset,
106
- );
107
- const chars = budget(params, 2 * Math.min(roots.length, limit));
108
- return page(
109
- roots.map((root) => {
110
- const reply = store.one<PostRecord>(
111
- `SELECT ${POST_COLUMNS} FROM posts WHERE board_id=? AND root=? AND id<>root ORDER BY created_at DESC,seq DESC LIMIT 1`,
112
- board,
113
- root.message_id,
114
- );
115
- const count =
116
- store.one<{ n: number }>(
117
- "SELECT COUNT(*) AS n FROM posts WHERE board_id=? AND root=? AND id<>root",
118
- board,
119
- root.message_id,
120
- )?.n ?? 0;
121
- return {
122
- thread_id: root.message_id,
123
- root_post: preview(root, chars),
124
- reply_count: count,
125
- last_activity_at:
126
- reply && reply.created_at > root.created_at
127
- ? reply.created_at
128
- : root.created_at,
129
- latest_reply: reply ? preview(reply, chars) : null,
130
- };
131
- }),
132
- params,
133
- );
134
- }
135
- if (params.action === "search_posts") return search(store, board, params);
136
- throw new Error(`Unsupported board read: ${params.action}`);
137
- }
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
- }
@@ -1,56 +0,0 @@
1
- import type { BoardParams } from "./contract.js";
2
-
3
- // Includes UTF-8 text, JSON escaping and metadata, in every tool mode.
4
- const MAX_RESPONSE_BYTES = 8000;
5
-
6
- export function serializeBoardResult(value: unknown): string {
7
- const text = JSON.stringify(value);
8
- if (Buffer.byteLength(text) > MAX_RESPONSE_BYTES)
9
- throw new Error(
10
- "Result exceeds the output budget. Reduce limit or max_chars_per_post; use read_post with a smaller limit_chars for long posts.",
11
- );
12
- return text;
13
- }
14
-
15
- export function checkMutationBudget(caller: string, params: BoardParams) {
16
- // Native acknowledgement reserve, checked before opening or creating storage.
17
- const target = params.target_agent ?? "";
18
- if (
19
- 2048 + Buffer.byteLength(caller) + Buffer.byteLength(target) >
20
- MAX_RESPONSE_BYTES
21
- )
22
- throw new Error(
23
- "Output budget is too small to acknowledge a message-board mutation; no change was made.",
24
- );
25
- }
26
-
27
- export function boundedBoardRead<T extends { value: unknown }>(
28
- params: BoardParams,
29
- fetch: (request: BoardParams) => T,
30
- ): T {
31
- const limit = Math.min(params.limit ?? 20, 50);
32
- const chars = Math.min(params.max_chars_per_post ?? 1000, 20000);
33
- const postChars = Math.min(params.limit_chars ?? 20000, 20000);
34
- const previews = ["list_threads", "search_posts", "read_thread"].includes(
35
- params.action,
36
- );
37
- const post = params.action === "read_post";
38
- const largest = post ? postChars : previews ? Math.max(limit, chars) : limit;
39
- for (let scale = 1; ; scale *= 2) {
40
- const reduced = (value: number) => Math.max(1, Math.floor(value / scale));
41
- // Reissue the original cursor/offset so continuation matches the reduced page.
42
- const result = fetch({
43
- ...params,
44
- ...(post
45
- ? { limit_chars: reduced(postChars) }
46
- : { limit: reduced(limit) }),
47
- ...(previews ? { max_chars_per_post: reduced(chars) } : {}),
48
- });
49
- if (Buffer.byteLength(JSON.stringify(result.value)) <= MAX_RESPONSE_BYTES)
50
- return result;
51
- if (Math.floor(largest / scale) <= 1)
52
- throw new Error(
53
- "The output budget is too small for this result's metadata.",
54
- );
55
- }
56
- }
@@ -1,327 +0,0 @@
1
- import { randomUUID } from "node:crypto";
2
- import { chmodSync, existsSync, mkdirSync } from "node:fs";
3
- import { dirname } from "node:path";
4
- import { DatabaseSync, type SQLInputValue } from "node:sqlite";
5
- import { caseFold } from "unicode-case-folding";
6
- import {
7
- agentPath,
8
- type BoardParams,
9
- MUTATIONS,
10
- required,
11
- } from "./contract.js";
12
- import { metadata, POST_COLUMNS, type PostRecord, preview } from "./paging.js";
13
- import { queryBoard } from "./queries.js";
14
- import { serializeBoardResult } from "./response.js";
15
-
16
- export interface BoardScope {
17
- boardId: string;
18
- rootSessionId: string;
19
- ownerFolder: string;
20
- agentName: string;
21
- callerSessionId: string;
22
- members: readonly string[];
23
- }
24
- const SCHEMA = `
25
- CREATE TABLE boards (board_id TEXT PRIMARY KEY, root_session_id TEXT NOT NULL, owner_folder TEXT NOT NULL, created_at TEXT NOT NULL);
26
- CREATE TABLE channels (board_id TEXT NOT NULL, name TEXT NOT NULL, name_search TEXT NOT NULL, created_at TEXT NOT NULL, author TEXT NOT NULL, PRIMARY KEY(board_id,name));
27
- CREATE TABLE posts (seq INTEGER PRIMARY KEY AUTOINCREMENT,board_id TEXT NOT NULL,id TEXT NOT NULL,channel TEXT NOT NULL,root TEXT NOT NULL,author TEXT NOT NULL,created_at TEXT NOT NULL,text TEXT NOT NULL,body_search TEXT NOT NULL,request_id TEXT NOT NULL,request TEXT NOT NULL,UNIQUE(board_id,id),UNIQUE(board_id,request_id));
28
- CREATE INDEX posts_channel ON posts(board_id,channel,created_at,seq);
29
- CREATE INDEX posts_root ON posts(board_id,root,created_at,seq);
30
- CREATE INDEX posts_order ON posts(board_id,created_at,seq);
31
- CREATE TABLE subscriptions (board_id TEXT NOT NULL,target TEXT NOT NULL,agent TEXT NOT NULL,enabled INTEGER NOT NULL,PRIMARY KEY(board_id,target,agent));
32
- PRAGMA user_version=1;`;
33
-
34
- /** One transaction/connection per call. Reads never create a file, schema or board. */
35
- export class BoardStore {
36
- readonly db: DatabaseSync;
37
- constructor(path: string, write: boolean) {
38
- const fresh = !existsSync(path);
39
- if (write && fresh) mkdirSync(dirname(path), { recursive: true });
40
- this.db = new DatabaseSync(path, { readOnly: !write });
41
- try {
42
- this.db.exec("PRAGMA busy_timeout=5000");
43
- if (write) {
44
- if (fresh) chmodSync(path, 0o600);
45
- this.db.exec("PRAGMA journal_mode=WAL; BEGIN IMMEDIATE");
46
- }
47
- const version = this.one<{ user_version: number }>(
48
- "PRAGMA user_version",
49
- )?.user_version;
50
- if (
51
- version === 0 &&
52
- write &&
53
- this.all("SELECT name FROM sqlite_master WHERE type='table'").length ===
54
- 0
55
- )
56
- this.db.exec(SCHEMA);
57
- else if (version !== 1)
58
- throw new Error("Unsupported Shepherdr board archive schema");
59
- if (write) this.db.exec("COMMIT");
60
- } catch (error) {
61
- this.db.close();
62
- throw error;
63
- }
64
- }
65
- one<T>(sql: string, ...args: SQLInputValue[]): T | undefined {
66
- return this.db.prepare(sql).get(...args) as T | undefined;
67
- }
68
- all<T>(sql: string, ...args: SQLInputValue[]): T[] {
69
- return this.db.prepare(sql).all(...args) as T[];
70
- }
71
- run(sql: string, ...args: SQLInputValue[]) {
72
- return this.db.prepare(sql).run(...args);
73
- }
74
- post(board: string, id: string): PostRecord {
75
- const post = this.one<PostRecord>(
76
- `SELECT ${POST_COLUMNS} FROM posts WHERE board_id=? AND id=?`,
77
- board,
78
- id,
79
- );
80
- if (!post) throw new Error("Post not found in this board");
81
- return post;
82
- }
83
- root(board: string, id: string): PostRecord {
84
- const post = this.post(board, id);
85
- if (post.thread_id !== id)
86
- throw new Error("thread_id must identify a first post");
87
- return post;
88
- }
89
- channel(board: string, name: string) {
90
- const channel = this.one<{
91
- channel_name: string;
92
- created_at: string;
93
- created_by: string;
94
- message_count: number;
95
- last_message_id: string | null;
96
- }>(
97
- `SELECT name AS channel_name,created_at,author AS created_by,
98
- (SELECT COUNT(*) FROM posts p WHERE p.board_id=c.board_id AND p.channel=c.name) AS message_count,
99
- (SELECT id FROM posts p WHERE p.board_id=c.board_id AND p.channel=c.name ORDER BY created_at DESC,seq DESC LIMIT 1) AS last_message_id
100
- FROM channels c WHERE board_id=? AND name=?`,
101
- board,
102
- name,
103
- );
104
- if (!channel) throw new Error("Channel not found in this board");
105
- return channel;
106
- }
107
- execute(scope: BoardScope, params: BoardParams, requestId: string) {
108
- const write = MUTATIONS.has(params.action);
109
- this.db.exec(write ? "BEGIN IMMEDIATE" : "BEGIN");
110
- try {
111
- const result = write
112
- ? this.mutate(scope, params, requestId)
113
- : { value: queryBoard(this, scope.boardId, params), recipients: [] };
114
- if (write) serializeBoardResult(result.value);
115
- this.db.exec("COMMIT");
116
- return result;
117
- } catch (error) {
118
- this.db.exec("ROLLBACK");
119
- throw error;
120
- }
121
- }
122
- close() {
123
- this.db.close();
124
- }
125
- private ensureBoard(scope: BoardScope, now: string) {
126
- this.run(
127
- "INSERT OR IGNORE INTO boards VALUES(?,?,?,?)",
128
- scope.boardId,
129
- scope.rootSessionId,
130
- scope.ownerFolder,
131
- now,
132
- );
133
- }
134
- private insertChannel(scope: BoardScope, name: string, now: string) {
135
- if (
136
- this.one(
137
- "SELECT 1 FROM channels WHERE board_id=? AND name=?",
138
- scope.boardId,
139
- name,
140
- )
141
- )
142
- throw new Error("Channel already exists");
143
- this.run(
144
- "INSERT INTO channels VALUES(?,?,?,?,?)",
145
- scope.boardId,
146
- name,
147
- caseFold(name),
148
- now,
149
- scope.agentName,
150
- );
151
- }
152
- private subscription(
153
- board: string,
154
- target: string,
155
- agent: string,
156
- enabled: boolean,
157
- implicit = false,
158
- ) {
159
- this.run(
160
- implicit
161
- ? "INSERT OR IGNORE INTO subscriptions VALUES(?,?,?,1)"
162
- : "INSERT INTO subscriptions VALUES(?,?,?,?) ON CONFLICT(board_id,target,agent) DO UPDATE SET enabled=excluded.enabled",
163
- ...[board, target, agent, ...(implicit ? [] : [enabled ? 1 : 0])],
164
- );
165
- }
166
- private resolve(scope: BoardScope, value: string) {
167
- const path = agentPath(value, scope.agentName);
168
- if (!scope.members.includes(path))
169
- throw new Error(`Agent not bound to this tree: ${path}`);
170
- return path;
171
- }
172
- private mutate(scope: BoardScope, params: BoardParams, requestId: string) {
173
- const board = scope.boardId;
174
- if (params.action === "post") return this.publish(scope, params, requestId);
175
- if (params.action === "create_channel") {
176
- const name = required(params.channel_name, "channel_name");
177
- const now = new Date().toISOString();
178
- this.ensureBoard(scope, now);
179
- this.insertChannel(scope, name, now);
180
- if (params.subscribe !== false)
181
- this.subscription(board, `channel:${name}`, scope.agentName, true);
182
- return { value: this.channel(board, name), recipients: [] };
183
- }
184
- const target_agent =
185
- params.target_agent === undefined
186
- ? scope.agentName
187
- : this.resolve(scope, params.target_agent);
188
- const root =
189
- params.thread_id === undefined
190
- ? undefined
191
- : this.root(board, params.thread_id);
192
- const channel = this.channel(
193
- board,
194
- root?.channel_name ?? required(params.channel_name, "channel_name"),
195
- );
196
- const thread_id = root?.thread_id ?? null;
197
- const target = root
198
- ? `thread:${root.thread_id}`
199
- : `channel:${channel.channel_name}`;
200
- const last = root
201
- ? (this.one<{ id: string }>(
202
- "SELECT id FROM posts WHERE board_id=? AND root=? ORDER BY created_at DESC,seq DESC LIMIT 1",
203
- board,
204
- root.thread_id,
205
- )?.id ?? null)
206
- : channel.last_message_id;
207
- const enabled = params.action === "subscribe";
208
- this.subscription(board, target, target_agent, enabled);
209
- return {
210
- value: {
211
- channel_name: channel.channel_name,
212
- thread_id,
213
- target_agent,
214
- enabled,
215
- last_message_id: last,
216
- },
217
- recipients: [],
218
- };
219
- }
220
- private publish(scope: BoardScope, params: BoardParams, requestId: string) {
221
- const board = scope.boardId;
222
- const request = JSON.stringify(
223
- Object.fromEntries(
224
- Object.entries({
225
- ...params,
226
- agents_to_notify: params.agents_to_notify ?? [],
227
- }).sort(([a], [b]) => a.localeCompare(b)),
228
- ),
229
- );
230
- const key = `${scope.callerSessionId}:${requestId}`;
231
- if (!requestId || Buffer.byteLength(key) > 1024)
232
- throw new Error("Invalid post invocation ID");
233
- const previous = this.one<{ id: string; request: string }>(
234
- "SELECT id,request FROM posts WHERE board_id=? AND request_id=?",
235
- board,
236
- key,
237
- );
238
- if (previous) {
239
- if (previous.request !== request)
240
- throw new Error("Invocation ID already used for a different post");
241
- return { value: metadata(this.post(board, previous.id)), recipients: [] };
242
- }
243
- const recipients = new Set(
244
- (params.agents_to_notify ?? []).map((name) => this.resolve(scope, name)),
245
- );
246
- const now = new Date().toISOString();
247
- const id = randomUUID();
248
- let channel: string;
249
- let root: string = id;
250
- if (params.thread_id !== undefined) {
251
- const post = this.root(board, params.thread_id);
252
- channel = post.channel_name;
253
- root = post.thread_id;
254
- } else if (params.new_channel_name !== undefined) {
255
- channel = params.new_channel_name;
256
- this.ensureBoard(scope, now);
257
- this.insertChannel(scope, channel, now);
258
- this.subscription(board, `channel:${channel}`, scope.agentName, true);
259
- } else
260
- channel = this.channel(
261
- board,
262
- required(params.channel_name, "channel_name"),
263
- ).channel_name;
264
- const target = root === id ? `channel:${channel}` : `thread:${root}`;
265
- for (const { agent } of this.all<{ agent: string }>(
266
- "SELECT agent FROM subscriptions WHERE board_id=? AND target=? AND enabled=1",
267
- board,
268
- target,
269
- ))
270
- recipients.add(agent);
271
- recipients.delete(scope.agentName);
272
- const post: PostRecord = {
273
- message_id: id,
274
- channel_name: channel,
275
- author: scope.agentName,
276
- thread_id: root,
277
- created_at: now,
278
- text: required(params.text, "text"),
279
- };
280
- this.run(
281
- "INSERT INTO posts(board_id,id,channel,root,author,created_at,text,body_search,request_id,request) VALUES(?,?,?,?,?,?,?,?,?,?)",
282
- board,
283
- id,
284
- channel,
285
- root,
286
- scope.agentName,
287
- now,
288
- post.text,
289
- caseFold(post.text),
290
- key,
291
- request,
292
- );
293
- this.subscription(board, `thread:${root}`, scope.agentName, true, true);
294
- return {
295
- value: metadata(post),
296
- notice: preview(post, 150),
297
- recipients: [...recipients],
298
- };
299
- }
300
- }
301
-
302
- export function validateMutation(params: BoardParams) {
303
- if (
304
- params.action === "create_channel" ||
305
- params.new_channel_name !== undefined
306
- ) {
307
- const name = required(
308
- params.new_channel_name ?? params.channel_name,
309
- "channel_name",
310
- );
311
- if (
312
- !name ||
313
- !name.isWellFormed() ||
314
- Buffer.byteLength(name) > 128 ||
315
- name.trim() !== name ||
316
- /\p{Cc}/u.test(name)
317
- )
318
- throw new Error(
319
- "Channel must be 1-128 UTF-8 bytes without edge whitespace/control characters",
320
- );
321
- }
322
- if (params.action === "post") {
323
- const text = required(params.text, "text");
324
- if (!text || !text.isWellFormed() || Buffer.byteLength(text) > 65536)
325
- throw new Error("Post must be 1-65536 UTF-8 bytes");
326
- }
327
- }
package/src/board/tool.ts DELETED
@@ -1,23 +0,0 @@
1
- import { defineTool } from "@earendil-works/pi-coding-agent";
2
- import { BoardParameters } from "./contract.js";
3
- import type { AgentBoard } from "./host.js";
4
- import { serializeBoardResult } from "./response.js";
5
-
6
- export function createBoardTool(board: AgentBoard) {
7
- return defineTool({
8
- name: "board",
9
- label: "Message board",
10
- description:
11
- "Shared discussions and saved board history; call help for actions",
12
- parameters: BoardParameters,
13
- executionMode: "sequential",
14
- async execute(id, params, signal, _onUpdate, ctx) {
15
- signal?.throwIfAborted();
16
- const value = await board.execute(ctx, params, id);
17
- return {
18
- content: [{ type: "text", text: serializeBoardResult(value) }],
19
- details: {},
20
- };
21
- },
22
- });
23
- }