@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.
- package/bin/workpad.ts +238 -17
- package/dist/bin/workpad.js +191 -13
- package/dist/plugins/badge/README.md +59 -10
- package/dist/plugins/badge/index.js +130 -8
- package/dist/plugins/badge/public/style.css +132 -12
- package/dist/plugins/chat/index.js +7 -1
- package/dist/plugins/claude/README.md +13 -5
- package/dist/plugins/claude/channel.js +25 -2
- package/dist/plugins/claude/doctor.js +43 -47
- package/dist/plugins/claude/index.js +24 -8
- package/dist/plugins/claude/session.js +46 -1
- package/dist/plugins/opencode/channel.js +42 -7
- package/dist/plugins/opencode/index.js +2 -0
- package/dist/src/agents.js +7 -2
- package/dist/src/client/page/main.js +23 -0
- package/dist/src/events.js +6 -5
- package/dist/src/help.js +18 -4
- package/dist/src/hub.js +62 -2
- package/dist/src/listen.js +36 -4
- package/dist/src/listeners.js +14 -4
- package/dist/src/pages/board.js +9 -4
- package/dist/src/pages/index.js +2 -4
- package/dist/src/pages/markdown.js +47 -16
- package/dist/src/pages/render.js +128 -32
- package/dist/src/server.js +69 -6
- package/dist/src/state.js +2 -1
- package/dist/src/status.js +11 -2
- package/dist/src/turns.js +41 -0
- package/package.json +6 -1
- package/plugins/badge/README.md +59 -10
- package/plugins/badge/index.ts +141 -8
- package/plugins/badge/public/style.css +132 -12
- package/plugins/chat/index.ts +9 -1
- package/plugins/claude/README.md +13 -5
- package/plugins/claude/channel.ts +26 -2
- package/plugins/claude/doctor.ts +58 -39
- package/plugins/claude/index.ts +30 -8
- package/plugins/claude/session.ts +32 -0
- package/plugins/opencode/channel.ts +42 -7
- package/plugins/opencode/index.ts +4 -0
- package/skills/workpad/SKILL.md +30 -6
- package/src/agents.ts +9 -1
- package/src/client/page/board.ts +29 -0
- package/src/define.ts +28 -1
- package/src/events.ts +23 -2
- package/src/help.ts +18 -4
- package/src/hub.ts +80 -2
- package/src/listen.ts +47 -4
- package/src/listeners.ts +22 -1
- package/src/pages/board.ts +10 -3
- package/src/pages/index.ts +8 -10
- package/src/pages/markdown.ts +55 -8
- package/src/pages/render.ts +132 -35
- package/src/server.ts +84 -6
- package/src/state.ts +3 -0
- package/src/status.ts +15 -1
- package/src/turns.ts +56 -0
package/src/pages/render.ts
CHANGED
|
@@ -8,7 +8,8 @@ import fs from 'node:fs'
|
|
|
8
8
|
import os from 'node:os'
|
|
9
9
|
import path from 'node:path'
|
|
10
10
|
import { fileURLToPath } from 'node:url'
|
|
11
|
-
import { execFileSync } from 'node:child_process'
|
|
11
|
+
import { execFile, execFileSync } from 'node:child_process'
|
|
12
|
+
import { promisify } from 'node:util'
|
|
12
13
|
import { renderMarkdown, type Island, type MdNode } from './markdown.ts'
|
|
13
14
|
import { html, raw, type Html } from '../html.ts'
|
|
14
15
|
import { INBOX_ICON, awaitingLabel } from '../icons.ts'
|
|
@@ -62,13 +63,18 @@ const body = (source: string) => source.replace(FRONTMATTER, '')
|
|
|
62
63
|
/** A page's title: its first heading, else its name. */
|
|
63
64
|
export function titleOf(file: string, fallback: string) {
|
|
64
65
|
try {
|
|
65
|
-
|
|
66
|
-
return h1 ? h1[1].replace(/[*_`]/g, '') : fallback
|
|
66
|
+
return headingOf(fs.readFileSync(file, 'utf8')) ?? fallback
|
|
67
67
|
} catch {
|
|
68
68
|
return fallback
|
|
69
69
|
}
|
|
70
70
|
}
|
|
71
71
|
|
|
72
|
+
/** The first heading of a page's markdown, past its frontmatter; null when it has none. */
|
|
73
|
+
function headingOf(source: string): string | null {
|
|
74
|
+
const h1 = /^#\s+(.+)$/m.exec(body(source))
|
|
75
|
+
return h1 ? h1[1].replace(/[*_`]/g, '') : null
|
|
76
|
+
}
|
|
77
|
+
|
|
72
78
|
function crumbs(id: string, name: string, base: string, entry?: RenderContext['entry']) {
|
|
73
79
|
const parts = id ? id.split('/') : []
|
|
74
80
|
// under a shared server, the overview of every project comes first, by its own name
|
|
@@ -161,6 +167,100 @@ function documentsIn(dir: string, shows: (rel: string) => boolean = rel => fileF
|
|
|
161
167
|
return [...new Set(files)].filter(shows).toSorted((a, b) => depth(a) - depth(b) || a.localeCompare(b))
|
|
162
168
|
}
|
|
163
169
|
|
|
170
|
+
/** A document as the overview lists it: its path in the project, its title, when its file last changed. */
|
|
171
|
+
interface Doc {
|
|
172
|
+
file: string
|
|
173
|
+
title: string
|
|
174
|
+
mtime: number
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function docOf(dir: string, file: string): Doc {
|
|
178
|
+
const abs = path.join(dir, file)
|
|
179
|
+
let mtime = 0
|
|
180
|
+
try {
|
|
181
|
+
mtime = fs.statSync(abs).mtimeMs
|
|
182
|
+
} catch {
|
|
183
|
+
/* gone meanwhile */
|
|
184
|
+
}
|
|
185
|
+
return { file, title: titleOf(abs, path.posix.basename(file)), mtime }
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Whether a project without pages has documents to read, without listing them: a markdown file in
|
|
190
|
+
* its top folder (a README). Cheap, so the overview can ask it of every project on each render;
|
|
191
|
+
* the files themselves are listed only when the reader opens the fold (filesFold).
|
|
192
|
+
*/
|
|
193
|
+
export function hasTopDocs(dir: string): boolean {
|
|
194
|
+
try {
|
|
195
|
+
return fs.readdirSync(dir).some(n => MARKDOWN.test(n))
|
|
196
|
+
} catch {
|
|
197
|
+
return false
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const run = promisify(execFile)
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* The files fold of a project without pages, listed when the reader opens it (GET /api/files on the
|
|
205
|
+
* shared server): documentsIn's list, but off the event loop. A checkout holds thousands of
|
|
206
|
+
* markdown files, and listing them on each render froze the shared server for many seconds.
|
|
207
|
+
*/
|
|
208
|
+
export async function filesFold(dir: string, base: string): Promise<{ count: number; html: string }> {
|
|
209
|
+
let files: string[]
|
|
210
|
+
try {
|
|
211
|
+
const { stdout } = await run(
|
|
212
|
+
'git',
|
|
213
|
+
['ls-files', '--cached', '--others', '--exclude-standard', '--', ':(icase)*.md', ':(icase)*.markdown'],
|
|
214
|
+
{ cwd: dir, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 },
|
|
215
|
+
)
|
|
216
|
+
files = stdout.split('\n').filter(f => f && !f.startsWith('.workpad/'))
|
|
217
|
+
} catch {
|
|
218
|
+
files = []
|
|
219
|
+
const walk = async (rel: string) => {
|
|
220
|
+
let entries: fs.Dirent[] = []
|
|
221
|
+
try {
|
|
222
|
+
entries = await fs.promises.readdir(path.join(dir, rel), { withFileTypes: true })
|
|
223
|
+
} catch {
|
|
224
|
+
return
|
|
225
|
+
}
|
|
226
|
+
for (const e of entries) {
|
|
227
|
+
if (e.isDirectory()) {
|
|
228
|
+
if (!SKIP.has(e.name) && !e.name.startsWith('.')) await walk(path.posix.join(rel, e.name))
|
|
229
|
+
} else if (MARKDOWN.test(e.name)) files.push(path.posix.join(rel, e.name))
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
await walk('')
|
|
233
|
+
}
|
|
234
|
+
const shows = fileFilter().shows
|
|
235
|
+
const depth = (f: string) => f.split('/').length
|
|
236
|
+
files = [...new Set(files)].filter(f => shows(f)).toSorted((a, b) => depth(a) - depth(b) || a.localeCompare(b))
|
|
237
|
+
// a title is in a file's first lines: read only those, a few files at a time
|
|
238
|
+
const docs: Doc[] = []
|
|
239
|
+
for (let i = 0; i < files.length; i += 32) {
|
|
240
|
+
const batch = await Promise.all(
|
|
241
|
+
files.slice(i, i + 32).map(async (file): Promise<Doc | null> => {
|
|
242
|
+
const abs = path.join(dir, file)
|
|
243
|
+
try {
|
|
244
|
+
const handle = await fs.promises.open(abs, 'r')
|
|
245
|
+
try {
|
|
246
|
+
const { mtimeMs } = await handle.stat()
|
|
247
|
+
const buf = Buffer.alloc(8192)
|
|
248
|
+
const { bytesRead } = await handle.read(buf, 0, buf.length, 0)
|
|
249
|
+
const name = path.posix.basename(file)
|
|
250
|
+
return { file, title: headingOf(buf.toString('utf8', 0, bytesRead)) ?? name, mtime: mtimeMs }
|
|
251
|
+
} finally {
|
|
252
|
+
await handle.close()
|
|
253
|
+
}
|
|
254
|
+
} catch {
|
|
255
|
+
return null // gone meanwhile (git also lists files deleted and not yet committed)
|
|
256
|
+
}
|
|
257
|
+
}),
|
|
258
|
+
)
|
|
259
|
+
for (const d of batch) if (d) docs.push(d)
|
|
260
|
+
}
|
|
261
|
+
return { count: docs.length, html: String(documentFolders(docs, dir, base, () => null)) }
|
|
262
|
+
}
|
|
263
|
+
|
|
164
264
|
/**
|
|
165
265
|
* The overview's list of the project's documents: each by its title, linked to its rendered page,
|
|
166
266
|
* with when its file last changed. The list can be sorted in the browser (sort.ts): by folder (as
|
|
@@ -177,19 +277,28 @@ function documentList(ctx: RenderContext) {
|
|
|
177
277
|
* (`docs/adr/`), so the tree is no deeper than what tells folders apart.
|
|
178
278
|
*/
|
|
179
279
|
function documentTree(
|
|
180
|
-
|
|
280
|
+
docs: Doc[],
|
|
181
281
|
dir: string,
|
|
182
282
|
base: string,
|
|
183
283
|
urlFor: (abs: string) => string | null,
|
|
184
284
|
open = false,
|
|
185
285
|
) {
|
|
286
|
+
return html`<details class="wp-documents wp-folded-documents"${raw(open ? ' open' : '')}>
|
|
287
|
+
<summary>Files <span class="wp-meta">${docs.length}</span></summary>
|
|
288
|
+
${documentFolders(docs, dir, base, urlFor)}
|
|
289
|
+
</details>`
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** The inside of a project's files fold: its documents by folder, a fold per folder with how many. */
|
|
293
|
+
function documentFolders(docs: Doc[], dir: string, base: string, urlFor: (abs: string) => string | null): Html {
|
|
186
294
|
interface Folder {
|
|
187
295
|
files: string[]
|
|
188
296
|
folders: Map<string, Folder>
|
|
189
297
|
count: number
|
|
190
298
|
}
|
|
191
299
|
const root: Folder = { files: [], folders: new Map(), count: 0 }
|
|
192
|
-
|
|
300
|
+
const byFile = new Map(docs.map(d => [d.file, d]))
|
|
301
|
+
for (const { file: f } of docs) {
|
|
193
302
|
let at = root
|
|
194
303
|
at.count++
|
|
195
304
|
const parts = f.split('/')
|
|
@@ -203,13 +312,7 @@ function documentTree(
|
|
|
203
312
|
const row = (f: string) => {
|
|
204
313
|
const abs = path.join(dir, f)
|
|
205
314
|
const name = path.posix.basename(f)
|
|
206
|
-
const title =
|
|
207
|
-
let mtime = 0
|
|
208
|
-
try {
|
|
209
|
-
mtime = fs.statSync(abs).mtimeMs
|
|
210
|
-
} catch {
|
|
211
|
-
/* gone meanwhile */
|
|
212
|
-
}
|
|
315
|
+
const { title, mtime } = byFile.get(f)!
|
|
213
316
|
return html`<li>
|
|
214
317
|
<a href="${urlFor(abs) ?? `${base}/-/${f}`}">${title}</a>
|
|
215
318
|
<span class="wp-meta">${title !== name && html`<code>${name}</code> · `}edited ${time(mtime)}</span>
|
|
@@ -234,10 +337,7 @@ function documentTree(
|
|
|
234
337
|
${f.files.map(row)}
|
|
235
338
|
</ul>`
|
|
236
339
|
}${[...f.folders].toSorted(([a], [b]) => a.localeCompare(b)).map(([name, sub]) => folder(name, sub))}`
|
|
237
|
-
return
|
|
238
|
-
<summary>Files <span class="wp-meta">${files.length}</span></summary>
|
|
239
|
-
${contents(root)}
|
|
240
|
-
</details>`
|
|
340
|
+
return contents(root)
|
|
241
341
|
}
|
|
242
342
|
|
|
243
343
|
/**
|
|
@@ -252,21 +352,15 @@ function documentsOf(
|
|
|
252
352
|
shows?: (rel: string) => boolean,
|
|
253
353
|
open = false,
|
|
254
354
|
) {
|
|
255
|
-
const
|
|
256
|
-
if (!
|
|
355
|
+
const docs = documentsIn(dir, shows).map(f => docOf(dir, f))
|
|
356
|
+
if (!docs.length) return ''
|
|
357
|
+
if (folded) return documentTree(docs, dir, base, urlFor, open)
|
|
257
358
|
const ctx = { project: { dir }, base, urlFor }
|
|
258
|
-
const rows =
|
|
359
|
+
const rows = docs.map(({ file: f, title, mtime }, i) => {
|
|
259
360
|
const abs = path.join(ctx.project.dir, f)
|
|
260
361
|
// a file without a heading goes by its name, and the line under it says the folder it is in
|
|
261
362
|
const name = path.posix.basename(f)
|
|
262
|
-
const title = titleOf(abs, name)
|
|
263
363
|
const where = title === name ? path.posix.dirname(f) : f
|
|
264
|
-
let mtime = 0
|
|
265
|
-
try {
|
|
266
|
-
mtime = fs.statSync(abs).mtimeMs
|
|
267
|
-
} catch {
|
|
268
|
-
/* gone meanwhile */
|
|
269
|
-
}
|
|
270
364
|
return html`<li data-order="${i}" data-updated="${mtime}" data-title="${title.toLowerCase()}">
|
|
271
365
|
<a href="${ctx.urlFor(abs) ?? `${ctx.base ?? ''}/-/${f}`}">${title}</a>
|
|
272
366
|
<span class="wp-meta"
|
|
@@ -274,7 +368,6 @@ function documentsOf(
|
|
|
274
368
|
>
|
|
275
369
|
</li>`
|
|
276
370
|
})
|
|
277
|
-
if (folded) return documentTree(files, dir, base, urlFor, open)
|
|
278
371
|
// in a section, so the heading isn't numbered like the page's own sections
|
|
279
372
|
return html`<section class="wp-documents">
|
|
280
373
|
<div class="wp-list-head">
|
|
@@ -325,7 +418,7 @@ function card(c: Card<BoardProject>, withProject: boolean) {
|
|
|
325
418
|
<a class="wp-board-title" href="${c.page.url}">${c.page.title}</a>
|
|
326
419
|
${counts(c.waiting, `${c.page.url}#wp-waiting`)}
|
|
327
420
|
${withProject && html`<span class="wp-board-project">${c.project.label}</span>`}
|
|
328
|
-
<span class="wp-meta wp-board-when">
|
|
421
|
+
<span class="wp-meta wp-board-when">updated ${time(c.page.updated)}</span>
|
|
329
422
|
</li>`
|
|
330
423
|
}
|
|
331
424
|
|
|
@@ -359,11 +452,12 @@ function emptyColumn(projects: BoardProject[]) {
|
|
|
359
452
|
function board(projects: BoardProject[], now: number) {
|
|
360
453
|
const states = byState(projects, now)
|
|
361
454
|
// of the projects without pages, those with documents to read get a column of their own in the
|
|
362
|
-
// per-project view (a worktree's README and docs), and only the truly empty fold at the end
|
|
363
|
-
|
|
455
|
+
// per-project view (a worktree's README and docs), and only the truly empty fold at the end. Which
|
|
456
|
+
// is which is a look at the top folder: listing a checkout's files (thousands, in a big repository)
|
|
457
|
+
// waits until the reader opens its fold (filesFold), so a render reads no project's files
|
|
364
458
|
const empty = withoutPages(projects)
|
|
365
|
-
const withDocs =
|
|
366
|
-
const bare = empty.filter(p => !
|
|
459
|
+
const withDocs = empty.filter(p => p.files && hasTopDocs(p.dir))
|
|
460
|
+
const bare = empty.filter(p => !withDocs.includes(p))
|
|
367
461
|
const hours = ACTIVE_FOR / 3_600_000
|
|
368
462
|
const stateColumn = (key: keyof typeof states, title: string, note: string) =>
|
|
369
463
|
html`<section class="wp-board-column wp-board-${key}${key === 'waiting' && states.waiting.length ? ' wp-board-waits' : ''}">
|
|
@@ -384,14 +478,17 @@ function board(projects: BoardProject[], now: number) {
|
|
|
384
478
|
${cards(col.cards, false)} ${p.files && documentsOf(p.dir, p.base, () => null, true)}
|
|
385
479
|
</section>`
|
|
386
480
|
}
|
|
387
|
-
// a project with documents and no pages: its column holds its files,
|
|
481
|
+
// a project with documents and no pages: its column holds its files, listed when the fold opens
|
|
482
|
+
// (board.ts in the page asks /api/files for them)
|
|
388
483
|
const docsColumn = (p: BoardProject) =>
|
|
389
484
|
html`<section class="wp-board-column wp-board-docs">
|
|
390
485
|
<header class="wp-board-head" title="${p.dir.replace(os.homedir(), '~')}">
|
|
391
486
|
<h2><a href="${p.base}/">${p.label}</a></h2>
|
|
392
|
-
<span class="wp-meta">no pages
|
|
487
|
+
<span class="wp-meta">no pages</span>
|
|
393
488
|
</header>
|
|
394
|
-
${
|
|
489
|
+
<details class="wp-documents wp-folded-documents" data-wp-files="${p.base}">
|
|
490
|
+
<summary>Files <span class="wp-meta"></span></summary>
|
|
491
|
+
</details>
|
|
395
492
|
</section>`
|
|
396
493
|
return html`<div class="wp-board-bar">
|
|
397
494
|
<div class="wp-board-switch" role="group" aria-label="Columns">
|
package/src/server.ts
CHANGED
|
@@ -67,7 +67,7 @@ import { SCROLL, agentMessagesIn, awaiting, isAgentMessage, projectStatus, type
|
|
|
67
67
|
import { formsIn, messageForms } from './pages/markdown.ts'
|
|
68
68
|
import { fileFilter, type FileFilter } from './files.ts'
|
|
69
69
|
import { titleOf } from './pages/render.ts'
|
|
70
|
-
import { createRegistry, holdStream, listenerOf } from './listeners.ts'
|
|
70
|
+
import { createRegistry, follows, holdStream, listenerOf } from './listeners.ts'
|
|
71
71
|
import { inPublic } from './public.ts'
|
|
72
72
|
import { build, type BuildResult } from './build.ts'
|
|
73
73
|
import { PAGE_CLIENT, RUNTIME, frontmatterOf, pageDocument, pluginParts, type Render, type SetUp } from './document.ts'
|
|
@@ -142,6 +142,13 @@ export interface WorkpadServer {
|
|
|
142
142
|
addListener(l: Listener): () => void
|
|
143
143
|
/** call `fn` whenever a listener comes or goes; returns what stops it */
|
|
144
144
|
onListeners(fn: () => void): () => void
|
|
145
|
+
/**
|
|
146
|
+
* Hold `listener` on each page no one follows (`workpad listen --unfollowed`), for as long as it
|
|
147
|
+
* isn't stopped: a page drops out once someone follows it, and joins when its last follower goes,
|
|
148
|
+
* as does a new page. `onPages` is told the pages, at once and whenever they change.
|
|
149
|
+
* @returns what stops it
|
|
150
|
+
*/
|
|
151
|
+
unfollowed(listener: Listener, onPages: (pages: string[]) => void): () => void
|
|
145
152
|
/** who listens now: the running listens and channels, and an entry's listens held for it */
|
|
146
153
|
listeners(): Listener[]
|
|
147
154
|
/** whether it serves its files (its config read first) */
|
|
@@ -416,10 +423,8 @@ export function createServer(
|
|
|
416
423
|
// what each form asks, for the API
|
|
417
424
|
let details: FormDetail[] = []
|
|
418
425
|
try {
|
|
419
|
-
const
|
|
420
|
-
asks =
|
|
421
|
-
chats = renderer?.chats(source)
|
|
422
|
-
details = renderer?.forms(source) ?? []
|
|
426
|
+
const said = renderer?.asks(pageSource(id, file))
|
|
427
|
+
if (said) ({ questions: asks, chats, forms: details } = said)
|
|
423
428
|
} catch (err) {
|
|
424
429
|
console.error('questions:', err)
|
|
425
430
|
}
|
|
@@ -442,10 +447,19 @@ export function createServer(
|
|
|
442
447
|
async function snapshot(listed: PagesSource['pages']): Promise<ProjectStatus> {
|
|
443
448
|
const { pages: renderer, handedOut, forReader } = await config()
|
|
444
449
|
const events = readEvents(project.eventsFile)
|
|
450
|
+
// each page's messages, the log gone through once instead of once for every chat of every page
|
|
451
|
+
const messages = new Map<string, WpEvent[]>()
|
|
452
|
+
for (const e of events) {
|
|
453
|
+
if (!isAgentMessage(e)) continue
|
|
454
|
+
const own = messages.get(e.page)
|
|
455
|
+
if (own) own.push(e)
|
|
456
|
+
else messages.set(e.page, [e])
|
|
457
|
+
}
|
|
445
458
|
const pages = listed.map(p => {
|
|
446
459
|
const page = { id: p.id, file: p.file, ...questionsOf(renderer, p.id, p.file) }
|
|
447
460
|
// the forms in the agent's messages in the page's chats are its questions too
|
|
448
|
-
|
|
461
|
+
const forms = messageForms(messages.get(p.id) ?? [], p.id, page.chats ?? [])
|
|
462
|
+
return { ...page, asks: [...page.asks, ...forms] }
|
|
449
463
|
})
|
|
450
464
|
return projectStatus({
|
|
451
465
|
pages,
|
|
@@ -718,6 +732,56 @@ export function createServer(
|
|
|
718
732
|
const pings = new Map<string, string>()
|
|
719
733
|
const pingCode = () => crypto.randomBytes(3).toString('hex')
|
|
720
734
|
|
|
735
|
+
// ---- the unfollowed pages ----------------------------------------------------------------------
|
|
736
|
+
// A listen on the pages no one follows (`workpad listen --unfollowed`, a coordinator's) is held as
|
|
737
|
+
// a listener on each of them, so they say someone listens; that listener follows nothing itself
|
|
738
|
+
// (listeners.ts, follows). The set is looked at again whenever a listener comes or goes and
|
|
739
|
+
// whenever a page changes (made, deleted).
|
|
740
|
+
interface Unfollowing {
|
|
741
|
+
listener: Listener
|
|
742
|
+
onPages(pages: string[]): void
|
|
743
|
+
held: Map<string, () => void>
|
|
744
|
+
told: string | null
|
|
745
|
+
}
|
|
746
|
+
const unfollowing = new Set<Unfollowing>()
|
|
747
|
+
let looking = false
|
|
748
|
+
function lookAgain() {
|
|
749
|
+
if (looking || !unfollowing.size) return
|
|
750
|
+
looking = true
|
|
751
|
+
// after what changed is done: holding a page is a change of listeners too
|
|
752
|
+
setImmediate(() => {
|
|
753
|
+
looking = false
|
|
754
|
+
const pages = pagesIn(project.pagesDir)
|
|
755
|
+
.map(p => p.id)
|
|
756
|
+
.filter(id => !registry.list(id).some(l => follows(l, id)))
|
|
757
|
+
for (const u of unfollowing) {
|
|
758
|
+
for (const [page, release] of u.held)
|
|
759
|
+
if (!pages.includes(page)) {
|
|
760
|
+
release()
|
|
761
|
+
u.held.delete(page)
|
|
762
|
+
}
|
|
763
|
+
for (const page of pages)
|
|
764
|
+
if (!u.held.has(page)) u.held.set(page, registry.add({ ...u.listener, page, unfollowed: true }))
|
|
765
|
+
const now = JSON.stringify(pages)
|
|
766
|
+
if (now !== u.told) {
|
|
767
|
+
u.told = now
|
|
768
|
+
u.onPages(pages)
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
})
|
|
772
|
+
}
|
|
773
|
+
registry.onChange(lookAgain)
|
|
774
|
+
function unfollowed(listener: Listener, onPages: (pages: string[]) => void): () => void {
|
|
775
|
+
const u: Unfollowing = { listener, onPages, held: new Map(), told: null }
|
|
776
|
+
unfollowing.add(u)
|
|
777
|
+
lookAgain()
|
|
778
|
+
return () => {
|
|
779
|
+
if (!unfollowing.delete(u)) return
|
|
780
|
+
for (const release of u.held.values()) release()
|
|
781
|
+
u.held.clear()
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
|
|
721
785
|
// ---- live changes ------------------------------------------------------------------------------
|
|
722
786
|
// The browser listens on a WebSocket at /api/live, each message `{ event, data }`. `change`: its
|
|
723
787
|
// page changed; `events`: the log grew; `listeners`: an agent started or stopped waiting; `style`:
|
|
@@ -757,6 +821,7 @@ export function createServer(
|
|
|
757
821
|
|
|
758
822
|
function pageChanged(id: string) {
|
|
759
823
|
onChange?.()
|
|
824
|
+
lookAgain()
|
|
760
825
|
for (const c of clients) {
|
|
761
826
|
if (c.isDir ? !c.page || id.startsWith(c.page + '/') : c.page === id || c.page + '/index' === id)
|
|
762
827
|
notify(c, 'change')
|
|
@@ -1218,6 +1283,18 @@ export function createServer(
|
|
|
1218
1283
|
if (p === '/api/status') return sendJson(res, 200, await status(q.page || null))
|
|
1219
1284
|
if (p === '/api/listeners') return sendJson(res, 200, listenersFor(q.page ?? null))
|
|
1220
1285
|
if (p === '/api/stamps') return sendJson(res, 200, stamps())
|
|
1286
|
+
if (p === '/api/listen' && url.searchParams.has('unfollowed')) {
|
|
1287
|
+
// on the pages no one follows, told which they are as they change
|
|
1288
|
+
const stop = unfollowed(listenerOf(url.searchParams), pages =>
|
|
1289
|
+
stream.send('pages', { projects: pages.length ? [{ dir: project.dir, base, pages }] : [] }),
|
|
1290
|
+
)
|
|
1291
|
+
const stream = holdStream(req, res, () => {
|
|
1292
|
+
stop()
|
|
1293
|
+
streams.delete(stream.end)
|
|
1294
|
+
})
|
|
1295
|
+
streams.add(stream.end)
|
|
1296
|
+
return
|
|
1297
|
+
}
|
|
1221
1298
|
if (p === '/api/listen') {
|
|
1222
1299
|
// any number listen on a page; each is a listener for as long as its connection is open
|
|
1223
1300
|
const remove = registry.add(listenerOf(url.searchParams))
|
|
@@ -1370,6 +1447,7 @@ export function createServer(
|
|
|
1370
1447
|
elsewhere: () => notifyAll('elsewhere'),
|
|
1371
1448
|
addListener: l => registry.add(l),
|
|
1372
1449
|
onListeners: fn => registry.onChange(fn),
|
|
1450
|
+
unfollowed,
|
|
1373
1451
|
status: (page = null) => status(page),
|
|
1374
1452
|
read: readList,
|
|
1375
1453
|
stream,
|
package/src/state.ts
CHANGED
|
@@ -107,6 +107,8 @@ export interface SubscriptionInfo {
|
|
|
107
107
|
since: string
|
|
108
108
|
/** taken on through its channel (`workpad listen --channel`) */
|
|
109
109
|
channel: boolean
|
|
110
|
+
/** not a page: the agent's channel takes the pages no one follows (`workpad listen --unfollowed --channel`) */
|
|
111
|
+
unfollowed?: true
|
|
110
112
|
}
|
|
111
113
|
|
|
112
114
|
/** An agent the board knows (GET /api/agents): it named itself, subscribed, wrote something, or listens now. */
|
|
@@ -303,6 +305,7 @@ export function subscriptionsOf(s: Pick<StateSource, 'base' | 'events'>): Subscr
|
|
|
303
305
|
page: e.page,
|
|
304
306
|
since: e.ts,
|
|
305
307
|
channel: !!e.data?.channel,
|
|
308
|
+
...(e.data?.unfollowed ? { unfollowed: true as const } : {}),
|
|
306
309
|
}))
|
|
307
310
|
}
|
|
308
311
|
|
package/src/status.ts
CHANGED
|
@@ -251,7 +251,7 @@ export function receivedIds(events: WpEvent[]): Set<string> {
|
|
|
251
251
|
export function channelSince(events: WpEvent[], agent: string, page: string): string | null {
|
|
252
252
|
let since: string | null = null
|
|
253
253
|
for (const e of subscriptions(events)) {
|
|
254
|
-
if (e.by !== agent) continue
|
|
254
|
+
if (e.by !== agent || e.data?.unfollowed) continue
|
|
255
255
|
if (!(e.page === '' || e.page === page || page.startsWith(`${e.page}/`))) continue
|
|
256
256
|
if (!e.data?.channel) return null
|
|
257
257
|
since ??= e.id
|
|
@@ -259,6 +259,15 @@ export function channelSince(events: WpEvent[], agent: string, page: string): st
|
|
|
259
259
|
return since
|
|
260
260
|
}
|
|
261
261
|
|
|
262
|
+
/**
|
|
263
|
+
* Does `agent` take the pages no one follows through its channel (`workpad listen --unfollowed
|
|
264
|
+
* --channel`)? Said by a subscription on every page (`''`) with data `{ channel: true, unfollowed:
|
|
265
|
+
* true }`; it makes no page the agent's (no subscriber of any), and `workpad agent unsubscribe`
|
|
266
|
+
* takes it off with the rest.
|
|
267
|
+
*/
|
|
268
|
+
export const takesUnfollowed = (events: WpEvent[], agent: string): boolean =>
|
|
269
|
+
subscriptions(events).some(e => e.by === agent && !!e.data?.unfollowed)
|
|
270
|
+
|
|
262
271
|
/**
|
|
263
272
|
* The ids of the reader's events the agent handled: acknowledged (`workpad:handled`), or replied
|
|
264
273
|
* to after them (see the top of this file). The log is gone through once: each of the reader's
|
|
@@ -372,6 +381,8 @@ export function projectStatus({ pages, events, listeners, forAgent, forReader }:
|
|
|
372
381
|
if (fromReader(e)) last.set(e.page, e.ts)
|
|
373
382
|
}
|
|
374
383
|
for (const e of subscriptions(events)) {
|
|
384
|
+
// taking the unfollowed pages makes none of them the agent's (takesUnfollowed)
|
|
385
|
+
if (e.data?.unfollowed) continue
|
|
375
386
|
const now = subscribers.get(e.page) ?? []
|
|
376
387
|
if (!now.includes(e.by!)) subscribers.set(e.page, [...now, e.by!])
|
|
377
388
|
}
|
|
@@ -403,6 +414,9 @@ export function projectStatus({ pages, events, listeners, forAgent, forReader }:
|
|
|
403
414
|
unreceived: own.filter(e => fromReader(e) && forAgent(e.type) && !received.has(e.id) && !handled.has(e.id)),
|
|
404
415
|
unhandled: own.filter(e => fromReader(e) && forAgent(e.type) && received.has(e.id) && !handled.has(e.id)),
|
|
405
416
|
awaitingReply: awaitingReply(own),
|
|
417
|
+
// what an agent last did on the page besides editing it (a message, a question in a chat):
|
|
418
|
+
// the reader's own events and the log's bookkeeping (received, handled, read…) aren't news
|
|
419
|
+
updated: own.findLast(e => !fromReader(e) && !e.type.startsWith('workpad:'))?.ts ?? null,
|
|
406
420
|
listeners: listening,
|
|
407
421
|
}
|
|
408
422
|
}),
|
package/src/turns.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// When an agent session's turn last ended, one file per session: `.workpad/turns/<session>`.
|
|
2
|
+
// A coding agent's harness gives the session what a channel pushes (the pong of `workpad agent
|
|
3
|
+
// ping`, an answer) only once its turn ends, so `workpad agent ping --wait`, run in the background
|
|
4
|
+
// while the agent works on, counts its timeout from the first turn end after its ping, not from the
|
|
5
|
+
// ping. The plugins of coding agents record it:
|
|
6
|
+
// - claude: the SessionStart hook marks the session as one whose turn ends are recorded, and the
|
|
7
|
+
// Stop hook records each end it lets happen (not one it continues with a reminder);
|
|
8
|
+
// - opencode: its channel marks a session once it follows it, and `hook stop`, which the plugin
|
|
9
|
+
// opencode loads runs when the session goes idle, records each end.
|
|
10
|
+
// The file holds the time of the last end (ms since the epoch, this machine's clock, as the wait's),
|
|
11
|
+
// or nothing: marked, no end yet. A session without a file (another harness, a hook not installed)
|
|
12
|
+
// has none of this, and the wait counts from its ping.
|
|
13
|
+
import fs from 'node:fs'
|
|
14
|
+
import path from 'node:path'
|
|
15
|
+
|
|
16
|
+
const dirOf = (wp: string) => path.join(wp, 'turns')
|
|
17
|
+
const fileOf = (wp: string, session: string) => path.join(dirOf(wp), encodeURIComponent(session))
|
|
18
|
+
|
|
19
|
+
/** Records older than this go when a turn end is written: their sessions are long over. */
|
|
20
|
+
const KEEP = 7 * 24 * 3600_000
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Record for `session` that its turn ended now (`ended`), or only that its turn ends are recorded
|
|
24
|
+
* (a mark: an end recorded before stays).
|
|
25
|
+
*/
|
|
26
|
+
export function recordTurn(wp: string, session: string | null, ended: boolean) {
|
|
27
|
+
if (!session) return
|
|
28
|
+
const dir = dirOf(wp)
|
|
29
|
+
const file = fileOf(wp, session)
|
|
30
|
+
if (!ended && fs.existsSync(file)) return
|
|
31
|
+
if (!fs.existsSync(dir)) {
|
|
32
|
+
fs.mkdirSync(dir, { recursive: true })
|
|
33
|
+
fs.writeFileSync(path.join(dir, '.gitignore'), "# when each agent session's turn last ended; not for git\n*\n")
|
|
34
|
+
}
|
|
35
|
+
if (ended)
|
|
36
|
+
for (const name of fs.readdirSync(dir))
|
|
37
|
+
if (name !== '.gitignore' && Date.now() - fs.statSync(path.join(dir, name)).mtimeMs > KEEP)
|
|
38
|
+
fs.rmSync(path.join(dir, name), { force: true })
|
|
39
|
+
fs.writeFileSync(`${file}.tmp`, ended ? String(Date.now()) : '')
|
|
40
|
+
fs.renameSync(`${file}.tmp`, file)
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* What is recorded of `session`'s turns: null when nothing is (its turn ends aren't recorded);
|
|
45
|
+
* else when its last turn ended, null when none has since it was marked.
|
|
46
|
+
*/
|
|
47
|
+
export function lastTurnEnd(wp: string, session: string): { ended: number | null } | null {
|
|
48
|
+
let text: string
|
|
49
|
+
try {
|
|
50
|
+
text = fs.readFileSync(fileOf(wp, session), 'utf8')
|
|
51
|
+
} catch {
|
|
52
|
+
return null
|
|
53
|
+
}
|
|
54
|
+
const ended = Number(text)
|
|
55
|
+
return { ended: text && Number.isFinite(ended) ? ended : null }
|
|
56
|
+
}
|