@bigmistqke/workpad 0.0.0-stage → 0.18.1

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 +1526 -0
  4. package/dist/_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/taggedTemplateLiteral.js +5 -0
  5. package/dist/bin/workpad.js +1202 -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 +2121 -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 +213 -0
  103. package/dist/src/html.js +34 -0
  104. package/dist/src/hub.js +348 -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 +761 -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 +592 -0
  213. package/solid/index.tsx +80 -0
  214. package/src/agents.ts +134 -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 +166 -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 +240 -0
  251. package/src/html.ts +44 -0
  252. package/src/hub.ts +435 -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 +845 -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/bin/workpad.ts ADDED
@@ -0,0 +1,1526 @@
1
+ #!/usr/bin/env node
2
+ import fs from 'node:fs'
3
+ import os from 'node:os'
4
+ import path from 'node:path'
5
+ import { spawn } from 'node:child_process'
6
+ import http from 'node:http'
7
+ import { parseArgs } from 'node:util'
8
+ import { fileURLToPath } from 'node:url'
9
+ import { pageId, findProjectDir, project as projectAt, configFileIn, type Project } from '../src/config.ts'
10
+ import {
11
+ appendEvent,
12
+ read,
13
+ readEvents,
14
+ follow,
15
+ matches,
16
+ handledIds,
17
+ handle,
18
+ prune,
19
+ editEvent,
20
+ handOut,
21
+ SUBSCRIBE,
22
+ NAME,
23
+ namesOf,
24
+ rewrite,
25
+ type EventFilter,
26
+ forAgent,
27
+ fromReader,
28
+ receivedIds,
29
+ channelSince,
30
+ subscriptions,
31
+ UNSUBSCRIBE,
32
+ } from '../src/events.ts'
33
+ import { BUILTIN_COMMANDS, createConfigLoader, pluginDir } from '../src/loader.ts'
34
+ import { pluginCommands, parseCommandArgs, usage, pluginCommandHelp, asksHelp } from '../src/plugins.ts'
35
+ import { commandHelp, commandList } from '../src/help.ts'
36
+ import { archived, archiveFile } from '../src/archive.ts'
37
+ import { thread } from '../src/thread.ts'
38
+ import { markdownFiles, migrate } from '../src/migrate.ts'
39
+ import { OLD, machineSteps, oldProjectDir, projectSteps } from '../src/rename.ts'
40
+ import { anchorsOf, hashOf, type Anchor } from '../src/anchors.ts'
41
+ import { projectToken } from '../src/auth.ts'
42
+ import { PACKAGE_DIR, packagePath } from '../src/package.ts'
43
+ import {
44
+ alive,
45
+ isShared,
46
+ projectServer,
47
+ recordedOrigin,
48
+ recordedPid,
49
+ sharedServer,
50
+ stuck,
51
+ stuckAt,
52
+ } from '../src/running.ts'
53
+ import {
54
+ machineDir,
55
+ machineServerFile,
56
+ matchesEntries,
57
+ readMachineConfig,
58
+ serverPaths,
59
+ stateDir,
60
+ } from '../src/entries.ts'
61
+ import { compareVersions, VERSION } from '../src/package.ts'
62
+ import { statusLines, whose } from '../src/status.ts'
63
+ import { holdForms, releaseForms, settleForms } from '../src/formstate.ts'
64
+ import { client, probe } from '../src/api.ts'
65
+ import { everyProject, holdChannel, listen } from '../src/listen.ts'
66
+ import type { Listener, PageStatus, WpEvent } from '../src/define.ts'
67
+
68
+ // a failing command prints its message, not a stack trace
69
+ const fail = (err: unknown) => {
70
+ console.error(`workpad: ${(err as Error)?.message ?? err}`)
71
+ process.exit(1)
72
+ }
73
+ process.on('uncaughtException', fail)
74
+ process.on('unhandledRejection', fail)
75
+
76
+ const HELP = `workpad — markdown pages in the browser, what the reader does on them as events in an ndjson log
77
+
78
+ ${commandList()}
79
+
80
+ \`workpad <command> --help\` says what a command takes and does, and does nothing else.
81
+ \`workpad --version\` prints the version of workpad that runs.
82
+
83
+ Every command works on the project of the current folder: the nearest folder upward with a
84
+ .workpad/ folder. A project needs no config: .workpad/config.ts only says what differs from
85
+ the defaults (markdown with the built-in plugins). Each project runs its own server; its port is in .workpad/server.json.
86
+ A project the machine config's entries include (${machineDir()}/config.json) is served by the one shared
87
+ server instead, under its path (/<entry>/<folder>), with an index of every entry at /. It is started
88
+ outside the agents' sandboxes (\`workpad serve\` outside any project, or a login service), and
89
+ \`serve\` takes an older one over; commands never start it. A wait without a server waits for one.
90
+ A page appends events {id, ts, page, type, action, data} to .workpad/events.ndjson;
91
+ which types it sends is up to its plugins (\`workpad docs\` says). The project's plugins
92
+ can add commands of their own; \`workpad help\` in a project lists them.`
93
+
94
+ const [first, ...rest] = process.argv.slice(2)
95
+ // `workpad --version` (or -v): which workpad runs, and nothing else (a linked checkout and an
96
+ // installed one look alike otherwise)
97
+ if (first === '--version' || first === '-v') {
98
+ console.log(VERSION)
99
+ process.exit(0)
100
+ }
101
+ // `workpad --help` and `-h`, where a command goes, ask for the help as `workpad help` does
102
+ const cmd = first === '--help' || first === '-h' ? 'help' : first
103
+ // a plugin's command parses its own arguments
104
+ const { values: opts, positionals } =
105
+ cmd && !BUILTIN_COMMANDS.has(cmd)
106
+ ? { values: {}, positionals: [] }
107
+ : parseArgs({
108
+ args: rest,
109
+ allowPositionals: true,
110
+ options: {
111
+ // more than once for listen only: several pages at a time
112
+ page: { type: 'string', multiple: true },
113
+ type: { type: 'string' },
114
+ data: { type: 'string' },
115
+ timeout: { type: 'string' },
116
+ since: { type: 'string' },
117
+ last: { type: 'string' },
118
+ follow: { type: 'boolean' },
119
+ id: { type: 'string' },
120
+ out: { type: 'string' },
121
+ skip: { type: 'string' },
122
+ help: { type: 'boolean', short: 'h' },
123
+ write: { type: 'boolean' },
124
+ read: { type: 'boolean' },
125
+ full: { type: 'boolean' },
126
+ agent: { type: 'string' },
127
+ clear: { type: 'boolean' },
128
+ wait: { type: 'boolean' },
129
+ channel: { type: 'boolean' },
130
+ all: { type: 'boolean' },
131
+ },
132
+ })
133
+
134
+ // `workpad <command> --help` (or -h): that command's help, and nothing else: never run a
135
+ // command that was only asked about (a wait would pick an answer up). A plugin's commands are
136
+ // helped where they run (below).
137
+ if (cmd && cmd !== 'help' && BUILTIN_COMMANDS.has(cmd) && opts.help) {
138
+ console.log(commandHelp(cmd))
139
+ process.exit(0)
140
+ }
141
+
142
+ const project = projectAt(findProjectDir())
143
+
144
+ /** Every --page given; only listen takes more than one. */
145
+ const pagesGiven: string[] = (opts.page as string[] | undefined) ?? []
146
+ if (pagesGiven.length > 1 && cmd !== 'listen') {
147
+ console.error(`workpad: ${cmd} takes --page once; only listen takes several`)
148
+ process.exit(1)
149
+ }
150
+ /** The one --page of a command that takes one. */
151
+ const pageOpt: string | undefined = pagesGiven[0]
152
+
153
+ /** The current project, or exit with how to make one. */
154
+ function needProject(): Project {
155
+ if (project) return project
156
+ console.error(`workpad: not inside a project (no .workpad/ folder in ${process.cwd()} or above it).
157
+ Run \`workpad init\` in the folder that should become one.`)
158
+ process.exit(1)
159
+ }
160
+
161
+ const filter = (): EventFilter => ({ page: pageOpt ? pageId(needProject(), pageOpt) : undefined, type: opts.type })
162
+
163
+ /** The running server of this project: the URL it is served at, or null (see projectServer). */
164
+ const running = (proj: Project): Promise<string | null> => projectServer(proj)
165
+
166
+ /**
167
+ * This project's server, started in the background when it is not running. Under the shared server
168
+ * nothing is started: it is started outside every agent's sandbox (a login service, or `workpad
169
+ * serve` in a terminal), since it serves every project of the entries and runs their plugins; a
170
+ * command inside one sandbox would start it boxed in there. Only `show` and a plugin's command that
171
+ * asks for the server get here. @returns the URL it serves the project at
172
+ */
173
+ async function ensureServer(): Promise<string> {
174
+ const proj = needProject()
175
+ const shared = isShared(proj)
176
+ const base = await running(proj)
177
+ if (shared) {
178
+ const server = await sharedServer(machineServerFile())
179
+ if (base) {
180
+ // an older one goes on serving: it is replaced by restarting it, from outside the sandboxes
181
+ if (server && compareVersions(VERSION, server.version) > 0)
182
+ console.error(
183
+ `workpad: the shared server runs ${server.version}, this is ${VERSION}; restart it to upgrade (\`workpad serve\` takes it over)`,
184
+ )
185
+ return base
186
+ }
187
+ const at = recordedOrigin(machineServerFile())
188
+ if (!server && at && (await stuckAt(at))) throw new Error(stuck(at, 'its login service log'))
189
+ throw new Error(
190
+ server
191
+ ? `the shared server at ${server.origin} does not serve ${proj.dir}; is it in an include of ${machineDir()}/config.json?`
192
+ : `the shared server is not running. It is started outside the agents' sandboxes: as a login service, or with \`workpad serve\` in a terminal, outside any project`,
193
+ )
194
+ }
195
+ if (base) return base
196
+ // A server whose process is alive but doesn't answer yet is starting, or busy (just started, every
197
+ // client reconnecting at once): it is waited for, never a second one started beside it. A second
198
+ // would take another port and record it, and the first would leave for it: the port changes, and
199
+ // whatever was connected follows it around
200
+ const recorded = recordedPid(proj)
201
+ if (recorded && recorded !== process.pid && alive(recorded)) {
202
+ for (let i = 0; i < 75; i++) {
203
+ await new Promise(r => setTimeout(r, 200))
204
+ const base = await running(proj)
205
+ if (base) return base
206
+ if (!alive(recorded)) break
207
+ }
208
+ if (alive(recorded))
209
+ throw new Error(`the server (pid ${recorded}) runs but doesn't answer; see ${proj.logFile}`)
210
+ }
211
+ // Several commands may get here at once (an agent starting three watches, say): the one that
212
+ // creates the lock file starts the server, the others wait for it. A lock whose command is gone
213
+ // is left over, and taken over. (Should two servers still start, the server lets one survive.)
214
+ const lock = path.join(proj.wp, 'server.lock')
215
+ const claim = () => {
216
+ try {
217
+ fs.writeFileSync(lock, String(process.pid), { flag: 'wx' })
218
+ return true
219
+ } catch (err) {
220
+ if ((err as NodeJS.ErrnoException).code !== 'EEXIST') throw err
221
+ return false
222
+ }
223
+ }
224
+ let mine = claim()
225
+ if (!mine) {
226
+ // taking a stale lock over must be exclusive too: remove it, then claim it again, so that of
227
+ // several commands finding it at once only one starts a server
228
+ let stale = false
229
+ try {
230
+ const owner = Number(fs.readFileSync(lock, 'utf8'))
231
+ try {
232
+ process.kill(owner, 0)
233
+ } catch (err) {
234
+ stale = (err as NodeJS.ErrnoException).code === 'ESRCH'
235
+ }
236
+ } catch {
237
+ /* removed meanwhile */
238
+ }
239
+ if (stale) {
240
+ try {
241
+ fs.unlinkSync(lock)
242
+ } catch {
243
+ /* another command removed it first */
244
+ }
245
+ mine = claim()
246
+ }
247
+ }
248
+ if (mine) {
249
+ const log = fs.openSync(proj.logFile, 'a')
250
+ const child = spawn(process.execPath, [fileURLToPath(import.meta.url), 'serve'], {
251
+ cwd: proj.dir,
252
+ detached: true,
253
+ stdio: ['ignore', log, log],
254
+ env: process.env,
255
+ })
256
+ child.unref()
257
+ }
258
+ for (let i = 0; i < 75; i++) {
259
+ await new Promise(r => setTimeout(r, 200))
260
+ const base = await running(proj)
261
+ if (base) return base
262
+ }
263
+ throw new Error(`server did not start; see ${proj.logFile}`)
264
+ }
265
+
266
+ /** This project's running server, or an error saying how to start one. */
267
+ async function needServer(): Promise<string> {
268
+ const proj = needProject()
269
+ const base = await running(proj)
270
+ if (base) return base
271
+ if (isShared(proj)) {
272
+ const at = recordedOrigin(machineServerFile())
273
+ throw new Error(
274
+ at
275
+ ? `the shared server recorded at ${at} did not answer, or does not serve ${proj.dir}`
276
+ : "the shared server is not running. It is started outside the agents' sandboxes: as a login service, or with `workpad serve` in a terminal, outside any project",
277
+ )
278
+ }
279
+ throw new Error('no server runs for this project; `workpad show <page>` starts it')
280
+ }
281
+
282
+ /**
283
+ * The project and page a target names: a page of this project, or a page's file in another project
284
+ * (a link to another board).
285
+ */
286
+ function pageIn(target: string): { proj: Project; id: string } {
287
+ const abs = path.resolve(target)
288
+ const other = /\.md$/.test(target) && fs.existsSync(abs) ? projectAt(findProjectDir(path.dirname(abs))) : null
289
+ const proj = other ?? needProject()
290
+ return { proj, id: pageId(proj, target) }
291
+ }
292
+
293
+ /** Where a project is served: its running server, or an error saying how to start one. */
294
+ async function serverOf(proj: Project): Promise<string> {
295
+ if (proj.dir === project?.dir) return needServer()
296
+ const base = await running(proj)
297
+ if (!base) throw new Error(`no server serves ${proj.dir}; \`workpad show\` there starts it`)
298
+ return base
299
+ }
300
+
301
+ /** The anchors of a page as its server renders it (src/anchors.ts). */
302
+ async function anchorsAt(base: string, id: string): Promise<Anchor[]> {
303
+ const res = await fetch(`${base}/api/render?page=${encodeURIComponent(id)}`)
304
+ if (!res.ok) throw new Error(`no page ${id} at ${base}`)
305
+ return anchorsOf(((await res.json()) as { html?: string }).html ?? '')
306
+ }
307
+
308
+ /** Is `anchor` on the page (a chat message by its event)? Else exit 1, saying what is. */
309
+ async function checkAnchor(proj: Project, base: string, id: string, anchor: string) {
310
+ const message = /^message:(.+)$/.exec(anchor)?.[1]
311
+ if (message) {
312
+ if (readEvents(proj.eventsFile).some(e => e.id === message && e.page === id)) return
313
+ console.error(`workpad: no chat message ${message} on ${id}`)
314
+ process.exit(1)
315
+ }
316
+ const anchors = await anchorsAt(base, id)
317
+ if (anchors.some(a => a.id === anchor)) return
318
+ console.error(
319
+ `workpad: no anchor ${hashOf(anchor)} on ${id}${anchors.length ? `; there are:\n${anchors.map(a => ` ${hashOf(a.id)}`).join('\n')}` : ''}`,
320
+ )
321
+ process.exit(1)
322
+ }
323
+
324
+ /** Is there a page (a markdown file) in this folder or below it? */
325
+ function hasPages(dir: string): boolean {
326
+ let entries: fs.Dirent[]
327
+ try {
328
+ entries = fs.readdirSync(dir, { withFileTypes: true })
329
+ } catch {
330
+ return false
331
+ }
332
+ return entries.some(e =>
333
+ e.isDirectory() ? !e.name.startsWith('.') && hasPages(path.join(dir, e.name)) : e.name.endsWith('.md'),
334
+ )
335
+ }
336
+
337
+ /**
338
+ * Ask the project's server. Without one running, a server made for this one question answers it,
339
+ * in this process, on no port: a command that only asks (status, docs, the hooks on every prompt)
340
+ * never starts one. It has no listeners, as no server runs to hold them.
341
+ */
342
+ async function api(route: string): Promise<any> {
343
+ const base = await running(needProject())
344
+ const res = base ? await fetch(`${base}${route}`) : await askInProcess(route)
345
+ const body = await res.json()
346
+ if (!res.ok) throw new Error(body.error ?? res.statusText)
347
+ return body
348
+ }
349
+
350
+ async function askInProcess(route: string): Promise<Response> {
351
+ // a project without pages has nothing open: no need to load its config to say so (the hooks ask
352
+ // on every prompt, in every project, most of which have no pages)
353
+ if (route.startsWith('/api/status') && !hasPages(needProject().pagesDir)) return Response.json([])
354
+ const { createServer } = await import('../src/server.ts')
355
+ const server = createServer(needProject())
356
+ const listener = http.createServer((req, res) => void server.handle(req, res))
357
+ await new Promise<void>(r => listener.listen(0, '127.0.0.1', r))
358
+ try {
359
+ const { port } = listener.address() as import('node:net').AddressInfo
360
+ const res = await fetch(`http://127.0.0.1:${port}${route}`)
361
+ // read now, while the server is there
362
+ const text = await res.text()
363
+ return new Response(text, { status: res.status, headers: res.headers })
364
+ } finally {
365
+ server.close()
366
+ listener.closeAllConnections()
367
+ listener.close()
368
+ }
369
+ }
370
+
371
+ function init(name: string | undefined) {
372
+ const dir = process.cwd()
373
+ const wp = path.join(dir, '.workpad')
374
+ if (fs.existsSync(wp)) {
375
+ console.log(`already a project: ${wp}`)
376
+ return
377
+ }
378
+ // the home folder is no repository: serving and watching all of it would be slow and expose everything
379
+ const home = dir === os.homedir()
380
+ // a name other than the folder's
381
+ const named = name && name !== path.basename(dir)
382
+ fs.mkdirSync(path.join(wp, 'pages'), { recursive: true })
383
+ // a config only for what differs from the defaults
384
+ if (named || home)
385
+ fs.writeFileSync(
386
+ path.join(wp, 'config.ts'),
387
+ `import { defineConfig } from '@bigmistqke/workpad'
388
+
389
+ export default defineConfig({
390
+ ${named ? ` name: '${name}',\n` : ''}${home ? ' // only .workpad/ is served: this folder is not a repository\n files: false,\n' : ''}})
391
+ `,
392
+ )
393
+ fs.writeFileSync(
394
+ path.join(wp, '.gitignore'),
395
+ `# pages are working documents; remove this line to keep them in git
396
+ pages/
397
+ # events from the pages (and which ones an agent received), and the running server's port and output
398
+ events.ndjson
399
+ server.json
400
+ server.log
401
+ server.lock
402
+ # the secret for anything that runs code (a plugin like the terminal)
403
+ token
404
+ `,
405
+ )
406
+ console.log(`project: ${wp}
407
+ pages: ${path.join(wp, 'pages')} (gitignored); \`workpad show <page>\` starts the server
408
+ config: ${configFileIn(wp) ?? `none: the defaults (markdown with the built-in plugins); add ${path.join(wp, 'config.ts')} to change them`}`)
409
+ }
410
+
411
+ // ---- status ------------------------------------------------------------------------------------
412
+
413
+ const relFile = (file: string) => path.relative(process.cwd(), file) || file
414
+
415
+ /**
416
+ * The project's config, as the command line needs it: for its plugins (their commands, the
417
+ * session, which events reach an agent), so without the pages. Loaded once per command.
418
+ */
419
+ const loaded = new Map<string, ReturnType<ReturnType<typeof createConfigLoader>['config']>>()
420
+ const projectConfig = (proj: Project) => {
421
+ if (!loaded.has(proj.dir)) loaded.set(proj.dir, createConfigLoader(proj, { pages: false }).config())
422
+ return loaded.get(proj.dir)!
423
+ }
424
+
425
+ /**
426
+ * What the config is made of, as modification times: the config file and the local plugins in
427
+ * `.workpad/plugins/`. A different stamp means a command that runs for long (the channel) has an
428
+ * old config.
429
+ */
430
+ function configStamp(proj: Project): string {
431
+ const dir = path.join(proj.wp, 'plugins')
432
+ let local: string[] = []
433
+ try {
434
+ local = (fs.readdirSync(dir, { recursive: true }) as string[])
435
+ .filter(f => /\.(ts|js|mjs|mts)$/.test(f))
436
+ .map(f => path.join(dir, f))
437
+ } catch {
438
+ /* no local plugins */
439
+ }
440
+ return [proj.configFile, ...local]
441
+ .filter((f): f is string => !!f)
442
+ .map(f => {
443
+ try {
444
+ return `${f}@${fs.statSync(f).mtimeMs}`
445
+ } catch {
446
+ return ''
447
+ }
448
+ })
449
+ .join('|')
450
+ }
451
+
452
+ /**
453
+ * Which event types reach an agent, kept up to date for as long as `signal` doesn't abort: a hand-out
454
+ * that runs for long (the channel, a `listen` without --wait) hears of a plugin added to the config
455
+ * after it started, rather than leaving that plugin's events for nobody.
456
+ */
457
+ async function liveForAgent(proj: Project, signal?: AbortSignal): Promise<(type: string) => boolean> {
458
+ let handed = (await projectConfig(proj)).handedOut
459
+ let stamp = configStamp(proj)
460
+ const timer = setInterval(() => {
461
+ const now = configStamp(proj)
462
+ if (now === stamp) return
463
+ stamp = now
464
+ loaded.set(proj.dir, createConfigLoader(proj, { pages: false }).config())
465
+ void projectConfig(proj).then(c => {
466
+ // a config that fails to load while it is being written keeps the types from before
467
+ if (!c.errors.length) handed = c.handedOut
468
+ })
469
+ }, 2000)
470
+ timer.unref()
471
+ signal?.addEventListener('abort', () => clearInterval(timer))
472
+ return type => forAgent(handed)(type)
473
+ }
474
+
475
+ /**
476
+ * Who runs this command: `--agent`, else `WORKPAD_AGENT`, else the agent session a plugin names; null
477
+ * when none says (a bare process). Any harness, a shell or a script can name itself with the first
478
+ * two: a plugin only fills it in for the agent programs it knows.
479
+ */
480
+ /** Subscribe `agent` to `page`, unless it is already (or nobody says who it is). */
481
+ function subscribe(proj: Project, page: string, agent: string | null, data?: Record<string, unknown>) {
482
+ if (!agent) return
483
+ const already = subscriptions(readEvents(proj.eventsFile)).some(e => e.page === page && e.by === agent)
484
+ if (!already) appendEvent(proj.eventsFile, { page, type: SUBSCRIBE, ...(data ? { data } : {}) }, 'cli', agent)
485
+ }
486
+
487
+ async function whoAmI(proj: Project): Promise<string | null> {
488
+ return (opts.agent as string | undefined) || process.env.WORKPAD_AGENT || (await currentSession(proj))
489
+ }
490
+
491
+ /**
492
+ * The agent session this command runs in, as the project's plugins know it (Claude Code's
493
+ * plugin reads it from the environment): the first one that names one. Null without any.
494
+ */
495
+ async function currentSession(proj: Project): Promise<string | null> {
496
+ try {
497
+ for (const e of (await projectConfig(proj)).plugins) {
498
+ const session = typeof e.session === 'function' ? await e.session() : null
499
+ if (session) return String(session)
500
+ }
501
+ } catch (err) {
502
+ console.error(`workpad: which session runs this: ${(err as Error).message}`)
503
+ }
504
+ return null
505
+ }
506
+
507
+ /** The status of one page, as the server says it; an error when there is no such page. */
508
+ async function pageStatus(proj: Project, target: string): Promise<PageStatus> {
509
+ const id = pageId(proj, target)
510
+ const p = ((await api(`/api/status?page=${encodeURIComponent(id)}`)) as PageStatus[]).find(s => s.page === id)
511
+ if (!p) throw new Error(`no page ${id}`)
512
+ return p
513
+ }
514
+
515
+ async function status() {
516
+ const proj = needProject()
517
+ const [pages, me]: [PageStatus[], string | null] = await Promise.all([
518
+ api(`/api/status${pageOpt ? `?page=${encodeURIComponent(pageId(proj, pageOpt))}` : ''}`),
519
+ whoAmI(proj),
520
+ ])
521
+ const names = namesOf(readEvents(proj.eventsFile))
522
+ const busy = pages.filter(p => p.unreceived.length || p.open.length)
523
+ if (!busy.length) {
524
+ console.log('nothing open: every question is answered, and every answer received')
525
+ return
526
+ }
527
+ for (const p of busy) {
528
+ console.log(`${p.page} (${whose(p, me, names)})`)
529
+ for (const l of statusLines(p, relFile(p.file))) console.log(` ${l}`)
530
+ }
531
+ }
532
+
533
+ switch (cmd) {
534
+ case 'serve': {
535
+ // outside any project, with a machine config: the shared server (to start at login, say)
536
+ if (!project && readMachineConfig()) {
537
+ const { startShared } = await import('../src/serve.ts')
538
+ await startShared()
539
+ break
540
+ }
541
+ const proj = needProject()
542
+ if (isShared(proj)) {
543
+ // the shared server, for every entry's projects; it takes over from an older one itself
544
+ const { startShared } = await import('../src/serve.ts')
545
+ await startShared()
546
+ break
547
+ }
548
+ const base = await running(proj)
549
+ if (base) {
550
+ console.error(`workpad: ${proj.name} is already served at ${base}`)
551
+ process.exit(1)
552
+ }
553
+ // the server only for the commands that run one: every other command (the hooks' among them,
554
+ // on every prompt) starts without it, a good part of its start-up time
555
+ const { start } = await import('../src/serve.ts')
556
+ await start(proj)
557
+ break
558
+ }
559
+ case 'build': {
560
+ // pages rendered once, as a static site: the config's `build`, with what is given here over it
561
+ const proj = needProject()
562
+ const { createServer } = await import('../src/server.ts') // as for serve: only when needed
563
+ const server = createServer(proj)
564
+ try {
565
+ const result = await server.build({
566
+ pages: positionals.length ? positionals : undefined,
567
+ out: opts.out,
568
+ skip:
569
+ opts.skip != null
570
+ ? opts.skip
571
+ .split(',')
572
+ .map(s => s.trim())
573
+ .filter(Boolean)
574
+ : undefined,
575
+ })
576
+ for (const w of result.warnings) console.error(`workpad build: ${w}`)
577
+ console.log(
578
+ `built ${result.pages.length} page${result.pages.length === 1 ? '' : 's'} into ${path.relative(process.cwd(), result.out) || '.'}`,
579
+ )
580
+ } finally {
581
+ server.close()
582
+ }
583
+ process.exit(0)
584
+ }
585
+ case 'init': {
586
+ init(positionals[0])
587
+ break
588
+ }
589
+ case 'root': {
590
+ const dir = needProject().pagesDir
591
+ fs.mkdirSync(dir, { recursive: true })
592
+ console.log(dir)
593
+ break
594
+ }
595
+ case 'new': {
596
+ // a page of its own: the exclusive create fails when the file exists, so two agents asking at once
597
+ // never get the same page; the second gets name-2
598
+ const name = (positionals[0] ?? '')
599
+ .replace(/\\/g, '/')
600
+ .replace(/\.md$/, '')
601
+ .replace(/^\/+|\/+$/g, '')
602
+ if (!name || name.split('/').some(part => !part || part === '.' || part === '..' || part === '-' || part === '_'))
603
+ throw new Error('usage: workpad new <name> (a page name like plan or task/plan)')
604
+ const proj = needProject()
605
+ // a name with submits in the log stays taken after its page is deleted, so a new page never
606
+ // receives the answers of an old one
607
+ const answered = new Set(readEvents(proj.eventsFile).map(e => e.page))
608
+ for (let n = 1; ; n++) {
609
+ const id = n === 1 ? name : `${name}-${n}`
610
+ if (answered.has(id)) continue
611
+ const file = path.join(proj.pagesDir, `${id}.md`)
612
+ fs.mkdirSync(path.dirname(file), { recursive: true })
613
+ try {
614
+ fs.writeFileSync(file, '', { flag: 'wx' })
615
+ // who made the page is subscribed to it: what is left on it is theirs to see to
616
+ subscribe(proj, id, await whoAmI(proj))
617
+ console.log(file)
618
+ break
619
+ } catch (err) {
620
+ if ((err as NodeJS.ErrnoException).code !== 'EEXIST') throw err
621
+ }
622
+ }
623
+ break
624
+ }
625
+ case 'agent': {
626
+ // Who you are on the boards (your id: --agent, WORKPAD_AGENT, or the session a plugin names),
627
+ // and what goes with it: the name you give yourself, who else is around, and whether a plugin's
628
+ // channel reaches you.
629
+ const proj = needProject()
630
+ const [sub, arg] = positionals
631
+ const me = await whoAmI(proj)
632
+ const nobody = () =>
633
+ new Error(
634
+ 'nobody here: say who with --agent or WORKPAD_AGENT (or a plugin of the config names the session: claude(), opencode())',
635
+ )
636
+ if (!sub) {
637
+ // who you are
638
+ if (!me) throw nobody()
639
+ const name = namesOf(readEvents(proj.eventsFile)).get(me)
640
+ console.log(name ? `${name} (${me})` : `${me} (no name: workpad agent name <name>)`)
641
+ break
642
+ }
643
+ if (sub === 'name') {
644
+ // One name per agent, on no page: the one before goes, so they don't pile up; --clear drops it
645
+ if (!me) throw nobody()
646
+ if (!arg && !opts.clear) throw new Error('usage: workpad agent name <name> | --clear')
647
+ rewrite(proj.eventsFile, e => (e.type === NAME && e.by === me ? null : e))
648
+ if (opts.clear) console.log(`${me} has no name now`)
649
+ else {
650
+ appendEvent(proj.eventsFile, { page: '', type: NAME, data: { name: arg } }, 'cli', me)
651
+ console.log(`${me} is ${arg} now`)
652
+ }
653
+ break
654
+ }
655
+ if (sub === 'list') {
656
+ // everyone the board knows: who named itself, is subscribed to a page, wrote something, or
657
+ // listens now
658
+ const events = readEvents(proj.eventsFile)
659
+ const names = namesOf(events)
660
+ const subscribed = new Map<string, string[]>()
661
+ const seen = new Set<string>()
662
+ for (const e of events) if (e.by) seen.add(e.by)
663
+ for (const e of subscriptions(events)) subscribed.set(e.by!, [...(subscribed.get(e.by!) ?? []), e.page || 'every page'])
664
+ const listening = new Map<string, string[]>()
665
+ const base = await running(proj)
666
+ if (base)
667
+ for (const l of (await (await fetch(`${base}/api/listeners`)).json()) as Listener[])
668
+ if (l.agent) {
669
+ seen.add(l.agent)
670
+ listening.set(l.agent, [...(listening.get(l.agent) ?? []), l.page || 'every page'])
671
+ }
672
+ if (!seen.size) {
673
+ console.log('no agents on this board yet')
674
+ break
675
+ }
676
+ for (const id of seen) {
677
+ const who = `${names.get(id) ?? id}${names.has(id) ? ` (${id})` : ''}${id === me ? ' · you' : ''}`
678
+ console.log(who)
679
+ if (subscribed.has(id)) console.log(` subscribed: ${[...new Set(subscribed.get(id))].join(', ')}`)
680
+ if (listening.has(id)) console.log(` listening: ${[...new Set(listening.get(id))].join(', ')}`)
681
+ // subscribed and not listening: gone, or between turns; one that is gone is taken off with unsubscribe
682
+ else if (subscribed.has(id) && base)
683
+ console.log(` not listening now (gone? \`workpad agent unsubscribe ${id}\` takes it off its pages)`)
684
+ }
685
+ break
686
+ }
687
+ if (sub === 'unsubscribe') {
688
+ // An agent's subscriptions, taken off: one gone for good (a relay that stopped) stays a
689
+ // subscriber of its pages otherwise. By its id or its name; the pages named, else all
690
+ if (!arg) throw new Error('usage: workpad agent unsubscribe <agent> [--page <page>…]')
691
+ const events = readEvents(proj.eventsFile)
692
+ const byName = [...namesOf(events)].find(([, name]) => name === arg)?.[0]
693
+ const agent = subscriptions(events).some(e => e.by === arg) ? arg : (byName ?? arg)
694
+ const mine = subscriptions(events).filter(e => e.by === agent)
695
+ if (!mine.length) throw new Error(`${arg} is subscribed to no page here`)
696
+ const pages = [...new Set(pagesGiven.map(p => pageId(proj, p)))]
697
+ for (const page of pages)
698
+ if (!mine.some(e => e.page === page))
699
+ throw new Error(`${arg} isn't subscribed to ${page}: its pages are ${mine.map(e => e.page || 'every page').join(', ')}`)
700
+ if (pages.length)
701
+ for (const page of pages) appendEvent(proj.eventsFile, { page: '', type: UNSUBSCRIBE, data: { agent, page } }, 'cli', me)
702
+ else appendEvent(proj.eventsFile, { page: '', type: UNSUBSCRIBE, data: { agent } }, 'cli', me)
703
+ const off = pages.length ? pages : [...new Set(mine.map(e => e.page || 'every page'))]
704
+ console.log(`${arg} is off ${off.length === 1 ? off[0] : `${off.length} pages: ${off.join(', ')}`}`)
705
+ break
706
+ }
707
+ if (sub === 'ping') {
708
+ // Does what a plugin pushes reach you? Without a code: ping your channels, which push a pong
709
+ // with a code into the session; with the code from the pong: confirm it came
710
+ const code = arg
711
+ if (!code && !me) throw nobody()
712
+ const base = await ensureServer()
713
+ const res = await fetch(`${base}/api/ping`, {
714
+ method: 'POST',
715
+ headers: { 'content-type': 'application/json' },
716
+ body: JSON.stringify(code ? { code } : { session: me }),
717
+ })
718
+ const body = (await res.json()) as { sent?: number; confirmed?: boolean; error?: string }
719
+ if (!res.ok) throw new Error(`${body.error ?? res.statusText}: \`workpad agent ping\` sends a new one`)
720
+ // which pages that covers: the session's own, and those with something waiting that aren't,
721
+ // so "your pages" isn't taken for every page
722
+ const covers = async () => {
723
+ if (!me) return ''
724
+ const pages = (await api('/api/status')) as PageStatus[]
725
+ const mine = pages.filter(p => p.subscribers.includes(me)).map(p => p.page)
726
+ const others = pages
727
+ .filter(p => !p.subscribers.includes(me) && (p.open.length || p.unreceived.length))
728
+ .map(p => p.page)
729
+ return [
730
+ ` The channel follows ${mine.length} page${mine.length === 1 ? '' : 's'}, those you made or listened on${mine.length ? `: ${mine.join(', ')}` : ''}.`,
731
+ others.length
732
+ ? ` Not yours, with questions waiting: ${others.join(', ')}. \`workpad listen --channel --page <page>\` takes one on; \`workpad listen --channel\` every page, also those made later.`
733
+ : '',
734
+ ].join('')
735
+ }
736
+ if (code) console.log(`confirmed: answers on your pages come to you now, as the pong did.${await covers()}`)
737
+ else if (body.confirmed) console.log(`answers on your pages come to you already, through this session’s channel.${await covers()}`)
738
+ else if (body.sent && opts.wait) {
739
+ // run in the background: it ends, and so wakes the agent, when the pong it pushed is confirmed,
740
+ // or when none came in time: then nothing brings answers here, and the agent listens instead
741
+ console.log('pinged this session’s channel: a pong comes to you as a message; confirm it with the command it names')
742
+ const limit = Date.now() + (opts.timeout ? Number(opts.timeout) * 1000 : 120_000)
743
+ while (Date.now() < limit) {
744
+ await new Promise(r => setTimeout(r, 1000))
745
+ const channels = (await api('/api/channels')) as { session: string | null; confirmed: boolean }[]
746
+ if (channels.some(c => c.session === me && c.confirmed)) {
747
+ console.log(`confirmed: answers on your pages come to you now.${await covers()}`)
748
+ process.exit(0)
749
+ }
750
+ }
751
+ console.log(
752
+ 'no pong was confirmed in time: nothing brings answers here. Listen for them (`workpad listen --wait --page <file>` in the background), and in Claude Code tell the user what `workpad claude doctor` says is wrong',
753
+ )
754
+ process.exit(1)
755
+ } else if (body.sent)
756
+ console.log(
757
+ 'pinged this session’s channel: a pong comes to you as a message, the way answers will, with the command that confirms it. It may only come once your turn has ended, so start no listen yet. Run `workpad agent ping --wait` in the background instead, and it ends when you confirmed the pong or when none came: then listen',
758
+ )
759
+ else {
760
+ console.log(
761
+ 'nothing brings answers to this session: listen for them (`workpad listen --wait --page <file>` in the background)',
762
+ )
763
+ process.exit(1)
764
+ }
765
+ break
766
+ }
767
+ throw new Error(
768
+ 'usage: workpad agent [name <name> | name --clear | list | unsubscribe <agent> [--page <p>…] | ping [<code> | --wait [--timeout <s>]]]',
769
+ )
770
+ }
771
+ case 'show': {
772
+ if (!positionals[0]) throw new Error('usage: workpad show <page|file> [<anchor>]')
773
+ const base = await ensureServer()
774
+ const id = pageId(project, positionals[0])
775
+ const anchor = positionals.slice(1).join(' ').trim()
776
+ if (anchor) await checkAnchor(project!, base, id, anchor)
777
+ console.log(`${base}/${id}${anchor ? hashOf(anchor) : ''}`)
778
+ break
779
+ }
780
+ case 'url': {
781
+ // a link to a page, or to a place on it: from the server's root by default, so it works through
782
+ // whatever address the board is opened at; --full for outside a board (a terminal, a review)
783
+ const target = positionals[0] ?? ''
784
+ const { proj, id } = pageIn(target)
785
+ const base = await serverOf(proj)
786
+ const anchor = positionals.slice(1).join(' ').trim()
787
+ if (anchor) await checkAnchor(proj, base, id, anchor)
788
+ const link = `${base}/${id}${anchor ? hashOf(anchor) : ''}`
789
+ console.log(opts.full ? link : link.slice(new URL(base).origin.length))
790
+ break
791
+ }
792
+ case 'check': {
793
+ // what is wrong on pages, as their server renders them: the notices above a page (Rendered.problems,
794
+ // a config or its frontmatter) and the errors blocks show in place (a diagram that doesn't parse)
795
+ const proj = needProject()
796
+ const base = await serverOf(proj)
797
+ const all = (dir: string, rel = ''): string[] =>
798
+ fs.readdirSync(dir, { withFileTypes: true }).flatMap(e =>
799
+ e.isDirectory()
800
+ ? all(path.join(dir, e.name), `${rel}${e.name}/`)
801
+ : e.name.endsWith('.md')
802
+ ? [`${rel}${e.name.slice(0, -3)}`]
803
+ : [],
804
+ )
805
+ const ids = positionals.length ? positionals.map(p => pageIn(p).id) : all(proj.pagesDir).sort()
806
+ const text = (s: string) =>
807
+ s
808
+ .replace(/<[^>]+>/g, '')
809
+ .replace(/&lt;/g, '<')
810
+ .replace(/&gt;/g, '>')
811
+ .replace(/&quot;/g, '"')
812
+ .replace(/&#39;/g, "'")
813
+ .replace(/&amp;/g, '&')
814
+ .trim()
815
+ let found = 0
816
+ const config = new Set<string>()
817
+ for (const id of ids) {
818
+ const res = await fetch(`${base}/api/render?page=${encodeURIComponent(id)}`)
819
+ if (!res.ok) {
820
+ console.log(`${id}\n no such page`)
821
+ found++
822
+ continue
823
+ }
824
+ const { html: body = '', notices = [] } = (await res.json()) as { html?: string; notices?: string[] }
825
+ const errors = [...body.matchAll(/<(\w+) class="wp-error"[^>]*>([\s\S]*?)<\/\1>/g)].map(m => text(m[2]))
826
+ // the config's errors are every page's: said once, at the end
827
+ for (const n of notices) if (n.startsWith('config: ')) config.add(n)
828
+ const problems = [...new Set([...notices.filter(n => !n.startsWith('config: ')), ...errors])]
829
+ if (!problems.length) continue
830
+ found += problems.length
831
+ console.log(`${id}\n${problems.map(p => ` ${p.replace(/\n/g, '\n ')}`).join('\n')}`)
832
+ }
833
+ for (const n of config) console.log(n)
834
+ found += config.size
835
+ if (!found) console.log(`nothing wrong on ${ids.length === 1 ? ids[0] : `${ids.length} pages`}`)
836
+ else process.exit(1)
837
+ break
838
+ }
839
+ case 'migrate': {
840
+ // a project and machine still under the old name (whiteboard) moved to workpad's names, then
841
+ // pages in an older syntax rewritten in the current one: a dry run unless --write
842
+ const old = project ? null : oldProjectDir()
843
+ const renames = [...(old ? projectSteps(old) : []), ...machineSteps()]
844
+ for (const step of renames) {
845
+ console.log(step.what)
846
+ if (opts.write) step.run()
847
+ }
848
+ const pagesOf = (dir: string) => path.join(dir, opts.write ? '.workpad' : OLD, 'pages')
849
+ const targets = positionals.length
850
+ ? positionals
851
+ : [project?.pagesDir ?? (old ? pagesOf(old) : needProject().pagesDir)].filter(t => fs.existsSync(t))
852
+ const files = targets.flatMap(t => {
853
+ if (!fs.existsSync(t)) throw new Error(`no such file or folder: ${t}`)
854
+ return markdownFiles(t)
855
+ })
856
+ let changed = 0
857
+ for (const file of files) {
858
+ const before = fs.readFileSync(file, 'utf8')
859
+ const { source, applied } = migrate(before)
860
+ if (!applied.length) continue
861
+ changed++
862
+ if (opts.write) fs.writeFileSync(file, source)
863
+ const what = applied.map(a => `${a.migration.name}${a.changes > 1 ? ` ×${a.changes}` : ''}`).join(', ')
864
+ const rel = path.relative(process.cwd(), file)
865
+ console.log(`${rel.startsWith('..') ? path.resolve(file) : rel}\n ${what}`)
866
+ }
867
+ const pages = (n: number) => `${n} page${n === 1 ? '' : 's'}`
868
+ const folders = renames.filter(r => !r.what.startsWith(' ')).length
869
+ const moved = folders ? `${folders} folder${folders === 1 ? '' : 's'}` : ''
870
+ if (!changed && !moved) console.log(`nothing to migrate: ${pages(files.length)} in the current syntax`)
871
+ else if (opts.write)
872
+ console.log([moved && `moved ${moved} to the new name`, changed && `migrated ${pages(changed)}`].filter(Boolean).join('; '))
873
+ else {
874
+ const todo = [moved && `${moved} to move to the new name`, changed && `${pages(changed)} to migrate`]
875
+ const how = moved ? 'does it' : `rewrites ${changed === 1 ? 'it' : 'them'}`
876
+ console.log(`${todo.filter(Boolean).join(' and ')}; workpad migrate --write ${how}`)
877
+ process.exit(1)
878
+ }
879
+ break
880
+ }
881
+ case 'anchors': {
882
+ // what a page can be linked to: `#<id>` and what it is
883
+ const target = positionals[0]
884
+ if (!target) throw new Error('usage: workpad anchors <page|file>')
885
+ const { proj, id } = pageIn(target)
886
+ const anchors = await anchorsAt(await serverOf(proj), id)
887
+ if (!anchors.length) console.error(`workpad: nothing on ${id} has an anchor`)
888
+ for (const a of anchors)
889
+ console.log(`${hashOf(a.id)} ${a.kind}${a.label !== a.id.slice(a.kind.length + 1) ? ` ${a.label}` : ''}`)
890
+ break
891
+ }
892
+ case 'archive':
893
+ case 'destroy': {
894
+ // a page that has done its job: its file leaves the pages, and its events leave the log (answers,
895
+ // chats, comments, what was read, received and handled), so it lingers neither as a page nor in
896
+ // the log. Archived, the file is kept in .workpad/archive/ with what was answered on it
897
+ // written in (src/archive.ts); destroyed, nothing is kept
898
+ const target = positionals[0]
899
+ if (!target) throw new Error(`usage: workpad ${cmd} <page|file>`)
900
+ const proj = needProject()
901
+ const id = pageId(proj, target)
902
+ if (id.startsWith('-/'))
903
+ throw new Error(
904
+ `${target} is a file of the repository, not a page: ${cmd} is for the pages in ${relFile(proj.pagesDir)}`,
905
+ )
906
+ const file = path.join(proj.pagesDir, `${id}.md`)
907
+ const exists = fs.existsSync(file)
908
+ const events = readEvents(proj.eventsFile).filter(e => e.page === id)
909
+ if (!exists && !events.length) {
910
+ console.error(`workpad: there is no page ${id}, nor events of it`)
911
+ process.exit(1)
912
+ }
913
+ // an agent still waiting on it would wait on nothing
914
+ const base = await running(proj)
915
+ if (base) {
916
+ try {
917
+ const listening = (
918
+ (await (await fetch(`${base}/api/listeners?page=${encodeURIComponent(id)}`)).json()) as Listener[]
919
+ ).filter(l => l.page === id)
920
+ if (listening.length)
921
+ console.error(
922
+ `workpad: ${listening.length} still listen${listening.length > 1 ? '' : 's'} on ${id}; stop ${listening.length > 1 ? 'them' : 'it'}, ${listening.length > 1 ? 'they' : 'it'} will hear nothing more`,
923
+ )
924
+ } catch {
925
+ /* the server is going: nothing to say */
926
+ }
927
+ }
928
+ let kept = ''
929
+ if (cmd === 'archive') {
930
+ const to = archiveFile(proj.wp, id)
931
+ const source = exists ? fs.readFileSync(file, 'utf8') : ''
932
+ const plugins = (await projectConfig(proj)).plugins
933
+ fs.mkdirSync(path.dirname(to), { recursive: true })
934
+ fs.writeFileSync(to, await archived({ page: id, source, events, plugins }))
935
+ kept = `, kept with its answers in ${relFile(to)}`
936
+ }
937
+ if (exists) fs.rmSync(file)
938
+ const removed = prune(proj.eventsFile, id)
939
+ console.log(
940
+ `${cmd === 'archive' ? 'archived' : 'destroyed'} ${id}: ${exists ? 'removed its file' : 'it had no file'}${kept}, and ${removed} event${removed === 1 ? '' : 's'} from the log`,
941
+ )
942
+ break
943
+ }
944
+ case 'prune': {
945
+ // a page's events, gone from the log, the page kept: all of them (it starts over), or one type,
946
+ // or one event
947
+ const target = positionals[0]
948
+ if (!target) throw new Error('usage: workpad prune <page|file> [--type <type>] [--id <event id>]')
949
+ const proj = needProject()
950
+ const id = pageId(proj, target)
951
+ const removed = prune(
952
+ proj.eventsFile,
953
+ id,
954
+ e => (!opts.type || e.type === opts.type) && (!opts.id || e.id === opts.id),
955
+ )
956
+ const which = [opts.type && `of type ${opts.type}`, opts.id && `with id ${opts.id}`].filter(Boolean).join(', ')
957
+ console.log(
958
+ `pruned ${removed} event${removed === 1 ? '' : 's'} of ${id}${which ? ` (${which})` : ''} from the log; the page stays`,
959
+ )
960
+ break
961
+ }
962
+ case 'edit': {
963
+ // an agent's own event, changed in place: --data is merged into its data
964
+ const eventId = positionals[0]
965
+ if (!eventId || !opts.data)
966
+ throw new Error("usage: workpad edit <event id> --data <json> (merged into the event's data)")
967
+ const proj = needProject()
968
+ let data: Record<string, unknown>
969
+ try {
970
+ data = JSON.parse(opts.data)
971
+ } catch {
972
+ throw new Error('--data must be a JSON object')
973
+ }
974
+ if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error('--data must be a JSON object')
975
+ console.log(JSON.stringify(editEvent(proj.eventsFile, eventId, data)))
976
+ break
977
+ }
978
+ case 'scroll': {
979
+ // show the reader a place on a page they have open: every tab with it scrolls there
980
+ const [target, ...where] = positionals
981
+ const to = where.join(' ').trim()
982
+ if (!target || !to) throw new Error('usage: workpad scroll <page|file> <heading, form name or text>')
983
+ const proj = needProject()
984
+ const id = pageId(proj, target)
985
+ const base = await needServer()
986
+ // what the page shows, to say now when nothing on it matches
987
+ const rendered = (await (
988
+ await fetch(`${base}/api/render?page=${encodeURIComponent(id)}`)
989
+ )
990
+ .json()
991
+ .catch(() => null)) as { html?: string; data?: unknown } | null
992
+ const text = (rendered?.html ?? '')
993
+ .replace(/<[^>]+>/g, ' ')
994
+ .replace(/&[a-z#0-9]+;/gi, ' ')
995
+ .replace(/\s+/g, ' ')
996
+ .toLowerCase()
997
+ const named = new RegExp(`<form[^>]*\\bname="${to.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}"`).test(
998
+ rendered?.html ?? '',
999
+ )
1000
+ if (rendered && !named && !text.includes(to.replace(/\s+/g, ' ').toLowerCase())) {
1001
+ console.error(
1002
+ `workpad: nothing on ${id} matches ${JSON.stringify(to)} (a heading's text, a form's name, or text on the page)`,
1003
+ )
1004
+ process.exit(1)
1005
+ }
1006
+ const res = await fetch(`${base}/api/scroll`, {
1007
+ method: 'POST',
1008
+ headers: { 'content-type': 'application/json' },
1009
+ body: JSON.stringify({ page: id, to }),
1010
+ })
1011
+ const { tabs } = (await res.json()) as { tabs: number }
1012
+ if (!tabs) {
1013
+ // a tab may be open but not connected: a background tab connects again when it is shown, and
1014
+ // then scrolls there (the scroll is in the log)
1015
+ console.error(
1016
+ `workpad: no tab of ${id} is connected now; one that is open scrolls there once it is back (a background tab connects again when it is shown). \`workpad show ${target}\` prints its URL`,
1017
+ )
1018
+ process.exit(1)
1019
+ }
1020
+ console.log(`scrolled ${tabs} tab${tabs > 1 ? 's' : ''} of ${id} to ${JSON.stringify(to)}`)
1021
+ break
1022
+ }
1023
+ case 'docs': {
1024
+ // how pages are written and the menu: a line per block, grouped by what an agent wants to do.
1025
+ // `workpad docs <block|plugin>`: the docs of the plugin that brings it; --all: every plugin's
1026
+ const info = await api('/api/docs')
1027
+ for (const e of info.errors) console.error(`config error: ${e}`)
1028
+ const plugins: { name: string; blocks?: string[]; menu?: boolean }[] = info.plugins ?? []
1029
+ const asked = positionals[0]
1030
+ if (asked && opts.all) throw new Error('docs takes a block or plugin, or --all, not both')
1031
+ const only = asked && (plugins.find(x => x.name === asked) ?? plugins.find(x => x.blocks?.includes(asked)))
1032
+ if (asked && !only)
1033
+ throw new Error(
1034
+ `no block or plugin named "${asked}" here: the blocks are on the menu (workpad docs), the plugins are ${plugins.map(x => x.name).join(', ')}`,
1035
+ )
1036
+ const shown = (x: { name: string }) => (only ? x.name === only.name : !!opts.all)
1037
+ if (!only)
1038
+ console.log(
1039
+ info.pages ? `${info.pages.trim()}\n` : 'The config failed to load, so pages show as their raw text.\n',
1040
+ )
1041
+ if (!only && !opts.all) {
1042
+ const rest = plugins.filter(x => !x.menu).map(x => x.name)
1043
+ if (rest.length) console.log(`Plugins with nothing on the menu: ${rest.join(', ')}.\n`)
1044
+ console.log(
1045
+ 'How to write a block: workpad docs <block>, the docs of the plugin that brings it (a plugin by its name too). Everything at once: workpad docs --all.',
1046
+ )
1047
+ }
1048
+ for (const e of (info.plugins ?? []).filter(shown)) {
1049
+ console.log(`<!-- plugin: ${e.name} -->\n# Plugin: ${e.name}\n`)
1050
+ if (e.error) console.log(`It failed to load: ${e.error}\n`)
1051
+ if (e.docs) console.log(`${e.docs.trim()}\n`)
1052
+ if (e.events?.length) {
1053
+ console.log(
1054
+ 'Events it writes (handed out: a `listen` on the page gets them, and `status` counts them; the others only when asked for by type):\n',
1055
+ )
1056
+ for (const v of e.events)
1057
+ console.log(`- \`${v.type}\`${v.handOut ? ' (handed out)' : ''}${v.description ? `: ${v.description}` : ''}`)
1058
+ console.log()
1059
+ }
1060
+ for (const c of e.commands)
1061
+ console.log(`- \`workpad ${[c.name, c.usage].filter(Boolean).join(' ')}\`: ${c.description}`)
1062
+ if (e.routes.length)
1063
+ console.log(`\nRoutes (\`auth\`: needs the project's token, header \`x-workpad-token\`):\n`)
1064
+ for (const r of e.routes) {
1065
+ const takes = [
1066
+ r.body && `body ${JSON.stringify(r.body)}`,
1067
+ r.query && `query ${JSON.stringify(r.query)}`,
1068
+ r.stream && 'server-sent events',
1069
+ ]
1070
+ .filter(Boolean)
1071
+ .join(', ')
1072
+ console.log(
1073
+ `- \`${r.method} ${r.path}\`${r.auth ? ' (auth)' : ''}: ${r.description}${takes ? ` (${takes})` : ''}`,
1074
+ )
1075
+ }
1076
+ console.log()
1077
+ }
1078
+ break
1079
+ }
1080
+ case 'events': {
1081
+ // the log as it is: every matching event, also the agent's own, and nothing marked received
1082
+ const f = filter()
1083
+ const log = needProject().eventsFile
1084
+ const { events, end } = read(log)
1085
+ let list = events.filter(e => matches(e, f))
1086
+ if (opts.since) {
1087
+ const i = list.findIndex(e => e.id === opts.since)
1088
+ const since = opts.since
1089
+ list = i >= 0 ? list.slice(i + 1) : list.filter(e => e.ts > since)
1090
+ }
1091
+ if (opts.last) list = list.slice(-Number(opts.last))
1092
+ for (const e of list) console.log(JSON.stringify(e))
1093
+ if (opts.follow)
1094
+ follow(log, end, e => {
1095
+ if (matches(e, f)) console.log(JSON.stringify(e))
1096
+ })
1097
+ break
1098
+ }
1099
+ case 'thread': {
1100
+ // an answer with its question: the form as written, the answers to it, and its chat (src/thread.ts)
1101
+ const eventId = positionals[0]
1102
+ if (!eventId) throw new Error('usage: workpad thread <event id>')
1103
+ const proj = needProject()
1104
+ const events = readEvents(proj.eventsFile)
1105
+ const event = events.find(e => e.id === eventId)
1106
+ if (!event) throw new Error(`no event ${eventId} in ${proj.eventsFile}`)
1107
+ const file = path.join(proj.pagesDir, `${event.page}.md`)
1108
+ const source = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : ''
1109
+ console.log(
1110
+ thread(
1111
+ eventId,
1112
+ events.filter(e => e.page === event.page),
1113
+ source,
1114
+ ),
1115
+ )
1116
+ break
1117
+ }
1118
+ case 'settle': {
1119
+ // questions a conclusion reached elsewhere answered (in a chat, the design moving on): settled,
1120
+ // they stop counting as unanswered (status, the page's counter, the turn-end check). The page's
1121
+ // forms named, or with --all every open (and held) one (asked for, so it's never run by
1122
+ // mistake); an answer after it opens one again (status.ts, SETTLE)
1123
+ const proj = needProject()
1124
+ const target = positionals[0]
1125
+ if (!target) throw new Error('usage: workpad settle <page|file> <form>… | --all')
1126
+ const p = await pageStatus(proj, target)
1127
+ const named = positionals.slice(1)
1128
+ if (named.length && opts.all) throw new Error('settle takes forms or --all, not both')
1129
+ if (!named.length && !opts.all)
1130
+ throw new Error(
1131
+ `name the forms to settle, or --all for every open one: open on ${p.page} ${p.open.length ? `are ${p.open.join(', ')}` : 'is none'}`,
1132
+ )
1133
+ const { forms, skipped } = settleForms(proj.eventsFile, p, opts.all ? 'all' : named, await whoAmI(proj))
1134
+ for (const { name, state } of skipped) console.error(`workpad: ${name} isn't open (${state}): left as it is`)
1135
+ console.log(forms.length ? `settled on ${p.page}: ${forms.join(', ')}` : `nothing to settle on ${p.page}`)
1136
+ break
1137
+ }
1138
+ case 'hold': {
1139
+ // a question that waits on something else than the reader (another merge, a decision
1140
+ // elsewhere): held, with why, it stops counting as waiting for them, and is open again once
1141
+ // released (status.ts, HOLD)
1142
+ const proj = needProject()
1143
+ const [target, ...rest] = positionals
1144
+ const reason = rest.length > 1 ? rest.at(-1)! : ''
1145
+ const forms = rest.slice(0, -1)
1146
+ if (!target || !forms.length || !reason.trim())
1147
+ throw new Error('usage: workpad hold <page|file> <form>… "<reason>"')
1148
+ const p = await pageStatus(proj, target)
1149
+ holdForms(proj.eventsFile, p, forms, reason, await whoAmI(proj))
1150
+ console.log(`held on ${p.page}: ${forms.join(', ')} (${reason.trim()})`)
1151
+ break
1152
+ }
1153
+ case 'release': {
1154
+ // held questions, open again
1155
+ const proj = needProject()
1156
+ const [target, ...forms] = positionals
1157
+ if (!target || !forms.length) throw new Error('usage: workpad release <page|file> <form>…')
1158
+ const p = await pageStatus(proj, target)
1159
+ releaseForms(proj.eventsFile, p, forms, await whoAmI(proj))
1160
+ console.log(`released on ${p.page}: ${forms.join(', ')}`)
1161
+ break
1162
+ }
1163
+ case 'handled': {
1164
+ // the agent acted on these answers: they are handled, and no wait hands them out again
1165
+ const proj = needProject()
1166
+ if (!positionals.length) throw new Error('usage: workpad handled <event id> [<event id>…]')
1167
+ const events = readEvents(proj.eventsFile)
1168
+ const handled = handledIds(events)
1169
+ const me = await whoAmI(proj)
1170
+ for (const id of positionals) {
1171
+ const event = events.find(e => e.id === id)
1172
+ if (!event) throw new Error(`no event ${id} in ${proj.eventsFile}`)
1173
+ if (handled.has(id)) console.error(`workpad: ${id} was handled already`)
1174
+ else console.log(JSON.stringify(handle(proj.eventsFile, event, me)))
1175
+ }
1176
+ break
1177
+ }
1178
+ case 'listen': {
1179
+ // What happens on the pages for this identity (who runs it: --agent, WORKPAD_AGENT, a plugin's
1180
+ // session): the reader's answers and other agents' events, never its own; also those from
1181
+ // before; of the plugins' events, those they declare for an agent (see handOut). One it received
1182
+ // before and still not handled comes again, marked `"again": true`. It prints each as it comes
1183
+ // and runs on; with --wait it prints all there are and stops, or with none, the first to come;
1184
+ // with --channel it hands the pages over to the session's channel and stops. Any number listen
1185
+ // on a page, each hearing everything. Without --page: every page (in a project of the machine's
1186
+ // entries, every page of the entry).
1187
+ const proj = needProject()
1188
+ const f = filter()
1189
+ const agent = await whoAmI(proj)
1190
+ if (opts.follow) throw new Error('listen runs on by itself: --wait stops at the first answer, --channel hands over to the channel')
1191
+ if (opts.wait && opts.channel) throw new Error('listen takes --wait or --channel, not both')
1192
+ if (opts.timeout && !opts.wait) throw new Error('--timeout goes with --wait')
1193
+ if (opts.channel) {
1194
+ await channelListen(proj, agent)
1195
+ break
1196
+ }
1197
+ const entry = !f.page && isShared(proj) ? matchesEntries(readMachineConfig()!, proj.dir) : null
1198
+ if (entry) {
1199
+ await entryListen(entry, f, agent)
1200
+ break
1201
+ }
1202
+ const isForAgent = await liveForAgent(proj)
1203
+ // the pages it listens on: each --page, so an agent with several pages needs one listen; who
1204
+ // listens on a page is subscribed to it (once), so it outlasts this listen
1205
+ const pages = [...new Set(pagesGiven.map(p => pageId(proj, p)))]
1206
+ for (const page of pages) subscribe(proj, page, agent)
1207
+ const queryFor = (page?: string) => ({
1208
+ ...(page ? { page } : {}),
1209
+ ...(f.type ? { type: f.type } : {}),
1210
+ ...(agent ? { agent } : {}),
1211
+ })
1212
+ // one line each; one handed out before and still not handled says so
1213
+ const print = (e: WpEvent, again: boolean) => console.log(JSON.stringify(again ? { ...e, again: true } : e))
1214
+ const at = () => needServer().catch(() => null)
1215
+ const options = { batch: !!opts.wait, forAgent: isForAgent, agent }
1216
+ if (opts.timeout && opts.wait)
1217
+ setTimeout(
1218
+ () => {
1219
+ console.error('timeout')
1220
+ process.exit(2)
1221
+ },
1222
+ Number(opts.timeout) * 1000,
1223
+ )
1224
+ // registered on each page (or on every page) before it reads the log
1225
+ await Promise.all(
1226
+ (pages.length ? pages : [undefined]).map(page => listen({ at, query: queryFor(page) }, { orNone: true })),
1227
+ )
1228
+ // several pages: what is on any of them (each with the pages below it, as one --page)
1229
+ const given = pages.length > 1 ? { ...f, page: null, pages } : f
1230
+ void handOut(proj.eventsFile, given, print, options).then(async () => {
1231
+ // a listen ends with answers, and the agent acts on them. What is left needs it again, which
1232
+ // is easily forgotten: say so, right with the answers: the answers to handle (reply, or
1233
+ // workpad handled), the chats waiting for a reply, the questions still unanswered
1234
+ if (opts.wait && pages.length) {
1235
+ try {
1236
+ const statuses = (
1237
+ await Promise.all(pages.map(page => api(`/api/status?page=${encodeURIComponent(page)}`)))
1238
+ ).flat() as PageStatus[]
1239
+ for (const p of statuses) {
1240
+ const again = `\`workpad listen --wait --page ${relFile(p.file)}\``
1241
+ if (p.unhandled.length)
1242
+ console.error(
1243
+ `workpad: handle these on ${p.page} once you acted on them: reply in their chat, or \`workpad handled ${p.unhandled.map(e => e.id).join(' ')}\`; until then each listen hands them out again`,
1244
+ )
1245
+ if (p.awaitingReply.length)
1246
+ console.error(
1247
+ `workpad: waiting for your reply on ${p.page}: the chat${p.awaitingReply.length > 1 ? 's' : ''} ${p.awaitingReply.join(', ')}`,
1248
+ )
1249
+ if (p.open.length)
1250
+ console.error(
1251
+ `workpad: still unanswered on ${p.page}: ${p.open.join(', ')} → run ${again} again, in the background, once you've acted on this`,
1252
+ )
1253
+ }
1254
+ } catch {
1255
+ /* no status: the answers are what matters */
1256
+ }
1257
+ }
1258
+ process.exit(0)
1259
+ })
1260
+ break
1261
+ }
1262
+ case 'append': {
1263
+ // the agent's side of the log: anything a page's plugins understand, such as a reply to a
1264
+ // comment. Waits skip what is appended here, so an agent does not hear its own events.
1265
+ const proj = needProject()
1266
+ if (!pageOpt || !opts.type)
1267
+ throw new Error("usage: workpad append --page <page|file> --type <type> [--data '<json>']")
1268
+ let data = {}
1269
+ if (opts.data) {
1270
+ try {
1271
+ data = JSON.parse(opts.data)
1272
+ } catch {
1273
+ throw new Error('--data must be JSON, e.g. \'{"text":"…"}\'')
1274
+ }
1275
+ }
1276
+ console.log(
1277
+ JSON.stringify(
1278
+ appendEvent(proj.eventsFile, { page: pageId(proj, pageOpt), type: opts.type, data }, 'cli', await whoAmI(proj)),
1279
+ ),
1280
+ )
1281
+ break
1282
+ }
1283
+ case 'status':
1284
+ await status()
1285
+ break
1286
+ case 'paths': {
1287
+ // what the shared server needs of the disk, from the machine config: for whatever boxes it in
1288
+ // (a sandbox wrapper: `safehouse --add-dirs="$(workpad paths --write)" …`)
1289
+ const config = readMachineConfig()
1290
+ if (!config) throw new Error(`no machine config: ${machineDir()}/config.json`)
1291
+ const paths = serverPaths(config, { packageDir: PACKAGE_DIR })
1292
+ // a sandbox grants only folders that exist: the state folder is workpad's own, so it is made
1293
+ // here; an entry's folder not there yet is left out (a restart grants it once it is)
1294
+ try {
1295
+ fs.mkdirSync(stateDir(), { recursive: true })
1296
+ } catch {
1297
+ /* made by whoever may: the wrapper runs outside the agents' sandboxes */
1298
+ }
1299
+ const write = paths.write.filter(d => fs.existsSync(d))
1300
+ const read = paths.read.filter(d => fs.existsSync(d))
1301
+ if (opts.write) console.log(write.join(':'))
1302
+ else if (opts.read) console.log(read.join(':'))
1303
+ else console.log(`write: ${write.join(':')}\nread: ${read.join(':')}`)
1304
+ break
1305
+ }
1306
+ case 'skill': {
1307
+ // the agent skill ships in this package; link it into whatever folder an agent reads skills from
1308
+ const source = packagePath('skills', 'workpad')
1309
+ if (!positionals[0]) {
1310
+ console.log(source)
1311
+ break
1312
+ }
1313
+ const target = path.join(path.resolve(positionals[0].replace(/^~(?=$|\/)/, os.homedir())), 'workpad')
1314
+ let existing = null
1315
+ try {
1316
+ existing = fs.lstatSync(target)
1317
+ } catch {}
1318
+ if (existing) {
1319
+ if (existing.isSymbolicLink() && path.resolve(path.dirname(target), fs.readlinkSync(target)) === source) {
1320
+ console.log(`already linked: ${target} -> ${source}`)
1321
+ break
1322
+ }
1323
+ console.error(`workpad: ${target} already exists; remove it first to link the skill there`)
1324
+ process.exit(1)
1325
+ }
1326
+ fs.mkdirSync(path.dirname(target), { recursive: true })
1327
+ fs.symlinkSync(source, target)
1328
+ console.log(`linked: ${target} -> ${source}`)
1329
+ break
1330
+ }
1331
+ default: {
1332
+ // `workpad <plugin> [sub] …`: a command of one of the project's plugins
1333
+ const commands = project ? await projectCommands(project) : []
1334
+ // `workpad help <command> [sub]`: as `<command> [sub] --help`
1335
+ if (cmd === 'help' && rest[0]) {
1336
+ const [name, sub] = rest
1337
+ if (BUILTIN_COMMANDS.has(name!)) console.log(commandHelp(name!))
1338
+ else {
1339
+ const theirs = commands.filter(c => c.plugin === name)
1340
+ const one = theirs.find(c => c.sub === sub) ?? (sub ? undefined : theirs.find(c => !c.sub))
1341
+ if (!theirs.length)
1342
+ throw new Error(`no command ${name}${project ? '' : ' (outside a project only the built-in ones)'}`)
1343
+ console.log(one ? pluginCommandHelp(one) : theirs.map(c => pluginCommandHelp(c)).join('\n\n'))
1344
+ }
1345
+ break
1346
+ }
1347
+ const mine = commands.filter(c => c.plugin === cmd)
1348
+ const found = mine.find(c => c.sub && c.sub === rest[0]) ?? mine.find(c => !c.sub)
1349
+ // `workpad <plugin> <sub> --help`: that command's help; `workpad <plugin> --help`: all of
1350
+ // the plugin's commands
1351
+ if (mine.length && asksHelp(found?.sub ? rest.slice(1) : rest)) {
1352
+ console.log(found?.sub ? pluginCommandHelp(found) : mine.map(c => pluginCommandHelp(c)).join('\n\n'))
1353
+ break
1354
+ }
1355
+ if (found && project) {
1356
+ const args = found.sub ? rest.slice(1) : rest
1357
+ const { options, positionals, rest: after } = parseCommandArgs(found.command, args, found.name)
1358
+ const me = await whoAmI(project)
1359
+ await found.command.run({
1360
+ options,
1361
+ positionals,
1362
+ rest: after,
1363
+ project: { name: project.name, dir: project.dir, wp: project.wp },
1364
+ eventsFile: project.eventsFile,
1365
+ // a plugin's folder, or the config's command's: `.workpad/<name>/`
1366
+ dataDir: pluginDir(project.wp, found.plugin),
1367
+ token: projectToken(project.wp),
1368
+ server: ensureServer,
1369
+ running: async () => {
1370
+ const base = await running(project)
1371
+ if (!base) {
1372
+ // not running, or running and stuck: the second is said, not taken for the first
1373
+ const shared = isShared(project)
1374
+ const at = recordedOrigin(shared ? machineServerFile() : project.serverFile)
1375
+ if (at && (await stuckAt(at))) throw new Error(stuck(at, shared ? 'its login service log' : project.logFile))
1376
+ return null
1377
+ }
1378
+ const health = isShared(project)
1379
+ ? await sharedServer(machineServerFile())
1380
+ : await fetch(`${base}/api/health`, { signal: AbortSignal.timeout(5000) })
1381
+ .then(r => r.json())
1382
+ .catch(() => null)
1383
+ return { base, version: String(health?.version ?? 'unknown') }
1384
+ },
1385
+ version: VERSION,
1386
+ // the API, at the project's server, started at its first call
1387
+ wp: client(async () => probe(await ensureServer()), { token: projectToken(project.wp), agent: me }),
1388
+ page: page => pageId(project, page),
1389
+ pagePath: page => `/${pageId(project, page ?? '')}`,
1390
+ status: async page => api(`/api/status${page ? `?page=${encodeURIComponent(pageId(project, page))}` : ''}`),
1391
+ handOut: async (filter, onEvent, options) =>
1392
+ handOut(project.eventsFile, { ...filter, page: filter.page ? pageId(project, filter.page) : null }, onEvent, {
1393
+ ...options,
1394
+ forAgent: await liveForAgent(project, options?.signal),
1395
+ }),
1396
+ listen: (page, { agent = null } = {}) =>
1397
+ listen({
1398
+ at: () => ensureServer().catch(() => null),
1399
+ query: { page: pageId(project, page), ...(agent ? { agent } : {}) },
1400
+ }),
1401
+ channel: (session, handlers) => holdChannel(() => ensureServer().catch(() => null), session, handlers),
1402
+ authLink: async to =>
1403
+ `${await ensureServer()}/_/auth?token=${encodeURIComponent(projectToken(project.wp))}&to=${encodeURIComponent(to)}`,
1404
+ })
1405
+ break
1406
+ }
1407
+ // asked for, the help goes to standard output; after a command it doesn't know, to standard error
1408
+ const asked = !cmd || cmd === 'help' || opts.help
1409
+ const print = asked ? console.log : console.error
1410
+ print(HELP)
1411
+ for (const [from, heading] of [
1412
+ ['config', "from this project's config"],
1413
+ ['plugin', "from this project's plugins"],
1414
+ ] as const) {
1415
+ const theirs = commands.filter(c => c.from === from)
1416
+ if (!theirs.length) continue
1417
+ print(`\n${heading}:\n`)
1418
+ for (const c of theirs)
1419
+ print(` workpad ${[c.name, usage(c.command)].filter(Boolean).join(' ')}\n ${c.command.description}`)
1420
+ }
1421
+ if (mine.length) console.error(`\nworkpad: ${cmd} has no command ${JSON.stringify(rest[0] ?? '')}`)
1422
+ if (!asked) process.exit(1)
1423
+ }
1424
+ }
1425
+
1426
+ /**
1427
+ * `workpad listen --channel`: the pages (each --page, else every page of the project, also those
1428
+ * made later) become this session's, and its channel brings their answers from its next round, also
1429
+ * those waiting now: so nothing is printed here, which would hand them out twice. Only for a session
1430
+ * whose channel is confirmed (`workpad agent ping`); else nothing is taken on.
1431
+ */
1432
+ async function channelListen(proj: Project, agent: string | null) {
1433
+ if (!agent) throw new Error('--channel needs a session: no --agent, WORKPAD_AGENT or plugin session names one')
1434
+ const channels = (await api('/api/channels')) as { session: string; confirmed: boolean }[]
1435
+ if (!channels.some(c => c.session === agent && c.confirmed)) {
1436
+ console.error(
1437
+ 'workpad: no confirmed channel brings answers to this session: run `workpad agent ping` and confirm its pong, or listen without --channel',
1438
+ )
1439
+ process.exit(1)
1440
+ }
1441
+ const pages = [...new Set(pagesGiven.map(p => pageId(proj, p)))]
1442
+ // taken on through the channel: it brings what is new, and the reader's answers still waiting;
1443
+ // what other agents said before that someone already received is skipped (channelSince)
1444
+ for (const page of pages.length ? pages : ['']) subscribe(proj, page, agent, { channel: true })
1445
+ const { events } = read(proj.eventsFile)
1446
+ const { handedOut } = await projectConfig(proj)
1447
+ const isForAgent = forAgent(handedOut)
1448
+ const handled = handledIds(events)
1449
+ const received = receivedIds(events)
1450
+ const skipped = events.filter(e => {
1451
+ if (fromReader(e) || !e.by || e.by === agent || !isForAgent(e.type) || handled.has(e.id)) return false
1452
+ if (!received.has(e.id)) return false
1453
+ const since = channelSince(events, agent, e.page)
1454
+ if (!since) return false
1455
+ return events.findIndex(x => x.id === e.id) < events.findIndex(x => x.id === since)
1456
+ })
1457
+ const where = pages.length ? pages.join(', ') : 'every page, also those made later'
1458
+ console.log(`the channel brings the answers on ${where}: your answers waiting there first, then each as it comes`)
1459
+ if (skipped.length) {
1460
+ const on = [...new Set(skipped.map(e => e.page))]
1461
+ console.log(
1462
+ `${skipped.length} earlier message${skipped.length === 1 ? '' : 's'} from other agents, received before, skipped (on ${on.join(', ')}): \`workpad listen --wait --page <page>\` hands them to you`,
1463
+ )
1464
+ }
1465
+ }
1466
+
1467
+ /**
1468
+ * A listen over a whole entry: every page of each of its projects, from each project's own log, each
1469
+ * event with the project it is from (`project`, its folder) and its page's `url`. Any number run.
1470
+ * Without a shared server running it waits for one, as any listen does. Projects that appear
1471
+ * meanwhile are followed too.
1472
+ */
1473
+ async function entryListen(entry: string, f: EventFilter, agent: string | null) {
1474
+ const file = machineServerFile()
1475
+ // across projects as they come: with --wait it stops at the first
1476
+ const count = opts.wait ? 1 : Infinity
1477
+ const done = new AbortController()
1478
+ let total = 0
1479
+ // after the last event is recorded as received, which follows handing it out
1480
+ done.signal.addEventListener('abort', () => setImmediate(() => process.exit(0)))
1481
+ if (opts.timeout && opts.wait)
1482
+ setTimeout(
1483
+ () => {
1484
+ console.error('timeout')
1485
+ process.exit(2)
1486
+ },
1487
+ Number(opts.timeout) * 1000,
1488
+ )
1489
+ let origin = ''
1490
+ const page = (id: string) => id.split('/').map(encodeURIComponent).join('/')
1491
+ // a hand-out per project of the entry, as the shared server names them, each event with its
1492
+ // project and its page's address
1493
+ const update = everyProject((p, signal) => {
1494
+ const proj = projectAt(p.dir)
1495
+ if (!proj) return
1496
+ void projectConfig(proj).then(({ handedOut }) =>
1497
+ handOut(
1498
+ proj.eventsFile,
1499
+ { type: f.type },
1500
+ e => {
1501
+ console.log(JSON.stringify({ ...e, project: p.dir, url: `${origin}${p.base}/${page(e.page)}` }))
1502
+ if (++total >= count) done.abort()
1503
+ },
1504
+ { forAgent: forAgent(handedOut), agent, signal: AbortSignal.any([signal, done.signal]) },
1505
+ ),
1506
+ )
1507
+ })
1508
+ // held at the shared server for as long as this runs (again after a restart)
1509
+ await listen({
1510
+ at: async () => {
1511
+ origin = (await sharedServer(file))?.origin ?? ''
1512
+ return origin || null
1513
+ },
1514
+ query: { entry, ...(f.type ? { type: f.type } : {}), ...(agent ? { agent } : {}) },
1515
+ onSnapshot: update,
1516
+ })
1517
+ // keeps the command running: the connection does not
1518
+ setInterval(() => {}, 1 << 30)
1519
+ }
1520
+
1521
+ /** The commands the project's config and plugins add: `workpad <name>`, `workpad <plugin> [sub]`. */
1522
+ async function projectCommands(proj: Project) {
1523
+ const { plugins, commands, errors } = await projectConfig(proj)
1524
+ for (const e of errors) console.error(`workpad: config error: ${(e as Error).message}`)
1525
+ return [...commands, ...plugins.flatMap(pluginCommands)]
1526
+ }