@bigmistqke/workpad 0.18.0 → 0.19.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 (57) hide show
  1. package/bin/workpad.ts +238 -17
  2. package/dist/bin/workpad.js +191 -13
  3. package/dist/plugins/badge/README.md +59 -10
  4. package/dist/plugins/badge/index.js +130 -8
  5. package/dist/plugins/badge/public/style.css +132 -12
  6. package/dist/plugins/chat/index.js +7 -1
  7. package/dist/plugins/claude/README.md +13 -5
  8. package/dist/plugins/claude/channel.js +25 -2
  9. package/dist/plugins/claude/doctor.js +43 -47
  10. package/dist/plugins/claude/index.js +24 -8
  11. package/dist/plugins/claude/session.js +46 -1
  12. package/dist/plugins/opencode/channel.js +42 -7
  13. package/dist/plugins/opencode/index.js +2 -0
  14. package/dist/src/agents.js +7 -2
  15. package/dist/src/client/page/main.js +23 -0
  16. package/dist/src/events.js +6 -5
  17. package/dist/src/help.js +18 -4
  18. package/dist/src/hub.js +62 -2
  19. package/dist/src/listen.js +36 -4
  20. package/dist/src/listeners.js +14 -4
  21. package/dist/src/pages/board.js +9 -4
  22. package/dist/src/pages/index.js +2 -4
  23. package/dist/src/pages/markdown.js +47 -16
  24. package/dist/src/pages/render.js +128 -32
  25. package/dist/src/server.js +69 -6
  26. package/dist/src/state.js +2 -1
  27. package/dist/src/status.js +11 -2
  28. package/dist/src/turns.js +41 -0
  29. package/package.json +6 -1
  30. package/plugins/badge/README.md +59 -10
  31. package/plugins/badge/index.ts +141 -8
  32. package/plugins/badge/public/style.css +132 -12
  33. package/plugins/chat/index.ts +9 -1
  34. package/plugins/claude/README.md +13 -5
  35. package/plugins/claude/channel.ts +26 -2
  36. package/plugins/claude/doctor.ts +58 -39
  37. package/plugins/claude/index.ts +30 -8
  38. package/plugins/claude/session.ts +32 -0
  39. package/plugins/opencode/channel.ts +42 -7
  40. package/plugins/opencode/index.ts +4 -0
  41. package/skills/workpad/SKILL.md +30 -6
  42. package/src/agents.ts +9 -1
  43. package/src/client/page/board.ts +29 -0
  44. package/src/define.ts +28 -1
  45. package/src/events.ts +23 -2
  46. package/src/help.ts +18 -4
  47. package/src/hub.ts +80 -2
  48. package/src/listen.ts +47 -4
  49. package/src/listeners.ts +22 -1
  50. package/src/pages/board.ts +10 -3
  51. package/src/pages/index.ts +8 -10
  52. package/src/pages/markdown.ts +55 -8
  53. package/src/pages/render.ts +132 -35
  54. package/src/server.ts +84 -6
  55. package/src/state.ts +3 -0
  56. package/src/status.ts +15 -1
  57. package/src/turns.ts +56 -0
@@ -1,6 +1,6 @@
1
1
  import { resolveBlocks } from "./blocks.js";
2
2
  import { createAgentMessageRender, createBlocksRender, createDocs, createMessageRender, createRender } from "./render.js";
3
- import { chatNames, formDetails, formNames } from "./markdown.js";
3
+ import { pageAsks } from "./markdown.js";
4
4
  // src/pages/index.ts
5
5
  function createPages(options) {
6
6
  const resolved = resolveBlocks(options.blocks);
@@ -19,9 +19,7 @@ function createPages(options) {
19
19
  agentMessage: createAgentMessageRender(blocks, options.links ?? [], options.composers),
20
20
  blocks: createBlocksRender(blocks, options.links ?? [], options.composers),
21
21
  docs: createDocs(blocks),
22
- questions: (page) => formNames(ended(page).body),
23
- chats: (page) => chatNames(ended(page).body),
24
- forms: (page) => formDetails(ended(page).body)
22
+ asks: (page) => pageAsks(ended(page).body)
25
23
  };
26
24
  }
27
25
  export { createPages };
@@ -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
@@ -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 };
@@ -7,7 +7,8 @@ import { ACTIVE_FOR, byProject, byState, total, withoutPages } from "./board.js"
7
7
  import fs from "node:fs";
8
8
  import path from "node:path";
9
9
  import os from "node:os";
10
- import { execFileSync } from "node:child_process";
10
+ import { execFile, execFileSync } from "node:child_process";
11
+ import { promisify } from "node:util";
11
12
  import { fileURLToPath } from "node:url";
12
13
  // src/pages/render.ts
13
14
  const BASE_CSS = new URL("../client/page/base.css", import.meta.url);
@@ -36,12 +37,16 @@ const body = (source) => source.replace(FRONTMATTER, "");
36
37
  /** A page's title: its first heading, else its name. */
37
38
  function titleOf(file, fallback) {
38
39
  try {
39
- const h1 = /^#\s+(.+)$/m.exec(body(fs.readFileSync(file, "utf8")));
40
- return h1 ? h1[1].replace(/[*_`]/g, "") : fallback;
40
+ return headingOf(fs.readFileSync(file, "utf8")) ?? fallback;
41
41
  } catch {
42
42
  return fallback;
43
43
  }
44
44
  }
45
+ /** The first heading of a page's markdown, past its frontmatter; null when it has none. */
46
+ function headingOf(source) {
47
+ const h1 = /^#\s+(.+)$/m.exec(body(source));
48
+ return h1 ? h1[1].replace(/[*_`]/g, "") : null;
49
+ }
45
50
  function crumbs(id, name, base, entry) {
46
51
  const parts = id ? id.split("/") : [];
47
52
  const above = entry ? html`<a href="/">workpad</a> / ` : "";
@@ -140,6 +145,101 @@ function documentsIn(dir, shows = (rel) => fileFilter().shows(rel)) {
140
145
  const depth = (f) => f.split("/").length;
141
146
  return [...new Set(files)].filter(shows).toSorted((a, b) => depth(a) - depth(b) || a.localeCompare(b));
142
147
  }
148
+ function docOf(dir, file) {
149
+ const abs = path.join(dir, file);
150
+ let mtime = 0;
151
+ try {
152
+ mtime = fs.statSync(abs).mtimeMs;
153
+ } catch {}
154
+ return {
155
+ file,
156
+ title: titleOf(abs, path.posix.basename(file)),
157
+ mtime
158
+ };
159
+ }
160
+ /**
161
+ * Whether a project without pages has documents to read, without listing them: a markdown file in
162
+ * its top folder (a README). Cheap, so the overview can ask it of every project on each render;
163
+ * the files themselves are listed only when the reader opens the fold (filesFold).
164
+ */
165
+ function hasTopDocs(dir) {
166
+ try {
167
+ return fs.readdirSync(dir).some((n) => MARKDOWN.test(n));
168
+ } catch {
169
+ return false;
170
+ }
171
+ }
172
+ const run = promisify(execFile);
173
+ /**
174
+ * The files fold of a project without pages, listed when the reader opens it (GET /api/files on the
175
+ * shared server): documentsIn's list, but off the event loop. A checkout holds thousands of
176
+ * markdown files, and listing them on each render froze the shared server for many seconds.
177
+ */
178
+ async function filesFold(dir, base) {
179
+ let files;
180
+ try {
181
+ const { stdout } = await run("git", [
182
+ "ls-files",
183
+ "--cached",
184
+ "--others",
185
+ "--exclude-standard",
186
+ "--",
187
+ ":(icase)*.md",
188
+ ":(icase)*.markdown"
189
+ ], {
190
+ cwd: dir,
191
+ encoding: "utf8",
192
+ maxBuffer: 67108864
193
+ });
194
+ files = stdout.split("\n").filter((f) => f && !f.startsWith(".workpad/"));
195
+ } catch {
196
+ files = [];
197
+ const walk = async (rel) => {
198
+ let entries = [];
199
+ try {
200
+ entries = await fs.promises.readdir(path.join(dir, rel), { withFileTypes: true });
201
+ } catch {
202
+ return;
203
+ }
204
+ for (const e of entries) if (e.isDirectory()) {
205
+ if (!SKIP.has(e.name) && !e.name.startsWith(".")) await walk(path.posix.join(rel, e.name));
206
+ } else if (MARKDOWN.test(e.name)) files.push(path.posix.join(rel, e.name));
207
+ };
208
+ await walk("");
209
+ }
210
+ const shows = fileFilter().shows;
211
+ const depth = (f) => f.split("/").length;
212
+ files = [...new Set(files)].filter((f) => shows(f)).toSorted((a, b) => depth(a) - depth(b) || a.localeCompare(b));
213
+ const docs = [];
214
+ for (let i = 0; i < files.length; i += 32) {
215
+ const batch = await Promise.all(files.slice(i, i + 32).map(async (file) => {
216
+ const abs = path.join(dir, file);
217
+ try {
218
+ const handle = await fs.promises.open(abs, "r");
219
+ try {
220
+ const { mtimeMs } = await handle.stat();
221
+ const buf = Buffer.alloc(8192);
222
+ const { bytesRead } = await handle.read(buf, 0, buf.length, 0);
223
+ const name = path.posix.basename(file);
224
+ return {
225
+ file,
226
+ title: headingOf(buf.toString("utf8", 0, bytesRead)) ?? name,
227
+ mtime: mtimeMs
228
+ };
229
+ } finally {
230
+ await handle.close();
231
+ }
232
+ } catch {
233
+ return null;
234
+ }
235
+ }));
236
+ for (const d of batch) if (d) docs.push(d);
237
+ }
238
+ return {
239
+ count: docs.length,
240
+ html: String(documentFolders(docs, dir, base, () => null))
241
+ };
242
+ }
143
243
  /**
144
244
  * The overview's list of the project's documents: each by its title, linked to its rendered page,
145
245
  * with when its file last changed. The list can be sorted in the browser (sort.ts): by folder (as
@@ -154,13 +254,21 @@ function documentList(ctx) {
154
254
  * documents would otherwise be one long list. A folder holding only one folder is shown as one
155
255
  * (`docs/adr/`), so the tree is no deeper than what tells folders apart.
156
256
  */
157
- function documentTree(files, dir, base, urlFor, open = false) {
257
+ function documentTree(docs, dir, base, urlFor, open = false) {
258
+ return html`<details class="wp-documents wp-folded-documents"${raw(open ? " open" : "")}>
259
+ <summary>Files <span class="wp-meta">${docs.length}</span></summary>
260
+ ${documentFolders(docs, dir, base, urlFor)}
261
+ </details>`;
262
+ }
263
+ /** The inside of a project's files fold: its documents by folder, a fold per folder with how many. */
264
+ function documentFolders(docs, dir, base, urlFor) {
158
265
  const root = {
159
266
  files: [],
160
267
  folders: /* @__PURE__ */ new Map(),
161
268
  count: 0
162
269
  };
163
- for (const f of files) {
270
+ const byFile = new Map(docs.map((d) => [d.file, d]));
271
+ for (const { file: f } of docs) {
164
272
  let at = root;
165
273
  at.count++;
166
274
  const parts = f.split("/");
@@ -178,11 +286,7 @@ function documentTree(files, dir, base, urlFor, open = false) {
178
286
  const row = (f) => {
179
287
  const abs = path.join(dir, f);
180
288
  const name = path.posix.basename(f);
181
- const title = titleOf(abs, name);
182
- let mtime = 0;
183
- try {
184
- mtime = fs.statSync(abs).mtimeMs;
185
- } catch {}
289
+ const { title, mtime } = byFile.get(f);
186
290
  return html`<li>
187
291
  <a href="${urlFor(abs) ?? `${base}/-/${f}`}">${title}</a>
188
292
  <span class="wp-meta">${title !== name && html`<code>${name}</code> · `}edited ${time(mtime)}</span>
@@ -202,32 +306,24 @@ function documentTree(files, dir, base, urlFor, open = false) {
202
306
  const contents = (f) => html`${f.files.length > 0 && html`<ul class="wp-index">
203
307
  ${f.files.map(row)}
204
308
  </ul>`}${[...f.folders].toSorted(([a], [b]) => a.localeCompare(b)).map(([name, sub]) => folder(name, sub))}`;
205
- return html`<details class="wp-documents wp-folded-documents"${raw(open ? " open" : "")}>
206
- <summary>Files <span class="wp-meta">${files.length}</span></summary>
207
- ${contents(root)}
208
- </details>`;
309
+ return contents(root);
209
310
  }
210
311
  /**
211
312
  * A project's documents, as its overview lists them: from its folder, linked where it serves them.
212
313
  * `folded`: in a fold that says how many (the shared server's overview, where each project has them).
213
314
  */
214
315
  function documentsOf(dir, base, urlFor, folded = false, shows, open = false) {
215
- const files = documentsIn(dir, shows);
216
- if (!files.length) return "";
316
+ const docs = documentsIn(dir, shows).map((f) => docOf(dir, f));
317
+ if (!docs.length) return "";
318
+ if (folded) return documentTree(docs, dir, base, urlFor, open);
217
319
  const ctx = {
218
320
  project: { dir },
219
321
  base,
220
322
  urlFor
221
323
  };
222
- const rows = files.map((f, i) => {
324
+ const rows = docs.map(({ file: f, title, mtime }, i) => {
223
325
  const abs = path.join(ctx.project.dir, f);
224
- const name = path.posix.basename(f);
225
- const title = titleOf(abs, name);
226
- const where = title === name ? path.posix.dirname(f) : f;
227
- let mtime = 0;
228
- try {
229
- mtime = fs.statSync(abs).mtimeMs;
230
- } catch {}
326
+ const where = title === path.posix.basename(f) ? path.posix.dirname(f) : f;
231
327
  return html`<li data-order="${i}" data-updated="${mtime}" data-title="${title.toLowerCase()}">
232
328
  <a href="${ctx.urlFor(abs) ?? `${ctx.base ?? ""}/-/${f}`}">${title}</a>
233
329
  <span class="wp-meta"
@@ -235,7 +331,6 @@ function documentsOf(dir, base, urlFor, folded = false, shows, open = false) {
235
331
  >
236
332
  </li>`;
237
333
  });
238
- if (folded) return documentTree(files, dir, base, urlFor, open);
239
334
  return html`<section class="wp-documents">
240
335
  <div class="wp-list-head">
241
336
  <h2>Documents</h2>
@@ -267,7 +362,7 @@ function card(c, withProject) {
267
362
  <a class="wp-board-title" href="${c.page.url}">${c.page.title}</a>
268
363
  ${counts(c.waiting, `${c.page.url}#wp-waiting`)}
269
364
  ${withProject && html`<span class="wp-board-project">${c.project.label}</span>`}
270
- <span class="wp-meta wp-board-when">edited ${time(c.page.mtime)}</span>
365
+ <span class="wp-meta wp-board-when">updated ${time(c.page.updated)}</span>
271
366
  </li>`;
272
367
  }
273
368
  function cards(list, withProject) {
@@ -294,10 +389,9 @@ function emptyColumn(projects) {
294
389
  */
295
390
  function board(projects, now) {
296
391
  const states = byState(projects, now);
297
- const docsOf = new Map(withoutPages(projects).map((p) => [p, p.files ? documentsIn(p.dir).length : 0]));
298
392
  const empty = withoutPages(projects);
299
- const withDocs = [...docsOf].filter(([, n]) => n > 0).map(([p]) => p);
300
- const bare = empty.filter((p) => !docsOf.get(p));
393
+ const withDocs = empty.filter((p) => p.files && hasTopDocs(p.dir));
394
+ const bare = empty.filter((p) => !withDocs.includes(p));
301
395
  const hours = ACTIVE_FOR / 36e5;
302
396
  const stateColumn = (key, title, note) => html`<section class="wp-board-column wp-board-${key}${key === "waiting" && states.waiting.length ? " wp-board-waits" : ""}">
303
397
  <header class="wp-board-head">
@@ -320,9 +414,11 @@ function board(projects, now) {
320
414
  const docsColumn = (p) => html`<section class="wp-board-column wp-board-docs">
321
415
  <header class="wp-board-head" title="${p.dir.replace(os.homedir(), "~")}">
322
416
  <h2><a href="${p.base}/">${p.label}</a></h2>
323
- <span class="wp-meta">no pages · ${docsOf.get(p)} file${docsOf.get(p) === 1 ? "" : "s"}</span>
417
+ <span class="wp-meta">no pages</span>
324
418
  </header>
325
- ${documentsOf(p.dir, p.base, () => null, true, void 0, true)}
419
+ <details class="wp-documents wp-folded-documents" data-wp-files="${p.base}">
420
+ <summary>Files <span class="wp-meta"></span></summary>
421
+ </details>
326
422
  </section>`;
327
423
  return html`<div class="wp-board-bar">
328
424
  <div class="wp-board-switch" role="group" aria-label="Columns">
@@ -662,4 +758,4 @@ ${GROUPS.map(([group, title]) => {
662
758
  `;
663
759
  };
664
760
  }
665
- export { createAgentMessageRender, createBlocksRender, createDocs, createMessageRender, createRender, titleOf };
761
+ export { createAgentMessageRender, createBlocksRender, createDocs, createMessageRender, createRender, filesFold, hasTopDocs, titleOf };
@@ -12,7 +12,7 @@ import { SCROLL, SUBSCRIBE, agentMessagesIn, awaiting, handledIds, isAgentMessag
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";
@@ -243,10 +243,8 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
243
243
  let chats;
244
244
  let details = [];
245
245
  try {
246
- const source = pageSource(id, file);
247
- asks = renderer?.questions(source) ?? [];
248
- chats = renderer?.chats(source);
249
- details = renderer?.forms(source) ?? [];
246
+ const said = renderer?.asks(pageSource(id, file));
247
+ if (said) ({questions: asks, chats, forms: details} = said);
250
248
  } catch (err) {
251
249
  console.error("questions:", err);
252
250
  }
@@ -267,15 +265,23 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
267
265
  async function snapshot(listed) {
268
266
  const { pages: renderer, handedOut, forReader } = await config();
269
267
  const events = readEvents(project.eventsFile);
268
+ const messages = /* @__PURE__ */ new Map();
269
+ for (const e of events) {
270
+ if (!isAgentMessage(e)) continue;
271
+ const own = messages.get(e.page);
272
+ if (own) own.push(e);
273
+ else messages.set(e.page, [e]);
274
+ }
270
275
  const pages = listed.map((p) => {
271
276
  const page = {
272
277
  id: p.id,
273
278
  file: p.file,
274
279
  ...questionsOf(renderer, p.id, p.file)
275
280
  };
281
+ const forms = messageForms(messages.get(p.id) ?? [], p.id, page.chats ?? []);
276
282
  return {
277
283
  ...page,
278
- asks: [...page.asks, ...messageForms(events, p.id, page.chats ?? [])]
284
+ asks: [...page.asks, ...forms]
279
285
  };
280
286
  });
281
287
  return projectStatus({
@@ -537,6 +543,48 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
537
543
  /** the codes of pings sent and not confirmed yet: the channel each went to */
538
544
  const pings = /* @__PURE__ */ new Map();
539
545
  const pingCode = () => crypto.randomBytes(3).toString("hex");
546
+ const unfollowing = /* @__PURE__ */ new Set();
547
+ let looking = false;
548
+ function lookAgain() {
549
+ if (looking || !unfollowing.size) return;
550
+ looking = true;
551
+ setImmediate(() => {
552
+ looking = false;
553
+ const pages = pagesIn(project.pagesDir).map((p) => p.id).filter((id) => !registry.list(id).some((l) => follows(l, id)));
554
+ for (const u of unfollowing) {
555
+ for (const [page, release] of u.held) if (!pages.includes(page)) {
556
+ release();
557
+ u.held.delete(page);
558
+ }
559
+ for (const page of pages) if (!u.held.has(page)) u.held.set(page, registry.add({
560
+ ...u.listener,
561
+ page,
562
+ unfollowed: true
563
+ }));
564
+ const now = JSON.stringify(pages);
565
+ if (now !== u.told) {
566
+ u.told = now;
567
+ u.onPages(pages);
568
+ }
569
+ }
570
+ });
571
+ }
572
+ registry.onChange(lookAgain);
573
+ function unfollowed(listener, onPages) {
574
+ const u = {
575
+ listener,
576
+ onPages,
577
+ held: /* @__PURE__ */ new Map(),
578
+ told: null
579
+ };
580
+ unfollowing.add(u);
581
+ lookAgain();
582
+ return () => {
583
+ if (!unfollowing.delete(u)) return;
584
+ for (const release of u.held.values()) release();
585
+ u.held.clear();
586
+ };
587
+ }
540
588
  const clients = /* @__PURE__ */ new Set();
541
589
  /** what the browser appended lately, by id: a send it retries is answered with what it got */
542
590
  const appended = /* @__PURE__ */ new Map();
@@ -557,6 +605,7 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
557
605
  });
558
606
  function pageChanged(id) {
559
607
  onChange?.();
608
+ lookAgain();
560
609
  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
610
  for (const c of clients) if (c.isDir && !c.page) notify(c, "change");
562
611
  }
@@ -929,6 +978,19 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
929
978
  if (p === "/api/status") return sendJson(res, 200, await status(q.page || null));
930
979
  if (p === "/api/listeners") return sendJson(res, 200, listenersFor(q.page ?? null));
931
980
  if (p === "/api/stamps") return sendJson(res, 200, stamps());
981
+ if (p === "/api/listen" && url.searchParams.has("unfollowed")) {
982
+ const stop = unfollowed(listenerOf(url.searchParams), (pages) => stream.send("pages", { projects: pages.length ? [{
983
+ dir: project.dir,
984
+ base,
985
+ pages
986
+ }] : [] }));
987
+ const stream = holdStream(req, res, () => {
988
+ stop();
989
+ streams.delete(stream.end);
990
+ });
991
+ streams.add(stream.end);
992
+ return;
993
+ }
932
994
  if (p === "/api/listen") {
933
995
  const remove = registry.add(listenerOf(url.searchParams));
934
996
  const stream = holdStream(req, res, () => {
@@ -1084,6 +1146,7 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
1084
1146
  elsewhere: () => notifyAll("elsewhere"),
1085
1147
  addListener: (l) => registry.add(l),
1086
1148
  onListeners: (fn) => registry.onChange(fn),
1149
+ unfollowed,
1087
1150
  status: (page = null) => status(page),
1088
1151
  read: readList,
1089
1152
  stream,
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. */
@@ -163,7 +163,7 @@ function receivedIds(events) {
163
163
  function channelSince(events, agent, page) {
164
164
  let since = null;
165
165
  for (const e of subscriptions(events)) {
166
- if (e.by !== agent) continue;
166
+ if (e.by !== agent || e.data?.unfollowed) continue;
167
167
  if (!(e.page === "" || e.page === page || page.startsWith(`${e.page}/`))) continue;
168
168
  if (!e.data?.channel) return null;
169
169
  since ??= e.id;
@@ -171,6 +171,13 @@ function channelSince(events, agent, page) {
171
171
  return since;
172
172
  }
173
173
  /**
174
+ * Does `agent` take the pages no one follows through its channel (`workpad listen --unfollowed
175
+ * --channel`)? Said by a subscription on every page (`''`) with data `{ channel: true, unfollowed:
176
+ * true }`; it makes no page the agent's (no subscriber of any), and `workpad agent unsubscribe`
177
+ * takes it off with the rest.
178
+ */
179
+ const takesUnfollowed = (events, agent) => subscriptions(events).some((e) => e.by === agent && !!e.data?.unfollowed);
180
+ /**
174
181
  * The ids of the reader's events the agent handled: acknowledged (`workpad:handled`), or replied
175
182
  * to after them (see the top of this file). The log is gone through once: each of the reader's
176
183
  * events is filed under what a reply would name (its id, its thread, its chat, its form), and an
@@ -244,6 +251,7 @@ function projectStatus({ pages, events, listeners, forAgent, forReader }) {
244
251
  if (fromReader(e)) last.set(e.page, e.ts);
245
252
  }
246
253
  for (const e of subscriptions(events)) {
254
+ if (e.data?.unfollowed) continue;
247
255
  const now = subscribers.get(e.page) ?? [];
248
256
  if (!now.includes(e.by)) subscribers.set(e.page, [...now, e.by]);
249
257
  }
@@ -281,6 +289,7 @@ function projectStatus({ pages, events, listeners, forAgent, forReader }) {
281
289
  unreceived: own.filter((e) => fromReader(e) && forAgent(e.type) && !received.has(e.id) && !handled.has(e.id)),
282
290
  unhandled: own.filter((e) => fromReader(e) && forAgent(e.type) && received.has(e.id) && !handled.has(e.id)),
283
291
  awaitingReply: awaitingReply(own),
292
+ updated: own.findLast((e) => !fromReader(e) && !e.type.startsWith("workpad:"))?.ts ?? null,
284
293
  listeners: listening
285
294
  };
286
295
  })
@@ -320,4 +329,4 @@ function agentMessagesIn(events, page, chat) {
320
329
  const replaced = new Set(own.map((e) => e.data.replaces).filter(Boolean).map(String));
321
330
  return own.filter((e) => !replaced.has(e.id));
322
331
  }
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 };
332
+ 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, 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 };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bigmistqke/workpad",
3
- "version": "0.18.0",
3
+ "version": "0.19.0",
4
4
  "description": "A workpad for you and your agent: it writes markdown pages you read live in the browser, you answer through forms it waits on",
5
5
  "keywords": [
6
6
  "agent",
@@ -84,6 +84,11 @@
84
84
  "source": "./plugins/code/index.ts",
85
85
  "types": "./plugins/code/index.ts",
86
86
  "default": "./dist/plugins/code/index.js"
87
+ },
88
+ "./badge": {
89
+ "source": "./plugins/badge/index.ts",
90
+ "types": "./plugins/badge/index.ts",
91
+ "default": "./dist/plugins/badge/index.js"
87
92
  }
88
93
  },
89
94
  "files": [