@bigmistqke/whiteboard 0.0.0-stage → 0.2.0

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 (158) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +628 -2
  3. package/bin/whiteboard.ts +488 -0
  4. package/dist/_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/taggedTemplateLiteral.js +5 -0
  5. package/dist/bin/whiteboard.js +542 -0
  6. package/dist/client/runtime.js +544 -0
  7. package/dist/define.js +7 -0
  8. package/dist/plugins/callout/README.md +13 -0
  9. package/dist/plugins/callout/index.js +27 -0
  10. package/dist/plugins/callout/style.css +12 -0
  11. package/dist/plugins/chat/README.md +46 -0
  12. package/dist/plugins/chat/client.js +3 -0
  13. package/dist/plugins/chat/index.js +47 -0
  14. package/dist/plugins/chat/style.css +24 -0
  15. package/dist/plugins/claude-code/index.js +120 -0
  16. package/dist/plugins/code/README.md +42 -0
  17. package/dist/plugins/code/diff.js +65 -0
  18. package/dist/plugins/code/index.js +77 -0
  19. package/dist/plugins/code/style.css +29 -0
  20. package/dist/plugins/comments/client.js +10 -0
  21. package/dist/plugins/comments/index.js +54 -0
  22. package/dist/plugins/comments/style.css +40 -0
  23. package/dist/plugins/details/README.md +17 -0
  24. package/dist/plugins/details/index.js +17 -0
  25. package/dist/plugins/details/style.css +3 -0
  26. package/dist/plugins/forge/README.md +12 -0
  27. package/dist/plugins/forge/index.js +83 -0
  28. package/dist/plugins/form/README.md +111 -0
  29. package/dist/plugins/form/index.js +102 -0
  30. package/dist/plugins/form/style.css +41 -0
  31. package/dist/plugins/gallery/README.md +30 -0
  32. package/dist/plugins/gallery/client.js +1 -0
  33. package/dist/plugins/gallery/index.js +74 -0
  34. package/dist/plugins/gallery/style.css +27 -0
  35. package/dist/plugins/grid/README.md +33 -0
  36. package/dist/plugins/grid/index.js +33 -0
  37. package/dist/plugins/grid/style.css +25 -0
  38. package/dist/plugins/iframe/README.md +18 -0
  39. package/dist/plugins/iframe/client.js +1 -0
  40. package/dist/plugins/iframe/index.js +40 -0
  41. package/dist/plugins/iframe/style.css +29 -0
  42. package/dist/plugins/index.js +30 -0
  43. package/dist/plugins/mermaid/README.md +21 -0
  44. package/dist/plugins/mermaid/index.js +35 -0
  45. package/dist/plugins/mermaid/style.css +16 -0
  46. package/dist/plugins/quiet/README.md +26 -0
  47. package/dist/plugins/quiet/index.js +17 -0
  48. package/dist/plugins/terminal/client.js +41 -0
  49. package/dist/plugins/terminal/host.js +332 -0
  50. package/dist/plugins/terminal/index.js +171 -0
  51. package/dist/plugins/terminal/modes.js +32 -0
  52. package/dist/plugins/terminal/server.js +256 -0
  53. package/dist/plugins/terminal/sizes.js +57 -0
  54. package/dist/plugins/terminal/style.css +357 -0
  55. package/dist/solid/index.js +36 -0
  56. package/dist/src/auth.js +54 -0
  57. package/dist/src/client/page/base.css +295 -0
  58. package/dist/src/client/page/main.js +1228 -0
  59. package/dist/src/config.js +76 -0
  60. package/dist/src/events.js +183 -0
  61. package/dist/src/html.js +34 -0
  62. package/dist/src/icons.js +6 -0
  63. package/dist/src/load.js +77 -0
  64. package/dist/src/loader.js +126 -0
  65. package/dist/src/package.js +33 -0
  66. package/dist/src/pages/blocks.js +50 -0
  67. package/dist/src/pages/index.js +15 -0
  68. package/dist/src/pages/markdown.js +410 -0
  69. package/dist/src/pages/render.js +311 -0
  70. package/dist/src/plugins.js +238 -0
  71. package/dist/src/running.js +24 -0
  72. package/dist/src/serve.js +71 -0
  73. package/dist/src/server.js +725 -0
  74. package/dist/src/status.js +71 -0
  75. package/package.json +131 -4
  76. package/plugins/callout/README.md +13 -0
  77. package/plugins/callout/index.ts +25 -0
  78. package/plugins/callout/style.css +12 -0
  79. package/plugins/chat/README.md +46 -0
  80. package/plugins/chat/autosize.ts +101 -0
  81. package/plugins/chat/client.tsx +93 -0
  82. package/plugins/chat/index.ts +61 -0
  83. package/plugins/chat/style.css +24 -0
  84. package/plugins/claude-code/index.ts +136 -0
  85. package/plugins/code/README.md +42 -0
  86. package/plugins/code/diff.ts +64 -0
  87. package/plugins/code/index.ts +94 -0
  88. package/plugins/code/style.css +29 -0
  89. package/plugins/comments/client.ts +492 -0
  90. package/plugins/comments/index.ts +54 -0
  91. package/plugins/comments/style.css +40 -0
  92. package/plugins/details/README.md +17 -0
  93. package/plugins/details/index.ts +21 -0
  94. package/plugins/details/style.css +3 -0
  95. package/plugins/forge/README.md +12 -0
  96. package/plugins/forge/index.ts +71 -0
  97. package/plugins/form/README.md +111 -0
  98. package/plugins/form/index.ts +104 -0
  99. package/plugins/form/style.css +41 -0
  100. package/plugins/gallery/README.md +30 -0
  101. package/plugins/gallery/client.tsx +64 -0
  102. package/plugins/gallery/index.ts +67 -0
  103. package/plugins/gallery/style.css +27 -0
  104. package/plugins/grid/README.md +33 -0
  105. package/plugins/grid/index.ts +36 -0
  106. package/plugins/grid/style.css +25 -0
  107. package/plugins/iframe/README.md +18 -0
  108. package/plugins/iframe/client.ts +46 -0
  109. package/plugins/iframe/index.ts +54 -0
  110. package/plugins/iframe/style.css +29 -0
  111. package/plugins/index.ts +21 -0
  112. package/plugins/mermaid/README.md +21 -0
  113. package/plugins/mermaid/index.ts +40 -0
  114. package/plugins/mermaid/style.css +16 -0
  115. package/plugins/quiet/README.md +26 -0
  116. package/plugins/quiet/index.ts +27 -0
  117. package/plugins/terminal/client.ts +317 -0
  118. package/plugins/terminal/host.ts +326 -0
  119. package/plugins/terminal/index.ts +138 -0
  120. package/plugins/terminal/modes.ts +30 -0
  121. package/plugins/terminal/server.ts +215 -0
  122. package/plugins/terminal/sizes.ts +60 -0
  123. package/plugins/terminal/style.css +71 -0
  124. package/skills/whiteboard/SKILL.md +302 -0
  125. package/solid/index.tsx +59 -0
  126. package/src/auth.ts +66 -0
  127. package/src/client/forms.ts +185 -0
  128. package/src/client/markdown.ts +36 -0
  129. package/src/client/page/base.css +295 -0
  130. package/src/client/page/elsewhere.ts +70 -0
  131. package/src/client/page/fresh.ts +205 -0
  132. package/src/client/page/live.ts +30 -0
  133. package/src/client/page/main.ts +272 -0
  134. package/src/client/page/orphans.ts +46 -0
  135. package/src/client/page/sort.ts +38 -0
  136. package/src/client/page/theme.ts +32 -0
  137. package/src/client/page/view.ts +9 -0
  138. package/src/client/page/waiting.ts +182 -0
  139. package/src/client/read.ts +73 -0
  140. package/src/client/runtime.ts +183 -0
  141. package/src/client/toast.ts +25 -0
  142. package/src/config.ts +96 -0
  143. package/src/define.ts +612 -0
  144. package/src/events.ts +218 -0
  145. package/src/html.ts +40 -0
  146. package/src/icons.ts +8 -0
  147. package/src/load.ts +89 -0
  148. package/src/loader.ts +112 -0
  149. package/src/package.ts +39 -0
  150. package/src/pages/blocks.ts +70 -0
  151. package/src/pages/index.ts +42 -0
  152. package/src/pages/markdown.ts +364 -0
  153. package/src/pages/render.ts +233 -0
  154. package/src/plugins.ts +197 -0
  155. package/src/running.ts +22 -0
  156. package/src/serve.ts +52 -0
  157. package/src/server.ts +667 -0
  158. package/src/status.ts +113 -0
package/src/server.ts ADDED
@@ -0,0 +1,667 @@
1
+ // The server of one project, as a request handler: `createServer(project)` gives one, and
2
+ // `start` in serve.ts makes it listen on a port. Nothing happens on import, and a server's state
3
+ // (listeners, open pages, watchers) lives in it, so tests can make one for a throwaway project and
4
+ // send it requests.
5
+ //
6
+ // / the overview: the project's pages
7
+ // /<page> a page from .whiteboard/pages/<page>.md
8
+ // /-/<path> a file of the project, from the repository (unless the config sets files: false)
9
+ // /_/docs how to write pages here: markdown, and each plugin's docs
10
+ // /_/file/<path> a file a plugin asked to serve (its client, a stylesheet)
11
+ // /_/auth sets the project's token as a cookie (see auth.ts)
12
+ // /api/<ext>/… a plugin's own routes (see Plugin in define.ts)
13
+ // /api/… the stored page, its render, events, live changes
14
+ //
15
+ // The core reads pages as they are stored and renders them as markdown, with the blocks the project's
16
+ // plugins bring (pages.ts). When the config fails to load, a page shows as its raw
17
+ // text.
18
+ import type { IncomingMessage, ServerResponse } from 'node:http'
19
+ import fs from 'node:fs'
20
+ import path from 'node:path'
21
+ import type { Project } from './config.ts'
22
+ import { appendEvent, readEvents, matches, pickedUp, fromReader, forAgent, CLAIM } from './events.ts'
23
+ import { html, raw, type Html } from './html.ts'
24
+ import { createConfigLoader, pluginDir, toPath, type LoadedConfig } from './loader.ts'
25
+ import { describeRoutes, dispatch, pluginCommands, mountRoutes, usage, type MountedRoute } from './plugins.ts'
26
+ import { createAuth } from './auth.ts'
27
+ import { FROM_SOURCE, PACKAGE_DIR } from './package.ts'
28
+ import { awaiting, covers, heard, questionState, unreadMessages } from './status.ts'
29
+ import { titleOf } from './pages/render.ts'
30
+ import type { Listener, PageSource, PageStatus, Plugin, PluginHooks, Rendered, StoredPage, PagesSource } from './define.ts'
31
+
32
+ const ENGINE_DIR = PACKAGE_DIR
33
+ // the browser runtime, built by build.ts
34
+ const RUNTIME = path.join(ENGINE_DIR, 'dist', 'client', 'runtime.js')
35
+ // the page in the browser (markdown live: morphing, blocks' islands, forms' marks), built by build.ts
36
+ const PAGE_CLIENT = path.join(ENGINE_DIR, 'dist', 'src', 'client', 'page', 'main.js')
37
+ const MIME: Record<string, string> = {
38
+ '.css': 'text/css', '.js': 'text/javascript', '.mjs': 'text/javascript', '.json': 'application/json', '.png': 'image/png',
39
+ '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp', '.avif': 'image/avif',
40
+ '.svg': 'image/svg+xml', '.pdf': 'application/pdf', '.mp4': 'video/mp4', '.webm': 'video/webm', '.woff': 'font/woff',
41
+ '.woff2': 'font/woff2', '.txt': 'text/plain; charset=utf-8', '.md': 'text/markdown; charset=utf-8',
42
+ '.csv': 'text/csv; charset=utf-8', '.html': 'text/html; charset=utf-8',
43
+ }
44
+ // files in .whiteboard/ that are the server's own bookkeeping, not content
45
+ const OWN_FILES = new Set(['events.ndjson', 'server.json', 'server.log', 'server.lock', 'token'])
46
+ const SKIP_DIRS = new Set(['node_modules', '.git'])
47
+ // a page's frontmatter: `---` lines around `key: value` lines, at the very start
48
+ const FRONTMATTER = /^---\r?\n([\s\S]*?)\r?\n---\r?\n/
49
+
50
+
51
+ /** A project's server: its request handler, and what it knows. */
52
+ export interface WhiteboardServer {
53
+ /** answer one request */
54
+ handle(req: IncomingMessage, res: ServerResponse): Promise<void>
55
+ /** what is open on each page (or on `page` and below), as /api/status gives it */
56
+ status(page?: string | null): Promise<PageStatus[]>
57
+ /** the project's config, loaded */
58
+ config(): Promise<LoadedConfig>
59
+ /** stop watching and end the live connections; the server answers nothing after */
60
+ close(): void
61
+ }
62
+
63
+ export function createServer(project: Project): WhiteboardServer {
64
+ const loader = createConfigLoader(project)
65
+ const auth = createAuth(project.wb)
66
+ // what close() stops: watchers, and the live connections' pings and responses
67
+ const watchers = new Set<fs.FSWatcher>()
68
+ const streams = new Set<() => void>()
69
+ const watch = (dir: string, options: fs.WatchOptions, fn: (name: string) => void) => {
70
+ try { watchers.add(fs.watch(dir, options, (_evt, name) => { if (name) fn(String(name)) })) } catch { /* gone, or not built */ }
71
+ }
72
+
73
+ // ---- plugins --------------------------------------------------------------------------------
74
+ // Behaviour on every page: each one's setup runs once per loaded config.
75
+
76
+ /** A plugin once set up: what its setup returned, its mounted routes, or why it failed. */
77
+ interface SetUp extends PluginHooks {
78
+ name: string
79
+ table: MountedRoute[]
80
+ plugin: Plugin
81
+ error?: Error
82
+ }
83
+
84
+ const setups = new WeakMap<LoadedConfig, Promise<SetUp[]>>()
85
+ // the plugins' own folders in .whiteboard/: changes in them reload nothing
86
+ const pluginDirs = new Set<string>()
87
+
88
+ /** The hooks of the loaded config's plugins, set up once per config. */
89
+ async function pluginHooks(): Promise<SetUp[]> {
90
+ const c = await config()
91
+ if (!setups.has(c)) {
92
+ setups.set(c, Promise.all(c.plugins.map(async (e): Promise<SetUp> => {
93
+ try {
94
+ pluginDirs.add(e.name)
95
+ const dataDir = pluginDir(project.wb, e.name)
96
+ const hooks = (await e.setup?.({ project: { name: project.name, dir: project.dir, wb: project.wb }, dataDir, authorized: auth.authorized, asset })) ?? {}
97
+ return { name: e.name, ...hooks, table: mountRoutes(e.name, hooks.routes), plugin: e }
98
+ } catch (err) {
99
+ console.error(`plugin ${e.name}:`, err)
100
+ return { name: e.name, table: [], plugin: e, error: err as Error }
101
+ }
102
+ })))
103
+ }
104
+ return setups.get(c)!
105
+ }
106
+
107
+ /**
108
+ * What the plugins add to the page shell for this request, and the notices of those that failed:
109
+ * a failing plugin shows on the page, as a failing config does, instead of quietly leaving its
110
+ * part out.
111
+ */
112
+ /** What the plugins add to a page: markup for its head and body, their browser modules, and notices. */
113
+ interface Extras {
114
+ head: Html[]
115
+ body: Html[]
116
+ clients: { name: string; client: string }[]
117
+ /** the event types that, from the agent, are messages for the reader (EventSpec.forReader) */
118
+ messages?: string[]
119
+ notices?: string[]
120
+ }
121
+
122
+ async function shellExtras(req: IncomingMessage): Promise<Extras & { notices: string[] }> {
123
+ const hooks = await pluginHooks()
124
+ const notices = hooks.filter(h => h.error).map(h => `plugin "${h.name}" failed to start: ${h.error!.message}`)
125
+ const parts = await Promise.all(hooks.map(async h => {
126
+ try { return (await h.shell?.(req)) ?? null } catch (err) {
127
+ console.error(`plugin ${h.name}:`, err)
128
+ notices.push(`plugin "${h.name}" failed on this page: ${(err as Error).message}`)
129
+ return null
130
+ }
131
+ }))
132
+ // their browser modules, which the runtime imports after the page's
133
+ const clients = hooks.filter(h => h.client && !h.error).map(h => ({ name: h.name, client: asset(h.client!) }))
134
+ const messages = [...(await config()).forReader]
135
+ return { head: parts.map(x => raw(String(x?.head ?? ''))), body: parts.map(x => raw(String(x?.body ?? ''))), clients, messages, notices }
136
+ }
137
+
138
+ /** A page with what the plugins add, their notices among the page's. */
139
+ async function page(req: IncomingMessage, stored: StoredPage, rendered: Render): Promise<string> {
140
+ const extras = await shellExtras(req)
141
+ return shell(stored, { ...rendered, notices: [...rendered.notices, ...extras.notices] }, extras)
142
+ }
143
+
144
+ /** The loaded config. Also applies its `files` setting to what is served and watched. */
145
+ async function config(): Promise<LoadedConfig> {
146
+ const c = await loader.config()
147
+ setFiles(c.files)
148
+ return c
149
+ }
150
+
151
+ // ---- assets: files a plugin asks to serve -------------------------------------------------------
152
+ // Served at /_/file/<absolute path>, only once asked for. Beside a file asked for, its neighbours
153
+ // too, since a client module may import them, but only browser assets (scripts, styles, images,
154
+ // fonts): a plugin's module in .whiteboard/ must not open up the project's token, log or config.
155
+ // Those folders are watched from then on.
156
+
157
+ const assets = new Set<string>()
158
+ const assetDirs = new Set<string>()
159
+ const BROWSER_ASSET = /\.(m?js|css|map|svg|png|jpe?g|gif|webp|avif|ico|woff2?|ttf|otf|wasm)$/i
160
+ const servable = (file: string) => assets.has(file) || (assetDirs.has(path.dirname(file)) && BROWSER_ASSET.test(file))
161
+
162
+ function asset(ref: string | URL): string {
163
+ const file = toPath(ref)
164
+ if (!assets.has(file)) {
165
+ assets.add(file)
166
+ const dir = path.dirname(file)
167
+ if (!assetDirs.has(dir)) {
168
+ assetDirs.add(dir)
169
+ // .whiteboard/ itself is watched already (setFiles), and so are the engine's own files
170
+ if (!within(dir, project.wb) && !ENGINE_WATCHED.some(d => within(dir, d))) {
171
+ watch(dir, {}, name => onSourceChange(path.join(dir, name)))
172
+ }
173
+ }
174
+ }
175
+ return `/_/file${file.split(path.sep).map(encodeURIComponent).join('/')}`
176
+ }
177
+
178
+ const within = (file: string, dir: string) => file === dir || file.startsWith(dir + path.sep)
179
+
180
+ // ---- stored pages ------------------------------------------------------------------------------
181
+
182
+ /** Resolve a path inside a base folder, refusing anything that escapes it. */
183
+ function inside(base: string, rel: string): string | null {
184
+ const p = path.resolve(base, '.' + path.posix.normalize('/' + rel))
185
+ return within(p, base) ? p : null
186
+ }
187
+
188
+ const isRepoId = (id: string) => id === '-' || id.startsWith('-/')
189
+
190
+ function frontmatter(source: string): Record<string, string> {
191
+ const m = FRONTMATTER.exec(source)
192
+ const out: Record<string, string> = {}
193
+ if (m) for (const line of m[1]!.split(/\r?\n/)) {
194
+ const kv = /^([\w-]+)\s*:\s*(.*)$/.exec(line)
195
+ if (kv) out[kv[1]!] = kv[2]!.trim().replace(/^["']|["']$/g, '')
196
+ }
197
+ return out
198
+ }
199
+
200
+ function pageSource(id: string, file: string): PageSource {
201
+ const source = fs.readFileSync(file, 'utf8')
202
+ return { kind: 'page', id, file, mtime: fs.statSync(file).mtimeMs, source, body: source.replace(FRONTMATTER, ''), frontmatter: frontmatter(source) }
203
+ }
204
+
205
+ /** The pages in a folder of the pages folder, newest first, with when each was last answered. */
206
+ function pagesIn(dir: string): PagesSource['pages'] {
207
+ const last = new Map<string, string>()
208
+ // the last time the reader sent something: what the agent appended doesn't count
209
+ for (const e of readEvents(project.eventsFile)) if (fromReader(e)) last.set(e.page, e.ts)
210
+ const out: PagesSource['pages'] = []
211
+ const walk = (d: string) => {
212
+ if (!fs.existsSync(d)) return
213
+ for (const ent of fs.readdirSync(d, { withFileTypes: true })) {
214
+ if (ent.name.startsWith('.') || ent.name === 'node_modules') continue
215
+ const full = path.join(d, ent.name)
216
+ if (ent.isDirectory()) walk(full)
217
+ else if (ent.name.endsWith('.md')) {
218
+ const id = path.relative(project.pagesDir, full).split(path.sep).join('/').replace(/\.md$/, '')
219
+ out.push({ id, file: full, mtime: fs.statSync(full).mtimeMs, lastEvent: last.get(id) ?? null, awaiting: 0 })
220
+ }
221
+ }
222
+ }
223
+ walk(dir)
224
+ return out.sort((a, b) => b.mtime - a.mtime)
225
+ }
226
+
227
+ /** Text files show as files; anything with a NUL byte near the start is binary. */
228
+ function isText(file: string): boolean {
229
+ const fd = fs.openSync(file, 'r')
230
+ const buf = Buffer.alloc(8192)
231
+ const n = fs.readSync(fd, buf, 0, buf.length, 0)
232
+ fs.closeSync(fd)
233
+ return !buf.subarray(0, n).includes(0)
234
+ }
235
+
236
+ /**
237
+ * A page id → the stored page, or one of: { redirect } (a folder asked for without its slash),
238
+ * { raw: file } (serve the bytes), null (nothing there).
239
+ */
240
+ function stored(id: string): StoredPage | { raw: string } | null {
241
+ if (!id) return { kind: 'pages', id: '', file: project.pagesDir, mtime: null, pages: pagesIn(project.pagesDir) }
242
+ if (isRepoId(id)) {
243
+ const rel = id.slice(2)
244
+ const target = inside(project.dir, rel)
245
+ if (!target || path.relative(project.dir, target).split(path.sep).includes('.git') || !fs.existsSync(target)) return null
246
+ const stat = fs.statSync(target)
247
+ if (stat.isDirectory()) {
248
+ const entries = fs.readdirSync(target, { withFileTypes: true })
249
+ .filter(e => !SKIP_DIRS.has(e.name) && e.name !== '.DS_Store')
250
+ .map(e => ({ name: e.name, dir: e.isDirectory() }))
251
+ .sort((a, b) => (Number(b.dir) - Number(a.dir)) || a.name.localeCompare(b.name))
252
+ return { kind: 'folder', id, file: target, mtime: stat.mtimeMs, entries }
253
+ }
254
+ if (/\.(md|markdown)$/i.test(target)) return pageSource(id, target)
255
+ if (stat.size > 1e6 || !isText(target)) return { raw: target }
256
+ return { kind: 'file', id, file: target, mtime: stat.mtimeMs, source: fs.readFileSync(target, 'utf8') }
257
+ }
258
+ const target = inside(project.pagesDir, id)
259
+ if (!target) return null
260
+ if (path.extname(id) && fs.existsSync(target) && fs.statSync(target).isFile()) return { raw: target }
261
+ if (fs.existsSync(target) && fs.statSync(target).isDirectory()) {
262
+ const index = path.join(target, 'index.md')
263
+ if (fs.existsSync(index)) return pageSource(id, index)
264
+ return { kind: 'pages', id, file: target, mtime: null, pages: pagesIn(target) }
265
+ }
266
+ const file = target + '.md'
267
+ return fs.existsSync(file) ? pageSource(id, file) : null
268
+ }
269
+
270
+ /** The URL that serves a file or folder on disk, or null when nothing here serves it. */
271
+ function urlOf(abs: string): string | null {
272
+ const rel = (dir: string) => path.relative(dir, abs).split(path.sep).map(encodeURIComponent).join('/')
273
+ if (within(abs, project.pagesDir)) return `/${rel(project.pagesDir).replace(/\.md$/, '')}`
274
+ if (FILES && within(abs, project.dir)) {
275
+ if (rel(project.dir).split('/').some(part => SKIP_DIRS.has(part))) return null
276
+ return `/-/${rel(project.dir)}`
277
+ }
278
+ return null
279
+ }
280
+
281
+ /** For links: the target if it exists (also with .md added), mapped to its URL. */
282
+ function urlFor(abs: string): string | null {
283
+ for (const candidate of [abs, abs + '.md']) {
284
+ if (fs.existsSync(candidate)) {
285
+ const url = urlOf(candidate)
286
+ if (url) return url + (fs.statSync(candidate).isDirectory() && !url.endsWith('/') ? '/' : '')
287
+ }
288
+ }
289
+ return null
290
+ }
291
+
292
+ // ---- rendering ---------------------------------------------------------------------------------
293
+
294
+ /** A config that failed to load: the page as stored, as text, under the error. */
295
+ function rawRender(page: StoredPage): Rendered {
296
+ const list = (items: [string, string][]) => html`<ul>${items.map(([href, text]) => html`<li><a href="${href}">${text}</a></li>`)}</ul>`
297
+ if (page.kind === 'pages') return { html: list(page.pages.map(p => [`/${p.id}`, p.id])) }
298
+ if (page.kind === 'folder') {
299
+ return { html: list(page.entries.map(e => [encodeURIComponent(e.name) + (e.dir ? '/' : ''), e.name + (e.dir ? '/' : '')] as [string, string])) }
300
+ }
301
+ return { html: html`<pre>${page.source}</pre>` }
302
+ }
303
+
304
+ const context = () => ({ project: { name: project.name, dir: project.dir, files: !!FILES }, asset, urlFor })
305
+
306
+ /** A render as the shell takes it. `page`: whether the page's browser part runs (not on raw text). */
307
+ interface Render {
308
+ page: boolean
309
+ out: Rendered
310
+ notices: string[]
311
+ }
312
+
313
+ /** Render a stored page as markdown, with the plugins' blocks, and anything the reader should be told. */
314
+ async function render(page: StoredPage): Promise<Render> {
315
+ const { pages, errors } = await config()
316
+ const notices = errors.map(e => `config: ${(e as Error).message}`)
317
+ let out: Rendered
318
+ let rendered = !!pages
319
+ try {
320
+ out = pages ? await pages.render(page, context()) : rawRender(page)
321
+ } catch (err) {
322
+ console.error('render:', err)
323
+ notices.push(`the page failed to render: ${(err as Error).message}`)
324
+ out = rawRender(page)
325
+ rendered = false
326
+ }
327
+ // HTML built with `html`: from here on it is a string, for the shell and for /api/render's JSON alike
328
+ const strings = { ...out, html: String(out.html ?? ''), ...(out.head != null ? { head: String(out.head) } : {}) }
329
+ return { page: rendered, out: strings, notices }
330
+ }
331
+
332
+ /**
333
+ * Per page: the questions it asks that have no answer yet, the reader's events no wait or watch
334
+ * picked up, who is listening, and the session that claimed it. What `whiteboard status` and the
335
+ * hooks report. The questions are a page's named forms.
336
+ */
337
+ async function status(only: string | null): Promise<PageStatus[]> {
338
+ const { pages, handedOut, forReader } = await config()
339
+ const isForAgent = forAgent(handedOut)
340
+ const all = readEvents(project.eventsFile)
341
+ const picked = pickedUp(all)
342
+ const owner = new Map<string, string | null>()
343
+ for (const e of all) if (e.type === CLAIM && !fromReader(e)) owner.set(e.page, (e.data?.session as string | undefined) ?? null)
344
+ const out: PageStatus[] = []
345
+ for (const p of pagesIn(project.pagesDir)) {
346
+ if (only && p.id !== only && !p.id.startsWith(only + '/')) continue
347
+ const page = pageSource(p.id, p.file)
348
+ let asks: string[] = []
349
+ try { asks = pages?.questions(page) ?? [] } catch (err) { console.error('questions:', err) }
350
+ const events = all.filter(e => e.page === p.id)
351
+ const listening = listenersFor(p.id)
352
+ // where each question stands, as the page shows it (see status.ts)
353
+ const questions = asks.map(name => ({ name, state: questionState(name, events, listening, id => picked.has(id)).state }))
354
+ const named = (...states: string[]) => questions.filter(q => states.includes(q.state)).map(q => q.name)
355
+ out.push({
356
+ page: p.id, title: titleOf(p.file, path.basename(p.id)), file: p.file, owner: owner.get(p.id) ?? null, asks, questions,
357
+ open: named('open'),
358
+ unheard: named('open').filter(name => !heard(name, listening)),
359
+ unread: unreadMessages(events, type => forReader.has(type)),
360
+ // the reader's events for an agent: a form's answers, and plugin events declared handOut
361
+ unpicked: events.filter(e => fromReader(e) && isForAgent(e.type) && !picked.has(e.id)),
362
+ listeners: listening,
363
+ })
364
+ }
365
+ return out
366
+ }
367
+
368
+ /** How to write pages here, as markdown: the pages' own docs, then each plugin's. */
369
+ async function docs() {
370
+ const { pages, errors } = await config()
371
+ // what each plugin declares: its routes (for an agent that wants to call them) and commands
372
+ const plugins = await Promise.all((await pluginHooks()).map(async h => ({
373
+ name: h.name,
374
+ error: h.error?.message ?? null,
375
+ docs: h.plugin.docs ? await h.plugin.docs() : null,
376
+ routes: describeRoutes(h.table),
377
+ commands: pluginCommands(h.plugin).map(c => ({ name: c.name, usage: usage(c.command), description: c.command.description })),
378
+ events: Object.entries(h.plugin.events ?? {}).map(([type, spec]) => ({ type, handOut: !!spec?.handOut, description: spec?.description ?? '' })),
379
+ })))
380
+ return { errors: errors.map(e => (e as Error).message), pages: pages?.docs(context()) ?? null, plugins }
381
+ }
382
+
383
+ const json = (s: unknown) => JSON.stringify(s).replace(/</g, '\\u003c')
384
+
385
+ // the page's corner (api.corner()): the one thing the core puts on every page, empty, for the
386
+ // page's and the plugins' floating buttons; above what covers the bottom of the window
387
+ const DOCK_STYLE = '#wb-dock{position:fixed;right:16px;bottom:calc(16px + var(--wb-inset-bottom,0px));z-index:10;display:flex;flex-direction:column;align-items:flex-end;gap:6px}#wb-dock:empty{display:none}'
388
+ // toasts (api.toast), centred above the same edge; in the page's theme colours where it has them
389
+ + '#wb-toasts{position:fixed;left:50%;transform:translateX(-50%);bottom:calc(16px + var(--wb-inset-bottom,0px));z-index:30;display:grid;gap:8px;width:min(440px,100vw - 32px);pointer-events:none}'
390
+ + '.wb-toast{pointer-events:auto;cursor:pointer;padding:10px 14px;border-radius:8px;font:.85rem/1.45 var(--sans,system-ui,sans-serif);background:var(--bg,Canvas);color:var(--text,CanvasText);border:1px solid var(--border,#8884);box-shadow:0 8px 28px rgb(0 0 0/.18)}'
391
+ + '.wb-toast[data-kind=warn]{border-left:4px solid var(--warn,#c98a00)}.wb-toast[data-action]{border-left:4px solid var(--accent,#1d5bbf)}'
392
+
393
+ /** `extras`: what plugins add to <head> and <body> (see shellExtras). */
394
+ function shell(page: StoredPage, { page: rendered, out, notices }: Render, extras: Extras = { head: [], body: [], clients: [] }): string {
395
+ const handoff = { id: page.id, kind: page.kind, client: rendered ? asset(PAGE_CLIENT) : null, data: out.data ?? null, plugins: extras.clients, messages: extras.messages ?? [] }
396
+ // the page's head and html are HTML already; the handoff is JSON made safe for a script tag
397
+ return String(html`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
398
+ <title>${out.title || page.id || project.name}</title>
399
+ <style>${DOCK_STYLE}</style>
400
+ ${raw(out.head ?? '')}${extras.head}</head>
401
+ <body data-page="${page.id}" data-kind="${page.kind}">
402
+ ${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
403
+ <div id="wb-root">${raw(String(out.html))}</div>
404
+ <div id="wb-dock"></div>
405
+ <script type="application/json" id="wb-page">${raw(json(handoff))}</script>
406
+ <script type="module" src="/_/runtime.js"></script>${extras.body}</body></html>`)
407
+ }
408
+
409
+ // ---- listeners ---------------------------------------------------------------------------------
410
+ // An agent waiting for answers (`whiteboard wait` or `watch`) holds a connection to /api/listen for
411
+ // as long as it runs: that connection is the listener, gone when the command is. Pages show what an
412
+ // agent is waiting for from these, so nothing depends on the agent marking it.
413
+
414
+ /** A listener as the server holds it. */
415
+ const listeners = new Set<Listener>()
416
+
417
+
418
+ const listenersFor = (page: string | null): Listener[] => [...listeners].filter(l => page == null || covers(l, page)).map(({ page, type, command, fallback }) => ({ page, type, command, ...(fallback && { fallback }) }))
419
+
420
+ // ---- live changes ------------------------------------------------------------------------------
421
+ // The browser listens at /api/watch. `change`: its page changed; `events`: the log grew;
422
+ // `listeners`: an agent started or stopped waiting; `style`: a stylesheet changed; `reload`:
423
+ // browser code changed.
424
+
425
+ /** A browser following its page at /api/watch; `pending`: what it will be told in a moment. */
426
+ interface WatchClient {
427
+ res: ServerResponse
428
+ page: string
429
+ isDir: boolean
430
+ pending?: Set<string>
431
+ }
432
+
433
+ const clients = new Set<WatchClient>()
434
+ function notify(client: WatchClient, kind: string) {
435
+ client.pending ??= new Set()
436
+ if (client.pending.size === 0) setTimeout(() => {
437
+ for (const k of client.pending!) client.res.write(`event: ${k}\ndata: {}\n\n`)
438
+ client.pending!.clear()
439
+ }, 60)
440
+ client.pending.add(kind)
441
+ }
442
+ const notifyAll = (kind: string) => { for (const c of clients) notify(c, kind) }
443
+
444
+ function pageChanged(id: string) {
445
+ for (const c of clients) {
446
+ if (c.isDir ? (!c.page || id.startsWith(c.page + '/')) : (c.page === id || c.page + '/index' === id)) notify(c, 'change')
447
+ }
448
+ // the overview lists every page
449
+ for (const c of clients) if (c.isDir && !c.page) notify(c, 'change')
450
+ }
451
+
452
+ /** A file in the project changed; `f` is its path relative to the project folder, with / separators. */
453
+ function fileChanged(f: string) {
454
+ if (f.split('/').some(part => SKIP_DIRS.has(part))) return
455
+ if (f.startsWith('.whiteboard/')) {
456
+ const inner = f.slice('.whiteboard/'.length)
457
+ if (inner === 'events.ndjson') return notifyAll('events')
458
+ if (inner.startsWith('pages/')) {
459
+ if (inner.endsWith('.md')) pageChanged(inner.slice('pages/'.length).replace(/\.md$/, ''))
460
+ return
461
+ }
462
+ if (OWN_FILES.has(inner) || pluginDirs.has(inner.split('/')[0]!)) return
463
+ // the config, or something it imports
464
+ return onSourceChange(path.join(project.dir, f))
465
+ }
466
+ if (!FILES) return
467
+ // a repository file; its folder's listing shows it too
468
+ pageChanged(`-/${f}`)
469
+ const parent = f.includes('/') ? f.slice(0, f.lastIndexOf('/')) : ''
470
+ pageChanged(`-${parent ? '/' + parent : ''}`)
471
+ }
472
+
473
+ // With files on, the whole project folder is watched (repository views stay live); with files off,
474
+ // only .whiteboard/, so a project in a large folder such as the home folder stays cheap.
475
+ let FILES: boolean | null = null
476
+ let watcher: fs.FSWatcher | null = null
477
+ function setFiles(files: boolean) {
478
+ if (files === FILES) return
479
+ FILES = files
480
+ if (watcher) { watcher.close(); watchers.delete(watcher) }
481
+ const base = files ? project.dir : project.wb
482
+ const prefix = files ? '' : '.whiteboard/'
483
+ watcher = fs.watch(base, { recursive: true }, (_evt, filename) => {
484
+ if (filename) fileChanged(prefix + filename.replace(/\\/g, '/'))
485
+ })
486
+ watchers.add(watcher)
487
+ }
488
+
489
+ // What a plugin or the config is made of changed. A stylesheet reloads in place; a browser module
490
+ // reloads the pages; anything else loads the config afresh and re-renders open pages.
491
+ let reloadTimer: ReturnType<typeof setTimeout> | undefined
492
+ async function onSourceChange(file: string) {
493
+ if (within(file, project.pagesDir)) return
494
+ if (path.dirname(file) === project.wb && OWN_FILES.has(path.basename(file))) return
495
+ if ([...pluginDirs].some(name => within(file, path.join(project.wb, name)))) return
496
+ if (file.endsWith('.css')) return notifyAll('style')
497
+ if (file.endsWith('.md')) return notifyAll('change')
498
+ if (file === RUNTIME || assets.has(file)) return notifyAll('reload')
499
+ // a build writes several files at once: load the config once they are all there
500
+ clearTimeout(reloadTimer)
501
+ reloadTimer = setTimeout(() => {
502
+ loader.invalidate()
503
+ config().then(() => notifyAll('change'))
504
+ }, 80)
505
+ }
506
+
507
+ // The engine's own files, when it runs from source: what a config loads from it runs from source
508
+ // too (the plugins), and the browser code from its build (npm run dev). A change to
509
+ // either reloads what it is made of, like a project's own files.
510
+ const ENGINE_BUILD = path.join(ENGINE_DIR, 'dist')
511
+ const ENGINE_WATCHED = !FROM_SOURCE ? [] : [ENGINE_BUILD, ...['plugins'].map(d => path.join(ENGINE_DIR, d))]
512
+ for (const dir of ENGINE_WATCHED) watch(dir, { recursive: true }, name => onSourceChange(path.join(dir, name)))
513
+
514
+ // ---- http --------------------------------------------------------------------------------------
515
+
516
+ function send(res: ServerResponse, status: number, body: string | Buffer, type = 'text/html; charset=utf-8') {
517
+ res.writeHead(status, { 'content-type': type, 'cache-control': 'no-store' })
518
+ res.end(body)
519
+ }
520
+ const sendJson = (res: ServerResponse, status: number, data: unknown) => send(res, status, JSON.stringify(data), 'application/json')
521
+ const sendFile = (res: ServerResponse, file: string) => send(res, 200, fs.readFileSync(file), MIME[path.extname(file).toLowerCase()] || 'application/octet-stream')
522
+
523
+ function readBody(req: IncomingMessage): Promise<string> {
524
+ return new Promise((resolve, reject) => {
525
+ const chunks: Buffer[] = []
526
+ let size = 0
527
+ req.on('data', (c: Buffer) => { size += c.length; if (size > 1e6) { reject(new Error('body too large')); req.destroy() } else chunks.push(c) })
528
+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
529
+ req.on('error', reject)
530
+ })
531
+ }
532
+
533
+ /** What a page id resolves to, or why it does not: the response to send instead. */
534
+ type Resolved = { page: StoredPage } | { raw: string } | { redirect: string } | { notFound: string }
535
+
536
+ async function resolve(id: string, requested: string): Promise<Resolved> {
537
+ await config()
538
+ if (isRepoId(id) && !FILES) return { notFound: 'This project does not serve its files: its config sets files: false.' }
539
+ if (id === '_/docs') {
540
+ // how pages are written, then each plugin's own docs, with their examples rendered live
541
+ const { pages, plugins } = await docs()
542
+ const source = [
543
+ pages ?? '',
544
+ ...plugins.filter(p => p.docs).map(p => `<a id="plugin-${p.name}"></a>\n\n${p.docs}`),
545
+ ].join('\n\n---\n\n')
546
+ return { page: { kind: 'page', id, file: path.join(project.pagesDir, '_docs.md'), mtime: null, source, body: source, frontmatter: {} } }
547
+ }
548
+ const found = stored(id)
549
+ if (!found) return { notFound: `${isRepoId(id) ? id.slice(2) : id} does not exist${isRepoId(id) ? '' : ' yet. This page loads as soon as it does'}.` }
550
+ if ('raw' in found) return found
551
+ // a folder is served at /dir/, so relative links resolve inside it
552
+ if ((found.kind === 'folder' || (found.kind === 'pages' && id)) && !requested.endsWith('/')) return { redirect: `/${id}/` }
553
+ // a list of pages says which await the reader: where their questions stand takes the config
554
+ if (found.kind === 'pages') {
555
+ const counts = new Map((await status(found.id || null)).map(s => [s.page, awaiting(s)]))
556
+ for (const p of found.pages) p.awaiting = counts.get(p.id) ?? 0
557
+ }
558
+ return { page: found }
559
+ }
560
+
561
+ async function handle(req: IncomingMessage, res: ServerResponse): Promise<void> {
562
+ try {
563
+ // a path like //x would otherwise read as a host
564
+ const url = new URL((req.url ?? '/').replace(/^\/+/, '/'), 'http://localhost')
565
+ const p = decodeURIComponent(url.pathname)
566
+ const q = Object.fromEntries(url.searchParams)
567
+
568
+ if (p === '/favicon.ico') { res.writeHead(204); res.end(); return }
569
+ if (p === '/_/runtime.js') return sendFile(res, RUNTIME)
570
+ if (auth.handle(req, res, p, q)) return
571
+ if (p.startsWith('/api/')) {
572
+ const hooks = await pluginHooks()
573
+ for (const h of hooks) if (await dispatch(h.table, req, res, url, auth.authorized)) return
574
+ // under a plugin's name, but none of its routes
575
+ const owner = hooks.find(h => p.startsWith(`/api/${h.name}/`) || p === `/api/${h.name}`)
576
+ if (owner) return sendJson(res, 404, { error: `plugin ${owner.name} has no route ${req.method} ${p}` })
577
+ }
578
+ if (p.startsWith('/_/file/')) {
579
+ const file = path.resolve(p.slice('/_/file'.length))
580
+ if (!servable(file) || !fs.existsSync(file) || !fs.statSync(file).isFile()) return send(res, 404, 'not found', 'text/plain')
581
+ return sendFile(res, file)
582
+ }
583
+ if (p === '/api/health') return sendJson(res, 200, { ok: true, dir: project.dir, pid: process.pid })
584
+ if (p === '/api/events' && req.method === 'POST') {
585
+ const body = JSON.parse(await readBody(req))
586
+ if (!body.type) return sendJson(res, 400, { error: 'event type required' })
587
+ return sendJson(res, 200, appendEvent(project.eventsFile, body))
588
+ }
589
+ // messages (comments, chat) written in markdown, as HTML: { texts } → { html, styles }
590
+ if (p === '/api/markdown' && req.method === 'POST') {
591
+ const { texts } = JSON.parse(await readBody(req)) as { texts?: unknown }
592
+ if (!Array.isArray(texts)) return sendJson(res, 400, { error: 'texts: an array of strings' })
593
+ const { pages } = await config()
594
+ const out = await Promise.all(texts.map(t => pages ? pages.message(String(t ?? ''), context()) : Promise.resolve({ html: String(html`${String(t ?? '')}`), styles: [] })))
595
+ return sendJson(res, 200, { html: out.map(o => o.html), styles: [...new Set(out.flatMap(o => o.styles))] })
596
+ }
597
+ if (p === '/api/events') {
598
+ const all = readEvents(project.eventsFile)
599
+ const picked = pickedUp(all)
600
+ return sendJson(res, 200, all.filter(e => matches(e, q)).map(e => (picked.has(e.id) ? { ...e, pickedUp: true } : e)))
601
+ }
602
+ if (p === '/api/docs') return sendJson(res, 200, await docs())
603
+ if (p === '/api/status') return sendJson(res, 200, await status(q.page || null))
604
+ if (p === '/api/listeners') return sendJson(res, 200, listenersFor(q.page ?? null))
605
+ if (p === '/api/listen') {
606
+ const fallback = 'fallback' in q
607
+ // one fallback per project: two would split what nobody else takes between them
608
+ if (fallback && [...listeners].some(l => l.fallback)) return sendJson(res, 409, { error: 'another agent is the fallback already' })
609
+ res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', connection: 'keep-alive' })
610
+ res.write(': listening\n\n')
611
+ const l: Listener = { page: q.page || '', type: q.type || null, command: q.command === 'wait' ? 'wait' : 'watch', ...(fallback && { fallback }) }
612
+ listeners.add(l)
613
+ notifyAll('listeners')
614
+ const ping = setInterval(() => res.write(': ping\n\n'), 25000)
615
+ const end = () => { clearInterval(ping); listeners.delete(l); streams.delete(end) }
616
+ streams.add(() => { end(); res.end() })
617
+ req.on('close', () => { end(); notifyAll('listeners') })
618
+ return
619
+ }
620
+ if (p === '/api/page' || p === '/api/render') {
621
+ const r = await resolve(q.page ?? '', '/')
622
+ if (!('page' in r)) return sendJson(res, 404, { error: 'notFound' in r ? r.notFound : 'not a page' })
623
+ if (p === '/api/page') return sendJson(res, 200, r.page)
624
+ const { out, notices } = await render(r.page)
625
+ return sendJson(res, 200, { ...out, notices, mtime: r.page.mtime })
626
+ }
627
+ if (p === '/api/watch') {
628
+ res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', connection: 'keep-alive' })
629
+ res.write(': connected\n\n')
630
+ const client = { res, page: q.page || '', isDir: 'dir' in q }
631
+ clients.add(client)
632
+ const ping = setInterval(() => res.write(': ping\n\n'), 25000)
633
+ const end = () => { clearInterval(ping); clients.delete(client); streams.delete(end) }
634
+ streams.add(() => { end(); res.end() })
635
+ req.on('close', end)
636
+ return
637
+ }
638
+
639
+ const path_ = p.replace(/^\/+/, '').replace(/\/+$/, '')
640
+ // a page is named without .md; a repository path is the file's own
641
+ const id = isRepoId(path_) ? path_ : path_.replace(/\.md$/, '')
642
+ const r = await resolve(id, p)
643
+ if ('redirect' in r) { res.writeHead(302, { location: r.redirect + url.search }); res.end(); return }
644
+ if ('raw' in r) return sendFile(res, r.raw)
645
+ if ('notFound' in r) {
646
+ const missing: PageSource = { kind: 'page', id, file: '', mtime: null, source: r.notFound, body: r.notFound, frontmatter: {} }
647
+ return send(res, 404, await page(req, missing, { page: false, out: { title: 'Not found', html: html`<h1>Not found</h1><p>${r.notFound}</p>` }, notices: [] }))
648
+ }
649
+ return send(res, 200, await page(req, r.page, await render(r.page)))
650
+ } catch (err) {
651
+ console.error(err)
652
+ send(res, 500, String((err as Error)?.stack || err), 'text/plain')
653
+ }
654
+ }
655
+
656
+ return {
657
+ handle,
658
+ status: (page = null) => status(page),
659
+ config,
660
+ close() {
661
+ for (const w of watchers) w.close()
662
+ watchers.clear()
663
+ for (const stop of [...streams]) stop()
664
+ clearTimeout(reloadTimer)
665
+ },
666
+ }
667
+ }