@bigmistqke/workpad 0.18.1 → 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 (55) hide show
  1. package/bin/workpad.ts +225 -21
  2. package/dist/bin/workpad.js +181 -15
  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 +6 -1
  15. package/dist/src/events.js +6 -5
  16. package/dist/src/help.js +16 -4
  17. package/dist/src/hub.js +55 -2
  18. package/dist/src/listen.js +36 -4
  19. package/dist/src/listeners.js +14 -4
  20. package/dist/src/pages/board.js +9 -4
  21. package/dist/src/pages/index.js +2 -4
  22. package/dist/src/pages/markdown.js +47 -16
  23. package/dist/src/pages/render.js +1 -1
  24. package/dist/src/server.js +69 -6
  25. package/dist/src/state.js +2 -1
  26. package/dist/src/status.js +11 -2
  27. package/dist/src/turns.js +41 -0
  28. package/package.json +6 -1
  29. package/plugins/badge/README.md +59 -10
  30. package/plugins/badge/index.ts +141 -8
  31. package/plugins/badge/public/style.css +132 -12
  32. package/plugins/chat/index.ts +9 -1
  33. package/plugins/claude/README.md +13 -5
  34. package/plugins/claude/channel.ts +26 -2
  35. package/plugins/claude/doctor.ts +58 -39
  36. package/plugins/claude/index.ts +30 -8
  37. package/plugins/claude/session.ts +32 -0
  38. package/plugins/opencode/channel.ts +42 -7
  39. package/plugins/opencode/index.ts +4 -0
  40. package/skills/workpad/SKILL.md +23 -3
  41. package/src/agents.ts +7 -0
  42. package/src/define.ts +28 -1
  43. package/src/events.ts +23 -2
  44. package/src/help.ts +16 -4
  45. package/src/hub.ts +71 -2
  46. package/src/listen.ts +47 -4
  47. package/src/listeners.ts +22 -1
  48. package/src/pages/board.ts +10 -3
  49. package/src/pages/index.ts +8 -10
  50. package/src/pages/markdown.ts +55 -8
  51. package/src/pages/render.ts +1 -1
  52. package/src/server.ts +84 -6
  53. package/src/state.ts +3 -0
  54. package/src/status.ts +15 -1
  55. package/src/turns.ts +56 -0
package/bin/workpad.ts CHANGED
@@ -28,6 +28,7 @@ import {
28
28
  receivedIds,
29
29
  channelSince,
30
30
  subscriptions,
31
+ takesUnfollowed,
31
32
  UNSUBSCRIBE,
32
33
  } from '../src/events.ts'
33
34
  import { BUILTIN_COMMANDS, createConfigLoader, pluginDir } from '../src/loader.ts'
@@ -62,7 +63,8 @@ import { compareVersions, VERSION } from '../src/package.ts'
62
63
  import { statusLines, whose } from '../src/status.ts'
63
64
  import { holdForms, releaseForms, settleForms } from '../src/formstate.ts'
64
65
  import { client, probe } from '../src/api.ts'
65
- import { everyProject, holdChannel, listen } from '../src/listen.ts'
66
+ import { everyPage, everyProject, holdChannel, listen } from '../src/listen.ts'
67
+ import { lastTurnEnd } from '../src/turns.ts'
66
68
  import type { Listener, PageStatus, WpEvent } from '../src/define.ts'
67
69
 
68
70
  // a failing command prints its message, not a stack trace
@@ -127,6 +129,7 @@ const { values: opts, positionals } =
127
129
  clear: { type: 'boolean' },
128
130
  wait: { type: 'boolean' },
129
131
  channel: { type: 'boolean' },
132
+ unfollowed: { type: 'boolean' },
130
133
  all: { type: 'boolean' },
131
134
  },
132
135
  })
@@ -160,6 +163,9 @@ Run \`workpad init\` in the folder that should become one.`)
160
163
 
161
164
  const filter = (): EventFilter => ({ page: pageOpt ? pageId(needProject(), pageOpt) : undefined, type: opts.type })
162
165
 
166
+ /** The longest `workpad agent ping --wait` waits, turn or no turn: a background process never lingers. */
167
+ const MAX_WAIT = 30 * 60_000
168
+
163
169
  /** The running server of this project: the URL it is served at, or null (see projectServer). */
164
170
  const running = (proj: Project): Promise<string | null> => projectServer(proj)
165
171
 
@@ -337,16 +343,39 @@ function hasPages(dir: string): boolean {
337
343
  /**
338
344
  * Ask the project's server. Without one running, a server made for this one question answers it,
339
345
  * in this process, on no port: a command that only asks (status, docs, the hooks on every prompt)
340
- * never starts one. It has no listeners, as no server runs to hold them.
346
+ * never starts one. It has no listeners, as no server runs to hold them. A server that runs but is
347
+ * busy is waited for (`runningOrBusy`): answered in this process, its listeners would be missed.
341
348
  */
342
349
  async function api(route: string): Promise<any> {
343
- const base = await running(needProject())
350
+ const base = await runningOrBusy(needProject())
344
351
  const res = base ? await fetch(`${base}${route}`) : await askInProcess(route)
345
352
  const body = await res.json()
346
353
  if (!res.ok) throw new Error(body.error ?? res.statusText)
347
354
  return body
348
355
  }
349
356
 
357
+ /** How long a command waits for a server too busy to answer (a status over many pages can take seconds). */
358
+ const BUSY_WAIT = 30_000
359
+
360
+ /**
361
+ * The running server of `proj`, or null when none runs. One that accepts connections and gives its
362
+ * health check no answer in time is busy, its event loop blocked by a slow request: it is waited
363
+ * for, up to BUSY_WAIT, then said to be stuck. Taken for none, a question would be answered without
364
+ * it, by a server in this process that knows nobody who listens.
365
+ */
366
+ async function runningOrBusy(proj: Project): Promise<string | null> {
367
+ const base = await running(proj)
368
+ if (base) return base
369
+ const shared = isShared(proj)
370
+ const at = recordedOrigin(shared ? machineServerFile() : proj.serverFile)
371
+ if (!at) return null
372
+ const deadline = Date.now() + BUSY_WAIT
373
+ while (await stuckAt(at))
374
+ if (Date.now() > deadline) throw new Error(stuck(at, shared ? 'its login service log' : proj.logFile))
375
+ // it answers now (or nothing is there): whether it is this project's
376
+ return running(proj)
377
+ }
378
+
350
379
  async function askInProcess(route: string): Promise<Response> {
351
380
  // a project without pages has nothing open: no need to load its config to say so (the hooks ask
352
381
  // on every prompt, in every project, most of which have no pages)
@@ -660,7 +689,11 @@ switch (cmd) {
660
689
  const subscribed = new Map<string, string[]>()
661
690
  const seen = new Set<string>()
662
691
  for (const e of events) if (e.by) seen.add(e.by)
663
- for (const e of subscriptions(events)) subscribed.set(e.by!, [...(subscribed.get(e.by!) ?? []), e.page || 'every page'])
692
+ for (const e of subscriptions(events))
693
+ subscribed.set(e.by!, [
694
+ ...(subscribed.get(e.by!) ?? []),
695
+ e.data?.unfollowed ? 'the pages no one follows (through its channel)' : e.page || 'every page',
696
+ ])
664
697
  const listening = new Map<string, string[]>()
665
698
  const base = await running(proj)
666
699
  if (base)
@@ -710,6 +743,7 @@ switch (cmd) {
710
743
  const code = arg
711
744
  if (!code && !me) throw nobody()
712
745
  const base = await ensureServer()
746
+ const pinged = Date.now()
713
747
  const res = await fetch(`${base}/api/ping`, {
714
748
  method: 'POST',
715
749
  headers: { 'content-type': 'application/json' },
@@ -737,21 +771,41 @@ switch (cmd) {
737
771
  else if (body.confirmed) console.log(`answers on your pages come to you already, through this session’s channel.${await covers()}`)
738
772
  else if (body.sent && opts.wait) {
739
773
  // run in the background: it ends, and so wakes the agent, when the pong it pushed is confirmed,
740
- // or when none came in time: then nothing brings answers here, and the agent listens instead
774
+ // or when none came in time: then nothing brings answers here, and the agent listens instead.
775
+ // The pong can't come before the session's turn ends, and the agent works on meanwhile: so
776
+ // the timeout counts from the first turn end after the ping, as its plugin's hook records it
777
+ // (turns.ts). A session whose turn ends aren't recorded counts from the ping. Either way it
778
+ // gives up after MAX_WAIT, so it never lingers.
741
779
  console.log('pinged this session’s channel: a pong comes to you as a message; confirm it with the command it names')
742
- const limit = Date.now() + (opts.timeout ? Number(opts.timeout) * 1000 : 120_000)
743
- while (Date.now() < limit) {
780
+ const timeout = opts.timeout ? Number(opts.timeout) * 1000 : 120_000
781
+ const giveUp = pinged + MAX_WAIT
782
+ const secs = `${Math.round(timeout / 1000)} s`
783
+ /** the first turn end after the ping, once seen: the one a pong would have come at */
784
+ let ended: number | null = null
785
+ for (;;) {
744
786
  await new Promise(r => setTimeout(r, 1000))
745
787
  const channels = (await api('/api/channels')) as { session: string | null; confirmed: boolean }[]
746
788
  if (channels.some(c => c.session === me && c.confirmed)) {
747
789
  console.log(`confirmed: answers on your pages come to you now.${await covers()}`)
748
790
  process.exit(0)
749
791
  }
792
+ const turns = lastTurnEnd(proj.wp, me!)
793
+ if (ended === null && turns?.ended != null && turns.ended >= pinged) ended = turns.ended
794
+ const why =
795
+ Date.now() >= giveUp
796
+ ? `no pong came within ${MAX_WAIT / 60_000} minutes`
797
+ : ended !== null && Date.now() >= ended + timeout
798
+ ? `no pong came within ${secs} after your turn ended`
799
+ : !turns && Date.now() >= pinged + timeout
800
+ ? `no pong came within ${secs}`
801
+ : null
802
+ if (why) {
803
+ console.log(
804
+ `${why}: nothing brings answers here. Listen for them (\`workpad listen --wait --page <file>\` in the background), and in Claude Code tell the user what \`workpad claude doctor\` says is wrong`,
805
+ )
806
+ process.exit(1)
807
+ }
750
808
  }
751
- console.log(
752
- 'no pong was confirmed in time: nothing brings answers here. Listen for them (`workpad listen --wait --page <file>` in the background), and in Claude Code tell the user what `workpad claude doctor` says is wrong',
753
- )
754
- process.exit(1)
755
809
  } else if (body.sent)
756
810
  console.log(
757
811
  'pinged this session’s channel: a pong comes to you as a message, the way answers will, with the command that confirms it. It may only come once your turn has ended, so start no listen yet. Run `workpad agent ping --wait` in the background instead, and it ends when you confirmed the pong or when none came: then listen',
@@ -1183,13 +1237,20 @@ switch (cmd) {
1183
1237
  // and runs on; with --wait it prints all there are and stops, or with none, the first to come;
1184
1238
  // with --channel it hands the pages over to the session's channel and stops. Any number listen
1185
1239
  // on a page, each hearing everything. Without --page: every page (in a project of the machine's
1186
- // entries, every page of the entry).
1240
+ // entries, every page of the entry). With --unfollowed: the pages no live session follows, for a
1241
+ // coordinator (holdUnfollowed).
1187
1242
  const proj = needProject()
1188
1243
  const f = filter()
1189
1244
  const agent = await whoAmI(proj)
1190
1245
  if (opts.follow) throw new Error('listen runs on by itself: --wait stops at the first answer, --channel hands over to the channel')
1191
1246
  if (opts.wait && opts.channel) throw new Error('listen takes --wait or --channel, not both')
1192
1247
  if (opts.timeout && !opts.wait) throw new Error('--timeout goes with --wait')
1248
+ if (opts.unfollowed) {
1249
+ if (pagesGiven.length) throw new Error('--unfollowed takes the pages no one follows: no --page with it')
1250
+ if (opts.channel) await channelUnfollowed(proj, agent)
1251
+ else await unfollowedListen(proj, f.type ?? null, agent)
1252
+ break
1253
+ }
1193
1254
  if (opts.channel) {
1194
1255
  await channelListen(proj, agent)
1195
1256
  break
@@ -1398,6 +1459,8 @@ switch (cmd) {
1398
1459
  at: () => ensureServer().catch(() => null),
1399
1460
  query: { page: pageId(project, page), ...(agent ? { agent } : {}) },
1400
1461
  }),
1462
+ unfollowed: (onEvent, { agent = null, mark, signal } = {}) =>
1463
+ holdUnfollowed(project, { at: () => ensureServer().catch(() => null), agent, mark, signal, onEvent }),
1401
1464
  channel: (session, handlers) => holdChannel(() => ensureServer().catch(() => null), session, handlers),
1402
1465
  authLink: async to =>
1403
1466
  `${await ensureServer()}/_/auth?token=${encodeURIComponent(projectToken(project.wp))}&to=${encodeURIComponent(to)}`,
@@ -1429,15 +1492,8 @@ switch (cmd) {
1429
1492
  * those waiting now: so nothing is printed here, which would hand them out twice. Only for a session
1430
1493
  * whose channel is confirmed (`workpad agent ping`); else nothing is taken on.
1431
1494
  */
1432
- async function channelListen(proj: Project, agent: string | null) {
1433
- if (!agent) throw new Error('--channel needs a session: no --agent, WORKPAD_AGENT or plugin session names one')
1434
- const channels = (await api('/api/channels')) as { session: string; confirmed: boolean }[]
1435
- if (!channels.some(c => c.session === agent && c.confirmed)) {
1436
- console.error(
1437
- 'workpad: no confirmed channel brings answers to this session: run `workpad agent ping` and confirm its pong, or listen without --channel',
1438
- )
1439
- process.exit(1)
1440
- }
1495
+ async function channelListen(proj: Project, who: string | null) {
1496
+ const agent = await confirmedChannel(who)
1441
1497
  const pages = [...new Set(pagesGiven.map(p => pageId(proj, p)))]
1442
1498
  // taken on through the channel: it brings what is new, and the reader's answers still waiting;
1443
1499
  // what other agents said before that someone already received is skipped (channelSince)
@@ -1464,6 +1520,154 @@ async function channelListen(proj: Project, agent: string | null) {
1464
1520
  }
1465
1521
  }
1466
1522
 
1523
+ /** `agent`, when a confirmed channel brings answers to it; else the command ends saying so. */
1524
+ async function confirmedChannel(agent: string | null): Promise<string> {
1525
+ if (!agent) throw new Error('--channel needs a session: no --agent, WORKPAD_AGENT or plugin session names one')
1526
+ const channels = (await api('/api/channels')) as { session: string; confirmed: boolean }[]
1527
+ if (!channels.some(c => c.session === agent && c.confirmed)) {
1528
+ console.error(
1529
+ 'workpad: no confirmed channel brings answers to this session: run `workpad agent ping` and confirm its pong, or listen without --channel',
1530
+ )
1531
+ process.exit(1)
1532
+ }
1533
+ return agent
1534
+ }
1535
+
1536
+ /** Where an answer on an unfollowed page is, under the shared server: its project's folder, and its page's address. */
1537
+ interface From {
1538
+ project: string
1539
+ url: string
1540
+ }
1541
+
1542
+ /**
1543
+ * Take the pages no one follows (`workpad listen --unfollowed`): a listen held at the server, which
1544
+ * holds it on each such page and says which they are as that changes; from each, the reader's
1545
+ * answers no other agent received (not the page's own agents' messages, nor what a session took
1546
+ * and works on between turns) go to `onEvent`, received by `agent` unless `mark` is false. Under
1547
+ * the shared server the pages of every project of this one's entry, each answer with where it is
1548
+ * (`from`). `onFirst`: the pages there were at first handed out what waited on them. Resolves once
1549
+ * the server holds it, or after a first try that found none running (it holds it once one runs).
1550
+ */
1551
+ async function holdUnfollowed(
1552
+ proj: Project,
1553
+ options: {
1554
+ at: () => Promise<string | null>
1555
+ agent: string | null
1556
+ type?: string | null
1557
+ mark?: boolean
1558
+ signal?: AbortSignal
1559
+ onEvent: (e: WpEvent, again: boolean, from: From | null) => void
1560
+ onFirst?: () => void
1561
+ },
1562
+ ): Promise<void> {
1563
+ const { agent, type, mark, signal, onEvent, onFirst } = options
1564
+ const shared = isShared(proj)
1565
+ const entry = shared ? matchesEntries(readMachineConfig()!, proj.dir) : null
1566
+ let origin = ''
1567
+ const address = (id: string) => id.split('/').map(encodeURIComponent).join('/')
1568
+ // what the pages of one list read before they follow: the backlog is handed out with the handOut
1569
+ let reading: Promise<void>[] = []
1570
+ const update = everyPage((p, stop) => {
1571
+ const there = p.dir === proj.dir ? proj : projectAt(p.dir)
1572
+ if (!there) return
1573
+ reading.push(
1574
+ projectConfig(there).then(({ handedOut }) => {
1575
+ if (stop.aborted) return
1576
+ void handOut(
1577
+ there.eventsFile,
1578
+ { page: p.page, exact: true, type },
1579
+ (e, again) => onEvent(e, again, shared ? { project: p.dir, url: `${origin}${p.base}/${address(e.page)}` } : null),
1580
+ {
1581
+ forAgent: forAgent(handedOut),
1582
+ agent,
1583
+ mark,
1584
+ readerOnly: true,
1585
+ notReceivedByOthers: true,
1586
+ signal: signal ? AbortSignal.any([stop, signal]) : stop,
1587
+ },
1588
+ )
1589
+ }),
1590
+ )
1591
+ })
1592
+ let first = true
1593
+ await listen(
1594
+ {
1595
+ at: shared
1596
+ ? async () => {
1597
+ origin = (await sharedServer(machineServerFile()))?.origin ?? ''
1598
+ return origin || null
1599
+ }
1600
+ : options.at,
1601
+ query: { unfollowed: '1', ...(entry && { entry }), ...(type && { type }), ...(agent && { agent }) },
1602
+ onPages: pages => {
1603
+ reading = []
1604
+ update(pages)
1605
+ if (!first) return
1606
+ first = false
1607
+ void Promise.all(reading).then(() => onFirst?.())
1608
+ },
1609
+ signal,
1610
+ },
1611
+ { orNone: true },
1612
+ )
1613
+ }
1614
+
1615
+ /**
1616
+ * `workpad listen --unfollowed`: the reader's answers on the pages no one follows, one line each, as
1617
+ * they come; with --wait all there are, or with none the first to come, and it stops. Under the
1618
+ * shared server each line says where it is (`project`, `url`).
1619
+ */
1620
+ async function unfollowedListen(proj: Project, type: string | null, agent: string | null) {
1621
+ if (opts.timeout && opts.wait)
1622
+ setTimeout(
1623
+ () => {
1624
+ console.error('timeout')
1625
+ process.exit(2)
1626
+ },
1627
+ Number(opts.timeout) * 1000,
1628
+ )
1629
+ let printed = 0
1630
+ // the first pages had what waited on them handed out: a --wait stops at the next one now
1631
+ let following = false
1632
+ let ending = false
1633
+ // after the last one is marked received, which follows printing it
1634
+ const end = () => {
1635
+ if (ending) return
1636
+ ending = true
1637
+ setImmediate(() => process.exit(0))
1638
+ }
1639
+ await holdUnfollowed(proj, {
1640
+ at: () => needServer().catch(() => null),
1641
+ agent,
1642
+ type,
1643
+ onEvent: (e, again, from) => {
1644
+ console.log(JSON.stringify({ ...e, ...(again && { again: true }), ...from }))
1645
+ printed++
1646
+ if (opts.wait && following) end()
1647
+ },
1648
+ onFirst: () => {
1649
+ following = true
1650
+ if (opts.wait && printed) end()
1651
+ },
1652
+ })
1653
+ // keeps the command running: the connection does not
1654
+ setInterval(() => {}, 1 << 30)
1655
+ }
1656
+
1657
+ /**
1658
+ * `workpad listen --unfollowed --channel`: the session's confirmed channel takes the pages no one
1659
+ * follows, for as long as it runs; none becomes the session's (status.ts, takesUnfollowed).
1660
+ */
1661
+ async function channelUnfollowed(proj: Project, agent: string | null) {
1662
+ const me = await confirmedChannel(agent)
1663
+ if (!takesUnfollowed(readEvents(proj.eventsFile), me))
1664
+ appendEvent(proj.eventsFile, { page: '', type: SUBSCRIBE, data: { channel: true, unfollowed: true } }, 'cli', me)
1665
+ const entry = isShared(proj) ? matchesEntries(readMachineConfig()!, proj.dir) : null
1666
+ console.log(
1667
+ `the channel brings the answers on the pages no one follows${entry ? `, in every project of ${entry}` : ''}: those waiting there first, then each as it comes; a page drops out while someone else follows it`,
1668
+ )
1669
+ }
1670
+
1467
1671
  /**
1468
1672
  * A listen over a whole entry: every page of each of its projects, from each project's own log, each
1469
1673
  * event with the project it is from (`project`, its folder) and its page's `url`. Any number run.
@@ -13,10 +13,11 @@ import { projectToken } from "../src/auth.js";
13
13
  import { PACKAGE_DIR, VERSION, compareVersions, packagePath } from "../src/package.js";
14
14
  import { alive, isShared, projectServer, recordedOrigin, recordedPid, sharedServer, stuck, stuckAt } from "../src/running.js";
15
15
  import { machineDir, machineServerFile, matchesEntries, readMachineConfig, serverPaths, stateDir } from "../src/entries.js";
16
- import { NAME, SUBSCRIBE, UNSUBSCRIBE, channelSince, fromReader, handledIds, namesOf, receivedIds, statusLines, subscriptions, whose } from "../src/status.js";
16
+ import { NAME, SUBSCRIBE, UNSUBSCRIBE, channelSince, fromReader, handledIds, namesOf, receivedIds, statusLines, subscriptions, takesUnfollowed, whose } from "../src/status.js";
17
17
  import { holdForms, releaseForms, settleForms } from "../src/formstate.js";
18
18
  import { client, probe } from "../src/api.js";
19
- import { everyProject, holdChannel, listen } from "../src/listen.js";
19
+ import { everyPage, everyProject, holdChannel, listen } from "../src/listen.js";
20
+ import { lastTurnEnd } from "../src/turns.js";
20
21
  import fs from "node:fs";
21
22
  import path from "node:path";
22
23
  import os from "node:os";
@@ -85,6 +86,7 @@ const { values: opts, positionals } = cmd && !BUILTIN_COMMANDS.has(cmd) ? {
85
86
  clear: { type: "boolean" },
86
87
  wait: { type: "boolean" },
87
88
  channel: { type: "boolean" },
89
+ unfollowed: { type: "boolean" },
88
90
  all: { type: "boolean" }
89
91
  }
90
92
  });
@@ -112,6 +114,8 @@ const filter = () => ({
112
114
  page: pageOpt ? pageId(needProject(), pageOpt) : void 0,
113
115
  type: opts.type
114
116
  });
117
+ /** The longest `workpad agent ping --wait` waits, turn or no turn: a background process never lingers. */
118
+ const MAX_WAIT = 18e5;
115
119
  /** The running server of this project: the URL it is served at, or null (see projectServer). */
116
120
  const running = (proj) => projectServer(proj);
117
121
  /**
@@ -256,15 +260,34 @@ function hasPages(dir) {
256
260
  /**
257
261
  * Ask the project's server. Without one running, a server made for this one question answers it,
258
262
  * in this process, on no port: a command that only asks (status, docs, the hooks on every prompt)
259
- * never starts one. It has no listeners, as no server runs to hold them.
263
+ * never starts one. It has no listeners, as no server runs to hold them. A server that runs but is
264
+ * busy is waited for (`runningOrBusy`): answered in this process, its listeners would be missed.
260
265
  */
261
266
  async function api(route) {
262
- const base = await running(needProject());
267
+ const base = await runningOrBusy(needProject());
263
268
  const res = base ? await fetch(`${base}${route}`) : await askInProcess(route);
264
269
  const body = await res.json();
265
270
  if (!res.ok) throw new Error(body.error ?? res.statusText);
266
271
  return body;
267
272
  }
273
+ /** How long a command waits for a server too busy to answer (a status over many pages can take seconds). */
274
+ const BUSY_WAIT = 3e4;
275
+ /**
276
+ * The running server of `proj`, or null when none runs. One that accepts connections and gives its
277
+ * health check no answer in time is busy, its event loop blocked by a slow request: it is waited
278
+ * for, up to BUSY_WAIT, then said to be stuck. Taken for none, a question would be answered without
279
+ * it, by a server in this process that knows nobody who listens.
280
+ */
281
+ async function runningOrBusy(proj) {
282
+ const base = await running(proj);
283
+ if (base) return base;
284
+ const shared = isShared(proj);
285
+ const at = recordedOrigin(shared ? machineServerFile() : proj.serverFile);
286
+ if (!at) return null;
287
+ const deadline = Date.now() + BUSY_WAIT;
288
+ while (await stuckAt(at)) if (Date.now() > deadline) throw new Error(stuck(at, shared ? "its login service log" : proj.logFile));
289
+ return running(proj);
290
+ }
268
291
  async function askInProcess(route) {
269
292
  if (route.startsWith("/api/status") && !hasPages(needProject().pagesDir)) return Response.json([]);
270
293
  const { createServer } = await import("../src/server.js");
@@ -518,7 +541,7 @@ switch (cmd) {
518
541
  const subscribed = /* @__PURE__ */ new Map();
519
542
  const seen = /* @__PURE__ */ new Set();
520
543
  for (const e of events) if (e.by) seen.add(e.by);
521
- for (const e of subscriptions(events)) subscribed.set(e.by, [...subscribed.get(e.by) ?? [], e.page || "every page"]);
544
+ for (const e of subscriptions(events)) subscribed.set(e.by, [...subscribed.get(e.by) ?? [], e.data?.unfollowed ? "the pages no one follows (through its channel)" : e.page || "every page"]);
522
545
  const listening = /* @__PURE__ */ new Map();
523
546
  const base = await running(proj);
524
547
  if (base) {
@@ -570,6 +593,7 @@ switch (cmd) {
570
593
  const code = arg;
571
594
  if (!code && !me) throw nobody();
572
595
  const base = await ensureServer();
596
+ const pinged = Date.now();
573
597
  const res = await fetch(`${base}/api/ping`, {
574
598
  method: "POST",
575
599
  headers: { "content-type": "application/json" },
@@ -588,16 +612,25 @@ switch (cmd) {
588
612
  else if (body.confirmed) console.log(`answers on your pages come to you already, through this session’s channel.${await covers()}`);
589
613
  else if (body.sent && opts.wait) {
590
614
  console.log("pinged this session’s channel: a pong comes to you as a message; confirm it with the command it names");
591
- const limit = Date.now() + (opts.timeout ? Number(opts.timeout) * 1e3 : 12e4);
592
- while (Date.now() < limit) {
615
+ const timeout = opts.timeout ? Number(opts.timeout) * 1e3 : 12e4;
616
+ const giveUp = pinged + MAX_WAIT;
617
+ const secs = `${Math.round(timeout / 1e3)} s`;
618
+ /** the first turn end after the ping, once seen: the one a pong would have come at */
619
+ let ended = null;
620
+ for (;;) {
593
621
  await new Promise((r) => setTimeout(r, 1e3));
594
622
  if ((await api("/api/channels")).some((c) => c.session === me && c.confirmed)) {
595
623
  console.log(`confirmed: answers on your pages come to you now.${await covers()}`);
596
624
  process.exit(0);
597
625
  }
626
+ const turns = lastTurnEnd(proj.wp, me);
627
+ if (ended === null && turns?.ended != null && turns.ended >= pinged) ended = turns.ended;
628
+ const why = Date.now() >= giveUp ? `no pong came within ${MAX_WAIT / 6e4} minutes` : ended !== null && Date.now() >= ended + timeout ? `no pong came within ${secs} after your turn ended` : !turns && Date.now() >= pinged + timeout ? `no pong came within ${secs}` : null;
629
+ if (why) {
630
+ console.log(`${why}: nothing brings answers here. Listen for them (\`workpad listen --wait --page <file>\` in the background), and in Claude Code tell the user what \`workpad claude doctor\` says is wrong`);
631
+ process.exit(1);
632
+ }
598
633
  }
599
- console.log("no pong was confirmed in time: nothing brings answers here. Listen for them (`workpad listen --wait --page <file>` in the background), and in Claude Code tell the user what `workpad claude doctor` says is wrong");
600
- process.exit(1);
601
634
  } else if (body.sent) console.log("pinged this session’s channel: a pong comes to you as a message, the way answers will, with the command that confirms it. It may only come once your turn has ended, so start no listen yet. Run `workpad agent ping --wait` in the background instead, and it ends when you confirmed the pong or when none came: then listen");
602
635
  else {
603
636
  console.log("nothing brings answers to this session: listen for them (`workpad listen --wait --page <file>` in the background)");
@@ -911,6 +944,12 @@ switch (cmd) {
911
944
  if (opts.follow) throw new Error("listen runs on by itself: --wait stops at the first answer, --channel hands over to the channel");
912
945
  if (opts.wait && opts.channel) throw new Error("listen takes --wait or --channel, not both");
913
946
  if (opts.timeout && !opts.wait) throw new Error("--timeout goes with --wait");
947
+ if (opts.unfollowed) {
948
+ if (pagesGiven.length) throw new Error("--unfollowed takes the pages no one follows: no --page with it");
949
+ if (opts.channel) await channelUnfollowed(proj, agent);
950
+ else await unfollowedListen(proj, f.type ?? null, agent);
951
+ break;
952
+ }
914
953
  if (opts.channel) {
915
954
  await channelListen(proj, agent);
916
955
  break;
@@ -1094,6 +1133,13 @@ switch (cmd) {
1094
1133
  ...agent ? { agent } : {}
1095
1134
  }
1096
1135
  }),
1136
+ unfollowed: (onEvent, { agent = null, mark, signal } = {}) => holdUnfollowed(project, {
1137
+ at: () => ensureServer().catch(() => null),
1138
+ agent,
1139
+ mark,
1140
+ signal,
1141
+ onEvent
1142
+ }),
1097
1143
  channel: (session, handlers) => holdChannel(() => ensureServer().catch(() => null), session, handlers),
1098
1144
  authLink: async (to) => `${await ensureServer()}/_/auth?token=${encodeURIComponent(projectToken(project.wp))}&to=${encodeURIComponent(to)}`
1099
1145
  });
@@ -1118,12 +1164,8 @@ switch (cmd) {
1118
1164
  * those waiting now: so nothing is printed here, which would hand them out twice. Only for a session
1119
1165
  * whose channel is confirmed (`workpad agent ping`); else nothing is taken on.
1120
1166
  */
1121
- async function channelListen(proj, agent) {
1122
- if (!agent) throw new Error("--channel needs a session: no --agent, WORKPAD_AGENT or plugin session names one");
1123
- if (!(await api("/api/channels")).some((c) => c.session === agent && c.confirmed)) {
1124
- console.error("workpad: no confirmed channel brings answers to this session: run `workpad agent ping` and confirm its pong, or listen without --channel");
1125
- process.exit(1);
1126
- }
1167
+ async function channelListen(proj, who) {
1168
+ const agent = await confirmedChannel(who);
1127
1169
  const pages = [...new Set(pagesGiven.map((p) => pageId(proj, p)))];
1128
1170
  for (const page of pages.length ? pages : [""]) subscribe(proj, page, agent, { channel: true });
1129
1171
  const { events } = read(proj.eventsFile);
@@ -1145,6 +1187,130 @@ async function channelListen(proj, agent) {
1145
1187
  console.log(`${skipped.length} earlier message${skipped.length === 1 ? "" : "s"} from other agents, received before, skipped (on ${on.join(", ")}): \`workpad listen --wait --page <page>\` hands them to you`);
1146
1188
  }
1147
1189
  }
1190
+ /** `agent`, when a confirmed channel brings answers to it; else the command ends saying so. */
1191
+ async function confirmedChannel(agent) {
1192
+ if (!agent) throw new Error("--channel needs a session: no --agent, WORKPAD_AGENT or plugin session names one");
1193
+ if (!(await api("/api/channels")).some((c) => c.session === agent && c.confirmed)) {
1194
+ console.error("workpad: no confirmed channel brings answers to this session: run `workpad agent ping` and confirm its pong, or listen without --channel");
1195
+ process.exit(1);
1196
+ }
1197
+ return agent;
1198
+ }
1199
+ /**
1200
+ * Take the pages no one follows (`workpad listen --unfollowed`): a listen held at the server, which
1201
+ * holds it on each such page and says which they are as that changes; from each, the reader's
1202
+ * answers no other agent received (not the page's own agents' messages, nor what a session took
1203
+ * and works on between turns) go to `onEvent`, received by `agent` unless `mark` is false. Under
1204
+ * the shared server the pages of every project of this one's entry, each answer with where it is
1205
+ * (`from`). `onFirst`: the pages there were at first handed out what waited on them. Resolves once
1206
+ * the server holds it, or after a first try that found none running (it holds it once one runs).
1207
+ */
1208
+ async function holdUnfollowed(proj, options) {
1209
+ const { agent, type, mark, signal, onEvent, onFirst } = options;
1210
+ const shared = isShared(proj);
1211
+ const entry = shared ? matchesEntries(readMachineConfig(), proj.dir) : null;
1212
+ let origin = "";
1213
+ const address = (id) => id.split("/").map(encodeURIComponent).join("/");
1214
+ let reading = [];
1215
+ const update = everyPage((p, stop) => {
1216
+ const there = p.dir === proj.dir ? proj : project$1(p.dir);
1217
+ if (!there) return;
1218
+ reading.push(projectConfig(there).then(({ handedOut }) => {
1219
+ if (stop.aborted) return;
1220
+ handOut(there.eventsFile, {
1221
+ page: p.page,
1222
+ exact: true,
1223
+ type
1224
+ }, (e, again) => onEvent(e, again, shared ? {
1225
+ project: p.dir,
1226
+ url: `${origin}${p.base}/${address(e.page)}`
1227
+ } : null), {
1228
+ forAgent: forAgent(handedOut),
1229
+ agent,
1230
+ mark,
1231
+ readerOnly: true,
1232
+ notReceivedByOthers: true,
1233
+ signal: signal ? AbortSignal.any([stop, signal]) : stop
1234
+ });
1235
+ }));
1236
+ });
1237
+ let first = true;
1238
+ await listen({
1239
+ at: shared ? async () => {
1240
+ origin = (await sharedServer(machineServerFile()))?.origin ?? "";
1241
+ return origin || null;
1242
+ } : options.at,
1243
+ query: {
1244
+ unfollowed: "1",
1245
+ ...entry && { entry },
1246
+ ...type && { type },
1247
+ ...agent && { agent }
1248
+ },
1249
+ onPages: (pages) => {
1250
+ reading = [];
1251
+ update(pages);
1252
+ if (!first) return;
1253
+ first = false;
1254
+ Promise.all(reading).then(() => onFirst?.());
1255
+ },
1256
+ signal
1257
+ }, { orNone: true });
1258
+ }
1259
+ /**
1260
+ * `workpad listen --unfollowed`: the reader's answers on the pages no one follows, one line each, as
1261
+ * they come; with --wait all there are, or with none the first to come, and it stops. Under the
1262
+ * shared server each line says where it is (`project`, `url`).
1263
+ */
1264
+ async function unfollowedListen(proj, type, agent) {
1265
+ if (opts.timeout && opts.wait) setTimeout(() => {
1266
+ console.error("timeout");
1267
+ process.exit(2);
1268
+ }, Number(opts.timeout) * 1e3);
1269
+ let printed = 0;
1270
+ let following = false;
1271
+ let ending = false;
1272
+ const end = () => {
1273
+ if (ending) return;
1274
+ ending = true;
1275
+ setImmediate(() => process.exit(0));
1276
+ };
1277
+ await holdUnfollowed(proj, {
1278
+ at: () => needServer().catch(() => null),
1279
+ agent,
1280
+ type,
1281
+ onEvent: (e, again, from) => {
1282
+ console.log(JSON.stringify({
1283
+ ...e,
1284
+ ...again && { again: true },
1285
+ ...from
1286
+ }));
1287
+ printed++;
1288
+ if (opts.wait && following) end();
1289
+ },
1290
+ onFirst: () => {
1291
+ following = true;
1292
+ if (opts.wait && printed) end();
1293
+ }
1294
+ });
1295
+ setInterval(() => {}, 1 << 30);
1296
+ }
1297
+ /**
1298
+ * `workpad listen --unfollowed --channel`: the session's confirmed channel takes the pages no one
1299
+ * follows, for as long as it runs; none becomes the session's (status.ts, takesUnfollowed).
1300
+ */
1301
+ async function channelUnfollowed(proj, agent) {
1302
+ const me = await confirmedChannel(agent);
1303
+ if (!takesUnfollowed(readEvents(proj.eventsFile), me)) appendEvent(proj.eventsFile, {
1304
+ page: "",
1305
+ type: SUBSCRIBE,
1306
+ data: {
1307
+ channel: true,
1308
+ unfollowed: true
1309
+ }
1310
+ }, "cli", me);
1311
+ const entry = isShared(proj) ? matchesEntries(readMachineConfig(), proj.dir) : null;
1312
+ console.log(`the channel brings the answers on the pages no one follows${entry ? `, in every project of ${entry}` : ""}: those waiting there first, then each as it comes; a page drops out while someone else follows it`);
1313
+ }
1148
1314
  /**
1149
1315
  * A listen over a whole entry: every page of each of its projects, from each project's own log, each
1150
1316
  * event with the project it is from (`project`, its folder) and its page's `url`. Any number run.