onionskin-cli 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/CHANGELOG.md +144 -0
  2. package/INSTALL.md +25 -0
  3. package/LICENSE +21 -0
  4. package/NOTICE +49 -0
  5. package/README.md +148 -2
  6. package/docs/contracts/batch.schema.json +839 -0
  7. package/docs/contracts/history.schema.json +126 -0
  8. package/docs/contracts/ops.schema.json +541 -0
  9. package/package.json +67 -4
  10. package/scripts/checker/check.py +411 -0
  11. package/scripts/checker/requirements.txt +5 -0
  12. package/scripts/install-check.mjs +9 -0
  13. package/scripts/requirements.txt +5 -0
  14. package/scripts/rewriter/apple/main.swift +135 -0
  15. package/scripts/rewriter/apple/onionskin-fm +0 -0
  16. package/scripts/rewriter/apple/onionskin-fm.json +6 -0
  17. package/skills/onionskin/SKILL.md +117 -0
  18. package/skills/onionskin/reference/batch.md +94 -0
  19. package/skills/onionskin/reference/formats.md +15 -0
  20. package/skills/onionskin/reference/ops.md +253 -0
  21. package/skills/onionskin/reference/troubleshooting.md +73 -0
  22. package/skills/onionskin/reference/voice-guide.md +86 -0
  23. package/skills/onionskin/voice.example.md +51 -0
  24. package/src/agent-detect.js +149 -0
  25. package/src/agent-events.js +159 -0
  26. package/src/agent-prompt.js +27 -0
  27. package/src/agent-runner.js +593 -0
  28. package/src/analyze.js +17 -0
  29. package/src/anchors.js +190 -0
  30. package/src/apply.js +387 -0
  31. package/src/auth.js +130 -0
  32. package/src/batch.js +322 -0
  33. package/src/check-worker.js +8 -0
  34. package/src/checker.js +293 -0
  35. package/src/cli.js +516 -0
  36. package/src/constants.js +20 -0
  37. package/src/diff.js +267 -0
  38. package/src/doctor.js +288 -0
  39. package/src/docx.js +438 -0
  40. package/src/fmt.js +30 -0
  41. package/src/fsutil.js +348 -0
  42. package/src/history-worker.js +16 -0
  43. package/src/history.js +576 -0
  44. package/src/lease.js +79 -0
  45. package/src/local.js +242 -0
  46. package/src/merge-pptx.js +198 -0
  47. package/src/merge-xlsx.js +453 -0
  48. package/src/merge.js +410 -0
  49. package/src/offload.js +34 -0
  50. package/src/ops/common.js +48 -0
  51. package/src/ops/docx-table.js +323 -0
  52. package/src/ops/docx.js +503 -0
  53. package/src/ops/engine.js +41 -0
  54. package/src/ops/pptx.js +336 -0
  55. package/src/ops/run.js +115 -0
  56. package/src/ops/runs.js +127 -0
  57. package/src/ops/schema.js +109 -0
  58. package/src/ops/xlsx.js +277 -0
  59. package/src/package.js +189 -0
  60. package/src/paths.js +64 -0
  61. package/src/person.js +66 -0
  62. package/src/pptx.js +194 -0
  63. package/src/question.js +47 -0
  64. package/src/quick-plan.js +107 -0
  65. package/src/quick.js +164 -0
  66. package/src/redline-check.js +251 -0
  67. package/src/redline-worker.js +29 -0
  68. package/src/redline.js +438 -0
  69. package/src/reply.js +410 -0
  70. package/src/review.js +274 -0
  71. package/src/rewrite-check.js +1014 -0
  72. package/src/rewriter-cleanup.js +105 -0
  73. package/src/rewriter-setup.js +104 -0
  74. package/src/rewriter.js +396 -0
  75. package/src/sanitize.js +42 -0
  76. package/src/sentence-span.js +25 -0
  77. package/src/server-entry.js +13 -0
  78. package/src/server.js +576 -0
  79. package/src/session.js +1912 -0
  80. package/src/settings.js +161 -0
  81. package/src/setup.js +199 -0
  82. package/src/stamp-words.js +10 -0
  83. package/src/stamps.js +59 -0
  84. package/src/style.js +110 -0
  85. package/src/suggest-reply.js +84 -0
  86. package/src/suggest.js +261 -0
  87. package/src/text.js +31 -0
  88. package/src/tracked-words.js +43 -0
  89. package/src/voice-guide.js +182 -0
  90. package/src/voice-learn.js +314 -0
  91. package/src/voice-sample-worker.js +95 -0
  92. package/src/voice-samples.js +329 -0
  93. package/src/voice-store.js +305 -0
  94. package/src/voice-worker.js +28 -0
  95. package/src/voice.js +297 -0
  96. package/src/xlsx.js +454 -0
  97. package/src/xml-tree.js +118 -0
  98. package/src/xml.js +127 -0
  99. package/src/zip-write.js +74 -0
  100. package/src/zip.js +88 -0
  101. package/vendor/engine/DocViewer-BZLXUcxJ.js +15137 -0
  102. package/vendor/engine/THIRD_PARTY_LICENSES.txt +79 -0
  103. package/vendor/engine/collab-BVynXMqc.js +2591 -0
  104. package/vendor/engine/collab.js +2 -0
  105. package/vendor/engine/core.js +4 -0
  106. package/vendor/engine/default-worker-DogNT09A.js +35625 -0
  107. package/vendor/engine/embed.js +107 -0
  108. package/vendor/engine/index.js +5 -0
  109. package/vendor/engine/office-engine.embed.js +184 -0
  110. package/vendor/engine/office-engine.worker.js +36030 -0
  111. package/vendor/engine/xlsx-ops-SYAv6V0f.js +939 -0
  112. package/vendor/engine-node/LICENSE +21 -0
  113. package/vendor/engine-node/engine-node.mjs +46618 -0
  114. package/vendor/engine.lock.json +26 -0
  115. package/web/dist/assets/index-BUtofdtr.js +197 -0
  116. package/web/dist/assets/index-Dfizlg0i.css +1 -0
  117. package/web/dist/index.html +14 -0
@@ -0,0 +1,161 @@
1
+ // Per-machine settings: <state>/settings.json (0600) and the one custom background image <state>/backgrounds/custom.<ext> (0600).
2
+ // The page never names a path: it uploads bytes, the server sniffs the type from the magic bytes and picks the file name itself.
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import { ensureStateDir, stateDir, sub, writeStateFile } from "./paths.js";
6
+
7
+ export const BG_PRESETS = ["pages", "paper", "aurora", "studio", "midnight"];
8
+ export const DEFAULT_BACKGROUND = { kind: "preset", name: "paper", strength: 60, blur: true };
9
+ export const AGENT_CLIS = ["claude"]; // the background agent is Claude Code only in this build
10
+ export const DEFAULT_AGENT = { cli: "claude", model: "sonnet", show: false };
11
+ export const MAX_IMAGE_BYTES = 15 * 1024 * 1024;
12
+ const EXT = { png: ".png", jpeg: ".jpg", webp: ".webp" };
13
+ const MIME = { png: "image/png", jpeg: "image/jpeg", webp: "image/webp" };
14
+
15
+ export class SettingsError extends Error {
16
+ constructor(status, message) {
17
+ super(message);
18
+ this.status = status;
19
+ }
20
+ }
21
+
22
+ /** "png" | "jpeg" | "webp" from the leading bytes, or null. The file name and the claimed type are never trusted. */
23
+ export function sniffImage(buf) {
24
+ if (!Buffer.isBuffer(buf) || buf.length < 12) return null;
25
+ if (buf.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return "png";
26
+ if (buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return "jpeg";
27
+ if (buf.toString("latin1", 0, 4) === "RIFF" && buf.toString("latin1", 8, 12) === "WEBP") return "webp";
28
+ return null;
29
+ }
30
+
31
+ const bgDir = () => path.join(stateDir(), "backgrounds");
32
+ function customFile() {
33
+ for (const e of ["png", "jpeg", "webp"]) {
34
+ try {
35
+ const f = path.join(bgDir(), `custom${EXT[e]}`);
36
+ const st = fs.lstatSync(f);
37
+ if (st.isFile()) return { file: f, type: e, version: Math.floor(st.mtimeMs) };
38
+ } catch {}
39
+ }
40
+ return null;
41
+ }
42
+ export const hasCustom = () => !!customFile();
43
+
44
+ /** Whatever is in `input`, reduced to a valid {kind,name,strength,blur}. Unknown or out-of-range parts fall back to the default; nothing is thrown. */
45
+ export function normalizeBackground(input) {
46
+ const d = DEFAULT_BACKGROUND;
47
+ const b = input && typeof input === "object" ? input : {};
48
+ const kind = b.kind === "custom" ? "custom" : "preset";
49
+ const n = Number(b.strength);
50
+ return {
51
+ kind,
52
+ name: kind === "custom" ? "custom" : BG_PRESETS.includes(b.name) ? b.name : d.name,
53
+ strength: Number.isFinite(n) ? Math.min(100, Math.max(0, Math.round(n))) : d.strength,
54
+ blur: typeof b.blur === "boolean" ? b.blur : d.blur,
55
+ };
56
+ }
57
+
58
+ /** Whatever is in `input`, reduced to a valid {cli,model,show}: a value outside the fixed lists falls back to the default. */
59
+ export function normalizeAgent(input) {
60
+ const a = input && typeof input === "object" ? input : {};
61
+ const d = DEFAULT_AGENT;
62
+ return {
63
+ cli: AGENT_CLIS.includes(a.cli) ? a.cli : d.cli,
64
+ model: typeof a.model === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(a.model) ? a.model : d.model,
65
+ show: typeof a.show === "boolean" ? a.show : d.show,
66
+ };
67
+ }
68
+
69
+ function rawSettings() {
70
+ try {
71
+ const j = JSON.parse(fs.readFileSync(path.join(stateDir(), "settings.json"), "utf8"));
72
+ return j && typeof j === "object" && !Array.isArray(j) ? j : {};
73
+ } catch {
74
+ return {};
75
+ }
76
+ }
77
+ /** One settings file holds every group: a write replaces its own group and keeps the rest. */
78
+ function writeGroup(name, value) {
79
+ ensureStateDir();
80
+ writeStateFile(path.join(stateDir(), "settings.json"), JSON.stringify({ ...rawSettings(), [name]: value }, null, 2) + "\n");
81
+ }
82
+
83
+ /** Read per call (the CLI may have changed the file). A missing, broken or custom-without-image file reads as the default. */
84
+ export function readSettings() {
85
+ let raw = {};
86
+ try {
87
+ raw = JSON.parse(fs.readFileSync(path.join(stateDir(), "settings.json"), "utf8"));
88
+ } catch {}
89
+ let background = normalizeBackground(raw?.background);
90
+ if (background.kind === "custom" && !hasCustom()) background = { ...DEFAULT_BACKGROUND, strength: background.strength, blur: background.blur };
91
+ const c = customFile();
92
+ return { background, customVersion: c ? c.version : null, agent: normalizeAgent(raw?.agent) };
93
+ }
94
+
95
+ /** Validates (strictly: a bad value is an error here, unlike a read) and stores the background choice. */
96
+ export function writeBackground(input) {
97
+ const b = input && typeof input === "object" ? input : null;
98
+ if (!b) throw new SettingsError(400, "background must be an object");
99
+ if (b.kind !== "preset" && b.kind !== "custom") throw new SettingsError(400, "background.kind must be preset or custom");
100
+ if (b.kind === "preset" && !BG_PRESETS.includes(b.name)) throw new SettingsError(400, `background.name must be one of ${BG_PRESETS.join(", ")}`);
101
+ if (b.strength !== undefined && !(Number.isFinite(b.strength) && b.strength >= 0 && b.strength <= 100)) throw new SettingsError(400, "background.strength must be 0 to 100");
102
+ if (b.blur !== undefined && typeof b.blur !== "boolean") throw new SettingsError(400, "background.blur must be true or false");
103
+ if (b.kind === "custom" && !hasCustom()) throw new SettingsError(409, "no custom image is stored");
104
+ writeGroup("background", normalizeBackground(b));
105
+ return readSettings();
106
+ }
107
+
108
+ /** Validates (strictly) and stores a change to the background agent's settings: any of cli, model, show. The other settings are kept. */
109
+ export function writeAgent(input) {
110
+ const a = input && typeof input === "object" ? input : null;
111
+ if (!a) throw new SettingsError(400, "agent must be an object");
112
+ if (a.cli !== undefined && !AGENT_CLIS.includes(a.cli)) throw new SettingsError(400, `agent.cli must be one of ${AGENT_CLIS.join(", ")}`);
113
+ if (a.model !== undefined && normalizeAgent({ model: a.model }).model !== a.model) throw new SettingsError(400, "agent.model must be a model name such as sonnet");
114
+ if (a.show !== undefined && typeof a.show !== "boolean") throw new SettingsError(400, "agent.show must be true or false");
115
+ writeGroup("agent", normalizeAgent({ ...rawSettings().agent, ...a }));
116
+ return readSettings();
117
+ }
118
+
119
+ /** Stores the bytes as the one custom image (the older one is removed). Returns the settings. */
120
+ export function saveCustomImage(bytes) {
121
+ if (!Buffer.isBuffer(bytes) || !bytes.length) throw new SettingsError(400, "no image data");
122
+ if (bytes.length > MAX_IMAGE_BYTES) throw new SettingsError(413, "image is larger than 15 MB");
123
+ const type = sniffImage(bytes);
124
+ if (!type) throw new SettingsError(415, "not a PNG, JPEG or WebP image");
125
+ ensureStateDir();
126
+ const dir = sub("backgrounds");
127
+ removeFiles(dir);
128
+ writeStateFile(path.join(dir, `custom${EXT[type]}`), bytes);
129
+ return readSettings();
130
+ }
131
+ function removeFiles(dir) {
132
+ for (const e of Object.values(EXT)) fs.rmSync(path.join(dir, `custom${e}`), { force: true });
133
+ }
134
+
135
+ /** Deletes the custom image; a custom choice falls back to the default preset. */
136
+ export function removeCustomImage() {
137
+ removeFiles(bgDir());
138
+ const cur = readSettings().background;
139
+ const raw = (() => {
140
+ try {
141
+ return JSON.parse(fs.readFileSync(path.join(stateDir(), "settings.json"), "utf8"));
142
+ } catch {
143
+ return null;
144
+ }
145
+ })();
146
+ if (raw?.background?.kind === "custom") writeBackground({ ...DEFAULT_BACKGROUND, strength: cur.strength, blur: cur.blur });
147
+ return readSettings();
148
+ }
149
+
150
+ /** { bytes, mime, version } of the stored image, or null. */
151
+ export function readCustomImage() {
152
+ const c = customFile();
153
+ if (!c) return null;
154
+ const bytes = fs.readFileSync(c.file);
155
+ return { bytes, mime: MIME[sniffImage(bytes) || c.type], version: c.version };
156
+ }
157
+
158
+ /** The CLI's `config background`: same validation, the file is copied as it is (the page scales it when it is shown). */
159
+ export function describeBackground(b) {
160
+ return b.kind === "custom" ? `custom image (strength ${b.strength}, blur ${b.blur ? "on" : "off"})` : `${b.name}${b.name === DEFAULT_BACKGROUND.name ? " (default)" : ""}`;
161
+ }
package/src/setup.js ADDED
@@ -0,0 +1,199 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import readline from "node:readline";
6
+ import { fileURLToPath } from "node:url";
7
+ import { PRODUCT } from "./constants.js";
8
+ import { findPython } from "./checker.js";
9
+
10
+ const here = path.dirname(fileURLToPath(import.meta.url));
11
+ export const SKILL_SOURCE = path.join(here, "..", "skills", PRODUCT.bin);
12
+ const MIN_NODE = 22;
13
+
14
+ /** Where agents read skills: Claude Code and the shared agents folder (Codex and others). Relative to the home directory. */
15
+ export const skillTargets = (home) => [path.join(home, ".claude", "skills", PRODUCT.bin), path.join(home, ".agents", "skills", PRODUCT.bin)];
16
+
17
+ /**
18
+ * `{ id, dir }` (the plugin id `onionskin@<marketplace>` and its installed folder) when the Claude Code plugin route already gives
19
+ * Claude Code this skill for every project: an install record with scope "user" in ~/.claude/plugins/installed_plugins.json that
20
+ * ~/.claude/settings.json does not turn off. Then a ~/.claude/skills/onionskin folder would make the same skill show twice. Anything
21
+ * unreadable or unexpected returns null, so setup installs the folder as before. Reads only the default ~/.claude, like skillTargets
22
+ * (a CLAUDE_CONFIG_DIR elsewhere is not looked at). The Codex plugin is not handled: ~/.agents/skills is shared by other agents too,
23
+ * so that folder is always installed.
24
+ */
25
+ export function claudePluginProvides(home) {
26
+ try {
27
+ const rec = JSON.parse(fs.readFileSync(path.join(home, ".claude", "plugins", "installed_plugins.json"), "utf8"));
28
+ let enabled = {};
29
+ try {
30
+ enabled = JSON.parse(fs.readFileSync(path.join(home, ".claude", "settings.json"), "utf8")).enabledPlugins || {};
31
+ } catch {}
32
+ for (const [id, installs] of Object.entries(rec?.plugins || {})) {
33
+ if (id.split("@")[0] !== PRODUCT.bin || enabled[id] === false || !Array.isArray(installs)) continue;
34
+ const user = installs.find((i) => i?.scope === "user");
35
+ if (user) return { id, dir: typeof user.installPath === "string" ? user.installPath : null };
36
+ }
37
+ } catch {}
38
+ return null;
39
+ }
40
+
41
+ export function parseSetupArgs(rest) {
42
+ const a = { dryRun: false, force: false, uninstall: false };
43
+ for (const x of rest) {
44
+ if (x === "--dry-run") a.dryRun = true;
45
+ else if (x === "--force") a.force = true;
46
+ else if (x === "--uninstall") a.uninstall = true;
47
+ else if (x.startsWith("-")) throw new Error(`unknown option ${x}`);
48
+ else throw new Error(`unexpected argument ${x}`);
49
+ }
50
+ if (a.uninstall && a.force) throw new Error("--force has no meaning with --uninstall");
51
+ return a;
52
+ }
53
+
54
+ /** The person's own voice guide beside the skill (src/voice-store.js reads it like a .env): never copied to an installed skill folder, never compared. */
55
+ const PERSONAL = "voice.md";
56
+
57
+ /** Every regular file under `dir` as [relative path, sha256], sorted. Symlinks and special files are not followed (a skill folder holds plain files). */
58
+ function tree(dir) {
59
+ const out = [];
60
+ const walk = (d, rel) => {
61
+ for (const e of fs.readdirSync(d, { withFileTypes: true }).sort((x, y) => (x.name < y.name ? -1 : 1))) {
62
+ const p = path.join(d, e.name);
63
+ const r = rel ? `${rel}/${e.name}` : e.name;
64
+ if (r === PERSONAL) continue;
65
+ if (e.isDirectory()) walk(p, r);
66
+ else if (e.isFile()) out.push([r, crypto.createHash("sha256").update(fs.readFileSync(p)).digest("hex")]);
67
+ else out.push([r, `non-regular:${e.isSymbolicLink() ? "symlink" : "special"}`]);
68
+ }
69
+ };
70
+ walk(dir, "");
71
+ return out;
72
+ }
73
+ const same = (a, b) => JSON.stringify(tree(a)) === JSON.stringify(tree(b));
74
+ /** true when the installed skill folder `dir` is byte-identical to `source` (default: this app's copy) */
75
+ export const skillMatches = (dir, source = SKILL_SOURCE) => same(dir, source);
76
+
77
+ /** true when `dir` is a skill folder of this tool (its SKILL.md frontmatter says `name: onionskin`) */
78
+ function isOurs(dir) {
79
+ try {
80
+ const head = fs.readFileSync(path.join(dir, "SKILL.md"), "utf8").slice(0, 400);
81
+ return new RegExp(`^name:\\s*${PRODUCT.bin}\\s*$`, "m").test(head);
82
+ } catch {
83
+ return false;
84
+ }
85
+ }
86
+
87
+ function copyTree(src, dest, top = true) {
88
+ fs.mkdirSync(dest, { recursive: true, mode: 0o755 });
89
+ for (const e of fs.readdirSync(src, { withFileTypes: true })) {
90
+ if (top && e.name === PERSONAL) continue;
91
+ const s = path.join(src, e.name);
92
+ const d = path.join(dest, e.name);
93
+ if (e.isDirectory()) copyTree(s, d, false);
94
+ else if (e.isFile()) fs.copyFileSync(s, d);
95
+ }
96
+ }
97
+
98
+ async function askYesNo(question) {
99
+ if (!process.stdin.isTTY) return false;
100
+ const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
101
+ const answer = await new Promise((r) => rl.question(`${question} [y/N] `, r));
102
+ rl.close();
103
+ return /^y(es)?$/i.test(answer.trim());
104
+ }
105
+
106
+ /**
107
+ * `onionskin setup`. Copies the skill folder to each target. Returns {exit, lines}; never writes outside `home`'s two skill folders.
108
+ * `ask(question) -> bool` is consulted before replacing a different existing folder (never when --force).
109
+ */
110
+ export async function runSetup(rest, { home = os.homedir(), source = SKILL_SOURCE, ask = askYesNo, nodeVersion = process.versions.node, python = findPython } = {}) {
111
+ const a = parseSetupArgs(rest);
112
+ const lines = [];
113
+ const say = (s) => lines.push(s);
114
+ let exit = 0;
115
+ const dry = a.dryRun ? "[dry run] " : "";
116
+
117
+ const major = Number(nodeVersion.split(".")[0]);
118
+ if (major < MIN_NODE) {
119
+ say(`node ${nodeVersion}: too old, ${PRODUCT.name} needs node >= ${MIN_NODE}`);
120
+ exit = 1;
121
+ } else say(`node ${nodeVersion}: ok (needs >= ${MIN_NODE})`);
122
+
123
+ if (!a.uninstall && !isOurs(source)) {
124
+ say(`cannot find the skill folder to install at ${source}`);
125
+ return { exit: 1, lines };
126
+ }
127
+
128
+ const plugin = a.uninstall ? null : claudePluginProvides(home)?.id;
129
+ for (const target of skillTargets(home)) {
130
+ let st = null;
131
+ try {
132
+ st = fs.lstatSync(target);
133
+ } catch {}
134
+ if (plugin && target === skillTargets(home)[0]) {
135
+ // the Claude Code plugin already gives Claude Code this skill: a second copy here would show twice. An identical copy is removed;
136
+ // a different one only with --force or a yes, like any replacement below.
137
+ const twice = `the Claude Code plugin ${plugin} provides this skill, so this copy would show twice`;
138
+ if (!st) say(`${target}: skipped (the Claude Code plugin ${plugin} provides this skill)`);
139
+ else if (st.isSymbolicLink() || !st.isDirectory() || !isOurs(target)) say(`${target}: left alone (not a ${PRODUCT.bin} skill folder this tool installed; ${twice})`);
140
+ else if (!same(source, target) && !a.force && (a.dryRun || !(await ask(`${target} differs from this version and ${twice}. Remove it?`)))) {
141
+ say(`${dry}${target}: kept (it differs from this version; ${twice}). Remove it with: ${PRODUCT.bin} setup --force`);
142
+ } else {
143
+ if (!a.dryRun) fs.rmSync(target, { recursive: true });
144
+ say(`${dry}${target}: removed (${twice})`);
145
+ }
146
+ continue;
147
+ }
148
+ if (a.uninstall) {
149
+ if (!st) say(`${target}: not installed`);
150
+ else if (st.isSymbolicLink() || !st.isDirectory() || !isOurs(target)) {
151
+ say(`${target}: left alone (not a ${PRODUCT.bin} skill folder this tool installed)`);
152
+ exit = 1;
153
+ } else {
154
+ if (!a.dryRun) fs.rmSync(target, { recursive: true });
155
+ say(`${dry}${target}: removed`);
156
+ }
157
+ continue;
158
+ }
159
+ if (st && (st.isSymbolicLink() || !st.isDirectory())) {
160
+ say(`${target}: left alone (it exists and is not a plain folder; move it away and run setup again)`);
161
+ exit = 1;
162
+ continue;
163
+ }
164
+ if (st && same(source, target)) {
165
+ say(`${target}: already up to date`);
166
+ continue;
167
+ }
168
+ if (st && !a.force) {
169
+ if (a.dryRun) {
170
+ say(`${dry}${target}: exists with different content; would ask before replacing it (--force skips the question). STALE: refresh with: ${PRODUCT.bin} setup --force`);
171
+ continue;
172
+ }
173
+ if (!(await ask(`${target} exists with different content. Replace it?`))) {
174
+ say(`${target}: kept (different version; answer yes or use --force to replace)`);
175
+ say(`${target}: STALE: this install differs from the skill shipped with this ${PRODUCT.name}, so the agent may follow an outdated protocol. Refresh it with: ${PRODUCT.bin} setup --force`);
176
+ exit = 1;
177
+ continue;
178
+ }
179
+ }
180
+ if (!a.dryRun) {
181
+ // copy next to the target, then swap, so a failed copy never leaves a half-installed skill
182
+ const parent = path.dirname(target);
183
+ fs.mkdirSync(parent, { recursive: true });
184
+ const tmp = path.join(parent, `.${PRODUCT.bin}.tmp-${process.pid}`);
185
+ fs.rmSync(tmp, { recursive: true, force: true });
186
+ copyTree(source, tmp);
187
+ if (st) fs.rmSync(target, { recursive: true });
188
+ fs.renameSync(tmp, target);
189
+ }
190
+ say(`${dry}${target}: ${st ? "replaced" : "installed"}`);
191
+ }
192
+
193
+ if (!a.uninstall) {
194
+ const py = python();
195
+ if (py) say(`deeper checker: ready (${py})`);
196
+ else say(`deeper checker: not set up yet. The built-in checks always run; the deeper ones are turned on from the review panel, or with \`${PRODUCT.bin} setup-checker\` (uses the network once)`);
197
+ }
198
+ return { exit, lines };
199
+ }
@@ -0,0 +1,10 @@
1
+ // The server's copy of the built-in stamps' words, from web/src/stamps.js (src/ cannot import the page's source: only web/dist is
2
+ // packaged). test/stamp-words.test.js checks that both stay the same. A comment whose words equal one of these was a stamp tap.
3
+ export const STAMP_WORDS = {
4
+ shorter: "Make this shorter. Keep the meaning.",
5
+ friendlier: "Make this sound friendlier. Keep the meaning.",
6
+ grammar: "Fix the grammar, spelling and punctuation here. Change nothing else.",
7
+ translate: "Translate this into {language}.",
8
+ };
9
+ export const BUILT_IN_STAMP_WORDS = Object.values(STAMP_WORDS);
10
+ export const STAMP_LANGUAGES = ["Spanish", "French", "German", "Portuguese", "Italian", "Chinese", "Japanese", "Korean"];
package/src/stamps.js ADDED
@@ -0,0 +1,59 @@
1
+ // Own stamps: <state>/stamps.json (0600), a list of {label, words} the person typed. Per machine, like settings.json.
2
+ // The words are sent later as the text of an ordinary comment. Onionskin writes this file only from a guarded browser POST. A process running as the same OS user could still write it directly; the reader checks the shape, not the origin.
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import { ensureStateDir, stateDir, writeStateFile } from "./paths.js";
6
+ import { SettingsError } from "./settings.js";
7
+
8
+ export const MAX_STAMPS = 8;
9
+ export const MAX_LABEL = 24;
10
+ export const MAX_WORDS = 300;
11
+ // C0 and C1 controls (this includes line breaks and tabs), and the bidirectional marks that can make text read in a different order than it is stored
12
+ const HIDDEN = /[\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/gu;
13
+ const LINE_BREAK = /[\r\n\u2028\u2029]/u;
14
+ const len = (s) => Array.from(s).length;
15
+
16
+ const clean = (s) => s.replace(HIDDEN, "").trim();
17
+
18
+ /** One stamp, strictly: a wrong shape, an unknown field or a length outside the cap is a 400 and nothing is trimmed to fit. */
19
+ function checkStamp(s) {
20
+ if (!s || typeof s !== "object" || Array.isArray(s)) throw new SettingsError(400, "Each stamp needs a name and words.");
21
+ if (Object.keys(s).some((k) => k !== "label" && k !== "words")) throw new SettingsError(400, "A stamp has only a name and words.");
22
+ if (typeof s.label !== "string" || typeof s.words !== "string") throw new SettingsError(400, "Each stamp needs a name and words.");
23
+ if (LINE_BREAK.test(s.label)) throw new SettingsError(400, "A stamp name has to fit on one line.");
24
+ const label = clean(s.label);
25
+ const words = clean(s.words.replace(/[\r\n\t\u2028\u2029]+/gu, " "));
26
+ if (!label || len(label) > MAX_LABEL) throw new SettingsError(400, `A stamp name needs 1 to ${MAX_LABEL} characters.`);
27
+ if (!words) throw new SettingsError(400, "A stamp needs words to send.");
28
+ if (len(words) > MAX_WORDS) throw new SettingsError(400, `That is too long. Keep it under ${MAX_WORDS} characters.`);
29
+ return { label, words };
30
+ }
31
+
32
+ /** Read per call. A missing or broken file, or a bad entry in it, reads as nothing: a hand-edited file can never reach the page unchecked. */
33
+ export function readStamps() {
34
+ let raw;
35
+ try {
36
+ raw = JSON.parse(fs.readFileSync(path.join(stateDir(), "stamps.json"), "utf8"));
37
+ } catch {
38
+ return [];
39
+ }
40
+ if (!Array.isArray(raw?.stamps)) return [];
41
+ const out = [];
42
+ for (const s of raw.stamps) {
43
+ try {
44
+ out.push(checkStamp(s));
45
+ } catch {}
46
+ if (out.length === MAX_STAMPS) break;
47
+ }
48
+ return out;
49
+ }
50
+
51
+ /** Validates the whole list (all or nothing) and stores it. Returns the stored list. */
52
+ export function writeStamps(list) {
53
+ if (!Array.isArray(list)) throw new SettingsError(400, "stamps must be a list");
54
+ if (list.length > MAX_STAMPS) throw new SettingsError(400, `You can keep up to ${MAX_STAMPS} stamps.`);
55
+ const stamps = list.map(checkStamp);
56
+ ensureStateDir();
57
+ writeStateFile(path.join(stateDir(), "stamps.json"), JSON.stringify({ stamps }, null, 2) + "\n");
58
+ return stamps;
59
+ }
package/src/style.js ADDED
@@ -0,0 +1,110 @@
1
+ // Writing preferences: <state>/style.json (0600), per machine. A closed set of fixed sentences plus the person's own typed words.
2
+ // The note sent to the agent is built here from those two things only: nothing from a document, a diff or an agent's text ever reaches it.
3
+ // Guard: this module keeps its own copy of what it last wrote (or first read) and re-reads the file on every read. A file changed by
4
+ // anything else while the server runs is put back from that copy and counted (styleChangedOutside). Ceiling: the copy lives in memory,
5
+ // so a change made while no server runs is trusted by the next server's first read.
6
+ import fs from "node:fs";
7
+ import path from "node:path";
8
+ import { ensureStateDir, stateDir, writeStateFile } from "./paths.js";
9
+ import { userText } from "./sanitize.js";
10
+ import { SettingsError } from "./settings.js";
11
+
12
+ export const MAX_WORDS = 280;
13
+
14
+ /** The eight fixed preferences. `label` is what the person sees, `sentence` is what the agent gets. */
15
+ export const TRAITS = [
16
+ { id: "short", label: "Keep it short", sentence: "Keep new text short." },
17
+ { id: "plain", label: "Plain words", sentence: "Use plain, everyday words." },
18
+ { id: "formal", label: "More formal", sentence: "Use a formal tone." },
19
+ { id: "relaxed", label: "More relaxed", sentence: "Use a relaxed, friendly tone." },
20
+ { id: "minimal", label: "Change as little as possible", sentence: "Change as little of my wording as possible." },
21
+ { id: "format", label: "Leave formatting alone", sentence: "Do not change formatting unless I ask." },
22
+ { id: "short_sentences", label: "Short sentences", sentence: "Use short sentences." },
23
+ { id: "no_exclaim", label: "No exclamation marks", sentence: "Do not use exclamation marks." },
24
+ ];
25
+ const IDS = TRAITS.map((t) => t.id);
26
+ const EXCLUSIVE = ["formal", "relaxed"]; // switch each other off: the last one chosen stays
27
+
28
+ // a SettingsError, so the server answers it as a 400 with no new error path
29
+ export class StyleError extends SettingsError {
30
+ constructor(message) {
31
+ super(400, message);
32
+ }
33
+ }
34
+
35
+ const file = () => path.join(stateDir(), "style.json");
36
+
37
+ /** Known ids once each, formal/relaxed reduced to the last one given. */
38
+ function cleanTraits(list) {
39
+ const out = [];
40
+ for (const id of list) if (IDS.includes(id) && !out.includes(id)) out.push(id);
41
+ const last = [...out].reverse().find((id) => EXCLUSIVE.includes(id));
42
+ return out.filter((id) => !EXCLUSIVE.includes(id) || id === last);
43
+ }
44
+
45
+ /** A missing or broken file reads as empty; an unknown id in it is dropped. */
46
+ function parse(text) {
47
+ let raw = null;
48
+ try {
49
+ raw = JSON.parse(text);
50
+ } catch {}
51
+ const traits = cleanTraits(Array.isArray(raw?.traits) ? raw.traits.filter((x) => typeof x === "string") : []);
52
+ const words = typeof raw?.words === "string" ? userText(raw.words, Infinity).replace(/\s+/g, " ").trim().slice(0, MAX_WORDS) : "";
53
+ return { traits, words };
54
+ }
55
+
56
+ let known = null; // {raw, style}: the exact file text this server last wrote or first read (null = no file), and what it parses to
57
+ let outside = 0; // outside changes found and put back since this server started
58
+
59
+ /** Re-reads the file. The first read is trusted; after that, any other text (a missing file included) is put back from the copy. */
60
+ function check() {
61
+ let raw = null;
62
+ try {
63
+ raw = fs.readFileSync(file(), "utf8");
64
+ } catch {}
65
+ if (!known) known = { raw, style: parse(raw) };
66
+ else if (raw !== known.raw) {
67
+ outside++;
68
+ try {
69
+ if (known.raw === null) fs.rmSync(file(), { force: true });
70
+ else writeStateFile(file(), known.raw);
71
+ } catch {} // the copy is still what counts, even when the file cannot be put back
72
+ }
73
+ return { traits: [...known.style.traits], words: known.style.words };
74
+ }
75
+
76
+ /** Read per call, through the guard: what this server last wrote, never a file someone else changed. */
77
+ export const readStyle = () => check();
78
+
79
+ /**
80
+ * Checks the file now (putting it back if it changed) and returns how many outside changes this server has found and undone since it
81
+ * started. It never resets: a caller keeps the number from when a batch was delivered and compares it at done.
82
+ */
83
+ export function styleChangedOutside() {
84
+ check();
85
+ return outside;
86
+ }
87
+
88
+ /** Strict (length is counted after stripping and collapsing, never cut first): an unknown preference id, a non-array or more than 280 characters is a 400 and nothing is written. */
89
+ export function writeStyle(input) {
90
+ const b = input && typeof input === "object" && !Array.isArray(input) ? input : null;
91
+ check(); // an outside change is counted and undone even when this write is refused
92
+ if (!b) throw new StyleError("style must be an object");
93
+ if (!Array.isArray(b.traits) || b.traits.some((id) => typeof id !== "string" || !IDS.includes(id))) throw new StyleError(`traits must be a list of: ${IDS.join(", ")}`);
94
+ if (b.words !== undefined && typeof b.words !== "string") throw new StyleError("words must be text");
95
+ const words = userText(b.words ?? "", Infinity).replace(/\s+/g, " ").trim();
96
+ if ([...words].length > MAX_WORDS) throw new StyleError(`words can be at most ${MAX_WORDS} characters`);
97
+ ensureStateDir();
98
+ const style = { traits: cleanTraits(b.traits), words };
99
+ const raw = JSON.stringify(style, null, 2) + "\n";
100
+ writeStateFile(file(), raw);
101
+ known = { raw, style }; // only after the write succeeded
102
+ return { traits: [...style.traits], words };
103
+ }
104
+
105
+ /** The text for `instructions.style_note`, or "" when nothing is chosen. About 540 characters at most by construction (cap 700). */
106
+ export function styleNote(style = readStyle()) {
107
+ const fixed = TRAITS.filter((t) => style.traits.includes(t.id)).map((t) => t.sentence);
108
+ if (!fixed.length && !style.words) return "";
109
+ return ["How I like text written:", ...fixed, ...(style.words ? [`Also: ${style.words}`] : [])].join(" ");
110
+ }
@@ -0,0 +1,84 @@
1
+ // Quick fixes (idea 10 option A), the pure half of "Use this": where in the file a suggestion may be written, and the one reply the
2
+ // local runner sends for it. No I/O and no session state: src/session.js (useSuggestion) and src/suggest.js both call these.
3
+ //
4
+ // What is written is only the changed middle of the sentence: the shortest span from the first change to the last, widened to whole words
5
+ // until it occurs exactly once in the paragraph (or text box) it sits in, otherwise the whole sentence. The engine refuses a find that
6
+ // occurs more than once, so a sentence that repeats word for word in its paragraph is refused and nothing is written.
7
+
8
+ /** The comment's result note and the run's summary (docs/contracts/routes.md). Fixed words: never the model's text. */
9
+ export const USE_NOTE = "Rewritten on this Mac. Nothing left this Mac.";
10
+ export const USE_SUMMARY = "Rewrote 1 sentence on this Mac. Nothing left this Mac.";
11
+
12
+ const isSpace = (ch) => /\s/u.test(ch);
13
+
14
+ /** Occurrences of `q` in `text`, overlapping ones counted (stricter than the engine's own count). */
15
+ function count(text, q) {
16
+ let n = 0;
17
+ for (let i = text.indexOf(q); i >= 0; i = text.indexOf(q, i + 1)) n++;
18
+ return n;
19
+ }
20
+
21
+ /**
22
+ * {find, replace} that turns `before` into `after` when `find` is swapped for `replace`, with `find` occurring once in `unitText` (the
23
+ * paragraph or text box `before` sits in); null when no such span exists (no change, or the sentence itself repeats in `unitText`).
24
+ */
25
+ export function changedMiddle(before, after, unitText = before) {
26
+ if (typeof before !== "string" || typeof after !== "string" || !before || before === after) return null;
27
+ let pre = 0;
28
+ while (pre < before.length && pre < after.length && before[pre] === after[pre]) pre++;
29
+ let suf = 0;
30
+ const room = Math.min(before.length, after.length) - pre;
31
+ while (suf < room && before[before.length - 1 - suf] === after[after.length - 1 - suf]) suf++;
32
+ let s = pre;
33
+ let e = before.length - suf; // the end of the span in `before`; the same distance from the end in `after`
34
+ // whole words: never split a word (or a surrogate pair, which is never a space)
35
+ while (s > 0 && !isSpace(before[s - 1])) s--;
36
+ while (e < before.length && !isSpace(before[e])) e++;
37
+ for (;;) {
38
+ const find = before.slice(s, e);
39
+ if (find.trim() && count(unitText, find) === 1) {
40
+ const replace = after.slice(s, after.length - (before.length - e));
41
+ if (before.slice(0, s) + replace + before.slice(e) !== after) return null; // cannot happen; refuse rather than write something else
42
+ return { find, replace };
43
+ }
44
+ if (s === 0 && e === before.length) return null;
45
+ // one more word on each side
46
+ while (s > 0 && isSpace(before[s - 1])) s--;
47
+ while (s > 0 && !isSpace(before[s - 1])) s--;
48
+ while (e < before.length && isSpace(before[e])) e++;
49
+ while (e < before.length && !isSpace(before[e])) e++;
50
+ }
51
+ }
52
+
53
+ /**
54
+ * Where a selection sits in `units` (readUnits of the bytes at hand), for a durable anchor built from them. {ok: true, text, start, end} with
55
+ * `text` the whole paragraph or text box and [start, end) the selection in it, or {ok: false, code}: "not_here" (the sentence is not at that place in these bytes), "protected",
56
+ * "not_eligible" (a table cell, a nested Word paragraph, a slide table, picture or the slide itself).
57
+ */
58
+ export function placeOf(units, d, quote) {
59
+ if (!d) return { ok: false, code: "not_here" };
60
+ if (d.protected) return { ok: false, code: "protected" };
61
+ let text = null;
62
+ if (units.format === "docx") {
63
+ if (!Array.isArray(d.path) || d.path.length > 2) return { ok: false, code: "not_eligible" };
64
+ text = units.paragraphs[d.ordinal]?.text ?? null;
65
+ } else if (units.format === "pptx") {
66
+ if (d.kind !== "shape" || d.cell) return { ok: false, code: "not_eligible" };
67
+ const slide = units.deck.slides[d.slideIndex];
68
+ const same = (slide?.shapes || []).filter((x) => x.id === d.shapeId);
69
+ text = (same.find((x) => x.ordinal === d.ordinal) || (same.length === 1 ? same[0] : null))?.text ?? null;
70
+ } else return { ok: false, code: "not_eligible" };
71
+ if (typeof text !== "string" || !Number.isInteger(d.start) || text.slice(d.start, d.end) !== quote) return { ok: false, code: "not_here" };
72
+ return { ok: true, text, start: d.start, end: d.end };
73
+ }
74
+
75
+ /**
76
+ * The reply JSON (`onionskin reply`) for one stored suggestion on the comment `commentId`: one find and replace on that comment's anchor,
77
+ * which `reply` turns into replace_text (Word) or replace_text_in_shape (PowerPoint) with the anchor's text hash as `expect`. `record` is the
78
+ * server's stored suggestion ({before, after}); nothing here comes from the page. Null when no safe span exists.
79
+ */
80
+ export function buildUseReply(record, commentId, unitText) {
81
+ const m = changedMiddle(record?.before, record?.after, unitText);
82
+ if (!m) return null;
83
+ return { summary: USE_SUMMARY, replies: [{ comment: commentId, find: m.find, replace: m.replace, note: USE_NOTE }] };
84
+ }