@0perator/operator 0.1.349 → 0.1.350
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 +7 -2
- package/dist/config/toolchain.js +151 -0
- package/dist/enterprise/cli.js +48 -1
- package/dist/gateway-cli.js +46 -4
- package/dist/models/bench.js +12 -7
- package/dist/models/switch.js +82 -29
- package/dist/toolchain/manifest.json +222 -0
- package/dist/toolchain/toolchain.py +2723 -0
- package/dist/toolchain-cli.js +26 -0
- package/dist/tools/computer.js +8 -0
- package/dist/tools/contract.js +9 -0
- package/dist/tools/git-pr.js +1 -0
- package/dist/tools/monitoring-tools.js +3 -0
- package/dist/tools/registry.js +34 -0
- package/dist/tools/wave-tools.js +4 -0
- package/dist/tools/wave2-tools.js +7 -0
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -116,7 +116,7 @@ if (process.argv.includes("--version") || process.argv.includes("-V")) {
|
|
|
116
116
|
}
|
|
117
117
|
if (process.argv.includes("--help")) {
|
|
118
118
|
process.stdout.write(mastheadLines(`v${VERSION}`).join("\n") +
|
|
119
|
-
"\n\nUsage:\n operator start the interactive session\n 0p short for operator (every subcommand works)\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");
|
|
119
|
+
"\n\nUsage:\n operator start the interactive session\n 0p short for operator (every subcommand works)\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 toolchain the llama-server store: status | verify | install | activate | rollback | migrate | which\n operator run <task>|- run one task headless (--model, --permissions, --output json, --cwd)\n operator --version print the version\n");
|
|
120
120
|
process.exit(0);
|
|
121
121
|
}
|
|
122
122
|
// operator/settings.json (override path via KODE_TSI_SETTINGS), env vars still win — see config/settings.ts.
|
|
@@ -200,7 +200,7 @@ catch { /* auth is optional — a local engine needs none */ }
|
|
|
200
200
|
// Seat resolution (enterprise SSO/RBAC readiness): with a managed auth policy deployed, the verified identity
|
|
201
201
|
// decides the widest tier this process may hold (it can only NARROW, never widen). With no managed policy this
|
|
202
202
|
// is a no-op and touches no network. `operator auth …` / --version / --help skip it (they must work signed-out).
|
|
203
|
-
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");
|
|
203
|
+
const SKIP_SEAT = process.argv[2] === "auth" || process.argv[2] === "audit" || process.argv[2] === "gateway" || process.argv[2] === "toolchain" || process.argv.includes("--version") || process.argv.includes("-V") || process.argv.includes("--help");
|
|
204
204
|
const SEAT = SKIP_SEAT
|
|
205
205
|
? { seat: { tier: settings.permissions.tier ?? "admin", source: "local-owner", reasons: ["seat resolution skipped for this command"] }, events: [], dropToken: false }
|
|
206
206
|
: await resolveSeat(settings, { creds: bootCreds });
|
|
@@ -2716,6 +2716,11 @@ if (process.argv[2] === "gateway") {
|
|
|
2716
2716
|
const { runGateway } = await import("./gateway-cli.js");
|
|
2717
2717
|
process.exit(await runGateway(process.argv.slice(3)));
|
|
2718
2718
|
}
|
|
2719
|
+
// `operator toolchain …` — the toolchain CLI (toolchain/ in the repo, dist/toolchain/ in the package).
|
|
2720
|
+
if (process.argv[2] === "toolchain") {
|
|
2721
|
+
const { runToolchain } = await import("./toolchain-cli.js");
|
|
2722
|
+
process.exit(runToolchain(process.argv.slice(3)));
|
|
2723
|
+
}
|
|
2719
2724
|
// `operator update` (bareword) and `operator --update` both self-update.
|
|
2720
2725
|
if (process.argv[2] === "update" || process.argv.includes("--update")) {
|
|
2721
2726
|
const { runUpdate } = await import("./update.js");
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
// The engine's llama-server resolver (toolchain v1, see toolchain/README.md). A binary resolves through its consumer's
|
|
2
|
+
// link, <home>/consumers/<consumer> → generations/<N>, into a sealed entry under <home>/store — or it does not resolve.
|
|
3
|
+
// There is no fallback to PATH or Homebrew: `toolchain activate` is the only writer of those links, and `toolchain which`
|
|
4
|
+
// and the gateway's resolveConsumerBin give the same answer (test/llama-resolver-contract.test.mts).
|
|
5
|
+
// Node-lazy like config/home.ts (process.getBuiltinModule, no static `node:` import) so the neutral bundle stays node-free.
|
|
6
|
+
function builtins() {
|
|
7
|
+
try {
|
|
8
|
+
const proc = globalThis.process;
|
|
9
|
+
const fs = proc?.getBuiltinModule?.("node:fs");
|
|
10
|
+
const os = proc?.getBuiltinModule?.("node:os");
|
|
11
|
+
const path = proc?.getBuiltinModule?.("node:path");
|
|
12
|
+
return fs && os && path ? { fs, os, path } : null;
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
/** An unresolved or refused binary. `code` is the exit status for it, EX_CONFIG, which supervise-gateway.sh parks on. */
|
|
19
|
+
export class ToolchainError extends Error {
|
|
20
|
+
reason;
|
|
21
|
+
code = 78;
|
|
22
|
+
constructor(reason) {
|
|
23
|
+
super(`toolchain: ${reason}`);
|
|
24
|
+
this.reason = reason;
|
|
25
|
+
this.name = "ToolchainError";
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
/** `$OPERATOR_TOOLCHAIN_HOME`, else `<runtime home>/toolchain`, where the runtime home is `$OPERATOR_HOME` or `~/.operator`
|
|
29
|
+
* (never KODE_HOME, the CLI's config home). */
|
|
30
|
+
export function toolchainHome() {
|
|
31
|
+
const env = globalThis.process?.env;
|
|
32
|
+
if (env?.OPERATOR_TOOLCHAIN_HOME)
|
|
33
|
+
return env.OPERATOR_TOOLCHAIN_HOME;
|
|
34
|
+
const b = builtins();
|
|
35
|
+
const runtime = env?.OPERATOR_HOME || (b ? b.path.join(b.os.homedir(), ".operator") : ".operator");
|
|
36
|
+
return b ? b.path.join(runtime, "toolchain") : `${runtime}/toolchain`;
|
|
37
|
+
}
|
|
38
|
+
/** A box is managed once `<home>/.lock` exists: its llama-server then comes from the store or not at all. */
|
|
39
|
+
export function isManaged() {
|
|
40
|
+
const b = builtins();
|
|
41
|
+
return !!b && b.fs.existsSync(b.path.join(toolchainHome(), ".lock"));
|
|
42
|
+
}
|
|
43
|
+
const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
44
|
+
/** The stable path a consumer launches `bin` from, e.g. `<home>/consumers/arena/bin/llama-server`. It names the consumer
|
|
45
|
+
* in `ps`, and its target moves only when that consumer is activated. */
|
|
46
|
+
export function consumerBin(consumer, bin) {
|
|
47
|
+
for (const n of [consumer, bin])
|
|
48
|
+
if (!NAME.test(n))
|
|
49
|
+
throw new ToolchainError(`invalid name ${JSON.stringify(n)}`);
|
|
50
|
+
const b = builtins();
|
|
51
|
+
const home = toolchainHome();
|
|
52
|
+
return b ? b.path.join(home, "consumers", consumer, "bin", bin) : `${home}/consumers/${consumer}/bin/${bin}`;
|
|
53
|
+
}
|
|
54
|
+
const realOrUndefined = (b, p) => { try {
|
|
55
|
+
return b.fs.realpathSync(p);
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
return undefined;
|
|
59
|
+
} };
|
|
60
|
+
const allowed = (b, p, mode) => { try {
|
|
61
|
+
b.fs.accessSync(p, mode);
|
|
62
|
+
return true;
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
return false;
|
|
66
|
+
} };
|
|
67
|
+
function entryIn(b, store, target) {
|
|
68
|
+
const rel = b.path.relative(store, target);
|
|
69
|
+
const entry = rel.split(b.path.sep)[0] ?? "";
|
|
70
|
+
if (!entry || entry === rel || entry.startsWith(".") || b.path.isAbsolute(rel))
|
|
71
|
+
return undefined; // .staging-*, .trash and loose files are not entries
|
|
72
|
+
return entry;
|
|
73
|
+
}
|
|
74
|
+
/** Resolve `bin` for `consumer`, or throw ToolchainError. A missing or dangling link, a consumer that is not on a
|
|
75
|
+
* generation, a realpath outside `<home>/store/<entry>/`, a target that is not an executable file and an entry that is
|
|
76
|
+
* writable (no longer sealed) all fail closed — the same rules as `toolchain which` and the gateway's resolveConsumerBin. */
|
|
77
|
+
export function resolveToolchainBin(bin, opts) {
|
|
78
|
+
const link = consumerBin(opts.consumer, bin);
|
|
79
|
+
const b = builtins();
|
|
80
|
+
if (!b)
|
|
81
|
+
throw new ToolchainError("node builtins are unavailable");
|
|
82
|
+
const home = toolchainHome();
|
|
83
|
+
const store = realOrUndefined(b, b.path.join(home, "store"));
|
|
84
|
+
if (!store)
|
|
85
|
+
throw new ToolchainError(`no store at ${b.path.join(home, "store")}`);
|
|
86
|
+
const consumer = b.path.join(home, "consumers", opts.consumer);
|
|
87
|
+
const gen = realOrUndefined(b, consumer);
|
|
88
|
+
if (!gen)
|
|
89
|
+
throw new ToolchainError(`consumer ${opts.consumer} is not activated (${consumer} is missing or dangling)`);
|
|
90
|
+
const n = b.path.basename(gen);
|
|
91
|
+
if (!/^\d+$/.test(n) || b.path.dirname(gen) !== realOrUndefined(b, b.path.join(home, "generations"))) {
|
|
92
|
+
throw new ToolchainError(`${consumer} points at ${gen}, not a generation`);
|
|
93
|
+
}
|
|
94
|
+
const target = realOrUndefined(b, b.path.join(gen, "bin", bin)); // through the generation just resolved: back through the consumer link, a flip in between would pair generation N with another build
|
|
95
|
+
if (!target)
|
|
96
|
+
throw new ToolchainError(`${link} is missing or dangling (generation ${n})`);
|
|
97
|
+
const entry = entryIn(b, store, target);
|
|
98
|
+
if (!entry)
|
|
99
|
+
throw new ToolchainError(`${link} resolves to ${target}, outside the sealed entries in ${store}`);
|
|
100
|
+
if (!allowed(b, target, b.fs.constants.X_OK) || !b.fs.statSync(target).isFile())
|
|
101
|
+
throw new ToolchainError(`${target} is not an executable file`);
|
|
102
|
+
if (allowed(b, b.path.join(store, entry), b.fs.constants.W_OK))
|
|
103
|
+
throw new ToolchainError(`store/${entry} is writable: the entry is no longer sealed (toolchain verify --deep)`);
|
|
104
|
+
return { path: link, realpath: target, entry, generation: Number(n) };
|
|
105
|
+
}
|
|
106
|
+
/** The store entry a path lies in once links are followed, or undefined when it is outside `<home>/store`. */
|
|
107
|
+
export function storeEntryOf(p) {
|
|
108
|
+
const b = builtins();
|
|
109
|
+
if (!b)
|
|
110
|
+
return undefined;
|
|
111
|
+
const store = realOrUndefined(b, b.path.join(toolchainHome(), "store"));
|
|
112
|
+
const target = realOrUndefined(b, p);
|
|
113
|
+
return store && target ? entryIn(b, store, target) : undefined;
|
|
114
|
+
}
|
|
115
|
+
function readJson(...parts) {
|
|
116
|
+
const b = builtins();
|
|
117
|
+
if (!b)
|
|
118
|
+
return undefined;
|
|
119
|
+
try {
|
|
120
|
+
return JSON.parse(b.fs.readFileSync(b.path.join(toolchainHome(), ...parts), "utf8"));
|
|
121
|
+
}
|
|
122
|
+
catch {
|
|
123
|
+
return undefined;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
/** A store entry's `.toolchain-entry.json` ({name, version, …}). */
|
|
127
|
+
export function storeEntryMeta(entry) {
|
|
128
|
+
return NAME.test(entry) ? readJson("store", entry, ".toolchain-entry.json") : undefined;
|
|
129
|
+
}
|
|
130
|
+
/** The manifest this box last applied (`<home>/manifest.applied.json`). */
|
|
131
|
+
export function appliedManifest() {
|
|
132
|
+
return readJson("manifest.applied.json");
|
|
133
|
+
}
|
|
134
|
+
/** The last `toolchain verify` result (`<home>/state.json`) and when it ran: its `ts`, else the file's mtime. */
|
|
135
|
+
export function verifyState() {
|
|
136
|
+
const state = readJson("state.json");
|
|
137
|
+
const b = builtins();
|
|
138
|
+
if (!state || !b)
|
|
139
|
+
return undefined;
|
|
140
|
+
const ts = state.ts;
|
|
141
|
+
let at = typeof ts === "number" ? (ts < 1e12 ? ts * 1000 : ts) : typeof ts === "string" ? Date.parse(ts) : NaN;
|
|
142
|
+
if (!Number.isFinite(at)) {
|
|
143
|
+
try {
|
|
144
|
+
at = b.fs.statSync(b.path.join(toolchainHome(), "state.json")).mtimeMs;
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
return undefined;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
return { result: typeof state.result === "string" ? state.result : "unknown", at };
|
|
151
|
+
}
|
package/dist/enterprise/cli.js
CHANGED
|
@@ -4,11 +4,13 @@
|
|
|
4
4
|
// operator audit verify [--file <path>] [--json] verify the hash-chained trail (rotated files + active); exit 2 on a break
|
|
5
5
|
// operator audit tail [n] the last n events, human-readable
|
|
6
6
|
// operator doctor [--json] [--strict] policy / seat / sandbox / home / audit / credential posture
|
|
7
|
-
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
7
|
+
import { existsSync, readFileSync, readdirSync, 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
11
|
import { operatorName } from "../config/boot-env.js";
|
|
12
|
+
import { ToolchainError, appliedManifest, isManaged, resolveToolchainBin, toolchainHome, verifyState } from "../config/toolchain.js";
|
|
13
|
+
import { formatAge } from "../memory/session-catalog.js";
|
|
12
14
|
import { auditFilesFor, verifyAuditFiles } from "../telemetry/audit-verify.js";
|
|
13
15
|
import { defaultEventsFile } from "../telemetry/events.js";
|
|
14
16
|
import { loadCredentials } from "../auth/store.js";
|
|
@@ -68,6 +70,50 @@ function auditTail(args, out) {
|
|
|
68
70
|
}
|
|
69
71
|
return 0;
|
|
70
72
|
}
|
|
73
|
+
/** Where llama-server comes from (the sealed store, or the legacy chain on an unmanaged box), whether every consumer still
|
|
74
|
+
* resolves into a sealed entry, and the last result `toolchain verify` recorded (state.json) — read, not re-derived. */
|
|
75
|
+
function toolchainChecks(add) {
|
|
76
|
+
const override = process.env.OPERATOR_LLAMA_SERVER;
|
|
77
|
+
if (override)
|
|
78
|
+
add("warn", `OPERATOR_LLAMA_SERVER=${override} overrides the toolchain resolver for the gateway`);
|
|
79
|
+
const home = toolchainHome();
|
|
80
|
+
if (!isManaged()) {
|
|
81
|
+
add("info", `unmanaged (no ${join(home, ".lock")}): the gateway picks llama-server through its legacy chain`);
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
add("ok", `managed: ${home}`);
|
|
85
|
+
const m = appliedManifest();
|
|
86
|
+
const today = new Date().toISOString().slice(0, 10);
|
|
87
|
+
if (!m)
|
|
88
|
+
add("warn", `no applied manifest at ${join(home, "manifest.applied.json")}`);
|
|
89
|
+
else if (!m.expires || m.expires < today)
|
|
90
|
+
add("warn", `manifest serial ${m.serial ?? "?"} ${m.expires ? `expired ${m.expires}` : "has no expiry"}: this box has stopped being reviewed`);
|
|
91
|
+
else
|
|
92
|
+
add("ok", `manifest serial ${m.serial ?? "?"}, expires ${m.expires}`);
|
|
93
|
+
let consumers = [];
|
|
94
|
+
try {
|
|
95
|
+
consumers = readdirSync(join(home, "consumers")).filter((c) => !c.startsWith(".")).sort();
|
|
96
|
+
}
|
|
97
|
+
catch { /* none activated */ }
|
|
98
|
+
if (!consumers.length)
|
|
99
|
+
add("fail", "no consumer is activated, so nothing can launch llama-server (toolchain install --activate aurora,portal,arena)");
|
|
100
|
+
for (const c of consumers) {
|
|
101
|
+
try {
|
|
102
|
+
const r = resolveToolchainBin("llama-server", { consumer: c }); // refuses an entry whose directory is writable
|
|
103
|
+
const writable = (statSync(r.realpath).mode & 0o222) !== 0;
|
|
104
|
+
add(writable ? "fail" : "ok", `${c} → gen ${r.generation} → ${r.entry}${writable ? `: ${r.realpath} is writable, so the entry is no longer sealed (toolchain verify --deep)` : " (sealed)"}`);
|
|
105
|
+
}
|
|
106
|
+
catch (e) {
|
|
107
|
+
add("fail", `${c}: ${e instanceof ToolchainError ? e.reason : String(e)}`);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
const st = verifyState();
|
|
111
|
+
const age = st && formatAge(st.at);
|
|
112
|
+
if (!st)
|
|
113
|
+
add("warn", "not verified yet (toolchain verify)");
|
|
114
|
+
else
|
|
115
|
+
add(st.result === "ok" ? "ok" : "warn", `verify: ${st.result}, ${age === "just now" ? age : `${age} ago`}`);
|
|
116
|
+
}
|
|
71
117
|
export async function collectChecks(settings, ctx) {
|
|
72
118
|
const rows = [];
|
|
73
119
|
const add = (id, status, message) => rows.push({ id, status, message });
|
|
@@ -111,6 +157,7 @@ export async function collectChecks(settings, ctx) {
|
|
|
111
157
|
const legacy = Object.keys(process.env).filter((k) => k.startsWith("KODE_") && process.env[operatorName(k)] === undefined).sort();
|
|
112
158
|
if (legacy.length)
|
|
113
159
|
add("env", "info", `set with the old KODE_ prefix (still read; the documented names are OPERATOR_*): ${legacy.map((k) => `${k} → ${operatorName(k)}`).join(", ")}`);
|
|
160
|
+
toolchainChecks((status, message) => add("toolchain", status, message));
|
|
114
161
|
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)");
|
|
115
162
|
return rows;
|
|
116
163
|
}
|
package/dist/gateway-cli.js
CHANGED
|
@@ -2,9 +2,11 @@
|
|
|
2
2
|
// supervisor that spawns llama-server and publishes ~/.operator/runtime/server.json), as a subcommand of the one
|
|
3
3
|
// `operator` binary instead of a separate `operator-gw` script. Same behaviour as that script, which now forwards here.
|
|
4
4
|
import { spawnSync } from "node:child_process";
|
|
5
|
-
import { existsSync, readFileSync, readdirSync, readlinkSync, rmSync, statSync, lstatSync } from "node:fs";
|
|
5
|
+
import { existsSync, readFileSync, readdirSync, readlinkSync, realpathSync, rmSync, statSync, lstatSync } from "node:fs";
|
|
6
6
|
import { homedir, userInfo } from "node:os";
|
|
7
7
|
import { join } from "node:path";
|
|
8
|
+
import { ToolchainError, isManaged, resolveToolchainBin, storeEntryMeta, storeEntryOf, verifyState } from "./config/toolchain.js";
|
|
9
|
+
import { formatAge } from "./memory/session-catalog.js";
|
|
8
10
|
const LABEL = "co.0perator.gateway";
|
|
9
11
|
function paths() {
|
|
10
12
|
const home = process.env.OPERATOR_HOME || join(homedir(), ".operator"); // the runtime's home, not the CLI's config home
|
|
@@ -40,11 +42,45 @@ function server(file) {
|
|
|
40
42
|
}
|
|
41
43
|
const launchctl = (...args) => spawnSync("launchctl", args, { stdio: "ignore" }).status ?? 1;
|
|
42
44
|
const domain = () => `gui/${userInfo().uid}`;
|
|
45
|
+
/** What the gateway will launch: on a managed box the aurora consumer's binary or nothing; otherwise the legacy chain's
|
|
46
|
+
* links (the PATH lookup that ends that chain happens inside the gateway, with the gateway's own PATH). */
|
|
47
|
+
function gatewayBinary(home) {
|
|
48
|
+
if (isManaged()) {
|
|
49
|
+
const st = verifyState();
|
|
50
|
+
const age = st && formatAge(st.at);
|
|
51
|
+
const toolchain = st ? `${st.result}, verified ${age === "just now" ? age : `${age} ago`}` : "managed, not verified yet (run toolchain verify)";
|
|
52
|
+
try {
|
|
53
|
+
const r = resolveToolchainBin("llama-server", { consumer: "aurora" });
|
|
54
|
+
const meta = storeEntryMeta(r.entry);
|
|
55
|
+
return { line: `${r.path} → ${r.realpath} (${meta?.name && meta.version ? `${meta.name} ${meta.version}, ` : ""}gen ${r.generation})`, realpath: r.realpath, toolchain };
|
|
56
|
+
}
|
|
57
|
+
catch (e) {
|
|
58
|
+
return { line: `unresolved: ${e instanceof ToolchainError ? e.reason : String(e)} — the gateway exits 78 until it resolves`, toolchain };
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
const link = join(home, "tools", "llama-server");
|
|
62
|
+
const legacy = [link, join(home, "tools", "llamacpp", "llama-server")].find((f) => existsSync(f));
|
|
63
|
+
if (legacy) {
|
|
64
|
+
const real = realpathSync(legacy);
|
|
65
|
+
return { line: `${legacy} → ${real}`, realpath: real, toolchain: `unmanaged (legacy resolution: ${legacy})` };
|
|
66
|
+
}
|
|
67
|
+
let dangling = false;
|
|
68
|
+
try {
|
|
69
|
+
dangling = lstatSync(link).isSymbolicLink();
|
|
70
|
+
}
|
|
71
|
+
catch { /* no link */ }
|
|
72
|
+
return { line: dangling ? `not linked (${link} → ${readlinkSync(link)} dangles)` : "not linked", toolchain: "unmanaged (legacy resolution: the gateway's PATH)" };
|
|
73
|
+
}
|
|
74
|
+
/** The executable image a live pid has mapped: the first txt entry lsof reports (-a: lsof ORs its selectors without it). */
|
|
75
|
+
function mappedExecutable(pid) {
|
|
76
|
+
const r = spawnSync("/usr/sbin/lsof", ["-nP", "-a", "-p", String(pid), "-d", "txt", "-Fn"], { encoding: "utf8", timeout: 5000 });
|
|
77
|
+
return r.status === 0 ? r.stdout.split("\n").find((l) => l.startsWith("n"))?.slice(1) : undefined;
|
|
78
|
+
}
|
|
43
79
|
const USAGE = `usage: operator gateway {start [-d]|stop|status|health|logs}
|
|
44
80
|
start run the gateway in the foreground
|
|
45
81
|
start -d start it through launchd (${LABEL})
|
|
46
82
|
stop stop the gateway and its llama-server
|
|
47
|
-
status gateway, llama-server, models and
|
|
83
|
+
status gateway, llama-server, models, binary and toolchain
|
|
48
84
|
health llama-server /health
|
|
49
85
|
logs follow the gateway and llama-server logs`;
|
|
50
86
|
export async function runGateway(args, out = (s) => process.stdout.write(s + "\n")) {
|
|
@@ -97,8 +133,14 @@ export async function runGateway(args, out = (s) => process.stdout.write(s + "\n
|
|
|
97
133
|
catch {
|
|
98
134
|
out(" (none)");
|
|
99
135
|
}
|
|
100
|
-
const
|
|
101
|
-
out(` binary: ${
|
|
136
|
+
const binary = gatewayBinary(p.home);
|
|
137
|
+
out(` binary: ${binary.line}`);
|
|
138
|
+
if (s?.pid && alive(s.pid)) {
|
|
139
|
+
const mapped = mappedExecutable(s.pid) ?? s.executable_realpath;
|
|
140
|
+
const pending = !!mapped && !!binary.realpath && mapped !== binary.realpath;
|
|
141
|
+
out(` running: pid ${s.pid} maps ${mapped ? (storeEntryOf(mapped) ?? mapped) : "an unknown binary"} (${s.build_info ?? "build unknown"})${pending ? " — RESTART PENDING" : ""}`);
|
|
142
|
+
}
|
|
143
|
+
out(` toolchain: ${binary.toolchain}`);
|
|
102
144
|
return 0;
|
|
103
145
|
}
|
|
104
146
|
case "health": {
|
package/dist/models/bench.js
CHANGED
|
@@ -88,14 +88,19 @@ export class ModelBench {
|
|
|
88
88
|
const reports = [];
|
|
89
89
|
for (const model of models) {
|
|
90
90
|
const sw = await switchModel(model.id, model, { ...opts, restartServer: true });
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
91
|
+
try {
|
|
92
|
+
if (sw.error) {
|
|
93
|
+
reports.push({ model: model.id, provider: model.provider, timestamp: new Date().toISOString(), tasks: [], summary: { totalTasks: 0, passed: 0, failed: 0, avgLatencyMs: 0, avgTokensPerSecond: 0, successRate: 0, score: 0 } });
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
this.baseUrl = "http://127.0.0.1:" + model.port + "/v1";
|
|
97
|
+
const report = await this.runSuite(model.id, opts?.tasks);
|
|
98
|
+
await this.saveReport(report);
|
|
99
|
+
reports.push(report);
|
|
100
|
+
}
|
|
101
|
+
finally {
|
|
102
|
+
await sw.server?.stop();
|
|
94
103
|
}
|
|
95
|
-
this.baseUrl = "http://localhost:" + model.port + "/v1";
|
|
96
|
-
const report = await this.runSuite(model.id, opts?.tasks);
|
|
97
|
-
await this.saveReport(report);
|
|
98
|
-
reports.push(report);
|
|
99
104
|
}
|
|
100
105
|
return reports;
|
|
101
106
|
}
|
package/dist/models/switch.js
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
|
+
import { resolveToolchainBin } from "../config/toolchain.js";
|
|
2
|
+
import { ownChild } from "../util/owned-children.js";
|
|
1
3
|
const nodeImport = (m) => import(m);
|
|
2
4
|
const DEFAULT_CONFIG_PATH = () => process.env.KODE_CONFIG ?? `${process.env.HOME ?? ""}/.0perator/config.yaml`;
|
|
5
|
+
const HEALTH_TIMEOUT_MS = 60_000;
|
|
6
|
+
const STOP_GRACE_MS = 10_000;
|
|
3
7
|
export async function switchModel(modelId, model, opts = {}) {
|
|
4
8
|
const configPath = opts.configPath ?? DEFAULT_CONFIG_PATH();
|
|
5
9
|
const { readFileSync, writeFileSync } = await nodeImport("node:fs");
|
|
@@ -16,42 +20,91 @@ export async function switchModel(modelId, model, opts = {}) {
|
|
|
16
20
|
.replace(/default:\s*.+/, `default: ${modelId}`)
|
|
17
21
|
.replace(/base_url:\s*.+/, `base_url: http://localhost:${model.port}/v1`);
|
|
18
22
|
writeFileSync(configPath, updated, "utf8");
|
|
19
|
-
let restarted = false;
|
|
20
23
|
if (opts.restartServer && model.provider === "llama-server" && model.path) {
|
|
21
24
|
try {
|
|
22
|
-
const
|
|
23
|
-
|
|
24
|
-
await new Promise(r => setTimeout(r, 1000));
|
|
25
|
-
const bin = opts.llamaServerBin ?? "/opt/homebrew/bin/llama-server";
|
|
26
|
-
const args = [
|
|
27
|
-
"--model", model.path, "--host", "0.0.0.0", "--port", String(model.port),
|
|
28
|
-
"--ctx-size", String(model.capabilities.contextWindow || 32768),
|
|
29
|
-
"--n-gpu-layers", "999", "--flash-attn", "on", "--jinja",
|
|
30
|
-
"--parallel", "2", "--cont-batching",
|
|
31
|
-
...(opts.serverArgs ?? []),
|
|
32
|
-
];
|
|
33
|
-
execSync(`nohup ${bin} ${args.join(" ")} > /tmp/llama-bench.log 2>&1 &`, { timeout: 5000 });
|
|
34
|
-
restarted = true;
|
|
35
|
-
let healthy = false;
|
|
36
|
-
for (let i = 0; i < 30; i++) {
|
|
37
|
-
await new Promise(r => setTimeout(r, 2000));
|
|
38
|
-
try {
|
|
39
|
-
const resp = await fetch(`http://localhost:${model.port}/health`);
|
|
40
|
-
if (resp.ok) {
|
|
41
|
-
healthy = true;
|
|
42
|
-
break;
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
catch { }
|
|
46
|
-
}
|
|
47
|
-
if (!healthy)
|
|
48
|
-
return { previous, current: modelId, provider: model.provider, port: model.port, restarted, error: "server did not become healthy within 60s" };
|
|
25
|
+
const server = await startServer(model, opts);
|
|
26
|
+
return { previous, current: modelId, provider: model.provider, port: model.port, restarted: true, server };
|
|
49
27
|
}
|
|
50
28
|
catch (e) {
|
|
51
29
|
return { previous, current: modelId, provider: model.provider, port: model.port, restarted: false, error: e?.message ?? String(e) };
|
|
52
30
|
}
|
|
53
31
|
}
|
|
54
|
-
return { previous, current: modelId, provider: model.provider, port: model.port, restarted };
|
|
32
|
+
return { previous, current: modelId, provider: model.provider, port: model.port, restarted: false };
|
|
33
|
+
}
|
|
34
|
+
async function portInUse(port) {
|
|
35
|
+
const { connect } = await nodeImport("node:net");
|
|
36
|
+
return new Promise((resolve) => {
|
|
37
|
+
const s = connect({ host: "127.0.0.1", port });
|
|
38
|
+
const done = (busy) => { s.destroy(); resolve(busy); };
|
|
39
|
+
s.once("connect", () => done(true));
|
|
40
|
+
s.once("error", (e) => done(e.code !== "ECONNREFUSED")); // an unexplained error is not proof the port is free
|
|
41
|
+
s.setTimeout(2000, () => done(true));
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
async function startServer(model, opts) {
|
|
45
|
+
const port = model.port;
|
|
46
|
+
const extra = opts.serverArgs ?? [];
|
|
47
|
+
if (extra.some((a) => /^--(host|port)(=|$)/.test(a)))
|
|
48
|
+
throw new Error("serverArgs may not set --host or --port: the server binds 127.0.0.1 on the model's port");
|
|
49
|
+
if (await portInUse(port))
|
|
50
|
+
throw new Error(`port ${port} is already in use — refusing to start a second server there`);
|
|
51
|
+
const bin = opts.llamaServerBin ?? resolveToolchainBin("llama-server", { consumer: "arena" }).path;
|
|
52
|
+
const [{ spawn }, fs, { join }, { homedir }] = await Promise.all([nodeImport("node:child_process"), nodeImport("node:fs"), nodeImport("node:path"), nodeImport("node:os")]);
|
|
53
|
+
const logDir = join(process.env.OPERATOR_HOME || join(homedir(), ".operator"), "logs");
|
|
54
|
+
fs.mkdirSync(logDir, { recursive: true });
|
|
55
|
+
const log = join(logDir, `bench-${port}.log`);
|
|
56
|
+
const args = [
|
|
57
|
+
"--model", model.path, "--host", "127.0.0.1", "--port", String(port),
|
|
58
|
+
"--ctx-size", String(model.capabilities.contextWindow || 32768),
|
|
59
|
+
"--n-gpu-layers", "999", "--flash-attn", "on", "--jinja",
|
|
60
|
+
"--parallel", "2", "--cont-batching",
|
|
61
|
+
...extra,
|
|
62
|
+
];
|
|
63
|
+
const fd = fs.openSync(log, "a", 0o600);
|
|
64
|
+
let child;
|
|
65
|
+
try {
|
|
66
|
+
child = spawn(bin, args, { stdio: ["ignore", fd, fd] });
|
|
67
|
+
}
|
|
68
|
+
finally {
|
|
69
|
+
fs.closeSync(fd);
|
|
70
|
+
}
|
|
71
|
+
ownChild(child, `bench llama-server :${port}`, { cmd: [bin, ...args].join(" ") });
|
|
72
|
+
let gone = false;
|
|
73
|
+
let spawnError;
|
|
74
|
+
const exited = new Promise((res) => {
|
|
75
|
+
child.once("exit", () => { gone = true; res(); });
|
|
76
|
+
child.once("error", (e) => { gone = true; spawnError = e; res(); });
|
|
77
|
+
});
|
|
78
|
+
const within = (ms) => new Promise((res) => {
|
|
79
|
+
const t = setTimeout(() => res(false), ms);
|
|
80
|
+
void exited.then(() => { clearTimeout(t); res(true); });
|
|
81
|
+
});
|
|
82
|
+
const handle = {
|
|
83
|
+
pid: child.pid ?? 0,
|
|
84
|
+
port,
|
|
85
|
+
async stop(graceMs = STOP_GRACE_MS) {
|
|
86
|
+
if (gone)
|
|
87
|
+
return;
|
|
88
|
+
child.kill("SIGTERM");
|
|
89
|
+
if (await within(graceMs))
|
|
90
|
+
return;
|
|
91
|
+
child.kill("SIGKILL");
|
|
92
|
+
await within(5000);
|
|
93
|
+
},
|
|
94
|
+
};
|
|
95
|
+
const deadline = Date.now() + HEALTH_TIMEOUT_MS;
|
|
96
|
+
while (!gone && Date.now() < deadline) {
|
|
97
|
+
try {
|
|
98
|
+
if ((await fetch(`http://127.0.0.1:${port}/health`, { signal: AbortSignal.timeout(2000) })).ok)
|
|
99
|
+
return handle;
|
|
100
|
+
}
|
|
101
|
+
catch { }
|
|
102
|
+
await within(250);
|
|
103
|
+
}
|
|
104
|
+
await handle.stop();
|
|
105
|
+
if (spawnError)
|
|
106
|
+
throw new Error(`could not start ${bin}: ${spawnError.message}`);
|
|
107
|
+
throw new Error(gone ? `llama-server exited before it became healthy (log: ${log})` : `server did not become healthy within 60s (log: ${log})`);
|
|
55
108
|
}
|
|
56
109
|
export async function currentModel(configPath) {
|
|
57
110
|
const path = configPath ?? DEFAULT_CONFIG_PATH();
|