@0perator/operator 0.1.349 → 0.1.351
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/autonomy/index.js +6 -5
- package/dist/autonomy/session-factory.js +4 -0
- package/dist/cli.js +32 -14
- 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/permissions/policy.js +5 -2
- package/dist/services/preflight.js +98 -44
- package/dist/session.js +12 -2
- 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 +38 -2
- package/dist/tools/wave-tools.js +4 -0
- package/dist/tools/wave2-tools.js +31 -9
- package/dist/ui/App.js +2 -2
- package/dist/ui/StatusRule.js +7 -6
- package/package.json +2 -2
package/dist/autonomy/index.js
CHANGED
|
@@ -276,17 +276,18 @@ export async function dispatchAutonomy(argv, settings) {
|
|
|
276
276
|
const cmd = argv[2];
|
|
277
277
|
if (!cmd || !AUTONOMY_COMMANDS.has(cmd))
|
|
278
278
|
return null;
|
|
279
|
-
// Headless paths skip the interactive preflight (cli.tsx's ensureServices), which
|
|
280
|
-
//
|
|
281
|
-
//
|
|
282
|
-
//
|
|
283
|
-
//
|
|
279
|
+
// Headless paths skip the interactive preflight (cli.tsx's ensureServices), which RESOLVES the dynamic Aurora
|
|
280
|
+
// endpoint from the operator-runtime server.json. Mirror it here — the same EnsureCfg (aurora launchd cfg +
|
|
281
|
+
// optional services) — so a headless `operator run/loop/board/routine` never sends to a baseless
|
|
282
|
+
// "/v1/chat/completions" (Failed to parse URL). Aurora itself loads on demand: the session's onDemand hook starts
|
|
283
|
+
// it for the first turn on it (session-factory.ts), so a run on another model never loads it.
|
|
284
284
|
// Guarded to the empty-base case (the only time we must discover/start), and gateway-aware: carry the
|
|
285
285
|
// gateway's published api_key (server.json) onto the endpoint config so the router authenticates to it.
|
|
286
286
|
if (!settings.endpoints.aurora.base) {
|
|
287
287
|
const auroraCfg = { base: settings.endpoints.aurora.base, ...settings.services?.aurora };
|
|
288
288
|
await ensureServices({
|
|
289
289
|
aurora: auroraCfg,
|
|
290
|
+
auroraOnDemand: true, // resolve the endpoint only: a run on Aurora loads it at its first turn
|
|
290
291
|
autopilot: settings.services?.autopilot,
|
|
291
292
|
vision: settings.services?.vision,
|
|
292
293
|
onProgress: (m) => process.stderr.write(`[services] ${m}\n`),
|
|
@@ -13,6 +13,7 @@ import { modelCtxFor, leanHarnessFor, DEFAULT_MODEL_ID } from "../router/models.
|
|
|
13
13
|
import { compactionThreshold, compactionCeilingTokens, turnWallClockMs, buildEndpointChain } from "../config/settings.js";
|
|
14
14
|
import { resolveMode } from "../classifier/modes.js";
|
|
15
15
|
import { classifierConfig } from "../classifier/config.js";
|
|
16
|
+
import { auroraOnDemand } from "../services/preflight.js";
|
|
16
17
|
/** Build the Aurora router from settings — the headless twin of cli.tsx's buildRouter(). Both share the one
|
|
17
18
|
* multi-tier chain builder (primary → other fleet nodes → back-compat single failover → cloud), so a
|
|
18
19
|
* wedged/degraded endpoint fails over through the whole fleet before the turn can error. */
|
|
@@ -63,6 +64,9 @@ export function createAutonomySession(settings, opts = {}) {
|
|
|
63
64
|
fastStart: settings.fastStart,
|
|
64
65
|
features: settings.features, // feature flags — registers flag-gated tools (e.g. cloudAgents) only when on
|
|
65
66
|
activeModel: settings.activeModel,
|
|
67
|
+
// A local Aurora loads for the first turn on it (owner, 11/03), never for the run starting: a run on moa or cortana
|
|
68
|
+
// (setModel below) never loads it.
|
|
69
|
+
onDemand: auroraOnDemand(settings.endpoints.aurora, settings.services?.aurora, () => buildRouterFromSettings(settings)),
|
|
66
70
|
contextPin: settings.contextPin, // the owner's /context choice (KODE_CONTEXT wins in loadSettings) holds for headless, ACP and delegated runs too
|
|
67
71
|
permissions: opts.permissions ?? settings.permissions,
|
|
68
72
|
// Audit attribution: without these every headless/cron/dream tool event carried session:"" and no seat.
|
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 });
|
|
@@ -245,7 +245,7 @@ if (settings.computer.enabled) {
|
|
|
245
245
|
const askNames = [...COMPUTER_TOOL_NAMES, ...(chauffeurServer ? CHAUFFEUR_ACTION_NAMES : [])];
|
|
246
246
|
computerAskRules = Object.fromEntries(askNames.map((n) => [n, "ask"]));
|
|
247
247
|
// Background sub-agents have no approver, so DENY every embodiment tool, reads included.
|
|
248
|
-
const denyNames = [...COMPUTER_TOOL_NAMES, ...(chauffeurServer ? CHAUFFEUR_TOOL_NAMES : [])];
|
|
248
|
+
const denyNames = [...COMPUTER_TOOL_NAMES, "desktop_screenshot", "desktop_read", ...(chauffeurServer ? CHAUFFEUR_TOOL_NAMES : [])];
|
|
249
249
|
computerDenyRules = Object.fromEntries(denyNames.map((n) => [n, "deny"]));
|
|
250
250
|
}
|
|
251
251
|
// STANDARD MCP: report-mcp (PDF tools) ships with Operator — always injected, even without the full-fleet
|
|
@@ -644,6 +644,18 @@ function Root() {
|
|
|
644
644
|
const freeRowsRef = useRef([]);
|
|
645
645
|
const freeStaleRef = useRef(false); // served from the disk cache after a failed read → the rows say " · cached"
|
|
646
646
|
const sessionRef = useRef(null); // lazy — never reconstruct on re-render
|
|
647
|
+
// Aurora loads on demand (owner, 11/03): the first turn that needs a local Aurora starts the launchd gateway, and boot
|
|
648
|
+
// never does. The hook is built on first use; it is inert where Aurora is not a launchd job on this box.
|
|
649
|
+
const auroraHookRef = useRef(null);
|
|
650
|
+
const auroraForTurn = async (signal) => {
|
|
651
|
+
if (!auroraHookRef.current) {
|
|
652
|
+
const { auroraOnDemand } = await import("./services/preflight.js");
|
|
653
|
+
auroraHookRef.current = auroraOnDemand(settings.endpoints.aurora, settings.services?.aurora, buildRouter, () => {
|
|
654
|
+
push({ kind: "message", message: { id: nextId(), role: "system", content: "aurora is not loaded — loading it for this turn…" } });
|
|
655
|
+
});
|
|
656
|
+
}
|
|
657
|
+
return auroraHookRef.current(signal);
|
|
658
|
+
};
|
|
647
659
|
// MCP opts the foreground session into the fleet MCP tool surface (off by default: local tools
|
|
648
660
|
// only, no network fan-out at session start). Background agents stay local-only + lean.
|
|
649
661
|
if (!sessionRef.current) {
|
|
@@ -651,6 +663,8 @@ function Root() {
|
|
|
651
663
|
systemPrompt: SYSTEM_PROMPT,
|
|
652
664
|
thinkMode, // start in the SAME mode the badge shows (settings.ui.reasoning, default "think") — it was only ever the badge that defaulted on
|
|
653
665
|
router: buildRouter(),
|
|
666
|
+
applyActiveModel: true, // the persisted /model choice still applies with the shell's chain injected
|
|
667
|
+
onDemand: auroraForTurn,
|
|
654
668
|
memory: buildMemory(settings.memory), // provider composite when configured; bare store (byte-identical) otherwise
|
|
655
669
|
mcp: settings.mcp,
|
|
656
670
|
mcpHub: embodimentHub, // scoped chauffeur hub when embodiment is on (undefined otherwise → no change)
|
|
@@ -796,9 +810,10 @@ function Root() {
|
|
|
796
810
|
background: true, // endpoint gate: this is a sub-agent — its Aurora requests yield the shared single slot to the interactive main turn (fixes the sub-agent-contention crawl + "4 min for a prompt")
|
|
797
811
|
cwd, // isolation: a code-editing bg agent gets its own worktree dir here so it can't touch the foreground tree
|
|
798
812
|
temperature: settings.temperature,
|
|
799
|
-
// Sub-agents
|
|
800
|
-
//
|
|
801
|
-
|
|
813
|
+
// Sub-agents have no approval prompt: any computer_* call is denied outright, and `unattended` keeps the
|
|
814
|
+
// signature lines live (permissions/signature.ts), so a force-push, deploy or destructive command is
|
|
815
|
+
// denied too, computer control on or off. The seat's tier still applies. Everything else runs as normal.
|
|
816
|
+
permissions: { mode: "bypass", tier: settings.permissions.tier, rules: computerDenyRules, unattended: true },
|
|
802
817
|
eventSink, eventActor: EVENT_ACTOR, sessionId: SESSION_ID, // a sub-agent's tool calls belong to THIS session in the ledger
|
|
803
818
|
});
|
|
804
819
|
const r = child.setModel(model);
|
|
@@ -903,6 +918,7 @@ function Root() {
|
|
|
903
918
|
const auroraCfg = { base: bootBase, ...settings.services?.aurora };
|
|
904
919
|
reports = await preflight.ensureServices({
|
|
905
920
|
aurora: auroraCfg,
|
|
921
|
+
auroraOnDemand: true, // resolve and report Aurora only: the turn that needs it loads it
|
|
906
922
|
autopilot: settings.services?.autopilot,
|
|
907
923
|
vision: settings.services?.vision,
|
|
908
924
|
onProgress: setBootDetail,
|
|
@@ -924,14 +940,11 @@ function Root() {
|
|
|
924
940
|
if (settings.endpoints.aurora.base !== bootBase || settings.endpoints.aurora.apiKey !== bootKeyBefore) {
|
|
925
941
|
session.useRouter(buildRouter());
|
|
926
942
|
}
|
|
927
|
-
// If the lever COLD-STARTED Aurora, prime it (fire-and-forget) so the first real turn doesn't
|
|
928
|
-
// eat the graph/Metal warmup. Skipped when Aurora was already up (state "up").
|
|
929
|
-
if (reports.find((r) => r.name === "aurora")?.state === "started") {
|
|
930
|
-
void preflight.warmAurora(settings.endpoints.aurora.base, settings.endpoints.aurora.model);
|
|
931
|
-
}
|
|
932
943
|
}
|
|
933
944
|
catch { /* preflight is best-effort — fall through to the authoritative health check */ }
|
|
934
|
-
|
|
945
|
+
// A local Aurora that is not loaded is not a failed boot: it loads on the first turn that needs it, and a
|
|
946
|
+
// session on another model (moa, cortana) never needs it.
|
|
947
|
+
const ok = reports.find((r) => r.name === "aurora")?.state === "idle" || (await session.health().catch(() => false));
|
|
935
948
|
setBoot(ok ? "ready" : "down");
|
|
936
949
|
if (!ok) {
|
|
937
950
|
const a = reports.find((r) => r.name === "aurora");
|
|
@@ -984,7 +997,7 @@ function Root() {
|
|
|
984
997
|
}
|
|
985
998
|
}
|
|
986
999
|
// Confirm, once in scrollback, what the lever did (started = it was down and we brought it up).
|
|
987
|
-
const line = reports.map((r) => `${r.name} ${r.state === "up" ? "✓" : r.state === "started" ? "✓ started" : "✗"}`).join(" · ");
|
|
1000
|
+
const line = reports.map((r) => `${r.name} ${r.state === "up" ? "✓" : r.state === "started" ? "✓ started" : r.state === "idle" ? "on demand" : "✗"}`).join(" · ");
|
|
988
1001
|
if (line) {
|
|
989
1002
|
// SearXNG is lazy (starts on first web_search), but if a backend is ALREADY reachable — an explicit
|
|
990
1003
|
// KODE_SEARXNG_URL, or a container still up from a prior session — show ✓ instead of a misleading
|
|
@@ -2686,7 +2699,7 @@ function Root() {
|
|
|
2686
2699
|
? `${spin} reading your prompt… (${fmtDuration(elapsed)})`
|
|
2687
2700
|
: `${spin} ${fmtMeta(elapsed, liveTok)}`
|
|
2688
2701
|
: metrics;
|
|
2689
|
-
return (_jsx(App, { messages: entries, live: live, status: status, stepLabel: stepLabel, prefill: prefill, liveTools: liveTools, route: route, ctxPct: ctxPct,
|
|
2702
|
+
return (_jsx(App, { messages: entries, live: live, status: status, stepLabel: stepLabel, prefill: prefill, liveTools: liveTools, route: route, ctxPct: ctxPct, ctxWindow: session.currentModel() === "moa" ? (ctxPin ? fmtCtx(ctxPin) : undefined) : fmtCtx(ctxPin ? Math.min(ctxPin, session.servedContext()) : session.servedContext()), version: VERSION, fullscreen: FULLSCREEN, metrics: liveMetrics, sessionTokens: session.sessionTokens() + liveTok, authUser: authUser, tier: EVENT_ACTOR.tier, planMode: planMode, thinkMode: thinkMode, verbs: settings.verbs, bgAgents: bgAgents, shellJobs: shellJobs, onBackground: onBackground, tasks: tasks, onSubmit: onSubmit, onQueue: onQueue, queuedPreview: queuedPreview, onEditQueued: popQueued, onDropQueued: onDropQueued, onInterrupt: onInterrupt, onCycleMode: onCycleMode, onCycleContext: onCycleContext, opMode: opMode, rcConnected: rcConnected, rcActive: rcActive, caffeinated: caffeinated, approval: approval, question: question, modelPicker: modelPicker, secretPrompt: secretPrompt, planExitPicker: planExitPicker, artifactsPicker: artifactsPicker, sessionsPicker: sessionsPicker, onApprovalDecide: (allow, always) => {
|
|
2690
2703
|
const cur = approval;
|
|
2691
2704
|
if (cur)
|
|
2692
2705
|
settleApproval(cur.id, allow, always); // first-wins with any remote follower answer
|
|
@@ -2716,6 +2729,11 @@ if (process.argv[2] === "gateway") {
|
|
|
2716
2729
|
const { runGateway } = await import("./gateway-cli.js");
|
|
2717
2730
|
process.exit(await runGateway(process.argv.slice(3)));
|
|
2718
2731
|
}
|
|
2732
|
+
// `operator toolchain …` — the toolchain CLI (toolchain/ in the repo, dist/toolchain/ in the package).
|
|
2733
|
+
if (process.argv[2] === "toolchain") {
|
|
2734
|
+
const { runToolchain } = await import("./toolchain-cli.js");
|
|
2735
|
+
process.exit(runToolchain(process.argv.slice(3)));
|
|
2736
|
+
}
|
|
2719
2737
|
// `operator update` (bareword) and `operator --update` both self-update.
|
|
2720
2738
|
if (process.argv[2] === "update" || process.argv.includes("--update")) {
|
|
2721
2739
|
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();
|