@bigmistqke/workpad 0.19.0 → 0.20.1

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 (89) hide show
  1. package/README.md +29 -16
  2. package/bin/workpad.ts +193 -37
  3. package/dist/bin/workpad.js +161 -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/claude/doctor.js +15 -5
  11. package/dist/plugins/comments/README.md +2 -1
  12. package/dist/plugins/comments/index.js +2 -0
  13. package/dist/plugins/comments/public/client.js +6 -5
  14. package/dist/plugins/comments/public/style.css +9 -0
  15. package/dist/plugins/form/README.md +1 -1
  16. package/dist/plugins/index.js +3 -1
  17. package/dist/plugins/opencode/channel.js +1 -0
  18. package/dist/plugins/progress/README.md +41 -0
  19. package/dist/plugins/progress/index.js +117 -0
  20. package/dist/plugins/progress/public/client.js +1 -0
  21. package/dist/plugins/progress/public/style.css +85 -0
  22. package/dist/plugins/progress/state.js +210 -0
  23. package/dist/solid/index.js +3 -1
  24. package/dist/src/agents.js +7 -3
  25. package/dist/src/anchors.js +25 -1
  26. package/dist/src/build.js +1 -1
  27. package/dist/src/client/page/base.css +48 -2
  28. package/dist/src/client/page/main.js +58 -30
  29. package/dist/src/document.js +6 -4
  30. package/dist/src/entries.js +6 -2
  31. package/dist/src/events.js +19 -9
  32. package/dist/src/files.js +26 -3
  33. package/dist/src/help.js +43 -8
  34. package/dist/src/hub.js +20 -4
  35. package/dist/src/loader.js +11 -6
  36. package/dist/src/migrate.js +1 -1
  37. package/dist/src/pages/board.js +1 -1
  38. package/dist/src/pages/markdown.js +3 -3
  39. package/dist/src/pages/render.js +16 -0
  40. package/dist/src/server.js +70 -32
  41. package/dist/src/set.js +99 -0
  42. package/dist/src/status.js +47 -8
  43. package/package.json +6 -1
  44. package/plugins/README.md +3 -1
  45. package/plugins/chat/README.md +7 -3
  46. package/plugins/chat/client.tsx +20 -3
  47. package/plugins/chat/index.ts +1 -0
  48. package/plugins/chat/public/style.css +10 -0
  49. package/plugins/claude/channel.ts +19 -5
  50. package/plugins/claude/doctor.ts +11 -3
  51. package/plugins/comments/README.md +2 -1
  52. package/plugins/comments/client.ts +19 -0
  53. package/plugins/comments/index.ts +7 -1
  54. package/plugins/comments/public/style.css +9 -0
  55. package/plugins/form/README.md +1 -1
  56. package/plugins/index.ts +2 -0
  57. package/plugins/opencode/channel.ts +2 -1
  58. package/plugins/progress/README.md +41 -0
  59. package/plugins/progress/client.ts +172 -0
  60. package/plugins/progress/index.ts +166 -0
  61. package/plugins/progress/public/style.css +85 -0
  62. package/plugins/progress/state.ts +278 -0
  63. package/skills/workpad/SKILL.md +126 -15
  64. package/solid/index.tsx +6 -2
  65. package/src/agents.ts +17 -2
  66. package/src/anchors.ts +32 -0
  67. package/src/build.ts +1 -1
  68. package/src/client/delivery.ts +49 -0
  69. package/src/client/forms.ts +18 -11
  70. package/src/client/page/base.css +48 -2
  71. package/src/client/page/waiting.ts +45 -25
  72. package/src/client/read.ts +9 -5
  73. package/src/client/runtime.ts +7 -3
  74. package/src/client/toast.ts +27 -3
  75. package/src/define.ts +92 -8
  76. package/src/document.ts +19 -5
  77. package/src/entries.ts +18 -7
  78. package/src/events.ts +26 -6
  79. package/src/files.ts +28 -2
  80. package/src/help.ts +42 -7
  81. package/src/hub.ts +25 -8
  82. package/src/loader.ts +20 -10
  83. package/src/migrate.ts +1 -1
  84. package/src/pages/board.ts +3 -1
  85. package/src/pages/markdown.ts +4 -4
  86. package/src/pages/render.ts +19 -1
  87. package/src/server.ts +114 -42
  88. package/src/set.ts +118 -0
  89. 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) {
@@ -135,6 +140,11 @@ async function ensureServer() {
135
140
  if (server && compareVersions(VERSION, server.version) > 0) console.error(`workpad: the shared server runs ${server.version}, this is ${VERSION}; restart it to upgrade (\`workpad serve\` takes it over)`);
136
141
  return base;
137
142
  }
143
+ const mine = server?.projects.find((p) => p.dir === proj.dir);
144
+ if (server && mine) {
145
+ console.error(`workpad: the shared server at ${server.origin} was slow to answer; it serves this project`);
146
+ return `${server.origin}${mine.base}`;
147
+ }
138
148
  const at = recordedOrigin(machineServerFile());
139
149
  if (!server && at && await stuckAt(at)) throw new Error(stuck(at, "its login service log"));
140
150
  throw new Error(server ? `the shared server at ${server.origin} does not serve ${proj.dir}; is it in an include of ${machineDir()}/config.json?` : `the shared server is not running. It is started outside the agents' sandboxes: as a login service, or with \`workpad serve\` in a terminal, outside any project`);
@@ -221,6 +231,41 @@ function pageIn(target) {
221
231
  id: pageId(proj, target)
222
232
  };
223
233
  }
234
+ /** The file a page or repository file of the project is: `README.md`, `plan`, `.workpad/pages/plan.md`. */
235
+ function fileOf(proj, target) {
236
+ const id = pageId(proj, target);
237
+ if (!id) throw new Error(`no page ${target}`);
238
+ return id === "-" || id.startsWith("-/") ? path.join(proj.dir, id.slice(2)) : path.join(proj.pagesDir, `${id}.md`);
239
+ }
240
+ /**
241
+ * What a file holds, or with `-` what comes on standard input: for markdown and JSON an agent writes,
242
+ * which never passes through the shell's quoting that way (a heredoc with a quoted delimiter, or a file).
243
+ */
244
+ function readInput(from, option) {
245
+ if (from === "-") return fs.readFileSync(0, "utf8");
246
+ if (!fs.existsSync(from)) throw new Error(`${option} ${from}: no such file`);
247
+ return fs.readFileSync(from, "utf8");
248
+ }
249
+ /**
250
+ * An event's data as the command line gives it: JSON from --data or --file (a file, or - for standard
251
+ * input), with --text-file's contents (a file, or -) as its `text`. Nothing given: undefined.
252
+ */
253
+ function eventData() {
254
+ if (opts.data !== void 0 && opts.file !== void 0) throw new Error("give the data with --data or --file, not both");
255
+ const json = opts.file !== void 0 ? readInput(opts.file, "--file") : opts.data;
256
+ let data;
257
+ if (json !== void 0) try {
258
+ data = JSON.parse(json);
259
+ } catch {
260
+ throw new Error(`${opts.file !== void 0 ? `--file ${opts.file}` : "--data"} must be JSON, e.g. {"text":"…"}; for markdown, --text-file <file|->`);
261
+ }
262
+ if (opts["text-file"] === void 0) return data;
263
+ 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\"");
264
+ return {
265
+ ...data,
266
+ text: readInput(opts["text-file"], "--text-file").replace(/\s+$/, "")
267
+ };
268
+ }
224
269
  /** Where a project is served: its running server, or an error saying how to start one. */
225
270
  async function serverOf(proj) {
226
271
  if (proj.dir === project?.dir) return needServer();
@@ -405,6 +450,20 @@ async function whoAmI(proj) {
405
450
  return opts.agent || process.env.WORKPAD_AGENT || await currentSession(proj);
406
451
  }
407
452
  /**
453
+ * Who runs this command, and the other id it goes by: the agent session a plugin names, when
454
+ * `--agent` or `WORKPAD_AGENT` named it otherwise. What it writes records both (appendEvent), and a
455
+ * listen leaves out what either wrote: a channel that knows the agent by its session, and the
456
+ * agent's commands that name it, are the same agent.
457
+ */
458
+ async function whoAmIWithSession(proj) {
459
+ const session = await currentSession(proj);
460
+ const me = opts.agent || process.env.WORKPAD_AGENT || session;
461
+ return {
462
+ me,
463
+ session: session !== me ? session : null
464
+ };
465
+ }
466
+ /**
408
467
  * The agent session this command runs in, as the project's plugins know it (Claude Code's
409
468
  * plugin reads it from the environment): the first one that names one. Null without any.
410
469
  */
@@ -429,16 +488,20 @@ async function pageStatus(proj, target) {
429
488
  async function status() {
430
489
  const proj = needProject();
431
490
  const [pages, me] = await Promise.all([api(`/api/status${pageOpt ? `?page=${encodeURIComponent(pageId(proj, pageOpt))}` : ""}`), whoAmI(proj)]);
432
- const names = namesOf(readEvents(proj.eventsFile));
491
+ const events = readEvents(proj.eventsFile);
492
+ const names = namesOf(events);
433
493
  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
- }
494
+ const now = Date.now();
495
+ const runs = running$1(events).filter((r) => pages.some((p) => p.page === r.page));
496
+ if (!busy.length) console.log("nothing open: every question is answered, and every answer received");
438
497
  for (const p of busy) {
439
498
  console.log(`${p.page} (${whose(p, me, names)})`);
440
499
  for (const l of statusLines(p, relFile(p.file))) console.log(` ${l}`);
441
500
  }
501
+ if (runs.length) {
502
+ console.log("running:");
503
+ for (const r of runs) console.log(` ${r.page}: ${line(r, now)}${r.by ? ` (${r.by === me ? "you" : names.get(r.by) ?? r.by})` : ""}`);
504
+ }
442
505
  }
443
506
  switch (cmd) {
444
507
  case "serve": {
@@ -664,6 +727,48 @@ switch (cmd) {
664
727
  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
728
  const ids = positionals.length ? positionals.map((p) => pageIn(p).id) : all(proj.pagesDir).sort();
666
729
  const text = (s) => s.replace(/<[^>]+>/g, "").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, "\"").replace(/&#39;/g, "'").replace(/&amp;/g, "&").trim();
730
+ const anchorsOfPage = /* @__PURE__ */ new Map();
731
+ const anchorsFor = (page) => {
732
+ if (!anchorsOfPage.has(page)) anchorsOfPage.set(page, anchorsAt(base, page).then((as) => as.map((a) => a.id), () => null));
733
+ return anchorsOfPage.get(page);
734
+ };
735
+ const served = new URL(base);
736
+ const root = served.pathname.replace(/\/$/, "");
737
+ /**
738
+ * The links of a rendered page to a place on another page of this project (`decisions.md#form:x`,
739
+ * or its own page by its file) whose anchor that page doesn't have. A link to `#…` alone is the
740
+ * render's own notice; one to another project, server or site isn't checked.
741
+ */
742
+ const brokenLinks = async (id, body) => {
743
+ const out = [];
744
+ for (const m of body.matchAll(/<a\b[^>]*?\shref="([^"]*)"/g)) {
745
+ const href = text(m[1]);
746
+ if (!href || href.startsWith("#")) continue;
747
+ let url;
748
+ try {
749
+ url = new URL(href, `${base}/${id.split("/").map(encodeURIComponent).join("/")}`);
750
+ } catch {
751
+ continue;
752
+ }
753
+ if (url.origin !== served.origin || !url.pathname.startsWith(`${root}/`) || url.hash.length < 2) continue;
754
+ let page;
755
+ let anchor;
756
+ try {
757
+ page = decodeURIComponent(url.pathname.slice(root.length + 1)).replace(/\/$/, "");
758
+ anchor = decodeURIComponent(url.hash.slice(1));
759
+ } catch {
760
+ continue;
761
+ }
762
+ if (anchor.startsWith("message:")) continue;
763
+ const repo = page === "-" || page.startsWith("-/");
764
+ if (repo ? !/\.(md|markdown)$/i.test(page) : path.extname(page) && !/\.md$/i.test(page)) continue;
765
+ if (!repo) page = page.replace(/\.md$/i, "");
766
+ const has = await anchorsFor(page);
767
+ if (!has) out.push(`a link to \`${page}${hashOf(anchor)}\`: there is no page ${page}`);
768
+ else if (!has.includes(anchor)) out.push(`a link to \`${page}${hashOf(anchor)}\`, which ${page} doesn't have${nearest(anchor, has)}`);
769
+ }
770
+ return out;
771
+ };
667
772
  let found = 0;
668
773
  const config = /* @__PURE__ */ new Set();
669
774
  for (const id of ids) {
@@ -674,9 +779,14 @@ switch (cmd) {
674
779
  continue;
675
780
  }
676
781
  const { html: body = "", notices = [] } = await res.json();
782
+ anchorsOfPage.set(id, Promise.resolve(anchorsOf(body).map((a) => a.id)));
677
783
  const errors = [...body.matchAll(/<(\w+) class="wp-error"[^>]*>([\s\S]*?)<\/\1>/g)].map((m) => text(m[2]));
678
784
  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])];
785
+ const problems = [.../* @__PURE__ */ new Set([
786
+ ...notices.filter((n) => !n.startsWith("config: ")),
787
+ ...errors,
788
+ ...await brokenLinks(id, body)
789
+ ])];
680
790
  if (!problems.length) continue;
681
791
  found += problems.length;
682
792
  console.log(`${id}\n${problems.map((p) => ` ${p.replace(/\n/g, "\n ")}`).join("\n")}`);
@@ -732,6 +842,17 @@ switch (cmd) {
732
842
  for (const a of anchors) console.log(`${hashOf(a.id)} ${a.kind}${a.label !== a.id.slice(a.kind.length + 1) ? ` ${a.label}` : ""}`);
733
843
  break;
734
844
  }
845
+ case "set": {
846
+ const [target, name] = positionals;
847
+ if (!target || !name || opts.file === void 0) throw new Error("usage: workpad set <page|file> <anchor|form> --file <file|->");
848
+ const file = fileOf(needProject(), target);
849
+ if (!fs.existsSync(file)) throw new Error(`no page ${target} (${relFile(file)})`);
850
+ const source = fs.readFileSync(file, "utf8");
851
+ const block = findBlock(source, name);
852
+ fs.writeFileSync(file, setBlock(source, name, readInput(opts.file, "--file")));
853
+ console.log(`replaced ${hashOf(block.id)} (${block.kind === "heading" ? "its section" : block.kind}) in ${relFile(file)}`);
854
+ break;
855
+ }
735
856
  case "archive":
736
857
  case "destroy": {
737
858
  const target = positionals[0];
@@ -782,15 +903,10 @@ switch (cmd) {
782
903
  }
783
904
  case "edit": {
784
905
  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)");
906
+ const data = eventData();
907
+ 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
908
  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");
909
+ if (!data || typeof data !== "object" || Array.isArray(data)) throw new Error("the data must be a JSON object");
794
910
  console.log(JSON.stringify(editEvent(proj.eventsFile, eventId, data)));
795
911
  break;
796
912
  }
@@ -898,9 +1014,19 @@ switch (cmd) {
898
1014
  const named = positionals.slice(1);
899
1015
  if (named.length && opts.all) throw new Error("settle takes forms or --all, not both");
900
1016
  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"}`);
1017
+ let replaced = null;
1018
+ if (opts["replace-with"] !== void 0) {
1019
+ if (opts.all || named.length !== 1) throw new Error("--replace-with replaces one form: name it, without --all");
1020
+ const source = fs.readFileSync(p.file, "utf8");
1021
+ replaced = setBlock(source, `form:${named[0]}`, readInput(opts["replace-with"], "--replace-with"));
1022
+ }
901
1023
  const { forms, skipped } = settleForms(proj.eventsFile, p, opts.all ? "all" : named, await whoAmI(proj));
902
1024
  for (const { name, state } of skipped) console.error(`workpad: ${name} isn't open (${state}): left as it is`);
903
1025
  console.log(forms.length ? `settled on ${p.page}: ${forms.join(", ")}` : `nothing to settle on ${p.page}`);
1026
+ if (replaced !== null) {
1027
+ fs.writeFileSync(p.file, replaced);
1028
+ console.log(`replaced the form ${named[0]} on ${p.page}`);
1029
+ }
904
1030
  break;
905
1031
  }
906
1032
  case "hold": {
@@ -940,7 +1066,8 @@ switch (cmd) {
940
1066
  case "listen": {
941
1067
  const proj = needProject();
942
1068
  const f = filter();
943
- const agent = await whoAmI(proj);
1069
+ const { me: agent, session } = await whoAmIWithSession(proj);
1070
+ const aliases = new Set(session ? [session] : []);
944
1071
  if (opts.follow) throw new Error("listen runs on by itself: --wait stops at the first answer, --channel hands over to the channel");
945
1072
  if (opts.wait && opts.channel) throw new Error("listen takes --wait or --channel, not both");
946
1073
  if (opts.timeout && !opts.wait) throw new Error("--timeout goes with --wait");
@@ -956,7 +1083,7 @@ switch (cmd) {
956
1083
  }
957
1084
  const entry = !f.page && isShared(proj) ? matchesEntries(readMachineConfig(), proj.dir) : null;
958
1085
  if (entry) {
959
- await entryListen(entry, f, agent);
1086
+ await entryListen(entry, f, agent, aliases);
960
1087
  break;
961
1088
  }
962
1089
  const isForAgent = await liveForAgent(proj);
@@ -975,7 +1102,8 @@ switch (cmd) {
975
1102
  const options = {
976
1103
  batch: !!opts.wait,
977
1104
  forAgent: isForAgent,
978
- agent
1105
+ agent,
1106
+ aliases
979
1107
  };
980
1108
  if (opts.timeout && opts.wait) setTimeout(() => {
981
1109
  console.error("timeout");
@@ -1006,18 +1134,16 @@ switch (cmd) {
1006
1134
  }
1007
1135
  case "append": {
1008
1136
  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
- }
1137
+ if (!pageOpt || !opts.type) throw new Error("usage: workpad append --page <page|file> --type <type> [--data '<json>' | --file <file|->] [--text-file <file|->]");
1138
+ const data = eventData() ?? {};
1139
+ const refused = refusal(opts.type, data, (await projectConfig(proj)).requires);
1140
+ 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 -`);
1141
+ const { me, session } = await whoAmIWithSession(proj);
1016
1142
  console.log(JSON.stringify(appendEvent(proj.eventsFile, {
1017
1143
  page: pageId(proj, pageOpt),
1018
1144
  type: opts.type,
1019
1145
  data
1020
- }, "cli", await whoAmI(proj))));
1146
+ }, "cli", me, session)));
1021
1147
  break;
1022
1148
  }
1023
1149
  case "status":
@@ -1112,6 +1238,7 @@ switch (cmd) {
1112
1238
  };
1113
1239
  },
1114
1240
  version: VERSION,
1241
+ agent: me,
1115
1242
  wp: client(async () => probe(await ensureServer()), {
1116
1243
  token: projectToken(project.wp),
1117
1244
  agent: me
@@ -1126,12 +1253,13 @@ switch (cmd) {
1126
1253
  ...options,
1127
1254
  forAgent: await liveForAgent(project, options?.signal)
1128
1255
  }),
1129
- listen: (page, { agent = null } = {}) => listen({
1256
+ listen: (page, { agent = null, signal } = {}) => listen({
1130
1257
  at: () => ensureServer().catch(() => null),
1131
1258
  query: {
1132
1259
  page: pageId(project, page),
1133
1260
  ...agent ? { agent } : {}
1134
- }
1261
+ },
1262
+ signal
1135
1263
  }),
1136
1264
  unfollowed: (onEvent, { agent = null, mark, signal } = {}) => holdUnfollowed(project, {
1137
1265
  at: () => ensureServer().catch(() => null),
@@ -1174,7 +1302,7 @@ async function channelListen(proj, who) {
1174
1302
  const handled = handledIds(events);
1175
1303
  const received = receivedIds(events);
1176
1304
  const skipped = events.filter((e) => {
1177
- if (fromReader(e) || !e.by || e.by === agent || !isForAgent(e.type) || handled.has(e.id)) return false;
1305
+ if (fromReader(e) || !e.by || e.by === agent || e.session === agent || !isForAgent(e.type) || handled.has(e.id)) return false;
1178
1306
  if (!received.has(e.id)) return false;
1179
1307
  const since = channelSince(events, agent, e.page);
1180
1308
  if (!since) return false;
@@ -1317,7 +1445,7 @@ async function channelUnfollowed(proj, agent) {
1317
1445
  * Without a shared server running it waits for one, as any listen does. Projects that appear
1318
1446
  * meanwhile are followed too.
1319
1447
  */
1320
- async function entryListen(entry, f, agent) {
1448
+ async function entryListen(entry, f, agent, aliases) {
1321
1449
  const file = machineServerFile();
1322
1450
  const count = opts.wait ? 1 : Infinity;
1323
1451
  const done = new AbortController();
@@ -1342,6 +1470,7 @@ async function entryListen(entry, f, agent) {
1342
1470
  }, {
1343
1471
  forAgent: forAgent(handedOut),
1344
1472
  agent,
1473
+ aliases,
1345
1474
  signal: AbortSignal.any([signal, done.signal])
1346
1475
  }));
1347
1476
  });
@@ -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: {