@bigmistqke/workpad 0.18.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/bin/workpad.ts +238 -17
  2. package/dist/bin/workpad.js +191 -13
  3. package/dist/plugins/badge/README.md +59 -10
  4. package/dist/plugins/badge/index.js +130 -8
  5. package/dist/plugins/badge/public/style.css +132 -12
  6. package/dist/plugins/chat/index.js +7 -1
  7. package/dist/plugins/claude/README.md +13 -5
  8. package/dist/plugins/claude/channel.js +25 -2
  9. package/dist/plugins/claude/doctor.js +43 -47
  10. package/dist/plugins/claude/index.js +24 -8
  11. package/dist/plugins/claude/session.js +46 -1
  12. package/dist/plugins/opencode/channel.js +42 -7
  13. package/dist/plugins/opencode/index.js +2 -0
  14. package/dist/src/agents.js +7 -2
  15. package/dist/src/client/page/main.js +23 -0
  16. package/dist/src/events.js +6 -5
  17. package/dist/src/help.js +18 -4
  18. package/dist/src/hub.js +62 -2
  19. package/dist/src/listen.js +36 -4
  20. package/dist/src/listeners.js +14 -4
  21. package/dist/src/pages/board.js +9 -4
  22. package/dist/src/pages/index.js +2 -4
  23. package/dist/src/pages/markdown.js +47 -16
  24. package/dist/src/pages/render.js +128 -32
  25. package/dist/src/server.js +69 -6
  26. package/dist/src/state.js +2 -1
  27. package/dist/src/status.js +11 -2
  28. package/dist/src/turns.js +41 -0
  29. package/package.json +6 -1
  30. package/plugins/badge/README.md +59 -10
  31. package/plugins/badge/index.ts +141 -8
  32. package/plugins/badge/public/style.css +132 -12
  33. package/plugins/chat/index.ts +9 -1
  34. package/plugins/claude/README.md +13 -5
  35. package/plugins/claude/channel.ts +26 -2
  36. package/plugins/claude/doctor.ts +58 -39
  37. package/plugins/claude/index.ts +30 -8
  38. package/plugins/claude/session.ts +32 -0
  39. package/plugins/opencode/channel.ts +42 -7
  40. package/plugins/opencode/index.ts +4 -0
  41. package/skills/workpad/SKILL.md +30 -6
  42. package/src/agents.ts +9 -1
  43. package/src/client/page/board.ts +29 -0
  44. package/src/define.ts +28 -1
  45. package/src/events.ts +23 -2
  46. package/src/help.ts +18 -4
  47. package/src/hub.ts +80 -2
  48. package/src/listen.ts +47 -4
  49. package/src/listeners.ts +22 -1
  50. package/src/pages/board.ts +10 -3
  51. package/src/pages/index.ts +8 -10
  52. package/src/pages/markdown.ts +55 -8
  53. package/src/pages/render.ts +132 -35
  54. package/src/server.ts +84 -6
  55. package/src/state.ts +3 -0
  56. package/src/status.ts +15 -1
  57. package/src/turns.ts +56 -0
@@ -1,19 +1,23 @@
1
1
  // `workpad claude doctor`: everything the channel needs to push the reader's answers into this
2
2
  // session, checked one by one, with what to do about each that fails. Each of these broke a channel
3
3
  // without a word once: Claude Code drops a server's messages when the session wasn't started with the
4
- // channels flag, a session started from another folder never sees the project's .mcp.json, and an Esc
5
- // on "New MCP server found" disables the server in a settings file `/mcp` then doesn't list at all
6
- // (in a git worktree without its own settings.local.json, in the main checkout's).
4
+ // channels flag, a session reads .mcp.json from the folder it runs in only, and an Esc on "New MCP
5
+ // server found" disables the server in a settings file `/mcp` then doesn't list at all (in a git
6
+ // worktree without its own settings.local.json, in the main checkout's).
7
+ //
8
+ // The folder Claude Code runs in is not always the pages' project: a wrapper can hand a session in
9
+ // one folder (a git worktree) the pages of another (a job's folder). .mcp.json and the approval are
10
+ // read from Claude's folder (claudeFolder), and both are named when they differ.
7
11
  //
8
12
  // It reads, and changes nothing: the files, the claude process it runs under (its command line and
9
13
  // folder, with ps and lsof), and what the project's server says (never started for it). The
10
- // channel's command is started once, asked to initialize, and stopped.
14
+ // channel's command is started once, in Claude's folder, asked to initialize, and stopped.
11
15
  import fs from 'node:fs'
12
16
  import os from 'node:os'
13
17
  import path from 'node:path'
14
18
  import { spawn, spawnSync } from 'node:child_process'
15
19
  import type { CommandContext } from '../../src/define.ts'
16
- import { claudePid, claudeProcess, recordedSession } from './session.ts'
20
+ import { claudeFolder, claudePid, claudeProcess, real, recordedSession } from './session.ts'
17
21
 
18
22
  const SERVER = 'workpad'
19
23
  const FLAG = '--dangerously-load-development-channels'
@@ -136,62 +140,85 @@ export function approvals(dir: string, home = os.homedir()): Line[] {
136
140
  return lines
137
141
  }
138
142
 
139
- /** The claude process's command line and folder. */
140
- function claudeLaunch(pid: number): { args: string | null; cwd: string | null } {
143
+ /** The claude process's command line. */
144
+ function claudeArgs(pid: number): string | null {
141
145
  const ps = spawnSync('ps', ['-o', 'args=', '-p', String(pid)], { encoding: 'utf8' })
142
- const lsof = spawnSync('lsof', ['-a', '-p', String(pid), '-d', 'cwd', '-Fn'], { encoding: 'utf8' })
143
- const cwd = lsof.status === 0 ? (lsof.stdout.split('\n').find(l => l.startsWith('n'))?.slice(1) ?? null) : null
144
- return { args: ps.status === 0 ? ps.stdout.trim() : null, cwd }
145
- }
146
-
147
- /** The workpad version a project pins (its package.json), and the one installed there, when it has them. */
148
- function pinned(dir: string): { pin: string | null; installed: string | null } {
149
- const pkg = readJson(path.join(dir, 'package.json'))?.value
150
- const pin = pkg?.dependencies?.['@bigmistqke/workpad'] ?? pkg?.devDependencies?.['@bigmistqke/workpad'] ?? null
151
- const installed = readJson(path.join(dir, 'node_modules', '@bigmistqke', 'workpad', 'package.json'))?.value?.version ?? null
152
- return { pin, installed }
146
+ return ps.status === 0 ? ps.stdout.trim() : null
153
147
  }
154
148
 
155
- export async function doctor(ctx: CommandContext) {
156
- const dir = ctx.project.dir
149
+ /**
150
+ * The checks of what Claude Code reads where it runs (`claude`, see claudeFolder): which folder
151
+ * that is, beside the pages' project (`pages`), when the two differ; the channel in its .mcp.json,
152
+ * and that its command answers, started there as Claude Code starts it; and the server approved and
153
+ * disabled nowhere in its settings. Each fix points at the folder it is for.
154
+ */
155
+ export async function channelChecks(
156
+ pages: string,
157
+ claude: { dir: string; from: string | null },
158
+ home = os.homedir(),
159
+ ): Promise<Line[]> {
160
+ const dir = claude.dir
161
+ const apart = real(pages) !== dir
157
162
  const lines: Line[] = []
163
+ if (apart)
164
+ lines.push({
165
+ mark: 'skip',
166
+ text: `pages: ${pages}; Claude's project: ${dir} (${claude.from ?? 'no Claude Code session found'}). The channel and its approval are read from Claude's`,
167
+ })
168
+ else if (claude.from)
169
+ lines.push({ mark: 'ok', text: `Claude Code runs in the project's folder (${dir})` })
170
+ const install = apart ? `workpad claude install --claude-dir ${dir}` : 'workpad claude install'
158
171
 
159
- // 1. the channel in .mcp.json, and its command starts
172
+ // the channel in .mcp.json, and its command starts
160
173
  const mcpFile = path.join(dir, '.mcp.json')
161
174
  const mcp = readJson(mcpFile)
162
175
  const entry = mcp?.value?.mcpServers?.[SERVER]
163
- if (!mcp) lines.push({ mark: 'fail', text: `no ${mcpFile}`, fix: 'workpad claude install' })
176
+ if (!mcp) lines.push({ mark: 'fail', text: `no ${mcpFile}`, fix: install })
164
177
  else if (mcp.value === undefined) lines.push({ mark: 'fail', text: `${mcpFile}: ${mcp.why}`, fix: 'fix the file' })
165
- else if (!entry?.command)
166
- lines.push({ mark: 'fail', text: `${mcpFile} has no "${SERVER}" server`, fix: 'workpad claude install' })
178
+ else if (!entry?.command) lines.push({ mark: 'fail', text: `${mcpFile} has no "${SERVER}" server`, fix: install })
167
179
  else {
168
- const env = { ...process.env, CLAUDE_PROJECT_DIR: process.env.CLAUDE_PROJECT_DIR ?? dir, ...(entry.env ?? {}) }
180
+ const env = { ...process.env, CLAUDE_PROJECT_DIR: dir, ...(entry.env ?? {}) }
169
181
  const command = expand(entry.command, env)
170
182
  const args = ((entry.args ?? []) as string[]).map(a => expand(a, env))
171
183
  const why = await probe(command, args, dir, env)
172
184
  const shown = [entry.command, ...(entry.args ?? [])].join(' ')
173
185
  lines.push(
174
186
  why
175
- ? { mark: 'fail', text: `the channel's command in ${mcpFile} doesn't answer: ${why}`, fix: `run it by hand to see why: ${shown}` }
187
+ ? { mark: 'fail', text: `the channel's command in ${mcpFile} doesn't answer: ${why}`, fix: `run it by hand in ${dir} to see why: ${shown}` }
176
188
  : { mark: 'ok', text: `${mcpFile} has the channel, and its command answers (${shown})` },
177
189
  )
178
190
  }
179
191
 
180
- // 2. enabled, and disabled in no settings scope
181
- lines.push(...approvals(dir))
192
+ // enabled, and disabled in no settings scope
193
+ lines.push(...approvals(dir, home))
194
+ return lines
195
+ }
182
196
 
183
- // 3. the session: started with the flag, from the project's folder
197
+ /** The workpad version a project pins (its package.json), and the one installed there, when it has them. */
198
+ function pinned(dir: string): { pin: string | null; installed: string | null } {
199
+ const pkg = readJson(path.join(dir, 'package.json'))?.value
200
+ const pin = pkg?.dependencies?.['@bigmistqke/workpad'] ?? pkg?.devDependencies?.['@bigmistqke/workpad'] ?? null
201
+ const installed = readJson(path.join(dir, 'node_modules', '@bigmistqke', 'workpad', 'package.json'))?.value?.version ?? null
202
+ return { pin, installed }
203
+ }
204
+
205
+ export async function doctor(ctx: CommandContext) {
206
+ const dir = ctx.project.dir
207
+ // 1. where Claude Code runs; the channel in its .mcp.json; 2. approved, and disabled in no settings scope
208
+ const lines = await channelChecks(dir, claudeFolder(dir))
209
+
210
+ // 3. the session: started with the flag
184
211
  const pid = claudePid()
185
212
  const envSession = process.env.CLAUDE_CODE_SESSION_ID || null
186
213
  if (!pid)
187
214
  lines.push({
188
215
  mark: 'skip',
189
216
  text: envSession
190
- ? "couldn't find the claude process (is ps permitted here?): its launch flag and folder are not checked"
217
+ ? "couldn't find the claude process (is ps permitted here?): its launch flag is not checked"
191
218
  : 'not run from a Claude Code session: its launch and channel are not checked',
192
219
  })
193
220
  else {
194
- const { args, cwd } = claudeLaunch(pid)
221
+ const args = claudeArgs(pid)
195
222
  if (args == null) lines.push({ mark: 'skip', text: `couldn't read the command line of claude (pid ${pid})` })
196
223
  else if (new RegExp(`${FLAG}(=|\\s+)\\S*server:${SERVER}\\b`).test(args))
197
224
  lines.push({ mark: 'ok', text: `the session was started with ${FLAG} server:${SERVER}` })
@@ -201,14 +228,6 @@ export async function doctor(ctx: CommandContext) {
201
228
  text: `the session was started without ${FLAG} server:${SERVER}: Claude Code drops what the channel sends`,
202
229
  fix: `restart it with: claude ${FLAG} server:${SERVER} (a resume or a restore keeps no flag it wasn't given)`,
203
230
  })
204
- if (cwd == null) lines.push({ mark: 'skip', text: `couldn't read the folder claude (pid ${pid}) runs in` })
205
- else if (path.resolve(cwd) === dir) lines.push({ mark: 'ok', text: `the session runs in the project's folder` })
206
- else
207
- lines.push({
208
- mark: 'fail',
209
- text: `the session runs in ${cwd}, not the project's folder: it doesn't see ${mcpFile}`,
210
- fix: `start claude in ${dir}`,
211
- })
212
231
  }
213
232
 
214
233
  // 4. the server, its version, and a channel for this session; 5. its ping confirmed
@@ -28,6 +28,7 @@ import { read, receivedBy } from '../../src/events.ts'
28
28
  import { channel } from './channel.ts'
29
29
  import { doctor } from './doctor.ts'
30
30
  import { recordSession } from './session.ts'
31
+ import { recordTurn } from '../../src/turns.ts'
31
32
 
32
33
  type Mode = 'session' | 'stop'
33
34
 
@@ -71,27 +72,44 @@ export default function claude(): Plugin {
71
72
  },
72
73
  doctor: {
73
74
  description:
74
- "check what the channel needs, a line each with what to do: the .mcp.json entry and its command, the server approved and disabled in no settings file, the session started with the channels flag in the project's folder, the server up at the project's version, a channel for this session, its ping confirmed",
75
+ "check what the channel needs, a line each with what to do: the .mcp.json entry and its command, the server approved and disabled in no settings file (both where Claude Code runs, named beside the pages' project when it is another folder), the session started with the channels flag, the server up at the project's version, a channel for this session, its ping confirmed",
75
76
  run: doctor,
76
77
  },
77
78
  install: {
78
- description: "add the channel to this project's .mcp.json and its hooks to .claude/settings.json",
79
+ description:
80
+ "add the channel to the .mcp.json and its hooks to the .claude/settings.json of the folder Claude Code runs in: this project's, or --claude-dir",
81
+ options: { 'claude-dir': CLAUDE_DIR },
79
82
  run: ctx => {
80
- installChannel(ctx.project.dir)
81
- installHooks(ctx.project.dir)
83
+ const dir = claudeDir(ctx)
84
+ installChannel(dir)
85
+ installHooks(dir)
82
86
  },
83
87
  },
84
88
  uninstall: {
85
- description: "take the channel and its hooks out of this project's settings again; other hooks, servers and settings stay",
89
+ description:
90
+ "take the channel and its hooks out of the settings again (this project's, or --claude-dir's); other hooks, servers and settings stay",
91
+ options: { 'claude-dir': CLAUDE_DIR },
86
92
  run: ctx => {
87
- uninstallChannel(ctx.project.dir)
88
- uninstallHooks(ctx.project.dir)
93
+ const dir = claudeDir(ctx)
94
+ uninstallChannel(dir)
95
+ uninstallHooks(dir)
89
96
  },
90
97
  },
91
98
  },
92
99
  }
93
100
  }
94
101
 
102
+ /**
103
+ * The folder Claude Code runs in, when it isn't the pages' project: a session a wrapper hands
104
+ * another folder's pages reads .mcp.json and its settings from its own folder.
105
+ */
106
+ const CLAUDE_DIR = {
107
+ type: 'string?',
108
+ value: 'folder',
109
+ description: "the folder Claude Code runs in, when not this project's (`workpad claude doctor` names it)",
110
+ } as const
111
+ const claudeDir = (ctx: CommandContext) => path.resolve((ctx.options['claude-dir'] as string | undefined) ?? ctx.project.dir)
112
+
95
113
  /** The JSON Claude Code passes a hook on its standard input, or nothing. */
96
114
  function hookInput(): { session_id?: string; stop_hook_active?: boolean; transcript_path?: string } {
97
115
  if (process.stdin.isTTY) return {}
@@ -106,12 +124,16 @@ async function hook(ctx: CommandContext, mode: Mode) {
106
124
  const input = hookInput()
107
125
  // the channel's environment can hold an id the conversation left (a resume): tell it the current one
108
126
  if (input.session_id) recordSession(ctx.dataDir, input.session_id)
109
- if (mode === 'session') return
127
+ // `workpad agent ping --wait` counts from a turn's end (turns.ts): from here on they are recorded
128
+ if (mode === 'session')
129
+ return recordTurn(ctx.project.wp, identity(input.session_id ?? process.env.CLAUDE_CODE_SESSION_ID ?? null), false)
110
130
  // A turn ends with something on the session's pages left: its turn goes on once, with that as the
111
131
  // reason; Claude Code marks a turn a hook continued (stop_hook_active), and that one ends, with
112
132
  // what is open shown to the reader instead.
113
133
  const agent = identity(input.session_id ?? process.env.CLAUDE_CODE_SESSION_ID ?? null)
114
134
  const left = await stopReminder(ctx, agent, inFlight(ctx, agent, input.transcript_path))
135
+ // the turn ends, unless the reminder below sends it on: then its next end is the one (turns.ts)
136
+ if (!left || input.stop_hook_active) recordTurn(ctx.project.wp, agent, true)
115
137
  if (!left) return
116
138
  if (input.stop_hook_active) return void console.log(JSON.stringify({ systemMessage: left.shown }))
117
139
  // As context for the turn, not a block: the turn goes on all the same (with the same guard,
@@ -37,6 +37,38 @@ export function claudeProcess(): string {
37
37
  return Number.isNaN(at) ? String(pid) : `${pid}-${at / 1000}`
38
38
  }
39
39
 
40
+ /** The folder a process runs in (with lsof), or null when it can't be read. */
41
+ function processCwd(pid: number): string | null {
42
+ const lsof = spawnSync('lsof', ['-a', '-p', String(pid), '-d', 'cwd', '-Fn'], { encoding: 'utf8' })
43
+ if (lsof.status !== 0) return null
44
+ return lsof.stdout.split('\n').find(l => l.startsWith('n'))?.slice(1) || null
45
+ }
46
+
47
+ /** A folder as the file system names it, symbolic links resolved (as given when it isn't there). */
48
+ export function real(dir: string): string {
49
+ try {
50
+ return fs.realpathSync(dir)
51
+ } catch {
52
+ return path.resolve(dir)
53
+ }
54
+ }
55
+
56
+ /**
57
+ * The folder Claude Code runs in, where it reads .mcp.json and its project settings: not always the
58
+ * pages' project (a wrapper can hand a session another folder's pages). CLAUDE_PROJECT_DIR when set
59
+ * (Claude Code gives it to hooks and MCP servers, not to an agent's commands); else the folder of
60
+ * the claude process this one runs under (found with ps, else by the CLAUDE_PID Claude Code gives an
61
+ * agent's commands); else, outside a session, `fallback`. With how it was found, for the doctor
62
+ * (null: no session was found, and it is `fallback`).
63
+ */
64
+ export function claudeFolder(fallback: string, env: NodeJS.ProcessEnv = process.env): { dir: string; from: string | null } {
65
+ if (env.CLAUDE_PROJECT_DIR) return { dir: real(env.CLAUDE_PROJECT_DIR), from: 'CLAUDE_PROJECT_DIR' }
66
+ const pid = claudePid() ?? (Number(env.CLAUDE_PID) || null)
67
+ const cwd = pid ? processCwd(pid) : null
68
+ if (cwd) return { dir: real(cwd), from: `the folder claude (pid ${pid}) runs in` }
69
+ return { dir: real(fallback), from: null }
70
+ }
71
+
40
72
  const sessionsDir = (dataDir: string) => path.join(dataDir, 'sessions')
41
73
 
42
74
  /** The conversation a hook says this claude process is on; records of processes that ended go. */
@@ -23,8 +23,10 @@ import fs from 'node:fs'
23
23
  import path from 'node:path'
24
24
  import readline from 'node:readline'
25
25
  import type { CommandContext, WpEvent } from '../../src/define.ts'
26
- import { channelSince, read, receive, receivedBy } from '../../src/events.ts'
27
- import { answerLine, identity, pong } from '../../src/agents.ts'
26
+ import { channelSince, read, receive, receivedBy, takesUnfollowed } from '../../src/events.ts'
27
+ import { answerLine, identity, pong, unfollowedLine } from '../../src/agents.ts'
28
+ import { project as projectAt } from '../../src/config.ts'
29
+ import { recordTurn } from '../../src/turns.ts'
28
30
 
29
31
  export async function channel(ctx: CommandContext) {
30
32
  const problem = (what: string, data?: unknown) => {
@@ -40,6 +42,8 @@ export async function channel(ctx: CommandContext) {
40
42
  const sessions = new Map<string, boolean>()
41
43
  const hold = (session: string) => {
42
44
  sessions.set(session, false)
45
+ // its turn ends are recorded from now on (`hook stop`), for `workpad agent ping --wait` (turns.ts)
46
+ recordTurn(ctx.project.wp, identity(session), false)
43
47
  ctx.channel(identity(session)!, {
44
48
  onPing: code => say({ session, pong: true, text: pong(code) }),
45
49
  onConfirmed: () => {
@@ -50,11 +54,37 @@ export async function channel(ctx: CommandContext) {
50
54
  }
51
55
  // each page followed on its own, so another session's answers are never handed out here
52
56
  const followed = new Set<string>()
57
+ // the sessions that took the pages no one follows on (`workpad listen --unfollowed --channel`),
58
+ // and the log each answer they were given from another project is in, to mark it received there
59
+ const unfollowed = new Map<string, AbortController>()
60
+ const logOf = new Map<string, string>()
61
+ const takeUnfollowed = (agent: string, session: string) => {
62
+ const wanted = takesUnfollowed(read(ctx.eventsFile).events, agent)
63
+ if (!wanted) {
64
+ unfollowed.get(session)?.abort()
65
+ unfollowed.delete(session)
66
+ return
67
+ }
68
+ if (unfollowed.has(session)) return
69
+ const stop = new AbortController()
70
+ unfollowed.set(session, stop)
71
+ void ctx
72
+ .unfollowed(
73
+ (e, again, from) => {
74
+ const log = from ? projectAt(from.project)?.eventsFile : null
75
+ if (log) logOf.set(e.id, log)
76
+ say({ session, id: e.id, page: e.page, type: e.type, text: unfollowedLine(e, again, from) })
77
+ },
78
+ { agent, mark: false, signal: stop.signal },
79
+ )
80
+ .catch(err => problem('taking the unfollowed pages failed', String(err)))
81
+ }
53
82
  const follow = async () => {
54
83
  // who each confirmed session is on the boards, and the session to bring its pages' answers to
55
84
  const who = new Map<string, string>()
56
85
  for (const [session, confirmed] of sessions) if (confirmed) who.set(identity(session)!, session)
57
86
  if (!who.size) return
87
+ for (const [agent, session] of who) takeUnfollowed(agent, session)
58
88
  for (const p of await ctx.status()) {
59
89
  const agent = p.subscribers.find(s => who.has(s))
60
90
  if (!agent || followed.has(p.page)) continue
@@ -81,11 +111,16 @@ export async function channel(ctx: CommandContext) {
81
111
  /** The plugin brought these answers into their session. */
82
112
  const received = (ids: string[], session: string) => {
83
113
  const agent = identity(session)
84
- const { events } = read(ctx.eventsFile)
85
- const had = receivedBy(events, agent)
86
- for (const id of ids) {
87
- const e = events.find(x => x.id === id)
88
- if (e && !had.has(id)) receive(ctx.eventsFile, e, agent)
114
+ // by log: this project's, or another's an unfollowed page is in
115
+ for (const log of new Set(ids.map(id => logOf.get(id) ?? ctx.eventsFile))) {
116
+ const { events } = read(log)
117
+ const had = receivedBy(events, agent)
118
+ for (const id of ids) {
119
+ if ((logOf.get(id) ?? ctx.eventsFile) !== log) continue
120
+ const e = events.find(x => x.id === id)
121
+ if (e && !had.has(id)) receive(log, e, agent)
122
+ logOf.delete(id)
123
+ }
89
124
  }
90
125
  }
91
126
 
@@ -19,6 +19,7 @@ import fs from 'node:fs'
19
19
  import path from 'node:path'
20
20
  import type { Plugin } from '../../src/define.ts'
21
21
  import { identity, stopReminder, workpadCommand } from '../../src/agents.ts'
22
+ import { recordTurn } from '../../src/turns.ts'
22
23
  import { channel } from './channel.ts'
23
24
  import { shimSource } from './shim.ts'
24
25
 
@@ -37,6 +38,9 @@ export default function opencode(): Plugin {
37
38
  if (ctx.positionals[0] !== 'stop') throw new Error('usage: workpad opencode hook stop')
38
39
  // a hook that fails must not get in the way of the session it runs in: say why, and exit cleanly
39
40
  try {
41
+ // the turn ended, for `workpad agent ping --wait` (turns.ts); one the plugin then sends on
42
+ // with what is left counts as ended a little early, since this can't tell
43
+ recordTurn(ctx.project.wp, identity(session()), true)
40
44
  const left = await stopReminder(ctx, identity(session()))
41
45
  if (left) console.log(JSON.stringify(left))
42
46
  } catch (err) {
@@ -224,6 +224,15 @@ Start on them? :button[Start it]
224
224
  ::::
225
225
  ```
226
226
 
227
+ **Badges:** `:badge[word]` is a status in a word, a grey dot before it.
228
+ `color`, `background` and `border` take a palette name (red orange yellow
229
+ green blue violet pink grey), each off unless set: `{background=red}` is a
230
+ red pill, its text made readable; `live` pulses the dot. The project's
231
+ presets (`workpad docs badge` lists them) give a word its look
232
+ (`:badge[you]`), or a badge names one (`{preset=person}`); built-in words
233
+ like `done` and `blocked` are presets too. The badge's own attributes win
234
+ over its `preset=`, which wins over its word's.
235
+
227
236
  **Nesting containers:** the outer fence needs more colons than anything
228
237
  inside it, `::::grid` around `:::item`. A `:::` closes the first open
229
238
  container whose fence is no longer than its own, so with equal colons the
@@ -425,11 +434,14 @@ message. Whether it does, only a round trip can tell. Once a session,
425
434
  before you first need answers, run
426
435
 
427
436
  ```sh
428
- workpad agent ping
437
+ workpad agent ping --wait # in the background
429
438
  ```
430
439
 
431
- - It says nothing brings answers to this session (exit 1): listen for
432
- them, below.
440
+ Run it in the background, so its end wakes you whatever happens; never
441
+ ping and then just wait for a pong that may not come.
442
+
443
+ - It says nothing brings answers to this session (exit 1 at once): listen
444
+ for them, below.
433
445
  - It pinged this session's channel: a message `workpad: pong` comes to
434
446
  you the way answers will. It may only come once your turn has ended (in
435
447
  opencode it does), so don't start a `listen` yet: end your turn if you
@@ -442,9 +454,12 @@ workpad agent ping
442
454
  once; the channel brings the user's answers waiting there and what
443
455
  comes. Other agents' messages from before that someone already received
444
456
  are skipped; it says how many, and `workpad listen --wait --page
445
- <file>` hands them to you when you want to catch up. No pong by your
446
- next turn: listen for them, below, and in Claude Code tell the user what
447
- `workpad claude doctor` says is wrong.
457
+ <file>` hands them to you when you want to catch up. Once you confirmed,
458
+ the background ping ends (exit 0). It keeps waiting while your turn
459
+ runs, so work on as long as you need; no pong confirmed within two
460
+ minutes after your turn ended: it ends with exit 1, and that wakes you:
461
+ listen for them, below, and in Claude Code tell the user what `workpad
462
+ claude doctor` says is wrong.
448
463
 
449
464
  The answers come as one line each: the page, what the user did, its id:
450
465
  `plan: form scope: "Smaller" (id mwv…; …)`. Act on each, handle it, then
@@ -488,6 +503,15 @@ the user that nobody is listening and their answers wait.
488
503
  (its folder) and `url`; act on it in that folder. Use it only when asked
489
504
  to look after the whole board, and with a confirmed channel, take
490
505
  `workpad listen --channel` instead.
506
+ - `workpad listen --unfollowed` is for a coordinator, so no page swallows
507
+ an answer: it takes only the pages no live session follows (its
508
+ session gone, parked, or with a channel never confirmed), across the
509
+ shared server's projects as above, and hands out the user's answers
510
+ there that no other agent received. A page drops out while its own
511
+ session listens again and joins when it goes; new pages join. What you
512
+ get counts as received; act on it in its project, or hand it on. It
513
+ takes `--wait` (re-run it after each) and, with a confirmed channel,
514
+ `--channel`.
491
515
  - `workpad events --page <file> [--type <name>] [--last 1]` lists what was
492
516
  submitted so far, for when you need the history rather than the next
493
517
  answer. With `--follow` it then prints each new event as it comes, without
package/src/agents.ts CHANGED
@@ -25,7 +25,8 @@ export const identity = (session: string | null): string | null => process.env.W
25
25
  const waitOn = (pages: PageStatus[]) => `workpad listen --wait ${pages.map(p => `--page ${relFile(p.file)}`).join(' ')}`
26
26
 
27
27
  /** For a page nobody listens on: a channel the session has may bring the answers instead. */
28
- const PING = 'run `workpad agent ping` if you haven\'t this session (answers may come to you); else'
28
+ const PING =
29
+ 'run `workpad agent ping --wait` in the background if you haven\'t this session (answers may come to you; it ends when you confirmed the pong, or when none came); else'
29
30
 
30
31
 
31
32
  /**
@@ -128,6 +129,13 @@ export const pong = (code: string) =>
128
129
  export const answerLine = (e: WpEvent, again = false) =>
129
130
  `${e.page}: ${describe(e)}${again ? ' (received before, not handled yet)' : ''} (id ${e.id}; \`workpad thread ${e.id}\` shows it with its question)`
130
131
 
132
+ /**
133
+ * An answer a channel brings from a page no one follows (`workpad listen --unfollowed --channel`):
134
+ * as answerLine, and under the shared server, the project it is in, where its commands run.
135
+ */
136
+ export const unfollowedLine = (e: WpEvent, again: boolean, from: { project: string; url: string } | null) =>
137
+ `${answerLine(e, again)}, on a page no one follows${from ? `, in ${from.project} (${from.url}): run its workpad commands there` : ''}`
138
+
131
139
  /** What to do about answers a channel brought: the same for every agent. */
132
140
  export const ANSWERS_NOTE =
133
141
  'Act on each as on an answer from `workpad listen`. Then handle it with one of: a reply in its chat (`workpad append`), when you have something to say; else `workpad handled <id>`. Nothing more is needed.'
@@ -132,6 +132,35 @@ export function trackBoard() {
132
132
  applyBoard(view)
133
133
  applySearch()
134
134
  })
135
+ // a project's files fold without its files in it: the server lists them once it is opened
136
+ document.addEventListener(
137
+ 'toggle',
138
+ e => {
139
+ const fold = e.target as HTMLDetailsElement
140
+ if (fold.dataset?.wpFiles && fold.open) void loadFiles(fold)
141
+ },
142
+ true,
143
+ )
135
144
  applyBoard(chosen())
136
145
  trackSearch()
137
146
  }
147
+
148
+ async function loadFiles(fold: HTMLDetailsElement) {
149
+ if (fold.dataset.wpLoaded) return
150
+ fold.dataset.wpLoaded = 'loading'
151
+ const count = fold.querySelector('summary .wp-meta')
152
+ if (count) count.textContent = '…'
153
+ try {
154
+ const res = await fetch(`/api/files?base=${encodeURIComponent(fold.dataset.wpFiles!)}`)
155
+ const body = (await res.json()) as { count?: number; html?: string; error?: string }
156
+ if (!res.ok) throw new Error(body.error ?? res.statusText)
157
+ if (count) count.textContent = String(body.count)
158
+ fold.insertAdjacentHTML('beforeend', body.count ? body.html! : '<p class="wp-meta">No markdown files.</p>')
159
+ fold.dataset.wpLoaded = 'yes'
160
+ applySearch()
161
+ } catch (err) {
162
+ delete fold.dataset.wpLoaded
163
+ if (count) count.textContent = ''
164
+ fold.insertAdjacentHTML('beforeend', `<p class="wp-meta">Couldn't list the files: ${String((err as Error).message)}</p>`)
165
+ }
166
+ }
package/src/define.ts CHANGED
@@ -370,6 +370,18 @@ export interface CommandContext {
370
370
  * a page; resolves once the server holds it.
371
371
  */
372
372
  listen(page: string, options?: { agent?: string | null }): Promise<void>
373
+ /**
374
+ * Take the pages no one follows (`workpad listen --unfollowed`), as `agent`, until `signal`
375
+ * aborts: listen on each, and hand the reader's answers there that no other agent received to
376
+ * `onEvent`, as handOut does (received by `agent` unless `mark` is false). A page drops out once someone follows it and
377
+ * joins when its last follower goes; new pages join. Under the shared server they are the pages
378
+ * of every project of this one's entry, and `from` says where each answer is (its project's
379
+ * folder, its page's address); else null. Resolves once the server holds it.
380
+ */
381
+ unfollowed(
382
+ onEvent: (event: WpEvent, again: boolean, from: { project: string; url: string } | null) => void,
383
+ options?: { agent?: string | null; mark?: boolean; signal?: AbortSignal },
384
+ ): Promise<void>
373
385
  /**
374
386
  * Be the channel of agent `session`, a plugin's command that pushes answers into it, for as long
375
387
  * as the command runs. Whether its messages reach the agent only the agent can say: `workpad
@@ -412,6 +424,8 @@ export interface PageStatus {
412
424
  unhandled: WpEvent[]
413
425
  /** the chats on the page whose latest message is the reader's: waiting for the agent's reply */
414
426
  awaitingReply: string[]
427
+ /** when an agent last added to the page's log (a message, a question in a chat), or null */
428
+ updated: string | null
415
429
  /** the running waits and watches that cover the page */
416
430
  listeners: Listener[]
417
431
  }
@@ -484,6 +498,8 @@ export interface IndexPage {
484
498
  url: string
485
499
  /** when its file last changed, in ms */
486
500
  mtime: number
501
+ /** when it last changed for the reader, in ms: its file, or an agent's message or question on it */
502
+ updated: number
487
503
  /** its questions waiting for the reader */
488
504
  open: string[]
489
505
  /** the agent's messages on it the reader hasn't read */
@@ -503,7 +519,7 @@ export interface IndexProject {
503
519
  base: string
504
520
  /** its pages, the latest changed first */
505
521
  pages: IndexPage[]
506
- /** when one of its pages last changed; 0 without pages */
522
+ /** when one of its pages was last updated (IndexPage.updated); 0 without pages */
507
523
  active: number
508
524
  error?: string
509
525
  }
@@ -635,6 +651,11 @@ export interface Listener {
635
651
  agent: string | null
636
652
  /** the name the agent gave itself (`workpad agent name`), when it did: as the server lists it */
637
653
  name?: string
654
+ /**
655
+ * held by `workpad listen --unfollowed` on a page no one else follows: it listens there, but
656
+ * follows nothing, so it never keeps another such listen off the page (listeners.ts, follows)
657
+ */
658
+ unfollowed?: true
638
659
  }
639
660
 
640
661
  /** How a toast looks and acts (Api.toast). */
@@ -931,6 +952,12 @@ interface BaseContext {
931
952
  inline(src: string): Promise<string>
932
953
  /** what a client gets when the block has no props() */
933
954
  defaults(): Promise<Record<string, unknown>>
955
+ /**
956
+ * Report what is wrong with the block as written, for whoever wrote the page, in one sentence (a
957
+ * value it doesn't know): shown above the page and listed by `workpad check` (Rendered.problems).
958
+ * The block still renders as best it can. Nothing in an agent's chat message: nobody there can fix it.
959
+ */
960
+ problem(text: string): void
934
961
  }
935
962
 
936
963
  /** `:::name[label]{attrs}` … `:::`, `::name[label]{attrs}`, `:name[label]{attrs}` */
package/src/events.ts CHANGED
@@ -22,6 +22,7 @@ import {
22
22
  namesOf,
23
23
  receivedIds,
24
24
  subscriptions,
25
+ takesUnfollowed,
25
26
  } from './status.ts'
26
27
 
27
28
  export {
@@ -37,6 +38,7 @@ export {
37
38
  namesOf,
38
39
  receivedIds,
39
40
  subscriptions,
41
+ takesUnfollowed,
40
42
  }
41
43
 
42
44
  /** What is appended: the id and time are added. */
@@ -372,6 +374,16 @@ export interface HandOutOptions {
372
374
  * gets what is new, not other agents' talk from before; `listen --wait` still hands it all out.
373
375
  */
374
376
  skipReceivedBefore?: string
377
+ /**
378
+ * Only the reader's events, no agent's: a listen on the pages no one follows takes the answers
379
+ * waiting there, not what the page's own agents said on them.
380
+ */
381
+ readerOnly?: boolean
382
+ /**
383
+ * Leave out what another agent received: it has it, and is on it (or handed it on). A listen on
384
+ * the pages no one follows takes what reached nobody, not what a session left for between turns.
385
+ */
386
+ notReceivedByOthers?: boolean
375
387
  }
376
388
 
377
389
  /**
@@ -402,6 +414,8 @@ export function handOut(
402
414
  mark = true,
403
415
  agent = null,
404
416
  skipReceivedBefore,
417
+ readerOnly = false,
418
+ notReceivedByOthers = false,
405
419
  } = options
406
420
  return new Promise(resolve => {
407
421
  let got = 0
@@ -412,7 +426,7 @@ export function handOut(
412
426
  resolve(got)
413
427
  }
414
428
  // 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)
429
+ const fromOthers = (e: WpEvent) => fromReader(e) || (!readerOnly && !!e.by && e.by !== agent)
416
430
  // of those, the ones for an agent, unless the filter names a type
417
431
  const wanted = (e: WpEvent) => fromOthers(e) && matches(e, filter) && (!!filter.type || isForAgent(e.type))
418
432
  // what this identity received before, by id: handed out again, it says so
@@ -428,13 +442,20 @@ export function handOut(
428
442
  const { events, end } = read(file)
429
443
  const handled = handledIds(events)
430
444
  before = receivedBy(events, agent)
445
+ const others = notReceivedByOthers
446
+ ? new Set(
447
+ events
448
+ .filter(e => e.type === RECEIVED && !fromReader(e) && (e.by ?? null) !== agent)
449
+ .map(e => String(e.data?.event)),
450
+ )
451
+ : new Set<string>()
431
452
  // the past before a channel's subscription: what someone received, unless it is the reader's
432
453
  let skipping = !!skipReceivedBefore
433
454
  const receivedAny = skipping ? receivedIds(events) : new Set<string>()
434
455
  for (const e of events) {
435
456
  if (skipping && e.id === skipReceivedBefore) skipping = false
436
457
  if (skipping && !fromReader(e) && receivedAny.has(e.id)) continue
437
- if (wanted(e) && !handled.has(e.id) && !hand(e)) return finish()
458
+ if (wanted(e) && !handled.has(e.id) && !others.has(e.id) && !hand(e)) return finish()
438
459
  }
439
460
  // a batch: what there was, if anything; else it goes on for the first to come
440
461
  if (batch && got) return finish()