@bigmistqke/workpad 0.18.1 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/README.md +18 -9
  2. package/bin/workpad.ts +412 -58
  3. package/dist/bin/workpad.js +336 -46
  4. package/dist/client/runtime.js +141 -18
  5. package/dist/plugins/badge/README.md +59 -10
  6. package/dist/plugins/badge/index.js +130 -8
  7. package/dist/plugins/badge/public/style.css +132 -12
  8. package/dist/plugins/chat/README.md +7 -3
  9. package/dist/plugins/chat/index.js +8 -1
  10. package/dist/plugins/chat/public/client.js +2 -2
  11. package/dist/plugins/chat/public/style.css +10 -0
  12. package/dist/plugins/claude/README.md +13 -5
  13. package/dist/plugins/claude/channel.js +47 -6
  14. package/dist/plugins/claude/doctor.js +43 -47
  15. package/dist/plugins/claude/index.js +24 -8
  16. package/dist/plugins/claude/session.js +46 -1
  17. package/dist/plugins/comments/README.md +2 -1
  18. package/dist/plugins/comments/index.js +2 -0
  19. package/dist/plugins/comments/public/client.js +6 -5
  20. package/dist/plugins/comments/public/style.css +9 -0
  21. package/dist/plugins/form/README.md +1 -1
  22. package/dist/plugins/index.js +3 -1
  23. package/dist/plugins/opencode/channel.js +43 -7
  24. package/dist/plugins/opencode/index.js +2 -0
  25. package/dist/plugins/progress/README.md +41 -0
  26. package/dist/plugins/progress/index.js +117 -0
  27. package/dist/plugins/progress/public/client.js +1 -0
  28. package/dist/plugins/progress/public/style.css +85 -0
  29. package/dist/plugins/progress/state.js +210 -0
  30. package/dist/solid/index.js +3 -1
  31. package/dist/src/agents.js +13 -4
  32. package/dist/src/anchors.js +25 -1
  33. package/dist/src/build.js +1 -1
  34. package/dist/src/client/page/base.css +48 -2
  35. package/dist/src/client/page/main.js +58 -30
  36. package/dist/src/document.js +6 -4
  37. package/dist/src/events.js +22 -11
  38. package/dist/src/help.js +59 -12
  39. package/dist/src/hub.js +69 -3
  40. package/dist/src/listen.js +36 -4
  41. package/dist/src/listeners.js +14 -4
  42. package/dist/src/loader.js +7 -2
  43. package/dist/src/migrate.js +1 -1
  44. package/dist/src/pages/board.js +9 -4
  45. package/dist/src/pages/index.js +2 -4
  46. package/dist/src/pages/markdown.js +50 -19
  47. package/dist/src/pages/render.js +17 -1
  48. package/dist/src/server.js +94 -18
  49. package/dist/src/set.js +99 -0
  50. package/dist/src/state.js +2 -1
  51. package/dist/src/status.js +57 -9
  52. package/dist/src/turns.js +41 -0
  53. package/package.json +11 -1
  54. package/plugins/README.md +3 -1
  55. package/plugins/badge/README.md +59 -10
  56. package/plugins/badge/index.ts +141 -8
  57. package/plugins/badge/public/style.css +132 -12
  58. package/plugins/chat/README.md +7 -3
  59. package/plugins/chat/client.tsx +20 -3
  60. package/plugins/chat/index.ts +10 -1
  61. package/plugins/chat/public/style.css +10 -0
  62. package/plugins/claude/README.md +13 -5
  63. package/plugins/claude/channel.ts +45 -7
  64. package/plugins/claude/doctor.ts +58 -39
  65. package/plugins/claude/index.ts +30 -8
  66. package/plugins/claude/session.ts +32 -0
  67. package/plugins/comments/README.md +2 -1
  68. package/plugins/comments/client.ts +19 -0
  69. package/plugins/comments/index.ts +7 -1
  70. package/plugins/comments/public/style.css +9 -0
  71. package/plugins/form/README.md +1 -1
  72. package/plugins/index.ts +2 -0
  73. package/plugins/opencode/channel.ts +44 -8
  74. package/plugins/opencode/index.ts +4 -0
  75. package/plugins/progress/README.md +41 -0
  76. package/plugins/progress/client.ts +172 -0
  77. package/plugins/progress/index.ts +166 -0
  78. package/plugins/progress/public/style.css +85 -0
  79. package/plugins/progress/state.ts +278 -0
  80. package/skills/workpad/SKILL.md +149 -18
  81. package/solid/index.tsx +6 -2
  82. package/src/agents.ts +24 -2
  83. package/src/anchors.ts +32 -0
  84. package/src/build.ts +1 -1
  85. package/src/client/delivery.ts +49 -0
  86. package/src/client/forms.ts +18 -11
  87. package/src/client/page/base.css +48 -2
  88. package/src/client/page/waiting.ts +45 -25
  89. package/src/client/read.ts +9 -5
  90. package/src/client/runtime.ts +7 -3
  91. package/src/client/toast.ts +27 -3
  92. package/src/define.ts +120 -9
  93. package/src/document.ts +19 -5
  94. package/src/events.ts +47 -6
  95. package/src/help.ts +58 -11
  96. package/src/hub.ts +80 -2
  97. package/src/listen.ts +47 -4
  98. package/src/listeners.ts +22 -1
  99. package/src/loader.ts +14 -4
  100. package/src/migrate.ts +1 -1
  101. package/src/pages/board.ts +12 -3
  102. package/src/pages/index.ts +8 -10
  103. package/src/pages/markdown.ts +59 -12
  104. package/src/pages/render.ts +20 -2
  105. package/src/server.ts +127 -19
  106. package/src/set.ts +118 -0
  107. package/src/state.ts +3 -0
  108. package/src/status.ts +115 -14
  109. package/src/turns.ts +56 -0
package/src/server.ts CHANGED
@@ -32,7 +32,6 @@ import {
32
32
  follow,
33
33
  handle as handleEvent,
34
34
  matches,
35
- receivedIds,
36
35
  handledIds,
37
36
  forAgent,
38
37
  namesOf,
@@ -63,11 +62,21 @@ import { describeRoutes, dispatch, pluginCommands, mountRoutes, usage } from './
63
62
  import { createAuth, sameSite } from './auth.ts'
64
63
  import { accept, refuse } from './ws.ts'
65
64
  import { FROM_SOURCE, PACKAGE_DIR, VERSION } from './package.ts'
66
- import { SCROLL, agentMessagesIn, awaiting, isAgentMessage, projectStatus, type ProjectStatus } from './status.ts'
65
+ import {
66
+ SCROLL,
67
+ agentLabel,
68
+ agentMessagesIn,
69
+ awaiting,
70
+ isAgentMessage,
71
+ projectStatus,
72
+ receivers,
73
+ refusal,
74
+ type ProjectStatus,
75
+ } from './status.ts'
67
76
  import { formsIn, messageForms } from './pages/markdown.ts'
68
77
  import { fileFilter, type FileFilter } from './files.ts'
69
78
  import { titleOf } from './pages/render.ts'
70
- import { createRegistry, holdStream, listenerOf } from './listeners.ts'
79
+ import { createRegistry, follows, holdStream, listenerOf } from './listeners.ts'
71
80
  import { inPublic } from './public.ts'
72
81
  import { build, type BuildResult } from './build.ts'
73
82
  import { PAGE_CLIENT, RUNTIME, frontmatterOf, pageDocument, pluginParts, type Render, type SetUp } from './document.ts'
@@ -106,6 +115,9 @@ const MIME: Record<string, string> = {
106
115
  '.csv': 'text/csv; charset=utf-8',
107
116
  '.html': 'text/html; charset=utf-8',
108
117
  }
118
+ /** How many of the browser's latest events the server knows by id, to answer a retried send with the first. */
119
+ const APPENDED_KEPT = 1000
120
+
109
121
  // files in .workpad/ that are the server's own bookkeeping, not content
110
122
  const OWN_FILES = new Set(['events.ndjson', 'server.json', 'server.log', 'server.lock', 'token'])
111
123
 
@@ -142,6 +154,13 @@ export interface WorkpadServer {
142
154
  addListener(l: Listener): () => void
143
155
  /** call `fn` whenever a listener comes or goes; returns what stops it */
144
156
  onListeners(fn: () => void): () => void
157
+ /**
158
+ * Hold `listener` on each page no one follows (`workpad listen --unfollowed`), for as long as it
159
+ * isn't stopped: a page drops out once someone follows it, and joins when its last follower goes,
160
+ * as does a new page. `onPages` is told the pages, at once and whenever they change.
161
+ * @returns what stops it
162
+ */
163
+ unfollowed(listener: Listener, onPages: (pages: string[]) => void): () => void
145
164
  /** who listens now: the running listens and channels, and an entry's listens held for it */
146
165
  listeners(): Listener[]
147
166
  /** whether it serves its files (its config read first) */
@@ -256,7 +275,8 @@ export function createServer(
256
275
  const notices = [...rendered.notices]
257
276
  const parts = await pluginParts(await pluginHooks(), req, {
258
277
  asset,
259
- messages: [...(await config()).forReader],
278
+ messages: Object.fromEntries((await config()).forReader),
279
+ handedOut: [...(await config()).handedOut],
260
280
  failed: message => {
261
281
  console.error(message)
262
282
  notices.push(message)
@@ -416,10 +436,8 @@ export function createServer(
416
436
  // what each form asks, for the API
417
437
  let details: FormDetail[] = []
418
438
  try {
419
- const source = pageSource(id, file)
420
- asks = renderer?.questions(source) ?? []
421
- chats = renderer?.chats(source)
422
- details = renderer?.forms(source) ?? []
439
+ const said = renderer?.asks(pageSource(id, file))
440
+ if (said) ({ questions: asks, chats, forms: details } = said)
423
441
  } catch (err) {
424
442
  console.error('questions:', err)
425
443
  }
@@ -442,17 +460,26 @@ export function createServer(
442
460
  async function snapshot(listed: PagesSource['pages']): Promise<ProjectStatus> {
443
461
  const { pages: renderer, handedOut, forReader } = await config()
444
462
  const events = readEvents(project.eventsFile)
463
+ // each page's messages, the log gone through once instead of once for every chat of every page
464
+ const messages = new Map<string, WpEvent[]>()
465
+ for (const e of events) {
466
+ if (!isAgentMessage(e)) continue
467
+ const own = messages.get(e.page)
468
+ if (own) own.push(e)
469
+ else messages.set(e.page, [e])
470
+ }
445
471
  const pages = listed.map(p => {
446
472
  const page = { id: p.id, file: p.file, ...questionsOf(renderer, p.id, p.file) }
447
473
  // the forms in the agent's messages in the page's chats are its questions too
448
- return { ...page, asks: [...page.asks, ...messageForms(events, p.id, page.chats ?? [])] }
474
+ const forms = messageForms(messages.get(p.id) ?? [], p.id, page.chats ?? [])
475
+ return { ...page, asks: [...page.asks, ...forms] }
449
476
  })
450
477
  return projectStatus({
451
478
  pages,
452
479
  events,
453
480
  listeners: listenersFor,
454
481
  forAgent: forAgent(handedOut),
455
- forReader: type => forReader.has(type),
482
+ forReader,
456
483
  })
457
484
  }
458
485
 
@@ -718,6 +745,56 @@ export function createServer(
718
745
  const pings = new Map<string, string>()
719
746
  const pingCode = () => crypto.randomBytes(3).toString('hex')
720
747
 
748
+ // ---- the unfollowed pages ----------------------------------------------------------------------
749
+ // A listen on the pages no one follows (`workpad listen --unfollowed`, a coordinator's) is held as
750
+ // a listener on each of them, so they say someone listens; that listener follows nothing itself
751
+ // (listeners.ts, follows). The set is looked at again whenever a listener comes or goes and
752
+ // whenever a page changes (made, deleted).
753
+ interface Unfollowing {
754
+ listener: Listener
755
+ onPages(pages: string[]): void
756
+ held: Map<string, () => void>
757
+ told: string | null
758
+ }
759
+ const unfollowing = new Set<Unfollowing>()
760
+ let looking = false
761
+ function lookAgain() {
762
+ if (looking || !unfollowing.size) return
763
+ looking = true
764
+ // after what changed is done: holding a page is a change of listeners too
765
+ setImmediate(() => {
766
+ looking = false
767
+ const pages = pagesIn(project.pagesDir)
768
+ .map(p => p.id)
769
+ .filter(id => !registry.list(id).some(l => follows(l, id)))
770
+ for (const u of unfollowing) {
771
+ for (const [page, release] of u.held)
772
+ if (!pages.includes(page)) {
773
+ release()
774
+ u.held.delete(page)
775
+ }
776
+ for (const page of pages)
777
+ if (!u.held.has(page)) u.held.set(page, registry.add({ ...u.listener, page, unfollowed: true }))
778
+ const now = JSON.stringify(pages)
779
+ if (now !== u.told) {
780
+ u.told = now
781
+ u.onPages(pages)
782
+ }
783
+ }
784
+ })
785
+ }
786
+ registry.onChange(lookAgain)
787
+ function unfollowed(listener: Listener, onPages: (pages: string[]) => void): () => void {
788
+ const u: Unfollowing = { listener, onPages, held: new Map(), told: null }
789
+ unfollowing.add(u)
790
+ lookAgain()
791
+ return () => {
792
+ if (!unfollowing.delete(u)) return
793
+ for (const release of u.held.values()) release()
794
+ u.held.clear()
795
+ }
796
+ }
797
+
721
798
  // ---- live changes ------------------------------------------------------------------------------
722
799
  // The browser listens on a WebSocket at /api/live, each message `{ event, data }`. `change`: its
723
800
  // page changed; `events`: the log grew; `listeners`: an agent started or stopped waiting; `style`:
@@ -735,8 +812,17 @@ export function createServer(
735
812
  }
736
813
 
737
814
  const clients = new Set<WatchClient>()
738
- /** what the browser appended lately, by id: a send it retries is answered with what it got */
739
- const appended = new Map<string, WpEvent>()
815
+ /**
816
+ * what the browser appended lately, by id: a send it retries is answered with what it got. From
817
+ * the log at the start, so a retry that comes after a restart (the first try got in, its answer
818
+ * didn't get out) is no second answer either.
819
+ */
820
+ const appended = new Map<string, WpEvent>(
821
+ readEvents(project.eventsFile)
822
+ .filter(e => !e.from)
823
+ .slice(-APPENDED_KEPT)
824
+ .map(e => [e.id, e]),
825
+ )
740
826
  function notify(client: WatchClient, kind: string) {
741
827
  client.pending ??= new Set()
742
828
  if (client.pending.size === 0)
@@ -757,6 +843,7 @@ export function createServer(
757
843
 
758
844
  function pageChanged(id: string) {
759
845
  onChange?.()
846
+ lookAgain()
760
847
  for (const c of clients) {
761
848
  if (c.isDir ? !c.page || id.startsWith(c.page + '/') : c.page === id || c.page + '/index' === id)
762
849
  notify(c, 'change')
@@ -1069,9 +1156,12 @@ export function createServer(
1069
1156
  // the browser sends it again when it heard nothing back: appended once, the same answer twice
1070
1157
  const again = isEventId(body.id) ? appended.get(body.id) : undefined
1071
1158
  if (again) return sendJson(res, 200, again)
1159
+ // an event without the data its type requires shows nowhere (a chat message with no text)
1160
+ const refused = refusal(body.type, body.data, (await config()).requires)
1161
+ if (refused) return sendJson(res, 400, { error: refused })
1072
1162
  const event = appendEvent(project.eventsFile, body)
1073
1163
  appended.set(event.id, event)
1074
- if (appended.size > 1000) appended.delete(appended.keys().next().value!)
1164
+ if (appended.size > APPENDED_KEPT) appended.delete(appended.keys().next().value!)
1075
1165
  return sendJson(res, 200, event)
1076
1166
  }
1077
1167
  // an agent shows the reader a place on a page: every tab with it open scrolls there
@@ -1199,7 +1289,7 @@ export function createServer(
1199
1289
  if (p === '/api/events') {
1200
1290
  const all = after(readEvents(project.eventsFile), q.since)
1201
1291
  // what became of each: received by a wait, handled by the agent (status.ts)
1202
- const received = receivedIds(all)
1292
+ const received = receivers(all)
1203
1293
  const handled = handledIds(all)
1204
1294
  return sendJson(
1205
1295
  res,
@@ -1207,17 +1297,34 @@ export function createServer(
1207
1297
  all
1208
1298
  // `type` and `kind` may be several, comma-separated (state.ts); `page` and `exact` as ever
1209
1299
  .filter(e => matches(e, { ...q, type: null }) && matchesQuery(e, q))
1210
- .map(e => ({
1211
- ...e,
1212
- ...(received.has(e.id) && { received: true }),
1213
- ...(handled.has(e.id) && { handled: true }),
1214
- })),
1300
+ .map(e => {
1301
+ const by = received.get(e.id)
1302
+ return {
1303
+ ...e,
1304
+ ...(received.has(e.id) && { received: true }),
1305
+ // who, as the page says it ("received by …")
1306
+ ...(by && { receivedBy: agentLabel(by, names) }),
1307
+ ...(handled.has(e.id) && { handled: true }),
1308
+ }
1309
+ }),
1215
1310
  )
1216
1311
  }
1217
1312
  if (p === '/api/docs') return sendJson(res, 200, await docs())
1218
1313
  if (p === '/api/status') return sendJson(res, 200, await status(q.page || null))
1219
1314
  if (p === '/api/listeners') return sendJson(res, 200, listenersFor(q.page ?? null))
1220
1315
  if (p === '/api/stamps') return sendJson(res, 200, stamps())
1316
+ if (p === '/api/listen' && url.searchParams.has('unfollowed')) {
1317
+ // on the pages no one follows, told which they are as they change
1318
+ const stop = unfollowed(listenerOf(url.searchParams), pages =>
1319
+ stream.send('pages', { projects: pages.length ? [{ dir: project.dir, base, pages }] : [] }),
1320
+ )
1321
+ const stream = holdStream(req, res, () => {
1322
+ stop()
1323
+ streams.delete(stream.end)
1324
+ })
1325
+ streams.add(stream.end)
1326
+ return
1327
+ }
1221
1328
  if (p === '/api/listen') {
1222
1329
  // any number listen on a page; each is a listener for as long as its connection is open
1223
1330
  const remove = registry.add(listenerOf(url.searchParams))
@@ -1370,6 +1477,7 @@ export function createServer(
1370
1477
  elsewhere: () => notifyAll('elsewhere'),
1371
1478
  addListener: l => registry.add(l),
1372
1479
  onListeners: fn => registry.onChange(fn),
1480
+ unfollowed,
1373
1481
  status: (page = null) => status(page),
1374
1482
  read: readList,
1375
1483
  stream,
package/src/set.ts ADDED
@@ -0,0 +1,118 @@
1
+ // `workpad set`: a block of a page replaced by its name, not by matching its text. The page is
2
+ // parsed (so a form shown as an example in a code fence is never touched), and each block it can
3
+ // replace is found by the anchor a link would use: a heading's slug for its section (up to the next
4
+ // heading of the same or a higher level), `<type>:<name>` for a named block (`form:logger`,
5
+ // `chat:notes`, `details:why`, `item:parser`). Everything outside the block stays as it was, byte
6
+ // for byte.
7
+ import { toString } from 'mdast-util-to-string'
8
+ import { parseMarkdown, slug, titleWords, type MdNode } from './pages/markdown.ts'
9
+ import { slugText, hashOf } from './anchors.ts'
10
+ import { edit } from './migrate.ts'
11
+
12
+ /** A block `set` can replace: its anchor, what it is, and where it is in the source. */
13
+ export interface SourceBlock {
14
+ /** the anchor that names it, without `#`: `form:logger`, `open-questions` */
15
+ id: string
16
+ /** `heading` for a section, else the directive's type (`form`, `chat`, `details`, `item`) */
17
+ kind: string
18
+ from: number
19
+ to: number
20
+ }
21
+
22
+ const start = (n: MdNode): number => n.position.start.offset
23
+ const end = (n: MdNode): number => n.position.end.offset
24
+
25
+ /** Directives that are named even without a name: a form or chat without one is `form`, `chat`. */
26
+ const NAMED_BY_TYPE = new Set(['form', 'chat'])
27
+
28
+ /**
29
+ * The blocks of a page's source, in source order, named as the page's anchors name them: headings
30
+ * (numbered on a repeat, as the page does), and container or leaf directives with a name (its
31
+ * `name` or `id`), a label (its slug), or of a type named by itself (a form or chat without a name).
32
+ * A repeat of a directive's id is numbered (`details:why-1`), as a details' is on the page.
33
+ */
34
+ export function blocksOf(source: string): SourceBlock[] {
35
+ const tree = parseMarkdown(source)
36
+ const out: SourceBlock[] = []
37
+ const headings = new Map<string, number>()
38
+ const taken = new Map<string, number>()
39
+ const walk = (parent: MdNode) => {
40
+ const kids = parent.children ?? []
41
+ kids.forEach((node, i) => {
42
+ if (node.type === 'heading' && node.position) {
43
+ // the badges and `:when`s in it aren't its words (titleWords), so they're never its slug
44
+ const id = slug(
45
+ titleWords(node.children ?? [], () => true),
46
+ headings,
47
+ )
48
+ // the section: the heading and what follows it up to the next of the same or a higher level
49
+ let last = node
50
+ for (const next of kids.slice(i + 1)) {
51
+ if (next.type === 'heading' && next.depth <= node.depth) break
52
+ last = next
53
+ }
54
+ if (id && !id.startsWith('wp-')) out.push({ id, kind: 'heading', from: start(node), to: end(last) })
55
+ } else if ((node.type === 'containerDirective' || node.type === 'leafDirective') && node.position) {
56
+ const attrs = (node.attributes ?? {}) as Record<string, string | null | undefined>
57
+ const label =
58
+ node.type === 'containerDirective' && node.children?.[0]?.data?.directiveLabel ? node.children[0] : null
59
+ const labelText = label
60
+ ? slugText(node.name === 'details' ? toString(label as any) : titleWords(label.children ?? [], () => true))
61
+ : ''
62
+ const name = attrs.name || attrs.id || (NAMED_BY_TYPE.has(node.name) ? node.name : labelText)
63
+ if (name) {
64
+ const base = `${node.name}:${name}`
65
+ let id = base
66
+ if (taken.has(base)) {
67
+ let n = taken.get(base)!
68
+ do id = `${base}-${++n}`
69
+ while (taken.has(id))
70
+ taken.set(base, n)
71
+ }
72
+ taken.set(id, 0)
73
+ out.push({ id, kind: node.name, from: start(node), to: end(node) })
74
+ }
75
+ }
76
+ walk(node)
77
+ })
78
+ }
79
+ walk(tree)
80
+ return out
81
+ }
82
+
83
+ /** `name` as a link writes it, or as typed: `#form:logger`, `form:logger`, `form%3Alogger`. */
84
+ function normalize(name: string): string {
85
+ let id = name.trim().replace(/^#/, '')
86
+ try {
87
+ id = decodeURIComponent(id)
88
+ } catch {
89
+ /* as written */
90
+ }
91
+ return id
92
+ }
93
+
94
+ /**
95
+ * The block `name` names: its anchor (`form:logger`, `open-questions`), or a block's bare name
96
+ * (`logger` for `form:logger`) when only one block has it. Throws, listing the page's blocks, when
97
+ * none does, or when the bare name fits several.
98
+ */
99
+ export function findBlock(source: string, name: string): SourceBlock {
100
+ const blocks = blocksOf(source)
101
+ const id = normalize(name)
102
+ // `#logger` is the anchor as a link writes it: that heading, never the form of that name
103
+ const exact = name.trim().startsWith('#')
104
+ const fits = blocks.filter(b => b.id === id || (!exact && b.id === `${b.kind}:${id}`))
105
+ if (fits.length === 1) return fits[0]
106
+ const list = (bs: SourceBlock[]) => bs.map(b => ` ${hashOf(b.id)} ${b.kind}`).join('\n')
107
+ if (fits.length > 1)
108
+ throw new Error(`${id} fits ${fits.length} blocks; name one by its anchor, with its #:\n${list(fits)}`)
109
+ throw new Error(
110
+ `no block ${hashOf(id)} on the page${blocks.length ? `; it has:\n${list(blocks)}` : ', nor any other with a name'}`,
111
+ )
112
+ }
113
+
114
+ /** `source` with the block `name` names replaced by `markdown` (its trailing blank lines left off). */
115
+ export function setBlock(source: string, name: string, markdown: string): string {
116
+ const block = findBlock(source, name)
117
+ return edit(source, [{ from: block.from, to: block.to, text: markdown.replace(/\s+$/, '') }])
118
+ }
package/src/state.ts CHANGED
@@ -107,6 +107,8 @@ export interface SubscriptionInfo {
107
107
  since: string
108
108
  /** taken on through its channel (`workpad listen --channel`) */
109
109
  channel: boolean
110
+ /** not a page: the agent's channel takes the pages no one follows (`workpad listen --unfollowed --channel`) */
111
+ unfollowed?: true
110
112
  }
111
113
 
112
114
  /** An agent the board knows (GET /api/agents): it named itself, subscribed, wrote something, or listens now. */
@@ -303,6 +305,7 @@ export function subscriptionsOf(s: Pick<StateSource, 'base' | 'events'>): Subscr
303
305
  page: e.page,
304
306
  since: e.ts,
305
307
  channel: !!e.data?.channel,
308
+ ...(e.data?.unfollowed ? { unfollowed: true as const } : {}),
306
309
  }))
307
310
  }
308
311
 
package/src/status.ts CHANGED
@@ -29,9 +29,10 @@
29
29
  // A message is an agent's event of a type a plugin declares `forReader` (a reply in a comment
30
30
  // thread, a chat message). It is unread until a `workpad:read` event from the reader names it,
31
31
  // which the page appends once the message has been in view; one the agent replaced (`replaces`)
32
- // no longer counts, nor one in a chat no longer on the page (its form or block taken off): the page
32
+ // no longer counts, nor one without the data its type requires (a chat message with no chat or
33
+ // no text: nothing shows it), nor one in a chat no longer on the page (its form or block taken off): the page
33
34
  // keeps those folded after its content, as a record, not as something to read.
34
- import type { FormState, Listener, Marks, PageStatus, WpEvent } from './define.ts'
35
+ import type { Delivery, FormState, Listener, Marks, PageStatus, WpEvent } from './define.ts'
35
36
 
36
37
  /**
37
38
  * Can this be a question's name, the type of its answers? Not with a colon: types with one belong
@@ -129,6 +130,44 @@ export function questionState(
129
130
  export const heard = (name: string, listeners: Listener[]): boolean =>
130
131
  listeners.some(l => l.type === null || l.type === name)
131
132
 
133
+ /**
134
+ * After how long an answer no agent received is late, in ms: the page flags it ("not received after
135
+ * 10 min") and counts it, as something went wrong on the agent's side (a session gone, a channel
136
+ * down, a server under load).
137
+ */
138
+ export const NOT_RECEIVED_AFTER = 10 * 60_000
139
+
140
+ /**
141
+ * Where one of the reader's events for an agent went (Delivery), at time `now` (ms): from its marks
142
+ * (received, handled; `receivedBy`), whether it is still on its way (`sending`), and who listens on
143
+ * its page (`listeners`, those covering it). Someone takes it when a listener hears its type
144
+ * (heard): a listen on the page, a confirmed channel, also a coordinator's listen on the unfollowed
145
+ * pages, which follows the page for no one but does receive what is sent there.
146
+ */
147
+ export function deliveryOf(
148
+ e: WpEvent,
149
+ listeners: Listener[],
150
+ now: number,
151
+ after: number = NOT_RECEIVED_AFTER,
152
+ ): Delivery {
153
+ if (e.sending) return { state: 'sending', text: 'sending…' }
154
+ if (e.handled) return { state: 'handled', text: 'handled' }
155
+ if (e.received)
156
+ return e.receivedBy
157
+ ? { state: 'received', text: `received by ${e.receivedBy}`, by: e.receivedBy }
158
+ : { state: 'received', text: 'received' }
159
+ const nobody = !heard(e.type, listeners)
160
+ if (now - Date.parse(e.ts) >= after)
161
+ return {
162
+ state: 'late',
163
+ text: `not received after ${Math.round(after / 60_000)} min${nobody ? ' · no one follows this page' : ''}`,
164
+ nobody,
165
+ }
166
+ return nobody
167
+ ? { state: 'unfollowed', text: 'no one follows this page — it waits until an agent listens' }
168
+ : { state: 'waiting', text: 'waiting for an agent to receive it' }
169
+ }
170
+
132
171
  /** The type of the event the page appends once messages were in view: `{ ids }`. */
133
172
  export const READ = 'workpad:read'
134
173
 
@@ -140,14 +179,42 @@ export const READ = 'workpad:read'
140
179
  export const SCROLL = 'workpad:scroll'
141
180
 
142
181
  /**
143
- * The agent's messages on a page the reader hasn't read: events from the agent of a type
144
- * `isMessage` says is for the reader, not named by a `workpad:read` from the reader, not
145
- * replaced by a later one (`replaces`), and, given the page's `chats`, not in a chat (`data.chat`)
146
- * that is no longer among them.
182
+ * The fields of an event's `data` its type requires (EventSpec.requires) that it lacks: each must
183
+ * be a non-empty string.
184
+ */
185
+ export const missingData = (data: Record<string, unknown> | null | undefined, requires: readonly string[]): string[] =>
186
+ requires.filter(field => {
187
+ const value = data?.[field]
188
+ return typeof value !== 'string' || !value.trim()
189
+ })
190
+
191
+ /**
192
+ * Why an event of `type` with this `data` can't go in the log, given the types that require data
193
+ * fields: what it lacks, and the shape it needs; null when nothing is missing.
194
+ */
195
+ export function refusal(
196
+ type: string,
197
+ data: Record<string, unknown> | null | undefined,
198
+ requires: ReadonlyMap<string, readonly string[]>,
199
+ ): string | null {
200
+ const fields = requires.get(type) ?? []
201
+ const missing = missingData(data, fields)
202
+ if (!missing.length) return null
203
+ const list = (names: readonly string[]) => names.join(names.length > 2 ? ', ' : ' and ').replace(/, (?=[^,]*$)/, ' and ')
204
+ const shape = JSON.stringify(Object.fromEntries(fields.map(f => [f, '…'])))
205
+ return `a ${type} needs ${list(fields)} in its data, each a non-empty string; ${list(missing)} ${missing.length > 1 ? 'are' : 'is'} missing or empty. Its data: ${shape}`
206
+ }
207
+
208
+ /**
209
+ * The agent's messages on a page the reader hasn't read: events from the agent of a type in
210
+ * `messages` (the types for the reader, each with the `data` fields it requires), not named by a
211
+ * `workpad:read` from the reader, not replaced by a later one (`replaces`), with the data their
212
+ * type requires (one without it shows nowhere on the page, so it waits for nobody), and, given the
213
+ * page's `chats`, not in a chat (`data.chat`) that is no longer among them.
147
214
  */
148
215
  export function unreadMessages(
149
216
  events: WpEvent[],
150
- isMessage: (type: string) => boolean,
217
+ messages: ReadonlyMap<string, readonly string[]>,
151
218
  chats?: ReadonlySet<string> | null,
152
219
  ): WpEvent[] {
153
220
  const read = new Set<string>()
@@ -157,10 +224,12 @@ export function unreadMessages(
157
224
  for (const id of (e.data?.ids as unknown[] | undefined) ?? []) read.add(String(id))
158
225
  if (e.data?.replaces) replaced.add(String(e.data.replaces))
159
226
  }
227
+ const shown = (e: WpEvent) => {
228
+ const requires = messages.get(e.type)
229
+ return !!requires && !missingData(e.data, requires).length
230
+ }
160
231
  const offPage = (e: WpEvent) => !!chats && typeof e.data?.chat === 'string' && !chats.has(e.data.chat)
161
- return events.filter(
162
- e => !fromReader(e) && isMessage(e.type) && !read.has(e.id) && !replaced.has(e.id) && !offPage(e),
163
- )
232
+ return events.filter(e => !fromReader(e) && shown(e) && !read.has(e.id) && !replaced.has(e.id) && !offPage(e))
164
233
  }
165
234
 
166
235
  /** How many things on a page wait for the reader: its open questions and unread messages. */
@@ -236,6 +305,24 @@ export function namesOf(events: WpEvent[]): Map<string, string> {
236
305
  return names
237
306
  }
238
307
 
308
+ /**
309
+ * Who received each answer first, by its id: the `by` of the first RECEIVED naming it (null when
310
+ * the command line knew no one). Only the command line's marks count.
311
+ */
312
+ export function receivers(events: WpEvent[]): Map<string, string | null> {
313
+ const by = new Map<string, string | null>()
314
+ for (const e of events)
315
+ if (e.type === RECEIVED && !fromReader(e)) {
316
+ const id = String(e.data?.event)
317
+ if (!by.has(id)) by.set(id, e.by ?? null)
318
+ }
319
+ return by
320
+ }
321
+
322
+ /** An agent as a page names it: the name it gave itself (`names`), else its id, a long one (a session's) cut short. */
323
+ export const agentLabel = (id: string, names: Map<string, string> = new Map()): string =>
324
+ names.get(id) ?? (id.length > 16 ? id.slice(0, 8) : id)
325
+
239
326
  /** The ids of the answers a wait or watch printed. Only the command line's marks count. */
240
327
  export function receivedIds(events: WpEvent[]): Set<string> {
241
328
  return new Set(events.filter(e => e.type === RECEIVED && !fromReader(e)).map(e => String(e.data?.event)))
@@ -251,7 +338,7 @@ export function receivedIds(events: WpEvent[]): Set<string> {
251
338
  export function channelSince(events: WpEvent[], agent: string, page: string): string | null {
252
339
  let since: string | null = null
253
340
  for (const e of subscriptions(events)) {
254
- if (e.by !== agent) continue
341
+ if (e.by !== agent || e.data?.unfollowed) continue
255
342
  if (!(e.page === '' || e.page === page || page.startsWith(`${e.page}/`))) continue
256
343
  if (!e.data?.channel) return null
257
344
  since ??= e.id
@@ -259,6 +346,15 @@ export function channelSince(events: WpEvent[], agent: string, page: string): st
259
346
  return since
260
347
  }
261
348
 
349
+ /**
350
+ * Does `agent` take the pages no one follows through its channel (`workpad listen --unfollowed
351
+ * --channel`)? Said by a subscription on every page (`''`) with data `{ channel: true, unfollowed:
352
+ * true }`; it makes no page the agent's (no subscriber of any), and `workpad agent unsubscribe`
353
+ * takes it off with the rest.
354
+ */
355
+ export const takesUnfollowed = (events: WpEvent[], agent: string): boolean =>
356
+ subscriptions(events).some(e => e.by === agent && !!e.data?.unfollowed)
357
+
262
358
  /**
263
359
  * The ids of the reader's events the agent handled: acknowledged (`workpad:handled`), or replied
264
360
  * to after them (see the top of this file). The log is gone through once: each of the reader's
@@ -325,8 +421,8 @@ export interface StatusInput {
325
421
  listeners: (page: string) => Listener[]
326
422
  /** the event types handed to an agent (a form's answers; plugins' events declared handOut) */
327
423
  forAgent: (type: string) => boolean
328
- /** the event types that are messages for the reader (declared forReader) */
329
- forReader: (type: string) => boolean
424
+ /** the event types that are messages for the reader (declared forReader), each with the `data` fields it requires */
425
+ forReader: ReadonlyMap<string, readonly string[]>
330
426
  }
331
427
 
332
428
  /** A project's status at one moment: what `workpad status`, the page lists and the log's marks take. */
@@ -372,6 +468,8 @@ export function projectStatus({ pages, events, listeners, forAgent, forReader }:
372
468
  if (fromReader(e)) last.set(e.page, e.ts)
373
469
  }
374
470
  for (const e of subscriptions(events)) {
471
+ // taking the unfollowed pages makes none of them the agent's (takesUnfollowed)
472
+ if (e.data?.unfollowed) continue
375
473
  const now = subscribers.get(e.page) ?? []
376
474
  if (!now.includes(e.by!)) subscribers.set(e.page, [...now, e.by!])
377
475
  }
@@ -403,6 +501,9 @@ export function projectStatus({ pages, events, listeners, forAgent, forReader }:
403
501
  unreceived: own.filter(e => fromReader(e) && forAgent(e.type) && !received.has(e.id) && !handled.has(e.id)),
404
502
  unhandled: own.filter(e => fromReader(e) && forAgent(e.type) && received.has(e.id) && !handled.has(e.id)),
405
503
  awaitingReply: awaitingReply(own),
504
+ // what an agent last did on the page besides editing it (a message, a question in a chat):
505
+ // the reader's own events and the log's bookkeeping (received, handled, read…) aren't news
506
+ updated: own.findLast(e => !fromReader(e) && !e.type.startsWith('workpad:'))?.ts ?? null,
406
507
  listeners: listening,
407
508
  }
408
509
  }),
@@ -440,7 +541,7 @@ export function statusLines(p: PageStatus, file: string, { waiting = true } = {}
440
541
  */
441
542
  export const whose = (p: PageStatus, me: string | null, names: Map<string, string> = new Map()): string =>
442
543
  p.subscribers.length
443
- ? p.subscribers.map(s => (s === me ? 'you' : (names.get(s) ?? (s.length > 16 ? s.slice(0, 8) : s)))).join(', ')
544
+ ? p.subscribers.map(s => (s === me ? 'you' : agentLabel(s, names))).join(', ')
444
545
  : 'no one subscribed'
445
546
 
446
547
  /** The type of a chat message: `{ chat, text }` (the chat plugin's; the core shows the agent's as small pages). */
package/src/turns.ts ADDED
@@ -0,0 +1,56 @@
1
+ // When an agent session's turn last ended, one file per session: `.workpad/turns/<session>`.
2
+ // A coding agent's harness gives the session what a channel pushes (the pong of `workpad agent
3
+ // ping`, an answer) only once its turn ends, so `workpad agent ping --wait`, run in the background
4
+ // while the agent works on, counts its timeout from the first turn end after its ping, not from the
5
+ // ping. The plugins of coding agents record it:
6
+ // - claude: the SessionStart hook marks the session as one whose turn ends are recorded, and the
7
+ // Stop hook records each end it lets happen (not one it continues with a reminder);
8
+ // - opencode: its channel marks a session once it follows it, and `hook stop`, which the plugin
9
+ // opencode loads runs when the session goes idle, records each end.
10
+ // The file holds the time of the last end (ms since the epoch, this machine's clock, as the wait's),
11
+ // or nothing: marked, no end yet. A session without a file (another harness, a hook not installed)
12
+ // has none of this, and the wait counts from its ping.
13
+ import fs from 'node:fs'
14
+ import path from 'node:path'
15
+
16
+ const dirOf = (wp: string) => path.join(wp, 'turns')
17
+ const fileOf = (wp: string, session: string) => path.join(dirOf(wp), encodeURIComponent(session))
18
+
19
+ /** Records older than this go when a turn end is written: their sessions are long over. */
20
+ const KEEP = 7 * 24 * 3600_000
21
+
22
+ /**
23
+ * Record for `session` that its turn ended now (`ended`), or only that its turn ends are recorded
24
+ * (a mark: an end recorded before stays).
25
+ */
26
+ export function recordTurn(wp: string, session: string | null, ended: boolean) {
27
+ if (!session) return
28
+ const dir = dirOf(wp)
29
+ const file = fileOf(wp, session)
30
+ if (!ended && fs.existsSync(file)) return
31
+ if (!fs.existsSync(dir)) {
32
+ fs.mkdirSync(dir, { recursive: true })
33
+ fs.writeFileSync(path.join(dir, '.gitignore'), "# when each agent session's turn last ended; not for git\n*\n")
34
+ }
35
+ if (ended)
36
+ for (const name of fs.readdirSync(dir))
37
+ if (name !== '.gitignore' && Date.now() - fs.statSync(path.join(dir, name)).mtimeMs > KEEP)
38
+ fs.rmSync(path.join(dir, name), { force: true })
39
+ fs.writeFileSync(`${file}.tmp`, ended ? String(Date.now()) : '')
40
+ fs.renameSync(`${file}.tmp`, file)
41
+ }
42
+
43
+ /**
44
+ * What is recorded of `session`'s turns: null when nothing is (its turn ends aren't recorded);
45
+ * else when its last turn ended, null when none has since it was marked.
46
+ */
47
+ export function lastTurnEnd(wp: string, session: string): { ended: number | null } | null {
48
+ let text: string
49
+ try {
50
+ text = fs.readFileSync(fileOf(wp, session), 'utf8')
51
+ } catch {
52
+ return null
53
+ }
54
+ const ended = Number(text)
55
+ return { ended: text && Number.isFinite(ended) ? ended : null }
56
+ }