@0perator/operator 0.1.222 → 0.1.261

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 (110) hide show
  1. package/README.md +6 -5
  2. package/dashboard/server.mjs +1 -1
  3. package/dist/acp/agent.js +320 -53
  4. package/dist/acp/auth.js +44 -0
  5. package/dist/acp/config-options.js +34 -0
  6. package/dist/acp/prompt.js +41 -0
  7. package/dist/acp/run.js +116 -10
  8. package/dist/acp/tool-map.js +48 -0
  9. package/dist/auth/byo.js +125 -0
  10. package/dist/auth/client.js +12 -6
  11. package/dist/auth/commands.js +71 -3
  12. package/dist/auth/identity.js +136 -0
  13. package/dist/auth/store.js +7 -5
  14. package/dist/autonomy/board.js +3 -2
  15. package/dist/autonomy/cron.js +332 -0
  16. package/dist/autonomy/delegate.js +168 -0
  17. package/dist/autonomy/dream.js +1 -1
  18. package/dist/autonomy/index.js +16 -2
  19. package/dist/autonomy/media-robot.js +137 -0
  20. package/dist/autonomy/profile.js +77 -0
  21. package/dist/autonomy/routines.js +5 -4
  22. package/dist/autonomy/session-factory.js +19 -10
  23. package/dist/background/index.js +8 -1
  24. package/dist/browser/cdp.js +266 -0
  25. package/dist/browser/session.js +286 -0
  26. package/dist/cli.js +207 -106
  27. package/dist/compose/client.js +56 -0
  28. package/dist/config/brand.js +3 -3
  29. package/dist/config/home.js +70 -0
  30. package/dist/config/managed.js +230 -0
  31. package/dist/config/persona.js +243 -21
  32. package/dist/config/scaffold.js +142 -0
  33. package/dist/config/settings.js +87 -20
  34. package/dist/config/skills-index.js +175 -0
  35. package/dist/consolidation/scheduler.js +10 -7
  36. package/dist/consolidation/sleep.js +17 -3
  37. package/dist/engine/agent.js +231 -21
  38. package/dist/engine/aurora.js +79 -14
  39. package/dist/engine/batch-scheduler.js +128 -0
  40. package/dist/engine/compaction.js +129 -2
  41. package/dist/engine/computer-event.js +139 -0
  42. package/dist/engine/continuation.js +55 -0
  43. package/dist/engine/contract.js +3 -1
  44. package/dist/engine/grandmaster.js +13 -3
  45. package/dist/engine/json-repair.js +105 -0
  46. package/dist/engine/messages.js +52 -5
  47. package/dist/engine/redact.js +25 -0
  48. package/dist/engine/rolling-summary.js +28 -11
  49. package/dist/engine/router-adapter.js +2 -0
  50. package/dist/engine/unrestricted.js +51 -0
  51. package/dist/engine/verify-gate.js +6 -0
  52. package/dist/enterprise/cli.js +137 -0
  53. package/dist/flywheel/processor.js +30 -2
  54. package/dist/flywheel/secret-gate.js +123 -0
  55. package/dist/index.browser.js +4 -0
  56. package/dist/index.js +4 -0
  57. package/dist/mcp/index.js +18 -24
  58. package/dist/memory/index.js +0 -0
  59. package/dist/memory/session-index.js +324 -0
  60. package/dist/memory/session-rewind.js +92 -0
  61. package/dist/memory/state-maintenance.js +441 -0
  62. package/dist/observability/index.js +3 -3
  63. package/dist/permissions/audit.js +4 -1
  64. package/dist/permissions/index.js +24 -12
  65. package/dist/permissions/policy.js +4 -3
  66. package/dist/permissions/tier.js +31 -14
  67. package/dist/remote/host.js +9 -2
  68. package/dist/router/models.js +62 -2
  69. package/dist/selfimprove/index.js +9 -7
  70. package/dist/session.js +129 -42
  71. package/dist/skills/catalogue.js +167 -0
  72. package/dist/telemetry/audit-verify.js +94 -0
  73. package/dist/telemetry/events.js +92 -7
  74. package/dist/telemetry/lifecycle.js +18 -0
  75. package/dist/tools/computer.js +1 -1
  76. package/dist/tools/deferred.js +117 -0
  77. package/dist/tools/executor.js +27 -23
  78. package/dist/tools/memory.js +117 -0
  79. package/dist/tools/mutating.js +6 -0
  80. package/dist/tools/registry.js +1022 -46
  81. package/dist/tools/sandbox.js +63 -17
  82. package/dist/tools/searxng.js +2 -2
  83. package/dist/tools/shell-session.js +36 -1
  84. package/dist/tools/tool-output-spill.js +4 -4
  85. package/dist/ui/ActivitySpinner.js +17 -6
  86. package/dist/ui/App.js +36 -14
  87. package/dist/ui/ArtifactPicker.js +109 -0
  88. package/dist/ui/Composer.js +39 -8
  89. package/dist/ui/Markdown.js +5 -3
  90. package/dist/ui/MouseProvider.js +99 -19
  91. package/dist/ui/QuestionPrompt.js +24 -3
  92. package/dist/ui/ThinkingSpinner.js +9 -5
  93. package/dist/ui/ToolStep.js +17 -12
  94. package/dist/ui/Transcript.js +28 -9
  95. package/dist/ui/capabilities.js +0 -9
  96. package/dist/ui/listhit.js +23 -0
  97. package/dist/ui/mouse.js +22 -0
  98. package/dist/ui/osc.js +7 -4
  99. package/dist/ui/progressbar.js +46 -0
  100. package/dist/ui/shimmer.js +43 -0
  101. package/dist/ui/theme.js +2 -0
  102. package/dist/ui/tick.js +48 -0
  103. package/dist/ui/toolicons.js +69 -0
  104. package/dist/ui/useInputHistory.js +3 -3
  105. package/dist/util/slash.js +1 -0
  106. package/dist/vault/cli.js +48 -0
  107. package/dist/vault/store.js +157 -0
  108. package/dist/vault/tool.js +50 -0
  109. package/package.json +3 -5
  110. package/CHANGELOG.md +0 -1629
@@ -6,10 +6,48 @@ export const DEFAULT_MODEL_ID = "operator-1m";
6
6
  export const MODEL_ALIASES = {
7
7
  "aurora-1m": "operator-1m",
8
8
  "aurora-128k": "operator-128k",
9
+ "spectre": "cortana", // flagship renamed Spectre -> Cortana 35B (2026-10-07); old id keeps resolving
9
10
  };
10
11
  export const BUILTIN_MODELS = [
11
12
  { id: "operator-1m", label: "Operator 300K", kind: "single", desc: "307,200-token (300K) context (:8097)", endpoint: "http://127.0.0.1:8097/v1", model: "aurora-code-1", ctx: 307200 },
12
13
  { id: "operator-128k", label: "Operator 128K", kind: "single", desc: "128K context, lighter RAM (:8096)", endpoint: "http://127.0.0.1:8096/v1", model: "aurora-code-1", ctx: 131072 },
14
+ // QwenCloud Token Plan BYO connectors (SPEC/providers.md §2 "API-key connectors"). Same keychain
15
+ // account ("qwen") serves both; the picker hides them until connected (§1 honest availability), and
16
+ // authHeaders NEVER sends the Operator token to this host. ctx starts conservative and self-clamps
17
+ // to the served truth (observeContext).
18
+ { id: "qwen3.8-max", label: "Qwen 3.8 Max", kind: "single", desc: "BYO QwenCloud Token Plan — credits from your plan", endpoint: "https://token-plan.maas.qwencloudapi.com/compatible-mode/v1", model: "qwen3.8-max", ctx: 262144, byo: "qwen", transport: "openai" },
19
+ { id: "qwen3.8-flash", label: "Qwen 3.8 Flash", kind: "single", desc: "BYO QwenCloud Token Plan — fast tier, your credits", endpoint: "https://token-plan.maas.qwencloudapi.com/compatible-mode/v1", model: "qwen3.8-flash", ctx: 262144, byo: "qwen", transport: "openai" },
20
+ // AXE Token Plan connector — the INVERSE of the QwenCloud entries: here AXE is the vendor
21
+ // (_ai-docs/architecture/axe-model-vendor.md, phase V1). api.axe.onl is AXE's own gateway
22
+ // (nginx + LiteLLM); third-party users paste an `sk-axe-…` virtual key (`operator auth byo axe`),
23
+ // stored under keychain account "axe" — a separate account from the operator token, so the two
24
+ // can never be confused (auth/byo.ts separation guard). Gateway-side sk-axe acceptance is the V0
25
+ // deployment step; until then the connector stays hidden (honest availability). A ghost-32b API
26
+ // SKU joins once the gateway routes JL1:8101 (reverse tunnel owed — api/README "524" note).
27
+ { id: "axe-aurora-300k", label: "AXE Aurora 300K (API)", kind: "single", desc: "BYO AXE Token Plan — agent-tuned 300K reasoner via api.axe.onl", endpoint: "https://api.axe.onl/v1", model: "aurora-code-1", ctx: 307200, byo: "axe", transport: "openai" },
28
+ // Spectre — the flagship, replacing Ghost (2026-10-07). Ghost 32B was the prior self-hosted abliterated
29
+ // Qwen3-VL-32B on this slot; retired when Spectre proved 4× faster at equal capability (its weights + restore
30
+ // command are kept at ~/.axe/logs/ghost-restore-cmd.txt — reversible). Spectre = Huihui-Qwen3.6-35B-A3B-
31
+ // abliterated: a 35B MoE with ~3B ACTIVE per token → ~40 tok/s (4× Ghost's dense-32B ~10), still abliterated
32
+ // (uncensored) AND vision-capable (ships an mmproj). Served on JL1:8101 via launchd com.axe.spectre-serve,
33
+ // thinking defaulted OFF server-side (--reasoning off) so it answers cleanly (no empty-content reasoning trap).
34
+ // ctx 32000 = the TRUTH: the llama.cpp server serves n_ctx=32768 (--ctx-size 32768, verified via /props), NOT the
35
+ // 65536 the profile claimed before 0.1.260. The 65536 lie made the engine overrun the real 32768 wall → the server
36
+ // truncated a round at token 32767 (finish=length) mid-tool-call, and that cut call poisoned the session (0.1.259).
37
+ // 32000 sits just UNDER the real wall (margin) AND under LEAN_HARNESS_CTX so Cortana drops the heavy memory/handoff
38
+ // (which alone was ~16K = half the window) — persona + unrestricted layer kept. Raise ONLY if the server's --ctx-size does.
39
+ { id: "cortana", label: "Cortana 35B", kind: "single", desc: "flagship — abliterated Qwen3.6-35B-A3B MoE (~3B active, ~40 tok/s), uncensored + vision (JL1:8112, llama.cpp, 32K ctx)", endpoint: "http://192.168.1.103:8112/v1", model: "/Volumes/Ai Storage/jl1-local/models/aurorax/Huihui-Qwen3.6-35B-A3B-abliterated.Q4_K_M.gguf", ctx: 32000 },
40
+ // Qwen3-4B — fast LOCAL tier (stock qwen3-4b-mlx-q4, 2.26GB MLX 4-bit, ctx 40960) served via mlx_lm.server
41
+ // on JL1:8110. Qwen3 vocab (151936) — the same family as ghost-32b, so it's the review-recommended quick tier
42
+ // AND the vocab lineage for ghost spec-decode (the actual draft is Qwen3-0.6B, too small to list here). Runs
43
+ // /no_think for speed. Picked (2026-10-07) from a fleet-wide 3B-class review; no 3B had been execution-graded,
44
+ // so this is the evidence-led default pending a dyno/coding-eval bench. 40960 ≥ LEAN_HARNESS_CTX → full harness.
45
+ { id: "scout", label: "Scout 4B", kind: "single", desc: "fast local tier — Qwen3-4B /no_think, Qwen3 vocab (JL1:8110, MLX 4-bit)", endpoint: "http://192.168.1.103:8110/v1", model: "/Volumes/Ai Storage/axe-models/qwen3-4b-mlx-q4", ctx: 32000 },
46
+ // Venice 24B — a LIGHTER uncensored alternative to the 35B Spectre: Dolphin-Mistral-24B-Venice-Edition
47
+ // (Q4_K_M, ~14GB) with a bolted-on Mistral-Small-3.1 mmproj for vision. Dense 24B (not MoE), served on
48
+ // JL1:8114 via llama.cpp (--jinja, q8 KV). ctx 32768 ≥ LEAN_HARNESS_CTX → full harness. A quick drop-in to
49
+ // test a smaller/different flavour alongside Spectre without the 35B footprint.
50
+ { id: "venice-24b", label: "Venice 24B", kind: "single", desc: "lighter uncensored tier — Dolphin-Mistral-24B-Venice + vision (JL1:8114, llama.cpp)", endpoint: "http://192.168.1.103:8114/v1", model: "/Volumes/Ai Storage/exotic-models/dolphin-mistral-24b-venice-gguf/cognitivecomputations_Dolphin-Mistral-24B-Venice-Edition-Q4_K_M.gguf", ctx: 32768 },
13
51
  { id: "moa", label: "MOA (Mixture of Agents)", kind: "orchestrated", desc: "fan out to proposers, synthesize with an aggregator" },
14
52
  ];
15
53
  /** The runtime registry: the built-ins, with any settings.models entries merged in (overriding a
@@ -26,17 +64,39 @@ export function findModel(registry, id) {
26
64
  const canon = MODEL_ALIASES[id] ?? id; // aurora-1m -> operator-1m (old ids keep resolving)
27
65
  return registry.find((m) => m.id === canon);
28
66
  }
67
+ /** The configured context window (tokens) for a model id — from BUILTIN_MODELS + settings overrides — or
68
+ * Infinity if unknown. Used to pick a LEAN harness: a small-context model (e.g. a self-hosted 8K Venice)
69
+ * can't take Operator's full memory + handoff injection (sized for Aurora's 300K); it fills the window and
70
+ * the model recites the memory instead of answering. Callers drop the heavy memory/handoff below a
71
+ * threshold while keeping the base persona (incl. the Direct/unrestricted section), so it stays uncensored. */
72
+ export function modelCtxFor(id, overrides) {
73
+ if (!id)
74
+ return Number.POSITIVE_INFINITY;
75
+ return findModel(modelRegistry(overrides), id)?.ctx ?? Number.POSITIVE_INFINITY;
76
+ }
77
+ /** ctx window below which the lean harness (no heavy memory/handoff) kicks in. Aurora/Qwen (128K+) stay
78
+ * full; a self-hosted small model (Venice 8K, or a 16K bump) goes lean. */
79
+ export const LEAN_HARNESS_CTX = 32768;
29
80
  /** Pure selection reducer for /model — no I/O (no settings read/write, no router mutation), so it's
30
81
  * directly testable. The moa-needs-config check lives in Session.setModel (it needs settings.moa,
31
- * which this module intentionally doesn't import). */
32
- export function selectModel(registry, id) {
82
+ * which this module intentionally doesn't import). `hasByo` (injected by the caller, see auth/byo)
83
+ * gates BYO connector profiles: honest "not connected" beats a request-time 401. */
84
+ export function selectModel(registry, id, hasByo) {
33
85
  const profile = findModel(registry, id);
34
86
  if (!profile)
35
87
  return { error: `unknown model "${id}" — choices: ${registry.map((m) => m.id).join(", ")}` };
36
88
  if (profile.kind === "single" && !profile.endpoint)
37
89
  return { error: `model "${id}" has no endpoint configured` };
90
+ if (profile.byo && hasByo && !hasByo(profile.byo)) {
91
+ return { error: `"${id}" is not connected — store the ${profile.byo} key first: operator auth byo ${profile.byo}` };
92
+ }
38
93
  return { profile };
39
94
  }
95
+ /** The picker-truth view of a registry: drops BYO profiles whose key isn't connected (and ALL
96
+ * unresolvable ones when the resolver is absent — a picker must never offer what setModel refuses). */
97
+ export function visibleModels(registry, hasByo) {
98
+ return registry.filter((p) => !p.byo || (hasByo ? hasByo(p.byo) : false));
99
+ }
40
100
  /** Strip a trailing /v1 so a ModelProfile/MoaAggregator endpoint can feed the AuroraRouter, whose
41
101
  * base is bare (engine/aurora.ts's chat() appends /v1/chat/completions itself). */
42
102
  export function endpointBase(endpoint) {
@@ -3,6 +3,8 @@
3
3
  // per-turn hook is where the other sinks layer in: MEMORY distillation, SKILL capture, and post-task
4
4
  // REFLECTION. All sinks are best-effort and MUST never block or throw into a turn. Node imports are lazy
5
5
  // (same mobile/JSCore-bundle discipline as services/preflight.ts) so the neutral bundle carries none of it.
6
+ import { operatorPath } from "../config/home.js";
7
+ import { redactSecrets } from "../engine/redact.js";
6
8
  const nodeImport = (m) => import(/* @vite-ignore */ m);
7
9
  // GW-18 (flywheel gate): markers of a STRUCTURED tool call that leaked into the assistant's plain text instead
8
10
  // of being parsed into tool_calls — the documented Qwen3 failure when the server runs without `--jinja` (the
@@ -25,11 +27,8 @@ async function captureFlywheel(r) {
25
27
  try {
26
28
  const { appendFile, mkdir } = await nodeImport("node:fs/promises");
27
29
  const { join } = await nodeImport("node:path");
28
- const home = process.env.HOME ?? "";
29
- if (!home)
30
- return;
31
- const dir = join(home, ".axe", "operator", "flywheel");
32
- await mkdir(dir, { recursive: true });
30
+ const dir = operatorPath("flywheel"); // follows $KODE_HOME/$KODE_PROFILE — one identity's prompts never land in another's corpus
31
+ await mkdir(dir, { recursive: true, mode: 0o700 });
33
32
  // graded = a promotable trajectory. A turn that changed files but never ran a passing check
34
33
  // (unverified, per the verify-before-done gate) is NOT promotable — that is precisely the hollow
35
34
  // "done" this whole loop exists to stop the fleet from training on.
@@ -38,8 +37,11 @@ async function captureFlywheel(r) {
38
37
  // and the serving side (GW-01/GW-18 `--jinja`) can be verified by the trend going to ~0.
39
38
  const parseFallback = hasLeakedToolCall(r.content);
40
39
  const graded = !!r.content.trim() && r.stopReason !== "repetition" && r.rounds > 0 && !r.unverified && !parseFallback;
41
- const row = JSON.stringify({ ts: Date.now(), graded, parse_fallback: parseFallback, ...r }) + "\n";
42
- await appendFile(join(dir, `${new Date().toISOString().slice(0, 10)}.jsonl`), row);
40
+ // The row carries the user's PROMPT and the full answer, and the corpus is read by the training pipeline —
41
+ // mask known secret shapes before they reach disk (the same boundary events.jsonl enforces) and keep the
42
+ // file owner-only; this used to be a 0644 file in a 0755 dir with raw prompts in it.
43
+ const row = redactSecrets(JSON.stringify({ ts: Date.now(), graded, parse_fallback: parseFallback, ...r })) + "\n";
44
+ await appendFile(join(dir, `${new Date().toISOString().slice(0, 10)}.jsonl`), row, { encoding: "utf8", mode: 0o600 });
43
45
  }
44
46
  catch { /* best-effort — capture never blocks or fails a turn */ }
45
47
  }
package/dist/session.js CHANGED
@@ -4,26 +4,48 @@
4
4
  import { runTurn, TurnAbortedError } from "./engine/agent.js";
5
5
  import { Conversation } from "./engine/messages.js";
6
6
  import { chat, health } from "./engine/aurora.js";
7
- import { compact, fitToWindow, turnStarts, SUMMARY_INSTRUCTION, stripTrailingOrphanToolCall, pickSummaryContent } from "./engine/compaction.js";
7
+ import { compact, fitToWindow, turnStarts, SUMMARY_INSTRUCTION, stripTrailingOrphanToolCall, pickSummaryContent, renderAnchorIndex, verbatimUserTail, applyAnchorVerification } from "./engine/compaction.js";
8
8
  import { globalTokenMeter, endpointKey } from "./engine/token-meter.js";
9
9
  import { spillToolOutput } from "./tools/tool-output-spill.js"; // GW-10-COMPLETE: node-side spill sink
10
10
  import { engineRouter } from "./engine/router-adapter.js";
11
11
  import { appendFileSync, mkdirSync } from "node:fs";
12
- import { join, dirname } from "node:path";
13
- import { homedir } from "node:os";
12
+ import { dirname } from "node:path";
13
+ import { operatorPath } from "./config/home.js";
14
14
  import { fanOutProposers, labelDrafts, DEFAULT_AGGREGATOR_PROMPT } from "./engine/moa.js";
15
15
  import { AuroraRouter } from "./router/router.js";
16
16
  import { operatorAgentPersona } from "./config/operator-harness.js";
17
- import { modelRegistry, findModel, selectModel, endpointBase, DEFAULT_MODEL_ID } from "./router/models.js";
17
+ import { modelRegistry, findModel, selectModel, visibleModels, endpointBase, DEFAULT_MODEL_ID, LEAN_HARNESS_CTX } from "./router/models.js";
18
+ import { getByoToken, hasByoToken } from "./auth/byo.js";
18
19
  import { Executor } from "./tools/executor.js";
19
20
  import { toSchemas, registry, disposeShellSessionKey } from "./tools/registry.js";
20
21
  import { MemoryStore } from "./memory/index.js";
21
22
  import { McpHub, withMcp } from "./mcp/index.js";
23
+ import { deferredEnabled, deferredRequestSchemas, deferredState, withDeferred } from "./tools/deferred.js";
22
24
  import { withPermissions, PermissionPolicy } from "./permissions/index.js";
23
25
  import { Telemetry } from "./observability/index.js";
24
26
  import { runSelfImprove } from "./selfimprove/index.js";
25
27
  import { RollingSummarizer } from "./engine/rolling-summary.js";
26
28
  import { createSleepScheduler } from "./consolidation/scheduler.js";
29
+ /** The system-prompt directive for an extended-reasoning mode ("" when off). The owner watches the model's
30
+ * reasoning stream live (dim, above the answer) and re-reads it in scrollback, so /think asks the model to
31
+ * EXPOSE its thinking as readable copy — options weighed, why one won, tradeoffs, the plan — at roughly 2-3× the
32
+ * detail of a terse chain of thought. Plain /think is enough; ultrathink only adds depth on top. */
33
+ export function thinkDirective(mode) {
34
+ if (mode === "off")
35
+ return "";
36
+ const think = `\n\n## THINK (active)\nYour reasoning is shown to the owner as you work, so write it as ` +
37
+ `readable thinking, not shorthand. Before you act, lay out: what you understand the task to be; the real ` +
38
+ `options you weighed (at least two whenever a choice exists) and what each would cost; WHY you chose the one ` +
39
+ `you did, and what would change your mind; the risks and edge cases you are guarding against; and your plan as ` +
40
+ `the concrete next steps. Between tool calls, say what the last result told you and what you will do next. ` +
41
+ `Give roughly two to three times the detail of a terse chain of thought — complete sentences, concrete names ` +
42
+ `(files, functions, commands), no filler.`;
43
+ if (mode === "think")
44
+ return think;
45
+ return think + `\n\n## ULTRATHINK (active)\nThink exhaustively before answering: reason step by step ` +
46
+ `through the whole problem, surface assumptions, weigh alternatives and edge cases, and check your ` +
47
+ `own work — then give the answer. Depth over speed for this turn.`;
48
+ }
27
49
  // The `spawn_agent` tool — a thin pass-through to the shell's delegate handler. The handler owns the
28
50
  // policy (cap) and the reply text; the tool just guards against an empty task. safe:false so it's an
29
51
  // action (gated when permissions are on), never run speculatively in the safe-parallel batch.
@@ -213,10 +235,12 @@ export class Session {
213
235
  eventActor;
214
236
  sessionId;
215
237
  mcpSchemas = []; // merged in after first-turn discovery (empty until then)
216
- wantMcp;
238
+ deferred = null; // HV3-04: set when the MCP surface crosses the threshold
239
+ wantMcp; // mutable: `/mcp on` flips it for the live session (enableMcp)
217
240
  systemPrompt;
218
241
  maxTokens;
219
242
  maxTurnTokens;
243
+ maxTurnWallClockMs;
220
244
  maxRounds;
221
245
  maxRoundsHard;
222
246
  compactionThreshold;
@@ -234,14 +258,17 @@ export class Session {
234
258
  // Rolling summarizer — instant compaction (Engine doc #2). A background process continuously
235
259
  // maintains a structured session-memory/summary.md during the session. When compact() fires,
236
260
  // it loads the pre-written summary — /compact went from up to 2 minutes to instant.
237
- rollingSummarizer = new RollingSummarizer();
261
+ rollingSummarizer;
238
262
  // Sleep-time consolidation scheduler — triggers memory reorganization during idle (Engine doc #1).
239
263
  sleepScheduler = null;
240
264
  constructor(cfg = {}) {
265
+ if (cfg.thinkMode)
266
+ this.thinkMode = cfg.thinkMode;
267
+ this.rollingSummarizer = new RollingSummarizer(cfg.rollingSummaryPath ? { summaryPath: cfg.rollingSummaryPath } : {});
241
268
  // Calibration durability (SPEC §5, token-meter): learned chars/token persist beside the operator
242
269
  // state dir, so the FIRST deep session after a restart already sizes correctly instead of running
243
270
  // on the cold prior. Best-effort by construction: a no-op off node, a cold start on corrupt/missing.
244
- globalTokenMeter.setPersistence(join(homedir(), ".axe", "operator", "token-calibration.json"));
271
+ globalTokenMeter.setPersistence(operatorPath("token-calibration.json"));
245
272
  // Per-session tool registry: the base set, plus `spawn_agent` when the shell provides a delegate
246
273
  // handler (foreground only). Both the executor (dispatch) and localSchemas (what the model sees)
247
274
  // are built from the same map, so the tool is advertised iff it's runnable.
@@ -275,6 +302,7 @@ export class Session {
275
302
  this.systemPrompt = cfg.systemPrompt;
276
303
  this.maxTokens = cfg.maxTokens ?? 2048;
277
304
  this.maxTurnTokens = cfg.maxTurnTokens;
305
+ this.maxTurnWallClockMs = cfg.maxTurnWallClockMs;
278
306
  this.maxRounds = cfg.maxRounds;
279
307
  this.maxRoundsHard = cfg.maxRoundsHard;
280
308
  this.compactionThreshold = cfg.compactionThreshold;
@@ -324,16 +352,13 @@ export class Session {
324
352
  `(/plan) to let you execute.`;
325
353
  return (base ?? "") + plan;
326
354
  }
327
- /** The system prompt with the ultrathink push appended when that mode is on. /think alone just enables
328
- * the model's native reasoning (no prompt change needed); ultrathink also asks it to go deeper. */
355
+ /** The system prompt with the think directive appended when extended reasoning is on. /think enables the
356
+ * model's native reasoning AND asks it to write that reasoning as readable copy (see thinkDirective);
357
+ * ultrathink adds the exhaustive push on top. */
329
358
  sysWithThink() {
330
359
  const base = this.sys();
331
- if (this.thinkMode !== "ultrathink")
332
- return base;
333
- const push = `\n\n## ULTRATHINK (active)\nThink exhaustively before answering: reason step by step ` +
334
- `through the whole problem, surface assumptions, weigh alternatives and edge cases, and check your ` +
335
- `own work — then give the answer. Depth over speed for this turn.`;
336
- return (base ?? "") + push;
360
+ const push = thinkDirective(this.thinkMode);
361
+ return push ? (base ?? "") + push : base;
337
362
  }
338
363
  /** Compose the tool executor: local tools + MCP (composite) with the permission/audit layer on top.
339
364
  * withPermissions returns the composite UNCHANGED when the policy is inert (bypass) — zero overhead.
@@ -344,7 +369,8 @@ export class Session {
344
369
  ? new PermissionPolicy({ mode: "gated", tier: this.policy.currentTier() }) // read-only: safe tools allow, mutating ask→deny (no approve fn)
345
370
  : this.policy;
346
371
  const approve = this.planMode ? undefined : this.approve; // no approver in plan mode = hard read-only
347
- return withPermissions(withMcp(this.executor, this.hub), policy, { approve, sink: this.eventSink, actor: this.eventActor, session: this.sessionId });
372
+ const base = withPermissions(withMcp(this.executor, this.hub), policy, { approve, sink: this.eventSink, actor: this.eventActor, session: this.sessionId });
373
+ return this.deferred ? withDeferred(base, this.deferred) : base;
348
374
  }
349
375
  /** Enter/leave plan mode (/plan). Read-only research + a proposed plan until the owner approves. */
350
376
  setPlanMode(on) {
@@ -443,16 +469,32 @@ export class Session {
443
469
  // then compact() uses it as the evicted span's replacement.
444
470
  const prewritten = this.rollingSummarizer.getSummary();
445
471
  if (prewritten) {
446
- const summaryMsg = {
447
- role: "user",
448
- content: `[Compacted summary (pre-written — instant)]:\n${prewritten}`,
449
- };
450
472
  const starts = turnStarts(this.convo.all);
451
473
  const minKeep = opts.minKeepTurns ?? 4;
452
- if (starts.length > minKeep) {
474
+ // GW-27-U2 STALENESS GATE (the silent-loss fix). The pre-written summary is trustworthy ONLY
475
+ // if (a) it isn't dirty (no threshold crossing since the fire) AND (b) its watermark covers
476
+ // every turn the cut would evict — i.e. coverage >= starts.length - minKeep. Turns added
477
+ // AFTER the fire but below the rolling threshold were previously dropped with zero trace:
478
+ // quiet turns (< the 5000-token cadence) accumulate uncovered, and /compact swapped in a
479
+ // summary that predates them. Uncovered => fall through to the live path (compact() skips on
480
+ // summarize failure rather than destroying the span, and fitToWindow OFFLOADS via GW-10 spill
481
+ // — lossless in both branches).
482
+ const covered = this.rollingSummarizer.getCoveredThrough();
483
+ const trustworthy = !this.rollingSummarizer.isStale() && starts.length > minKeep && covered >= starts.length - minKeep;
484
+ if (trustworthy) {
453
485
  const cutIndex = starts[starts.length - minKeep];
486
+ const evicted = this.convo.all.slice(0, cutIndex);
487
+ // H2 (audit-engine §2): the instant path used to insert the raw pre-written blob — skipping
488
+ // the GW-31/N1 backstop the auto-favored path EXISTS to guarantee. Coverage proved it knows
489
+ // about these turns; now it also carries their anchors and the user's own words. All
490
+ // render-side and mechanical — the "instant" property is untouched (microseconds, zero calls).
491
+ const summaryMsg = {
492
+ role: "user",
493
+ content: `[Compacted summary (pre-written — instant)]:\n${prewritten}${renderAnchorIndex(evicted)}${verbatimUserTail(evicted)}`,
494
+ };
454
495
  const kept = this.convo.all.slice(cutIndex);
455
496
  this.convo.replaceAll([summaryMsg, ...kept]);
497
+ applyAnchorVerification(summaryMsg, evicted, this.convo.all);
456
498
  const before = this.requestEstimate();
457
499
  this.convo.replaceAll(fitToWindow(this.convo.all, opts));
458
500
  return Math.max(0, before - this.requestEstimate());
@@ -474,7 +516,7 @@ export class Session {
474
516
  // Start the scheduler if not already enabled
475
517
  const sleepEnabled = process.env.KODE_SLEEP_CONSOLIDATION === "1";
476
518
  if (!sleepEnabled)
477
- return { lessonsExtracted: 0, lessonsPersisted: 0, memoryDeduped: 0, error: "consolidation disabled — set KODE_SLEEP_CONSOLIDATION=1" };
519
+ return { lessonsExtracted: 0, lessonsPersisted: 0, memoryDeduped: 0, error: "consolidation disabled — enable autonomy.sleepConsolidation in settings" };
478
520
  this.sleepScheduler = createSleepScheduler({
479
521
  consolidation: { enabled: true, idleThresholdSec: 30, stepsBetweenPasses: 10, modelTier: "fast" },
480
522
  });
@@ -495,9 +537,10 @@ export class Session {
495
537
  return this.inner.currentName();
496
538
  }
497
539
  /** All model profiles the owner can pick between (/model) — built-ins plus any settings.models
498
- * overrides passed in at construction. */
540
+ * overrides passed in at construction. BYO connectors appear ONLY when their vendor key is
541
+ * connected (SPEC/providers.md §1 "Honest availability": the picker shows what can actually run). */
499
542
  modelRegistry() {
500
- return this.registry;
543
+ return visibleModels(this.registry, hasByoToken);
501
544
  }
502
545
  /** The active /model selection (id), for the status line + persistence. */
503
546
  currentModel() {
@@ -509,14 +552,17 @@ export class Session {
509
552
  * error instead of throwing, so the shell can show it inline: an unknown id, or "moa" selected
510
553
  * with no settings.moa configured. */
511
554
  setModel(id) {
512
- const { profile, error } = selectModel(this.registry, id);
555
+ const { profile, error } = selectModel(this.registry, id, hasByoToken);
513
556
  if (error || !profile)
514
557
  return { ok: false, error };
515
558
  if (profile.kind === "orchestrated" && !this.moaConfig?.proposers?.length) {
516
559
  return { ok: false, error: `MOA needs a "moa" block (proposers + aggregator) in settings.json — see MOA-DESIGN.md` };
517
560
  }
518
561
  if (profile.kind === "single" && profile.endpoint) {
519
- this.inner = new AuroraRouter([{ name: profile.id, base: endpointBase(profile.endpoint), model: profile.model ?? profile.id, ctxLimit: profile.ctx ?? this.inner.ctxLimit() }]);
562
+ // BYO connectors carry their vendor bearer (never the Operator token — see authHeaders scoping);
563
+ // selectModel already refused the id if the key is not connected, so resolution can't miss here.
564
+ const token = profile.byo ? getByoToken(profile.byo) : undefined;
565
+ this.inner = new AuroraRouter([{ name: profile.id, base: endpointBase(profile.endpoint), model: profile.model ?? profile.id, ctxLimit: profile.ctx ?? this.inner.ctxLimit(), token, transport: profile.transport }]);
520
566
  this.router = engineRouter(this.inner);
521
567
  }
522
568
  this.modelId = profile.id;
@@ -561,9 +607,24 @@ export class Session {
561
607
  ...stripTrailingOrphanToolCall(span),
562
608
  { role: "user", content: SUMMARY_INSTRUCTION },
563
609
  ];
610
+ // A small-context active model (e.g. a self-hosted 8K Venice) can't summarize its OWN overflow — the
611
+ // [system + tools + span] summarize request itself exceeds the window, so compaction frees nothing and
612
+ // the session walls ("compaction can't free enough space"). Route the summarizer to the large-context
613
+ // DEFAULT (Aurora/operator-1m, 300K) instead: it loses the live-turn's prefix-cache reuse (Aurora's
614
+ // prefix differs from the small model's), but that trade is what lets a small model compact continuously
615
+ // and run autonomously for hours. A large active model keeps the cache-safe same-endpoint path.
616
+ let sumBase = this.lastBase ?? this.inner.base;
617
+ let sumModel = this.lastModel ?? this.inner.model;
618
+ if (this.inner.ctxLimit() < LEAN_HARNESS_CTX) {
619
+ const big = findModel(this.registry, DEFAULT_MODEL_ID);
620
+ if (big?.endpoint) {
621
+ sumBase = endpointBase(big.endpoint);
622
+ sumModel = big.model ?? big.id;
623
+ }
624
+ }
564
625
  const r = await chat(messages, {
565
- base: this.lastBase ?? this.inner.base, // the endpoint the live turn actually used (failover/MOA-aware)
566
- model: this.lastModel ?? this.inner.model,
626
+ base: sumBase, // small-ctx active model → large default (Aurora) summarizes; else the live endpoint (cache-safe)
627
+ model: sumModel,
567
628
  tools: this.allSchemas(), // identical tools → the span prefix-matches the live turn's cached KV
568
629
  maxTokens: SUMMARY_MAX_TOKENS,
569
630
  temperature: 0,
@@ -597,7 +658,7 @@ export class Session {
597
658
  const stamp = new Date().toISOString().replace(/[:.]/g, "-");
598
659
  this.handoffFile = envFile && envFile.trim()
599
660
  ? envFile
600
- : join(homedir(), ".axe", "operator", "handoff", `session-${stamp}.md`);
661
+ : operatorPath("handoff", `session-${stamp}.md`);
601
662
  mkdirSync(dirname(this.handoffFile), { recursive: true });
602
663
  }
603
664
  const block = `\n## Auto-compaction @ ${new Date().toISOString()} (evicted ${evicted} msg)\n\n${summary}\n`;
@@ -617,7 +678,9 @@ export class Session {
617
678
  const summaryText = await this.summarize(this.convo.all);
618
679
  if (summaryText) {
619
680
  this.rollingSummarizer.setSummary(summaryText);
620
- this.rollingSummarizer.markSummaryFired();
681
+ // GW-27-U2: record coverage — the summary spans the conversation AS OF NOW, so /compact
682
+ // may trust it only while the eviction cut stays inside this watermark.
683
+ this.rollingSummarizer.markSummaryFired(turnStarts(this.convo.all).length);
621
684
  }
622
685
  }
623
686
  catch { /* best-effort — rolling summary never blocks a turn */ }
@@ -637,21 +700,40 @@ export class Session {
637
700
  this.recallBlock = "";
638
701
  }
639
702
  }
640
- if (this.wantMcp) {
641
- try {
642
- if (!this.hub)
643
- this.hub = await McpHub.fromConfig();
644
- if (this.hub)
645
- this.hub.spillSink = spillToolOutput; // GW-10-COMPLETE: MCP offload
646
- await this.hub.discover();
647
- this.tools = this.buildTools(); // rebind so dispatch sees the discovered tools
648
- this.mcpSchemas = this.hub.schemas();
649
- }
650
- catch { /* gateway unreachable — stay local-only */ }
703
+ if (this.wantMcp)
704
+ await this.discoverMcp();
705
+ }
706
+ /** Build the MCP hub (from the owned-MCP registry unless one was injected) and discover its tools, then rebind
707
+ * dispatch + schemas. Best-effort — an unreachable gateway leaves the session local-only. */
708
+ async discoverMcp() {
709
+ try {
710
+ if (!this.hub)
711
+ this.hub = await McpHub.fromConfig();
712
+ if (!this.hub)
713
+ return;
714
+ this.hub.spillSink = spillToolOutput; // GW-10-COMPLETE: MCP offload
715
+ await this.hub.discover();
716
+ this.tools = this.buildTools(); // rebind so dispatch sees the discovered tools
717
+ this.mcpSchemas = this.hub.schemas();
718
+ // HV3-04: when the MCP surface is fat, its schemas stop riding every request — they move
719
+ // behind tool_search/describe/call meta-tools, loaded on demand.
720
+ this.deferred = deferredEnabled(this.mcpSchemas.length, globalThis.process?.env) ? deferredState(this.mcpSchemas) : null;
721
+ this.tools = this.buildTools(); // rebind again so the deferred layer wraps the permission stack
651
722
  }
723
+ catch { /* gateway unreachable — stay local-only */ }
724
+ }
725
+ /** `/mcp on`: switch the fleet MCP layer on for THIS session without a restart (the first-turn path in
726
+ * maybeRecall does the same discovery). Returns how many tools are now available (0 if the gateway is down). */
727
+ async enableMcp() {
728
+ this.wantMcp = true;
729
+ await this.discoverMcp();
730
+ return this.mcpToolCount();
652
731
  }
653
- /** Local registry schemas plus any fleet MCP tool schemas discovered this session. */
732
+ /** Local registry schemas plus any fleet MCP tool schemas discovered this session.
733
+ * Under HV3-04 deferral: locals + only the MCP tools described this session + the meta trio. */
654
734
  allSchemas() {
735
+ if (this.deferred)
736
+ return deferredRequestSchemas(this.localSchemas, this.deferred);
655
737
  return this.mcpSchemas.length ? [...this.localSchemas, ...this.mcpSchemas] : this.localSchemas;
656
738
  }
657
739
  /** How many fleet MCP tools were discovered this session (0 until first turn / if MCP is off). */
@@ -767,6 +849,7 @@ export class Session {
767
849
  background: this.background, // endpoint gate: a sub-agent's rounds yield the shared slot to the main turn
768
850
  maxTokens: this.maxTokens,
769
851
  maxTurnTokens: this.maxTurnTokens, // opt-in per-turn cost ceiling (total tokens); undefined → no cap
852
+ maxTurnWallClockMs: this.maxTurnWallClockMs, // opt-in per-turn TIME ceiling; the brake on hour-long crawling turns
770
853
  maxRounds: this.maxRounds, // soft round budget from settings.maxRounds (undefined → runTurn default)
771
854
  maxRoundsHard: this.maxRoundsHard, // absolute ceiling; undefined → runTurn default 400, tighter for bg sub-agents
772
855
  compactionThreshold: this.compactionThreshold, // settings.compaction.threshold; undefined → runTurn default 0.85
@@ -788,6 +871,10 @@ export class Session {
788
871
  // reminder round when a turn changed files but ran no passing check. Every surface routes through
789
872
  // here, so the gate is uniform across CLI, web/RC, headless, and loop turns.
790
873
  verifyGate: { enabled: process.env.KODE_VERIFY_GATE !== "0", maxNudges: Number(process.env.KODE_VERIFY_GATE_MAX) || 1 },
874
+ // Turn-continuation: a text-only reply that ends on an unperformed action announcement ("Let me implement
875
+ // these now.") gets one nudge to actually do it (≤2/turn) instead of finalizing. Off in plan mode — there
876
+ // the text IS the deliverable ("I'll implement this once you approve") — and via KODE_TURN_CONTINUATION=0.
877
+ turnContinuation: { enabled: process.env.KODE_TURN_CONTINUATION !== "0" && !this.planMode },
791
878
  });
792
879
  this.telemetry.record({ type: "turn", rounds: res.rounds, toolCalls: res.toolCalls, interrupted: false, durationMs: Math.round(performance.now() - _t0), ctxPct: this.ctxPct(), stopReason: res.stopReason });
793
880
  this.sessionTokensTotal += (res.tokens ?? 0) + (res.promptTokens ?? 0); // cumulative session spend
@@ -0,0 +1,167 @@
1
+ // HV3-07 — official optional-skills catalogue: browse/install/remove against the gated catalog that
2
+ // ships in the repo (operator-home/skills-catalogue/), activating a skill = copying its tree into
3
+ // $KODE_HOME/skills/<category>/<name>/ where the operator-home-v2 phase-3 local-skills index picks it
4
+ // up immediately (skill_list/skill_fetch unchanged). Nothing in the catalogue is ever injected on its
5
+ // own — that gating is the whole point (Hermes ships these as "not activated by default").
6
+ // Node builtins stay behind lazy variable-specifier imports (purity contract, session-rewind idiom).
7
+ import { operatorPath } from "../config/home.js";
8
+ async function nodeImport(id) {
9
+ const g = globalThis;
10
+ try {
11
+ const m = g.process?.getBuiltinModule?.(id);
12
+ if (m)
13
+ return m;
14
+ }
15
+ catch { /* dynamic */ }
16
+ const spec = id;
17
+ return import(spec);
18
+ }
19
+ /** Catalogue root; overridable for tests via env, else repo-relative to this module. */
20
+ export function catalogueDir() {
21
+ const env = globalThis.process?.env;
22
+ if (env?.KODE_CATALOGUE_DIR)
23
+ return env.KODE_CATALOGUE_DIR;
24
+ // src/skills/catalogue.ts and dist/skills/catalogue.js are both two levels below kode-tsi/.
25
+ // import.meta is absent in the neutral iife bundle (schema-side reach only, run() never fires
26
+ // there) — try/catch degrades to "" and existsSync() reports "no catalogue" instead of throwing.
27
+ try {
28
+ return new URL("../../operator-home/skills-catalogue", import.meta.url).pathname;
29
+ }
30
+ catch {
31
+ return "";
32
+ }
33
+ }
34
+ function parseFrontmatter(text) {
35
+ const m = /^---\n([\s\S]*?)\n---/.exec(text);
36
+ if (!m)
37
+ return {};
38
+ const out = {};
39
+ for (const line of m[1].split("\n")) {
40
+ const kv = /^(name|description)\s*:\s*(.+)$/.exec(line);
41
+ if (kv)
42
+ out[kv[1]] = kv[2].replace(/^["']|["']$/g, "").trim();
43
+ }
44
+ return out;
45
+ }
46
+ /** Walk the catalogue at ANY depth: <cat>/<skill>, <cat>/<group>/<skill>, <cat>/SKILL.md all
47
+ * resolve to one entry each — the count browse reports always equals the SKILL.md count on disk
48
+ * (the live e2e asserts exactly this; the fixed-depth version shipped blind to mlops subgroups). */
49
+ export async function listCatalogue() {
50
+ const fs = await nodeImport("node:fs");
51
+ const path = await nodeImport("node:path");
52
+ const root = catalogueDir();
53
+ if (!root || !fs.existsSync(root))
54
+ return [];
55
+ const out = [];
56
+ const found = [];
57
+ const walk = (dir, rel) => {
58
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
59
+ if (!e.isDirectory() || e.name.startsWith("."))
60
+ continue;
61
+ const sub = path.join(dir, e.name);
62
+ const rsub = rel ? `${rel}/${e.name}` : e.name;
63
+ if (fs.existsSync(path.join(sub, "SKILL.md")))
64
+ found.push({ dir: sub, rel: rsub });
65
+ else
66
+ walk(sub, rsub);
67
+ }
68
+ };
69
+ walk(root, "");
70
+ for (const { dir, rel } of found) {
71
+ const fm = parseFrontmatter(fs.readFileSync(path.join(dir, "SKILL.md"), "utf8"));
72
+ let files = 0;
73
+ try {
74
+ const count = (d) => { for (const e of fs.readdirSync(d, { withFileTypes: true })) {
75
+ if (e.isDirectory())
76
+ count(path.join(d, e.name));
77
+ else
78
+ files++;
79
+ } };
80
+ count(dir);
81
+ }
82
+ catch {
83
+ files = 1;
84
+ }
85
+ out.push({
86
+ category: rel.split("/")[0] ?? rel,
87
+ name: fm.name?.trim() ? fm.name.trim() : path.basename(dir),
88
+ description: (fm.description ?? "").slice(0, 140),
89
+ path: rel,
90
+ files,
91
+ });
92
+ }
93
+ return out.sort((a, b) => a.category.localeCompare(b.category) || a.name.localeCompare(b.name));
94
+ }
95
+ /** Install = copy the tree into $KODE_HOME/skills/<path> + a source marker; refuses overwrite. */
96
+ export async function installSkill(name) {
97
+ const fs = await nodeImport("node:fs");
98
+ const path = await nodeImport("node:path");
99
+ const entry = (await listCatalogue()).find((e) => e.name === name);
100
+ if (!entry)
101
+ return `skill_catalog: '${name}' not in the catalogue (browse first)`;
102
+ const dest = operatorPath("skills", entry.category, name);
103
+ if (fs.existsSync(dest))
104
+ return `skill_catalog: already installed at skills/${entry.category}/${name} (remove first to reinstall)`;
105
+ const src = path.join(catalogueDir(), entry.path);
106
+ try {
107
+ fs.cpSync(src, dest, { recursive: true });
108
+ fs.writeFileSync(path.join(dest, ".from-catalogue"), `source: operator-home/skills-catalogue/${entry.path}\ninstalled: ${new Date().toISOString()}\n`);
109
+ }
110
+ catch (e) {
111
+ return `skill_catalog install failed: ${e.message}`;
112
+ }
113
+ return `installed '${name}' (${entry.category}, ${entry.files} files) -> skills/${entry.path} — live in skill_list/skill_fetch next session; ${entry.description.slice(0, 80)}`;
114
+ }
115
+ /** Remove = delete ONLY catalogue-marked trees (never a hand-written skill dir). */
116
+ export async function removeSkill(name) {
117
+ const fs = await nodeImport("node:fs");
118
+ const path = await nodeImport("node:path");
119
+ const home = operatorPath("skills");
120
+ let hits = [];
121
+ try {
122
+ for (const cat of fs.readdirSync(home, { withFileTypes: true })) {
123
+ if (!cat.isDirectory())
124
+ continue;
125
+ const cand = path.join(home, cat.name, name);
126
+ if (fs.existsSync(path.join(cand, ".from-catalogue")))
127
+ hits.push(cand);
128
+ }
129
+ }
130
+ catch { /* no skills dir */ }
131
+ if (!hits.length)
132
+ return `skill_catalog: no catalogue-installed '${name}' found (hand-installed skills are never removed here)`;
133
+ try {
134
+ for (const h of hits)
135
+ fs.rmSync(h, { recursive: true, force: true });
136
+ }
137
+ catch (e) {
138
+ return `skill_catalog remove failed: ${e.message}`;
139
+ }
140
+ return `removed ${hits.length} installed copy(ies) of '${name}' (catalogue source untouched)`;
141
+ }
142
+ /** run() for the `skill_catalog` registry tool. */
143
+ export async function runSkillCatalog(args) {
144
+ const action = String(args.action ?? "browse");
145
+ try {
146
+ if (action === "browse") {
147
+ const entries = await listCatalogue();
148
+ if (!entries.length)
149
+ return "skill_catalog: no catalogue present (operator-home/skills-catalogue missing)";
150
+ const q = String(args.query ?? "").toLowerCase();
151
+ const matched = entries.filter((e) => !q || e.name.toLowerCase().includes(q) || e.category.toLowerCase().includes(q) || e.description.toLowerCase().includes(q));
152
+ const shown = matched.slice(0, 120);
153
+ const cats = new Set(matched.map((e) => e.category));
154
+ return `${matched.length} of ${entries.length} catalogue entries (${cats.size} categories)\n` +
155
+ shown.map((e) => `${e.name} [${e.category}] — ${e.description}`).join("\n") +
156
+ (matched.length > shown.length ? `\n… +${matched.length - shown.length} more — refine with query` : "");
157
+ }
158
+ if (action === "install")
159
+ return await installSkill(String(args.name ?? ""));
160
+ if (action === "remove")
161
+ return await removeSkill(String(args.name ?? ""));
162
+ return `skill_catalog: unknown action '${action}' (browse|install|remove)`;
163
+ }
164
+ catch (e) {
165
+ return `skill_catalog error: ${e.message}`;
166
+ }
167
+ }