@0perator/operator 0.1.263 → 0.1.275

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 (38) hide show
  1. package/dist/auth/store.js +36 -5
  2. package/dist/cli.js +119 -26
  3. package/dist/config/persona.js +14 -1
  4. package/dist/engine/agent.js +4 -4
  5. package/dist/engine/anthropic.js +48 -0
  6. package/dist/engine/batch-scheduler.js +68 -21
  7. package/dist/engine/cli.js +1171 -0
  8. package/dist/mcp/index.js +2 -1
  9. package/dist/permissions/index.js +11 -4
  10. package/dist/remote/host.js +46 -5
  11. package/dist/remote/pairing.js +70 -0
  12. package/dist/router/models.js +8 -1
  13. package/dist/router/models.js.bak +78 -0
  14. package/dist/router/models.js.bak-1791259923 +78 -0
  15. package/dist/router/models.js.bak-pre-gateway +78 -0
  16. package/dist/router/models.js.bak-pre-patch2 +78 -0
  17. package/dist/router/models.js.bak2 +78 -0
  18. package/dist/services/model-autodetect.js +240 -0
  19. package/dist/tools/chauffeur.js +16 -3
  20. package/dist/tools/deferred.js +2 -1
  21. package/dist/tools/executor.js +15 -3
  22. package/dist/tools/native-redirect.js +140 -0
  23. package/dist/tools/power-tools.js +627 -0
  24. package/dist/tools/registry.js +252 -5
  25. package/dist/tools/registry.js.bak-1791259948 +1914 -0
  26. package/dist/tools/registry.js.bak-pre-plugins +1914 -0
  27. package/dist/ui/App.js +5 -4
  28. package/dist/ui/BusTray.js +70 -0
  29. package/dist/ui/Composer.js +28 -1
  30. package/dist/ui/ToolStep.js +1 -1
  31. package/dist/ui/format.js +18 -0
  32. package/dist/ui/liveTools.js +2 -5
  33. package/dist/ui/qr.js +10 -0
  34. package/dist/ui/resize.js +160 -0
  35. package/dist/ui/slashCommands.js +43 -0
  36. package/dist/ui/term.js +17 -0
  37. package/dist/util/slash.js +1 -1
  38. package/package.json +3 -1
@@ -0,0 +1,627 @@
1
+ // Power-tools — the AXE "power tools" set (originally ~/.axe/mcp/tools/power_tools.py, "Nova's Wishlist"),
2
+ // ported into Operator as native tools, each behind a FEATURE FLAG so a deployment limits what a user can
3
+ // reach (James, 2026-10-10: "build all of these into operators system and surfaces — we can limit what users
4
+ // can access with feature flags"). Decision log: _ai-docs/decisions/2026-10-10-power-tools-feature-flagged.md.
5
+ //
6
+ // GATING (fail-closed, two layers):
7
+ // 1. Visibility — `disabledPowerToolNames(cfg)` drives `visibleRegistry()` (registry.ts), so a disabled tool
8
+ // is absent from BOTH the model's schemas AND the session executor (not hidden-but-callable — genuinely not
9
+ // runnable), and from the system-prompt catalogue. This is the engine's "advertised iff runnable" invariant.
10
+ // 2. Backstop — each fleet run() re-checks the module-level active config (set once at startup via
11
+ // setActivePowerTools), so even a direct registry call on a disabled tool returns a clean "disabled"
12
+ // result instead of touching the fleet.
13
+ // Per-USER access is the existing tier system (permissions/tier.ts): the mutating power-tools are not in
14
+ // ENTERPRISE_MUTATING, so enterprise/readonly seats are denied them by default; the local owner (admin) gets them.
15
+ //
16
+ // Self-contained on purpose: only a TYPE import of Tool (erased at runtime) so there is no import cycle with
17
+ // registry.ts (which spreads POWER_TOOLS into its TOOLS array). Node builtins are reached lazily via
18
+ // process.getBuiltinModule to keep them out of the mobile JSCore bundle (same pattern as registry.ts).
19
+ export const DEFAULT_POWER_TOOLS = {
20
+ logWatch: true,
21
+ fleetOps: false,
22
+ fleetMemory: false,
23
+ trainingCapture: false,
24
+ hfUpload: false,
25
+ };
26
+ /** Each power-tool → the flag group that gates it. The single source of truth for both the visibility filter
27
+ * and the run() backstop; a new power-tool joins the gate by adding one row here. */
28
+ export const POWER_TOOL_GROUP = {
29
+ log_watch: "logWatch",
30
+ axe_push: "fleetOps",
31
+ fleet_ssh: "fleetOps",
32
+ edge_train_status: "fleetOps",
33
+ qdrant_search: "fleetMemory",
34
+ qdrant_store: "fleetMemory",
35
+ hydra_add: "trainingCapture",
36
+ hf_upload: "hfUpload",
37
+ };
38
+ // Owner-facing hint for how to enable a disabled group — the external settings path only. The matching env
39
+ // override (KODE_POWERTOOLS_*) is documented at code level (settings.ts), not in this model-visible string:
40
+ // an internal env-var name must never appear in prose a user/model reads (branding-boundary.test.mts).
41
+ const GROUP_ENABLE_HINT = {
42
+ logWatch: "powerTools.logWatch",
43
+ fleetOps: "powerTools.fleetOps",
44
+ fleetMemory: "powerTools.fleetMemory",
45
+ trainingCapture: "powerTools.trainingCapture",
46
+ hfUpload: "powerTools.hfUpload",
47
+ };
48
+ /** Names disabled under `cfg` — the set `visibleRegistry()` removes from the schemas + catalogue + executor. */
49
+ export function disabledPowerToolNames(cfg = DEFAULT_POWER_TOOLS) {
50
+ const off = new Set();
51
+ for (const [name, group] of Object.entries(POWER_TOOL_GROUP)) {
52
+ if (!cfg[group])
53
+ off.add(name);
54
+ }
55
+ return off;
56
+ }
57
+ /** Every power-tool name (whatever its flag state) — used by the catalogue/parity tests and the visibility filter. */
58
+ export function allPowerToolNames() {
59
+ return Object.keys(POWER_TOOL_GROUP);
60
+ }
61
+ // Module-level active config, set once at startup (cli.tsx / session-factory) so the run() backstop is a cheap
62
+ // in-memory check, not a settings-file re-read. Defaults to DEFAULT_POWER_TOOLS (fleet OFF) → fail-closed.
63
+ let activePowerTools = DEFAULT_POWER_TOOLS;
64
+ export function setActivePowerTools(cfg) {
65
+ activePowerTools = cfg;
66
+ }
67
+ export function activePowerToolsConfig() {
68
+ return activePowerTools;
69
+ }
70
+ function groupOf(name) {
71
+ return POWER_TOOL_GROUP[name];
72
+ }
73
+ /** The backstop: a clean, structured "disabled by feature flag" result (never a throw) if the tool's group is
74
+ * off in the active config. Returns null when enabled (proceed). */
75
+ function flagBlock(name) {
76
+ const group = groupOf(name);
77
+ if (activePowerTools[group])
78
+ return null;
79
+ return JSON.stringify({
80
+ tool: name,
81
+ enabled: false,
82
+ reason: `\`${name}\` is disabled by feature flag (group "${group}" is off).`,
83
+ enable_with: GROUP_ENABLE_HINT[group],
84
+ });
85
+ }
86
+ // ── Local helpers (self-contained; no registry.ts import) ───────────────────────────────────────────────────
87
+ function str(v) {
88
+ return typeof v === "string" ? v : v == null ? "" : String(v);
89
+ }
90
+ function num(v, dflt) {
91
+ const n = Number(v);
92
+ return Number.isFinite(n) ? n : dflt;
93
+ }
94
+ function sleep(ms) {
95
+ return new Promise((r) => setTimeout(r, ms));
96
+ }
97
+ /** Lazy node builtin via process.getBuiltinModule (Node ≥20.16) — keeps a static `node:` import out of the
98
+ * mobile bundle. Returns undefined off-node (so a tool degrades to a clean error instead of crashing). */
99
+ function nodeBuiltin(id) {
100
+ const proc = globalThis.process;
101
+ try {
102
+ return proc?.getBuiltinModule?.(id);
103
+ }
104
+ catch {
105
+ return undefined;
106
+ }
107
+ }
108
+ function env(name) {
109
+ return globalThis.process?.env?.[name];
110
+ }
111
+ function homedir() {
112
+ const os = nodeBuiltin("node:os");
113
+ return os?.homedir?.() ?? env("HOME") ?? ".";
114
+ }
115
+ function expandHome(p) {
116
+ return p.startsWith("~/") || p === "~" ? p.replace(/^~/, homedir()) : p;
117
+ }
118
+ /** fetch JSON with a hard timeout; returns {ok,status,json} or {ok:false,error}. Never throws. */
119
+ async function fetchJson(url, init, timeoutMs) {
120
+ const c = new AbortController();
121
+ const t = setTimeout(() => c.abort(), timeoutMs);
122
+ try {
123
+ const r = await fetch(url, { ...init, signal: c.signal });
124
+ const text = await r.text();
125
+ let json;
126
+ try {
127
+ json = text ? JSON.parse(text) : undefined;
128
+ }
129
+ catch {
130
+ json = text;
131
+ }
132
+ return { ok: r.ok, status: r.status, json };
133
+ }
134
+ catch (e) {
135
+ return { ok: false, error: String(e?.message ?? e) };
136
+ }
137
+ finally {
138
+ clearTimeout(t);
139
+ }
140
+ }
141
+ /** POST a JSON body to localhost Ollama for a nomic-embed-text embedding. Shared by the two qdrant tools. */
142
+ async function embed(text, ollama) {
143
+ const r = await fetchJson(`${ollama}/api/embeddings`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ model: "nomic-embed-text", prompt: text }) }, 10000);
144
+ if (!r.ok)
145
+ return { error: `embedding backend (ollama ${ollama}) unreachable: ${r.error ?? r.status}` };
146
+ const emb = r.json?.embedding;
147
+ if (!Array.isArray(emb))
148
+ return { error: "embedding backend returned no vector (is nomic-embed-text pulled?)" };
149
+ return emb;
150
+ }
151
+ // Fleet endpoints — env-overridable; defaults are the CURRENT fleet (JL1 .103, JL2 .146), NOT the Python's stale
152
+ // .147/.122 (those predate the DO decommission + JL2 move). A deployment sets KODE_FLEET_* to match its mesh.
153
+ function fleetPushUrls() {
154
+ const custom = env("KODE_FLEET_PUSH_URLS");
155
+ if (custom)
156
+ return custom.split(",").map((u, i) => [`endpoint-${i}`, u.trim()]);
157
+ return [
158
+ ["jl2", "http://192.168.1.146:8088/push"],
159
+ ["jl1/local", "http://localhost:8088/push"],
160
+ ];
161
+ }
162
+ function fleetNodeMap() {
163
+ const custom = env("KODE_FLEET_NODES");
164
+ if (custom) {
165
+ try {
166
+ return JSON.parse(custom);
167
+ }
168
+ catch {
169
+ /* fall through to defaults */
170
+ }
171
+ }
172
+ return {
173
+ jl1: "localhost", nova: "localhost",
174
+ jl2: "192.168.1.146", forge: "192.168.1.146",
175
+ jl3: "192.168.1.122", vigil: "192.168.1.122",
176
+ jl4: "192.168.1.28", reaper: "192.168.1.28",
177
+ jla: "192.168.1.148", studio: "192.168.1.148",
178
+ };
179
+ }
180
+ function qdrantUrl(arg) {
181
+ return str(arg) || env("KODE_QDRANT_URL") || "http://10.10.0.1:6333";
182
+ }
183
+ function ollamaUrl() {
184
+ return env("KODE_OLLAMA_URL") || "http://localhost:11434";
185
+ }
186
+ // ── run() implementations ────────────────────────────────────────────────────────────────────────────────
187
+ /** log_watch — block until `pattern` appears in `log_path` (or timeout). Agnostic: pure filesystem tail. */
188
+ async function logWatch(args) {
189
+ const block = flagBlock("log_watch");
190
+ if (block)
191
+ return block;
192
+ const logPath = expandHome(str(args.log_path));
193
+ const pattern = str(args.pattern);
194
+ if (!logPath || !pattern)
195
+ return JSON.stringify({ found: false, error: "log_path and pattern are required" });
196
+ // Default 120s (aligns with the bash default), capped at 900s (the engine's wall-clock budget).
197
+ const timeoutSec = Math.min(Math.max(num(args.timeout_sec, 120), 1), 900);
198
+ const tailLines = Math.min(Math.max(num(args.tail_lines, 5), 1), 50);
199
+ const fs = nodeBuiltin("node:fs");
200
+ if (!fs)
201
+ return JSON.stringify({ found: false, error: "filesystem unavailable in this runtime" });
202
+ if (!fs.existsSync(logPath))
203
+ return JSON.stringify({ found: false, error: `log file not found: ${str(args.log_path)}` });
204
+ const start = Date.now();
205
+ let lastSize = fs.statSync(logPath).size;
206
+ let context = [];
207
+ while ((Date.now() - start) / 1000 < timeoutSec) {
208
+ let size = 0;
209
+ try {
210
+ size = fs.statSync(logPath).size;
211
+ }
212
+ catch {
213
+ break; // file rotated/removed
214
+ }
215
+ if (size > lastSize) {
216
+ let chunk = "";
217
+ try {
218
+ const fd = fs.openSync(logPath, "r");
219
+ const buf = Buffer.alloc(size - lastSize);
220
+ fs.readSync(fd, buf, 0, buf.length, lastSize);
221
+ fs.closeSync(fd);
222
+ chunk = buf.toString("utf8");
223
+ }
224
+ catch (e) {
225
+ return JSON.stringify({ found: false, error: `read failed: ${String(e?.message ?? e)}` });
226
+ }
227
+ lastSize = size;
228
+ for (const line of chunk.split(/\r?\n/)) {
229
+ context.push(line);
230
+ if (context.length > tailLines * 2)
231
+ context = context.slice(-tailLines);
232
+ if (line.toLowerCase().includes(pattern.toLowerCase())) {
233
+ return JSON.stringify({
234
+ found: true,
235
+ matched_line: line.trim(),
236
+ pattern,
237
+ context: context.slice(-tailLines),
238
+ elapsed_sec: Math.round((Date.now() - start) / 100) / 10,
239
+ log: str(args.log_path),
240
+ });
241
+ }
242
+ }
243
+ }
244
+ await sleep(2000);
245
+ }
246
+ return JSON.stringify({
247
+ found: false,
248
+ pattern,
249
+ timeout_sec: timeoutSec,
250
+ elapsed_sec: Math.round((Date.now() - start) / 100) / 10,
251
+ note: `pattern '${pattern}' not found within ${timeoutSec}s`,
252
+ last_lines: context.slice(-tailLines),
253
+ });
254
+ }
255
+ /** fleet_ssh — run a command on a fleet node (localhost = local exec), via the node alias map. Mutating. */
256
+ async function fleetSsh(args) {
257
+ const block = flagBlock("fleet_ssh");
258
+ if (block)
259
+ return block;
260
+ const node = str(args.node);
261
+ const command = str(args.command);
262
+ if (!node || !command)
263
+ return JSON.stringify({ error: "node and command are required" });
264
+ const timeout = Math.min(Math.max(num(args.timeout, 30), 1), 300);
265
+ const cp = nodeBuiltin("node:child_process");
266
+ if (!cp)
267
+ return JSON.stringify({ error: "subprocess unavailable in this runtime", node });
268
+ const host = fleetNodeMap()[node.toLowerCase()] ?? node;
269
+ const t0 = Date.now();
270
+ const runProc = (file, argv) => new Promise((resolve) => {
271
+ let out = "", err = "", done = false;
272
+ const child = cp.spawn(file, argv, { shell: file === "bash" });
273
+ const timer = setTimeout(() => {
274
+ if (!done) {
275
+ done = true;
276
+ try {
277
+ child.kill("SIGKILL");
278
+ }
279
+ catch { /* already gone */ }
280
+ resolve(JSON.stringify({ error: `timed out after ${timeout}s`, node, host }));
281
+ }
282
+ }, timeout * 1000);
283
+ child.stdout?.on("data", (d) => (out += d.toString()));
284
+ child.stderr?.on("data", (d) => (err += d.toString()));
285
+ child.on("error", (e) => {
286
+ if (!done) {
287
+ done = true;
288
+ clearTimeout(timer);
289
+ resolve(JSON.stringify({ error: String(e.message), node, host }));
290
+ }
291
+ });
292
+ child.on("close", (code) => {
293
+ if (done)
294
+ return;
295
+ done = true;
296
+ clearTimeout(timer);
297
+ resolve(JSON.stringify({
298
+ node, host,
299
+ stdout: out.trim(),
300
+ stderr: err.trim(),
301
+ exit_code: code ?? -1,
302
+ duration_ms: Math.round(Date.now() - t0),
303
+ }));
304
+ });
305
+ });
306
+ if (host === "localhost")
307
+ return runProc("bash", ["-lc", command]);
308
+ const user = ["jl4", "reaper", "jla", "studio"].includes(node.toLowerCase()) ? "studio" : "home";
309
+ return runProc("ssh", ["-o", "ConnectTimeout=5", "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=no", `${user}@${host}`, command]);
310
+ }
311
+ /** axe_push — fleet push notification; tries each fleet-app endpoint, degrades to a clean "not delivered". */
312
+ async function axePush(args) {
313
+ const block = flagBlock("axe_push");
314
+ if (block)
315
+ return block;
316
+ const message = str(args.message);
317
+ if (!message)
318
+ return JSON.stringify({ sent: false, error: "message is required" });
319
+ const body = JSON.stringify({
320
+ title: str(args.title) || "AXE",
321
+ message,
322
+ priority: str(args.priority) || "default",
323
+ tags: str(args.tags) || "axe",
324
+ });
325
+ for (const [name, url] of fleetPushUrls()) {
326
+ const r = await fetchJson(url, { method: "POST", headers: { "Content-Type": "application/json" }, body }, 3000);
327
+ if (r.ok) {
328
+ const result = (r.json && typeof r.json === "object" ? r.json : {});
329
+ return JSON.stringify({ ...result, sent: true, via: name });
330
+ }
331
+ }
332
+ return JSON.stringify({
333
+ sent: false,
334
+ note: "fleet notification app is DOWN (outage): retry once; if still down, tell the owner. The message was NOT delivered.",
335
+ message,
336
+ });
337
+ }
338
+ /** edge_train_status — tail the Edge training log + parse the latest step line. Read-only. (Fleet/stale: the
339
+ * Edge pre-training project is paused, so this usually reports NOT_RUNNING; kept for fleet deployments that
340
+ * revive it.) */
341
+ async function edgeTrainStatus(_args) {
342
+ const block = flagBlock("edge_train_status");
343
+ if (block)
344
+ return block;
345
+ const fs = nodeBuiltin("node:fs");
346
+ if (!fs)
347
+ return JSON.stringify({ status: "UNKNOWN", error: "filesystem unavailable" });
348
+ const base = `${homedir()}/Desktop/Desktop - JL1/Edge`;
349
+ const logs = [`${base}/edge2-large-resumed.log`, `${base}/edge2-large-training.log`, `${base}/edge2-v2-training.log`];
350
+ const re = /step\s+([\d,]+)\/([\d,]+)\s+│\s+loss\s+([\d.]+)\s+│\s+lr\s+([\d.e+-]+)\s+│\s+([\d.]+)\s+tok\/s\s+│\s+gnorm\s+([\d.]+)\s+│\s+ETA\s+([\d.]+)h/;
351
+ for (const log of logs) {
352
+ if (!fs.existsSync(log))
353
+ continue;
354
+ let tail = "";
355
+ try {
356
+ const data = fs.readFileSync(log, "utf8");
357
+ tail = data.split(/\r?\n/).slice(-50).join("\n");
358
+ }
359
+ catch {
360
+ continue;
361
+ }
362
+ const lines = tail.split(/\r?\n/).reverse();
363
+ for (const line of lines) {
364
+ const m = re.exec(line);
365
+ if (m) {
366
+ const step = parseInt(m[1].replace(/,/g, ""), 10);
367
+ const total = parseInt(m[2].replace(/,/g, ""), 10);
368
+ const etaH = parseFloat(m[7]);
369
+ return JSON.stringify({
370
+ model: "Edge-1.3B", status: "TRAINING", log: log.split("/").pop(),
371
+ current_step: step, total_steps: total, progress_pct: Math.round((step / total) * 1000) / 10,
372
+ train_loss: parseFloat(m[3]), learning_rate: parseFloat(m[4]), tok_per_sec: parseFloat(m[5]),
373
+ grad_norm: parseFloat(m[6]), eta_hours: etaH, eta_human: `${Math.floor(etaH)}h ${Math.floor((etaH % 1) * 60)}m`,
374
+ });
375
+ }
376
+ }
377
+ }
378
+ return JSON.stringify({ model: "Edge-1.3B", status: "NOT_RUNNING", note: "no active Edge training log found." });
379
+ }
380
+ /** qdrant_search — semantic (vector) search against the AXE fleet Qdrant. Read-only. Distinct from the local
381
+ * `memory_search` note store: this is the fleet-wide vector memory (nomic-embed + Qdrant mesh). */
382
+ async function qdrantSearch(args) {
383
+ const block = flagBlock("qdrant_search");
384
+ if (block)
385
+ return block;
386
+ const query = str(args.query);
387
+ if (!query)
388
+ return JSON.stringify({ error: "query is required" });
389
+ const collection = str(args.collection) || "axe_persistent_memory";
390
+ const topK = Math.min(Math.max(num(args.top_k, 5), 1), 20);
391
+ const qurl = qdrantUrl(args.qdrant_url);
392
+ const vec = await embed(query, ollamaUrl());
393
+ if ("error" in vec)
394
+ return JSON.stringify({ error: vec.error, query, collection });
395
+ const r = await fetchJson(`${qurl}/collections/${encodeURIComponent(collection)}/points/search`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ vector: vec, limit: topK, with_payload: true }) }, 10000);
396
+ if (!r.ok)
397
+ return JSON.stringify({ error: `fleet Qdrant (${qurl}) unreachable: ${r.error ?? r.status}`, query, collection });
398
+ const hits = (r.json?.result) ?? [];
399
+ return JSON.stringify({
400
+ query, collection, count: hits.length,
401
+ results: hits.map((h) => ({ score: Math.round(Number(h.score ?? 0) * 1e4) / 1e4, id: h.id, payload: h.payload ?? {} })),
402
+ });
403
+ }
404
+ /** qdrant_store — embed + upsert text into the AXE fleet Qdrant. Mutating. */
405
+ async function qdrantStore(args) {
406
+ const block = flagBlock("qdrant_store");
407
+ if (block)
408
+ return block;
409
+ const text = str(args.text);
410
+ if (!text)
411
+ return JSON.stringify({ stored: false, error: "text is required" });
412
+ const collection = str(args.collection) || "axe_persistent_memory";
413
+ const qurl = qdrantUrl(args.qdrant_url);
414
+ let meta = {};
415
+ const rawMeta = args.metadata;
416
+ if (rawMeta && typeof rawMeta === "object")
417
+ meta = rawMeta;
418
+ else if (typeof rawMeta === "string" && rawMeta && rawMeta !== "{}") {
419
+ try {
420
+ meta = JSON.parse(rawMeta);
421
+ }
422
+ catch { /* ignore bad metadata */ }
423
+ }
424
+ meta.ts = new Date().toISOString();
425
+ meta.text = text.slice(0, 500);
426
+ meta.source = "operator_power_tools";
427
+ const vec = await embed(text, ollamaUrl());
428
+ if ("error" in vec)
429
+ return JSON.stringify({ stored: false, error: vec.error });
430
+ // Deterministic numeric id from the text hash (first 8 hex → int), matching the Python tool.
431
+ const crypto = nodeBuiltin("node:crypto");
432
+ const pointId = crypto ? parseInt(crypto.createHash("sha256").update(text).digest("hex").slice(0, 8), 16) : Math.abs(hashString(text));
433
+ const r = await fetchJson(`${qurl}/collections/${encodeURIComponent(collection)}/points`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ points: [{ id: pointId, vector: vec, payload: meta }] }) }, 10000);
434
+ if (!r.ok)
435
+ return JSON.stringify({ stored: false, error: `fleet Qdrant (${qurl}) unreachable: ${r.error ?? r.status}` });
436
+ return JSON.stringify({ stored: true, point_id: pointId, collection, text_len: text.length, result: r.json?.status });
437
+ }
438
+ function hashString(s) {
439
+ let h = 0;
440
+ for (let i = 0; i < s.length; i++)
441
+ h = (Math.imul(31, h) + s.charCodeAt(i)) | 0;
442
+ return h;
443
+ }
444
+ /** hydra_add — append a validated prompt/response pair to the Hydra SFT pipeline (fleet training dir). Mutating. */
445
+ async function hydraAdd(args) {
446
+ const block = flagBlock("hydra_add");
447
+ if (block)
448
+ return block;
449
+ const prompt = str(args.prompt);
450
+ const response = str(args.response);
451
+ if (!prompt || !response)
452
+ return JSON.stringify({ added: false, error: "prompt and response are required" });
453
+ const score = num(args.score, 0.8);
454
+ const fs = nodeBuiltin("node:fs");
455
+ if (!fs)
456
+ return JSON.stringify({ added: false, error: "filesystem unavailable" });
457
+ const today = new Date().toISOString().slice(0, 10);
458
+ const tier = score >= 0.85 ? "curated" : score >= 0.7 ? "scored" : "raw";
459
+ const dir = `${homedir()}/.axe/training/hydra/${tier}`;
460
+ const file = `${dir}/agent_${today}.jsonl`;
461
+ const entry = {
462
+ ts: new Date().toISOString(),
463
+ source: str(args.source) || "operator",
464
+ score,
465
+ tags: str(args.tags).split(",").map((t) => t.trim()).filter(Boolean),
466
+ messages: [
467
+ { role: "user", content: prompt },
468
+ { role: "assistant", content: response },
469
+ ],
470
+ };
471
+ try {
472
+ fs.mkdirSync(dir, { recursive: true });
473
+ fs.appendFileSync(file, JSON.stringify(entry) + "\n", "utf8");
474
+ }
475
+ catch (e) {
476
+ return JSON.stringify({ added: false, error: String(e?.message ?? e) });
477
+ }
478
+ return JSON.stringify({ added: true, path: file, tier, score, training_eligible: score >= 0.7, curated: score >= 0.85 });
479
+ }
480
+ /** hf_upload — push a local file to the HuggingFace Hub via the official `huggingface-cli upload`. Needs
481
+ * `HF_TOKEN`/`HUGGINGFACE_TOKEN` in the engine env + huggingface-cli installed; degrades cleanly if absent.
482
+ * (The original Python listed this tool but never implemented it; this is the honest minimal version — HF push
483
+ * is git+LFS, so the canonical CLI is the right transport rather than a hand-rolled LFS client.) Mutating. */
484
+ async function hfUpload(args) {
485
+ const block = flagBlock("hf_upload");
486
+ if (block)
487
+ return block;
488
+ const repoId = str(args.repo_id);
489
+ const localFile = expandHome(str(args.local_file));
490
+ if (!repoId || !localFile)
491
+ return JSON.stringify({ uploaded: false, error: "repo_id and local_file are required" });
492
+ const token = env("HF_TOKEN") || env("HUGGINGFACE_TOKEN") || env("HUGGING_FACE_HUB_TOKEN");
493
+ if (!token)
494
+ return JSON.stringify({ uploaded: false, error: "no HF token in env (set HF_TOKEN) — hf_upload needs an authenticated token." });
495
+ const cp = nodeBuiltin("node:child_process");
496
+ const fs = nodeBuiltin("node:fs");
497
+ if (!cp || !fs)
498
+ return JSON.stringify({ uploaded: false, error: "subprocess/filesystem unavailable in this runtime" });
499
+ if (!fs.existsSync(localFile))
500
+ return JSON.stringify({ uploaded: false, error: `local_file not found: ${str(args.local_file)}` });
501
+ const pathInRepo = str(args.path_in_repo) || localFile.split("/").pop() || "file";
502
+ const repoType = str(args.repo_type) || "model";
503
+ const argv = ["upload", repoId, localFile, pathInRepo, "--repo-type", repoType, "--token", token];
504
+ return new Promise((resolve) => {
505
+ let out = "", err = "", done = false;
506
+ const child = cp.spawn("huggingface-cli", argv);
507
+ const timer = setTimeout(() => { if (!done) {
508
+ done = true;
509
+ try {
510
+ child.kill("SIGKILL");
511
+ }
512
+ catch { /* gone */ }
513
+ resolve(JSON.stringify({ uploaded: false, error: "upload timed out after 600s" }));
514
+ } }, 600000);
515
+ child.stdout?.on("data", (d) => (out += d.toString()));
516
+ child.stderr?.on("data", (d) => (err += d.toString()));
517
+ child.on("error", (e) => { if (!done) {
518
+ done = true;
519
+ clearTimeout(timer);
520
+ resolve(JSON.stringify({ uploaded: false, error: /ENOENT/.test(String(e.message)) ? "huggingface-cli not installed (pip install huggingface_hub)" : String(e.message) }));
521
+ } });
522
+ child.on("close", (code) => {
523
+ if (done)
524
+ return;
525
+ done = true;
526
+ clearTimeout(timer);
527
+ if (code === 0)
528
+ resolve(JSON.stringify({ uploaded: true, repo_id: repoId, path_in_repo: pathInRepo, repo_type: repoType, output: out.trim().split(/\r?\n/).pop() }));
529
+ else
530
+ resolve(JSON.stringify({ uploaded: false, exit_code: code, error: (err.trim() || out.trim()).split(/\r?\n/).slice(-3).join(" ") }));
531
+ });
532
+ });
533
+ }
534
+ // ── The tool objects (spread into registry.ts TOOLS; gated by visibleRegistry + the run() backstop) ─────────
535
+ export const POWER_TOOLS = [
536
+ {
537
+ name: "log_watch", safe: true,
538
+ description: "Watch a log file and BLOCK until a text pattern appears (or timeout) — for waiting on a build/test/deploy/training " +
539
+ "line to show up. Polls the file for new content; returns the matched line + surrounding context + elapsed time. " +
540
+ "Read-only. Prefer this over a bash `tail -f | grep` loop for a one-shot wait.",
541
+ parameters: { type: "object", properties: {
542
+ log_path: { type: "string", description: "path to the log file (\\~ is expanded)" },
543
+ pattern: { type: "string", description: "substring to wait for (case-insensitive)" },
544
+ timeout_sec: { type: "number", description: "max seconds to block (default 120, max 900)" },
545
+ tail_lines: { type: "number", description: "lines of context to return around the match (default 5)" },
546
+ }, required: ["log_path", "pattern"] },
547
+ run: logWatch,
548
+ },
549
+ {
550
+ name: "fleet_ssh", safe: false,
551
+ description: "Run a shell command on an AXE fleet node by alias (jl1/jl2/jl3/jl4/jla or a raw host; jl1=local exec). " +
552
+ "Returns stdout/stderr/exit_code/duration. For fleet ops across the mesh; a non-fleet remote is just `ssh` in bash.",
553
+ parameters: { type: "object", properties: {
554
+ node: { type: "string", description: "node alias (jl1/jl2/jl3/jl4/jla, nova/forge/vigil/reaper/studio) or a hostname" },
555
+ command: { type: "string", description: "the shell command to run on that node" },
556
+ timeout: { type: "number", description: "timeout in seconds (default 30, max 300)" },
557
+ }, required: ["node", "command"] },
558
+ run: fleetSsh,
559
+ },
560
+ {
561
+ name: "axe_push", safe: false,
562
+ description: "Send a push notification through the AXE Fleet App (native notification on the fleet) — a heads-up to the owner " +
563
+ "when a long task finishes. Tries each fleet endpoint; if the app is down it reports the message was NOT delivered.",
564
+ parameters: { type: "object", properties: {
565
+ message: { type: "string", description: "notification body" },
566
+ title: { type: "string", description: "notification title (default AXE)" },
567
+ priority: { type: "string", description: "low | default | high | urgent" },
568
+ tags: { type: "string", description: "comma-separated tags" },
569
+ }, required: ["message"] },
570
+ run: axePush,
571
+ },
572
+ {
573
+ name: "edge_train_status", safe: true,
574
+ description: "Read the live AXE Edge model training status (step, loss, lr, tok/s, gnorm, ETA) from its log. Read-only. Reports NOT_RUNNING when no training is active.",
575
+ parameters: { type: "object", properties: {} },
576
+ run: edgeTrainStatus,
577
+ },
578
+ {
579
+ name: "qdrant_search", safe: true,
580
+ description: "Semantic (vector) search against the AXE FLEET memory (Qdrant + nomic-embed) — different from `memory_search` " +
581
+ "(local note store): this searches the fleet-wide vector DB by meaning. Read-only; returns scored payloads.",
582
+ parameters: { type: "object", properties: {
583
+ query: { type: "string", description: "natural-language query" },
584
+ collection: { type: "string", description: "Qdrant collection (default axe_persistent_memory)" },
585
+ top_k: { type: "number", description: "results to return, 1-20 (default 5)" },
586
+ qdrant_url: { type: "string", description: "override the Qdrant endpoint" },
587
+ }, required: ["query"] },
588
+ run: qdrantSearch,
589
+ },
590
+ {
591
+ name: "qdrant_store", safe: false,
592
+ description: "Store text with a semantic embedding in the AXE FLEET Qdrant (for later `qdrant_search`) — the fleet-wide vector " +
593
+ "memory, distinct from the local `memory_store`. Mutating.",
594
+ parameters: { type: "object", properties: {
595
+ text: { type: "string", description: "content to embed + store" },
596
+ collection: { type: "string", description: "Qdrant collection (default axe_persistent_memory)" },
597
+ metadata: { type: "object", description: "optional metadata tags (object or JSON string)" },
598
+ qdrant_url: { type: "string", description: "override the Qdrant endpoint" },
599
+ }, required: ["text"] },
600
+ run: qdrantStore,
601
+ },
602
+ {
603
+ name: "hydra_add", safe: false,
604
+ description: "Append a validated prompt/response pair to the AXE Hydra SFT pipeline (tiered by quality score: ≥0.85 curated, " +
605
+ "≥0.7 scored, else raw) so a good interaction becomes training data. Mutating (writes to the fleet training dir).",
606
+ parameters: { type: "object", properties: {
607
+ prompt: { type: "string", description: "the user prompt / instruction" },
608
+ response: { type: "string", description: "the high-quality response" },
609
+ score: { type: "number", description: "quality 0.0-1.0 (≥0.7 enters the curated set; default 0.8)" },
610
+ source: { type: "string", description: "source agent/system (default operator)" },
611
+ tags: { type: "string", description: "comma-separated tags" },
612
+ }, required: ["prompt", "response"] },
613
+ run: hydraAdd,
614
+ },
615
+ {
616
+ name: "hf_upload", safe: false,
617
+ description: "Upload a local file to a HuggingFace Hub repo via the official huggingface-cli (needs HF_TOKEN in the engine env + " +
618
+ "huggingface-cli installed). Mutating. Degrades to a clear error if the token/CLI is missing.",
619
+ parameters: { type: "object", properties: {
620
+ repo_id: { type: "string", description: "e.g. axetechnologies/my-model" },
621
+ local_file: { type: "string", description: "path to the local file to upload (\\~ expanded)" },
622
+ path_in_repo: { type: "string", description: "destination path in the repo (default: the file's basename)" },
623
+ repo_type: { type: "string", description: "model | dataset | space (default model)" },
624
+ }, required: ["repo_id", "local_file"] },
625
+ run: hfUpload,
626
+ },
627
+ ];