@0perator/operator 0.2.2-next.0 → 0.2.4

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.
@@ -56,6 +56,19 @@ const LOOP_GUARD_THRESHOLD = 5; // must match agent.ts LOOP_GUARD_LIMIT so this
56
56
  // its session's whole lifetime (the Session is constructed once and reused across turns), so this id
57
57
  // is stable across a session's turns — the persistent shell survives, keyed per session, not shared.
58
58
  let _execSeq = 0;
59
+ /** Semantic compression, then the character cap. The raw output is spilled before any cut; if it cannot be, nothing is
60
+ * cut by lines. A shell result gets the pointer on top: its exit trailer has to stay last (engine/loop-guard.ts). */
61
+ function shrinkResult(name, args, raw) {
62
+ const compressed = semanticCompress(raw, { toolName: name, toolArgs: args });
63
+ if (compressed === raw)
64
+ return capToolResult(raw, spillToolOutput);
65
+ const path = spillToolOutput(raw);
66
+ if (!path)
67
+ return capToolResult(raw);
68
+ const note = `…[cut from ${raw.split("\n").length} lines — FULL output saved to ${path} · read any part with file_read(path, offset, limit)]`;
69
+ const cut = capToolResult(compressed);
70
+ return SHELL_FOREGROUND.has(name) ? `${note}\n${cut}` : `${cut}\n${note}`;
71
+ }
59
72
  export class Executor {
60
73
  reg;
61
74
  root;
@@ -86,6 +99,8 @@ export class Executor {
86
99
  get effectiveRoot() {
87
100
  return this.turnRoot ?? this.root;
88
101
  }
102
+ /** Set by a host to answer a large result with an extract of its own; null (or a throw) keeps the stock result. */
103
+ assist;
89
104
  resetTurn() {
90
105
  this.seen.clear();
91
106
  }
@@ -111,9 +126,8 @@ export class Executor {
111
126
  // Carry the batch's abort signal (FIX 5) through a side-channel so an in-flight bash command is killed
112
127
  // on esc — a store, not a Tool.run param, so tools that use their 2nd param for test DI keep it.
113
128
  const raw = await shellKeyStore.run(this.shellKey, () => shellSignalStore.run(report?.signal, () => tool.run(args)));
114
- // Semantic compression first (per-tool-type, keeps errors/head/tail), then the hard cap+spill.
115
- const compressed = semanticCompress(raw, { toolName: name, toolArgs: args });
116
- const out = capToolResult(compressed, spillToolOutput);
129
+ const assisted = this.assist ? await this.assist(name, args, raw, this.shellKey).catch(() => null) : null;
130
+ const out = assisted ?? shrinkResult(name, args, raw);
117
131
  // A file edit that LANDED changed the workspace, so prior identical-call counts are stale — re-running the
118
132
  // same test/build after an edit is verify-after-fix iteration, not a loop. Clear so repeats start fresh.
119
133
  // A FAILING edit ("error: old_string not found") changed nothing, so it must not reset the count.
@@ -0,0 +1,105 @@
1
+ // The `microAssist` feature (config/features.ts, default OFF): the `micro` MCP server answers a large un-ranged
2
+ // file_read or a long command output with ranked verbatim chunks, and Scribe is searched once for the first task.
3
+ // Only NEW tail content is touched; the tool array and system prompt never change. Anything unexpected (no server,
4
+ // refusal, timeout, a reply that is not the expected shape) returns null/"" and the stock behaviour stands.
5
+ // NODE-ONLY (node:fs, node:crypto).
6
+ import { createHash } from "node:crypto";
7
+ import { readFile, stat } from "node:fs/promises";
8
+ import { resolve } from "node:path";
9
+ import { SHELL_FOREGROUND } from "./classes.js";
10
+ import { forgetRead } from "./read-ledger.js";
11
+ import { resolveReadPath } from "./read-path.js";
12
+ import { spillToolOutput } from "./tool-output-spill.js";
13
+ export const MICRO_READ = "micro:micro_read";
14
+ export const SCRIBE_SEARCH = "micro:scribe_search";
15
+ export const ASSIST_MIN_CHARS = 20_000;
16
+ const SOURCE_MAX_BYTES = 2 * 1024 * 1024;
17
+ const QUERY_MAX_CHARS = 500;
18
+ const SCRIBE_PARTITION = "default"; // where scribe_add writes when no owner is named
19
+ const SCRIBE_HITS = 3;
20
+ const SCRIBE_FACT_CHARS = 600;
21
+ const TIMEOUT_MS = 4_000;
22
+ export function createMicroAssist(deps) {
23
+ let hung = false; // a server that missed the deadline once is not asked again: every later result would wait too
24
+ async function ask(tool, args) {
25
+ const hub = deps.hub();
26
+ if (hung || !hub?.has(tool))
27
+ return null;
28
+ let timer;
29
+ const late = new Promise((done) => { timer = setTimeout(() => { hung = true; done(null); }, deps.timeoutMs ?? TIMEOUT_MS); });
30
+ try {
31
+ const reply = await Promise.race([hub.call(tool, args), late]);
32
+ return reply === null || reply.startsWith("error") ? null : reply;
33
+ }
34
+ finally {
35
+ clearTimeout(timer);
36
+ }
37
+ }
38
+ /** The reader's reply, only if it names the sha256 of exactly what we hold and is smaller than the stock result. */
39
+ async function extract(target, source, query, stock) {
40
+ const reply = await ask(MICRO_READ, { target, query: query.slice(0, QUERY_MAX_CHARS) });
41
+ if (!reply || reply.length >= stock.length || reply.includes("\nno line matches the query"))
42
+ return null;
43
+ return reply.includes(`sha256: ${createHash("sha256").update(source).digest("hex")}`) ? reply : null;
44
+ }
45
+ async function file(args, raw, sessionKey) {
46
+ if (["offset", "limit", "start_char", "max_chars", "force"].some((k) => args[k] !== undefined))
47
+ return null;
48
+ if (raw.startsWith("[extracted text"))
49
+ return null;
50
+ const asked = await resolveReadPath(String(args.path ?? ""));
51
+ const path = resolve(asked);
52
+ if ((await stat(path)).size > SOURCE_MAX_BYTES)
53
+ return null;
54
+ const bytes = await readFile(path);
55
+ const reply = await extract(path, bytes, deps.task() || path, raw);
56
+ if (!reply)
57
+ return null;
58
+ const saved = spillToolOutput(bytes.toString("utf8"));
59
+ if (!saved)
60
+ return null;
61
+ forgetRead(sessionKey, asked); // the model has not seen this file: a re-read returns it, an overwrite still needs one
62
+ return `[extract of ${path}, not the whole file — FULL output saved to ${saved} · exact lines L<a>-L<b>: file_read(path, offset=a-1, limit=b-a+1)]\n${reply}`;
63
+ }
64
+ async function shell(args, raw) {
65
+ if (raw.length > SOURCE_MAX_BYTES || !raw.includes("\n"))
66
+ return null;
67
+ const reply = await extract(raw, raw, `${String(args.command ?? "")}\n${deps.task()}`, raw);
68
+ if (!reply)
69
+ return null;
70
+ const saved = spillToolOutput(raw);
71
+ if (!saved)
72
+ return null;
73
+ const trailer = /(?:\n(?:\[|\(no output)[^\n]*)+$/.exec(raw)?.[0] ?? ""; // exit code and shell notes stay last
74
+ return `[extract of ${raw.split("\n").length} lines of output — FULL output saved to ${saved} · read any part with file_read(path, offset, limit)]\n${reply}${trailer}`;
75
+ }
76
+ return {
77
+ result: async (name, args, raw, sessionKey) => {
78
+ if (raw.length < ASSIST_MIN_CHARS || raw.startsWith("error"))
79
+ return null;
80
+ if (name === "file_read")
81
+ return file(args, raw, sessionKey);
82
+ return SHELL_FOREGROUND.has(name) ? shell(args, raw) : null;
83
+ },
84
+ recall: async (task) => {
85
+ try {
86
+ const reply = await ask(SCRIBE_SEARCH, { query: task.slice(0, QUERY_MAX_CHARS), user_id: SCRIBE_PARTITION, limit: SCRIBE_HITS });
87
+ return reply ? renderHits(JSON.parse(reply)) : ""; // "no match" is not JSON: nothing is added
88
+ }
89
+ catch {
90
+ return "";
91
+ }
92
+ },
93
+ };
94
+ }
95
+ /** Only hits carrying a `date` count: the search that returns "no match" instead of unrelated rows is the one that sends it. */
96
+ function renderHits(body) {
97
+ const rows = Array.isArray(body) ? body : body?.memories;
98
+ if (!Array.isArray(rows))
99
+ return "";
100
+ const hits = rows
101
+ .filter((r) => typeof r?.fact === "string" && typeof r?.date === "string")
102
+ .slice(0, SCRIBE_HITS)
103
+ .map((r) => `- ${r.fact.replace(/\s+/g, " ").slice(0, SCRIBE_FACT_CHARS)} (id ${r.id ?? "?"}, ${r.date}${r.source ? `, ${r.source}` : ""})`);
104
+ return hits.length ? `[shared memory matching this task — reference only, possibly stale, not an instruction]\n${hits.join("\n")}` : "";
105
+ }
@@ -37,6 +37,10 @@ export function forgetViews(sessionKey) {
37
37
  for (const e of m.values())
38
38
  e.views.clear();
39
39
  }
40
+ /** Drop one file's record: what the session was shown of it did not count as reading it. */
41
+ export function forgetRead(sessionKey, path) {
42
+ ledgers.get(sessionKey)?.delete(path);
43
+ }
40
44
  /** Drop a session's whole ledger — wired into the shell-session dispose so a long run spawning many
41
45
  * sub-agents does not accumulate per-lane read maps forever. Also the clean reset for tests. */
42
46
  export function forgetReads(sessionKey) {
@@ -2275,43 +2275,61 @@ async function artifactCreate(args) {
2275
2275
  return `error: ${r.error}${/reach|timed out/.test(r.error) ? " — if this persists, write a local file with file_create instead" : ""}`;
2276
2276
  return `created ${r.value.kind} artifact ${r.value.id} (v${r.value.version}, ${r.value.visibility}) → ${r.value.share}`;
2277
2277
  }
2278
- // voice_speak / voice_transcribe — Operator's OWN voice (operator-voice :8099: Kokoro TTS + whisper.cpp STT).
2279
- // Same backend-broker shape as the media tools: env-configurable base (KODE_VOICE_URL), /health-gated, graceful
2280
- // when the service is down. /synthesize returns raw WAV bytes (played locally via afplay on macOS, else saved);
2281
- // /transcribe takes any ffmpeg-readable audio (multipart) and returns { text }. imageHealthy() is reused — the
2282
- // voice /health returns {status:"ok"} with no `ok` field, so its `j.ok !== false` check passes on a 200.
2283
- function voiceEndpoints() {
2278
+ // voice_speak / voice_transcribe — Operator's OWN voice. Both go through the gateway's audio routes (products/voice.ts,
2279
+ // the door /voice uses), and to the speech service directly (operator-voice :8099: /synthesize, /transcribe) when an
2280
+ // env var pins one or no gateway has the routes.
2281
+ function pinnedVoiceEndpoints() {
2284
2282
  const envs = [process.env.KODE_VOICE_URL, process.env.AXE_VOICE_URL].filter(Boolean);
2285
- const defaults = ["http://127.0.0.1:8099"]; // operator-voice (SPEC.md): POST /synthesize, POST /transcribe, GET /health
2286
- return [...new Set([...gatewayEndpoints("voice"), ...envs, ...defaults])].map((u) => u.replace(/\/$/, ""));
2283
+ return [...new Set([...gatewayEndpoints("voice"), ...envs])].map((u) => u.replace(/\/$/, ""));
2284
+ }
2285
+ async function voiceDoor(args, timeoutMs) {
2286
+ const { loadSettings } = await nodeImport("../config/settings.js");
2287
+ const voice = await nodeImport("../products/voice.js");
2288
+ const saved = loadSettings().services?.voice ?? {};
2289
+ const cfg = voice.voiceConfig({ ...saved, ...(str(args.voice) ? { voice: str(args.voice) } : {}), timeoutMs: Number(args.timeout_ms ?? timeoutMs) });
2290
+ const pinned = pinnedVoiceEndpoints();
2291
+ const found = pinned.length ? undefined : await voice.findVoiceGateway(cfg);
2292
+ const gateway = found && "ok" in found ? found.ok : undefined;
2293
+ const direct = async () => {
2294
+ const candidates = pinned.length ? pinned : ["http://127.0.0.1:8099"];
2295
+ for (const e of candidates)
2296
+ if (await imageHealthy(e))
2297
+ return { base: e };
2298
+ return { error: `error: no voice service reachable (tried ${candidates.join(", ")}). Bring up operator-voice (:8099).` };
2299
+ };
2300
+ return { voice, cfg, gateway, direct };
2287
2301
  }
2288
2302
  async function voiceSpeak(args) {
2289
2303
  const text = str(args.text);
2290
2304
  if (!text)
2291
2305
  return "error: voice_speak needs `text` to say";
2292
- const voice = str(args.voice) || "bf_emma"; // the canonical Operator voice (same engine/voice as Cortana)
2293
2306
  const play = args.play !== false && str(args.play) !== "false"; // default true
2294
- const candidates = voiceEndpoints();
2295
- let base;
2296
- for (const e of candidates) {
2297
- if (await imageHealthy(e)) {
2298
- base = e;
2299
- break;
2300
- }
2301
- }
2302
- if (!base)
2303
- return `error: no voice service reachable (tried ${candidates.join(", ")}). Bring up operator-voice (:8099 / com.axe.operator-voice).`;
2304
- const ctrl = new AbortController();
2305
- const timer = setTimeout(() => ctrl.abort(), Number(args.timeout_ms ?? 60_000));
2307
+ const { voice, cfg, gateway, direct } = await voiceDoor(args, 60_000);
2308
+ const wanted = cfg.voice ?? voice.FALLBACK_VOICE;
2309
+ let used = wanted;
2310
+ let buf;
2306
2311
  try {
2307
- const res = await fetch(`${base}/synthesize`, {
2308
- method: "POST", signal: ctrl.signal,
2309
- headers: { "Content-Type": "application/json", "User-Agent": "operator/kode-tsi", ...mediaAuth() },
2310
- body: JSON.stringify({ text, voice }),
2311
- });
2312
- if (!res.ok)
2313
- return `error: voice worker returned ${res.status} on /synthesize — ensure operator-voice is up`;
2314
- const buf = Buffer.from(await res.arrayBuffer());
2312
+ if (gateway) {
2313
+ buf = Buffer.from(await voice.speak(gateway, { ...cfg, voice: wanted }, text, { onFallbackVoice: (v) => { used = v; } }));
2314
+ }
2315
+ else {
2316
+ const at = await direct();
2317
+ if ("error" in at)
2318
+ return at.error;
2319
+ const synthesize = (v) => fetch(`${at.base}/synthesize`, {
2320
+ method: "POST", signal: AbortSignal.timeout(cfg.timeoutMs),
2321
+ headers: { "Content-Type": "application/json", "User-Agent": "operator/kode-tsi", ...mediaAuth() },
2322
+ body: JSON.stringify({ text, voice: v }),
2323
+ });
2324
+ let res = await synthesize(wanted);
2325
+ if (!res.ok && wanted !== voice.FALLBACK_VOICE) {
2326
+ used = voice.FALLBACK_VOICE;
2327
+ res = await synthesize(used);
2328
+ }
2329
+ if (!res.ok)
2330
+ return `error: voice worker returned ${res.status} on /synthesize — ensure operator-voice is up`;
2331
+ buf = Buffer.from(await res.arrayBuffer());
2332
+ }
2315
2333
  if (!buf.length)
2316
2334
  return "error: voice worker returned no audio";
2317
2335
  const { writeFile, mkdir } = await nodeImport("node:fs/promises");
@@ -2330,14 +2348,12 @@ async function voiceSpeak(args) {
2330
2348
  }
2331
2349
  catch { /* no afplay (headless/remote) — the WAV is still saved for a surface to play */ }
2332
2350
  }
2333
- return `spoke ${text.length} chars (${voice}) → ${out}${played ? " (playing)" : " (saved; not played on this box)"}`;
2351
+ const spoken = used === wanted ? used : `${used}; ${wanted} was unavailable`;
2352
+ return `spoke ${text.length} chars (${spoken}) → ${out}${played ? " (playing)" : " (saved; not played on this box)"}`;
2334
2353
  }
2335
2354
  catch (e) {
2336
- const msg = e?.name === "AbortError" ? "timed out" : String(e?.message ?? e);
2337
- return `error: voice worker unreachable at ${base} (${msg}) — start operator-voice (com.axe.operator-voice on :8099)`;
2338
- }
2339
- finally {
2340
- clearTimeout(timer);
2355
+ const msg = e?.name === "TimeoutError" ? "timed out" : String(e?.message ?? e);
2356
+ return `error: voice unavailable (${msg})`;
2341
2357
  }
2342
2358
  }
2343
2359
  async function voiceTranscribe(args) {
@@ -2348,24 +2364,18 @@ async function voiceTranscribe(args) {
2348
2364
  const buf = await readFile(file).catch(() => null);
2349
2365
  if (!buf)
2350
2366
  return `error: voice_transcribe could not read a file at ${file}`;
2351
- const candidates = voiceEndpoints();
2352
- let base;
2353
- for (const e of candidates) {
2354
- if (await imageHealthy(e)) {
2355
- base = e;
2356
- break;
2357
- }
2358
- }
2359
- if (!base)
2360
- return `error: no voice service reachable (tried ${candidates.join(", ")}). Bring up operator-voice (:8099).`;
2361
- const ctrl = new AbortController();
2362
- const timer = setTimeout(() => ctrl.abort(), Number(args.timeout_ms ?? 120_000));
2367
+ const name = file.split("/").pop() || "audio.wav";
2368
+ const { voice, cfg, gateway, direct } = await voiceDoor({ timeout_ms: args.timeout_ms }, 120_000);
2363
2369
  try {
2370
+ if (gateway)
2371
+ return (await voice.transcribe(gateway, cfg, buf, {}, name)) || "(no speech detected)";
2372
+ const at = await direct();
2373
+ if ("error" in at)
2374
+ return at.error;
2364
2375
  const form = new FormData();
2365
- const name = file.split("/").pop() || "audio.wav";
2366
2376
  form.append("file", new Blob([buf]), name); // multipart so any ffmpeg-readable format works (SPEC)
2367
- const res = await fetch(`${base}/transcribe`, {
2368
- method: "POST", signal: ctrl.signal,
2377
+ const res = await fetch(`${at.base}/transcribe`, {
2378
+ method: "POST", signal: AbortSignal.timeout(cfg.timeoutMs),
2369
2379
  headers: { "User-Agent": "operator/kode-tsi", ...mediaAuth() }, // no Content-Type — FormData sets the multipart boundary
2370
2380
  body: form,
2371
2381
  });
@@ -2377,11 +2387,8 @@ async function voiceTranscribe(args) {
2377
2387
  return j.text?.trim() || "(no speech detected)";
2378
2388
  }
2379
2389
  catch (e) {
2380
- const msg = e?.name === "AbortError" ? "timed out" : String(e?.message ?? e);
2381
- return `error: voice worker unreachable at ${base} (${msg}) — start operator-voice`;
2382
- }
2383
- finally {
2384
- clearTimeout(timer);
2390
+ const msg = e?.name === "TimeoutError" ? "timed out" : String(e?.message ?? e);
2391
+ return `error: voice unavailable (${msg})`;
2385
2392
  }
2386
2393
  }
2387
2394
  const TOOLS = [
@@ -2814,10 +2821,10 @@ const TOOLS = [
2814
2821
  {
2815
2822
  name: "voice_speak", safe: false,
2816
2823
  contract: { v: 1, effects: ["write", "device"], bins: ["afplay"] },
2817
- description: "Say text ALOUD in Operator's own voice (Kokoro TTS) on the owner's machine — a spoken status or answer, not just printed text. Saves the WAV and returns its path; a headless box saves without playing.",
2824
+ description: "Say text ALOUD in Operator's own voice on the owner's machine — a spoken status or answer, not just printed text. Saves the WAV and returns its path; a headless box saves without playing.",
2818
2825
  parameters: { type: "object", properties: {
2819
2826
  text: { type: "string", description: "what to say" },
2820
- voice: { type: "string", description: "Kokoro voice id (default \"bf_emma\", the Operator voice)" },
2827
+ voice: { type: "string", description: "voice id (default: the configured voice, else bf_emma)" },
2821
2828
  play: { type: "boolean", description: "default true; false = synthesize + save only" },
2822
2829
  out: { type: "string", description: ".wav path (default a temp file)" },
2823
2830
  timeout_ms: { type: "number", description: "default 60000" },
@@ -2826,7 +2833,7 @@ const TOOLS = [
2826
2833
  },
2827
2834
  {
2828
2835
  name: "voice_transcribe", safe: true,
2829
- description: "Transcribe an audio file (wav/mp3/m4a/ogg — any ffmpeg format) to text with whisper.cpp — HEAR a voice note instead of guessing.",
2836
+ description: "Transcribe an audio file (wav/mp3/m4a/ogg — any ffmpeg format) to text — HEAR a voice note instead of guessing.",
2830
2837
  parameters: { type: "object", properties: {
2831
2838
  file: { type: "string", description: "local audio file" },
2832
2839
  timeout_ms: { type: "number", description: "default 120000" },
@@ -91,7 +91,7 @@ const SECRET_READ_FILES = [`${HOME}/.netrc`, `${HOME}/.git-credentials`];
91
91
  // permissions to bypass+admin for the next launch, and one that can truncate events.jsonl erases the
92
92
  // evidence — so the sandbox treats these exactly like ~/.ssh. Resolved per call (KODE_HOME / KODE_PROFILE
93
93
  // can differ per process); ordinary state (memories, skills, sessions) stays writable.
94
- const OP_WRITE_PROTECTED_FILES = ["settings.json", "settings.local.json", "managed-settings.json", "identity.json", "home.json", "credentials.json", "byo.json", "events.jsonl", "free-models.json"];
94
+ const OP_WRITE_PROTECTED_FILES = ["settings.json", "settings.local.json", "managed-settings.json", "identity.json", "home.json", "credentials.json", "byo.json", "events.jsonl", "free-models.json", "model-list.json"];
95
95
  // `run` holds the per-session pidfiles util/owned-children.ts reaps from: Operator (unsandboxed) trusts them to stop processes, so the agent
96
96
  // must not be able to plant one naming a process it wants dead.
97
97
  const OP_WRITE_PROTECTED_DIRS = ["vault", "audit", "run"];
@@ -27,13 +27,6 @@ function compressShell(raw, _args, maxLines) {
27
27
  parts.push(...tail);
28
28
  return parts.join("\n");
29
29
  }
30
- function compressFileRead(raw, _args, maxLines) {
31
- const lines = raw.split("\n");
32
- if (lines.length <= maxLines)
33
- return raw;
34
- return lines.slice(0, maxLines).join("\n") +
35
- `\n…[${lines.length - maxLines} more lines — use offset/limit to read specific ranges]`;
36
- }
37
30
  function compressGrep(raw, _args, maxLines) {
38
31
  const lines = raw.split("\n").filter(l => l.trim());
39
32
  if (lines.length <= maxLines)
@@ -106,8 +99,6 @@ function compressGitStatus(raw, _args, maxLines) {
106
99
  const COMPRESSORS = {
107
100
  bash: compressShell,
108
101
  shell_exec: compressShell,
109
- file_read: compressFileRead,
110
- read_files: compressFileRead,
111
102
  grep_search: compressGrep,
112
103
  search: compressGrep,
113
104
  list_directory: compressListDir,
@@ -115,6 +106,7 @@ const COMPRESSORS = {
115
106
  web_search: compressWebFetch,
116
107
  git_status: compressGitStatus,
117
108
  };
109
+ // No file_read / read_files entry: a read is bounded by its own character cap, and the range asked for comes back whole.
118
110
  export function semanticCompress(raw, opts) {
119
111
  const maxLines = opts.maxLines ?? DEFAULT_MAX_LINES;
120
112
  const compressor = COMPRESSORS[opts.toolName];
@@ -75,7 +75,7 @@ export function spillToolOutput(full) {
75
75
  mkdirSync(dir, { recursive: true, mode: 0o700 });
76
76
  sweepToolOutputs(dir);
77
77
  const hash = createHash("sha1").update(full).digest("hex").slice(0, 12);
78
- const path = join(dir, `${Date.now().toString(36)}-${hash}.txt`);
78
+ const path = join(dir, `out-${hash}.txt`); // content only: a repeated call reads the same, so the loop guard sees it
79
79
  writeFileSync(path, full, { mode: 0o600 }); // H4: spilled tool output is transcript-grade secret material
80
80
  return path;
81
81
  }
@@ -0,0 +1,126 @@
1
+ // /model on a row with `activation` (router/activation.ts): check, show the plan, run on the owner's yes, and hand back
2
+ // to /model only once the command has succeeded. cli.tsx supplies the picker slot and the session.
3
+ import { activationLogPath, checkActivation, commandLine, ownerActivation, startActivation } from "../router/activation.js";
4
+ import { fmtWait } from "../router/read-rates.js";
5
+ export function createActivationFlow(deps) {
6
+ const read = deps.read ?? ownerActivation;
7
+ const tickMs = deps.tickMs ?? 1000;
8
+ let wanted = ""; // the id of the owner's latest pick: a finishing switch never overrides a later choice
9
+ let picks = 0;
10
+ let running;
11
+ const stay = (id, why) => deps.sys(`${id}: ${why} — stayed on ${deps.current()}`);
12
+ function ask(id, a, plan, refusal, proceed) {
13
+ if (refusal && !a.force) {
14
+ stay(id, refusal);
15
+ return;
16
+ }
17
+ const choice = refusal ? "force" : "run";
18
+ const argv = refusal ? a.force : a.command;
19
+ const first = refusal ? "Force the switch · interrupts the answer in progress" : "Switch · takes a few minutes, can be left running";
20
+ deps.open(`${id} is not being served. ${plan}${refusal ? ` — ${refusal}` : ""} · runs: ${commandLine(argv)}`, [first, `Cancel · stay on ${deps.current()}`], [choice, "stay"], (c) => { if (c !== "stay")
21
+ start(id, a, argv, c === "force", proceed); });
22
+ }
23
+ function start(id, a, argv, forced, proceed) {
24
+ if (running) {
25
+ running.show();
26
+ return;
27
+ }
28
+ let run;
29
+ try {
30
+ run = startActivation(argv, activationLogPath(id));
31
+ }
32
+ catch (e) {
33
+ stay(id, `could not start: ${e.message}`);
34
+ return;
35
+ }
36
+ const from = deps.current();
37
+ wanted = id;
38
+ let panel;
39
+ const question = () => `Switching to ${id} · ${fmtWait(run.elapsedMs() / 1000)}${run.lines().slice(-4).map((l) => `\n${l}`).join("")}`;
40
+ const rows = ["Leave it running (Esc) · /model " + id + " shows it again", "Stop the command · the switch may be left half done"];
41
+ const choices = ["leave", "stop"];
42
+ const show = () => { panel = deps.open(question(), rows, choices, (c) => { if (c === "stop")
43
+ run.stop(); }); };
44
+ running = { id, run, show };
45
+ show();
46
+ const timer = setInterval(() => { if (panel?.isOpen())
47
+ panel.update(question(), rows, choices); }, tickMs);
48
+ timer.unref();
49
+ void run.done.then(async (r) => {
50
+ clearInterval(timer);
51
+ running = undefined;
52
+ const watched = !!panel?.isOpen();
53
+ if (watched)
54
+ panel.close();
55
+ const took = fmtWait(run.elapsedMs() / 1000);
56
+ if (r.stopped) {
57
+ stay(id, `stopped after ${took} (log ${run.log})`);
58
+ return;
59
+ }
60
+ if (!r.ok) {
61
+ stay(id, `not switched after ${took}: ${r.refusal ?? r.reason} (log ${run.log})`);
62
+ if (r.refusal && a.force && !forced) {
63
+ if (watched && wanted === id)
64
+ ask(id, a, "The command refused.", r.refusal, proceed);
65
+ else
66
+ deps.sys(`/model ${id} offers to force it`);
67
+ }
68
+ return;
69
+ }
70
+ deps.sys(`${id}: ready after ${took} · ${r.reason}`);
71
+ const moved = () => wanted !== id || deps.current() !== from;
72
+ if (!deps.idle())
73
+ deps.sys(`${id}: the session switches when this turn ends`);
74
+ while (!deps.idle() && !moved())
75
+ await new Promise((done) => setTimeout(done, tickMs));
76
+ if (moved()) {
77
+ deps.sys(`${id} is ready; the session stays on ${deps.current()} — /model ${id} to use it`);
78
+ return;
79
+ }
80
+ proceed(watched);
81
+ });
82
+ }
83
+ return {
84
+ /** The owner picked `id`. False: the row has no activation, /model goes on as usual. True: handled here, and
85
+ * `proceed` runs once the model is served (`watched`: the progress panel was still open). */
86
+ pick(id, proceed) {
87
+ const mine = ++picks;
88
+ const entry = read(id);
89
+ if (entry.error) {
90
+ stay(id, entry.error);
91
+ return true;
92
+ }
93
+ const a = entry.activation;
94
+ if (!a) {
95
+ wanted = id;
96
+ return false;
97
+ }
98
+ if (running) { // one switch at a time; asking for a second one changes nothing about the first
99
+ if (running.id === id)
100
+ wanted = id;
101
+ else
102
+ deps.sys(`a switch to ${running.id} is still running — wait for it, or stop it, before ${id}`);
103
+ running.show();
104
+ return true;
105
+ }
106
+ wanted = id;
107
+ if (!a.check && id === deps.current()) {
108
+ proceed(true);
109
+ return true;
110
+ }
111
+ if (a.check)
112
+ deps.sys(`${id}: checking whether it is being served…`);
113
+ void checkActivation(a).then((c) => {
114
+ if (mine !== picks)
115
+ return;
116
+ if (c.state === "serving")
117
+ proceed(true);
118
+ else if (c.state === "error")
119
+ stay(id, `activation check failed: ${c.reason}`);
120
+ else
121
+ ask(id, a, c.plan, c.refusal, proceed);
122
+ });
123
+ return true;
124
+ },
125
+ };
126
+ }
@@ -17,8 +17,9 @@ export const FREE_ROW_PRESETS = ["operator"];
17
17
  /** Sign-in providers whose rows /model reads from their own /models once signed in (router/provider-models.ts). Unlike
18
18
  * 0perator Free they are listed under "+ Connect a provider key", where picking one points at the sign-in. */
19
19
  export const PROVIDER_ROW_PRESETS = ["portal"];
20
- /** The /model main rows, in this order; everything else sits behind MORE_ROW. operator-dense left 2026-11-30 (its
21
- * gateway route was retired: the registry only offers what is served). */
20
+ /** The /model main rows while the gateway publishes no list (router/model-list.ts), in this order; everything else sits
21
+ * behind MORE_ROW. operator-dense left 2026-11-30 (its gateway route was retired: the registry only offers what is
22
+ * served). */
22
23
  export const MAIN_MODEL_IDS = ["operator-flash", "kimi-linear-48b"];
23
24
  /** The last main row: an action that opens the rest (other fleet rows, connected providers, free rows, MOA, connect). */
24
25
  export const MORE_ROW = "More models…";
@@ -55,24 +56,28 @@ export function modelPickerView(models, o) {
55
56
  entries: [...ordered.map((profile) => ({ kind: "model", profile })), { kind: "connect" }],
56
57
  };
57
58
  }
58
- /** The first /model screen: the main rows present in `models` (MAIN_MODEL_IDS order), then "More models…". */
59
+ /** The first screen's ids: the gateway's list when the registry has any of it, else MAIN_MODEL_IDS. */
60
+ export function mainIds(models, listed = []) {
61
+ return listed.some((id) => models.some((m) => m.id === id)) ? listed : MAIN_MODEL_IDS;
62
+ }
63
+ /** The first /model screen: the main rows present in `models` (mainIds order), then "More models…". */
59
64
  export function mainPickerView(models, o) {
60
- const main = MAIN_MODEL_IDS.flatMap((id) => models.filter((m) => m.id === id));
65
+ const main = mainIds(models, o.main).flatMap((id) => models.filter((m) => m.id === id));
61
66
  return {
62
67
  rows: [...modelRows(main, o), MORE_ROW],
63
68
  entries: [...main.map((profile) => ({ kind: "model", profile })), { kind: "more" }],
64
69
  };
65
70
  }
66
71
  /** Whether a row is one of the main /model rows (and so not repeated under "More models…"). */
67
- export function isMainModel(m) {
68
- return MAIN_MODEL_IDS.includes(m.id);
72
+ export function isMainModel(m, ids = MAIN_MODEL_IDS) {
73
+ return ids.includes(m.id);
69
74
  }
70
75
  function modelRows(ordered, o) {
71
76
  return ordered.map((m) => {
72
77
  const active = m.id === o.active;
73
78
  const row = pickerRow(m, { servedCtx: active && m.kind === "single" ? o.servedCtx : undefined });
74
79
  const cost = active ? [] : costParts(o.cost?.(m), o.now);
75
- const tail = `${o.staleFree && m.tier === "free" ? " · cached" : ""}${active ? " (active)" : ""}`;
80
+ const tail = `${o.down?.has(m.id) ? " · unavailable" : ""}${o.staleFree && m.tier === "free" ? " · cached" : ""}${active ? " (active)" : ""}`;
76
81
  if (!cost.length)
77
82
  return `${row}${tail}`;
78
83
  const segs = [seg(row), ...cost, ...(tail ? [seg(tail)] : [])];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0perator/operator",
3
- "version": "0.2.2-next.0",
3
+ "version": "0.2.4",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "operator": "dist/cli.js",