@bigmistqke/workpad 0.18.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/bin/workpad.ts +238 -17
  2. package/dist/bin/workpad.js +191 -13
  3. package/dist/plugins/badge/README.md +59 -10
  4. package/dist/plugins/badge/index.js +130 -8
  5. package/dist/plugins/badge/public/style.css +132 -12
  6. package/dist/plugins/chat/index.js +7 -1
  7. package/dist/plugins/claude/README.md +13 -5
  8. package/dist/plugins/claude/channel.js +25 -2
  9. package/dist/plugins/claude/doctor.js +43 -47
  10. package/dist/plugins/claude/index.js +24 -8
  11. package/dist/plugins/claude/session.js +46 -1
  12. package/dist/plugins/opencode/channel.js +42 -7
  13. package/dist/plugins/opencode/index.js +2 -0
  14. package/dist/src/agents.js +7 -2
  15. package/dist/src/client/page/main.js +23 -0
  16. package/dist/src/events.js +6 -5
  17. package/dist/src/help.js +18 -4
  18. package/dist/src/hub.js +62 -2
  19. package/dist/src/listen.js +36 -4
  20. package/dist/src/listeners.js +14 -4
  21. package/dist/src/pages/board.js +9 -4
  22. package/dist/src/pages/index.js +2 -4
  23. package/dist/src/pages/markdown.js +47 -16
  24. package/dist/src/pages/render.js +128 -32
  25. package/dist/src/server.js +69 -6
  26. package/dist/src/state.js +2 -1
  27. package/dist/src/status.js +11 -2
  28. package/dist/src/turns.js +41 -0
  29. package/package.json +6 -1
  30. package/plugins/badge/README.md +59 -10
  31. package/plugins/badge/index.ts +141 -8
  32. package/plugins/badge/public/style.css +132 -12
  33. package/plugins/chat/index.ts +9 -1
  34. package/plugins/claude/README.md +13 -5
  35. package/plugins/claude/channel.ts +26 -2
  36. package/plugins/claude/doctor.ts +58 -39
  37. package/plugins/claude/index.ts +30 -8
  38. package/plugins/claude/session.ts +32 -0
  39. package/plugins/opencode/channel.ts +42 -7
  40. package/plugins/opencode/index.ts +4 -0
  41. package/skills/workpad/SKILL.md +30 -6
  42. package/src/agents.ts +9 -1
  43. package/src/client/page/board.ts +29 -0
  44. package/src/define.ts +28 -1
  45. package/src/events.ts +23 -2
  46. package/src/help.ts +18 -4
  47. package/src/hub.ts +80 -2
  48. package/src/listen.ts +47 -4
  49. package/src/listeners.ts +22 -1
  50. package/src/pages/board.ts +10 -3
  51. package/src/pages/index.ts +8 -10
  52. package/src/pages/markdown.ts +55 -8
  53. package/src/pages/render.ts +132 -35
  54. package/src/server.ts +84 -6
  55. package/src/state.ts +3 -0
  56. package/src/status.ts +15 -1
  57. package/src/turns.ts +56 -0
package/src/help.ts CHANGED
@@ -30,7 +30,7 @@ export const COMMAND_HELP: Record<string, CommandHelp> = {
30
30
  },
31
31
 
32
32
  agent: {
33
- usage: '[name <name> | name --clear | list | unsubscribe <agent> [--page <p>…] | ping [<code>]]',
33
+ usage: '[name <name> | name --clear | list | unsubscribe <agent> [--page <p>…] | ping [<code> | --wait [--timeout <s>]]]',
34
34
  summary: 'who you are on the boards: your id and name; name yourself, see who else is around, check a channel reaches you',
35
35
  details: `Your id is --agent, else WORKPAD_AGENT, else the session an agent plugin names (claude(),
36
36
  opencode()). Alone, it says your id and your name.
@@ -46,7 +46,11 @@ opencode()). Alone, it says your id and your name.
46
46
  into the session, the way answers will, with the code to confirm with. Once
47
47
  confirmed, the channel listens on your pages, and the answers it brings count
48
48
  as received. No channel (exit 1), or no pong: nothing brings answers here, so
49
- listen for them.`,
49
+ listen for them. --wait: run it in the background; it pings and ends when
50
+ the pong is confirmed (exit 0), or --timeout seconds (120) after the
51
+ session's turn ended without one (exit 1): then listen. A pong comes only
52
+ once the turn ends, so it waits while the turn runs, 30 minutes at most;
53
+ where its plugin records no turn ends, it counts from the ping.`,
50
54
  },
51
55
 
52
56
  show: {
@@ -152,7 +156,7 @@ One chat's messages: workpad chat prune <page|file> <chat>.`,
152
156
  --follow then print each new one as it comes`,
153
157
  },
154
158
  listen: {
155
- usage: '[--page <p>…] [--type <t>] [--wait [--timeout <s>] | --channel] [--agent <who>]',
159
+ usage: '[--page <p>… | --unfollowed] [--type <t>] [--wait [--timeout <s>] | --channel] [--agent <who>]',
156
160
  summary:
157
161
  "print what you haven't handled on the pages (the reader's answers, other agents' messages) and each as it comes; --wait stops at the first, --channel hands over to your channel",
158
162
  details: `${FILTERS}
@@ -160,6 +164,7 @@ One chat's messages: workpad chat prune <page|file> <chat>.`,
160
164
  --wait stop once it printed: all there are, or with none, the first to come
161
165
  --timeout <seconds> with --wait: exit 2 when nothing came
162
166
  --channel make the pages yours and exit: your session's channel brings their answers
167
+ --unfollowed the pages no live session follows, for a coordinator: see below
163
168
  --agent <who> who listens (else WORKPAD_AGENT, else the session an agent plugin names)
164
169
 
165
170
  It prints, one line each, everything on the page you haven't handled, also from before it started,
@@ -175,7 +180,16 @@ answers to handle, chats waiting for your reply, questions still unanswered.
175
180
 
176
181
  Any number listen on a page, and each hears everything there but its own events: agents can talk
177
182
  to each other in the same chats. Without --page it listens on every page (in a project of the
178
- machine's entries, every page of the entry).`,
183
+ machine's entries, every page of the entry).
184
+
185
+ --unfollowed is for a coordinator, so no page swallows an answer: it listens on every page no live
186
+ session follows (in a project of the machine's entries, in every project of the entry, each line
187
+ with its \`project\` and \`url\`), and hands out the reader's answers there that no other agent
188
+ received. Following is listening now: a running listen on the page, or a confirmed channel of a
189
+ session it belongs to; a subscriber that is gone, between turns, or whose channel was never
190
+ confirmed follows nothing. A page drops out while someone follows it, and joins when its last
191
+ follower goes, as do new pages. What it hands out counts as received by you. With --channel your
192
+ confirmed channel takes these pages on (none becomes yours) and it exits.`,
179
193
  },
180
194
  append: {
181
195
  usage: '--page <p> --type <t> [--data <json>]',
package/src/hub.ts CHANGED
@@ -19,10 +19,14 @@
19
19
  // a listen over a whole entry, for as long as the connection is open: held on
20
20
  // every page of its projects, also those that appear meanwhile; its stream is
21
21
  // told the entry's projects (listeners.ts). Any number run
22
+ // /api/listen?unfollowed[&entry=<name>][&agent=<who>]
23
+ // a listen on the pages no one follows, across every project (or one entry's):
24
+ // held on each, and told them (`event: pages`) as they change (listeners.ts)
22
25
  //
23
26
  // A project's server is made when the project is found and closed when it goes, so a project
24
27
  // appears and disappears without a restart. Each keeps its own state, config and log, as it would
25
28
  // on a port of its own: the shared server only routes.
29
+ import { filesFold } from './pages/render.ts'
26
30
  import fs from 'node:fs'
27
31
  import path from 'node:path'
28
32
  import type { IncomingMessage, ServerResponse } from 'node:http'
@@ -88,6 +92,32 @@ export function createHub({
88
92
  tell: () => void
89
93
  }
90
94
  const entryListens = new Set<EntryListen>()
95
+
96
+ // the listens on the pages no one follows (`workpad listen --unfollowed`): each project holds
97
+ // one for it, and says which of its pages those are; its stream is told them all together
98
+ interface UnfollowedListen {
99
+ entry: string | null
100
+ listener: Listener
101
+ held: Map<Served, () => void>
102
+ pages: Map<Served, string[]>
103
+ tell: () => void
104
+ }
105
+ const unfollowedListens = new Set<UnfollowedListen>()
106
+ function takeOn(s: Served, ul: UnfollowedListen) {
107
+ if (ul.held.has(s) || (ul.entry && s.entry !== ul.entry)) return
108
+ ul.held.set(
109
+ s,
110
+ s.server.unfollowed(ul.listener, pages => {
111
+ ul.pages.set(s, pages)
112
+ ul.tell()
113
+ }),
114
+ )
115
+ }
116
+ function letGo(s: Served, ul: UnfollowedListen) {
117
+ ul.held.get(s)?.()
118
+ ul.held.delete(s)
119
+ if (ul.pages.delete(s)) ul.tell()
120
+ }
91
121
  /** An entry listen held on one of its projects, so the project's pages say it listens. */
92
122
  function hold(s: Served, el: EntryListen) {
93
123
  if (!el.held.has(s)) el.held.set(s, s.server.addListener(el.listener))
@@ -123,6 +153,7 @@ export function createHub({
123
153
  for (const [key, s] of served)
124
154
  if (!wanted.has(key)) {
125
155
  for (const el of entryListens) release(s, el)
156
+ for (const ul of unfollowedListens) letGo(s, ul)
126
157
  s.server.close()
127
158
  served.delete(key)
128
159
  console.log(`workpad: ${s.base} is gone (${s.dir})`)
@@ -142,6 +173,7 @@ export function createHub({
142
173
  const s: Served = { ...p, project, server }
143
174
  served.set(key, s)
144
175
  for (const el of entryListens) if (el.entry === p.entry) hold(s, el)
176
+ for (const ul of unfollowedListens) takeOn(s, ul)
145
177
  console.log(`workpad: ${p.base} → ${p.dir}`)
146
178
  }
147
179
  // an entry listen follows its projects coming and going
@@ -230,12 +262,13 @@ export function createHub({
230
262
  title: p.title,
231
263
  url: `${s.base}/${p.page.split('/').map(encodeURIComponent).join('/')}`,
232
264
  mtime: mtimeOf(p.file),
265
+ updated: Math.max(mtimeOf(p.file), p.updated ? Date.parse(p.updated) : 0),
233
266
  open: p.open,
234
267
  unread: p.unread.length,
235
268
  unreceived: p.unreceived.length,
236
269
  }))
237
- .toSorted((a, b) => b.mtime - a.mtime)
238
- return { ...at, pages, active: pages[0]?.mtime ?? 0 }
270
+ .toSorted((a, b) => b.updated - a.updated)
271
+ return { ...at, pages, active: pages[0]?.updated ?? 0 }
239
272
  }
240
273
  const index = () => Promise.all([...served.values()].map(indexOf))
241
274
 
@@ -291,6 +324,7 @@ export function createHub({
291
324
  setImmediate(() => onShutdown?.())
292
325
  return
293
326
  }
327
+ if (p === '/api/listen' && url.searchParams.has('unfollowed')) return listenUnfollowed(req, res, url.searchParams)
294
328
  if (p === '/api/listen' && url.searchParams.has('entry')) return listenEntry(req, res, url.searchParams)
295
329
  // the API across every project: each project's list, put together
296
330
  const what = /^\/api\/(\w+)$/.exec(p)?.[1]
@@ -302,6 +336,14 @@ export function createHub({
302
336
  return sendJson(res, 200, all.flat())
303
337
  }
304
338
  if (p === '/api/stream') return streamAll(req, res, Object.fromEntries(url.searchParams))
339
+ // a project's files, for its fold on the overview: listed when the reader opens it, off the
340
+ // event loop, so the overview's render reads no project's files (src/pages/render.ts)
341
+ if (p === '/api/files') {
342
+ const s = [...served.values()].find(x => x.base === url.searchParams.get('base'))
343
+ if (!s) return sendJson(res, 404, { error: 'no such project' })
344
+ if (!(await s.server.files().catch(() => false))) return sendJson(res, 403, { error: 'its files are not served' })
345
+ return sendJson(res, 200, await filesFold(s.dir, s.base))
346
+ }
305
347
  if (p === '/favicon.ico') {
306
348
  res.writeHead(204)
307
349
  return void res.end()
@@ -371,6 +413,42 @@ export function createHub({
371
413
  }
372
414
  const closers = new Set<() => void>()
373
415
 
416
+ /**
417
+ * A listen on the pages no one follows (`workpad listen --unfollowed`), across every project or
418
+ * one entry's: each project holds it on those of its pages (WorkpadServer.unfollowed), and its
419
+ * stream is told them all, once for several changes.
420
+ */
421
+ function listenUnfollowed(req: IncomingMessage, res: ServerResponse, q: URLSearchParams) {
422
+ let telling = false
423
+ const ul: UnfollowedListen = {
424
+ entry: q.get('entry'),
425
+ listener: listenerOf(q),
426
+ held: new Map(),
427
+ pages: new Map(),
428
+ tell: () => {
429
+ if (telling) return
430
+ telling = true
431
+ setImmediate(() => {
432
+ telling = false
433
+ const projects = [...ul.pages]
434
+ .filter(([, pages]) => pages.length)
435
+ .map(([s, pages]) => ({ dir: s.dir, base: s.base, pages }))
436
+ stream.send('pages', { projects })
437
+ })
438
+ },
439
+ }
440
+ const stream = holdStream(req, res, () => {
441
+ closers.delete(stream.end)
442
+ unfollowedListens.delete(ul)
443
+ for (const s of [...ul.held.keys()]) letGo(s, ul)
444
+ })
445
+ closers.add(stream.end)
446
+ unfollowedListens.add(ul)
447
+ for (const s of served.values()) takeOn(s, ul)
448
+ // told at once, also with no project to take on
449
+ ul.tell()
450
+ }
451
+
374
452
  /** /api/stream across every project: as a project's, each event with its project. */
375
453
  function streamAll(req: IncomingMessage, res: ServerResponse, query: Record<string, string>) {
376
454
  res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', connection: 'keep-alive' })
package/src/listen.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  // and the listen hands out from each project's log.
6
6
  import http from 'node:http'
7
7
  import https from 'node:https'
8
- import type { Followed, Snapshot } from './listeners.ts'
8
+ import type { Followed, Snapshot, Unfollowed } from './listeners.ts'
9
9
 
10
10
  /**
11
11
  * A held GET to the server, over http or https as its address says: a server reached at an https
@@ -22,6 +22,10 @@ export interface ListenOptions {
22
22
  query: Record<string, string>
23
23
  /** a listen over a whole entry: the projects it covers, at once and on every change */
24
24
  onSnapshot?: (snapshot: Snapshot) => void
25
+ /** a listen on the unfollowed pages (`unfollowed` in the query): which they are, at once and on every change */
26
+ onPages?: (unfollowed: Unfollowed) => void
27
+ /** let go of the server, and don't connect again */
28
+ signal?: AbortSignal
25
29
  }
26
30
 
27
31
  /**
@@ -29,15 +33,22 @@ export interface ListenOptions {
29
33
  * Resolves once the server holds it; with `orNone`, also after a first try that found no server
30
34
  * running (a listen reads the log all the same, and registers once one appears).
31
35
  */
32
- export function listen({ at, query, onSnapshot }: ListenOptions, { orNone = false } = {}): Promise<void> {
36
+ export function listen(
37
+ { at, query, onSnapshot, onPages, signal }: ListenOptions,
38
+ { orNone = false } = {},
39
+ ): Promise<void> {
33
40
  return new Promise(settled => {
41
+ let current: http.ClientRequest | null = null
42
+ signal?.addEventListener('abort', () => current?.destroy())
34
43
  const connect = async () => {
44
+ if (signal?.aborted) return settled()
35
45
  let base: string | null = null
36
46
  try {
37
47
  base = await at()
38
48
  } catch {
39
49
  /* none runs */
40
50
  }
51
+ if (signal?.aborted) return settled()
41
52
  if (!base) {
42
53
  if (orNone) settled()
43
54
  return setTimeout(connect, 2000).unref()
@@ -49,7 +60,7 @@ export function listen({ at, query, onSnapshot }: ListenOptions, { orNone = fals
49
60
  setTimeout(connect, ms).unref()
50
61
  }
51
62
  }
52
- const req = get(`${base}/api/listen?${new URLSearchParams(query)}`, res => {
63
+ const req = (current = get(`${base}/api/listen?${new URLSearchParams(query)}`, res => {
53
64
  res.setEncoding('utf8')
54
65
  settled()
55
66
  // held: the connection alone does not keep the command running. Not before: until the
@@ -66,10 +77,11 @@ export function listen({ at, query, onSnapshot }: ListenOptions, { orNone = fals
66
77
  const event = /^event: (.*)$/m.exec(block)?.[1]
67
78
  const data = /^data: (.*)$/m.exec(block)?.[1]
68
79
  if (event === 'projects' && data && onSnapshot) onSnapshot(JSON.parse(data) as Snapshot)
80
+ if (event === 'pages' && data && onPages) onPages(JSON.parse(data) as Unfollowed)
69
81
  }
70
82
  })
71
83
  res.on('close', () => retry(1000))
72
- })
84
+ }))
73
85
  req.on('error', () => retry(2000))
74
86
  }
75
87
  void connect()
@@ -98,6 +110,37 @@ export function everyProject(start: (project: Followed, signal: AbortSignal) =>
98
110
  }
99
111
  }
100
112
 
113
+ /** A page of a project a listen on the unfollowed pages takes. */
114
+ export interface PageOf extends Followed {
115
+ page: string
116
+ }
117
+
118
+ /**
119
+ * A listen on the unfollowed pages: `start` is called once for each page as it joins, to hand out
120
+ * from its project's log; a page that drops out (someone follows it now) is stopped (`signal`).
121
+ * @returns what takes each list of pages the server sends
122
+ */
123
+ export function everyPage(start: (page: PageOf, signal: AbortSignal) => void): (unfollowed: Unfollowed) => void {
124
+ const taken = new Map<string, AbortController>()
125
+ return ({ projects }) => {
126
+ const now = new Set<string>()
127
+ for (const p of projects)
128
+ for (const page of p.pages) {
129
+ const key = `${p.dir}\n${page}`
130
+ now.add(key)
131
+ if (taken.has(key)) continue
132
+ const stop = new AbortController()
133
+ taken.set(key, stop)
134
+ start({ dir: p.dir, base: p.base, page }, stop.signal)
135
+ }
136
+ for (const [key, stop] of taken)
137
+ if (!now.has(key)) {
138
+ stop.abort()
139
+ taken.delete(key)
140
+ }
141
+ }
142
+ }
143
+
101
144
  /** What a channel's line does with what the server sends it (`CommandContext.channel`). */
102
145
  export interface ChannelHandlers {
103
146
  /** `workpad agent ping` in the session: push the pong, with this code, into it */
package/src/listeners.ts CHANGED
@@ -26,7 +26,9 @@ export function createRegistry(): Registry {
26
26
  }
27
27
  return {
28
28
  list: (page = null) =>
29
- [...listeners].filter(l => page == null || covers(l, page)).map(({ page, type, agent }) => ({ page, type, agent })),
29
+ [...listeners]
30
+ .filter(l => page == null || covers(l, page))
31
+ .map(({ page, type, agent, unfollowed }) => ({ page, type, agent, ...(unfollowed && { unfollowed }) })),
30
32
  add(l) {
31
33
  listeners.add(l)
32
34
  changed()
@@ -59,8 +61,27 @@ export const listenerOf = (q: URLSearchParams): Listener => ({
59
61
  page: q.get('page') || '',
60
62
  type: q.get('type') || null,
61
63
  agent: q.get('agent') || null,
64
+ ...(q.has('unfollowed') && { unfollowed: true as const }),
62
65
  })
63
66
 
67
+ /**
68
+ * Does `l` follow `page`: is someone there to take whatever comes on it? A listener covering the
69
+ * page, for every type: a running listen on it (or above it, or on every page), and a confirmed
70
+ * channel, which holds one on each page of its session's. A listen for one form only (`--type`)
71
+ * leaves the rest to no one, and a listen on the unfollowed pages follows nothing itself. A
72
+ * subscriber listening nowhere (gone, between turns, or a channel never confirmed) is no listener.
73
+ */
74
+ export const follows = (l: Listener, page: string): boolean => !l.unfollowed && !l.type && covers(l, page)
75
+
76
+ /**
77
+ * What a listen on the unfollowed pages (`workpad listen --unfollowed`) is told (`event: pages`), at
78
+ * once and whenever it changes: per project, the pages no one follows now; a project with none is
79
+ * left out.
80
+ */
81
+ export interface Unfollowed {
82
+ projects: (Followed & { pages: string[] })[]
83
+ }
84
+
64
85
  /**
65
86
  * Hold a /api/listen connection open as an event stream (with a ping, so nothing between closes it
66
87
  * as idle). `send` writes an event on it; `onEnd` runs once, when the agent goes or `end` is called.
@@ -23,6 +23,13 @@ export const waitingOn = (p: IndexPage): Waiting => ({
23
23
 
24
24
  export const total = (w: Waiting): number => w.open + w.unread + w.unreceived
25
25
 
26
+ /**
27
+ * How much a card needs the reader: something waiting on it first, then the newest update (its file,
28
+ * or an agent's message or question on it) first.
29
+ */
30
+ export const byAttention = (a: Card, b: Card): number =>
31
+ Number(total(b.waiting) > 0) - Number(total(a.waiting) > 0) || b.page.updated - a.page.updated
32
+
26
33
  /** A page on the board, with the project it is in. */
27
34
  export interface Card<P extends IndexProject = IndexProject> {
28
35
  page: IndexPage
@@ -48,10 +55,10 @@ export function byState<P extends IndexProject>(
48
55
  for (const project of projects)
49
56
  for (const page of project.pages) {
50
57
  const card = { page, project, waiting: waitingOn(page) }
51
- const column = total(card.waiting) > 0 ? 'waiting' : now - page.mtime <= activeFor ? 'active' : 'quiet'
58
+ const column = total(card.waiting) > 0 ? 'waiting' : now - page.updated <= activeFor ? 'active' : 'quiet'
52
59
  columns[column].push(card)
53
60
  }
54
- for (const cards of [columns.waiting, columns.active, columns.quiet]) cards.sort((a, b) => b.page.mtime - a.page.mtime)
61
+ for (const cards of [columns.waiting, columns.active, columns.quiet]) cards.sort(byAttention)
55
62
  return columns
56
63
  }
57
64
 
@@ -70,7 +77,7 @@ export function byProject<P extends IndexProject>(projects: readonly P[]): Proje
70
77
  .map(project => {
71
78
  const cards = project.pages
72
79
  .map(page => ({ page, project, waiting: waitingOn(page) }))
73
- .sort((a, b) => b.page.mtime - a.page.mtime)
80
+ .sort(byAttention)
74
81
  const waiting = cards.reduce(
75
82
  (sum, c) => ({
76
83
  open: sum.open + c.waiting.open,
@@ -3,7 +3,7 @@
3
3
  // loaded config (see loader.ts); the server renders with it.
4
4
  import { resolveBlocks, type BlockEntry } from './blocks.ts'
5
5
  import { createAgentMessageRender, createBlocksRender, createDocs, createMessageRender, createRender } from './render.ts'
6
- import { chatNames, formDetails, formNames, type FormDetail, type Island } from './markdown.ts'
6
+ import { pageAsks, type Island, type PageAsks } from './markdown.ts'
7
7
  import type { PageSource, RenderContext, Rendered, StoredPage } from '../define.ts'
8
8
  import type { Plugin, TextLink } from '../define.ts'
9
9
 
@@ -28,12 +28,12 @@ export interface Pages {
28
28
  render(page: StoredPage, ctx: RenderContext): Promise<Rendered>
29
29
  /** how pages are written, and which blocks the plugins bring: what `workpad docs` prints first */
30
30
  docs(ctx: RenderContext): string
31
- /** the questions a page asks: its named forms, whose answers are events of their name */
32
- questions(page: PageSource): string[]
33
- /** the chats a page shows: one under every form, and the chat blocks */
34
- chats(page: PageSource): string[]
35
- /** what each of a page's `:::form`s asks: its question, options and buttons */
36
- forms(page: PageSource): FormDetail[]
31
+ /**
32
+ * What a page asks, with what the plugins add at its end: its questions (its named forms, whose
33
+ * answers are events of their name), its chats (one under every form, and the chat blocks) and
34
+ * what each of its `:::form`s asks (its question, options and buttons). One parse for all three.
35
+ */
36
+ asks(page: PageSource): PageAsks
37
37
  /** a message's markdown (a comment, a chat message) as HTML, and the stylesheets it needs */
38
38
  message(text: string, ctx: RenderContext): Promise<{ html: string; styles: string[] }>
39
39
  /**
@@ -72,8 +72,6 @@ export function createPages(options: PagesOptions): Pages {
72
72
  agentMessage: createAgentMessageRender(blocks, options.links ?? [], options.composers),
73
73
  blocks: createBlocksRender(blocks, options.links ?? [], options.composers),
74
74
  docs: createDocs(blocks),
75
- questions: page => formNames(ended(page).body),
76
- chats: page => chatNames(ended(page).body),
77
- forms: page => formDetails(ended(page).body),
75
+ asks: page => pageAsks(ended(page).body),
78
76
  }
79
77
  }
@@ -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
  /**