@0perator/operator 0.1.172 → 0.1.235

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 (70) hide show
  1. package/CHANGELOG.md +858 -0
  2. package/README.md +4 -4
  3. package/dist/acp/agent.js +42 -3
  4. package/dist/acp/config-options.js +34 -0
  5. package/dist/acp/run.js +83 -2
  6. package/dist/auth/byo.js +118 -0
  7. package/dist/auth/commands.js +34 -1
  8. package/dist/autonomy/dream.js +1 -1
  9. package/dist/autonomy/index.js +16 -2
  10. package/dist/autonomy/media-robot.js +138 -0
  11. package/dist/autonomy/profile.js +77 -0
  12. package/dist/autonomy/session-factory.js +13 -9
  13. package/dist/background/index.js +8 -1
  14. package/dist/cli.js +132 -95
  15. package/dist/compose/client.js +56 -0
  16. package/dist/config/persona.js +186 -14
  17. package/dist/config/settings.js +49 -16
  18. package/dist/consolidation/scheduler.js +7 -4
  19. package/dist/consolidation/sleep.js +15 -1
  20. package/dist/engine/agent.js +152 -9
  21. package/dist/engine/aurora.js +73 -14
  22. package/dist/engine/compaction.js +129 -2
  23. package/dist/engine/computer-event.js +139 -0
  24. package/dist/engine/continuation.js +55 -0
  25. package/dist/engine/contract.js +3 -1
  26. package/dist/engine/grandmaster.js +13 -3
  27. package/dist/engine/messages.js +2 -2
  28. package/dist/engine/redact.js +25 -0
  29. package/dist/engine/rolling-summary.js +22 -7
  30. package/dist/engine/router-adapter.js +2 -0
  31. package/dist/engine/unrestricted.js +51 -0
  32. package/dist/engine/verify-gate.js +6 -0
  33. package/dist/index.browser.js +4 -0
  34. package/dist/index.js +4 -0
  35. package/dist/memory/index.js +0 -0
  36. package/dist/permissions/audit.js +4 -1
  37. package/dist/permissions/policy.js +4 -3
  38. package/dist/permissions/tier.js +31 -14
  39. package/dist/remote/host.js +9 -2
  40. package/dist/router/models.js +43 -2
  41. package/dist/session.js +113 -36
  42. package/dist/telemetry/events.js +8 -3
  43. package/dist/tools/computer.js +1 -1
  44. package/dist/tools/executor.js +22 -17
  45. package/dist/tools/mutating.js +6 -0
  46. package/dist/tools/registry.js +872 -27
  47. package/dist/tools/shell-session.js +36 -1
  48. package/dist/tools/tool-output-spill.js +2 -2
  49. package/dist/ui/ActivitySpinner.js +17 -6
  50. package/dist/ui/App.js +36 -14
  51. package/dist/ui/ArtifactPicker.js +109 -0
  52. package/dist/ui/BusTray.js +70 -0
  53. package/dist/ui/Composer.js +39 -8
  54. package/dist/ui/Markdown.js +5 -3
  55. package/dist/ui/MouseProvider.js +99 -19
  56. package/dist/ui/QuestionPrompt.js +24 -3
  57. package/dist/ui/ThinkingSpinner.js +9 -5
  58. package/dist/ui/ToolStep.js +17 -12
  59. package/dist/ui/Transcript.js +14 -7
  60. package/dist/ui/capabilities.js +0 -9
  61. package/dist/ui/listhit.js +23 -0
  62. package/dist/ui/mouse.js +22 -0
  63. package/dist/ui/osc.js +7 -4
  64. package/dist/ui/progressbar.js +46 -0
  65. package/dist/ui/shimmer.js +43 -0
  66. package/dist/ui/theme.js +2 -0
  67. package/dist/ui/tick.js +48 -0
  68. package/dist/ui/toolicons.js +69 -0
  69. package/dist/util/slash.js +1 -0
  70. package/package.json +2 -2
@@ -67,6 +67,7 @@ async function shellExec(args) {
67
67
  const sess = await getShellSession();
68
68
  const r = await sess.run(toRun, timeout);
69
69
  let out = r.output || "";
70
+ const { shellResultNotes } = await import("./shell-session.js");
70
71
  if (r.timedOut) {
71
72
  return (out ? out + "\n" : "") + `[timed out after ${timeout}ms — the shell was reset (cwd/env cleared); narrow the command or pass a larger timeout_ms]`;
72
73
  }
@@ -75,9 +76,14 @@ async function shellExec(args) {
75
76
  // Surface a NON-ZERO exit as a trailer so a failing check is observable to the model AND the
76
77
  // verify-before-done gate (engine/verify-gate.ts); exit 0 / unknown stays byte-identical so no
77
78
  // existing bash-output test changes. (Previously the code was dropped whenever a command printed.)
79
+ // GW-35: session runs with `set -o pipefail`, so r.exitCode = first failing stage — the semantics
80
+ // verify-gate.ts and the model both assume (a failing check behind `| tail` can no longer clear
81
+ // verify-before-done). Normalize SIGPIPE truncation + actionable hints; pure helper, unit-tested.
82
+ const { exitForTrailer, notes } = shellResultNotes(command, r.exitCode, out);
83
+ const noteTail = notes.length ? "\n" + notes.join("\n") : "";
78
84
  if (out)
79
- return r.exitCode ? out + `\n[exit ${r.exitCode}]` : out;
80
- return r.exitCode === 0 ? "(no output)" : `(no output; exit ${r.exitCode ?? "?"})`;
85
+ return exitForTrailer ? out + `\n[exit ${exitForTrailer}]` + noteTail : out + noteTail;
86
+ return exitForTrailer === 0 ? "(no output)" : `(no output; exit ${exitForTrailer ?? "?"})` + noteTail;
81
87
  }
82
88
  catch (e) {
83
89
  return `error running command: ${String(e?.message ?? e)}`;
@@ -265,7 +271,7 @@ async function grepSearch(args) {
265
271
  // errors immediately, but a FIFO with no writer hangs grep on open forever. Killed grep still leaves
266
272
  // whatever it matched in stdout (handled in the catch), so a real dir with a stray pipe can't wedge
267
273
  // the agent.
268
- const { stdout } = await pexecFile("grep", [...flags, "-E", pattern, path], { maxBuffer: 10 * 1024 * 1024, timeout: 20_000, killSignal: "SIGKILL" });
274
+ const { stdout } = await pexecFile("grep", [...flags, "-E", pattern, path], { maxBuffer: 10 * 1024 * 1024, timeout: 300_000, killSignal: "SIGKILL" });
269
275
  return capMatches(stdout);
270
276
  }
271
277
  catch (e) {
@@ -338,7 +344,7 @@ async function ripgrepSearch(args) {
338
344
  if (glob)
339
345
  gflags.push(`--include=${glob}`);
340
346
  try {
341
- const { stdout } = await pexecFile("grep", [...gflags, "-E", pattern, path], { maxBuffer: 10 * 1024 * 1024, timeout: 20_000, killSignal: "SIGKILL" });
347
+ const { stdout } = await pexecFile("grep", [...gflags, "-E", pattern, path], { maxBuffer: 10 * 1024 * 1024, timeout: 300_000, killSignal: "SIGKILL" });
342
348
  return capG(stdout);
343
349
  }
344
350
  catch (ge) {
@@ -357,7 +363,7 @@ async function ripgrepSearch(args) {
357
363
  rgArgs.push("-g", glob);
358
364
  rgArgs.push("-e", pattern, path);
359
365
  try {
360
- const { stdout } = await pexecFile("rg", rgArgs, { maxBuffer: 10 * 1024 * 1024, timeout: 20_000, killSignal: "SIGKILL" });
366
+ const { stdout } = await pexecFile("rg", rgArgs, { maxBuffer: 10 * 1024 * 1024, timeout: 300_000, killSignal: "SIGKILL" });
361
367
  return capG(stdout);
362
368
  }
363
369
  catch (e) {
@@ -419,19 +425,23 @@ async function gitStatus(args) {
419
425
  // ONE memory store (src/memory) backs the memory_store/memory_search/checkpoint tools AND the Session's
420
426
  // start-of-session recall — a single JSONL file, so a note stored mid-turn is what a later session recalls.
421
427
  // SPEC §8 eyes SQLite eventually; swapping the store's backing is a MemoryStore-internal change from here.
422
- const memory = new MemoryStore();
428
+ // Built LAZILY (first use, not at module import) so KODE_MEMORY_FILE — e.g. the test harness's per-process
429
+ // isolation default — is honored however late it is set; an eager `new MemoryStore()` resolved the prod
430
+ // path before any test could redirect it.
431
+ let _memoryStore;
432
+ const memory = () => (_memoryStore ??= new MemoryStore());
423
433
  async function memoryStore(args) {
424
434
  const text = str(args.text);
425
435
  if (!text)
426
436
  return "error: no text given";
427
437
  const tags = Array.isArray(args.tags) ? args.tags.map(String) : [];
428
- const ok = await memory.capture(text, tags);
438
+ const ok = await memory().capture(text, tags);
429
439
  return ok ? `stored memory (${tags.join(",") || "no tags"})` : "error: could not store memory";
430
440
  }
431
441
  async function memorySearch(args) {
432
442
  const query = str(args.query);
433
443
  const limit = Number(args.limit ?? 10);
434
- const hits = await memory.recall(query || undefined, limit);
444
+ const hits = await memory().recall(query || undefined, limit);
435
445
  return hits.length
436
446
  ? hits.map(h => `[${new Date(h.ts).toISOString()}] ${h.text}`).join("\n")
437
447
  : "(no matches)";
@@ -470,6 +480,15 @@ async function clearStaleCheckpointLock(workspace) {
470
480
  }
471
481
  catch { /* best-effort — if this fails the checkpoint just proceeds and may error as before */ }
472
482
  }
483
+ // What a checkpoint stages. A bare `git add -A` stages the WHOLE enclosing repo no matter which subdirectory
484
+ // it runs from, so a checkpoint from ~/.axe/repos/x would sweep up sibling dirs (up to the 2GB ~/.axe
485
+ // monorepo). The default is therefore the pathspec `.` (the workspace subtree only); explicit `paths` narrow
486
+ // it to exactly those entries. Everything follows `--` so a path can never be read as an option.
487
+ function checkpointAddArgs(args) {
488
+ const raw = Array.isArray(args.paths) ? args.paths : args.paths ? [args.paths] : [];
489
+ const paths = raw.map((p) => expandPath(str(p))).filter(Boolean);
490
+ return ["add", "-A", "--", ...(paths.length ? paths : ["."])];
491
+ }
473
492
  // checkpoint = git add+commit in workspace + a memory note, one call (SPEC §8). Never adds
474
493
  // Co-Authored-By / AI attribution — the commit message is exactly the caller's summary.
475
494
  async function checkpoint(args) {
@@ -495,7 +514,7 @@ async function checkpoint(args) {
495
514
  // Clear a lock orphaned by a PRIOR killed checkpoint before it dooms this one (see helper above).
496
515
  await clearStaleCheckpointLock(workspace);
497
516
  }
498
- await checkpointGit(["add", "-A"], workspace, 120_000);
517
+ await checkpointGit(checkpointAddArgs(args), workspace, 120_000);
499
518
  try {
500
519
  await checkpointGit(["commit", "--no-verify", "-m", summary], workspace, 60_000);
501
520
  }
@@ -509,7 +528,7 @@ async function checkpoint(args) {
509
528
  const { stdout: sha } = await checkpointGit(["rev-parse", "--short", "HEAD"], workspace, 10_000);
510
529
  if (push)
511
530
  await checkpointGit(["push"], workspace, 120_000);
512
- await memory.capture(summary, ["checkpoint", workspace]);
531
+ await memory().capture(summary, ["checkpoint", workspace]);
513
532
  return `checkpoint ${sha.trim()} — ${summary}${initialized ? " (new git repo initialized here)" : ""}${push ? " (pushed)" : ""}`;
514
533
  }
515
534
  catch (e) {
@@ -553,10 +572,13 @@ async function webSearch(args) {
553
572
  // never yields "(no results)" when the other could answer.
554
573
  // SearXNG: an explicit KODE_SEARXNG_URL if reachable, else a container Operator stands up on demand
555
574
  // and tears down when idle / at exit (ensureSearxng handles both; null = unavailable here).
556
- // Pin SearXNG to independent, non-Microsoft indexes by default (Brave + Mojeek are own-crawler; Google
557
- // + Startpage are non-MS). Deliberately excludes Bing and DuckDuckGo (DDG is Bing-syndicated). Microsoft
558
- // is only ever reached via the autopilot fallback below, and only when SearXNG is entirely unavailable.
559
- const searxEngines = process.env.KODE_SEARXNG_ENGINES ?? "brave,mojeek,google,startpage";
575
+ // Pin SearXNG to independent, non-Microsoft indexes by default. Still excludes Bing + DuckDuckGo (DDG is
576
+ // Bing-syndicated); Microsoft is only ever reached via the autopilot fallback below. Dropped Brave and
577
+ // Google from the default: from server/container IPs Brave returns "Suspended: too many requests" and
578
+ // Google "Suspended: access denied", so a query that included them returned ZERO results (verified
579
+ // 2026-10-03). Mojeek (own crawler) and Startpage (Google-proxied, non-MS) both return reliably — keep
580
+ // those. Override with KODE_SEARXNG_ENGINES / settings.search.searxngEngines to add more.
581
+ const searxEngines = process.env.KODE_SEARXNG_ENGINES ?? "mojeek,startpage";
560
582
  const searx = await ensureSearxng();
561
583
  if (searx) {
562
584
  try {
@@ -576,7 +598,7 @@ async function webSearch(args) {
576
598
  if (ap) {
577
599
  const res = await fetch(`${ap.replace(/\/$/, "")}/serp`, {
578
600
  method: "POST", signal: ctrl.signal,
579
- headers: { "Content-Type": "application/json", "User-Agent": "operator/kode-tsi" },
601
+ headers: { "Content-Type": "application/json", "User-Agent": "operator/kode-tsi", ...mediaAuth() },
580
602
  body: JSON.stringify({ query: q, num: n, engine }),
581
603
  });
582
604
  if (res.ok) {
@@ -586,7 +608,7 @@ async function webSearch(args) {
586
608
  return fmtResults(rows, n);
587
609
  }
588
610
  }
589
- return "error: web_search found no results — the local SearXNG (auto-managed via Docker) and the AXE autopilot SERP both returned nothing or are unavailable. Ensure Docker is running, or set KODE_AUTOPILOT_URL / KODE_SEARXNG_URL.";
611
+ return "error: web_search found no results — the local SearXNG (auto-managed via Docker) and the AXE autopilot SERP both returned nothing or are unavailable. Ensure Docker is running, or set search.autopilotUrl / search.searxngUrl in Operator's settings.";
590
612
  }
591
613
  catch (e) {
592
614
  const msg = e instanceof Error ? e.message : String(e);
@@ -606,7 +628,7 @@ async function autopilotMarkdown(url, signal) {
606
628
  try {
607
629
  const res = await fetch(`${ap.replace(/\/$/, "")}/markdown`, {
608
630
  method: "POST", signal,
609
- headers: { "Content-Type": "application/json", "User-Agent": "operator/kode-tsi" },
631
+ headers: { "Content-Type": "application/json", "User-Agent": "operator/kode-tsi", ...mediaAuth() },
610
632
  body: JSON.stringify({ url }),
611
633
  });
612
634
  if (!res.ok)
@@ -641,12 +663,16 @@ async function webFetch(args) {
641
663
  // answer. Retry through a real browser if one is configured; otherwise this reads as guidance,
642
664
  // not a scary raw error, since the block is expected behavior rather than a tool failure.
643
665
  if (res.status === 403 || res.status === 429) {
644
- const rendered = await autopilotMarkdown(url, ctrl.signal);
666
+ // Ladder: first-party autopilot renderer if configured, else the public Jina Reader
667
+ // (keyless tier works from a plain fetch; set KODE_JINA_KEY for higher rate limits,
668
+ // KODE_JINA_URL to self-host). Today's root cause: NO autopilot on fleet boxes made
669
+ // every Cloudflare-fronted site a permanent "note:" dead-end for the model.
670
+ const rendered = (await autopilotMarkdown(url, ctrl.signal)) ?? (await jinaMarkdown(url, ctrl.signal));
645
671
  if (rendered) {
646
672
  const max = Number(args.max_chars ?? 20_000);
647
673
  return rendered.length > max ? `${rendered.slice(0, max)}\n…[truncated ${rendered.length - max} chars]` : rendered;
648
674
  }
649
- return `note: ${url} blocks automated fetch (HTTP ${res.status}) — it needs a real browser; try web_search or the browser tools instead.`;
675
+ return `note: ${url} blocks automated fetch (HTTP ${res.status}) AND both render fallbacks are unavailable (autopilot unset; Jina failed or rate-limited — retry once in a bit). Try web_search (works: local SearXNG) or a differently-hosted mirror of the page.`;
650
676
  }
651
677
  return `error: HTTP ${res.status} fetching ${url}`;
652
678
  }
@@ -679,6 +705,33 @@ function authHeaders(args) {
679
705
  return h;
680
706
  }
681
707
  const HTTP_BODY_CAP = 200_000; // cap a response body so one huge payload can't balloon the model's context
708
+ /** Public render fallback for web_fetch's 403/429 path: Jina Reader (r.jina.ai/<url> returns
709
+ * markdown; keyless 20 RPM, Bearer KODE_JINA_KEY for more; KODE_JINA_URL swaps to a self-hosted
710
+ * instance). Default-ON because fleet boxes have no autopilot and NO headless browser; opt out
711
+ * with KODE_WEB_RENDER=0 (tests pin that; unit suites must not hit the network). Returns null on
712
+ * any failure — the caller degrades to guidance exactly as before. */
713
+ async function jinaMarkdown(url, signal) {
714
+ if (process.env.KODE_WEB_RENDER === "0")
715
+ return null;
716
+ const base = (process.env.KODE_JINA_URL || "https://r.jina.ai").replace(/\/$/, "");
717
+ try {
718
+ // HONEST identity only: a full Chrome-UA string from node's TLS fingerprint is a Cloudflare
719
+ // dead giveaway (UA/TLS mismatch -> "Just a moment..." 403 — measured today; the same request
720
+ // with `operator/kode-tsi` returned 200). The PRIMARY fetch spoofing is right (we impersonate a
721
+ // visitor to origin sites); the RENDERER must be itself — it is a service, not a visitor.
722
+ const headers = { "User-Agent": "operator/kode-tsi", "Accept": "text/plain" };
723
+ if (process.env.KODE_JINA_KEY)
724
+ headers.Authorization = `Bearer ${process.env.KODE_JINA_KEY}`;
725
+ const res = await fetch(`${base}/${url}`, { signal, headers, redirect: "follow" });
726
+ if (!res.ok)
727
+ return null;
728
+ const text = (await res.text()).trim();
729
+ return text.length > 200 ? text : null; // error stubs are short; real renders aren't
730
+ }
731
+ catch {
732
+ return null;
733
+ }
734
+ }
682
735
  // Real HTTP client — the capability gap beyond web_fetch's dumb GET-and-scrape. Any method, custom
683
736
  // headers, JSON or raw body, bearer/basic auth, follow redirects, timeout. Returns status + headers +
684
737
  // (capped) body verbatim (no HTML-stripping — this is for APIs, not pages). safe:false: it can POST/PUT/
@@ -899,6 +952,596 @@ async function taskClear(args) {
899
952
  agentTasks.length = 0;
900
953
  return `cleared all ${before} task(s) — plan is empty`;
901
954
  }
955
+ // Image generation via the AXE image service (FLUX.1-schnell, OpenAI-images-compatible) — a SHARED FLEET
956
+ // service on a dedicated image node, so it works from EVERY surface (any Operator node, web, mobile) and the
957
+ // generation never runs on whatever node is serving the LLM. The broker is SCALE-TO-ZERO: each request spawns a
958
+ // short-lived process that loads FLUX, renders, and exits (steady-state RAM = 0). This is the ONLY sanctioned
959
+ // way to make images — loading a diffusion model inline in a turn pins GBs on the serving box, swaps, and
960
+ // crawls decode to ~1 tok/s. Returns the saved PNG path(s), never the base64 (that would flood the transcript).
961
+ /** Candidate image-service endpoints in priority order: explicit env first, then the shared fleet service
962
+ * (Cloudflare-tunneled — reachable from anywhere), then a local broker as a last resort. De-duped, trailing
963
+ * slash trimmed. KODE_IMAGE_URL / AXE_IMAGE_URL override. */
964
+ /** ONE-API gateway: when KODE_GATEWAY_URL is set, prefer the unified route `api.axe.onl/<service>/…`, which
965
+ * fans out to the broker server-side (one door, one token). Empty when unset → per-broker URLs are used. The
966
+ * gateway strips the `/<service>/` prefix, so the broker still sees its native OpenAI path. See
967
+ * `_ai-docs/2026-10-05-one-api-gateway.md` + `api/nginx/api.axe.onl.conf`. */
968
+ function gatewayEndpoints(service) {
969
+ const g = process.env.KODE_GATEWAY_URL;
970
+ return g ? [`${g.replace(/\/$/, "")}/${service}`] : [];
971
+ }
972
+ function imageEndpoints() {
973
+ const envs = [process.env.KODE_IMAGE_URL, process.env.AXE_IMAGE_URL].filter(Boolean);
974
+ const defaults = ["https://image.axe.onl", "http://127.0.0.1:8791"];
975
+ return [...new Set([...gatewayEndpoints("images"), ...envs, ...defaults])].map((u) => u.replace(/\/$/, ""));
976
+ }
977
+ /** Candidate IDENTITY-broker endpoints (reference-likeness: SDXL RealVisXL + IP-Adapter-FaceID on JL1:8793).
978
+ * Used when image_generate carries a `reference` (preserve a SPECIFIC face). The JL1 LAN IP is tried FIRST so
979
+ * a cold render (~80-90s to load the 9.4GB pipeline) never hits Cloudflare's ~100s edge timeout (524); the
980
+ * public host is the fallback for nodes off the LAN + for the response URL apps render. KODE_IDENTITY_URL wins. */
981
+ function identityEndpoints() {
982
+ const envs = [process.env.KODE_IDENTITY_URL].filter(Boolean);
983
+ const defaults = ["http://192.168.1.103:8793", "https://identity.axe.onl", "http://127.0.0.1:8793"];
984
+ return [...new Set([...envs, ...defaults])].map((u) => u.replace(/\/$/, ""));
985
+ }
986
+ /** Media-broker auth: send a bearer token to the image/video/vision brokers when KODE_MEDIA_TOKEN is set.
987
+ * ENV-GATED on BOTH sides — the brokers stay open until their MEDIA_AUTH_TOKEN is set, and the tools send a
988
+ * header only when KODE_MEDIA_TOKEN is set — so the two can roll out in either order with no mid-rollout
989
+ * breakage. The token lives in the environment only: never in a URL, a log, or a tool result. */
990
+ function mediaAuth() {
991
+ const t = process.env.KODE_MEDIA_TOKEN;
992
+ return t ? { Authorization: `Bearer ${t}` } : {};
993
+ }
994
+ /** Is an image endpoint reachable + ready? Fast /health probe so we fail over off a dead endpoint BEFORE
995
+ * committing to a ~tens-of-seconds generation, instead of hanging the whole turn on it. */
996
+ async function imageHealthy(base) {
997
+ try {
998
+ const c = new AbortController();
999
+ const t = setTimeout(() => c.abort(), 4000);
1000
+ const r = await fetch(`${base}/health`, { signal: c.signal, headers: { "User-Agent": "operator/kode-tsi", ...mediaAuth() } });
1001
+ clearTimeout(t);
1002
+ if (!r.ok)
1003
+ return false;
1004
+ const j = (await r.json().catch(() => ({})));
1005
+ return j.ok !== false;
1006
+ }
1007
+ catch {
1008
+ return false;
1009
+ }
1010
+ }
1011
+ /** Flywheel keystone: record each media generation (prompt, params, output refs) to a provenance JSONL
1012
+ * (+ an optional HTTP sink) so image/video gen COMPOUNDS — the accumulated (prompt → output) corpus is the
1013
+ * fuel for prompt-rewriting (retrieval over accepted asks), best-of-N reward selection, and a Red-Queen-gated
1014
+ * periodic FLUX/LTX LoRA. Best-effort and off the hot path: the local append is awaited (fast); the HTTP sink
1015
+ * is fire-and-forget with a 3s cap; every failure is swallowed so provenance never fails a generation.
1016
+ * Mirrors telemetry/events.ts (JSONL + sink, 0600). Design: _ai-docs/2026-10-05-media-gen-flywheel.md. */
1017
+ async function recordMediaGen(rec) {
1018
+ try {
1019
+ const { appendFile, mkdir } = await nodeImport("node:fs/promises");
1020
+ const os = await nodeImport("node:os");
1021
+ const { join, dirname } = await nodeImport("node:path");
1022
+ const file = process.env.KODE_MEDIA_PROVENANCE_FILE || join(os.homedir(), ".axe", "operator", "media-gen.jsonl");
1023
+ const line = JSON.stringify({ ts: new Date().toISOString(), node: os.hostname(), ...rec }) + "\n";
1024
+ await mkdir(dirname(file), { recursive: true }).catch(() => { });
1025
+ await appendFile(file, line, { encoding: "utf8", mode: 0o600 });
1026
+ const url = process.env.KODE_MEDIA_PROVENANCE_URL;
1027
+ if (url) {
1028
+ const c = new AbortController();
1029
+ const t = setTimeout(() => c.abort(), 3000);
1030
+ void fetch(url, { method: "POST", signal: c.signal, headers: { "Content-Type": "application/json", "User-Agent": "operator/kode-tsi" }, body: line }).catch(() => { }).finally(() => clearTimeout(t));
1031
+ }
1032
+ }
1033
+ catch { /* provenance is best-effort — never fail a generation over it */ }
1034
+ }
1035
+ /** Resolve the renderable reference for each generated media item: PREFER the broker's public URL (a short
1036
+ * link the app surfaces render inline, with no base64 flooding the LLM context), else decode b64 → save a
1037
+ * local file. Writes locally only when the caller asked for a file (`out`) or no URL came back (older
1038
+ * broker). Shared by image_generate + video_generate so the URL-first contract is identical for both. */
1039
+ async function saveGeneratedMedia(items, outArg, ext) {
1040
+ const { writeFile, mkdir } = await nodeImport("node:fs/promises");
1041
+ const { tmpdir } = await nodeImport("node:os");
1042
+ const { join, dirname } = await nodeImport("node:path");
1043
+ const kind = ext === "png" ? "image" : "video";
1044
+ const dotExt = new RegExp(`(\\.${ext})?$`, "i");
1045
+ const refs = []; // renderable reference per item — public URL when present, else a local path
1046
+ const saved = []; // local files actually written (out was given, or there was no URL to point to)
1047
+ for (let i = 0; i < items.length; i++) {
1048
+ const { b64_json: b64, url } = items[i];
1049
+ let localPath;
1050
+ if (b64 && (outArg || !url)) {
1051
+ const p = outArg
1052
+ ? (items.length > 1 ? outArg.replace(dotExt, `-${i + 1}.${ext}`) : (outArg.toLowerCase().endsWith(`.${ext}`) ? outArg : `${outArg}.${ext}`))
1053
+ : join(tmpdir(), `axe-${kind}-${Date.now().toString(36)}-${i + 1}.${ext}`);
1054
+ await mkdir(dirname(p), { recursive: true }).catch(() => { });
1055
+ await writeFile(p, Buffer.from(b64, "base64"));
1056
+ saved.push(p);
1057
+ localPath = p;
1058
+ }
1059
+ const ref = url ?? localPath;
1060
+ if (ref)
1061
+ refs.push(ref);
1062
+ }
1063
+ return { refs, saved };
1064
+ }
1065
+ async function imageGenerate(args) {
1066
+ const prompt = str(args.prompt);
1067
+ if (!prompt)
1068
+ return "error: image_generate needs a prompt";
1069
+ const size = /^\d+x\d+$/.test(str(args.size)) ? str(args.size) : "512x512";
1070
+ const n = Math.max(1, Math.min(Number(args.n) || 1, 4));
1071
+ const wantExpand = args.expand === true || str(args.expand) === "true"; // ask the broker to rewrite the prompt via Aurora (never blocks; used:false = ran on the original)
1072
+ // Route reference-bearing requests to the IDENTITY broker (preserve a SPECIFIC face via IP-Adapter-FaceID);
1073
+ // plain text-to-image stays on flux. Try identity first when a reference is given, fall back to flux if the
1074
+ // identity node is asleep — a request never hard-fails just because one broker is down.
1075
+ const wantIdentity = !!str(args.reference);
1076
+ let base;
1077
+ let identity = false;
1078
+ if (wantIdentity)
1079
+ for (const e of identityEndpoints()) {
1080
+ if (await imageHealthy(e)) {
1081
+ base = e;
1082
+ identity = true;
1083
+ break;
1084
+ }
1085
+ }
1086
+ if (!base)
1087
+ for (const e of imageEndpoints()) {
1088
+ if (await imageHealthy(e)) {
1089
+ base = e;
1090
+ break;
1091
+ }
1092
+ }
1093
+ if (!base)
1094
+ return `error: no image service reachable. Bring up the flux-worker (image.axe.onl / :8791)${wantIdentity ? " or the identity-worker (identity.axe.onl / :8793)" : ""}. Do NOT load a diffusion model inline — that starves the serving model.`;
1095
+ const ctrl = new AbortController();
1096
+ const timer = setTimeout(() => ctrl.abort(), Number(args.timeout_ms ?? 180_000)); // a cold FLUX load + denoise is ~tens of seconds
1097
+ try {
1098
+ const genBody = { prompt, n, size, ...(wantExpand ? { expand: true } : {}), ...(Number(args.steps) > 0 ? { steps: Number(args.steps) } : {}) };
1099
+ if (!identity)
1100
+ genBody.model = "flux-schnell"; // the identity broker runs RealVisXL and picks its own base
1101
+ if (str(args.reference)) {
1102
+ genBody.reference = str(args.reference); // the FACE (identity) — or the init (flux)
1103
+ genBody.strength = Number(args.strength ?? 0.65);
1104
+ if (identity)
1105
+ genBody.ip_adapter_scale = Number(args.ip_adapter_scale ?? 0.8); // IP-Adapter-FaceID strength
1106
+ else
1107
+ genBody.image = str(args.reference); // flux img2img: the reference doubles as init
1108
+ }
1109
+ const res = await fetch(`${base}/v1/images/generations`, {
1110
+ method: "POST", signal: ctrl.signal,
1111
+ headers: { "Content-Type": "application/json", "User-Agent": "operator/kode-tsi", ...mediaAuth() },
1112
+ body: JSON.stringify(genBody),
1113
+ });
1114
+ if (!res.ok)
1115
+ return `error: image worker returned ${res.status} — ensure the flux-worker broker (com.axe.flux-worker) is up`;
1116
+ const j = (await res.json().catch(() => ({})));
1117
+ const imgs = j.data ?? [];
1118
+ if (!imgs.length)
1119
+ return "error: image worker returned no image data";
1120
+ const { refs, saved } = await saveGeneratedMedia(imgs, str(args.out), "png");
1121
+ if (!refs.length)
1122
+ return "error: image worker returned no url and no decodable PNG";
1123
+ const exp = j.axe_prompt_expansion?.used ? j.axe_prompt_expansion.expanded : undefined; // the broker-rewritten prompt that was actually rendered
1124
+ const id = j.axe_identity?.identity_applied ? j.axe_identity : undefined; // the identity broker injected a real face (honest method/fidelity)
1125
+ const i2i = !id && j.axe_img2img?.used ? j.axe_img2img : undefined; // pose/style restyle from a reference — NOT the exact face
1126
+ await recordMediaGen({ tool: "image_generate", prompt, model: id?.base_model || "flux-schnell", params: { size, n }, refs, ok: true, ...(exp ? { expanded: exp } : {}), ...(id ? { identity: id } : {}), ...(i2i ? { img2img: i2i } : {}) });
1127
+ const extra = saved.length && refs.some((r) => /^https?:\/\//.test(r)) ? ` (also saved: ${saved.join(", ")})` : "";
1128
+ const expNote = exp ? ` (expanded → "${exp.length > 160 ? exp.slice(0, 160) + "…" : exp}")` : "";
1129
+ // Honest provenance in the result: name WHICH reference mechanism actually ran, so likeness is never overclaimed.
1130
+ const refNote = id
1131
+ ? ` (identity: ${id.method ?? "reference"}${id.base_model ? ` on ${id.base_model}` : ""}${id.fidelity_note ? ` — ${id.fidelity_note}` : ""})`
1132
+ : i2i
1133
+ ? ` (img2img restyle @ strength ${i2i.strength ?? "?"} — matches pose/composition/style, NOT the exact face)`
1134
+ : "";
1135
+ return `generated ${refs.length} image${refs.length > 1 ? "s" : ""} (${size}) → ${refs.join(", ")}${extra}${expNote}${refNote}`;
1136
+ }
1137
+ catch (e) {
1138
+ const msg = e?.name === "AbortError" ? "timed out" : String(e?.message ?? e);
1139
+ return `error: image worker unreachable at ${base} (${msg}) — start the flux-worker broker (com.axe.flux-worker on the image node). Do NOT load a diffusion model inline; that starves the serving model.`;
1140
+ }
1141
+ finally {
1142
+ clearTimeout(timer);
1143
+ }
1144
+ }
1145
+ // video_generate — same scale-to-zero broker as image_generate (the flux-worker node also serves /v1/video),
1146
+ // so generation NEVER runs on the LLM-serving box. Mirrors image_generate's URL-first contract (prefer the
1147
+ // broker's public url, fall back to a saved local file) via saveGeneratedMedia. KODE_VIDEO_URL overrides,
1148
+ // else it reuses the image endpoints (same broker host).
1149
+ /** Candidate video-service endpoints in priority order: KODE_VIDEO_URL first, then the shared image
1150
+ * endpoints (the flux-worker broker serves /v1/video alongside /v1/images). De-duped, trailing slash trimmed. */
1151
+ function videoEndpoints() {
1152
+ const envs = [process.env.KODE_VIDEO_URL].filter(Boolean);
1153
+ // The LTX video broker lives at its OWN host (video.axe.onl), not the image host — do NOT fall back to the
1154
+ // image endpoints, whose /health is 200 but which 404 on /v1/video (we'd pick a healthy-but-wrong broker).
1155
+ // LAN-FIRST: hit the JL2 video worker directly (192.168.1.146:8792) before the Cloudflare-fronted host —
1156
+ // an LTX render takes >100s, which trips CF's ~100s edge timeout (524). The LAN path has no such cap; the
1157
+ // CF host stays as a fallback for off-LAN callers. Same fix as the identity broker's LAN-first ordering.
1158
+ const defaults = ["http://192.168.1.146:8792", "https://video.axe.onl"];
1159
+ return [...new Set([...envs, ...defaults])].map((u) => u.replace(/\/$/, ""));
1160
+ }
1161
+ async function videoGenerate(args) {
1162
+ const prompt = str(args.prompt);
1163
+ if (!prompt)
1164
+ return "error: video_generate needs a prompt";
1165
+ const size = /^\d+x\d+$/.test(str(args.size)) ? str(args.size) : "704x480"; // LTX natural default; the broker rounds w/h to ×32
1166
+ const numFrames = Math.max(1, Math.min(Number(args.num_frames) || 97, 257)); // LTX default ≈97 (~4s @ 24fps); broker rounds to 8n+1
1167
+ const fps = Math.max(1, Math.min(Number(args.fps) || 24, 60));
1168
+ const seed = Number.isFinite(Number(args.seed)) ? Number(args.seed) : undefined;
1169
+ const model = str(args.model);
1170
+ const refImage = str(args.reference_image); // image-to-video: the broker uses this as LTX first-frame conditioning (path/url or b64)
1171
+ const wantExpand = args.expand === true || str(args.expand) === "true";
1172
+ // Pick the first reachable endpoint (shared fleet service preferred), failing fast over dead ones.
1173
+ const candidates = videoEndpoints();
1174
+ let base;
1175
+ for (const e of candidates) {
1176
+ if (await imageHealthy(e)) {
1177
+ base = e;
1178
+ break;
1179
+ }
1180
+ }
1181
+ if (!base)
1182
+ return `error: no video service reachable (tried ${candidates.join(", ")}). Bring up the flux-worker broker on the image node (it serves /v1/video). Do NOT load a video model inline — that starves the serving model.`;
1183
+ const ctrl = new AbortController();
1184
+ const timer = setTimeout(() => ctrl.abort(), Number(args.timeout_ms ?? 600_000)); // a cold video model load + sampling runs minutes, not seconds
1185
+ try {
1186
+ const res = await fetch(`${base}/v1/video/generations`, {
1187
+ method: "POST", signal: ctrl.signal,
1188
+ headers: { "Content-Type": "application/json", "User-Agent": "operator/kode-tsi", ...mediaAuth() },
1189
+ body: JSON.stringify({ prompt, size, num_frames: numFrames, fps, ...(seed != null ? { seed } : {}), ...(model ? { model } : {}), ...(refImage ? { image: refImage } : {}), ...(wantExpand ? { expand: true } : {}) }),
1190
+ });
1191
+ if (!res.ok)
1192
+ return `error: video worker returned ${res.status} — ensure the flux-worker broker serves /v1/video (video_gen.py)`;
1193
+ const j = (await res.json().catch(() => ({})));
1194
+ const vids = j.data ?? [];
1195
+ if (!vids.length)
1196
+ return "error: video worker returned no video data";
1197
+ const { refs, saved } = await saveGeneratedMedia(vids, str(args.out), "mp4");
1198
+ if (!refs.length)
1199
+ return "error: video worker returned no url and no decodable video";
1200
+ const exp = j.axe_prompt_expansion?.used ? j.axe_prompt_expansion.expanded : undefined;
1201
+ await recordMediaGen({ tool: "video_generate", prompt, model: model || "ltx-video", params: { size, num_frames: numFrames, fps, ...(seed != null ? { seed } : {}) }, refs, ok: true, ...(refImage ? { conditioned: j.conditioned !== false } : {}), ...(exp ? { expanded: exp } : {}) });
1202
+ const extra = saved.length && refs.some((r) => /^https?:\/\//.test(r)) ? ` (also saved: ${saved.join(", ")})` : "";
1203
+ const condNote = refImage ? (j.conditioned !== false ? " (image-conditioned)" : " (reference ignored — broker not image-conditioned yet)") : "";
1204
+ const expNote = exp ? ` (expanded → "${exp.length > 160 ? exp.slice(0, 160) + "…" : exp}")` : "";
1205
+ return `generated ${refs.length} video${refs.length > 1 ? "s" : ""} (${size}, ${numFrames}f @ ${fps}fps) → ${refs.join(", ")}${extra}${condNote}${expNote}`;
1206
+ }
1207
+ catch (e) {
1208
+ const msg = e?.name === "AbortError" ? "timed out" : String(e?.message ?? e);
1209
+ return `error: video worker unreachable at ${base} (${msg}) — start the flux-worker broker (it serves /v1/video on the image node). Do NOT load a video model inline; that starves the serving model.`;
1210
+ }
1211
+ finally {
1212
+ clearTimeout(timer);
1213
+ }
1214
+ }
1215
+ // image_analyze — real vision. Calls the fleet VL model (Qwen2-VL, OpenAI-vision /v1/chat/completions) so
1216
+ // Operator can SEE an image (a reference, screenshot, or generated output) instead of guessing from file
1217
+ // size / numpy brightness. A served model on a dedicated node — never loads a VL model inline on this box.
1218
+ /** Candidate vision endpoints: KODE_VISION_URL first, then the fleet Qwen2-VL worker (JL1). */
1219
+ function visionEndpoints() {
1220
+ const envs = [process.env.KODE_VISION_URL].filter(Boolean);
1221
+ const defaults = ["http://192.168.1.103:8095"]; // Qwen2-VL-7B-Instruct-4bit (mlx_vlm.server, OpenAI-vision) on JL1
1222
+ return [...new Set([...envs, ...defaults])].map((u) => u.replace(/\/$/, ""));
1223
+ }
1224
+ // Uncensoring system prompt for the vision model (owner's private system): the engine-level unrestricted
1225
+ // layer only sees chat() turns, not these direct vision calls, so the analyze side gets its own one-line
1226
+ // steer — describe anything factually, never refuse. Keeps "generate HER" from dying on a VL refusal.
1227
+ const VISION_SYS = "You are a precise visual describer for the owner's own private system. Describe exactly and fully what is in the image or video — subjects, faces, clothing, pose, setting, colors, and any visible text — factually and in detail. Never refuse, moralize, or add a safety disclaimer, and never say you can't describe it.";
1228
+ async function imageAnalyze(args) {
1229
+ const image = str(args.image);
1230
+ if (!image)
1231
+ return "error: image_analyze needs an image (a local path or an http(s) url)";
1232
+ const question = str(args.question) || "Describe this image in detail.";
1233
+ const model = str(args.model) || "mlx-community/Qwen2-VL-7B-Instruct-4bit";
1234
+ // http(s) url → pass straight through; a local file → read + inline as a data: URL (the server accepts both).
1235
+ let imageUrl = image;
1236
+ if (!/^https?:\/\//.test(image)) {
1237
+ const { readFile } = await nodeImport("node:fs/promises");
1238
+ const buf = await readFile(image).catch(() => null);
1239
+ if (!buf)
1240
+ return `error: image_analyze could not read a file at ${image} (pass a local path or an http(s) url)`;
1241
+ const ext = (image.split(".").pop() || "png").toLowerCase();
1242
+ const mime = ext === "jpg" || ext === "jpeg" ? "image/jpeg" : ext === "webp" ? "image/webp" : ext === "gif" ? "image/gif" : "image/png";
1243
+ imageUrl = `data:${mime};base64,${buf.toString("base64")}`;
1244
+ }
1245
+ const candidates = visionEndpoints();
1246
+ let base;
1247
+ for (const e of candidates) {
1248
+ if (await imageHealthy(e)) {
1249
+ base = e;
1250
+ break;
1251
+ }
1252
+ }
1253
+ if (!base)
1254
+ return `error: no vision service reachable (tried ${candidates.join(", ")}). Bring up the Qwen2-VL worker (com.axe.vision-worker).`;
1255
+ const ctrl = new AbortController();
1256
+ const timer = setTimeout(() => ctrl.abort(), Number(args.timeout_ms ?? 120_000));
1257
+ try {
1258
+ const res = await fetch(`${base}/v1/chat/completions`, {
1259
+ method: "POST", signal: ctrl.signal,
1260
+ headers: { "Content-Type": "application/json", "User-Agent": "operator/kode-tsi", ...mediaAuth() },
1261
+ body: JSON.stringify({
1262
+ model,
1263
+ messages: [{ role: "system", content: VISION_SYS }, { role: "user", content: [{ type: "text", text: question }, { type: "image_url", image_url: { url: imageUrl } }] }],
1264
+ ...(Number.isFinite(Number(args.max_tokens)) ? { max_tokens: Number(args.max_tokens) } : {}), temperature: 0,
1265
+ }),
1266
+ });
1267
+ if (!res.ok)
1268
+ return `error: vision worker returned ${res.status} — ensure the Qwen2-VL worker is up`;
1269
+ const j = (await res.json().catch(() => ({})));
1270
+ const text = j.choices?.[0]?.message?.content?.trim();
1271
+ return text || "error: vision worker returned no text";
1272
+ }
1273
+ catch (e) {
1274
+ const msg = e?.name === "AbortError" ? "timed out" : String(e?.message ?? e);
1275
+ return `error: vision worker unreachable at ${base} (${msg}) — start the Qwen2-VL worker (com.axe.vision-worker)`;
1276
+ }
1277
+ finally {
1278
+ clearTimeout(timer);
1279
+ }
1280
+ }
1281
+ // video_analyze — real video understanding: ffmpeg samples frames evenly across the clip, then the VL model
1282
+ // (same Qwen2-VL endpoint, multi-image) describes what happens. Needs ffmpeg on PATH; verified the model
1283
+ // synthesizes motion from ordered frames ("calm ocean with gentle waves, golden hue").
1284
+ async function videoAnalyze(args) {
1285
+ const video = str(args.video);
1286
+ if (!video)
1287
+ return "error: video_analyze needs a video (a local path or an http(s) url)";
1288
+ const question = str(args.question) || "These frames are sampled in order across a video. Describe what happens across the video.";
1289
+ const nFrames = Math.max(2, Math.min(Number(args.frames) || 8, 16));
1290
+ const model = str(args.model) || "mlx-community/Qwen2-VL-7B-Instruct-4bit";
1291
+ const { mkdtemp, readFile, rm, writeFile, readdir } = await nodeImport("node:fs/promises");
1292
+ const os = await nodeImport("node:os");
1293
+ const { join } = await nodeImport("node:path");
1294
+ const { execFile } = await nodeImport("node:child_process");
1295
+ const { promisify } = await nodeImport("node:util");
1296
+ const pexec = promisify(execFile);
1297
+ const dir = await mkdtemp(join(os.tmpdir(), "axe-va-"));
1298
+ try {
1299
+ let src = video;
1300
+ if (/^https?:\/\//.test(video)) {
1301
+ const r = await fetch(video).catch(() => null);
1302
+ if (!r || !r.ok)
1303
+ return `error: video_analyze could not fetch ${video}`;
1304
+ src = join(dir, "src.mp4");
1305
+ await writeFile(src, Buffer.from(await r.arrayBuffer()));
1306
+ }
1307
+ let fps = 2;
1308
+ try {
1309
+ const { stdout } = await pexec("ffprobe", ["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", src]);
1310
+ const dur = parseFloat(stdout.trim());
1311
+ if (dur > 0)
1312
+ fps = Math.max(0.1, Math.min(nFrames / dur, 8)); // ~nFrames spread across the whole clip
1313
+ }
1314
+ catch { /* ffprobe missing → default fps */ }
1315
+ try {
1316
+ await pexec("ffmpeg", ["-nostdin", "-y", "-loglevel", "error", "-i", src, "-vf", `scale=384:-1,fps=${fps}`, "-frames:v", String(nFrames * 3), join(dir, "f%03d.png")]);
1317
+ }
1318
+ catch {
1319
+ return "error: ffmpeg failed to sample frames — is it installed, and is the input a valid video?";
1320
+ }
1321
+ const files = (await readdir(dir)).filter((f) => /^f\d+\.png$/.test(f)).sort();
1322
+ if (!files.length)
1323
+ return "error: no frames extracted from the video (is it a valid video file?)";
1324
+ const step = Math.max(1, Math.floor(files.length / nFrames));
1325
+ const picked = files.filter((_f, i) => i % step === 0).slice(0, nFrames);
1326
+ const parts = [{ type: "text", text: `${question} (${picked.length} frames, in order)` }];
1327
+ for (const f of picked) {
1328
+ const b = await readFile(join(dir, f));
1329
+ parts.push({ type: "image_url", image_url: { url: `data:image/png;base64,${b.toString("base64")}` } });
1330
+ }
1331
+ const candidates = visionEndpoints();
1332
+ let base;
1333
+ for (const e of candidates) {
1334
+ if (await imageHealthy(e)) {
1335
+ base = e;
1336
+ break;
1337
+ }
1338
+ }
1339
+ if (!base)
1340
+ return `error: no vision service reachable (tried ${candidates.join(", ")}). Bring up the Qwen2-VL worker.`;
1341
+ const ctrl = new AbortController();
1342
+ const timer = setTimeout(() => ctrl.abort(), Number(args.timeout_ms ?? 180_000));
1343
+ try {
1344
+ const res = await fetch(`${base}/v1/chat/completions`, {
1345
+ method: "POST", signal: ctrl.signal,
1346
+ headers: { "Content-Type": "application/json", "User-Agent": "operator/kode-tsi", ...mediaAuth() },
1347
+ body: JSON.stringify({ model, messages: [{ role: "system", content: VISION_SYS }, { role: "user", content: parts }], ...(Number.isFinite(Number(args.max_tokens)) ? { max_tokens: Number(args.max_tokens) } : {}), temperature: 0 }),
1348
+ });
1349
+ if (!res.ok)
1350
+ return `error: vision worker returned ${res.status} — ensure the Qwen2-VL worker is up`;
1351
+ const j = (await res.json().catch(() => ({})));
1352
+ const text = j.choices?.[0]?.message?.content?.trim();
1353
+ return text ? `video analysis (${picked.length} frames) → ${text}` : "error: vision worker returned no text";
1354
+ }
1355
+ finally {
1356
+ clearTimeout(timer);
1357
+ }
1358
+ }
1359
+ catch (e) {
1360
+ const msg = e?.name === "AbortError" ? "timed out" : String(e?.message ?? e);
1361
+ return `error: video_analyze failed (${msg}) — needs ffmpeg on PATH + the Qwen2-VL worker`;
1362
+ }
1363
+ finally {
1364
+ await rm(dir, { recursive: true, force: true }).catch(() => { });
1365
+ }
1366
+ }
1367
+ // image_recreate — the "share a reference → recreate it" flow in one call: SEE the reference with the vision
1368
+ // model (extract a faithful text-to-image prompt), then generate from it. Pixel-level fidelity (same face/
1369
+ // scene) needs img2img/IP-Adapter reference-conditioning on the broker — until that lands this captures the
1370
+ // reference's subject/style/composition/lighting via a detailed analyzed prompt, which is the enterprise-grade
1371
+ // path available now. Composes image_analyze + image_generate (both above).
1372
+ async function imageRecreate(args) {
1373
+ const reference = str(args.reference);
1374
+ if (!reference)
1375
+ return "error: image_recreate needs a reference image (a local path or an http(s) url)";
1376
+ const extra = str(args.instructions); // optional "...but make it X" adjustments layered on top of the match
1377
+ const size = /^\d+x\d+$/.test(str(args.size)) ? str(args.size) : "1024x1024";
1378
+ const q = "Write ONE detailed text-to-image generation prompt that would recreate this image as closely as "
1379
+ + "possible. Cover: main subject, pose/expression, clothing, setting/background, lighting, mood, art style, "
1380
+ + "color palette, and camera/lens if it's a photo. Output ONLY the prompt text — no preamble, no quotes.";
1381
+ const extracted = (await imageAnalyze({ image: reference, question: q })).trim();
1382
+ if (extracted.startsWith("error:"))
1383
+ return `image_recreate: could not analyze the reference — ${extracted}`;
1384
+ const genPrompt = extra ? `${extracted}. ${extra}` : extracted;
1385
+ const gen = await imageGenerate({ prompt: genPrompt, size, reference, ...(str(args.strength) ? { strength: str(args.strength) } : {}), ...(str(args.out) ? { out: str(args.out) } : {}) });
1386
+ if (gen.startsWith("error:"))
1387
+ return `image_recreate: analyzed the reference but generation failed — ${gen}`;
1388
+ const seen = extracted.length > 280 ? extracted.slice(0, 280) + "…" : extracted;
1389
+ return `${gen}\n ↳ recreated from your reference. Understood as: ${seen}\n (self-review: image_analyze the result and compare to the reference; refine + rerun if it's off.)`;
1390
+ }
1391
+ // artifact_create — the NATIVE "make a shareable page/design/deck" path: posts the content to the compose.casa
1392
+ // artifact surface (JSON-RPC tools/call) and returns a public, clickable URL. So Operator never hunts for a
1393
+ // compose MCP, hand-rolls an HTML file, or asks "where should I put artifacts/" — it just makes one. compose/
1394
+ // create for a page/svg/markdown; compose/canvas for interactive HTML/JS (animations, visualizations, decks).
1395
+ async function artifactCreate(args) {
1396
+ const content = str(args.content);
1397
+ if (!content)
1398
+ return "error: artifact_create needs content (an HTML page, SVG, or markdown)";
1399
+ const title = str(args.title) || "Operator artifact";
1400
+ const ctIn = str(args.content_type).toLowerCase();
1401
+ const ct = /^(html|svg|markdown|css|text|canvas)$/.test(ctIn) ? ctIn : "html";
1402
+ const base = (process.env.KODE_COMPOSE_URL || "https://compose.casa").replace(/\/$/, "");
1403
+ const canvas = ct === "canvas";
1404
+ const rpc = {
1405
+ jsonrpc: "2.0", id: 1, method: "tools/call",
1406
+ params: canvas
1407
+ ? { name: "compose/canvas", arguments: { html: content, title } }
1408
+ : { name: "compose/create", arguments: { content, content_type: ct, title } },
1409
+ };
1410
+ const token = process.env.KODE_COMPOSE_TOKEN || process.env.KODE_OPERATOR_TOKEN || process.env.OPERATOR_TOKEN;
1411
+ const ctrl = new AbortController();
1412
+ const timer = setTimeout(() => ctrl.abort(), Number(args.timeout_ms ?? 30_000));
1413
+ try {
1414
+ const res = await fetch(`${base}/mcp`, {
1415
+ method: "POST", signal: ctrl.signal,
1416
+ headers: { "Content-Type": "application/json", "User-Agent": "operator/kode-tsi", ...(token ? { Authorization: `Bearer ${token}` } : {}) },
1417
+ body: JSON.stringify(rpc),
1418
+ });
1419
+ if (!res.ok)
1420
+ return `error: compose.casa returned ${res.status} — the artifact surface is at ${base}/mcp — if it moved, the owner needs to update Operator's compose endpoint.`;
1421
+ const j = (await res.json().catch(() => ({})));
1422
+ if (j.error)
1423
+ return `error: compose.casa: ${j.error.message ?? "unknown error"}`;
1424
+ const text = (j.result?.content ?? []).map((c) => c.text ?? "").join(" ").trim();
1425
+ const rel = text.match(/\/v\/[A-Za-z0-9_-]+/); // compose returns a relative "/v/<id>"
1426
+ const url = rel ? `${base}${rel[0]}` : (text.match(/https?:\/\/\S+/) || [])[0];
1427
+ return url ? `created artifact → ${url}` : (text ? `artifact created: ${text}` : "artifact created (no URL returned)");
1428
+ }
1429
+ catch (e) {
1430
+ const msg = e?.name === "AbortError" ? "timed out" : String(e?.message ?? e);
1431
+ return `error: could not reach the artifact surface at ${base}/mcp (${msg})`;
1432
+ }
1433
+ finally {
1434
+ clearTimeout(timer);
1435
+ }
1436
+ }
1437
+ // voice_speak / voice_transcribe — Operator's OWN voice (operator-voice :8099: Kokoro TTS + whisper.cpp STT).
1438
+ // Same backend-broker shape as the media tools: env-configurable base (KODE_VOICE_URL), /health-gated, graceful
1439
+ // when the service is down. /synthesize returns raw WAV bytes (played locally via afplay on macOS, else saved);
1440
+ // /transcribe takes any ffmpeg-readable audio (multipart) and returns { text }. imageHealthy() is reused — the
1441
+ // voice /health returns {status:"ok"} with no `ok` field, so its `j.ok !== false` check passes on a 200.
1442
+ function voiceEndpoints() {
1443
+ const envs = [process.env.KODE_VOICE_URL, process.env.AXE_VOICE_URL].filter(Boolean);
1444
+ const defaults = ["http://127.0.0.1:8099"]; // operator-voice (SPEC.md): POST /synthesize, POST /transcribe, GET /health
1445
+ return [...new Set([...gatewayEndpoints("voice"), ...envs, ...defaults])].map((u) => u.replace(/\/$/, ""));
1446
+ }
1447
+ async function voiceSpeak(args) {
1448
+ const text = str(args.text);
1449
+ if (!text)
1450
+ return "error: voice_speak needs `text` to say";
1451
+ const voice = str(args.voice) || "bf_emma"; // the canonical Operator voice (same engine/voice as Cortana)
1452
+ const play = args.play !== false && str(args.play) !== "false"; // default true
1453
+ const candidates = voiceEndpoints();
1454
+ let base;
1455
+ for (const e of candidates) {
1456
+ if (await imageHealthy(e)) {
1457
+ base = e;
1458
+ break;
1459
+ }
1460
+ }
1461
+ if (!base)
1462
+ return `error: no voice service reachable (tried ${candidates.join(", ")}). Bring up operator-voice (:8099 / com.axe.operator-voice).`;
1463
+ const ctrl = new AbortController();
1464
+ const timer = setTimeout(() => ctrl.abort(), Number(args.timeout_ms ?? 60_000));
1465
+ try {
1466
+ const res = await fetch(`${base}/synthesize`, {
1467
+ method: "POST", signal: ctrl.signal,
1468
+ headers: { "Content-Type": "application/json", "User-Agent": "operator/kode-tsi", ...mediaAuth() },
1469
+ body: JSON.stringify({ text, voice }),
1470
+ });
1471
+ if (!res.ok)
1472
+ return `error: voice worker returned ${res.status} on /synthesize — ensure operator-voice is up`;
1473
+ const buf = Buffer.from(await res.arrayBuffer());
1474
+ if (!buf.length)
1475
+ return "error: voice worker returned no audio";
1476
+ const { writeFile, mkdir } = await nodeImport("node:fs/promises");
1477
+ const os = await nodeImport("node:os");
1478
+ const { join, dirname } = await nodeImport("node:path");
1479
+ const out = str(args.out) || join(os.tmpdir(), `operator-voice-${Date.now().toString(36)}.wav`);
1480
+ await mkdir(dirname(out), { recursive: true }).catch(() => { });
1481
+ await writeFile(out, buf);
1482
+ let played = false;
1483
+ if (play && process.platform === "darwin") {
1484
+ try {
1485
+ const { spawn } = await nodeImport("node:child_process");
1486
+ spawn("afplay", [out], { detached: true, stdio: "ignore" }).unref(); // fire-and-forget; don't block the turn on playback
1487
+ played = true;
1488
+ }
1489
+ catch { /* no afplay (headless/remote) — the WAV is still saved for a surface to play */ }
1490
+ }
1491
+ return `spoke ${text.length} chars (${voice}) → ${out}${played ? " (playing)" : " (saved; not played on this box)"}`;
1492
+ }
1493
+ catch (e) {
1494
+ const msg = e?.name === "AbortError" ? "timed out" : String(e?.message ?? e);
1495
+ return `error: voice worker unreachable at ${base} (${msg}) — start operator-voice (com.axe.operator-voice on :8099)`;
1496
+ }
1497
+ finally {
1498
+ clearTimeout(timer);
1499
+ }
1500
+ }
1501
+ async function voiceTranscribe(args) {
1502
+ const file = str(args.file);
1503
+ if (!file)
1504
+ return "error: voice_transcribe needs a `file` (path to wav/mp3/m4a/ogg audio)";
1505
+ const { readFile } = await nodeImport("node:fs/promises");
1506
+ const buf = await readFile(file).catch(() => null);
1507
+ if (!buf)
1508
+ return `error: voice_transcribe could not read a file at ${file}`;
1509
+ const candidates = voiceEndpoints();
1510
+ let base;
1511
+ for (const e of candidates) {
1512
+ if (await imageHealthy(e)) {
1513
+ base = e;
1514
+ break;
1515
+ }
1516
+ }
1517
+ if (!base)
1518
+ return `error: no voice service reachable (tried ${candidates.join(", ")}). Bring up operator-voice (:8099).`;
1519
+ const ctrl = new AbortController();
1520
+ const timer = setTimeout(() => ctrl.abort(), Number(args.timeout_ms ?? 120_000));
1521
+ try {
1522
+ const form = new FormData();
1523
+ const name = file.split("/").pop() || "audio.wav";
1524
+ form.append("file", new Blob([buf]), name); // multipart so any ffmpeg-readable format works (SPEC)
1525
+ const res = await fetch(`${base}/transcribe`, {
1526
+ method: "POST", signal: ctrl.signal,
1527
+ headers: { "User-Agent": "operator/kode-tsi", ...mediaAuth() }, // no Content-Type — FormData sets the multipart boundary
1528
+ body: form,
1529
+ });
1530
+ if (!res.ok)
1531
+ return `error: voice worker returned ${res.status} on /transcribe`;
1532
+ const j = (await res.json().catch(() => ({})));
1533
+ if (j.error)
1534
+ return `error: transcription failed — ${j.error}`;
1535
+ return j.text?.trim() || "(no speech detected)";
1536
+ }
1537
+ catch (e) {
1538
+ const msg = e?.name === "AbortError" ? "timed out" : String(e?.message ?? e);
1539
+ return `error: voice worker unreachable at ${base} (${msg}) — start operator-voice`;
1540
+ }
1541
+ finally {
1542
+ clearTimeout(timer);
1543
+ }
1544
+ }
902
1545
  const TOOLS = [
903
1546
  {
904
1547
  name: "bash", safe: false,
@@ -909,6 +1552,7 @@ const TOOLS = [
909
1552
  "run the command. stdout and stderr come back merged (like a terminal) with the exit code. " +
910
1553
  "Optional `cwd` runs that one command in a subshell without moving the session. For a " +
911
1554
  "long-running server/build/watcher use shell_background instead so this shell isn't blocked. " +
1555
+ "Pipelines run with `set -o pipefail`: if ANY stage fails the pipeline fails and you see [exit N] — a check hidden behind `| tail` can never fake success. " +
912
1556
  "Prefer SINGLE quotes for patterns and paths (grep -l '^x', not grep -l \"^x\"): a raw double-quote " +
913
1557
  "inside the command can break tool-call serialization on the local model and make the call fail.",
914
1558
  parameters: { type: "object", properties: {
@@ -1070,9 +1714,10 @@ const TOOLS = [
1070
1714
  },
1071
1715
  {
1072
1716
  name: "checkpoint", safe: false,
1073
- description: "Git add+commit a workspace and leave a memory note, in one call.",
1717
+ description: "Git add+commit a workspace and leave a memory note, in one call. Stages only the workspace's own subtree (never sibling dirs of the enclosing repo); pass `paths` to stage just those files/dirs.",
1074
1718
  parameters: { type: "object", properties: {
1075
1719
  summary: { type: "string" }, workspace: { type: "string" }, push: { type: "boolean" },
1720
+ paths: { type: "array", items: { type: "string" } },
1076
1721
  }, required: ["summary"] },
1077
1722
  run: checkpoint,
1078
1723
  },
@@ -1141,11 +1786,109 @@ const TOOLS = [
1141
1786
  }, required: ["query"] },
1142
1787
  run: webSearch,
1143
1788
  },
1789
+ {
1790
+ name: "image_generate",
1791
+ description: "Generate an image from a text prompt via the AXE image worker (local FLUX.1-schnell, scale-to-zero — no cloud key, no resident GPU). Writes a PNG and returns its path. This is the ONLY way to make images: NEVER load a diffusion model inline (e.g. ml.load of FLUX weights) — that pins GBs on the serving box and crawls your own decode.",
1792
+ parameters: { type: "object", properties: {
1793
+ prompt: { type: "string", description: "what to generate" },
1794
+ size: { type: "string", description: 'WxH, e.g. "512x512" (default) or "1024x1024"' },
1795
+ n: { type: "number", description: "how many images (1-4, default 1)" },
1796
+ reference: { type: "string", description: "optional reference image (path/url). A FACE photo → routes to the identity broker and preserves THAT specific person (IP-Adapter-FaceID) — this is how you 'generate HER'. Otherwise → flux img2img (restyle / match composition)." },
1797
+ strength: { type: "number", description: "img2img / denoise strength when a reference is given (0-1, default 0.65; lower = closer to the reference)" },
1798
+ ip_adapter_scale: { type: "number", description: "identity strength when a reference FACE is given (0-1, default 0.8; higher = stronger likeness to the person)" },
1799
+ expand: { type: "boolean", description: "ask the worker to auto-expand/rewrite the prompt (Aurora) before rendering; the richer prompt is returned and logged to the flywheel (never blocks)" },
1800
+ steps: { type: "number", description: "sampling steps (schnell default 4); raise to ~8 for finer img2img control (retain-vs-restyle resolution) when a reference is given" },
1801
+ out: { type: "string", description: "output .png path (default a temp file); for n>1 an index is appended" },
1802
+ timeout_ms: { type: "number", description: "default 180000 — a cold FLUX load + render is tens of seconds" },
1803
+ }, required: ["prompt"] },
1804
+ run: imageGenerate,
1805
+ },
1806
+ {
1807
+ name: "video_generate",
1808
+ description: "Generate a short video from a text prompt via the AXE video worker (LTX-Video on the scale-to-zero broker at video.axe.onl — no cloud key, no resident GPU). Returns the video's URL (renderable in-app) or a saved .mp4 path. NEVER load a video model inline (e.g. ml.load of weights) — that pins GBs on the serving box and crawls your own decode.",
1809
+ parameters: { type: "object", properties: {
1810
+ prompt: { type: "string", description: "what to generate" },
1811
+ size: { type: "string", description: 'WxH, e.g. "704x480" (default; the broker rounds w/h to multiples of 32)' },
1812
+ num_frames: { type: "number", description: "frames to render (default 97 ≈ 4s @ 24fps; the broker rounds to 8n+1)" },
1813
+ fps: { type: "number", description: "playback frames per second (default 24)" },
1814
+ seed: { type: "number", description: "optional seed for a reproducible render" },
1815
+ reference_image: { type: "string", description: "optional first-frame image (path/url) to condition on — image-to-video (e.g. animate a still made by image_generate)" },
1816
+ expand: { type: "boolean", description: "ask the worker to auto-expand/rewrite the prompt (Aurora) before rendering" },
1817
+ out: { type: "string", description: "output .mp4 path (default a temp file); for multiple results an index is appended" },
1818
+ timeout_ms: { type: "number", description: "default 600000 — a cold LTX load + sampling runs minutes" },
1819
+ }, required: ["prompt"] },
1820
+ run: videoGenerate,
1821
+ },
1822
+ {
1823
+ name: "image_analyze", safe: true,
1824
+ description: "Analyze/describe an image via the AXE vision model (Qwen2-VL on the fleet — REAL vision, not pixel stats). Pass a local path or an http(s) url + an optional question; returns the model's answer. Use this to actually SEE a reference, screenshot, or generated image before acting on it — NEVER guess an image's content from its file size or numpy brightness.",
1825
+ parameters: { type: "object", properties: {
1826
+ image: { type: "string", description: "a local file path or an http(s) url to the image" },
1827
+ question: { type: "string", description: 'what to ask about the image (default "Describe this image in detail.")' },
1828
+ max_tokens: { type: "number", description: "optional cap on answer length; omit for a full, uncapped description" },
1829
+ timeout_ms: { type: "number", description: "default 120000" },
1830
+ }, required: ["image"] },
1831
+ run: imageAnalyze,
1832
+ },
1833
+ {
1834
+ name: "video_analyze", safe: true,
1835
+ description: "Analyze/describe a VIDEO via the AXE vision model — ffmpeg samples frames evenly across the clip and Qwen2-VL (multi-image) describes what happens. Pass a local path or an http(s) url + an optional question; returns the analysis. Use this to actually SEE a video's content — never guess from the file.",
1836
+ parameters: { type: "object", properties: {
1837
+ video: { type: "string", description: "a local file path or an http(s) url to the video" },
1838
+ question: { type: "string", description: "what to ask about the video (default: describe what happens across it)" },
1839
+ frames: { type: "number", description: "how many frames to sample across the clip (2-16, default 8)" },
1840
+ max_tokens: { type: "number", description: "optional cap on answer length; omit for a full, uncapped description" },
1841
+ timeout_ms: { type: "number", description: "default 180000" },
1842
+ }, required: ["video"] },
1843
+ run: videoAnalyze,
1844
+ },
1845
+ {
1846
+ name: "voice_speak", safe: false,
1847
+ description: "Speak text aloud in Operator's OWN voice (Kokoro TTS on operator-voice :8099). Synthesizes `text` to speech in `voice` (default bf_emma, the canonical Operator/Cortana voice) and plays it on the owner's machine. Use it to actually SAY something to the owner — a spoken status, answer, or heads-up — not just print it. Saves the WAV and returns its path; on a headless/remote box it saves without playing (pass play:false to only synthesize for a surface to play).",
1848
+ parameters: { type: "object", properties: {
1849
+ text: { type: "string", description: "what to say" },
1850
+ voice: { type: "string", description: 'Kokoro voice id (default "bf_emma", the Operator voice)' },
1851
+ play: { type: "boolean", description: "play it locally (default true); false = synthesize + save only" },
1852
+ out: { type: "string", description: "output .wav path (default a temp file)" },
1853
+ timeout_ms: { type: "number", description: "default 60000" },
1854
+ }, required: ["text"] },
1855
+ run: voiceSpeak,
1856
+ },
1857
+ {
1858
+ name: "voice_transcribe", safe: true,
1859
+ description: "Transcribe an audio file to text via Operator's speech-to-text (whisper.cpp on operator-voice :8099). Pass a local `file` (wav/mp3/m4a/ogg — any ffmpeg-readable format); returns the transcribed text. Use this to actually HEAR a voice note or recording the owner shares, instead of guessing at it.",
1860
+ parameters: { type: "object", properties: {
1861
+ file: { type: "string", description: "local path to an audio file (wav/mp3/m4a/ogg)" },
1862
+ timeout_ms: { type: "number", description: "default 120000" },
1863
+ }, required: ["file"] },
1864
+ run: voiceTranscribe,
1865
+ },
1866
+ {
1867
+ name: "image_recreate",
1868
+ description: "Recreate a shared REFERENCE image: Operator SEES it with the vision model, extracts a faithful text-to-image prompt, and generates a matching image — the 'share a reference → recreate it' flow in one call. Pass a local path or http(s) url + optional `instructions` to adjust. Returns the recreation + what it understood. (Pixel-exact fidelity — same face/scene — will use img2img/IP-Adapter once the edit broker lands; today it matches subject/style/composition/lighting from the analyzed prompt.)",
1869
+ parameters: { type: "object", properties: {
1870
+ reference: { type: "string", description: "the reference image to recreate (a local path or an http(s) url)" },
1871
+ instructions: { type: "string", description: "optional adjustments layered on the match, e.g. 'but in daylight' or 'make it a wide shot'" },
1872
+ size: { type: "string", description: 'WxH, default "1024x1024"' },
1873
+ out: { type: "string", description: "output .png path (default a temp file)" },
1874
+ }, required: ["reference"] },
1875
+ run: imageRecreate,
1876
+ },
1877
+ {
1878
+ name: "artifact_create",
1879
+ description: "Make a shareable ARTIFACT — an HTML page / dashboard / landing page, an SVG, a markdown doc, a DECK / PRESENTATION, or an interactive canvas — hosted on compose.casa, returning a public clickable URL. This is THE way to create an artifact / design / page / deck for the owner: NEVER write a local file or hunt for a 'compose' folder. Pass the full content; use content_type 'canvas' for interactive HTML/JS (animations, visualizations, presentations).",
1880
+ parameters: { type: "object", properties: {
1881
+ content: { type: "string", description: "the full artifact content — a complete HTML document, SVG, or markdown" },
1882
+ title: { type: "string", description: "a short title for the artifact" },
1883
+ content_type: { type: "string", description: "html (default) | svg | markdown | canvas (interactive HTML/JS — animations, visualizations, presentations)" },
1884
+ }, required: ["content"] },
1885
+ run: artifactCreate,
1886
+ },
1144
1887
  {
1145
1888
  name: "skill_list", safe: true,
1146
- description: "List or search AXE skills from the Operator registry (operator.axe.onl /v1/skills) — reusable playbooks for code review, security audit, debugging, architecture, and more. Read-only.",
1889
+ description: "List or search AXE skills from the Operator registry (operator.axe.onl /v1/skills) — reusable playbooks for code review, security audit, debugging, architecture, and more. With no query it lists the curated skills; pass a query to search the full catalogue (community skills too). Read-only.",
1147
1890
  parameters: { type: "object", properties: {
1148
- query: { type: "string", description: "optional search term to filter skills" },
1891
+ query: { type: "string", description: "optional search term — also searches community skills; omit for the curated list" },
1149
1892
  } },
1150
1893
  run: (a) => skillList(str(a.query)),
1151
1894
  },
@@ -1206,7 +1949,14 @@ async function operatorGet(path) {
1206
1949
  }
1207
1950
  return null;
1208
1951
  }
1209
- async function skillList(query) {
1952
+ // Community-catalogue slugs ("community__axehub:ClawHub:…") dwarf our curated set — the default list dumped
1953
+ // 200+ of them into context every call. The DEFAULT (no-query) list is curated-only; a search still reaches
1954
+ // community, and skill_fetch takes any slug.
1955
+ const isCommunitySkill = (s) => {
1956
+ const slug = String(s?.slug ?? s?.name ?? "");
1957
+ return slug.includes("community__") || slug.includes(":");
1958
+ };
1959
+ export async function skillList(query) {
1210
1960
  // Prefer the ranked /search when a query is given; fall back to the full list.
1211
1961
  const local = await localSkills();
1212
1962
  const localBlock = local.length ? `your profile skills:\n${local.map((l) => `• ${l.name} (profile)`).join("\n")}\n\n` : "";
@@ -1219,15 +1969,21 @@ async function skillList(query) {
1219
1969
  if (r === null) {
1220
1970
  return localBlock ? `${localBlock}(hub unreachable — showing profile skills only)` : "error: skill registry unreachable (operator.axe.onl / skills.axe.onl)";
1221
1971
  }
1222
- const arr = Array.isArray(r) ? r : r.results ?? r.skills ?? [];
1223
- if (!Array.isArray(arr) || arr.length === 0)
1972
+ const all = Array.isArray(r) ? r : r.results ?? r.skills ?? [];
1973
+ if (!Array.isArray(all) || all.length === 0)
1224
1974
  return `${localBlock}${query ? `no hub skills match "${query}"` : "no skills in the hub yet"}`;
1975
+ // Default list = OUR curated skills only; a search (query) returns community matches too.
1976
+ const arr = query ? all : all.filter((s) => !isCommunitySkill(s));
1977
+ const hidden = all.length - arr.length;
1978
+ const hiddenNote = hidden > 0 ? `\n(${hidden} community skill${hidden === 1 ? "" : "s"} not listed — skill_list "<search>" finds them; skill_fetch takes any slug)` : "";
1979
+ if (arr.length === 0)
1980
+ return `${localBlock}no curated skills listed${hiddenNote}`;
1225
1981
  // Compact one-line-per-skill: name — description (from the skillmd metadata).
1226
1982
  const lines = arr.slice(0, 40).map((s) => {
1227
1983
  const desc = s?.metadata?.taxonomy?.description ?? s?.metadata?.description ?? s?.description ?? "";
1228
1984
  return `• ${s?.name ?? "?"}${desc ? ` — ${String(desc).replace(/\s+/g, " ").slice(0, 140)}` : ""}`;
1229
1985
  });
1230
- return `${localBlock}${arr.length} hub skill${arr.length === 1 ? "" : "s"} (skill_fetch <name> to use one):\n${lines.join("\n")}`;
1986
+ return `${localBlock}${arr.length} hub skill${arr.length === 1 ? "" : "s"} (skill_fetch <name> to use one):\n${lines.join("\n")}${hiddenNote}`;
1231
1987
  }
1232
1988
  async function skillFetch(slug) {
1233
1989
  if (!slug)
@@ -1243,7 +1999,11 @@ async function skillFetch(slug) {
1243
1999
  catch { /* fall through to hub */ }
1244
2000
  }
1245
2001
  }
1246
- const r = await operatorGet(`/v1/skills/${encodeURIComponent(slug)}`);
2002
+ // The hub matches the RAW stored skill name as the path segment (no server-side URL-decode), and many
2003
+ // community slugs contain ':' (e.g. "community__axehub:ClawHub:…"). encodeURIComponent turns ':' into
2004
+ // %3A → 404, so those skills couldn't be fetched at all — curated slugs have no special chars, which hid
2005
+ // the bug. Keep ':' literal; everything else encodeURIComponent already leaves path-safe.
2006
+ const r = await operatorGet(`/v1/skills/${encodeURIComponent(slug).replace(/%3A/gi, ":")}`);
1247
2007
  if (r === null)
1248
2008
  return `error: skill '${slug}' unreachable or not found`;
1249
2009
  if (typeof r === "string")
@@ -1308,3 +2068,88 @@ export function toSchemas(reg = registry) {
1308
2068
  function: { name: t.name, description: t.description, parameters: t.parameters },
1309
2069
  }));
1310
2070
  }
2071
+ const CATALOGUE_LIST_CAP = 24000;
2072
+ const MCP_NOTE_MAX = 12;
2073
+ // Best-effort SYNCHRONOUS read of the owned-MCP registry (the name-keyed map loadMcpConfig consumes, from
2074
+ // $KODE_MCP_CONFIG or ~/.axe/cli/backend/mcp_servers.json) so the catalogue names the servers actually
2075
+ // configured, not a hard-coded example. process.getBuiltinModule (Node ≥20.16) keeps this module free of a
2076
+ // static node: import (see the header); any failure → "" and the caller keeps its minimal static note.
2077
+ function ownedMcpNote() {
2078
+ try {
2079
+ const proc = globalThis.process;
2080
+ const fs = proc?.getBuiltinModule?.("node:fs");
2081
+ const os = proc?.getBuiltinModule?.("node:os");
2082
+ if (!fs || !os)
2083
+ return "";
2084
+ const raw = JSON.parse(fs.readFileSync(proc?.env?.KODE_MCP_CONFIG ?? `${os.homedir()}/.axe/cli/backend/mcp_servers.json`, "utf8"));
2085
+ const map = (raw && typeof raw === "object" && "mcpServers" in raw ? raw.mcpServers : raw);
2086
+ const servers = Object.entries(map ?? {}).filter(([, c]) => c && typeof c === "object");
2087
+ if (!servers.length)
2088
+ return "";
2089
+ const adv = servers.filter(([, c]) => c.advertise !== false);
2090
+ const label = ([name, c]) => {
2091
+ const purpose = String(c.purpose ?? c.category ?? "").replace(/\s+/g, " ").trim().slice(0, 80);
2092
+ const n = Number(c.tools_approx);
2093
+ return name + (purpose ? ` — ${purpose}` : "") + (n > 0 ? ` (~${Math.round(n)} tools)` : "");
2094
+ };
2095
+ const shown = adv.slice(0, MCP_NOTE_MAX).map(label).join("; ");
2096
+ const overflow = adv.length - MCP_NOTE_MAX;
2097
+ const optIn = servers.length - adv.length;
2098
+ return (shown ? ` Owned MCP servers: ${shown}${overflow > 0 ? `; +${overflow} more` : ""}.` : "") + (optIn > 0 ? ` ${optIn} more owned MCP servers (opt-in).` : "");
2099
+ }
2100
+ catch {
2101
+ return "";
2102
+ }
2103
+ }
2104
+ // A compact, SELF-MAINTAINING capability index for the system prompt. The per-call tool SCHEMAS
2105
+ // (toSchemas) already tell the model how to CALL each tool; this gives it the high-level MAP of its
2106
+ // whole surface — every native tool one line each (name — trimmed description, in declaration order,
2107
+ // which is already grouped), plus the MCP layer, the in-session /commands, the headless CLI modes, and
2108
+ // the skills catalogue. Rendered from the LIVE registry so a newly-added tool appears here automatically
2109
+ // (no prose to drift) — that is the whole point: "Operator aware of all its tools". Pass a merged map
2110
+ // (native + connected MCP tools) to include those too; defaults to the native registry. `lean` (a
2111
+ // small-context model) skips the per-tool list — it duplicates the schemas attached to every request — and
2112
+ // keeps only the surface summary; the list is also char-capped so a large merged map can't blow the prompt.
2113
+ export function renderToolCatalogue(reg = registry, opts = {}) {
2114
+ const short = (d) => {
2115
+ const one = d.replace(/\s+/g, " ").trim();
2116
+ if (one.length <= 150)
2117
+ return one;
2118
+ const cut = one.slice(0, 150);
2119
+ const sp = cut.lastIndexOf(" ");
2120
+ return (sp > 60 ? cut.slice(0, sp) : cut) + "…";
2121
+ };
2122
+ let head;
2123
+ if (opts.lean) {
2124
+ head = `Your tool schemas are attached to every request — they are the full list of what you can call; use a tool you HAVE, don't claim one you don't.`;
2125
+ }
2126
+ else {
2127
+ const tools = [...reg.values()];
2128
+ const lines = [];
2129
+ let used = 0;
2130
+ for (const t of tools) {
2131
+ const line = `- \`${t.name}\` — ${short(t.description)}`;
2132
+ if (used + line.length + 1 > CATALOGUE_LIST_CAP)
2133
+ break;
2134
+ lines.push(line);
2135
+ used += line.length + 1;
2136
+ }
2137
+ head =
2138
+ `You act through TOOLS, not prose. Your ${tools.length} native tools, each already callable this session` +
2139
+ (lines.length < tools.length ? ` (first ${lines.length} listed — the rest are in your attached tool schemas)` : "") +
2140
+ `:\n` + lines.join("\n");
2141
+ }
2142
+ return (`\n\n## Your capabilities — the full surface (use a tool you HAVE; don't claim one you don't)\n` +
2143
+ head +
2144
+ `\n\n**MCP tools** — with the MCP layer on (the owner types \`/mcp on\`) more tools load from configured servers and ` +
2145
+ `appear alongside the native ones.` +
2146
+ ownedMcpNote() +
2147
+ ` If one you expect is missing, say the MCP layer needs enabling rather than hand-rolling its job.` +
2148
+ `\n**In-session /commands** (the owner types these; you do NOT call them): /help /model /route /compact ` +
2149
+ `/stats /mcp /new /artifacts /services /clear /exit.` +
2150
+ `\n**Headless CLI modes** (how the owner runs you unattended — same engine + persona): \`operator run\` ` +
2151
+ `(one task), \`operator loop\` (continuous), \`operator board\` / \`operator dream\` (autonomy), ` +
2152
+ `\`operator media-robot\` (best-of-N media + vision-judge flywheel).` +
2153
+ `\n**Skills** — \`skill_list\` / \`skill_fetch\` / \`skill_save\` reach the 60k+ AXE skills catalogue ` +
2154
+ `(curated + community); prefer applying an existing skill over rebuilding a capability from scratch.`);
2155
+ }