@0perator/operator 0.1.284 → 0.1.313

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 (99) hide show
  1. package/README.md +24 -2
  2. package/dist/acp/agent.js +3 -2
  3. package/dist/acp/config-options.js +15 -1
  4. package/dist/acp/tool-map.js +2 -1
  5. package/dist/auth/commands.js +69 -13
  6. package/dist/autonomy/agent-cli.js +304 -0
  7. package/dist/autonomy/cloud-agent.js +439 -0
  8. package/dist/autonomy/cron-lifecycle.js +78 -0
  9. package/dist/autonomy/cron-lock.js +121 -0
  10. package/dist/autonomy/cron.js +216 -43
  11. package/dist/autonomy/delegate.js +5 -1
  12. package/dist/autonomy/incidents.js +135 -0
  13. package/dist/autonomy/session-factory.js +25 -16
  14. package/dist/background/index.js +40 -0
  15. package/dist/bus/inbox.js +20 -0
  16. package/dist/classifier/config.js +47 -0
  17. package/dist/classifier/modes.js +41 -0
  18. package/dist/classifier/types.js +1 -0
  19. package/dist/cli.js +529 -53
  20. package/dist/config/features.js +69 -0
  21. package/dist/config/persona.js +118 -99
  22. package/dist/config/scaffold.js +15 -0
  23. package/dist/config/settings.js +96 -6
  24. package/dist/consolidation/sleep.js +73 -11
  25. package/dist/engine/agent.js +275 -18
  26. package/dist/engine/anthropic-chat.js +343 -0
  27. package/dist/engine/aurora.js +101 -13
  28. package/dist/engine/batch-scheduler.js +41 -9
  29. package/dist/engine/classifier.js +85 -0
  30. package/dist/engine/compaction.js +24 -5
  31. package/dist/engine/fast-start.js +25 -0
  32. package/dist/engine/loop-guard.js +448 -0
  33. package/dist/engine/moa.js +5 -1
  34. package/dist/engine/net-error.js +24 -0
  35. package/dist/engine/repetition-guard.js +180 -0
  36. package/dist/engine/selfheal.js +8 -0
  37. package/dist/engine/toolcalls.js +51 -1
  38. package/dist/engine/verify-gate.js +2 -0
  39. package/dist/flywheel/processor.js +78 -31
  40. package/dist/flywheel/srft.js +13 -0
  41. package/dist/hooks/index.js +196 -0
  42. package/dist/mcp/config.js +21 -1
  43. package/dist/memory/index.js +0 -0
  44. package/dist/memory/providers.js +210 -0
  45. package/dist/memory/session-catalog.js +422 -0
  46. package/dist/memory/session-providers.js +121 -0
  47. package/dist/memory/session-sources.js +335 -0
  48. package/dist/memory/skylark.js +131 -0
  49. package/dist/models/bench.js +103 -0
  50. package/dist/models/registry.js +144 -0
  51. package/dist/models/switch.js +69 -0
  52. package/dist/observability/blackbox.js +37 -0
  53. package/dist/permissions/policy.js +31 -6
  54. package/dist/router/discovery.js +127 -0
  55. package/dist/router/models.js +117 -24
  56. package/dist/router/portal.js +100 -0
  57. package/dist/router/router.js +1 -1
  58. package/dist/services/preflight.js +55 -7
  59. package/dist/session.js +316 -46
  60. package/dist/tools/chauffeur.js +12 -0
  61. package/dist/tools/executor.js +19 -9
  62. package/dist/tools/find-files.js +483 -0
  63. package/dist/tools/git-pr.js +94 -0
  64. package/dist/tools/incident-tools.js +82 -0
  65. package/dist/tools/memory.js +12 -2
  66. package/dist/tools/registry.js +281 -85
  67. package/dist/tools/semantic-compress.js +124 -0
  68. package/dist/tools/shell-context.js +1 -0
  69. package/dist/tools/shell-jobs.js +160 -0
  70. package/dist/tools/shell-session.js +170 -4
  71. package/dist/tools/wave-tools.js +609 -0
  72. package/dist/tools/wave2-tools.js +411 -0
  73. package/dist/ui/App.js +15 -4
  74. package/dist/ui/BgPanel.js +30 -6
  75. package/dist/ui/Composer.js +11 -1
  76. package/dist/ui/QuestionPrompt.js +31 -11
  77. package/dist/ui/SessionPicker.js +86 -0
  78. package/dist/ui/StatusRule.js +5 -5
  79. package/dist/ui/ToolStep.js +2 -1
  80. package/dist/ui/Transcript.js +17 -1
  81. package/dist/ui/index.js +1 -1
  82. package/dist/ui/liveTools.js +21 -3
  83. package/dist/ui/slashCommands.js +2 -0
  84. package/dist/util/screenshots.js +74 -8
  85. package/dist/util/slash.js +2 -2
  86. package/package.json +8 -2
  87. package/dist/engine/cli.js +0 -1171
  88. package/dist/router/models.js.bak +0 -78
  89. package/dist/router/models.js.bak-1791259923 +0 -78
  90. package/dist/router/models.js.bak-pre-gateway +0 -78
  91. package/dist/router/models.js.bak-pre-patch2 +0 -78
  92. package/dist/router/models.js.bak2 +0 -78
  93. package/dist/services/model-autodetect.js +0 -240
  94. package/dist/tools/native-redirect.js +0 -140
  95. package/dist/tools/power-tools.js +0 -627
  96. package/dist/tools/registry.js.bak-1791259948 +0 -1914
  97. package/dist/tools/registry.js.bak-pre-plugins +0 -1914
  98. package/dist/ui/BusTray.js +0 -70
  99. package/dist/ui/resize.js +0 -160
@@ -0,0 +1,103 @@
1
+ import { ModelRegistry } from "./registry.js";
2
+ import { switchModel } from "./switch.js";
3
+ import { operatorPath } from "../config/home.js";
4
+ const nodeImport = (m) => import(m);
5
+ const STANDARD_TASKS = [
6
+ { id: "code-fizzbuzz", name: "FizzBuzz", category: "code-edit", prompt: "Write a JavaScript function fizzbuzz(n) returning an array from 1..n: multiples of 3='Fizz', 5='Buzz', both='FizzBuzz', else string number. ONLY the function.", expectedPattern: /function\s+fizzbuzz|const\s+fizzbuzz/, maxTokens: 512, timeoutMs: 30000 },
7
+ { id: "code-sort", name: "Merge sort", category: "code-edit", prompt: "Write TypeScript mergeSort(arr: number[]): number[] implementing merge sort. ONLY the function.", expectedPattern: /function\s+mergeSort|const\s+mergeSort/, maxTokens: 1024, timeoutMs: 45000 },
8
+ { id: "reasoning-math", name: "Math reasoning", category: "reasoning", prompt: "Apples cost $2, oranges $3. I buy 5 apples and some oranges for exactly $25. How many oranges? Step by step, final answer as single number on last line.", expectedPattern: /5/, maxTokens: 512, timeoutMs: 30000 },
9
+ { id: "tool-json", name: "JSON output", category: "tool-use", prompt: "Generate valid JSON: {name: string, age: number, skills: string[]} for Alice, 35, knows TypeScript/Rust/Python. ONLY JSON.", expectedPattern: /"name"\s*:\s*"Alice"/, maxTokens: 256, timeoutMs: 20000 },
10
+ { id: "multi-step-plan", name: "Deploy plan", category: "multi-step", prompt: "List 10 numbered shell commands to deploy a Node.js app: SSH, install Node, clone, deps, build, systemd, enable, start, check. ONLY commands.", expectedPattern: /ssh|systemctl|npm|git clone/, maxTokens: 1024, timeoutMs: 45000 },
11
+ { id: "memory-extract", name: "Fact extraction", category: "memory", prompt: "Extract 3 key facts as JSON string array from: 'Rust released 2015 by Mozilla. Memory safety without GC. LLVM backend. Most loved on StackOverflow.'", expectedPattern: /\[.*".*Rust.*".*\]/s, maxTokens: 512, timeoutMs: 30000 },
12
+ { id: "file-grep", name: "Grep command", category: "file-search", prompt: "What ripgrep command finds all TypeScript files exporting a default class? Give ONLY the rg command.", expectedPattern: /rg|grep/, maxTokens: 256, timeoutMs: 20000 },
13
+ { id: "code-debug", name: "Bug finding", category: "code-edit", prompt: "Find the bug: function sum(arr) { let t=0; for(let i=0;i<=arr.length;i++) t+=arr[i]; return t; } One sentence.", expectedPattern: /<=|off.by.one|undefined|NaN/i, maxTokens: 256, timeoutMs: 20000 },
14
+ ];
15
+ export class ModelBench {
16
+ registry;
17
+ baseUrl;
18
+ reportDir;
19
+ constructor(opts) {
20
+ this.registry = new ModelRegistry(opts?.homeDir);
21
+ this.baseUrl = opts?.baseUrl ?? "http://localhost:8097/v1";
22
+ this.reportDir = opts?.reportDir ?? (opts?.homeDir ? `${opts.homeDir}/bench` : operatorPath("bench"));
23
+ }
24
+ async complete(prompt, maxTokens, timeoutMs) {
25
+ const start = Date.now();
26
+ const controller = new AbortController();
27
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
28
+ try {
29
+ const resp = await fetch(this.baseUrl + "/chat/completions", {
30
+ method: "POST",
31
+ headers: { "Content-Type": "application/json" },
32
+ body: JSON.stringify({ model: "default", messages: [{ role: "user", content: prompt }], max_tokens: maxTokens, temperature: 0 }),
33
+ signal: controller.signal,
34
+ });
35
+ clearTimeout(timer);
36
+ if (!resp.ok)
37
+ throw new Error("API " + resp.status);
38
+ const data = await resp.json();
39
+ const text = data.choices?.[0]?.message?.content ?? "";
40
+ const tokens = data.usage?.completion_tokens ?? text.split(/\s+/).length;
41
+ return { text, tokens, latencyMs: Date.now() - start };
42
+ }
43
+ catch (e) {
44
+ clearTimeout(timer);
45
+ throw e;
46
+ }
47
+ }
48
+ async runTask(task, model) {
49
+ try {
50
+ const { text, tokens, latencyMs } = await this.complete(task.prompt, task.maxTokens, task.timeoutMs);
51
+ const matched = task.expectedPattern ? task.expectedPattern.test(text) : true;
52
+ return { taskId: task.id, model, success: true, latencyMs, tokensGenerated: tokens, tokensPerSecond: tokens / (latencyMs / 1000), matchedExpected: matched, raw: text.slice(0, 500) };
53
+ }
54
+ catch (e) {
55
+ return { taskId: task.id, model, success: false, latencyMs: 0, tokensGenerated: 0, tokensPerSecond: 0, matchedExpected: false, error: e?.message ?? String(e) };
56
+ }
57
+ }
58
+ async runSuite(model, tasks) {
59
+ const suite = tasks ?? STANDARD_TASKS;
60
+ const results = [];
61
+ for (const task of suite)
62
+ results.push(await this.runTask(task, model));
63
+ const passed = results.filter(r => r.success && r.matchedExpected);
64
+ const successful = results.filter(r => r.success);
65
+ const avgLat = successful.length ? successful.reduce((a, r) => a + r.latencyMs, 0) / successful.length : 0;
66
+ const avgTps = successful.length ? successful.reduce((a, r) => a + r.tokensPerSecond, 0) / successful.length : 0;
67
+ return {
68
+ model, provider: this.baseUrl, timestamp: new Date().toISOString(), tasks: results,
69
+ summary: { totalTasks: suite.length, passed: passed.length, failed: suite.length - passed.length, avgLatencyMs: Math.round(avgLat), avgTokensPerSecond: Math.round(avgTps * 10) / 10, successRate: Math.round((passed.length / suite.length) * 1000) / 10, score: Math.round((passed.length / suite.length) * 100) },
70
+ };
71
+ }
72
+ async saveReport(report) {
73
+ const { writeFileSync, mkdirSync } = await nodeImport("node:fs");
74
+ mkdirSync(this.reportDir, { recursive: true });
75
+ const slug = report.model.replace(/[^a-zA-Z0-9_-]/g, "_");
76
+ const ts = report.timestamp.replace(/[:.]/g, "-").slice(0, 19);
77
+ const path = this.reportDir + "/" + slug + "_" + ts + ".json";
78
+ writeFileSync(path, JSON.stringify(report, null, 2), { mode: 0o600 });
79
+ return path;
80
+ }
81
+ async compareModels(reports) {
82
+ const sorted = [...reports].sort((a, b) => b.summary.score - a.summary.score);
83
+ const lines = ["# Model Comparison", "", "| Rank | Model | Score | Pass | Fail | Avg Latency | Avg TPS |", "|------|-------|-------|------|------|-------------|---------|"];
84
+ sorted.forEach((r, i) => lines.push("| " + (i + 1) + " | " + r.model + " | " + r.summary.score + "/100 | " + r.summary.passed + " | " + r.summary.failed + " | " + r.summary.avgLatencyMs + "ms | " + r.summary.avgTokensPerSecond + " |"));
85
+ return lines.join("\n");
86
+ }
87
+ async runRotation(models, opts) {
88
+ const reports = [];
89
+ for (const model of models) {
90
+ const sw = await switchModel(model.id, model, { ...opts, restartServer: true });
91
+ if (sw.error) {
92
+ reports.push({ model: model.id, provider: model.provider, timestamp: new Date().toISOString(), tasks: [], summary: { totalTasks: 0, passed: 0, failed: 0, avgLatencyMs: 0, avgTokensPerSecond: 0, successRate: 0, score: 0 } });
93
+ continue;
94
+ }
95
+ this.baseUrl = "http://localhost:" + model.port + "/v1";
96
+ const report = await this.runSuite(model.id, opts?.tasks);
97
+ await this.saveReport(report);
98
+ reports.push(report);
99
+ }
100
+ return reports;
101
+ }
102
+ }
103
+ export { STANDARD_TASKS };
@@ -0,0 +1,144 @@
1
+ import { get_operator_home } from "../config/home.js";
2
+ const nodeImport = (m) => import(m);
3
+ const MODELS_DEV_URL = "https://models.dev/api.json";
4
+ const CACHE_TTL = 4 * 3600_000;
5
+ export class ModelRegistry {
6
+ cacheFile;
7
+ localFile;
8
+ cache = null;
9
+ cacheTime = 0;
10
+ constructor(homeDir) {
11
+ const home = homeDir ?? get_operator_home();
12
+ this.cacheFile = `${home}/models_dev_cache.json`;
13
+ this.localFile = `${home}/local_models.json`;
14
+ }
15
+ async fetchModelsDevRegistry() {
16
+ if (this.cache && Date.now() - this.cacheTime < CACHE_TTL)
17
+ return this.cache;
18
+ try {
19
+ const { readFileSync, existsSync } = await nodeImport("node:fs");
20
+ if (existsSync(this.cacheFile)) {
21
+ const raw = readFileSync(this.cacheFile, "utf8");
22
+ const parsed = JSON.parse(raw);
23
+ if (parsed._fetchedAt && Date.now() - parsed._fetchedAt < CACHE_TTL) {
24
+ this.cache = parsed;
25
+ this.cacheTime = parsed._fetchedAt;
26
+ return parsed;
27
+ }
28
+ }
29
+ }
30
+ catch { }
31
+ try {
32
+ const resp = await fetch(MODELS_DEV_URL);
33
+ if (!resp.ok)
34
+ throw new Error(`models.dev ${resp.status}`);
35
+ const data = await resp.json();
36
+ data._fetchedAt = Date.now();
37
+ this.cache = data;
38
+ this.cacheTime = Date.now();
39
+ const { writeFileSync, mkdirSync } = await nodeImport("node:fs");
40
+ const { dirname } = await nodeImport("node:path");
41
+ mkdirSync(dirname(this.cacheFile), { recursive: true });
42
+ writeFileSync(this.cacheFile, JSON.stringify(data), "utf8");
43
+ return data;
44
+ }
45
+ catch {
46
+ return this.cache ?? {};
47
+ }
48
+ }
49
+ async getModelInfo(modelId) {
50
+ const reg = await this.fetchModelsDevRegistry();
51
+ const providers = reg.providers ?? reg.data ?? {};
52
+ for (const [pid, prov] of Object.entries(providers)) {
53
+ const models = prov?.models ?? {};
54
+ for (const [mid, info] of Object.entries(models)) {
55
+ if (mid === modelId || info?.name === modelId) {
56
+ return {
57
+ id: mid, name: info.name ?? mid, family: info.family ?? "",
58
+ providerId: pid, reasoning: !!info.reasoning, toolCall: !!info.tool_call,
59
+ vision: !!info.attachment || (info.input_modalities ?? []).includes("image"),
60
+ structuredOutput: !!info.structured_output, openWeights: !!info.open_weights,
61
+ contextWindow: info.context_window ?? 0, maxOutput: info.max_output ?? 0,
62
+ costInput: info.cost_input ?? 0, costOutput: info.cost_output ?? 0,
63
+ knowledgeCutoff: info.knowledge_cutoff ?? "", releaseDate: info.release_date ?? "",
64
+ status: info.status ?? "",
65
+ };
66
+ }
67
+ }
68
+ }
69
+ return null;
70
+ }
71
+ async listLocalModels() {
72
+ try {
73
+ const { readFileSync, existsSync } = await nodeImport("node:fs");
74
+ if (!existsSync(this.localFile))
75
+ return [];
76
+ return JSON.parse(readFileSync(this.localFile, "utf8"));
77
+ }
78
+ catch {
79
+ return [];
80
+ }
81
+ }
82
+ async addLocalModel(model) {
83
+ const models = await this.listLocalModels();
84
+ const idx = models.findIndex(m => m.id === model.id);
85
+ if (idx >= 0)
86
+ models[idx] = model;
87
+ else
88
+ models.push(model);
89
+ const { writeFileSync, mkdirSync } = await nodeImport("node:fs");
90
+ const { dirname } = await nodeImport("node:path");
91
+ mkdirSync(dirname(this.localFile), { recursive: true });
92
+ writeFileSync(this.localFile, JSON.stringify(models, null, 2), "utf8");
93
+ }
94
+ async removeLocalModel(id) {
95
+ const models = await this.listLocalModels();
96
+ const filtered = models.filter(m => m.id !== id);
97
+ if (filtered.length === models.length)
98
+ return false;
99
+ const { writeFileSync } = await nodeImport("node:fs");
100
+ writeFileSync(this.localFile, JSON.stringify(filtered, null, 2), "utf8");
101
+ return true;
102
+ }
103
+ async discoverOllamaModels(host = "localhost", port = 11434) {
104
+ try {
105
+ const resp = await fetch(`http://${host}:${port}/api/tags`);
106
+ if (!resp.ok)
107
+ return [];
108
+ const data = await resp.json();
109
+ return (data.models ?? []).map((m) => ({
110
+ id: m.name ?? m.model, path: "", quant: m.details?.quantization_level ?? "",
111
+ paramCount: m.details?.parameter_size ?? "", contextWindow: 0,
112
+ provider: "ollama", port, added: m.modified_at ?? new Date().toISOString(),
113
+ capabilities: {
114
+ supportsTools: true, supportsVision: (m.details?.families ?? []).includes("clip"),
115
+ supportsReasoning: false, contextWindow: 0, maxOutputTokens: 0,
116
+ modelFamily: m.details?.family ?? "",
117
+ },
118
+ }));
119
+ }
120
+ catch {
121
+ return [];
122
+ }
123
+ }
124
+ async discoverLlamaServerModels(port = 8097) {
125
+ try {
126
+ const resp = await fetch(`http://localhost:${port}/v1/models`);
127
+ if (!resp.ok)
128
+ return [];
129
+ const data = await resp.json();
130
+ return (data.data ?? []).map((m) => ({
131
+ id: m.id ?? m.model, path: m.id ?? "", quant: "unknown",
132
+ paramCount: "", contextWindow: 0,
133
+ provider: "llama-server", port, added: new Date().toISOString(),
134
+ capabilities: {
135
+ supportsTools: true, supportsVision: false, supportsReasoning: false,
136
+ contextWindow: 0, maxOutputTokens: 0, modelFamily: "",
137
+ },
138
+ }));
139
+ }
140
+ catch {
141
+ return [];
142
+ }
143
+ }
144
+ }
@@ -0,0 +1,69 @@
1
+ const nodeImport = (m) => import(m);
2
+ const DEFAULT_CONFIG_PATH = () => process.env.KODE_CONFIG ?? `${process.env.HOME ?? ""}/.0perator/config.yaml`;
3
+ export async function switchModel(modelId, model, opts = {}) {
4
+ const configPath = opts.configPath ?? DEFAULT_CONFIG_PATH();
5
+ const { readFileSync, writeFileSync } = await nodeImport("node:fs");
6
+ let raw;
7
+ try {
8
+ raw = readFileSync(configPath, "utf8");
9
+ }
10
+ catch {
11
+ raw = "";
12
+ }
13
+ const prevMatch = raw.match(/default:\s*(.+)/);
14
+ const previous = prevMatch?.[1]?.trim() ?? "unknown";
15
+ const updated = raw
16
+ .replace(/default:\s*.+/, `default: ${modelId}`)
17
+ .replace(/base_url:\s*.+/, `base_url: http://localhost:${model.port}/v1`);
18
+ writeFileSync(configPath, updated, "utf8");
19
+ let restarted = false;
20
+ if (opts.restartServer && model.provider === "llama-server" && model.path) {
21
+ try {
22
+ const { execSync } = await nodeImport("node:child_process");
23
+ execSync("pkill -f llama-server || true", { timeout: 5000 });
24
+ await new Promise(r => setTimeout(r, 1000));
25
+ const bin = opts.llamaServerBin ?? "/opt/homebrew/bin/llama-server";
26
+ const args = [
27
+ "--model", model.path, "--host", "0.0.0.0", "--port", String(model.port),
28
+ "--ctx-size", String(model.capabilities.contextWindow || 32768),
29
+ "--n-gpu-layers", "999", "--flash-attn", "on", "--jinja",
30
+ "--parallel", "2", "--cont-batching",
31
+ ...(opts.serverArgs ?? []),
32
+ ];
33
+ execSync(`nohup ${bin} ${args.join(" ")} > /tmp/llama-bench.log 2>&1 &`, { timeout: 5000 });
34
+ restarted = true;
35
+ let healthy = false;
36
+ for (let i = 0; i < 30; i++) {
37
+ await new Promise(r => setTimeout(r, 2000));
38
+ try {
39
+ const resp = await fetch(`http://localhost:${model.port}/health`);
40
+ if (resp.ok) {
41
+ healthy = true;
42
+ break;
43
+ }
44
+ }
45
+ catch { }
46
+ }
47
+ if (!healthy)
48
+ return { previous, current: modelId, provider: model.provider, port: model.port, restarted, error: "server did not become healthy within 60s" };
49
+ }
50
+ catch (e) {
51
+ return { previous, current: modelId, provider: model.provider, port: model.port, restarted: false, error: e?.message ?? String(e) };
52
+ }
53
+ }
54
+ return { previous, current: modelId, provider: model.provider, port: model.port, restarted };
55
+ }
56
+ export async function currentModel(configPath) {
57
+ const path = configPath ?? DEFAULT_CONFIG_PATH();
58
+ try {
59
+ const { readFileSync } = await nodeImport("node:fs");
60
+ const raw = readFileSync(path, "utf8");
61
+ const model = raw.match(/default:\s*(.+)/)?.[1]?.trim() ?? "unknown";
62
+ const baseUrl = raw.match(/base_url:\s*(.+)/)?.[1]?.trim() ?? "";
63
+ const provider = raw.match(/provider:\s*(.+)/)?.[1]?.trim() ?? "unknown";
64
+ return { model, baseUrl, provider };
65
+ }
66
+ catch {
67
+ return { model: "unknown", baseUrl: "", provider: "unknown" };
68
+ }
69
+ }
@@ -0,0 +1,37 @@
1
+ // Truncation black-box — the CONTENT-BEARING sibling of telemetry.jsonl (which is metrics-only by policy
2
+ // and must stay that way). When a tool call's arguments arrive unparseable, the engine fires
3
+ // AgentOpts.onTruncationEvidence with the raw fragment; this module is where a node host lands it:
4
+ // a local-only, append-only, 0600 JSONL under the operator home. Motivation (2026-10-19): the live
5
+ // "arguments were CUT OFF at 4% ctx" incident could not be root-caused because every synthetic repro was
6
+ // clean and nothing recorded what the stream actually carried — the next occurrence hands us the raw args
7
+ // tail, the round's REAL finish_reason, and the budget that was in force, instead of a screenshot.
8
+ // Best-effort like telemetry: never throws, never blocks a turn. Disable with telemetry.enabled=false
9
+ // (one owner switch for both local sinks) or KODE_BLACKBOX=0.
10
+ import { appendFileSync, mkdirSync, renameSync, statSync } from "node:fs";
11
+ import { dirname } from "node:path";
12
+ import { operatorPath } from "../config/home.js";
13
+ const DEFAULT_FILE = process.env.KODE_BLACKBOX_FILE ?? operatorPath("blackbox", "truncations.jsonl");
14
+ const ARGS_CAP = 8192; // raw-fragment cap per record — enough to see where/how the JSON died
15
+ const ROTATE_BYTES = 2 * 1024 * 1024; // rotate to .1 past ~2MB so a truncation storm can't eat the disk
16
+ /** Append one evidence record. Sync on purpose: records are rare (a truncation is an incident), tiny, and
17
+ * a crash right after the event must not lose the one line that explains it. */
18
+ export function recordTruncation(e, file = DEFAULT_FILE) {
19
+ if (process.env.KODE_BLACKBOX === "0")
20
+ return;
21
+ try {
22
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
23
+ try {
24
+ if (statSync(file).size > ROTATE_BYTES)
25
+ renameSync(file, file + ".1"); // one generation kept
26
+ }
27
+ catch { /* no file yet */ }
28
+ const args = e.args.length > ARGS_CAP
29
+ ? e.args.slice(0, 512) + `\n…[${e.args.length - ARGS_CAP} chars elided]…\n` + e.args.slice(-(ARGS_CAP - 512))
30
+ : e.args;
31
+ const line = { ts: new Date().toISOString(), ...e, args, argsLen: e.args.length };
32
+ appendFileSync(file, JSON.stringify(line) + "\n", { encoding: "utf8", mode: 0o600 });
33
+ }
34
+ catch {
35
+ /* best-effort — diagnostics must never degrade the diagnosed thing */
36
+ }
37
+ }
@@ -1,8 +1,8 @@
1
1
  // Operator permission policy — SPEC §11 (agent safety). Decides, per tool call, whether it may run,
2
- // must be approved, or is refused. DESIGNED TO BE INERT BY DEFAULT: mode "bypass" (the default) allows
3
- // everything with no prompt and no log — zero gates, zero overhead — so the owner's experience is
4
- // unchanged until they deliberately turn enforcement on. Enterprise deployments flip mode to "gated"
5
- // (mutating tools require approval) or tighten `rules`; "audit" allows-but-records (see audit.ts).
2
+ // must be approved, or is refused. The CLASS stays inert when constructed without a mode ("bypass":
3
+ // zero gates, zero overhead — programmatic/embedded callers opt in explicitly), but the SHIPPED
4
+ // settings default is "gated" (2026-10-23): mutating tools ask the user to Allow/Deny on spawn,
5
+ // Claude Code-style; shift+tab/Autonomous or settings flip it back. "audit" allows-but-records.
6
6
  import { registrySafeTools, tierAllows } from "./tier.js";
7
7
  import { signatureLine } from "./signature.js";
8
8
  // Read-only tools (registry `safe: true`) — never gated unless a rule says otherwise. DERIVED from the
@@ -25,16 +25,35 @@ function looksDangerous(_name, args) {
25
25
  const blob = `${cmd} ${gitArgs}`;
26
26
  return blob.trim().length > 0 && DANGEROUS.some((re) => re.test(blob));
27
27
  }
28
+ function globMatch(pattern, text) {
29
+ const re = new RegExp("^" + pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".") + "$", "i");
30
+ return re.test(text);
31
+ }
32
+ function matchesAllowlist(allow, name, args) {
33
+ const serialized = typeof args.command === "string" ? args.command
34
+ : typeof args.path === "string" ? args.path
35
+ : Array.isArray(args.args) ? args.args.join(" ")
36
+ : JSON.stringify(args);
37
+ return allow.some((p) => {
38
+ if (!globMatch(p.tool, name))
39
+ return false;
40
+ if (!p.args)
41
+ return true;
42
+ return globMatch(p.args, serialized);
43
+ });
44
+ }
28
45
  export class PermissionPolicy {
29
46
  mode;
30
47
  rules;
31
48
  safe;
32
49
  tier;
50
+ allow;
33
51
  constructor(cfg = {}) {
34
52
  this.mode = cfg.mode ?? "bypass";
35
53
  this.rules = cfg.rules ?? {};
36
54
  this.safe = new Set(cfg.safeTools ?? DEFAULT_SAFE);
37
55
  this.tier = cfg.tier ?? "admin";
56
+ this.allow = cfg.allow ?? [];
38
57
  }
39
58
  /** True when the policy can never block, prompt, or log — lets the wrapper skip itself entirely (no
40
59
  * overhead). Requires the full-access owner tier: a narrowed tier is always enforced, even in bypass. */
@@ -64,7 +83,7 @@ export class PermissionPolicy {
64
83
  }
65
84
  /** The decision for one tool call. Precedence: tier ceiling (a denied tool can't be granted by any
66
85
  * rule) → human-signature line (money/prod/destructive always ask, beating a rule/mode) → per-tool
67
- * rule → mode. */
86
+ * rule → allowlist pattern match → mode. */
68
87
  decide(name, args) {
69
88
  if (!this.allowsTool(name))
70
89
  return "deny"; // tier ceiling — absolute, above rules and mode
@@ -75,11 +94,17 @@ export class PermissionPolicy {
75
94
  return rule; // explicit override within the tier
76
95
  if (this.mode === "bypass" || this.mode === "audit")
77
96
  return "allow"; // audit records but never blocks
78
- // "gated": read-only tools run; mutating tools ask; a dangerous shell shape always asks.
97
+ // "gated": read-only tools run; allowlisted patterns auto-allow (but dangerous shapes still ask);
98
+ // everything else asks.
79
99
  if (this.safe.has(name))
80
100
  return "allow";
81
101
  if (looksDangerous(name, args))
82
102
  return "ask";
103
+ if (this.allow.length && matchesAllowlist(this.allow, name, args))
104
+ return "allow";
83
105
  return "ask"; // any mutating tool
84
106
  }
107
+ addAllowPattern(pattern) {
108
+ this.allow.push(pattern);
109
+ }
85
110
  }
@@ -0,0 +1,127 @@
1
+ // Model discovery — turn "a server is running on the fleet" into a named, truthfully-sized model profile
2
+ // WITHOUT editing the catalog. Frontier model platforms treat models as DATA the serving layer advertises
3
+ // (OpenAI `GET /v1/models` + llama.cpp `/props`) and a gateway polls + auto-catalogs them; this is that
4
+ // layer for Operator. Drop a llama.cpp/vLLM/TGI server onto a fleet node, list its base in
5
+ // settings.fleet.auroraNodes, and it appears in `/model` — named by the server, with its REAL context
6
+ // window read from `/props` — no code change, and no hand-typed ctx that can drift from the served wall
7
+ // (the "operator-1m labelled 300K while serving 600K" class of bug the manual catalog kept producing).
8
+ //
9
+ // Design mirrors the rest of router/models.ts: health-gated (a base that doesn't answer in time is simply
10
+ // absent — an honest picker never offers a dead endpoint, same spirit as visibleModels), merged UNDER
11
+ // settings.models (an explicit hand override by id ALWAYS wins — discovery informs, never overrides an
12
+ // owner's choice), and cached with a short TTL so it never runs on a render/keystroke path. Kept
13
+ // dependency-free except the ModelProfile type (the no-cycle rule models.ts documents).
14
+ const DEFAULTS = { timeoutMs: 2500, marginPct: 0.98 };
15
+ /** A bare base ("http://host:8097") → the OpenAI base the AuroraRouter wants ("http://host:8097/v1").
16
+ * settings.fleet.auroraNodes holds bare bases; ModelProfile.endpoint includes /v1. */
17
+ function v1(base) {
18
+ return base.replace(/\/+$/, "") + "/v1";
19
+ }
20
+ /** A stable, human-ish host tag ("192.168.1.103:8097") for ids/labels when a server advertises no alias. */
21
+ function hostTag(base) {
22
+ try {
23
+ const u = new URL(base);
24
+ return u.port ? `${u.hostname}:${u.port}` : u.hostname;
25
+ }
26
+ catch {
27
+ return base.replace(/^https?:\/\//, "").replace(/\/+$/, "");
28
+ }
29
+ }
30
+ function slug(s) {
31
+ return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
32
+ }
33
+ function fmtK(n) {
34
+ return n >= 1000 ? `${Math.round(n / 1000)}K` : String(n);
35
+ }
36
+ /** A served model id that is actually a filesystem path (llama.cpp's default when `--alias` is unset) is
37
+ * not a name a human picked — fall back to the host tag rather than show a gguf path in the picker. Set
38
+ * the server's `--alias` to its friendly name and discovery uses it: that's the true self-registration. */
39
+ function isPathLike(id) {
40
+ return !!id && (id.includes("/") || id.toLowerCase().endsWith(".gguf"));
41
+ }
42
+ async function getJson(url, timeoutMs, f) {
43
+ const ctl = new AbortController();
44
+ const t = setTimeout(() => ctl.abort(), timeoutMs);
45
+ try {
46
+ const r = await f(url, { signal: ctl.signal });
47
+ if (!r.ok)
48
+ return null;
49
+ return await r.json();
50
+ }
51
+ catch {
52
+ return null; // unreachable / timeout / bad JSON → treated as "down", never throws into the caller
53
+ }
54
+ finally {
55
+ clearTimeout(t);
56
+ }
57
+ }
58
+ /** Probe one fleet base and build a ModelProfile from what the SERVER reports, or null if it doesn't
59
+ * answer `/props` in time (→ absent from the picker). `/props` is the source of truth for the context
60
+ * window (default_generation_settings.n_ctx) and the self-chosen name (model_alias); `/v1/models` is a
61
+ * secondary name source. */
62
+ export async function probeHost(base, opts = {}) {
63
+ const timeoutMs = opts.timeoutMs ?? DEFAULTS.timeoutMs;
64
+ const marginPct = opts.marginPct ?? DEFAULTS.marginPct;
65
+ const f = opts.fetchImpl ?? fetch;
66
+ const bare = base.replace(/\/+$/, "");
67
+ const props = await getJson(`${bare}/props`, timeoutMs, f);
68
+ if (!props)
69
+ return null; // health gate: no /props → down → not offered
70
+ const nCtx = Number(props?.default_generation_settings?.n_ctx ?? props?.n_ctx);
71
+ if (!Number.isFinite(nCtx) || nCtx <= 0)
72
+ return null; // can't size it truthfully → skip
73
+ const models = await getJson(`${v1(bare)}/models`, timeoutMs, f);
74
+ const servedId = models?.data?.[0]?.id;
75
+ // The self-chosen name: the first candidate that is a real name, not a path — llama.cpp sets BOTH
76
+ // model_alias and the /v1/models id to the gguf PATH when `--alias` is unset, so a path from either
77
+ // source is rejected and we fall back to a host tag rather than leak a filesystem path into the picker.
78
+ const alias = [props?.model_alias, servedId].find((x) => typeof x === "string" && x.length > 0 && !isPathLike(x));
79
+ const tag = hostTag(bare);
80
+ const ctx = Math.floor(nCtx * marginPct);
81
+ return {
82
+ id: alias ? `fleet-${slug(alias)}-${slug(tag)}` : `fleet-${slug(tag)}`,
83
+ label: alias ? `${alias} (${tag})` : `Aurora ${fmtK(nCtx)} @ ${tag}`,
84
+ kind: "single",
85
+ endpoint: v1(bare),
86
+ model: servedId || alias || "aurora-code-1",
87
+ ctx,
88
+ desc: `auto-discovered — served ${nCtx.toLocaleString()} ctx${props?.total_slots ? `, ${props.total_slots} slot(s)` : ""} at ${tag}`,
89
+ };
90
+ }
91
+ /** Probe every base in parallel, drop the unreachable, and dedup by endpoint (a box listed twice) keeping
92
+ * the first. Result is meant to be MERGED UNDER settings.models:
93
+ * modelRegistry([...discovered, ...(settings.models ?? [])])
94
+ * so a hand-written override by id always wins over the auto-discovered record. */
95
+ export async function discoverFleetModels(bases, opts = {}) {
96
+ const uniq = [...new Set((bases ?? []).filter(Boolean))];
97
+ const probed = await Promise.all(uniq.map((b) => probeHost(b, opts)));
98
+ const out = [];
99
+ const seen = new Set();
100
+ for (const p of probed) {
101
+ if (!p || seen.has(p.endpoint))
102
+ continue;
103
+ seen.add(p.endpoint);
104
+ out.push(p);
105
+ }
106
+ return out;
107
+ }
108
+ // ── cache ────────────────────────────────────────────────────────────────
109
+ // Discovery hits the network, so it must never run on a render/keystroke path. A short TTL keeps the
110
+ // picker fresh (a newly-started node shows within one TTL) without re-probing every `/model` open.
111
+ let cache = null;
112
+ const TTL_MS = 60_000;
113
+ /** Cached discovery for the given bases: the last good result within the TTL, else an awaited refresh.
114
+ * A probe wave that finds nothing returns [] (callers then show builtins + settings.models only). */
115
+ export async function getDiscoveredModels(bases, opts = {}) {
116
+ const key = [...new Set((bases ?? []).filter(Boolean))].sort().join(",");
117
+ const now = Date.now();
118
+ if (cache && cache.key === key && now - cache.at < TTL_MS)
119
+ return cache.models;
120
+ const models = await discoverFleetModels(bases, opts);
121
+ cache = { at: now, key, models };
122
+ return models;
123
+ }
124
+ /** Reset the cache — tests, and a forced `/model` refresh. */
125
+ export function clearDiscoveryCache() {
126
+ cache = null;
127
+ }