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/person.js ADDED
@@ -0,0 +1,66 @@
1
+ // A person at a terminal vs a coding agent. Agents (and scripts) get the CLI's agent output unchanged; a person who types
2
+ // `onionskin <file>` or `onionskin open <file>` gets plain words, and the server starts its background agent on the file (src/agent-runner.js).
3
+ import { PRODUCT } from "./constants.js";
4
+
5
+ const BIN = PRODUCT.bin;
6
+ const DOC_EXT = /\.(docx|xlsx|pptx)$/i;
7
+ export const GET_CLAUDE_CODE = "https://claude.com/product/claude-code";
8
+
9
+ /**
10
+ * Environment variables an agent sets for the commands it runs. Exact names only: people export CODEX_HOME, API keys and
11
+ * CLAUDE_CODE_* settings in their shell profile, so a prefix match would treat them as agents.
12
+ * Claude Code: CLAUDECODE=1. Codex 0.167: CODEX_THREAD_ID, CODEX_TOOL_CALL_ID, CODEX_CI, CODEX_SANDBOX (seen in a real `codex exec` command).
13
+ */
14
+ export const AGENT_ENV = ["CLAUDECODE", "CODEX_THREAD_ID", "CODEX_TOOL_CALL_ID", "CODEX_CI", "CODEX_SANDBOX"];
15
+
16
+ export const shellQuote = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;
17
+
18
+ /** True when an agent or a script runs this command: an agent's environment variable, or stdin or stdout that is not a terminal. */
19
+ export function isAgentRun({ env = {}, stdinTTY = false, stdoutTTY = false } = {}) {
20
+ if (AGENT_ENV.some((k) => env[k])) return true;
21
+ return !(stdinTTY && stdoutTTY);
22
+ }
23
+
24
+ /**
25
+ * Strips --agent / --no-agent from `open` and `poll` and says who the output is for.
26
+ * Returns { argv, person, offer }: person = plain words; offer = the background agent starts on the file (never with --no-agent).
27
+ */
28
+ export function pickAudience(argv, ctx) {
29
+ if (!["open", "poll"].includes(argv[0])) return { argv, person: false, offer: false };
30
+ const agent = argv.includes("--agent");
31
+ const noAgent = argv.includes("--no-agent");
32
+ if (agent && noAgent) throw new Error("--agent and --no-agent cannot be combined");
33
+ const rest = argv.filter((x) => x !== "--agent" && x !== "--no-agent");
34
+ if (agent) return { argv: rest, person: false, offer: false };
35
+ if (noAgent) return { argv: rest, person: true, offer: false };
36
+ const person = !isAgentRun(ctx);
37
+ return { argv: rest, person, offer: person };
38
+ }
39
+
40
+ /** `onionskin report.docx` is `onionskin open report.docx`: a first argument that names a Word, Excel or PowerPoint file. */
41
+ export function expandShortcut(argv, commands) {
42
+ const first = argv[0];
43
+ if (!first || first.startsWith("-") || first in commands || !DOC_EXT.test(first)) return argv;
44
+ return ["open", ...argv];
45
+ }
46
+
47
+ const later = (realPath) =>
48
+ `When you want an agent on it, run this in a terminal:\n ${BIN} ${shellQuote(realPath)}\nor, inside Claude Code, type:\n /onionskin ${shellQuote(realPath)}\n(in Codex, ask it to use the onionskin skill on that file).\n`;
49
+
50
+ /**
51
+ * What a person sees after `open`. `offer`: the background agent starts on the file (`found`: Claude Code is installed); one plain line says so.
52
+ * Without `offer` (--no-agent) only the page opens, and the text says how to get an agent later.
53
+ */
54
+ export function personOpenText({ name, url, realPath, browser = true, found = false, codex = false, offer = false }) {
55
+ let t = browser ? `Opened ${name} in your browser.\n ${url}\n\n` : `Opened ${name}. Open this link in your browser:\n ${url}\n\n`;
56
+ t += `Onionskin works together with a coding agent: you mark up the file in the page and press Send, and the agent makes the changes and answers your comments.\n\n`;
57
+ if (!offer) return t + later(realPath);
58
+ if (!found && codex) return t + `Codex is on this Mac. To work on this file, say to Codex:\n open ${name} in Onionskin\nTo start an agent from this command instead, get Claude Code: ${GET_CLAUDE_CODE}\n`;
59
+ if (!found) return t + `Claude Code was not found on this Mac, so no agent can start yet. Get Claude Code: ${GET_CLAUDE_CODE}\nSign in to it once, then press Try again in the page.\n`;
60
+ return t + `Claude Code is starting in the background to work on this file with you. Press Send in the page when you are ready.\n`;
61
+ }
62
+
63
+ /** What a person sees from `poll`: two plain lines and no batch. */
64
+ export function personPollText(realPath) {
65
+ return `${BIN} poll is the command the coding agent runs to wait for your Send; you do not need to type it.\nTo start, run: ${BIN} ${shellQuote(realPath)} (it opens the file and starts Claude Code on it in the background)\n`;
66
+ }
package/src/pptx.js ADDED
@@ -0,0 +1,194 @@
1
+ import { attrOf, local, readRels } from "./xlsx.js";
2
+ import { walkXml } from "./xml.js";
3
+ import { normText, similarity, textHash } from "./text.js";
4
+ import { openZip } from "./zip.js";
5
+ import { summarizeRuns } from "./fmt.js";
6
+ import { untrusted } from "./sanitize.js";
7
+
8
+ // PPTX durable anchors. A slide is identified by its p:sldId id (stable across reorder, insert and delete; the part path is only a hint,
9
+ // writers renumber parts), a shape by its cNvPr id plus its name and its ordinal among shapes with the same id. Shape text is the
10
+ // paragraphs joined by LF, as `onionskin apply` reads it.
11
+
12
+ const EMPTY = textHash("");
13
+ const CTX = 40;
14
+ const KEEP = 2000;
15
+
16
+ const SHAPE_TAGS = new Set(["sp", "pic", "graphicFrame", "grpSp", "cxnSp"]);
17
+ const KIND = { sp: "shape", pic: "image", graphicFrame: "table", grpSp: "group", cxnSp: "line" };
18
+
19
+ /** ppt/presentation.xml order + each slide's shapes: [{id, index, part, title, titleHash, shapes:[{id, name, ordinal, kind, text, hash}]}] */
20
+ export function parseDeck(bytes) {
21
+ const zip = openZip(bytes);
22
+ const px = zip.readText("ppt/presentation.xml");
23
+ if (px == null) throw new Error("ppt/presentation.xml missing");
24
+ const rels = readRels(zip, "ppt/presentation.xml");
25
+ const slides = [];
26
+ walkXml(px, {
27
+ onOpen(n, a) {
28
+ if (local(n) === "sldId") slides.push({ id: a.id ?? null, index: slides.length, part: rels.get(attrOf(a, "id")) || null });
29
+ },
30
+ });
31
+ let loaded = false;
32
+ const load = () => {
33
+ if (loaded) return;
34
+ loaded = true;
35
+ for (const s of slides) Object.assign(s, readSlide(zip, s.part));
36
+ };
37
+ return { slides, ensure: load };
38
+ }
39
+
40
+ function readSlide(zip, part) {
41
+ const out = { shapes: [], title: "", titleHash: EMPTY };
42
+ const xml = part ? zip.readText(part) : null;
43
+ if (xml == null) return out;
44
+ const stack = []; // open shape containers
45
+ let para = null; // current paragraph text of the innermost shape
46
+ let inT = false;
47
+ const seen = new Map();
48
+ const at = []; // open element names, to tell a text color (rPr > solidFill > srgbClr) from any other color in the slide
49
+ walkXml(xml, {
50
+ onOpen(n, a) {
51
+ const l = local(n);
52
+ at.push(l);
53
+ if (SHAPE_TAGS.has(l)) stack.push({ tag: l, id: null, name: "", paras: [], isTitle: false, runs: [], run: null });
54
+ else if (!stack.length) return;
55
+ const top = stack[stack.length - 1];
56
+ if (l === "r") top.run = { text: false, p: {} };
57
+ else if (top.run && l === "rPr") Object.assign(top.run.p, { b: a.b === "1" || a.b === "true" ? "1" : "", i: a.i === "1" || a.i === "true" ? "1" : "", u: a.u && a.u !== "none" ? a.u : "", size: a.sz || "", strike: a.strike && a.strike !== "noStrike" ? a.strike : "" });
58
+ else if (top.run && (l === "srgbClr" || l === "schemeClr") && at[at.length - 2] === "solidFill" && at[at.length - 3] === "rPr") top.run.p.color = String(a.val || "").toUpperCase();
59
+ else if (top.run && l === "latin" && at[at.length - 2] === "rPr") top.run.p.font = a.typeface || "";
60
+ if (l === "cNvPr" && top && top.id === null) {
61
+ top.id = a.id != null ? Number(a.id) : null;
62
+ top.name = a.name ?? "";
63
+ } else if (l === "ph" && top) {
64
+ top.ph = a.type || "object"; // no type = a content placeholder
65
+ if (a.type === "title" || a.type === "ctrTitle") top.isTitle = true;
66
+ }
67
+ else if (l === "p" && top) para = "";
68
+ else if (l === "t" && para !== null) (inT = true, top.run && (top.run.text = true));
69
+ else if (l === "br" && para !== null) para += "\n";
70
+ else if (l === "tc" && top) top.cellStart = true;
71
+ },
72
+ onText(t) {
73
+ if (inT && para !== null) para += t;
74
+ },
75
+ onClose(n) {
76
+ const l = local(n);
77
+ at.pop();
78
+ if (l === "r" && stack.length) {
79
+ const top = stack[stack.length - 1];
80
+ if (top.run?.text) top.runs.push(top.run.p);
81
+ top.run = null;
82
+ }
83
+ if (l === "t") inT = false;
84
+ else if (l === "p" && para !== null && stack.length) {
85
+ stack[stack.length - 1].paras.push(para);
86
+ para = null;
87
+ } else if (SHAPE_TAGS.has(l) && stack.length) {
88
+ const sh = stack.pop();
89
+ const text = sh.paras.join("\n");
90
+ const id = sh.id ?? -1;
91
+ const ordinal = seen.get(id) || 0;
92
+ seen.set(id, ordinal + 1);
93
+ out.shapes.push({ id, name: sh.name, ordinal, kind: KIND[sh.tag], text, hash: textHash(text), isTitle: sh.isTitle, placeholder: sh.ph || null, fmt: summarizeRuns(sh.runs) });
94
+ if (sh.isTitle && !out.title) out.title = text;
95
+ }
96
+ },
97
+ });
98
+ out.titleHash = textHash(out.title);
99
+ return out;
100
+ }
101
+
102
+ /** `onionskin shapes`: every shape of one slide (or of all slides) as {shape_id, name, kind, placeholder, text_preview}; read-only, from the PPTX parts. */
103
+ export function listShapes(deck, slideId = null) {
104
+ deck.ensure();
105
+ const slides = slideId == null ? deck.slides : deck.slides.filter((s) => s.id === String(slideId));
106
+ if (!slides.length) throw new Error(`no slide with id ${JSON.stringify(String(slideId).slice(0, 40))}; the slide ids are ${deck.slides.map((s) => s.id).join(", ")}`);
107
+ return slides.map((s) => ({
108
+ slide_id: s.id,
109
+ slide_index: s.index + 1,
110
+ shapes: s.shapes.map((sh) => ({ shape_id: sh.id, name: untrusted(sh.name, 100), kind: sh.kind, placeholder: sh.placeholder, text_preview: untrusted(normText(sh.text), 80) })),
111
+ }));
112
+ }
113
+
114
+ const slideById = (deck, id) => deck.slides.find((s) => s.id === String(id)) || null;
115
+
116
+ /**
117
+ * Engine location {slideIndex, slideId?, shapeId?, shapeName?, cell?} (+ the text the browser saw) -> durable anchor, from the written
118
+ * bytes. `ctx` = {quote, prefix, suffix, text}. Returns null when the slide does not exist.
119
+ */
120
+ export function pptxDurable(deck, loc, ctx = {}) {
121
+ deck.ensure();
122
+ const slide = (loc.slideId != null && slideById(deck, loc.slideId)) || deck.slides[loc.slideIndex];
123
+ if (!slide) return null;
124
+ const base = { format: "pptx", ...(loc.protected ? { protected: true } : {}), slideId: slide.id, slidePart: slide.part, slideIndex: slide.index, slideTitle: normText(slide.title).slice(0, 120), titleHash: slide.titleHash, shapeId: null, shapeName: "", ordinal: 0, kind: "slide", text: "", textHash: null, quote: "", prefix: "", suffix: "", start: null, end: null, cell: loc.cell || null };
125
+ if (loc.shapeId == null) return base;
126
+ const same = slide.shapes.filter((s) => s.id === loc.shapeId);
127
+ let sh = same[0];
128
+ if (same.length > 1) {
129
+ const want = textHash(ctx.text || ctx.quote || "");
130
+ sh = same.find((s) => s.name === loc.shapeName && s.hash === want) || same.find((s) => s.hash === want) || same.find((s) => s.name === loc.shapeName) || same[0];
131
+ }
132
+ if (!sh) return { ...base, shapeId: loc.shapeId, shapeName: loc.shapeName || "", kind: "shape" };
133
+ const q = normText(ctx.quote || "");
134
+ const raw = ctx.quote || "";
135
+ const at = q ? sh.text.indexOf(raw) : -1;
136
+ return {
137
+ ...base,
138
+ shapeId: sh.id, shapeName: sh.name, ordinal: sh.ordinal, kind: sh.kind,
139
+ text: normText(sh.text).slice(0, KEEP), textHash: sh.hash,
140
+ // a text range inside the shape: the quote and what surrounds it
141
+ quote: ctx.shapeWide ? "" : q,
142
+ prefix: normText(ctx.prefix || "").slice(-CTX),
143
+ suffix: normText(ctx.suffix || "").slice(0, CTX),
144
+ start: !ctx.shapeWide && at >= 0 ? at : null,
145
+ end: !ctx.shapeWide && at >= 0 ? at + raw.length : null,
146
+ };
147
+ }
148
+
149
+ /**
150
+ * Re-resolve against new bytes. Slide: by p:sldId id; else the part path together with the title; else the title alone when unique.
151
+ * Shape (when the anchor has one): by id (+ ordinal); else the same name with the same text; else the same text; else the same name.
152
+ * Result: {method, slideId, slideIndex, shapeId, shapeName, start, end, changed, text} or {method:"none"}. A deleted slide or shape is "none".
153
+ */
154
+ export function resolvePptx(deck, d) {
155
+ if (!d) return { method: "none" };
156
+ deck.ensure();
157
+ let slide = d.slideId != null ? slideById(deck, d.slideId) : null;
158
+ let method = "id";
159
+ if (!slide) {
160
+ const part = deck.slides.filter((s) => s.part && s.part === d.slidePart && s.titleHash === d.titleHash && d.titleHash !== EMPTY);
161
+ const title = deck.slides.filter((s) => s.titleHash === d.titleHash && d.titleHash !== EMPTY);
162
+ if (part.length === 1) [slide, method] = [part[0], "part"];
163
+ else if (title.length === 1) [slide, method] = [title[0], "title"];
164
+ }
165
+ if (!slide) return { method: "none" };
166
+ const out = { method, slideId: slide.id, slideIndex: slide.index, shapeId: null, shapeName: "", start: null, end: null, changed: false, text: "", titleChanged: slide.titleHash !== d.titleHash };
167
+ if (d.shapeId == null) return out;
168
+ const shapes = slide.shapes;
169
+ const byId = shapes.filter((s) => s.id === d.shapeId);
170
+ let sh = null;
171
+ let how = "";
172
+ if (byId.length === 1) [sh, how] = [byId[0], "id"];
173
+ else if (byId.length > 1) {
174
+ sh = byId.find((s) => s.ordinal === d.ordinal && (s.name === d.shapeName || s.hash === d.textHash)) || byId.find((s) => s.name === d.shapeName && s.hash === d.textHash) || null;
175
+ if (sh) how = "id";
176
+ }
177
+ if (!sh) {
178
+ const nameText = shapes.filter((s) => s.name && s.name === d.shapeName && s.hash === d.textHash);
179
+ const text = shapes.filter((s) => d.textHash && d.textHash !== EMPTY && s.hash === d.textHash);
180
+ const name = shapes.filter((s) => s.name && s.name === d.shapeName);
181
+ if (nameText.length === 1) [sh, how] = [nameText[0], "name+text"];
182
+ else if (text.length === 1) [sh, how] = [text[0], "text"];
183
+ else if (name.length === 1 && d.textHash && d.textHash !== EMPTY) [sh, how] = [name[0], "name"];
184
+ }
185
+ if (!sh) return { method: "none" };
186
+ const stext = normText(sh.text);
187
+ const q = d.quote || "";
188
+ const at = q ? sh.text.indexOf(q) : -1;
189
+ return { ...out, method: method === "id" ? how : `${method}+${how}`, shapeId: sh.id, shapeName: sh.name, start: at >= 0 ? at : null, end: at >= 0 ? at + q.length : null, changed: sh.hash !== d.textHash, text: stext.slice(0, 200), quoteLost: !!q && at < 0 };
190
+ }
191
+
192
+ /** Locator fields for the batch: the names the `apply` targets use. */
193
+ export const pptxLocator = (d) =>
194
+ d ? { slide_id: /^\d{1,10}$/.test(String(d.slideId ?? "")) ? String(d.slideId) : null, shape_id: Number.isInteger(d.shapeId) ? d.shapeId : null, text_hash: d.textHash ?? null, start: d.start ?? null, end: d.end ?? null } : null;
@@ -0,0 +1,47 @@
1
+ import { untrusted } from "./sanitize.js";
2
+
3
+ /**
4
+ * A question the agent asks instead of declining: `{"comment":"c1","ask":"Which date?","options":["March 3","March 13"]}`.
5
+ * The agent wrote it after reading the document, so every string is untrusted. It is cleaned like other untrusted text (one line, no
6
+ * control, bidirectional or zero-width characters) and then checked. A string over its cap is refused, never cut, so the card shows the
7
+ * whole text the agent later reads back. The checks run on the cleaned text, so a hidden character cannot slip a link or a duplicate past.
8
+ * `Sessions.done()` is the trust boundary; `planReplies` runs the same checks only to tell the agent what to fix.
9
+ */
10
+ export const QUESTION_MAX = 160;
11
+ export const OPTION_MAX = 40;
12
+ export const OPTIONS_MIN = 2;
13
+ export const OPTIONS_MAX = 4;
14
+ export const QUESTIONS_PER_BATCH = 3;
15
+ export const QUESTION_FIX = "A question needs 2 to 4 short options (40 characters each) and no links.";
16
+ /** The note on the card when `done` received a question it would not show. */
17
+ export const BAD_QUESTION_NOTE = "The agent asked a question that could not be shown.";
18
+
19
+ const LINK = /:\/\/|www\./i;
20
+ const len = (s) => [...s].length; // code points, as untrusted() and the schema count
21
+
22
+ /** One string: cleaned, then refused when empty, over `max` or a link. Returns {text} or {reason}. */
23
+ function cleanOne(v, max, what) {
24
+ if (typeof v !== "string") return { reason: `${what} must be a string` };
25
+ const text = untrusted(v, Number.MAX_SAFE_INTEGER);
26
+ if (!text) return { reason: `${what} is empty` };
27
+ if (len(text) > max) return { reason: `${what} is longer than ${max} characters` };
28
+ if (LINK.test(text)) return { reason: `${what} contains a link` };
29
+ return { text };
30
+ }
31
+
32
+ /** `{ask, options}` -> `{question: {text, options}}`, or `{code: "bad_question", reason}`. */
33
+ export function cleanQuestion({ ask, options } = {}) {
34
+ const refuse = (reason) => ({ code: "bad_question", reason });
35
+ const q = cleanOne(ask, QUESTION_MAX, "the question");
36
+ if (q.reason) return refuse(q.reason);
37
+ if (!Array.isArray(options)) return refuse("options must be a list");
38
+ if (options.length < OPTIONS_MIN || options.length > OPTIONS_MAX) return refuse(`give ${OPTIONS_MIN} to ${OPTIONS_MAX} options (got ${options.length})`);
39
+ const out = [];
40
+ for (const [i, o] of options.entries()) {
41
+ const c = cleanOne(o, OPTION_MAX, `option ${i + 1}`);
42
+ if (c.reason) return refuse(c.reason);
43
+ out.push(c.text);
44
+ }
45
+ if (new Set(out.map((o) => o.toLowerCase())).size !== out.length) return refuse("two options are the same");
46
+ return { question: { text: q.text, options: out } };
47
+ }
@@ -0,0 +1,107 @@
1
+ // Quick changes (idea 8), the two halves that need the file: the preview the page shows before Send, and the planner the local runner
2
+ // (src/local.js) asks. Both read the person's own typed note and the file's bytes; nothing from the document ever becomes the command.
3
+ //
4
+ // The trust argument: the command is the person's typed note, and the count is the number the person saw on the Send button. The plan
5
+ // binds that number as `expect.count`, so a file that changed since the preview, or a tampered number, fails the count check and nothing
6
+ // is written (the batch then goes to the agent unchanged).
7
+ //
8
+ // Ceiling: previews run the engine on the server's main thread (as the merge does); a large file pauses other requests while one runs.
9
+ // The page asks 600 ms after typing stops, and answers are cached by file hash and command. Upgrade path: a worker.
10
+
11
+ import { checkRegularOwned, readDoc, sha256 } from "./fsutil.js";
12
+ import { recognize, refusalFor, wordsFor } from "./quick.js";
13
+ import { userText } from "./sanitize.js";
14
+
15
+ const CACHE_MAX = 64;
16
+ const cache = new Map(); // `${sha}\0${format}\0${command}` -> match
17
+
18
+ const WHY_UNDONE = "You undid this change, so the agent will do it.";
19
+ const WHY_ALL_PROTECTED = "Every match is in a protected place, so the agent will do this one.";
20
+
21
+ /**
22
+ * True when the next Send's batch would carry something besides the note (what `quickPlanner.wants` refuses), from what the server holds:
23
+ * a batch waiting or delivered, comments sent and not yet taken by an agent or queued, the person's edits from an earlier Send. Draft
24
+ * comments are the page's to count: the Send replaces them with the page's own list.
25
+ */
26
+ function ridesAlong(s) {
27
+ if (s.delivered || s.pending || s.queued) return true;
28
+ if ((s.edits || []).length) return true;
29
+ return (s.comments || []).some((c) => c.status === "sent" || c.status === "queued");
30
+ }
31
+
32
+ async function previewOf(bytes, format, q) {
33
+ const { previewAll } = await import("./ops/run.js"); // pulls in the engine: loaded on first use
34
+ const p = await previewAll(bytes, format, q.op);
35
+ const count = p.ok ? p.count : 0;
36
+ const skipped = p.ok ? p.protected || 0 : 0;
37
+ let why = refusalFor(q.kind, p, q.find);
38
+ if (!why && count - skipped <= 0) why = WHY_ALL_PROTECTED;
39
+ return { p, count, skipped, why };
40
+ }
41
+
42
+ /**
43
+ * What the page shows for `note` on the file as it is on disk right now: {match: null} (not a quick request) or
44
+ * {match: {action, command, count, protectedCount, local, why, text, label}}. Read only.
45
+ */
46
+ export async function quickPreview(s, note) {
47
+ const q = recognize(userText(note), s.format);
48
+ if (!q) return { match: null };
49
+ if (ridesAlong(s)) return { match: null }; // the next Send carries more than the note, so `wants` says no: the button must not promise otherwise
50
+ // the person undid a local run of these very words: the next Send goes to the agent (src/local.js skipsLocal), so the button must not say otherwise
51
+ if (s.skipLocalNote && userText(note).trim() === String(s.skipLocalNote).trim()) return { match: { action: q.kind, command: q.command, count: 0, protectedCount: 0, local: false, why: WHY_UNDONE } };
52
+ let bytes;
53
+ try {
54
+ checkRegularOwned(s.file);
55
+ bytes = readDoc(s.file);
56
+ } catch {
57
+ return { match: null };
58
+ }
59
+ const key = `${sha256(bytes)}\0${s.format}\0${q.command}`;
60
+ let match = cache.get(key);
61
+ if (!match) {
62
+ try {
63
+ const { count, skipped, why } = await previewOf(bytes, s.format, q);
64
+ match = { action: q.kind, command: q.command, count, protectedCount: skipped, local: !why, why: why || null, ...wordsFor(q, count, skipped) };
65
+ } catch {
66
+ return { match: null }; // the engine could not read it: the agent will
67
+ }
68
+ if (cache.size >= CACHE_MAX) cache.delete(cache.keys().next().value);
69
+ cache.set(key, match);
70
+ }
71
+ return { match };
72
+ }
73
+
74
+ /** The local runner's planner for a quick change. See src/local.js for the contract of `wants` and `plan`. */
75
+ export const quickPlanner = {
76
+ name: "quick",
77
+
78
+ /** Pure and synchronous: a whole Send that is only a note, the person confirmed a count for exactly this note, nothing else rides along. */
79
+ wants(s, batch) {
80
+ // at the Send it is on the session (held for that Send); the runner asks again when it starts, and then it is on the delivery
81
+ const c = s.quickConfirm ?? (s.delivered?.batch === batch ? s.delivered.quick : undefined);
82
+ if (!c || typeof c.command !== "string" || !Number.isInteger(c.count) || c.count < 1) return false;
83
+ if ((batch.instructions?.comments || []).length) return false;
84
+ if ((batch.untrusted_document_evidence?.user_edits || []).length) return false;
85
+ const q = recognize(batch.instructions?.overall_note, batch.format);
86
+ return !!q && q.command === c.command;
87
+ },
88
+
89
+ /** Counts again on the bytes about to be written. Any guard failing returns null: nothing is written and the agent gets the batch. */
90
+ async plan(s, batch) {
91
+ const confirmed = s.delivered?.quick;
92
+ if (!confirmed || s.delivered.batch !== batch) return null;
93
+ const q = recognize(batch.instructions?.overall_note, batch.format);
94
+ if (!q || q.command !== confirmed.command) return null;
95
+ let bytes;
96
+ try {
97
+ checkRegularOwned(s.file);
98
+ bytes = readDoc(s.file);
99
+ } catch {
100
+ return null;
101
+ }
102
+ if (sha256(bytes) !== batch.base_sha256) return null; // the file moved since the Send
103
+ const { count, skipped, why } = await previewOf(bytes, batch.format, q);
104
+ if (why || count !== confirmed.count) return null; // not what the person saw
105
+ return { reply: { summary: wordsFor(q, count, skipped).summary, replies: [], ops: [{ ...q.op, expect: { count } }] } };
106
+ },
107
+ };
package/src/quick.js ADDED
@@ -0,0 +1,164 @@
1
+ // Quick changes: the small closed set of requests Onionskin can do without the agent.
2
+ // Pure: it reads the person's own typed note and nothing else. Document text never reaches this file.
3
+ // Anything not recognized exactly returns null, and the request goes to the agent as it does today.
4
+
5
+ const MAX_NOTE = 200;
6
+ const MAX_BARE_WORDS = 6;
7
+ const MAX_BARE_CHARS = 60;
8
+ const MIN_FIND = 2;
9
+ const BANNED_WORDS = new Set(["and", "or", "then", "with", "to", "in"]);
10
+ const TAILS = ["everywhere", "throughout", "in the document", "in the whole document", "in the file"];
11
+ const OPEN_QUOTES = new Set(['"', "“"]);
12
+ const QUOTES = /["“”]/;
13
+
14
+ /** The note as it is compared and shown: one line, no politeness, no closing punctuation, one tail dropped. null when it cannot be a quick request. */
15
+ export function normalizeNote(note) {
16
+ if (typeof note !== "string") return null;
17
+ let t = note.trim();
18
+ if (!t || t.length > MAX_NOTE || /[\r\n\u2028\u2029]/.test(t)) return null;
19
+ t = t.replace(/[.!]$/, "").replace(/\s+/g, " ").trim();
20
+ t = t.replace(/^please /i, "");
21
+ if (/\p{Cc}/u.test(t)) return null;
22
+ const low = t.toLowerCase();
23
+ for (const tail of TAILS) {
24
+ if (low.endsWith(` ${tail}`)) {
25
+ t = t.slice(0, t.length - tail.length - 1).trimEnd();
26
+ break;
27
+ }
28
+ }
29
+ return t || null;
30
+ }
31
+
32
+ // ---- headings -----------------------------------------------------------------------------------------------------
33
+ const TARGETS = ["every heading", "each heading", "all headings", "all the headings", "the headings"];
34
+ const SETS = {
35
+ bold: { bold: true },
36
+ italic: { italic: true },
37
+ underline: { underline: true },
38
+ "no bold": { bold: false },
39
+ "no italic": { italic: false },
40
+ "no underline": { underline: false },
41
+ };
42
+ /** Every accepted heading phrase (lower case) -> the `set` it means. Built from templates; test/quick.test.js pins the list. */
43
+ export const HEADING_PHRASES = (() => {
44
+ const m = new Map();
45
+ const verbs = { bold: "bold", italicize: "italic", underline: "underline" };
46
+ const adjectives = { bold: "bold", italic: "italic", underlined: "underline" };
47
+ const removals = { "the bold": "bold", bold: "bold", italics: "italic", "the italics": "italic", "the underline": "underline", underlining: "underline" };
48
+ for (const t of TARGETS) {
49
+ for (const [v, k] of Object.entries(verbs)) m.set(`${v} ${t}`, SETS[k]);
50
+ for (const [a, k] of Object.entries(adjectives)) m.set(`make ${t} ${a}`, SETS[k]);
51
+ for (const [r, k] of Object.entries(removals)) m.set(`remove ${r} from ${t}`, SETS[`no ${k}`]);
52
+ }
53
+ return m;
54
+ })();
55
+
56
+ // ---- replace ------------------------------------------------------------------------------------------------------
57
+ /** A bare span: 1 to 6 words, up to 60 characters, no list or sentence punctuation, none of the joining words. */
58
+ function bareSpan(s) {
59
+ if (!s || s.length > MAX_BARE_CHARS || /[,;:?!]/.test(s) || QUOTES.test(s)) return false;
60
+ const words = s.split(" ");
61
+ if (words.length > MAX_BARE_WORDS || words.some((w) => !w || BANNED_WORDS.has(w.toLowerCase()))) return false;
62
+ return true;
63
+ }
64
+
65
+ /** Reads one side of "replace A with B" from the start of `s`. Returns {value, rest} or null. A quoted side keeps commas and joining words. */
66
+ function quoted(s) {
67
+ if (!OPEN_QUOTES.has(s[0])) return null;
68
+ const end = s.slice(1).search(QUOTES);
69
+ if (end < 0) return null;
70
+ return { value: s.slice(1, end + 1), rest: s.slice(end + 2) };
71
+ }
72
+
73
+ function parseReplace(t) {
74
+ const m = /^replace (?:(?:all|every) )?(.+)$/i.exec(t);
75
+ if (!m) return null;
76
+ const body = m[1];
77
+ let find;
78
+ let rest;
79
+ if (OPEN_QUOTES.has(body[0])) {
80
+ const q = quoted(body);
81
+ if (!q || !q.rest.startsWith(" with ")) return null;
82
+ find = { text: q.value, quoted: true };
83
+ rest = q.rest.slice(" with ".length);
84
+ } else {
85
+ const at = body.search(/ with /i);
86
+ if (at < 0) return null;
87
+ find = { text: body.slice(0, at), quoted: false };
88
+ rest = body.slice(at + " with ".length);
89
+ }
90
+ let repl;
91
+ if (OPEN_QUOTES.has(rest[0])) {
92
+ const q = quoted(rest);
93
+ if (!q || q.rest) return null; // nothing may follow the closing quote
94
+ repl = { text: q.value, quoted: true };
95
+ } else repl = { text: rest, quoted: false };
96
+ if (!find.quoted && !bareSpan(find.text)) return null;
97
+ if (!repl.quoted && !bareSpan(repl.text)) return null; // also refuses an empty bare replacement: removing text must be said as ""
98
+ if (find.text.trim().length < MIN_FIND || find.text === repl.text) return null;
99
+ return { find: find.text, replace: repl.text };
100
+ }
101
+
102
+ /**
103
+ * Recognizes a quick request in the person's note for a file of `format` ("docx", "xlsx", "pptx").
104
+ * Returns null (not recognized: the agent does it) or
105
+ * { command, kind: "replace"|"headings", op, find?, replace?, set? }
106
+ * where `op` is the ops-file op WITHOUT `expect`: the caller adds the count the person confirmed.
107
+ * Matching is case-sensitive. Heading formatting is DOCX only.
108
+ */
109
+ export function recognize(note, format) {
110
+ const command = normalizeNote(note);
111
+ if (!command) return null;
112
+ const set = HEADING_PHRASES.get(command.toLowerCase());
113
+ if (set) {
114
+ if (format !== "docx") return null;
115
+ return { command, kind: "headings", set: { ...set }, op: { op: "format_all", scope: "headings", set: { ...set } } };
116
+ }
117
+ const r = parseReplace(command);
118
+ if (!r) return null;
119
+ return { command, kind: "replace", find: r.find, replace: r.replace, op: { op: "replace_all_text", find: r.find, replace: r.replace, match_case: true } };
120
+ }
121
+
122
+ /**
123
+ * Why a counted request cannot run as a quick change, or null when it can. `p` is previewAll's answer.
124
+ * Returned strings are the plain wording the page shows.
125
+ */
126
+ export function refusalFor(kind, p, find) {
127
+ if (!p?.ok) return "The agent will look into it.";
128
+ if (!p.count) return kind === "replace" ? `No "${find}" in this file. The agent will look into it.` : "No headings in this file. The agent will look into it.";
129
+ if (p.partial_words) return "Some matches are part of longer words, so the agent will do this one.";
130
+ if (p.in_formulas) return "Some matches are inside formulas, so the agent will do this one.";
131
+ return null;
132
+ }
133
+
134
+ // ---- wording ------------------------------------------------------------------------------------------------------
135
+ const clip = (s, n = 60) => (s.length > n ? `${s.slice(0, n - 1)}…` : s);
136
+ const places = (n) => `${n} ${n === 1 ? "place" : "places"}`;
137
+ const headings = (n) => `${n} ${n === 1 ? "heading" : "headings"}`;
138
+ /** The one style a heading phrase sets: ["bold"|"italic"|"underlined", true|false]. */
139
+ function styleOf(set) {
140
+ const k = Object.keys(set)[0];
141
+ return [k === "underline" ? "underlined" : k, set[k] === true];
142
+ }
143
+
144
+ /**
145
+ * The plain words for a recognized, counted request. `n` is the count the person confirms; `skipped` how many of those are protected places the
146
+ * run leaves alone. text: the preview line's middle; label: the Send button; summary: what the activity entry says afterwards.
147
+ */
148
+ export function wordsFor(q, n, skipped = 0) {
149
+ const done = n - skipped;
150
+ if (q.kind === "replace") {
151
+ const find = `"${clip(q.find)}"`;
152
+ return {
153
+ text: q.replace === "" ? `remove ${find} in ${places(n)}` : `replace ${find} with "${clip(q.replace)}" in ${places(n)}`,
154
+ label: `Replace in ${places(n)}`,
155
+ summary: `${q.replace === "" ? `Removed ${find}` : `Replaced ${find} with "${clip(q.replace)}"`} in ${places(done)}. No AI was used.`,
156
+ };
157
+ }
158
+ const [word, on] = styleOf(q.set);
159
+ return {
160
+ text: on ? `make ${headings(n)} ${word}` : `remove ${word} from ${headings(n)}`,
161
+ label: `Change ${headings(n)}`,
162
+ summary: `${on ? `Made ${headings(done)} ${word}` : `Removed ${word} from ${headings(done)}`}. No AI was used.`,
163
+ };
164
+ }