@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
@@ -1,5 +1,5 @@
1
1
  import { html, raw } from "../html.js";
2
- import { anchorsOf, slugText } from "../anchors.js";
2
+ import { anchorsOf, nearest, slugText } from "../anchors.js";
3
3
  import { agentMessagesIn, isQuestionName } from "../status.js";
4
4
  import path from "node:path";
5
5
  import crypto from "node:crypto";
@@ -295,13 +295,8 @@ function titleWords(nodes, resolve) {
295
295
  };
296
296
  return nodes.map(words).join("").replace(/\s*\u0000[\s\u0000]*/g, " ").trim();
297
297
  }
298
- /**
299
- * The forms a page asks the reader to answer, by name: `:::form{name=…}` containers and
300
- * hand-written <form name="…"> without an action. Parsed, so a form shown as an example inside a
301
- * code block doesn't count.
302
- */
303
- function formNames(source) {
304
- const tree = parseMarkdown(String(source ?? ""));
298
+ /** formNames of a source parsed already. */
299
+ function formNamesIn(tree) {
305
300
  const names = [];
306
301
  const walk = (node) => {
307
302
  if (node.type === "containerDirective" && node.name === "form") {
@@ -319,10 +314,10 @@ function formNames(source) {
319
314
  }
320
315
  /**
321
316
  * The `:::form`s in a source by the name they are written with, null for one without; in order, and
322
- * not those shown in a code fence. For a message's forms, which are named in their chat.
317
+ * not those shown in a code fence. For a message's forms, which are named in their chat. Kept: a
318
+ * status asks it of every agent message in every chat, and a message's text never changes.
323
319
  */
324
- function formsIn(source) {
325
- const text = String(source ?? "");
320
+ const formsIn = byText(5e3, (text) => {
326
321
  const out = [];
327
322
  const walk = (node) => {
328
323
  if (node.type === "containerDirective" && node.name === "form") {
@@ -337,7 +332,7 @@ function formsIn(source) {
337
332
  };
338
333
  walk(parseMarkdown(text));
339
334
  return out;
340
- }
335
+ });
341
336
  /** The text of nodes without the inline blocks in them (a form's inputs). */
342
337
  const plainText = (nodes) => nodes.map((n) => n.type === "textDirective" || n.type === "leafDirective" ? " " : n.children ? plainText(n.children) : n.value ?? "").join("").replace(/\s+/g, " ").trim();
343
338
  /** What one `:::form` node asks (FormDetail). */
@@ -375,15 +370,47 @@ function describeForm(node) {
375
370
  }
376
371
  /** What each `:::form` in a source asks, in order (not those shown in a code fence). */
377
372
  function formDetails(source) {
373
+ return formDetailsIn(parseMarkdown(String(source ?? "")));
374
+ }
375
+ /** formDetails of a source parsed already. */
376
+ function formDetailsIn(tree) {
378
377
  const out = [];
379
378
  const walk = (node) => {
380
379
  if (node.type === "containerDirective" && node.name === "form") out.push(describeForm(node));
381
380
  for (const child of node.children ?? []) walk(child);
382
381
  };
383
- walk(parseMarkdown(String(source ?? "")));
382
+ walk(tree);
384
383
  return out;
385
384
  }
386
385
  /**
386
+ * A page's questions, chats and forms, from one parse of its source. The same source is asked again
387
+ * after the config reloads, which a change to a plugin does: its answer is kept.
388
+ */
389
+ const pageAsks = byText(1e3, (source) => {
390
+ const tree = parseMarkdown(source);
391
+ return {
392
+ questions: formNamesIn(tree),
393
+ chats: chatNamesIn(tree),
394
+ forms: formDetailsIn(tree)
395
+ };
396
+ });
397
+ /**
398
+ * `fn` with its answers kept by the text it was asked about, the oldest dropped past `limit`: for
399
+ * what is read from a parse, asked again and again of the same pages and messages. What it answers
400
+ * is shared, never to be changed.
401
+ */
402
+ function byText(limit, fn) {
403
+ const kept = /* @__PURE__ */ new Map();
404
+ return (source) => {
405
+ const text = String(source ?? "");
406
+ if (kept.has(text)) return kept.get(text);
407
+ const value = fn(text);
408
+ if (kept.size >= limit) kept.delete(kept.keys().next().value);
409
+ kept.set(text, value);
410
+ return value;
411
+ };
412
+ }
413
+ /**
387
414
  * The forms in the agent's messages in `chats` (a page's chats, chatNames), by their names there:
388
415
  * `<chat>/<name>`, an unnamed one numbered in its chat (Api.message). They are questions of the
389
416
  * page as much as its own forms are.
@@ -414,8 +441,11 @@ function chatForms(events, page, chat) {
414
441
  * on the page.
415
442
  */
416
443
  function chatNames(source) {
417
- const tree = parseMarkdown(String(source ?? ""));
418
- const names = formNames(source);
444
+ return chatNamesIn(parseMarkdown(String(source ?? "")));
445
+ }
446
+ /** chatNames of a source parsed already. */
447
+ function chatNamesIn(tree) {
448
+ const names = formNamesIn(tree);
419
449
  const without = /* @__PURE__ */ new Set();
420
450
  const walk = (node) => {
421
451
  if (node.type === "containerDirective" && node.name === "form" && node.attributes?.chat === "false") without.add(node.attributes.name ?? "");
@@ -715,7 +745,8 @@ plugin "${name}" failed to compose around block "${block.name}": ${err.message}<
715
745
  inline,
716
746
  fileUrl,
717
747
  anchor,
718
- chat: inChat
748
+ chat: inChat,
749
+ problem
719
750
  };
720
751
  /**
721
752
  * Attributes a block doesn't read (Block.attrs), when it says which it does: a typo, or one from
@@ -843,13 +874,13 @@ plugin "${name}" failed to compose around block "${block.name}": ${err.message}<
843
874
  await transform(tree);
844
875
  const out = stringify(tree.children ?? []);
845
876
  if (links.length) {
846
- const ids = new Set(anchorsOf(String(out)).map((a) => a.id));
877
+ const ids = anchorsOf(String(out)).map((a) => a.id);
847
878
  for (const url of links) {
848
879
  let id = url.slice(1);
849
880
  try {
850
881
  id = decodeURIComponent(id);
851
882
  } catch {}
852
- if (id && !id.startsWith("message:") && !ids.has(id)) problem(`a link to \`${url}\`, which this page doesn't have: \`workpad anchors\` lists what it has`);
883
+ if (id && !id.startsWith("message:") && !ids.includes(id)) problem(`a link to \`${url}\`, which this page doesn't have${nearest(id, ids)}`);
853
884
  }
854
885
  }
855
886
  return {
@@ -860,4 +891,4 @@ plugin "${name}" failed to compose around block "${block.name}": ${err.message}<
860
891
  problems
861
892
  };
862
893
  }
863
- export { chatForms, chatNames, formDetails, formNames, formSource, formsIn, messageForms, parseAttrs, parseMarkdown, renderMarkdown, slug, titleWords };
894
+ export { chatForms, chatNames, formDetails, formSource, formsIn, messageForms, pageAsks, parseAttrs, parseMarkdown, renderMarkdown, slug, titleWords };
@@ -356,13 +356,29 @@ function counts(w, href) {
356
356
  >${badge("open", w.open, "open", w.open === 1 ? "1 question waiting for you" : `${w.open} questions waiting for you`)}${badge("unread", w.unread, "unread", w.unread === 1 ? "1 message you haven’t read" : `${w.unread} messages you haven’t read`)}${badge("unreceived", w.unreceived, "not received", w.unreceived === 1 ? "1 answer no agent received" : `${w.unreceived} answers no agent received`)}</span
357
357
  >`;
358
358
  }
359
+ /** A page's running progress on its card: a small bar (or a dot, without a count), its id, count and note. */
360
+ function progressLine(p) {
361
+ const count = p.n != null && p.total != null ? `${p.n.toLocaleString("en-US")} / ${p.total.toLocaleString("en-US")}` : "";
362
+ const width = p.n != null && p.total ? `${Math.round(p.n / p.total * 1e3) / 10}%` : null;
363
+ return html`<span
364
+ class="wp-board-progress"
365
+ ${p.stale ? html` data-stale` : ""}
366
+ title="${p.id}: running${p.stale ? ", no update for a while" : ""}"
367
+ >${width != null ? html`<span class="wp-board-progress-bar"><span style="width:${width}"></span></span>` : html`<span class="wp-board-progress-dot"></span>`}<span class="wp-board-progress-text">${[
368
+ p.id,
369
+ count,
370
+ p.note
371
+ ].filter(Boolean).join(" · ")}</span></span
372
+ >`;
373
+ }
359
374
  /** A page on the board: its title, what waits on it, and (in a column of states) its project. */
360
375
  function card(c, withProject) {
361
376
  return html`<li class="wp-board-card${total(c.waiting) > 0 ? " wp-board-waits" : ""}">
362
377
  <a class="wp-board-title" href="${c.page.url}">${c.page.title}</a>
363
378
  ${counts(c.waiting, `${c.page.url}#wp-waiting`)}
364
379
  ${withProject && html`<span class="wp-board-project">${c.project.label}</span>`}
365
- <span class="wp-meta wp-board-when">edited ${time(c.page.mtime)}</span>
380
+ ${c.page.progress && progressLine(c.page.progress)}
381
+ <span class="wp-meta wp-board-when">updated ${time(c.page.updated)}</span>
366
382
  </li>`;
367
383
  }
368
384
  function cards(list, withProject) {
@@ -8,11 +8,11 @@ import { describeRoutes, dispatch, mountRoutes, pluginCommands, usage } from "./
8
8
  import { createAuth, sameSite } from "./auth.js";
9
9
  import { accept, refuse } from "./ws.js";
10
10
  import { FROM_SOURCE, PACKAGE_DIR, VERSION } from "./package.js";
11
- import { SCROLL, SUBSCRIBE, agentMessagesIn, awaiting, handledIds, isAgentMessage, namesOf, projectStatus, receivedIds, subscriptions } from "./status.js";
11
+ import { SCROLL, SUBSCRIBE, agentLabel, agentMessagesIn, awaiting, handledIds, isAgentMessage, namesOf, projectStatus, receivers, refusal, subscriptions } from "./status.js";
12
12
  import { formsIn, messageForms } from "./pages/markdown.js";
13
13
  import { fileFilter } from "./files.js";
14
14
  import { titleOf } from "./pages/render.js";
15
- import { createRegistry, holdStream, listenerOf } from "./listeners.js";
15
+ import { createRegistry, follows, holdStream, listenerOf } from "./listeners.js";
16
16
  import { inPublic } from "./public.js";
17
17
  import { build } from "./build.js";
18
18
  import { PAGE_CLIENT, RUNTIME, frontmatterOf, pageDocument, pluginParts } from "./document.js";
@@ -45,6 +45,8 @@ const MIME = {
45
45
  ".csv": "text/csv; charset=utf-8",
46
46
  ".html": "text/html; charset=utf-8"
47
47
  };
48
+ /** How many of the browser's latest events the server knows by id, to answer a retried send with the first. */
49
+ const APPENDED_KEPT = 1e3;
48
50
  const OWN_FILES = /* @__PURE__ */ new Set([
49
51
  "events.ndjson",
50
52
  "server.json",
@@ -118,7 +120,8 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
118
120
  const notices = [...rendered.notices];
119
121
  const parts = await pluginParts(await pluginHooks(), req, {
120
122
  asset,
121
- messages: [...(await config()).forReader],
123
+ messages: Object.fromEntries((await config()).forReader),
124
+ handedOut: [...(await config()).handedOut],
122
125
  failed: (message) => {
123
126
  console.error(message);
124
127
  notices.push(message);
@@ -243,10 +246,8 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
243
246
  let chats;
244
247
  let details = [];
245
248
  try {
246
- const source = pageSource(id, file);
247
- asks = renderer?.questions(source) ?? [];
248
- chats = renderer?.chats(source);
249
- details = renderer?.forms(source) ?? [];
249
+ const said = renderer?.asks(pageSource(id, file));
250
+ if (said) ({questions: asks, chats, forms: details} = said);
250
251
  } catch (err) {
251
252
  console.error("questions:", err);
252
253
  }
@@ -267,15 +268,23 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
267
268
  async function snapshot(listed) {
268
269
  const { pages: renderer, handedOut, forReader } = await config();
269
270
  const events = readEvents(project.eventsFile);
271
+ const messages = /* @__PURE__ */ new Map();
272
+ for (const e of events) {
273
+ if (!isAgentMessage(e)) continue;
274
+ const own = messages.get(e.page);
275
+ if (own) own.push(e);
276
+ else messages.set(e.page, [e]);
277
+ }
270
278
  const pages = listed.map((p) => {
271
279
  const page = {
272
280
  id: p.id,
273
281
  file: p.file,
274
282
  ...questionsOf(renderer, p.id, p.file)
275
283
  };
284
+ const forms = messageForms(messages.get(p.id) ?? [], p.id, page.chats ?? []);
276
285
  return {
277
286
  ...page,
278
- asks: [...page.asks, ...messageForms(events, p.id, page.chats ?? [])]
287
+ asks: [...page.asks, ...forms]
279
288
  };
280
289
  });
281
290
  return projectStatus({
@@ -283,7 +292,7 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
283
292
  events,
284
293
  listeners: listenersFor,
285
294
  forAgent: forAgent(handedOut),
286
- forReader: (type) => forReader.has(type)
295
+ forReader
287
296
  });
288
297
  }
289
298
  /** Per page, below `only` when given: what `workpad status` and the hooks report (see snapshot). */
@@ -537,9 +546,55 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
537
546
  /** the codes of pings sent and not confirmed yet: the channel each went to */
538
547
  const pings = /* @__PURE__ */ new Map();
539
548
  const pingCode = () => crypto.randomBytes(3).toString("hex");
549
+ const unfollowing = /* @__PURE__ */ new Set();
550
+ let looking = false;
551
+ function lookAgain() {
552
+ if (looking || !unfollowing.size) return;
553
+ looking = true;
554
+ setImmediate(() => {
555
+ looking = false;
556
+ const pages = pagesIn(project.pagesDir).map((p) => p.id).filter((id) => !registry.list(id).some((l) => follows(l, id)));
557
+ for (const u of unfollowing) {
558
+ for (const [page, release] of u.held) if (!pages.includes(page)) {
559
+ release();
560
+ u.held.delete(page);
561
+ }
562
+ for (const page of pages) if (!u.held.has(page)) u.held.set(page, registry.add({
563
+ ...u.listener,
564
+ page,
565
+ unfollowed: true
566
+ }));
567
+ const now = JSON.stringify(pages);
568
+ if (now !== u.told) {
569
+ u.told = now;
570
+ u.onPages(pages);
571
+ }
572
+ }
573
+ });
574
+ }
575
+ registry.onChange(lookAgain);
576
+ function unfollowed(listener, onPages) {
577
+ const u = {
578
+ listener,
579
+ onPages,
580
+ held: /* @__PURE__ */ new Map(),
581
+ told: null
582
+ };
583
+ unfollowing.add(u);
584
+ lookAgain();
585
+ return () => {
586
+ if (!unfollowing.delete(u)) return;
587
+ for (const release of u.held.values()) release();
588
+ u.held.clear();
589
+ };
590
+ }
540
591
  const clients = /* @__PURE__ */ new Set();
541
- /** what the browser appended lately, by id: a send it retries is answered with what it got */
542
- const appended = /* @__PURE__ */ new Map();
592
+ /**
593
+ * what the browser appended lately, by id: a send it retries is answered with what it got. From
594
+ * the log at the start, so a retry that comes after a restart (the first try got in, its answer
595
+ * didn't get out) is no second answer either.
596
+ */
597
+ const appended = new Map(readEvents(project.eventsFile).filter((e) => !e.from).slice(-1e3).map((e) => [e.id, e]));
543
598
  function notify(client, kind) {
544
599
  client.pending ??= /* @__PURE__ */ new Set();
545
600
  if (client.pending.size === 0) setTimeout(() => {
@@ -557,6 +612,7 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
557
612
  });
558
613
  function pageChanged(id) {
559
614
  onChange?.();
615
+ lookAgain();
560
616
  for (const c of clients) if (c.isDir ? !c.page || id.startsWith(c.page + "/") : c.page === id || c.page + "/index" === id) notify(c, "change");
561
617
  for (const c of clients) if (c.isDir && !c.page) notify(c, "change");
562
618
  }
@@ -798,9 +854,11 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
798
854
  if (!body.type) return sendJson(res, 400, { error: "event type required" });
799
855
  const again = isEventId(body.id) ? appended.get(body.id) : void 0;
800
856
  if (again) return sendJson(res, 200, again);
857
+ const refused = refusal(body.type, body.data, (await config()).requires);
858
+ if (refused) return sendJson(res, 400, { error: refused });
801
859
  const event = appendEvent(project.eventsFile, body);
802
860
  appended.set(event.id, event);
803
- if (appended.size > 1e3) appended.delete(appended.keys().next().value);
861
+ if (appended.size > APPENDED_KEPT) appended.delete(appended.keys().next().value);
804
862
  return sendJson(res, 200, event);
805
863
  }
806
864
  if (p === "/api/scroll" && req.method === "POST") {
@@ -914,21 +972,38 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
914
972
  }
915
973
  if (p === "/api/events") {
916
974
  const all = after(readEvents(project.eventsFile), q.since);
917
- const received = receivedIds(all);
975
+ const received = receivers(all);
918
976
  const handled = handledIds(all);
919
977
  return sendJson(res, 200, all.filter((e) => matches(e, {
920
978
  ...q,
921
979
  type: null
922
- }) && matchesQuery(e, q)).map((e) => ({
923
- ...e,
924
- ...received.has(e.id) && { received: true },
925
- ...handled.has(e.id) && { handled: true }
926
- })));
980
+ }) && matchesQuery(e, q)).map((e) => {
981
+ const by = received.get(e.id);
982
+ return {
983
+ ...e,
984
+ ...received.has(e.id) && { received: true },
985
+ ...by && { receivedBy: agentLabel(by, names) },
986
+ ...handled.has(e.id) && { handled: true }
987
+ };
988
+ }));
927
989
  }
928
990
  if (p === "/api/docs") return sendJson(res, 200, await docs());
929
991
  if (p === "/api/status") return sendJson(res, 200, await status(q.page || null));
930
992
  if (p === "/api/listeners") return sendJson(res, 200, listenersFor(q.page ?? null));
931
993
  if (p === "/api/stamps") return sendJson(res, 200, stamps());
994
+ if (p === "/api/listen" && url.searchParams.has("unfollowed")) {
995
+ const stop = unfollowed(listenerOf(url.searchParams), (pages) => stream.send("pages", { projects: pages.length ? [{
996
+ dir: project.dir,
997
+ base,
998
+ pages
999
+ }] : [] }));
1000
+ const stream = holdStream(req, res, () => {
1001
+ stop();
1002
+ streams.delete(stream.end);
1003
+ });
1004
+ streams.add(stream.end);
1005
+ return;
1006
+ }
932
1007
  if (p === "/api/listen") {
933
1008
  const remove = registry.add(listenerOf(url.searchParams));
934
1009
  const stream = holdStream(req, res, () => {
@@ -1084,6 +1159,7 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
1084
1159
  elsewhere: () => notifyAll("elsewhere"),
1085
1160
  addListener: (l) => registry.add(l),
1086
1161
  onListeners: (fn) => registry.onChange(fn),
1162
+ unfollowed,
1087
1163
  status: (page = null) => status(page),
1088
1164
  read: readList,
1089
1165
  stream,
@@ -0,0 +1,99 @@
1
+ import { parseMarkdown, slug, titleWords } from "./pages/markdown.js";
2
+ import { hashOf, slugText } from "./anchors.js";
3
+ import { edit } from "./migrate.js";
4
+ import { toString } from "mdast-util-to-string";
5
+ // src/set.ts
6
+ const start = (n) => n.position.start.offset;
7
+ const end = (n) => n.position.end.offset;
8
+ /** Directives that are named even without a name: a form or chat without one is `form`, `chat`. */
9
+ const NAMED_BY_TYPE = /* @__PURE__ */ new Set(["form", "chat"]);
10
+ /**
11
+ * The blocks of a page's source, in source order, named as the page's anchors name them: headings
12
+ * (numbered on a repeat, as the page does), and container or leaf directives with a name (its
13
+ * `name` or `id`), a label (its slug), or of a type named by itself (a form or chat without a name).
14
+ * A repeat of a directive's id is numbered (`details:why-1`), as a details' is on the page.
15
+ */
16
+ function blocksOf(source) {
17
+ const tree = parseMarkdown(source);
18
+ const out = [];
19
+ const headings = /* @__PURE__ */ new Map();
20
+ const taken = /* @__PURE__ */ new Map();
21
+ const walk = (parent) => {
22
+ const kids = parent.children ?? [];
23
+ kids.forEach((node, i) => {
24
+ if (node.type === "heading" && node.position) {
25
+ const id = slug(titleWords(node.children ?? [], () => true), headings);
26
+ let last = node;
27
+ for (const next of kids.slice(i + 1)) {
28
+ if (next.type === "heading" && next.depth <= node.depth) break;
29
+ last = next;
30
+ }
31
+ if (id && !id.startsWith("wp-")) out.push({
32
+ id,
33
+ kind: "heading",
34
+ from: start(node),
35
+ to: end(last)
36
+ });
37
+ } else if ((node.type === "containerDirective" || node.type === "leafDirective") && node.position) {
38
+ const attrs = node.attributes ?? {};
39
+ const label = node.type === "containerDirective" && node.children?.[0]?.data?.directiveLabel ? node.children[0] : null;
40
+ const labelText = label ? slugText(node.name === "details" ? toString(label) : titleWords(label.children ?? [], () => true)) : "";
41
+ const name = attrs.name || attrs.id || (NAMED_BY_TYPE.has(node.name) ? node.name : labelText);
42
+ if (name) {
43
+ const base = `${node.name}:${name}`;
44
+ let id = base;
45
+ if (taken.has(base)) {
46
+ let n = taken.get(base);
47
+ do
48
+ id = `${base}-${++n}`;
49
+ while (taken.has(id));
50
+ taken.set(base, n);
51
+ }
52
+ taken.set(id, 0);
53
+ out.push({
54
+ id,
55
+ kind: node.name,
56
+ from: start(node),
57
+ to: end(node)
58
+ });
59
+ }
60
+ }
61
+ walk(node);
62
+ });
63
+ };
64
+ walk(tree);
65
+ return out;
66
+ }
67
+ /** `name` as a link writes it, or as typed: `#form:logger`, `form:logger`, `form%3Alogger`. */
68
+ function normalize(name) {
69
+ let id = name.trim().replace(/^#/, "");
70
+ try {
71
+ id = decodeURIComponent(id);
72
+ } catch {}
73
+ return id;
74
+ }
75
+ /**
76
+ * The block `name` names: its anchor (`form:logger`, `open-questions`), or a block's bare name
77
+ * (`logger` for `form:logger`) when only one block has it. Throws, listing the page's blocks, when
78
+ * none does, or when the bare name fits several.
79
+ */
80
+ function findBlock(source, name) {
81
+ const blocks = blocksOf(source);
82
+ const id = normalize(name);
83
+ const exact = name.trim().startsWith("#");
84
+ const fits = blocks.filter((b) => b.id === id || !exact && b.id === `${b.kind}:${id}`);
85
+ if (fits.length === 1) return fits[0];
86
+ const list = (bs) => bs.map((b) => ` ${hashOf(b.id)} ${b.kind}`).join("\n");
87
+ if (fits.length > 1) throw new Error(`${id} fits ${fits.length} blocks; name one by its anchor, with its #:\n${list(fits)}`);
88
+ throw new Error(`no block ${hashOf(id)} on the page${blocks.length ? `; it has:\n${list(blocks)}` : ", nor any other with a name"}`);
89
+ }
90
+ /** `source` with the block `name` names replaced by `markdown` (its trailing blank lines left off). */
91
+ function setBlock(source, name, markdown) {
92
+ const block = findBlock(source, name);
93
+ return edit(source, [{
94
+ from: block.from,
95
+ to: block.to,
96
+ text: markdown.replace(/\s+$/, "")
97
+ }]);
98
+ }
99
+ export { blocksOf, findBlock, setBlock };
package/dist/src/state.js CHANGED
@@ -128,7 +128,8 @@ function subscriptionsOf(s) {
128
128
  agent: e.by,
129
129
  page: e.page,
130
130
  since: e.ts,
131
- channel: !!e.data?.channel
131
+ channel: !!e.data?.channel,
132
+ ...e.data?.unfollowed ? { unfollowed: true } : {}
132
133
  }));
133
134
  }
134
135
  /** Everyone the board knows, in the order the log first names them, then those only listening. */
@@ -75,20 +75,45 @@ const READ = "workpad:read";
75
75
  */
76
76
  const SCROLL = "workpad:scroll";
77
77
  /**
78
- * The agent's messages on a page the reader hasn't read: events from the agent of a type
79
- * `isMessage` says is for the reader, not named by a `workpad:read` from the reader, not
80
- * replaced by a later one (`replaces`), and, given the page's `chats`, not in a chat (`data.chat`)
81
- * that is no longer among them.
78
+ * The fields of an event's `data` its type requires (EventSpec.requires) that it lacks: each must
79
+ * be a non-empty string.
82
80
  */
83
- function unreadMessages(events, isMessage, chats) {
81
+ const missingData = (data, requires) => requires.filter((field) => {
82
+ const value = data?.[field];
83
+ return typeof value !== "string" || !value.trim();
84
+ });
85
+ /**
86
+ * Why an event of `type` with this `data` can't go in the log, given the types that require data
87
+ * fields: what it lacks, and the shape it needs; null when nothing is missing.
88
+ */
89
+ function refusal(type, data, requires) {
90
+ const fields = requires.get(type) ?? [];
91
+ const missing = missingData(data, fields);
92
+ if (!missing.length) return null;
93
+ const list = (names) => names.join(names.length > 2 ? ", " : " and ").replace(/, (?=[^,]*$)/, " and ");
94
+ const shape = JSON.stringify(Object.fromEntries(fields.map((f) => [f, "…"])));
95
+ return `a ${type} needs ${list(fields)} in its data, each a non-empty string; ${list(missing)} ${missing.length > 1 ? "are" : "is"} missing or empty. Its data: ${shape}`;
96
+ }
97
+ /**
98
+ * The agent's messages on a page the reader hasn't read: events from the agent of a type in
99
+ * `messages` (the types for the reader, each with the `data` fields it requires), not named by a
100
+ * `workpad:read` from the reader, not replaced by a later one (`replaces`), with the data their
101
+ * type requires (one without it shows nowhere on the page, so it waits for nobody), and, given the
102
+ * page's `chats`, not in a chat (`data.chat`) that is no longer among them.
103
+ */
104
+ function unreadMessages(events, messages, chats) {
84
105
  const read = /* @__PURE__ */ new Set();
85
106
  const replaced = /* @__PURE__ */ new Set();
86
107
  for (const e of events) {
87
108
  if (e.type === "workpad:read" && fromReader(e)) for (const id of e.data?.ids ?? []) read.add(String(id));
88
109
  if (e.data?.replaces) replaced.add(String(e.data.replaces));
89
110
  }
111
+ const shown = (e) => {
112
+ const requires = messages.get(e.type);
113
+ return !!requires && !missingData(e.data, requires).length;
114
+ };
90
115
  const offPage = (e) => !!chats && typeof e.data?.chat === "string" && !chats.has(e.data.chat);
91
- return events.filter((e) => !fromReader(e) && isMessage(e.type) && !read.has(e.id) && !replaced.has(e.id) && !offPage(e));
116
+ return events.filter((e) => !fromReader(e) && shown(e) && !read.has(e.id) && !replaced.has(e.id) && !offPage(e));
92
117
  }
93
118
  /** How many things on a page wait for the reader: its open questions and unread messages. */
94
119
  const awaiting = (p) => p.open.length + p.unread.length;
@@ -149,6 +174,20 @@ function namesOf(events) {
149
174
  for (const e of events) if (e.type === "workpad:name" && e.from === "cli" && e.by && typeof e.data?.name === "string") names.set(e.by, e.data.name);
150
175
  return names;
151
176
  }
177
+ /**
178
+ * Who received each answer first, by its id: the `by` of the first RECEIVED naming it (null when
179
+ * the command line knew no one). Only the command line's marks count.
180
+ */
181
+ function receivers(events) {
182
+ const by = /* @__PURE__ */ new Map();
183
+ for (const e of events) if (e.type === "workpad:received" && !fromReader(e)) {
184
+ const id = String(e.data?.event);
185
+ if (!by.has(id)) by.set(id, e.by ?? null);
186
+ }
187
+ return by;
188
+ }
189
+ /** An agent as a page names it: the name it gave itself (`names`), else its id, a long one (a session's) cut short. */
190
+ const agentLabel = (id, names = /* @__PURE__ */ new Map()) => names.get(id) ?? (id.length > 16 ? id.slice(0, 8) : id);
152
191
  /** The ids of the answers a wait or watch printed. Only the command line's marks count. */
153
192
  function receivedIds(events) {
154
193
  return new Set(events.filter((e) => e.type === "workpad:received" && !fromReader(e)).map((e) => String(e.data?.event)));
@@ -163,7 +202,7 @@ function receivedIds(events) {
163
202
  function channelSince(events, agent, page) {
164
203
  let since = null;
165
204
  for (const e of subscriptions(events)) {
166
- if (e.by !== agent) continue;
205
+ if (e.by !== agent || e.data?.unfollowed) continue;
167
206
  if (!(e.page === "" || e.page === page || page.startsWith(`${e.page}/`))) continue;
168
207
  if (!e.data?.channel) return null;
169
208
  since ??= e.id;
@@ -171,6 +210,13 @@ function channelSince(events, agent, page) {
171
210
  return since;
172
211
  }
173
212
  /**
213
+ * Does `agent` take the pages no one follows through its channel (`workpad listen --unfollowed
214
+ * --channel`)? Said by a subscription on every page (`''`) with data `{ channel: true, unfollowed:
215
+ * true }`; it makes no page the agent's (no subscriber of any), and `workpad agent unsubscribe`
216
+ * takes it off with the rest.
217
+ */
218
+ const takesUnfollowed = (events, agent) => subscriptions(events).some((e) => e.by === agent && !!e.data?.unfollowed);
219
+ /**
174
220
  * The ids of the reader's events the agent handled: acknowledged (`workpad:handled`), or replied
175
221
  * to after them (see the top of this file). The log is gone through once: each of the reader's
176
222
  * events is filed under what a reply would name (its id, its thread, its chat, its form), and an
@@ -244,6 +290,7 @@ function projectStatus({ pages, events, listeners, forAgent, forReader }) {
244
290
  if (fromReader(e)) last.set(e.page, e.ts);
245
291
  }
246
292
  for (const e of subscriptions(events)) {
293
+ if (e.data?.unfollowed) continue;
247
294
  const now = subscribers.get(e.page) ?? [];
248
295
  if (!now.includes(e.by)) subscribers.set(e.page, [...now, e.by]);
249
296
  }
@@ -281,6 +328,7 @@ function projectStatus({ pages, events, listeners, forAgent, forReader }) {
281
328
  unreceived: own.filter((e) => fromReader(e) && forAgent(e.type) && !received.has(e.id) && !handled.has(e.id)),
282
329
  unhandled: own.filter((e) => fromReader(e) && forAgent(e.type) && received.has(e.id) && !handled.has(e.id)),
283
330
  awaitingReply: awaitingReply(own),
331
+ updated: own.findLast((e) => !fromReader(e) && !e.type.startsWith("workpad:"))?.ts ?? null,
284
332
  listeners: listening
285
333
  };
286
334
  })
@@ -306,7 +354,7 @@ function statusLines(p, file, { waiting = true } = {}) {
306
354
  * Who is subscribed to a page, said to `me`: `you` among them, the others by the name they gave
307
355
  * themselves (`names`), else their id, a long one (a session's) cut short.
308
356
  */
309
- const whose = (p, me, names = /* @__PURE__ */ new Map()) => p.subscribers.length ? p.subscribers.map((s) => s === me ? "you" : names.get(s) ?? (s.length > 16 ? s.slice(0, 8) : s)).join(", ") : "no one subscribed";
357
+ const whose = (p, me, names = /* @__PURE__ */ new Map()) => p.subscribers.length ? p.subscribers.map((s) => s === me ? "you" : agentLabel(s, names)).join(", ") : "no one subscribed";
310
358
  /** The type of a chat message: `{ chat, text }` (the chat plugin's; the core shows the agent's as small pages). */
311
359
  const CHAT_MESSAGE = "chat:message";
312
360
  /** Is this a chat message of the agent's, which shows as a small page (forms and all)? */
@@ -320,4 +368,4 @@ function agentMessagesIn(events, page, chat) {
320
368
  const replaced = new Set(own.map((e) => e.data.replaces).filter(Boolean).map(String));
321
369
  return own.filter((e) => !replaced.has(e.id));
322
370
  }
323
- export { CHAT_MESSAGE, HANDLED, HOLD, NAME, READ, RECEIVED, RELEASE, SCROLL, SETTLE, SUBSCRIBE, UNSUBSCRIBE, agentMessagesIn, awaiting, awaitingReply, channelSince, covers, fromReader, handledIds, heard, holdOf, isAgentMessage, isQuestionName, namesOf, projectStatus, questionState, receivedIds, settleNested, statusLines, subscriptions, unreadMessages, whose };
371
+ export { CHAT_MESSAGE, HANDLED, HOLD, NAME, READ, RECEIVED, RELEASE, SCROLL, SETTLE, SUBSCRIBE, UNSUBSCRIBE, agentLabel, agentMessagesIn, awaiting, awaitingReply, channelSince, covers, fromReader, handledIds, heard, holdOf, isAgentMessage, isQuestionName, missingData, namesOf, projectStatus, questionState, receivedIds, receivers, refusal, settleNested, statusLines, subscriptions, takesUnfollowed, unreadMessages, whose };
@@ -0,0 +1,41 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ // src/turns.ts
4
+ const dirOf = (wp) => path.join(wp, "turns");
5
+ const fileOf = (wp, session) => path.join(dirOf(wp), encodeURIComponent(session));
6
+ /** Records older than this go when a turn end is written: their sessions are long over. */
7
+ const KEEP = 6048e5;
8
+ /**
9
+ * Record for `session` that its turn ended now (`ended`), or only that its turn ends are recorded
10
+ * (a mark: an end recorded before stays).
11
+ */
12
+ function recordTurn(wp, session, ended) {
13
+ if (!session) return;
14
+ const dir = dirOf(wp);
15
+ const file = fileOf(wp, session);
16
+ if (!ended && fs.existsSync(file)) return;
17
+ if (!fs.existsSync(dir)) {
18
+ fs.mkdirSync(dir, { recursive: true });
19
+ fs.writeFileSync(path.join(dir, ".gitignore"), "# when each agent session's turn last ended; not for git\n*\n");
20
+ }
21
+ if (ended) {
22
+ for (const name of fs.readdirSync(dir)) if (name !== ".gitignore" && Date.now() - fs.statSync(path.join(dir, name)).mtimeMs > KEEP) fs.rmSync(path.join(dir, name), { force: true });
23
+ }
24
+ fs.writeFileSync(`${file}.tmp`, ended ? String(Date.now()) : "");
25
+ fs.renameSync(`${file}.tmp`, file);
26
+ }
27
+ /**
28
+ * What is recorded of `session`'s turns: null when nothing is (its turn ends aren't recorded);
29
+ * else when its last turn ended, null when none has since it was marked.
30
+ */
31
+ function lastTurnEnd(wp, session) {
32
+ let text;
33
+ try {
34
+ text = fs.readFileSync(fileOf(wp, session), "utf8");
35
+ } catch {
36
+ return null;
37
+ }
38
+ const ended = Number(text);
39
+ return { ended: text && Number.isFinite(ended) ? ended : null };
40
+ }
41
+ export { lastTurnEnd, recordTurn };