@howaboua/pi-agent-board 0.0.0-stage → 0.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +30 -0
- package/INTEGRATION.md +31 -0
- package/LICENSE +21 -0
- package/README.md +112 -2
- package/changelog.ts +337 -0
- package/dist/viewer/archive.js +242 -0
- package/dist/viewer/config.js +85 -0
- package/dist/viewer/contracts.js +1 -0
- package/dist/viewer/server.js +172 -0
- package/dist/viewer/source.js +29 -0
- package/dist/viewer/web/app.js +515 -0
- package/dist/viewer/web/index.html +41 -0
- package/dist/viewer/web/style.css +517 -0
- package/index.ts +122 -0
- package/package.json +68 -5
- package/src/activity.ts +274 -0
- package/src/archive.ts +108 -0
- package/src/awareness.ts +184 -0
- package/src/briefing.ts +24 -0
- package/src/config.ts +182 -0
- package/src/context-briefing.ts +227 -0
- package/src/contract.ts +246 -0
- package/src/delivery.ts +85 -0
- package/src/identity.ts +174 -0
- package/src/integration.ts +54 -0
- package/src/paging.ts +54 -0
- package/src/protocol.ts +78 -0
- package/src/queries.ts +171 -0
- package/src/response.ts +56 -0
- package/src/runtime.ts +614 -0
- package/src/search.ts +93 -0
- package/src/store.ts +391 -0
- package/src/summaries.ts +118 -0
- package/src/summarizer.ts +199 -0
- package/src/tool.ts +22 -0
- package/src/turns.ts +101 -0
- package/src/viewer/archive.ts +301 -0
- package/src/viewer/config.ts +111 -0
- package/src/viewer/contracts.ts +98 -0
- package/src/viewer/index.ts +158 -0
- package/src/viewer/server.ts +199 -0
- package/src/viewer/source.ts +33 -0
- package/src/viewer/web/app.js +515 -0
- package/src/viewer/web/index.html +41 -0
- package/src/viewer/web/style.css +517 -0
- package/tsconfig.json +5 -0
package/src/tool.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { defineTool } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { BoardParameters } from "./contract.js";
|
|
3
|
+
import { serializeBoardResult } from "./response.js";
|
|
4
|
+
import type { BoardRuntime } from "./runtime.js";
|
|
5
|
+
|
|
6
|
+
export function createBoardTool(board: BoardRuntime) {
|
|
7
|
+
return defineTool({
|
|
8
|
+
name: "board",
|
|
9
|
+
label: "Message board",
|
|
10
|
+
description: "Shared discussions and saved board history",
|
|
11
|
+
parameters: BoardParameters,
|
|
12
|
+
executionMode: "sequential",
|
|
13
|
+
async execute(id, params, signal, _onUpdate, ctx) {
|
|
14
|
+
signal?.throwIfAborted();
|
|
15
|
+
const value = await board.execute(ctx, params, id);
|
|
16
|
+
return {
|
|
17
|
+
content: [{ type: "text", text: serializeBoardResult(value) }],
|
|
18
|
+
details: {},
|
|
19
|
+
};
|
|
20
|
+
},
|
|
21
|
+
});
|
|
22
|
+
}
|
package/src/turns.ts
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import type {
|
|
3
|
+
ExtensionAPI,
|
|
4
|
+
ExtensionContext,
|
|
5
|
+
} from "@earendil-works/pi-coding-agent";
|
|
6
|
+
import { sendPolicyMessage } from "./delivery.js";
|
|
7
|
+
import { type BoardBinding, binding } from "./identity.js";
|
|
8
|
+
import type { BoardEnvelope } from "./protocol.js";
|
|
9
|
+
|
|
10
|
+
type ActiveEnvelope = Extract<BoardEnvelope, { operation: "board-active" }>;
|
|
11
|
+
type NoticeEnvelope = Extract<BoardEnvelope, { operation: "board-notify" }>;
|
|
12
|
+
|
|
13
|
+
/** Turn IDs are transient capabilities. A stale snapshot cannot reach a later turn. */
|
|
14
|
+
export class BoardTurns {
|
|
15
|
+
private current: { ctx: ExtensionContext; turnId: string } | undefined;
|
|
16
|
+
readonly active = new Map<string, { sessionId: string; turnId: string }>();
|
|
17
|
+
constructor(
|
|
18
|
+
pi: ExtensionAPI,
|
|
19
|
+
register: (
|
|
20
|
+
ctx: ExtensionContext,
|
|
21
|
+
request: ActiveEnvelope,
|
|
22
|
+
) => Promise<unknown>,
|
|
23
|
+
availability: (ctx: ExtensionContext, error?: unknown) => void,
|
|
24
|
+
seen: (ctx: ExtensionContext, ids: string[]) => void,
|
|
25
|
+
) {
|
|
26
|
+
pi.on("session_start", () => {
|
|
27
|
+
this.current = undefined;
|
|
28
|
+
this.active.clear();
|
|
29
|
+
});
|
|
30
|
+
pi.on("agent_start", async (_event, ctx) => {
|
|
31
|
+
const own = binding(ctx);
|
|
32
|
+
if (!own.enabled) return;
|
|
33
|
+
const turnId = randomUUID();
|
|
34
|
+
this.current = { ctx, turnId };
|
|
35
|
+
try {
|
|
36
|
+
await register(ctx, { operation: "board-active", caller: own, turnId });
|
|
37
|
+
availability(ctx);
|
|
38
|
+
} catch (error) {
|
|
39
|
+
availability(ctx, error);
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
const stop = async () => {
|
|
43
|
+
const current = this.current;
|
|
44
|
+
this.current = undefined;
|
|
45
|
+
if (!current) return;
|
|
46
|
+
try {
|
|
47
|
+
await register(current.ctx, {
|
|
48
|
+
operation: "board-active",
|
|
49
|
+
caller: binding(current.ctx),
|
|
50
|
+
turnId: null,
|
|
51
|
+
previousTurnId: current.turnId,
|
|
52
|
+
});
|
|
53
|
+
} catch {
|
|
54
|
+
/* No retry or delayed removal may affect a later turn. */
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
pi.on("agent_end", stop);
|
|
58
|
+
pi.on("agent_settled", stop);
|
|
59
|
+
pi.on("session_shutdown", async () => {
|
|
60
|
+
await stop();
|
|
61
|
+
this.active.clear();
|
|
62
|
+
});
|
|
63
|
+
this.deliver = (request) => {
|
|
64
|
+
const current = this.current;
|
|
65
|
+
if (!current || current.turnId !== request.turnId || current.ctx.isIdle())
|
|
66
|
+
return false;
|
|
67
|
+
const own = binding(current.ctx);
|
|
68
|
+
if (
|
|
69
|
+
!own.enabled ||
|
|
70
|
+
own.boardId !== request.boardId ||
|
|
71
|
+
own.sessionId !== request.sessionId ||
|
|
72
|
+
own.agentName !== request.target
|
|
73
|
+
)
|
|
74
|
+
return false;
|
|
75
|
+
// No await between running-turn check and steering. Never use the idle kickoff.
|
|
76
|
+
sendPolicyMessage(
|
|
77
|
+
pi,
|
|
78
|
+
{
|
|
79
|
+
customType: "shepherdr-board-post",
|
|
80
|
+
content: `Board post ${JSON.stringify(request.notice)}`,
|
|
81
|
+
display: true,
|
|
82
|
+
},
|
|
83
|
+
{ deliverAs: "steer" },
|
|
84
|
+
);
|
|
85
|
+
seen(current.ctx, [request.notice.message_id]);
|
|
86
|
+
return true;
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
readonly deliver: (request: NoticeEnvelope) => boolean;
|
|
90
|
+
register(caller: BoardBinding, request: ActiveEnvelope) {
|
|
91
|
+
if (request.turnId)
|
|
92
|
+
this.active.set(caller.agentName, {
|
|
93
|
+
sessionId: caller.sessionId,
|
|
94
|
+
turnId: request.turnId,
|
|
95
|
+
});
|
|
96
|
+
else if (
|
|
97
|
+
this.active.get(caller.agentName)?.turnId === request.previousTurnId
|
|
98
|
+
)
|
|
99
|
+
this.active.delete(caller.agentName);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
import { statSync } from "node:fs";
|
|
2
|
+
import {
|
|
3
|
+
DatabaseSync,
|
|
4
|
+
type SQLInputValue,
|
|
5
|
+
type SQLOutputValue,
|
|
6
|
+
} from "node:sqlite";
|
|
7
|
+
import { caseFold } from "unicode-case-folding";
|
|
8
|
+
import type {
|
|
9
|
+
BoardDetail,
|
|
10
|
+
BoardIndex,
|
|
11
|
+
BoardSummary,
|
|
12
|
+
DiscussionSummary,
|
|
13
|
+
Post,
|
|
14
|
+
ThreadDetail,
|
|
15
|
+
ThreadPage,
|
|
16
|
+
ThreadStatus,
|
|
17
|
+
ViewSource,
|
|
18
|
+
} from "./contracts.ts";
|
|
19
|
+
|
|
20
|
+
type Row = Record<string, SQLOutputValue>;
|
|
21
|
+
function text(row: Row, key: string): string {
|
|
22
|
+
const value = row[key];
|
|
23
|
+
if (typeof value !== "string")
|
|
24
|
+
throw new Error(`Invalid board archive field: ${key}`);
|
|
25
|
+
return value;
|
|
26
|
+
}
|
|
27
|
+
function count(row: Row, key: string): number {
|
|
28
|
+
const value = row[key];
|
|
29
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value))
|
|
30
|
+
throw new Error(`Invalid board archive count: ${key}`);
|
|
31
|
+
return value;
|
|
32
|
+
}
|
|
33
|
+
function nullableText(row: Row, key: string): string | null {
|
|
34
|
+
return row[key] === null ? null : text(row, key);
|
|
35
|
+
}
|
|
36
|
+
function post(row: Row): Post {
|
|
37
|
+
return {
|
|
38
|
+
id: text(row, "id"),
|
|
39
|
+
channel: text(row, "channel"),
|
|
40
|
+
author: text(row, "author"),
|
|
41
|
+
createdAt: text(row, "created_at"),
|
|
42
|
+
text: text(row, "text"),
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The archive is opened read-only; no migrations, board creation or subscriptions. */
|
|
47
|
+
export class Archive {
|
|
48
|
+
private readonly db: DatabaseSync | undefined;
|
|
49
|
+
private readonly source: ViewSource;
|
|
50
|
+
constructor(source: ViewSource) {
|
|
51
|
+
this.source = source;
|
|
52
|
+
try {
|
|
53
|
+
statSync(source.databasePath);
|
|
54
|
+
} catch (error) {
|
|
55
|
+
if (error instanceof Error && "code" in error && error.code === "ENOENT")
|
|
56
|
+
return;
|
|
57
|
+
throw error;
|
|
58
|
+
}
|
|
59
|
+
const db = new DatabaseSync(source.databasePath, { readOnly: true });
|
|
60
|
+
try {
|
|
61
|
+
db.exec("PRAGMA busy_timeout=2000; PRAGMA query_only=ON; BEGIN");
|
|
62
|
+
if (db.prepare("PRAGMA user_version").get()?.["user_version"] !== 1)
|
|
63
|
+
throw new Error("Unsupported board archive version");
|
|
64
|
+
this.db = db;
|
|
65
|
+
} catch (error) {
|
|
66
|
+
db.close();
|
|
67
|
+
throw error;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
close(): void {
|
|
71
|
+
this.db?.close();
|
|
72
|
+
}
|
|
73
|
+
private all(sql: string, ...args: SQLInputValue[]): Row[] {
|
|
74
|
+
return this.db?.prepare(sql).all(...args) ?? [];
|
|
75
|
+
}
|
|
76
|
+
private hasTable(name: string): boolean {
|
|
77
|
+
return (
|
|
78
|
+
this.all(
|
|
79
|
+
"SELECT name FROM sqlite_master WHERE type='table' AND name=?",
|
|
80
|
+
name,
|
|
81
|
+
).length > 0
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
private status(id: string, threadId: string): ThreadStatus {
|
|
85
|
+
if (!this.hasTable("thread_statuses")) return "open";
|
|
86
|
+
const value = this.all(
|
|
87
|
+
"SELECT status FROM thread_statuses WHERE board_id=? AND thread_id=?",
|
|
88
|
+
id,
|
|
89
|
+
threadId,
|
|
90
|
+
)[0]?.["status"];
|
|
91
|
+
return value === "completed" || value === "abandoned" ? value : "open";
|
|
92
|
+
}
|
|
93
|
+
private summary(id: string, threadId: string): DiscussionSummary | null {
|
|
94
|
+
if (!this.hasTable("thread_summaries")) return null;
|
|
95
|
+
const row = this.all(
|
|
96
|
+
`SELECT s.*, EXISTS(SELECT 1 FROM posts p WHERE p.board_id=s.board_id AND p.root=s.thread_id
|
|
97
|
+
AND p.seq>(SELECT seq FROM posts covered WHERE covered.board_id=s.board_id AND covered.id=s.through_message_id)) AS has_newer_posts
|
|
98
|
+
FROM thread_summaries s WHERE s.board_id=? AND s.thread_id=?`,
|
|
99
|
+
id,
|
|
100
|
+
threadId,
|
|
101
|
+
)[0];
|
|
102
|
+
return row
|
|
103
|
+
? {
|
|
104
|
+
text: text(row, "text"),
|
|
105
|
+
createdAt: text(row, "created_at"),
|
|
106
|
+
throughMessageId: text(row, "through_message_id"),
|
|
107
|
+
hasNewerPosts: count(row, "has_newer_posts") === 1,
|
|
108
|
+
provider: text(row, "provider"),
|
|
109
|
+
model: text(row, "model"),
|
|
110
|
+
reasoning: text(row, "reasoning"),
|
|
111
|
+
}
|
|
112
|
+
: null;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
index(): BoardIndex {
|
|
116
|
+
const { databasePath: _path, ...context } = this.source;
|
|
117
|
+
const boards: BoardSummary[] = this.all(
|
|
118
|
+
`SELECT b.board_id,b.root_session_id,b.created_at,
|
|
119
|
+
(SELECT MAX(created_at) FROM posts WHERE board_id=b.board_id) AS last_activity,
|
|
120
|
+
(SELECT COUNT(*) FROM channels WHERE board_id=b.board_id) AS channels,
|
|
121
|
+
(SELECT COUNT(*) FROM posts WHERE board_id=b.board_id) AS posts,
|
|
122
|
+
(SELECT COUNT(DISTINCT author) FROM posts WHERE board_id=b.board_id) AS agents
|
|
123
|
+
FROM boards b WHERE owner_folder=? ORDER BY COALESCE(last_activity,b.created_at) DESC`,
|
|
124
|
+
this.source.folder,
|
|
125
|
+
).map((row) => ({
|
|
126
|
+
id: text(row, "board_id"),
|
|
127
|
+
rootSessionId: text(row, "root_session_id"),
|
|
128
|
+
createdAt: text(row, "created_at"),
|
|
129
|
+
lastActivity: nullableText(row, "last_activity"),
|
|
130
|
+
channels: count(row, "channels"),
|
|
131
|
+
posts: count(row, "posts"),
|
|
132
|
+
agents: count(row, "agents"),
|
|
133
|
+
}));
|
|
134
|
+
if (!boards.some((board) => board.id === context.boardId))
|
|
135
|
+
boards.unshift({
|
|
136
|
+
id: context.boardId,
|
|
137
|
+
rootSessionId: context.sessionId,
|
|
138
|
+
createdAt: null,
|
|
139
|
+
lastActivity: null,
|
|
140
|
+
channels: 0,
|
|
141
|
+
posts: 0,
|
|
142
|
+
agents: 0,
|
|
143
|
+
});
|
|
144
|
+
return { context, boards };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
private board(id: string): BoardSummary {
|
|
148
|
+
const board = this.index().boards.find((board) => board.id === id);
|
|
149
|
+
if (!board) throw new Error("Board not found in this folder");
|
|
150
|
+
return board;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
detail(id: string): BoardDetail {
|
|
154
|
+
const board = this.board(id);
|
|
155
|
+
const channels = this.all(
|
|
156
|
+
`SELECT c.name,c.author,c.created_at,COUNT(p.id) AS posts,
|
|
157
|
+
COUNT(CASE WHEN p.id=p.root THEN 1 END) AS threads,MAX(p.created_at) AS last_activity
|
|
158
|
+
FROM channels c LEFT JOIN posts p ON p.board_id=c.board_id AND p.channel=c.name
|
|
159
|
+
WHERE c.board_id=? GROUP BY c.name ORDER BY COALESCE(last_activity,c.created_at) DESC,c.name`,
|
|
160
|
+
id,
|
|
161
|
+
).map((row) => ({
|
|
162
|
+
name: text(row, "name"),
|
|
163
|
+
author: text(row, "author"),
|
|
164
|
+
createdAt: text(row, "created_at"),
|
|
165
|
+
posts: count(row, "posts"),
|
|
166
|
+
threads: count(row, "threads"),
|
|
167
|
+
lastActivity: nullableText(row, "last_activity"),
|
|
168
|
+
}));
|
|
169
|
+
const agents = this.all(
|
|
170
|
+
"SELECT author,COUNT(*) AS posts,MAX(created_at) AS last_activity FROM posts WHERE board_id=? GROUP BY author ORDER BY posts DESC,author",
|
|
171
|
+
id,
|
|
172
|
+
).map((row) => ({
|
|
173
|
+
name: text(row, "author"),
|
|
174
|
+
posts: count(row, "posts"),
|
|
175
|
+
lastActivity: text(row, "last_activity"),
|
|
176
|
+
}));
|
|
177
|
+
const subscriptions = this.all(
|
|
178
|
+
"SELECT target,agent,enabled FROM subscriptions WHERE board_id=? ORDER BY target,agent",
|
|
179
|
+
id,
|
|
180
|
+
).map((row) => ({
|
|
181
|
+
target: text(row, "target"),
|
|
182
|
+
agent: text(row, "agent"),
|
|
183
|
+
enabled: count(row, "enabled") === 1,
|
|
184
|
+
}));
|
|
185
|
+
return { board, channels, agents, subscriptions };
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
threads(id: string, params: URLSearchParams): ThreadPage {
|
|
189
|
+
this.board(id);
|
|
190
|
+
const channel = params.get("channel");
|
|
191
|
+
const query = params.get("q");
|
|
192
|
+
const author = params.get("author");
|
|
193
|
+
const summaries =
|
|
194
|
+
this.hasTable("thread_summaries") && params.get("full") !== "true";
|
|
195
|
+
if (query && query.length > 1000) throw new Error("Search is too long");
|
|
196
|
+
const where = ["r.board_id=?", "r.id=r.root"];
|
|
197
|
+
const args: SQLInputValue[] = [id];
|
|
198
|
+
if (channel !== null) {
|
|
199
|
+
where.push("r.channel=?");
|
|
200
|
+
args.push(channel);
|
|
201
|
+
}
|
|
202
|
+
if (query || author) {
|
|
203
|
+
const match = ["m.board_id=r.board_id", "m.root=r.id"];
|
|
204
|
+
if (query) {
|
|
205
|
+
match.push("instr(m.body_search,?)>0");
|
|
206
|
+
args.push(caseFold(query));
|
|
207
|
+
}
|
|
208
|
+
if (author) {
|
|
209
|
+
match.push("m.author=?");
|
|
210
|
+
args.push(author);
|
|
211
|
+
}
|
|
212
|
+
const originals = `EXISTS(SELECT 1 FROM posts m WHERE ${match.join(" AND ")})`;
|
|
213
|
+
if (summaries) {
|
|
214
|
+
const summaryMatch = ["s.board_id=r.board_id", "s.thread_id=r.id"];
|
|
215
|
+
if (query) {
|
|
216
|
+
summaryMatch.push("instr(s.body_search,?)>0");
|
|
217
|
+
args.push(caseFold(query));
|
|
218
|
+
}
|
|
219
|
+
if (author) {
|
|
220
|
+
summaryMatch.push(
|
|
221
|
+
"EXISTS(SELECT 1 FROM posts a WHERE a.board_id=r.board_id AND a.root=r.id AND a.author=?)",
|
|
222
|
+
);
|
|
223
|
+
args.push(author);
|
|
224
|
+
}
|
|
225
|
+
where.push(
|
|
226
|
+
`((NOT EXISTS(SELECT 1 FROM thread_summaries s WHERE s.board_id=r.board_id AND s.thread_id=r.id) AND ${originals}) OR EXISTS(SELECT 1 FROM thread_summaries s WHERE ${summaryMatch.join(" AND ")}))`,
|
|
227
|
+
);
|
|
228
|
+
} else where.push(originals);
|
|
229
|
+
}
|
|
230
|
+
const cursor = this.cursor(params);
|
|
231
|
+
const rows = this.all(
|
|
232
|
+
`SELECT r.id,r.channel,r.author,r.text,r.created_at,
|
|
233
|
+
MAX(p.created_at) AS last_activity,MAX(p.seq) AS last_seq,COUNT(*)-1 AS replies
|
|
234
|
+
FROM posts r JOIN posts p ON p.board_id=r.board_id AND p.root=r.id
|
|
235
|
+
WHERE ${where.join(" AND ")} GROUP BY r.id HAVING MAX(p.seq)<? ORDER BY last_seq DESC LIMIT 41`,
|
|
236
|
+
...args,
|
|
237
|
+
cursor ?? Number.MAX_SAFE_INTEGER,
|
|
238
|
+
);
|
|
239
|
+
const visible = rows.slice(0, 40);
|
|
240
|
+
const last = visible.at(-1);
|
|
241
|
+
return {
|
|
242
|
+
threads: visible.map((row) => {
|
|
243
|
+
const threadId = text(row, "id");
|
|
244
|
+
const summary = this.summary(id, threadId);
|
|
245
|
+
return {
|
|
246
|
+
status: this.status(id, threadId),
|
|
247
|
+
summarized: summary !== null,
|
|
248
|
+
id: threadId,
|
|
249
|
+
channel: text(row, "channel"),
|
|
250
|
+
author: text(row, "author"),
|
|
251
|
+
preview: (params.get("full") === "true"
|
|
252
|
+
? text(row, "text")
|
|
253
|
+
: (summary?.text ?? text(row, "text"))
|
|
254
|
+
).slice(0, 600),
|
|
255
|
+
createdAt: text(row, "created_at"),
|
|
256
|
+
lastActivity: text(row, "last_activity"),
|
|
257
|
+
replies: count(row, "replies"),
|
|
258
|
+
};
|
|
259
|
+
}),
|
|
260
|
+
nextCursor:
|
|
261
|
+
rows.length > 40 && last ? String(count(last, "last_seq")) : null,
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
thread(id: string, threadId: string, params: URLSearchParams): ThreadDetail {
|
|
266
|
+
this.board(id);
|
|
267
|
+
const root = this.all(
|
|
268
|
+
"SELECT id,channel,author,created_at,text FROM posts WHERE board_id=? AND id=? AND root=id",
|
|
269
|
+
id,
|
|
270
|
+
threadId,
|
|
271
|
+
)[0];
|
|
272
|
+
if (!root) throw new Error("Thread not found in this board");
|
|
273
|
+
const summary = this.summary(id, threadId);
|
|
274
|
+
const status = this.status(id, threadId);
|
|
275
|
+
if (summary && params.get("full") !== "true")
|
|
276
|
+
return { status, summary, root: null, replies: [], nextCursor: null };
|
|
277
|
+
const rows = this.all(
|
|
278
|
+
"SELECT seq,id,channel,author,created_at,text FROM posts WHERE board_id=? AND root=? AND id<>root AND seq>? ORDER BY seq LIMIT 81",
|
|
279
|
+
id,
|
|
280
|
+
threadId,
|
|
281
|
+
this.cursor(params) ?? 0,
|
|
282
|
+
);
|
|
283
|
+
const visible = rows.slice(0, 80);
|
|
284
|
+
const last = visible.at(-1);
|
|
285
|
+
return {
|
|
286
|
+
status,
|
|
287
|
+
summary,
|
|
288
|
+
root: post(root),
|
|
289
|
+
replies: visible.map(post),
|
|
290
|
+
nextCursor: rows.length > 80 && last ? String(count(last, "seq")) : null,
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
private cursor(params: URLSearchParams): number | undefined {
|
|
295
|
+
const value = params.get("cursor");
|
|
296
|
+
if (value === null) return undefined;
|
|
297
|
+
if (!/^[0-9]+$/.test(value) || !Number.isSafeInteger(Number(value)))
|
|
298
|
+
throw new Error("Invalid page cursor");
|
|
299
|
+
return Number(value);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
|
|
6
|
+
export interface ViewerConfig {
|
|
7
|
+
host: string;
|
|
8
|
+
port: number;
|
|
9
|
+
publicUrl: string;
|
|
10
|
+
openCommand: string[] | null;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function stateDirectory(): string {
|
|
14
|
+
return join(
|
|
15
|
+
process.env["PI_CODING_AGENT_DIR"] || join(homedir(), ".pi", "agent"),
|
|
16
|
+
"board-viewer",
|
|
17
|
+
);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function configPath(): string {
|
|
21
|
+
return join(stateDirectory(), "config.json");
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export async function loadConfig(): Promise<ViewerConfig> {
|
|
25
|
+
let value: unknown;
|
|
26
|
+
try {
|
|
27
|
+
value = JSON.parse(await readFile(configPath(), "utf8"));
|
|
28
|
+
} catch (error) {
|
|
29
|
+
if (!(error instanceof Error && "code" in error && error.code === "ENOENT"))
|
|
30
|
+
throw error;
|
|
31
|
+
value = {};
|
|
32
|
+
}
|
|
33
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
34
|
+
throw new Error("Viewer config must be an object");
|
|
35
|
+
const config = value as Record<string, unknown>;
|
|
36
|
+
const host = config["host"] ?? "127.0.0.1";
|
|
37
|
+
const port = config["port"] ?? 47984;
|
|
38
|
+
if (typeof host !== "string" || !["127.0.0.1", "0.0.0.0"].includes(host))
|
|
39
|
+
throw new Error("Viewer host must be 127.0.0.1 or 0.0.0.0");
|
|
40
|
+
if (
|
|
41
|
+
typeof port !== "number" ||
|
|
42
|
+
!Number.isInteger(port) ||
|
|
43
|
+
port < 1024 ||
|
|
44
|
+
port > 65535
|
|
45
|
+
)
|
|
46
|
+
throw new Error("Viewer port must be an integer from 1024 to 65535");
|
|
47
|
+
const publicUrl = config["publicUrl"] ?? `http://127.0.0.1:${port}`;
|
|
48
|
+
if (typeof publicUrl !== "string")
|
|
49
|
+
throw new Error("Viewer publicUrl must be an HTTP or HTTPS origin");
|
|
50
|
+
const url = new URL(publicUrl);
|
|
51
|
+
if (
|
|
52
|
+
!["http:", "https:"].includes(url.protocol) ||
|
|
53
|
+
url.username ||
|
|
54
|
+
url.password ||
|
|
55
|
+
url.pathname !== "/" ||
|
|
56
|
+
url.search ||
|
|
57
|
+
url.hash
|
|
58
|
+
)
|
|
59
|
+
throw new Error(
|
|
60
|
+
"Viewer publicUrl must be an HTTP or HTTPS origin without a path",
|
|
61
|
+
);
|
|
62
|
+
const command = config["openCommand"];
|
|
63
|
+
if (
|
|
64
|
+
command !== undefined &&
|
|
65
|
+
command !== null &&
|
|
66
|
+
(!Array.isArray(command) ||
|
|
67
|
+
!command.length ||
|
|
68
|
+
!command.every((part) => typeof part === "string" && part.length > 0))
|
|
69
|
+
)
|
|
70
|
+
throw new Error(
|
|
71
|
+
"Viewer openCommand must be an argument array, or null for link only",
|
|
72
|
+
);
|
|
73
|
+
const defaultCommand =
|
|
74
|
+
process.platform === "darwin"
|
|
75
|
+
? ["open"]
|
|
76
|
+
: process.platform === "win32"
|
|
77
|
+
? ["rundll32", "url.dll,FileProtocolHandler"]
|
|
78
|
+
: ["xdg-open"];
|
|
79
|
+
return {
|
|
80
|
+
host,
|
|
81
|
+
port,
|
|
82
|
+
publicUrl: url.origin,
|
|
83
|
+
openCommand:
|
|
84
|
+
command === null
|
|
85
|
+
? null
|
|
86
|
+
: command === undefined
|
|
87
|
+
? defaultCommand
|
|
88
|
+
: (command as string[]),
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export async function accessKey(): Promise<string> {
|
|
93
|
+
const directory = stateDirectory();
|
|
94
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
95
|
+
const path = join(directory, "access-key");
|
|
96
|
+
try {
|
|
97
|
+
await writeFile(path, randomBytes(32).toString("hex"), {
|
|
98
|
+
flag: "wx",
|
|
99
|
+
mode: 0o600,
|
|
100
|
+
});
|
|
101
|
+
} catch (error) {
|
|
102
|
+
if (!(error instanceof Error && "code" in error && error.code === "EEXIST"))
|
|
103
|
+
throw error;
|
|
104
|
+
}
|
|
105
|
+
const key = (await readFile(path, "utf8")).trim();
|
|
106
|
+
if (!/^[a-f0-9]{64}$/.test(key))
|
|
107
|
+
throw new Error(
|
|
108
|
+
"Invalid viewer access key; remove the access-key file and restart the viewer",
|
|
109
|
+
);
|
|
110
|
+
return key;
|
|
111
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
interface ViewContext {
|
|
2
|
+
sessionId: string;
|
|
3
|
+
sessionName: string | null;
|
|
4
|
+
boardId: string;
|
|
5
|
+
folder: string;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export interface ViewSource extends ViewContext {
|
|
9
|
+
databasePath: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface BoardSummary {
|
|
13
|
+
id: string;
|
|
14
|
+
rootSessionId: string;
|
|
15
|
+
createdAt: string | null;
|
|
16
|
+
lastActivity: string | null;
|
|
17
|
+
channels: number;
|
|
18
|
+
posts: number;
|
|
19
|
+
agents: number;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface BoardIndex {
|
|
23
|
+
context: ViewContext;
|
|
24
|
+
boards: BoardSummary[];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
interface Channel {
|
|
28
|
+
name: string;
|
|
29
|
+
author: string;
|
|
30
|
+
createdAt: string;
|
|
31
|
+
posts: number;
|
|
32
|
+
threads: number;
|
|
33
|
+
lastActivity: string | null;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
interface Agent {
|
|
37
|
+
name: string;
|
|
38
|
+
posts: number;
|
|
39
|
+
lastActivity: string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
interface Subscription {
|
|
43
|
+
target: string;
|
|
44
|
+
agent: string;
|
|
45
|
+
enabled: boolean;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface BoardDetail {
|
|
49
|
+
board: BoardSummary;
|
|
50
|
+
channels: Channel[];
|
|
51
|
+
agents: Agent[];
|
|
52
|
+
subscriptions: Subscription[];
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
interface ThreadSummary {
|
|
56
|
+
status: ThreadStatus;
|
|
57
|
+
summarized: boolean;
|
|
58
|
+
id: string;
|
|
59
|
+
channel: string;
|
|
60
|
+
author: string;
|
|
61
|
+
preview: string;
|
|
62
|
+
createdAt: string;
|
|
63
|
+
lastActivity: string;
|
|
64
|
+
replies: number;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export interface ThreadPage {
|
|
68
|
+
threads: ThreadSummary[];
|
|
69
|
+
nextCursor: string | null;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export interface Post {
|
|
73
|
+
id: string;
|
|
74
|
+
channel: string;
|
|
75
|
+
author: string;
|
|
76
|
+
createdAt: string;
|
|
77
|
+
text: string;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export interface ThreadDetail {
|
|
81
|
+
status: ThreadStatus;
|
|
82
|
+
summary: DiscussionSummary | null;
|
|
83
|
+
root: Post | null;
|
|
84
|
+
replies: Post[];
|
|
85
|
+
nextCursor: string | null;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export type ThreadStatus = "open" | "completed" | "abandoned";
|
|
89
|
+
|
|
90
|
+
export interface DiscussionSummary {
|
|
91
|
+
text: string;
|
|
92
|
+
createdAt: string;
|
|
93
|
+
throughMessageId: string;
|
|
94
|
+
hasNewerPosts: boolean;
|
|
95
|
+
provider: string;
|
|
96
|
+
model: string;
|
|
97
|
+
reasoning: string;
|
|
98
|
+
}
|