@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
@@ -8,15 +8,18 @@ import { archiveFile, archived } from "../src/archive.js";
8
8
  import { thread } from "../src/thread.js";
9
9
  import { markdownFiles, migrate } from "../src/migrate.js";
10
10
  import { OLD, machineSteps, oldProjectDir, projectSteps } from "../src/rename.js";
11
- import { anchorsOf, hashOf } from "../src/anchors.js";
11
+ import { anchorsOf, hashOf, nearest } from "../src/anchors.js";
12
+ import { findBlock, setBlock } from "../src/set.js";
12
13
  import { projectToken } from "../src/auth.js";
13
14
  import { PACKAGE_DIR, VERSION, compareVersions, packagePath } from "../src/package.js";
14
15
  import { alive, isShared, projectServer, recordedOrigin, recordedPid, sharedServer, stuck, stuckAt } from "../src/running.js";
15
16
  import { machineDir, machineServerFile, matchesEntries, readMachineConfig, serverPaths, stateDir } from "../src/entries.js";
16
- import { NAME, SUBSCRIBE, UNSUBSCRIBE, channelSince, fromReader, handledIds, namesOf, receivedIds, statusLines, subscriptions, whose } from "../src/status.js";
17
+ import { NAME, SUBSCRIBE, UNSUBSCRIBE, channelSince, fromReader, handledIds, namesOf, receivedIds, refusal, statusLines, subscriptions, takesUnfollowed, whose } from "../src/status.js";
17
18
  import { holdForms, releaseForms, settleForms } from "../src/formstate.js";
18
19
  import { client, probe } from "../src/api.js";
19
- import { everyProject, holdChannel, listen } from "../src/listen.js";
20
+ import { everyPage, everyProject, holdChannel, listen } from "../src/listen.js";
21
+ import { lastTurnEnd } from "../src/turns.js";
22
+ import { line, running as running$1 } from "../plugins/progress/state.js";
20
23
  import fs from "node:fs";
21
24
  import path from "node:path";
22
25
  import os from "node:os";
@@ -85,7 +88,11 @@ const { values: opts, positionals } = cmd && !BUILTIN_COMMANDS.has(cmd) ? {
85
88
  clear: { type: "boolean" },
86
89
  wait: { type: "boolean" },
87
90
  channel: { type: "boolean" },
88
- all: { type: "boolean" }
91
+ unfollowed: { type: "boolean" },
92
+ all: { type: "boolean" },
93
+ file: { type: "string" },
94
+ "text-file": { type: "string" },
95
+ "replace-with": { type: "string" }
89
96
  }
90
97
  });
91
98
  if (cmd && cmd !== "help" && BUILTIN_COMMANDS.has(cmd) && opts.help) {
@@ -112,6 +119,8 @@ const filter = () => ({
112
119
  page: pageOpt ? pageId(needProject(), pageOpt) : void 0,
113
120
  type: opts.type
114
121
  });
122
+ /** The longest `workpad agent ping --wait` waits, turn or no turn: a background process never lingers. */
123
+ const MAX_WAIT = 18e5;
115
124
  /** The running server of this project: the URL it is served at, or null (see projectServer). */
116
125
  const running = (proj) => projectServer(proj);
117
126
  /**
@@ -217,6 +226,41 @@ function pageIn(target) {
217
226
  id: pageId(proj, target)
218
227
  };
219
228
  }
229
+ /** The file a page or repository file of the project is: `README.md`, `plan`, `.workpad/pages/plan.md`. */
230
+ function fileOf(proj, target) {
231
+ const id = pageId(proj, target);
232
+ if (!id) throw new Error(`no page ${target}`);
233
+ return id === "-" || id.startsWith("-/") ? path.join(proj.dir, id.slice(2)) : path.join(proj.pagesDir, `${id}.md`);
234
+ }
235
+ /**
236
+ * What a file holds, or with `-` what comes on standard input: for markdown and JSON an agent writes,
237
+ * which never passes through the shell's quoting that way (a heredoc with a quoted delimiter, or a file).
238
+ */
239
+ function readInput(from, option) {
240
+ if (from === "-") return fs.readFileSync(0, "utf8");
241
+ if (!fs.existsSync(from)) throw new Error(`${option} ${from}: no such file`);
242
+ return fs.readFileSync(from, "utf8");
243
+ }
244
+ /**
245
+ * An event's data as the command line gives it: JSON from --data or --file (a file, or - for standard
246
+ * input), with --text-file's contents (a file, or -) as its `text`. Nothing given: undefined.
247
+ */
248
+ function eventData() {
249
+ if (opts.data !== void 0 && opts.file !== void 0) throw new Error("give the data with --data or --file, not both");
250
+ const json = opts.file !== void 0 ? readInput(opts.file, "--file") : opts.data;
251
+ let data;
252
+ if (json !== void 0) try {
253
+ data = JSON.parse(json);
254
+ } catch {
255
+ throw new Error(`${opts.file !== void 0 ? `--file ${opts.file}` : "--data"} must be JSON, e.g. {"text":"…"}; for markdown, --text-file <file|->`);
256
+ }
257
+ if (opts["text-file"] === void 0) return data;
258
+ if (data !== void 0 && (!data || typeof data !== "object" || Array.isArray(data))) throw new Error("with --text-file, the data must be a JSON object: the text goes in as its \"text\"");
259
+ return {
260
+ ...data,
261
+ text: readInput(opts["text-file"], "--text-file").replace(/\s+$/, "")
262
+ };
263
+ }
220
264
  /** Where a project is served: its running server, or an error saying how to start one. */
221
265
  async function serverOf(proj) {
222
266
  if (proj.dir === project?.dir) return needServer();
@@ -256,15 +300,34 @@ function hasPages(dir) {
256
300
  /**
257
301
  * Ask the project's server. Without one running, a server made for this one question answers it,
258
302
  * in this process, on no port: a command that only asks (status, docs, the hooks on every prompt)
259
- * never starts one. It has no listeners, as no server runs to hold them.
303
+ * never starts one. It has no listeners, as no server runs to hold them. A server that runs but is
304
+ * busy is waited for (`runningOrBusy`): answered in this process, its listeners would be missed.
260
305
  */
261
306
  async function api(route) {
262
- const base = await running(needProject());
307
+ const base = await runningOrBusy(needProject());
263
308
  const res = base ? await fetch(`${base}${route}`) : await askInProcess(route);
264
309
  const body = await res.json();
265
310
  if (!res.ok) throw new Error(body.error ?? res.statusText);
266
311
  return body;
267
312
  }
313
+ /** How long a command waits for a server too busy to answer (a status over many pages can take seconds). */
314
+ const BUSY_WAIT = 3e4;
315
+ /**
316
+ * The running server of `proj`, or null when none runs. One that accepts connections and gives its
317
+ * health check no answer in time is busy, its event loop blocked by a slow request: it is waited
318
+ * for, up to BUSY_WAIT, then said to be stuck. Taken for none, a question would be answered without
319
+ * it, by a server in this process that knows nobody who listens.
320
+ */
321
+ async function runningOrBusy(proj) {
322
+ const base = await running(proj);
323
+ if (base) return base;
324
+ const shared = isShared(proj);
325
+ const at = recordedOrigin(shared ? machineServerFile() : proj.serverFile);
326
+ if (!at) return null;
327
+ const deadline = Date.now() + BUSY_WAIT;
328
+ while (await stuckAt(at)) if (Date.now() > deadline) throw new Error(stuck(at, shared ? "its login service log" : proj.logFile));
329
+ return running(proj);
330
+ }
268
331
  async function askInProcess(route) {
269
332
  if (route.startsWith("/api/status") && !hasPages(needProject().pagesDir)) return Response.json([]);
270
333
  const { createServer } = await import("../src/server.js");
@@ -382,6 +445,20 @@ async function whoAmI(proj) {
382
445
  return opts.agent || process.env.WORKPAD_AGENT || await currentSession(proj);
383
446
  }
384
447
  /**
448
+ * Who runs this command, and the other id it goes by: the agent session a plugin names, when
449
+ * `--agent` or `WORKPAD_AGENT` named it otherwise. What it writes records both (appendEvent), and a
450
+ * listen leaves out what either wrote: a channel that knows the agent by its session, and the
451
+ * agent's commands that name it, are the same agent.
452
+ */
453
+ async function whoAmIWithSession(proj) {
454
+ const session = await currentSession(proj);
455
+ const me = opts.agent || process.env.WORKPAD_AGENT || session;
456
+ return {
457
+ me,
458
+ session: session !== me ? session : null
459
+ };
460
+ }
461
+ /**
385
462
  * The agent session this command runs in, as the project's plugins know it (Claude Code's
386
463
  * plugin reads it from the environment): the first one that names one. Null without any.
387
464
  */
@@ -406,16 +483,20 @@ async function pageStatus(proj, target) {
406
483
  async function status() {
407
484
  const proj = needProject();
408
485
  const [pages, me] = await Promise.all([api(`/api/status${pageOpt ? `?page=${encodeURIComponent(pageId(proj, pageOpt))}` : ""}`), whoAmI(proj)]);
409
- const names = namesOf(readEvents(proj.eventsFile));
486
+ const events = readEvents(proj.eventsFile);
487
+ const names = namesOf(events);
410
488
  const busy = pages.filter((p) => p.unreceived.length || p.open.length);
411
- if (!busy.length) {
412
- console.log("nothing open: every question is answered, and every answer received");
413
- return;
414
- }
489
+ const now = Date.now();
490
+ const runs = running$1(events).filter((r) => pages.some((p) => p.page === r.page));
491
+ if (!busy.length) console.log("nothing open: every question is answered, and every answer received");
415
492
  for (const p of busy) {
416
493
  console.log(`${p.page} (${whose(p, me, names)})`);
417
494
  for (const l of statusLines(p, relFile(p.file))) console.log(` ${l}`);
418
495
  }
496
+ if (runs.length) {
497
+ console.log("running:");
498
+ for (const r of runs) console.log(` ${r.page}: ${line(r, now)}${r.by ? ` (${r.by === me ? "you" : names.get(r.by) ?? r.by})` : ""}`);
499
+ }
419
500
  }
420
501
  switch (cmd) {
421
502
  case "serve": {
@@ -518,7 +599,7 @@ switch (cmd) {
518
599
  const subscribed = /* @__PURE__ */ new Map();
519
600
  const seen = /* @__PURE__ */ new Set();
520
601
  for (const e of events) if (e.by) seen.add(e.by);
521
- for (const e of subscriptions(events)) subscribed.set(e.by, [...subscribed.get(e.by) ?? [], e.page || "every page"]);
602
+ for (const e of subscriptions(events)) subscribed.set(e.by, [...subscribed.get(e.by) ?? [], e.data?.unfollowed ? "the pages no one follows (through its channel)" : e.page || "every page"]);
522
603
  const listening = /* @__PURE__ */ new Map();
523
604
  const base = await running(proj);
524
605
  if (base) {
@@ -570,6 +651,7 @@ switch (cmd) {
570
651
  const code = arg;
571
652
  if (!code && !me) throw nobody();
572
653
  const base = await ensureServer();
654
+ const pinged = Date.now();
573
655
  const res = await fetch(`${base}/api/ping`, {
574
656
  method: "POST",
575
657
  headers: { "content-type": "application/json" },
@@ -588,16 +670,25 @@ switch (cmd) {
588
670
  else if (body.confirmed) console.log(`answers on your pages come to you already, through this session’s channel.${await covers()}`);
589
671
  else if (body.sent && opts.wait) {
590
672
  console.log("pinged this session’s channel: a pong comes to you as a message; confirm it with the command it names");
591
- const limit = Date.now() + (opts.timeout ? Number(opts.timeout) * 1e3 : 12e4);
592
- while (Date.now() < limit) {
673
+ const timeout = opts.timeout ? Number(opts.timeout) * 1e3 : 12e4;
674
+ const giveUp = pinged + MAX_WAIT;
675
+ const secs = `${Math.round(timeout / 1e3)} s`;
676
+ /** the first turn end after the ping, once seen: the one a pong would have come at */
677
+ let ended = null;
678
+ for (;;) {
593
679
  await new Promise((r) => setTimeout(r, 1e3));
594
680
  if ((await api("/api/channels")).some((c) => c.session === me && c.confirmed)) {
595
681
  console.log(`confirmed: answers on your pages come to you now.${await covers()}`);
596
682
  process.exit(0);
597
683
  }
684
+ const turns = lastTurnEnd(proj.wp, me);
685
+ if (ended === null && turns?.ended != null && turns.ended >= pinged) ended = turns.ended;
686
+ const why = Date.now() >= giveUp ? `no pong came within ${MAX_WAIT / 6e4} minutes` : ended !== null && Date.now() >= ended + timeout ? `no pong came within ${secs} after your turn ended` : !turns && Date.now() >= pinged + timeout ? `no pong came within ${secs}` : null;
687
+ if (why) {
688
+ console.log(`${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`);
689
+ process.exit(1);
690
+ }
598
691
  }
599
- console.log("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");
600
- process.exit(1);
601
692
  } else if (body.sent) console.log("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");
602
693
  else {
603
694
  console.log("nothing brings answers to this session: listen for them (`workpad listen --wait --page <file>` in the background)");
@@ -631,6 +722,48 @@ switch (cmd) {
631
722
  const all = (dir, rel = "") => fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => e.isDirectory() ? all(path.join(dir, e.name), `${rel}${e.name}/`) : e.name.endsWith(".md") ? [`${rel}${e.name.slice(0, -3)}`] : []);
632
723
  const ids = positionals.length ? positionals.map((p) => pageIn(p).id) : all(proj.pagesDir).sort();
633
724
  const text = (s) => s.replace(/<[^>]+>/g, "").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, "\"").replace(/&#39;/g, "'").replace(/&amp;/g, "&").trim();
725
+ const anchorsOfPage = /* @__PURE__ */ new Map();
726
+ const anchorsFor = (page) => {
727
+ if (!anchorsOfPage.has(page)) anchorsOfPage.set(page, anchorsAt(base, page).then((as) => as.map((a) => a.id), () => null));
728
+ return anchorsOfPage.get(page);
729
+ };
730
+ const served = new URL(base);
731
+ const root = served.pathname.replace(/\/$/, "");
732
+ /**
733
+ * The links of a rendered page to a place on another page of this project (`decisions.md#form:x`,
734
+ * or its own page by its file) whose anchor that page doesn't have. A link to `#…` alone is the
735
+ * render's own notice; one to another project, server or site isn't checked.
736
+ */
737
+ const brokenLinks = async (id, body) => {
738
+ const out = [];
739
+ for (const m of body.matchAll(/<a\b[^>]*?\shref="([^"]*)"/g)) {
740
+ const href = text(m[1]);
741
+ if (!href || href.startsWith("#")) continue;
742
+ let url;
743
+ try {
744
+ url = new URL(href, `${base}/${id.split("/").map(encodeURIComponent).join("/")}`);
745
+ } catch {
746
+ continue;
747
+ }
748
+ if (url.origin !== served.origin || !url.pathname.startsWith(`${root}/`) || url.hash.length < 2) continue;
749
+ let page;
750
+ let anchor;
751
+ try {
752
+ page = decodeURIComponent(url.pathname.slice(root.length + 1)).replace(/\/$/, "");
753
+ anchor = decodeURIComponent(url.hash.slice(1));
754
+ } catch {
755
+ continue;
756
+ }
757
+ if (anchor.startsWith("message:")) continue;
758
+ const repo = page === "-" || page.startsWith("-/");
759
+ if (repo ? !/\.(md|markdown)$/i.test(page) : path.extname(page) && !/\.md$/i.test(page)) continue;
760
+ if (!repo) page = page.replace(/\.md$/i, "");
761
+ const has = await anchorsFor(page);
762
+ if (!has) out.push(`a link to \`${page}${hashOf(anchor)}\`: there is no page ${page}`);
763
+ else if (!has.includes(anchor)) out.push(`a link to \`${page}${hashOf(anchor)}\`, which ${page} doesn't have${nearest(anchor, has)}`);
764
+ }
765
+ return out;
766
+ };
634
767
  let found = 0;
635
768
  const config = /* @__PURE__ */ new Set();
636
769
  for (const id of ids) {
@@ -641,9 +774,14 @@ switch (cmd) {
641
774
  continue;
642
775
  }
643
776
  const { html: body = "", notices = [] } = await res.json();
777
+ anchorsOfPage.set(id, Promise.resolve(anchorsOf(body).map((a) => a.id)));
644
778
  const errors = [...body.matchAll(/<(\w+) class="wp-error"[^>]*>([\s\S]*?)<\/\1>/g)].map((m) => text(m[2]));
645
779
  for (const n of notices) if (n.startsWith("config: ")) config.add(n);
646
- const problems = [.../* @__PURE__ */ new Set([...notices.filter((n) => !n.startsWith("config: ")), ...errors])];
780
+ const problems = [.../* @__PURE__ */ new Set([
781
+ ...notices.filter((n) => !n.startsWith("config: ")),
782
+ ...errors,
783
+ ...await brokenLinks(id, body)
784
+ ])];
647
785
  if (!problems.length) continue;
648
786
  found += problems.length;
649
787
  console.log(`${id}\n${problems.map((p) => ` ${p.replace(/\n/g, "\n ")}`).join("\n")}`);
@@ -699,6 +837,17 @@ switch (cmd) {
699
837
  for (const a of anchors) console.log(`${hashOf(a.id)} ${a.kind}${a.label !== a.id.slice(a.kind.length + 1) ? ` ${a.label}` : ""}`);
700
838
  break;
701
839
  }
840
+ case "set": {
841
+ const [target, name] = positionals;
842
+ if (!target || !name || opts.file === void 0) throw new Error("usage: workpad set <page|file> <anchor|form> --file <file|->");
843
+ const file = fileOf(needProject(), target);
844
+ if (!fs.existsSync(file)) throw new Error(`no page ${target} (${relFile(file)})`);
845
+ const source = fs.readFileSync(file, "utf8");
846
+ const block = findBlock(source, name);
847
+ fs.writeFileSync(file, setBlock(source, name, readInput(opts.file, "--file")));
848
+ console.log(`replaced ${hashOf(block.id)} (${block.kind === "heading" ? "its section" : block.kind}) in ${relFile(file)}`);
849
+ break;
850
+ }
702
851
  case "archive":
703
852
  case "destroy": {
704
853
  const target = positionals[0];
@@ -749,15 +898,10 @@ switch (cmd) {
749
898
  }
750
899
  case "edit": {
751
900
  const eventId = positionals[0];
752
- if (!eventId || !opts.data) throw new Error("usage: workpad edit <event id> --data <json> (merged into the event's data)");
901
+ const data = eventData();
902
+ if (!eventId || data === void 0) throw new Error("usage: workpad edit <event id> --data <json> | --file <file|-> | --text-file <file|-> (merged into the event's data)");
753
903
  const proj = needProject();
754
- let data;
755
- try {
756
- data = JSON.parse(opts.data);
757
- } catch {
758
- throw new Error("--data must be a JSON object");
759
- }
760
- if (!data || typeof data !== "object" || Array.isArray(data)) throw new Error("--data must be a JSON object");
904
+ if (!data || typeof data !== "object" || Array.isArray(data)) throw new Error("the data must be a JSON object");
761
905
  console.log(JSON.stringify(editEvent(proj.eventsFile, eventId, data)));
762
906
  break;
763
907
  }
@@ -865,9 +1009,19 @@ switch (cmd) {
865
1009
  const named = positionals.slice(1);
866
1010
  if (named.length && opts.all) throw new Error("settle takes forms or --all, not both");
867
1011
  if (!named.length && !opts.all) throw new Error(`name the forms to settle, or --all for every open one: open on ${p.page} ${p.open.length ? `are ${p.open.join(", ")}` : "is none"}`);
1012
+ let replaced = null;
1013
+ if (opts["replace-with"] !== void 0) {
1014
+ if (opts.all || named.length !== 1) throw new Error("--replace-with replaces one form: name it, without --all");
1015
+ const source = fs.readFileSync(p.file, "utf8");
1016
+ replaced = setBlock(source, `form:${named[0]}`, readInput(opts["replace-with"], "--replace-with"));
1017
+ }
868
1018
  const { forms, skipped } = settleForms(proj.eventsFile, p, opts.all ? "all" : named, await whoAmI(proj));
869
1019
  for (const { name, state } of skipped) console.error(`workpad: ${name} isn't open (${state}): left as it is`);
870
1020
  console.log(forms.length ? `settled on ${p.page}: ${forms.join(", ")}` : `nothing to settle on ${p.page}`);
1021
+ if (replaced !== null) {
1022
+ fs.writeFileSync(p.file, replaced);
1023
+ console.log(`replaced the form ${named[0]} on ${p.page}`);
1024
+ }
871
1025
  break;
872
1026
  }
873
1027
  case "hold": {
@@ -907,17 +1061,24 @@ switch (cmd) {
907
1061
  case "listen": {
908
1062
  const proj = needProject();
909
1063
  const f = filter();
910
- const agent = await whoAmI(proj);
1064
+ const { me: agent, session } = await whoAmIWithSession(proj);
1065
+ const aliases = new Set(session ? [session] : []);
911
1066
  if (opts.follow) throw new Error("listen runs on by itself: --wait stops at the first answer, --channel hands over to the channel");
912
1067
  if (opts.wait && opts.channel) throw new Error("listen takes --wait or --channel, not both");
913
1068
  if (opts.timeout && !opts.wait) throw new Error("--timeout goes with --wait");
1069
+ if (opts.unfollowed) {
1070
+ if (pagesGiven.length) throw new Error("--unfollowed takes the pages no one follows: no --page with it");
1071
+ if (opts.channel) await channelUnfollowed(proj, agent);
1072
+ else await unfollowedListen(proj, f.type ?? null, agent);
1073
+ break;
1074
+ }
914
1075
  if (opts.channel) {
915
1076
  await channelListen(proj, agent);
916
1077
  break;
917
1078
  }
918
1079
  const entry = !f.page && isShared(proj) ? matchesEntries(readMachineConfig(), proj.dir) : null;
919
1080
  if (entry) {
920
- await entryListen(entry, f, agent);
1081
+ await entryListen(entry, f, agent, aliases);
921
1082
  break;
922
1083
  }
923
1084
  const isForAgent = await liveForAgent(proj);
@@ -936,7 +1097,8 @@ switch (cmd) {
936
1097
  const options = {
937
1098
  batch: !!opts.wait,
938
1099
  forAgent: isForAgent,
939
- agent
1100
+ agent,
1101
+ aliases
940
1102
  };
941
1103
  if (opts.timeout && opts.wait) setTimeout(() => {
942
1104
  console.error("timeout");
@@ -967,18 +1129,16 @@ switch (cmd) {
967
1129
  }
968
1130
  case "append": {
969
1131
  const proj = needProject();
970
- if (!pageOpt || !opts.type) throw new Error("usage: workpad append --page <page|file> --type <type> [--data '<json>']");
971
- let data = {};
972
- if (opts.data) try {
973
- data = JSON.parse(opts.data);
974
- } catch {
975
- throw new Error("--data must be JSON, e.g. '{\"text\":\"…\"}'");
976
- }
1132
+ if (!pageOpt || !opts.type) throw new Error("usage: workpad append --page <page|file> --type <type> [--data '<json>' | --file <file|->] [--text-file <file|->]");
1133
+ const data = eventData() ?? {};
1134
+ const refused = refusal(opts.type, data, (await projectConfig(proj)).requires);
1135
+ if (refused) throw new Error(`${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 -`);
1136
+ const { me, session } = await whoAmIWithSession(proj);
977
1137
  console.log(JSON.stringify(appendEvent(proj.eventsFile, {
978
1138
  page: pageId(proj, pageOpt),
979
1139
  type: opts.type,
980
1140
  data
981
- }, "cli", await whoAmI(proj))));
1141
+ }, "cli", me, session)));
982
1142
  break;
983
1143
  }
984
1144
  case "status":
@@ -1073,6 +1233,7 @@ switch (cmd) {
1073
1233
  };
1074
1234
  },
1075
1235
  version: VERSION,
1236
+ agent: me,
1076
1237
  wp: client(async () => probe(await ensureServer()), {
1077
1238
  token: projectToken(project.wp),
1078
1239
  agent: me
@@ -1087,12 +1248,20 @@ switch (cmd) {
1087
1248
  ...options,
1088
1249
  forAgent: await liveForAgent(project, options?.signal)
1089
1250
  }),
1090
- listen: (page, { agent = null } = {}) => listen({
1251
+ listen: (page, { agent = null, signal } = {}) => listen({
1091
1252
  at: () => ensureServer().catch(() => null),
1092
1253
  query: {
1093
1254
  page: pageId(project, page),
1094
1255
  ...agent ? { agent } : {}
1095
- }
1256
+ },
1257
+ signal
1258
+ }),
1259
+ unfollowed: (onEvent, { agent = null, mark, signal } = {}) => holdUnfollowed(project, {
1260
+ at: () => ensureServer().catch(() => null),
1261
+ agent,
1262
+ mark,
1263
+ signal,
1264
+ onEvent
1096
1265
  }),
1097
1266
  channel: (session, handlers) => holdChannel(() => ensureServer().catch(() => null), session, handlers),
1098
1267
  authLink: async (to) => `${await ensureServer()}/_/auth?token=${encodeURIComponent(projectToken(project.wp))}&to=${encodeURIComponent(to)}`
@@ -1118,12 +1287,8 @@ switch (cmd) {
1118
1287
  * those waiting now: so nothing is printed here, which would hand them out twice. Only for a session
1119
1288
  * whose channel is confirmed (`workpad agent ping`); else nothing is taken on.
1120
1289
  */
1121
- async function channelListen(proj, agent) {
1122
- if (!agent) throw new Error("--channel needs a session: no --agent, WORKPAD_AGENT or plugin session names one");
1123
- if (!(await api("/api/channels")).some((c) => c.session === agent && c.confirmed)) {
1124
- console.error("workpad: no confirmed channel brings answers to this session: run `workpad agent ping` and confirm its pong, or listen without --channel");
1125
- process.exit(1);
1126
- }
1290
+ async function channelListen(proj, who) {
1291
+ const agent = await confirmedChannel(who);
1127
1292
  const pages = [...new Set(pagesGiven.map((p) => pageId(proj, p)))];
1128
1293
  for (const page of pages.length ? pages : [""]) subscribe(proj, page, agent, { channel: true });
1129
1294
  const { events } = read(proj.eventsFile);
@@ -1132,7 +1297,7 @@ async function channelListen(proj, agent) {
1132
1297
  const handled = handledIds(events);
1133
1298
  const received = receivedIds(events);
1134
1299
  const skipped = events.filter((e) => {
1135
- if (fromReader(e) || !e.by || e.by === agent || !isForAgent(e.type) || handled.has(e.id)) return false;
1300
+ if (fromReader(e) || !e.by || e.by === agent || e.session === agent || !isForAgent(e.type) || handled.has(e.id)) return false;
1136
1301
  if (!received.has(e.id)) return false;
1137
1302
  const since = channelSince(events, agent, e.page);
1138
1303
  if (!since) return false;
@@ -1145,13 +1310,137 @@ async function channelListen(proj, agent) {
1145
1310
  console.log(`${skipped.length} earlier message${skipped.length === 1 ? "" : "s"} from other agents, received before, skipped (on ${on.join(", ")}): \`workpad listen --wait --page <page>\` hands them to you`);
1146
1311
  }
1147
1312
  }
1313
+ /** `agent`, when a confirmed channel brings answers to it; else the command ends saying so. */
1314
+ async function confirmedChannel(agent) {
1315
+ if (!agent) throw new Error("--channel needs a session: no --agent, WORKPAD_AGENT or plugin session names one");
1316
+ if (!(await api("/api/channels")).some((c) => c.session === agent && c.confirmed)) {
1317
+ console.error("workpad: no confirmed channel brings answers to this session: run `workpad agent ping` and confirm its pong, or listen without --channel");
1318
+ process.exit(1);
1319
+ }
1320
+ return agent;
1321
+ }
1322
+ /**
1323
+ * Take the pages no one follows (`workpad listen --unfollowed`): a listen held at the server, which
1324
+ * holds it on each such page and says which they are as that changes; from each, the reader's
1325
+ * answers no other agent received (not the page's own agents' messages, nor what a session took
1326
+ * and works on between turns) go to `onEvent`, received by `agent` unless `mark` is false. Under
1327
+ * the shared server the pages of every project of this one's entry, each answer with where it is
1328
+ * (`from`). `onFirst`: the pages there were at first handed out what waited on them. Resolves once
1329
+ * the server holds it, or after a first try that found none running (it holds it once one runs).
1330
+ */
1331
+ async function holdUnfollowed(proj, options) {
1332
+ const { agent, type, mark, signal, onEvent, onFirst } = options;
1333
+ const shared = isShared(proj);
1334
+ const entry = shared ? matchesEntries(readMachineConfig(), proj.dir) : null;
1335
+ let origin = "";
1336
+ const address = (id) => id.split("/").map(encodeURIComponent).join("/");
1337
+ let reading = [];
1338
+ const update = everyPage((p, stop) => {
1339
+ const there = p.dir === proj.dir ? proj : project$1(p.dir);
1340
+ if (!there) return;
1341
+ reading.push(projectConfig(there).then(({ handedOut }) => {
1342
+ if (stop.aborted) return;
1343
+ handOut(there.eventsFile, {
1344
+ page: p.page,
1345
+ exact: true,
1346
+ type
1347
+ }, (e, again) => onEvent(e, again, shared ? {
1348
+ project: p.dir,
1349
+ url: `${origin}${p.base}/${address(e.page)}`
1350
+ } : null), {
1351
+ forAgent: forAgent(handedOut),
1352
+ agent,
1353
+ mark,
1354
+ readerOnly: true,
1355
+ notReceivedByOthers: true,
1356
+ signal: signal ? AbortSignal.any([stop, signal]) : stop
1357
+ });
1358
+ }));
1359
+ });
1360
+ let first = true;
1361
+ await listen({
1362
+ at: shared ? async () => {
1363
+ origin = (await sharedServer(machineServerFile()))?.origin ?? "";
1364
+ return origin || null;
1365
+ } : options.at,
1366
+ query: {
1367
+ unfollowed: "1",
1368
+ ...entry && { entry },
1369
+ ...type && { type },
1370
+ ...agent && { agent }
1371
+ },
1372
+ onPages: (pages) => {
1373
+ reading = [];
1374
+ update(pages);
1375
+ if (!first) return;
1376
+ first = false;
1377
+ Promise.all(reading).then(() => onFirst?.());
1378
+ },
1379
+ signal
1380
+ }, { orNone: true });
1381
+ }
1382
+ /**
1383
+ * `workpad listen --unfollowed`: the reader's answers on the pages no one follows, one line each, as
1384
+ * they come; with --wait all there are, or with none the first to come, and it stops. Under the
1385
+ * shared server each line says where it is (`project`, `url`).
1386
+ */
1387
+ async function unfollowedListen(proj, type, agent) {
1388
+ if (opts.timeout && opts.wait) setTimeout(() => {
1389
+ console.error("timeout");
1390
+ process.exit(2);
1391
+ }, Number(opts.timeout) * 1e3);
1392
+ let printed = 0;
1393
+ let following = false;
1394
+ let ending = false;
1395
+ const end = () => {
1396
+ if (ending) return;
1397
+ ending = true;
1398
+ setImmediate(() => process.exit(0));
1399
+ };
1400
+ await holdUnfollowed(proj, {
1401
+ at: () => needServer().catch(() => null),
1402
+ agent,
1403
+ type,
1404
+ onEvent: (e, again, from) => {
1405
+ console.log(JSON.stringify({
1406
+ ...e,
1407
+ ...again && { again: true },
1408
+ ...from
1409
+ }));
1410
+ printed++;
1411
+ if (opts.wait && following) end();
1412
+ },
1413
+ onFirst: () => {
1414
+ following = true;
1415
+ if (opts.wait && printed) end();
1416
+ }
1417
+ });
1418
+ setInterval(() => {}, 1 << 30);
1419
+ }
1420
+ /**
1421
+ * `workpad listen --unfollowed --channel`: the session's confirmed channel takes the pages no one
1422
+ * follows, for as long as it runs; none becomes the session's (status.ts, takesUnfollowed).
1423
+ */
1424
+ async function channelUnfollowed(proj, agent) {
1425
+ const me = await confirmedChannel(agent);
1426
+ if (!takesUnfollowed(readEvents(proj.eventsFile), me)) appendEvent(proj.eventsFile, {
1427
+ page: "",
1428
+ type: SUBSCRIBE,
1429
+ data: {
1430
+ channel: true,
1431
+ unfollowed: true
1432
+ }
1433
+ }, "cli", me);
1434
+ const entry = isShared(proj) ? matchesEntries(readMachineConfig(), proj.dir) : null;
1435
+ console.log(`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`);
1436
+ }
1148
1437
  /**
1149
1438
  * A listen over a whole entry: every page of each of its projects, from each project's own log, each
1150
1439
  * event with the project it is from (`project`, its folder) and its page's `url`. Any number run.
1151
1440
  * Without a shared server running it waits for one, as any listen does. Projects that appear
1152
1441
  * meanwhile are followed too.
1153
1442
  */
1154
- async function entryListen(entry, f, agent) {
1443
+ async function entryListen(entry, f, agent, aliases) {
1155
1444
  const file = machineServerFile();
1156
1445
  const count = opts.wait ? 1 : Infinity;
1157
1446
  const done = new AbortController();
@@ -1176,6 +1465,7 @@ async function entryListen(entry, f, agent) {
1176
1465
  }, {
1177
1466
  forAgent: forAgent(handedOut),
1178
1467
  agent,
1468
+ aliases,
1179
1469
  signal: AbortSignal.any([signal, done.signal])
1180
1470
  }));
1181
1471
  });