@bigmistqke/whiteboard 0.4.0 → 0.6.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 (128) hide show
  1. package/README.md +177 -26
  2. package/bin/whiteboard.ts +331 -16
  3. package/dist/bin/whiteboard.js +268 -17
  4. package/dist/client/runtime.js +66 -23
  5. package/dist/plugins/ansi/README.md +36 -0
  6. package/dist/plugins/ansi/index.js +64 -0
  7. package/dist/plugins/ansi/public/style.css +28 -0
  8. package/dist/plugins/badge/README.md +28 -0
  9. package/dist/plugins/badge/index.js +24 -0
  10. package/dist/plugins/badge/public/style.css +30 -0
  11. package/dist/plugins/chat/public/style.css +7 -2
  12. package/dist/plugins/code/README.md +4 -2
  13. package/dist/plugins/code/diff.js +12 -2
  14. package/dist/plugins/draft/README.md +14 -0
  15. package/dist/plugins/draft/index.js +21 -0
  16. package/dist/plugins/draft/public/style.css +21 -0
  17. package/dist/plugins/grid/README.md +12 -12
  18. package/dist/plugins/grid/index.js +7 -19
  19. package/dist/plugins/grid/public/style.css +4 -33
  20. package/dist/plugins/iframe/README.md +7 -7
  21. package/dist/plugins/iframe/index.js +11 -11
  22. package/dist/plugins/iframe/public/style.css +15 -0
  23. package/dist/plugins/index.js +11 -3
  24. package/dist/plugins/lightbox/README.md +22 -0
  25. package/dist/plugins/lightbox/index.js +20 -0
  26. package/dist/plugins/lightbox/public/client.js +4 -0
  27. package/dist/plugins/lightbox/public/style.css +66 -0
  28. package/dist/plugins/steps/README.md +42 -0
  29. package/dist/plugins/steps/index.js +60 -0
  30. package/dist/plugins/steps/public/client.js +1 -0
  31. package/dist/plugins/steps/public/style.css +77 -0
  32. package/dist/plugins/terminal/host.js +9 -3
  33. package/dist/plugins/terminal/public/client.js +1 -1
  34. package/dist/plugins/terminal/sizes.js +2 -1
  35. package/dist/plugins/toc/README.md +21 -3
  36. package/dist/plugins/toc/index.js +8 -2
  37. package/dist/plugins/toc/public/client.js +1 -1
  38. package/dist/plugins/toc/public/style.css +10 -4
  39. package/dist/plugins/window/README.md +34 -14
  40. package/dist/plugins/window/index.js +21 -13
  41. package/dist/src/auth.js +6 -4
  42. package/dist/src/client/page/base.css +61 -1
  43. package/dist/src/client/page/main.js +74 -20
  44. package/dist/src/entries.js +211 -0
  45. package/dist/src/events.js +1 -1
  46. package/dist/src/hub.js +272 -0
  47. package/dist/src/loader.js +12 -3
  48. package/dist/src/package.js +23 -1
  49. package/dist/src/pages/blocks.js +1 -0
  50. package/dist/src/pages/index.js +1 -1
  51. package/dist/src/pages/markdown.js +87 -33
  52. package/dist/src/pages/render.js +157 -28
  53. package/dist/src/pages/window.js +17 -18
  54. package/dist/src/running.js +37 -2
  55. package/dist/src/serve.js +111 -2
  56. package/dist/src/server.js +264 -23
  57. package/package.json +3 -2
  58. package/plugins/ansi/README.md +36 -0
  59. package/plugins/ansi/index.ts +95 -0
  60. package/plugins/ansi/public/style.css +28 -0
  61. package/plugins/badge/README.md +28 -0
  62. package/plugins/badge/index.ts +35 -0
  63. package/plugins/badge/public/style.css +30 -0
  64. package/plugins/chat/public/style.css +7 -2
  65. package/plugins/code/README.md +4 -2
  66. package/plugins/code/diff.ts +14 -2
  67. package/plugins/code/index.ts +3 -1
  68. package/plugins/draft/README.md +14 -0
  69. package/plugins/draft/index.ts +23 -0
  70. package/plugins/draft/public/style.css +21 -0
  71. package/plugins/grid/README.md +12 -12
  72. package/plugins/grid/index.ts +11 -26
  73. package/plugins/grid/public/style.css +4 -33
  74. package/plugins/iframe/README.md +7 -7
  75. package/plugins/iframe/index.ts +15 -15
  76. package/plugins/iframe/public/style.css +15 -0
  77. package/plugins/index.ts +10 -2
  78. package/plugins/lightbox/README.md +22 -0
  79. package/plugins/lightbox/client.ts +99 -0
  80. package/plugins/lightbox/index.ts +25 -0
  81. package/plugins/lightbox/public/style.css +66 -0
  82. package/plugins/mermaid/index.ts +4 -2
  83. package/plugins/steps/README.md +42 -0
  84. package/plugins/steps/client.ts +75 -0
  85. package/plugins/steps/index.ts +84 -0
  86. package/plugins/steps/public/style.css +77 -0
  87. package/plugins/terminal/client.ts +16 -7
  88. package/plugins/terminal/host.ts +12 -6
  89. package/plugins/terminal/sizes.ts +3 -1
  90. package/plugins/toc/README.md +21 -3
  91. package/plugins/toc/client.ts +47 -6
  92. package/plugins/toc/index.ts +19 -6
  93. package/plugins/toc/public/style.css +10 -4
  94. package/plugins/window/README.md +34 -14
  95. package/plugins/window/index.ts +20 -13
  96. package/skills/whiteboard/SKILL.md +18 -10
  97. package/src/auth.ts +8 -5
  98. package/src/client/base.ts +19 -0
  99. package/src/client/forms.ts +2 -1
  100. package/src/client/markdown.ts +2 -1
  101. package/src/client/page/base.css +61 -1
  102. package/src/client/page/elsewhere.ts +72 -16
  103. package/src/client/page/fresh.ts +2 -1
  104. package/src/client/page/main.ts +18 -6
  105. package/src/client/page/sort.ts +2 -1
  106. package/src/client/runtime.ts +62 -25
  107. package/src/define.ts +126 -19
  108. package/src/entries.ts +258 -0
  109. package/src/events.ts +2 -1
  110. package/src/hub.ts +355 -0
  111. package/src/loader.ts +14 -3
  112. package/src/package.ts +22 -0
  113. package/src/pages/blocks.ts +3 -0
  114. package/src/pages/index.ts +6 -4
  115. package/src/pages/markdown.ts +89 -32
  116. package/src/pages/render.ts +181 -28
  117. package/src/pages/window.ts +23 -25
  118. package/src/running.ts +47 -1
  119. package/src/serve.ts +114 -1
  120. package/src/server.ts +332 -26
  121. package/dist/plugins/gallery/README.md +0 -30
  122. package/dist/plugins/gallery/index.js +0 -75
  123. package/dist/plugins/gallery/public/client.js +0 -1
  124. package/dist/plugins/gallery/public/style.css +0 -90
  125. package/plugins/gallery/README.md +0 -30
  126. package/plugins/gallery/client.tsx +0 -70
  127. package/plugins/gallery/index.ts +0 -89
  128. package/plugins/gallery/public/style.css +0 -90
package/bin/whiteboard.ts CHANGED
@@ -25,8 +25,17 @@ import {
25
25
  import { BUILTIN_COMMANDS, createConfigLoader, pluginDir } from '../src/loader.ts'
26
26
  import { pluginCommands, parseCommandArgs, usage } from '../src/plugins.ts'
27
27
  import { projectToken } from '../src/auth.ts'
28
- import { packagePath } from '../src/package.ts'
29
- import { runningServer } from '../src/running.ts'
28
+ import { PACKAGE_DIR, packagePath } from '../src/package.ts'
29
+ import { recordedSharedPort, runningServer, sharedServer } from '../src/running.ts'
30
+ import {
31
+ machineDir,
32
+ machineServerFile,
33
+ matchesEntries,
34
+ readMachineConfig,
35
+ serverPaths,
36
+ stateDir,
37
+ } from '../src/entries.ts'
38
+ import { compareVersions, VERSION } from '../src/package.ts'
30
39
  import { statusLines, takenByOther, whose } from '../src/status.ts'
31
40
  import type { Listener, PageStatus, WbEvent } from '../src/define.ts'
32
41
 
@@ -47,6 +56,8 @@ const HELP = `whiteboard — markdown pages in the browser, what the reader does
47
56
  whiteboard url <page|file> the same: print the page URL
48
57
  whiteboard close <page> a page that did its job: remove its file, and its events from the log
49
58
  whiteboard prune <page> [--type <t>] [--id <id>] remove a page's events from the log, keep the page
59
+ whiteboard build [globs…] [--out <dir>] [--skip <a,b>] pages as a static site: plain HTML, links
60
+ relative, without forms, chats, comments and drafts (the config's build)
50
61
  whiteboard edit <event id> --data <json> change an agent's own event in place (merged into its data)
51
62
  whiteboard scroll <page|file> <where> scroll the tabs that have the page open to a heading's text,
52
63
  a form's name or any text on it (opening details around it)
@@ -58,18 +69,27 @@ const HELP = `whiteboard — markdown pages in the browser, what the reader does
58
69
  whiteboard append --page <p> --type <t> [--data <json>] add an event to a page's log (e.g. a reply)
59
70
  whiteboard pick <event id> record an event as picked up, as wait does when it hands one out
60
71
  whiteboard status [--page <p>] per page: questions without an answer, answers no agent picked up, who listens
61
- whiteboard serve run this project's server in the foreground
72
+ whiteboard serve run this project's server in the foreground; for a project of the
73
+ machine's entries, or outside any project, the shared server
62
74
  whiteboard skill [dir] print where the agent skill is, or link it into a skills folder
75
+ whiteboard paths [--write|--read] the folders the shared server needs, ':' between them, for a sandbox
76
+ wrapper to grant: --write the entries' folders and its state, --read
77
+ the machine config and whiteboard itself
63
78
 
64
79
  filters: --page <page|file> (includes pages below it) --type <type>
65
80
  wait: --timeout <seconds> (exit 2 on timeout) --count <n> (default 1)
66
81
  wait, watch without --page: the fallback, taking only what no other wait or watch would, on any
67
- page, also once they stop; one per project (a second exits 1)
82
+ page, also once they stop; one per project (a second exits 1), or, in a project of the
83
+ machine's entries, one for the whole entry, each event with its project and url
68
84
  events: --since <iso time or event id> --last <n>
69
85
 
70
86
  Every command works on the project of the current folder: the nearest folder upward with a
71
87
  .whiteboard/ folder. A project needs no config: .whiteboard/config.ts only says what differs from
72
88
  the defaults (markdown with the built-in plugins). Each project runs its own server; its port is in .whiteboard/server.json.
89
+ A project the machine config's entries include (${machineDir()}/config.json) is served by the one shared
90
+ server instead, under its path (/<entry>/<folder>), with an index of every entry at /. It is started
91
+ outside the agents' sandboxes (\`whiteboard serve\` outside any project, or a login service), and
92
+ \`serve\` takes an older one over; commands never start it. A wait without a server waits for one.
73
93
  A page appends events {id, ts, page, type, action, data} to .whiteboard/events.ndjson;
74
94
  which types it sends is up to its plugins (\`whiteboard docs\` says). The project's plugins
75
95
  can add commands of their own; \`whiteboard help\` in a project lists them.`
@@ -94,7 +114,11 @@ const { values: opts, positionals } =
94
114
  last: { type: 'string' },
95
115
  follow: { type: 'boolean' },
96
116
  id: { type: 'string' },
117
+ out: { type: 'string' },
118
+ skip: { type: 'string' },
97
119
  help: { type: 'boolean', short: 'h' },
120
+ write: { type: 'boolean' },
121
+ read: { type: 'boolean' },
98
122
  },
99
123
  })
100
124
 
@@ -110,13 +134,58 @@ Run \`whiteboard init\` in the folder that should become one.`)
110
134
 
111
135
  const filter = (): EventFilter => ({ page: opts.page ? pageId(needProject(), opts.page) : undefined, type: opts.type })
112
136
 
113
- /** The running server of this project: its base URL, or null. */
114
- const running = (proj: Project) => runningServer(proj)
137
+ /**
138
+ * Is this project one of the machine's entries (see src/entries.ts)? Then the shared server serves
139
+ * it, under its path, and no server of its own runs. A project outside every include runs its own.
140
+ */
141
+ function isShared(proj: Project): boolean {
142
+ const config = readMachineConfig()
143
+ return !!config && !!matchesEntries(config, proj.dir)
144
+ }
145
+
146
+ /**
147
+ * The running server of this project: the URL it is served at (`http://localhost:4777`, or
148
+ * `http://localhost:4777/rg/develop` under the shared server), or null.
149
+ */
150
+ async function running(proj: Project): Promise<string | null> {
151
+ if (!isShared(proj)) return runningServer(proj)
152
+ const file = machineServerFile()
153
+ const shared = await sharedServer(file)
154
+ if (!shared) return null
155
+ // a project made a moment ago: the server looks again
156
+ const mine =
157
+ shared.projects.find(p => p.dir === proj.dir) ??
158
+ (await sharedServer(file, { rescan: true }))?.projects.find(p => p.dir === proj.dir)
159
+ return mine ? `${shared.origin}${mine.base}` : null
160
+ }
115
161
 
116
- /** This project's server, started in the background when it is not running. @returns its base URL */
162
+ /**
163
+ * This project's server, started in the background when it is not running. Under the shared server
164
+ * nothing is started: it is started outside every agent's sandbox (a login service, or `whiteboard
165
+ * serve` in a terminal), since it serves every project of the entries and runs their plugins; a
166
+ * command inside one sandbox would start it boxed in there. Only `show` and a plugin's command that
167
+ * asks for the server get here. @returns the URL it serves the project at
168
+ */
117
169
  async function ensureServer(): Promise<string> {
118
170
  const proj = needProject()
171
+ const shared = isShared(proj)
119
172
  const base = await running(proj)
173
+ if (shared) {
174
+ const server = await sharedServer(machineServerFile())
175
+ if (base) {
176
+ // an older one goes on serving: it is replaced by restarting it, from outside the sandboxes
177
+ if (server && compareVersions(VERSION, server.version) > 0)
178
+ console.error(
179
+ `whiteboard: the shared server runs ${server.version}, this is ${VERSION}; restart it to upgrade (\`whiteboard serve\` takes it over)`,
180
+ )
181
+ return base
182
+ }
183
+ throw new Error(
184
+ server
185
+ ? `the shared server at ${server.origin} does not serve ${proj.dir}; is it in an include of ${machineDir()}/config.json?`
186
+ : `the shared server is not running. It is started outside the agents' sandboxes: as a login service, or with \`whiteboard serve\` in a terminal, outside any project`,
187
+ )
188
+ }
120
189
  if (base) return base
121
190
  // Several commands may get here at once (an agent starting three watches, say): the one that
122
191
  // creates the lock file starts the server, the others wait for it. A lock whose command is gone
@@ -173,13 +242,69 @@ async function ensureServer(): Promise<string> {
173
242
  throw new Error(`server did not start; see ${proj.logFile}`)
174
243
  }
175
244
 
245
+ /** This project's running server, or an error saying how to start one. */
246
+ async function needServer(): Promise<string> {
247
+ const proj = needProject()
248
+ const base = await running(proj)
249
+ if (base) return base
250
+ if (isShared(proj)) {
251
+ const port = recordedSharedPort(machineServerFile())
252
+ throw new Error(
253
+ port
254
+ ? `the shared server recorded on port ${port} did not answer, or does not serve ${proj.dir}`
255
+ : "the shared server is not running. It is started outside the agents' sandboxes: as a login service, or with `whiteboard serve` in a terminal, outside any project",
256
+ )
257
+ }
258
+ throw new Error('no server runs for this project; `whiteboard show <page>` starts it')
259
+ }
260
+
261
+ /** Is there a page (a markdown file) in this folder or below it? */
262
+ function hasPages(dir: string): boolean {
263
+ let entries: fs.Dirent[]
264
+ try {
265
+ entries = fs.readdirSync(dir, { withFileTypes: true })
266
+ } catch {
267
+ return false
268
+ }
269
+ return entries.some(e =>
270
+ e.isDirectory() ? !e.name.startsWith('.') && hasPages(path.join(dir, e.name)) : e.name.endsWith('.md'),
271
+ )
272
+ }
273
+
274
+ /**
275
+ * Ask the project's server. Without one running, a server made for this one question answers it,
276
+ * in this process, on no port: a command that only asks (status, docs, the hooks on every prompt)
277
+ * never starts one. It has no listeners, as no server runs to hold them.
278
+ */
176
279
  async function api(route: string): Promise<any> {
177
- const res = await fetch(`${await ensureServer()}${route}`)
280
+ const base = await running(needProject())
281
+ const res = base ? await fetch(`${base}${route}`) : await askInProcess(route)
178
282
  const body = await res.json()
179
283
  if (!res.ok) throw new Error(body.error ?? res.statusText)
180
284
  return body
181
285
  }
182
286
 
287
+ async function askInProcess(route: string): Promise<Response> {
288
+ // a project without pages has nothing open: no need to load its config to say so (the hooks ask
289
+ // on every prompt, in every project, most of which have no pages)
290
+ if (route.startsWith('/api/status') && !hasPages(needProject().pagesDir)) return Response.json([])
291
+ const { createServer } = await import('../src/server.ts')
292
+ const server = createServer(needProject())
293
+ const listener = http.createServer((req, res) => void server.handle(req, res))
294
+ await new Promise<void>(r => listener.listen(0, '127.0.0.1', r))
295
+ try {
296
+ const { port } = listener.address() as import('node:net').AddressInfo
297
+ const res = await fetch(`http://127.0.0.1:${port}${route}`)
298
+ // read now, while the server is there
299
+ const text = await res.text()
300
+ return new Response(text, { status: res.status, headers: res.headers })
301
+ } finally {
302
+ server.close()
303
+ listener.closeAllConnections()
304
+ listener.close()
305
+ }
306
+ }
307
+
183
308
  /**
184
309
  * Tell the project's server that an agent is waiting, for as long as this command runs: pages show
185
310
  * what is waited for. Holds one connection open, the listener; reconnects when the server restarts.
@@ -192,9 +317,11 @@ async function api(route: string): Promise<any> {
192
317
  function listen(f: EventFilter, command: 'wait' | 'watch', fallback = false): Promise<void> {
193
318
  return new Promise(registered => {
194
319
  const connect = async () => {
320
+ // a wait never starts a server: without one, it waits for one to appear (the log is read
321
+ // without it all the same)
195
322
  let base
196
323
  try {
197
- base = await ensureServer()
324
+ base = await needServer()
198
325
  } catch {
199
326
  return setTimeout(connect, 2000).unref()
200
327
  }
@@ -234,11 +361,14 @@ function listen(f: EventFilter, command: 'wait' | 'watch', fallback = false): Pr
234
361
  * Who else listens, kept current: the fallback leaves to them what they would take. Calls
235
362
  * `changed` after each change (the server's live channel says when).
236
363
  */
237
- async function otherListeners(changed: () => void): Promise<() => Listener[]> {
364
+ async function otherListeners(
365
+ changed: () => void,
366
+ server: () => Promise<string> = needServer,
367
+ ): Promise<() => Listener[]> {
238
368
  let list: Listener[] = []
239
369
  const load = async () => {
240
370
  try {
241
- list = (await (await fetch(`${await ensureServer()}/api/listeners`)).json()) as Listener[]
371
+ list = (await (await fetch(`${await server()}/api/listeners`)).json()) as Listener[]
242
372
  } catch {
243
373
  /* the server restarts */
244
374
  }
@@ -254,7 +384,7 @@ async function otherListeners(changed: () => void): Promise<() => Listener[]> {
254
384
  }
255
385
  let base
256
386
  try {
257
- base = await ensureServer()
387
+ base = await server()
258
388
  } catch {
259
389
  return retry()
260
390
  }
@@ -329,8 +459,11 @@ const relFile = (file: string) => path.relative(process.cwd(), file) || file
329
459
  * The project's config, as the command line needs it: for its plugins (their commands, the
330
460
  * session, which events reach an agent), so without the pages. Loaded once per command.
331
461
  */
332
- let loaded: ReturnType<ReturnType<typeof createConfigLoader>['config']> | null = null
333
- const projectConfig = (proj: Project) => (loaded ??= createConfigLoader(proj, { pages: false }).config())
462
+ const loaded = new Map<string, ReturnType<ReturnType<typeof createConfigLoader>['config']>>()
463
+ const projectConfig = (proj: Project) => {
464
+ if (!loaded.has(proj.dir)) loaded.set(proj.dir, createConfigLoader(proj, { pages: false }).config())
465
+ return loaded.get(proj.dir)!
466
+ }
334
467
 
335
468
  /**
336
469
  * The agent session this command runs in, as the project's plugins know it (Claude Code's
@@ -369,16 +502,56 @@ async function status() {
369
502
 
370
503
  switch (cmd) {
371
504
  case 'serve': {
505
+ // outside any project, with a machine config: the shared server (to start at login, say)
506
+ if (!project && readMachineConfig()) {
507
+ const { startShared } = await import('../src/serve.ts')
508
+ await startShared()
509
+ break
510
+ }
372
511
  const proj = needProject()
512
+ if (isShared(proj)) {
513
+ // the shared server, for every entry's projects; it takes over from an older one itself
514
+ const { startShared } = await import('../src/serve.ts')
515
+ await startShared()
516
+ break
517
+ }
373
518
  const base = await running(proj)
374
519
  if (base) {
375
520
  console.error(`whiteboard: ${proj.name} is already served at ${base}`)
376
521
  process.exit(1)
377
522
  }
523
+ // the server only for the commands that run one: every other command (the hooks' among them,
524
+ // on every prompt) starts without it, a good part of its start-up time
378
525
  const { start } = await import('../src/serve.ts')
379
526
  await start(proj)
380
527
  break
381
528
  }
529
+ case 'build': {
530
+ // pages rendered once, as a static site: the config's `build`, with what is given here over it
531
+ const proj = needProject()
532
+ const { createServer } = await import('../src/server.ts') // as for serve: only when needed
533
+ const server = createServer(proj)
534
+ try {
535
+ const result = await server.build({
536
+ pages: positionals.length ? positionals : undefined,
537
+ out: opts.out,
538
+ skip:
539
+ opts.skip != null
540
+ ? opts.skip
541
+ .split(',')
542
+ .map(s => s.trim())
543
+ .filter(Boolean)
544
+ : undefined,
545
+ })
546
+ for (const w of result.warnings) console.error(`whiteboard build: ${w}`)
547
+ console.log(
548
+ `built ${result.pages.length} page${result.pages.length === 1 ? '' : 's'} into ${path.relative(process.cwd(), result.out) || '.'}`,
549
+ )
550
+ } finally {
551
+ server.close()
552
+ }
553
+ process.exit(0)
554
+ }
382
555
  case 'init': {
383
556
  init(positionals[0])
384
557
  break
@@ -423,7 +596,7 @@ switch (cmd) {
423
596
  case 'show':
424
597
  case 'url': {
425
598
  if (cmd === 'show' && !positionals[0]) throw new Error('usage: whiteboard show <page|file>')
426
- const base = await ensureServer()
599
+ const base = cmd === 'show' ? await ensureServer() : await needServer()
427
600
  console.log(`${base}/${pageId(project, positionals[0] ?? '')}`)
428
601
  break
429
602
  }
@@ -507,7 +680,7 @@ switch (cmd) {
507
680
  if (!target || !to) throw new Error('usage: whiteboard scroll <page|file> <heading, form name or text>')
508
681
  const proj = needProject()
509
682
  const id = pageId(proj, target)
510
- const base = await ensureServer()
683
+ const base = await needServer()
511
684
  // what the page shows, to say now when nothing on it matches
512
685
  const rendered = (await (
513
686
  await fetch(`${base}/api/render?page=${encodeURIComponent(id)}`)
@@ -627,6 +800,12 @@ switch (cmd) {
627
800
  // events (default 1); `watch` never does.
628
801
  const proj = needProject()
629
802
  const f = filter()
803
+ // without --page in a project of the machine's entries: the fallback of the whole entry
804
+ const entry = !f.page && isShared(proj) ? matchesEntries(readMachineConfig()!, proj.dir) : null
805
+ if (entry) {
806
+ await entryFallback(entry, f, cmd)
807
+ break
808
+ }
630
809
  const { handedOut } = await projectConfig(proj)
631
810
  // without --page, the fallback: only what no other listener would take, on any page, as it comes
632
811
  // and once they stop listening (an answer left in the log, too)
@@ -703,6 +882,26 @@ switch (cmd) {
703
882
  case 'status':
704
883
  await status()
705
884
  break
885
+ case 'paths': {
886
+ // what the shared server needs of the disk, from the machine config: for whatever boxes it in
887
+ // (a sandbox wrapper: `safehouse --add-dirs="$(whiteboard paths --write)" …`)
888
+ const config = readMachineConfig()
889
+ if (!config) throw new Error(`no machine config: ${machineDir()}/config.json`)
890
+ const paths = serverPaths(config, { packageDir: PACKAGE_DIR })
891
+ // a sandbox grants only folders that exist: the state folder is whiteboard's own, so it is made
892
+ // here; an entry's folder not there yet is left out (a restart grants it once it is)
893
+ try {
894
+ fs.mkdirSync(stateDir(), { recursive: true })
895
+ } catch {
896
+ /* made by whoever may: the wrapper runs outside the agents' sandboxes */
897
+ }
898
+ const write = paths.write.filter(d => fs.existsSync(d))
899
+ const read = paths.read.filter(d => fs.existsSync(d))
900
+ if (opts.write) console.log(write.join(':'))
901
+ else if (opts.read) console.log(read.join(':'))
902
+ else console.log(`write: ${write.join(':')}\nread: ${read.join(':')}`)
903
+ break
904
+ }
706
905
  case 'skill': {
707
906
  // the agent skill ships in this package; link it into whatever folder an agent reads skills from
708
907
  const source = packagePath('skills', 'whiteboard')
@@ -771,6 +970,122 @@ switch (cmd) {
771
970
  }
772
971
  }
773
972
 
973
+ /**
974
+ * The fallback of a whole entry: what no other wait or watch in any of its projects would take, on
975
+ * any page, also once they stop, from each project's own log, each event with the project it is
976
+ * from (`project`, its folder) and its page's `url`. One per entry: the shared server holds it, and
977
+ * refuses a second (exit 1). Without a shared server running it waits for one, as any wait does: who
978
+ * else listens is the server's to say. Projects that appear meanwhile are followed too.
979
+ */
980
+ async function entryFallback(entry: string, f: EventFilter, command: 'wait' | 'watch') {
981
+ const file = machineServerFile()
982
+ const count = command === 'wait' ? Number(opts.count ?? 1) : Infinity
983
+ const done = new AbortController()
984
+ let total = 0
985
+ // after the last event is recorded as picked up, which follows handing it out
986
+ done.signal.addEventListener('abort', () => setImmediate(() => process.exit(0)))
987
+ if (opts.timeout && command === 'wait')
988
+ setTimeout(
989
+ () => {
990
+ console.error('timeout')
991
+ process.exit(2)
992
+ },
993
+ Number(opts.timeout) * 1000,
994
+ )
995
+ // hold the entry's fallback at the shared server, for as long as this runs (again after a restart)
996
+ await new Promise<void>(registered => {
997
+ const connect = async () => {
998
+ const shared = await sharedServer(file)
999
+ if (!shared) return setTimeout(connect, 2000).unref()
1000
+ const q = new URLSearchParams({ entry, command, ...(f.type ? { type: f.type } : {}) })
1001
+ let again = false
1002
+ const retry = (ms: number) => {
1003
+ if (!again) {
1004
+ again = true
1005
+ setTimeout(connect, ms).unref()
1006
+ }
1007
+ }
1008
+ const req = http.get(`${shared.origin}/api/listen?${q}`, res => {
1009
+ if (res.statusCode === 409) {
1010
+ let body = ''
1011
+ res.on('data', d => (body += d))
1012
+ res.on('end', () => {
1013
+ console.error(
1014
+ `whiteboard: ${JSON.parse(body || '{}').error ?? 'another agent is the fallback'}. Add --page to wait on a page of your own.`,
1015
+ )
1016
+ process.exit(1)
1017
+ })
1018
+ return
1019
+ }
1020
+ res.resume()
1021
+ registered()
1022
+ res.on('close', () => retry(1000))
1023
+ })
1024
+ req.on('error', () => retry(2000))
1025
+ req.on('socket', socket => socket.unref())
1026
+ }
1027
+ connect()
1028
+ })
1029
+ // a hand-out per project of the entry, as the shared server knows them
1030
+ const following = new Map<string, AbortController>()
1031
+ async function start(p: { dir: string; base: string }, origin: string) {
1032
+ const proj = projectAt(p.dir)
1033
+ if (!proj) return
1034
+ const stop = new AbortController()
1035
+ following.set(p.dir, stop)
1036
+ const { handedOut } = await projectConfig(proj)
1037
+ let recheck = () => {}
1038
+ const at = async () => {
1039
+ const shared = await sharedServer(file)
1040
+ const now = shared?.projects.find(x => x.dir === p.dir)
1041
+ if (!shared || !now) throw new Error('not served')
1042
+ return `${shared.origin}${now.base}`
1043
+ }
1044
+ const others = await otherListeners(() => recheck(), at)
1045
+ // as for a project's fallback: hold each event a moment, for a wait that just started
1046
+ const held = new Set<string>()
1047
+ const skip = (e: WbEvent) => {
1048
+ if (!held.has(e.id)) {
1049
+ held.add(e.id)
1050
+ setTimeout(() => recheck(), 500).unref()
1051
+ return true
1052
+ }
1053
+ return takenByOther(others(), e)
1054
+ }
1055
+ const page = (id: string) => id.split('/').map(encodeURIComponent).join('/')
1056
+ await handOut(
1057
+ proj.eventsFile,
1058
+ { type: f.type },
1059
+ e => {
1060
+ console.log(JSON.stringify({ ...e, project: p.dir, url: `${origin}${p.base}/${page(e.page)}` }))
1061
+ if (++total >= count) done.abort()
1062
+ },
1063
+ {
1064
+ forAgent: forAgent(handedOut),
1065
+ signal: AbortSignal.any([stop.signal, done.signal]),
1066
+ skip,
1067
+ recheck: again => {
1068
+ recheck = again
1069
+ },
1070
+ },
1071
+ )
1072
+ }
1073
+ const sync = async () => {
1074
+ const shared = await sharedServer(file)
1075
+ if (!shared) return
1076
+ const mine = shared.projects.filter(p => p.entry === entry)
1077
+ for (const p of mine) if (!following.has(p.dir)) void start(p, shared.origin)
1078
+ for (const [dir, stop] of following)
1079
+ if (!mine.some(p => p.dir === dir)) {
1080
+ stop.abort()
1081
+ following.delete(dir)
1082
+ }
1083
+ }
1084
+ await sync()
1085
+ // keeps the command running, and follows projects coming and going
1086
+ setInterval(sync, 2000)
1087
+ }
1088
+
774
1089
  /** The commands the project's plugins add: `whiteboard <plugin> [sub]`. */
775
1090
  async function projectCommands(proj: Project) {
776
1091
  const { plugins, errors } = await projectConfig(proj)