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/reply.js ADDED
@@ -0,0 +1,410 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { FORMATS, PRODUCT } from "./constants.js";
4
+ import { ApplyError, APPLY_EXIT, applyCommand } from "./apply.js";
5
+ import { parseTicket } from "./lease.js";
6
+ import { isAgentHolder } from "./agent-detect.js";
7
+ import { QUESTION_FIX, QUESTIONS_PER_BATCH, cleanQuestion } from "./question.js";
8
+ import { SUGGESTIONS_MAX, SUGGEST_FIX, cleanSuggestion } from "./review.js";
9
+ import { VOICE_FIX, cleanVoiceDraft } from "./voice-guide.js";
10
+
11
+ /**
12
+ * `onionskin reply`: one call that answers a whole batch. The agent names comment ids and says what to change; this command fills in
13
+ * the anchor ids and the `expect` hashes from the batch the session holds (never from the agent), then runs the SAME `apply` code
14
+ * (validation, lease ticket, protected checks, atomic or --partial write) and, when the write landed, the SAME `done` path.
15
+ */
16
+
17
+ const MAX_INPUT_BYTES = 5 * 1024 * 1024;
18
+ const MODES = ["find", "text", "set", "ops", "decline", "ask"];
19
+ const SHORTHAND_EXTRAS = ["occurrence", "all", "match_case"]; // passed to replace_text / replace_text_in_shape with `find`
20
+
21
+ /** A failure with a JSON body for stdout and the exit code to use. */
22
+ export class ReplyError extends Error {
23
+ constructor(message, { exit = APPLY_EXIT.invalid, body = {} } = {}) {
24
+ super(message);
25
+ this.exit = exit;
26
+ this.body = { ok: false, finished: false, error: message, ...body };
27
+ }
28
+ }
29
+
30
+ // --then-poll waits this long unless --timeout says otherwise: just under the 10 minute cap most agent shells put on one command
31
+ const THEN_POLL_SECONDS = 590;
32
+ const clip = (s, n = 60) => (String(s).length > n ? String(s).slice(0, n - 1) + "…" : String(s));
33
+ /** The note the user reads when the agent gave none: says what was done, from the reply itself. */
34
+ const autoNote = (r, mode) =>
35
+ mode === "find" ? (r.replace === "" ? `Removed "${clip(r.find)}".` : `Replaced "${clip(r.find)}" with "${clip(r.replace)}".`) : mode === "text" ? "Rewrote this text." : mode === "set" ? "Set the value." : mode === "decline" ? "Declined." : "Done.";
36
+
37
+ export function parseReplyArgs(rest) {
38
+ const a = { file: "", lease: "", json: null, from: "", partial: false, thenPoll: false, timeout: 0 };
39
+ for (let i = 0; i < rest.length; i++) {
40
+ const x = rest[i];
41
+ const val = (name) => {
42
+ const v = x.includes("=") ? x.slice(x.indexOf("=") + 1) : rest[++i];
43
+ if (v === undefined || v === "") throw new Error(`${name} wants a value`);
44
+ return v;
45
+ };
46
+ if (x === "--partial") a.partial = true;
47
+ else if (x === "--then-poll") a.thenPoll = true;
48
+ else if (x === "--lease" || x.startsWith("--lease=")) a.lease = val("--lease");
49
+ else if (x === "--json" || x.startsWith("--json=")) a.json = val("--json");
50
+ else if (x === "--file" || x.startsWith("--file=")) a.from = val("--file");
51
+ else if (x === "--timeout" || x.startsWith("--timeout=")) {
52
+ a.timeout = Number(val("--timeout"));
53
+ if (!Number.isFinite(a.timeout) || a.timeout <= 0) throw new Error("--timeout wants a number of seconds, e.g. --timeout 300");
54
+ } else if (x.startsWith("-")) throw new Error(`unknown option ${x}`);
55
+ else if (!a.file) a.file = x;
56
+ else throw new Error(`unexpected argument ${x}`);
57
+ }
58
+ if (!a.file && !a.lease) throw new Error(`Usage: ${PRODUCT.bin} reply [<file>] --lease <ticket> [--json '<json>' | --file <path>] [--partial] [--then-poll [--timeout N]] (JSON on stdin when neither --json nor --file is given; the ticket names the file when <file> is left out)`);
59
+ if (a.json !== null && a.from) throw new Error("--json and --file contradict each other");
60
+ if (a.timeout && !a.thenPoll) throw new Error("--timeout only goes with --then-poll");
61
+ if (a.lease && !parseTicket(a.lease)) throw new Error("--lease wants the value printed in the batch (<batch id>:<token>)");
62
+ if (a.thenPoll && !a.timeout) a.timeout = THEN_POLL_SECONDS;
63
+ return a;
64
+ }
65
+
66
+ /**
67
+ * An agent Onionskin started (holder onionskin-bg-* or, in Terminal, onionskin-term-*) answers only with `--file`, and only with the one file the
68
+ * server's prompt names: <ONIONSKIN_AGENT_DIR>/reply-<the batch id of --lease>.json, a regular file (its real path, so no symlink leads out).
69
+ * So a hostile document cannot make it read some other file into a reply. A parse error there never quotes the input.
70
+ */
71
+ function checkBackgroundInput(a, agentDir, batchId) {
72
+ const want = agentDir ? path.join(agentDir, `reply-${batchId}.json`) : `reply-${batchId}.json in your work folder`;
73
+ const fix = `write the reply JSON with the Write tool to ${want}, then pass it with --file`;
74
+ if (!a.from) throw new ReplyError("the background agent answers with --file only", { body: { code: "bad_reply", lease_kept: true, fix } });
75
+ let real = null, dir = null;
76
+ try {
77
+ dir = fs.realpathSync(agentDir || "");
78
+ real = fs.realpathSync(a.from);
79
+ } catch {}
80
+ if (!agentDir || !dir || !real || real !== path.join(dir, `reply-${batchId}.json`) || !fs.lstatSync(real).isFile()) throw new ReplyError(`the background agent's --file must be ${want} (a file in its own work folder)`, { body: { code: "bad_reply", lease_kept: true, fix } });
81
+ a.from = real; // read what was checked
82
+ }
83
+
84
+ async function readInput(a, readStdin, { quiet = false } = {}) {
85
+ let raw;
86
+ if (a.json !== null) raw = a.json;
87
+ else if (a.from) {
88
+ let st;
89
+ try {
90
+ st = fs.statSync(a.from);
91
+ } catch (err) {
92
+ throw new ReplyError(`cannot read ${a.from}: ${err.message}`);
93
+ }
94
+ if (!st.isFile() || st.size > MAX_INPUT_BYTES) throw new ReplyError(`${a.from} is not a regular file under ${MAX_INPUT_BYTES / 1024 / 1024} MB`);
95
+ raw = fs.readFileSync(a.from, "utf8");
96
+ } else raw = await readStdin();
97
+ if (Buffer.byteLength(raw) > MAX_INPUT_BYTES) throw new ReplyError("the reply JSON is larger than 5 MB");
98
+ try {
99
+ return JSON.parse(raw);
100
+ } catch (err) {
101
+ // quiet: a position at most, never the characters of the input
102
+ throw new ReplyError(quiet ? `the reply is not valid JSON${/position \d+/.test(err.message) ? ` (at ${/position \d+/.exec(err.message)[0]})` : ""}` : `the reply is not valid JSON: ${err.message}`);
103
+ }
104
+ }
105
+
106
+ const isObj = (v) => v && typeof v === "object" && !Array.isArray(v);
107
+ const bad = (comment, code, reason, fix) => ({ comment, code, reason, ...(fix ? { fix } : {}) });
108
+
109
+ /**
110
+ * Pure: the reply JSON and the delivered batch -> {ops, owners, replies, errors}. `owners[i]` is the comment id op i answers (null for a
111
+ * batch-wide op). `errors` is empty when the reply can be applied. Nothing here reads the file or the agent's idea of a hash.
112
+ */
113
+ export function planReplies(batch, input, { partial = false } = {}) {
114
+ const errors = [];
115
+ const ops = [];
116
+ const owners = [];
117
+ const replies = []; // {comment, decline, note, opIndexes:[...]}
118
+ if (!isObj(input)) return { ops, owners, replies, errors: [bad(null, "bad_reply", "the reply must be a JSON object: {\"summary\":...,\"replies\":[...]}")] };
119
+ for (const k of Object.keys(input)) {
120
+ if (!["summary", "replies", "ops", "suggest", "voice_draft", "document_instructions_ignored"].includes(k)) errors.push(bad(null, "bad_reply", `unknown top-level field "${k}"`, "allowed: summary, replies, ops, suggest, voice_draft, document_instructions_ignored"));
121
+ }
122
+ if (batch.instructions?.voice_request) {
123
+ const r = planVoiceDraft(input);
124
+ return { ...r, errors: [...errors, ...r.errors] };
125
+ }
126
+ if (input.voice_draft !== undefined) errors.push(bad(null, "voice_draft_not_allowed", "voice_draft answers a voice guide request; this batch is not one", batch.instructions?.review ? "answer with suggest" : "answer each comment in replies"));
127
+ if (batch.instructions?.review) {
128
+ const r = planSuggestions(batch, input);
129
+ return { ...r, errors: [...errors, ...r.errors] };
130
+ }
131
+ if (input.suggest !== undefined) errors.push(bad(null, "suggest_not_allowed", "suggest answers a review; this batch is not one", "answer each comment in replies"));
132
+ if (input.summary !== undefined && typeof input.summary !== "string") errors.push(bad(null, "bad_reply", "summary must be a string"));
133
+ if (!Array.isArray(input.replies)) errors.push(bad(null, "bad_reply", "replies must be an array (it may be empty when the batch has only an overall note)"));
134
+ if (input.ops !== undefined && !Array.isArray(input.ops)) errors.push(bad(null, "bad_reply", "ops must be an array of full ops"));
135
+ if (errors.length) return { ops, owners, replies, errors };
136
+
137
+ const comments = batch.instructions?.comments || [];
138
+ const byId = new Map(comments.map((c) => [c.id, c]));
139
+ const anchors = new Map((batch.untrusted_document_evidence?.anchors || []).map((x) => [x.id, x]));
140
+ const seen = new Set();
141
+ const format = batch.format;
142
+
143
+ input.replies.forEach((r, i) => {
144
+ const at = `replies[${i}]`;
145
+ if (!isObj(r) || typeof r.comment !== "string" || !r.comment) return errors.push(bad(null, "bad_reply", `${at} needs a "comment" id`));
146
+ const id = r.comment;
147
+ if (!byId.has(id)) return errors.push(bad(id, "unknown_comment", `no comment ${JSON.stringify(id.slice(0, 64))} in the delivered batch`, `comment ids of this batch: ${comments.map((c) => c.id).join(", ") || "(none)"}`));
148
+ if (seen.has(id)) return errors.push(bad(id, "duplicate_reply", "this comment is answered twice", "one reply per comment; put several ops in its `ops` array"));
149
+ seen.add(id);
150
+ const modes = MODES.filter((m) => (m === "find" ? "find" in r || "replace" in r : m in r));
151
+ if (modes.length !== 1) return errors.push(bad(id, "bad_reply", modes.length ? `give exactly one of find+replace, text, set, ops, decline, ask (got ${modes.join(", ")})` : "give one of find+replace, text, set, ops, decline, ask", "see reference/ops.md, section reply"));
152
+ const mode = modes[0];
153
+ // a question carries no note and no ops: the card shows only the question and its options
154
+ const allowed = mode === "ask" ? ["comment", "ask", "options"] : ["comment", "note", ...(mode === "find" ? ["find", "replace", ...SHORTHAND_EXTRAS] : [mode])];
155
+ const extra = Object.keys(r).filter((k) => !allowed.includes(k));
156
+ if (extra.length) return errors.push(bad(id, "bad_reply", `unexpected field(s) for ${mode}: ${extra.join(", ")}`, mode === "ask" ? "a question has only comment, ask and options" : undefined));
157
+ if (mode === "ask") {
158
+ // the same checks as done (the trust boundary), here only so the agent gets a fix before anything is sent
159
+ if (byId.get(id).answer) return errors.push(bad(id, "already_asked", "this comment already carries the user's answer to a question", "one question per comment: carry out the reading the user chose, or decline"));
160
+ const q = cleanQuestion({ ask: r.ask, options: r.options });
161
+ if (!q.question) return errors.push(bad(id, "bad_question", q.reason, QUESTION_FIX));
162
+ if (replies.filter((x) => x.ask).length >= QUESTIONS_PER_BATCH) return errors.push(bad(id, "too_many_questions", `at most ${QUESTIONS_PER_BATCH} questions per batch`, "decline the others, or carry out the likeliest reading"));
163
+ replies.push({ comment: id, ask: true, question: q.question, opIndexes: [] });
164
+ return;
165
+ }
166
+ if (r.note !== undefined && typeof r.note !== "string") return errors.push(bad(id, "bad_reply", "note must be a string"));
167
+ const rep = { comment: id, decline: mode === "decline", note: r.note || autoNote(r, mode), opIndexes: [] };
168
+ replies.push(rep);
169
+ if (mode === "decline") {
170
+ if (r.decline !== true) errors.push(bad(id, "bad_reply", "decline must be true"));
171
+ return;
172
+ }
173
+ if (mode === "ops") {
174
+ if (!Array.isArray(r.ops) || !r.ops.length || !r.ops.every(isObj)) return errors.push(bad(id, "bad_reply", "ops must be a non-empty array of full ops"));
175
+ for (const op of r.ops) (rep.opIndexes.push(ops.length), ops.push(op), owners.push(id));
176
+ return;
177
+ }
178
+ // shorthand: the anchor of this comment supplies target and expect
179
+ const anchor = anchors.get(byId.get(id).anchor_id);
180
+ const hash = anchor?.resolved ? anchor.locator?.text_hash : null;
181
+ const refuse = (code, reason, fix) => errors.push(bad(id, code, reason, fix));
182
+ if (!anchor?.resolved || !anchor.locator) return refuse("anchor_unresolved", "this comment's anchor did not resolve to a place in the file", "decline it, or send full `ops` with your own target");
183
+ if (!hash) return refuse("anchor_has_no_hash", "this anchor carries no text hash to check against (an empty or whole-sheet or slide-level anchor)", "send full `ops` with your own target and expect, or decline");
184
+ const base = { id, target: { anchor_id: anchor.id }, expect: { text_hash: hash } };
185
+ let op;
186
+ if (mode === "find") {
187
+ if (typeof r.find !== "string" || !r.find || typeof r.replace !== "string") return refuse("bad_reply", "find needs a non-empty string and replace needs a string");
188
+ const extras = Object.fromEntries(SHORTHAND_EXTRAS.filter((k) => k in r).map((k) => [k, r[k]]));
189
+ if (format === "docx") op = { op: "replace_text", ...base, find: r.find, replace: r.replace, ...extras };
190
+ else if (format === "pptx") op = { op: "replace_text_in_shape", ...base, find: r.find, replace: r.replace, ...extras };
191
+ else return refuse("shorthand_not_for_format", "find/replace does not apply to a .xlsx cell", "use `set` for a cell or range");
192
+ } else if (mode === "text") {
193
+ if (typeof r.text !== "string") return refuse("bad_reply", "text must be a string");
194
+ if (format === "docx") op = { op: "replace_text", ...base, text: r.text };
195
+ else if (format === "pptx") op = { op: "set_shape_text", ...base, paragraphs: r.text.split("\n") };
196
+ else return refuse("shorthand_not_for_format", "text does not apply to a .xlsx cell", "use `set` for a cell or range");
197
+ } else if (mode === "set") {
198
+ if (format !== "xlsx") return refuse("shorthand_not_for_format", `set applies to a .xlsx cell or range, not a .${format}`, "use `find`+`replace` or `text`");
199
+ op = { op: "set_cells", ...base, values: r.set };
200
+ }
201
+ rep.opIndexes.push(ops.length);
202
+ ops.push(op);
203
+ owners.push(id);
204
+ });
205
+
206
+ (input.ops || []).forEach((op) => {
207
+ if (!isObj(op)) return errors.push(bad(null, "bad_reply", "every entry of ops must be an op object"));
208
+ ops.push(op);
209
+ owners.push(null);
210
+ });
211
+
212
+ const missing = comments.filter((c) => !seen.has(c.id)).map((c) => c.id);
213
+ if (missing.length && !partial) errors.push(bad(null, "missing_reply", `no reply for comment(s): ${missing.join(", ")}`, "answer every comment (decline what you will not do), or pass --partial"));
214
+ return { ops, owners, replies, errors };
215
+ }
216
+
217
+ /** The run's summary when the agent gave none. A change that answered only the overall note has no comment to count, so `written` says it. */
218
+ export function autoSummaryText({ applied, declined, asked, written, userEdits = 0 }) {
219
+ const parts = [applied ? `${applied} changed` : "", declined ? `${declined} declined` : "", asked ? `${asked} question${asked > 1 ? "s" : ""}` : ""].filter(Boolean);
220
+ if (parts.length) return parts.join(", ");
221
+ if (written) return "Changed the file as your note asked";
222
+ // a Send that carried only the person's own edits: they are in the file already, so "No change needed" alone reads as if nothing was kept
223
+ return userEdits ? "Your edits are saved. Nothing else needed changing." : "No change needed";
224
+ }
225
+
226
+ /**
227
+ * A review batch (instructions.review): the answer is `suggest` only. Nothing is written, so no ops and no replies. The checks are the ones
228
+ * `done` makes against the file (src/review.js), here against the batch's units, so the agent learns what to fix before anything is sent.
229
+ */
230
+ function planSuggestions(batch, input) {
231
+ const errors = [];
232
+ const none = { ops: [], owners: [], replies: [] };
233
+ if (input.ops !== undefined || (input.replies !== undefined && !(Array.isArray(input.replies) && input.replies.length === 0))) errors.push(bad(null, "review_only", "this batch is a review: change nothing", `answer with {"suggest":[...]} only (${SUGGEST_FIX})`));
234
+ if (input.summary !== undefined && typeof input.summary !== "string") errors.push(bad(null, "bad_reply", "summary must be a string"));
235
+ const list = input.suggest ?? [];
236
+ if (!Array.isArray(list)) errors.push(bad(null, "bad_suggestion", "suggest must be a list", SUGGEST_FIX));
237
+ else if (list.length > SUGGESTIONS_MAX) errors.push(bad(null, "too_many_suggestions", `at most ${SUGGESTIONS_MAX} suggestions (got ${list.length}); more than that and none would be shown`, "keep the most important ones"));
238
+ else {
239
+ const units = batch.untrusted_document_evidence?.units || [];
240
+ list.forEach((raw, i) => {
241
+ const c = cleanSuggestion(raw, units, batch.format);
242
+ if (c.reason) errors.push(bad(null, "bad_suggestion", `suggest[${i}]: ${c.reason}`, SUGGEST_FIX));
243
+ });
244
+ }
245
+ return { ...none, errors, suggestions: Array.isArray(list) ? list : [] };
246
+ }
247
+
248
+ /**
249
+ * A voice guide request (instructions.voice_request): the answer is `voice_draft` only, a Markdown draft of the guide. Nothing is written,
250
+ * so no replies, ops or suggest. The check is the one `done` makes (cleanVoiceDraft), here only so the agent learns what to fix.
251
+ */
252
+ function planVoiceDraft(input) {
253
+ const errors = [];
254
+ if (input.ops !== undefined || input.suggest !== undefined || (input.replies !== undefined && !(Array.isArray(input.replies) && input.replies.length === 0))) errors.push(bad(null, "voice_only", "this batch asks for a draft of the voice guide: change nothing", 'answer with {"voice_draft": "..."} only, no replies, ops or suggest'));
255
+ if (input.summary !== undefined && typeof input.summary !== "string") errors.push(bad(null, "bad_reply", "summary must be a string"));
256
+ const d = cleanVoiceDraft(input.voice_draft);
257
+ if (d.code) errors.push(bad(null, "bad_voice_draft", input.voice_draft === undefined ? "voice_draft is missing" : `${d.code}: ${d.reason}`, VOICE_FIX));
258
+ return { ops: [], owners: [], replies: [], errors };
259
+ }
260
+
261
+ const FIX = {
262
+ expect_mismatch: "The text there is not what the batch said (the file changed since). Decline this comment, or poll again for a fresh batch.",
263
+ anchor_not_found: "Read the reason: the find text must occur in the anchor (once, or add occurrence/all), or the anchor no longer resolves to one place. Correct the reply, decline this comment, or send full `ops` with an explicit target.",
264
+ skipped_protected: "Protected place (field, equation, content control or similar): it cannot be rewritten losslessly. Decline this comment with a note.",
265
+ };
266
+ const fixFor = (r) => FIX[r.status] || (r.status === "refused" ? `Refused by the engine${r.code ? ` (${r.code})` : ""}. Change the op as the reason says, or decline.` : undefined);
267
+ const brief = (comment, r) => ({ comment, op: r.op, status: r.status, ...(r.code ? { code: r.code } : {}), ...(r.reason ? { reason: r.reason } : {}), ...(r.actual_excerpt ? { actual_excerpt: r.actual_excerpt } : {}), ...(fixFor(r) ? { fix: fixFor(r) } : {}) });
268
+
269
+ /**
270
+ * The command. `deps` = {server: {healthy, req, json}, finish(file, results, lease) -> done's JSON, pollNext(file, timeout) -> string, readStdin(), holder?}.
271
+ * Returns {exit, body, next, emitted} where `body` is the JSON object for stdout (already written through `deps.emitBody` when `emitted`) and `next` (with --then-poll) the second line; a failed wait becomes {status: "poll_failed"}.
272
+ * Throws ReplyError for input problems; everything it prints is JSON on stdout.
273
+ */
274
+ export async function replyCommand(rest, deps) {
275
+ let a;
276
+ try {
277
+ a = parseReplyArgs(rest);
278
+ } catch (err) {
279
+ throw new ReplyError(err.message);
280
+ }
281
+ const { server } = deps;
282
+ if (!a.file) {
283
+ // no file given: the ticket's batch id names the session (the token is still checked by apply and done)
284
+ if (!(await server.healthy())) throw new ReplyError(`the ${PRODUCT.name} server is not running, so the delivery named by --lease cannot be checked. Nothing was written.`, { exit: APPLY_EXIT.write_refused });
285
+ const w = await server.req({ method: "GET", path: `/cli/batch-file?batch_id=${encodeURIComponent(parseTicket(a.lease)?.batch_id || "")}` });
286
+ a.file = w.status === 200 ? server.json(w.text).file || "" : "";
287
+ if (!a.file) throw new ReplyError(`No delivered batch matches this ticket: your delivery was taken back, finished or handed on. Nothing was written. Run \`${PRODUCT.bin} poll <file>\` again.`, { exit: APPLY_EXIT.write_refused, body: { code: "stale_batch" } });
288
+ }
289
+ let real;
290
+ try {
291
+ real = fs.realpathSync(path.resolve(a.file));
292
+ } catch {
293
+ throw new ReplyError(`File not found: ${JSON.stringify(a.file.slice(0, 200))}`, { exit: APPLY_EXIT.error });
294
+ }
295
+ if (!FORMATS[path.extname(real).toLowerCase().slice(1)]) throw new ReplyError("Only .docx, .xlsx and .pptx files are supported");
296
+ const ticket = parseTicket(a.lease);
297
+ if (!ticket) throw new ReplyError(`--lease <ticket> is required: it is the lease_ticket of the batch (\`${PRODUCT.bin} status <file> --ticket\` prints it again)`);
298
+ const bg = !deps.holder && isAgentHolder(process.env[`${PRODUCT.envPrefix}_HOLDER`]);
299
+ if (bg) checkBackgroundInput(a, process.env[`${PRODUCT.envPrefix}_AGENT_DIR`], ticket.batch_id);
300
+ const input = await readInput(a, deps.readStdin, { quiet: bg });
301
+
302
+ // the batch the session holds for this delivery: the only source of anchors and hashes
303
+ if (!(await server.healthy())) throw new ReplyError(`the ${PRODUCT.name} server is not running, so the delivery named by --lease cannot be checked. Nothing was written.`, { exit: APPLY_EXIT.write_refused });
304
+ const r = await server.req({ method: "GET", path: `/cli/batch?file=${encodeURIComponent(real)}` });
305
+ const held = r.status === 200 ? server.json(r.text).batch : null;
306
+ if (!held) throw new ReplyError(`No batch is delivered for this file, so the ticket is void. Nothing was written. Run \`${PRODUCT.bin} poll\` and wait for the user's Send.`, { exit: APPLY_EXIT.write_refused, body: { code: "no_batch" } });
307
+ if (held.batch_id !== ticket.batch_id) throw new ReplyError(`The ticket belongs to batch ${ticket.batch_id}, but the delivered batch is ${held.batch_id}: your delivery was taken back, finished or handed on. Nothing was written. Run \`${PRODUCT.bin} poll\` again.`, { exit: APPLY_EXIT.write_refused, body: { code: "stale_batch" } });
308
+
309
+ const plan = planReplies(held, input, { partial: a.partial });
310
+ if (plan.errors.length) throw new ReplyError("the reply cannot be applied; nothing was written and the batch is still open", { body: { code: "bad_reply", lease_kept: true, problems: plan.errors } });
311
+
312
+ const failedReplies = new Map(); // comment id -> first failing op result (partial mode)
313
+ const partlyApplied = new Map(); // comment id -> note: some of its ops applied, some did not (partial mode)
314
+ let written = false;
315
+ let opsApplied = 0;
316
+ let problems = [];
317
+ if (plan.ops.length) {
318
+ let out;
319
+ try {
320
+ // deps.holder: the local runner names its own holder, so an ONIONSKIN_HOLDER in the server's environment cannot stand in for it
321
+ out = await applyCommand([real, "--lease", a.lease, ...(a.partial ? ["--partial"] : []), ...(deps.holder ? ["--holder", deps.holder] : [])], server, { ops: { schema: "onionskin.ops/1", ops: plan.ops }, batch: held });
322
+ } catch (err) {
323
+ if (!(err instanceof ApplyError)) throw err;
324
+ const rep = err.report;
325
+ const mapped = rep?.errors ? rep.errors.map((e) => ({ comment: plan.owners[Number(/^\$\.ops\[(\d+)\]/.exec(e)?.[1])] ?? null, error: e })) : undefined;
326
+ throw new ReplyError(err.message, { exit: err.exit, body: { code: rep?.status || (err.exit === APPLY_EXIT.write_refused ? "write_refused" : "apply_failed"), ...(rep?.status === "invalid_ops" ? { lease_kept: true } : {}), ...(mapped ? { problems: mapped } : {}), ...(rep?.write_error ? { write_error: rep.write_error } : {}), ...(rep?.outside_change ? { outside_change: rep.outside_change } : {}) } });
327
+ }
328
+ const { report, exit } = out;
329
+ written = !!report.written;
330
+ opsApplied = report.results.filter((x) => x.status === "applied").length;
331
+ const failed = report.results.filter((x) => x.status !== "applied");
332
+ problems = failed.filter((x) => x.status !== "not_applied").map((x) => brief(plan.owners[x.index], x));
333
+ const stopped = report.status === "outside_change" || (exit !== APPLY_EXIT.ok && !(a.partial && exit === APPLY_EXIT.partial));
334
+ if (stopped) {
335
+ // nothing was finished: the batch stays delivered, the lease is kept, the agent fixes the named replies and calls again
336
+ throw new ReplyError(report.note || "the ops did not apply; nothing was written and the batch is still open", {
337
+ exit,
338
+ body: { code: report.status || (report.written === false && report.write_error ? "write_refused" : "not_applied"), written: false, ...(exit === APPLY_EXIT.not_applied || report.blocked_by_safety_check ? { lease_kept: true } : {}), problems, ...(report.blocked_by_safety_check ? { blocked_by_safety_check: report.blocked_by_safety_check } : {}), ...(report.write_error ? { write_error: report.write_error } : {}), ...(report.outside_change ? { outside_change: report.outside_change } : {}) },
339
+ });
340
+ }
341
+ const failedIdx = new Set(failed.map((x) => x.index));
342
+ for (const x of failed) {
343
+ const c = plan.owners[x.index];
344
+ if (!c || failedReplies.has(c)) continue;
345
+ const mine = plan.replies.find((rep) => rep.comment === c)?.opIndexes || [];
346
+ // several ops, only some failed: the edit is partly in the file, so the comment is not reported as declined
347
+ if (mine.length > 1 && mine.some((i) => !failedIdx.has(i))) partlyApplied.set(c, `${mine.filter((i) => failedIdx.has(i)).length} of ${mine.length} ops did not apply (${x.code || x.status})`);
348
+ else failedReplies.set(c, x);
349
+ }
350
+ }
351
+
352
+ // results for done: built from the replies, never from the agent's idea of what happened
353
+ const applied = [];
354
+ const declined = [];
355
+ const asked = [];
356
+ const results = plan.replies.map((rep) => {
357
+ if (rep.ask) {
358
+ asked.push(rep.comment);
359
+ return { comment_id: rep.comment, status: "asked", ask: rep.question.text, options: rep.question.options };
360
+ }
361
+ const f = failedReplies.get(rep.comment);
362
+ if (rep.decline || f) {
363
+ declined.push(rep.comment);
364
+ const why = f ? `Not applied (${f.code || f.status}).${rep.note ? ` ${rep.note}` : ""}` : rep.note;
365
+ return { comment_id: rep.comment, status: "declined", note: why };
366
+ }
367
+ applied.push(rep.comment);
368
+ const part = partlyApplied.get(rep.comment);
369
+ return { comment_id: rep.comment, status: "done", note: part ? `Partly applied: ${part}.${rep.note ? ` ${rep.note}` : ""}` : rep.note };
370
+ });
371
+ const autoSummary = autoSummaryText({ applied: applied.length, declined: declined.length, asked: asked.length, written, userEdits: held.untrusted_document_evidence?.user_edits?.length || 0 });
372
+ const review = !!held.instructions?.review;
373
+ const voice = !!held.instructions?.voice_request;
374
+ const ignoredField = input.document_instructions_ignored !== undefined ? { document_instructions_ignored: input.document_instructions_ignored } : {};
375
+ // a review's suggestions and a voice draft go to done as the agent wrote them: done checks them again (the trust boundary)
376
+ const finishBody = voice
377
+ ? { summary: input.summary || "Drafted a voice guide.", results: [], voice_draft: input.voice_draft, ...ignoredField }
378
+ : { summary: input.summary || (review ? "" : autoSummary), results, ...(review ? { suggestions: plan.suggestions } : {}), ...ignoredField };
379
+ let j;
380
+ try {
381
+ j = await deps.finish(real, finishBody, a.lease);
382
+ } catch (err) {
383
+ throw new ReplyError(`${written ? "The edit is in the file, but " : ""}the batch could not be finished: ${err.message}`, { exit: APPLY_EXIT.error, body: { code: "done_failed", written, results: finishBody } });
384
+ }
385
+ const body = {
386
+ ok: !!j.ok,
387
+ // `applied` lists comment ids only: a reply whose ops answered the overall note has none, so these two say whether the file changed
388
+ changed: written,
389
+ ops_applied: opsApplied,
390
+ applied,
391
+ declined,
392
+ asked,
393
+ ...(problems.length ? { not_applied: problems } : {}),
394
+ ...(review ? { suggested: Number(j.suggestions) || 0, not_shown: Number(j.dropped) || 0 } : {}),
395
+ // "received": kept for the user to review (they read and approve every word before it is saved); "not_kept": done refused it
396
+ ...(voice ? { voice_draft: j.voice_draft === "kept" ? "received" : "not_kept" } : {}),
397
+ flags: j.flags || [],
398
+ ...(j.checks?.notice ? { checks_notice: j.checks.notice } : {}),
399
+ };
400
+ if (!a.thenPoll) return { exit: APPLY_EXIT.ok, body, next: null };
401
+ // the batch is finished: say so first, so a kill or a failure while waiting for the next batch never hides the result
402
+ if (deps.emitBody) await deps.emitBody(body);
403
+ let next;
404
+ try {
405
+ next = await deps.pollNext(real, a.timeout);
406
+ } catch (err) {
407
+ next = { status: "poll_failed", error: String(err?.message || err).slice(0, 300) };
408
+ }
409
+ return { exit: APPLY_EXIT.ok, body, next, emitted: !!deps.emitBody };
410
+ }