@0perator/operator 0.1.333 → 0.1.335

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.
@@ -35,6 +35,11 @@ const ANTHROPIC_BASE = "https://api.anthropic.com/v1";
35
35
  const GEMINI_BASE = "https://generativelanguage.googleapis.com/v1beta/openai"; // Google's OpenAI-compatible surface — no native transport
36
36
  const GEMINI_CHAT_PATH = "/chat/completions"; // the base already carries its version: …/v1beta/openai/chat/completions
37
37
  const QWEN_BASE = "https://token-plan.maas.qwencloudapi.com/compatible-mode/v1";
38
+ /** Output ceilings (ModelProfile.maxOutput) — only where the vendor's limit is cited. Anthropic: the current Claude
39
+ * family's max_tokens ceiling (a larger value is a 400). QwenCloud qwen3.8-flash: the vendor's own 400 on JL2
40
+ * 2026-10-28 — "Range of max_tokens should be [1, 131072]". */
41
+ export const ANTHROPIC_MAX_OUTPUT = 128_000;
42
+ const QWEN_FLASH_MAX_OUTPUT = 131_072;
38
43
  const NOUS_BASE = "https://inference-api.nousresearch.com/v1";
39
44
  // Registry order IS picker order (visibleModels keeps it): fleet rows first (this box, then JL1), then the
40
45
  // connected-provider rows (hidden until their key is connected), then the by-id-only lanes, then MOA. Free
@@ -108,9 +113,9 @@ export const BUILTIN_MODELS = [
108
113
  // "anthropic" routes it through engine/anthropic-chat.ts (x-api-key auth from the BYO "anthropic" key; the
109
114
  // Operator token is NEVER sent here — authHeaders scoping + anthropic-chat's own key resolution). Model ids
110
115
  // are the vendor's complete 5.5-family ids (never a date suffix); ctx is the documented 1M, self-clamps to served truth.
111
- { id: "claude-opus", tier: "power_turbo", label: "Claude Opus 5.5", box: "Anthropic", kind: "single", desc: "BYO Anthropic — the strongest Claude (native Messages wire), your Anthropic key", endpoint: ANTHROPIC_BASE, model: "claude-opus-5-5", ctx: 1000000, byo: "anthropic", transport: "anthropic" },
112
- { id: "claude-sonnet", tier: "power_turbo", label: "Claude Sonnet 5.5", box: "Anthropic", kind: "single", desc: "BYO Anthropic — full tool-using delegate/chat target (native Messages wire), your Anthropic key", endpoint: ANTHROPIC_BASE, model: "claude-sonnet-5-5", ctx: 1000000, byo: "anthropic", transport: "anthropic" },
113
- { id: "claude-haiku", tier: "economy", label: "Claude Haiku 5.5", box: "Anthropic", kind: "single", desc: "BYO Anthropic — the fast, cheap Claude for light work, your Anthropic key", endpoint: ANTHROPIC_BASE, model: "claude-haiku-5-5", ctx: 1000000, byo: "anthropic", transport: "anthropic" },
116
+ { id: "claude-opus", tier: "power_turbo", label: "Claude Opus 5.5", box: "Anthropic", kind: "single", desc: "BYO Anthropic — the strongest Claude (native Messages wire), your Anthropic key", endpoint: ANTHROPIC_BASE, model: "claude-opus-5-5", ctx: 1000000, maxOutput: ANTHROPIC_MAX_OUTPUT, byo: "anthropic", transport: "anthropic" },
117
+ { id: "claude-sonnet", tier: "power_turbo", label: "Claude Sonnet 5.5", box: "Anthropic", kind: "single", desc: "BYO Anthropic — full tool-using delegate/chat target (native Messages wire), your Anthropic key", endpoint: ANTHROPIC_BASE, model: "claude-sonnet-5-5", ctx: 1000000, maxOutput: ANTHROPIC_MAX_OUTPUT, byo: "anthropic", transport: "anthropic" },
118
+ { id: "claude-haiku", tier: "economy", label: "Claude Haiku 5.5", box: "Anthropic", kind: "single", desc: "BYO Anthropic — the fast, cheap Claude for light work, your Anthropic key", endpoint: ANTHROPIC_BASE, model: "claude-haiku-5-5", ctx: 1000000, maxOutput: ANTHROPIC_MAX_OUTPUT, byo: "anthropic", transport: "anthropic" },
114
119
  // Gemini — BYO Google connectors over Google's OpenAI-compatible base (no native transport needed; the
115
120
  // strict openai dialect is what that surface accepts). Same "gemini" key account as the byo-model preset.
116
121
  { id: "gemini-pro", tier: "power_turbo", label: "Gemini 2.5 Pro", box: "Google", kind: "single", desc: "BYO Google — Gemini 2.5 Pro over the OpenAI-compatible base, your Gemini key", endpoint: GEMINI_BASE, model: "gemini-2.5-pro", ctx: 1000000, byo: "gemini", transport: "openai", chatPath: GEMINI_CHAT_PATH },
@@ -120,7 +125,7 @@ export const BUILTIN_MODELS = [
120
125
  // authHeaders NEVER sends the Operator token to this host. ctx starts conservative and self-clamps
121
126
  // to the served truth (observeContext).
122
127
  { id: "qwen3.8-max", tier: "power_turbo", label: "Qwen 3.8 Max", box: "QwenCloud", kind: "single", desc: "BYO QwenCloud Token Plan — credits from your plan", endpoint: QWEN_BASE, model: "qwen3.8-max", ctx: 262144, byo: "qwen", transport: "openai" },
123
- { id: "qwen3.8-flash", tier: "economy", label: "Qwen 3.8 Flash", box: "QwenCloud", kind: "single", desc: "BYO QwenCloud Token Plan — fast tier, your credits", endpoint: QWEN_BASE, model: "qwen3.8-flash", ctx: 262144, byo: "qwen", transport: "openai" },
128
+ { id: "qwen3.8-flash", tier: "economy", label: "Qwen 3.8 Flash", box: "QwenCloud", kind: "single", desc: "BYO QwenCloud Token Plan — fast tier, your credits", endpoint: QWEN_BASE, model: "qwen3.8-flash", ctx: 262144, maxOutput: QWEN_FLASH_MAX_OUTPUT, byo: "qwen", transport: "openai" },
124
129
  // ── by-id lanes (hidden from the picker, still resolve) ────────────────────────────────────────────────
125
130
  // The cloud slot of the SAME Aurora, folded out of the picker in 0.1.332 (one Aurora row; the cloud legs ride
126
131
  // in buildEndpointChain's failover chain). Reachable by id for scripts. api.0perator.co is AXE's OWN gateway
@@ -130,12 +135,12 @@ export const BUILTIN_MODELS = [
130
135
  { id: "axe-aurora-300k", tier: "power", label: "Aurora Code 1", params: "35B-A3B", box: "cloud", kind: "single", desc: "remote shared slot via api.0perator.co (api.axe.onl as fallback) — contended decode measured 1-4.6 tok/s vs local 24-47; cold >~100K prefills can hit the Cloudflare ~125s edge cutoff", endpoint: GATEWAY_BASE, endpoints: [GATEWAY_BASE, LEGACY_GATEWAY_BASE], model: "aurora-code-1", ctx: 307200, transport: "openai", hidden: true },
131
136
  { id: "operator-128k", tier: "economy", label: "Aurora Code 1", params: "35B-A3B", box: "JL2", kind: "single", desc: "128K context, lighter RAM (:8096) — slot not served on this fleet today; hidden from the picker, resolves by id when the slot comes up", endpoint: "http://127.0.0.1:8096/v1", model: "aurora-code-1", ctx: 131072, hidden: true },
132
137
  // ── orchestrated ────────────────────────────────────────────────────────────────────────────────────────
133
- { id: "moa", tier: "power_turbo", label: "MOA", box: "mixture of agents", kind: "orchestrated", desc: "the team slot — fans each turn to aurora-local + Cortana + Qwen2.5-Coder proposers (settings.moa, 60s fan-out, graceful per-draft failure) and synthesizes with local Aurora as agent-loop aggregator; roster + benchmark in _ai-docs" },
138
+ { id: "moa", tier: "power_turbo", label: "MOA", box: "mixture of agents", kind: "orchestrated", desc: "the team slot — each turn goes to Cortana + Dolphin 7B (JL1) through the 0perator gateway in parallel, then Cortana writes the answer (settings.moa overrides)" },
134
139
  ];
135
140
  export const OPERATOR_FREE_ACCOUNT = "0perator";
136
141
  export const BYO_PRESETS = {
137
142
  openai: { label: "OpenAI", box: "OpenAI", endpoint: "https://api.openai.com/v1", model: "gpt-5", ctx: 272000, account: "openai", envAlias: "OPENAI_API_KEY" },
138
- anthropic: { label: "Anthropic", box: "Anthropic", endpoint: ANTHROPIC_BASE, model: "claude-sonnet-5-5", ctx: 1000000, account: "anthropic", transport: "anthropic", envAlias: "ANTHROPIC_API_KEY" },
143
+ anthropic: { label: "Anthropic", box: "Anthropic", endpoint: ANTHROPIC_BASE, model: "claude-sonnet-5-5", ctx: 1000000, maxOutput: ANTHROPIC_MAX_OUTPUT, account: "anthropic", transport: "anthropic", envAlias: "ANTHROPIC_API_KEY" },
139
144
  gemini: { label: "Google (Gemini)", box: "Google", endpoint: GEMINI_BASE, model: "gemini-2.5-pro", ctx: 1000000, account: "gemini", envAlias: "GEMINI_API_KEY", chatPath: GEMINI_CHAT_PATH },
140
145
  groq: { label: "Groq", box: "Groq", endpoint: "https://api.groq.com/openai/v1", model: "llama-3.3-70b-versatile", ctx: 131072, account: "groq", envAlias: "GROQ_API_KEY" },
141
146
  deepseek: { label: "DeepSeek", box: "DeepSeek", endpoint: "https://api.deepseek.com/v1", model: "deepseek-chat", ctx: 131072, account: "deepseek", envAlias: "DEEPSEEK_API_KEY" },
package/dist/session.js CHANGED
@@ -31,6 +31,7 @@ import { withHooks } from "./hooks/index.js";
31
31
  import { Telemetry } from "./observability/index.js";
32
32
  import { runSelfImprove } from "./selfimprove/index.js";
33
33
  import { RollingSummarizer } from "./engine/rolling-summary.js";
34
+ import { decisionPointsEnabled } from "./engine/decision-points.js";
34
35
  import { createSleepScheduler } from "./consolidation/scheduler.js";
35
36
  /** The system-prompt directive for an extended-reasoning mode ("" when off). The owner watches the model's
36
37
  * reasoning stream live (dim, above the answer) and re-reads it in scrollback, so /think asks the model to
@@ -207,19 +208,21 @@ function makeAskTool(handler) {
207
208
  return {
208
209
  name: "ask_user",
209
210
  safe: false,
210
- description: "Ask the owner a single, clarifying multiple-choice question when the task is genuinely ambiguous " +
211
- "and a wrong assumption would waste real work. Blocks until they choose, then returns the chosen " +
212
- "option(s). Use SPARINGLY — prefer a sensible default and proceeding; never ask what you can determine " +
213
- "from the code or the request. Provide 2-4 concrete options — the owner ALWAYS also gets a free-text " +
214
- "'type your own' choice, so list the likely paths, don't try to enumerate every one. By default the " +
215
- "owner picks exactly ONE option; set multiSelect:true when the options are not mutually exclusive and " +
216
- "the owner may pick several (they toggle each with Space and confirm the set) — the reply then lists " +
217
- "every option they chose.",
211
+ description: "Put a decision to the owner as a multiple-choice question; blocks until they choose, then returns the " +
212
+ "chosen option(s). ASK at a decision point: before the first change of a new build, feature or multi-step " +
213
+ "refactor (offer your short plan as the first option), when there are 2+ genuinely different approaches, " +
214
+ "scopes or tradeoffs, or before a destructive/irreversible step. DON'T ask for routine work (a typo, a clear " +
215
+ "small edit, a bug you found, running a check) or for anything you can determine from the code or the request. " +
216
+ "Give 2-4 concrete options, the recommended one FIRST labelled \"(recommended)\", each a short line saying " +
217
+ "what happens — the owner ALWAYS also gets a free-text 'type your own' choice, so list the likely paths, " +
218
+ "don't enumerate every one. Once answered, proceed with that choice. By default the owner picks exactly ONE " +
219
+ "option; set multiSelect:true when the options are not mutually exclusive (they toggle each with Space and " +
220
+ "confirm the set) — the reply then lists every option they chose.",
218
221
  parameters: {
219
222
  type: "object",
220
223
  properties: {
221
- question: { type: "string", description: "The clarifying question, one sentence." },
222
- options: { type: "array", items: { type: "string" }, description: "2-4 concrete choices." },
224
+ question: { type: "string", description: "The decision, one sentence." },
225
+ options: { type: "array", items: { type: "string" }, description: "2-4 concrete choices, recommended first (labelled \"(recommended)\")." },
223
226
  multiSelect: { type: "boolean", description: "Allow the owner to select more than one option (default false = pick exactly one)." },
224
227
  },
225
228
  required: ["question", "options"],
@@ -353,6 +356,7 @@ export class Session {
353
356
  * outlives the 15s-abort classification); `operator run` headless MUST. Safe to call anytime, twice,
354
357
  * from anywhere: the pending promise is swapped and failures were already swallowed by the module. */
355
358
  async flushRouteShadow() { const p = this._shadowPending; this._shadowPending = Promise.resolve(); await p; }
359
+ decisionPoints;
356
360
  planMode = false; // /plan: research read-only + propose a plan, no mutations until the owner approves
357
361
  thinkMode = "off"; // /think, /ultrathink — extended reasoning
358
362
  recalled = false;
@@ -405,6 +409,7 @@ export class Session {
405
409
  reg.set("stop_agent", makeStopTool(cfg.stopAgent));
406
410
  if (cfg.askUser)
407
411
  reg.set("ask_user", makeAskTool(cfg.askUser));
412
+ this.decisionPoints = decisionPointsEnabled(cfg.decisionPoints);
408
413
  reg.set("self_status", makeSelfStatusTool(() => ({
409
414
  model: this.currentModel(),
410
415
  route: this.currentRoute(),
@@ -825,6 +830,8 @@ export class Session {
825
830
  token: token ?? (hasGatewayLeg && !requiresOperatorToken(ep) ? "" : undefined),
826
831
  transport: profile.transport,
827
832
  chatPath: profile.chatPath,
833
+ maxOutput: profile.maxOutput,
834
+ provider: profile.box,
828
835
  }));
829
836
  this.inner = new AuroraRouter(eps);
830
837
  this.router = this.wrap(this.inner);
@@ -1295,15 +1302,20 @@ export class Session {
1295
1302
  // these now.") gets one nudge to actually do it (≤2/turn) instead of finalizing. Off in plan mode — there
1296
1303
  // the text IS the deliverable ("I'll implement this once you approve") — and via KODE_TURN_CONTINUATION=0.
1297
1304
  turnContinuation: { enabled: process.env.KODE_TURN_CONTINUATION !== "0" && !this.planMode },
1305
+ // Decision points: a build turn's first change waits for the owner's choice of direction (ask_user). Off in
1306
+ // plan mode (the plan + exit picker IS the decision) and inert where ask_user isn't registered (headless).
1307
+ decisionPoints: { enabled: this.decisionPoints && !this.planMode },
1298
1308
  });
1299
1309
  this.telemetry.record({ type: "turn", rounds: res.rounds, toolCalls: res.toolCalls, interrupted: false, durationMs: Math.round(performance.now() - _t0), ctxPct: this.ctxPct(), stopReason: res.stopReason });
1300
- // MOA phase-0 ROUTE SHADOW (observability ONLY — routing is untouched): ON by default, opt out with
1301
- // KODE_MOA_SHADOW=0. Labels
1310
+ // MOA phase-0 ROUTE SHADOW (observability ONLY — routing is untouched): OPT-IN with KODE_MOA_SHADOW=1 (was on
1311
+ // by default until 0.1.334). Its classifier call goes to the SAME endpoint as the turn, and on a single-slot
1312
+ // llama-server (Cortana, --parallel 1) that 8-token call evicted the session's cached prompt after every turn:
1313
+ // the next round re-read ~42K tokens (~100 s) — measured on JL1 2026-10-28. Labels
1302
1314
  // the turn with the gate's own 9-label contract and appends {label, model-that-ran, cost} to
1303
1315
  // ~/.axe/operator/route-shadow/<date>.jsonl. The classifier runs as a BACKGROUND-priority call on
1304
1316
  // the endpoint gate (a main turn always outranks it) with a 15s abort, and routeShadowTurn swallows
1305
1317
  // every failure — observability that can degrade the observed thing is not observability.
1306
- if (process.env.KODE_MOA_SHADOW !== "0") {
1318
+ if (process.env.KODE_MOA_SHADOW === "1") {
1307
1319
  const prof = findModel(this.liveRegistry(), this.modelId);
1308
1320
  // Not on a vendor's paid wire: an 8-token classifier call per Claude turn costs money and returns nothing once the model thinks.
1309
1321
  const shadowBase = prof?.endpoint && prof.transport !== "anthropic" ? endpointBase(prof.endpoint) : undefined;
@@ -0,0 +1,151 @@
1
+ // Document → TEXT, so file_read and image_analyze read a PDF/DOCX/XLSX/PPTX by its words instead of a
2
+ // picture of page 1 (the Hermes read_extract model). Dependency-free: macOS PDFKit through the JXA ObjC
3
+ // bridge for PDF, `textutil` for the word-processor formats, and `unzip` + the OOXML parts for sheets and
4
+ // decks. Every extractor is time-bounded; a failure or an empty result returns null so the caller can
5
+ // fall back (image_analyze then renders the page for vision — the scanned-PDF case).
6
+ import { pexecFile } from "./exec.js";
7
+ export const DOC_TEXT_TIMEOUT_MS = 30_000;
8
+ const MAX_BUFFER = 32 * 1024 * 1024;
9
+ const TEXTUTIL_EXTS = new Set(["doc", "docx", "rtf", "rtfd", "html", "htm", "odt", "webarchive", "wordml"]);
10
+ export const DOC_TEXT_EXTS = new Set(["pdf", "xlsx", "pptx", ...TEXTUTIL_EXTS]);
11
+ export function docExt(path) {
12
+ const base = path.split(/[\\/]/).pop() || "";
13
+ return base.includes(".") ? (base.split(".").pop() || "").toLowerCase() : "";
14
+ }
15
+ const opts = { timeout: DOC_TEXT_TIMEOUT_MS, killSignal: "SIGKILL", maxBuffer: MAX_BUFFER };
16
+ // Pages joined with a form feed so the page count survives the trip through stdout.
17
+ const PDFKIT_JXA = `ObjC.import("PDFKit");
18
+ function run(argv) {
19
+ const d = $.PDFDocument.alloc.initWithURL($.NSURL.fileURLWithPath(argv[0]));
20
+ if (!d) return "";
21
+ const out = [];
22
+ for (let i = 0; i < d.pageCount; i++) { const s = d.pageAtIndex(i).string; out.push(s && !s.isNil() ? s.js : ""); }
23
+ return out.join("\\f");
24
+ }`;
25
+ async function pdfText(path) {
26
+ const { stdout } = await pexecFile("osascript", ["-l", "JavaScript", "-e", PDFKIT_JXA, path], opts);
27
+ const pages = stdout.replace(/\n$/, "").split("\f");
28
+ const text = pages.map((p, i) => (pages.length > 1 ? `--- page ${i + 1} ---\n${p.trim()}` : p.trim())).join("\n\n");
29
+ return { text, method: "PDFKit", pages: pages.length };
30
+ }
31
+ async function textutilText(path) {
32
+ try {
33
+ const { stdout } = await pexecFile("textutil", ["-convert", "txt", "-stdout", path], opts);
34
+ return { text: stdout, method: "textutil" };
35
+ }
36
+ catch (e) {
37
+ if (docExt(path) !== "docx")
38
+ throw e;
39
+ return docxText(path); // no textutil (non-macOS): read the OOXML body directly
40
+ }
41
+ }
42
+ async function zipList(path) {
43
+ const { stdout } = await pexecFile("unzip", ["-Z1", path], opts);
44
+ return stdout.split("\n").filter(Boolean);
45
+ }
46
+ async function zipPart(path, part) {
47
+ return (await pexecFile("unzip", ["-p", path, part], opts)).stdout;
48
+ }
49
+ const byNumber = (re) => (a, b) => Number((re.exec(a) || [])[1]) - Number((re.exec(b) || [])[1]);
50
+ export function xmlUnescape(s) {
51
+ return s.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&apos;/g, "'")
52
+ .replace(/&#(\d+);/g, (_m, d) => String.fromCodePoint(Number(d)))
53
+ .replace(/&#x([0-9a-f]+);/gi, (_m, h) => String.fromCodePoint(parseInt(h, 16)))
54
+ .replace(/&amp;/g, "&");
55
+ }
56
+ const runs = (xml, tag) => [...xml.matchAll(new RegExp(`<${tag}(?:\\s[^>]*)?>([^<]*)</${tag}>`, "g"))].map((m) => xmlUnescape(m[1]));
57
+ /** Sheet XML + the shared-string table → tab-separated rows. Shared (t="s"), inline (t="inlineStr") and
58
+ * literal values; formulas show their cached value. */
59
+ export function xlsxSheetRows(sheetXml, shared) {
60
+ const rows = [];
61
+ for (const row of sheetXml.matchAll(/<row\b[^>]*>([\s\S]*?)<\/row>/g)) {
62
+ const cells = [];
63
+ for (const c of row[1].matchAll(/<c\b([^>]*?)(?:\/>|>([\s\S]*?)<\/c>)/g)) {
64
+ const attrs = c[1];
65
+ const body = c[2] ?? "";
66
+ const t = (/\bt="([^"]+)"/.exec(attrs) || [])[1];
67
+ const v = (/<v>([^<]*)<\/v>/.exec(body) || [])[1];
68
+ cells.push(t === "s" ? (shared[Number(v)] ?? "") : t === "inlineStr" ? runs(body, "t").join("") : v != null ? xmlUnescape(v) : "");
69
+ }
70
+ while (cells.length && cells[cells.length - 1] === "")
71
+ cells.pop();
72
+ if (cells.length)
73
+ rows.push(cells.join("\t"));
74
+ }
75
+ return rows;
76
+ }
77
+ async function xlsxText(path) {
78
+ const parts = await zipList(path);
79
+ const shared = parts.includes("xl/sharedStrings.xml")
80
+ ? [...(await zipPart(path, "xl/sharedStrings.xml")).matchAll(/<si>([\s\S]*?)<\/si>/g)].map((m) => runs(m[1], "t").join(""))
81
+ : [];
82
+ const re = /^xl\/worksheets\/sheet(\d+)\.xml$/;
83
+ const sheets = parts.filter((p) => re.test(p)).sort(byNumber(re));
84
+ const out = [];
85
+ for (const s of sheets)
86
+ out.push(`--- sheet ${(re.exec(s) || [])[1]} ---\n${xlsxSheetRows(await zipPart(path, s), shared).join("\n")}`);
87
+ return { text: out.join("\n\n"), method: "xlsx (OOXML)", pages: sheets.length };
88
+ }
89
+ async function docxText(path) {
90
+ const xml = await zipPart(path, "word/document.xml");
91
+ const paras = [...xml.matchAll(/<w:p\b[^>]*>([\s\S]*?)<\/w:p>/g)].map((m) => runs(m[1], "w:t").join(""));
92
+ return { text: paras.join("\n"), method: "docx (OOXML)" };
93
+ }
94
+ async function pptxText(path) {
95
+ const re = /^ppt\/slides\/slide(\d+)\.xml$/;
96
+ const slides = (await zipList(path)).filter((p) => re.test(p)).sort(byNumber(re));
97
+ const out = [];
98
+ for (const s of slides) {
99
+ const xml = await zipPart(path, s);
100
+ const paras = [...xml.matchAll(/<a:p\b[^>]*>([\s\S]*?)<\/a:p>/g)].map((m) => runs(m[1], "a:t").join("")).filter((p) => p.trim());
101
+ out.push(`--- slide ${(re.exec(s) || [])[1]} ---\n${paras.join("\n")}`);
102
+ }
103
+ return { text: out.join("\n\n"), method: "pptx (OOXML)", pages: slides.length };
104
+ }
105
+ /** Extract a document's text, or null when the format isn't one we extract, the extractor is missing or
106
+ * fails, or the document carries no text layer (whitespace/page markers only). */
107
+ /** The path every extractor receives: absolute and an existing regular file, or null. Each extractor hands the path
108
+ * to a CLI as an argument (osascript after `-e <script>`, textutil, unzip); a relative "path" beginning with `-` was
109
+ * parsed as an OPTION — `-e<js>` ran as JavaScript from an auto-approved read tool (review of 0.1.334). An absolute
110
+ * path starts with "/" and can never be read as a flag. */
111
+ export async function safeDocPath(path) {
112
+ const nodePath = "node:path";
113
+ const nodeFs = "node:fs/promises"; // variable specifiers keep node out of the neutral graph
114
+ const { resolve } = await import(nodePath);
115
+ const { stat } = await import(nodeFs);
116
+ const abs = resolve(path);
117
+ if (!abs.startsWith("/"))
118
+ return null;
119
+ try {
120
+ return (await stat(abs)).isFile() ? abs : null;
121
+ }
122
+ catch {
123
+ return null;
124
+ }
125
+ }
126
+ export async function extractDocText(rawPath) {
127
+ const ext = docExt(rawPath);
128
+ if (!DOC_TEXT_EXTS.has(ext))
129
+ return null;
130
+ const path = await safeDocPath(rawPath);
131
+ if (!path)
132
+ return null;
133
+ try {
134
+ const r = ext === "pdf" ? await pdfText(path) : ext === "xlsx" ? await xlsxText(path) : ext === "pptx" ? await pptxText(path) : await textutilText(path);
135
+ if (!r)
136
+ return null;
137
+ const meaningful = r.text.replace(/--- (page|sheet|slide) \d+ ---/g, "").trim();
138
+ return meaningful ? r : null;
139
+ }
140
+ catch {
141
+ return null;
142
+ }
143
+ }
144
+ /** "PDFKit, 3 pages" / "xlsx (OOXML), 2 sheets" / "textutil" — the provenance line both readers print. */
145
+ export function describeDocText(path, doc) {
146
+ if (!doc.pages)
147
+ return doc.method;
148
+ const ext = docExt(path);
149
+ const unit = ext === "xlsx" ? "sheet" : ext === "pptx" ? "slide" : "page";
150
+ return `${doc.method}, ${doc.pages} ${unit}${doc.pages === 1 ? "" : "s"}`;
151
+ }
@@ -17,6 +17,17 @@ export function expandPath(p) {
17
17
  return home + p.slice(1);
18
18
  return p;
19
19
  }
20
+ /** Read-side only (tools/read-path.ts resolveReadPath): tried when the literal path does not exist. A path pasted from a terminal arrives shell-quoted: `~/Downloads/Expense\ Form.pdf` or `'~/My File.pdf'`. The file
21
+ * tools call fs directly, so the backslash or quotes become part of the name and the file "doesn't exist" — on
22
+ * 2026-10-28 that sent Quick Look a nonexistent path and image_analyze hung 47 minutes. Undo the quoting a shell
23
+ * would: one pair of wrapping quotes, and a backslash before a shell-special character. A backslash before
24
+ * anything else stays (Windows `C:\Users\x` is untouched). */
25
+ export function unshellPath(p) {
26
+ let s = p.trim();
27
+ if (s.length >= 2 && ((s.startsWith("'") && s.endsWith("'")) || (s.startsWith('"') && s.endsWith('"'))))
28
+ return s.slice(1, -1);
29
+ return s.replace(/\\([ ()'"&;|<>$`!*?[\]{}#=%^,])/g, "$1");
30
+ }
20
31
  /** Strip trailing slashes; keep "/" as "/". */
21
32
  function normPath(p) {
22
33
  if (!p)
@@ -0,0 +1,18 @@
1
+ // Read-side path resolution for the file tools. A path pasted from a terminal arrives shell-quoted
2
+ // (`~/Downloads/Expense\ Form.pdf`), so the literal name "doesn't exist" — on 2026-10-28 that sent Quick Look a
3
+ // nonexistent file and image_analyze hung 47 minutes. The quoting is undone ONLY when the literal path does not exist
4
+ // and the unquoted one does: a real file whose name contains a backslash, quotes or edge spaces is always read as
5
+ // typed, and writes never use this (a write must never land on a different file than the one named).
6
+ import { expandPath, unshellPath } from "./paths.js";
7
+ const nodeImport = (m) => import(m);
8
+ export async function resolveReadPath(raw, exists) {
9
+ const literal = expandPath(raw);
10
+ const check = exists ?? (async (p) => {
11
+ const { access } = await nodeImport("node:fs/promises");
12
+ return access(p).then(() => true, () => false);
13
+ });
14
+ if (!literal || (await check(literal)))
15
+ return literal;
16
+ const unquoted = expandPath(unshellPath(raw));
17
+ return unquoted !== literal && (await check(unquoted)) ? unquoted : literal;
18
+ }