@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
@@ -316,7 +316,11 @@ export function titleWords(nodes: MdNode[], resolve: (name: string) => unknown):
316
316
  * code block doesn't count.
317
317
  */
318
318
  export function formNames(source: string) {
319
- const tree = parseMarkdown(String(source ?? ''))
319
+ return formNamesIn(parseMarkdown(String(source ?? '')))
320
+ }
321
+
322
+ /** formNames of a source parsed already. */
323
+ function formNamesIn(tree: MdNode) {
320
324
  const names: string[] = []
321
325
  const walk = (node: MdNode) => {
322
326
  if (node.type === 'containerDirective' && node.name === 'form') {
@@ -338,10 +342,10 @@ export function formNames(source: string) {
338
342
 
339
343
  /**
340
344
  * The `:::form`s in a source by the name they are written with, null for one without; in order, and
341
- * not those shown in a code fence. For a message's forms, which are named in their chat.
345
+ * not those shown in a code fence. For a message's forms, which are named in their chat. Kept: a
346
+ * status asks it of every agent message in every chat, and a message's text never changes.
342
347
  */
343
- export function formsIn(source: string): { name: string | null; markdown: string }[] {
344
- const text = String(source ?? '')
348
+ export const formsIn = byText(5000, (text): readonly { readonly name: string | null; readonly markdown: string }[] => {
345
349
  const out: { name: string | null; markdown: string }[] = []
346
350
  const walk = (node: MdNode) => {
347
351
  if (node.type === 'containerDirective' && node.name === 'form') {
@@ -356,7 +360,7 @@ export function formsIn(source: string): { name: string | null; markdown: string
356
360
  }
357
361
  walk(parseMarkdown(text))
358
362
  return out
359
- }
363
+ })
360
364
 
361
365
  /** One option of a form's question, as written: `:radio[Label]{name=field value=… recommended other}`. */
362
366
  export interface FormOption {
@@ -429,15 +433,53 @@ function describeForm(node: MdNode): FormDetail {
429
433
 
430
434
  /** What each `:::form` in a source asks, in order (not those shown in a code fence). */
431
435
  export function formDetails(source: string): FormDetail[] {
436
+ return formDetailsIn(parseMarkdown(String(source ?? '')))
437
+ }
438
+
439
+ /** formDetails of a source parsed already. */
440
+ function formDetailsIn(tree: MdNode): FormDetail[] {
432
441
  const out: FormDetail[] = []
433
442
  const walk = (node: MdNode) => {
434
443
  if (node.type === 'containerDirective' && node.name === 'form') out.push(describeForm(node))
435
444
  for (const child of node.children ?? []) walk(child)
436
445
  }
437
- walk(parseMarkdown(String(source ?? '')))
446
+ walk(tree)
438
447
  return out
439
448
  }
440
449
 
450
+ /** What a page asks: its questions (formNames), its chats (chatNames), what each form asks (formDetails). */
451
+ export interface PageAsks {
452
+ questions: string[]
453
+ chats: string[]
454
+ forms: FormDetail[]
455
+ }
456
+
457
+ /**
458
+ * A page's questions, chats and forms, from one parse of its source. The same source is asked again
459
+ * after the config reloads, which a change to a plugin does: its answer is kept.
460
+ */
461
+ export const pageAsks = byText(1000, (source): Readonly<PageAsks> => {
462
+ const tree = parseMarkdown(source)
463
+ return { questions: formNamesIn(tree), chats: chatNamesIn(tree), forms: formDetailsIn(tree) }
464
+ })
465
+
466
+ /**
467
+ * `fn` with its answers kept by the text it was asked about, the oldest dropped past `limit`: for
468
+ * what is read from a parse, asked again and again of the same pages and messages. What it answers
469
+ * is shared, never to be changed.
470
+ */
471
+ function byText<T>(limit: number, fn: (text: string) => T): (source: string) => T {
472
+ const kept = new Map<string, T>()
473
+ return source => {
474
+ const text = String(source ?? '')
475
+ if (kept.has(text)) return kept.get(text)!
476
+ const value = fn(text)
477
+ if (kept.size >= limit) kept.delete(kept.keys().next().value!)
478
+ kept.set(text, value)
479
+ return value
480
+ }
481
+ }
482
+
441
483
  /**
442
484
  * The forms in the agent's messages in `chats` (a page's chats, chatNames), by their names there:
443
485
  * `<chat>/<name>`, an unnamed one numbered in its chat (Api.message). They are questions of the
@@ -473,8 +515,12 @@ export function chatForms(
473
515
  * on the page.
474
516
  */
475
517
  export function chatNames(source: string) {
476
- const tree = parseMarkdown(String(source ?? ''))
477
- const names: string[] = formNames(source)
518
+ return chatNamesIn(parseMarkdown(String(source ?? '')))
519
+ }
520
+
521
+ /** chatNames of a source parsed already. */
522
+ function chatNamesIn(tree: MdNode) {
523
+ const names: string[] = formNamesIn(tree)
478
524
  // a form without its chat (`chat=false`): no chat of that name
479
525
  const without = new Set<string>()
480
526
  const walk = (node: MdNode) => {
@@ -808,6 +854,7 @@ plugin "${name}" failed to compose around block "${block.name}": ${(err as Error
808
854
  fileUrl,
809
855
  anchor,
810
856
  chat: inChat,
857
+ problem,
811
858
  }
812
859
 
813
860
  /**
@@ -418,7 +418,7 @@ function card(c: Card<BoardProject>, withProject: boolean) {
418
418
  <a class="wp-board-title" href="${c.page.url}">${c.page.title}</a>
419
419
  ${counts(c.waiting, `${c.page.url}#wp-waiting`)}
420
420
  ${withProject && html`<span class="wp-board-project">${c.project.label}</span>`}
421
- <span class="wp-meta wp-board-when">edited ${time(c.page.mtime)}</span>
421
+ <span class="wp-meta wp-board-when">updated ${time(c.page.updated)}</span>
422
422
  </li>`
423
423
  }
424
424
 
package/src/server.ts CHANGED
@@ -67,7 +67,7 @@ import { SCROLL, agentMessagesIn, awaiting, isAgentMessage, projectStatus, type
67
67
  import { formsIn, messageForms } from './pages/markdown.ts'
68
68
  import { fileFilter, type FileFilter } from './files.ts'
69
69
  import { titleOf } from './pages/render.ts'
70
- import { createRegistry, holdStream, listenerOf } from './listeners.ts'
70
+ import { createRegistry, follows, holdStream, listenerOf } from './listeners.ts'
71
71
  import { inPublic } from './public.ts'
72
72
  import { build, type BuildResult } from './build.ts'
73
73
  import { PAGE_CLIENT, RUNTIME, frontmatterOf, pageDocument, pluginParts, type Render, type SetUp } from './document.ts'
@@ -142,6 +142,13 @@ export interface WorkpadServer {
142
142
  addListener(l: Listener): () => void
143
143
  /** call `fn` whenever a listener comes or goes; returns what stops it */
144
144
  onListeners(fn: () => void): () => void
145
+ /**
146
+ * Hold `listener` on each page no one follows (`workpad listen --unfollowed`), for as long as it
147
+ * isn't stopped: a page drops out once someone follows it, and joins when its last follower goes,
148
+ * as does a new page. `onPages` is told the pages, at once and whenever they change.
149
+ * @returns what stops it
150
+ */
151
+ unfollowed(listener: Listener, onPages: (pages: string[]) => void): () => void
145
152
  /** who listens now: the running listens and channels, and an entry's listens held for it */
146
153
  listeners(): Listener[]
147
154
  /** whether it serves its files (its config read first) */
@@ -416,10 +423,8 @@ export function createServer(
416
423
  // what each form asks, for the API
417
424
  let details: FormDetail[] = []
418
425
  try {
419
- const source = pageSource(id, file)
420
- asks = renderer?.questions(source) ?? []
421
- chats = renderer?.chats(source)
422
- details = renderer?.forms(source) ?? []
426
+ const said = renderer?.asks(pageSource(id, file))
427
+ if (said) ({ questions: asks, chats, forms: details } = said)
423
428
  } catch (err) {
424
429
  console.error('questions:', err)
425
430
  }
@@ -442,10 +447,19 @@ export function createServer(
442
447
  async function snapshot(listed: PagesSource['pages']): Promise<ProjectStatus> {
443
448
  const { pages: renderer, handedOut, forReader } = await config()
444
449
  const events = readEvents(project.eventsFile)
450
+ // each page's messages, the log gone through once instead of once for every chat of every page
451
+ const messages = new Map<string, WpEvent[]>()
452
+ for (const e of events) {
453
+ if (!isAgentMessage(e)) continue
454
+ const own = messages.get(e.page)
455
+ if (own) own.push(e)
456
+ else messages.set(e.page, [e])
457
+ }
445
458
  const pages = listed.map(p => {
446
459
  const page = { id: p.id, file: p.file, ...questionsOf(renderer, p.id, p.file) }
447
460
  // 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 ?? [])] }
461
+ const forms = messageForms(messages.get(p.id) ?? [], p.id, page.chats ?? [])
462
+ return { ...page, asks: [...page.asks, ...forms] }
449
463
  })
450
464
  return projectStatus({
451
465
  pages,
@@ -718,6 +732,56 @@ export function createServer(
718
732
  const pings = new Map<string, string>()
719
733
  const pingCode = () => crypto.randomBytes(3).toString('hex')
720
734
 
735
+ // ---- the unfollowed pages ----------------------------------------------------------------------
736
+ // A listen on the pages no one follows (`workpad listen --unfollowed`, a coordinator's) is held as
737
+ // a listener on each of them, so they say someone listens; that listener follows nothing itself
738
+ // (listeners.ts, follows). The set is looked at again whenever a listener comes or goes and
739
+ // whenever a page changes (made, deleted).
740
+ interface Unfollowing {
741
+ listener: Listener
742
+ onPages(pages: string[]): void
743
+ held: Map<string, () => void>
744
+ told: string | null
745
+ }
746
+ const unfollowing = new Set<Unfollowing>()
747
+ let looking = false
748
+ function lookAgain() {
749
+ if (looking || !unfollowing.size) return
750
+ looking = true
751
+ // after what changed is done: holding a page is a change of listeners too
752
+ setImmediate(() => {
753
+ looking = false
754
+ const pages = pagesIn(project.pagesDir)
755
+ .map(p => p.id)
756
+ .filter(id => !registry.list(id).some(l => follows(l, id)))
757
+ for (const u of unfollowing) {
758
+ for (const [page, release] of u.held)
759
+ if (!pages.includes(page)) {
760
+ release()
761
+ u.held.delete(page)
762
+ }
763
+ for (const page of pages)
764
+ if (!u.held.has(page)) u.held.set(page, registry.add({ ...u.listener, page, unfollowed: true }))
765
+ const now = JSON.stringify(pages)
766
+ if (now !== u.told) {
767
+ u.told = now
768
+ u.onPages(pages)
769
+ }
770
+ }
771
+ })
772
+ }
773
+ registry.onChange(lookAgain)
774
+ function unfollowed(listener: Listener, onPages: (pages: string[]) => void): () => void {
775
+ const u: Unfollowing = { listener, onPages, held: new Map(), told: null }
776
+ unfollowing.add(u)
777
+ lookAgain()
778
+ return () => {
779
+ if (!unfollowing.delete(u)) return
780
+ for (const release of u.held.values()) release()
781
+ u.held.clear()
782
+ }
783
+ }
784
+
721
785
  // ---- live changes ------------------------------------------------------------------------------
722
786
  // The browser listens on a WebSocket at /api/live, each message `{ event, data }`. `change`: its
723
787
  // page changed; `events`: the log grew; `listeners`: an agent started or stopped waiting; `style`:
@@ -757,6 +821,7 @@ export function createServer(
757
821
 
758
822
  function pageChanged(id: string) {
759
823
  onChange?.()
824
+ lookAgain()
760
825
  for (const c of clients) {
761
826
  if (c.isDir ? !c.page || id.startsWith(c.page + '/') : c.page === id || c.page + '/index' === id)
762
827
  notify(c, 'change')
@@ -1218,6 +1283,18 @@ export function createServer(
1218
1283
  if (p === '/api/status') return sendJson(res, 200, await status(q.page || null))
1219
1284
  if (p === '/api/listeners') return sendJson(res, 200, listenersFor(q.page ?? null))
1220
1285
  if (p === '/api/stamps') return sendJson(res, 200, stamps())
1286
+ if (p === '/api/listen' && url.searchParams.has('unfollowed')) {
1287
+ // on the pages no one follows, told which they are as they change
1288
+ const stop = unfollowed(listenerOf(url.searchParams), pages =>
1289
+ stream.send('pages', { projects: pages.length ? [{ dir: project.dir, base, pages }] : [] }),
1290
+ )
1291
+ const stream = holdStream(req, res, () => {
1292
+ stop()
1293
+ streams.delete(stream.end)
1294
+ })
1295
+ streams.add(stream.end)
1296
+ return
1297
+ }
1221
1298
  if (p === '/api/listen') {
1222
1299
  // any number listen on a page; each is a listener for as long as its connection is open
1223
1300
  const remove = registry.add(listenerOf(url.searchParams))
@@ -1370,6 +1447,7 @@ export function createServer(
1370
1447
  elsewhere: () => notifyAll('elsewhere'),
1371
1448
  addListener: l => registry.add(l),
1372
1449
  onListeners: fn => registry.onChange(fn),
1450
+ unfollowed,
1373
1451
  status: (page = null) => status(page),
1374
1452
  read: readList,
1375
1453
  stream,
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
@@ -251,7 +251,7 @@ export function receivedIds(events: WpEvent[]): Set<string> {
251
251
  export function channelSince(events: WpEvent[], agent: string, page: string): string | null {
252
252
  let since: string | null = null
253
253
  for (const e of subscriptions(events)) {
254
- if (e.by !== agent) continue
254
+ if (e.by !== agent || e.data?.unfollowed) continue
255
255
  if (!(e.page === '' || e.page === page || page.startsWith(`${e.page}/`))) continue
256
256
  if (!e.data?.channel) return null
257
257
  since ??= e.id
@@ -259,6 +259,15 @@ export function channelSince(events: WpEvent[], agent: string, page: string): st
259
259
  return since
260
260
  }
261
261
 
262
+ /**
263
+ * Does `agent` take the pages no one follows through its channel (`workpad listen --unfollowed
264
+ * --channel`)? Said by a subscription on every page (`''`) with data `{ channel: true, unfollowed:
265
+ * true }`; it makes no page the agent's (no subscriber of any), and `workpad agent unsubscribe`
266
+ * takes it off with the rest.
267
+ */
268
+ export const takesUnfollowed = (events: WpEvent[], agent: string): boolean =>
269
+ subscriptions(events).some(e => e.by === agent && !!e.data?.unfollowed)
270
+
262
271
  /**
263
272
  * The ids of the reader's events the agent handled: acknowledged (`workpad:handled`), or replied
264
273
  * to after them (see the top of this file). The log is gone through once: each of the reader's
@@ -372,6 +381,8 @@ export function projectStatus({ pages, events, listeners, forAgent, forReader }:
372
381
  if (fromReader(e)) last.set(e.page, e.ts)
373
382
  }
374
383
  for (const e of subscriptions(events)) {
384
+ // taking the unfollowed pages makes none of them the agent's (takesUnfollowed)
385
+ if (e.data?.unfollowed) continue
375
386
  const now = subscribers.get(e.page) ?? []
376
387
  if (!now.includes(e.by!)) subscribers.set(e.page, [...now, e.by!])
377
388
  }
@@ -403,6 +414,9 @@ export function projectStatus({ pages, events, listeners, forAgent, forReader }:
403
414
  unreceived: own.filter(e => fromReader(e) && forAgent(e.type) && !received.has(e.id) && !handled.has(e.id)),
404
415
  unhandled: own.filter(e => fromReader(e) && forAgent(e.type) && received.has(e.id) && !handled.has(e.id)),
405
416
  awaitingReply: awaitingReply(own),
417
+ // what an agent last did on the page besides editing it (a message, a question in a chat):
418
+ // the reader's own events and the log's bookkeeping (received, handled, read…) aren't news
419
+ updated: own.findLast(e => !fromReader(e) && !e.type.startsWith('workpad:'))?.ts ?? null,
406
420
  listeners: listening,
407
421
  }
408
422
  }),
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
+ }