@bigmistqke/workpad 0.19.0 → 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 (83) hide show
  1. package/README.md +18 -9
  2. package/bin/workpad.ts +187 -37
  3. package/dist/bin/workpad.js +156 -32
  4. package/dist/client/runtime.js +141 -18
  5. package/dist/plugins/chat/README.md +7 -3
  6. package/dist/plugins/chat/index.js +1 -0
  7. package/dist/plugins/chat/public/client.js +2 -2
  8. package/dist/plugins/chat/public/style.css +10 -0
  9. package/dist/plugins/claude/channel.js +22 -4
  10. package/dist/plugins/comments/README.md +2 -1
  11. package/dist/plugins/comments/index.js +2 -0
  12. package/dist/plugins/comments/public/client.js +6 -5
  13. package/dist/plugins/comments/public/style.css +9 -0
  14. package/dist/plugins/form/README.md +1 -1
  15. package/dist/plugins/index.js +3 -1
  16. package/dist/plugins/opencode/channel.js +1 -0
  17. package/dist/plugins/progress/README.md +41 -0
  18. package/dist/plugins/progress/index.js +117 -0
  19. package/dist/plugins/progress/public/client.js +1 -0
  20. package/dist/plugins/progress/public/style.css +85 -0
  21. package/dist/plugins/progress/state.js +210 -0
  22. package/dist/solid/index.js +3 -1
  23. package/dist/src/agents.js +7 -3
  24. package/dist/src/anchors.js +25 -1
  25. package/dist/src/build.js +1 -1
  26. package/dist/src/client/page/base.css +48 -2
  27. package/dist/src/client/page/main.js +58 -30
  28. package/dist/src/document.js +6 -4
  29. package/dist/src/events.js +19 -9
  30. package/dist/src/help.js +43 -8
  31. package/dist/src/hub.js +14 -1
  32. package/dist/src/loader.js +7 -2
  33. package/dist/src/migrate.js +1 -1
  34. package/dist/src/pages/board.js +1 -1
  35. package/dist/src/pages/markdown.js +3 -3
  36. package/dist/src/pages/render.js +16 -0
  37. package/dist/src/server.js +25 -12
  38. package/dist/src/set.js +99 -0
  39. package/dist/src/status.js +47 -8
  40. package/package.json +6 -1
  41. package/plugins/README.md +3 -1
  42. package/plugins/chat/README.md +7 -3
  43. package/plugins/chat/client.tsx +20 -3
  44. package/plugins/chat/index.ts +1 -0
  45. package/plugins/chat/public/style.css +10 -0
  46. package/plugins/claude/channel.ts +19 -5
  47. package/plugins/comments/README.md +2 -1
  48. package/plugins/comments/client.ts +19 -0
  49. package/plugins/comments/index.ts +7 -1
  50. package/plugins/comments/public/style.css +9 -0
  51. package/plugins/form/README.md +1 -1
  52. package/plugins/index.ts +2 -0
  53. package/plugins/opencode/channel.ts +2 -1
  54. package/plugins/progress/README.md +41 -0
  55. package/plugins/progress/client.ts +172 -0
  56. package/plugins/progress/index.ts +166 -0
  57. package/plugins/progress/public/style.css +85 -0
  58. package/plugins/progress/state.ts +278 -0
  59. package/skills/workpad/SKILL.md +126 -15
  60. package/solid/index.tsx +6 -2
  61. package/src/agents.ts +17 -2
  62. package/src/anchors.ts +32 -0
  63. package/src/build.ts +1 -1
  64. package/src/client/delivery.ts +49 -0
  65. package/src/client/forms.ts +18 -11
  66. package/src/client/page/base.css +48 -2
  67. package/src/client/page/waiting.ts +45 -25
  68. package/src/client/read.ts +9 -5
  69. package/src/client/runtime.ts +7 -3
  70. package/src/client/toast.ts +27 -3
  71. package/src/define.ts +92 -8
  72. package/src/document.ts +19 -5
  73. package/src/events.ts +26 -6
  74. package/src/help.ts +42 -7
  75. package/src/hub.ts +9 -0
  76. package/src/loader.ts +14 -4
  77. package/src/migrate.ts +1 -1
  78. package/src/pages/board.ts +3 -1
  79. package/src/pages/markdown.ts +4 -4
  80. package/src/pages/render.ts +19 -1
  81. package/src/server.ts +43 -13
  82. package/src/set.ts +118 -0
  83. package/src/status.ts +100 -13
package/README.md CHANGED
@@ -283,8 +283,9 @@ time it is read. A listen prints everything on its page not handled yet,
283
283
  including what came before it started and what it was handed before (marked
284
284
  `"again": true`), so an answer an agent saw and forgot comes back. So an
285
285
  agent can ask, do other work, and listen later. Any number listen on a
286
- page, and each hears everything there but its own events; the page's green
287
- dot lists who listens.
286
+ page, and each hears everything there but its own events (written under its
287
+ id, or in its session when `WORKPAD_AGENT` names it); another agent's message
288
+ comes to it once, not again; the page's green dot lists who listens.
288
289
 
289
290
  `listen` is built from smaller pieces that are commands too, for a script that
290
291
  wants to use the log its own way:
@@ -434,22 +435,23 @@ commands answer it too.
434
435
  | `workpad new <name>` | create a page under a name no other page has (`name`, else `name-2`, …), print its path |
435
436
  | `workpad show <page\|file> [<anchor>]` | start the project's server if needed (never the shared one), print the page's URL; with an anchor, one that opens the page there |
436
437
  | `workpad url <page\|file> [<anchor>] [--full]` | a link to a page or a place on it, from the server's root (`/rg/jobs/x/decisions#form:logger`), so it works however the board is opened; `--full` for the whole URL; checks the anchor |
437
- | `workpad settle <page\|file> <form>… \| --all` | settle questions answered elsewhere (a chat, the design moving on): no longer unanswered; an answer opens one again |
438
+ | `workpad settle <page\|file> <form>… \| --all` | settle questions answered elsewhere (a chat, the design moving on): no longer unanswered; an answer opens one again. With one form and `--replace-with <file\|->`, the form on the page is replaced with that markdown (what was decided) in the same step |
438
439
  | `workpad hold <page\|file> <form>… "<reason>"` | hold questions that wait on something else ("waits for !2145"): shown held with the reason, not waiting for the reader, not settled; an answer ends the hold |
439
440
  | `workpad release <page\|file> <form>…` | release held questions: they wait for the reader again |
440
- | `workpad check [<page\|file>…]` | what is wrong on pages as they render, a line each; exits 1 when there is any |
441
+ | `workpad check [<page\|file>…]` | what is wrong on pages as they render, a line each, links to an anchor that isn't there included (on the page, or on another page of the project, with the nearest it has); exits 1 when there is any |
441
442
  | `workpad migrate [<folder\|file>…] [--write]` | after updating workpad, pages written in an older syntax in the current one (0.15: items as `:::item`, `steps` → `tabs`, callouts → alerts, `:check` → `:checkbox`, an ansi fence's title window); code is left alone, a second run changes nothing. Before that, a project or machine still under the old name, whiteboard, moves to the new one (see above). A dry run lists each page and what would change, exiting 1 when any would; `--write` rewrites them. Default: `.workpad/pages` |
442
443
  | `workpad anchors <page\|file>` | what a page can be linked to: `#open-questions` (a heading), `#form:logger`, `#chat:notes`, `#tab:intro`, `#details:why` |
444
+ | `workpad set <page\|file> <anchor\|form> --file <file\|->` | replace one block of a page, found by parsing it: a form (`form:logger`), a heading's section (`open-questions`, up to the next heading of its level), a named block (`chat:notes`), with markdown from a file or standard input; the rest of the page stays byte for byte; a name the page lacks exits 1, listing what it has |
443
445
  | `workpad archive <page>` | a page that did its job: it leaves the pages and its events the log, kept in `.workpad/archive/` as markdown with what was answered on it |
444
446
  | `workpad destroy <page>` | a throwaway page: remove its file, and all its events from the log |
445
447
  | `workpad prune <page> [--type <t>] [--id <id>]` | remove a page's events from the log (all, one type, or one), keep the page |
446
- | `workpad edit <event id> --data <json>` | change an agent's own event in place: merged into its data, its id kept |
448
+ | `workpad edit <event id> --data <json> \| --file <file\|-> \| --text-file <file\|->` | change an agent's own event in place: merged into its data, its id kept |
447
449
  | `workpad thread <event id>` | an answer or chat message with its question: the form as written (chosen options marked), its answers and its chat, in order |
448
450
  | `workpad scroll <page\|file> <where>` | scroll the tabs that have the page open to a heading's text, a form's name or any text on it; exits 1 when nothing matches or no tab has it open |
449
451
  | `workpad docs [<block\|plugin> \| --all]` | print how to write pages in this project: a line per block, grouped by what it is for (ask, show, arrange, mark); with a block's or plugin's name, that plugin's docs; with `--all`, every plugin's |
450
452
  | `workpad events [filters] [--follow]` | print recorded events; with `--follow`, then each new one as it comes, marking nothing |
451
453
  | `workpad listen [filters] [--wait \| --channel] [--agent <who>]` | print everything matching you haven't handled (the reader's answers, other agents' messages; one handed out before with `"again": true`), then each as it comes, never exiting; with `--wait`, exit once it printed what there is, or with nothing there the next; with `--channel`, make the pages yours and exit, your session's confirmed channel bringing their answers (without `--page`, every page, also later ones); any number listen on a page; with `--page`, subscribes you to it; without, every page (in a project of the machine config's entries, every page of the entry, each event with its `project` and `url`) |
452
- | `workpad append --page <p> --type <t> [--data <json>]` | add an event to a page's log, such as a reply to a comment |
454
+ | `workpad append --page <p> --type <t> [--data <json> \| --file <file\|->] [--text-file <file\|->]` | add an event to a page's log, such as a reply to a comment: its data as JSON on the command line, or from a file or standard input (`--file`), with markdown from a file or standard input as its `text` (`--text-file`) |
453
455
  | `workpad handled <event id…>` | you handled these answers (a reply in their chat does it too): no listen hands them out again |
454
456
  | `workpad agent [name <n> \| name --clear \| list \| unsubscribe <agent> [--page <p>…] \| ping [<code>]]` | who you are (your id, `--agent`): alone, your id and name; `name` names you (one per agent, shown in the list of who listens and in `status`); `list` everyone on the board, saying who is subscribed and not listening; `unsubscribe` takes an agent (id or name) off the pages named, else off all; `ping` checks that an agent plugin's channel reaches you (it pushes a pong with a code; with the code, confirms it, and the channel then brings the answers on your pages, as received) |
455
457
  | `workpad status [--page <p>]` | per page: who is subscribed, questions without an answer, answers nobody received, answers received and not handled, chats waiting for a reply, who is listening |
@@ -677,13 +679,20 @@ Not started.
677
679
  recorded in the log, so it holds in every browser. An answered form waits
678
680
  for an agent to receive it; once one has it, the form folds into a card:
679
681
  what you chose (several answers each on a line, under the button you
680
- pressed), what you wrote, and "received · change" while the agent is on
682
+ pressed), what you wrote, and "received by <agent> · change" while the agent is on
681
683
  it, "decided · change" once it handled it; a click opens it again. Its chat folds into "💬 n messages", and opens when the agent
682
684
  writes there, or stays open while you are writing in it. The corner's
683
685
  toasts go to the next question ("→ unanswered (n)") and the next
684
686
  unread message ("→ unread (n)", whose ✕ puts it away until another
685
- comes), and the tab title gets a `(!n)` prefix. An answer sent while nobody
686
- listens says so in a toast; it stays in the log for whoever listens next.
687
+ comes), and the tab title gets a `(!n)` prefix.
688
+ - **Where what you sent went.** Beside an answer, a chat message or a
689
+ comment, in a small line: "no one follows this page — it waits until an
690
+ agent listens" (it stays in the log for whoever listens next), "waiting
691
+ for an agent to receive it", "received by <agent>", "handled". One no
692
+ agent received after 10 minutes says "not received after 10 min" in the
693
+ warning colour, and the corner counts them ("→ not received (n)"). A send
694
+ the server doesn't answer is tried again a few times (never appended
695
+ twice); one that never gets through says so, with a button to try again.
687
696
  - **Who listens.** The dot at the end of the header is green while the page
688
697
  is live and someone listens for its answers, grey when nobody does
689
698
  (answers wait in the log), and a ring while the page reconnects. A click
package/bin/workpad.ts CHANGED
@@ -38,7 +38,8 @@ import { archived, archiveFile } from '../src/archive.ts'
38
38
  import { thread } from '../src/thread.ts'
39
39
  import { markdownFiles, migrate } from '../src/migrate.ts'
40
40
  import { OLD, machineSteps, oldProjectDir, projectSteps } from '../src/rename.ts'
41
- 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'
42
43
  import { projectToken } from '../src/auth.ts'
43
44
  import { PACKAGE_DIR, packagePath } from '../src/package.ts'
44
45
  import {
@@ -60,11 +61,12 @@ import {
60
61
  stateDir,
61
62
  } from '../src/entries.ts'
62
63
  import { compareVersions, VERSION } from '../src/package.ts'
63
- import { statusLines, whose } from '../src/status.ts'
64
+ import { refusal, statusLines, whose } from '../src/status.ts'
64
65
  import { holdForms, releaseForms, settleForms } from '../src/formstate.ts'
65
66
  import { client, probe } from '../src/api.ts'
66
67
  import { everyPage, everyProject, holdChannel, listen } from '../src/listen.ts'
67
68
  import { lastTurnEnd } from '../src/turns.ts'
69
+ import { line as progressLine, running as runningProgress } from '../plugins/progress/state.ts'
68
70
  import type { Listener, PageStatus, WpEvent } from '../src/define.ts'
69
71
 
70
72
  // a failing command prints its message, not a stack trace
@@ -131,6 +133,9 @@ const { values: opts, positionals } =
131
133
  channel: { type: 'boolean' },
132
134
  unfollowed: { type: 'boolean' },
133
135
  all: { type: 'boolean' },
136
+ file: { type: 'string' },
137
+ 'text-file': { type: 'string' },
138
+ 'replace-with': { type: 'string' },
134
139
  },
135
140
  })
136
141
 
@@ -296,6 +301,46 @@ function pageIn(target: string): { proj: Project; id: string } {
296
301
  return { proj, id: pageId(proj, target) }
297
302
  }
298
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
+
299
344
  /** Where a project is served: its running server, or an error saying how to start one. */
300
345
  async function serverOf(proj: Project): Promise<string> {
301
346
  if (proj.dir === project?.dir) return needServer()
@@ -517,6 +562,18 @@ async function whoAmI(proj: Project): Promise<string | null> {
517
562
  return (opts.agent as string | undefined) || process.env.WORKPAD_AGENT || (await currentSession(proj))
518
563
  }
519
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
+
520
577
  /**
521
578
  * The agent session this command runs in, as the project's plugins know it (Claude Code's
522
579
  * plugin reads it from the environment): the first one that names one. Null without any.
@@ -547,16 +604,24 @@ async function status() {
547
604
  api(`/api/status${pageOpt ? `?page=${encodeURIComponent(pageId(proj, pageOpt))}` : ''}`),
548
605
  whoAmI(proj),
549
606
  ])
550
- const names = namesOf(readEvents(proj.eventsFile))
607
+ const events = readEvents(proj.eventsFile)
608
+ const names = namesOf(events)
551
609
  const busy = pages.filter(p => p.unreceived.length || p.open.length)
552
- if (!busy.length) {
553
- console.log('nothing open: every question is answered, and every answer received')
554
- return
555
- }
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')
556
614
  for (const p of busy) {
557
615
  console.log(`${p.page} (${whose(p, me, names)})`)
558
616
  for (const l of statusLines(p, relFile(p.file))) console.log(` ${l}`)
559
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
+ }
560
625
  }
561
626
 
562
627
  switch (cmd) {
@@ -866,6 +931,58 @@ switch (cmd) {
866
931
  .replace(/&#39;/g, "'")
867
932
  .replace(/&amp;/g, '&')
868
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
+ }
869
986
  let found = 0
870
987
  const config = new Set<string>()
871
988
  for (const id of ids) {
@@ -876,10 +993,13 @@ switch (cmd) {
876
993
  continue
877
994
  }
878
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)))
879
997
  const errors = [...body.matchAll(/<(\w+) class="wp-error"[^>]*>([\s\S]*?)<\/\1>/g)].map(m => text(m[2]))
880
998
  // the config's errors are every page's: said once, at the end
881
999
  for (const n of notices) if (n.startsWith('config: ')) config.add(n)
882
- 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
+ ]
883
1003
  if (!problems.length) continue
884
1004
  found += problems.length
885
1005
  console.log(`${id}\n${problems.map(p => ` ${p.replace(/\n/g, '\n ')}`).join('\n')}`)
@@ -943,6 +1063,21 @@ switch (cmd) {
943
1063
  console.log(`${hashOf(a.id)} ${a.kind}${a.label !== a.id.slice(a.kind.length + 1) ? ` ${a.label}` : ''}`)
944
1064
  break
945
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
+ }
946
1081
  case 'archive':
947
1082
  case 'destroy': {
948
1083
  // a page that has done its job: its file leaves the pages, and its events leave the log (answers,
@@ -1016,17 +1151,14 @@ switch (cmd) {
1016
1151
  case 'edit': {
1017
1152
  // an agent's own event, changed in place: --data is merged into its data
1018
1153
  const eventId = positionals[0]
1019
- if (!eventId || !opts.data)
1020
- 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
+ )
1021
1159
  const proj = needProject()
1022
- let data: Record<string, unknown>
1023
- try {
1024
- data = JSON.parse(opts.data)
1025
- } catch {
1026
- throw new Error('--data must be a JSON object')
1027
- }
1028
- if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error('--data must be a JSON object')
1029
- 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>)))
1030
1162
  break
1031
1163
  }
1032
1164
  case 'scroll': {
@@ -1184,9 +1316,21 @@ switch (cmd) {
1184
1316
  throw new Error(
1185
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'}`,
1186
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
+ }
1187
1327
  const { forms, skipped } = settleForms(proj.eventsFile, p, opts.all ? 'all' : named, await whoAmI(proj))
1188
1328
  for (const { name, state } of skipped) console.error(`workpad: ${name} isn't open (${state}): left as it is`)
1189
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
+ }
1190
1334
  break
1191
1335
  }
1192
1336
  case 'hold': {
@@ -1241,7 +1385,9 @@ switch (cmd) {
1241
1385
  // coordinator (holdUnfollowed).
1242
1386
  const proj = needProject()
1243
1387
  const f = filter()
1244
- 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] : [])
1245
1391
  if (opts.follow) throw new Error('listen runs on by itself: --wait stops at the first answer, --channel hands over to the channel')
1246
1392
  if (opts.wait && opts.channel) throw new Error('listen takes --wait or --channel, not both')
1247
1393
  if (opts.timeout && !opts.wait) throw new Error('--timeout goes with --wait')
@@ -1257,7 +1403,7 @@ switch (cmd) {
1257
1403
  }
1258
1404
  const entry = !f.page && isShared(proj) ? matchesEntries(readMachineConfig()!, proj.dir) : null
1259
1405
  if (entry) {
1260
- await entryListen(entry, f, agent)
1406
+ await entryListen(entry, f, agent, aliases)
1261
1407
  break
1262
1408
  }
1263
1409
  const isForAgent = await liveForAgent(proj)
@@ -1273,7 +1419,7 @@ switch (cmd) {
1273
1419
  // one line each; one handed out before and still not handled says so
1274
1420
  const print = (e: WpEvent, again: boolean) => console.log(JSON.stringify(again ? { ...e, again: true } : e))
1275
1421
  const at = () => needServer().catch(() => null)
1276
- const options = { batch: !!opts.wait, forAgent: isForAgent, agent }
1422
+ const options = { batch: !!opts.wait, forAgent: isForAgent, agent, aliases }
1277
1423
  if (opts.timeout && opts.wait)
1278
1424
  setTimeout(
1279
1425
  () => {
@@ -1325,19 +1471,20 @@ switch (cmd) {
1325
1471
  // comment. Waits skip what is appended here, so an agent does not hear its own events.
1326
1472
  const proj = needProject()
1327
1473
  if (!pageOpt || !opts.type)
1328
- throw new Error("usage: workpad append --page <page|file> --type <type> [--data '<json>']")
1329
- let data = {}
1330
- if (opts.data) {
1331
- try {
1332
- data = JSON.parse(opts.data)
1333
- } catch {
1334
- throw new Error('--data must be JSON, e.g. \'{"text":"…"}\'')
1335
- }
1336
- }
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)
1337
1486
  console.log(
1338
- JSON.stringify(
1339
- appendEvent(proj.eventsFile, { page: pageId(proj, pageOpt), type: opts.type, data }, 'cli', await whoAmI(proj)),
1340
- ),
1487
+ JSON.stringify(appendEvent(proj.eventsFile, { page: pageId(proj, pageOpt), type: opts.type, data }, 'cli', me, session)),
1341
1488
  )
1342
1489
  break
1343
1490
  }
@@ -1444,6 +1591,7 @@ switch (cmd) {
1444
1591
  return { base, version: String(health?.version ?? 'unknown') }
1445
1592
  },
1446
1593
  version: VERSION,
1594
+ agent: me,
1447
1595
  // the API, at the project's server, started at its first call
1448
1596
  wp: client(async () => probe(await ensureServer()), { token: projectToken(project.wp), agent: me }),
1449
1597
  page: page => pageId(project, page),
@@ -1454,10 +1602,11 @@ switch (cmd) {
1454
1602
  ...options,
1455
1603
  forAgent: await liveForAgent(project, options?.signal),
1456
1604
  }),
1457
- listen: (page, { agent = null } = {}) =>
1605
+ listen: (page, { agent = null, signal } = {}) =>
1458
1606
  listen({
1459
1607
  at: () => ensureServer().catch(() => null),
1460
1608
  query: { page: pageId(project, page), ...(agent ? { agent } : {}) },
1609
+ signal,
1461
1610
  }),
1462
1611
  unfollowed: (onEvent, { agent = null, mark, signal } = {}) =>
1463
1612
  holdUnfollowed(project, { at: () => ensureServer().catch(() => null), agent, mark, signal, onEvent }),
@@ -1504,7 +1653,8 @@ async function channelListen(proj: Project, who: string | null) {
1504
1653
  const handled = handledIds(events)
1505
1654
  const received = receivedIds(events)
1506
1655
  const skipped = events.filter(e => {
1507
- 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
1508
1658
  if (!received.has(e.id)) return false
1509
1659
  const since = channelSince(events, agent, e.page)
1510
1660
  if (!since) return false
@@ -1674,7 +1824,7 @@ async function channelUnfollowed(proj: Project, agent: string | null) {
1674
1824
  * Without a shared server running it waits for one, as any listen does. Projects that appear
1675
1825
  * meanwhile are followed too.
1676
1826
  */
1677
- async function entryListen(entry: string, f: EventFilter, agent: string | null) {
1827
+ async function entryListen(entry: string, f: EventFilter, agent: string | null, aliases: ReadonlySet<string>) {
1678
1828
  const file = machineServerFile()
1679
1829
  // across projects as they come: with --wait it stops at the first
1680
1830
  const count = opts.wait ? 1 : Infinity
@@ -1705,7 +1855,7 @@ async function entryListen(entry: string, f: EventFilter, agent: string | null)
1705
1855
  console.log(JSON.stringify({ ...e, project: p.dir, url: `${origin}${p.base}/${page(e.page)}` }))
1706
1856
  if (++total >= count) done.abort()
1707
1857
  },
1708
- { forAgent: forAgent(handedOut), agent, signal: AbortSignal.any([signal, done.signal]) },
1858
+ { forAgent: forAgent(handedOut), agent, aliases, signal: AbortSignal.any([signal, done.signal]) },
1709
1859
  ),
1710
1860
  )
1711
1861
  })