@bigmistqke/workpad 0.0.0-stage → 0.18.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 (277) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +781 -2
  3. package/bin/workpad.ts +1509 -0
  4. package/dist/_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/taggedTemplateLiteral.js +5 -0
  5. package/dist/bin/workpad.js +1190 -0
  6. package/dist/client/runtime.js +1194 -0
  7. package/dist/define.js +27 -0
  8. package/dist/plugins/alert/README.md +18 -0
  9. package/dist/plugins/alert/index.js +40 -0
  10. package/dist/plugins/alert/public/style.css +40 -0
  11. package/dist/plugins/ansi/README.md +36 -0
  12. package/dist/plugins/ansi/index.js +63 -0
  13. package/dist/plugins/ansi/public/style.css +28 -0
  14. package/dist/plugins/badge/README.md +32 -0
  15. package/dist/plugins/badge/index.js +28 -0
  16. package/dist/plugins/badge/public/style.css +30 -0
  17. package/dist/plugins/chat/README.md +81 -0
  18. package/dist/plugins/chat/index.js +96 -0
  19. package/dist/plugins/chat/public/client.js +3 -0
  20. package/dist/plugins/chat/public/style.css +143 -0
  21. package/dist/plugins/claude/README.md +116 -0
  22. package/dist/plugins/claude/channel.js +130 -0
  23. package/dist/plugins/claude/doctor.js +316 -0
  24. package/dist/plugins/claude/index.js +199 -0
  25. package/dist/plugins/claude/session.js +68 -0
  26. package/dist/plugins/code/README.md +54 -0
  27. package/dist/plugins/code/diff.js +75 -0
  28. package/dist/plugins/code/index.js +105 -0
  29. package/dist/plugins/code/public/client.js +1 -0
  30. package/dist/plugins/code/public/style.css +99 -0
  31. package/dist/plugins/comments/README.md +30 -0
  32. package/dist/plugins/comments/index.js +39 -0
  33. package/dist/plugins/comments/public/client.js +24 -0
  34. package/dist/plugins/comments/public/style.css +224 -0
  35. package/dist/plugins/details/README.md +24 -0
  36. package/dist/plugins/details/index.js +28 -0
  37. package/dist/plugins/details/public/style.css +7 -0
  38. package/dist/plugins/draft/README.md +14 -0
  39. package/dist/plugins/draft/index.js +27 -0
  40. package/dist/plugins/draft/public/style.css +21 -0
  41. package/dist/plugins/forge/README.md +22 -0
  42. package/dist/plugins/forge/index.js +83 -0
  43. package/dist/plugins/form/README.md +126 -0
  44. package/dist/plugins/form/index.js +179 -0
  45. package/dist/plugins/form/public/style.css +172 -0
  46. package/dist/plugins/grid/README.md +45 -0
  47. package/dist/plugins/grid/index.js +35 -0
  48. package/dist/plugins/grid/public/style.css +98 -0
  49. package/dist/plugins/iframe/README.md +18 -0
  50. package/dist/plugins/iframe/index.js +49 -0
  51. package/dist/plugins/iframe/public/style.css +28 -0
  52. package/dist/plugins/index.js +44 -0
  53. package/dist/plugins/lightbox/README.md +24 -0
  54. package/dist/plugins/lightbox/index.js +20 -0
  55. package/dist/plugins/lightbox/public/client.js +4 -0
  56. package/dist/plugins/lightbox/public/style.css +66 -0
  57. package/dist/plugins/mermaid/README.md +21 -0
  58. package/dist/plugins/mermaid/index.js +42 -0
  59. package/dist/plugins/mermaid/public/style.css +21 -0
  60. package/dist/plugins/opencode/README.md +48 -0
  61. package/dist/plugins/opencode/channel.js +92 -0
  62. package/dist/plugins/opencode/index.js +64 -0
  63. package/dist/plugins/opencode/shim.js +150 -0
  64. package/dist/plugins/quiet/README.md +26 -0
  65. package/dist/plugins/quiet/index.js +23 -0
  66. package/dist/plugins/tabs/README.md +44 -0
  67. package/dist/plugins/tabs/index.js +75 -0
  68. package/dist/plugins/tabs/public/client.js +1 -0
  69. package/dist/plugins/tabs/public/style.css +98 -0
  70. package/dist/plugins/terminal/README.md +63 -0
  71. package/dist/plugins/terminal/host.js +338 -0
  72. package/dist/plugins/terminal/index.js +170 -0
  73. package/dist/plugins/terminal/modes.js +32 -0
  74. package/dist/plugins/terminal/public/client.js +41 -0
  75. package/dist/plugins/terminal/public/style.css +511 -0
  76. package/dist/plugins/terminal/server.js +256 -0
  77. package/dist/plugins/terminal/sizes.js +58 -0
  78. package/dist/plugins/timeline/README.md +48 -0
  79. package/dist/plugins/timeline/index.js +83 -0
  80. package/dist/plugins/timeline/public/style.css +138 -0
  81. package/dist/plugins/toc/README.md +40 -0
  82. package/dist/plugins/toc/index.js +29 -0
  83. package/dist/plugins/toc/public/client.js +1 -0
  84. package/dist/plugins/toc/public/style.css +117 -0
  85. package/dist/plugins/window/README.md +51 -0
  86. package/dist/plugins/window/index.js +91 -0
  87. package/dist/solid/index.js +41 -0
  88. package/dist/src/agents.js +81 -0
  89. package/dist/src/anchors.js +52 -0
  90. package/dist/src/api.js +282 -0
  91. package/dist/src/archive.js +49 -0
  92. package/dist/src/auth.js +67 -0
  93. package/dist/src/build.js +159 -0
  94. package/dist/src/client/page/base.css +1762 -0
  95. package/dist/src/client/page/main.js +2098 -0
  96. package/dist/src/config.js +76 -0
  97. package/dist/src/document.js +93 -0
  98. package/dist/src/entries.js +264 -0
  99. package/dist/src/events.js +322 -0
  100. package/dist/src/files.js +47 -0
  101. package/dist/src/formstate.js +65 -0
  102. package/dist/src/help.js +211 -0
  103. package/dist/src/html.js +34 -0
  104. package/dist/src/hub.js +341 -0
  105. package/dist/src/icons.js +6 -0
  106. package/dist/src/listen.js +132 -0
  107. package/dist/src/listeners.js +64 -0
  108. package/dist/src/load.js +81 -0
  109. package/dist/src/loader.js +179 -0
  110. package/dist/src/migrate.js +314 -0
  111. package/dist/src/package.js +52 -0
  112. package/dist/src/pages/blocks.js +67 -0
  113. package/dist/src/pages/board.js +59 -0
  114. package/dist/src/pages/index.js +27 -0
  115. package/dist/src/pages/markdown.js +863 -0
  116. package/dist/src/pages/render.js +665 -0
  117. package/dist/src/pages/window.js +29 -0
  118. package/dist/src/plugins.js +283 -0
  119. package/dist/src/public.js +24 -0
  120. package/dist/src/rename.js +130 -0
  121. package/dist/src/running.js +146 -0
  122. package/dist/src/serve.js +188 -0
  123. package/dist/src/server.js +1105 -0
  124. package/dist/src/site.js +179 -0
  125. package/dist/src/state.js +155 -0
  126. package/dist/src/status.js +323 -0
  127. package/dist/src/thread.js +68 -0
  128. package/dist/src/watchdog.js +38 -0
  129. package/dist/src/ws.js +128 -0
  130. package/package.json +154 -4
  131. package/plugins/README.md +304 -0
  132. package/plugins/alert/README.md +18 -0
  133. package/plugins/alert/index.ts +50 -0
  134. package/plugins/alert/public/style.css +40 -0
  135. package/plugins/ansi/README.md +36 -0
  136. package/plugins/ansi/index.ts +95 -0
  137. package/plugins/ansi/public/style.css +28 -0
  138. package/plugins/badge/README.md +32 -0
  139. package/plugins/badge/index.ts +36 -0
  140. package/plugins/badge/public/style.css +30 -0
  141. package/plugins/chat/README.md +81 -0
  142. package/plugins/chat/autosize.ts +139 -0
  143. package/plugins/chat/client.tsx +187 -0
  144. package/plugins/chat/index.ts +146 -0
  145. package/plugins/chat/public/style.css +143 -0
  146. package/plugins/claude/README.md +116 -0
  147. package/plugins/claude/channel.ts +136 -0
  148. package/plugins/claude/doctor.ts +274 -0
  149. package/plugins/claude/index.ts +248 -0
  150. package/plugins/claude/session.ts +70 -0
  151. package/plugins/code/README.md +54 -0
  152. package/plugins/code/client.ts +73 -0
  153. package/plugins/code/diff.ts +96 -0
  154. package/plugins/code/index.ts +136 -0
  155. package/plugins/code/public/style.css +99 -0
  156. package/plugins/comments/README.md +30 -0
  157. package/plugins/comments/client.ts +723 -0
  158. package/plugins/comments/index.ts +48 -0
  159. package/plugins/comments/public/style.css +224 -0
  160. package/plugins/details/README.md +24 -0
  161. package/plugins/details/index.ts +30 -0
  162. package/plugins/details/public/style.css +7 -0
  163. package/plugins/draft/README.md +14 -0
  164. package/plugins/draft/index.ts +23 -0
  165. package/plugins/draft/public/style.css +21 -0
  166. package/plugins/forge/README.md +22 -0
  167. package/plugins/forge/index.ts +84 -0
  168. package/plugins/form/README.md +126 -0
  169. package/plugins/form/index.ts +199 -0
  170. package/plugins/form/public/style.css +172 -0
  171. package/plugins/grid/README.md +45 -0
  172. package/plugins/grid/index.ts +41 -0
  173. package/plugins/grid/public/style.css +98 -0
  174. package/plugins/iframe/README.md +18 -0
  175. package/plugins/iframe/index.ts +53 -0
  176. package/plugins/iframe/public/style.css +28 -0
  177. package/plugins/index.ts +49 -0
  178. package/plugins/lightbox/README.md +24 -0
  179. package/plugins/lightbox/client.ts +109 -0
  180. package/plugins/lightbox/index.ts +25 -0
  181. package/plugins/lightbox/public/style.css +66 -0
  182. package/plugins/mermaid/README.md +21 -0
  183. package/plugins/mermaid/index.ts +46 -0
  184. package/plugins/mermaid/public/style.css +21 -0
  185. package/plugins/opencode/README.md +48 -0
  186. package/plugins/opencode/channel.ts +112 -0
  187. package/plugins/opencode/index.ts +91 -0
  188. package/plugins/opencode/shim.ts +166 -0
  189. package/plugins/quiet/README.md +26 -0
  190. package/plugins/quiet/index.ts +28 -0
  191. package/plugins/tabs/README.md +44 -0
  192. package/plugins/tabs/client.ts +96 -0
  193. package/plugins/tabs/index.ts +103 -0
  194. package/plugins/tabs/public/style.css +98 -0
  195. package/plugins/terminal/README.md +63 -0
  196. package/plugins/terminal/client.ts +391 -0
  197. package/plugins/terminal/host.ts +434 -0
  198. package/plugins/terminal/index.ts +199 -0
  199. package/plugins/terminal/modes.ts +30 -0
  200. package/plugins/terminal/public/style.css +225 -0
  201. package/plugins/terminal/server.ts +266 -0
  202. package/plugins/terminal/sizes.ts +72 -0
  203. package/plugins/timeline/README.md +48 -0
  204. package/plugins/timeline/index.ts +82 -0
  205. package/plugins/timeline/public/style.css +138 -0
  206. package/plugins/toc/README.md +40 -0
  207. package/plugins/toc/client.ts +236 -0
  208. package/plugins/toc/index.ts +55 -0
  209. package/plugins/toc/public/style.css +117 -0
  210. package/plugins/window/README.md +51 -0
  211. package/plugins/window/index.ts +92 -0
  212. package/skills/workpad/SKILL.md +588 -0
  213. package/solid/index.tsx +80 -0
  214. package/src/agents.ts +133 -0
  215. package/src/anchors.ts +85 -0
  216. package/src/api.ts +444 -0
  217. package/src/archive.ts +75 -0
  218. package/src/auth.ts +99 -0
  219. package/src/build.ts +213 -0
  220. package/src/client/base.ts +19 -0
  221. package/src/client/forms.ts +420 -0
  222. package/src/client/markdown.ts +147 -0
  223. package/src/client/page/base.css +1762 -0
  224. package/src/client/page/board.ts +137 -0
  225. package/src/client/page/elsewhere.ts +153 -0
  226. package/src/client/page/fresh.ts +343 -0
  227. package/src/client/page/heading-link.ts +32 -0
  228. package/src/client/page/live.ts +134 -0
  229. package/src/client/page/main.ts +398 -0
  230. package/src/client/page/orphans.ts +64 -0
  231. package/src/client/page/place.ts +260 -0
  232. package/src/client/page/sort.ts +49 -0
  233. package/src/client/page/sticky.ts +58 -0
  234. package/src/client/page/theme.ts +36 -0
  235. package/src/client/page/view.ts +9 -0
  236. package/src/client/page/waiting.ts +278 -0
  237. package/src/client/page/window.ts +40 -0
  238. package/src/client/reactive.ts +19 -0
  239. package/src/client/read.ts +111 -0
  240. package/src/client/runtime.ts +499 -0
  241. package/src/client/scroll.ts +90 -0
  242. package/src/client/toast.ts +99 -0
  243. package/src/config.ts +111 -0
  244. package/src/define.ts +997 -0
  245. package/src/document.ts +191 -0
  246. package/src/entries.ts +352 -0
  247. package/src/events.ts +463 -0
  248. package/src/files.ts +74 -0
  249. package/src/formstate.ts +72 -0
  250. package/src/help.ts +238 -0
  251. package/src/html.ts +44 -0
  252. package/src/hub.ts +426 -0
  253. package/src/icons.ts +18 -0
  254. package/src/listen.ts +171 -0
  255. package/src/listeners.ts +89 -0
  256. package/src/load.ts +113 -0
  257. package/src/loader.ts +227 -0
  258. package/src/migrate.ts +352 -0
  259. package/src/package.ts +62 -0
  260. package/src/pages/blocks.ts +106 -0
  261. package/src/pages/board.ts +89 -0
  262. package/src/pages/index.ts +79 -0
  263. package/src/pages/markdown.ts +976 -0
  264. package/src/pages/render.ts +748 -0
  265. package/src/pages/window.ts +69 -0
  266. package/src/plugins.ts +319 -0
  267. package/src/public.ts +39 -0
  268. package/src/rename.ts +147 -0
  269. package/src/running.ts +171 -0
  270. package/src/serve.ts +221 -0
  271. package/src/server.ts +1385 -0
  272. package/src/site.ts +170 -0
  273. package/src/state.ts +327 -0
  274. package/src/status.ts +466 -0
  275. package/src/thread.ts +98 -0
  276. package/src/watchdog.ts +53 -0
  277. package/src/ws.ts +155 -0
package/src/events.ts ADDED
@@ -0,0 +1,463 @@
1
+ // The project's events, one JSON object per line, in `.workpad/events.ndjson`. An event has a
2
+ // `type`: a submitted form's type is the form's name; a plugin can append events of its own.
3
+ //
4
+ // Two layers. The primitives work on the log and nothing else: read it, follow it, append to it,
5
+ // record that an agent received or handled an event. Handing out (`handOut`) is built from them alone: it gives
6
+ // each answer to an agent once, also one given before it started, and never the agent's own. The
7
+ // command line offers both (`events`, `events --follow`, `append`, `handled`; `listen`), and a
8
+ // script can import them (`@bigmistqke/workpad/log`) to use the log in ways of its own.
9
+ import fs from 'node:fs'
10
+ import crypto from 'node:crypto'
11
+ import type { WpEvent } from './define.ts'
12
+ import {
13
+ SETTLE,
14
+ HANDLED,
15
+ NAME,
16
+ RECEIVED,
17
+ SUBSCRIBE,
18
+ UNSUBSCRIBE,
19
+ channelSince,
20
+ fromReader,
21
+ handledIds,
22
+ namesOf,
23
+ receivedIds,
24
+ subscriptions,
25
+ } from './status.ts'
26
+
27
+ export {
28
+ SETTLE,
29
+ HANDLED,
30
+ NAME,
31
+ RECEIVED,
32
+ SUBSCRIBE,
33
+ UNSUBSCRIBE,
34
+ channelSince,
35
+ fromReader,
36
+ handledIds,
37
+ namesOf,
38
+ receivedIds,
39
+ subscriptions,
40
+ }
41
+
42
+ /** What is appended: the id and time are added. */
43
+ export interface EventInput {
44
+ /** the id the browser gave it, so a send it retries is appended once (see isEventId); else a new one */
45
+ id?: unknown
46
+ page?: unknown
47
+ type?: unknown
48
+ action?: string | null
49
+ data?: Record<string, unknown>
50
+ }
51
+
52
+ /** Which events: `page` (and the pages below it) and `type`, as `workpad listen` takes them. */
53
+ export interface EventFilter {
54
+ page?: string | null
55
+ /** several pages: an event on any of them (each with the pages below it, unless `exact`) */
56
+ pages?: string[] | null
57
+ type?: string | null
58
+ /** `page` alone, not the pages below it */
59
+ exact?: boolean
60
+ }
61
+
62
+ // ---- primitives ----------------------------------------------------------------------------------
63
+
64
+ /** An event id as the log has them: the time in base 36, a dash, random hex. */
65
+ export const isEventId = (id: unknown): id is string =>
66
+ typeof id === 'string' && /^[0-9a-z]{6,12}-[0-9a-f]{6,32}$/.test(id)
67
+
68
+ /**
69
+ * Append one event; `action` is the button that submitted a form, null for anything else. `from`
70
+ * is set only for events the command line writes ('cli'), so that waits skip them and pages can
71
+ * tell them apart; what the browser appends has none.
72
+ */
73
+ export function appendEvent(
74
+ file: string,
75
+ input: EventInput,
76
+ from: 'cli' | null = null,
77
+ by: string | null = null,
78
+ ): WpEvent {
79
+ const event: WpEvent = {
80
+ id: isEventId(input.id) ? input.id : `${Date.now().toString(36)}-${crypto.randomBytes(3).toString('hex')}`,
81
+ ts: new Date().toISOString(),
82
+ page: String(input.page ?? ''),
83
+ type: String(input.type ?? ''),
84
+ action: input.action ?? null,
85
+ data: input.data ?? {},
86
+ ...(from ? { from } : {}),
87
+ ...(by ? { by } : {}),
88
+ }
89
+ fs.appendFileSync(file, JSON.stringify(event) + '\n')
90
+ return event
91
+ }
92
+
93
+ export function parseLines(text: string): WpEvent[] {
94
+ const out: WpEvent[] = []
95
+ for (const line of text.split('\n')) {
96
+ if (!line.trim()) continue
97
+ let event
98
+ try {
99
+ event = JSON.parse(line)
100
+ } catch {
101
+ continue /* a corrupt line */
102
+ }
103
+ out.push(event)
104
+ }
105
+ return out
106
+ }
107
+
108
+ export function readEvents(file: string): WpEvent[] {
109
+ return read(file).events
110
+ }
111
+
112
+ // A log from before the marks were named received and handled (0.10 and older) is converted once,
113
+ // the first time anything reads it: each old mark gets its new type, and nothing else changes.
114
+ const RENAMED: Record<string, string> = { 'workpad:taken': RECEIVED, 'workpad:picked': HANDLED }
115
+ const OLD_MARKS = Object.keys(RENAMED).map(type => Buffer.from(`"type":"${type}"`))
116
+
117
+ function convert(file: string) {
118
+ rewrite(file, e => (RENAMED[e.type] ? { ...e, type: RENAMED[e.type] } : e))
119
+ }
120
+
121
+ /**
122
+ * The events in the log, and the byte offset they end at: after its last whole line. A line still
123
+ * being written is left out, and following from `end` gets it whole, so reading and then following
124
+ * from `end` never loses or splits an event.
125
+ */
126
+ export function read(file: string): { events: WpEvent[]; end: number } {
127
+ let buf: Buffer
128
+ try {
129
+ buf = fs.readFileSync(file)
130
+ } catch {
131
+ return { events: [], end: 0 }
132
+ }
133
+ if (OLD_MARKS.some(m => buf.includes(m))) {
134
+ convert(file)
135
+ try {
136
+ buf = fs.readFileSync(file)
137
+ } catch {
138
+ return { events: [], end: 0 }
139
+ }
140
+ }
141
+ const end = buf.lastIndexOf(0x0a) + 1
142
+ return { events: parseLines(buf.subarray(0, end).toString('utf8')), end }
143
+ }
144
+
145
+ /**
146
+ * Call `onEvent` for each event appended to the log from byte `from` on (a line boundary, such as
147
+ * `read`'s `end`), in order, as whole lines arrive. Checks every `interval` ms (default 200).
148
+ * Returns a function that stops it.
149
+ *
150
+ * The log can be rewritten under it (`prune`: a page closed, its events gone): a new file, or a
151
+ * shorter one. Then it reads the log again and goes on after the last event it had passed on (by
152
+ * time, and by id among those of the same time), so nothing is passed on twice.
153
+ */
154
+ export function follow(
155
+ file: string,
156
+ from: number,
157
+ onEvent: (event: WpEvent) => void,
158
+ { interval = 200 } = {},
159
+ ): () => void {
160
+ let offset = from
161
+ let partial = ''
162
+ let inode: number | null = null
163
+ try {
164
+ inode = fs.statSync(file).ino
165
+ } catch {
166
+ /* not there yet */
167
+ }
168
+ // where it is in the log, to find its place again after a rewrite
169
+ let lastTs = ''
170
+ let atLastTs = new Set<string>()
171
+ // the events before `from` count as passed on: the place starts after the last of them
172
+ if (from > 0) {
173
+ let before: WpEvent[] = []
174
+ try {
175
+ before = parseLines(fs.readFileSync(file).subarray(0, from).toString('utf8'))
176
+ } catch {
177
+ /* not there */
178
+ }
179
+ for (const e of before) {
180
+ if (e.ts > lastTs) {
181
+ lastTs = e.ts
182
+ atLastTs = new Set()
183
+ }
184
+ if (e.ts === lastTs) atLastTs.add(e.id)
185
+ }
186
+ }
187
+ const pass = (e: WpEvent) => {
188
+ if (e.ts > lastTs) {
189
+ lastTs = e.ts
190
+ atLastTs = new Set()
191
+ }
192
+ atLastTs.add(e.id)
193
+ onEvent(e)
194
+ }
195
+ const poll = () => {
196
+ let stat: fs.Stats
197
+ try {
198
+ stat = fs.statSync(file)
199
+ } catch {
200
+ return
201
+ }
202
+ if ((inode != null && stat.ino !== inode) || stat.size < offset) {
203
+ // rewritten: read it again, and go on after the place reached
204
+ inode = stat.ino
205
+ const { events, end } = read(file)
206
+ offset = end
207
+ partial = ''
208
+ for (const e of events) if (e.ts > lastTs || (e.ts === lastTs && !atLastTs.has(e.id))) pass(e)
209
+ return
210
+ }
211
+ inode = stat.ino
212
+ if (stat.size === offset) return
213
+ const fd = fs.openSync(file, 'r')
214
+ const buf = Buffer.alloc(stat.size - offset)
215
+ fs.readSync(fd, buf, 0, buf.length, offset)
216
+ fs.closeSync(fd)
217
+ offset = stat.size
218
+ const text = partial + buf.toString('utf8')
219
+ const cut = text.lastIndexOf('\n')
220
+ partial = text.slice(cut + 1)
221
+ for (const e of parseLines(text.slice(0, cut + 1))) pass(e)
222
+ }
223
+ const timer = setInterval(poll, interval)
224
+ return () => clearInterval(timer)
225
+ }
226
+
227
+ /**
228
+ * Rewrite the log, event by event: `change` returns the event to keep (as it is, or changed) or
229
+ * null to drop it. The log is written anew and put in place in one rename; when an event was
230
+ * appended while it was being written, it starts over, so none is lost. A follow running across it
231
+ * reads it again and goes on after the last event it passed on (see follow). Lines that aren't
232
+ * events are kept as they are. Returns how many were dropped and changed.
233
+ */
234
+ export function rewrite(
235
+ file: string,
236
+ change: (event: WpEvent) => WpEvent | null,
237
+ ): { removed: number; changed: number } {
238
+ for (let attempt = 0; attempt < 10; attempt++) {
239
+ let buf: Buffer
240
+ try {
241
+ buf = fs.readFileSync(file)
242
+ } catch {
243
+ return { removed: 0, changed: 0 }
244
+ }
245
+ const keep: string[] = []
246
+ let removed = 0,
247
+ changed = 0
248
+ for (const line of buf.toString('utf8').split('\n')) {
249
+ if (!line.trim()) continue
250
+ let ev: WpEvent | null = null
251
+ try {
252
+ ev = JSON.parse(line)
253
+ } catch {
254
+ /* not an event: kept */
255
+ }
256
+ if (!ev) {
257
+ keep.push(line)
258
+ continue
259
+ }
260
+ const next = change(ev)
261
+ if (!next) {
262
+ removed++
263
+ continue
264
+ }
265
+ const text = JSON.stringify(next)
266
+ if (text !== JSON.stringify(ev)) changed++
267
+ keep.push(next === ev ? line : text)
268
+ }
269
+ if (!removed && !changed) return { removed, changed }
270
+ const tmp = `${file}.${process.pid}.tmp`
271
+ fs.writeFileSync(tmp, keep.length ? keep.join('\n') + '\n' : '')
272
+ // appended to meanwhile: that event would be lost with the old file
273
+ if (fs.statSync(file).size !== buf.length) {
274
+ fs.rmSync(tmp, { force: true })
275
+ continue
276
+ }
277
+ fs.renameSync(tmp, file)
278
+ return { removed, changed }
279
+ }
280
+ throw new Error('the log kept changing while it was being rewritten; try again')
281
+ }
282
+
283
+ /** Remove a page's events from the log (`workpad archive` and `destroy`, `workpad prune`): those of exactly
284
+ * that page, and of them only those `which` says (all by default). Returns how many. */
285
+ export function prune(file: string, page: string, which: (event: WpEvent) => boolean = () => true): number {
286
+ return rewrite(file, e => (e.page === page && which(e) ? null : e)).removed
287
+ }
288
+
289
+ /**
290
+ * Change an agent's event in place (`workpad edit`): `data` is merged into its data; its id, time
291
+ * and everything else stay, so what refers to it (a reply, a mark, a read) still does. Only an
292
+ * agent's own events (`from: cli`): what the reader sent stays as they sent it. Returns the event
293
+ * as it is now.
294
+ */
295
+ export function editEvent(file: string, id: string, data: Record<string, unknown>): WpEvent {
296
+ const found = readEvents(file).find(e => e.id === id)
297
+ if (!found) throw new Error(`no event ${id} in the log`)
298
+ if (fromReader(found))
299
+ throw new Error(
300
+ `event ${id} is the reader's (${found.type}): what the reader sent stays as they sent it; an agent edits only its own`,
301
+ )
302
+ let edited: WpEvent | null = null
303
+ rewrite(file, e => (e.id === id ? (edited = { ...e, data: { ...e.data, ...data } }) : e))
304
+ return edited ?? found
305
+ }
306
+
307
+ /** `page` matches the page itself and every page below it, unless `exact`. */
308
+ const onPage = (event: WpEvent, page: string, exact?: boolean) =>
309
+ event.page === page || (!exact && event.page.startsWith(page + '/'))
310
+
311
+ export function matches(event: WpEvent, { page, pages, type, exact }: EventFilter = {}): boolean {
312
+ if (page && !onPage(event, page, exact)) return false
313
+ if (pages && !pages.some(p => onPage(event, p, exact))) return false
314
+ if (type && event.type !== type) return false
315
+ return true
316
+ }
317
+
318
+ // When an agent receives an event, a `workpad:received` event naming it is appended; when the
319
+ // agent is done with it, a `workpad:handled` (status.ts says what else counts as handled). The
320
+ // log is the only record: pages and `status` read the same marks.
321
+
322
+ /** Record that an agent (`by`, when it is known) received `event`. */
323
+ export function receive(file: string, event: WpEvent, by: string | null = null): WpEvent {
324
+ return appendEvent(file, { page: event.page, type: RECEIVED, data: { event: event.id } }, 'cli', by)
325
+ }
326
+
327
+ /** Record that an agent (`by`) handled `event` (`workpad handled`): it is no longer handed out. */
328
+ export function handle(file: string, event: WpEvent, by: string | null = null): WpEvent {
329
+ return appendEvent(file, { page: event.page, type: HANDLED, data: { event: event.id } }, 'cli', by)
330
+ }
331
+
332
+ // ---- handing out ---------------------------------------------------------------------------------
333
+
334
+ /**
335
+ * Which event types reach an agent unasked: a form's answers (types without a colon) always, and of
336
+ * the plugins' events (`<plugin>:<what>`) those declared `handOut: true`, given in `handedOut`.
337
+ */
338
+ export const forAgent =
339
+ (handedOut: ReadonlySet<string> = new Set()) =>
340
+ (type: string): boolean =>
341
+ !type.includes(':') || handedOut.has(type)
342
+
343
+ export interface HandOutOptions {
344
+ /** which event types it hands out unasked (see forAgent); a filter's `type` is handed out always */
345
+ forAgent?: (type: string) => boolean
346
+ /** stop after this many (default: no limit) */
347
+ count?: number
348
+ /**
349
+ * `workpad listen --wait`: everything there is now at once, and with nothing there,
350
+ * the first that comes (and any that come with it), then stop
351
+ */
352
+ batch?: boolean
353
+ /** after the backlog, follow the log for new events (default true) */
354
+ follow?: boolean
355
+ /** how often to look for new events, in ms (default 200) */
356
+ interval?: number
357
+ /** stops following */
358
+ signal?: AbortSignal
359
+ /**
360
+ * who it hands out to: an identity, or null for an unnamed process. Its own events are never
361
+ * handed to it, other agents' are; its received marks say it; `again` is what it received before.
362
+ */
363
+ agent?: string | null
364
+ /**
365
+ * Mark each as received once handed out (default true). Without, the receiver marks it itself
366
+ * once it has it (a channel: once its message is in the session).
367
+ */
368
+ mark?: boolean
369
+ /**
370
+ * An event's id (a channel's subscription, see channelSince): of the backlog before it, what
371
+ * someone already received is skipped, unless it is the reader's. A session that takes pages on
372
+ * gets what is new, not other agents' talk from before; `listen --wait` still hands it all out.
373
+ */
374
+ skipReceivedBefore?: string
375
+ }
376
+
377
+ /**
378
+ * Hand the events that match `filter` to `onEvent`, for agent `agent`: the reader's, and other
379
+ * agents' (an agent's event says who wrote it, `by`; one that doesn't is handed to no one). Each is
380
+ * marked received by `agent` once handed out. First the backlog: what is not handled, also from before
381
+ * this started, those `agent` received before saying so (`again`). Then, with `follow`, every new one as
382
+ * it comes. The backlog and the following split the log at one line boundary, so no event falls
383
+ * between them. Any number hand out from one log at once: each gets every event. Of the plugins'
384
+ * events only those for an agent (`forAgent`), unless the filter asks for a type by name.
385
+ *
386
+ * Resolves with how many were handed out: once `count` is reached, after the backlog without
387
+ * `follow`, or when `signal` aborts.
388
+ */
389
+ export function handOut(
390
+ file: string,
391
+ filter: EventFilter,
392
+ onEvent: (event: WpEvent, again: boolean) => void,
393
+ options: HandOutOptions = {},
394
+ ): Promise<number> {
395
+ const {
396
+ count = Infinity,
397
+ follow: following = true,
398
+ interval,
399
+ signal,
400
+ forAgent: isForAgent = forAgent(),
401
+ batch = false,
402
+ mark = true,
403
+ agent = null,
404
+ skipReceivedBefore,
405
+ } = options
406
+ return new Promise(resolve => {
407
+ let got = 0
408
+ let stop = () => {}
409
+ const finish = () => {
410
+ stop()
411
+ signal?.removeEventListener('abort', finish)
412
+ resolve(got)
413
+ }
414
+ // whose events: the reader's, and another agent's that says who it is
415
+ const fromOthers = (e: WpEvent) => fromReader(e) || (!!e.by && e.by !== agent)
416
+ // of those, the ones for an agent, unless the filter names a type
417
+ const wanted = (e: WpEvent) => fromOthers(e) && matches(e, filter) && (!!filter.type || isForAgent(e.type))
418
+ // what this identity received before, by id: handed out again, it says so
419
+ let before = new Set<string>()
420
+ // false once enough were handed out
421
+ const hand = (e: WpEvent) => {
422
+ onEvent(e, before.has(e.id))
423
+ if (mark) receive(file, e, agent)
424
+ // onEvent may have aborted it (a hand-out over several logs that has enough)
425
+ return ++got < count && !signal?.aborted
426
+ }
427
+ if (count <= 0 || signal?.aborted) return finish()
428
+ const { events, end } = read(file)
429
+ const handled = handledIds(events)
430
+ before = receivedBy(events, agent)
431
+ // the past before a channel's subscription: what someone received, unless it is the reader's
432
+ let skipping = !!skipReceivedBefore
433
+ const receivedAny = skipping ? receivedIds(events) : new Set<string>()
434
+ for (const e of events) {
435
+ if (skipping && e.id === skipReceivedBefore) skipping = false
436
+ if (skipping && !fromReader(e) && receivedAny.has(e.id)) continue
437
+ if (wanted(e) && !handled.has(e.id) && !hand(e)) return finish()
438
+ }
439
+ // a batch: what there was, if anything; else it goes on for the first to come
440
+ if (batch && got) return finish()
441
+ if (!following) return finish()
442
+ signal?.addEventListener('abort', finish)
443
+ stop = follow(
444
+ file,
445
+ end,
446
+ e => {
447
+ if (got < count && wanted(e) && !hand(e)) return finish()
448
+ // a batch ends with the first that came, once the events read with it are handed out too
449
+ if (batch && got) queueMicrotask(finish)
450
+ },
451
+ { interval },
452
+ )
453
+ })
454
+ }
455
+
456
+ /** The ids of the events `agent` received (null: an unnamed process, whose marks say no one). */
457
+ export function receivedBy(events: WpEvent[], agent: string | null): Set<string> {
458
+ const ids = new Set<string>()
459
+ for (const e of events)
460
+ if (e.type === RECEIVED && e.from === 'cli' && (e.by ?? null) === agent && typeof e.data?.event === 'string')
461
+ ids.add(e.data.event)
462
+ return ids
463
+ }
package/src/files.ts ADDED
@@ -0,0 +1,74 @@
1
+ // Which of a project's own files workpad shows: lists in a folder's page and the overview, serves
2
+ // at `-/<path>`, links to, and watches for changes. The config's `files` says it: `false` none,
3
+ // `true` (the default) all, or `{ include, exclude }`: globs relative to the project folder.
4
+ // node_modules and .git are always left out, at any depth: a repository's tools keep them, and an
5
+ // install or a checkout changes thousands of files there that nothing shows. `exclude` leaves out
6
+ // more; with `include`, only what it names is shown. A glob naming a folder takes in what is in it.
7
+ import path from 'node:path'
8
+
9
+ /** The config's `files` as an object: what to show of the project's own files. */
10
+ export interface FilesConfig {
11
+ /** globs of what to show, relative to the project folder (`docs/**`, `*.md`); without it, all */
12
+ include?: string[]
13
+ /** globs of what to leave out as well, on top of node_modules and .git (`dist`, `**\/*.log`) */
14
+ exclude?: string[]
15
+ }
16
+
17
+ /** Left out always: what a repository keeps for its tools. */
18
+ export const ALWAYS_EXCLUDED = ['**/node_modules', '**/.git']
19
+
20
+ export interface FileFilter {
21
+ /** the setting it was made from, to tell whether a new one changes anything */
22
+ key: string
23
+ /** Is this file or folder shown? `rel`: its path in the project folder, with `/` */
24
+ shows(rel: string): boolean
25
+ /** Can this folder hold something shown? A folder an include reaches into is walked, not shown. */
26
+ mayHold(rel: string): boolean
27
+ }
28
+
29
+ const glob = (rel: string, g: string) => path.posix.matchesGlob(rel, g)
30
+
31
+ /** The path and each folder above it: `a/b/c` → `a/b/c`, `a/b`, `a`. */
32
+ function* upward(rel: string) {
33
+ for (let p = rel; p && p !== '.'; p = path.posix.dirname(p)) yield p
34
+ }
35
+
36
+ /**
37
+ * Can a match of `g` be inside the folder `rel`? Segment by segment, up to the glob's first `**`
38
+ * (which can stand for any folders): `docs/*.md` reaches into `docs`, `*.md` into no folder at all.
39
+ */
40
+ function reachesInto(g: string, rel: string): boolean {
41
+ const parts = g.split('/')
42
+ const dirs = rel.split('/')
43
+ for (let i = 0; i < dirs.length; i++) {
44
+ const part = parts[i]
45
+ if (part === undefined) return false
46
+ if (part === '**') return true
47
+ // the glob's last segment names what is matched itself, not a folder to look in
48
+ if (i === parts.length - 1) return false
49
+ if (!path.posix.matchesGlob(dirs[i]!, part)) return false
50
+ }
51
+ return true
52
+ }
53
+
54
+ /** The filter for a project's `files` setting (anything but an object: everything but the always-excluded). */
55
+ export function fileFilter(files?: boolean | FilesConfig): FileFilter {
56
+ const config = typeof files === 'object' && files ? files : {}
57
+ const exclude = [...ALWAYS_EXCLUDED, ...(config.exclude ?? [])]
58
+ const include = config.include?.length ? config.include : null
59
+ // left out: it, or a folder it is in, matches an exclude
60
+ const excluded = (rel: string) => [...upward(rel)].some(p => exclude.some(g => glob(p, g)))
61
+ // taken in: it, or a folder it is in, matches an include
62
+ const included = (rel: string) => !include || [...upward(rel)].some(p => include.some(g => glob(p, g)))
63
+ return {
64
+ key: JSON.stringify({ include, exclude }),
65
+ shows: rel => !!rel && !excluded(rel) && included(rel),
66
+ mayHold: rel => {
67
+ if (!rel) return true
68
+ if (excluded(rel)) return false
69
+ if (!include || included(rel)) return true
70
+ // a folder on the way to what an include names: `docs` for `docs/adr/**`; any for `**/*.md`
71
+ return include.some(g => reachesInto(g, rel))
72
+ },
73
+ }
74
+ }
@@ -0,0 +1,72 @@
1
+ // What an agent changes of where a page's questions stand, without answering them: settle (answered
2
+ // elsewhere), hold (waits on something else, with a reason) and release (open again). Each is an event
3
+ // of the agent's in the log (SETTLE, HOLD, RELEASE in status.ts), checked against the page's status
4
+ // first. One definition for the command line (`workpad settle`, `hold`, `release`) and the
5
+ // server's API (POST /api/forms/settle, /hold, /release), so the two refuse the same things.
6
+ import type { PageStatus, WpEvent } from './define.ts'
7
+ import { appendEvent } from './events.ts'
8
+ import { HOLD, RELEASE, SETTLE } from './status.ts'
9
+
10
+ /** A refusal: what was asked can't be done as asked. `status` is for the API's answer. */
11
+ export class FormStateError extends Error {
12
+ status = 400
13
+ }
14
+
15
+ /** Are these questions of the page? Else a refusal that says which are. */
16
+ function check(p: PageStatus, names: string[]) {
17
+ if (!names.length)
18
+ throw new FormStateError(`name the forms: the questions on ${p.page} are ${p.asks.join(', ') || 'none'}`)
19
+ for (const name of names)
20
+ if (!p.asks.includes(name))
21
+ throw new FormStateError(`no form ${name} on ${p.page}: its questions are ${p.asks.join(', ') || 'none'}`)
22
+ }
23
+
24
+ const stateOf = (p: PageStatus, name: string) => p.questions.find(q => q.name === name)?.state
25
+
26
+ export interface Settled {
27
+ /** the event appended, or null when nothing was settled */
28
+ event: WpEvent | null
29
+ forms: string[]
30
+ /** the forms named that weren't settled, with why: an answer in stays to see to */
31
+ skipped: { name: string; state: string }[]
32
+ }
33
+
34
+ /**
35
+ * Settle questions (`workpad settle`): those named, or every open and held one (`all`). Only what
36
+ * waits for the reader, or is held, settles: an answer in stays the agent's to see to.
37
+ */
38
+ export function settleForms(file: string, p: PageStatus, named: string[] | 'all', by: string | null): Settled {
39
+ const unsettled = (name: string) => p.open.includes(name) || p.held.some(h => h.name === name)
40
+ if (named !== 'all') check(p, named)
41
+ const forms = named === 'all' ? [...p.open, ...p.held.map(h => h.name)] : named.filter(unsettled)
42
+ const skipped =
43
+ named === 'all' ? [] : named.filter(n => !unsettled(n)).map(name => ({ name, state: stateOf(p, name) ?? '' }))
44
+ const event = forms.length ? appendEvent(file, { page: p.page, type: SETTLE, data: { forms } }, 'cli', by) : null
45
+ return { event, forms, skipped }
46
+ }
47
+
48
+ /**
49
+ * Hold questions, with a reason (`workpad hold`): those that wait for the reader (or are held
50
+ * already: the new reason replaces the old). Until released, or answered after all, each is held.
51
+ */
52
+ export function holdForms(file: string, p: PageStatus, names: string[], reason: string, by: string | null): WpEvent {
53
+ check(p, names)
54
+ if (!reason.trim()) throw new FormStateError('say why it is held: what it waits for ("waits for !2145")')
55
+ const answered = names.filter(n => !p.open.includes(n) && !p.held.some(h => h.name === n))
56
+ if (answered.length)
57
+ throw new FormStateError(
58
+ `only a question that waits for the reader is held: ${answered.map(n => `${n} is ${stateOf(p, n)}`).join(', ')}`,
59
+ )
60
+ return appendEvent(file, { page: p.page, type: HOLD, data: { forms: names, reason: reason.trim() } }, 'cli', by)
61
+ }
62
+
63
+ /** Release held questions (`workpad release`): open again, or as their answers say. */
64
+ export function releaseForms(file: string, p: PageStatus, names: string[], by: string | null): WpEvent {
65
+ check(p, names)
66
+ const free = names.filter(n => !p.held.some(h => h.name === n))
67
+ if (free.length)
68
+ throw new FormStateError(
69
+ `${free.join(', ')} ${free.length > 1 ? "aren't" : "isn't"} held on ${p.page}${p.held.length ? `: held are ${p.held.map(h => h.name).join(', ')}` : ''}`,
70
+ )
71
+ return appendEvent(file, { page: p.page, type: RELEASE, data: { forms: names } }, 'cli', by)
72
+ }