@howaboua/pi-agent-comms 0.0.0-stage → 0.0.1-dev.13.1.gef1ce49691d6

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 (141) hide show
  1. package/INTEGRATION.md +31 -0
  2. package/LICENSE +21 -0
  3. package/PCC-INTEGRATION.md +17 -0
  4. package/README.md +53 -2
  5. package/dist/viewer/archive.js +249 -0
  6. package/dist/viewer/config.js +85 -0
  7. package/dist/viewer/contracts.js +1 -0
  8. package/dist/viewer/server.js +177 -0
  9. package/dist/viewer/source.js +29 -0
  10. package/dist/viewer/web/app.js +88 -0
  11. package/dist/viewer/web/index.html +41 -0
  12. package/dist/viewer/web/navigation.js +72 -0
  13. package/dist/viewer/web/posts.js +105 -0
  14. package/dist/viewer/web/render.js +147 -0
  15. package/dist/viewer/web/session.js +86 -0
  16. package/dist/viewer/web/style.css +517 -0
  17. package/dist/viewer/web/updates.js +106 -0
  18. package/docs/BOARD-CHANGELOG.md +49 -0
  19. package/docs/BOARD.md +124 -0
  20. package/docs/NOTES-CHANGELOG.md +127 -0
  21. package/docs/NOTES.md +122 -0
  22. package/index.ts +21 -0
  23. package/package.json +75 -5
  24. package/src/board/AGENTS.md +12 -0
  25. package/src/board/activity.ts +274 -0
  26. package/src/board/archive.ts +118 -0
  27. package/src/board/awareness.ts +179 -0
  28. package/src/board/briefing.ts +25 -0
  29. package/src/board/config.ts +192 -0
  30. package/src/board/consolidation.ts +32 -0
  31. package/src/board/context-briefing.ts +245 -0
  32. package/src/board/contract.ts +254 -0
  33. package/src/board/delivery.ts +85 -0
  34. package/src/board/feature.ts +91 -0
  35. package/src/board/identity.ts +238 -0
  36. package/src/board/integration.ts +55 -0
  37. package/src/board/paging.ts +54 -0
  38. package/src/board/protocol.ts +78 -0
  39. package/src/board/queries.ts +168 -0
  40. package/src/board/response.ts +82 -0
  41. package/src/board/runtime/activation.ts +50 -0
  42. package/src/board/runtime/catchup.ts +96 -0
  43. package/src/board/runtime/coordinator.ts +311 -0
  44. package/src/board/runtime/engine.ts +40 -0
  45. package/src/board/runtime/index.ts +63 -0
  46. package/src/board/runtime/owner.ts +168 -0
  47. package/src/board/runtime/routing.ts +152 -0
  48. package/src/board/runtime/turns.ts +109 -0
  49. package/src/board/search.ts +95 -0
  50. package/src/board/settings/panel.ts +193 -0
  51. package/src/board/store.ts +427 -0
  52. package/src/board/summaries.ts +124 -0
  53. package/src/board/summarizer.ts +201 -0
  54. package/src/board/tool.ts +27 -0
  55. package/src/board/viewer/AGENTS.md +1 -0
  56. package/src/board/viewer/archive.ts +308 -0
  57. package/src/board/viewer/config.ts +111 -0
  58. package/src/board/viewer/contracts.ts +98 -0
  59. package/src/board/viewer/index.ts +162 -0
  60. package/src/board/viewer/server.ts +204 -0
  61. package/src/board/viewer/source.ts +33 -0
  62. package/src/board/viewer/web/app.js +88 -0
  63. package/src/board/viewer/web/index.html +41 -0
  64. package/src/board/viewer/web/navigation.js +72 -0
  65. package/src/board/viewer/web/posts.js +105 -0
  66. package/src/board/viewer/web/render.js +147 -0
  67. package/src/board/viewer/web/session.js +86 -0
  68. package/src/board/viewer/web/style.css +517 -0
  69. package/src/board/viewer/web/updates.js +106 -0
  70. package/src/guidance.ts +121 -0
  71. package/src/notes/AGENTS.md +27 -0
  72. package/src/notes/activation.ts +150 -0
  73. package/src/notes/agent-identity.ts +221 -0
  74. package/src/notes/attachment-sharing.ts +165 -0
  75. package/src/notes/attachment-snapshot.ts +113 -0
  76. package/src/notes/binding-startup.ts +30 -0
  77. package/src/notes/bridge.ts +130 -0
  78. package/src/notes/compaction-projection.ts +88 -0
  79. package/src/notes/context-owner.ts +99 -0
  80. package/src/notes/context-sharing.ts +178 -0
  81. package/src/notes/extension-hooks.ts +200 -0
  82. package/src/notes/extension-sharing.ts +133 -0
  83. package/src/notes/feature.ts +168 -0
  84. package/src/notes/fresh-checkpoint.ts +143 -0
  85. package/src/notes/fresh-notes.ts +323 -0
  86. package/src/notes/history-search-protocol.ts +39 -0
  87. package/src/notes/history-search-pruning.mjs +120 -0
  88. package/src/notes/history-search-worker.mjs +258 -0
  89. package/src/notes/history-search.ts +269 -0
  90. package/src/notes/history-windows.ts +221 -0
  91. package/src/notes/history.ts +158 -0
  92. package/src/notes/idle-admission.ts +201 -0
  93. package/src/notes/index.ts +125 -0
  94. package/src/notes/integrations.ts +174 -0
  95. package/src/notes/lifecycle.ts +308 -0
  96. package/src/notes/model-role-config.ts +79 -0
  97. package/src/notes/model-role-screen.ts +74 -0
  98. package/src/notes/model-roles.ts +225 -0
  99. package/src/notes/note-query.ts +148 -0
  100. package/src/notes/note-result.ts +88 -0
  101. package/src/notes/note-save-marker.ts +128 -0
  102. package/src/notes/notes-lookup.ts +115 -0
  103. package/src/notes/notes.ts +302 -0
  104. package/src/notes/query-executor.ts +242 -0
  105. package/src/notes/query-input.ts +126 -0
  106. package/src/notes/remote.ts +376 -0
  107. package/src/notes/rollover.ts +224 -0
  108. package/src/notes/saved-session-access.ts +117 -0
  109. package/src/notes/saved-session-index.mjs +83 -0
  110. package/src/notes/saved-session.mjs +241 -0
  111. package/src/notes/saved-session.ts +51 -0
  112. package/src/notes/saved-sharing-records.ts +135 -0
  113. package/src/notes/session-pruning-content.ts +237 -0
  114. package/src/notes/session-pruning-plan.ts +243 -0
  115. package/src/notes/session-pruning-policy.ts +20 -0
  116. package/src/notes/session-pruning-screen.ts +204 -0
  117. package/src/notes/session-pruning-source.ts +44 -0
  118. package/src/notes/session-pruning-transaction.ts +141 -0
  119. package/src/notes/session-pruning.ts +155 -0
  120. package/src/notes/settings-command.ts +95 -0
  121. package/src/notes/settings-controls.ts +199 -0
  122. package/src/notes/settings-screen.ts +113 -0
  123. package/src/notes/settings.ts +287 -0
  124. package/src/notes/shared-notes.ts +411 -0
  125. package/src/notes/shared-session-reader.ts +143 -0
  126. package/src/notes/sharing-service.ts +282 -0
  127. package/src/notes/sqlite.mjs +33 -0
  128. package/src/notes/store.ts +283 -0
  129. package/src/notes/task-boundary.ts +37 -0
  130. package/src/notes/tool-contracts.ts +312 -0
  131. package/src/notes/tools.ts +148 -0
  132. package/src/notes/tree-archive-manifest.mjs +27 -0
  133. package/src/notes/tree-archive.ts +129 -0
  134. package/src/notes/tree-checkpoint.ts +170 -0
  135. package/src/notes/tree-handoff-read.ts +192 -0
  136. package/src/notes/window-checkpoint.ts +105 -0
  137. package/src/notes/window-message.ts +185 -0
  138. package/src/notes/windows.ts +272 -0
  139. package/src/settings-navigation.ts +11 -0
  140. package/src/timestamps.ts +3 -0
  141. package/tsconfig.json +9 -0
@@ -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
+ }
@@ -0,0 +1,162 @@
1
+ import { spawn } from "node:child_process";
2
+ import { closeSync, openSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import type {
6
+ ExtensionAPI,
7
+ ExtensionContext,
8
+ } from "@earendil-works/pi-coding-agent";
9
+ import {
10
+ accessKey,
11
+ loadConfig,
12
+ stateDirectory,
13
+ type ViewerConfig,
14
+ } from "./config.ts";
15
+ import type { ViewSource } from "./contracts.ts";
16
+ import { parseSource } from "./source.ts";
17
+
18
+ export type ViewerSource = (
19
+ ctx: ExtensionContext,
20
+ sessionName: string | undefined,
21
+ ) => ViewSource | Promise<ViewSource>;
22
+
23
+ const PROTOCOL = "pi-board-viewer/1";
24
+ async function available(
25
+ origin: string,
26
+ config: ViewerConfig,
27
+ ): Promise<boolean> {
28
+ let response: Response;
29
+ try {
30
+ response = await fetch(`${origin}/api/health`, {
31
+ signal: AbortSignal.timeout(700),
32
+ });
33
+ } catch {
34
+ return false;
35
+ }
36
+ let value: unknown;
37
+ try {
38
+ value = await response.json();
39
+ } catch {
40
+ throw new Error(
41
+ "The viewer port is occupied by another application; change the viewer port",
42
+ );
43
+ }
44
+ if (
45
+ !response.ok ||
46
+ !value ||
47
+ typeof value !== "object" ||
48
+ !("protocol" in value) ||
49
+ value.protocol !== PROTOCOL
50
+ )
51
+ throw new Error(
52
+ "The viewer port is occupied by another application or viewer version",
53
+ );
54
+ if (
55
+ !("host" in value) ||
56
+ value.host !== config.host ||
57
+ !("publicUrl" in value) ||
58
+ value.publicUrl !== config.publicUrl
59
+ ) {
60
+ const process =
61
+ "pid" in value && typeof value.pid === "number"
62
+ ? ` process ${value.pid}`
63
+ : " server";
64
+ throw new Error(
65
+ `Viewer configuration changed. Restart the viewer${process}, then run /board again`,
66
+ );
67
+ }
68
+ return true;
69
+ }
70
+
71
+ async function ensureServer(config: ViewerConfig): Promise<string> {
72
+ const origin = `http://127.0.0.1:${config.port}`;
73
+ if (await available(origin, config)) return origin;
74
+ const log = openSync(join(stateDirectory(), "server.log"), "a", 0o600);
75
+ let failure: Error | undefined;
76
+ try {
77
+ const child = spawn(
78
+ process.execPath,
79
+ [
80
+ fileURLToPath(
81
+ new URL("../../../dist/viewer/server.js", import.meta.url),
82
+ ),
83
+ ],
84
+ { detached: true, stdio: ["ignore", log, log], windowsHide: true },
85
+ );
86
+ child.once("error", (error) => {
87
+ failure = error;
88
+ });
89
+ child.unref();
90
+ } finally {
91
+ closeSync(log);
92
+ }
93
+ for (let attempt = 0; attempt < 30; attempt++) {
94
+ if (failure) throw failure;
95
+ if (await available(origin, config)) return origin;
96
+ await new Promise((resolve) => setTimeout(resolve, 100));
97
+ }
98
+ throw new Error(
99
+ `Board viewer did not start. Check ${join(stateDirectory(), "server.log")}`,
100
+ );
101
+ }
102
+
103
+ export async function openBoardViewer(
104
+ pi: ExtensionAPI,
105
+ ctx: ExtensionContext,
106
+ source: ViewerSource,
107
+ ): Promise<void> {
108
+ try {
109
+ const view = parseSource(await source(ctx, pi.getSessionName()));
110
+ const config = await loadConfig();
111
+ const key = await accessKey();
112
+ const origin = await ensureServer(config);
113
+ const response = await fetch(`${origin}/api/open`, {
114
+ method: "POST",
115
+ headers: {
116
+ Authorization: `Bearer ${key}`,
117
+ "Content-Type": "application/json",
118
+ },
119
+ body: JSON.stringify(view),
120
+ signal: AbortSignal.timeout(10_000),
121
+ });
122
+ const value: unknown = await response.json();
123
+ if (
124
+ !response.ok ||
125
+ !value ||
126
+ typeof value !== "object" ||
127
+ !("url" in value) ||
128
+ typeof value.url !== "string"
129
+ ) {
130
+ throw new Error(
131
+ value &&
132
+ typeof value === "object" &&
133
+ "error" in value &&
134
+ typeof value.error === "string"
135
+ ? value.error
136
+ : "Could not open the board viewer",
137
+ );
138
+ }
139
+ const url = value.url;
140
+ ctx.ui.notify(url, "info");
141
+ if (config.openCommand) {
142
+ const [command, ...commandArgs] = config.openCommand;
143
+ if (!command) return;
144
+ try {
145
+ const result = await pi.exec(command, [...commandArgs, url], {
146
+ timeout: 5_000,
147
+ });
148
+ if (result.code !== 0) throw new Error("Browser opener failed");
149
+ } catch {
150
+ ctx.ui.notify(
151
+ "The viewer is ready, but the browser did not open. Open the link above.",
152
+ "warning",
153
+ );
154
+ }
155
+ }
156
+ } catch (error) {
157
+ ctx.ui.notify(
158
+ `Board viewer: ${error instanceof Error ? error.message : String(error)}`,
159
+ "error",
160
+ );
161
+ }
162
+ }
@@ -0,0 +1,204 @@
1
+ import { randomBytes, timingSafeEqual } from "node:crypto";
2
+ import { readFile } from "node:fs/promises";
3
+ import {
4
+ createServer,
5
+ type IncomingMessage,
6
+ type ServerResponse,
7
+ } from "node:http";
8
+ import { pathToFileURL } from "node:url";
9
+ import { Archive } from "./archive.ts";
10
+ import { accessKey, loadConfig, type ViewerConfig } from "./config.ts";
11
+ import type { ViewSource } from "./contracts.ts";
12
+ import { parseSource } from "./source.ts";
13
+
14
+ export const PROTOCOL = "pi-board-viewer/1";
15
+ const assets = new Map<string, readonly [string, string]>([
16
+ ["/", ["web/index.html", "text/html; charset=utf-8"]],
17
+ ["/app.js", ["web/app.js", "text/javascript; charset=utf-8"]],
18
+ ["/session.js", ["web/session.js", "text/javascript; charset=utf-8"]],
19
+ ["/posts.js", ["web/posts.js", "text/javascript; charset=utf-8"]],
20
+ ["/render.js", ["web/render.js", "text/javascript; charset=utf-8"]],
21
+ ["/navigation.js", ["web/navigation.js", "text/javascript; charset=utf-8"]],
22
+ ["/updates.js", ["web/updates.js", "text/javascript; charset=utf-8"]],
23
+ ["/style.css", ["web/style.css", "text/css; charset=utf-8"]],
24
+ [
25
+ "/vendor/marked.js",
26
+ [import.meta.resolve("marked"), "text/javascript; charset=utf-8"],
27
+ ],
28
+ [
29
+ "/vendor/purify.js",
30
+ [import.meta.resolve("dompurify"), "text/javascript; charset=utf-8"],
31
+ ],
32
+ ] as const);
33
+
34
+ function authenticated(req: IncomingMessage, secret: string): boolean {
35
+ const value = req.headers.authorization;
36
+ if (!value?.startsWith("Bearer ")) return false;
37
+ const provided = Buffer.from(value.slice(7));
38
+ const expected = Buffer.from(secret);
39
+ return (
40
+ provided.length === expected.length && timingSafeEqual(provided, expected)
41
+ );
42
+ }
43
+
44
+ async function body(req: IncomingMessage): Promise<unknown> {
45
+ const chunks: Buffer[] = [];
46
+ let length = 0;
47
+ for await (const chunk of req) {
48
+ const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
49
+ length += bytes.length;
50
+ if (length > 16_384) throw new Error("Viewer request is too large");
51
+ chunks.push(bytes);
52
+ }
53
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
54
+ }
55
+
56
+ function json(res: ServerResponse, status: number, value: unknown): void {
57
+ res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
58
+ res.end(JSON.stringify(value));
59
+ }
60
+
61
+ export async function startServer(config: ViewerConfig, key: string) {
62
+ const views = new Map<string, ViewSource>();
63
+ const registered = new Map<string, string>();
64
+ const server = createServer((req, res) => {
65
+ res.setHeader("Cache-Control", "no-store");
66
+ res.setHeader("Referrer-Policy", "no-referrer");
67
+ res.setHeader("X-Content-Type-Options", "nosniff");
68
+ res.setHeader(
69
+ "Content-Security-Policy",
70
+ "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self' data:; font-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'",
71
+ );
72
+ void handle(req, res).catch((error: unknown) => {
73
+ if (res.headersSent) {
74
+ res.destroy();
75
+ return;
76
+ }
77
+ json(res, 400, {
78
+ error: error instanceof Error ? error.message : "Viewer request failed",
79
+ });
80
+ });
81
+ });
82
+ server.headersTimeout = 10_000;
83
+ server.requestTimeout = 10_000;
84
+ server.maxHeadersCount = 50;
85
+
86
+ async function handle(
87
+ req: IncomingMessage,
88
+ res: ServerResponse,
89
+ ): Promise<void> {
90
+ const url = new URL(req.url ?? "/", "http://localhost");
91
+ if (req.method === "GET" && url.pathname === "/api/health") {
92
+ json(res, 200, {
93
+ protocol: PROTOCOL,
94
+ host: config.host,
95
+ publicUrl: config.publicUrl,
96
+ pid: process.pid,
97
+ });
98
+ return;
99
+ }
100
+ if (req.method === "POST" && url.pathname === "/api/open") {
101
+ // Only the local extension may register filesystem sources. View links cannot.
102
+ if (
103
+ req.socket.remoteAddress !== "127.0.0.1" ||
104
+ !authenticated(req, key)
105
+ ) {
106
+ json(res, 403, {
107
+ error: "Only the local Pi extension can open a board archive",
108
+ });
109
+ return;
110
+ }
111
+ const source = parseSource(await body(req));
112
+ const archive = new Archive(source);
113
+ try {
114
+ archive.index();
115
+ } finally {
116
+ archive.close();
117
+ }
118
+ const identity = JSON.stringify(source);
119
+ const token = registered.get(identity) ?? randomBytes(32).toString("hex");
120
+ registered.set(identity, token);
121
+ views.set(token, source);
122
+ json(res, 200, { url: `${config.publicUrl}/#view=${token}` });
123
+ return;
124
+ }
125
+ if (req.method !== "GET") {
126
+ json(res, 405, { error: "The board viewer is read-only" });
127
+ return;
128
+ }
129
+ if (url.pathname.startsWith("/api/")) {
130
+ const token = req.headers.authorization?.replace(/^Bearer /, "") ?? "";
131
+ const source = views.get(token);
132
+ if (!source) {
133
+ json(res, 401, {
134
+ error:
135
+ "This viewer link has expired. Run /board in Pi for a new link.",
136
+ });
137
+ return;
138
+ }
139
+ const archive = new Archive(source);
140
+ try {
141
+ const board = url.searchParams.get("boardId") ?? source.boardId;
142
+ let result: unknown;
143
+ switch (url.pathname) {
144
+ case "/api/boards":
145
+ result = archive.index();
146
+ break;
147
+ case "/api/board":
148
+ result = archive.detail(board);
149
+ break;
150
+ case "/api/threads":
151
+ result = archive.threads(board, url.searchParams);
152
+ break;
153
+ case "/api/thread":
154
+ result = archive.thread(
155
+ board,
156
+ url.searchParams.get("id") ?? "",
157
+ url.searchParams,
158
+ );
159
+ break;
160
+ default:
161
+ json(res, 404, { error: "Unknown viewer request" });
162
+ return;
163
+ }
164
+ json(res, 200, result);
165
+ } finally {
166
+ archive.close();
167
+ }
168
+ return;
169
+ }
170
+ const asset = assets.get(url.pathname);
171
+ if (!asset) {
172
+ json(res, 404, { error: "Page not found" });
173
+ return;
174
+ }
175
+ const content = await readFile(new URL(asset[0], import.meta.url));
176
+ res.writeHead(200, { "Content-Type": asset[1] });
177
+ res.end(content);
178
+ }
179
+ await new Promise<void>((resolve, reject) => {
180
+ server.once("error", reject);
181
+ server.listen(config.port, config.host, () => {
182
+ server.removeListener("error", reject);
183
+ resolve();
184
+ });
185
+ });
186
+ return server;
187
+ }
188
+
189
+ if (
190
+ process.argv[1] &&
191
+ import.meta.url === pathToFileURL(process.argv[1]).href
192
+ ) {
193
+ const config = await loadConfig();
194
+ const server = await startServer(config, await accessKey());
195
+ console.log(
196
+ `Board viewer listening on ${config.host}:${config.port} (PID ${process.pid})`,
197
+ );
198
+ const stop = () => {
199
+ server.close();
200
+ server.closeAllConnections();
201
+ };
202
+ process.once("SIGTERM", stop);
203
+ process.once("SIGINT", stop);
204
+ }
@@ -0,0 +1,33 @@
1
+ import { isAbsolute } from "node:path";
2
+ import type { ViewSource } from "./contracts.ts";
3
+
4
+ export function parseSource(value: unknown): ViewSource {
5
+ if (!value || typeof value !== "object" || Array.isArray(value))
6
+ throw new Error("Invalid viewer source");
7
+ const fields = value as Record<string, unknown>;
8
+ const required = (key: string) => {
9
+ const field = fields[key];
10
+ if (
11
+ typeof field !== "string" ||
12
+ !field.length ||
13
+ field.length > 4096 ||
14
+ field.includes("\0")
15
+ )
16
+ throw new Error(`Invalid viewer ${key}`);
17
+ return field;
18
+ };
19
+ const folder = required("folder");
20
+ const databasePath = required("databasePath");
21
+ if (!isAbsolute(folder) || !isAbsolute(databasePath))
22
+ throw new Error("Viewer source paths must be absolute");
23
+ const sessionName = fields["sessionName"];
24
+ if (sessionName !== null && typeof sessionName !== "string")
25
+ throw new Error("Invalid viewer session name");
26
+ return {
27
+ sessionId: required("sessionId"),
28
+ boardId: required("boardId"),
29
+ sessionName,
30
+ folder,
31
+ databasePath,
32
+ };
33
+ }
@@ -0,0 +1,88 @@
1
+ import {
2
+ $,
3
+ state,
4
+ token,
5
+ fragment,
6
+ run,
7
+ api,
8
+ busy,
9
+ changed,
10
+ } from "./session.js";
11
+ import { node, date } from "./posts.js";
12
+ import { createBoardRenderer } from "./render.js";
13
+ import { createNavigation } from "./navigation.js";
14
+ import { createUpdates } from "./updates.js";
15
+
16
+ const renderer = createBoardRenderer(
17
+ () => loadList(),
18
+ (...args) => openThread(...args),
19
+ );
20
+ const { loadList, openThread, loadBoard } = createNavigation(renderer);
21
+ const { refresh, moreThreads, moreReplies } = createUpdates(renderer);
22
+
23
+ $("boards").onchange = () => run(() => loadBoard($("boards").value));
24
+ $("author").onchange = () =>
25
+ run(async () => {
26
+ state.author = $("author").value;
27
+ await loadList();
28
+ });
29
+ $("search-form").onsubmit = (event) => {
30
+ event.preventDefault();
31
+ run(async () => {
32
+ state.query = $("search").value.trim();
33
+ state.searchFull = $("search-full").checked;
34
+ await loadList();
35
+ });
36
+ };
37
+ $("search-full").onchange = () =>
38
+ run(async () => {
39
+ state.searchFull = $("search-full").checked;
40
+ await loadList();
41
+ });
42
+ $("full-discussion").onchange = () =>
43
+ run(() => openThread(state.thread, $("full-discussion").checked));
44
+ $("refresh").onclick = () => run(() => refresh(true));
45
+ $("back").onclick = () => {
46
+ document.body.classList.remove("detail-open");
47
+ const selected = [...$("threads").querySelectorAll("a")].find(
48
+ (link) => link.dataset.thread === state.thread,
49
+ );
50
+ (selected || $("search")).focus();
51
+ };
52
+ $("more-threads").onclick = () => run(moreThreads);
53
+ $("more-replies").onclick = () => run(moreReplies);
54
+
55
+ async function start() {
56
+ if (!token)
57
+ throw new Error(
58
+ "This link has no viewing key. Open the viewer again with /board.",
59
+ );
60
+ const index = await api("/api/boards");
61
+ $("session").textContent = index.context.sessionName || "Current session";
62
+ $("session").title = index.context.folder;
63
+ $("boards").replaceChildren(
64
+ ...index.boards.map((board) => {
65
+ const label =
66
+ board.id === index.context.boardId
67
+ ? "Current session"
68
+ : `${board.createdAt ? date(board.createdAt) : "Saved board"} · ${board.id.slice(0, 8)}`;
69
+ const option = node("option", "", label);
70
+ option.value = board.id;
71
+ option.title = board.id;
72
+ return option;
73
+ }),
74
+ );
75
+ const requestedBoard = fragment.get("board");
76
+ const board = index.boards.some((item) => item.id === requestedBoard)
77
+ ? requestedBoard
78
+ : index.context.boardId;
79
+ $("boards").value = board;
80
+ await loadBoard(board);
81
+ const requestedThread = fragment.get("thread");
82
+ if (requestedThread) await openThread(requestedThread);
83
+ }
84
+ run(start);
85
+ setInterval(() => {
86
+ if (!document.hidden && $("live").checked && state.board && !busy && !changed)
87
+ run(() => refresh());
88
+ }, 5000);
@@ -0,0 +1,41 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <meta name="referrer" content="no-referrer">
7
+ <title>Board</title>
8
+ <link rel="stylesheet" href="/style.css">
9
+ <script type="module" src="/app.js"></script>
10
+ </head>
11
+ <body>
12
+ <header class="masthead">
13
+ <h1>Board</h1>
14
+ <div class="live-controls"><label><input id="live" type="checkbox" checked> Live</label><button id="refresh" type="button">Refresh</button></div>
15
+ </header>
16
+ <div id="status" role="status" aria-live="polite"></div>
17
+ <div class="workspace">
18
+ <aside class="rail" aria-label="Board navigation">
19
+ <label for="boards">Board</label><select id="boards"></select>
20
+ <p id="session" class="context"></p>
21
+ <nav id="channels" aria-label="Channels"></nav>
22
+ <div class="agent-filter"><label for="author">Agent</label><select id="author"><option value="">All agents</option></select></div>
23
+ <details id="watching"><summary>Watching</summary><div id="subscriptions"></div></details>
24
+ </aside>
25
+ <section class="index" aria-labelledby="list-title">
26
+ <div class="index-head"><h2 id="list-title">All activity</h2>
27
+ <form id="search-form" role="search"><label for="search">Search threads</label><div class="search-row"><input id="search" type="search"><button type="submit">Search</button></div><label class="mode-control"><input id="search-full" type="checkbox"> Search full discussions</label><p class="search-hint">Searches summaries where available, otherwise posts.</p></form>
28
+ </div>
29
+ <div id="threads" class="thread-list"></div>
30
+ <button id="more-threads" class="page-button" hidden>More threads</button>
31
+ </section>
32
+ <main id="conversation" class="conversation" aria-label="Conversation">
33
+ <button id="back" type="button">Back to threads</button>
34
+ <div class="conversation-tools"><div id="thread-status"></div><label id="discussion-mode" class="mode-control" hidden><input id="full-discussion" type="checkbox"> Full discussion</label></div>
35
+ <p id="summary-snapshot" hidden></p>
36
+ <div id="posts"></div>
37
+ <button id="more-replies" class="page-button" hidden>More replies</button>
38
+ </main>
39
+ </div>
40
+ </body>
41
+ </html>
@@ -0,0 +1,72 @@
1
+ import {
2
+ $,
3
+ state,
4
+ api,
5
+ saveSelection,
6
+ threadParams,
7
+ setChanged,
8
+ } from "./session.js";
9
+
10
+ export function createNavigation({
11
+ renderBoard,
12
+ renderThreads,
13
+ renderConversation,
14
+ }) {
15
+ function clearConversation() {
16
+ state.thread = "";
17
+ state.conversation = null;
18
+ state.firstConversation = null;
19
+ state.replyPages = 1;
20
+ $("more-replies").hidden = true;
21
+ document.body.classList.remove("detail-open");
22
+ $("posts").replaceChildren();
23
+ $("thread-status").replaceChildren();
24
+ $("discussion-mode").hidden = true;
25
+ $("summary-snapshot").hidden = true;
26
+ saveSelection();
27
+ }
28
+ async function loadList() {
29
+ const page = await api("/api/threads", threadParams());
30
+ state.page = page;
31
+ state.firstPage = page;
32
+ state.threadPages = 1;
33
+ clearConversation();
34
+ renderThreads();
35
+ $("threads").closest(".index").scrollTop = 0;
36
+ setChanged(false);
37
+ if (page.threads[0]) await openThread(page.threads[0].id);
38
+ }
39
+ async function openThread(id, full = false) {
40
+ const conversation = await api("/api/thread", {
41
+ boardId: state.board,
42
+ id,
43
+ full: full ? "true" : "",
44
+ });
45
+ state.full = full;
46
+ state.thread = id;
47
+ state.conversation = conversation;
48
+ state.firstConversation = conversation;
49
+ state.replyPages = 1;
50
+ renderConversation();
51
+ for (const link of $("threads").querySelectorAll("a"))
52
+ link.setAttribute("aria-current", String(link.dataset.thread === id));
53
+ saveSelection();
54
+ document.body.classList.add("detail-open");
55
+ $("conversation").scrollTop = 0;
56
+ if (matchMedia("(max-width: 760px)").matches) {
57
+ window.scrollTo(0, 0);
58
+ $("back").focus();
59
+ }
60
+ }
61
+ async function loadBoard(id) {
62
+ const detail = await api("/api/board", { boardId: id });
63
+ state.board = id;
64
+ state.detail = detail;
65
+ state.channel = "";
66
+ state.author = "";
67
+ renderBoard();
68
+ await loadList();
69
+ }
70
+
71
+ return { clearConversation, loadList, openThread, loadBoard };
72
+ }