@bigmistqke/workpad 0.0.0-stage → 0.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +781 -2
- package/bin/workpad.ts +1509 -0
- package/dist/_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/taggedTemplateLiteral.js +5 -0
- package/dist/bin/workpad.js +1190 -0
- package/dist/client/runtime.js +1194 -0
- package/dist/define.js +27 -0
- package/dist/plugins/alert/README.md +18 -0
- package/dist/plugins/alert/index.js +40 -0
- package/dist/plugins/alert/public/style.css +40 -0
- package/dist/plugins/ansi/README.md +36 -0
- package/dist/plugins/ansi/index.js +63 -0
- package/dist/plugins/ansi/public/style.css +28 -0
- package/dist/plugins/badge/README.md +32 -0
- package/dist/plugins/badge/index.js +28 -0
- package/dist/plugins/badge/public/style.css +30 -0
- package/dist/plugins/chat/README.md +81 -0
- package/dist/plugins/chat/index.js +96 -0
- package/dist/plugins/chat/public/client.js +3 -0
- package/dist/plugins/chat/public/style.css +143 -0
- package/dist/plugins/claude/README.md +116 -0
- package/dist/plugins/claude/channel.js +130 -0
- package/dist/plugins/claude/doctor.js +316 -0
- package/dist/plugins/claude/index.js +199 -0
- package/dist/plugins/claude/session.js +68 -0
- package/dist/plugins/code/README.md +54 -0
- package/dist/plugins/code/diff.js +75 -0
- package/dist/plugins/code/index.js +105 -0
- package/dist/plugins/code/public/client.js +1 -0
- package/dist/plugins/code/public/style.css +99 -0
- package/dist/plugins/comments/README.md +30 -0
- package/dist/plugins/comments/index.js +39 -0
- package/dist/plugins/comments/public/client.js +24 -0
- package/dist/plugins/comments/public/style.css +224 -0
- package/dist/plugins/details/README.md +24 -0
- package/dist/plugins/details/index.js +28 -0
- package/dist/plugins/details/public/style.css +7 -0
- package/dist/plugins/draft/README.md +14 -0
- package/dist/plugins/draft/index.js +27 -0
- package/dist/plugins/draft/public/style.css +21 -0
- package/dist/plugins/forge/README.md +22 -0
- package/dist/plugins/forge/index.js +83 -0
- package/dist/plugins/form/README.md +126 -0
- package/dist/plugins/form/index.js +179 -0
- package/dist/plugins/form/public/style.css +172 -0
- package/dist/plugins/grid/README.md +45 -0
- package/dist/plugins/grid/index.js +35 -0
- package/dist/plugins/grid/public/style.css +98 -0
- package/dist/plugins/iframe/README.md +18 -0
- package/dist/plugins/iframe/index.js +49 -0
- package/dist/plugins/iframe/public/style.css +28 -0
- package/dist/plugins/index.js +44 -0
- package/dist/plugins/lightbox/README.md +24 -0
- package/dist/plugins/lightbox/index.js +20 -0
- package/dist/plugins/lightbox/public/client.js +4 -0
- package/dist/plugins/lightbox/public/style.css +66 -0
- package/dist/plugins/mermaid/README.md +21 -0
- package/dist/plugins/mermaid/index.js +42 -0
- package/dist/plugins/mermaid/public/style.css +21 -0
- package/dist/plugins/opencode/README.md +48 -0
- package/dist/plugins/opencode/channel.js +92 -0
- package/dist/plugins/opencode/index.js +64 -0
- package/dist/plugins/opencode/shim.js +150 -0
- package/dist/plugins/quiet/README.md +26 -0
- package/dist/plugins/quiet/index.js +23 -0
- package/dist/plugins/tabs/README.md +44 -0
- package/dist/plugins/tabs/index.js +75 -0
- package/dist/plugins/tabs/public/client.js +1 -0
- package/dist/plugins/tabs/public/style.css +98 -0
- package/dist/plugins/terminal/README.md +63 -0
- package/dist/plugins/terminal/host.js +338 -0
- package/dist/plugins/terminal/index.js +170 -0
- package/dist/plugins/terminal/modes.js +32 -0
- package/dist/plugins/terminal/public/client.js +41 -0
- package/dist/plugins/terminal/public/style.css +511 -0
- package/dist/plugins/terminal/server.js +256 -0
- package/dist/plugins/terminal/sizes.js +58 -0
- package/dist/plugins/timeline/README.md +48 -0
- package/dist/plugins/timeline/index.js +83 -0
- package/dist/plugins/timeline/public/style.css +138 -0
- package/dist/plugins/toc/README.md +40 -0
- package/dist/plugins/toc/index.js +29 -0
- package/dist/plugins/toc/public/client.js +1 -0
- package/dist/plugins/toc/public/style.css +117 -0
- package/dist/plugins/window/README.md +51 -0
- package/dist/plugins/window/index.js +91 -0
- package/dist/solid/index.js +41 -0
- package/dist/src/agents.js +81 -0
- package/dist/src/anchors.js +52 -0
- package/dist/src/api.js +282 -0
- package/dist/src/archive.js +49 -0
- package/dist/src/auth.js +67 -0
- package/dist/src/build.js +159 -0
- package/dist/src/client/page/base.css +1762 -0
- package/dist/src/client/page/main.js +2098 -0
- package/dist/src/config.js +76 -0
- package/dist/src/document.js +93 -0
- package/dist/src/entries.js +264 -0
- package/dist/src/events.js +322 -0
- package/dist/src/files.js +47 -0
- package/dist/src/formstate.js +65 -0
- package/dist/src/help.js +211 -0
- package/dist/src/html.js +34 -0
- package/dist/src/hub.js +341 -0
- package/dist/src/icons.js +6 -0
- package/dist/src/listen.js +132 -0
- package/dist/src/listeners.js +64 -0
- package/dist/src/load.js +81 -0
- package/dist/src/loader.js +179 -0
- package/dist/src/migrate.js +314 -0
- package/dist/src/package.js +52 -0
- package/dist/src/pages/blocks.js +67 -0
- package/dist/src/pages/board.js +59 -0
- package/dist/src/pages/index.js +27 -0
- package/dist/src/pages/markdown.js +863 -0
- package/dist/src/pages/render.js +665 -0
- package/dist/src/pages/window.js +29 -0
- package/dist/src/plugins.js +283 -0
- package/dist/src/public.js +24 -0
- package/dist/src/rename.js +130 -0
- package/dist/src/running.js +146 -0
- package/dist/src/serve.js +188 -0
- package/dist/src/server.js +1105 -0
- package/dist/src/site.js +179 -0
- package/dist/src/state.js +155 -0
- package/dist/src/status.js +323 -0
- package/dist/src/thread.js +68 -0
- package/dist/src/watchdog.js +38 -0
- package/dist/src/ws.js +128 -0
- package/package.json +154 -4
- package/plugins/README.md +304 -0
- package/plugins/alert/README.md +18 -0
- package/plugins/alert/index.ts +50 -0
- package/plugins/alert/public/style.css +40 -0
- package/plugins/ansi/README.md +36 -0
- package/plugins/ansi/index.ts +95 -0
- package/plugins/ansi/public/style.css +28 -0
- package/plugins/badge/README.md +32 -0
- package/plugins/badge/index.ts +36 -0
- package/plugins/badge/public/style.css +30 -0
- package/plugins/chat/README.md +81 -0
- package/plugins/chat/autosize.ts +139 -0
- package/plugins/chat/client.tsx +187 -0
- package/plugins/chat/index.ts +146 -0
- package/plugins/chat/public/style.css +143 -0
- package/plugins/claude/README.md +116 -0
- package/plugins/claude/channel.ts +136 -0
- package/plugins/claude/doctor.ts +274 -0
- package/plugins/claude/index.ts +248 -0
- package/plugins/claude/session.ts +70 -0
- package/plugins/code/README.md +54 -0
- package/plugins/code/client.ts +73 -0
- package/plugins/code/diff.ts +96 -0
- package/plugins/code/index.ts +136 -0
- package/plugins/code/public/style.css +99 -0
- package/plugins/comments/README.md +30 -0
- package/plugins/comments/client.ts +723 -0
- package/plugins/comments/index.ts +48 -0
- package/plugins/comments/public/style.css +224 -0
- package/plugins/details/README.md +24 -0
- package/plugins/details/index.ts +30 -0
- package/plugins/details/public/style.css +7 -0
- package/plugins/draft/README.md +14 -0
- package/plugins/draft/index.ts +23 -0
- package/plugins/draft/public/style.css +21 -0
- package/plugins/forge/README.md +22 -0
- package/plugins/forge/index.ts +84 -0
- package/plugins/form/README.md +126 -0
- package/plugins/form/index.ts +199 -0
- package/plugins/form/public/style.css +172 -0
- package/plugins/grid/README.md +45 -0
- package/plugins/grid/index.ts +41 -0
- package/plugins/grid/public/style.css +98 -0
- package/plugins/iframe/README.md +18 -0
- package/plugins/iframe/index.ts +53 -0
- package/plugins/iframe/public/style.css +28 -0
- package/plugins/index.ts +49 -0
- package/plugins/lightbox/README.md +24 -0
- package/plugins/lightbox/client.ts +109 -0
- package/plugins/lightbox/index.ts +25 -0
- package/plugins/lightbox/public/style.css +66 -0
- package/plugins/mermaid/README.md +21 -0
- package/plugins/mermaid/index.ts +46 -0
- package/plugins/mermaid/public/style.css +21 -0
- package/plugins/opencode/README.md +48 -0
- package/plugins/opencode/channel.ts +112 -0
- package/plugins/opencode/index.ts +91 -0
- package/plugins/opencode/shim.ts +166 -0
- package/plugins/quiet/README.md +26 -0
- package/plugins/quiet/index.ts +28 -0
- package/plugins/tabs/README.md +44 -0
- package/plugins/tabs/client.ts +96 -0
- package/plugins/tabs/index.ts +103 -0
- package/plugins/tabs/public/style.css +98 -0
- package/plugins/terminal/README.md +63 -0
- package/plugins/terminal/client.ts +391 -0
- package/plugins/terminal/host.ts +434 -0
- package/plugins/terminal/index.ts +199 -0
- package/plugins/terminal/modes.ts +30 -0
- package/plugins/terminal/public/style.css +225 -0
- package/plugins/terminal/server.ts +266 -0
- package/plugins/terminal/sizes.ts +72 -0
- package/plugins/timeline/README.md +48 -0
- package/plugins/timeline/index.ts +82 -0
- package/plugins/timeline/public/style.css +138 -0
- package/plugins/toc/README.md +40 -0
- package/plugins/toc/client.ts +236 -0
- package/plugins/toc/index.ts +55 -0
- package/plugins/toc/public/style.css +117 -0
- package/plugins/window/README.md +51 -0
- package/plugins/window/index.ts +92 -0
- package/skills/workpad/SKILL.md +588 -0
- package/solid/index.tsx +80 -0
- package/src/agents.ts +133 -0
- package/src/anchors.ts +85 -0
- package/src/api.ts +444 -0
- package/src/archive.ts +75 -0
- package/src/auth.ts +99 -0
- package/src/build.ts +213 -0
- package/src/client/base.ts +19 -0
- package/src/client/forms.ts +420 -0
- package/src/client/markdown.ts +147 -0
- package/src/client/page/base.css +1762 -0
- package/src/client/page/board.ts +137 -0
- package/src/client/page/elsewhere.ts +153 -0
- package/src/client/page/fresh.ts +343 -0
- package/src/client/page/heading-link.ts +32 -0
- package/src/client/page/live.ts +134 -0
- package/src/client/page/main.ts +398 -0
- package/src/client/page/orphans.ts +64 -0
- package/src/client/page/place.ts +260 -0
- package/src/client/page/sort.ts +49 -0
- package/src/client/page/sticky.ts +58 -0
- package/src/client/page/theme.ts +36 -0
- package/src/client/page/view.ts +9 -0
- package/src/client/page/waiting.ts +278 -0
- package/src/client/page/window.ts +40 -0
- package/src/client/reactive.ts +19 -0
- package/src/client/read.ts +111 -0
- package/src/client/runtime.ts +499 -0
- package/src/client/scroll.ts +90 -0
- package/src/client/toast.ts +99 -0
- package/src/config.ts +111 -0
- package/src/define.ts +997 -0
- package/src/document.ts +191 -0
- package/src/entries.ts +352 -0
- package/src/events.ts +463 -0
- package/src/files.ts +74 -0
- package/src/formstate.ts +72 -0
- package/src/help.ts +238 -0
- package/src/html.ts +44 -0
- package/src/hub.ts +426 -0
- package/src/icons.ts +18 -0
- package/src/listen.ts +171 -0
- package/src/listeners.ts +89 -0
- package/src/load.ts +113 -0
- package/src/loader.ts +227 -0
- package/src/migrate.ts +352 -0
- package/src/package.ts +62 -0
- package/src/pages/blocks.ts +106 -0
- package/src/pages/board.ts +89 -0
- package/src/pages/index.ts +79 -0
- package/src/pages/markdown.ts +976 -0
- package/src/pages/render.ts +748 -0
- package/src/pages/window.ts +69 -0
- package/src/plugins.ts +319 -0
- package/src/public.ts +39 -0
- package/src/rename.ts +147 -0
- package/src/running.ts +171 -0
- package/src/serve.ts +221 -0
- package/src/server.ts +1385 -0
- package/src/site.ts +170 -0
- package/src/state.ts +327 -0
- package/src/status.ts +466 -0
- package/src/thread.ts +98 -0
- package/src/watchdog.ts +53 -0
- package/src/ws.ts +155 -0
|
@@ -0,0 +1,1190 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { configFileIn, findProjectDir, pageId, project as project$1 } from "../src/config.js";
|
|
3
|
+
import { appendEvent, editEvent, follow, forAgent, handOut, handle, matches, prune, read, readEvents, rewrite } from "../src/events.js";
|
|
4
|
+
import { BUILTIN_COMMANDS, createConfigLoader, pluginDir } from "../src/loader.js";
|
|
5
|
+
import { asksHelp, parseCommandArgs, pluginCommandHelp, pluginCommands, usage } from "../src/plugins.js";
|
|
6
|
+
import { commandHelp, commandList } from "../src/help.js";
|
|
7
|
+
import { archiveFile, archived } from "../src/archive.js";
|
|
8
|
+
import { thread } from "../src/thread.js";
|
|
9
|
+
import { markdownFiles, migrate } from "../src/migrate.js";
|
|
10
|
+
import { OLD, machineSteps, oldProjectDir, projectSteps } from "../src/rename.js";
|
|
11
|
+
import { anchorsOf, hashOf } from "../src/anchors.js";
|
|
12
|
+
import { projectToken } from "../src/auth.js";
|
|
13
|
+
import { PACKAGE_DIR, VERSION, compareVersions, packagePath } from "../src/package.js";
|
|
14
|
+
import { alive, isShared, projectServer, recordedOrigin, recordedPid, sharedServer, stuck, stuckAt } from "../src/running.js";
|
|
15
|
+
import { machineDir, machineServerFile, matchesEntries, readMachineConfig, serverPaths, stateDir } from "../src/entries.js";
|
|
16
|
+
import { NAME, SUBSCRIBE, UNSUBSCRIBE, channelSince, fromReader, handledIds, namesOf, receivedIds, statusLines, subscriptions, whose } from "../src/status.js";
|
|
17
|
+
import { holdForms, releaseForms, settleForms } from "../src/formstate.js";
|
|
18
|
+
import { client, probe } from "../src/api.js";
|
|
19
|
+
import { everyProject, holdChannel, listen } from "../src/listen.js";
|
|
20
|
+
import fs from "node:fs";
|
|
21
|
+
import path from "node:path";
|
|
22
|
+
import os from "node:os";
|
|
23
|
+
import { spawn } from "node:child_process";
|
|
24
|
+
import http from "node:http";
|
|
25
|
+
import { parseArgs } from "node:util";
|
|
26
|
+
import { fileURLToPath } from "node:url";
|
|
27
|
+
// bin/workpad.ts
|
|
28
|
+
const fail = (err) => {
|
|
29
|
+
console.error(`workpad: ${err?.message ?? err}`);
|
|
30
|
+
process.exit(1);
|
|
31
|
+
};
|
|
32
|
+
process.on("uncaughtException", fail);
|
|
33
|
+
process.on("unhandledRejection", fail);
|
|
34
|
+
const HELP = `workpad — markdown pages in the browser, what the reader does on them as events in an ndjson log
|
|
35
|
+
|
|
36
|
+
${commandList()}
|
|
37
|
+
|
|
38
|
+
\`workpad <command> --help\` says what a command takes and does, and does nothing else.
|
|
39
|
+
\`workpad --version\` prints the version of workpad that runs.
|
|
40
|
+
|
|
41
|
+
Every command works on the project of the current folder: the nearest folder upward with a
|
|
42
|
+
.workpad/ folder. A project needs no config: .workpad/config.ts only says what differs from
|
|
43
|
+
the defaults (markdown with the built-in plugins). Each project runs its own server; its port is in .workpad/server.json.
|
|
44
|
+
A project the machine config's entries include (${machineDir()}/config.json) is served by the one shared
|
|
45
|
+
server instead, under its path (/<entry>/<folder>), with an index of every entry at /. It is started
|
|
46
|
+
outside the agents' sandboxes (\`workpad serve\` outside any project, or a login service), and
|
|
47
|
+
\`serve\` takes an older one over; commands never start it. A wait without a server waits for one.
|
|
48
|
+
A page appends events {id, ts, page, type, action, data} to .workpad/events.ndjson;
|
|
49
|
+
which types it sends is up to its plugins (\`workpad docs\` says). The project's plugins
|
|
50
|
+
can add commands of their own; \`workpad help\` in a project lists them.`;
|
|
51
|
+
const [first, ...rest] = process.argv.slice(2);
|
|
52
|
+
if (first === "--version" || first === "-v") {
|
|
53
|
+
console.log(VERSION);
|
|
54
|
+
process.exit(0);
|
|
55
|
+
}
|
|
56
|
+
const cmd = first === "--help" || first === "-h" ? "help" : first;
|
|
57
|
+
const { values: opts, positionals } = cmd && !BUILTIN_COMMANDS.has(cmd) ? {
|
|
58
|
+
values: {},
|
|
59
|
+
positionals: []
|
|
60
|
+
} : parseArgs({
|
|
61
|
+
args: rest,
|
|
62
|
+
allowPositionals: true,
|
|
63
|
+
options: {
|
|
64
|
+
page: {
|
|
65
|
+
type: "string",
|
|
66
|
+
multiple: true
|
|
67
|
+
},
|
|
68
|
+
type: { type: "string" },
|
|
69
|
+
data: { type: "string" },
|
|
70
|
+
timeout: { type: "string" },
|
|
71
|
+
since: { type: "string" },
|
|
72
|
+
last: { type: "string" },
|
|
73
|
+
follow: { type: "boolean" },
|
|
74
|
+
id: { type: "string" },
|
|
75
|
+
out: { type: "string" },
|
|
76
|
+
skip: { type: "string" },
|
|
77
|
+
help: {
|
|
78
|
+
type: "boolean",
|
|
79
|
+
short: "h"
|
|
80
|
+
},
|
|
81
|
+
write: { type: "boolean" },
|
|
82
|
+
read: { type: "boolean" },
|
|
83
|
+
full: { type: "boolean" },
|
|
84
|
+
agent: { type: "string" },
|
|
85
|
+
clear: { type: "boolean" },
|
|
86
|
+
wait: { type: "boolean" },
|
|
87
|
+
channel: { type: "boolean" },
|
|
88
|
+
all: { type: "boolean" }
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
if (cmd && cmd !== "help" && BUILTIN_COMMANDS.has(cmd) && opts.help) {
|
|
92
|
+
console.log(commandHelp(cmd));
|
|
93
|
+
process.exit(0);
|
|
94
|
+
}
|
|
95
|
+
const project = project$1(findProjectDir());
|
|
96
|
+
/** Every --page given; only listen takes more than one. */
|
|
97
|
+
const pagesGiven = opts.page ?? [];
|
|
98
|
+
if (pagesGiven.length > 1 && cmd !== "listen") {
|
|
99
|
+
console.error(`workpad: ${cmd} takes --page once; only listen takes several`);
|
|
100
|
+
process.exit(1);
|
|
101
|
+
}
|
|
102
|
+
/** The one --page of a command that takes one. */
|
|
103
|
+
const pageOpt = pagesGiven[0];
|
|
104
|
+
/** The current project, or exit with how to make one. */
|
|
105
|
+
function needProject() {
|
|
106
|
+
if (project) return project;
|
|
107
|
+
console.error(`workpad: not inside a project (no .workpad/ folder in ${process.cwd()} or above it).
|
|
108
|
+
Run \`workpad init\` in the folder that should become one.`);
|
|
109
|
+
process.exit(1);
|
|
110
|
+
}
|
|
111
|
+
const filter = () => ({
|
|
112
|
+
page: pageOpt ? pageId(needProject(), pageOpt) : void 0,
|
|
113
|
+
type: opts.type
|
|
114
|
+
});
|
|
115
|
+
/** The running server of this project: the URL it is served at, or null (see projectServer). */
|
|
116
|
+
const running = (proj) => projectServer(proj);
|
|
117
|
+
/**
|
|
118
|
+
* This project's server, started in the background when it is not running. Under the shared server
|
|
119
|
+
* nothing is started: it is started outside every agent's sandbox (a login service, or `workpad
|
|
120
|
+
* serve` in a terminal), since it serves every project of the entries and runs their plugins; a
|
|
121
|
+
* command inside one sandbox would start it boxed in there. Only `show` and a plugin's command that
|
|
122
|
+
* asks for the server get here. @returns the URL it serves the project at
|
|
123
|
+
*/
|
|
124
|
+
async function ensureServer() {
|
|
125
|
+
const proj = needProject();
|
|
126
|
+
const shared = isShared(proj);
|
|
127
|
+
const base = await running(proj);
|
|
128
|
+
if (shared) {
|
|
129
|
+
const server = await sharedServer(machineServerFile());
|
|
130
|
+
if (base) {
|
|
131
|
+
if (server && compareVersions(VERSION, server.version) > 0) console.error(`workpad: the shared server runs ${server.version}, this is ${VERSION}; restart it to upgrade (\`workpad serve\` takes it over)`);
|
|
132
|
+
return base;
|
|
133
|
+
}
|
|
134
|
+
const at = recordedOrigin(machineServerFile());
|
|
135
|
+
if (!server && at && await stuckAt(at)) throw new Error(stuck(at, "its login service log"));
|
|
136
|
+
throw new Error(server ? `the shared server at ${server.origin} does not serve ${proj.dir}; is it in an include of ${machineDir()}/config.json?` : `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`);
|
|
137
|
+
}
|
|
138
|
+
if (base) return base;
|
|
139
|
+
const recorded = recordedPid(proj);
|
|
140
|
+
if (recorded && recorded !== process.pid && alive(recorded)) {
|
|
141
|
+
for (let i = 0; i < 75; i++) {
|
|
142
|
+
await new Promise((r) => setTimeout(r, 200));
|
|
143
|
+
const base = await running(proj);
|
|
144
|
+
if (base) return base;
|
|
145
|
+
if (!alive(recorded)) break;
|
|
146
|
+
}
|
|
147
|
+
if (alive(recorded)) throw new Error(`the server (pid ${recorded}) runs but doesn't answer; see ${proj.logFile}`);
|
|
148
|
+
}
|
|
149
|
+
const lock = path.join(proj.wp, "server.lock");
|
|
150
|
+
const claim = () => {
|
|
151
|
+
try {
|
|
152
|
+
fs.writeFileSync(lock, String(process.pid), { flag: "wx" });
|
|
153
|
+
return true;
|
|
154
|
+
} catch (err) {
|
|
155
|
+
if (err.code !== "EEXIST") throw err;
|
|
156
|
+
return false;
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
let mine = claim();
|
|
160
|
+
if (!mine) {
|
|
161
|
+
let stale = false;
|
|
162
|
+
try {
|
|
163
|
+
const owner = Number(fs.readFileSync(lock, "utf8"));
|
|
164
|
+
try {
|
|
165
|
+
process.kill(owner, 0);
|
|
166
|
+
} catch (err) {
|
|
167
|
+
stale = err.code === "ESRCH";
|
|
168
|
+
}
|
|
169
|
+
} catch {}
|
|
170
|
+
if (stale) {
|
|
171
|
+
try {
|
|
172
|
+
fs.unlinkSync(lock);
|
|
173
|
+
} catch {}
|
|
174
|
+
mine = claim();
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
if (mine) {
|
|
178
|
+
const log = fs.openSync(proj.logFile, "a");
|
|
179
|
+
spawn(process.execPath, [fileURLToPath(import.meta.url), "serve"], {
|
|
180
|
+
cwd: proj.dir,
|
|
181
|
+
detached: true,
|
|
182
|
+
stdio: [
|
|
183
|
+
"ignore",
|
|
184
|
+
log,
|
|
185
|
+
log
|
|
186
|
+
],
|
|
187
|
+
env: process.env
|
|
188
|
+
}).unref();
|
|
189
|
+
}
|
|
190
|
+
for (let i = 0; i < 75; i++) {
|
|
191
|
+
await new Promise((r) => setTimeout(r, 200));
|
|
192
|
+
const base = await running(proj);
|
|
193
|
+
if (base) return base;
|
|
194
|
+
}
|
|
195
|
+
throw new Error(`server did not start; see ${proj.logFile}`);
|
|
196
|
+
}
|
|
197
|
+
/** This project's running server, or an error saying how to start one. */
|
|
198
|
+
async function needServer() {
|
|
199
|
+
const proj = needProject();
|
|
200
|
+
const base = await running(proj);
|
|
201
|
+
if (base) return base;
|
|
202
|
+
if (isShared(proj)) {
|
|
203
|
+
const at = recordedOrigin(machineServerFile());
|
|
204
|
+
throw new Error(at ? `the shared server recorded at ${at} did not answer, or does not serve ${proj.dir}` : "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");
|
|
205
|
+
}
|
|
206
|
+
throw new Error("no server runs for this project; `workpad show <page>` starts it");
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* The project and page a target names: a page of this project, or a page's file in another project
|
|
210
|
+
* (a link to another board).
|
|
211
|
+
*/
|
|
212
|
+
function pageIn(target) {
|
|
213
|
+
const abs = path.resolve(target);
|
|
214
|
+
const proj = (/\.md$/.test(target) && fs.existsSync(abs) ? project$1(findProjectDir(path.dirname(abs))) : null) ?? needProject();
|
|
215
|
+
return {
|
|
216
|
+
proj,
|
|
217
|
+
id: pageId(proj, target)
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
/** Where a project is served: its running server, or an error saying how to start one. */
|
|
221
|
+
async function serverOf(proj) {
|
|
222
|
+
if (proj.dir === project?.dir) return needServer();
|
|
223
|
+
const base = await running(proj);
|
|
224
|
+
if (!base) throw new Error(`no server serves ${proj.dir}; \`workpad show\` there starts it`);
|
|
225
|
+
return base;
|
|
226
|
+
}
|
|
227
|
+
/** The anchors of a page as its server renders it (src/anchors.ts). */
|
|
228
|
+
async function anchorsAt(base, id) {
|
|
229
|
+
const res = await fetch(`${base}/api/render?page=${encodeURIComponent(id)}`);
|
|
230
|
+
if (!res.ok) throw new Error(`no page ${id} at ${base}`);
|
|
231
|
+
return anchorsOf((await res.json()).html ?? "");
|
|
232
|
+
}
|
|
233
|
+
/** Is `anchor` on the page (a chat message by its event)? Else exit 1, saying what is. */
|
|
234
|
+
async function checkAnchor(proj, base, id, anchor) {
|
|
235
|
+
const message = /^message:(.+)$/.exec(anchor)?.[1];
|
|
236
|
+
if (message) {
|
|
237
|
+
if (readEvents(proj.eventsFile).some((e) => e.id === message && e.page === id)) return;
|
|
238
|
+
console.error(`workpad: no chat message ${message} on ${id}`);
|
|
239
|
+
process.exit(1);
|
|
240
|
+
}
|
|
241
|
+
const anchors = await anchorsAt(base, id);
|
|
242
|
+
if (anchors.some((a) => a.id === anchor)) return;
|
|
243
|
+
console.error(`workpad: no anchor ${hashOf(anchor)} on ${id}${anchors.length ? `; there are:\n${anchors.map((a) => ` ${hashOf(a.id)}`).join("\n")}` : ""}`);
|
|
244
|
+
process.exit(1);
|
|
245
|
+
}
|
|
246
|
+
/** Is there a page (a markdown file) in this folder or below it? */
|
|
247
|
+
function hasPages(dir) {
|
|
248
|
+
let entries;
|
|
249
|
+
try {
|
|
250
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
251
|
+
} catch {
|
|
252
|
+
return false;
|
|
253
|
+
}
|
|
254
|
+
return entries.some((e) => e.isDirectory() ? !e.name.startsWith(".") && hasPages(path.join(dir, e.name)) : e.name.endsWith(".md"));
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Ask the project's server. Without one running, a server made for this one question answers it,
|
|
258
|
+
* in this process, on no port: a command that only asks (status, docs, the hooks on every prompt)
|
|
259
|
+
* never starts one. It has no listeners, as no server runs to hold them.
|
|
260
|
+
*/
|
|
261
|
+
async function api(route) {
|
|
262
|
+
const base = await running(needProject());
|
|
263
|
+
const res = base ? await fetch(`${base}${route}`) : await askInProcess(route);
|
|
264
|
+
const body = await res.json();
|
|
265
|
+
if (!res.ok) throw new Error(body.error ?? res.statusText);
|
|
266
|
+
return body;
|
|
267
|
+
}
|
|
268
|
+
async function askInProcess(route) {
|
|
269
|
+
if (route.startsWith("/api/status") && !hasPages(needProject().pagesDir)) return Response.json([]);
|
|
270
|
+
const { createServer } = await import("../src/server.js");
|
|
271
|
+
const server = createServer(needProject());
|
|
272
|
+
const listener = http.createServer((req, res) => void server.handle(req, res));
|
|
273
|
+
await new Promise((r) => listener.listen(0, "127.0.0.1", r));
|
|
274
|
+
try {
|
|
275
|
+
const { port } = listener.address();
|
|
276
|
+
const res = await fetch(`http://127.0.0.1:${port}${route}`);
|
|
277
|
+
const text = await res.text();
|
|
278
|
+
return new Response(text, {
|
|
279
|
+
status: res.status,
|
|
280
|
+
headers: res.headers
|
|
281
|
+
});
|
|
282
|
+
} finally {
|
|
283
|
+
server.close();
|
|
284
|
+
listener.closeAllConnections();
|
|
285
|
+
listener.close();
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
function init(name) {
|
|
289
|
+
const dir = process.cwd();
|
|
290
|
+
const wp = path.join(dir, ".workpad");
|
|
291
|
+
if (fs.existsSync(wp)) {
|
|
292
|
+
console.log(`already a project: ${wp}`);
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
const home = dir === os.homedir();
|
|
296
|
+
const named = name && name !== path.basename(dir);
|
|
297
|
+
fs.mkdirSync(path.join(wp, "pages"), { recursive: true });
|
|
298
|
+
if (named || home) fs.writeFileSync(path.join(wp, "config.ts"), `import { defineConfig } from '@bigmistqke/workpad'
|
|
299
|
+
|
|
300
|
+
export default defineConfig({
|
|
301
|
+
${named ? ` name: '${name}',\n` : ""}${home ? " // only .workpad/ is served: this folder is not a repository\n files: false,\n" : ""}})
|
|
302
|
+
`);
|
|
303
|
+
fs.writeFileSync(path.join(wp, ".gitignore"), `# pages are working documents; remove this line to keep them in git
|
|
304
|
+
pages/
|
|
305
|
+
# events from the pages (and which ones an agent received), and the running server's port and output
|
|
306
|
+
events.ndjson
|
|
307
|
+
server.json
|
|
308
|
+
server.log
|
|
309
|
+
server.lock
|
|
310
|
+
# the secret for anything that runs code (a plugin like the terminal)
|
|
311
|
+
token
|
|
312
|
+
`);
|
|
313
|
+
console.log(`project: ${wp}
|
|
314
|
+
pages: ${path.join(wp, "pages")} (gitignored); \`workpad show <page>\` starts the server
|
|
315
|
+
config: ${configFileIn(wp) ?? `none: the defaults (markdown with the built-in plugins); add ${path.join(wp, "config.ts")} to change them`}`);
|
|
316
|
+
}
|
|
317
|
+
const relFile = (file) => path.relative(process.cwd(), file) || file;
|
|
318
|
+
/**
|
|
319
|
+
* The project's config, as the command line needs it: for its plugins (their commands, the
|
|
320
|
+
* session, which events reach an agent), so without the pages. Loaded once per command.
|
|
321
|
+
*/
|
|
322
|
+
const loaded = /* @__PURE__ */ new Map();
|
|
323
|
+
const projectConfig = (proj) => {
|
|
324
|
+
if (!loaded.has(proj.dir)) loaded.set(proj.dir, createConfigLoader(proj, { pages: false }).config());
|
|
325
|
+
return loaded.get(proj.dir);
|
|
326
|
+
};
|
|
327
|
+
/**
|
|
328
|
+
* What the config is made of, as modification times: the config file and the local plugins in
|
|
329
|
+
* `.workpad/plugins/`. A different stamp means a command that runs for long (the channel) has an
|
|
330
|
+
* old config.
|
|
331
|
+
*/
|
|
332
|
+
function configStamp(proj) {
|
|
333
|
+
const dir = path.join(proj.wp, "plugins");
|
|
334
|
+
let local = [];
|
|
335
|
+
try {
|
|
336
|
+
local = fs.readdirSync(dir, { recursive: true }).filter((f) => /\.(ts|js|mjs|mts)$/.test(f)).map((f) => path.join(dir, f));
|
|
337
|
+
} catch {}
|
|
338
|
+
return [proj.configFile, ...local].filter((f) => !!f).map((f) => {
|
|
339
|
+
try {
|
|
340
|
+
return `${f}@${fs.statSync(f).mtimeMs}`;
|
|
341
|
+
} catch {
|
|
342
|
+
return "";
|
|
343
|
+
}
|
|
344
|
+
}).join("|");
|
|
345
|
+
}
|
|
346
|
+
/**
|
|
347
|
+
* Which event types reach an agent, kept up to date for as long as `signal` doesn't abort: a hand-out
|
|
348
|
+
* that runs for long (the channel, a `listen` without --wait) hears of a plugin added to the config
|
|
349
|
+
* after it started, rather than leaving that plugin's events for nobody.
|
|
350
|
+
*/
|
|
351
|
+
async function liveForAgent(proj, signal) {
|
|
352
|
+
let handed = (await projectConfig(proj)).handedOut;
|
|
353
|
+
let stamp = configStamp(proj);
|
|
354
|
+
const timer = setInterval(() => {
|
|
355
|
+
const now = configStamp(proj);
|
|
356
|
+
if (now === stamp) return;
|
|
357
|
+
stamp = now;
|
|
358
|
+
loaded.set(proj.dir, createConfigLoader(proj, { pages: false }).config());
|
|
359
|
+
projectConfig(proj).then((c) => {
|
|
360
|
+
if (!c.errors.length) handed = c.handedOut;
|
|
361
|
+
});
|
|
362
|
+
}, 2e3);
|
|
363
|
+
timer.unref();
|
|
364
|
+
signal?.addEventListener("abort", () => clearInterval(timer));
|
|
365
|
+
return (type) => forAgent(handed)(type);
|
|
366
|
+
}
|
|
367
|
+
/**
|
|
368
|
+
* Who runs this command: `--agent`, else `WORKPAD_AGENT`, else the agent session a plugin names; null
|
|
369
|
+
* when none says (a bare process). Any harness, a shell or a script can name itself with the first
|
|
370
|
+
* two: a plugin only fills it in for the agent programs it knows.
|
|
371
|
+
*/
|
|
372
|
+
/** Subscribe `agent` to `page`, unless it is already (or nobody says who it is). */
|
|
373
|
+
function subscribe(proj, page, agent, data) {
|
|
374
|
+
if (!agent) return;
|
|
375
|
+
if (!subscriptions(readEvents(proj.eventsFile)).some((e) => e.page === page && e.by === agent)) appendEvent(proj.eventsFile, {
|
|
376
|
+
page,
|
|
377
|
+
type: SUBSCRIBE,
|
|
378
|
+
...data ? { data } : {}
|
|
379
|
+
}, "cli", agent);
|
|
380
|
+
}
|
|
381
|
+
async function whoAmI(proj) {
|
|
382
|
+
return opts.agent || process.env.WORKPAD_AGENT || await currentSession(proj);
|
|
383
|
+
}
|
|
384
|
+
/**
|
|
385
|
+
* The agent session this command runs in, as the project's plugins know it (Claude Code's
|
|
386
|
+
* plugin reads it from the environment): the first one that names one. Null without any.
|
|
387
|
+
*/
|
|
388
|
+
async function currentSession(proj) {
|
|
389
|
+
try {
|
|
390
|
+
for (const e of (await projectConfig(proj)).plugins) {
|
|
391
|
+
const session = typeof e.session === "function" ? await e.session() : null;
|
|
392
|
+
if (session) return String(session);
|
|
393
|
+
}
|
|
394
|
+
} catch (err) {
|
|
395
|
+
console.error(`workpad: which session runs this: ${err.message}`);
|
|
396
|
+
}
|
|
397
|
+
return null;
|
|
398
|
+
}
|
|
399
|
+
/** The status of one page, as the server says it; an error when there is no such page. */
|
|
400
|
+
async function pageStatus(proj, target) {
|
|
401
|
+
const id = pageId(proj, target);
|
|
402
|
+
const p = (await api(`/api/status?page=${encodeURIComponent(id)}`)).find((s) => s.page === id);
|
|
403
|
+
if (!p) throw new Error(`no page ${id}`);
|
|
404
|
+
return p;
|
|
405
|
+
}
|
|
406
|
+
async function status() {
|
|
407
|
+
const proj = needProject();
|
|
408
|
+
const [pages, me] = await Promise.all([api(`/api/status${pageOpt ? `?page=${encodeURIComponent(pageId(proj, pageOpt))}` : ""}`), whoAmI(proj)]);
|
|
409
|
+
const names = namesOf(readEvents(proj.eventsFile));
|
|
410
|
+
const busy = pages.filter((p) => p.unreceived.length || p.open.length);
|
|
411
|
+
if (!busy.length) {
|
|
412
|
+
console.log("nothing open: every question is answered, and every answer received");
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
415
|
+
for (const p of busy) {
|
|
416
|
+
console.log(`${p.page} (${whose(p, me, names)})`);
|
|
417
|
+
for (const l of statusLines(p, relFile(p.file))) console.log(` ${l}`);
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
switch (cmd) {
|
|
421
|
+
case "serve": {
|
|
422
|
+
if (!project && readMachineConfig()) {
|
|
423
|
+
const { startShared } = await import("../src/serve.js");
|
|
424
|
+
await startShared();
|
|
425
|
+
break;
|
|
426
|
+
}
|
|
427
|
+
const proj = needProject();
|
|
428
|
+
if (isShared(proj)) {
|
|
429
|
+
const { startShared } = await import("../src/serve.js");
|
|
430
|
+
await startShared();
|
|
431
|
+
break;
|
|
432
|
+
}
|
|
433
|
+
const base = await running(proj);
|
|
434
|
+
if (base) {
|
|
435
|
+
console.error(`workpad: ${proj.name} is already served at ${base}`);
|
|
436
|
+
process.exit(1);
|
|
437
|
+
}
|
|
438
|
+
const { start } = await import("../src/serve.js");
|
|
439
|
+
await start(proj);
|
|
440
|
+
break;
|
|
441
|
+
}
|
|
442
|
+
case "build": {
|
|
443
|
+
const proj = needProject();
|
|
444
|
+
const { createServer } = await import("../src/server.js");
|
|
445
|
+
const server = createServer(proj);
|
|
446
|
+
try {
|
|
447
|
+
const result = await server.build({
|
|
448
|
+
pages: positionals.length ? positionals : void 0,
|
|
449
|
+
out: opts.out,
|
|
450
|
+
skip: opts.skip != null ? opts.skip.split(",").map((s) => s.trim()).filter(Boolean) : void 0
|
|
451
|
+
});
|
|
452
|
+
for (const w of result.warnings) console.error(`workpad build: ${w}`);
|
|
453
|
+
console.log(`built ${result.pages.length} page${result.pages.length === 1 ? "" : "s"} into ${path.relative(process.cwd(), result.out) || "."}`);
|
|
454
|
+
} finally {
|
|
455
|
+
server.close();
|
|
456
|
+
}
|
|
457
|
+
process.exit(0);
|
|
458
|
+
}
|
|
459
|
+
case "init":
|
|
460
|
+
init(positionals[0]);
|
|
461
|
+
break;
|
|
462
|
+
case "root": {
|
|
463
|
+
const dir = needProject().pagesDir;
|
|
464
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
465
|
+
console.log(dir);
|
|
466
|
+
break;
|
|
467
|
+
}
|
|
468
|
+
case "new": {
|
|
469
|
+
const name = (positionals[0] ?? "").replace(/\\/g, "/").replace(/\.md$/, "").replace(/^\/+|\/+$/g, "");
|
|
470
|
+
if (!name || name.split("/").some((part) => !part || part === "." || part === ".." || part === "-" || part === "_")) throw new Error("usage: workpad new <name> (a page name like plan or task/plan)");
|
|
471
|
+
const proj = needProject();
|
|
472
|
+
const answered = new Set(readEvents(proj.eventsFile).map((e) => e.page));
|
|
473
|
+
for (let n = 1;; n++) {
|
|
474
|
+
const id = n === 1 ? name : `${name}-${n}`;
|
|
475
|
+
if (answered.has(id)) continue;
|
|
476
|
+
const file = path.join(proj.pagesDir, `${id}.md`);
|
|
477
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
478
|
+
try {
|
|
479
|
+
fs.writeFileSync(file, "", { flag: "wx" });
|
|
480
|
+
subscribe(proj, id, await whoAmI(proj));
|
|
481
|
+
console.log(file);
|
|
482
|
+
break;
|
|
483
|
+
} catch (err) {
|
|
484
|
+
if (err.code !== "EEXIST") throw err;
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
break;
|
|
488
|
+
}
|
|
489
|
+
case "agent": {
|
|
490
|
+
const proj = needProject();
|
|
491
|
+
const [sub, arg] = positionals;
|
|
492
|
+
const me = await whoAmI(proj);
|
|
493
|
+
const nobody = () => /* @__PURE__ */ new Error("nobody here: say who with --agent or WORKPAD_AGENT (or a plugin of the config names the session: claude(), opencode())");
|
|
494
|
+
if (!sub) {
|
|
495
|
+
if (!me) throw nobody();
|
|
496
|
+
const name = namesOf(readEvents(proj.eventsFile)).get(me);
|
|
497
|
+
console.log(name ? `${name} (${me})` : `${me} (no name: workpad agent name <name>)`);
|
|
498
|
+
break;
|
|
499
|
+
}
|
|
500
|
+
if (sub === "name") {
|
|
501
|
+
if (!me) throw nobody();
|
|
502
|
+
if (!arg && !opts.clear) throw new Error("usage: workpad agent name <name> | --clear");
|
|
503
|
+
rewrite(proj.eventsFile, (e) => e.type === "workpad:name" && e.by === me ? null : e);
|
|
504
|
+
if (opts.clear) console.log(`${me} has no name now`);
|
|
505
|
+
else {
|
|
506
|
+
appendEvent(proj.eventsFile, {
|
|
507
|
+
page: "",
|
|
508
|
+
type: NAME,
|
|
509
|
+
data: { name: arg }
|
|
510
|
+
}, "cli", me);
|
|
511
|
+
console.log(`${me} is ${arg} now`);
|
|
512
|
+
}
|
|
513
|
+
break;
|
|
514
|
+
}
|
|
515
|
+
if (sub === "list") {
|
|
516
|
+
const events = readEvents(proj.eventsFile);
|
|
517
|
+
const names = namesOf(events);
|
|
518
|
+
const subscribed = /* @__PURE__ */ new Map();
|
|
519
|
+
const seen = /* @__PURE__ */ new Set();
|
|
520
|
+
for (const e of events) if (e.by) seen.add(e.by);
|
|
521
|
+
for (const e of subscriptions(events)) subscribed.set(e.by, [...subscribed.get(e.by) ?? [], e.page || "every page"]);
|
|
522
|
+
const listening = /* @__PURE__ */ new Map();
|
|
523
|
+
const base = await running(proj);
|
|
524
|
+
if (base) {
|
|
525
|
+
for (const l of await (await fetch(`${base}/api/listeners`)).json()) if (l.agent) {
|
|
526
|
+
seen.add(l.agent);
|
|
527
|
+
listening.set(l.agent, [...listening.get(l.agent) ?? [], l.page || "every page"]);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
if (!seen.size) {
|
|
531
|
+
console.log("no agents on this board yet");
|
|
532
|
+
break;
|
|
533
|
+
}
|
|
534
|
+
for (const id of seen) {
|
|
535
|
+
const who = `${names.get(id) ?? id}${names.has(id) ? ` (${id})` : ""}${id === me ? " · you" : ""}`;
|
|
536
|
+
console.log(who);
|
|
537
|
+
if (subscribed.has(id)) console.log(` subscribed: ${[...new Set(subscribed.get(id))].join(", ")}`);
|
|
538
|
+
if (listening.has(id)) console.log(` listening: ${[...new Set(listening.get(id))].join(", ")}`);
|
|
539
|
+
else if (subscribed.has(id) && base) console.log(` not listening now (gone? \`workpad agent unsubscribe ${id}\` takes it off its pages)`);
|
|
540
|
+
}
|
|
541
|
+
break;
|
|
542
|
+
}
|
|
543
|
+
if (sub === "unsubscribe") {
|
|
544
|
+
if (!arg) throw new Error("usage: workpad agent unsubscribe <agent> [--page <page>…]");
|
|
545
|
+
const events = readEvents(proj.eventsFile);
|
|
546
|
+
const byName = [...namesOf(events)].find(([, name]) => name === arg)?.[0];
|
|
547
|
+
const agent = subscriptions(events).some((e) => e.by === arg) ? arg : byName ?? arg;
|
|
548
|
+
const mine = subscriptions(events).filter((e) => e.by === agent);
|
|
549
|
+
if (!mine.length) throw new Error(`${arg} is subscribed to no page here`);
|
|
550
|
+
const pages = [...new Set(pagesGiven.map((p) => pageId(proj, p)))];
|
|
551
|
+
for (const page of pages) if (!mine.some((e) => e.page === page)) throw new Error(`${arg} isn't subscribed to ${page}: its pages are ${mine.map((e) => e.page || "every page").join(", ")}`);
|
|
552
|
+
if (pages.length) for (const page of pages) appendEvent(proj.eventsFile, {
|
|
553
|
+
page: "",
|
|
554
|
+
type: UNSUBSCRIBE,
|
|
555
|
+
data: {
|
|
556
|
+
agent,
|
|
557
|
+
page
|
|
558
|
+
}
|
|
559
|
+
}, "cli", me);
|
|
560
|
+
else appendEvent(proj.eventsFile, {
|
|
561
|
+
page: "",
|
|
562
|
+
type: UNSUBSCRIBE,
|
|
563
|
+
data: { agent }
|
|
564
|
+
}, "cli", me);
|
|
565
|
+
const off = pages.length ? pages : [...new Set(mine.map((e) => e.page || "every page"))];
|
|
566
|
+
console.log(`${arg} is off ${off.length === 1 ? off[0] : `${off.length} pages: ${off.join(", ")}`}`);
|
|
567
|
+
break;
|
|
568
|
+
}
|
|
569
|
+
if (sub === "ping") {
|
|
570
|
+
const code = arg;
|
|
571
|
+
if (!code && !me) throw nobody();
|
|
572
|
+
const base = await ensureServer();
|
|
573
|
+
const res = await fetch(`${base}/api/ping`, {
|
|
574
|
+
method: "POST",
|
|
575
|
+
headers: { "content-type": "application/json" },
|
|
576
|
+
body: JSON.stringify(code ? { code } : { session: me })
|
|
577
|
+
});
|
|
578
|
+
const body = await res.json();
|
|
579
|
+
if (!res.ok) throw new Error(`${body.error ?? res.statusText}: \`workpad agent ping\` sends a new one`);
|
|
580
|
+
const covers = async () => {
|
|
581
|
+
if (!me) return "";
|
|
582
|
+
const pages = await api("/api/status");
|
|
583
|
+
const mine = pages.filter((p) => p.subscribers.includes(me)).map((p) => p.page);
|
|
584
|
+
const others = pages.filter((p) => !p.subscribers.includes(me) && (p.open.length || p.unreceived.length)).map((p) => p.page);
|
|
585
|
+
return [` The channel follows ${mine.length} page${mine.length === 1 ? "" : "s"}, those you made or listened on${mine.length ? `: ${mine.join(", ")}` : ""}.`, others.length ? ` Not yours, with questions waiting: ${others.join(", ")}. \`workpad listen --channel --page <page>\` takes one on; \`workpad listen --channel\` every page, also those made later.` : ""].join("");
|
|
586
|
+
};
|
|
587
|
+
if (code) console.log(`confirmed: answers on your pages come to you now, as the pong did.${await covers()}`);
|
|
588
|
+
else if (body.confirmed) console.log(`answers on your pages come to you already, through this session’s channel.${await covers()}`);
|
|
589
|
+
else if (body.sent) console.log("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; if none has come by your next turn, nothing brings answers here: listen for them then");
|
|
590
|
+
else {
|
|
591
|
+
console.log("nothing brings answers to this session: listen for them (`workpad listen --wait --page <file>` in the background)");
|
|
592
|
+
process.exit(1);
|
|
593
|
+
}
|
|
594
|
+
break;
|
|
595
|
+
}
|
|
596
|
+
throw new Error("usage: workpad agent [name <name> | name --clear | list | unsubscribe <agent> [--page <p>…] | ping [<code>]]");
|
|
597
|
+
}
|
|
598
|
+
case "show": {
|
|
599
|
+
if (!positionals[0]) throw new Error("usage: workpad show <page|file> [<anchor>]");
|
|
600
|
+
const base = await ensureServer();
|
|
601
|
+
const id = pageId(project, positionals[0]);
|
|
602
|
+
const anchor = positionals.slice(1).join(" ").trim();
|
|
603
|
+
if (anchor) await checkAnchor(project, base, id, anchor);
|
|
604
|
+
console.log(`${base}/${id}${anchor ? hashOf(anchor) : ""}`);
|
|
605
|
+
break;
|
|
606
|
+
}
|
|
607
|
+
case "url": {
|
|
608
|
+
const { proj, id } = pageIn(positionals[0] ?? "");
|
|
609
|
+
const base = await serverOf(proj);
|
|
610
|
+
const anchor = positionals.slice(1).join(" ").trim();
|
|
611
|
+
if (anchor) await checkAnchor(proj, base, id, anchor);
|
|
612
|
+
const link = `${base}/${id}${anchor ? hashOf(anchor) : ""}`;
|
|
613
|
+
console.log(opts.full ? link : link.slice(new URL(base).origin.length));
|
|
614
|
+
break;
|
|
615
|
+
}
|
|
616
|
+
case "check": {
|
|
617
|
+
const proj = needProject();
|
|
618
|
+
const base = await serverOf(proj);
|
|
619
|
+
const all = (dir, rel = "") => fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => e.isDirectory() ? all(path.join(dir, e.name), `${rel}${e.name}/`) : e.name.endsWith(".md") ? [`${rel}${e.name.slice(0, -3)}`] : []);
|
|
620
|
+
const ids = positionals.length ? positionals.map((p) => pageIn(p).id) : all(proj.pagesDir).sort();
|
|
621
|
+
const text = (s) => s.replace(/<[^>]+>/g, "").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, "\"").replace(/'/g, "'").replace(/&/g, "&").trim();
|
|
622
|
+
let found = 0;
|
|
623
|
+
const config = /* @__PURE__ */ new Set();
|
|
624
|
+
for (const id of ids) {
|
|
625
|
+
const res = await fetch(`${base}/api/render?page=${encodeURIComponent(id)}`);
|
|
626
|
+
if (!res.ok) {
|
|
627
|
+
console.log(`${id}\n no such page`);
|
|
628
|
+
found++;
|
|
629
|
+
continue;
|
|
630
|
+
}
|
|
631
|
+
const { html: body = "", notices = [] } = await res.json();
|
|
632
|
+
const errors = [...body.matchAll(/<(\w+) class="wp-error"[^>]*>([\s\S]*?)<\/\1>/g)].map((m) => text(m[2]));
|
|
633
|
+
for (const n of notices) if (n.startsWith("config: ")) config.add(n);
|
|
634
|
+
const problems = [.../* @__PURE__ */ new Set([...notices.filter((n) => !n.startsWith("config: ")), ...errors])];
|
|
635
|
+
if (!problems.length) continue;
|
|
636
|
+
found += problems.length;
|
|
637
|
+
console.log(`${id}\n${problems.map((p) => ` ${p.replace(/\n/g, "\n ")}`).join("\n")}`);
|
|
638
|
+
}
|
|
639
|
+
for (const n of config) console.log(n);
|
|
640
|
+
found += config.size;
|
|
641
|
+
if (!found) console.log(`nothing wrong on ${ids.length === 1 ? ids[0] : `${ids.length} pages`}`);
|
|
642
|
+
else process.exit(1);
|
|
643
|
+
break;
|
|
644
|
+
}
|
|
645
|
+
case "migrate": {
|
|
646
|
+
const old = project ? null : oldProjectDir();
|
|
647
|
+
const renames = [...old ? projectSteps(old) : [], ...machineSteps()];
|
|
648
|
+
for (const step of renames) {
|
|
649
|
+
console.log(step.what);
|
|
650
|
+
if (opts.write) step.run();
|
|
651
|
+
}
|
|
652
|
+
const pagesOf = (dir) => path.join(dir, opts.write ? ".workpad" : OLD, "pages");
|
|
653
|
+
const files = (positionals.length ? positionals : [project?.pagesDir ?? (old ? pagesOf(old) : needProject().pagesDir)].filter((t) => fs.existsSync(t))).flatMap((t) => {
|
|
654
|
+
if (!fs.existsSync(t)) throw new Error(`no such file or folder: ${t}`);
|
|
655
|
+
return markdownFiles(t);
|
|
656
|
+
});
|
|
657
|
+
let changed = 0;
|
|
658
|
+
for (const file of files) {
|
|
659
|
+
const before = fs.readFileSync(file, "utf8");
|
|
660
|
+
const { source, applied } = migrate(before);
|
|
661
|
+
if (!applied.length) continue;
|
|
662
|
+
changed++;
|
|
663
|
+
if (opts.write) fs.writeFileSync(file, source);
|
|
664
|
+
const what = applied.map((a) => `${a.migration.name}${a.changes > 1 ? ` ×${a.changes}` : ""}`).join(", ");
|
|
665
|
+
const rel = path.relative(process.cwd(), file);
|
|
666
|
+
console.log(`${rel.startsWith("..") ? path.resolve(file) : rel}\n ${what}`);
|
|
667
|
+
}
|
|
668
|
+
const pages = (n) => `${n} page${n === 1 ? "" : "s"}`;
|
|
669
|
+
const folders = renames.filter((r) => !r.what.startsWith(" ")).length;
|
|
670
|
+
const moved = folders ? `${folders} folder${folders === 1 ? "" : "s"}` : "";
|
|
671
|
+
if (!changed && !moved) console.log(`nothing to migrate: ${pages(files.length)} in the current syntax`);
|
|
672
|
+
else if (opts.write) console.log([moved && `moved ${moved} to the new name`, changed && `migrated ${pages(changed)}`].filter(Boolean).join("; "));
|
|
673
|
+
else {
|
|
674
|
+
const todo = [moved && `${moved} to move to the new name`, changed && `${pages(changed)} to migrate`];
|
|
675
|
+
const how = moved ? "does it" : `rewrites ${changed === 1 ? "it" : "them"}`;
|
|
676
|
+
console.log(`${todo.filter(Boolean).join(" and ")}; workpad migrate --write ${how}`);
|
|
677
|
+
process.exit(1);
|
|
678
|
+
}
|
|
679
|
+
break;
|
|
680
|
+
}
|
|
681
|
+
case "anchors": {
|
|
682
|
+
const target = positionals[0];
|
|
683
|
+
if (!target) throw new Error("usage: workpad anchors <page|file>");
|
|
684
|
+
const { proj, id } = pageIn(target);
|
|
685
|
+
const anchors = await anchorsAt(await serverOf(proj), id);
|
|
686
|
+
if (!anchors.length) console.error(`workpad: nothing on ${id} has an anchor`);
|
|
687
|
+
for (const a of anchors) console.log(`${hashOf(a.id)} ${a.kind}${a.label !== a.id.slice(a.kind.length + 1) ? ` ${a.label}` : ""}`);
|
|
688
|
+
break;
|
|
689
|
+
}
|
|
690
|
+
case "archive":
|
|
691
|
+
case "destroy": {
|
|
692
|
+
const target = positionals[0];
|
|
693
|
+
if (!target) throw new Error(`usage: workpad ${cmd} <page|file>`);
|
|
694
|
+
const proj = needProject();
|
|
695
|
+
const id = pageId(proj, target);
|
|
696
|
+
if (id.startsWith("-/")) throw new Error(`${target} is a file of the repository, not a page: ${cmd} is for the pages in ${relFile(proj.pagesDir)}`);
|
|
697
|
+
const file = path.join(proj.pagesDir, `${id}.md`);
|
|
698
|
+
const exists = fs.existsSync(file);
|
|
699
|
+
const events = readEvents(proj.eventsFile).filter((e) => e.page === id);
|
|
700
|
+
if (!exists && !events.length) {
|
|
701
|
+
console.error(`workpad: there is no page ${id}, nor events of it`);
|
|
702
|
+
process.exit(1);
|
|
703
|
+
}
|
|
704
|
+
const base = await running(proj);
|
|
705
|
+
if (base) try {
|
|
706
|
+
const listening = (await (await fetch(`${base}/api/listeners?page=${encodeURIComponent(id)}`)).json()).filter((l) => l.page === id);
|
|
707
|
+
if (listening.length) console.error(`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`);
|
|
708
|
+
} catch {}
|
|
709
|
+
let kept = "";
|
|
710
|
+
if (cmd === "archive") {
|
|
711
|
+
const to = archiveFile(proj.wp, id);
|
|
712
|
+
const source = exists ? fs.readFileSync(file, "utf8") : "";
|
|
713
|
+
const plugins = (await projectConfig(proj)).plugins;
|
|
714
|
+
fs.mkdirSync(path.dirname(to), { recursive: true });
|
|
715
|
+
fs.writeFileSync(to, await archived({
|
|
716
|
+
page: id,
|
|
717
|
+
source,
|
|
718
|
+
events,
|
|
719
|
+
plugins
|
|
720
|
+
}));
|
|
721
|
+
kept = `, kept with its answers in ${relFile(to)}`;
|
|
722
|
+
}
|
|
723
|
+
if (exists) fs.rmSync(file);
|
|
724
|
+
const removed = prune(proj.eventsFile, id);
|
|
725
|
+
console.log(`${cmd === "archive" ? "archived" : "destroyed"} ${id}: ${exists ? "removed its file" : "it had no file"}${kept}, and ${removed} event${removed === 1 ? "" : "s"} from the log`);
|
|
726
|
+
break;
|
|
727
|
+
}
|
|
728
|
+
case "prune": {
|
|
729
|
+
const target = positionals[0];
|
|
730
|
+
if (!target) throw new Error("usage: workpad prune <page|file> [--type <type>] [--id <event id>]");
|
|
731
|
+
const proj = needProject();
|
|
732
|
+
const id = pageId(proj, target);
|
|
733
|
+
const removed = prune(proj.eventsFile, id, (e) => (!opts.type || e.type === opts.type) && (!opts.id || e.id === opts.id));
|
|
734
|
+
const which = [opts.type && `of type ${opts.type}`, opts.id && `with id ${opts.id}`].filter(Boolean).join(", ");
|
|
735
|
+
console.log(`pruned ${removed} event${removed === 1 ? "" : "s"} of ${id}${which ? ` (${which})` : ""} from the log; the page stays`);
|
|
736
|
+
break;
|
|
737
|
+
}
|
|
738
|
+
case "edit": {
|
|
739
|
+
const eventId = positionals[0];
|
|
740
|
+
if (!eventId || !opts.data) throw new Error("usage: workpad edit <event id> --data <json> (merged into the event's data)");
|
|
741
|
+
const proj = needProject();
|
|
742
|
+
let data;
|
|
743
|
+
try {
|
|
744
|
+
data = JSON.parse(opts.data);
|
|
745
|
+
} catch {
|
|
746
|
+
throw new Error("--data must be a JSON object");
|
|
747
|
+
}
|
|
748
|
+
if (!data || typeof data !== "object" || Array.isArray(data)) throw new Error("--data must be a JSON object");
|
|
749
|
+
console.log(JSON.stringify(editEvent(proj.eventsFile, eventId, data)));
|
|
750
|
+
break;
|
|
751
|
+
}
|
|
752
|
+
case "scroll": {
|
|
753
|
+
const [target, ...where] = positionals;
|
|
754
|
+
const to = where.join(" ").trim();
|
|
755
|
+
if (!target || !to) throw new Error("usage: workpad scroll <page|file> <heading, form name or text>");
|
|
756
|
+
const proj = needProject();
|
|
757
|
+
const id = pageId(proj, target);
|
|
758
|
+
const base = await needServer();
|
|
759
|
+
const rendered = await (await fetch(`${base}/api/render?page=${encodeURIComponent(id)}`)).json().catch(() => null);
|
|
760
|
+
const text = (rendered?.html ?? "").replace(/<[^>]+>/g, " ").replace(/&[a-z#0-9]+;/gi, " ").replace(/\s+/g, " ").toLowerCase();
|
|
761
|
+
const named = new RegExp(`<form[^>]*\\bname="${to.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}"`).test(rendered?.html ?? "");
|
|
762
|
+
if (rendered && !named && !text.includes(to.replace(/\s+/g, " ").toLowerCase())) {
|
|
763
|
+
console.error(`workpad: nothing on ${id} matches ${JSON.stringify(to)} (a heading's text, a form's name, or text on the page)`);
|
|
764
|
+
process.exit(1);
|
|
765
|
+
}
|
|
766
|
+
const { tabs } = await (await fetch(`${base}/api/scroll`, {
|
|
767
|
+
method: "POST",
|
|
768
|
+
headers: { "content-type": "application/json" },
|
|
769
|
+
body: JSON.stringify({
|
|
770
|
+
page: id,
|
|
771
|
+
to
|
|
772
|
+
})
|
|
773
|
+
})).json();
|
|
774
|
+
if (!tabs) {
|
|
775
|
+
console.error(`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`);
|
|
776
|
+
process.exit(1);
|
|
777
|
+
}
|
|
778
|
+
console.log(`scrolled ${tabs} tab${tabs > 1 ? "s" : ""} of ${id} to ${JSON.stringify(to)}`);
|
|
779
|
+
break;
|
|
780
|
+
}
|
|
781
|
+
case "docs": {
|
|
782
|
+
const info = await api("/api/docs");
|
|
783
|
+
for (const e of info.errors) console.error(`config error: ${e}`);
|
|
784
|
+
const plugins = info.plugins ?? [];
|
|
785
|
+
const asked = positionals[0];
|
|
786
|
+
if (asked && opts.all) throw new Error("docs takes a block or plugin, or --all, not both");
|
|
787
|
+
const only = asked && (plugins.find((x) => x.name === asked) ?? plugins.find((x) => x.blocks?.includes(asked)));
|
|
788
|
+
if (asked && !only) throw new Error(`no block or plugin named "${asked}" here: the blocks are on the menu (workpad docs), the plugins are ${plugins.map((x) => x.name).join(", ")}`);
|
|
789
|
+
const shown = (x) => only ? x.name === only.name : !!opts.all;
|
|
790
|
+
if (!only) console.log(info.pages ? `${info.pages.trim()}\n` : "The config failed to load, so pages show as their raw text.\n");
|
|
791
|
+
if (!only && !opts.all) {
|
|
792
|
+
const rest = plugins.filter((x) => !x.menu).map((x) => x.name);
|
|
793
|
+
if (rest.length) console.log(`Plugins with nothing on the menu: ${rest.join(", ")}.\n`);
|
|
794
|
+
console.log("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.");
|
|
795
|
+
}
|
|
796
|
+
for (const e of (info.plugins ?? []).filter(shown)) {
|
|
797
|
+
console.log(`<!-- plugin: ${e.name} -->\n# Plugin: ${e.name}\n`);
|
|
798
|
+
if (e.error) console.log(`It failed to load: ${e.error}\n`);
|
|
799
|
+
if (e.docs) console.log(`${e.docs.trim()}\n`);
|
|
800
|
+
if (e.events?.length) {
|
|
801
|
+
console.log("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");
|
|
802
|
+
for (const v of e.events) console.log(`- \`${v.type}\`${v.handOut ? " (handed out)" : ""}${v.description ? `: ${v.description}` : ""}`);
|
|
803
|
+
console.log();
|
|
804
|
+
}
|
|
805
|
+
for (const c of e.commands) console.log(`- \`workpad ${[c.name, c.usage].filter(Boolean).join(" ")}\`: ${c.description}`);
|
|
806
|
+
if (e.routes.length) console.log(`\nRoutes (\`auth\`: needs the project's token, header \`x-workpad-token\`):\n`);
|
|
807
|
+
for (const r of e.routes) {
|
|
808
|
+
const takes = [
|
|
809
|
+
r.body && `body ${JSON.stringify(r.body)}`,
|
|
810
|
+
r.query && `query ${JSON.stringify(r.query)}`,
|
|
811
|
+
r.stream && "server-sent events"
|
|
812
|
+
].filter(Boolean).join(", ");
|
|
813
|
+
console.log(`- \`${r.method} ${r.path}\`${r.auth ? " (auth)" : ""}: ${r.description}${takes ? ` (${takes})` : ""}`);
|
|
814
|
+
}
|
|
815
|
+
console.log();
|
|
816
|
+
}
|
|
817
|
+
break;
|
|
818
|
+
}
|
|
819
|
+
case "events": {
|
|
820
|
+
const f = filter();
|
|
821
|
+
const log = needProject().eventsFile;
|
|
822
|
+
const { events, end } = read(log);
|
|
823
|
+
let list = events.filter((e) => matches(e, f));
|
|
824
|
+
if (opts.since) {
|
|
825
|
+
const i = list.findIndex((e) => e.id === opts.since);
|
|
826
|
+
const since = opts.since;
|
|
827
|
+
list = i >= 0 ? list.slice(i + 1) : list.filter((e) => e.ts > since);
|
|
828
|
+
}
|
|
829
|
+
if (opts.last) list = list.slice(-Number(opts.last));
|
|
830
|
+
for (const e of list) console.log(JSON.stringify(e));
|
|
831
|
+
if (opts.follow) follow(log, end, (e) => {
|
|
832
|
+
if (matches(e, f)) console.log(JSON.stringify(e));
|
|
833
|
+
});
|
|
834
|
+
break;
|
|
835
|
+
}
|
|
836
|
+
case "thread": {
|
|
837
|
+
const eventId = positionals[0];
|
|
838
|
+
if (!eventId) throw new Error("usage: workpad thread <event id>");
|
|
839
|
+
const proj = needProject();
|
|
840
|
+
const events = readEvents(proj.eventsFile);
|
|
841
|
+
const event = events.find((e) => e.id === eventId);
|
|
842
|
+
if (!event) throw new Error(`no event ${eventId} in ${proj.eventsFile}`);
|
|
843
|
+
const file = path.join(proj.pagesDir, `${event.page}.md`);
|
|
844
|
+
const source = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : "";
|
|
845
|
+
console.log(thread(eventId, events.filter((e) => e.page === event.page), source));
|
|
846
|
+
break;
|
|
847
|
+
}
|
|
848
|
+
case "settle": {
|
|
849
|
+
const proj = needProject();
|
|
850
|
+
const target = positionals[0];
|
|
851
|
+
if (!target) throw new Error("usage: workpad settle <page|file> <form>… | --all");
|
|
852
|
+
const p = await pageStatus(proj, target);
|
|
853
|
+
const named = positionals.slice(1);
|
|
854
|
+
if (named.length && opts.all) throw new Error("settle takes forms or --all, not both");
|
|
855
|
+
if (!named.length && !opts.all) throw new Error(`name the forms to settle, or --all for every open one: open on ${p.page} ${p.open.length ? `are ${p.open.join(", ")}` : "is none"}`);
|
|
856
|
+
const { forms, skipped } = settleForms(proj.eventsFile, p, opts.all ? "all" : named, await whoAmI(proj));
|
|
857
|
+
for (const { name, state } of skipped) console.error(`workpad: ${name} isn't open (${state}): left as it is`);
|
|
858
|
+
console.log(forms.length ? `settled on ${p.page}: ${forms.join(", ")}` : `nothing to settle on ${p.page}`);
|
|
859
|
+
break;
|
|
860
|
+
}
|
|
861
|
+
case "hold": {
|
|
862
|
+
const proj = needProject();
|
|
863
|
+
const [target, ...rest] = positionals;
|
|
864
|
+
const reason = rest.length > 1 ? rest.at(-1) : "";
|
|
865
|
+
const forms = rest.slice(0, -1);
|
|
866
|
+
if (!target || !forms.length || !reason.trim()) throw new Error("usage: workpad hold <page|file> <form>… \"<reason>\"");
|
|
867
|
+
const p = await pageStatus(proj, target);
|
|
868
|
+
holdForms(proj.eventsFile, p, forms, reason, await whoAmI(proj));
|
|
869
|
+
console.log(`held on ${p.page}: ${forms.join(", ")} (${reason.trim()})`);
|
|
870
|
+
break;
|
|
871
|
+
}
|
|
872
|
+
case "release": {
|
|
873
|
+
const proj = needProject();
|
|
874
|
+
const [target, ...forms] = positionals;
|
|
875
|
+
if (!target || !forms.length) throw new Error("usage: workpad release <page|file> <form>…");
|
|
876
|
+
const p = await pageStatus(proj, target);
|
|
877
|
+
releaseForms(proj.eventsFile, p, forms, await whoAmI(proj));
|
|
878
|
+
console.log(`released on ${p.page}: ${forms.join(", ")}`);
|
|
879
|
+
break;
|
|
880
|
+
}
|
|
881
|
+
case "handled": {
|
|
882
|
+
const proj = needProject();
|
|
883
|
+
if (!positionals.length) throw new Error("usage: workpad handled <event id> [<event id>…]");
|
|
884
|
+
const events = readEvents(proj.eventsFile);
|
|
885
|
+
const handled = handledIds(events);
|
|
886
|
+
const me = await whoAmI(proj);
|
|
887
|
+
for (const id of positionals) {
|
|
888
|
+
const event = events.find((e) => e.id === id);
|
|
889
|
+
if (!event) throw new Error(`no event ${id} in ${proj.eventsFile}`);
|
|
890
|
+
if (handled.has(id)) console.error(`workpad: ${id} was handled already`);
|
|
891
|
+
else console.log(JSON.stringify(handle(proj.eventsFile, event, me)));
|
|
892
|
+
}
|
|
893
|
+
break;
|
|
894
|
+
}
|
|
895
|
+
case "listen": {
|
|
896
|
+
const proj = needProject();
|
|
897
|
+
const f = filter();
|
|
898
|
+
const agent = await whoAmI(proj);
|
|
899
|
+
if (opts.follow) throw new Error("listen runs on by itself: --wait stops at the first answer, --channel hands over to the channel");
|
|
900
|
+
if (opts.wait && opts.channel) throw new Error("listen takes --wait or --channel, not both");
|
|
901
|
+
if (opts.timeout && !opts.wait) throw new Error("--timeout goes with --wait");
|
|
902
|
+
if (opts.channel) {
|
|
903
|
+
await channelListen(proj, agent);
|
|
904
|
+
break;
|
|
905
|
+
}
|
|
906
|
+
const entry = !f.page && isShared(proj) ? matchesEntries(readMachineConfig(), proj.dir) : null;
|
|
907
|
+
if (entry) {
|
|
908
|
+
await entryListen(entry, f, agent);
|
|
909
|
+
break;
|
|
910
|
+
}
|
|
911
|
+
const isForAgent = await liveForAgent(proj);
|
|
912
|
+
const pages = [...new Set(pagesGiven.map((p) => pageId(proj, p)))];
|
|
913
|
+
for (const page of pages) subscribe(proj, page, agent);
|
|
914
|
+
const queryFor = (page) => ({
|
|
915
|
+
...page ? { page } : {},
|
|
916
|
+
...f.type ? { type: f.type } : {},
|
|
917
|
+
...agent ? { agent } : {}
|
|
918
|
+
});
|
|
919
|
+
const print = (e, again) => console.log(JSON.stringify(again ? {
|
|
920
|
+
...e,
|
|
921
|
+
again: true
|
|
922
|
+
} : e));
|
|
923
|
+
const at = () => needServer().catch(() => null);
|
|
924
|
+
const options = {
|
|
925
|
+
batch: !!opts.wait,
|
|
926
|
+
forAgent: isForAgent,
|
|
927
|
+
agent
|
|
928
|
+
};
|
|
929
|
+
if (opts.timeout && opts.wait) setTimeout(() => {
|
|
930
|
+
console.error("timeout");
|
|
931
|
+
process.exit(2);
|
|
932
|
+
}, Number(opts.timeout) * 1e3);
|
|
933
|
+
await Promise.all((pages.length ? pages : [void 0]).map((page) => listen({
|
|
934
|
+
at,
|
|
935
|
+
query: queryFor(page)
|
|
936
|
+
}, { orNone: true })));
|
|
937
|
+
const given = pages.length > 1 ? {
|
|
938
|
+
...f,
|
|
939
|
+
page: null,
|
|
940
|
+
pages
|
|
941
|
+
} : f;
|
|
942
|
+
handOut(proj.eventsFile, given, print, options).then(async () => {
|
|
943
|
+
if (opts.wait && pages.length) try {
|
|
944
|
+
const statuses = (await Promise.all(pages.map((page) => api(`/api/status?page=${encodeURIComponent(page)}`)))).flat();
|
|
945
|
+
for (const p of statuses) {
|
|
946
|
+
const again = `\`workpad listen --wait --page ${relFile(p.file)}\``;
|
|
947
|
+
if (p.unhandled.length) console.error(`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`);
|
|
948
|
+
if (p.awaitingReply.length) console.error(`workpad: waiting for your reply on ${p.page}: the chat${p.awaitingReply.length > 1 ? "s" : ""} ${p.awaitingReply.join(", ")}`);
|
|
949
|
+
if (p.open.length) console.error(`workpad: still unanswered on ${p.page}: ${p.open.join(", ")} → run ${again} again, in the background, once you've acted on this`);
|
|
950
|
+
}
|
|
951
|
+
} catch {}
|
|
952
|
+
process.exit(0);
|
|
953
|
+
});
|
|
954
|
+
break;
|
|
955
|
+
}
|
|
956
|
+
case "append": {
|
|
957
|
+
const proj = needProject();
|
|
958
|
+
if (!pageOpt || !opts.type) throw new Error("usage: workpad append --page <page|file> --type <type> [--data '<json>']");
|
|
959
|
+
let data = {};
|
|
960
|
+
if (opts.data) try {
|
|
961
|
+
data = JSON.parse(opts.data);
|
|
962
|
+
} catch {
|
|
963
|
+
throw new Error("--data must be JSON, e.g. '{\"text\":\"…\"}'");
|
|
964
|
+
}
|
|
965
|
+
console.log(JSON.stringify(appendEvent(proj.eventsFile, {
|
|
966
|
+
page: pageId(proj, pageOpt),
|
|
967
|
+
type: opts.type,
|
|
968
|
+
data
|
|
969
|
+
}, "cli", await whoAmI(proj))));
|
|
970
|
+
break;
|
|
971
|
+
}
|
|
972
|
+
case "status":
|
|
973
|
+
await status();
|
|
974
|
+
break;
|
|
975
|
+
case "paths": {
|
|
976
|
+
const config = readMachineConfig();
|
|
977
|
+
if (!config) throw new Error(`no machine config: ${machineDir()}/config.json`);
|
|
978
|
+
const paths = serverPaths(config, { packageDir: PACKAGE_DIR });
|
|
979
|
+
try {
|
|
980
|
+
fs.mkdirSync(stateDir(), { recursive: true });
|
|
981
|
+
} catch {}
|
|
982
|
+
const write = paths.write.filter((d) => fs.existsSync(d));
|
|
983
|
+
const read = paths.read.filter((d) => fs.existsSync(d));
|
|
984
|
+
if (opts.write) console.log(write.join(":"));
|
|
985
|
+
else if (opts.read) console.log(read.join(":"));
|
|
986
|
+
else console.log(`write: ${write.join(":")}\nread: ${read.join(":")}`);
|
|
987
|
+
break;
|
|
988
|
+
}
|
|
989
|
+
case "skill": {
|
|
990
|
+
const source = packagePath("skills", "workpad");
|
|
991
|
+
if (!positionals[0]) {
|
|
992
|
+
console.log(source);
|
|
993
|
+
break;
|
|
994
|
+
}
|
|
995
|
+
const target = path.join(path.resolve(positionals[0].replace(/^~(?=$|\/)/, os.homedir())), "workpad");
|
|
996
|
+
let existing = null;
|
|
997
|
+
try {
|
|
998
|
+
existing = fs.lstatSync(target);
|
|
999
|
+
} catch {}
|
|
1000
|
+
if (existing) {
|
|
1001
|
+
if (existing.isSymbolicLink() && path.resolve(path.dirname(target), fs.readlinkSync(target)) === source) {
|
|
1002
|
+
console.log(`already linked: ${target} -> ${source}`);
|
|
1003
|
+
break;
|
|
1004
|
+
}
|
|
1005
|
+
console.error(`workpad: ${target} already exists; remove it first to link the skill there`);
|
|
1006
|
+
process.exit(1);
|
|
1007
|
+
}
|
|
1008
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
1009
|
+
fs.symlinkSync(source, target);
|
|
1010
|
+
console.log(`linked: ${target} -> ${source}`);
|
|
1011
|
+
break;
|
|
1012
|
+
}
|
|
1013
|
+
default: {
|
|
1014
|
+
const commands = project ? await projectCommands(project) : [];
|
|
1015
|
+
if (cmd === "help" && rest[0]) {
|
|
1016
|
+
const [name, sub] = rest;
|
|
1017
|
+
if (BUILTIN_COMMANDS.has(name)) console.log(commandHelp(name));
|
|
1018
|
+
else {
|
|
1019
|
+
const theirs = commands.filter((c) => c.plugin === name);
|
|
1020
|
+
const one = theirs.find((c) => c.sub === sub) ?? (sub ? void 0 : theirs.find((c) => !c.sub));
|
|
1021
|
+
if (!theirs.length) throw new Error(`no command ${name}${project ? "" : " (outside a project only the built-in ones)"}`);
|
|
1022
|
+
console.log(one ? pluginCommandHelp(one) : theirs.map((c) => pluginCommandHelp(c)).join("\n\n"));
|
|
1023
|
+
}
|
|
1024
|
+
break;
|
|
1025
|
+
}
|
|
1026
|
+
const mine = commands.filter((c) => c.plugin === cmd);
|
|
1027
|
+
const found = mine.find((c) => c.sub && c.sub === rest[0]) ?? mine.find((c) => !c.sub);
|
|
1028
|
+
if (mine.length && asksHelp(found?.sub ? rest.slice(1) : rest)) {
|
|
1029
|
+
console.log(found?.sub ? pluginCommandHelp(found) : mine.map((c) => pluginCommandHelp(c)).join("\n\n"));
|
|
1030
|
+
break;
|
|
1031
|
+
}
|
|
1032
|
+
if (found && project) {
|
|
1033
|
+
const args = found.sub ? rest.slice(1) : rest;
|
|
1034
|
+
const { options, positionals, rest: after } = parseCommandArgs(found.command, args, found.name);
|
|
1035
|
+
const me = await whoAmI(project);
|
|
1036
|
+
await found.command.run({
|
|
1037
|
+
options,
|
|
1038
|
+
positionals,
|
|
1039
|
+
rest: after,
|
|
1040
|
+
project: {
|
|
1041
|
+
name: project.name,
|
|
1042
|
+
dir: project.dir,
|
|
1043
|
+
wp: project.wp
|
|
1044
|
+
},
|
|
1045
|
+
eventsFile: project.eventsFile,
|
|
1046
|
+
dataDir: pluginDir(project.wp, found.plugin),
|
|
1047
|
+
token: projectToken(project.wp),
|
|
1048
|
+
server: ensureServer,
|
|
1049
|
+
running: async () => {
|
|
1050
|
+
const base = await running(project);
|
|
1051
|
+
if (!base) {
|
|
1052
|
+
const shared = isShared(project);
|
|
1053
|
+
const at = recordedOrigin(shared ? machineServerFile() : project.serverFile);
|
|
1054
|
+
if (at && await stuckAt(at)) throw new Error(stuck(at, shared ? "its login service log" : project.logFile));
|
|
1055
|
+
return null;
|
|
1056
|
+
}
|
|
1057
|
+
const health = isShared(project) ? await sharedServer(machineServerFile()) : await fetch(`${base}/api/health`, { signal: AbortSignal.timeout(5e3) }).then((r) => r.json()).catch(() => null);
|
|
1058
|
+
return {
|
|
1059
|
+
base,
|
|
1060
|
+
version: String(health?.version ?? "unknown")
|
|
1061
|
+
};
|
|
1062
|
+
},
|
|
1063
|
+
version: VERSION,
|
|
1064
|
+
wp: client(async () => probe(await ensureServer()), {
|
|
1065
|
+
token: projectToken(project.wp),
|
|
1066
|
+
agent: me
|
|
1067
|
+
}),
|
|
1068
|
+
page: (page) => pageId(project, page),
|
|
1069
|
+
pagePath: (page) => `/${pageId(project, page ?? "")}`,
|
|
1070
|
+
status: async (page) => api(`/api/status${page ? `?page=${encodeURIComponent(pageId(project, page))}` : ""}`),
|
|
1071
|
+
handOut: async (filter, onEvent, options) => handOut(project.eventsFile, {
|
|
1072
|
+
...filter,
|
|
1073
|
+
page: filter.page ? pageId(project, filter.page) : null
|
|
1074
|
+
}, onEvent, {
|
|
1075
|
+
...options,
|
|
1076
|
+
forAgent: await liveForAgent(project, options?.signal)
|
|
1077
|
+
}),
|
|
1078
|
+
listen: (page, { agent = null } = {}) => listen({
|
|
1079
|
+
at: () => ensureServer().catch(() => null),
|
|
1080
|
+
query: {
|
|
1081
|
+
page: pageId(project, page),
|
|
1082
|
+
...agent ? { agent } : {}
|
|
1083
|
+
}
|
|
1084
|
+
}),
|
|
1085
|
+
channel: (session, handlers) => holdChannel(() => ensureServer().catch(() => null), session, handlers),
|
|
1086
|
+
authLink: async (to) => `${await ensureServer()}/_/auth?token=${encodeURIComponent(projectToken(project.wp))}&to=${encodeURIComponent(to)}`
|
|
1087
|
+
});
|
|
1088
|
+
break;
|
|
1089
|
+
}
|
|
1090
|
+
const asked = !cmd || cmd === "help" || opts.help;
|
|
1091
|
+
const print = asked ? console.log : console.error;
|
|
1092
|
+
print(HELP);
|
|
1093
|
+
for (const [from, heading] of [["config", "from this project's config"], ["plugin", "from this project's plugins"]]) {
|
|
1094
|
+
const theirs = commands.filter((c) => c.from === from);
|
|
1095
|
+
if (!theirs.length) continue;
|
|
1096
|
+
print(`\n${heading}:\n`);
|
|
1097
|
+
for (const c of theirs) print(` workpad ${[c.name, usage(c.command)].filter(Boolean).join(" ")}\n ${c.command.description}`);
|
|
1098
|
+
}
|
|
1099
|
+
if (mine.length) console.error(`\nworkpad: ${cmd} has no command ${JSON.stringify(rest[0] ?? "")}`);
|
|
1100
|
+
if (!asked) process.exit(1);
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
/**
|
|
1104
|
+
* `workpad listen --channel`: the pages (each --page, else every page of the project, also those
|
|
1105
|
+
* made later) become this session's, and its channel brings their answers from its next round, also
|
|
1106
|
+
* those waiting now: so nothing is printed here, which would hand them out twice. Only for a session
|
|
1107
|
+
* whose channel is confirmed (`workpad agent ping`); else nothing is taken on.
|
|
1108
|
+
*/
|
|
1109
|
+
async function channelListen(proj, agent) {
|
|
1110
|
+
if (!agent) throw new Error("--channel needs a session: no --agent, WORKPAD_AGENT or plugin session names one");
|
|
1111
|
+
if (!(await api("/api/channels")).some((c) => c.session === agent && c.confirmed)) {
|
|
1112
|
+
console.error("workpad: no confirmed channel brings answers to this session: run `workpad agent ping` and confirm its pong, or listen without --channel");
|
|
1113
|
+
process.exit(1);
|
|
1114
|
+
}
|
|
1115
|
+
const pages = [...new Set(pagesGiven.map((p) => pageId(proj, p)))];
|
|
1116
|
+
for (const page of pages.length ? pages : [""]) subscribe(proj, page, agent, { channel: true });
|
|
1117
|
+
const { events } = read(proj.eventsFile);
|
|
1118
|
+
const { handedOut } = await projectConfig(proj);
|
|
1119
|
+
const isForAgent = forAgent(handedOut);
|
|
1120
|
+
const handled = handledIds(events);
|
|
1121
|
+
const received = receivedIds(events);
|
|
1122
|
+
const skipped = events.filter((e) => {
|
|
1123
|
+
if (fromReader(e) || !e.by || e.by === agent || !isForAgent(e.type) || handled.has(e.id)) return false;
|
|
1124
|
+
if (!received.has(e.id)) return false;
|
|
1125
|
+
const since = channelSince(events, agent, e.page);
|
|
1126
|
+
if (!since) return false;
|
|
1127
|
+
return events.findIndex((x) => x.id === e.id) < events.findIndex((x) => x.id === since);
|
|
1128
|
+
});
|
|
1129
|
+
const where = pages.length ? pages.join(", ") : "every page, also those made later";
|
|
1130
|
+
console.log(`the channel brings the answers on ${where}: your answers waiting there first, then each as it comes`);
|
|
1131
|
+
if (skipped.length) {
|
|
1132
|
+
const on = [...new Set(skipped.map((e) => e.page))];
|
|
1133
|
+
console.log(`${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`);
|
|
1134
|
+
}
|
|
1135
|
+
}
|
|
1136
|
+
/**
|
|
1137
|
+
* A listen over a whole entry: every page of each of its projects, from each project's own log, each
|
|
1138
|
+
* event with the project it is from (`project`, its folder) and its page's `url`. Any number run.
|
|
1139
|
+
* Without a shared server running it waits for one, as any listen does. Projects that appear
|
|
1140
|
+
* meanwhile are followed too.
|
|
1141
|
+
*/
|
|
1142
|
+
async function entryListen(entry, f, agent) {
|
|
1143
|
+
const file = machineServerFile();
|
|
1144
|
+
const count = opts.wait ? 1 : Infinity;
|
|
1145
|
+
const done = new AbortController();
|
|
1146
|
+
let total = 0;
|
|
1147
|
+
done.signal.addEventListener("abort", () => setImmediate(() => process.exit(0)));
|
|
1148
|
+
if (opts.timeout && opts.wait) setTimeout(() => {
|
|
1149
|
+
console.error("timeout");
|
|
1150
|
+
process.exit(2);
|
|
1151
|
+
}, Number(opts.timeout) * 1e3);
|
|
1152
|
+
let origin = "";
|
|
1153
|
+
const page = (id) => id.split("/").map(encodeURIComponent).join("/");
|
|
1154
|
+
const update = everyProject((p, signal) => {
|
|
1155
|
+
const proj = project$1(p.dir);
|
|
1156
|
+
if (!proj) return;
|
|
1157
|
+
projectConfig(proj).then(({ handedOut }) => handOut(proj.eventsFile, { type: f.type }, (e) => {
|
|
1158
|
+
console.log(JSON.stringify({
|
|
1159
|
+
...e,
|
|
1160
|
+
project: p.dir,
|
|
1161
|
+
url: `${origin}${p.base}/${page(e.page)}`
|
|
1162
|
+
}));
|
|
1163
|
+
if (++total >= count) done.abort();
|
|
1164
|
+
}, {
|
|
1165
|
+
forAgent: forAgent(handedOut),
|
|
1166
|
+
agent,
|
|
1167
|
+
signal: AbortSignal.any([signal, done.signal])
|
|
1168
|
+
}));
|
|
1169
|
+
});
|
|
1170
|
+
await listen({
|
|
1171
|
+
at: async () => {
|
|
1172
|
+
origin = (await sharedServer(file))?.origin ?? "";
|
|
1173
|
+
return origin || null;
|
|
1174
|
+
},
|
|
1175
|
+
query: {
|
|
1176
|
+
entry,
|
|
1177
|
+
...f.type ? { type: f.type } : {},
|
|
1178
|
+
...agent ? { agent } : {}
|
|
1179
|
+
},
|
|
1180
|
+
onSnapshot: update
|
|
1181
|
+
});
|
|
1182
|
+
setInterval(() => {}, 1 << 30);
|
|
1183
|
+
}
|
|
1184
|
+
/** The commands the project's config and plugins add: `workpad <name>`, `workpad <plugin> [sub]`. */
|
|
1185
|
+
async function projectCommands(proj) {
|
|
1186
|
+
const { plugins, commands, errors } = await projectConfig(proj);
|
|
1187
|
+
for (const e of errors) console.error(`workpad: config error: ${e.message}`);
|
|
1188
|
+
return [...commands, ...plugins.flatMap(pluginCommands)];
|
|
1189
|
+
}
|
|
1190
|
+
export {};
|