@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
@@ -3,6 +3,7 @@ import { read, receivedBy } from "../../src/events.js";
3
3
  import { channel } from "./channel.js";
4
4
  import { doctor } from "./doctor.js";
5
5
  import { recordSession } from "./session.js";
6
+ import { recordTurn } from "../../src/turns.js";
6
7
  import fs from "node:fs";
7
8
  import path from "node:path";
8
9
  // plugins/claude/index.ts
@@ -37,26 +38,40 @@ function claude() {
37
38
  run: channel
38
39
  },
39
40
  doctor: {
40
- description: "check what the channel needs, a line each with what to do: the .mcp.json entry and its command, the server approved and disabled in no settings file, the session started with the channels flag in the project's folder, the server up at the project's version, a channel for this session, its ping confirmed",
41
+ description: "check what the channel needs, a line each with what to do: the .mcp.json entry and its command, the server approved and disabled in no settings file (both where Claude Code runs, named beside the pages' project when it is another folder), the session started with the channels flag, the server up at the project's version, a channel for this session, its ping confirmed",
41
42
  run: doctor
42
43
  },
43
44
  install: {
44
- description: "add the channel to this project's .mcp.json and its hooks to .claude/settings.json",
45
+ description: "add the channel to the .mcp.json and its hooks to the .claude/settings.json of the folder Claude Code runs in: this project's, or --claude-dir",
46
+ options: { "claude-dir": CLAUDE_DIR },
45
47
  run: (ctx) => {
46
- installChannel(ctx.project.dir);
47
- installHooks(ctx.project.dir);
48
+ const dir = claudeDir(ctx);
49
+ installChannel(dir);
50
+ installHooks(dir);
48
51
  }
49
52
  },
50
53
  uninstall: {
51
- description: "take the channel and its hooks out of this project's settings again; other hooks, servers and settings stay",
54
+ description: "take the channel and its hooks out of the settings again (this project's, or --claude-dir's); other hooks, servers and settings stay",
55
+ options: { "claude-dir": CLAUDE_DIR },
52
56
  run: (ctx) => {
53
- uninstallChannel(ctx.project.dir);
54
- uninstallHooks(ctx.project.dir);
57
+ const dir = claudeDir(ctx);
58
+ uninstallChannel(dir);
59
+ uninstallHooks(dir);
55
60
  }
56
61
  }
57
62
  }
58
63
  };
59
64
  }
65
+ /**
66
+ * The folder Claude Code runs in, when it isn't the pages' project: a session a wrapper hands
67
+ * another folder's pages reads .mcp.json and its settings from its own folder.
68
+ */
69
+ const CLAUDE_DIR = {
70
+ type: "string?",
71
+ value: "folder",
72
+ description: "the folder Claude Code runs in, when not this project's (`workpad claude doctor` names it)"
73
+ };
74
+ const claudeDir = (ctx) => path.resolve(ctx.options["claude-dir"] ?? ctx.project.dir);
60
75
  /** The JSON Claude Code passes a hook on its standard input, or nothing. */
61
76
  function hookInput() {
62
77
  if (process.stdin.isTTY) return {};
@@ -69,9 +84,10 @@ function hookInput() {
69
84
  async function hook(ctx, mode) {
70
85
  const input = hookInput();
71
86
  if (input.session_id) recordSession(ctx.dataDir, input.session_id);
72
- if (mode === "session") return;
87
+ if (mode === "session") return recordTurn(ctx.project.wp, identity(input.session_id ?? process.env.CLAUDE_CODE_SESSION_ID ?? null), false);
73
88
  const agent = identity(input.session_id ?? process.env.CLAUDE_CODE_SESSION_ID ?? null);
74
89
  const left = await stopReminder(ctx, agent, inFlight(ctx, agent, input.transcript_path));
90
+ if (!left || input.stop_hook_active) recordTurn(ctx.project.wp, agent, true);
75
91
  if (!left) return;
76
92
  if (input.stop_hook_active) return void console.log(JSON.stringify({ systemMessage: left.shown }));
77
93
  console.log(JSON.stringify({ hookSpecificOutput: {
@@ -37,6 +37,51 @@ function claudeProcess() {
37
37
  const at = started.status === 0 ? Date.parse(started.stdout.trim()) : NaN;
38
38
  return Number.isNaN(at) ? String(pid) : `${pid}-${at / 1e3}`;
39
39
  }
40
+ /** The folder a process runs in (with lsof), or null when it can't be read. */
41
+ function processCwd(pid) {
42
+ const lsof = spawnSync("lsof", [
43
+ "-a",
44
+ "-p",
45
+ String(pid),
46
+ "-d",
47
+ "cwd",
48
+ "-Fn"
49
+ ], { encoding: "utf8" });
50
+ if (lsof.status !== 0) return null;
51
+ return lsof.stdout.split("\n").find((l) => l.startsWith("n"))?.slice(1) || null;
52
+ }
53
+ /** A folder as the file system names it, symbolic links resolved (as given when it isn't there). */
54
+ function real(dir) {
55
+ try {
56
+ return fs.realpathSync(dir);
57
+ } catch {
58
+ return path.resolve(dir);
59
+ }
60
+ }
61
+ /**
62
+ * The folder Claude Code runs in, where it reads .mcp.json and its project settings: not always the
63
+ * pages' project (a wrapper can hand a session another folder's pages). CLAUDE_PROJECT_DIR when set
64
+ * (Claude Code gives it to hooks and MCP servers, not to an agent's commands); else the folder of
65
+ * the claude process this one runs under (found with ps, else by the CLAUDE_PID Claude Code gives an
66
+ * agent's commands); else, outside a session, `fallback`. With how it was found, for the doctor
67
+ * (null: no session was found, and it is `fallback`).
68
+ */
69
+ function claudeFolder(fallback, env = process.env) {
70
+ if (env.CLAUDE_PROJECT_DIR) return {
71
+ dir: real(env.CLAUDE_PROJECT_DIR),
72
+ from: "CLAUDE_PROJECT_DIR"
73
+ };
74
+ const pid = claudePid() ?? (Number(env.CLAUDE_PID) || null);
75
+ const cwd = pid ? processCwd(pid) : null;
76
+ if (cwd) return {
77
+ dir: real(cwd),
78
+ from: `the folder claude (pid ${pid}) runs in`
79
+ };
80
+ return {
81
+ dir: real(fallback),
82
+ from: null
83
+ };
84
+ }
40
85
  const sessionsDir = (dataDir) => path.join(dataDir, "sessions");
41
86
  /** The conversation a hook says this claude process is on; records of processes that ended go. */
42
87
  function recordSession(dataDir, session) {
@@ -65,4 +110,4 @@ function alive(pid) {
65
110
  return err.code === "EPERM";
66
111
  }
67
112
  }
68
- export { claudePid, claudeProcess, recordSession, recordedSession };
113
+ export { claudeFolder, claudePid, claudeProcess, real, recordSession, recordedSession };
@@ -1,6 +1,8 @@
1
- import { channelSince } from "../../src/status.js";
2
1
  import { read, receive, receivedBy } from "../../src/events.js";
3
- import { answerLine, identity, pong } from "../../src/agents.js";
2
+ import { channelSince, takesUnfollowed } from "../../src/status.js";
3
+ import { answerLine, identity, pong, unfollowedLine } from "../../src/agents.js";
4
+ import { project } from "../../src/config.js";
5
+ import { recordTurn } from "../../src/turns.js";
4
6
  import fs from "node:fs";
5
7
  import path from "node:path";
6
8
  import readline from "node:readline";
@@ -15,6 +17,7 @@ async function channel(ctx) {
15
17
  const sessions = /* @__PURE__ */ new Map();
16
18
  const hold = (session) => {
17
19
  sessions.set(session, false);
20
+ recordTurn(ctx.project.wp, identity(session), false);
18
21
  ctx.channel(identity(session), {
19
22
  onPing: (code) => say({
20
23
  session,
@@ -28,10 +31,38 @@ async function channel(ctx) {
28
31
  });
29
32
  };
30
33
  const followed = /* @__PURE__ */ new Set();
34
+ const unfollowed = /* @__PURE__ */ new Map();
35
+ const logOf = /* @__PURE__ */ new Map();
36
+ const takeUnfollowed = (agent, session) => {
37
+ if (!takesUnfollowed(read(ctx.eventsFile).events, agent)) {
38
+ unfollowed.get(session)?.abort();
39
+ unfollowed.delete(session);
40
+ return;
41
+ }
42
+ if (unfollowed.has(session)) return;
43
+ const stop = new AbortController();
44
+ unfollowed.set(session, stop);
45
+ ctx.unfollowed((e, again, from) => {
46
+ const log = from ? project(from.project)?.eventsFile : null;
47
+ if (log) logOf.set(e.id, log);
48
+ say({
49
+ session,
50
+ id: e.id,
51
+ page: e.page,
52
+ type: e.type,
53
+ text: unfollowedLine(e, again, from)
54
+ });
55
+ }, {
56
+ agent,
57
+ mark: false,
58
+ signal: stop.signal
59
+ }).catch((err) => problem("taking the unfollowed pages failed", String(err)));
60
+ };
31
61
  const follow = async () => {
32
62
  const who = /* @__PURE__ */ new Map();
33
63
  for (const [session, confirmed] of sessions) if (confirmed) who.set(identity(session), session);
34
64
  if (!who.size) return;
65
+ for (const [agent, session] of who) takeUnfollowed(agent, session);
35
66
  for (const p of await ctx.status()) {
36
67
  const agent = p.subscribers.find((s) => who.has(s));
37
68
  if (!agent || followed.has(p.page)) continue;
@@ -63,11 +94,15 @@ async function channel(ctx) {
63
94
  /** The plugin brought these answers into their session. */
64
95
  const received = (ids, session) => {
65
96
  const agent = identity(session);
66
- const { events } = read(ctx.eventsFile);
67
- const had = receivedBy(events, agent);
68
- for (const id of ids) {
69
- const e = events.find((x) => x.id === id);
70
- if (e && !had.has(id)) receive(ctx.eventsFile, e, agent);
97
+ for (const log of new Set(ids.map((id) => logOf.get(id) ?? ctx.eventsFile))) {
98
+ const { events } = read(log);
99
+ const had = receivedBy(events, agent);
100
+ for (const id of ids) {
101
+ if ((logOf.get(id) ?? ctx.eventsFile) !== log) continue;
102
+ const e = events.find((x) => x.id === id);
103
+ if (e && !had.has(id)) receive(log, e, agent);
104
+ logOf.delete(id);
105
+ }
71
106
  }
72
107
  };
73
108
  const round = () => follow().catch((err) => problem("finding the sessions’ pages failed", String(err)));
@@ -1,4 +1,5 @@
1
1
  import { identity, stopReminder, workpadCommand } from "../../src/agents.js";
2
+ import { recordTurn } from "../../src/turns.js";
2
3
  import { channel } from "./channel.js";
3
4
  import { shimSource } from "./shim.js";
4
5
  import fs from "node:fs";
@@ -16,6 +17,7 @@ function opencode() {
16
17
  async run(ctx) {
17
18
  if (ctx.positionals[0] !== "stop") throw new Error("usage: workpad opencode hook stop");
18
19
  try {
20
+ recordTurn(ctx.project.wp, identity(session()), true);
19
21
  const left = await stopReminder(ctx, identity(session()));
20
22
  if (left) console.log(JSON.stringify(left));
21
23
  } catch (err) {
@@ -15,7 +15,7 @@ const identity = (session) => process.env.WORKPAD_AGENT || session;
15
15
  /** The one listen for these pages, stopping at the first answer: a --page each. */
16
16
  const waitOn = (pages) => `workpad listen --wait ${pages.map((p) => `--page ${relFile(p.file)}`).join(" ")}`;
17
17
  /** For a page nobody listens on: a channel the session has may bring the answers instead. */
18
- const PING = "run `workpad agent ping` if you haven't this session (answers may come to you); else";
18
+ const PING = "run `workpad agent ping --wait` in the background if you haven't this session (answers may come to you; it ends when you confirmed the pong, or when none came); else";
19
19
  /**
20
20
  * A turn of `session` ends: nothing when its pages have nothing left for it; else what to tell the
21
21
  * agent to do before it ends its turn (`reason`), and what is open in one line, for the reader (`shown`).
@@ -76,6 +76,11 @@ const NPX = ["npx", "@bigmistqke/workpad"];
76
76
  const pong = (code) => `workpad: pong. Answers on your workpad pages will reach you like this message did, and count as received once they do: no \`workpad listen\` needs to run for them (\`workpad listen --channel\` makes more pages yours). Run \`workpad agent ping ${code}\` to confirm.`;
77
77
  /** An answer a channel pushes into its session, in one line: the page, what the reader did, how to see its question. */
78
78
  const answerLine = (e, again = false) => `${e.page}: ${describe(e)}${again ? " (received before, not handled yet)" : ""} (id ${e.id}; \`workpad thread ${e.id}\` shows it with its question)`;
79
+ /**
80
+ * An answer a channel brings from a page no one follows (`workpad listen --unfollowed --channel`):
81
+ * as answerLine, and under the shared server, the project it is in, where its commands run.
82
+ */
83
+ const unfollowedLine = (e, again, from) => `${answerLine(e, again)}, on a page no one follows${from ? `, in ${from.project} (${from.url}): run its workpad commands there` : ""}`;
79
84
  /** What to do about answers a channel brought: the same for every agent. */
80
85
  const ANSWERS_NOTE = "Act on each as on an answer from `workpad listen`. Then handle it with one of: a reply in its chat (`workpad append`), when you have something to say; else `workpad handled <id>`. Nothing more is needed.";
81
- export { ANSWERS_NOTE, answerLine, describe, identity, pong, stopReminder, workpadCommand };
86
+ export { ANSWERS_NOTE, answerLine, describe, identity, pong, stopReminder, unfollowedLine, workpadCommand };
@@ -1419,9 +1419,32 @@ function trackBoard() {
1419
1419
  applyBoard(view);
1420
1420
  applySearch();
1421
1421
  });
1422
+ document.addEventListener("toggle", (e) => {
1423
+ const fold = e.target;
1424
+ if (fold.dataset?.wpFiles && fold.open) loadFiles(fold);
1425
+ }, true);
1422
1426
  applyBoard(chosen());
1423
1427
  trackSearch();
1424
1428
  }
1429
+ async function loadFiles(fold) {
1430
+ if (fold.dataset.wpLoaded) return;
1431
+ fold.dataset.wpLoaded = "loading";
1432
+ const count = fold.querySelector("summary .wp-meta");
1433
+ if (count) count.textContent = "…";
1434
+ try {
1435
+ const res = await fetch(`/api/files?base=${encodeURIComponent(fold.dataset.wpFiles)}`);
1436
+ const body = await res.json();
1437
+ if (!res.ok) throw new Error(body.error ?? res.statusText);
1438
+ if (count) count.textContent = String(body.count);
1439
+ fold.insertAdjacentHTML("beforeend", body.count ? body.html : "<p class=\"wp-meta\">No markdown files.</p>");
1440
+ fold.dataset.wpLoaded = "yes";
1441
+ applySearch();
1442
+ } catch (err) {
1443
+ delete fold.dataset.wpLoaded;
1444
+ if (count) count.textContent = "";
1445
+ fold.insertAdjacentHTML("beforeend", `<p class="wp-meta">Couldn't list the files: ${String(err.message)}</p>`);
1446
+ }
1447
+ }
1425
1448
  // src/client/page/sticky.ts
1426
1449
  function place$1(body) {
1427
1450
  const nav = document.querySelector(".wp-nav");
@@ -1,4 +1,4 @@
1
- import { HANDLED, NAME, RECEIVED, SUBSCRIBE, UNSUBSCRIBE, channelSince, fromReader, handledIds, namesOf, receivedIds, subscriptions } from "./status.js";
1
+ import { HANDLED, NAME, RECEIVED, SUBSCRIBE, UNSUBSCRIBE, channelSince, fromReader, handledIds, namesOf, receivedIds, subscriptions, takesUnfollowed } from "./status.js";
2
2
  import fs from "node:fs";
3
3
  import crypto from "node:crypto";
4
4
  // src/events.ts
@@ -276,7 +276,7 @@ const forAgent = (handedOut = /* @__PURE__ */ new Set()) => (type) => !type.incl
276
276
  * `follow`, or when `signal` aborts.
277
277
  */
278
278
  function handOut(file, filter, onEvent, options = {}) {
279
- const { count = Infinity, follow: following = true, interval, signal, forAgent: isForAgent = forAgent(), batch = false, mark = true, agent = null, skipReceivedBefore } = options;
279
+ const { count = Infinity, follow: following = true, interval, signal, forAgent: isForAgent = forAgent(), batch = false, mark = true, agent = null, skipReceivedBefore, readerOnly = false, notReceivedByOthers = false } = options;
280
280
  return new Promise((resolve) => {
281
281
  let got = 0;
282
282
  let stop = () => {};
@@ -285,7 +285,7 @@ function handOut(file, filter, onEvent, options = {}) {
285
285
  signal?.removeEventListener("abort", finish);
286
286
  resolve(got);
287
287
  };
288
- const fromOthers = (e) => fromReader(e) || !!e.by && e.by !== agent;
288
+ const fromOthers = (e) => fromReader(e) || !readerOnly && !!e.by && e.by !== agent;
289
289
  const wanted = (e) => fromOthers(e) && matches(e, filter) && (!!filter.type || isForAgent(e.type));
290
290
  let before = /* @__PURE__ */ new Set();
291
291
  const hand = (e) => {
@@ -297,12 +297,13 @@ function handOut(file, filter, onEvent, options = {}) {
297
297
  const { events, end } = read(file);
298
298
  const handled = handledIds(events);
299
299
  before = receivedBy(events, agent);
300
+ const others = notReceivedByOthers ? new Set(events.filter((e) => e.type === "workpad:received" && !fromReader(e) && (e.by ?? null) !== agent).map((e) => String(e.data?.event))) : /* @__PURE__ */ new Set();
300
301
  let skipping = !!skipReceivedBefore;
301
302
  const receivedAny = skipping ? receivedIds(events) : /* @__PURE__ */ new Set();
302
303
  for (const e of events) {
303
304
  if (skipping && e.id === skipReceivedBefore) skipping = false;
304
305
  if (skipping && !fromReader(e) && receivedAny.has(e.id)) continue;
305
- if (wanted(e) && !handled.has(e.id) && !hand(e)) return finish();
306
+ if (wanted(e) && !handled.has(e.id) && !others.has(e.id) && !hand(e)) return finish();
306
307
  }
307
308
  if (batch && got) return finish();
308
309
  if (!following) return finish();
@@ -319,4 +320,4 @@ function receivedBy(events, agent) {
319
320
  for (const e of events) if (e.type === "workpad:received" && e.from === "cli" && (e.by ?? null) === agent && typeof e.data?.event === "string") ids.add(e.data.event);
320
321
  return ids;
321
322
  }
322
- export { HANDLED, NAME, RECEIVED, SUBSCRIBE, UNSUBSCRIBE, appendEvent, channelSince, editEvent, follow, forAgent, fromReader, handOut, handle, handledIds, isEventId, matches, namesOf, parseLines, prune, read, readEvents, receive, receivedBy, receivedIds, rewrite, subscriptions };
323
+ export { HANDLED, NAME, RECEIVED, SUBSCRIBE, UNSUBSCRIBE, appendEvent, channelSince, editEvent, follow, forAgent, fromReader, handOut, handle, handledIds, isEventId, matches, namesOf, parseLines, prune, read, readEvents, receive, receivedBy, receivedIds, rewrite, subscriptions, takesUnfollowed };
package/dist/src/help.js CHANGED
@@ -18,7 +18,7 @@ const COMMAND_HELP = {
18
18
  details: "Subfolders are fine (task/plan). Whoever runs it (--agent, WORKPAD_AGENT, a plugin's session) is subscribed to the page."
19
19
  },
20
20
  agent: {
21
- usage: "[name <name> | name --clear | list | unsubscribe <agent> [--page <p>…] | ping [<code>]]",
21
+ usage: "[name <name> | name --clear | list | unsubscribe <agent> [--page <p>…] | ping [<code> | --wait [--timeout <s>]]]",
22
22
  summary: "who you are on the boards: your id and name; name yourself, see who else is around, check a channel reaches you",
23
23
  details: `Your id is --agent, else WORKPAD_AGENT, else the session an agent plugin names (claude(),
24
24
  opencode()). Alone, it says your id and your name.
@@ -34,7 +34,11 @@ opencode()). Alone, it says your id and your name.
34
34
  into the session, the way answers will, with the code to confirm with. Once
35
35
  confirmed, the channel listens on your pages, and the answers it brings count
36
36
  as received. No channel (exit 1), or no pong: nothing brings answers here, so
37
- listen for them.`
37
+ listen for them. --wait: run it in the background; it pings and ends when
38
+ the pong is confirmed (exit 0), or --timeout seconds (120) after the
39
+ session's turn ended without one (exit 1): then listen. A pong comes only
40
+ once the turn ends, so it waits while the turn runs, 30 minutes at most;
41
+ where its plugin records no turn ends, it counts from the ping.`
38
42
  },
39
43
  show: {
40
44
  usage: "<page|file> [<anchor>]",
@@ -129,13 +133,14 @@ One chat's messages: workpad chat prune <page|file> <chat>.`
129
133
  --follow then print each new one as it comes`
130
134
  },
131
135
  listen: {
132
- usage: "[--page <p>…] [--type <t>] [--wait [--timeout <s>] | --channel] [--agent <who>]",
136
+ usage: "[--page <p>… | --unfollowed] [--type <t>] [--wait [--timeout <s>] | --channel] [--agent <who>]",
133
137
  summary: "print what you haven't handled on the pages (the reader's answers, other agents' messages) and each as it comes; --wait stops at the first, --channel hands over to your channel",
134
138
  details: `${FILTERS}
135
139
  --page again several pages in one listen: it listens on each, and takes what comes on any
136
140
  --wait stop once it printed: all there are, or with none, the first to come
137
141
  --timeout <seconds> with --wait: exit 2 when nothing came
138
142
  --channel make the pages yours and exit: your session's channel brings their answers
143
+ --unfollowed the pages no live session follows, for a coordinator: see below
139
144
  --agent <who> who listens (else WORKPAD_AGENT, else the session an agent plugin names)
140
145
 
141
146
  It prints, one line each, everything on the page you haven't handled, also from before it started,
@@ -151,7 +156,16 @@ answers to handle, chats waiting for your reply, questions still unanswered.
151
156
 
152
157
  Any number listen on a page, and each hears everything there but its own events: agents can talk
153
158
  to each other in the same chats. Without --page it listens on every page (in a project of the
154
- machine's entries, every page of the entry).`
159
+ machine's entries, every page of the entry).
160
+
161
+ --unfollowed is for a coordinator, so no page swallows an answer: it listens on every page no live
162
+ session follows (in a project of the machine's entries, in every project of the entry, each line
163
+ with its \`project\` and \`url\`), and hands out the reader's answers there that no other agent
164
+ received. Following is listening now: a running listen on the page, or a confirmed channel of a
165
+ session it belongs to; a subscriber that is gone, between turns, or whose channel was never
166
+ confirmed follows nothing. A page drops out while someone follows it, and joins when its last
167
+ follower goes, as do new pages. What it hands out counts as received by you. With --channel your
168
+ confirmed channel takes these pages on (none becomes yours) and it exits.`
155
169
  },
156
170
  append: {
157
171
  usage: "--page <p> --type <t> [--data <json>]",
package/dist/src/hub.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { filesFold } from "./pages/render.js";
1
2
  import { project } from "./config.js";
2
3
  import { followEntries, machineDir, readMachineConfig, stateDir } from "./entries.js";
3
4
  import { VERSION, compareVersions } from "./package.js";
@@ -11,6 +12,19 @@ function createHub({ dir = machineDir(), state = stateDir(), home, interval, onS
11
12
  let origins = [];
12
13
  const allowed = () => origins;
13
14
  const entryListens = /* @__PURE__ */ new Set();
15
+ const unfollowedListens = /* @__PURE__ */ new Set();
16
+ function takeOn(s, ul) {
17
+ if (ul.held.has(s) || ul.entry && s.entry !== ul.entry) return;
18
+ ul.held.set(s, s.server.unfollowed(ul.listener, (pages) => {
19
+ ul.pages.set(s, pages);
20
+ ul.tell();
21
+ }));
22
+ }
23
+ function letGo(s, ul) {
24
+ ul.held.get(s)?.();
25
+ ul.held.delete(s);
26
+ if (ul.pages.delete(s)) ul.tell();
27
+ }
14
28
  /** An entry listen held on one of its projects, so the project's pages say it listens. */
15
29
  function hold(s, el) {
16
30
  if (!el.held.has(s)) el.held.set(s, s.server.addListener(el.listener));
@@ -33,6 +47,7 @@ function createHub({ dir = machineDir(), state = stateDir(), home, interval, onS
33
47
  const wanted = new Map(projects.map((p) => [`${p.base}\n${p.dir}\n${p.files ?? ""}`, p]));
34
48
  for (const [key, s] of served) if (!wanted.has(key)) {
35
49
  for (const el of entryListens) release(s, el);
50
+ for (const ul of unfollowedListens) letGo(s, ul);
36
51
  s.server.close();
37
52
  served.delete(key);
38
53
  console.log(`workpad: ${s.base} is gone (${s.dir})`);
@@ -56,6 +71,7 @@ function createHub({ dir = machineDir(), state = stateDir(), home, interval, onS
56
71
  };
57
72
  served.set(key, s);
58
73
  for (const el of entryListens) if (el.entry === p.entry) hold(s, el);
74
+ for (const ul of unfollowedListens) takeOn(s, ul);
59
75
  console.log(`workpad: ${p.base} → ${p.dir}`);
60
76
  }
61
77
  for (const el of entryListens) el.tell();
@@ -134,14 +150,15 @@ function createHub({ dir = machineDir(), state = stateDir(), home, interval, onS
134
150
  title: p.title,
135
151
  url: `${s.base}/${p.page.split("/").map(encodeURIComponent).join("/")}`,
136
152
  mtime: mtimeOf(p.file),
153
+ updated: Math.max(mtimeOf(p.file), p.updated ? Date.parse(p.updated) : 0),
137
154
  open: p.open,
138
155
  unread: p.unread.length,
139
156
  unreceived: p.unreceived.length
140
- })).toSorted((a, b) => b.mtime - a.mtime);
157
+ })).toSorted((a, b) => b.updated - a.updated);
141
158
  return {
142
159
  ...at,
143
160
  pages,
144
- active: pages[0]?.mtime ?? 0
161
+ active: pages[0]?.updated ?? 0
145
162
  };
146
163
  }
147
164
  const index = () => Promise.all([...served.values()].map(indexOf));
@@ -205,6 +222,7 @@ function createHub({ dir = machineDir(), state = stateDir(), home, interval, onS
205
222
  setImmediate(() => onShutdown?.());
206
223
  return;
207
224
  }
225
+ if (p === "/api/listen" && url.searchParams.has("unfollowed")) return listenUnfollowed(req, res, url.searchParams);
208
226
  if (p === "/api/listen" && url.searchParams.has("entry")) return listenEntry(req, res, url.searchParams);
209
227
  const what = /^\/api\/(\w+)$/.exec(p)?.[1];
210
228
  if (req.method === "GET" && what && API_LISTS.includes(what)) {
@@ -213,6 +231,12 @@ function createHub({ dir = machineDir(), state = stateDir(), home, interval, onS
213
231
  return sendJson(res, 200, all.flat());
214
232
  }
215
233
  if (p === "/api/stream") return streamAll(req, res, Object.fromEntries(url.searchParams));
234
+ if (p === "/api/files") {
235
+ const s = [...served.values()].find((x) => x.base === url.searchParams.get("base"));
236
+ if (!s) return sendJson(res, 404, { error: "no such project" });
237
+ if (!await s.server.files().catch(() => false)) return sendJson(res, 403, { error: "its files are not served" });
238
+ return sendJson(res, 200, await filesFold(s.dir, s.base));
239
+ }
216
240
  if (p === "/favicon.ico") {
217
241
  res.writeHead(204);
218
242
  res.end();
@@ -283,6 +307,42 @@ function createHub({ dir = machineDir(), state = stateDir(), home, interval, onS
283
307
  el.tell();
284
308
  }
285
309
  const closers = /* @__PURE__ */ new Set();
310
+ /**
311
+ * A listen on the pages no one follows (`workpad listen --unfollowed`), across every project or
312
+ * one entry's: each project holds it on those of its pages (WorkpadServer.unfollowed), and its
313
+ * stream is told them all, once for several changes.
314
+ */
315
+ function listenUnfollowed(req, res, q) {
316
+ let telling = false;
317
+ const ul = {
318
+ entry: q.get("entry"),
319
+ listener: listenerOf(q),
320
+ held: /* @__PURE__ */ new Map(),
321
+ pages: /* @__PURE__ */ new Map(),
322
+ tell: () => {
323
+ if (telling) return;
324
+ telling = true;
325
+ setImmediate(() => {
326
+ telling = false;
327
+ const projects = [...ul.pages].filter(([, pages]) => pages.length).map(([s, pages]) => ({
328
+ dir: s.dir,
329
+ base: s.base,
330
+ pages
331
+ }));
332
+ stream.send("pages", { projects });
333
+ });
334
+ }
335
+ };
336
+ const stream = holdStream(req, res, () => {
337
+ closers.delete(stream.end);
338
+ unfollowedListens.delete(ul);
339
+ for (const s of [...ul.held.keys()]) letGo(s, ul);
340
+ });
341
+ closers.add(stream.end);
342
+ unfollowedListens.add(ul);
343
+ for (const s of served.values()) takeOn(s, ul);
344
+ ul.tell();
345
+ }
286
346
  /** /api/stream across every project: as a project's, each event with its project. */
287
347
  function streamAll(req, res, query) {
288
348
  res.writeHead(200, {
@@ -12,13 +12,17 @@ const get = (url, onResponse) => (url.startsWith("https:") ? https : http).get(u
12
12
  * Resolves once the server holds it; with `orNone`, also after a first try that found no server
13
13
  * running (a listen reads the log all the same, and registers once one appears).
14
14
  */
15
- function listen({ at, query, onSnapshot }, { orNone = false } = {}) {
15
+ function listen({ at, query, onSnapshot, onPages, signal }, { orNone = false } = {}) {
16
16
  return new Promise((settled) => {
17
+ let current = null;
18
+ signal?.addEventListener("abort", () => current?.destroy());
17
19
  const connect = async () => {
20
+ if (signal?.aborted) return settled();
18
21
  let base = null;
19
22
  try {
20
23
  base = await at();
21
24
  } catch {}
25
+ if (signal?.aborted) return settled();
22
26
  if (!base) {
23
27
  if (orNone) settled();
24
28
  return setTimeout(connect, 2e3).unref();
@@ -30,7 +34,7 @@ function listen({ at, query, onSnapshot }, { orNone = false } = {}) {
30
34
  setTimeout(connect, ms).unref();
31
35
  }
32
36
  };
33
- get(`${base}/api/listen?${new URLSearchParams(query)}`, (res) => {
37
+ (current = get(`${base}/api/listen?${new URLSearchParams(query)}`, (res) => {
34
38
  res.setEncoding("utf8");
35
39
  settled();
36
40
  res.socket.unref();
@@ -44,10 +48,11 @@ function listen({ at, query, onSnapshot }, { orNone = false } = {}) {
44
48
  const event = /^event: (.*)$/m.exec(block)?.[1];
45
49
  const data = /^data: (.*)$/m.exec(block)?.[1];
46
50
  if (event === "projects" && data && onSnapshot) onSnapshot(JSON.parse(data));
51
+ if (event === "pages" && data && onPages) onPages(JSON.parse(data));
47
52
  }
48
53
  });
49
54
  res.on("close", () => retry(1e3));
50
- }).on("error", () => retry(2e3));
55
+ })).on("error", () => retry(2e3));
51
56
  };
52
57
  connect();
53
58
  });
@@ -73,6 +78,33 @@ function everyProject(start) {
73
78
  };
74
79
  }
75
80
  /**
81
+ * A listen on the unfollowed pages: `start` is called once for each page as it joins, to hand out
82
+ * from its project's log; a page that drops out (someone follows it now) is stopped (`signal`).
83
+ * @returns what takes each list of pages the server sends
84
+ */
85
+ function everyPage(start) {
86
+ const taken = /* @__PURE__ */ new Map();
87
+ return ({ projects }) => {
88
+ const now = /* @__PURE__ */ new Set();
89
+ for (const p of projects) for (const page of p.pages) {
90
+ const key = `${p.dir}\n${page}`;
91
+ now.add(key);
92
+ if (taken.has(key)) continue;
93
+ const stop = new AbortController();
94
+ taken.set(key, stop);
95
+ start({
96
+ dir: p.dir,
97
+ base: p.base,
98
+ page
99
+ }, stop.signal);
100
+ }
101
+ for (const [key, stop] of taken) if (!now.has(key)) {
102
+ stop.abort();
103
+ taken.delete(key);
104
+ }
105
+ };
106
+ }
107
+ /**
76
108
  * Hold an agent channel's line at the server (/api/channel) for as long as the process runs, and
77
109
  * again after the server restarts, then saying it was confirmed: the server forgets that. `move`:
78
110
  * the session it serves changed (a resume); it was confirmed for the process, not the session, so
@@ -129,4 +161,4 @@ function holdChannel(at, first, { onPing, onConfirmed }) {
129
161
  current?.destroy();
130
162
  } };
131
163
  }
132
- export { everyProject, holdChannel, listen };
164
+ export { everyPage, everyProject, holdChannel, listen };
@@ -7,10 +7,11 @@ function createRegistry() {
7
7
  for (const fn of watchers) fn();
8
8
  };
9
9
  return {
10
- list: (page = null) => [...listeners].filter((l) => page == null || covers(l, page)).map(({ page, type, agent }) => ({
10
+ list: (page = null) => [...listeners].filter((l) => page == null || covers(l, page)).map(({ page, type, agent, unfollowed }) => ({
11
11
  page,
12
12
  type,
13
- agent
13
+ agent,
14
+ ...unfollowed && { unfollowed }
14
15
  })),
15
16
  add(l) {
16
17
  listeners.add(l);
@@ -29,9 +30,18 @@ function createRegistry() {
29
30
  const listenerOf = (q) => ({
30
31
  page: q.get("page") || "",
31
32
  type: q.get("type") || null,
32
- agent: q.get("agent") || null
33
+ agent: q.get("agent") || null,
34
+ ...q.has("unfollowed") && { unfollowed: true }
33
35
  });
34
36
  /**
37
+ * Does `l` follow `page`: is someone there to take whatever comes on it? A listener covering the
38
+ * page, for every type: a running listen on it (or above it, or on every page), and a confirmed
39
+ * channel, which holds one on each page of its session's. A listen for one form only (`--type`)
40
+ * leaves the rest to no one, and a listen on the unfollowed pages follows nothing itself. A
41
+ * subscriber listening nowhere (gone, between turns, or a channel never confirmed) is no listener.
42
+ */
43
+ const follows = (l, page) => !l.unfollowed && !l.type && covers(l, page);
44
+ /**
35
45
  * Hold a /api/listen connection open as an event stream (with a ping, so nothing between closes it
36
46
  * as idle). `send` writes an event on it; `onEnd` runs once, when the agent goes or `end` is called.
37
47
  */
@@ -61,4 +71,4 @@ function holdStream(req, res, onEnd) {
61
71
  }
62
72
  };
63
73
  }
64
- export { createRegistry, holdStream, listenerOf };
74
+ export { createRegistry, follows, holdStream, listenerOf };
@@ -7,6 +7,11 @@ const waitingOn = (p) => ({
7
7
  unreceived: p.unreceived
8
8
  });
9
9
  const total = (w) => w.open + w.unread + w.unreceived;
10
+ /**
11
+ * How much a card needs the reader: something waiting on it first, then the newest update (its file,
12
+ * or an agent's message or question on it) first.
13
+ */
14
+ const byAttention = (a, b) => Number(total(b.waiting) > 0) - Number(total(a.waiting) > 0) || b.page.updated - a.page.updated;
10
15
  /** Every project's pages by state, each column newest first. */
11
16
  function byState(projects, now, activeFor = ACTIVE_FOR) {
12
17
  const columns = {
@@ -20,13 +25,13 @@ function byState(projects, now, activeFor = ACTIVE_FOR) {
20
25
  project,
21
26
  waiting: waitingOn(page)
22
27
  };
23
- columns[total(card.waiting) > 0 ? "waiting" : now - page.mtime <= activeFor ? "active" : "quiet"].push(card);
28
+ columns[total(card.waiting) > 0 ? "waiting" : now - page.updated <= activeFor ? "active" : "quiet"].push(card);
24
29
  }
25
30
  for (const cards of [
26
31
  columns.waiting,
27
32
  columns.active,
28
33
  columns.quiet
29
- ]) cards.sort((a, b) => b.page.mtime - a.page.mtime);
34
+ ]) cards.sort(byAttention);
30
35
  return columns;
31
36
  }
32
37
  /** The projects with pages, a column each, the one changed last first. */
@@ -36,7 +41,7 @@ function byProject(projects) {
36
41
  page,
37
42
  project,
38
43
  waiting: waitingOn(page)
39
- })).sort((a, b) => b.page.mtime - a.page.mtime);
44
+ })).sort(byAttention);
40
45
  return {
41
46
  project,
42
47
  cards,
@@ -56,4 +61,4 @@ function byProject(projects) {
56
61
  function withoutPages(projects) {
57
62
  return projects.filter((p) => !p.pages.length).toSorted((a, b) => a.label.localeCompare(b.label));
58
63
  }
59
- export { ACTIVE_FOR, byProject, byState, total, waitingOn, withoutPages };
64
+ export { ACTIVE_FOR, byAttention, byProject, byState, total, waitingOn, withoutPages };