onionskin-cli 0.0.0-stage → 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +136 -0
- package/INSTALL.md +17 -0
- package/LICENSE +21 -0
- package/NOTICE +46 -0
- package/README.md +88 -2
- package/docs/contracts/batch.schema.json +839 -0
- package/docs/contracts/history.schema.json +126 -0
- package/docs/contracts/ops.schema.json +541 -0
- package/package.json +54 -4
- package/scripts/checker/check.py +411 -0
- package/scripts/checker/requirements.txt +5 -0
- package/scripts/install-check.mjs +9 -0
- package/scripts/requirements.txt +5 -0
- package/scripts/rewriter/apple/main.swift +135 -0
- package/scripts/rewriter/apple/onionskin-fm +0 -0
- package/scripts/rewriter/apple/onionskin-fm.json +6 -0
- package/skills/onionskin/SKILL.md +117 -0
- package/skills/onionskin/reference/batch.md +94 -0
- package/skills/onionskin/reference/formats.md +15 -0
- package/skills/onionskin/reference/ops.md +253 -0
- package/skills/onionskin/reference/troubleshooting.md +73 -0
- package/skills/onionskin/reference/voice-guide.md +86 -0
- package/skills/onionskin/voice.example.md +51 -0
- package/src/agent-detect.js +149 -0
- package/src/agent-events.js +159 -0
- package/src/agent-prompt.js +27 -0
- package/src/agent-runner.js +593 -0
- package/src/analyze.js +17 -0
- package/src/anchors.js +190 -0
- package/src/apply.js +387 -0
- package/src/auth.js +130 -0
- package/src/batch.js +322 -0
- package/src/check-worker.js +8 -0
- package/src/checker.js +293 -0
- package/src/cli.js +516 -0
- package/src/constants.js +20 -0
- package/src/diff.js +267 -0
- package/src/doctor.js +247 -0
- package/src/docx.js +438 -0
- package/src/fmt.js +30 -0
- package/src/fsutil.js +348 -0
- package/src/history-worker.js +16 -0
- package/src/history.js +576 -0
- package/src/lease.js +79 -0
- package/src/local.js +242 -0
- package/src/merge-pptx.js +198 -0
- package/src/merge-xlsx.js +453 -0
- package/src/merge.js +410 -0
- package/src/offload.js +34 -0
- package/src/ops/common.js +48 -0
- package/src/ops/docx-table.js +323 -0
- package/src/ops/docx.js +503 -0
- package/src/ops/engine.js +41 -0
- package/src/ops/pptx.js +336 -0
- package/src/ops/run.js +115 -0
- package/src/ops/runs.js +127 -0
- package/src/ops/schema.js +109 -0
- package/src/ops/xlsx.js +277 -0
- package/src/package.js +189 -0
- package/src/paths.js +64 -0
- package/src/person.js +66 -0
- package/src/pptx.js +194 -0
- package/src/question.js +47 -0
- package/src/quick-plan.js +107 -0
- package/src/quick.js +164 -0
- package/src/redline-check.js +251 -0
- package/src/redline-worker.js +29 -0
- package/src/redline.js +438 -0
- package/src/reply.js +410 -0
- package/src/review.js +274 -0
- package/src/rewrite-check.js +1014 -0
- package/src/rewriter-cleanup.js +105 -0
- package/src/rewriter-setup.js +104 -0
- package/src/rewriter.js +396 -0
- package/src/sanitize.js +42 -0
- package/src/sentence-span.js +25 -0
- package/src/server-entry.js +13 -0
- package/src/server.js +576 -0
- package/src/session.js +1910 -0
- package/src/settings.js +161 -0
- package/src/setup.js +160 -0
- package/src/stamp-words.js +10 -0
- package/src/stamps.js +59 -0
- package/src/style.js +110 -0
- package/src/suggest-reply.js +84 -0
- package/src/suggest.js +261 -0
- package/src/text.js +31 -0
- package/src/tracked-words.js +43 -0
- package/src/voice-guide.js +182 -0
- package/src/voice-learn.js +314 -0
- package/src/voice-sample-worker.js +95 -0
- package/src/voice-samples.js +329 -0
- package/src/voice-store.js +305 -0
- package/src/voice-worker.js +28 -0
- package/src/voice.js +297 -0
- package/src/xlsx.js +454 -0
- package/src/xml-tree.js +118 -0
- package/src/xml.js +127 -0
- package/src/zip-write.js +74 -0
- package/src/zip.js +88 -0
- package/vendor/engine/DocViewer-BZLXUcxJ.js +15137 -0
- package/vendor/engine/THIRD_PARTY_LICENSES.txt +79 -0
- package/vendor/engine/collab-BVynXMqc.js +2591 -0
- package/vendor/engine/collab.js +2 -0
- package/vendor/engine/core.js +4 -0
- package/vendor/engine/default-worker-DogNT09A.js +35625 -0
- package/vendor/engine/embed.js +107 -0
- package/vendor/engine/index.js +5 -0
- package/vendor/engine/office-engine.embed.js +184 -0
- package/vendor/engine/office-engine.worker.js +36030 -0
- package/vendor/engine/xlsx-ops-SYAv6V0f.js +939 -0
- package/vendor/engine-node/LICENSE +21 -0
- package/vendor/engine-node/engine-node.mjs +46618 -0
- package/vendor/engine.lock.json +26 -0
- package/web/dist/assets/index-CFISATkn.js +197 -0
- package/web/dist/assets/index-spXE4oTz.css +1 -0
- package/web/dist/index.html +14 -0
package/src/cli.js
ADDED
|
@@ -0,0 +1,516 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import http from "node:http";
|
|
4
|
+
import net from "node:net";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import tty from "node:tty";
|
|
7
|
+
import { spawn } from "node:child_process";
|
|
8
|
+
import { fileURLToPath } from "node:url";
|
|
9
|
+
import { PRODUCT, SERVER_PROTOCOL } from "./constants.js";
|
|
10
|
+
import { holderFor, loadHolder, loadTicketRecord, parseTicket, saveHolder } from "./lease.js";
|
|
11
|
+
import { ensureStateDir, serverRecordPath, socketPath, stateDir } from "./paths.js";
|
|
12
|
+
import { ApplyError, applyCommand, commitCommand, summarizeReport } from "./apply.js";
|
|
13
|
+
import { ReplyError, replyCommand } from "./reply.js";
|
|
14
|
+
import { setupChecker } from "./checker.js";
|
|
15
|
+
import { runSetup } from "./setup.js";
|
|
16
|
+
import { expandShortcut, personOpenText, personPollText, pickAudience, shellQuote } from "./person.js";
|
|
17
|
+
import { findClaude, findCodex, isAgentHolder } from "./agent-detect.js";
|
|
18
|
+
import { BG_PRESETS, DEFAULT_BACKGROUND, MAX_IMAGE_BYTES, SettingsError, describeBackground, readSettings, saveCustomImage, writeBackground } from "./settings.js";
|
|
19
|
+
|
|
20
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
21
|
+
const BIN = PRODUCT.bin;
|
|
22
|
+
const HELP = `${PRODUCT.name}
|
|
23
|
+
|
|
24
|
+
${BIN} open <file.docx|xlsx|pptx> [--no-open] [--no-agent|--agent] Open the file in the browser editor (also: ${BIN} <file>). At a terminal it also starts Claude Code on it in the background; --no-agent only opens the page, --agent prints the agent's output
|
|
25
|
+
${BIN} poll <file> [--ack] [--full] [--timeout <secs>] [--agent] Block until the user hits Send, print the batch as JSON (--full: the complete batch even when you already have the rules)
|
|
26
|
+
${BIN} status <file> [--ticket] Print session state without blocking (--ticket: re-read your delivery's ticket)
|
|
27
|
+
${BIN} apply <file> --ops <ops.json> --lease <ticket> [--dry-run] [--partial] [--summary] [--batch <batch.json>]
|
|
28
|
+
Make anchored edits through the same engine the browser uses
|
|
29
|
+
${BIN} reply <file> --lease <ticket> [--json '<json>' | --file <path>] [--partial] [--then-poll [--timeout <secs>]]
|
|
30
|
+
Answer the whole batch in ONE call: apply + done (JSON on stdin when no --json/--file); --then-poll waits for the next batch
|
|
31
|
+
${BIN} commit <file> --from <candidate> --lease <ticket> [--base <sha256>]
|
|
32
|
+
Submit a COPY edited with another tool through the checked write
|
|
33
|
+
${BIN} done <file> --results <results.json> --lease <ticket> [--summary] Report the finished run
|
|
34
|
+
${BIN} setup [--dry-run] [--force] [--uninstall] Install the agent skill into ~/.claude/skills and ~/.agents/skills
|
|
35
|
+
${BIN} setup-checker Create the Python venv for the deeper checks at \`done\` (uses the network once)
|
|
36
|
+
${BIN} setup-rewriter [--remove] Turn on quick fixes on this Mac: quick spelling and grammar fixes on one sentence, with Apple's built-in model (macOS 26 or later, Apple Intelligence on; nothing is downloaded); --remove turns them off
|
|
37
|
+
${BIN} doctor [--json] [--verbose] Check the install (OK / MISSING / NOTE per line, fix command on each failure); exit 1 if a required check fails
|
|
38
|
+
${BIN} shapes <file.pptx> [--slide <slide id>] List the shapes of a slide (id, name, placeholder, text preview) as JSON; read-only
|
|
39
|
+
${BIN} config background <${BG_PRESETS.join("|")}|default> Choose the background behind the editing UI (this machine)
|
|
40
|
+
${BIN} config background --image <file> [--strength 0-100] [--no-blur] Use your own PNG, JPEG or WebP (max 15 MB, scaled by the page)
|
|
41
|
+
${BIN} config get background Print the current background choice
|
|
42
|
+
${BIN} stop Stop the local server (and remove a leftover socket file nothing answers on)
|
|
43
|
+
${BIN} --version Print the version
|
|
44
|
+
`;
|
|
45
|
+
|
|
46
|
+
/** The flags each subcommand accepts (parseArgs and parseApplyArgs reject any other). */
|
|
47
|
+
export const FLAGS = {
|
|
48
|
+
open: ["--no-open"],
|
|
49
|
+
poll: ["--ack", "--full", "--timeout"],
|
|
50
|
+
reply: ["--lease", "--json", "--file", "--partial", "--then-poll", "--timeout"],
|
|
51
|
+
status: ["--ticket"],
|
|
52
|
+
done: ["--results", "--lease", "--summary"],
|
|
53
|
+
apply: ["--ops", "--dry-run", "--partial", "--batch", "--holder", "--lease", "--standalone", "--summary"],
|
|
54
|
+
commit: ["--from", "--lease", "--base", "--standalone", "--holder"],
|
|
55
|
+
setup: ["--dry-run", "--force", "--uninstall"],
|
|
56
|
+
"setup-checker": [],
|
|
57
|
+
"setup-rewriter": ["--model", "--remove", "--clean-old"],
|
|
58
|
+
doctor: ["--json", "--verbose"],
|
|
59
|
+
shapes: ["--slide"],
|
|
60
|
+
config: ["--image", "--strength", "--no-blur"],
|
|
61
|
+
stop: [],
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
/** The lines of HELP that belong to one subcommand: its usage line(s) and the indented lines that continue them. */
|
|
65
|
+
export function commandHelp(cmd) {
|
|
66
|
+
const keep = [];
|
|
67
|
+
let on = false;
|
|
68
|
+
for (const line of HELP.split("\n").slice(2)) {
|
|
69
|
+
if (line.startsWith(` ${BIN} `)) on = line.startsWith(` ${BIN} ${cmd} `) || line === ` ${BIN} ${cmd}`;
|
|
70
|
+
else if (!/^\s{10,}\S/.test(line)) on = false; // a continuation line is indented deeper than a usage line
|
|
71
|
+
if (on) keep.push(line);
|
|
72
|
+
}
|
|
73
|
+
return keep.length ? keep.join("\n") + "\n" : HELP;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// a flag's value is never a request for help: `reply --json '-h'`
|
|
77
|
+
const TAKES_VALUE = ["--json", "--file", "--results", "--ops", "--batch", "--from", "--lease", "--base", "--holder", "--model", "--image", "--timeout", "--slide", "--strength"];
|
|
78
|
+
export const asksForHelp = (argv) => argv[0] in FLAGS && argv.slice(1).some((x, i) => (x === "--help" || x === "-h") && !TAKES_VALUE.includes(argv[i]));
|
|
79
|
+
|
|
80
|
+
export { shellQuote };
|
|
81
|
+
|
|
82
|
+
function req(options, body) {
|
|
83
|
+
return new Promise((resolve, reject) => {
|
|
84
|
+
const r = http.request({ socketPath: socketPath(), ...options, headers: { ...(body ? { "content-type": "application/json" } : {}), ...(options.headers || {}) } }, (res) => {
|
|
85
|
+
const chunks = [];
|
|
86
|
+
res.on("data", (c) => chunks.push(c));
|
|
87
|
+
res.on("end", () => resolve({ status: res.statusCode, text: Buffer.concat(chunks).toString("utf8") }));
|
|
88
|
+
res.on("aborted", () => reject(new Error("server connection closed")));
|
|
89
|
+
res.on("close", () => !res.complete && reject(new Error("server connection closed")));
|
|
90
|
+
});
|
|
91
|
+
r.on("error", reject);
|
|
92
|
+
if (options.signal) options.signal.addEventListener("abort", () => r.destroy(new Error("aborted")), { once: true });
|
|
93
|
+
if (body) r.write(JSON.stringify(body));
|
|
94
|
+
r.end();
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
const json = (t) => {
|
|
98
|
+
try {
|
|
99
|
+
return JSON.parse(t);
|
|
100
|
+
} catch {
|
|
101
|
+
return { error: t.slice(0, 200) };
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
async function healthy() {
|
|
106
|
+
try {
|
|
107
|
+
const r = await req({ method: "GET", path: "/health", timeout: 1500 });
|
|
108
|
+
const j = json(r.text);
|
|
109
|
+
return r.status === 200 && j.protocol === SERVER_PROTOCOL;
|
|
110
|
+
} catch {
|
|
111
|
+
return false;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* `stop` leaves no dead socket behind: the socket file in our own state folder that nothing listens on (a server that crashed or was killed
|
|
117
|
+
* leaves it) is removed. It stays when anything could hold it: a connect that is not refused, a server record or a start lock whose
|
|
118
|
+
* process is still alive, a file that is not a socket or not ours. Returns true when a file was removed.
|
|
119
|
+
*/
|
|
120
|
+
async function removeStaleSocket() {
|
|
121
|
+
const sock = socketPath();
|
|
122
|
+
let st;
|
|
123
|
+
try {
|
|
124
|
+
st = fs.lstatSync(sock);
|
|
125
|
+
} catch {
|
|
126
|
+
return false;
|
|
127
|
+
}
|
|
128
|
+
if (!st.isSocket() || st.uid !== process.getuid() || path.dirname(sock) !== stateDir()) return false;
|
|
129
|
+
const refused = await new Promise((resolve) => {
|
|
130
|
+
const c = net.connect(sock);
|
|
131
|
+
c.setTimeout(1500, () => (c.destroy(), resolve(false)));
|
|
132
|
+
c.once("connect", () => (c.destroy(), resolve(false)));
|
|
133
|
+
c.once("error", (e) => resolve(e.code === "ECONNREFUSED"));
|
|
134
|
+
});
|
|
135
|
+
if (!refused) return false;
|
|
136
|
+
for (const f of [serverRecordPath(), path.join(stateDir(), "start.lock")]) {
|
|
137
|
+
let pid;
|
|
138
|
+
try {
|
|
139
|
+
pid = Number.parseInt(JSON.parse(fs.readFileSync(f, "utf8")).pid ?? fs.readFileSync(f, "utf8"), 10);
|
|
140
|
+
} catch {
|
|
141
|
+
try {
|
|
142
|
+
pid = Number.parseInt(fs.readFileSync(f, "utf8"), 10); // the start lock holds the bare pid
|
|
143
|
+
} catch {
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
if (!Number.isInteger(pid)) continue;
|
|
148
|
+
try {
|
|
149
|
+
process.kill(pid, 0);
|
|
150
|
+
return false; // that process is alive: it may be starting up on this socket
|
|
151
|
+
} catch (e) {
|
|
152
|
+
if (e.code === "EPERM") return false;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
try {
|
|
156
|
+
fs.unlinkSync(sock);
|
|
157
|
+
return true;
|
|
158
|
+
} catch {
|
|
159
|
+
return false;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Starts the detached server and waits (event-based) for its "ready" line. */
|
|
164
|
+
async function ensureServer() {
|
|
165
|
+
ensureStateDir();
|
|
166
|
+
if (await healthy()) return;
|
|
167
|
+
const child = spawn(process.execPath, [path.join(here, "server-entry.js")], { detached: true, stdio: ["ignore", "pipe", "ignore"], env: process.env });
|
|
168
|
+
await new Promise((resolve, reject) => {
|
|
169
|
+
const to = setTimeout(() => reject(new Error(`could not start the ${PRODUCT.name} server`)), 15000);
|
|
170
|
+
child.stdout.once("data", () => (clearTimeout(to), resolve()));
|
|
171
|
+
child.once("exit", () => (clearTimeout(to), resolve())); // lost a race to another server: it is healthy now
|
|
172
|
+
child.once("error", (e) => (clearTimeout(to), reject(e)));
|
|
173
|
+
});
|
|
174
|
+
child.stdout.destroy();
|
|
175
|
+
child.unref();
|
|
176
|
+
if (!(await healthy())) throw new Error(`the ${PRODUCT.name} server did not come up`);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function openBrowser(url) {
|
|
180
|
+
const cmd = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", "", url]] : ["xdg-open", [url]];
|
|
181
|
+
const c = spawn(cmd[0], cmd[1], { detached: true, stdio: "ignore" });
|
|
182
|
+
c.on("error", () => {});
|
|
183
|
+
c.unref();
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** `config background <preset|default>`, `config background --image <file> [--strength N] [--no-blur]`, `config get background` */
|
|
187
|
+
export function parseConfigArgs(args) {
|
|
188
|
+
const a = { action: "", key: "", value: "", image: "", strength: null, blur: null };
|
|
189
|
+
const pos = [];
|
|
190
|
+
for (let i = 0; i < args.length; i++) {
|
|
191
|
+
const x = args[i];
|
|
192
|
+
if (x === "--no-blur") a.blur = false;
|
|
193
|
+
else if (x === "--image" || x.startsWith("--image=")) {
|
|
194
|
+
a.image = x.includes("=") ? x.slice(x.indexOf("=") + 1) : args[++i];
|
|
195
|
+
if (!a.image) throw new Error("--image wants a file path");
|
|
196
|
+
} else if (x === "--strength" || x.startsWith("--strength=")) {
|
|
197
|
+
const v = x.includes("=") ? x.split("=")[1] : args[++i];
|
|
198
|
+
a.strength = /^\d{1,3}$/.test(v || "") ? Number(v) : NaN;
|
|
199
|
+
if (!(a.strength >= 0 && a.strength <= 100)) throw new Error("--strength wants a whole number from 0 to 100");
|
|
200
|
+
} else if (x.startsWith("-")) throw new Error(`unknown option ${x}`);
|
|
201
|
+
else pos.push(x);
|
|
202
|
+
}
|
|
203
|
+
if (pos[0] === "get") {
|
|
204
|
+
if (pos[1] !== "background" || pos.length > 2) throw new Error(`Usage: ${BIN} config get background`);
|
|
205
|
+
return { ...a, action: "get", key: "background" };
|
|
206
|
+
}
|
|
207
|
+
if (pos[0] !== "background") throw new Error(`Usage: ${BIN} config background <${BG_PRESETS.join("|")}|default> | --image <file> [--strength N] [--no-blur] or ${BIN} config get background`);
|
|
208
|
+
if (a.image) {
|
|
209
|
+
if (pos.length > 1) throw new Error("--image and a preset name cannot be combined");
|
|
210
|
+
return { ...a, action: "set", key: "background", value: "custom" };
|
|
211
|
+
}
|
|
212
|
+
if (pos.length !== 2 || ![...BG_PRESETS, "default"].includes(pos[1])) throw new Error(`background wants one of ${BG_PRESETS.join(", ")}, default, or --image <file>`);
|
|
213
|
+
return { ...a, action: "set", key: "background", value: pos[1] === "default" ? DEFAULT_BACKGROUND.name : pos[1], reset: pos[1] === "default" };
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Writes <state>/settings.json (and copies the image) directly: no server needs to be running, and a running one re-reads the file per page load. */
|
|
217
|
+
export function configCommand(args) {
|
|
218
|
+
const a = parseConfigArgs(args);
|
|
219
|
+
ensureStateDir();
|
|
220
|
+
if (a.action === "get") return `${describeBackground(readSettings().background)}\n`;
|
|
221
|
+
const cur = readSettings().background;
|
|
222
|
+
const keep = a.reset ? { strength: DEFAULT_BACKGROUND.strength, blur: DEFAULT_BACKGROUND.blur } : { strength: a.strength ?? cur.strength, blur: a.blur ?? cur.blur }; // `default` resets the sliders too
|
|
223
|
+
if (a.image) {
|
|
224
|
+
let st;
|
|
225
|
+
try {
|
|
226
|
+
st = fs.statSync(a.image);
|
|
227
|
+
} catch {
|
|
228
|
+
throw new Error(`cannot read ${a.image}`);
|
|
229
|
+
}
|
|
230
|
+
if (!st.isFile()) throw new Error(`${a.image} is not a file`);
|
|
231
|
+
if (st.size > MAX_IMAGE_BYTES) throw new Error("that image is larger than 15 MB");
|
|
232
|
+
try {
|
|
233
|
+
saveCustomImage(fs.readFileSync(a.image));
|
|
234
|
+
} catch (err) {
|
|
235
|
+
if (err instanceof SettingsError) throw new Error(err.message);
|
|
236
|
+
throw err;
|
|
237
|
+
}
|
|
238
|
+
writeBackground({ kind: "custom", ...keep });
|
|
239
|
+
return `Background set to your image. It is copied as it is; the page scales it (and the copy keeps its metadata on disk). Reload the page to see it.\n`;
|
|
240
|
+
}
|
|
241
|
+
writeBackground({ kind: "preset", name: a.value, ...keep });
|
|
242
|
+
return `Background set to ${a.value}. Reload the page to see it.\n`;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const out = (text) => new Promise((r) => process.stdout.write(text, r));
|
|
246
|
+
|
|
247
|
+
const realOrSame = (file) => {
|
|
248
|
+
try {
|
|
249
|
+
return fs.realpathSync(file);
|
|
250
|
+
} catch {
|
|
251
|
+
return file;
|
|
252
|
+
}
|
|
253
|
+
};
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* Waits for the user's next Send on `file` and returns the batch (or the {status} object). Shared by `poll` and `reply --then-poll`.
|
|
257
|
+
* a = {ack, full, compact, timeout}; `quiet` skips the human line on STDERR.
|
|
258
|
+
*/
|
|
259
|
+
async function pollFor(file, a, { quiet = false } = {}) {
|
|
260
|
+
// an agent Onionskin started (in the background or in Terminal) never starts a server, and never reconnects to one: a server that stopped means its review ended
|
|
261
|
+
const bg = isAgentHolder(process.env[`${PRODUCT.envPrefix}_HOLDER`]); // the background agent, or the same agent opened in Terminal
|
|
262
|
+
const serverGone = { status: "closed", reason: "the server stopped" };
|
|
263
|
+
if (bg) {
|
|
264
|
+
if (!(await healthy())) return serverGone;
|
|
265
|
+
} else await ensureServer();
|
|
266
|
+
if (!quiet) process.stderr.write(`Waiting for the user to hit Send on ${path.basename(file)}...\n`);
|
|
267
|
+
const deadline = a.timeout ? Date.now() + a.timeout * 1000 : Infinity;
|
|
268
|
+
let ack = a.ack;
|
|
269
|
+
const realFile = realOrSame(file);
|
|
270
|
+
const holder = holderFor(realFile, process.env[`${PRODUCT.envPrefix}_HOLDER`]);
|
|
271
|
+
for (let failures = 0; ; ) {
|
|
272
|
+
const remaining = deadline - Date.now();
|
|
273
|
+
if (remaining <= 0) return { status: "timeout", waited_seconds: a.timeout, next_step: "Run the same poll command again to keep waiting." };
|
|
274
|
+
const ac = new AbortController();
|
|
275
|
+
const timer = Number.isFinite(remaining) ? setTimeout(() => ac.abort(), remaining) : null;
|
|
276
|
+
try {
|
|
277
|
+
const r = await req({ method: "GET", path: `/cli/poll?file=${encodeURIComponent(file)}${ack ? "&ack=1" : ""}${a.full ? "&full=1" : ""}${a.compact ? "&compact=1" : ""}&holder=${encodeURIComponent(holder)}`, signal: ac.signal });
|
|
278
|
+
clearTimeout(timer);
|
|
279
|
+
if (r.status !== 200) throw new Error(json(r.text).error || `server answered ${r.status}`);
|
|
280
|
+
const batch = json(r.text);
|
|
281
|
+
// remember only the holder id (so `poll --ack` renews the same lease). The ticket is printed in the batch's commands; the server keeps a copy
|
|
282
|
+
// for `status --ticket`. No per-file credential is stored here: a later poll must not be able to replace it.
|
|
283
|
+
// (not the background agent's reserved holder: the person's own agent would then load it and poll as the background agent)
|
|
284
|
+
if (batch.lease?.holder && batch.batch_id && !isAgentHolder(batch.lease.holder)) saveHolder(realFile, batch.lease.holder);
|
|
285
|
+
return batch;
|
|
286
|
+
} catch (err) {
|
|
287
|
+
clearTimeout(timer);
|
|
288
|
+
if (ac.signal.aborted) continue; // deadline reached: loop returns the timeout
|
|
289
|
+
if (/not found|no such session/i.test(err.message)) throw err;
|
|
290
|
+
if (bg) return serverGone;
|
|
291
|
+
if (++failures > 5) throw err;
|
|
292
|
+
process.stderr.write(`Lost the connection (${err.message}); reconnecting.\n`);
|
|
293
|
+
await new Promise((r) => setTimeout(r, 1000 * failures));
|
|
294
|
+
await ensureServer();
|
|
295
|
+
// the session lives in the server's state dir; re-open it so the poll can register
|
|
296
|
+
await req({ method: "POST", path: "/cli/open" }, { file });
|
|
297
|
+
ack = false;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** `done`: reports `results` for the delivery named by `lease` (a ticket string) and returns the server's answer. Shared by `done` and `reply`. */
|
|
303
|
+
async function finishBatch(file, results, lease) {
|
|
304
|
+
if (!(await healthy())) throw new Error(`the ${PRODUCT.name} server is not running`);
|
|
305
|
+
const realFile = realOrSame(file);
|
|
306
|
+
// the only credential is the ticket printed in the batch's `done` command; a delivery without it is refused, with no per-file fallback
|
|
307
|
+
const ticket = parseTicket(lease);
|
|
308
|
+
const st = json((await req({ method: "GET", path: `/cli/status?file=${encodeURIComponent(realFile)}` })).text);
|
|
309
|
+
if (!ticket && st.delivered_batch) throw new Error(`a batch is delivered for this file: pass --lease <ticket> (it is printed in the batch's done command; run \`${BIN} status <file> --ticket\` if you lost it, only the agent that polled gets it back)`);
|
|
310
|
+
const claim = ticket ? { holder: process.env[`${PRODUCT.envPrefix}_HOLDER`] || loadTicketRecord(ticket.batch_id)?.holder, lease_token: ticket.token, batch_id: ticket.batch_id } : {};
|
|
311
|
+
const r = await req({ method: "POST", path: "/cli/done" }, { file, results, ...claim });
|
|
312
|
+
const j = json(r.text);
|
|
313
|
+
if (r.status !== 200) throw new Error(j.error || "done failed");
|
|
314
|
+
return j;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
const readStdin = async () => {
|
|
318
|
+
if (process.stdin.isTTY) throw new ReplyError("no reply JSON: pass --json '<json>' or --file <path>, or pipe it on stdin");
|
|
319
|
+
const chunks = [];
|
|
320
|
+
for await (const c of process.stdin) chunks.push(c);
|
|
321
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
322
|
+
};
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
export function parseArgs(argv) {
|
|
326
|
+
const [cmd, ...rest] = argv;
|
|
327
|
+
const a = { cmd, file: "", noOpen: false, ack: false, timeout: 0, results: "", lease: "" };
|
|
328
|
+
for (let i = 0; i < rest.length; i++) {
|
|
329
|
+
const x = rest[i];
|
|
330
|
+
if (x.startsWith("--") && !(FLAGS[cmd] || []).includes(x.split("=")[0])) throw new Error(`unknown option ${x}`);
|
|
331
|
+
if (x === "--no-open") a.noOpen = true;
|
|
332
|
+
else if (x === "--ack") a.ack = true;
|
|
333
|
+
else if (x === "--full") a.full = true;
|
|
334
|
+
else if (x === "--ticket") a.ticket = true;
|
|
335
|
+
else if (x === "--summary") a.summary = true;
|
|
336
|
+
else if (x === "--slide" || x.startsWith("--slide=")) {
|
|
337
|
+
a.slide = x.includes("=") ? x.split("=")[1] : rest[++i];
|
|
338
|
+
if (!/^\d{1,10}$/.test(a.slide || "")) throw new Error("--slide wants a slide id (digits, the locator.slide_id of an anchor)");
|
|
339
|
+
}
|
|
340
|
+
else if (x === "--json" || x === "--verbose") a[x.slice(2)] = true; // doctor
|
|
341
|
+
else if (x === "--remove") a.remove = true; // setup-rewriter
|
|
342
|
+
else if (x === "--clean-old") a.cleanOld = true; // setup-rewriter, from install.sh: only removes what the older Granite download left
|
|
343
|
+
else if (x === "--model" || x.startsWith("--model=")) a.model = x.includes("=") ? x.split("=")[1] : rest[++i]; // setup-rewriter
|
|
344
|
+
else if (x === "--timeout" || x.startsWith("--timeout=")) {
|
|
345
|
+
const v = x.includes("=") ? x.split("=")[1] : rest[++i];
|
|
346
|
+
a.timeout = Number(v);
|
|
347
|
+
if (!Number.isFinite(a.timeout) || a.timeout <= 0) throw new Error("--timeout wants a number of seconds, e.g. --timeout 300");
|
|
348
|
+
} else if (x === "--results" || x.startsWith("--results=")) {
|
|
349
|
+
a.results = x.includes("=") ? x.split("=")[1] : rest[++i];
|
|
350
|
+
if (!a.results) throw new Error("--results wants a JSON file path");
|
|
351
|
+
} else if (x === "--lease" || x.startsWith("--lease=")) {
|
|
352
|
+
a.lease = x.includes("=") ? x.slice(x.indexOf("=") + 1) : rest[++i];
|
|
353
|
+
if (!parseTicket(a.lease)) throw new Error("--lease wants the value printed in the batch's commands (<batch id>:<token>)");
|
|
354
|
+
} else if (x.startsWith("-")) throw new Error(`unknown option ${x}`);
|
|
355
|
+
else if (!a.file) a.file = x;
|
|
356
|
+
else throw new Error(`unexpected argument ${x}`);
|
|
357
|
+
}
|
|
358
|
+
if (["open", "poll", "status", "done", "shapes"].includes(cmd) && !a.file) throw new Error(`Usage: ${BIN} ${cmd} <file>`);
|
|
359
|
+
if (cmd === "done" && !a.results) throw new Error(`Usage: ${BIN} done <file> --results <results.json>`);
|
|
360
|
+
return a;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
async function main() {
|
|
364
|
+
// isatty, not process.stdin.isTTY: the stdin stream is never created, so an agent started on this terminal gets it untouched.
|
|
365
|
+
// a person at a terminal gets plain words for `open` and `poll` (src/person.js); an agent or a script gets the output below, unchanged
|
|
366
|
+
const aud = pickAudience(expandShortcut(process.argv.slice(2), FLAGS), { env: process.env, stdinTTY: tty.isatty(0), stdoutTTY: tty.isatty(1) });
|
|
367
|
+
const argv = aud.argv;
|
|
368
|
+
if (!argv.length || ["-h", "--help", "help"].includes(argv[0])) return out(HELP);
|
|
369
|
+
if (asksForHelp(argv)) return out(commandHelp(argv[0])); // one path for every subcommand, before any of them parses its flags or runs
|
|
370
|
+
if (["-v", "--version", "version"].includes(argv[0])) return out(`${JSON.parse(fs.readFileSync(path.join(here, "..", "package.json"), "utf8")).version}\n`);
|
|
371
|
+
if (argv[0] === "setup") {
|
|
372
|
+
const r = await runSetup(argv.slice(1));
|
|
373
|
+
await out(r.lines.join("\n") + "\n");
|
|
374
|
+
process.exit(r.exit);
|
|
375
|
+
}
|
|
376
|
+
if (argv[0] === "setup-checker") {
|
|
377
|
+
const py = setupChecker();
|
|
378
|
+
return out(`checker ready: ${py}\n`);
|
|
379
|
+
}
|
|
380
|
+
if (argv[0] === "setup-rewriter") {
|
|
381
|
+
const a = parseArgs(argv);
|
|
382
|
+
if (a.file) throw new Error(`unexpected argument ${a.file}`);
|
|
383
|
+
if (a.cleanOld) {
|
|
384
|
+
const { cleanOldHelper } = await import("./rewriter-cleanup.js");
|
|
385
|
+
const old = cleanOldHelper();
|
|
386
|
+
// the install path: the old settings file is gone, so quick fixes that were on are off until the person turns them on again
|
|
387
|
+
return out(old.line ? `${old.removed.includes("rewriter.json") ? `${old.freed} Quick fixes are off until you run: onionskin setup-rewriter` : old.line}\n` : "");
|
|
388
|
+
}
|
|
389
|
+
const { setupRewriter } = await import("./rewriter-setup.js");
|
|
390
|
+
const r = await setupRewriter({ model: a.model, remove: !!a.remove });
|
|
391
|
+
return out(r.removed ? "quick fixes are off\n" : `quick fixes are on (${r.name})\n`);
|
|
392
|
+
}
|
|
393
|
+
if (argv[0] === "config") return out(configCommand(argv.slice(1)));
|
|
394
|
+
if (argv[0] === "doctor") {
|
|
395
|
+
const a = parseArgs(argv);
|
|
396
|
+
if (a.file) throw new Error(`unexpected argument ${a.file}`);
|
|
397
|
+
const { runDoctor, formatDoctor } = await import("./doctor.js");
|
|
398
|
+
const r = await runDoctor({ verbose: !!a.verbose });
|
|
399
|
+
await out(a.json ? JSON.stringify(r, null, 2) + "\n" : formatDoctor(r));
|
|
400
|
+
process.exit(r.ok ? 0 : 1);
|
|
401
|
+
}
|
|
402
|
+
if (argv[0] === "reply") {
|
|
403
|
+
// JSON on STDOUT only (also for failures), so an agent parses one stream; the exit code says whether the batch was finished
|
|
404
|
+
let r;
|
|
405
|
+
try {
|
|
406
|
+
r = await replyCommand(argv.slice(1), { server: { healthy, req, json }, finish: finishBatch, pollNext: (file, timeout) => pollFor(file, { ack: true, timeout, compact: true }, { quiet: true }), readStdin, emitBody: (b) => out(JSON.stringify(b) + "\n") });
|
|
407
|
+
} catch (err) {
|
|
408
|
+
const body = err instanceof ReplyError ? err.body : { code: "reply_failed", error: String(err?.message || err).slice(0, 300) };
|
|
409
|
+
await out(JSON.stringify(body) + "\n");
|
|
410
|
+
process.exit(err instanceof ReplyError ? err.exit : 1);
|
|
411
|
+
}
|
|
412
|
+
await out((r.emitted ? "" : JSON.stringify(r.body) + "\n") + (r.next ? JSON.stringify(r.next) + "\n" : ""));
|
|
413
|
+
process.exit(r.exit);
|
|
414
|
+
}
|
|
415
|
+
if (argv[0] === "apply" || argv[0] === "commit") {
|
|
416
|
+
let r;
|
|
417
|
+
try {
|
|
418
|
+
r = await (argv[0] === "apply" ? applyCommand : commitCommand)(argv.slice(1), { healthy, req, json });
|
|
419
|
+
} catch (err) {
|
|
420
|
+
if (!(err instanceof ApplyError)) throw err;
|
|
421
|
+
await out(JSON.stringify(err.report ? { ...err.report, error: err.message } : { schema: `onionskin.${argv[0]}-report/1`, status: "error", written: false, error: err.message }, null, 2) + "\n");
|
|
422
|
+
process.stderr.write(err.message + "\n");
|
|
423
|
+
process.exit(err.exit);
|
|
424
|
+
}
|
|
425
|
+
await out(JSON.stringify(argv[0] === "apply" && argv.includes("--summary") ? summarizeReport(r.report, r.exit) : r.report, null, argv.includes("--summary") ? 0 : 2) + "\n");
|
|
426
|
+
process.exit(r.exit);
|
|
427
|
+
}
|
|
428
|
+
const a = parseArgs(argv);
|
|
429
|
+
const file = a.file ? path.resolve(a.file) : "";
|
|
430
|
+
if (a.cmd === "shapes") {
|
|
431
|
+
const { readDoc } = await import("./fsutil.js");
|
|
432
|
+
const { parseDeck, listShapes } = await import("./pptx.js");
|
|
433
|
+
const real = fs.realpathSync(file);
|
|
434
|
+
if (path.extname(real).toLowerCase() !== ".pptx") throw new Error("shapes reads a .pptx file");
|
|
435
|
+
return out(JSON.stringify({ file: path.basename(real), slides: listShapes(parseDeck(readDoc(real)), a.slide ?? null) }, null, 2) + "\n");
|
|
436
|
+
}
|
|
437
|
+
if (a.cmd === "poll" && aud.person) {
|
|
438
|
+
await out(personPollText(file));
|
|
439
|
+
process.exit(2);
|
|
440
|
+
}
|
|
441
|
+
if (a.cmd === "open") {
|
|
442
|
+
await ensureServer();
|
|
443
|
+
// a person at a terminal (not --no-agent): the server starts its background agent on the file
|
|
444
|
+
const r = await req({ method: "POST", path: "/cli/open" }, aud.offer ? { file, agent: "background" } : { file });
|
|
445
|
+
const j = json(r.text);
|
|
446
|
+
if (r.status !== 200) throw new Error(j.error || "could not open that file");
|
|
447
|
+
const realPath = fs.realpathSync(file);
|
|
448
|
+
if (!a.noOpen) openBrowser(j.url);
|
|
449
|
+
if (aud.person) return out(personOpenText({ name: path.basename(realPath), url: j.url, realPath, browser: !a.noOpen, found: !!findClaude(process.env), codex: !!findCodex(process.env), offer: aud.offer }));
|
|
450
|
+
const typed = a.file;
|
|
451
|
+
await out(`Opened ${typed}${realPath !== path.resolve(typed) ? ` (real path ${realPath})` : ""}\n${j.url}\n\nTo receive the user's batch, run:\n ${BIN} poll ${shellQuote(realPath)}\nAny path form of this file (as typed or the real path) works in later commands.\nIt can run in the background (Claude Code) or in the foreground with --timeout <secs> (see the skill).\n`);
|
|
452
|
+
} else if (a.cmd === "poll") {
|
|
453
|
+
return out(JSON.stringify(await pollFor(file, a), null, 2) + "\n");
|
|
454
|
+
} else if (a.cmd === "status") {
|
|
455
|
+
if (!(await healthy())) return out(JSON.stringify({ state: "no-server" }, null, 2) + "\n");
|
|
456
|
+
const r = await req({ method: "GET", path: `/cli/status?file=${encodeURIComponent(file)}` });
|
|
457
|
+
if (r.status !== 200) throw new Error(json(r.text).error || "no such session");
|
|
458
|
+
const st = json(r.text);
|
|
459
|
+
if (a.ticket) {
|
|
460
|
+
// only the agent whose holder id matches the delivery's gets the ticket back (a second agent on the same file does not)
|
|
461
|
+
const realFile = fs.realpathSync(file);
|
|
462
|
+
const rec = st.delivered_batch ? loadTicketRecord(st.delivered_batch) : null;
|
|
463
|
+
const holder = process.env[`${PRODUCT.envPrefix}_HOLDER`] || loadHolder(realFile);
|
|
464
|
+
if (!rec) throw new Error("no batch is delivered for this file, so there is no ticket. Run poll.");
|
|
465
|
+
if (!holder || rec.holder !== holder) throw new Error("the delivered batch belongs to another poller; only that agent can read its ticket. Run poll to take your own delivery.");
|
|
466
|
+
st.ticket = `${rec.batch_id}:${rec.token}`;
|
|
467
|
+
}
|
|
468
|
+
return out(JSON.stringify(st, null, 2) + "\n");
|
|
469
|
+
} else if (a.cmd === "done") {
|
|
470
|
+
let results;
|
|
471
|
+
try {
|
|
472
|
+
results = JSON.parse(fs.readFileSync(a.results, "utf8"));
|
|
473
|
+
} catch (err) {
|
|
474
|
+
throw new Error(`cannot read ${a.results}: ${err.message}`);
|
|
475
|
+
}
|
|
476
|
+
const j = await finishBatch(file, results, a.lease);
|
|
477
|
+
if (a.summary) return out(JSON.stringify({ ok: !!j.ok, flags: (j.flags || []).map((f) => ({ code: f.code, severity: f.severity })), ...(j.checks?.notice ? { checks_notice: j.checks.notice } : {}) }) + "\n");
|
|
478
|
+
return out(JSON.stringify(j, null, 2) + "\n");
|
|
479
|
+
} else if (a.cmd === "stop") {
|
|
480
|
+
if (await healthy()) {
|
|
481
|
+
const pid = json((await req({ method: "GET", path: "/health", timeout: 1500 }).catch(() => ({ text: "" }))).text).pid;
|
|
482
|
+
await req({ method: "POST", path: "/cli/stop" }, {});
|
|
483
|
+
// the server answers first and exits a moment later: "stopped" is printed only once its process is gone (waits at most 5 s)
|
|
484
|
+
const gone = () => {
|
|
485
|
+
try {
|
|
486
|
+
process.kill(pid, 0);
|
|
487
|
+
return false;
|
|
488
|
+
} catch {
|
|
489
|
+
return true;
|
|
490
|
+
}
|
|
491
|
+
};
|
|
492
|
+
for (let i = 0; i < 100 && Number.isInteger(pid) && !gone(); i++) await new Promise((r) => setTimeout(r, 50));
|
|
493
|
+
}
|
|
494
|
+
await removeStaleSocket(); // a socket file nothing answers on is no use to anyone, and `doctor` would keep reporting it
|
|
495
|
+
return out("stopped\n");
|
|
496
|
+
} else throw new Error(`unknown command ${a.cmd}\n${HELP}`);
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
if (process.argv[1] && fs.realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
500
|
+
// ONIONSKIN_TRACE=<file>: one JSON line per command (name, start, end, exit code) for the loop benchmarks. Off unless set.
|
|
501
|
+
if (process.env.ONIONSKIN_TRACE) {
|
|
502
|
+
const start = Date.now();
|
|
503
|
+
process.on("exit", (code) => {
|
|
504
|
+
try {
|
|
505
|
+
fs.appendFileSync(process.env.ONIONSKIN_TRACE, JSON.stringify({ cmd: process.argv[2], flags: process.argv.slice(3).filter((x) => x.startsWith("--")), start, end: Date.now(), code }) + "\n");
|
|
506
|
+
} catch {}
|
|
507
|
+
});
|
|
508
|
+
}
|
|
509
|
+
main().then(
|
|
510
|
+
() => process.exit(0),
|
|
511
|
+
(err) => {
|
|
512
|
+
console.error(err.message || String(err));
|
|
513
|
+
process.exit(1);
|
|
514
|
+
}
|
|
515
|
+
);
|
|
516
|
+
}
|
package/src/constants.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// The product name and CLI binary name live here only. Rename by editing this file (and package.json "bin").
|
|
2
|
+
export const PRODUCT = {
|
|
3
|
+
name: "Onionskin",
|
|
4
|
+
bin: "onionskin",
|
|
5
|
+
stateDirName: ".onionskin",
|
|
6
|
+
envPrefix: "ONIONSKIN",
|
|
7
|
+
};
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
export const SERVER_PROTOCOL = 5; // 2: session.stage, reply, compact polls, /cli/batch-file, stop ends waiting polls; 3: question cards (/api/answer, results "asked"); 4: quick, review and suggestion routes, local history kind, merge in every format (/api/merge edits, /cli/agent-write ops), /api/export-tracked; 5: "Build my voice guide" (/api/voice/build, /api/voice/draft/discard, done takes voice_draft)
|
|
11
|
+
export const FORMATS = {
|
|
12
|
+
docx: { main: "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml", part: "/word/document.xml" },
|
|
13
|
+
xlsx: { main: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml", part: "/xl/workbook.xml" },
|
|
14
|
+
pptx: { main: "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml", part: "/ppt/presentation.xml" },
|
|
15
|
+
};
|
|
16
|
+
export const REFUSED_EXTENSIONS = new Set([".docm", ".xlsm", ".pptm"]);
|
|
17
|
+
export const env = (suffix, fallback) => process.env[`${PRODUCT.envPrefix}_${suffix}`] ?? fallback;
|
|
18
|
+
|
|
19
|
+
/** The largest document that is opened, sent, written or checked. Enforced by size BEFORE the bytes are read. */
|
|
20
|
+
export const MAX_DOC_BYTES = 200 * 1024 * 1024;
|