@bigmistqke/workpad 0.18.1 → 0.20.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 (109) hide show
  1. package/README.md +18 -9
  2. package/bin/workpad.ts +412 -58
  3. package/dist/bin/workpad.js +336 -46
  4. package/dist/client/runtime.js +141 -18
  5. package/dist/plugins/badge/README.md +59 -10
  6. package/dist/plugins/badge/index.js +130 -8
  7. package/dist/plugins/badge/public/style.css +132 -12
  8. package/dist/plugins/chat/README.md +7 -3
  9. package/dist/plugins/chat/index.js +8 -1
  10. package/dist/plugins/chat/public/client.js +2 -2
  11. package/dist/plugins/chat/public/style.css +10 -0
  12. package/dist/plugins/claude/README.md +13 -5
  13. package/dist/plugins/claude/channel.js +47 -6
  14. package/dist/plugins/claude/doctor.js +43 -47
  15. package/dist/plugins/claude/index.js +24 -8
  16. package/dist/plugins/claude/session.js +46 -1
  17. package/dist/plugins/comments/README.md +2 -1
  18. package/dist/plugins/comments/index.js +2 -0
  19. package/dist/plugins/comments/public/client.js +6 -5
  20. package/dist/plugins/comments/public/style.css +9 -0
  21. package/dist/plugins/form/README.md +1 -1
  22. package/dist/plugins/index.js +3 -1
  23. package/dist/plugins/opencode/channel.js +43 -7
  24. package/dist/plugins/opencode/index.js +2 -0
  25. package/dist/plugins/progress/README.md +41 -0
  26. package/dist/plugins/progress/index.js +117 -0
  27. package/dist/plugins/progress/public/client.js +1 -0
  28. package/dist/plugins/progress/public/style.css +85 -0
  29. package/dist/plugins/progress/state.js +210 -0
  30. package/dist/solid/index.js +3 -1
  31. package/dist/src/agents.js +13 -4
  32. package/dist/src/anchors.js +25 -1
  33. package/dist/src/build.js +1 -1
  34. package/dist/src/client/page/base.css +48 -2
  35. package/dist/src/client/page/main.js +58 -30
  36. package/dist/src/document.js +6 -4
  37. package/dist/src/events.js +22 -11
  38. package/dist/src/help.js +59 -12
  39. package/dist/src/hub.js +69 -3
  40. package/dist/src/listen.js +36 -4
  41. package/dist/src/listeners.js +14 -4
  42. package/dist/src/loader.js +7 -2
  43. package/dist/src/migrate.js +1 -1
  44. package/dist/src/pages/board.js +9 -4
  45. package/dist/src/pages/index.js +2 -4
  46. package/dist/src/pages/markdown.js +50 -19
  47. package/dist/src/pages/render.js +17 -1
  48. package/dist/src/server.js +94 -18
  49. package/dist/src/set.js +99 -0
  50. package/dist/src/state.js +2 -1
  51. package/dist/src/status.js +57 -9
  52. package/dist/src/turns.js +41 -0
  53. package/package.json +11 -1
  54. package/plugins/README.md +3 -1
  55. package/plugins/badge/README.md +59 -10
  56. package/plugins/badge/index.ts +141 -8
  57. package/plugins/badge/public/style.css +132 -12
  58. package/plugins/chat/README.md +7 -3
  59. package/plugins/chat/client.tsx +20 -3
  60. package/plugins/chat/index.ts +10 -1
  61. package/plugins/chat/public/style.css +10 -0
  62. package/plugins/claude/README.md +13 -5
  63. package/plugins/claude/channel.ts +45 -7
  64. package/plugins/claude/doctor.ts +58 -39
  65. package/plugins/claude/index.ts +30 -8
  66. package/plugins/claude/session.ts +32 -0
  67. package/plugins/comments/README.md +2 -1
  68. package/plugins/comments/client.ts +19 -0
  69. package/plugins/comments/index.ts +7 -1
  70. package/plugins/comments/public/style.css +9 -0
  71. package/plugins/form/README.md +1 -1
  72. package/plugins/index.ts +2 -0
  73. package/plugins/opencode/channel.ts +44 -8
  74. package/plugins/opencode/index.ts +4 -0
  75. package/plugins/progress/README.md +41 -0
  76. package/plugins/progress/client.ts +172 -0
  77. package/plugins/progress/index.ts +166 -0
  78. package/plugins/progress/public/style.css +85 -0
  79. package/plugins/progress/state.ts +278 -0
  80. package/skills/workpad/SKILL.md +149 -18
  81. package/solid/index.tsx +6 -2
  82. package/src/agents.ts +24 -2
  83. package/src/anchors.ts +32 -0
  84. package/src/build.ts +1 -1
  85. package/src/client/delivery.ts +49 -0
  86. package/src/client/forms.ts +18 -11
  87. package/src/client/page/base.css +48 -2
  88. package/src/client/page/waiting.ts +45 -25
  89. package/src/client/read.ts +9 -5
  90. package/src/client/runtime.ts +7 -3
  91. package/src/client/toast.ts +27 -3
  92. package/src/define.ts +120 -9
  93. package/src/document.ts +19 -5
  94. package/src/events.ts +47 -6
  95. package/src/help.ts +58 -11
  96. package/src/hub.ts +80 -2
  97. package/src/listen.ts +47 -4
  98. package/src/listeners.ts +22 -1
  99. package/src/loader.ts +14 -4
  100. package/src/migrate.ts +1 -1
  101. package/src/pages/board.ts +12 -3
  102. package/src/pages/index.ts +8 -10
  103. package/src/pages/markdown.ts +59 -12
  104. package/src/pages/render.ts +20 -2
  105. package/src/server.ts +127 -19
  106. package/src/set.ts +118 -0
  107. package/src/state.ts +3 -0
  108. package/src/status.ts +115 -14
  109. package/src/turns.ts +56 -0
package/bin/workpad.ts CHANGED
@@ -28,6 +28,7 @@ import {
28
28
  receivedIds,
29
29
  channelSince,
30
30
  subscriptions,
31
+ takesUnfollowed,
31
32
  UNSUBSCRIBE,
32
33
  } from '../src/events.ts'
33
34
  import { BUILTIN_COMMANDS, createConfigLoader, pluginDir } from '../src/loader.ts'
@@ -37,7 +38,8 @@ import { archived, archiveFile } from '../src/archive.ts'
37
38
  import { thread } from '../src/thread.ts'
38
39
  import { markdownFiles, migrate } from '../src/migrate.ts'
39
40
  import { OLD, machineSteps, oldProjectDir, projectSteps } from '../src/rename.ts'
40
- import { anchorsOf, hashOf, type Anchor } from '../src/anchors.ts'
41
+ import { anchorsOf, hashOf, nearest, type Anchor } from '../src/anchors.ts'
42
+ import { findBlock, setBlock } from '../src/set.ts'
41
43
  import { projectToken } from '../src/auth.ts'
42
44
  import { PACKAGE_DIR, packagePath } from '../src/package.ts'
43
45
  import {
@@ -59,10 +61,12 @@ import {
59
61
  stateDir,
60
62
  } from '../src/entries.ts'
61
63
  import { compareVersions, VERSION } from '../src/package.ts'
62
- import { statusLines, whose } from '../src/status.ts'
64
+ import { refusal, statusLines, whose } from '../src/status.ts'
63
65
  import { holdForms, releaseForms, settleForms } from '../src/formstate.ts'
64
66
  import { client, probe } from '../src/api.ts'
65
- import { everyProject, holdChannel, listen } from '../src/listen.ts'
67
+ import { everyPage, everyProject, holdChannel, listen } from '../src/listen.ts'
68
+ import { lastTurnEnd } from '../src/turns.ts'
69
+ import { line as progressLine, running as runningProgress } from '../plugins/progress/state.ts'
66
70
  import type { Listener, PageStatus, WpEvent } from '../src/define.ts'
67
71
 
68
72
  // a failing command prints its message, not a stack trace
@@ -127,7 +131,11 @@ const { values: opts, positionals } =
127
131
  clear: { type: 'boolean' },
128
132
  wait: { type: 'boolean' },
129
133
  channel: { type: 'boolean' },
134
+ unfollowed: { type: 'boolean' },
130
135
  all: { type: 'boolean' },
136
+ file: { type: 'string' },
137
+ 'text-file': { type: 'string' },
138
+ 'replace-with': { type: 'string' },
131
139
  },
132
140
  })
133
141
 
@@ -160,6 +168,9 @@ Run \`workpad init\` in the folder that should become one.`)
160
168
 
161
169
  const filter = (): EventFilter => ({ page: pageOpt ? pageId(needProject(), pageOpt) : undefined, type: opts.type })
162
170
 
171
+ /** The longest `workpad agent ping --wait` waits, turn or no turn: a background process never lingers. */
172
+ const MAX_WAIT = 30 * 60_000
173
+
163
174
  /** The running server of this project: the URL it is served at, or null (see projectServer). */
164
175
  const running = (proj: Project): Promise<string | null> => projectServer(proj)
165
176
 
@@ -290,6 +301,46 @@ function pageIn(target: string): { proj: Project; id: string } {
290
301
  return { proj, id: pageId(proj, target) }
291
302
  }
292
303
 
304
+ /** The file a page or repository file of the project is: `README.md`, `plan`, `.workpad/pages/plan.md`. */
305
+ function fileOf(proj: Project, target: string): string {
306
+ const id = pageId(proj, target)
307
+ if (!id) throw new Error(`no page ${target}`)
308
+ return id === '-' || id.startsWith('-/') ? path.join(proj.dir, id.slice(2)) : path.join(proj.pagesDir, `${id}.md`)
309
+ }
310
+
311
+ /**
312
+ * What a file holds, or with `-` what comes on standard input: for markdown and JSON an agent writes,
313
+ * which never passes through the shell's quoting that way (a heredoc with a quoted delimiter, or a file).
314
+ */
315
+ function readInput(from: string, option: string): string {
316
+ if (from === '-') return fs.readFileSync(0, 'utf8')
317
+ if (!fs.existsSync(from)) throw new Error(`${option} ${from}: no such file`)
318
+ return fs.readFileSync(from, 'utf8')
319
+ }
320
+
321
+ /**
322
+ * An event's data as the command line gives it: JSON from --data or --file (a file, or - for standard
323
+ * input), with --text-file's contents (a file, or -) as its `text`. Nothing given: undefined.
324
+ */
325
+ function eventData(): unknown {
326
+ if (opts.data !== undefined && opts.file !== undefined) throw new Error('give the data with --data or --file, not both')
327
+ const json = opts.file !== undefined ? readInput(opts.file, '--file') : opts.data
328
+ let data: unknown
329
+ if (json !== undefined) {
330
+ try {
331
+ data = JSON.parse(json)
332
+ } catch {
333
+ throw new Error(
334
+ `${opts.file !== undefined ? `--file ${opts.file}` : '--data'} must be JSON, e.g. {"text":"…"}; for markdown, --text-file <file|->`,
335
+ )
336
+ }
337
+ }
338
+ if (opts['text-file'] === undefined) return data
339
+ if (data !== undefined && (!data || typeof data !== 'object' || Array.isArray(data)))
340
+ throw new Error('with --text-file, the data must be a JSON object: the text goes in as its "text"')
341
+ return { ...(data as object | undefined), text: readInput(opts['text-file'], '--text-file').replace(/\s+$/, '') }
342
+ }
343
+
293
344
  /** Where a project is served: its running server, or an error saying how to start one. */
294
345
  async function serverOf(proj: Project): Promise<string> {
295
346
  if (proj.dir === project?.dir) return needServer()
@@ -337,16 +388,39 @@ function hasPages(dir: string): boolean {
337
388
  /**
338
389
  * Ask the project's server. Without one running, a server made for this one question answers it,
339
390
  * in this process, on no port: a command that only asks (status, docs, the hooks on every prompt)
340
- * never starts one. It has no listeners, as no server runs to hold them.
391
+ * never starts one. It has no listeners, as no server runs to hold them. A server that runs but is
392
+ * busy is waited for (`runningOrBusy`): answered in this process, its listeners would be missed.
341
393
  */
342
394
  async function api(route: string): Promise<any> {
343
- const base = await running(needProject())
395
+ const base = await runningOrBusy(needProject())
344
396
  const res = base ? await fetch(`${base}${route}`) : await askInProcess(route)
345
397
  const body = await res.json()
346
398
  if (!res.ok) throw new Error(body.error ?? res.statusText)
347
399
  return body
348
400
  }
349
401
 
402
+ /** How long a command waits for a server too busy to answer (a status over many pages can take seconds). */
403
+ const BUSY_WAIT = 30_000
404
+
405
+ /**
406
+ * The running server of `proj`, or null when none runs. One that accepts connections and gives its
407
+ * health check no answer in time is busy, its event loop blocked by a slow request: it is waited
408
+ * for, up to BUSY_WAIT, then said to be stuck. Taken for none, a question would be answered without
409
+ * it, by a server in this process that knows nobody who listens.
410
+ */
411
+ async function runningOrBusy(proj: Project): Promise<string | null> {
412
+ const base = await running(proj)
413
+ if (base) return base
414
+ const shared = isShared(proj)
415
+ const at = recordedOrigin(shared ? machineServerFile() : proj.serverFile)
416
+ if (!at) return null
417
+ const deadline = Date.now() + BUSY_WAIT
418
+ while (await stuckAt(at))
419
+ if (Date.now() > deadline) throw new Error(stuck(at, shared ? 'its login service log' : proj.logFile))
420
+ // it answers now (or nothing is there): whether it is this project's
421
+ return running(proj)
422
+ }
423
+
350
424
  async function askInProcess(route: string): Promise<Response> {
351
425
  // a project without pages has nothing open: no need to load its config to say so (the hooks ask
352
426
  // on every prompt, in every project, most of which have no pages)
@@ -488,6 +562,18 @@ async function whoAmI(proj: Project): Promise<string | null> {
488
562
  return (opts.agent as string | undefined) || process.env.WORKPAD_AGENT || (await currentSession(proj))
489
563
  }
490
564
 
565
+ /**
566
+ * Who runs this command, and the other id it goes by: the agent session a plugin names, when
567
+ * `--agent` or `WORKPAD_AGENT` named it otherwise. What it writes records both (appendEvent), and a
568
+ * listen leaves out what either wrote: a channel that knows the agent by its session, and the
569
+ * agent's commands that name it, are the same agent.
570
+ */
571
+ async function whoAmIWithSession(proj: Project): Promise<{ me: string | null; session: string | null }> {
572
+ const session = await currentSession(proj)
573
+ const me = (opts.agent as string | undefined) || process.env.WORKPAD_AGENT || session
574
+ return { me, session: session !== me ? session : null }
575
+ }
576
+
491
577
  /**
492
578
  * The agent session this command runs in, as the project's plugins know it (Claude Code's
493
579
  * plugin reads it from the environment): the first one that names one. Null without any.
@@ -518,16 +604,24 @@ async function status() {
518
604
  api(`/api/status${pageOpt ? `?page=${encodeURIComponent(pageId(proj, pageOpt))}` : ''}`),
519
605
  whoAmI(proj),
520
606
  ])
521
- const names = namesOf(readEvents(proj.eventsFile))
607
+ const events = readEvents(proj.eventsFile)
608
+ const names = namesOf(events)
522
609
  const busy = pages.filter(p => p.unreceived.length || p.open.length)
523
- if (!busy.length) {
524
- console.log('nothing open: every question is answered, and every answer received')
525
- return
526
- }
610
+ // the progress running on the pages asked about (plugins/progress), the latest moved first
611
+ const now = Date.now()
612
+ const runs = runningProgress(events).filter(r => pages.some(p => p.page === r.page))
613
+ if (!busy.length) console.log('nothing open: every question is answered, and every answer received')
527
614
  for (const p of busy) {
528
615
  console.log(`${p.page} (${whose(p, me, names)})`)
529
616
  for (const l of statusLines(p, relFile(p.file))) console.log(` ${l}`)
530
617
  }
618
+ if (runs.length) {
619
+ console.log('running:')
620
+ for (const r of runs)
621
+ console.log(
622
+ ` ${r.page}: ${progressLine(r, now)}${r.by ? ` (${r.by === me ? 'you' : (names.get(r.by) ?? r.by)})` : ''}`,
623
+ )
624
+ }
531
625
  }
532
626
 
533
627
  switch (cmd) {
@@ -660,7 +754,11 @@ switch (cmd) {
660
754
  const subscribed = new Map<string, string[]>()
661
755
  const seen = new Set<string>()
662
756
  for (const e of events) if (e.by) seen.add(e.by)
663
- for (const e of subscriptions(events)) subscribed.set(e.by!, [...(subscribed.get(e.by!) ?? []), e.page || 'every page'])
757
+ for (const e of subscriptions(events))
758
+ subscribed.set(e.by!, [
759
+ ...(subscribed.get(e.by!) ?? []),
760
+ e.data?.unfollowed ? 'the pages no one follows (through its channel)' : e.page || 'every page',
761
+ ])
664
762
  const listening = new Map<string, string[]>()
665
763
  const base = await running(proj)
666
764
  if (base)
@@ -710,6 +808,7 @@ switch (cmd) {
710
808
  const code = arg
711
809
  if (!code && !me) throw nobody()
712
810
  const base = await ensureServer()
811
+ const pinged = Date.now()
713
812
  const res = await fetch(`${base}/api/ping`, {
714
813
  method: 'POST',
715
814
  headers: { 'content-type': 'application/json' },
@@ -737,21 +836,41 @@ switch (cmd) {
737
836
  else if (body.confirmed) console.log(`answers on your pages come to you already, through this session’s channel.${await covers()}`)
738
837
  else if (body.sent && opts.wait) {
739
838
  // run in the background: it ends, and so wakes the agent, when the pong it pushed is confirmed,
740
- // or when none came in time: then nothing brings answers here, and the agent listens instead
839
+ // or when none came in time: then nothing brings answers here, and the agent listens instead.
840
+ // The pong can't come before the session's turn ends, and the agent works on meanwhile: so
841
+ // the timeout counts from the first turn end after the ping, as its plugin's hook records it
842
+ // (turns.ts). A session whose turn ends aren't recorded counts from the ping. Either way it
843
+ // gives up after MAX_WAIT, so it never lingers.
741
844
  console.log('pinged this session’s channel: a pong comes to you as a message; confirm it with the command it names')
742
- const limit = Date.now() + (opts.timeout ? Number(opts.timeout) * 1000 : 120_000)
743
- while (Date.now() < limit) {
845
+ const timeout = opts.timeout ? Number(opts.timeout) * 1000 : 120_000
846
+ const giveUp = pinged + MAX_WAIT
847
+ const secs = `${Math.round(timeout / 1000)} s`
848
+ /** the first turn end after the ping, once seen: the one a pong would have come at */
849
+ let ended: number | null = null
850
+ for (;;) {
744
851
  await new Promise(r => setTimeout(r, 1000))
745
852
  const channels = (await api('/api/channels')) as { session: string | null; confirmed: boolean }[]
746
853
  if (channels.some(c => c.session === me && c.confirmed)) {
747
854
  console.log(`confirmed: answers on your pages come to you now.${await covers()}`)
748
855
  process.exit(0)
749
856
  }
857
+ const turns = lastTurnEnd(proj.wp, me!)
858
+ if (ended === null && turns?.ended != null && turns.ended >= pinged) ended = turns.ended
859
+ const why =
860
+ Date.now() >= giveUp
861
+ ? `no pong came within ${MAX_WAIT / 60_000} minutes`
862
+ : ended !== null && Date.now() >= ended + timeout
863
+ ? `no pong came within ${secs} after your turn ended`
864
+ : !turns && Date.now() >= pinged + timeout
865
+ ? `no pong came within ${secs}`
866
+ : null
867
+ if (why) {
868
+ console.log(
869
+ `${why}: nothing brings answers here. Listen for them (\`workpad listen --wait --page <file>\` in the background), and in Claude Code tell the user what \`workpad claude doctor\` says is wrong`,
870
+ )
871
+ process.exit(1)
872
+ }
750
873
  }
751
- console.log(
752
- 'no pong was confirmed in time: nothing brings answers here. Listen for them (`workpad listen --wait --page <file>` in the background), and in Claude Code tell the user what `workpad claude doctor` says is wrong',
753
- )
754
- process.exit(1)
755
874
  } else if (body.sent)
756
875
  console.log(
757
876
  'pinged this session’s channel: a pong comes to you as a message, the way answers will, with the command that confirms it. It may only come once your turn has ended, so start no listen yet. Run `workpad agent ping --wait` in the background instead, and it ends when you confirmed the pong or when none came: then listen',
@@ -812,6 +931,58 @@ switch (cmd) {
812
931
  .replace(/&#39;/g, "'")
813
932
  .replace(/&amp;/g, '&')
814
933
  .trim()
934
+ // the anchors of each page a link goes to, rendered once (null: there is no such page)
935
+ const anchorsOfPage = new Map<string, Promise<string[] | null>>()
936
+ const anchorsFor = (page: string) => {
937
+ if (!anchorsOfPage.has(page))
938
+ anchorsOfPage.set(
939
+ page,
940
+ anchorsAt(base, page).then(
941
+ as => as.map(a => a.id),
942
+ () => null,
943
+ ),
944
+ )
945
+ return anchorsOfPage.get(page)!
946
+ }
947
+ const served = new URL(base)
948
+ const root = served.pathname.replace(/\/$/, '')
949
+ /**
950
+ * The links of a rendered page to a place on another page of this project (`decisions.md#form:x`,
951
+ * or its own page by its file) whose anchor that page doesn't have. A link to `#…` alone is the
952
+ * render's own notice; one to another project, server or site isn't checked.
953
+ */
954
+ const brokenLinks = async (id: string, body: string): Promise<string[]> => {
955
+ const out: string[] = []
956
+ for (const m of body.matchAll(/<a\b[^>]*?\shref="([^"]*)"/g)) {
957
+ const href = text(m[1])
958
+ if (!href || href.startsWith('#')) continue
959
+ let url: URL
960
+ try {
961
+ url = new URL(href, `${base}/${id.split('/').map(encodeURIComponent).join('/')}`)
962
+ } catch {
963
+ continue
964
+ }
965
+ if (url.origin !== served.origin || !url.pathname.startsWith(`${root}/`) || url.hash.length < 2) continue
966
+ let page: string
967
+ let anchor: string
968
+ try {
969
+ page = decodeURIComponent(url.pathname.slice(root.length + 1)).replace(/\/$/, '')
970
+ anchor = decodeURIComponent(url.hash.slice(1))
971
+ } catch {
972
+ continue
973
+ }
974
+ // a chat message is drawn later, and a file of the repository other than markdown has none
975
+ if (anchor.startsWith('message:')) continue
976
+ const repo = page === '-' || page.startsWith('-/')
977
+ if (repo ? !/\.(md|markdown)$/i.test(page) : path.extname(page) && !/\.md$/i.test(page)) continue
978
+ if (!repo) page = page.replace(/\.md$/i, '')
979
+ const has = await anchorsFor(page)
980
+ if (!has) out.push(`a link to \`${page}${hashOf(anchor)}\`: there is no page ${page}`)
981
+ else if (!has.includes(anchor))
982
+ out.push(`a link to \`${page}${hashOf(anchor)}\`, which ${page} doesn't have${nearest(anchor, has)}`)
983
+ }
984
+ return out
985
+ }
815
986
  let found = 0
816
987
  const config = new Set<string>()
817
988
  for (const id of ids) {
@@ -822,10 +993,13 @@ switch (cmd) {
822
993
  continue
823
994
  }
824
995
  const { html: body = '', notices = [] } = (await res.json()) as { html?: string; notices?: string[] }
996
+ anchorsOfPage.set(id, Promise.resolve(anchorsOf(body).map(a => a.id)))
825
997
  const errors = [...body.matchAll(/<(\w+) class="wp-error"[^>]*>([\s\S]*?)<\/\1>/g)].map(m => text(m[2]))
826
998
  // the config's errors are every page's: said once, at the end
827
999
  for (const n of notices) if (n.startsWith('config: ')) config.add(n)
828
- const problems = [...new Set([...notices.filter(n => !n.startsWith('config: ')), ...errors])]
1000
+ const problems = [
1001
+ ...new Set([...notices.filter(n => !n.startsWith('config: ')), ...errors, ...(await brokenLinks(id, body))]),
1002
+ ]
829
1003
  if (!problems.length) continue
830
1004
  found += problems.length
831
1005
  console.log(`${id}\n${problems.map(p => ` ${p.replace(/\n/g, '\n ')}`).join('\n')}`)
@@ -889,6 +1063,21 @@ switch (cmd) {
889
1063
  console.log(`${hashOf(a.id)} ${a.kind}${a.label !== a.id.slice(a.kind.length + 1) ? ` ${a.label}` : ''}`)
890
1064
  break
891
1065
  }
1066
+ case 'set': {
1067
+ // a block of a page replaced by name (a form, a heading's section, a named block), with markdown
1068
+ // from a file or standard input: found by parsing the page, never by matching its text
1069
+ const [target, name] = positionals
1070
+ if (!target || !name || opts.file === undefined)
1071
+ throw new Error('usage: workpad set <page|file> <anchor|form> --file <file|->')
1072
+ const proj = needProject()
1073
+ const file = fileOf(proj, target)
1074
+ if (!fs.existsSync(file)) throw new Error(`no page ${target} (${relFile(file)})`)
1075
+ const source = fs.readFileSync(file, 'utf8')
1076
+ const block = findBlock(source, name)
1077
+ fs.writeFileSync(file, setBlock(source, name, readInput(opts.file, '--file')))
1078
+ console.log(`replaced ${hashOf(block.id)} (${block.kind === 'heading' ? 'its section' : block.kind}) in ${relFile(file)}`)
1079
+ break
1080
+ }
892
1081
  case 'archive':
893
1082
  case 'destroy': {
894
1083
  // a page that has done its job: its file leaves the pages, and its events leave the log (answers,
@@ -962,17 +1151,14 @@ switch (cmd) {
962
1151
  case 'edit': {
963
1152
  // an agent's own event, changed in place: --data is merged into its data
964
1153
  const eventId = positionals[0]
965
- if (!eventId || !opts.data)
966
- throw new Error("usage: workpad edit <event id> --data <json> (merged into the event's data)")
1154
+ const data = eventData()
1155
+ if (!eventId || data === undefined)
1156
+ throw new Error(
1157
+ "usage: workpad edit <event id> --data <json> | --file <file|-> | --text-file <file|-> (merged into the event's data)",
1158
+ )
967
1159
  const proj = needProject()
968
- let data: Record<string, unknown>
969
- try {
970
- data = JSON.parse(opts.data)
971
- } catch {
972
- throw new Error('--data must be a JSON object')
973
- }
974
- if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error('--data must be a JSON object')
975
- console.log(JSON.stringify(editEvent(proj.eventsFile, eventId, data)))
1160
+ if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error('the data must be a JSON object')
1161
+ console.log(JSON.stringify(editEvent(proj.eventsFile, eventId, data as Record<string, unknown>)))
976
1162
  break
977
1163
  }
978
1164
  case 'scroll': {
@@ -1130,9 +1316,21 @@ switch (cmd) {
1130
1316
  throw new Error(
1131
1317
  `name the forms to settle, or --all for every open one: open on ${p.page} ${p.open.length ? `are ${p.open.join(', ')}` : 'is none'}`,
1132
1318
  )
1319
+ // --replace-with: the form on the page becomes what was decided, in the same step. Made first,
1320
+ // so a form the page doesn't have settles nothing
1321
+ let replaced: string | null = null
1322
+ if (opts['replace-with'] !== undefined) {
1323
+ if (opts.all || named.length !== 1) throw new Error('--replace-with replaces one form: name it, without --all')
1324
+ const source = fs.readFileSync(p.file, 'utf8')
1325
+ replaced = setBlock(source, `form:${named[0]}`, readInput(opts['replace-with'], '--replace-with'))
1326
+ }
1133
1327
  const { forms, skipped } = settleForms(proj.eventsFile, p, opts.all ? 'all' : named, await whoAmI(proj))
1134
1328
  for (const { name, state } of skipped) console.error(`workpad: ${name} isn't open (${state}): left as it is`)
1135
1329
  console.log(forms.length ? `settled on ${p.page}: ${forms.join(', ')}` : `nothing to settle on ${p.page}`)
1330
+ if (replaced !== null) {
1331
+ fs.writeFileSync(p.file, replaced)
1332
+ console.log(`replaced the form ${named[0]} on ${p.page}`)
1333
+ }
1136
1334
  break
1137
1335
  }
1138
1336
  case 'hold': {
@@ -1183,20 +1381,29 @@ switch (cmd) {
1183
1381
  // and runs on; with --wait it prints all there are and stops, or with none, the first to come;
1184
1382
  // with --channel it hands the pages over to the session's channel and stops. Any number listen
1185
1383
  // on a page, each hearing everything. Without --page: every page (in a project of the machine's
1186
- // entries, every page of the entry).
1384
+ // entries, every page of the entry). With --unfollowed: the pages no live session follows, for a
1385
+ // coordinator (holdUnfollowed).
1187
1386
  const proj = needProject()
1188
1387
  const f = filter()
1189
- const agent = await whoAmI(proj)
1388
+ const { me: agent, session } = await whoAmIWithSession(proj)
1389
+ // what it wrote in its session, when WORKPAD_AGENT or --agent names it, is its own too
1390
+ const aliases = new Set(session ? [session] : [])
1190
1391
  if (opts.follow) throw new Error('listen runs on by itself: --wait stops at the first answer, --channel hands over to the channel')
1191
1392
  if (opts.wait && opts.channel) throw new Error('listen takes --wait or --channel, not both')
1192
1393
  if (opts.timeout && !opts.wait) throw new Error('--timeout goes with --wait')
1394
+ if (opts.unfollowed) {
1395
+ if (pagesGiven.length) throw new Error('--unfollowed takes the pages no one follows: no --page with it')
1396
+ if (opts.channel) await channelUnfollowed(proj, agent)
1397
+ else await unfollowedListen(proj, f.type ?? null, agent)
1398
+ break
1399
+ }
1193
1400
  if (opts.channel) {
1194
1401
  await channelListen(proj, agent)
1195
1402
  break
1196
1403
  }
1197
1404
  const entry = !f.page && isShared(proj) ? matchesEntries(readMachineConfig()!, proj.dir) : null
1198
1405
  if (entry) {
1199
- await entryListen(entry, f, agent)
1406
+ await entryListen(entry, f, agent, aliases)
1200
1407
  break
1201
1408
  }
1202
1409
  const isForAgent = await liveForAgent(proj)
@@ -1212,7 +1419,7 @@ switch (cmd) {
1212
1419
  // one line each; one handed out before and still not handled says so
1213
1420
  const print = (e: WpEvent, again: boolean) => console.log(JSON.stringify(again ? { ...e, again: true } : e))
1214
1421
  const at = () => needServer().catch(() => null)
1215
- const options = { batch: !!opts.wait, forAgent: isForAgent, agent }
1422
+ const options = { batch: !!opts.wait, forAgent: isForAgent, agent, aliases }
1216
1423
  if (opts.timeout && opts.wait)
1217
1424
  setTimeout(
1218
1425
  () => {
@@ -1264,19 +1471,20 @@ switch (cmd) {
1264
1471
  // comment. Waits skip what is appended here, so an agent does not hear its own events.
1265
1472
  const proj = needProject()
1266
1473
  if (!pageOpt || !opts.type)
1267
- throw new Error("usage: workpad append --page <page|file> --type <type> [--data '<json>']")
1268
- let data = {}
1269
- if (opts.data) {
1270
- try {
1271
- data = JSON.parse(opts.data)
1272
- } catch {
1273
- throw new Error('--data must be JSON, e.g. \'{"text":"…"}\'')
1274
- }
1275
- }
1474
+ throw new Error(
1475
+ "usage: workpad append --page <page|file> --type <type> [--data '<json>' | --file <file|->] [--text-file <file|->]",
1476
+ )
1477
+ const data = (eventData() ?? {}) as Record<string, unknown>
1478
+ // an event without the data its type requires shows nowhere (a chat message with no text):
1479
+ // most often its JSON was lost to the shell's quoting
1480
+ const refused = refusal(opts.type, data as Record<string, unknown>, (await projectConfig(proj)).requires)
1481
+ if (refused)
1482
+ throw new Error(
1483
+ `${refused}\nNothing was appended. Pass it so the shell's quoting can't lose it: the JSON in a file with --file message.json, or the text on standard input with --text-file -`,
1484
+ )
1485
+ const { me, session } = await whoAmIWithSession(proj)
1276
1486
  console.log(
1277
- JSON.stringify(
1278
- appendEvent(proj.eventsFile, { page: pageId(proj, pageOpt), type: opts.type, data }, 'cli', await whoAmI(proj)),
1279
- ),
1487
+ JSON.stringify(appendEvent(proj.eventsFile, { page: pageId(proj, pageOpt), type: opts.type, data }, 'cli', me, session)),
1280
1488
  )
1281
1489
  break
1282
1490
  }
@@ -1383,6 +1591,7 @@ switch (cmd) {
1383
1591
  return { base, version: String(health?.version ?? 'unknown') }
1384
1592
  },
1385
1593
  version: VERSION,
1594
+ agent: me,
1386
1595
  // the API, at the project's server, started at its first call
1387
1596
  wp: client(async () => probe(await ensureServer()), { token: projectToken(project.wp), agent: me }),
1388
1597
  page: page => pageId(project, page),
@@ -1393,11 +1602,14 @@ switch (cmd) {
1393
1602
  ...options,
1394
1603
  forAgent: await liveForAgent(project, options?.signal),
1395
1604
  }),
1396
- listen: (page, { agent = null } = {}) =>
1605
+ listen: (page, { agent = null, signal } = {}) =>
1397
1606
  listen({
1398
1607
  at: () => ensureServer().catch(() => null),
1399
1608
  query: { page: pageId(project, page), ...(agent ? { agent } : {}) },
1609
+ signal,
1400
1610
  }),
1611
+ unfollowed: (onEvent, { agent = null, mark, signal } = {}) =>
1612
+ holdUnfollowed(project, { at: () => ensureServer().catch(() => null), agent, mark, signal, onEvent }),
1401
1613
  channel: (session, handlers) => holdChannel(() => ensureServer().catch(() => null), session, handlers),
1402
1614
  authLink: async to =>
1403
1615
  `${await ensureServer()}/_/auth?token=${encodeURIComponent(projectToken(project.wp))}&to=${encodeURIComponent(to)}`,
@@ -1429,15 +1641,8 @@ switch (cmd) {
1429
1641
  * those waiting now: so nothing is printed here, which would hand them out twice. Only for a session
1430
1642
  * whose channel is confirmed (`workpad agent ping`); else nothing is taken on.
1431
1643
  */
1432
- async function channelListen(proj: Project, agent: string | null) {
1433
- if (!agent) throw new Error('--channel needs a session: no --agent, WORKPAD_AGENT or plugin session names one')
1434
- const channels = (await api('/api/channels')) as { session: string; confirmed: boolean }[]
1435
- if (!channels.some(c => c.session === agent && c.confirmed)) {
1436
- console.error(
1437
- 'workpad: no confirmed channel brings answers to this session: run `workpad agent ping` and confirm its pong, or listen without --channel',
1438
- )
1439
- process.exit(1)
1440
- }
1644
+ async function channelListen(proj: Project, who: string | null) {
1645
+ const agent = await confirmedChannel(who)
1441
1646
  const pages = [...new Set(pagesGiven.map(p => pageId(proj, p)))]
1442
1647
  // taken on through the channel: it brings what is new, and the reader's answers still waiting;
1443
1648
  // what other agents said before that someone already received is skipped (channelSince)
@@ -1448,7 +1653,8 @@ async function channelListen(proj: Project, agent: string | null) {
1448
1653
  const handled = handledIds(events)
1449
1654
  const received = receivedIds(events)
1450
1655
  const skipped = events.filter(e => {
1451
- if (fromReader(e) || !e.by || e.by === agent || !isForAgent(e.type) || handled.has(e.id)) return false
1656
+ if (fromReader(e) || !e.by || e.by === agent || e.session === agent || !isForAgent(e.type) || handled.has(e.id))
1657
+ return false
1452
1658
  if (!received.has(e.id)) return false
1453
1659
  const since = channelSince(events, agent, e.page)
1454
1660
  if (!since) return false
@@ -1464,13 +1670,161 @@ async function channelListen(proj: Project, agent: string | null) {
1464
1670
  }
1465
1671
  }
1466
1672
 
1673
+ /** `agent`, when a confirmed channel brings answers to it; else the command ends saying so. */
1674
+ async function confirmedChannel(agent: string | null): Promise<string> {
1675
+ if (!agent) throw new Error('--channel needs a session: no --agent, WORKPAD_AGENT or plugin session names one')
1676
+ const channels = (await api('/api/channels')) as { session: string; confirmed: boolean }[]
1677
+ if (!channels.some(c => c.session === agent && c.confirmed)) {
1678
+ console.error(
1679
+ 'workpad: no confirmed channel brings answers to this session: run `workpad agent ping` and confirm its pong, or listen without --channel',
1680
+ )
1681
+ process.exit(1)
1682
+ }
1683
+ return agent
1684
+ }
1685
+
1686
+ /** Where an answer on an unfollowed page is, under the shared server: its project's folder, and its page's address. */
1687
+ interface From {
1688
+ project: string
1689
+ url: string
1690
+ }
1691
+
1692
+ /**
1693
+ * Take the pages no one follows (`workpad listen --unfollowed`): a listen held at the server, which
1694
+ * holds it on each such page and says which they are as that changes; from each, the reader's
1695
+ * answers no other agent received (not the page's own agents' messages, nor what a session took
1696
+ * and works on between turns) go to `onEvent`, received by `agent` unless `mark` is false. Under
1697
+ * the shared server the pages of every project of this one's entry, each answer with where it is
1698
+ * (`from`). `onFirst`: the pages there were at first handed out what waited on them. Resolves once
1699
+ * the server holds it, or after a first try that found none running (it holds it once one runs).
1700
+ */
1701
+ async function holdUnfollowed(
1702
+ proj: Project,
1703
+ options: {
1704
+ at: () => Promise<string | null>
1705
+ agent: string | null
1706
+ type?: string | null
1707
+ mark?: boolean
1708
+ signal?: AbortSignal
1709
+ onEvent: (e: WpEvent, again: boolean, from: From | null) => void
1710
+ onFirst?: () => void
1711
+ },
1712
+ ): Promise<void> {
1713
+ const { agent, type, mark, signal, onEvent, onFirst } = options
1714
+ const shared = isShared(proj)
1715
+ const entry = shared ? matchesEntries(readMachineConfig()!, proj.dir) : null
1716
+ let origin = ''
1717
+ const address = (id: string) => id.split('/').map(encodeURIComponent).join('/')
1718
+ // what the pages of one list read before they follow: the backlog is handed out with the handOut
1719
+ let reading: Promise<void>[] = []
1720
+ const update = everyPage((p, stop) => {
1721
+ const there = p.dir === proj.dir ? proj : projectAt(p.dir)
1722
+ if (!there) return
1723
+ reading.push(
1724
+ projectConfig(there).then(({ handedOut }) => {
1725
+ if (stop.aborted) return
1726
+ void handOut(
1727
+ there.eventsFile,
1728
+ { page: p.page, exact: true, type },
1729
+ (e, again) => onEvent(e, again, shared ? { project: p.dir, url: `${origin}${p.base}/${address(e.page)}` } : null),
1730
+ {
1731
+ forAgent: forAgent(handedOut),
1732
+ agent,
1733
+ mark,
1734
+ readerOnly: true,
1735
+ notReceivedByOthers: true,
1736
+ signal: signal ? AbortSignal.any([stop, signal]) : stop,
1737
+ },
1738
+ )
1739
+ }),
1740
+ )
1741
+ })
1742
+ let first = true
1743
+ await listen(
1744
+ {
1745
+ at: shared
1746
+ ? async () => {
1747
+ origin = (await sharedServer(machineServerFile()))?.origin ?? ''
1748
+ return origin || null
1749
+ }
1750
+ : options.at,
1751
+ query: { unfollowed: '1', ...(entry && { entry }), ...(type && { type }), ...(agent && { agent }) },
1752
+ onPages: pages => {
1753
+ reading = []
1754
+ update(pages)
1755
+ if (!first) return
1756
+ first = false
1757
+ void Promise.all(reading).then(() => onFirst?.())
1758
+ },
1759
+ signal,
1760
+ },
1761
+ { orNone: true },
1762
+ )
1763
+ }
1764
+
1765
+ /**
1766
+ * `workpad listen --unfollowed`: the reader's answers on the pages no one follows, one line each, as
1767
+ * they come; with --wait all there are, or with none the first to come, and it stops. Under the
1768
+ * shared server each line says where it is (`project`, `url`).
1769
+ */
1770
+ async function unfollowedListen(proj: Project, type: string | null, agent: string | null) {
1771
+ if (opts.timeout && opts.wait)
1772
+ setTimeout(
1773
+ () => {
1774
+ console.error('timeout')
1775
+ process.exit(2)
1776
+ },
1777
+ Number(opts.timeout) * 1000,
1778
+ )
1779
+ let printed = 0
1780
+ // the first pages had what waited on them handed out: a --wait stops at the next one now
1781
+ let following = false
1782
+ let ending = false
1783
+ // after the last one is marked received, which follows printing it
1784
+ const end = () => {
1785
+ if (ending) return
1786
+ ending = true
1787
+ setImmediate(() => process.exit(0))
1788
+ }
1789
+ await holdUnfollowed(proj, {
1790
+ at: () => needServer().catch(() => null),
1791
+ agent,
1792
+ type,
1793
+ onEvent: (e, again, from) => {
1794
+ console.log(JSON.stringify({ ...e, ...(again && { again: true }), ...from }))
1795
+ printed++
1796
+ if (opts.wait && following) end()
1797
+ },
1798
+ onFirst: () => {
1799
+ following = true
1800
+ if (opts.wait && printed) end()
1801
+ },
1802
+ })
1803
+ // keeps the command running: the connection does not
1804
+ setInterval(() => {}, 1 << 30)
1805
+ }
1806
+
1807
+ /**
1808
+ * `workpad listen --unfollowed --channel`: the session's confirmed channel takes the pages no one
1809
+ * follows, for as long as it runs; none becomes the session's (status.ts, takesUnfollowed).
1810
+ */
1811
+ async function channelUnfollowed(proj: Project, agent: string | null) {
1812
+ const me = await confirmedChannel(agent)
1813
+ if (!takesUnfollowed(readEvents(proj.eventsFile), me))
1814
+ appendEvent(proj.eventsFile, { page: '', type: SUBSCRIBE, data: { channel: true, unfollowed: true } }, 'cli', me)
1815
+ const entry = isShared(proj) ? matchesEntries(readMachineConfig()!, proj.dir) : null
1816
+ console.log(
1817
+ `the channel brings the answers on the pages no one follows${entry ? `, in every project of ${entry}` : ''}: those waiting there first, then each as it comes; a page drops out while someone else follows it`,
1818
+ )
1819
+ }
1820
+
1467
1821
  /**
1468
1822
  * A listen over a whole entry: every page of each of its projects, from each project's own log, each
1469
1823
  * event with the project it is from (`project`, its folder) and its page's `url`. Any number run.
1470
1824
  * Without a shared server running it waits for one, as any listen does. Projects that appear
1471
1825
  * meanwhile are followed too.
1472
1826
  */
1473
- async function entryListen(entry: string, f: EventFilter, agent: string | null) {
1827
+ async function entryListen(entry: string, f: EventFilter, agent: string | null, aliases: ReadonlySet<string>) {
1474
1828
  const file = machineServerFile()
1475
1829
  // across projects as they come: with --wait it stops at the first
1476
1830
  const count = opts.wait ? 1 : Infinity
@@ -1501,7 +1855,7 @@ async function entryListen(entry: string, f: EventFilter, agent: string | null)
1501
1855
  console.log(JSON.stringify({ ...e, project: p.dir, url: `${origin}${p.base}/${page(e.page)}` }))
1502
1856
  if (++total >= count) done.abort()
1503
1857
  },
1504
- { forAgent: forAgent(handedOut), agent, signal: AbortSignal.any([signal, done.signal]) },
1858
+ { forAgent: forAgent(handedOut), agent, aliases, signal: AbortSignal.any([signal, done.signal]) },
1505
1859
  ),
1506
1860
  )
1507
1861
  })