@0perator/operator 0.1.330 → 0.1.332

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.
@@ -0,0 +1,110 @@
1
+ // /model's pure half — the rows and their order, the "+ Connect a provider key" action, the context step and /context
2
+ // rows, the provider rows, and what a picked answer means — so cli.tsx only wires them to the Session (the same split as
3
+ // planExit.ts). Every picker here resolves by INDEX into the entries its rows were drawn from: row text can repeat.
4
+ import { BYO_PRESETS, fmtCtx, pickerRow, shortName } from "../router/models.js";
5
+ import { markPickerOptions, portalIdFor } from "../router/portal.js";
6
+ import { CONTEXT_PRESETS } from "../config/settings.js";
7
+ import { DISCUSS } from "./QuestionPrompt.js";
8
+ /** The last /model row: an action, never a ModelProfile — so the lists fed from the registry (the ACP dropdown, a
9
+ * follower's model list) can never offer it. */
10
+ export const CONNECT_ROW = "+ Connect a provider key (Anthropic, Google, Nous, OpenAI, …)";
11
+ /** Presets whose zero-price rows /model lists once their key is connected (router/free-models.ts) — OpenRouter's
12
+ * `:free` listing joins here. */
13
+ export const FREE_ROW_PRESETS = ["nous"];
14
+ // fleet → connected providers → free rows → MOA. The built-ins already list this box (JL2) before JL1.
15
+ const group = (m) => (m.kind === "orchestrated" ? 3 : m.tier === "free" ? 2 : m.byo ? 1 : 0);
16
+ /** The picker order of a visible registry: fleet rows, the connected providers, the free rows, then MOA — a stable
17
+ * partition, so registry order decides inside each group. */
18
+ export function pickerOrder(models) {
19
+ return models.map((m, i) => ({ m, i })).sort((a, b) => group(a.m) - group(b.m) || a.i - b.i).map(({ m }) => m);
20
+ }
21
+ /** The /model rows in picker order — pickerRow for each (the active single model shows its served window), " · cached"
22
+ * on free rows served from the disk cache — closed by the connect row. */
23
+ export function modelPickerView(models, o) {
24
+ const ordered = pickerOrder(models);
25
+ const rows = ordered.map((m) => {
26
+ const active = m.id === o.active;
27
+ const row = pickerRow(m, { servedCtx: active && m.kind === "single" ? o.servedCtx : undefined });
28
+ return `${row}${o.staleFree && m.tier === "free" ? " · cached" : ""}${active ? " (active)" : ""}`;
29
+ });
30
+ return {
31
+ rows: [...rows, CONNECT_ROW],
32
+ entries: [...ordered.map((profile) => ({ kind: "model", profile })), { kind: "connect" }],
33
+ };
34
+ }
35
+ /** The rows with the portal's live markers (● ○ ✕ ?) on the model rows — same count, same order; the connect row is
36
+ * never marked. `cat` undefined leaves them as they are. */
37
+ export function markModelRows(view, cat) {
38
+ const models = view.entries.flatMap((e) => (e.kind === "model" ? [e.profile] : []));
39
+ return [...markPickerOptions(view.rows.slice(0, models.length), models.map(portalIdFor), cat), ...view.rows.slice(models.length)];
40
+ }
41
+ /** Whether a /model pick earns the "Context for this session" step: a single model whose window beats the smallest
42
+ * pin (at or under it there is nothing to choose). */
43
+ export function wantsContextStep(p, window) {
44
+ return p.kind === "single" && window > Math.min(...CONTEXT_PRESETS);
45
+ }
46
+ /** The context rows — 1M, 600K, 300K, then "auto (served N)" — with the current choice moved to the top and marked;
47
+ * a pin that is no preset (KODE_CONTEXT=262144) gets its own row, so the current one is always on screen. */
48
+ export function contextPickerView(current, served) {
49
+ const choices = [...[...CONTEXT_PRESETS].sort((a, b) => b - a), undefined];
50
+ const pins = [current, ...choices.filter((p) => p !== current)];
51
+ const name = (p) => (p === undefined ? `auto (served ${served.toLocaleString("en-US")})` : fmtCtx(p));
52
+ return { rows: pins.map((p, i) => `${name(p)}${i === 0 ? " (current)" : ""}`), pins };
53
+ }
54
+ /** The line every context change prints: `context → 600K (served 1,048,576) · fill 12%`; a pin above the served
55
+ * window says the engine runs on the served one. */
56
+ export function contextLine(pin, served, fillPct) {
57
+ const clamp = pin !== undefined && pin > served ? ` — using ${fmtCtx(served)}` : "";
58
+ return `context → ${pin === undefined ? "auto" : fmtCtx(pin)} (served ${served.toLocaleString("en-US")}${clamp}) · fill ${fillPct}%`;
59
+ }
60
+ /** `has` (auth/byo.ts hasByoToken) asked at most once per account while one /model picker is open — a keychain miss
61
+ * spawns `security` (~20-50 ms), so the open looks up only the accounts a row needs, each once. */
62
+ export function onceEach(has) {
63
+ const seen = new Map();
64
+ return (account, endpoint) => {
65
+ const k = `${account}\u0000${endpoint ?? ""}`;
66
+ let v = seen.get(k);
67
+ if (v === undefined)
68
+ seen.set(k, (v = has(account, endpoint)));
69
+ return v;
70
+ };
71
+ }
72
+ /** The connected accounts among the presets — one pass through `has` (pass the open's onceEach), each checked against
73
+ * its preset's own host so a vendor's env variable counts only there. */
74
+ export function connectedAccounts(has, presets = BYO_PRESETS) {
75
+ return new Set(Object.values(presets).filter((p) => has(p.account, p.endpoint)).map((p) => p.account));
76
+ }
77
+ /** The provider rows, from the presets in their order — never listByoAccounts, which sees only the file tier:
78
+ * `<label>`, plus " ✓ connected" for an account in `connected`. */
79
+ export function providerPickerView(connected, presets = BYO_PRESETS) {
80
+ const choices = Object.entries(presets).map(([preset, p]) => ({ preset, p }));
81
+ return { rows: choices.map(({ p }) => `${p.label}${connected.has(p.account) ? " ✓ connected" : ""}`), choices };
82
+ }
83
+ /** What a QuestionPrompt answer means for a picker whose rows were drawn from `entries`: the row picked (by index), the
84
+ * owner's typed reply, or null — the empty reply / ctrl+c that resolves DISCUSS is never applied as a choice. */
85
+ export function pickerAnswer(entries, answer, index) {
86
+ if (index !== undefined)
87
+ return index >= 0 && index < entries.length ? { entry: entries[index] } : null;
88
+ const typed = answer.trim();
89
+ return !typed || answer === DISCUSS ? null : { typed };
90
+ }
91
+ /** The /model line after a pick: `model → <id> · ctx N% · turns N`; a free row repeats its caveat instead. */
92
+ export function modelLine(id, chosen, ctxPct, turns) {
93
+ if (chosen?.tier === "free")
94
+ return `model → ${id} · ${chosen.desc ?? "free tier"}`;
95
+ return `model → ${id} · ctx ${ctxPct}% · turns ${turns}`;
96
+ }
97
+ /** After a key is stored: the rows it unlocked, by name — or why none show yet. */
98
+ export function keyStoredLine(account, rows, preset, free = false) {
99
+ if (rows.length)
100
+ return `${account} key stored — rows added: ${rows.map(shortName).join(", ")}`;
101
+ return free
102
+ ? `${account} key stored — its free rows did not load yet; /model fetches them again`
103
+ : `${account} key stored — no /model row uses it yet: operator auth byo-model --preset ${preset} adds one`;
104
+ }
105
+ /** True for text that reads as a credential, not a model id (a vendor key prefix, or one long unbroken token): such text is
106
+ * never echoed back in an "unknown model" line, which would put it in the transcript and relay it to followers. */
107
+ export function looksLikeSecret(text) {
108
+ const t = text.trim();
109
+ return /^(?:sk-|sk_|ghp_|gho_|xai-|AIza|op_|key-)/.test(t) || /^[A-Za-z0-9_\-]{40,}$/.test(t);
110
+ }
@@ -4,7 +4,9 @@ export const SLASH_COMMANDS = [
4
4
  { name: "login", description: "sign in: /login opens the browser to approve; or /login <email> for a 6-digit code (then /login <code>), or /login <token>", args: "[email|code|token]" },
5
5
  { name: "logout", description: "sign out and clear stored credentials" },
6
6
  { name: "whoami", description: "show the signed-in identity" },
7
- { name: "model", description: "pick a model: operator-1m · operator-128k · qwen connectors · moa", args: "[id]" },
7
+ { name: "model", description: "pick a model — fleet, connected providers, free rows; + connect a key", args: "[id]" },
8
+ { name: "context", description: "context window for this session: 1M · 600K · 300K · auto (ctrl+x cycles)", args: "[300k|600k|1m|auto]" },
9
+ { name: "ctx", description: "alias of /context", args: "[300k|600k|1m|auto]" },
8
10
  { name: "route", description: "pin routing to an endpoint, or auto (by size)", args: "[endpoint|auto]" },
9
11
  { name: "endpoints", description: "show the Operator endpoint + live health" },
10
12
  { name: "services", description: "ensure/inspect the service lever (Operator+autopilot+searxng)", args: "[stop]" },
@@ -0,0 +1,52 @@
1
+ // Keep the Mac awake while Operator runs. A long autonomous turn on a laptop dies with the lid's idle timer; the owner
2
+ // has been running `caffeinate` by hand in every terminal tab. macOS ships `caffeinate`; `-w <pid>` ties the
3
+ // assertion to THIS process so it can never outlive the session; `-i -m -s` keep the system, disk and (on AC) sleep
4
+ // assertions up without holding the DISPLAY awake — the screen may still dim and lock while the model works, which
5
+ // is the right default for a machine left in an office overnight (`-d` is a deliberate non-default). No-op anywhere
6
+ // else (platform gate) or when the binary is missing.
7
+ import { spawn } from "node:child_process";
8
+ import { existsSync } from "node:fs";
9
+ import { ownChild } from "./owned-children.js";
10
+ export const CAFFEINATE_BIN = "/usr/bin/caffeinate";
11
+ /** Pure: the argv for the given pid. `-w` makes caffeinate exit when that pid exits. */
12
+ export function caffeinateArgs(pid) {
13
+ return ["-ims", "-w", String(pid)];
14
+ }
15
+ /** Settings then env (env wins): `KODE_CAFFEINATE=0` or `settings.caffeinate === false` turns it off. Default ON. */
16
+ export function caffeinateEnabled(setting, env = process.env) {
17
+ if (env.KODE_CAFFEINATE === "0" || env.KODE_CAFFEINATE === "false")
18
+ return false;
19
+ if (env.KODE_CAFFEINATE === "1" || env.KODE_CAFFEINATE === "true")
20
+ return true;
21
+ return setting !== false;
22
+ }
23
+ const INERT = { active: false, stop: () => { } };
24
+ /** Start the assertion for `pid` (default: this process). Returns an inert handle when unsupported. */
25
+ export function startCaffeinate(pid = process.pid, platformName = process.platform, bin = CAFFEINATE_BIN) {
26
+ if (platformName !== "darwin" || !existsSync(bin))
27
+ return INERT;
28
+ let child;
29
+ try {
30
+ child = spawn(bin, caffeinateArgs(pid), { stdio: "ignore", detached: false });
31
+ }
32
+ catch {
33
+ return INERT;
34
+ }
35
+ if (!child.pid)
36
+ return INERT;
37
+ ownChild(child, "caffeinate", { cmd: `${bin} ${caffeinateArgs(pid).join(" ")}` }); // killed at exit, reaped if we crash (-w ties it to this pid as well)
38
+ let alive = true;
39
+ child.once("exit", () => { alive = false; });
40
+ child.once("error", () => { alive = false; });
41
+ const started = child;
42
+ return {
43
+ get active() { return alive; },
44
+ get pid() { return started.pid; },
45
+ stop: () => { if (alive) {
46
+ try {
47
+ started.kill("SIGTERM");
48
+ }
49
+ catch { /* already gone */ }
50
+ } alive = false; },
51
+ };
52
+ }
@@ -2,10 +2,11 @@
2
2
  // to handleSlash. A pasted path like "/Users/foo/bar" or multi-line text starting with "/" is NOT
3
3
  // a slash command — it goes to the model as user input.
4
4
  const KNOWN = new Set([
5
- "help", "model", "route", "endpoints", "services", "audit", "dashboard", "plan", "mode",
5
+ "help", "model", "context", "ctx", "route", "endpoints", "services", "audit", "dashboard", "plan", "mode",
6
6
  "think", "ultrathink", "compact", "remember", "memory", "mcp", "whoami", "agents", "jobs", "monitor",
7
7
  "bg", "new", "clear", "exit", "quit", "stats", "login", "logout", "remote", "remotecontrol", "rc",
8
- "artifacts", "sessions", "skills", "deep-research", "deepresearch", "research", "pair",
8
+ "artifacts", "sessions", "skills", "skill", "allow", "caffeinate", "caffeine", "deep-research", "deepresearch",
9
+ "research", "pair",
9
10
  ]);
10
11
  export function isSlashCommand(text) {
11
12
  const t = text.trim();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0perator/operator",
3
- "version": "0.1.330",
3
+ "version": "0.1.332",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "operator": "dist/cli.js",