@0perator/operator 0.1.341 → 0.1.342

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/README.md CHANGED
@@ -67,15 +67,34 @@ src/
67
67
  ## Run
68
68
 
69
69
  ```
70
- operator+ # Air⇄1M routing (default)
71
- operator # 1M-only
72
- operator+ --resume # reload the last conversation
70
+ npm install -g @0perator/operator # every box runs the release; `operator update` later
71
+ operator # interactive session
72
+ operator --resume # reload the last conversation in this directory
73
73
  ```
74
- Requires Aurora serving locally (Air `:8098` / 1M `:8097`). Dev: `npm install && npm run dev`.
75
- Env (the internal `KODE_` prefix is retained for compatibility): `KODE_AIR`, `KODE_1M`, `KODE_SADDLE`,
76
- `KODE_TSI_ROUTER=1m`, `KODE_SYSTEM_PROMPT`, `KODE_SESSION_FILE`; knowledge base `KODE_KB_URL` /
77
- `KODE_KB_TOKEN` / `KODE_KB_ENV_PATH` (see below); MCP config `KODE_MCP_CONFIG` / `KODE_MCP_SECRETS`
78
- (default: Operator home, falling back to the legacy python-core location).
74
+ Dev: `npm install && npm run dev`, or `scripts/operator-dev.sh` installed as `operator-dev` for unreleased `main`.
75
+
76
+ ### Headless — `operator run`
77
+ One task, no terminal UI, for SSH, CI, cron and other agents (the shape of `codex exec` and `hermes -z`):
78
+ ```
79
+ operator run "fix the failing test" # progress on stderr, the answer on stdout
80
+ echo "summarise CHANGELOG.md" | operator run - # task from stdin (also when stdin is a pipe and no task is given)
81
+ operator run --output json "…" # one result object: {type, ok, exitCode, result, rounds, toolCalls, durationMs}
82
+ operator run --output stream-json "…" # one JSON event per line (= --json)
83
+ ```
84
+ Flags: `--model ID`, `--permissions gated|audit|bypass` (headless has no one to approve, so `gated` denies),
85
+ `--cwd DIR`, `--max-turns N`, `--max-seconds S`, `--loop`, `--log FILE`, `--keep-awake`.
86
+ Exit codes: 0 done, 1 the task failed, 2 bad command line, 130 interrupted.
87
+ Sign-in without a keychain (SSH, CI): export the token as `OPERATOR_TOKEN`.
88
+
89
+ ### Environment
90
+ Variables use the `OPERATOR_` prefix: `OPERATOR_MODEL`, `OPERATOR_PERMISSIONS`, `OPERATOR_TOKEN`,
91
+ `OPERATOR_SETTINGS` (settings file), `OPERATOR_CONFIG_HOME` (default `~/.axe/operator`), `OPERATOR_SYSTEM_PROMPT`,
92
+ `OPERATOR_KB_URL` / `OPERATOR_KB_TOKEN` (see below), `OPERATOR_MCP_CONFIG` / `OPERATOR_MCP_SECRETS`. The older
93
+ `KODE_` names are still read; `operator doctor` lists any in use. `OPERATOR_HOME` stays the local model
94
+ runtime's home (`~/.operator`). Fleet defaults belong in settings.json `env` / `envFiles`.
95
+
96
+ ### Local model runtime
97
+ `operator gateway start [-d] | stop | status | health | logs` (was `operator-gw`, which now forwards here).
79
98
 
80
99
  ## Knowledge base
81
100
 
@@ -10,7 +10,7 @@ import { recordLiveProgress, roundProgressed, touchedPaths } from "../memory/liv
10
10
  import { getAgentTasks } from "../tools/registry.js";
11
11
  /** Streaming handlers that render a turn's activity through the reporter. Text deltas stream only in
12
12
  * human mode (JSON mode reports the settled content as one event, to stay line-parseable). */
13
- function handlersFor(reporter, json, prompt = "") {
13
+ function handlersFor(reporter, json, prompt = "", onDelta) {
14
14
  const touched = [];
15
15
  const session = `headless-${process.pid}`;
16
16
  return {
@@ -30,7 +30,7 @@ function handlersFor(reporter, json, prompt = "") {
30
30
  recordLiveProgress(process.env.KODE_HANDOFF_FILE, { session, cwd: process.cwd(), request: prompt, tasks: getAgentTasks(), touched });
31
31
  }
32
32
  },
33
- onDelta: json ? undefined : (chunk) => process.stdout.write(chunk),
33
+ onDelta: json ? undefined : onDelta ?? ((chunk) => process.stdout.write(chunk)),
34
34
  };
35
35
  }
36
36
  /**
@@ -38,9 +38,39 @@ function handlersFor(reporter, json, prompt = "") {
38
38
  * to interrupt the in-flight turn so Ctrl-C stops cleanly (and the caller's keep-awake teardown runs).
39
39
  */
40
40
  export async function runHeadless(settings, prompt, opts = {}) {
41
- const reporter = opts.reporter ?? makeReporter({ json: opts.json, logFile: opts.logFile });
41
+ const output = opts.output ?? (opts.json ? "stream-json" : "text");
42
+ let result = {};
43
+ const reporter = opts.reporter ?? makeReporter({
44
+ json: output !== "text",
45
+ logFile: opts.logFile,
46
+ out: output === "json" ? () => { } : output === "text" ? (s) => process.stderr.write(s) : undefined,
47
+ });
48
+ let streamed = "";
42
49
  const session = createAutonomySession(settings);
43
- const handlers = handlersFor(reporter, !!opts.json, prompt);
50
+ const handlers = handlersFor(reporter, output !== "text", prompt, (chunk) => { streamed += chunk; process.stdout.write(chunk); });
51
+ const answer = (content) => {
52
+ if (!content)
53
+ return;
54
+ if (output === "json") {
55
+ result.result = content;
56
+ return;
57
+ }
58
+ if (output === "text" && streamed) {
59
+ if (!streamed.endsWith("\n"))
60
+ process.stdout.write("\n");
61
+ return;
62
+ } // already on stdout
63
+ if (output === "text") {
64
+ process.stdout.write(content.endsWith("\n") ? content : content + "\n");
65
+ return;
66
+ }
67
+ reporter.line(content);
68
+ };
69
+ const finish = (code) => {
70
+ if (output === "json")
71
+ process.stdout.write(JSON.stringify({ type: "result", ok: code === 0, exitCode: code, ...result }) + "\n");
72
+ return code;
73
+ };
44
74
  const controller = new AbortController();
45
75
  const onSig = () => { controller.abort(); try {
46
76
  session.interrupt();
@@ -59,21 +89,23 @@ export async function runHeadless(settings, prompt, opts = {}) {
59
89
  onTurn: (i) => reporter.event("turn", { turn: i.turn, tools: i.toolCalls, rounds: i.rounds, durationMs: Math.round(i.durationMs) }),
60
90
  }, controller.signal);
61
91
  reporter.event("done", { reason: res.reason, turns: res.turns, toolCalls: res.toolCalls });
62
- if (res.lastContent)
63
- reporter.line(res.lastContent);
92
+ result = { reason: res.reason, turns: res.turns, toolCalls: res.toolCalls };
93
+ answer(res.lastContent);
64
94
  await session.flushRouteShadow(); // MOA phase-0: the last turn's shadow record must not die with the process
65
- return res.reason === "error" ? 1 : res.reason === "interrupted" ? 130 : 0;
95
+ return finish(res.reason === "error" ? 1 : res.reason === "interrupted" ? 130 : 0);
66
96
  }
67
97
  const outcome = await session.send(prompt, handlers);
68
98
  reporter.event("done", { rounds: outcome.rounds, toolCalls: outcome.toolCalls, interrupted: outcome.interrupted, durationMs: Math.round(outcome.durationMs ?? 0) });
69
- if (outcome.content)
70
- reporter.line(outcome.content);
99
+ result = { rounds: outcome.rounds, toolCalls: outcome.toolCalls, interrupted: outcome.interrupted, durationMs: Math.round(outcome.durationMs ?? 0) };
100
+ answer(outcome.content);
71
101
  await session.flushRouteShadow(); // MOA phase-0: headless one-shot exits before fire-and-forget would land
72
- return outcome.interrupted ? 130 : 0;
102
+ return finish(outcome.interrupted ? 130 : 0);
73
103
  }
74
104
  catch (e) {
75
- reporter.event("error", { message: e instanceof Error ? e.message : String(e) });
76
- return 1;
105
+ const message = e instanceof Error ? e.message : String(e);
106
+ reporter.event("error", { message });
107
+ result = { ...result, error: message };
108
+ return finish(1);
77
109
  }
78
110
  finally {
79
111
  process.off("SIGINT", onSig);
@@ -1,7 +1,9 @@
1
1
  // Autonomy CLI dispatch — the entry the shell (cli.tsx) calls BEFORE mounting Ink, alongside the existing
2
2
  // `operator auth` / `operator update` barewords. It owns the unattended subcommands:
3
3
  //
4
- // operator run "<task>" [--keep-awake] [--json] [--log F] [--loop] [--max-turns N] [--max-seconds S]
4
+ // operator run "<task>"|- [--model ID] [--permissions gated|audit|bypass] [--cwd DIR]
5
+ // [--output text|json|stream-json] [--json] [--log F] [--loop] [--max-turns N]
6
+ // [--max-seconds S] [--keep-awake]
5
7
  // operator loop "<objective>" (alias for `run --loop`)
6
8
  // operator board <list|add "<task>"|run|status> [--json] [--max N] [--keep-awake]
7
9
  // operator routine <list|run <id>|install <id> [--crontab]|watch> [--keep-awake]
@@ -53,7 +55,39 @@ function parseFlags(args, valued) {
53
55
  }
54
56
  return { bool, val, positional };
55
57
  }
56
- const VALUED = new Set(["log", "max-turns", "max-seconds", "max", "n", "source", "sink", "kind"]);
58
+ const VALUED = new Set(["log", "max-turns", "max-seconds", "max", "n", "source", "sink", "kind", "model", "permissions", "cwd", "output"]);
59
+ const OUTPUTS = ["text", "json", "stream-json"];
60
+ const PERMISSION_MODES = ["gated", "audit", "bypass"];
61
+ const RUN_USAGE = `usage: operator run "<task>"|- [--model ID] [--permissions gated|audit|bypass] [--cwd DIR] [--output text|json|stream-json] [--max-turns N] [--max-seconds S]`;
62
+ /** Validate `operator run` flags. A string is the usage error (exit 2: the command line itself is wrong,
63
+ * the shell convention; 1 stays "the task failed"). */
64
+ export function runFlags(args) {
65
+ const f = parseFlags(args, VALUED);
66
+ const output = (f.val.get("output") ?? (f.bool.has("json") ? "stream-json" : "text"));
67
+ if (!OUTPUTS.includes(output))
68
+ return `--output must be one of ${OUTPUTS.join(", ")}`;
69
+ const pm = f.val.get("permissions");
70
+ if (pm !== undefined && !PERMISSION_MODES.includes(pm))
71
+ return `--permissions must be one of ${PERMISSION_MODES.join(", ")}`;
72
+ const model = f.val.get("model");
73
+ if (model !== undefined && !model)
74
+ return "--model needs a model id";
75
+ return { output, model, permissions: pm, cwd: f.val.get("cwd") };
76
+ }
77
+ function usage(msg) {
78
+ process.stderr.write(`operator: ${msg}\n${RUN_USAGE}\n`);
79
+ return 2;
80
+ }
81
+ /** The task: the positional words, or stdin for `-` (and when nothing is given and stdin is a pipe). */
82
+ async function readTask(positional) {
83
+ const fromStdin = positional.length === 1 && positional[0] === "-" || (positional.length === 0 && !process.stdin.isTTY);
84
+ if (!fromStdin)
85
+ return positional.join(" ").trim();
86
+ const chunks = [];
87
+ for await (const c of process.stdin)
88
+ chunks.push(c);
89
+ return Buffer.concat(chunks).toString("utf8").trim();
90
+ }
57
91
  function intFlag(f, key) {
58
92
  const v = f.val.get(key);
59
93
  if (v === undefined)
@@ -256,14 +290,29 @@ export async function dispatchAutonomy(argv, settings) {
256
290
  }
257
291
  const f = parseFlags(argv.slice(3), VALUED);
258
292
  if (cmd === "run" || cmd === "loop") {
259
- const prompt = f.positional.join(" ").trim();
260
- if (!prompt) {
261
- process.stderr.write(`usage: operator ${cmd} "<task>"\n`);
262
- return 1;
293
+ const rf = runFlags(argv.slice(3));
294
+ if (typeof rf === "string")
295
+ return usage(rf);
296
+ const { output, model, permissions: pm, cwd } = rf;
297
+ if (cwd !== undefined) {
298
+ try {
299
+ process.chdir(cwd);
300
+ }
301
+ catch {
302
+ return usage(`--cwd: no such directory: ${cwd}`);
303
+ }
263
304
  }
305
+ const prompt = await readTask(f.positional);
306
+ if (!prompt)
307
+ return usage("no task given");
308
+ // Flags beat settings and KODE_* the same way the env overrides beat the file: for this run only.
309
+ if (model)
310
+ settings.endpoints.aurora = { ...settings.endpoints.aurora, model };
311
+ if (pm)
312
+ settings.permissions = { ...settings.permissions, mode: pm };
264
313
  const loop = cmd === "loop" || f.bool.has("loop");
265
314
  return withKeepAwake(wantKeepAwake(settings, f), "Operator run", () => runHeadless(settings, prompt, {
266
- json: f.bool.has("json"),
315
+ output,
267
316
  logFile: f.val.get("log"),
268
317
  loop,
269
318
  maxTurns: intFlag(f, "max-turns"),
package/dist/boot.js ADDED
@@ -0,0 +1,6 @@
1
+ // First import of cli.tsx: ESM evaluates imports in order, so the settings-carried environment is in place
2
+ // before any module reads process.env at load time.
3
+ import { applyBootEnv, applyEnvAliases } from "./config/boot-env.js";
4
+ applyEnvAliases(); // first: OPERATOR_SETTINGS decides which settings file applyBootEnv reads
5
+ applyBootEnv();
6
+ applyEnvAliases(); // settings `env` may use OPERATOR_ names too
package/dist/cli.js CHANGED
@@ -4,6 +4,7 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
4
4
  // headless + tested); this file only maps Session's streaming callbacks onto React state and renders
5
5
  // the SPEC §6 <App>. The port's whole point — full-frame React reconciliation + Ink <Static> — is what
6
6
  // makes the scroll/echo/overwrite bug class of the ANSI-cursor Python core structurally impossible.
7
+ import "./boot.js";
7
8
  import { useCallback, useEffect, useRef, useState } from "react";
8
9
  import { render, Box, Text, useApp } from "ink";
9
10
  import { App } from "./ui/index.js";
@@ -111,7 +112,7 @@ if (process.argv.includes("--version") || process.argv.includes("-V")) {
111
112
  }
112
113
  if (process.argv.includes("--help")) {
113
114
  process.stdout.write(mastheadLines(`v${VERSION}`).join("\n") +
114
- "\n\nUsage:\n operator start the interactive session\n operator --resume resume the last session in this directory\n operator --update update to the latest build (git fast-forward)\n operator --fullscreen fullscreen layout: composer pinned to the bottom (or settings.ui.fullscreen)\n operator auth sign in / manage your AXE account\n operator run <task> run one task headless\n operator --version print the version\n");
115
+ "\n\nUsage:\n operator start the interactive session\n operator --resume resume the last session in this directory\n operator update update to the latest release\n operator --fullscreen fullscreen layout: composer pinned to the bottom (or settings.ui.fullscreen)\n operator auth sign in / manage your AXE account\n operator gateway the local model runtime: start | stop | status | health | logs\n operator run <task>|- run one task headless (--model, --permissions, --output json, --cwd)\n operator --version print the version\n");
115
116
  process.exit(0);
116
117
  }
117
118
  // operator/settings.json (override path via KODE_TSI_SETTINGS), env vars still win — see config/settings.ts.
@@ -195,7 +196,7 @@ catch { /* auth is optional — a local engine needs none */ }
195
196
  // Seat resolution (enterprise SSO/RBAC readiness): with a managed auth policy deployed, the verified identity
196
197
  // decides the widest tier this process may hold (it can only NARROW, never widen). With no managed policy this
197
198
  // is a no-op and touches no network. `operator auth …` / --version / --help skip it (they must work signed-out).
198
- const SKIP_SEAT = process.argv[2] === "auth" || process.argv[2] === "audit" || process.argv.includes("--version") || process.argv.includes("-V") || process.argv.includes("--help");
199
+ const SKIP_SEAT = process.argv[2] === "auth" || process.argv[2] === "audit" || process.argv[2] === "gateway" || process.argv.includes("--version") || process.argv.includes("-V") || process.argv.includes("--help");
199
200
  const SEAT = SKIP_SEAT
200
201
  ? { seat: { tier: settings.permissions.tier ?? "admin", source: "local-owner", reasons: ["seat resolution skipped for this command"] }, events: [], dropToken: false }
201
202
  : await resolveSeat(settings, { creds: bootCreds });
@@ -2663,6 +2664,11 @@ if (process.argv[2] === "vault") {
2663
2664
  const { runVault } = await import("./vault/cli.js");
2664
2665
  process.exit(await runVault(process.argv.slice(3)));
2665
2666
  }
2667
+ // `operator gateway …` — the local model runtime's gateway (was the separate `operator-gw` script).
2668
+ if (process.argv[2] === "gateway") {
2669
+ const { runGateway } = await import("./gateway-cli.js");
2670
+ process.exit(await runGateway(process.argv.slice(3)));
2671
+ }
2666
2672
  // `operator update` (bareword) and `operator --update` both self-update.
2667
2673
  if (process.argv[2] === "update" || process.argv.includes("--update")) {
2668
2674
  const { runUpdate } = await import("./update.js");
@@ -0,0 +1,89 @@
1
+ // Settings-carried environment: `env` (name → value) and `envFiles` (dotenv files) in settings.json, applied
2
+ // before any other module of the CLI loads. This is what a fleet node's launcher script used to export
3
+ // (compose/vision URLs, Chrome path, secrets env files) — keeping it in settings means every install shape
4
+ // (npm, source checkout, ACP, headless) starts with the same environment and no wrapper is needed.
5
+ // Precedence: a variable already in the process environment always wins, then `env`, then `envFiles` in order.
6
+ //
7
+ // OPERATOR_* is the documented prefix; the engine still reads KODE_* (119 call sites, and the env children inherit),
8
+ // so applyEnvAliases copies each OPERATOR_X onto KODE_X at boot. A few names don't follow the prefix rule, and
9
+ // OPERATOR_HOME / OPERATOR_SCRATCH already mean something else (the local model runtime's ~/.operator, set in the
10
+ // gateway's launchd job; the per-project scratch dir the engine exports), so they are never aliased.
11
+ import { readFileSync } from "node:fs";
12
+ import { homedir } from "node:os";
13
+ import { operatorPath } from "./home.js";
14
+ /** Parse a dotenv / shell-export file: `KEY=value`, optional `export `, quotes stripped, `#` comments skipped. */
15
+ export function parseDotenv(text) {
16
+ const out = {};
17
+ for (const raw of text.split("\n")) {
18
+ const line = raw.trim();
19
+ if (!line || line.startsWith("#"))
20
+ continue;
21
+ const m = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line);
22
+ if (!m)
23
+ continue;
24
+ let v = m[2].trim();
25
+ if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'")))
26
+ v = v.slice(1, -1);
27
+ out[m[1]] = v;
28
+ }
29
+ return out;
30
+ }
31
+ const RENAMED = {
32
+ OPERATOR_TOKEN: "KODE_OPERATOR_TOKEN", // already the skills/compose bearer name; now also the headless sign-in token
33
+ OPERATOR_SETTINGS: "KODE_TSI_SETTINGS",
34
+ OPERATOR_MCP: "KODE_TSI_MCP",
35
+ OPERATOR_CONFIG_HOME: "KODE_HOME", // settings, sessions, memory (~/.axe/operator)
36
+ };
37
+ const NOT_ALIASED = new Set(["OPERATOR_HOME", "OPERATOR_SCRATCH"]);
38
+ /** Copy OPERATOR_X onto the KODE_ name the engine reads. A KODE_ variable already set wins (explicit beats alias). */
39
+ export function applyEnvAliases(env = process.env) {
40
+ const set = [];
41
+ for (const [k, v] of Object.entries(env)) {
42
+ if (!k.startsWith("OPERATOR_") || v === undefined || NOT_ALIASED.has(k))
43
+ continue;
44
+ const target = RENAMED[k] ?? `KODE_${k.slice("OPERATOR_".length)}`;
45
+ if (env[target] !== undefined)
46
+ continue;
47
+ env[target] = v;
48
+ set.push(target);
49
+ }
50
+ return set;
51
+ }
52
+ /** The documented OPERATOR_ name for a KODE_ variable (for `operator doctor`). */
53
+ export function operatorName(kodeName) {
54
+ const renamed = Object.entries(RENAMED).find(([, k]) => k === kodeName);
55
+ return renamed ? renamed[0] : kodeName.replace(/^KODE_/, "OPERATOR_");
56
+ }
57
+ const expandHome = (p) => p.replace(/^~(?=\/|$)/, homedir());
58
+ /** Apply `env` + `envFiles` from the settings file onto `env`. Returns the names it set (values never). */
59
+ export function applyBootEnv(file = process.env.KODE_TSI_SETTINGS ?? operatorPath("settings.json"), env = process.env) {
60
+ let s;
61
+ try {
62
+ s = JSON.parse(readFileSync(file, "utf8"));
63
+ }
64
+ catch {
65
+ return [];
66
+ }
67
+ const set = [];
68
+ const fill = (vars) => {
69
+ for (const [k, v] of Object.entries(vars)) {
70
+ if (env[k] !== undefined || typeof v !== "string")
71
+ continue;
72
+ env[k] = v;
73
+ set.push(k);
74
+ }
75
+ };
76
+ if (s.env && typeof s.env === "object" && !Array.isArray(s.env))
77
+ fill(s.env);
78
+ if (Array.isArray(s.envFiles)) {
79
+ for (const f of s.envFiles) {
80
+ if (typeof f !== "string")
81
+ continue;
82
+ try {
83
+ fill(parseDotenv(readFileSync(expandHome(f), "utf8")));
84
+ }
85
+ catch { /* a missing secrets file is not fatal */ }
86
+ }
87
+ }
88
+ return set;
89
+ }
@@ -8,6 +8,7 @@ import { existsSync, readFileSync, statSync } from "node:fs";
8
8
  import { join } from "node:path";
9
9
  import { auditHome } from "../config/scaffold.js";
10
10
  import { get_operator_home } from "../config/home.js";
11
+ import { operatorName } from "../config/boot-env.js";
11
12
  import { auditFilesFor, verifyAuditFiles } from "../telemetry/audit-verify.js";
12
13
  import { defaultEventsFile } from "../telemetry/events.js";
13
14
  import { loadCredentials } from "../auth/store.js";
@@ -107,6 +108,9 @@ export async function collectChecks(settings, ctx) {
107
108
  add("audit", "info", "no remote audit sink configured: the local chain detects edits, but an append-only remote/SIEM copy is what makes the trail non-repudiable");
108
109
  const creds = await loadCredentials().catch(() => null);
109
110
  add("credentials", "info", process.env.KODE_OPERATOR_TOKEN ? "operator token supplied through the environment" : creds ? `signed in as ${creds.user ?? "?"}` : "not signed in");
111
+ const legacy = Object.keys(process.env).filter((k) => k.startsWith("KODE_") && process.env[operatorName(k)] === undefined).sort();
112
+ if (legacy.length)
113
+ add("env", "info", `set with the old KODE_ prefix (still read; the documented names are OPERATOR_*): ${legacy.map((k) => `${k} → ${operatorName(k)}`).join(", ")}`);
110
114
  add("acp", "info", "`operator acp`: permission requests are bridged to the editor (fail-closed); SDK @zed-industries/agent-client-protocol is deprecated → @agentclientprotocol/sdk (migration pending)");
111
115
  return rows;
112
116
  }
@@ -0,0 +1,133 @@
1
+ // `operator gateway start|stop|status|health|logs` — the local model runtime's gateway (operator-runtime/: a
2
+ // supervisor that spawns llama-server and publishes ~/.operator/runtime/server.json), as a subcommand of the one
3
+ // `operator` binary instead of a separate `operator-gw` script. Same behaviour as that script, which now forwards here.
4
+ import { spawnSync } from "node:child_process";
5
+ import { existsSync, readFileSync, readdirSync, readlinkSync, rmSync, statSync, lstatSync } from "node:fs";
6
+ import { homedir, userInfo } from "node:os";
7
+ import { join } from "node:path";
8
+ const LABEL = "co.0perator.gateway";
9
+ function paths() {
10
+ const home = process.env.OPERATOR_HOME || join(homedir(), ".operator"); // the runtime's home, not the CLI's config home
11
+ return {
12
+ home,
13
+ gateway: join(home, "gateway", "server.cjs"),
14
+ serverJson: join(home, "runtime", "server.json"),
15
+ bootLock: join(home, "runtime", "boot.lock"),
16
+ plist: join(homedir(), "Library", "LaunchAgents", `${LABEL}.plist`),
17
+ };
18
+ }
19
+ const alive = (pid) => { try {
20
+ process.kill(pid, 0);
21
+ return true;
22
+ }
23
+ catch {
24
+ return false;
25
+ } };
26
+ const readPid = (file) => { try {
27
+ const n = parseInt(readFileSync(file, "utf8").trim(), 10);
28
+ return Number.isFinite(n) ? n : undefined;
29
+ }
30
+ catch {
31
+ return undefined;
32
+ } };
33
+ function server(file) {
34
+ try {
35
+ return JSON.parse(readFileSync(file, "utf8"));
36
+ }
37
+ catch {
38
+ return undefined;
39
+ }
40
+ }
41
+ const launchctl = (...args) => spawnSync("launchctl", args, { stdio: "ignore" }).status ?? 1;
42
+ const domain = () => `gui/${userInfo().uid}`;
43
+ const USAGE = `usage: operator gateway {start [-d]|stop|status|health|logs}
44
+ start run the gateway in the foreground
45
+ start -d start it through launchd (${LABEL})
46
+ stop stop the gateway and its llama-server
47
+ status gateway, llama-server, models and binary
48
+ health llama-server /health
49
+ logs follow the gateway and llama-server logs`;
50
+ export async function runGateway(args, out = (s) => process.stdout.write(s + "\n")) {
51
+ const p = paths();
52
+ const [cmd = "status", ...rest] = args;
53
+ switch (cmd) {
54
+ case "start": {
55
+ if (rest[0] === "-d") {
56
+ if (!existsSync(p.plist)) {
57
+ out(`${p.plist} is not installed — run operator-runtime/scripts/install.sh first.`);
58
+ return 1;
59
+ }
60
+ launchctl("bootstrap", domain(), p.plist);
61
+ const code = launchctl("kickstart", "-k", `${domain()}/${LABEL}`);
62
+ out(code === 0 ? "gateway started through launchd" : "launchctl kickstart failed");
63
+ return code;
64
+ }
65
+ return spawnSync(process.execPath, [p.gateway, ...rest], { stdio: "inherit" }).status ?? 1;
66
+ }
67
+ case "stop": {
68
+ launchctl("bootout", `${domain()}/${LABEL}`);
69
+ const gw = readPid(p.bootLock);
70
+ const llama = server(p.serverJson)?.pid;
71
+ for (const pid of [gw, llama])
72
+ if (pid) {
73
+ try {
74
+ process.kill(pid);
75
+ }
76
+ catch { /* already gone */ }
77
+ }
78
+ rmSync(p.bootLock, { force: true });
79
+ rmSync(p.serverJson, { force: true });
80
+ out("gateway stopped");
81
+ return 0;
82
+ }
83
+ case "status": {
84
+ const gw = readPid(p.bootLock);
85
+ out("Operator runtime");
86
+ out(` gateway: ${gw === undefined ? "not running" : alive(gw) ? `running (pid ${gw})` : `dead (stale lock, pid was ${gw})`}`);
87
+ const s = server(p.serverJson);
88
+ out(` llama-server: ${!s ? "not running" : s.pid && alive(s.pid) ? `running (pid ${s.pid}, ${s.base_url ?? "?"})` : `dead (stale state, pid was ${s.pid ?? "?"})`}`);
89
+ out(" models:");
90
+ try {
91
+ const models = readdirSync(join(p.home, "models"));
92
+ if (!models.length)
93
+ out(" (none)");
94
+ for (const m of models)
95
+ out(` ${m} (${(statSync(join(p.home, "models", m)).size / 1e9).toFixed(1)} GB)`);
96
+ }
97
+ catch {
98
+ out(" (none)");
99
+ }
100
+ const bin = join(p.home, "tools", "llama-server");
101
+ out(` binary: ${existsSync(bin) && lstatSync(bin).isSymbolicLink() ? readlinkSync(bin) : "not linked"}`);
102
+ return 0;
103
+ }
104
+ case "health": {
105
+ const base = server(p.serverJson)?.base_url;
106
+ if (!base) {
107
+ out("no server.json — the gateway is not running");
108
+ return 1;
109
+ }
110
+ const url = `${base.replace(/\/v1\/?$/, "")}/health`;
111
+ try {
112
+ const r = await fetch(url, { signal: AbortSignal.timeout(5000) });
113
+ out(JSON.stringify(await r.json(), null, 2));
114
+ return r.ok ? 0 : 1;
115
+ }
116
+ catch {
117
+ out(`llama-server is not responding at ${url}`);
118
+ return 1;
119
+ }
120
+ }
121
+ case "logs": {
122
+ const logs = ["gateway.log", "gateway.error.log", "llama-server.log"].map((f) => join(p.home, "logs", f)).filter(existsSync);
123
+ if (!logs.length) {
124
+ out(`no logs under ${join(p.home, "logs")}`);
125
+ return 1;
126
+ }
127
+ return spawnSync("tail", ["-f", ...logs], { stdio: "inherit" }).status ?? 0;
128
+ }
129
+ default:
130
+ out(USAGE);
131
+ return cmd === "help" || cmd === "--help" ? 0 : 2;
132
+ }
133
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0perator/operator",
3
- "version": "0.1.341",
3
+ "version": "0.1.342",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "operator": "dist/cli.js",