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
package/src/diff.js ADDED
@@ -0,0 +1,267 @@
1
+ // A small word-level text diff for the History sidebar. No dependencies, pure functions.
2
+ //
3
+ // diffText(a, b) -> { ops, level } the text changed; level is "word" or "sentence"
4
+ // | { identical: true, ops: [] } the same string
5
+ // | { formatting_only: true, ops: [] } only whitespace differs
6
+ // | { too_large: true } more than HARD_CAP_TOKENS on one side: nothing is computed
7
+ // ops are compact: ["=", text] unchanged (trimmed to CONTEXT_WORDS words on each side of a change), ["-", text] removed,
8
+ // ["+", text] added, ["…"] where unchanged text was left out. Concatenating the "=" and "-" texts (and "…" as nothing) gives the old
9
+ // text; "=" and "+" the new one, apart from the trimmed parts. Callers pass text that was already sanitized: ops are slices of it.
10
+ //
11
+ // Ceilings: Myers O(ND) with D <= MAX_D, so a pair that differs in more than MAX_D tokens is reported as one removed + one added block.
12
+ // A changed middle over WORD_LIMIT tokens on either side is diffed by sentence first, and each changed sentence block is refined by
13
+ // word only when it is small. Tokens are words, whitespace runs, single punctuation marks, and single CJK characters.
14
+
15
+ const CONTEXT_WORDS = 6;
16
+ const WORD_LIMIT = 2000;
17
+ export const HARD_CAP_TOKENS = 60_000;
18
+ const MAX_D = 2000;
19
+ const CJK = "\\p{Script=Han}|\\p{Script=Hiragana}|\\p{Script=Katakana}";
20
+ const TOKEN = new RegExp(`(?:${CJK})|(?:(?!${CJK})[\\p{L}\\p{N}\\p{M}])+(?:['’](?:(?!${CJK})[\\p{L}\\p{N}\\p{M}])+)*|\\s+|[^\\s]`, "gu");
21
+ const IS_WORD = new RegExp(`^(?:${CJK}|[\\p{L}\\p{N}\\p{M}])`, "u");
22
+ const IS_CJK = new RegExp(`^(?:${CJK})$`, "u");
23
+ const SENTENCE = /[^.!?。!?\n]*(?:[.!?。!?]+|\n|$)\s*/gu;
24
+
25
+ export const tokenize = (s) => s.match(TOKEN) || [];
26
+ const sentences = (s) => (s.match(SENTENCE) || []).filter(Boolean);
27
+
28
+ /** Myers shortest edit script over two token arrays: [["=", i, j] ... ] collapsed to runs {t, a0, a1, b0, b1}; null when D exceeds maxD. */
29
+ function myers(a, b, maxD) {
30
+ const n = a.length;
31
+ const m = b.length;
32
+ const off = maxD + 1;
33
+ const v = new Int32Array(2 * maxD + 3);
34
+ const trace = [];
35
+ let found = -1;
36
+ for (let d = 0; d <= maxD && found < 0; d++) {
37
+ trace.push(v.slice(off - d, off + d + 1));
38
+ for (let k = -d; k <= d; k += 2) {
39
+ let x = k === -d || (k !== d && v[off + k - 1] < v[off + k + 1]) ? v[off + k + 1] : v[off + k - 1] + 1;
40
+ let y = x - k;
41
+ while (x < n && y < m && a[x] === b[y]) (x++, y++);
42
+ v[off + k] = x;
43
+ if (x >= n && y >= m) {
44
+ found = d;
45
+ break;
46
+ }
47
+ }
48
+ }
49
+ if (found < 0) return null;
50
+ const edits = []; // reversed: "=", "-" (a index) or "+" (b index)
51
+ let x = n;
52
+ let y = m;
53
+ for (let d = found; d >= 0; d--) {
54
+ const vv = trace[d];
55
+ const k = x - y;
56
+ let prevK;
57
+ if (d === 0) prevK = 0;
58
+ else prevK = k === -d || (k !== d && vv[k - 1 + d] < vv[k + 1 + d]) ? k + 1 : k - 1;
59
+ const prevX = d === 0 ? 0 : vv[prevK + d];
60
+ const prevY = prevX - prevK;
61
+ while (x > prevX && y > prevY) {
62
+ edits.push(["=", x - 1, y - 1]);
63
+ x--;
64
+ y--;
65
+ }
66
+ if (d > 0) {
67
+ if (prevK === k + 1) edits.push(["+", -1, prevY]);
68
+ else edits.push(["-", prevX, -1]);
69
+ x = prevX;
70
+ y = prevY;
71
+ }
72
+ }
73
+ return edits.reverse();
74
+ }
75
+
76
+ /** Token arrays -> raw ops [[type, text]] (adjacent equal types merged). Common prefix and suffix are cut first: they cost nothing. */
77
+ function diffTokens(a, b) {
78
+ let p = 0;
79
+ while (p < a.length && p < b.length && a[p] === b[p]) p++;
80
+ let s = 0;
81
+ while (s < a.length - p && s < b.length - p && a[a.length - 1 - s] === b[b.length - 1 - s]) s++;
82
+ const A = a.slice(p, a.length - s);
83
+ const B = b.slice(p, b.length - s);
84
+ const out = [];
85
+ const push = (t, text) => {
86
+ if (!text) return;
87
+ if (out.length && out[out.length - 1][0] === t) out[out.length - 1][1] += text;
88
+ else out.push([t, text]);
89
+ };
90
+ push("=", a.slice(0, p).join(""));
91
+ if (A.length || B.length) {
92
+ const script = A.length && B.length ? myers(A, B, MAX_D) : null;
93
+ if (!script) {
94
+ push("-", A.join(""));
95
+ push("+", B.join(""));
96
+ } else {
97
+ // within one change block deletions come before insertions
98
+ let dels = "";
99
+ let ins = "";
100
+ const flush = () => {
101
+ push("-", dels);
102
+ push("+", ins);
103
+ dels = ins = "";
104
+ };
105
+ for (const [t, i, j] of script) {
106
+ if (t === "-") dels += A[i];
107
+ else if (t === "+") ins += B[j];
108
+ else (flush(), push("=", A[i]));
109
+ }
110
+ flush();
111
+ }
112
+ }
113
+ push("=", a.slice(a.length - s).join(""));
114
+ return out;
115
+ }
116
+
117
+ /** Sentence-level diff; a changed block (removed + added run) is refined by word when both sides are small. */
118
+ function diffSentences(a, b) {
119
+ const sa = sentences(a);
120
+ const sb = sentences(b);
121
+ const raw = diffTokens(sa, sb);
122
+ const out = [];
123
+ let coarse = false;
124
+ for (let i = 0; i < raw.length; i++) {
125
+ const cur = raw[i];
126
+ const next = raw[i + 1];
127
+ if (cur[0] === "-" && next?.[0] === "+") {
128
+ const ta = tokenize(cur[1]);
129
+ const tb = tokenize(next[1]);
130
+ if (ta.length <= WORD_LIMIT && tb.length <= WORD_LIMIT) out.push(...diffTokens(ta, tb));
131
+ else (out.push(cur, next), (coarse = true));
132
+ i++;
133
+ } else {
134
+ if (cur[0] !== "=") coarse = true;
135
+ out.push(cur);
136
+ }
137
+ }
138
+ return { raw: out, coarse };
139
+ }
140
+
141
+ const wordWeight = (tok) => (IS_CJK.test(tok) ? 1 / 3 : IS_WORD.test(tok) ? 1 : 0);
142
+
143
+ /** The last (or first) `n` words' worth of tokens of an unchanged run. */
144
+ function edge(text, n, fromEnd) {
145
+ const toks = tokenize(text);
146
+ let w = 0;
147
+ let i = fromEnd ? toks.length : 0;
148
+ while (fromEnd ? i > 0 : i < toks.length) {
149
+ const t = toks[fromEnd ? i - 1 : i];
150
+ const nw = w + wordWeight(t);
151
+ if (nw > n) break;
152
+ w = nw;
153
+ i += fromEnd ? -1 : 1;
154
+ }
155
+ return fromEnd ? { kept: toks.slice(i).join(""), cut: i > 0 } : { kept: toks.slice(0, i).join(""), cut: i < toks.length };
156
+ }
157
+
158
+ /** Merge a lone whitespace "=" between two changes into both sides, so "a b" -> "c d" reads as one replaced phrase. */
159
+ function mergeChanges(raw) {
160
+ let ops = raw.map((o) => [o[0], o[1]]);
161
+ // pass 2: [change][whitespace =][change] -> one block with the whitespace on both sides
162
+ let again = true;
163
+ while (again) {
164
+ again = false;
165
+ const res = [];
166
+ for (let i = 0; i < ops.length; i++) {
167
+ const op = ops[i];
168
+ if (op[0] === "=" && /^\s+$/.test(op[1]) && res.length && res[res.length - 1][0] !== "=" && ops[i + 1] && ops[i + 1][0] !== "=") {
169
+ res.push(["-", op[1]], ["+", op[1]]);
170
+ again = true;
171
+ } else res.push(op);
172
+ }
173
+ ops = res;
174
+ }
175
+ // group every change block into one "-" run followed by one "+" run
176
+ const grouped = [];
177
+ for (let i = 0; i < ops.length; ) {
178
+ if (ops[i][0] === "=") {
179
+ grouped.push(ops[i++]);
180
+ continue;
181
+ }
182
+ let del = "";
183
+ let add = "";
184
+ while (i < ops.length && ops[i][0] !== "=") {
185
+ if (ops[i][0] === "-") del += ops[i][1];
186
+ else add += ops[i][1];
187
+ i++;
188
+ }
189
+ if (del) grouped.push(["-", del]);
190
+ if (add) grouped.push(["+", add]);
191
+ }
192
+ return grouped;
193
+ }
194
+
195
+ /** Keep at most `context` words of unchanged text next to a change; the rest becomes ["…"]. */
196
+ function trim(ops, context) {
197
+ const out = [];
198
+ ops.forEach((op, i) => {
199
+ if (op[0] !== "=") return out.push(op);
200
+ const first = i === 0;
201
+ const last = i === ops.length - 1;
202
+ const total = tokenize(op[1]).reduce((w, t) => w + wordWeight(t), 0);
203
+ if (total <= (first || last ? context : context * 2)) return out.push(op);
204
+ // the cut side loses its whitespace: the ellipsis stands where the text was left out
205
+ if (first) out.push(["…"], ["=", edge(op[1], context, true).kept.trimStart()]);
206
+ else if (last) out.push(["=", edge(op[1], context, false).kept.trimEnd()], ["…"]);
207
+ else out.push(["=", edge(op[1], context, false).kept.trimEnd()], ["…"], ["=", edge(op[1], context, true).kept.trimStart()]);
208
+ });
209
+ return out;
210
+ }
211
+
212
+ export function diffText(a, b, { context = CONTEXT_WORDS } = {}) {
213
+ a = String(a ?? "");
214
+ b = String(b ?? "");
215
+ if (a === b) return { identical: true, ops: [] };
216
+ if (a.replace(/\s+/g, "") === b.replace(/\s+/g, "")) return { formatting_only: true, ops: [] };
217
+ const ta = tokenize(a);
218
+ const tb = tokenize(b);
219
+ if (ta.length > HARD_CAP_TOKENS || tb.length > HARD_CAP_TOKENS) return { too_large: true };
220
+ let p = 0;
221
+ while (p < ta.length && p < tb.length && ta[p] === tb[p]) p++;
222
+ let s = 0;
223
+ while (s < ta.length - p && s < tb.length - p && ta[ta.length - 1 - s] === tb[tb.length - 1 - s]) s++;
224
+ const middle = Math.max(ta.length - p - s, tb.length - p - s);
225
+ let raw;
226
+ let level = "word";
227
+ if (middle > WORD_LIMIT) {
228
+ const r = diffSentences(a, b);
229
+ raw = r.raw;
230
+ level = "sentence";
231
+ } else raw = diffTokens(ta, tb);
232
+ return { ops: trim(mergeChanges(raw), context), level };
233
+ }
234
+
235
+
236
+ /**
237
+ * The full edit script between two raw strings, for rebuilding both sides (the tracked-changes copy): nothing is trimmed, sanitized or
238
+ * skipped. Returns [[type, text]] with types "=", "-", "+": the "=" and "-" texts concatenated give `a` exactly, "=" and "+" give `b`.
239
+ * Same tokenizer and change grouping as diffText; a changed middle over WORD_LIMIT tokens goes by sentence first; past HARD_CAP_TOKENS,
240
+ * or when Myers gives up (MAX_D), the changed middle is one removal plus one addition.
241
+ */
242
+ export function diffRaw(a, b) {
243
+ a = String(a ?? "");
244
+ b = String(b ?? "");
245
+ if (a === b) return a ? [["=", a]] : [];
246
+ const ta = tokenize(a);
247
+ const tb = tokenize(b);
248
+ let raw;
249
+ if (ta.length > HARD_CAP_TOKENS || tb.length > HARD_CAP_TOKENS) {
250
+ let p = 0;
251
+ while (p < a.length && p < b.length && a[p] === b[p]) p++;
252
+ let s = 0;
253
+ while (s < a.length - p && s < b.length - p && a[a.length - 1 - s] === b[b.length - 1 - s]) s++;
254
+ raw = [["=", a.slice(0, p)], ["-", a.slice(p, a.length - s)], ["+", b.slice(p, b.length - s)], ["=", a.slice(a.length - s)]].filter((o) => o[1]);
255
+ } else {
256
+ let p = 0;
257
+ while (p < ta.length && p < tb.length && ta[p] === tb[p]) p++;
258
+ let s = 0;
259
+ while (s < ta.length - p && s < tb.length - p && ta[ta.length - 1 - s] === tb[tb.length - 1 - s]) s++;
260
+ raw = Math.max(ta.length - p - s, tb.length - p - s) > WORD_LIMIT ? diffSentences(a, b).raw : diffTokens(ta, tb);
261
+ }
262
+ const ops = mergeChanges(raw);
263
+ // the tokenizer covers every character, but a rebuild that does not give both sides back exactly must never be used
264
+ const side = (keep) => ops.filter((o) => o[0] === "=" || o[0] === keep).map((o) => o[1]).join("");
265
+ if (side("-") !== a || side("+") !== b) return [["-", a], ["+", b]].filter((o) => o[1]);
266
+ return ops;
267
+ }
package/src/doctor.js ADDED
@@ -0,0 +1,288 @@
1
+ // `onionskin doctor`: one line per check, OK / MISSING / NOTE, written to be pasted into a bug report.
2
+ // MISSING on a `required` check makes the command exit 1; optional checks (Python checker, LibreOffice, ...) only ever NOTE.
3
+ // Never prints tokens, tickets, cookies, document names or document content; the home directory is shown as `~`.
4
+ import { spawnSync } from "node:child_process";
5
+ import crypto from "node:crypto";
6
+ import fs from "node:fs";
7
+ import http from "node:http";
8
+ import os from "node:os";
9
+ import path from "node:path";
10
+ import { fileURLToPath } from "node:url";
11
+ import { PRODUCT, SERVER_PROTOCOL } from "./constants.js";
12
+ import { describeBackground, normalizeBackground } from "./settings.js";
13
+ import { PROBE_REASONS, appleHelperState, appleStateLine, rewriterStatus } from "./rewriter.js";
14
+ import { probeHelper } from "./rewriter-setup.js";
15
+ import { SKILL_SOURCE, claudePluginProvides, skillMatches, skillTargets } from "./setup.js";
16
+
17
+ const here = path.dirname(fileURLToPath(import.meta.url));
18
+ const BIN = PRODUCT.bin;
19
+ const DEFAULT_APP_ROOT = path.resolve(here, "..");
20
+ const PATH_FIX = `echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc (then open a new Terminal window)`;
21
+ const REINSTALL_FIX = "sh install.sh (from the unzipped onionskin folder)";
22
+
23
+ const sha = (f) => crypto.createHash("sha256").update(fs.readFileSync(f)).digest("hex");
24
+ function hashTree(dir) {
25
+ const out = {};
26
+ const walk = (d, rel) => {
27
+ for (const e of fs.readdirSync(d, { withFileTypes: true })) {
28
+ const r = rel ? `${rel}/${e.name}` : e.name;
29
+ if (e.isDirectory()) walk(path.join(d, e.name), r);
30
+ else if (e.isFile()) out[r] = sha(path.join(d, e.name));
31
+ }
32
+ };
33
+ walk(dir, "");
34
+ return out;
35
+ }
36
+
37
+ /** Compares vendor/engine and vendor/engine-node with the hashes in vendor/engine.lock.json (what `npm run verify:vendor` checks, minus the build-time entry hash). */
38
+ function verifyVendor(appRoot) {
39
+ const lockPath = path.join(appRoot, "vendor", "engine.lock.json");
40
+ if (!fs.existsSync(lockPath)) return { present: false, problems: [] };
41
+ const problems = [];
42
+ const lock = JSON.parse(fs.readFileSync(lockPath, "utf8"));
43
+ const cmp = (label, dir, files) => {
44
+ const now = fs.existsSync(dir) ? hashTree(dir) : {};
45
+ for (const [f, h] of Object.entries(files || {})) if (now[f] !== h) problems.push(`${now[f] ? "changed" : "missing"} ${label}/${f}`);
46
+ for (const f of Object.keys(now)) if (!(f in (files || {}))) problems.push(`extra ${label}/${f}`);
47
+ };
48
+ cmp("vendor/engine", path.join(appRoot, "vendor", "engine"), lock.files);
49
+ if (lock.node) cmp("vendor/engine-node", path.join(appRoot, "vendor", "engine-node"), lock.node.files);
50
+ return { present: true, problems };
51
+ }
52
+
53
+ function probeServer(sock) {
54
+ return new Promise((resolve) => {
55
+ if (!fs.existsSync(sock)) return resolve({ state: "none" });
56
+ const r = http.get({ socketPath: sock, path: "/health", timeout: 1500 }, (res) => {
57
+ const chunks = [];
58
+ res.on("data", (c) => chunks.push(c));
59
+ res.on("end", () => {
60
+ try {
61
+ const j = JSON.parse(Buffer.concat(chunks).toString("utf8"));
62
+ resolve(res.statusCode === 200 && j.protocol === SERVER_PROTOCOL ? { state: "up", sessions: Number.isInteger(j.sessions) ? j.sessions : null } : { state: "wrong" });
63
+ } catch {
64
+ resolve({ state: "wrong" });
65
+ }
66
+ });
67
+ });
68
+ r.on("timeout", () => (r.destroy(), resolve({ state: "dead" })));
69
+ r.on("error", () => resolve({ state: "dead" }));
70
+ });
71
+ }
72
+
73
+ function defaultBrowserId() {
74
+ if (process.platform !== "darwin") return null;
75
+ const r = spawnSync("defaults", ["read", "com.apple.LaunchServices/com.apple.launchservices.secure", "LSHandlers"], { encoding: "utf8", timeout: 4000 });
76
+ if (r.status !== 0) return null;
77
+ for (const block of r.stdout.split(/\n\s*\{/)) {
78
+ const id = /LSHandlerURLScheme = https;/.test(block) ? [...block.matchAll(/LSHandlerRoleAll = "?([^";\s]+)/g)].map((m) => m[1]).filter((x) => x !== "-").pop() : null;
79
+ if (id && id !== "-") return id;
80
+ }
81
+ return null;
82
+ }
83
+
84
+ const run = (cmd, args, env) => {
85
+ try {
86
+ const r = spawnSync(cmd, args, { encoding: "utf8", timeout: 8000, env });
87
+ return r.status === 0 ? (r.stdout || r.stderr).trim() : null;
88
+ } catch {
89
+ return null;
90
+ }
91
+ };
92
+
93
+ /**
94
+ * @param {object} o home, appRoot, env, verbose: where to look. probes: injectable `defaultBrowser()` and `freeBytes(dir)` for tests.
95
+ * @returns {Promise<{schema:string, ok:boolean, version:string|null, checks:Array<{status:string,name:string,detail:string,fix?:string,required:boolean}>}>}
96
+ */
97
+ export async function runDoctor(o = {}) {
98
+ const home = o.home || os.homedir();
99
+ const appRoot = o.appRoot || DEFAULT_APP_ROOT;
100
+ const env = o.env || process.env;
101
+ const state = env[`${PRODUCT.envPrefix}_STATE_DIR`] ? path.resolve(env[`${PRODUCT.envPrefix}_STATE_DIR`]) : path.join(home, PRODUCT.stateDirName);
102
+ const homes = [...new Set([home, (() => { try { return fs.realpathSync(home); } catch { return home; } })()])].sort((a, b) => b.length - a.length);
103
+ const show = (s) => {
104
+ let t = String(s);
105
+ for (const h of homes) t = t.split(h).join("~");
106
+ return t;
107
+ };
108
+ const checks = [];
109
+ const add = (status, name, detail = "", { required = false, fix } = {}) => checks.push({ status, name: show(name), detail: show(detail), ...(fix && status !== "OK" ? { fix: show(fix) } : {}), required });
110
+ const whichAll = (name) => {
111
+ const out = [];
112
+ for (const d of (env.PATH || "").split(":")) {
113
+ if (!d) continue;
114
+ const p = path.join(d, name);
115
+ try {
116
+ fs.accessSync(p, fs.constants.X_OK);
117
+ if (fs.statSync(p).isFile()) out.push(p);
118
+ } catch {}
119
+ }
120
+ return out;
121
+ };
122
+ const which = (name) => whichAll(name)[0] || null;
123
+
124
+ let version = null;
125
+ try {
126
+ version = JSON.parse(fs.readFileSync(path.join(appRoot, "package.json"), "utf8")).version;
127
+ } catch {}
128
+
129
+ // system
130
+ add("NOTE", "platform", `${process.platform} ${os.arch()}, macOS ${process.platform === "darwin" ? run("sw_vers", ["-productVersion"], env) || "unknown" : "n/a"}`);
131
+ const major = Number(process.versions.node.split(".")[0]);
132
+ add(major >= 22 ? "OK" : "MISSING", "node", `v${process.versions.node}${major >= 22 ? "" : " (needs 22 or newer)"}`, { required: true, fix: "install Node 22 or newer: brew install node (or https://nodejs.org/en/download)" });
133
+ const nodeOnPath = which("node");
134
+ add(nodeOnPath ? "OK" : "MISSING", "node on PATH", nodeOnPath || "the launcher needs `node` on PATH", { required: true, fix: "install Node (see above), then open a new Terminal window" });
135
+
136
+ // app
137
+ add(version ? "OK" : "MISSING", "this app copy", version ? `version ${version} at ${appRoot}` : `no package.json at ${appRoot}`, { required: true, fix: REINSTALL_FIX });
138
+ add(fs.existsSync(path.join(appRoot, "web", "dist", "index.html")) ? "OK" : "MISSING", "web app (web/dist)", "", { required: true, fix: REINSTALL_FIX });
139
+ add(fs.existsSync(path.join(appRoot, "vendor", "engine-node", "engine-node.mjs")) && fs.existsSync(path.join(appRoot, "vendor", "engine", "index.js")) ? "OK" : "MISSING", "document engine (vendor/)", "", { required: true, fix: REINSTALL_FIX });
140
+ try {
141
+ const v = verifyVendor(appRoot);
142
+ if (!v.present) add("NOTE", "app file integrity", "no vendor lock in this copy; nothing to compare");
143
+ else add(v.problems.length ? "MISSING" : "OK", "app file integrity", v.problems.length ? `${v.problems.length} file(s) differ from vendor/engine.lock.json: ${v.problems.slice(0, 3).join(", ")}` : "vendor files match vendor/engine.lock.json", { required: true, fix: "sh install.sh (reinstall from the original zip)" });
144
+ } catch (err) {
145
+ add("MISSING", "app file integrity", `could not verify: ${err.message}`, { required: true, fix: "sh install.sh (reinstall from the original zip)" });
146
+ }
147
+
148
+ // launcher
149
+ const found = which(BIN);
150
+ const launcher = found || path.join(home, ".local", "bin", BIN);
151
+ if (fs.existsSync(launcher)) {
152
+ const target = ((fs.readFileSync(launcher, "utf8").match(/exec node "([^"]+)"/)) || [])[1];
153
+ // the installer writes `exec node "<app>/src/cli.js"`; any other launcher (a symlink, npm link) is judged by whether it runs
154
+ add(!target || fs.existsSync(target) ? "OK" : "MISSING", "launcher", `${launcher}${target ? ` -> ${target}` : " (custom launcher)"}`, { required: true, fix: REINSTALL_FIX });
155
+ const v = run(launcher, ["--version"], env);
156
+ add(v ? "OK" : "MISSING", `${BIN} --version`, v || "the launcher did not run", { required: true, fix: REINSTALL_FIX });
157
+ } else add("MISSING", "launcher", `${launcher} not found`, { required: true, fix: REINSTALL_FIX });
158
+ // Which copy is answering, and any other onionskin command that could answer instead (npm's global one and the installer's
159
+ // ~/.local/bin one, for example): the first on PATH wins, so two copies can drift apart. Compared by the cli.js each one runs.
160
+ const real = (p) => {
161
+ try {
162
+ return fs.realpathSync(p);
163
+ } catch {
164
+ return p;
165
+ }
166
+ };
167
+ const runs = (p) => {
168
+ try {
169
+ const t = (fs.readFileSync(p, "utf8").slice(0, 400).match(/exec node "([^"]+)"/) || [])[1]; // the installer's 2-line launcher
170
+ return real(t || p);
171
+ } catch {
172
+ return real(p);
173
+ }
174
+ };
175
+ const self = real(path.join(appRoot, "src", "cli.js"));
176
+ add("NOTE", "running from", self);
177
+ const others = new Map();
178
+ for (const p of [...whichAll(BIN), path.join(home, ".local", "bin", BIN)]) if (fs.existsSync(p) && runs(p) !== self && !others.has(runs(p))) others.set(runs(p), p);
179
+ for (const [t, p] of others) add("NOTE", `another ${BIN}`, `${p} runs ${t}, a different copy`, { fix: "keep one copy: remove the npm one with npm uninstall -g onionskin-cli, or the installer one with sh ~/.onionskin/app/*/install.sh --uninstall" });
180
+ const launcherDir = path.dirname(launcher);
181
+ const onPath = (env.PATH || "").split(":").includes(launcherDir);
182
+ add(onPath ? "OK" : "NOTE", `${launcherDir} on PATH`, onPath ? "yes" : "no: Terminal cannot find the command by name", { fix: PATH_FIX });
183
+
184
+ // skills
185
+ const plugin = claudePluginProvides(home);
186
+ const appSkill = appRoot === DEFAULT_APP_ROOT ? SKILL_SOURCE : path.join(appRoot, "skills", BIN);
187
+ for (const [label, dir] of [["Claude Code", skillTargets(home)[0]], ["Codex / agents", skillTargets(home)[1]]]) {
188
+ if (plugin && label === "Claude Code") {
189
+ // the same rule `setup` uses: with the plugin installed, the folder is left out on purpose. The plugin's copy follows the
190
+ // repository, the app's copy follows the release, so a difference between them is only a NOTE.
191
+ const id = plugin.id;
192
+ if (fs.existsSync(dir)) add("NOTE", `skill for ${label}`, `the Claude Code plugin ${id} provides it and ${dir} is a second copy, so it can show twice`, { fix: `${BIN} setup --force` });
193
+ else {
194
+ let match = false;
195
+ try {
196
+ match = !!plugin.dir && skillMatches(plugin.dir, appSkill);
197
+ } catch {}
198
+ if (match) add("OK", `skill for ${label}`, `provided by the Claude Code plugin ${id}, the same as this app's copy`);
199
+ else add("NOTE", `skill for ${label}`, `provided by the Claude Code plugin ${id}, which differs from this app's copy`, { fix: `claude plugin marketplace update ${id.split("@")[1]}, then claude plugin update ${id}, or reinstall Onionskin` });
200
+ }
201
+ continue;
202
+ }
203
+ if (!fs.existsSync(dir)) {
204
+ add("MISSING", `skill for ${label}`, `${dir} not found`, { required: true, fix: `${BIN} setup` });
205
+ continue;
206
+ }
207
+ let same = false;
208
+ try {
209
+ same = skillMatches(dir, appSkill);
210
+ } catch {}
211
+ add(same ? "OK" : "MISSING", `skill for ${label}`, `${dir} ${same ? "matches this app's copy" : "differs from this app's copy"}`, { required: true, fix: `${BIN} setup --force` });
212
+ }
213
+ add(which("claude") ? "OK" : "NOTE", "Claude Code command (claude)", which("claude") || "not on PATH here (fine if you use the desktop app or Codex)");
214
+ add(which("codex") ? "OK" : "NOTE", "Codex command (codex)", which("codex") || "not on PATH here");
215
+
216
+ // optional deeper check
217
+ const py = env[`${PRODUCT.envPrefix}_PYTHON`] || path.join(state, "venv", "bin", "python");
218
+ if (fs.existsSync(py)) {
219
+ const ok = run(py, ["-c", "import lxml, docx, openpyxl, pptx, defusedxml; print('libraries import')"], env);
220
+ add(ok ? "OK" : "NOTE", "deeper check (Python venv)", `${py}: ${ok || "present but the libraries do not import"}`, { fix: `${BIN} setup-checker` });
221
+ } else add("NOTE", "deeper check (Python venv)", "not set up (optional)", { fix: `${BIN} setup-checker (needs Python 3.10+ and internet once)` });
222
+ // quick fixes: what the setup says, then whether Apple's model can be used here (decided without starting the helper; only a helper
223
+ // that passed every check is asked, with --probe; tests pass o.probes.apple for appleHelperState and o.probes.appleProbe)
224
+ const rw = rewriterStatus(state, o.probes?.apple);
225
+ const apple = appleHelperState(o.probes?.apple);
226
+ let unavailable = apple.ok ? null : apple.reason;
227
+ if (apple.ok && (rw.on ? rw.backend === "apple" : true)) {
228
+ const pr = await (o.probes?.appleProbe || probeHelper)(apple.bin);
229
+ if (pr.status !== 0) unavailable = PROBE_REASONS[/^unavailable: (\w+)/.exec(String(pr.stdout || "").trim())?.[1]] ?? "no_answer";
230
+ }
231
+ const line = unavailable === "no_answer" ? "Apple's built-in model did not say whether it is available." : unavailable ? appleStateLine(unavailable) : null;
232
+ if (rw.on && !(rw.backend === "apple" && line)) add("OK", "quick fixes", `on (${rw.name}): spelling and grammar fixes on one sentence`);
233
+ else if (line) add("NOTE", "quick fixes", `${rw.on ? "set up, but not available now" : "off"}: ${line} Fix grammar goes to the agent.`);
234
+ else add("NOTE", "quick fixes", rw.reason === "not_set_up" ? "off. To turn them on, ask the agent to set them up" : `off: the setup is damaged (${rw.reason}). To fix it, ask the agent to set them up again`, { fix: `${BIN} setup-rewriter` });
235
+ const soffice = ["/Applications/LibreOffice.app/Contents/MacOS/soffice"].find((p) => fs.existsSync(p)) || which("soffice");
236
+ add(soffice ? "OK" : "NOTE", "LibreOffice (conversion check)", soffice || "not installed (optional)", { fix: "brew install --cask libreoffice" });
237
+
238
+ // browser
239
+ const browsers = (o.probes?.browsers ? o.probes.browsers() : [["Google Chrome", "/Applications/Google Chrome.app"], ["Safari", "/Applications/Safari.app"], ["Brave", "/Applications/Brave Browser.app"], ["Microsoft Edge", "/Applications/Microsoft Edge.app"], ["Firefox", "/Applications/Firefox.app"], ["Arc", "/Applications/Arc.app"]].filter(([, p]) => fs.existsSync(p)).map(([n]) => n));
240
+ add(browsers.length ? "OK" : "MISSING", "browser", browsers.length ? browsers.join(", ") : "none found in /Applications", { required: true, fix: "install Google Chrome: https://www.google.com/chrome" });
241
+ const dflt = (o.probes?.defaultBrowser || defaultBrowserId)();
242
+ if (dflt) add(/^com\.google\.chrome$/i.test(dflt) ? "OK" : "NOTE", "default browser", /^com\.google\.chrome$/i.test(dflt) ? "Google Chrome" : `${dflt}: only Chrome is tested`, { fix: "System Settings > Desktop & Dock > Default web browser > Google Chrome" });
243
+ else add("NOTE", "default browser", "could not be read; only Chrome is tested");
244
+
245
+ // state dir, disk, server
246
+ if (fs.existsSync(state)) {
247
+ const st = fs.statSync(state);
248
+ const ours = st.uid === process.getuid() && !(st.mode & 0o077);
249
+ add(ours ? "OK" : "NOTE", "state folder", `${state} mode ${(st.mode & 0o777).toString(8)}, ${st.uid === process.getuid() ? "owned by you" : "NOT owned by you"}`, { fix: `chmod 700 ${state}` });
250
+ } else add("NOTE", "state folder", `${state} does not exist yet (created on first use)`);
251
+ try {
252
+ let raw = {};
253
+ try {
254
+ raw = JSON.parse(fs.readFileSync(path.join(state, "settings.json"), "utf8"));
255
+ } catch {}
256
+ const b = normalizeBackground(raw?.background);
257
+ const hasImg = ["png", "jpg", "webp"].some((e) => fs.existsSync(path.join(state, "backgrounds", `custom.${e}`)));
258
+ const missing = b.kind === "custom" && !hasImg;
259
+ add("NOTE", "background", missing ? "custom image chosen but its file is missing (the default is shown)" : describeBackground(b), missing ? { fix: `${BIN} config background default` } : {});
260
+ } catch {
261
+ add("NOTE", "background", "could not be read");
262
+ }
263
+ let probeDir = state;
264
+ while (!fs.existsSync(probeDir) && path.dirname(probeDir) !== probeDir) probeDir = path.dirname(probeDir);
265
+ try {
266
+ const free = (o.probes?.freeBytes || ((d) => { const s = fs.statfsSync(d); return s.bavail * s.bsize; }))(probeDir);
267
+ const mb = Math.floor(free / 1048576);
268
+ add(mb < 200 ? "MISSING" : mb < 2048 ? "NOTE" : "OK", "free disk space", `${mb >= 1024 ? (mb / 1024).toFixed(1) + " GB" : mb + " MB"} free where the state folder lives`, { required: true, fix: "free some disk space; Onionskin keeps a snapshot of the file at every step" });
269
+ } catch {
270
+ add("NOTE", "free disk space", "could not be read");
271
+ }
272
+ const srv = await probeServer(path.join(state, "s.sock"));
273
+ if (srv.state === "up") {
274
+ add("OK", "server", "running and reachable on its Unix socket");
275
+ add("NOTE", "open sessions", srv.sessions == null ? "unknown (older server)" : `${srv.sessions} (names are not printed${o.verbose ? "; --verbose does not add them either" : ""})`);
276
+ } else if (srv.state === "none") add("NOTE", "server", "not running (it starts on the first `onionskin open`)");
277
+ else add("NOTE", "server", srv.state === "dead" ? "a leftover socket file exists but nothing answers" : "something answered that is not this server's protocol", { fix: `${BIN} stop` });
278
+ if (o.verbose) add("NOTE", "PATH entries", (env.PATH || "").split(":").filter(Boolean).join(" "));
279
+
280
+ return { schema: `${BIN}.doctor/1`, ok: !checks.some((c) => c.required && c.status === "MISSING"), version, checks };
281
+ }
282
+
283
+ export function formatDoctor(r) {
284
+ const lines = [`${PRODUCT.name} doctor${r.version ? ` ${r.version}` : ""}`, ""];
285
+ for (const c of r.checks) lines.push(`${c.status.padEnd(8)}${c.name}${c.detail ? ": " + c.detail : ""}${c.fix ? `. Fix: ${c.fix}` : ""}`);
286
+ lines.push("", r.ok ? "Result: OK (no required check failed)." : "Result: a required check failed (see MISSING lines).", "Copy everything above when reporting a problem.");
287
+ return lines.join("\n") + "\n";
288
+ }