@0perator/operator 0.1.24 → 0.1.26

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.
package/dist/cli.js CHANGED
@@ -8,15 +8,16 @@ import { useCallback, useEffect, useRef, useState } from "react";
8
8
  import { render, Box, Text, useApp } from "ink";
9
9
  import { App } from "./ui/index.js";
10
10
  import { mastheadLines } from "./ui/Masthead.js";
11
+ import { RemoteHost } from "./remote/host.js";
11
12
  import { Session } from "./session.js";
12
13
  import { AuroraRouter } from "./router/router.js";
13
14
  import { BackgroundAgents } from "./background/index.js";
14
15
  import { loadSettings } from "./config/settings.js";
15
16
  import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
16
17
  import { join } from "node:path";
17
- import { homedir } from "node:os";
18
+ import { homedir, hostname } from "node:os";
18
19
  import { createHash } from "node:crypto";
19
- const VERSION = "0.1.24";
20
+ const VERSION = "0.1.26";
20
21
  // operator/settings.json (override path via KODE_TSI_SETTINGS), env vars still win — see config/settings.ts.
21
22
  const settings = loadSettings();
22
23
  // Propagate the resolved sandbox mode to the tool layer (registry reads KODE_SANDBOX at exec time).
@@ -28,6 +29,8 @@ if (settings.search?.autopilotUrl)
28
29
  process.env.KODE_AUTOPILOT_URL = settings.search.autopilotUrl;
29
30
  if (settings.search?.searxngUrl)
30
31
  process.env.KODE_SEARXNG_URL = settings.search.searxngUrl;
32
+ if (settings.search?.searxngEngines)
33
+ process.env.KODE_SEARXNG_ENGINES = settings.search.searxngEngines;
31
34
  const sd = settings.search?.docker;
32
35
  if (sd) {
33
36
  if (sd.enabled === false)
@@ -169,11 +172,31 @@ function Root() {
169
172
  // adds the tool to a per-session set so it stops prompting. (No approver ⇒ policy fail-safe denies.)
170
173
  const [approval, setApproval] = useState(null);
171
174
  const alwaysAllowRef = useRef(new Set());
175
+ // Pending gated approvals by id. Both the local keystroke and a remote follower's approval_response
176
+ // route through settleApproval — FIRST answer wins (§7); the map delete makes it idempotent.
177
+ const pendingApprovals = useRef(new Map());
178
+ const settleApproval = useCallback((id, allow, always = false) => {
179
+ const resolve = pendingApprovals.current.get(id);
180
+ if (!resolve)
181
+ return; // already settled (first-wins)
182
+ pendingApprovals.current.delete(id);
183
+ resolve(allow);
184
+ setApproval((cur) => {
185
+ if (cur && cur.id === id && allow && always)
186
+ alwaysAllowRef.current.add(cur.name);
187
+ return cur && cur.id === id ? null : cur;
188
+ });
189
+ }, []);
172
190
  const approveFn = useCallback((name, args) => {
173
191
  if (alwaysAllowRef.current.has(name))
174
192
  return Promise.resolve(true);
175
- return new Promise((resolve) => setApproval({ name, args, resolve }));
176
- }, []);
193
+ const id = "ap_" + Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
194
+ return new Promise((resolve) => {
195
+ pendingApprovals.current.set(id, resolve);
196
+ setApproval({ id, name, args, resolve: (b) => settleApproval(id, b) });
197
+ remoteRef.current?.approvalRequest(id, name, args); // mirror to followers (owner-scoped)
198
+ });
199
+ }, [settleApproval]);
177
200
  const sessionRef = useRef(null); // lazy — never reconstruct on re-render
178
201
  // MCP opts the foreground session into the fleet MCP tool surface (off by default: local tools
179
202
  // only, no network fan-out at session start). Background agents stay local-only + lean.
@@ -227,7 +250,10 @@ function Root() {
227
250
  const liveReasoning = useRef(""); // current completion's reasoning ("thinking"), shown dim + above the answer
228
251
  const queued = useRef("");
229
252
  const statusRef = useRef("idle");
230
- const setStat = (s) => { statusRef.current = s; setStatus(s); };
253
+ // Remote-control host (SPEC/remote-session.md): non-null only while /remotecontrol is active. Every
254
+ // state mutation below also mirrors to it so attached followers see identical transcript/tool/activity.
255
+ const remoteRef = useRef(null);
256
+ const setStat = (s) => { statusRef.current = s; setStatus(s); remoteRef.current?.setActivity(s); };
231
257
  const push = (e) => setEntries((prev) => [...prev, e]);
232
258
  const submitRef = useRef(() => { });
233
259
  // Backstop the slash-/ESC-quit paths: an ordinary terminal close or `kill` must still tear down any
@@ -276,6 +302,8 @@ function Root() {
276
302
  }, []);
277
303
  const sendTurn = useCallback(async (text) => {
278
304
  push({ kind: "message", message: { id: nextId(), role: "user", content: text } });
305
+ remoteRef.current?.userPrompt(text); // mirror to followers
306
+ remoteRef.current?.turnStart(); // allocate this turn's assistant id (stable stream→final)
279
307
  liveText.current = "";
280
308
  liveReasoning.current = "";
281
309
  setLive(null);
@@ -285,12 +313,13 @@ function Root() {
285
313
  setStat("thinking");
286
314
  try {
287
315
  const outcome = await session.send(text, {
288
- onRoute: (label, pct) => { setRoute(label); setCtxPct(pct); },
316
+ onRoute: (label, pct) => { setRoute(label); setCtxPct(pct); remoteRef.current?.setStatus(pct, label); },
289
317
  onDelta: (chunk) => {
290
318
  liveText.current += chunk;
291
319
  setLiveTok((t) => t + 1); // ≈1 token per streamed delta — batched with setLive, no extra render
292
320
  setStat("streaming");
293
321
  setLive({ kind: "message", message: { id: "live", role: "assistant", content: liveText.current, reasoning: liveReasoning.current || undefined } });
322
+ remoteRef.current?.streamAssistant(liveText.current, liveReasoning.current || undefined);
294
323
  },
295
324
  onReasoning: (chunk) => {
296
325
  // Thinking streams before/between content — accumulate it and show it dimmed in the live entry
@@ -301,6 +330,7 @@ function Root() {
301
330
  // counter + tok/s keep moving during a long thinking phase (they were frozen before content).
302
331
  setStat("thinking");
303
332
  setLive({ kind: "message", message: { id: "live", role: "assistant", content: liveText.current, reasoning: liveReasoning.current } });
333
+ remoteRef.current?.streamAssistant(liveText.current, liveReasoning.current || undefined);
304
334
  },
305
335
  onAutoContinue: (round) => {
306
336
  push({ kind: "message", message: { id: nextId(), role: "assistant", content: `↻ still working — auto-continuing past ${round} tool rounds`, reasoning: "" } });
@@ -320,6 +350,7 @@ function Root() {
320
350
  durationMs, summary: firstLine(ev.result),
321
351
  };
322
352
  push({ kind: "tool", step });
353
+ remoteRef.current?.toolStep(step);
323
354
  }
324
355
  liveText.current = "";
325
356
  liveReasoning.current = "";
@@ -329,6 +360,7 @@ function Root() {
329
360
  });
330
361
  if (outcome.interrupted) {
331
362
  push({ kind: "message", message: { id: nextId(), role: "assistant", content: "⎋ interrupted — output above kept" } });
363
+ remoteRef.current?.system("⎋ interrupted — output above kept");
332
364
  }
333
365
  else if (outcome.content.trim()) {
334
366
  // Keep the final answer's thinking (dim, above the answer), plus a dim note when generation was
@@ -340,6 +372,7 @@ function Root() {
340
372
  : undefined;
341
373
  const reasoning = [liveReasoning.current.trim(), stopNote].filter(Boolean).join("\n") || undefined;
342
374
  push({ kind: "message", message: { id: nextId(), role: "assistant", content: outcome.content, reasoning } });
375
+ remoteRef.current?.finalAssistant(outcome.content, reasoning);
343
376
  }
344
377
  // Surface the turn's real generation metrics in the status rule: tokens · gen tok/s · wall time.
345
378
  if (!outcome.interrupted && (outcome.tokens || outcome.durationMs)) {
@@ -368,6 +401,7 @@ function Root() {
368
401
  }, []);
369
402
  const sys = useCallback((text) => {
370
403
  push({ kind: "message", message: { id: nextId(), role: "system", content: text } });
404
+ remoteRef.current?.system(text);
371
405
  }, []);
372
406
  const handleSlash = useCallback(async (cmd) => {
373
407
  const [name, ...rest] = cmd.slice(1).split(/\s+/);
@@ -473,9 +507,39 @@ function Root() {
473
507
  sys(`spawned ${id} in the background — /bg to list · /bg stop ${id} to cancel`);
474
508
  }
475
509
  break;
510
+ case "remotecontrol":
511
+ case "remote": {
512
+ if (remoteRef.current) {
513
+ remoteRef.current.stop();
514
+ remoteRef.current = null;
515
+ sys("remote control stopped — followers detached");
516
+ break;
517
+ }
518
+ const { loadCredentials } = await import("./auth/store.js");
519
+ const creds = await loadCredentials().catch(() => null);
520
+ const token = process.env.KODE_OPERATOR_TOKEN || creds?.token || "";
521
+ const url = process.env.KODE_RELAY_URL || "wss://api.axe.onl/session/ws";
522
+ const rh = new RemoteHost(url, token, { title: `Operator · ${process.cwd().split("/").pop() || "session"}`, cwd: process.cwd(), host: hostname(), surface: "cli" }, {
523
+ onPrompt: (text) => submitRef.current(text), // follower drives a turn
524
+ onApprovalResponse: (id, approve) => settleApproval(id, approve), // first-wins with local
525
+ onInterrupt: () => s.interrupt(), // follower cancels the turn
526
+ onState: (st, detail) => {
527
+ if (st === "live")
528
+ sys(`✷ remote control LIVE — session ${rh.id} · attach from the app to drive it. /remotecontrol again to stop.`);
529
+ else if (st === "error")
530
+ sys(`remote control error: ${detail ?? "connection lost"} — /remotecontrol to retry`);
531
+ else if (st === "closed")
532
+ sys("remote control disconnected");
533
+ },
534
+ });
535
+ remoteRef.current = rh;
536
+ rh.connect();
537
+ sys(`connecting remote control → ${url} …`);
538
+ break;
539
+ }
476
540
  default: sys(`unknown command /${name} — try /help`);
477
541
  }
478
- }, [exit, sys, bg, authUser]);
542
+ }, [exit, sys, bg, authUser, approval, settleApproval]);
479
543
  const onSubmit = useCallback((text) => {
480
544
  const t = text.trim();
481
545
  if (t.startsWith("/")) {
@@ -519,14 +583,9 @@ function Root() {
519
583
  ? `${SPIN[Math.floor(elapsed * 4) % SPIN.length]} ${fmtMeta(elapsed, liveTok)}`
520
584
  : metrics;
521
585
  return (_jsx(App, { messages: entries, live: live, status: status, stepLabel: stepLabel, route: route, ctxPct: ctxPct, version: VERSION, metrics: liveMetrics, authUser: authUser, verbs: settings.verbs, bgAgents: bgAgents, onSubmit: onSubmit, onQueue: onQueue, onInterrupt: onInterrupt, approval: approval, onApprovalDecide: (allow, always) => {
522
- setApproval((cur) => {
523
- if (cur) {
524
- if (allow && always)
525
- alwaysAllowRef.current.add(cur.name);
526
- cur.resolve(allow);
527
- }
528
- return null;
529
- });
586
+ const cur = approval;
587
+ if (cur)
588
+ settleApproval(cur.id, allow, always); // first-wins with any remote follower answer
530
589
  } }));
531
590
  }
532
591
  // `operator auth …` runs as a plain CLI before the Ink shell — no TTY needed, so PAT login works
@@ -0,0 +1,172 @@
1
+ const V = 1;
2
+ export class RemoteHost {
3
+ url;
4
+ token;
5
+ meta;
6
+ cb;
7
+ ws = null;
8
+ seq = 0;
9
+ sessionId = null;
10
+ ownerSub = null;
11
+ closedByUs = false;
12
+ // Transcript mirror for late-joiner snapshots (upsert by id, same semantics followers use).
13
+ entries = [];
14
+ activity = "idle";
15
+ ctxPct = 0;
16
+ route = "aurora";
17
+ curAsstId = null; // per-turn assistant message id (stable across stream→final)
18
+ liveTimer = null;
19
+ livePending = null;
20
+ turnN = 0;
21
+ constructor(url, token, meta, cb) {
22
+ this.url = url;
23
+ this.token = token;
24
+ this.meta = meta;
25
+ this.cb = cb;
26
+ }
27
+ connect() {
28
+ this.cb.onState?.("connecting");
29
+ let ws;
30
+ try {
31
+ ws = new WebSocket(this.url);
32
+ }
33
+ catch (e) {
34
+ this.cb.onState?.("error", String(e));
35
+ return;
36
+ }
37
+ this.ws = ws;
38
+ ws.addEventListener("open", () => {
39
+ this.send("hello", null, { token: this.token, role: "host", sessionId: this.sessionId ?? undefined });
40
+ });
41
+ ws.addEventListener("message", (ev) => this.onMessage(String(ev.data)));
42
+ ws.addEventListener("close", () => { this.cb.onState?.(this.closedByUs ? "closed" : "error", this.closedByUs ? undefined : "relay closed"); });
43
+ ws.addEventListener("error", () => { this.cb.onState?.("error", "socket error"); });
44
+ }
45
+ get id() { return this.sessionId; }
46
+ get connected() { return !!this.ws && this.ws.readyState === 1; }
47
+ stop() {
48
+ this.closedByUs = true;
49
+ if (this.liveTimer) {
50
+ clearTimeout(this.liveTimer);
51
+ this.liveTimer = null;
52
+ }
53
+ try {
54
+ this.ws?.close();
55
+ }
56
+ catch { /* ignore */ }
57
+ this.ws = null;
58
+ }
59
+ onMessage(data) {
60
+ let f;
61
+ try {
62
+ f = JSON.parse(data);
63
+ }
64
+ catch {
65
+ return;
66
+ }
67
+ if (f.v !== V)
68
+ return;
69
+ switch (f.type) {
70
+ case "welcome":
71
+ this.sessionId = f.payload?.sessionId ?? this.sessionId;
72
+ this.ownerSub = f.payload?.ownerSub ?? null;
73
+ this.send("register", this.sessionId, { title: this.meta.title, surface: this.meta.surface ?? "cli", cwd: this.meta.cwd, host: this.meta.host });
74
+ this.cb.onState?.("live");
75
+ break;
76
+ case "attach": // a follower joined — send a full snapshot BEFORE any further delta (§8)
77
+ this.sendSnapshot();
78
+ break;
79
+ case "prompt":
80
+ if (typeof f.payload?.text === "string")
81
+ this.cb.onPrompt(f.payload.text);
82
+ break;
83
+ case "approval_response":
84
+ if (f.payload?.id)
85
+ this.cb.onApprovalResponse(String(f.payload.id), !!f.payload.approve);
86
+ break;
87
+ case "interrupt":
88
+ this.cb.onInterrupt();
89
+ break;
90
+ case "error":
91
+ this.cb.onState?.("error", f.payload?.message ?? f.payload?.code);
92
+ break;
93
+ }
94
+ }
95
+ send(type, sessionId, payload, seq = null) {
96
+ if (!this.ws || this.ws.readyState !== 1)
97
+ return;
98
+ const frame = { v: V, type, sessionId: sessionId ?? this.sessionId, seq, ts: Date.now(), payload };
99
+ try {
100
+ this.ws.send(JSON.stringify(frame));
101
+ }
102
+ catch { /* dropped; follower re-attaches on gap */ }
103
+ }
104
+ state(type, payload) { this.send(type, this.sessionId, payload, ++this.seq); }
105
+ sendSnapshot() {
106
+ this.flushLive();
107
+ this.send("snapshot", this.sessionId, { transcript: this.entries, activity: this.activity, status: { ctxPct: this.ctxPct, route: this.route } }, this.seq);
108
+ }
109
+ // ── mirror upserts ────────────────────────────────────────────────────────
110
+ upsertMessage(id, role, content, reasoning) {
111
+ const e = { kind: "message", message: { id, role, content, ...(reasoning ? { reasoning } : {}) } };
112
+ const i = this.entries.findIndex((x) => x.kind === "message" && x.message.id === id);
113
+ if (i >= 0)
114
+ this.entries[i] = e;
115
+ else
116
+ this.entries.push(e);
117
+ return e;
118
+ }
119
+ upsertTool(step) {
120
+ const e = { kind: "tool", step };
121
+ const i = this.entries.findIndex((x) => x.kind === "tool" && x.step.id === step.id);
122
+ if (i >= 0)
123
+ this.entries[i] = e;
124
+ else
125
+ this.entries.push(e);
126
+ return e;
127
+ }
128
+ // ── public turn-aware emitters (called from cli.tsx sendTurn) ──────────────
129
+ userPrompt(text) {
130
+ const e = this.upsertMessage("u" + (++this.turnN) + "_" + Date.now().toString(36), "user", text);
131
+ this.state("transcript", { entry: e });
132
+ }
133
+ turnStart() { this.curAsstId = "a" + this.turnN + "_" + Date.now().toString(36); }
134
+ /** streaming assistant content/reasoning — coalesced to ~one flush per 80ms (§8 flush-rate). */
135
+ streamAssistant(content, reasoning) {
136
+ if (!this.curAsstId)
137
+ this.turnStart();
138
+ this.livePending = { content, reasoning };
139
+ if (this.liveTimer)
140
+ return;
141
+ this.liveTimer = setTimeout(() => this.flushLive(), 80);
142
+ }
143
+ flushLive() {
144
+ if (this.liveTimer) {
145
+ clearTimeout(this.liveTimer);
146
+ this.liveTimer = null;
147
+ }
148
+ if (!this.livePending || !this.curAsstId)
149
+ return;
150
+ const { content, reasoning } = this.livePending;
151
+ this.livePending = null;
152
+ const e = this.upsertMessage(this.curAsstId, "assistant", content, reasoning);
153
+ this.state("transcript", { entry: e });
154
+ }
155
+ finalAssistant(content, reasoning) {
156
+ if (!this.curAsstId)
157
+ this.turnStart();
158
+ this.flushLive();
159
+ const e = this.upsertMessage(this.curAsstId, "assistant", content, reasoning);
160
+ this.state("transcript", { entry: e });
161
+ this.curAsstId = null;
162
+ }
163
+ system(content) {
164
+ const e = this.upsertMessage("s" + Date.now().toString(36) + Math.random().toString(36).slice(2, 6), "system", content);
165
+ this.state("transcript", { entry: e });
166
+ }
167
+ toolStep(step) { this.state("tool_step", { step: this.pickTool(step) }); }
168
+ pickTool(step) { this.upsertTool(step); return step; }
169
+ setActivity(state, label) { this.activity = state; this.state("activity", { state, ...(label ? { label } : {}) }); }
170
+ setStatus(ctxPct, route) { this.ctxPct = ctxPct; this.route = route; this.state("status", { ctxPct, route }); }
171
+ approvalRequest(id, tool, args) { this.state("approval_request", { id, tool, args }); }
172
+ }
@@ -270,10 +270,14 @@ async function webSearch(args) {
270
270
  // never yields "(no results)" when the other could answer.
271
271
  // SearXNG: an explicit KODE_SEARXNG_URL if reachable, else a container Operator stands up on demand
272
272
  // and tears down when idle / at exit (ensureSearxng handles both; null = unavailable here).
273
+ // Pin SearXNG to independent, non-Microsoft indexes by default (Brave + Mojeek are own-crawler; Google
274
+ // + Startpage are non-MS). Deliberately excludes Bing and DuckDuckGo (DDG is Bing-syndicated). Microsoft
275
+ // is only ever reached via the autopilot fallback below, and only when SearXNG is entirely unavailable.
276
+ const searxEngines = process.env.KODE_SEARXNG_ENGINES ?? "brave,mojeek,google,startpage";
273
277
  const searx = await ensureSearxng();
274
278
  if (searx) {
275
279
  try {
276
- const res = await fetch(`${searx.replace(/\/$/, "")}/search?q=${encodeURIComponent(q)}&format=json`, { signal: ctrl.signal, headers: { "User-Agent": "operator/kode-tsi" } });
280
+ const res = await fetch(`${searx.replace(/\/$/, "")}/search?q=${encodeURIComponent(q)}&format=json&engines=${encodeURIComponent(searxEngines)}`, { signal: ctrl.signal, headers: { "User-Agent": "operator/kode-tsi" } });
277
281
  if (res.ok) {
278
282
  const j = await res.json().catch(() => ({}));
279
283
  const rows = j.results ?? [];
@@ -568,12 +572,21 @@ const TOOLS = [
568
572
  },
569
573
  {
570
574
  name: "skill_fetch", safe: true,
571
- description: "Fetch one AXE skill by slug from the Operator registry (operator.axe.onl /v1/skills/{slug}) and return its instructions to follow. Read-only.",
575
+ description: "Fetch one AXE skill by name from the hub (or your profile) and return its full instructions to follow/apply. Checks your saved profile skills first, then the hub (operator.axe.onl/skills.axe.onl). Read-only.",
572
576
  parameters: { type: "object", properties: {
573
- slug: { type: "string", description: "the skill slug/name to fetch" },
577
+ slug: { type: "string", description: "the skill name/slug to fetch and use" },
574
578
  }, required: ["slug"] },
575
579
  run: (a) => skillFetch(str(a.slug)),
576
580
  },
581
+ {
582
+ name: "skill_save",
583
+ description: "Save a reusable skill to your profile so it persists and is available next session with no settings edit — auto-harvest a new capability. Saved skills are listed by skill_list and loaded by skill_fetch (profile skills take precedence over the hub). Use when you've worked out a repeatable playbook worth keeping.",
584
+ parameters: { type: "object", properties: {
585
+ name: { type: "string", description: "short skill name (kebab-cased automatically)" },
586
+ content: { type: "string", description: "the skill instructions/playbook (skillmd or plain markdown)" },
587
+ }, required: ["name", "content"] },
588
+ run: (a) => skillSave(str(a.name), str(a.content)),
589
+ },
577
590
  ];
578
591
  // AXE skill registry (parity with the Python core): a REMOTE HTTPS registry reachable from every surface
579
592
  // (CLI/web/mobile), so skills work everywhere without local fleet access. Bearer from OPERATOR_TOKEN or
@@ -615,18 +628,95 @@ async function operatorGet(path) {
615
628
  return null;
616
629
  }
617
630
  async function skillList(query) {
618
- const r = await operatorGet(`/v1/skills${query ? `?q=${encodeURIComponent(query)}` : ""}`);
619
- if (r === null)
620
- return "error: skill registry unreachable (operator.axe.onl / skills.axe.onl)";
621
- return JSON.stringify(r).slice(0, 8000);
631
+ // Prefer the ranked /search when a query is given; fall back to the full list.
632
+ const local = await localSkills();
633
+ const localBlock = local.length ? `your profile skills:\n${local.map((l) => `• ${l.name} (profile)`).join("\n")}\n\n` : "";
634
+ const path = query ? `/v1/skills/search?q=${encodeURIComponent(query)}` : "/v1/skills";
635
+ const r = (await operatorGet(path)) ?? (query ? await operatorGet("/v1/skills") : null);
636
+ if (r === null) {
637
+ return localBlock ? `${localBlock}(hub unreachable — showing profile skills only)` : "error: skill registry unreachable (operator.axe.onl / skills.axe.onl)";
638
+ }
639
+ const arr = Array.isArray(r) ? r : r.results ?? r.skills ?? [];
640
+ if (!Array.isArray(arr) || arr.length === 0)
641
+ return `${localBlock}${query ? `no hub skills match "${query}"` : "no skills in the hub yet"}`;
642
+ // Compact one-line-per-skill: name — description (from the skillmd metadata).
643
+ const lines = arr.slice(0, 40).map((s) => {
644
+ const desc = s?.metadata?.taxonomy?.description ?? s?.metadata?.description ?? s?.description ?? "";
645
+ return `• ${s?.name ?? "?"}${desc ? ` — ${String(desc).replace(/\s+/g, " ").slice(0, 140)}` : ""}`;
646
+ });
647
+ return `${localBlock}${arr.length} hub skill${arr.length === 1 ? "" : "s"} (skill_fetch <name> to use one):\n${lines.join("\n")}`;
622
648
  }
623
649
  async function skillFetch(slug) {
624
650
  if (!slug)
625
- return "error: skill_fetch needs a slug";
651
+ return "error: skill_fetch needs a slug (name)";
652
+ // Personal profile skills win over the hub (a user's own saved version is
653
+ // theirs to trust), and work even when the hub is unreachable.
654
+ for (const ls of await localSkills()) {
655
+ if (ls.name === slug || ls.name === slugify(slug)) {
656
+ try {
657
+ const { readFile } = await nodeImport("node:fs/promises");
658
+ return `# skill: ${ls.name} (profile)\n\n${await readFile(ls.file, "utf8")}`.slice(0, 24000);
659
+ }
660
+ catch { /* fall through to hub */ }
661
+ }
662
+ }
626
663
  const r = await operatorGet(`/v1/skills/${encodeURIComponent(slug)}`);
627
664
  if (r === null)
628
665
  return `error: skill '${slug}' unreachable or not found`;
629
- return typeof r === "string" ? r : JSON.stringify(r).slice(0, 16000);
666
+ if (typeof r === "string")
667
+ return r;
668
+ // The hub returns the full skillmd in `content` — that's the usable instruction
669
+ // set. Return it directly (with a short provenance header) so the model can
670
+ // apply the skill, rather than dumping the metadata JSON.
671
+ const o = r;
672
+ if (o.content)
673
+ return `# skill: ${o.name ?? slug}${o.version ? ` v${o.version}` : ""}\n\n${o.content}`.slice(0, 24000);
674
+ return JSON.stringify(r).slice(0, 16000);
675
+ }
676
+ // Save a skill to the user's local profile so it persists + is reusable next
677
+ // session without any settings edit. This is the "profile skills" A/B against
678
+ // hub-only: local skills live at ~/.axe/operator/skills/<name>.md and are listed
679
+ // by skill_list alongside the hub. (Contributing to the shared hub needs the hub
680
+ // write endpoint — separate; this is the always-available personal path.)
681
+ function slugify(s) {
682
+ return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 64) || "skill";
683
+ }
684
+ async function localSkillsDir() {
685
+ const { homedir } = await nodeImport("node:os");
686
+ const { join } = await nodeImport("node:path");
687
+ return join(homedir(), ".axe", "operator", "skills");
688
+ }
689
+ async function skillSave(name, content) {
690
+ if (!name || !content)
691
+ return "error: skill_save needs name and content";
692
+ try {
693
+ const { mkdir, writeFile } = await nodeImport("node:fs/promises");
694
+ const { join } = await nodeImport("node:path");
695
+ const dir = await localSkillsDir();
696
+ await mkdir(dir, { recursive: true });
697
+ const file = join(dir, `${slugify(name)}.md`);
698
+ // Stamp skillmd frontmatter if the content doesn't already carry it.
699
+ const body = content.trimStart().startsWith("---")
700
+ ? content
701
+ : `---\nname: ${slugify(name)}\nsource: profile\n---\n\n${content}`;
702
+ await writeFile(file, body, "utf8");
703
+ return `saved skill '${slugify(name)}' to your profile (${file}) — reusable next session; skill_fetch ${slugify(name)} to load it.`;
704
+ }
705
+ catch (e) {
706
+ return `error saving skill: ${e.message}`;
707
+ }
708
+ }
709
+ async function localSkills() {
710
+ try {
711
+ const { readdir } = await nodeImport("node:fs/promises");
712
+ const { join } = await nodeImport("node:path");
713
+ const dir = await localSkillsDir();
714
+ const files = (await readdir(dir).catch(() => []));
715
+ return files.filter((f) => f.endsWith(".md")).map((f) => ({ name: f.replace(/\.md$/, ""), file: join(dir, f) }));
716
+ }
717
+ catch {
718
+ return [];
719
+ }
630
720
  }
631
721
  export const registry = new Map(TOOLS.map(t => [t.name, t]));
632
722
  export function toSchemas(reg = registry) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0perator/operator",
3
- "version": "0.1.24",
3
+ "version": "0.1.26",
4
4
  "description": "Operator (KODE) — TypeScript + Ink terminal coding agent. Full-frame render, single-engine core shared across CLI/web/mobile; runs against a local Aurora model.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -25,7 +25,8 @@
25
25
  "dependencies": {
26
26
  "chalk": "^5.6.2",
27
27
  "ink": "^5.0.1",
28
- "react": "^18.3.1"
28
+ "react": "^18.3.1",
29
+ "ws": "^8.18.0"
29
30
  },
30
31
  "devDependencies": {
31
32
  "@types/node": "^22.20.3",