@0perator/operator 0.1.332 → 0.1.334

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 (37) hide show
  1. package/dist/auth/byo.js +5 -0
  2. package/dist/auth/commands.js +1 -1
  3. package/dist/cli.js +2 -1
  4. package/dist/config/persona.js +42 -7
  5. package/dist/config/settings.js +29 -5
  6. package/dist/engine/agent.js +57 -4
  7. package/dist/engine/anthropic-chat.js +4 -4
  8. package/dist/engine/aurora.js +8 -1
  9. package/dist/engine/compaction.js +4 -2
  10. package/dist/engine/decision-points.js +78 -0
  11. package/dist/engine/moa.js +4 -1
  12. package/dist/engine/router-adapter.js +2 -0
  13. package/dist/engine/selfheal.js +41 -0
  14. package/dist/router/free-models.js +3 -2
  15. package/dist/router/models.js +15 -6
  16. package/dist/services/preflight.js +17 -2
  17. package/dist/session.js +25 -13
  18. package/dist/tools/doc-text.js +129 -0
  19. package/dist/tools/paths.js +13 -1
  20. package/dist/tools/registry.js +117 -44
  21. package/dist/tools/vision-gateway.js +55 -0
  22. package/dist/ui/QuestionPrompt.js +4 -3
  23. package/dist/ui/modelPicker.js +2 -2
  24. package/package.json +1 -1
  25. package/dist/engine/cli.js +0 -1171
  26. package/dist/router/models.js.bak +0 -78
  27. package/dist/router/models.js.bak-1791259923 +0 -78
  28. package/dist/router/models.js.bak-pre-gateway +0 -78
  29. package/dist/router/models.js.bak-pre-patch2 +0 -78
  30. package/dist/router/models.js.bak2 +0 -78
  31. package/dist/services/model-autodetect.js +0 -240
  32. package/dist/tools/native-redirect.js +0 -140
  33. package/dist/tools/power-tools.js +0 -627
  34. package/dist/tools/registry.js.bak-1791259948 +0 -1914
  35. package/dist/tools/registry.js.bak-pre-plugins +0 -1914
  36. package/dist/ui/BusTray.js +0 -70
  37. package/dist/ui/resize.js +0 -160
@@ -85,7 +85,8 @@ export function freeModelLabel(id) {
85
85
  }
86
86
  function freeProfile(row, preset) {
87
87
  const params = paramsFromId(row.id);
88
- const expiry = Object.entries(PROMO_EXPIRY).find(([frag]) => row.id.includes(frag))?.[1];
88
+ const stated = typeof row.expiration_date === "string" && /^\d{4}-\d{2}-\d{2}/.test(row.expiration_date) ? row.expiration_date.slice(0, 10) : undefined;
89
+ const expiry = stated ?? Object.entries(PROMO_EXPIRY).find(([frag]) => row.id.includes(frag))?.[1];
89
90
  return {
90
91
  id: `${preset.account}-${freeModelSlug(row.id)}`,
91
92
  label: freeModelLabel(row.id),
@@ -93,7 +94,7 @@ function freeProfile(row, preset) {
93
94
  box: `${preset.box ?? preset.label} · free`,
94
95
  kind: "single",
95
96
  tier: "free",
96
- desc: `${FREE_TIER_CAVEAT}${expiry ? `, expires ${expiry}` : ""}`,
97
+ desc: `${preset.freeCaveat ?? FREE_TIER_CAVEAT}${expiry ? `, expires ${expiry}` : ""}`,
97
98
  endpoint: preset.endpoint,
98
99
  model: row.id,
99
100
  ctx: typeof row.context_length === "number" && row.context_length > 0 ? row.context_length : DEFAULT_FREE_CTX,
@@ -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,11 +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
  ];
140
+ export const OPERATOR_FREE_ACCOUNT = "0perator";
135
141
  export const BYO_PRESETS = {
136
142
  openai: { label: "OpenAI", box: "OpenAI", endpoint: "https://api.openai.com/v1", model: "gpt-5", ctx: 272000, account: "openai", envAlias: "OPENAI_API_KEY" },
137
- 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" },
138
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 },
139
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" },
140
146
  deepseek: { label: "DeepSeek", box: "DeepSeek", endpoint: "https://api.deepseek.com/v1", model: "deepseek-chat", ctx: 131072, account: "deepseek", envAlias: "DEEPSEEK_API_KEY" },
@@ -145,6 +151,9 @@ export const BYO_PRESETS = {
145
151
  qwen: { label: "QwenCloud", box: "QwenCloud", endpoint: QWEN_BASE, model: "qwen3.8-max", ctx: 262144, account: "qwen" },
146
152
  // Nous Portal — the free cloud tier (router/free-models.ts lists its `:free` rows once this key is connected;
147
153
  // the vendor requires an account even for free models). 50 RPM / 500k TPM; prompts may be used for training.
154
+ // 0perator's own free catalog (portal router behind AuthGate): the free models we serve with OUR provider accounts,
155
+ // listed for every signed-in Operator with no vendor key. The rows come from its /models (pricing 0).
156
+ operator: { label: "0perator Free", box: "0perator", endpoint: `https://${PRODUCT_API_HOST}/free/v1`, model: "nvidia/nemotron-3-ultra-550b-a55b:free", ctx: 262144, account: OPERATOR_FREE_ACCOUNT, transport: "openai", signIn: true, freeCaveat: "free via 0perator — the model's provider may log or train on prompts; shared rate limits" },
148
157
  nous: { label: "Nous Portal", box: "Nous", endpoint: NOUS_BASE, model: "reflection/beam-1.0-501b-a23b:free", ctx: 262144, account: "nous", transport: "openai", envAlias: "NOUS_API_KEY" },
149
158
  };
150
159
  /** The vendor env var a BYO account answers to (ByoPreset.envAlias), or undefined for an account no preset names. */
@@ -75,6 +75,19 @@ async function waitReady(url, okOnly, waitSec) {
75
75
  * mid-load model. If nothing is listening, restart the loaded job, else bootout any half-state and
76
76
  * bootstrap the plist fresh, then poll. Best-effort by construction — on a machine without that agent
77
77
  * every launchctl step fails and we return "down" with the reason so the caller shows the manual hint. */
78
+ /** A box not yet moved to the co.0perator.* labels (2026-10-28) still has the job under an older one: when the
79
+ * configured plist is not on disk but a legacy plist beside it is, drive that job instead of reporting "not installed". */
80
+ async function withLegacyLabel(cfg) {
81
+ if (!cfg.plistPath || !cfg.legacyLabels?.length || (await fileExists(expandHome(cfg.plistPath))))
82
+ return cfg;
83
+ const dir = cfg.plistPath.slice(0, cfg.plistPath.lastIndexOf("/"));
84
+ for (const legacy of cfg.legacyLabels) {
85
+ const plistPath = `${dir}/${legacy}.plist`;
86
+ if (await fileExists(expandHome(plistPath)))
87
+ return { ...cfg, launchdLabel: legacy, plistPath };
88
+ }
89
+ return cfg;
90
+ }
78
91
  async function ensureLaunchd(name, healthUrl, okOnly, cfg, onProgress) {
79
92
  const waitSec = cfg.waitSec ?? 45;
80
93
  const first = await probe(healthUrl, okOnly);
@@ -89,6 +102,7 @@ async function ensureLaunchd(name, healthUrl, okOnly, cfg, onProgress) {
89
102
  }
90
103
  if (cfg.autostart === false)
91
104
  return { name, state: "down", detail: "down (autostart off)" };
105
+ cfg = await withLegacyLabel(cfg);
92
106
  const label = cfg.launchdLabel;
93
107
  const uid = typeof process.getuid === "function" ? process.getuid() : NaN;
94
108
  if (!label || Number.isNaN(uid))
@@ -222,8 +236,9 @@ export function ensureVisionUp(url = "http://127.0.0.1:7788") {
222
236
  }
223
237
  const r = await ensureLaunchd("vision", `${url.replace(/\/$/, "")}/health`, true, {
224
238
  autostart: true,
225
- launchdLabel: "axe.vision-bot",
226
- plistPath: "~/Library/LaunchAgents/axe.vision-bot.plist",
239
+ launchdLabel: "co.0perator.vision",
240
+ plistPath: "~/Library/LaunchAgents/co.0perator.vision.plist",
241
+ legacyLabels: ["axe.vision-bot"],
227
242
  waitSec: 12, // qwen2.5vl:7b is an ollama-backed worker — a cold load is seconds, not minutes
228
243
  });
229
244
  const ok = r.state === "up" || r.state === "started";
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,129 @@
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
+ export async function extractDocText(path) {
108
+ const ext = docExt(path);
109
+ if (!DOC_TEXT_EXTS.has(ext))
110
+ return null;
111
+ try {
112
+ const r = ext === "pdf" ? await pdfText(path) : ext === "xlsx" ? await xlsxText(path) : ext === "pptx" ? await pptxText(path) : await textutilText(path);
113
+ if (!r)
114
+ return null;
115
+ const meaningful = r.text.replace(/--- (page|sheet|slide) \d+ ---/g, "").trim();
116
+ return meaningful ? r : null;
117
+ }
118
+ catch {
119
+ return null;
120
+ }
121
+ }
122
+ /** "PDFKit, 3 pages" / "xlsx (OOXML), 2 sheets" / "textutil" — the provenance line both readers print. */
123
+ export function describeDocText(path, doc) {
124
+ if (!doc.pages)
125
+ return doc.method;
126
+ const ext = docExt(path);
127
+ const unit = ext === "xlsx" ? "sheet" : ext === "pptx" ? "slide" : "page";
128
+ return `${doc.method}, ${doc.pages} ${unit}${doc.pages === 1 ? "" : "s"}`;
129
+ }
@@ -7,7 +7,8 @@
7
7
  // Node-free by construction (reads process.env only, no imports) so the tools module still loads in the
8
8
  // headless conformance runner. Only a LEADING ~ is a home reference: bare "~" and "~/rest"; "~user" (a
9
9
  // different account's home) and a ~ anywhere but the first character are left untouched, matching the shell.
10
- export function expandPath(p) {
10
+ export function expandPath(raw) {
11
+ const p = unshellPath(raw);
11
12
  const home = process.env.HOME ?? process.env.USERPROFILE ?? "";
12
13
  if (!home)
13
14
  return p;
@@ -17,6 +18,17 @@ export function expandPath(p) {
17
18
  return home + p.slice(1);
18
19
  return p;
19
20
  }
21
+ /** A path pasted from a terminal arrives shell-quoted: `~/Downloads/Expense\ Form.pdf` or `'~/My File.pdf'`. The file
22
+ * tools call fs directly, so the backslash or quotes become part of the name and the file "doesn't exist" — on
23
+ * 2026-10-28 that sent Quick Look a nonexistent path and image_analyze hung 47 minutes. Undo the quoting a shell
24
+ * would: one pair of wrapping quotes, and a backslash before a shell-special character. A backslash before
25
+ * anything else stays (Windows `C:\Users\x` is untouched). */
26
+ export function unshellPath(p) {
27
+ let s = p.trim();
28
+ if (s.length >= 2 && ((s.startsWith("'") && s.endsWith("'")) || (s.startsWith('"') && s.endsWith('"'))))
29
+ return s.slice(1, -1);
30
+ return s.replace(/\\([ ()'"&;|<>$`!*?[\]{}#=%^,])/g, "$1");
31
+ }
20
32
  /** Strip trailing slashes; keep "/" as "/". */
21
33
  function normPath(p) {
22
34
  if (!p)