@0perator/operator 0.1.313 → 0.1.322

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 (58) hide show
  1. package/dist/autonomy/agent-cli.js +6 -2
  2. package/dist/autonomy/cron.js +1 -1
  3. package/dist/autonomy/delegate.js +29 -4
  4. package/dist/autonomy/index.js +22 -0
  5. package/dist/autonomy/profile.js +1 -1
  6. package/dist/browser/cdp.js +1 -1
  7. package/dist/cli.js +128 -43
  8. package/dist/config/persona.js +29 -12
  9. package/dist/config/settings.js +12 -7
  10. package/dist/engine/agent.js +4 -2
  11. package/dist/engine/aurora.js +8 -3
  12. package/dist/engine/batch-scheduler.js +3 -3
  13. package/dist/engine/compaction.js +1 -1
  14. package/dist/engine/loop-guard.js +1 -1
  15. package/dist/engine/router-adapter.js +1 -0
  16. package/dist/idle/activity.js +20 -0
  17. package/dist/idle/index.js +5 -0
  18. package/dist/idle/monitor.js +71 -0
  19. package/dist/idle/policy.js +66 -0
  20. package/dist/idle/proc.js +22 -0
  21. package/dist/idle/reaper.js +69 -0
  22. package/dist/idle/session-record.js +59 -0
  23. package/dist/index.js +1 -1
  24. package/dist/mcp/config.js +72 -14
  25. package/dist/mcp/index.js +9 -2
  26. package/dist/memory/index.js +1 -1
  27. package/dist/permissions/index.js +22 -7
  28. package/dist/permissions/tier.js +1 -1
  29. package/dist/remote/host.js +20 -2
  30. package/dist/remote/safe-commands.js +38 -0
  31. package/dist/services/preflight.js +54 -2
  32. package/dist/services/store-sync.js +111 -0
  33. package/dist/session-teardown.js +10 -1
  34. package/dist/session.js +43 -1
  35. package/dist/skills/catalogue.js +1 -1
  36. package/dist/tools/chauffeur-native.js +155 -0
  37. package/dist/tools/chauffeur.js +14 -3
  38. package/dist/tools/download.js +229 -0
  39. package/dist/tools/executor.js +1 -1
  40. package/dist/tools/monitoring-tools.js +312 -0
  41. package/dist/tools/paths.js +154 -0
  42. package/dist/tools/registry.js +309 -18
  43. package/dist/tools/shell-jobs.js +5 -2
  44. package/dist/tools/shell-session.js +4 -2
  45. package/dist/tools/tool-output-spill.js +1 -1
  46. package/dist/ui/Composer.js +5 -2
  47. package/dist/ui/QuestionPrompt.js +1 -1
  48. package/dist/ui/ToolStep.js +16 -1
  49. package/dist/ui/liveTools.js +1 -1
  50. package/dist/util/mentions.js +1 -1
  51. package/dist/vault/store.js +1 -1
  52. package/mcp/README.md +88 -0
  53. package/mcp/ocr-macos.swift +45 -0
  54. package/mcp/powertools-media.mjs +464 -0
  55. package/mcp/powertools-toolbox.mjs +1114 -0
  56. package/mcp/powertools.md +210 -0
  57. package/mcp/powertools.mjs +861 -0
  58. package/package.json +2 -1
@@ -19,11 +19,16 @@ const COLOR = { selected: theme.muted, running: theme.running, done: theme.succe
19
19
  const KEY_ARGS = ["path", "file", "filename", "command", "cmd", "pattern", "url", "query", "workspace", "cwd", "name"];
20
20
  // Bulky payloads — never dumped (they'd bury the path and blow up the line); shown as a size instead.
21
21
  const BULK_ARGS = ["content", "text", "body", "data", "new_string", "old_string", "diff", "message"];
22
+ const SHELL_TOOLS = new Set(["bash", "shell_exec", "shell_background"]);
22
23
  export function argsPreview(args) {
23
24
  if (!args)
24
25
  return "";
25
26
  const parts = [];
26
27
  const seen = new Set();
28
+ // Shell tools with a description: show ONLY the description as the primary label (command goes dim below).
29
+ if (typeof args.description === "string" && args.description) {
30
+ return args.description;
31
+ }
27
32
  // 1) identifying keys, in full — the file name/path is the point, so it is NEVER clipped.
28
33
  for (const k of KEY_ARGS) {
29
34
  const v = args[k];
@@ -51,6 +56,16 @@ export function argsPreview(args) {
51
56
  }
52
57
  return parts.join(", ");
53
58
  }
59
+ /** For shell tools with a description, the command is shown dim beneath the description line. */
60
+ export function shellCommandHint(step) {
61
+ if (!SHELL_TOOLS.has(step.name) || !step.args?.description)
62
+ return null;
63
+ const cmd = step.args.command;
64
+ if (typeof cmd !== "string")
65
+ return null;
66
+ const trimmed = cmd.replace(/\s+/g, " ").trim();
67
+ return trimmed.length > 120 ? trimmed.slice(0, 117) + "..." : trimmed;
68
+ }
54
69
  export function ToolStep({ step }) {
55
70
  // ONE shared animation clock (tick.ts) drives both the per-action icon animation AND the live elapsed timer,
56
71
  // so a running row needs no setInterval of its own — this replaces N per-row 250ms timers with a single
@@ -71,5 +86,5 @@ export function ToolStep({ step }) {
71
86
  // lands. Only RUNNING media rows get the bar — everything else renders exactly as before.
72
87
  const isRunningMedia = toolKind(step.name) === "media" && step.status === "running";
73
88
  const mediaFraction = isRunningMedia && elapsed != null ? mediaProgressFraction(elapsed, mediaEtaMs(step.name, step.args)) : undefined;
74
- return (_jsxs(Box, { flexDirection: "column", children: [_jsxs(Text, { children: [_jsx(Text, { color: step.status === "running" ? KIND_HUE[toolKind(step.name)] : COLOR[step.status], bold: true, children: glyphFor(step.name, step.status, frame) }), " ", step.status === "running" ? _jsx(ShimmerText, { text: step.name, frame: frame, palette: huePalette(KIND_HUE[toolKind(step.name)]) }) : step.name, "(", argsPreview(step.args), ")", mediaFraction != null ? (_jsxs(Text, { children: [" ", _jsx(Text, { color: theme.mediaProgress, children: renderBar(mediaFraction) }), " ", Math.round(mediaFraction * 100), "%"] })) : null, elapsed != null ? _jsxs(Text, { dimColor: true, children: [" ", formatDuration(elapsed)] }) : null, editDiff ? (_jsxs(Text, { children: [" ", _jsxs(Text, { color: theme.success, children: ["+", editDiff.added] }), " ", _jsxs(Text, { color: theme.error, children: ["-", editDiff.removed] })] })) : null] }), rowBackgroundHint(step, now) ? _jsxs(Text, { dimColor: true, children: [" ", rowBackgroundHint(step, now)] }) : null, step.summary ? step.summary.split("\n").map((l, i) => (_jsxs(Text, { dimColor: true, children: [" ", l] }, `sm${i}`))) : null, editDiff?.preview?.map((l, i) => (_jsxs(Text, { color: l.kind === "add" ? theme.success : theme.error, children: [" ", l.kind === "add" ? "+ " : "- ", l.text] }, i)))] }));
89
+ return (_jsxs(Box, { flexDirection: "column", children: [_jsxs(Text, { children: [_jsx(Text, { color: step.status === "running" ? KIND_HUE[toolKind(step.name)] : COLOR[step.status], bold: true, children: glyphFor(step.name, step.status, frame) }), " ", step.status === "running" ? _jsx(ShimmerText, { text: step.name, frame: frame, palette: huePalette(KIND_HUE[toolKind(step.name)]) }) : step.name, "(", argsPreview(step.args), ")", mediaFraction != null ? (_jsxs(Text, { children: [" ", _jsx(Text, { color: theme.mediaProgress, children: renderBar(mediaFraction) }), " ", Math.round(mediaFraction * 100), "%"] })) : null, elapsed != null ? _jsxs(Text, { dimColor: true, children: [" ", formatDuration(elapsed)] }) : null, editDiff ? (_jsxs(Text, { children: [" ", _jsxs(Text, { color: theme.success, children: ["+", editDiff.added] }), " ", _jsxs(Text, { color: theme.error, children: ["-", editDiff.removed] })] })) : null] }), shellCommandHint(step) ? _jsxs(Text, { dimColor: true, children: [" ", shellCommandHint(step)] }) : null, rowBackgroundHint(step, now) ? _jsxs(Text, { dimColor: true, children: [" ", rowBackgroundHint(step, now)] }) : null, step.summary ? step.summary.split("\n").map((l, i) => (_jsxs(Text, { dimColor: true, children: [" ", l] }, `sm${i}`))) : null, editDiff?.preview?.map((l, i) => (_jsxs(Text, { color: l.kind === "add" ? theme.success : theme.error, children: [" ", l.kind === "add" ? "+ " : "- ", l.text] }, i)))] }));
75
90
  }
@@ -20,7 +20,7 @@ export function settleLiveTool(rows, id, result, now = Date.now()) {
20
20
  }
21
21
  const SHELL_TOOLS = new Set(["bash", "shell_exec"]);
22
22
  export const BACKGROUND_HINT_AFTER_MS = 2000;
23
- /** Inline per-row variant of the hint, under the running command itself (Claude Code parity). */
23
+ /** Inline per-row variant of the hint, under the running command itself (matches Claude Code). */
24
24
  export function rowBackgroundHint(step, now = Date.now(), inTmux = !!process.env.TMUX) {
25
25
  if (!SHELL_TOOLS.has(step.name) || step.status !== "running")
26
26
  return null;
@@ -1,4 +1,4 @@
1
- // @file mentions (parity with modern coding agents): when the owner types `@path`, inline that file's content into the
1
+ // @file mentions (matching modern coding agents): when the owner types `@path`, inline that file's content into the
2
2
  // SENT prompt (the visible message keeps the @path as typed). Only tokens that resolve to a real file are
3
3
  // expanded — `@someone` that isn't a path is left untouched — and each file is bounded + oversized/dir
4
4
  // paths are skipped, so a stray `@node_modules/...` can't blow the context. Matched at a word boundary so
@@ -1,5 +1,5 @@
1
1
  // Credential vault (HV3-02b) — origin-bound website logins for the browser, keychain-first.
2
- // THE CONTRACT (inherited from the Hermes playbook and enforced by test):
2
+ // THE CONTRACT (inherited from the reference playbook and enforced by test):
3
3
  // 1. Secrets NEVER enter model context: they are not returned by any tool, not accepted as tool
4
4
  // arguments, and not logged. Save happens on the CLI TTY (operator vault add); fill takes a
5
5
  // HANDLE + selectors only — the password goes straight from keychain into the page over CDP.
package/mcp/README.md ADDED
@@ -0,0 +1,88 @@
1
+ # kode-tsi MCP servers (stdio)
2
+
3
+ ## powertools (canonical — slices 1–5 + classics)
4
+
5
+ **Register as:** `powertools` (short alias `pt` fine in local config)
6
+ **File:** `powertools.mjs` (v0.4) + `powertools-toolbox.mjs` (§4) + `powertools-media.mjs` (`convert`/`scan`)
7
+ **Tests:** `../test/powertools-mcp.test.mjs` · `../test/powertools-media.test.mjs`
8
+ **Brief:** `../_ai-docs/2026-10-24-cli-power-mcp-brief.md`
9
+ **SOP:** `../_ai-docs/sops/brief-slice-protocol.md`
10
+ **Full catalogue:** [`powertools.md`](./powertools.md) — every tool, model usage, toolbox + media
11
+ **Classics map:** `../_ai-docs/research/2026-10-24-forgotten-powertools.md`
12
+
13
+ Zero-dep stdio JSON-RPC MCP.
14
+
15
+ | Tool | Binary | Notes |
16
+ |------|--------|--------|
17
+ | `json_query` | jq | inline or root path |
18
+ | `yaml_query` | yq | `--security-disable-file-ops` |
19
+ | `find_files` | fd | typed params only |
20
+ | `search_text` | rg | typed params only |
21
+ | `disk_usage` | duf | JSON mounts |
22
+ | `list_ports` | lsof | listening TCP |
23
+ | `hash_file` | shasum | SHA-1/256/512 |
24
+ | `hex_dump` | xxd | capped length |
25
+ | `dns_lookup` | dig | hostname + type only |
26
+ | `diff_files` | diff | unified, two root paths |
27
+ | `sqlite_query` | sqlite3 | `-readonly`; SELECT/WITH/PRAGMA |
28
+ | `process_list` | ps | fixed columns |
29
+ | `tool_status` | — | always present |
30
+ | §4 toolbox (25) | various | see `powertools.md` — file_info…watch_health_loop; mutate/SSH gated |
31
+ | `convert` | sips/ffmpeg | images/video/audio/pdf → typed formats; mutate gate |
32
+ | `scan` | tesseract / Vision + ffmpeg | OCR image/PDF; sample+OCR video frames (no VL) |
33
+
34
+ Guardrails: argv-only spawn, cleared `env: {}` (media uses allowlisted PATH/HOME overlay), `POWERTOOLS_ROOT` required (no cwd fail-open), soft-miss (missing bins omit tools — server still starts), 5s default timeout (media up to 180s), 64 KiB output cap. Mutate/SSH: `POWERTOOLS_ALLOW_MUTATE`, `POWERTOOLS_SSH_HOSTS`, `POWERTOOLS_SSH_CMDS`, `POWERTOOLS_RESPAWN_UNITS`.
35
+
36
+ ### Verify
37
+
38
+ ```bash
39
+ cd <repo-root> # e.g. /Users/jl2/work/kode-cli-power
40
+ node --test kode-tsi/test/powertools-mcp.test.mjs kode-tsi/test/powertools-media.test.mjs
41
+ ```
42
+
43
+ Core brew: `jq` `yq` `fd` `ripgrep` `duf` `ffmpeg` (`tesseract` on Linux for `scan`). Classics usually ship with macOS: `lsof` `shasum` `xxd` `dig` `diff` `sqlite3` `ps` `sips`.
44
+
45
+ ### Where Operator reads MCP config
46
+
47
+ 1. `$KODE_MCP_CONFIG` if set (base file), else operator-home / legacy `mcp_servers.json`
48
+ 2. **Merge-load:** if `$KODE_MCP_EXTRA` is set, that JSON is layered on top (same name → extra wins)
49
+
50
+ Secrets: sibling `.mcp_secrets.json` for `${VAR}` expansion.
51
+
52
+ ### Live drive (no restart)
53
+
54
+ ```text
55
+ /mcp add powertools /path/to/sandbox # upserts writable overlay + reload
56
+ /mcp reload # rediscover after editing config
57
+ /mcp on|off # saved setting
58
+ /mcp # status + per-server inventory
59
+ ```
60
+
61
+ Writable overlay: `$KODE_MCP_EXTRA` if set, else `$KODE_HOME/mcp_servers.json`.
62
+
63
+ Manual overlay still works:
64
+
65
+ ```bash
66
+ ROOT=/Users/jl2/work/kode-cli-power
67
+ export KODE_MCP_EXTRA=/tmp/powertools-extra.json
68
+ cat > "$KODE_MCP_EXTRA" <<EOF
69
+ {
70
+ "powertools": {
71
+ "command": "node",
72
+ "args": ["$ROOT/kode-tsi/mcp/powertools.mjs"],
73
+ "env": { "POWERTOOLS_ROOT": "$ROOT" }
74
+ }
75
+ }
76
+ EOF
77
+ operator
78
+ # /mcp reload
79
+ ```
80
+
81
+ ### Frozen / not this server
82
+
83
+ - `src/tools/cli-power.py` — frozen unsafe prototype; do not extend.
84
+ - Skills under `operator-home/skills-catalogue/cli-power/` — retargeted to powertools MCP / bash; do not point at `cli-power.py`.
85
+
86
+ ### Remote control
87
+
88
+ Follower `/mcp` stays **blocked** (`REMOTE_ESCALATION_COMMANDS`). Prefer `/pair` (QR e2e) over long-lived token RC when sharing a session.
@@ -0,0 +1,45 @@
1
+ #!/usr/bin/env swift
2
+ // ocr-macos.swift — Vision-framework OCR for powertools `scan` (macOS).
3
+ // Usage: swift ocr-macos.swift <image-path>
4
+ // argv-only; no network. Prints recognized text to stdout.
5
+
6
+ import Foundation
7
+ import Vision
8
+ import AppKit
9
+
10
+ guard CommandLine.arguments.count >= 2 else {
11
+ fputs("usage: ocr-macos.swift <image-path>\n", stderr)
12
+ exit(2)
13
+ }
14
+
15
+ let path = CommandLine.arguments[1]
16
+ guard FileManager.default.fileExists(atPath: path) else {
17
+ fputs("error: file not found\n", stderr)
18
+ exit(1)
19
+ }
20
+ guard let img = NSImage(contentsOfFile: path),
21
+ let tiff = img.tiffRepresentation,
22
+ let rep = NSBitmapImageRep(data: tiff),
23
+ let cg = rep.cgImage else {
24
+ fputs("error: could not decode image (try convert to=jpg first)\n", stderr)
25
+ exit(1)
26
+ }
27
+ if cg.width <= 2 || cg.height <= 2 {
28
+ fputs("error: image too small for OCR (need >2px each side)\n", stderr)
29
+ exit(1)
30
+ }
31
+
32
+ let request = VNRecognizeTextRequest()
33
+ request.recognitionLevel = .accurate
34
+ request.usesLanguageCorrection = true
35
+
36
+ let handler = VNImageRequestHandler(cgImage: cg, options: [:])
37
+ do {
38
+ try handler.perform([request])
39
+ } catch {
40
+ fputs("error: \(error.localizedDescription)\n", stderr)
41
+ exit(1)
42
+ }
43
+
44
+ let lines = (request.results ?? []).compactMap { $0.topCandidates(1).first?.string }
45
+ print(lines.joined(separator: "\n"))
@@ -0,0 +1,464 @@
1
+ // powertools-media.mjs — convert + scan (fleet media prep / OCR).
2
+ // Loaded by powertools.mjs. Same security contract: argv-only, path root, caps.
3
+ // Minimal allowlisted env (PATH/HOME/TMPDIR) for ffmpeg/sips/swift — never inherits process.env.
4
+
5
+ import { mkdir, mkdtemp, rm, access, copyFile } from "node:fs/promises";
6
+ import { join, extname, basename, dirname } from "node:path";
7
+ import { tmpdir } from "node:os";
8
+ import { fileURLToPath } from "node:url";
9
+
10
+ const HERE = fileURLToPath(new URL(".", import.meta.url));
11
+ const OCR_SWIFT = join(HERE, "ocr-macos.swift");
12
+
13
+ const IMAGE_IN = new Set(["heic", "heif", "jpg", "jpeg", "png", "webp", "gif", "tiff", "tif", "bmp", "jp2"]);
14
+ const IMAGE_OUT = new Set(["jpg", "jpeg", "png", "webp", "gif", "tiff", "bmp"]);
15
+ const VIDEO_IN = new Set(["mp4", "mov", "mkv", "webm", "avi", "m4v"]);
16
+ const VIDEO_OUT = new Set(["mp4", "webm", "gif", "jpg", "jpeg", "png"]); // jpg/png = frame extract
17
+ const AUDIO_IN = new Set(["mp3", "wav", "m4a", "aac", "flac", "ogg", "wma"]);
18
+ const AUDIO_OUT = new Set(["mp3", "wav", "m4a"]);
19
+ const DOC_IN = new Set(["pdf"]);
20
+
21
+ const MAX_EDGE = 4096;
22
+ const SCAN_MAX_FRAMES = 12;
23
+ const CONVERT_TIMEOUT_MS = 120_000;
24
+ const SCAN_TIMEOUT_MS = 180_000;
25
+
26
+ function mutateAllowed() {
27
+ return process.env.POWERTOOLS_ALLOW_MUTATE === "1" || process.env.POWERTOOLS_ALLOW_MUTATE === "true";
28
+ }
29
+
30
+ function extOf(p) {
31
+ return extname(p).toLowerCase().replace(/^\./, "");
32
+ }
33
+
34
+ function normalizeTo(to) {
35
+ const t = String(to || "").toLowerCase().replace(/^\./, "");
36
+ if (t === "jpeg") return "jpg";
37
+ return t;
38
+ }
39
+
40
+ /** Safe env overlay — absolute bins + these keys only (no inherited secrets). */
41
+ function mediaEnv() {
42
+ return {
43
+ PATH: "/usr/bin:/bin:/usr/sbin:/sbin:/opt/homebrew/bin:/usr/local/bin",
44
+ HOME: process.env.HOME || "/var/empty",
45
+ TMPDIR: process.env.TMPDIR || tmpdir(),
46
+ LANG: "C.UTF-8",
47
+ };
48
+ }
49
+
50
+ /**
51
+ * @param {object} S shared helpers from powertools.mjs
52
+ */
53
+ export function buildMedia(S) {
54
+ const {
55
+ findBinary,
56
+ resolveUnderRoot,
57
+ runCapped,
58
+ okText,
59
+ errText,
60
+ clampInt,
61
+ PROJECT_ROOT,
62
+ UNTRUSTED,
63
+ } = S;
64
+
65
+ const binCandidates = {
66
+ sips: ["/usr/bin/sips"],
67
+ ffmpeg: ["/opt/homebrew/bin/ffmpeg", "/usr/local/bin/ffmpeg", "/usr/bin/ffmpeg"],
68
+ ffprobe: ["/opt/homebrew/bin/ffprobe", "/usr/local/bin/ffprobe", "/usr/bin/ffprobe"],
69
+ tesseract: ["/opt/homebrew/bin/tesseract", "/usr/local/bin/tesseract", "/usr/bin/tesseract"],
70
+ qlmanage: ["/usr/bin/qlmanage"],
71
+ pdftoppm: ["/opt/homebrew/bin/pdftoppm", "/usr/local/bin/pdftoppm", "/usr/bin/pdftoppm"],
72
+ swift: ["/usr/bin/swift", "/usr/local/bin/swift"],
73
+ };
74
+
75
+ const B = {};
76
+ for (const [name, cands] of Object.entries(binCandidates)) {
77
+ B[name] = findBinary(name, cands);
78
+ }
79
+
80
+ function need(name) {
81
+ if (!B[name]) return errText(`error: binary '${name}' not installed on this host (soft-miss)`);
82
+ return null;
83
+ }
84
+
85
+ function runMedia(bin, argv, extra = {}) {
86
+ return runCapped(bin, argv, {
87
+ timeoutMs: CONVERT_TIMEOUT_MS,
88
+ env: mediaEnv(),
89
+ ...extra,
90
+ });
91
+ }
92
+
93
+ /** Resolve an output path that may not exist yet (parent must stay under root). */
94
+ async function resolveOutPath(outArg, defaultPath) {
95
+ const destArg = outArg || defaultPath;
96
+ const existing = await resolveUnderRoot(destArg);
97
+ if (!existing.error) return { path: existing.path };
98
+
99
+ const abs = destArg.startsWith("/") ? destArg : join(PROJECT_ROOT, destArg);
100
+ const parent = dirname(abs);
101
+ const rp = await resolveUnderRoot(parent);
102
+ if (rp.error) {
103
+ // parent may also be missing — walk up one more under root
104
+ const grand = dirname(parent);
105
+ const rg = await resolveUnderRoot(grand);
106
+ if (rg.error) return { error: existing.error || rp.error };
107
+ await mkdir(parent, { recursive: true }).catch(() => {});
108
+ } else {
109
+ await mkdir(parent, { recursive: true }).catch(() => {});
110
+ }
111
+ const checkParent = await resolveUnderRoot(dirname(abs));
112
+ if (checkParent.error) return { error: checkParent.error };
113
+ // Lexical stay-under-root for the new file
114
+ const rootCheck = await resolveUnderRoot(dirname(abs));
115
+ if (rootCheck.error) return { error: rootCheck.error };
116
+ return { path: abs };
117
+ }
118
+
119
+ function defaultOutPath(srcPath, to) {
120
+ const base = basename(srcPath, extname(srcPath));
121
+ return join(dirname(srcPath), `${base}.${to}`);
122
+ }
123
+
124
+ async function convertImage(src, to, outPath, maxEdge) {
125
+ // Prefer sips on macOS for Apple formats (HEIC) and common rasters.
126
+ if (B.sips && ["jpg", "png", "tiff", "gif", "bmp", "jp2"].includes(to === "jpeg" ? "jpg" : to) && to !== "webp") {
127
+ const sipsFmt = to === "jpg" ? "jpeg" : to;
128
+ const argv = ["-s", "format", sipsFmt];
129
+ if (maxEdge) argv.push("-Z", String(maxEdge));
130
+ argv.push(src, "--out", outPath);
131
+ const r = await runMedia(B.sips, argv);
132
+ if (!r.isError) return okText(`converted → ${outPath}\nengine: sips\n${(r.content?.[0]?.text || "").trim()}`);
133
+ // fall through to ffmpeg
134
+ }
135
+ const miss = need("ffmpeg");
136
+ if (miss) return miss;
137
+ const argv = ["-nostdin", "-y", "-loglevel", "error", "-i", src];
138
+ if (maxEdge) {
139
+ argv.push("-vf", `scale='min(iw,${maxEdge})':'min(ih,${maxEdge})':force_original_aspect_ratio=decrease`);
140
+ }
141
+ if (to === "jpg" || to === "jpeg") argv.push("-q:v", "2");
142
+ argv.push(outPath);
143
+ const r = await runMedia(B.ffmpeg, argv);
144
+ if (r.isError) return r;
145
+ return okText(`converted → ${outPath}\nengine: ffmpeg`);
146
+ }
147
+
148
+ async function convertVideo(src, to, outPath, args) {
149
+ const miss = need("ffmpeg");
150
+ if (miss) return miss;
151
+ const ss = Number(args?.start_sec);
152
+ const dur = Number(args?.duration_sec);
153
+ // Frame extract
154
+ if (to === "jpg" || to === "jpeg" || to === "png") {
155
+ const argv = ["-nostdin", "-y", "-loglevel", "error"];
156
+ if (Number.isFinite(ss) && ss >= 0) argv.push("-ss", String(ss));
157
+ argv.push("-i", src, "-frames:v", "1", outPath);
158
+ const r = await runMedia(B.ffmpeg, argv);
159
+ if (r.isError) return r;
160
+ return okText(`frame extracted → ${outPath}\nengine: ffmpeg`);
161
+ }
162
+ const argv = ["-nostdin", "-y", "-loglevel", "error"];
163
+ if (Number.isFinite(ss) && ss >= 0) argv.push("-ss", String(ss));
164
+ argv.push("-i", src);
165
+ if (Number.isFinite(dur) && dur > 0) argv.push("-t", String(dur));
166
+ if (to === "gif") {
167
+ argv.push("-vf", "fps=10,scale=480:-1:flags=lanczos", outPath);
168
+ } else if (to === "webm") {
169
+ argv.push("-c:v", "libvpx-vp9", "-b:v", "0", "-crf", "32", "-c:a", "libopus", outPath);
170
+ } else {
171
+ argv.push("-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", "-movflags", "+faststart", outPath);
172
+ }
173
+ const r = await runMedia(B.ffmpeg, argv);
174
+ if (r.isError) return r;
175
+ return okText(`converted → ${outPath}\nengine: ffmpeg`);
176
+ }
177
+
178
+ async function convertAudio(src, to, outPath) {
179
+ const miss = need("ffmpeg");
180
+ if (miss) return miss;
181
+ const argv = ["-nostdin", "-y", "-loglevel", "error", "-i", src];
182
+ if (to === "mp3") argv.push("-codec:a", "libmp3lame", "-q:a", "2");
183
+ else if (to === "wav") argv.push("-codec:a", "pcm_s16le");
184
+ else argv.push("-codec:a", "aac", "-b:a", "192k"); // m4a
185
+ argv.push(outPath);
186
+ const r = await runMedia(B.ffmpeg, argv);
187
+ if (r.isError) return r;
188
+ return okText(`converted → ${outPath}\nengine: ffmpeg`);
189
+ }
190
+
191
+ async function convertDoc(src, to, outPath) {
192
+ if (to !== "png" && to !== "jpg" && to !== "jpeg") {
193
+ return errText("error: pdf convert only supports to=png|jpg");
194
+ }
195
+ if (B.qlmanage) {
196
+ const dir = await mkdtemp(join(tmpdir(), "pt-ql-"));
197
+ try {
198
+ const r = await runMedia(B.qlmanage, ["-t", "-s", "1600", "-o", dir, src]);
199
+ if (r.isError) return r;
200
+ const preview = join(dir, `${basename(src)}.png`);
201
+ try {
202
+ await access(preview);
203
+ } catch {
204
+ return errText("error: qlmanage produced no preview");
205
+ }
206
+ if (to === "png") {
207
+ await copyFile(preview, outPath);
208
+ return okText(`converted → ${outPath}\nengine: qlmanage`);
209
+ }
210
+ return convertImage(preview, "jpg", outPath, 1600);
211
+ } finally {
212
+ await rm(dir, { recursive: true, force: true }).catch(() => {});
213
+ }
214
+ }
215
+ if (B.pdftoppm) {
216
+ const prefix = outPath.replace(/\.(png|jpg|jpeg)$/i, "");
217
+ const fmt = to === "png" ? "png" : "jpeg";
218
+ const r = await runMedia(B.pdftoppm, ["-f", "1", "-l", "1", `-` + fmt, "-singlefile", src, prefix]);
219
+ if (r.isError) return r;
220
+ return okText(`converted → ${outPath}\nengine: pdftoppm`);
221
+ }
222
+ return errText("error: pdf convert needs qlmanage (macOS) or pdftoppm (poppler) — soft-miss");
223
+ }
224
+
225
+ async function handleConvert(args) {
226
+ if (!mutateAllowed()) {
227
+ return errText("error: convert requires POWERTOOLS_ALLOW_MUTATE=1 (writes output under root)");
228
+ }
229
+ const to = normalizeTo(args?.to);
230
+ if (!to) return errText("error: to is required (jpg|png|webp|gif|tiff|bmp|mp4|webm|wav|mp3|m4a|…)");
231
+ const srcR = await resolveUnderRoot(args?.path);
232
+ if (srcR.error) return errText(srcR.error);
233
+ const srcExt = extOf(srcR.path);
234
+ const maxEdge = args?.max_edge != null ? clampInt(args.max_edge, 0, MAX_EDGE) : 0;
235
+
236
+ const outAbs = args?.out
237
+ ? null
238
+ : defaultOutPath(srcR.path, to);
239
+ const outR = args?.out
240
+ ? await resolveOutPath(args.out, args.out)
241
+ : await resolveUnderRoot(outAbs);
242
+ if (outR.error) return errText(outR.error);
243
+
244
+ if (IMAGE_IN.has(srcExt) && IMAGE_OUT.has(to)) {
245
+ return convertImage(srcR.path, to, outR.path, maxEdge || undefined);
246
+ }
247
+ if (VIDEO_IN.has(srcExt) && VIDEO_OUT.has(to)) {
248
+ return convertVideo(srcR.path, to, outR.path, args);
249
+ }
250
+ if (AUDIO_IN.has(srcExt) && AUDIO_OUT.has(to)) {
251
+ return convertAudio(srcR.path, to, outR.path);
252
+ }
253
+ if (DOC_IN.has(srcExt) && (to === "png" || to === "jpg" || to === "jpeg")) {
254
+ return convertDoc(srcR.path, to, outR.path);
255
+ }
256
+ // Cross: image→ pretends as video not allowed; video audio extract
257
+ if (VIDEO_IN.has(srcExt) && AUDIO_OUT.has(to)) {
258
+ const miss = need("ffmpeg");
259
+ if (miss) return miss;
260
+ const argv = ["-nostdin", "-y", "-loglevel", "error", "-i", srcR.path, "-vn"];
261
+ if (to === "mp3") argv.push("-codec:a", "libmp3lame", "-q:a", "2");
262
+ else if (to === "wav") argv.push("-codec:a", "pcm_s16le");
263
+ else argv.push("-codec:a", "aac", "-b:a", "192k");
264
+ argv.push(outR.path);
265
+ const r = await runMedia(B.ffmpeg, argv);
266
+ if (r.isError) return r;
267
+ return okText(`audio extracted → ${outR.path}\nengine: ffmpeg`);
268
+ }
269
+
270
+ return errText(
271
+ `error: unsupported convert ${srcExt || "?"} → ${to}. ` +
272
+ `Images: ${[...IMAGE_IN].join(",")}|→|${[...IMAGE_OUT].join(",")}; ` +
273
+ `Video: ${[...VIDEO_IN].join(",")}|→|${[...VIDEO_OUT].join(",")}; ` +
274
+ `Audio: ${[...AUDIO_IN].join(",")}|→|${[...AUDIO_OUT].join(",")}; pdf→png|jpg`,
275
+ );
276
+ }
277
+
278
+ async function ocrImageFile(imagePath, lang) {
279
+ if (B.tesseract) {
280
+ const r = await runCapped(B.tesseract, [imagePath, "stdout", "-l", lang || "eng"], {
281
+ timeoutMs: SCAN_TIMEOUT_MS,
282
+ env: mediaEnv(),
283
+ });
284
+ return r;
285
+ }
286
+ if (B.swift && process.platform === "darwin") {
287
+ try {
288
+ await access(OCR_SWIFT);
289
+ } catch {
290
+ return errText("error: ocr-macos.swift missing beside powertools-media.mjs");
291
+ }
292
+ return runCapped(B.swift, [OCR_SWIFT, imagePath], {
293
+ timeoutMs: SCAN_TIMEOUT_MS,
294
+ env: mediaEnv(),
295
+ });
296
+ }
297
+ return errText(
298
+ "error: scan needs tesseract (Linux/fleet) or swift+Vision (macOS) — soft-miss. " +
299
+ "Install tesseract or run on a Mac.",
300
+ );
301
+ }
302
+
303
+ async function ensureRasterForOcr(srcPath) {
304
+ const ext = extOf(srcPath);
305
+ if (["jpg", "jpeg", "png", "tiff", "tif", "bmp", "gif"].includes(ext)) return { path: srcPath, cleanup: null };
306
+ // HEIC/webp/pdf/video frame → temp jpg under os tmp (not required under root)
307
+ const dir = await mkdtemp(join(tmpdir(), "pt-scan-"));
308
+ const out = join(dir, "frame.jpg");
309
+ if (IMAGE_IN.has(ext)) {
310
+ const r = await convertImage(srcPath, "jpg", out, 2048);
311
+ if (r.isError) {
312
+ await rm(dir, { recursive: true, force: true }).catch(() => {});
313
+ return { error: r };
314
+ }
315
+ return { path: out, cleanup: dir };
316
+ }
317
+ if (DOC_IN.has(ext)) {
318
+ const r = await convertDoc(srcPath, "jpg", out);
319
+ if (r.isError) {
320
+ await rm(dir, { recursive: true, force: true }).catch(() => {});
321
+ return { error: r };
322
+ }
323
+ return { path: out, cleanup: dir };
324
+ }
325
+ await rm(dir, { recursive: true, force: true }).catch(() => {});
326
+ return { error: errText(`error: scan: cannot rasterize .${ext}`) };
327
+ }
328
+
329
+ async function probeDurationSec(path) {
330
+ if (!B.ffprobe) return null;
331
+ const r = await runCapped(
332
+ B.ffprobe,
333
+ ["-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", path],
334
+ { timeoutMs: 15_000, env: mediaEnv() },
335
+ );
336
+ if (r.isError) return null;
337
+ const n = Number((r.content?.[0]?.text || "").trim());
338
+ return Number.isFinite(n) && n > 0 ? n : null;
339
+ }
340
+
341
+ async function handleScan(args) {
342
+ const srcR = await resolveUnderRoot(args?.path);
343
+ if (srcR.error) return errText(srcR.error);
344
+ const lang = String(args?.lang || "eng").replace(/[^a-zA-Z_]/g, "") || "eng";
345
+ const frames = clampInt(args?.frames, 5, SCAN_MAX_FRAMES);
346
+ const ext = extOf(srcR.path);
347
+
348
+ // Video: sample frames → OCR each
349
+ if (VIDEO_IN.has(ext)) {
350
+ const miss = need("ffmpeg");
351
+ if (miss) return miss;
352
+ const dur = (await probeDurationSec(srcR.path)) || 10;
353
+ const dir = await mkdtemp(join(tmpdir(), "pt-scan-vid-"));
354
+ try {
355
+ const parts = [];
356
+ for (let i = 0; i < frames; i++) {
357
+ const t = frames === 1 ? 0 : (dur * i) / (frames - 1);
358
+ const framePath = join(dir, `f${i}.jpg`);
359
+ const fr = await runMedia(B.ffmpeg, [
360
+ "-nostdin",
361
+ "-y",
362
+ "-loglevel",
363
+ "error",
364
+ "-ss",
365
+ String(t.toFixed(3)),
366
+ "-i",
367
+ srcR.path,
368
+ "-frames:v",
369
+ "1",
370
+ framePath,
371
+ ]);
372
+ if (fr.isError) {
373
+ parts.push(`[frame ${i + 1} @ ${t.toFixed(2)}s]\n(error extracting frame)`);
374
+ continue;
375
+ }
376
+ const ocr = await ocrImageFile(framePath, lang);
377
+ const text = ocr.isError
378
+ ? `(ocr error: ${ocr.content?.[0]?.text || "unknown"})`
379
+ : (ocr.content?.[0]?.text || "").trim() || "(no text)";
380
+ parts.push(`[frame ${i + 1} @ ${t.toFixed(2)}s]\n${text}`);
381
+ }
382
+ return okText(parts.join("\n\n") + `\n\n(scanned ${frames} frames · ${UNTRUSTED})`);
383
+ } finally {
384
+ await rm(dir, { recursive: true, force: true }).catch(() => {});
385
+ }
386
+ }
387
+
388
+ // Image / PDF
389
+ if (!IMAGE_IN.has(ext) && !DOC_IN.has(ext)) {
390
+ return errText(
391
+ `error: scan supports images (${[...IMAGE_IN].join(",")}), pdf, and video (${[...VIDEO_IN].join(",")})`,
392
+ );
393
+ }
394
+
395
+ // PDF/HEIC may need mutate-less temp convert — convertImage to tmp doesn't use mutate gate
396
+ // but convertDoc/Image write to tmp outside root — OK.
397
+ // For HEIC we call convertImage directly to tmp (bypass mutate) — already local functions.
398
+
399
+ const prep = await ensureRasterForOcr(srcR.path);
400
+ if (prep.error) return prep.error;
401
+ try {
402
+ const ocr = await ocrImageFile(prep.path, lang);
403
+ if (ocr.isError) return ocr;
404
+ const text = (ocr.content?.[0]?.text || "").trim() || "(no text recognized)";
405
+ return okText(text + `\n\n(source: ${srcR.path} · ${UNTRUSTED})`);
406
+ } finally {
407
+ if (prep.cleanup) await rm(prep.cleanup, { recursive: true, force: true }).catch(() => {});
408
+ }
409
+ }
410
+
411
+ const toolDefs = [
412
+ {
413
+ name: "convert",
414
+ needs: [],
415
+ def: {
416
+ name: "convert",
417
+ description:
418
+ "Convert media under POWERTOOLS_ROOT: images (heic/png/webp/…→jpg/png/… via sips|ffmpeg), " +
419
+ "video (mp4/mov/mkv/webm→mp4/webm/gif or frame→jpg), audio (→mp3/wav/m4a), pdf→png/jpg. " +
420
+ "Requires POWERTOOLS_ALLOW_MUTATE=1. " +
421
+ UNTRUSTED,
422
+ inputSchema: {
423
+ type: "object",
424
+ required: ["path", "to"],
425
+ properties: {
426
+ path: { type: "string", description: "source file under root" },
427
+ to: {
428
+ type: "string",
429
+ description: "target format: jpg|png|webp|gif|tiff|bmp|mp4|webm|wav|mp3|m4a",
430
+ },
431
+ out: { type: "string", description: "output path under root (default: sibling with new ext)" },
432
+ max_edge: { type: "number", description: "image long-edge cap (px)" },
433
+ start_sec: { type: "number", description: "video: start time / frame timestamp" },
434
+ duration_sec: { type: "number", description: "video: clip duration" },
435
+ },
436
+ },
437
+ },
438
+ handler: handleConvert,
439
+ },
440
+ {
441
+ name: "scan",
442
+ needs: [],
443
+ def: {
444
+ name: "scan",
445
+ description:
446
+ "OCR text from an image/PDF or sample frames from a video (no VL model). " +
447
+ "Backends: tesseract, or macOS Vision via ocr-macos.swift. Video: ffmpeg frame sample + OCR. " +
448
+ UNTRUSTED,
449
+ inputSchema: {
450
+ type: "object",
451
+ required: ["path"],
452
+ properties: {
453
+ path: { type: "string", description: "image, pdf, or video under root" },
454
+ lang: { type: "string", description: "tesseract lang (default eng)" },
455
+ frames: { type: "number", description: "video frames to sample (default 5, max 12)" },
456
+ },
457
+ },
458
+ },
459
+ handler: handleScan,
460
+ },
461
+ ];
462
+
463
+ return { resolvedBins: B, toolDefs, allToolNames: toolDefs.map((t) => t.name) };
464
+ }