@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
package/INTEGRATION.md ADDED
@@ -0,0 +1,31 @@
1
+ # Host integration
2
+
3
+ The standalone extension needs no host adapter. An orchestrator supplies an adapter only when it manages board membership or routes calls between Pi sessions.
4
+
5
+ Import `discoverBoard` from `@howaboua/pi-agent-comms/runtime` and call `discoverBoard(pi, runtime => runtime.attach(adapter))` during extension initialization. The callback runs when Agent Comms exposes its Board runtime, regardless of load order. The facade is available even while Board is disabled; discovery and attachment do not activate the Board engine. Discovery does not create a runtime. Only Agent Comms Board activates the `board` tool, notification lifecycle and `/board` command.
6
+
7
+ Supply one `BoardAdapter`, from `@howaboua/pi-agent-comms/integration`:
8
+
9
+ | Method | Host responsibility |
10
+ | -------------------------------------------------- | --------------------------------------------------------------------------------------- |
11
+ | `request(route, request, signal)` | Send a board envelope to its owning Pi session using the host's authenticated transport |
12
+ | `commitDirectory(own, directory, caller, request)` | Apply a validated member registration or removal and persist the resulting directory |
13
+ | `routeNotice(ctx, request, signal)` | Route a notice toward the named member without waking an idle agent |
14
+ | `propagateEnabled(ctx, enabled)` | Forward the root's enablement change to its children |
15
+ | `briefing(member, population)` | Optional host-specific board guidance |
16
+
17
+ The transport receiver calls `runtime.handle(ctx, envelope, signal)`. Normal board operations use `runtime.execute(ctx, input, requestId)`. Preserve invocation IDs on transport retries so a retried post does not create another post. Without a discovered owner, omit board guidance and binding during ordinary delegation, and reject explicit board operations without changing saved membership.
18
+
19
+ The runtime owns request validation, storage, tool registration, settings, subscriptions, current-turn notification checks and model-visible board results. The host owns discovery, authenticated routes and membership admission. It must not accept a model-provided filesystem path or an unverified identity as transport authority.
20
+
21
+ Bindings retain board, root-session and member-session IDs, an agent path, the owner folder, the database path, enablement and an optional upstream route. Agent names use `/root` and child paths. The upstream route is opaque to the runtime. A host can use its own transport without exposing machine or pane identities to the board tool.
22
+
23
+ Shepherdr's adapter is in `pi-shepherdr/src/board`. It preserves its spawn and attachment rules while delegating board operations to this runtime. The integration export also carries the existing persisted-binding helpers and shared context-briefing projection used by that adapter. They do not create a second owner.
24
+
25
+ ## Compatibility
26
+
27
+ Keep schema-v1 archives at their existing paths and preserve saved `shepherdr-board-*` records. Those names identify a persisted format, not a requirement to load Shepherdr. Never rebind a resumed member by inventing a fresh root board.
28
+
29
+ Only one transport adapter may attach to a runtime. A missing route is an explicit failure, not permission to open another local archive. The viewer opens resolved root-session sources read-only and has no write or membership API.
30
+
31
+ PCC integration is discovered separately. Its absence leaves the native Pi tool available. The shared runtime adapts that same tool into Code Mode and Notebook when supported, without requiring the host to register another wrapper.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Igor Warzocha
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,17 @@
1
+ # Optional PCC integration
2
+
3
+ [Agent Comms](README.md) provides Notes and Board. This contract covers its Notes feature.
4
+
5
+ Notes owns its four tools, local storage, family sharing, checkpoint policy and context windows. PCC is optional. Without Notes, PCC provides ordinary Pi and native provider compaction without notes tools.
6
+
7
+ Notes uses PCC's public `code-mode`, `prompt-mode` and `developer-messages` exports. Code and Notebook promote Notes' compact discovery entry and routing guidance. History remains deferred. Notes' own on-demand help describes its result fields. `new_context` remains a sequential model-only tool, never a nested call. Freshness uses persisted Notes receipts and completed tool outcomes, including generic nested-call evidence through exec and wait.
8
+
9
+ Notes declares Pi's `outputSchema` and returns its canonical payload as `structuredContent`. Pi's built-in codemode, Code and Notebook receive the same object without parsing display text. Native model-facing text remains unchanged. Shared reads preserve structured paths and availability warnings.
10
+
11
+ Returned kickoff messages are annotated for developer-role delivery, not sent during preparation. Other models retain ordinary Pi custom messages. Context projection remains active for saved retirement boundaries even when Notes is disabled for the selected model.
12
+
13
+ Notes owns automatic read-only hybrid note retrieval and its response cache. History reads Pi JSONL sessions, without backend lookup or protected delivery. PCC supplies provider authentication and generic protected-output delivery for encrypted notes. `canDeliverProtectedOutput(pi, ctx)` checks the active delivery capability, not merely whether the PCC package is installed. JavaScript receives ordinary values for plaintext results and receipts for encrypted notes while compatible provider requests receive the original encrypted blocks. Neither package decrypts them locally. Cached data retains account and backend provenance.
14
+
15
+ The optional `pi-notes-compaction:owner:v1` discovery channel exposes Notes identity, sharing and projection to consumers such as Suggestions. It does not transfer tool registration or session authority. PCC may check this channel for Notes availability during upgrade admission. Normal turn context delivery uses ordinary Pi context hooks. Notes registers read-only branch projection through PCC's public `compaction` export for isolated consumers such as voice summarisation.
16
+
17
+ Pi owns session lifecycle. Notes decides when to request or cancel compaction. PCC implements the selected provider compaction method and respects context changes from extensions. Neither extension replaces another extension's preparation.
package/README.md CHANGED
@@ -1,3 +1,54 @@
1
- # Temporary Holding Version
1
+ # Pi Agent Comms
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Keep checkpoints and searchable session history across fresh context windows, and share discussions through agent boards. Notes and Board work independently with any Pi model. Shepherdr can connect agent families and remote sessions; Pi Codex Conversion adds Code Mode, Notebook and compatible encrypted notes delivery. Neither is required for standalone use.
4
+
5
+ ## Install
6
+
7
+ Requires Pi 1.5.0 or newer and Node.js 22.18 or newer.
8
+
9
+ Agent Comms is the combined alternative to the maintained standalone [Notes Compaction](../pi-notes-compaction) and [Agent Board](../pi-agent-board) packages. All three receive shared implementation improvements. The standalone packages are not deprecated.
10
+
11
+ Agent Comms is available on the `@dev` preview channel only. Shepherdr sharing requires its `@core` preview channel. Stable Shepherdr users should keep the standalone Notes Compaction and Agent Board packages.
12
+
13
+ Choose Agent Comms for both features in one package, or keep the standalone packages. Do not load Agent Comms alongside either standalone extension. To switch to Agent Comms:
14
+
15
+ ```sh
16
+ pi remove npm:@howaboua/pi-notes-compaction
17
+ pi remove npm:@howaboua/pi-agent-board
18
+ pi install npm:@howaboua/pi-agent-comms@dev
19
+ ```
20
+
21
+ For a source checkout, install from the repository root:
22
+
23
+ ```sh
24
+ bun install
25
+ bun run --cwd packages/pi-agent-comms build
26
+ pi install ./packages/pi-agent-comms
27
+ ```
28
+
29
+ Remove direct loads of the standalone extensions too. Update participating sessions together and reload Pi.
30
+
31
+ Existing notes, history, settings, model roles, board archives, subscriptions, viewer configuration and session records continue without an import. Their storage locations and persisted identifiers stay unchanged. No database or session-file rename is needed.
32
+
33
+ ## Use
34
+
35
+ - `/notes` opens the Notes tab. Ask the agent to save a checkpoint, then start a new context window. The `notes`, `history`, `new_context` and `get_context_remaining` tools retain their existing behaviour.
36
+ - `/board` opens the Board tab. Ask the agent to post a discussion, then choose **Open viewer** to read it in your browser. The viewer starts only on demand.
37
+ - Tab or Shift-Tab switches between Notes and Board. `/board settings` remains an alias for the Board tab.
38
+ - `/roles` opens Notes' model roles subview, also available through **Model roles** in Notes.
39
+
40
+ Notes defaults to **All models**. Its **Active** setting also offers **Whitelist** and **Off**. Board defaults to on and retains `/board on|off [session|folder|global]` and `/board status`. Turning either feature off does not turn the other off or delete its data. Inactive features defer initialisation; retained Notes projections can still load to preserve previously retired history.
41
+
42
+ ## Guides
43
+
44
+ - [Notes](docs/NOTES.md): checkpoints, history, rollover, model roles, activation and optional remote lookup
45
+ - [Board](docs/BOARD.md): discussions, summaries, enablement, archives and browser access
46
+ - [Host integration](INTEGRATION.md): Board membership and routing
47
+ - [Optional PCC integration](PCC-INTEGRATION.md): Notes and provider capabilities
48
+ - [Extension APIs](../../docs/extension-apis.md): public imports and integration lifecycles
49
+
50
+ Earlier release history remains in the [Notes changelog](docs/NOTES-CHANGELOG.md) and [Board changelog](docs/BOARD-CHANGELOG.md).
51
+
52
+ ## License
53
+
54
+ MIT
@@ -0,0 +1,249 @@
1
+ import { statSync } from "node:fs";
2
+ import { DatabaseSync, } from "node:sqlite";
3
+ import { caseFold } from "unicode-case-folding";
4
+ function text(row, key) {
5
+ const value = row[key];
6
+ if (typeof value !== "string")
7
+ throw new Error(`Invalid board archive field: ${key}`);
8
+ return value;
9
+ }
10
+ function count(row, key) {
11
+ const value = row[key];
12
+ if (typeof value !== "number" || !Number.isSafeInteger(value))
13
+ throw new Error(`Invalid board archive count: ${key}`);
14
+ return value;
15
+ }
16
+ function timestamp(row, key) {
17
+ return new Date(text(row, key)).toISOString().slice(0, 16) + "Z";
18
+ }
19
+ function nullableTimestamp(row, key) {
20
+ return row[key] === null ? null : timestamp(row, key);
21
+ }
22
+ function post(row) {
23
+ return {
24
+ id: text(row, "id"),
25
+ channel: text(row, "channel"),
26
+ author: text(row, "author"),
27
+ createdAt: timestamp(row, "created_at"),
28
+ text: text(row, "text"),
29
+ };
30
+ }
31
+ /** The archive is opened read-only; no migrations, board creation or subscriptions. */
32
+ export class Archive {
33
+ db;
34
+ source;
35
+ constructor(source) {
36
+ this.source = source;
37
+ try {
38
+ statSync(source.databasePath);
39
+ }
40
+ catch (error) {
41
+ if (error instanceof Error && "code" in error && error.code === "ENOENT")
42
+ return;
43
+ throw error;
44
+ }
45
+ const db = new DatabaseSync(source.databasePath, { readOnly: true });
46
+ try {
47
+ db.exec("PRAGMA busy_timeout=2000; PRAGMA query_only=ON; BEGIN");
48
+ if (db.prepare("PRAGMA user_version").get()?.["user_version"] !== 1)
49
+ throw new Error("Unsupported board archive version");
50
+ this.db = db;
51
+ }
52
+ catch (error) {
53
+ db.close();
54
+ throw error;
55
+ }
56
+ }
57
+ close() {
58
+ this.db?.close();
59
+ }
60
+ all(sql, ...args) {
61
+ return this.db?.prepare(sql).all(...args) ?? [];
62
+ }
63
+ hasTable(name) {
64
+ return (this.all("SELECT name FROM sqlite_master WHERE type='table' AND name=?", name).length > 0);
65
+ }
66
+ status(id, threadId) {
67
+ if (!this.hasTable("thread_statuses"))
68
+ return "open";
69
+ const value = this.all("SELECT status FROM thread_statuses WHERE board_id=? AND thread_id=?", id, threadId)[0]?.["status"];
70
+ return value === "completed" || value === "abandoned" ? value : "open";
71
+ }
72
+ summary(id, threadId) {
73
+ if (!this.hasTable("thread_summaries"))
74
+ return null;
75
+ const row = this.all(`SELECT s.*, EXISTS(SELECT 1 FROM posts p WHERE p.board_id=s.board_id AND p.root=s.thread_id
76
+ 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
77
+ FROM thread_summaries s WHERE s.board_id=? AND s.thread_id=?`, id, threadId)[0];
78
+ return row
79
+ ? {
80
+ text: text(row, "text"),
81
+ createdAt: timestamp(row, "created_at"),
82
+ throughMessageId: text(row, "through_message_id"),
83
+ hasNewerPosts: count(row, "has_newer_posts") === 1,
84
+ provider: text(row, "provider"),
85
+ model: text(row, "model"),
86
+ reasoning: text(row, "reasoning"),
87
+ }
88
+ : null;
89
+ }
90
+ index() {
91
+ const { databasePath: _path, ...context } = this.source;
92
+ const boards = this.all(`SELECT b.board_id,b.root_session_id,b.created_at,
93
+ (SELECT created_at FROM posts WHERE board_id=b.board_id ORDER BY seq DESC LIMIT 1) AS last_activity,
94
+ (SELECT COUNT(*) FROM channels WHERE board_id=b.board_id) AS channels,
95
+ (SELECT COUNT(*) FROM posts WHERE board_id=b.board_id) AS posts,
96
+ (SELECT COUNT(DISTINCT author) FROM posts WHERE board_id=b.board_id) AS agents
97
+ FROM boards b WHERE owner_folder=? ORDER BY substr(COALESCE(last_activity,b.created_at),1,16) DESC,(SELECT MAX(seq) FROM posts WHERE board_id=b.board_id) DESC,b.board_id DESC`, this.source.folder).map((row) => ({
98
+ id: text(row, "board_id"),
99
+ rootSessionId: text(row, "root_session_id"),
100
+ createdAt: timestamp(row, "created_at"),
101
+ lastActivity: nullableTimestamp(row, "last_activity"),
102
+ channels: count(row, "channels"),
103
+ posts: count(row, "posts"),
104
+ agents: count(row, "agents"),
105
+ }));
106
+ if (!boards.some((board) => board.id === context.boardId))
107
+ boards.unshift({
108
+ id: context.boardId,
109
+ rootSessionId: context.sessionId,
110
+ createdAt: null,
111
+ lastActivity: null,
112
+ channels: 0,
113
+ posts: 0,
114
+ agents: 0,
115
+ });
116
+ return { context, boards };
117
+ }
118
+ board(id) {
119
+ const board = this.index().boards.find((board) => board.id === id);
120
+ if (!board)
121
+ throw new Error("Board not found in this folder");
122
+ return board;
123
+ }
124
+ detail(id) {
125
+ const board = this.board(id);
126
+ const channels = this.all(`SELECT c.name,c.author,c.created_at,COUNT(p.id) AS posts,
127
+ COUNT(CASE WHEN p.id=p.root THEN 1 END) AS threads,
128
+ (SELECT created_at FROM posts latest WHERE latest.board_id=c.board_id AND latest.channel=c.name ORDER BY seq DESC LIMIT 1) AS last_activity
129
+ FROM channels c LEFT JOIN posts p ON p.board_id=c.board_id AND p.channel=c.name
130
+ WHERE c.board_id=? GROUP BY c.name ORDER BY substr(COALESCE(last_activity,c.created_at),1,16) DESC,MAX(p.seq) DESC,c.name`, id).map((row) => ({
131
+ name: text(row, "name"),
132
+ author: text(row, "author"),
133
+ createdAt: timestamp(row, "created_at"),
134
+ posts: count(row, "posts"),
135
+ threads: count(row, "threads"),
136
+ lastActivity: nullableTimestamp(row, "last_activity"),
137
+ }));
138
+ const agents = this.all(`SELECT author,COUNT(*) AS posts,
139
+ (SELECT created_at FROM posts latest WHERE latest.board_id=p.board_id AND latest.author=p.author ORDER BY seq DESC LIMIT 1) AS last_activity
140
+ FROM posts p WHERE board_id=? GROUP BY author ORDER BY posts DESC,author`, id).map((row) => ({
141
+ name: text(row, "author"),
142
+ posts: count(row, "posts"),
143
+ lastActivity: timestamp(row, "last_activity"),
144
+ }));
145
+ const subscriptions = this.all("SELECT target,agent,enabled FROM subscriptions WHERE board_id=? ORDER BY target,agent", id).map((row) => ({
146
+ target: text(row, "target"),
147
+ agent: text(row, "agent"),
148
+ enabled: count(row, "enabled") === 1,
149
+ }));
150
+ return { board, channels, agents, subscriptions };
151
+ }
152
+ threads(id, params) {
153
+ this.board(id);
154
+ const channel = params.get("channel");
155
+ const query = params.get("q");
156
+ const author = params.get("author");
157
+ const summaries = this.hasTable("thread_summaries") && params.get("full") !== "true";
158
+ if (query && query.length > 1000)
159
+ throw new Error("Search is too long");
160
+ const where = ["r.board_id=?", "r.id=r.root"];
161
+ const args = [id];
162
+ if (channel !== null) {
163
+ where.push("r.channel=?");
164
+ args.push(channel);
165
+ }
166
+ if (query || author) {
167
+ const match = ["m.board_id=r.board_id", "m.root=r.id"];
168
+ if (query) {
169
+ match.push("instr(m.body_search,?)>0");
170
+ args.push(caseFold(query));
171
+ }
172
+ if (author) {
173
+ match.push("m.author=?");
174
+ args.push(author);
175
+ }
176
+ const originals = `EXISTS(SELECT 1 FROM posts m WHERE ${match.join(" AND ")})`;
177
+ if (summaries) {
178
+ const summaryMatch = ["s.board_id=r.board_id", "s.thread_id=r.id"];
179
+ if (query) {
180
+ summaryMatch.push("instr(s.body_search,?)>0");
181
+ args.push(caseFold(query));
182
+ }
183
+ if (author) {
184
+ summaryMatch.push("EXISTS(SELECT 1 FROM posts a WHERE a.board_id=r.board_id AND a.root=r.id AND a.author=?)");
185
+ args.push(author);
186
+ }
187
+ where.push(`((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 ")}))`);
188
+ }
189
+ else
190
+ where.push(originals);
191
+ }
192
+ const cursor = this.cursor(params);
193
+ const rows = this.all(`SELECT r.id,r.channel,r.author,r.text,r.created_at,
194
+ (SELECT created_at FROM posts latest WHERE latest.board_id=r.board_id AND latest.root=r.id ORDER BY seq DESC LIMIT 1) AS last_activity,
195
+ MAX(p.seq) AS last_seq,COUNT(*)-1 AS replies
196
+ FROM posts r JOIN posts p ON p.board_id=r.board_id AND p.root=r.id
197
+ WHERE ${where.join(" AND ")} GROUP BY r.id HAVING MAX(p.seq)<? ORDER BY last_seq DESC LIMIT 41`, ...args, cursor ?? Number.MAX_SAFE_INTEGER);
198
+ const visible = rows.slice(0, 40);
199
+ const last = visible.at(-1);
200
+ return {
201
+ threads: visible.map((row) => {
202
+ const threadId = text(row, "id");
203
+ const summary = this.summary(id, threadId);
204
+ return {
205
+ status: this.status(id, threadId),
206
+ summarized: summary !== null,
207
+ id: threadId,
208
+ channel: text(row, "channel"),
209
+ author: text(row, "author"),
210
+ preview: (params.get("full") === "true"
211
+ ? text(row, "text")
212
+ : (summary?.text ?? text(row, "text"))).slice(0, 600),
213
+ createdAt: timestamp(row, "created_at"),
214
+ lastActivity: timestamp(row, "last_activity"),
215
+ replies: count(row, "replies"),
216
+ };
217
+ }),
218
+ nextCursor: rows.length > 40 && last ? String(count(last, "last_seq")) : null,
219
+ };
220
+ }
221
+ thread(id, threadId, params) {
222
+ this.board(id);
223
+ const root = this.all("SELECT id,channel,author,created_at,text FROM posts WHERE board_id=? AND id=? AND root=id", id, threadId)[0];
224
+ if (!root)
225
+ throw new Error("Thread not found in this board");
226
+ const summary = this.summary(id, threadId);
227
+ const status = this.status(id, threadId);
228
+ if (summary && params.get("full") !== "true")
229
+ return { status, summary, root: null, replies: [], nextCursor: null };
230
+ const rows = this.all("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", id, threadId, this.cursor(params) ?? 0);
231
+ const visible = rows.slice(0, 80);
232
+ const last = visible.at(-1);
233
+ return {
234
+ status,
235
+ summary,
236
+ root: post(root),
237
+ replies: visible.map(post),
238
+ nextCursor: rows.length > 80 && last ? String(count(last, "seq")) : null,
239
+ };
240
+ }
241
+ cursor(params) {
242
+ const value = params.get("cursor");
243
+ if (value === null)
244
+ return undefined;
245
+ if (!/^[0-9]+$/.test(value) || !Number.isSafeInteger(Number(value)))
246
+ throw new Error("Invalid page cursor");
247
+ return Number(value);
248
+ }
249
+ }
@@ -0,0 +1,85 @@
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
+ export function stateDirectory() {
6
+ return join(process.env["PI_CODING_AGENT_DIR"] || join(homedir(), ".pi", "agent"), "board-viewer");
7
+ }
8
+ function configPath() {
9
+ return join(stateDirectory(), "config.json");
10
+ }
11
+ export async function loadConfig() {
12
+ let value;
13
+ try {
14
+ value = JSON.parse(await readFile(configPath(), "utf8"));
15
+ }
16
+ catch (error) {
17
+ if (!(error instanceof Error && "code" in error && error.code === "ENOENT"))
18
+ throw error;
19
+ value = {};
20
+ }
21
+ if (!value || typeof value !== "object" || Array.isArray(value))
22
+ throw new Error("Viewer config must be an object");
23
+ const config = value;
24
+ const host = config["host"] ?? "127.0.0.1";
25
+ const port = config["port"] ?? 47984;
26
+ if (typeof host !== "string" || !["127.0.0.1", "0.0.0.0"].includes(host))
27
+ throw new Error("Viewer host must be 127.0.0.1 or 0.0.0.0");
28
+ if (typeof port !== "number" ||
29
+ !Number.isInteger(port) ||
30
+ port < 1024 ||
31
+ port > 65535)
32
+ throw new Error("Viewer port must be an integer from 1024 to 65535");
33
+ const publicUrl = config["publicUrl"] ?? `http://127.0.0.1:${port}`;
34
+ if (typeof publicUrl !== "string")
35
+ throw new Error("Viewer publicUrl must be an HTTP or HTTPS origin");
36
+ const url = new URL(publicUrl);
37
+ if (!["http:", "https:"].includes(url.protocol) ||
38
+ url.username ||
39
+ url.password ||
40
+ url.pathname !== "/" ||
41
+ url.search ||
42
+ url.hash)
43
+ throw new Error("Viewer publicUrl must be an HTTP or HTTPS origin without a path");
44
+ const command = config["openCommand"];
45
+ if (command !== undefined &&
46
+ command !== null &&
47
+ (!Array.isArray(command) ||
48
+ !command.length ||
49
+ !command.every((part) => typeof part === "string" && part.length > 0)))
50
+ throw new Error("Viewer openCommand must be an argument array, or null for link only");
51
+ const defaultCommand = process.platform === "darwin"
52
+ ? ["open"]
53
+ : process.platform === "win32"
54
+ ? ["rundll32", "url.dll,FileProtocolHandler"]
55
+ : ["xdg-open"];
56
+ return {
57
+ host,
58
+ port,
59
+ publicUrl: url.origin,
60
+ openCommand: command === null
61
+ ? null
62
+ : command === undefined
63
+ ? defaultCommand
64
+ : command,
65
+ };
66
+ }
67
+ export async function accessKey() {
68
+ const directory = stateDirectory();
69
+ await mkdir(directory, { recursive: true, mode: 0o700 });
70
+ const path = join(directory, "access-key");
71
+ try {
72
+ await writeFile(path, randomBytes(32).toString("hex"), {
73
+ flag: "wx",
74
+ mode: 0o600,
75
+ });
76
+ }
77
+ catch (error) {
78
+ if (!(error instanceof Error && "code" in error && error.code === "EEXIST"))
79
+ throw error;
80
+ }
81
+ const key = (await readFile(path, "utf8")).trim();
82
+ if (!/^[a-f0-9]{64}$/.test(key))
83
+ throw new Error("Invalid viewer access key; remove the access-key file and restart the viewer");
84
+ return key;
85
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,177 @@
1
+ import { randomBytes, timingSafeEqual } from "node:crypto";
2
+ import { readFile } from "node:fs/promises";
3
+ import { createServer, } from "node:http";
4
+ import { pathToFileURL } from "node:url";
5
+ import { Archive } from "./archive.js";
6
+ import { accessKey, loadConfig } from "./config.js";
7
+ import { parseSource } from "./source.js";
8
+ export const PROTOCOL = "pi-board-viewer/1";
9
+ const assets = new Map([
10
+ ["/", ["web/index.html", "text/html; charset=utf-8"]],
11
+ ["/app.js", ["web/app.js", "text/javascript; charset=utf-8"]],
12
+ ["/session.js", ["web/session.js", "text/javascript; charset=utf-8"]],
13
+ ["/posts.js", ["web/posts.js", "text/javascript; charset=utf-8"]],
14
+ ["/render.js", ["web/render.js", "text/javascript; charset=utf-8"]],
15
+ ["/navigation.js", ["web/navigation.js", "text/javascript; charset=utf-8"]],
16
+ ["/updates.js", ["web/updates.js", "text/javascript; charset=utf-8"]],
17
+ ["/style.css", ["web/style.css", "text/css; charset=utf-8"]],
18
+ [
19
+ "/vendor/marked.js",
20
+ [import.meta.resolve("marked"), "text/javascript; charset=utf-8"],
21
+ ],
22
+ [
23
+ "/vendor/purify.js",
24
+ [import.meta.resolve("dompurify"), "text/javascript; charset=utf-8"],
25
+ ],
26
+ ]);
27
+ function authenticated(req, secret) {
28
+ const value = req.headers.authorization;
29
+ if (!value?.startsWith("Bearer "))
30
+ return false;
31
+ const provided = Buffer.from(value.slice(7));
32
+ const expected = Buffer.from(secret);
33
+ return (provided.length === expected.length && timingSafeEqual(provided, expected));
34
+ }
35
+ async function body(req) {
36
+ const chunks = [];
37
+ let length = 0;
38
+ for await (const chunk of req) {
39
+ const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
40
+ length += bytes.length;
41
+ if (length > 16_384)
42
+ throw new Error("Viewer request is too large");
43
+ chunks.push(bytes);
44
+ }
45
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
46
+ }
47
+ function json(res, status, value) {
48
+ res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
49
+ res.end(JSON.stringify(value));
50
+ }
51
+ export async function startServer(config, key) {
52
+ const views = new Map();
53
+ const registered = new Map();
54
+ const server = createServer((req, res) => {
55
+ res.setHeader("Cache-Control", "no-store");
56
+ res.setHeader("Referrer-Policy", "no-referrer");
57
+ res.setHeader("X-Content-Type-Options", "nosniff");
58
+ res.setHeader("Content-Security-Policy", "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'");
59
+ void handle(req, res).catch((error) => {
60
+ if (res.headersSent) {
61
+ res.destroy();
62
+ return;
63
+ }
64
+ json(res, 400, {
65
+ error: error instanceof Error ? error.message : "Viewer request failed",
66
+ });
67
+ });
68
+ });
69
+ server.headersTimeout = 10_000;
70
+ server.requestTimeout = 10_000;
71
+ server.maxHeadersCount = 50;
72
+ async function handle(req, res) {
73
+ const url = new URL(req.url ?? "/", "http://localhost");
74
+ if (req.method === "GET" && url.pathname === "/api/health") {
75
+ json(res, 200, {
76
+ protocol: PROTOCOL,
77
+ host: config.host,
78
+ publicUrl: config.publicUrl,
79
+ pid: process.pid,
80
+ });
81
+ return;
82
+ }
83
+ if (req.method === "POST" && url.pathname === "/api/open") {
84
+ // Only the local extension may register filesystem sources. View links cannot.
85
+ if (req.socket.remoteAddress !== "127.0.0.1" ||
86
+ !authenticated(req, key)) {
87
+ json(res, 403, {
88
+ error: "Only the local Pi extension can open a board archive",
89
+ });
90
+ return;
91
+ }
92
+ const source = parseSource(await body(req));
93
+ const archive = new Archive(source);
94
+ try {
95
+ archive.index();
96
+ }
97
+ finally {
98
+ archive.close();
99
+ }
100
+ const identity = JSON.stringify(source);
101
+ const token = registered.get(identity) ?? randomBytes(32).toString("hex");
102
+ registered.set(identity, token);
103
+ views.set(token, source);
104
+ json(res, 200, { url: `${config.publicUrl}/#view=${token}` });
105
+ return;
106
+ }
107
+ if (req.method !== "GET") {
108
+ json(res, 405, { error: "The board viewer is read-only" });
109
+ return;
110
+ }
111
+ if (url.pathname.startsWith("/api/")) {
112
+ const token = req.headers.authorization?.replace(/^Bearer /, "") ?? "";
113
+ const source = views.get(token);
114
+ if (!source) {
115
+ json(res, 401, {
116
+ error: "This viewer link has expired. Run /board in Pi for a new link.",
117
+ });
118
+ return;
119
+ }
120
+ const archive = new Archive(source);
121
+ try {
122
+ const board = url.searchParams.get("boardId") ?? source.boardId;
123
+ let result;
124
+ switch (url.pathname) {
125
+ case "/api/boards":
126
+ result = archive.index();
127
+ break;
128
+ case "/api/board":
129
+ result = archive.detail(board);
130
+ break;
131
+ case "/api/threads":
132
+ result = archive.threads(board, url.searchParams);
133
+ break;
134
+ case "/api/thread":
135
+ result = archive.thread(board, url.searchParams.get("id") ?? "", url.searchParams);
136
+ break;
137
+ default:
138
+ json(res, 404, { error: "Unknown viewer request" });
139
+ return;
140
+ }
141
+ json(res, 200, result);
142
+ }
143
+ finally {
144
+ archive.close();
145
+ }
146
+ return;
147
+ }
148
+ const asset = assets.get(url.pathname);
149
+ if (!asset) {
150
+ json(res, 404, { error: "Page not found" });
151
+ return;
152
+ }
153
+ const content = await readFile(new URL(asset[0], import.meta.url));
154
+ res.writeHead(200, { "Content-Type": asset[1] });
155
+ res.end(content);
156
+ }
157
+ await new Promise((resolve, reject) => {
158
+ server.once("error", reject);
159
+ server.listen(config.port, config.host, () => {
160
+ server.removeListener("error", reject);
161
+ resolve();
162
+ });
163
+ });
164
+ return server;
165
+ }
166
+ if (process.argv[1] &&
167
+ import.meta.url === pathToFileURL(process.argv[1]).href) {
168
+ const config = await loadConfig();
169
+ const server = await startServer(config, await accessKey());
170
+ console.log(`Board viewer listening on ${config.host}:${config.port} (PID ${process.pid})`);
171
+ const stop = () => {
172
+ server.close();
173
+ server.closeAllConnections();
174
+ };
175
+ process.once("SIGTERM", stop);
176
+ process.once("SIGINT", stop);
177
+ }