@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
@@ -8,16 +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, takesUnfollowed, 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
20
  import { everyPage, everyProject, holdChannel, listen } from "../src/listen.js";
20
21
  import { lastTurnEnd } from "../src/turns.js";
22
+ import { line, running as running$1 } from "../plugins/progress/state.js";
21
23
  import fs from "node:fs";
22
24
  import path from "node:path";
23
25
  import os from "node:os";
@@ -87,7 +89,10 @@ const { values: opts, positionals } = cmd && !BUILTIN_COMMANDS.has(cmd) ? {
87
89
  wait: { type: "boolean" },
88
90
  channel: { type: "boolean" },
89
91
  unfollowed: { type: "boolean" },
90
- all: { type: "boolean" }
92
+ all: { type: "boolean" },
93
+ file: { type: "string" },
94
+ "text-file": { type: "string" },
95
+ "replace-with": { type: "string" }
91
96
  }
92
97
  });
93
98
  if (cmd && cmd !== "help" && BUILTIN_COMMANDS.has(cmd) && opts.help) {
@@ -221,6 +226,41 @@ function pageIn(target) {
221
226
  id: pageId(proj, target)
222
227
  };
223
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
+ }
224
264
  /** Where a project is served: its running server, or an error saying how to start one. */
225
265
  async function serverOf(proj) {
226
266
  if (proj.dir === project?.dir) return needServer();
@@ -405,6 +445,20 @@ async function whoAmI(proj) {
405
445
  return opts.agent || process.env.WORKPAD_AGENT || await currentSession(proj);
406
446
  }
407
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
+ /**
408
462
  * The agent session this command runs in, as the project's plugins know it (Claude Code's
409
463
  * plugin reads it from the environment): the first one that names one. Null without any.
410
464
  */
@@ -429,16 +483,20 @@ async function pageStatus(proj, target) {
429
483
  async function status() {
430
484
  const proj = needProject();
431
485
  const [pages, me] = await Promise.all([api(`/api/status${pageOpt ? `?page=${encodeURIComponent(pageId(proj, pageOpt))}` : ""}`), whoAmI(proj)]);
432
- const names = namesOf(readEvents(proj.eventsFile));
486
+ const events = readEvents(proj.eventsFile);
487
+ const names = namesOf(events);
433
488
  const busy = pages.filter((p) => p.unreceived.length || p.open.length);
434
- if (!busy.length) {
435
- console.log("nothing open: every question is answered, and every answer received");
436
- return;
437
- }
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");
438
492
  for (const p of busy) {
439
493
  console.log(`${p.page} (${whose(p, me, names)})`);
440
494
  for (const l of statusLines(p, relFile(p.file))) console.log(` ${l}`);
441
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
+ }
442
500
  }
443
501
  switch (cmd) {
444
502
  case "serve": {
@@ -664,6 +722,48 @@ switch (cmd) {
664
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)}`] : []);
665
723
  const ids = positionals.length ? positionals.map((p) => pageIn(p).id) : all(proj.pagesDir).sort();
666
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
+ };
667
767
  let found = 0;
668
768
  const config = /* @__PURE__ */ new Set();
669
769
  for (const id of ids) {
@@ -674,9 +774,14 @@ switch (cmd) {
674
774
  continue;
675
775
  }
676
776
  const { html: body = "", notices = [] } = await res.json();
777
+ anchorsOfPage.set(id, Promise.resolve(anchorsOf(body).map((a) => a.id)));
677
778
  const errors = [...body.matchAll(/<(\w+) class="wp-error"[^>]*>([\s\S]*?)<\/\1>/g)].map((m) => text(m[2]));
678
779
  for (const n of notices) if (n.startsWith("config: ")) config.add(n);
679
- 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
+ ])];
680
785
  if (!problems.length) continue;
681
786
  found += problems.length;
682
787
  console.log(`${id}\n${problems.map((p) => ` ${p.replace(/\n/g, "\n ")}`).join("\n")}`);
@@ -732,6 +837,17 @@ switch (cmd) {
732
837
  for (const a of anchors) console.log(`${hashOf(a.id)} ${a.kind}${a.label !== a.id.slice(a.kind.length + 1) ? ` ${a.label}` : ""}`);
733
838
  break;
734
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
+ }
735
851
  case "archive":
736
852
  case "destroy": {
737
853
  const target = positionals[0];
@@ -782,15 +898,10 @@ switch (cmd) {
782
898
  }
783
899
  case "edit": {
784
900
  const eventId = positionals[0];
785
- 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)");
786
903
  const proj = needProject();
787
- let data;
788
- try {
789
- data = JSON.parse(opts.data);
790
- } catch {
791
- throw new Error("--data must be a JSON object");
792
- }
793
- 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");
794
905
  console.log(JSON.stringify(editEvent(proj.eventsFile, eventId, data)));
795
906
  break;
796
907
  }
@@ -898,9 +1009,19 @@ switch (cmd) {
898
1009
  const named = positionals.slice(1);
899
1010
  if (named.length && opts.all) throw new Error("settle takes forms or --all, not both");
900
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
+ }
901
1018
  const { forms, skipped } = settleForms(proj.eventsFile, p, opts.all ? "all" : named, await whoAmI(proj));
902
1019
  for (const { name, state } of skipped) console.error(`workpad: ${name} isn't open (${state}): left as it is`);
903
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
+ }
904
1025
  break;
905
1026
  }
906
1027
  case "hold": {
@@ -940,7 +1061,8 @@ switch (cmd) {
940
1061
  case "listen": {
941
1062
  const proj = needProject();
942
1063
  const f = filter();
943
- const agent = await whoAmI(proj);
1064
+ const { me: agent, session } = await whoAmIWithSession(proj);
1065
+ const aliases = new Set(session ? [session] : []);
944
1066
  if (opts.follow) throw new Error("listen runs on by itself: --wait stops at the first answer, --channel hands over to the channel");
945
1067
  if (opts.wait && opts.channel) throw new Error("listen takes --wait or --channel, not both");
946
1068
  if (opts.timeout && !opts.wait) throw new Error("--timeout goes with --wait");
@@ -956,7 +1078,7 @@ switch (cmd) {
956
1078
  }
957
1079
  const entry = !f.page && isShared(proj) ? matchesEntries(readMachineConfig(), proj.dir) : null;
958
1080
  if (entry) {
959
- await entryListen(entry, f, agent);
1081
+ await entryListen(entry, f, agent, aliases);
960
1082
  break;
961
1083
  }
962
1084
  const isForAgent = await liveForAgent(proj);
@@ -975,7 +1097,8 @@ switch (cmd) {
975
1097
  const options = {
976
1098
  batch: !!opts.wait,
977
1099
  forAgent: isForAgent,
978
- agent
1100
+ agent,
1101
+ aliases
979
1102
  };
980
1103
  if (opts.timeout && opts.wait) setTimeout(() => {
981
1104
  console.error("timeout");
@@ -1006,18 +1129,16 @@ switch (cmd) {
1006
1129
  }
1007
1130
  case "append": {
1008
1131
  const proj = needProject();
1009
- if (!pageOpt || !opts.type) throw new Error("usage: workpad append --page <page|file> --type <type> [--data '<json>']");
1010
- let data = {};
1011
- if (opts.data) try {
1012
- data = JSON.parse(opts.data);
1013
- } catch {
1014
- throw new Error("--data must be JSON, e.g. '{\"text\":\"…\"}'");
1015
- }
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);
1016
1137
  console.log(JSON.stringify(appendEvent(proj.eventsFile, {
1017
1138
  page: pageId(proj, pageOpt),
1018
1139
  type: opts.type,
1019
1140
  data
1020
- }, "cli", await whoAmI(proj))));
1141
+ }, "cli", me, session)));
1021
1142
  break;
1022
1143
  }
1023
1144
  case "status":
@@ -1112,6 +1233,7 @@ switch (cmd) {
1112
1233
  };
1113
1234
  },
1114
1235
  version: VERSION,
1236
+ agent: me,
1115
1237
  wp: client(async () => probe(await ensureServer()), {
1116
1238
  token: projectToken(project.wp),
1117
1239
  agent: me
@@ -1126,12 +1248,13 @@ switch (cmd) {
1126
1248
  ...options,
1127
1249
  forAgent: await liveForAgent(project, options?.signal)
1128
1250
  }),
1129
- listen: (page, { agent = null } = {}) => listen({
1251
+ listen: (page, { agent = null, signal } = {}) => listen({
1130
1252
  at: () => ensureServer().catch(() => null),
1131
1253
  query: {
1132
1254
  page: pageId(project, page),
1133
1255
  ...agent ? { agent } : {}
1134
- }
1256
+ },
1257
+ signal
1135
1258
  }),
1136
1259
  unfollowed: (onEvent, { agent = null, mark, signal } = {}) => holdUnfollowed(project, {
1137
1260
  at: () => ensureServer().catch(() => null),
@@ -1174,7 +1297,7 @@ async function channelListen(proj, who) {
1174
1297
  const handled = handledIds(events);
1175
1298
  const received = receivedIds(events);
1176
1299
  const skipped = events.filter((e) => {
1177
- 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;
1178
1301
  if (!received.has(e.id)) return false;
1179
1302
  const since = channelSince(events, agent, e.page);
1180
1303
  if (!since) return false;
@@ -1317,7 +1440,7 @@ async function channelUnfollowed(proj, agent) {
1317
1440
  * Without a shared server running it waits for one, as any listen does. Projects that appear
1318
1441
  * meanwhile are followed too.
1319
1442
  */
1320
- async function entryListen(entry, f, agent) {
1443
+ async function entryListen(entry, f, agent, aliases) {
1321
1444
  const file = machineServerFile();
1322
1445
  const count = opts.wait ? 1 : Infinity;
1323
1446
  const done = new AbortController();
@@ -1342,6 +1465,7 @@ async function entryListen(entry, f, agent) {
1342
1465
  }, {
1343
1466
  forAgent: forAgent(handedOut),
1344
1467
  agent,
1468
+ aliases,
1345
1469
  signal: AbortSignal.any([signal, done.signal])
1346
1470
  }));
1347
1471
  });
@@ -102,23 +102,82 @@ function questionState(name, events, listeners, marks) {
102
102
  hold
103
103
  };
104
104
  }
105
+ /** Does anyone listen for the answer to question `name`? Not: it is unheard. */
106
+ const heard = (name, listeners) => listeners.some((l) => l.type === null || l.type === name);
107
+ /**
108
+ * After how long an answer no agent received is late, in ms: the page flags it ("not received after
109
+ * 10 min") and counts it, as something went wrong on the agent's side (a session gone, a channel
110
+ * down, a server under load).
111
+ */
112
+ const NOT_RECEIVED_AFTER = 6e5;
113
+ /**
114
+ * Where one of the reader's events for an agent went (Delivery), at time `now` (ms): from its marks
115
+ * (received, handled; `receivedBy`), whether it is still on its way (`sending`), and who listens on
116
+ * its page (`listeners`, those covering it). Someone takes it when a listener hears its type
117
+ * (heard): a listen on the page, a confirmed channel, also a coordinator's listen on the unfollowed
118
+ * pages, which follows the page for no one but does receive what is sent there.
119
+ */
120
+ function deliveryOf(e, listeners, now, after = NOT_RECEIVED_AFTER) {
121
+ if (e.sending) return {
122
+ state: "sending",
123
+ text: "sending…"
124
+ };
125
+ if (e.handled) return {
126
+ state: "handled",
127
+ text: "handled"
128
+ };
129
+ if (e.received) return e.receivedBy ? {
130
+ state: "received",
131
+ text: `received by ${e.receivedBy}`,
132
+ by: e.receivedBy
133
+ } : {
134
+ state: "received",
135
+ text: "received"
136
+ };
137
+ const nobody = !heard(e.type, listeners);
138
+ if (now - Date.parse(e.ts) >= after) return {
139
+ state: "late",
140
+ text: `not received after ${Math.round(after / 6e4)} min${nobody ? " · no one follows this page" : ""}`,
141
+ nobody
142
+ };
143
+ return nobody ? {
144
+ state: "unfollowed",
145
+ text: "no one follows this page — it waits until an agent listens"
146
+ } : {
147
+ state: "waiting",
148
+ text: "waiting for an agent to receive it"
149
+ };
150
+ }
105
151
  /** The type of the event the page appends once messages were in view: `{ ids }`. */
106
152
  const READ = "workpad:read";
107
153
  /**
108
- * The agent's messages on a page the reader hasn't read: events from the agent of a type
109
- * `isMessage` says is for the reader, not named by a `workpad:read` from the reader, not
110
- * replaced by a later one (`replaces`), and, given the page's `chats`, not in a chat (`data.chat`)
111
- * that is no longer among them.
154
+ * The fields of an event's `data` its type requires (EventSpec.requires) that it lacks: each must
155
+ * be a non-empty string.
156
+ */
157
+ const missingData = (data, requires) => requires.filter((field) => {
158
+ const value = data?.[field];
159
+ return typeof value !== "string" || !value.trim();
160
+ });
161
+ /**
162
+ * The agent's messages on a page the reader hasn't read: events from the agent of a type in
163
+ * `messages` (the types for the reader, each with the `data` fields it requires), not named by a
164
+ * `workpad:read` from the reader, not replaced by a later one (`replaces`), with the data their
165
+ * type requires (one without it shows nowhere on the page, so it waits for nobody), and, given the
166
+ * page's `chats`, not in a chat (`data.chat`) that is no longer among them.
112
167
  */
113
- function unreadMessages(events, isMessage, chats) {
168
+ function unreadMessages(events, messages, chats) {
114
169
  const read = /* @__PURE__ */ new Set();
115
170
  const replaced = /* @__PURE__ */ new Set();
116
171
  for (const e of events) {
117
172
  if (e.type === "workpad:read" && fromReader(e)) for (const id of e.data?.ids ?? []) read.add(String(id));
118
173
  if (e.data?.replaces) replaced.add(String(e.data.replaces));
119
174
  }
175
+ const shown = (e) => {
176
+ const requires = messages.get(e.type);
177
+ return !!requires && !missingData(e.data, requires).length;
178
+ };
120
179
  const offPage = (e) => !!chats && typeof e.data?.chat === "string" && !chats.has(e.data.chat);
121
- return events.filter((e) => !fromReader(e) && isMessage(e.type) && !read.has(e.id) && !replaced.has(e.id) && !offPage(e));
180
+ return events.filter((e) => !fromReader(e) && shown(e) && !read.has(e.id) && !replaced.has(e.id) && !offPage(e));
122
181
  }
123
182
  /**
124
183
  * The type of the event that settles questions (`workpad settle`): `{ forms: [<name>…] }`. An
@@ -329,16 +388,21 @@ async function onSubmit(e) {
329
388
  }
330
389
  const sendButtons = (form) => [...form.querySelectorAll("button, input[type=submit]")].filter((b) => (b instanceof HTMLInputElement || b.type !== "button" && b.type !== "reset") && b.form === form);
331
390
  function showStatus(form) {
332
- const text = form.dataset.wpState === "failed" ? ["couldn't send it", "bad"] : form.dataset.wpState === "sending" ? null : form.hasAttribute("data-wp-pending") ? ["waiting for an agent to receive it", null] : form.hasAttribute("data-wp-received") ? ["the agent has it", null] : null;
391
+ const last = api$1.last(form.getAttribute("name"));
392
+ const delivery = last ? api$1.delivery().get(last.id) : void 0;
393
+ const answered = form.hasAttribute("data-wp-pending") || form.hasAttribute("data-wp-received");
394
+ const text = form.dataset.wpState === "failed" ? ["couldn't send it", "bad"] : form.dataset.wpState === "sending" || !answered || !delivery || delivery.state === "sending" ? null : [delivery.text, delivery.state === "late" ? "warn" : null];
333
395
  let el = form.querySelector(".wp-form-status");
334
- const last = sendButtons(form).at(-1);
335
- if (!text || !last) return void el?.remove();
396
+ const button = sendButtons(form).at(-1);
397
+ if (!text || !button) return void el?.remove();
336
398
  if (!el) el = Object.assign(document.createElement("span"), { className: "wp-form-status" });
337
399
  el.setAttribute("role", "status");
338
- if (el.previousElementSibling !== last) last.after(el);
400
+ if (el.previousElementSibling !== button) button.after(el);
339
401
  el.textContent = text[0];
340
402
  if (text[1]) el.dataset.kind = text[1];
341
403
  else delete el.dataset.kind;
404
+ if (text[1] === "bad") delete el.dataset.wpDelivery;
405
+ else el.dataset.wpDelivery = delivery.state;
342
406
  }
343
407
  const ATTR = {
344
408
  open: "data-wp-open",
@@ -439,6 +503,9 @@ function trackForms(el, pageId, core) {
439
503
  document.addEventListener("submit", onSubmit, { capture: true });
440
504
  api$1.onRendered(refresh);
441
505
  api$1.listeners.on(mark);
506
+ api$1.delivery.on(() => {
507
+ for (const form of forms()) showStatus(form);
508
+ });
442
509
  api$1.events.on(() => {
443
510
  restoreLast(false);
444
511
  mark();
@@ -468,6 +535,39 @@ function trackForms(el, pageId, core) {
468
535
  /** For the api: every named form and where it stands, as it changes. */
469
536
  const forms_ = reactive(() => current);
470
537
  const formsApi = { forms: forms_ };
538
+ // src/client/delivery.ts
539
+ const same = (a, b) => a.size === b.size && [...a].every(([id, d]) => b.get(id)?.text === d.text);
540
+ /**
541
+ * The delivery of each of the reader's events for an agent among `events`: a form's answer (a type
542
+ * without a colon) and the plugins' types in `handedOut`.
543
+ */
544
+ function trackDelivery(events, listeners, handedOut) {
545
+ const forAgent = (e) => fromReader(e) && (isQuestionName(e.type) || handedOut.has(e.type));
546
+ let current = /* @__PURE__ */ new Map();
547
+ let timer;
548
+ const value = reactive(() => current);
549
+ const update = () => {
550
+ const now = Date.now();
551
+ const listening = listeners();
552
+ const next = /* @__PURE__ */ new Map();
553
+ let soonest = Infinity;
554
+ for (const e of events()) {
555
+ if (!forAgent(e)) continue;
556
+ const d = deliveryOf(e, listening, now);
557
+ next.set(e.id, d);
558
+ if (d.state === "waiting" || d.state === "unfollowed") soonest = Math.min(soonest, Date.parse(e.ts) + NOT_RECEIVED_AFTER - now);
559
+ }
560
+ clearTimeout(timer);
561
+ if (soonest < Infinity) timer = setTimeout(update, Math.max(0, soonest) + 50);
562
+ if (same(current, next)) return;
563
+ current = next;
564
+ value.notify();
565
+ };
566
+ events.on(update);
567
+ listeners.on(update);
568
+ update();
569
+ return value;
570
+ }
471
571
  // src/client/toast.ts
472
572
  let box = null;
473
573
  function place(corner) {
@@ -480,7 +580,7 @@ function place(corner) {
480
580
  return box;
481
581
  }
482
582
  function createToast(corner) {
483
- return function toast(text, { kind = "info", ms = 7e3, onClick, onDismiss, name, order = 0, details } = {}) {
583
+ return function toast(text, { kind = "info", ms = 7e3, onClick, onDismiss, name, order = 0, details, meta, bar } = {}) {
484
584
  const el = document.createElement("button");
485
585
  let timer;
486
586
  const close = () => {
@@ -496,6 +596,27 @@ function createToast(corner) {
496
596
  label.className = "wp-toast-text";
497
597
  label.textContent = text;
498
598
  el.append(label);
599
+ let metaEl = null;
600
+ let barEl = null;
601
+ const setMeta = (text) => {
602
+ if (!text) return void metaEl?.remove();
603
+ metaEl ??= Object.assign(document.createElement("span"), { className: "wp-toast-meta" });
604
+ metaEl.textContent = text;
605
+ if (!metaEl.isConnected) label.after(metaEl);
606
+ };
607
+ const setBar = (to) => {
608
+ if (!to) return void barEl?.remove();
609
+ if (!barEl) {
610
+ barEl = Object.assign(document.createElement("span"), { className: "wp-toast-bar" });
611
+ barEl.append(document.createElement("span"));
612
+ }
613
+ barEl.dataset.tone = to.tone ?? "accent";
614
+ barEl.toggleAttribute("data-indeterminate", to.value == null);
615
+ barEl.style.setProperty("--wp-toast-bar", to.value == null ? "" : `${Math.max(0, Math.min(1, to.value)) * 100}%`);
616
+ if (!barEl.isConnected) el.append(barEl);
617
+ };
618
+ setMeta(meta);
619
+ setBar(bar);
499
620
  let more = null;
500
621
  let detail = null;
501
622
  if (details) {
@@ -538,8 +659,10 @@ function createToast(corner) {
538
659
  place(corner()).append(el);
539
660
  return {
540
661
  close,
541
- update: (next) => {
662
+ update: (next, more) => {
542
663
  label.textContent = next;
664
+ if (more && "meta" in more) setMeta(more.meta);
665
+ if (more && "bar" in more) setBar(more.bar);
543
666
  },
544
667
  hide: () => {
545
668
  el.hidden = true;
@@ -552,12 +675,12 @@ function createToast(corner) {
552
675
  };
553
676
  }
554
677
  // src/client/read.ts
555
- let isMessage = () => false;
678
+ let messages$1 = /* @__PURE__ */ new Map();
556
679
  let getEvents = () => [];
557
680
  let send = () => {};
558
681
  let chats = () => null;
559
682
  const sending$1 = /* @__PURE__ */ new Set();
560
- const unread$1 = () => unreadMessages(getEvents(), isMessage, chats()).filter((e) => !sending$1.has(e.id));
683
+ const unread$1 = () => unreadMessages(getEvents(), messages$1, chats()).filter((e) => !sending$1.has(e.id));
561
684
  /**
562
685
  * The chats the page's content shows, by name: the one under every form and each chat block; null
563
686
  * while there is no page content (a folder, raw text), when every chat's messages count.
@@ -617,8 +740,7 @@ function observeMessages() {
617
740
  }
618
741
  }
619
742
  function trackReading(options) {
620
- const types = new Set(options.messages);
621
- isMessage = (type) => types.has(type);
743
+ messages$1 = new Map(Object.entries(options.messages));
622
744
  getEvents = options.events;
623
745
  send = options.send;
624
746
  chats = chatsShown;
@@ -1006,7 +1128,8 @@ const api = {
1006
1128
  writeTitle();
1007
1129
  },
1008
1130
  toast: createToast(cornerOfPage),
1009
- ...formsApi
1131
+ ...formsApi,
1132
+ delivery: trackDelivery(eventsValue, listenersValue, new Set(handoff.handedOut ?? []))
1010
1133
  };
1011
1134
  const changeListeners = /* @__PURE__ */ new Set();
1012
1135
  async function getJson(url) {
@@ -1146,7 +1269,7 @@ if (handoff.client) try {
1146
1269
  if (live) {
1147
1270
  trackForms(root, page, api);
1148
1271
  trackReading({
1149
- messages: handoff.messages ?? [],
1272
+ messages: handoff.messages ?? {},
1150
1273
  events: () => events,
1151
1274
  send: (ids) => {
1152
1275
  append(READ, { ids }).catch((err) => console.error("marking read:", err));
@@ -19,7 +19,7 @@ its answers are events of that type, and a link to it is
19
19
  chat. A form on the page can't have a `/` in its name.
20
20
 
21
21
  To rework a message (an option more, a typo), edit it in place:
22
- `workpad edit <its id> --data '{"text":"…"}'`. It updates in the reader's
22
+ `workpad edit <its id> --text-file -` with the new text on standard input. It updates in the reader's
23
23
  tab, marked new until they've seen it, and a form in it that keeps its name
24
24
  keeps its answers.
25
25
 
@@ -41,10 +41,14 @@ message `#message:<its event id>`; a folded form's chat opens for it.
41
41
 
42
42
  A message is a `chat:message` event, `{ "chat": "<name>", "text": "…" }`,
43
43
  never an answer: under a form it never makes a choice (only the reader can,
44
- with a message of yours marked `answer`, below). Answer in the same chat:
44
+ with a message of yours marked `answer`, below). Answer in the same chat, the
45
+ text from standard input (a quoted heredoc: no shell quoting in the markdown)
46
+ or a file (`--text-file reply.md`):
45
47
 
46
48
  ```sh
47
- workpad append --page <file> --type chat:message --data '{"chat":"<name>","text":"your answer"}'
49
+ workpad append --page <file> --type chat:message --data '{"chat":"<name>"}' --text-file - <<'EOF'
50
+ your answer, in markdown
51
+ EOF
48
52
  ```
49
53
 
50
54
  Two more fields, both optional:
@@ -68,6 +68,7 @@ function chatPlugin({ page: pageChat = true } = {}) {
68
68
  events: { "chat:message": {
69
69
  handOut: true,
70
70
  forReader: true,
71
+ requires: ["chat", "text"],
71
72
  description: "a message in a chat: `{ chat, text }`, and `replaces` or `replyTo` (see below)"
72
73
  } },
73
74
  commands: { prune: {