@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.
@@ -274,11 +274,15 @@ const FETCH_TRIES = 3; // a transient network drop ("fetch failed") gets a coupl
274
274
  * "fetch failed") — no SSE bytes have streamed yet, so a resend is safe and can't duplicate output.
275
275
  * An HTTP response (even 4xx/5xx) RESOLVES the fetch and is returned as-is for the caller to classify;
276
276
  * an abort (signal fired) is never retried. */
277
+ /** The chat-completions URL for a router base (`/v1` already stripped) and an optional profile chatPath. */
278
+ export function chatUrl(base, chatPath) {
279
+ return `${base}${chatPath ?? "/v1/chat/completions"}`;
280
+ }
277
281
  async function fetchChat(o, body) {
278
282
  let lastErr;
279
283
  for (let attempt = 0; attempt < FETCH_TRIES; attempt++) {
280
284
  try {
281
- return await fetch(`${o.base}/v1/chat/completions`, {
285
+ return await fetch(chatUrl(o.base, o.chatPath), {
282
286
  method: "POST",
283
287
  headers: { "Content-Type": "application/json", ...authHeaders(o) },
284
288
  body,
@@ -183,10 +183,13 @@ export function pickSummaryContent(content, reasoning) {
183
183
  return (reasoning ?? "").trim();
184
184
  }
185
185
  /** A "turn" starts at a user message. Returns the index of each turn start, in order. */
186
+ /** An engine-injected user-role message (nudges, reminders, notes — continuation.ts::engineNote) is not a turn the
187
+ * owner started and not the owner's voice: compaction must neither count it as a turn boundary nor quote it back. */
188
+ const isEngineNote = (m) => typeof m.content === "string" && m.content.startsWith("[engine note");
186
189
  export function turnStarts(conversation) {
187
190
  const idxs = [];
188
191
  conversation.forEach((m, i) => {
189
- if (m.role === "user")
192
+ if (m.role === "user" && !isEngineNote(m))
190
193
  idxs.push(i);
191
194
  });
192
195
  return idxs;
@@ -316,7 +319,7 @@ export function applyAnchorVerification(summaryMsg, evicted, outAll) {
316
319
  * exactly the shape frontier compaction uses (objective pinned at head, recency at tail) and keeps the
317
320
  * block bounded regardless of span depth. */
318
321
  export function verbatimUserTail(span, k = 3, capPerMsg = 400) {
319
- const users = span.filter((m) => m.role === "user" && typeof m.content === "string" && m.content.trim().length > 0);
322
+ const users = span.filter((m) => m.role === "user" && typeof m.content === "string" && m.content.trim().length > 0 && !isEngineNote(m));
320
323
  if (!users.length)
321
324
  return "";
322
325
  const head = users[0];
@@ -69,3 +69,101 @@ export function detectAnnouncedDelegation(content, calledTools) {
69
69
  const text = (content ?? "").trim();
70
70
  return !!text && DELEGATION_RE.test(text);
71
71
  }
72
+ // ── Owner-facing turns (0.1.331) ─────────────────────────────────────────────────────────────────────────────
73
+ // Every mid-turn nudge the engine injects rides in the USER role (the only role a chat template lets a second voice
74
+ // use), so a model read them as the owner speaking and answered them in conversation — "You're right — I wrote
75
+ // compose blocks without validating them" to a verify-gate reminder, and a stale "hello operator" answered an hour
76
+ // later with "Hey. What's the play?". The owner saw a model talking to itself. Three rules fix the shape:
77
+ // 1. an engine note is MARKED as such, so the model can tell it from the owner;
78
+ // 2. a reply that reacts to a speaker who did not speak (after round 0 nothing but tool results and engine notes
79
+ // arrive) is redirected into a one-line status for the owner;
80
+ // 3. a turn never ends on nothing: an empty reply gets one reframed retry and then an engine-composed status, and
81
+ // a final with open tasks and no question or report gets one nudge to close with a status plus a steering
82
+ // question — the owner is always left with something to answer, never a silent stop.
83
+ /** Prefix every engine-injected user-role message so the model never mistakes it for the owner. */
84
+ export const ENGINE_NOTE_PREFIX = "[engine note — automatic, not from the owner] ";
85
+ export function engineNote(text) {
86
+ return text.startsWith(ENGINE_NOTE_PREFIX) ? text : ENGINE_NOTE_PREFIX + text;
87
+ }
88
+ export const SELF_DIALOGUE_NUDGE_MAX = 2;
89
+ export const SELF_DIALOGUE_NUDGE = "Nobody spoke: the owner has sent nothing new since they last wrote, and engine notes are not the owner. Do not " +
90
+ "answer an imagined message, do not write a line for the owner and reply to it, and do not quote or paraphrase an " +
91
+ "owner message that is not in the conversation. Give the owner ONE line of status addressed to them (what is done, " +
92
+ "what you are doing now), then continue the task.";
93
+ // Concessions and acknowledgements that only make sense as a reply to a NEW message — not references to the original
94
+ // request ("as you asked, here it is" is a normal closing line).
95
+ const REACTION_RE = /\b(?:you['’]re (?:right|correct)|you are (?:right|correct)|good (?:question|point|catch)|fair (?:point|enough)|you are (?:calling|asking) me|the user (?:just )?(?:said|says|is (?:calling|asking|pointing)|called|asked|wants|pointed)|thanks for (?:pointing|the (?:reminder|nudge|catch)))\b/i;
96
+ // A fabricated exchange inside one reply: a greeting/question line written FOR the owner and then answered below it
97
+ // (a greeting-question that IS the whole reply is a real question to the owner).
98
+ const FABRICATED_LINE_RE = /^(?:hey|hi|hello|yo)\b[^\n]{0,60}\?[ \t]*\n+\s*\S/im;
99
+ // A speaker-labelled line the model wrote for someone else: "User: …", "Owner: …", "> continue".
100
+ const SPEAKER_LABEL_RE = /^(?:user|owner|human|james|you)\s*:\s*\S/im;
101
+ // A reply that is NOTHING but a greeting, after the owner has already been answered in this turn: the model is
102
+ // replying to a stale "hello" from the start of the conversation ("Hey. What's the play?" an hour into a fix round).
103
+ const GREETING_ONLY_RE = /^(?:hey|hi|hello|yo)\b[^\n]{0,80}$/i;
104
+ /** True when a model reply reacts to a speaker who did not speak. `repliesSinceOwner` is 0 for the first model
105
+ * reply after the owner wrote — the turn's first real reply, or the one right after an ask_user answer landed —
106
+ * where acknowledging (or greeting) is fine. */
107
+ export function detectSelfDialogue(content, repliesSinceOwner) {
108
+ if (repliesSinceOwner < 1)
109
+ return false;
110
+ const text = (content ?? "").trim();
111
+ if (!text)
112
+ return false;
113
+ return REACTION_RE.test(text) || FABRICATED_LINE_RE.test(text) || SPEAKER_LABEL_RE.test(text) || GREETING_ONLY_RE.test(text);
114
+ }
115
+ /** A model that was just told what the marker means may echo it back; the owner must never see it. */
116
+ export function stripEngineEcho(content) {
117
+ return (content ?? "").replace(/^\s*\[engine note[^\]]*\]\s*/i, "").replace(/^\s*engine note:\s*/i, "");
118
+ }
119
+ export const CLOSING_NUDGE = "You are about to end this turn with work still open and no question for the owner. Either continue the open " +
120
+ "items now, or close properly: one line of status per open item (done / in progress / blocked and why) and " +
121
+ "ONE question whose answer steers the next step. Never end on a bare stop.";
122
+ /** Unattended runs have nobody to answer a question: close with the status and the next step instead. */
123
+ export const CLOSING_NUDGE_UNATTENDED = "You are about to end this turn with work still open. Either continue the open items now, or close properly: one " +
124
+ "line of status per open item (done / in progress / blocked and why) and the next step you will take when resumed. " +
125
+ "Never end on a bare stop.";
126
+ const QUESTION_RE = /[??]\s*(?:\*\*|_)?\s*$/m;
127
+ // A labelled status report ("Status: …", "## Progress", "Open items —"), not a sentence that merely starts with "done".
128
+ const STATUS_RE = /^(?:#{1,4}\s*|\*\*)?(?:status|where (?:things|we) (?:stand|are)|progress|open items?|next steps?|blocked(?: on)?)\b\s*(?:\*\*)?\s*[:—–-]/im;
129
+ // A final that names remaining work without a task list ("cameras and lights are still to do").
130
+ const REMAINING_RE = /\b(?:still to do|still (?:need|needs|remain)|remaining|left to do|to do next|not (?:yet )?done|haven['’]t (?:done|finished|started)|next up)\b/i;
131
+ /** True when a text-only final should not end the turn as is: work remains (open task-list items, or — with no task
132
+ * list — the text itself names remaining work) and the text neither asks the owner anything, hands back, nor
133
+ * reports status. A hand-back ("let me know…") or a report already leaves the owner with something to act on. */
134
+ export function needsClosingSteer(content, hasOpenTasks) {
135
+ const text = (content ?? "").trim();
136
+ if (!hasOpenTasks && !(text && REMAINING_RE.test(text)))
137
+ return false;
138
+ if (!text)
139
+ return true;
140
+ if (QUESTION_RE.test(text))
141
+ return false;
142
+ if (HANDBACK_RE.test(text) || SUMMARY_RE.test(text) || STATUS_RE.test(text))
143
+ return false;
144
+ return true;
145
+ }
146
+ /** True for a final the ENGINE wrote (a stop/pause/yield note or the no-reply status) rather than the model — the
147
+ * flywheel must not grade it as the model's answer and a planner must not accept it as a sub-agent's result. */
148
+ export function isEngineFinal(content) {
149
+ return /^\s*(?:\[(?:stopped|paused|turn ended|no reply came back from the model|declined by the provider)\b|\((?:the model returned an empty response|hit the output limit before an answer landed))/i.test(content ?? "");
150
+ }
151
+ export const EMPTY_REPLY_NUDGE = "Your reply was empty. Answer the owner now in plain text: what is done, what you are doing or about to do, and " +
152
+ "one question if you are blocked. If a tool call is needed, make the call — but never return nothing.";
153
+ /** The active task list as the owner should read it — without the compaction header renderActiveTasks() carries. */
154
+ function tasksBlock(activeTasks) {
155
+ const t = (activeTasks ?? "").replace(/^\[Your active task list[^\n]*\]\n?/, "").trim();
156
+ return t ? `\n\nOpen items:\n${t}` : "";
157
+ }
158
+ /** The engine's own closing status when the model gives nothing: the active task list (when any) and a steer. */
159
+ export function emptyReplyStatus(activeTasks, tries) {
160
+ const tasks = tasksBlock(activeTasks) || "\n\nNo open items on the task list.";
161
+ return `[no reply came back from the model after ${tries} tries. Where things stand:${tasks}\n\nTell me which step to take next, or say "continue" to resume from here.]`;
162
+ }
163
+ /** Append the active task list and a steer to an engine stop note. A yield note (sub-agents will resume the turn)
164
+ * gets the list only — asking the owner to steer there would contradict "nothing needed from you". */
165
+ export function closeStopNote(note, activeTasks) {
166
+ const yielded = /sub-agents? (?:are running|dispatched)|waiting on sub-agents/i.test(note);
167
+ const steer = yielded ? "" : `\n\nTo steer: tell me which step to take next, or say "continue" to resume from here.`;
168
+ return note + tasksBlock(activeTasks) + steer;
169
+ }
@@ -4,14 +4,15 @@
4
4
  // single adapter that binds them, and the surface kode-web imports rather than reimplementing.
5
5
  import { AuroraRouter } from "../router/router.js";
6
6
  import { globalTokenMeter } from "./token-meter.js";
7
- const toRE = (e) => ({
7
+ const toRE = (e, pin) => ({
8
8
  base: e.base,
9
9
  model: e.model,
10
- ctxWindow: e.ctxLimit,
10
+ ctxWindow: pin && pin > 0 ? Math.min(e.ctxLimit, pin) : e.ctxLimit,
11
11
  label: e.name,
12
12
  token: e.token,
13
13
  loopbackAuth: e.loopbackAuth,
14
14
  transport: e.transport,
15
+ chatPath: e.chatPath,
15
16
  });
16
17
  function estimateTokens(messages, tools) {
17
18
  const chars = JSON.stringify(messages).length + (tools ? JSON.stringify(tools).length : 0);
@@ -21,16 +22,16 @@ function estimateTokens(messages, tools) {
21
22
  return Math.ceil(chars / globalTokenMeter.pooledPromptRatio());
22
23
  }
23
24
  /** Wrap an AuroraRouter so the agentic loop can call select()/recover(). */
24
- export function engineRouter(inner = new AuroraRouter()) {
25
+ export function engineRouter(inner = new AuroraRouter(), opts = {}) {
25
26
  return {
26
27
  select(messages, tools) {
27
- return toRE(inner.routeBySize(estimateTokens(messages, tools)));
28
+ return toRE(inner.routeBySize(estimateTokens(messages, tools)), opts.contextPin?.());
28
29
  },
29
30
  recover(failed, kind) {
30
31
  // context_exceeded → jump to the largest window; busy/unavailable → hop to a healthy one.
31
32
  const next = kind === "context_exceeded" ? inner.escalate() : inner.failover();
32
33
  // If the router hands back the same endpoint, there's nowhere further to go → exhausted.
33
- return next.base === failed.base ? null : toRE(next);
34
+ return next.base === failed.base ? null : toRE(next, opts.contextPin?.());
34
35
  },
35
36
  observeContext(endpoint, servedCtx) {
36
37
  inner.observeContextLimit(endpoint.base, servedCtx); // clamp the roster's optimistic ctxLimit to the served truth
@@ -14,15 +14,42 @@ const VERIFY_HEADS = new Set([
14
14
  "npm", "pnpm", "yarn", "bun", "npx", "node", "deno", "tsc", "tsx", "vitest", "jest", "mocha",
15
15
  "pytest", "python", "python3", "unittest", "go", "cargo", "rustc", "make", "cmake", "ctest",
16
16
  "gradle", "mvn", "dotnet", "rspec", "rake", "ruff", "mypy", "pyright", "eslint", "phpunit", "bats",
17
+ // runners that wrap the above, and the checks a docs/config deliverable has (a markdown repo is not
18
+ // "nothing runnable": links, embedded compose/yaml, lint — 2026-10-28 SmartBase fix round)
19
+ "poetry", "uv", "tox", "nox", "pipenv", "pre-commit", "ruby", "perl", "php", "swift", "xcodebuild",
20
+ "docker", "markdownlint", "markdownlint-cli2", "lychee", "markdown-link-check", "vale", "yamllint",
21
+ "shellcheck", "hadolint",
17
22
  ]);
18
- function segmentHeads(cmd) {
23
+ function segmentArgs(cmd) {
19
24
  return cmd
20
25
  .split(/\|\||&&|[;|&\n]/) // pipeline / list segments
21
26
  .map((s) => s.trim())
22
27
  .filter(Boolean)
23
28
  .map((s) => s.replace(/^(?:[A-Za-z_][A-Za-z0-9_]*=\S+\s+)+/, "")) // strip leading VAR=val env prefixes
24
29
  .map((s) => s.replace(/^(?:cd\s+\S+\s*(?:&&|;)\s*)/, "")) // strip a leading `cd x &&`
25
- .map((s) => (s.split(/\s+/)[0] || "").replace(/^.*\//, "")); // basename of the head token
30
+ .map((s) => s.split(/\s+/).filter(Boolean))
31
+ .filter((t) => t.length > 0);
32
+ }
33
+ // `docker ps` / `docker images` report state, the same class as `ls`: only a validator, a build or a real run checks
34
+ // anything — `compose … config|build|run|up`, `build`, `buildx build`, `run`, `manifest inspect` (an image resolves).
35
+ function dockerVerifies(rest) {
36
+ const sub = rest.find((t) => !t.startsWith("-"));
37
+ if (sub === "compose")
38
+ return rest.some((t) => t === "config" || t === "build" || t === "run" || t === "up");
39
+ if (sub === "manifest")
40
+ return rest.includes("inspect");
41
+ if (sub === "buildx")
42
+ return rest.includes("build");
43
+ return sub === "build" || sub === "run";
44
+ }
45
+ function segmentVerifies(args) {
46
+ const head = args[0].replace(/^.*\//, ""); // basename of the head token
47
+ if (!VERIFY_HEADS.has(head))
48
+ return false;
49
+ const rest = args.slice(1);
50
+ if (rest.length === 1 && /^(?:-v|-V|--version|version|-h|--help|help)$/.test(rest[0]))
51
+ return false; // a version/help probe checks nothing
52
+ return head === "docker" ? dockerVerifies(rest) : true;
26
53
  }
27
54
  /** True when `cmd` is a real build/test/typecheck/run — i.e. counts as a verification. */
28
55
  export function isVerifyCmd(cmd) {
@@ -34,7 +61,7 @@ export function isVerifyCmd(cmd) {
34
61
  // STRING (quoting lives inside scripts). Reject at the gate; callers downgrade to not-verified.
35
62
  if (/\$\(|`/.test(cmd))
36
63
  return false;
37
- if (segmentHeads(cmd).some((h) => VERIFY_HEADS.has(h)))
64
+ if (segmentArgs(cmd).some(segmentVerifies))
38
65
  return true;
39
66
  // Running a local script/binary is also a verify: ./x, bash x.sh, sh x.sh — but not `bash -c '...'`.
40
67
  return /(?:^|\|\||&&|[;|&]\s*)\s*\.?\/\S/.test(cmd) || /\b(?:bash|sh|zsh)\s+[^-]\S*/.test(cmd);
@@ -0,0 +1,83 @@
1
+ // Live progress journal: progress is saved WHILE a turn runs, not only when the model remembers to call
2
+ // session_handoff or when compaction fires. After every tool round that changed something (a landed file write/edit
3
+ // or a task_* call) the shell rewrites one marker-delimited block at the END of the per-working-directory handoff
4
+ // file — the file the next session in this directory auto-loads ("continue from where it leaves off"). A mid-flight
5
+ // cutoff (a killed session, a wedged model, an empty reply) therefore loses nothing the owner would have to ask for:
6
+ // the request, the task list with its states, the files touched and the last thing the model said are already on
7
+ // disk. The block is keyed by session (two tabs in one directory keep their own), rewritten atomically (tmp +
8
+ // rename, so ENOSPC or a kill mid-write never truncates the owner's handoff), budgeted to fit the 6000-char tail the
9
+ // persona loads, and settled ("turn completed") when the turn ends normally so a finished turn is never offered as
10
+ // something to resume.
11
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
12
+ import { dirname, relative, isAbsolute } from "node:path";
13
+ export const LIVE_START = "<!-- live-progress:start";
14
+ export const LIVE_END = "<!-- live-progress:end -->";
15
+ const MUTATING = new Set(["file_write", "file_edit", "task_add", "task_update", "task_clear"]);
16
+ const MAX_FILES = 12;
17
+ const MAX_TASK_CHARS = 80;
18
+ const MAX_BLOCK_CHARS = 1500;
19
+ const ERROR_RESULT = /^\s*(?:error\b|loop guard|permission denied)/i;
20
+ const landed = (e) => !ERROR_RESULT.test(e.result ?? "");
21
+ /** True when a tool round changed state worth journaling (a failed write is not progress). */
22
+ export function roundProgressed(events) {
23
+ return events.some((e) => MUTATING.has(e.name) && landed(e));
24
+ }
25
+ /** The file paths a round actually touched (file_write / file_edit `path` whose result was not an error). */
26
+ export function touchedPaths(events) {
27
+ return events.filter((e) => (e.name === "file_write" || e.name === "file_edit") && landed(e)).map((e) => String(e.args?.path ?? "")).filter(Boolean);
28
+ }
29
+ const MARK = { pending: "[ ]", in_progress: "[>]", done: "[x]", cancelled: "[~]" };
30
+ const openTag = (session) => `${LIVE_START} ${session} -->`;
31
+ const clip = (s, n) => (s.length <= n ? s : s.slice(0, n - 1) + "…");
32
+ const rel = (p, cwd) => (cwd && isAbsolute(p) && p.startsWith(cwd) ? relative(cwd, p) || "." : p);
33
+ /** Pure: the block as it lands in the handoff file (budgeted to stay inside the tail the next session reads). */
34
+ export function liveProgressBlock(p) {
35
+ const at = (p.at ?? new Date()).toISOString();
36
+ const head = p.completed
37
+ ? `## Live progress — turn completed ${at} (nothing to resume from here)`
38
+ : `## Live progress (auto-saved ${at}) — the turn may have been cut off here; resume from this`;
39
+ const tasks = p.tasks.length
40
+ ? p.tasks.map((t) => `${MARK[t.status] ?? "[ ]"} #${t.id} ${clip(t.text.replace(/\s+/g, " "), MAX_TASK_CHARS)} (${t.status})`).join("\n")
41
+ : "(no task list this turn)";
42
+ const files = [...new Set(p.touched.map((f) => rel(f, p.cwd)))];
43
+ const shown = files.slice(-MAX_FILES);
44
+ const fileList = shown.length ? shown.join("\n") + (files.length > shown.length ? `\n(+${files.length - shown.length} earlier)` : "") : "(none yet)";
45
+ const body = [
46
+ head,
47
+ `REQUEST: ${clip(p.request.replace(/\s+/g, " ").trim(), 400)}`,
48
+ `TASKS:\n${tasks}`,
49
+ `FILES TOUCHED THIS TURN:\n${fileList}`,
50
+ p.narration?.trim() ? `LAST SAID: ${clip(p.narration.replace(/\s+/g, " ").trim(), 300)}` : "",
51
+ ].filter(Boolean).join("\n");
52
+ return `${openTag(p.session)}\n${clip(body, MAX_BLOCK_CHARS)}\n${LIVE_END}\n`;
53
+ }
54
+ /** Remove THIS session's block (complete, or half-written after a crash) from the handoff text. */
55
+ function withoutOwnBlock(text, session) {
56
+ const tag = openTag(session).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
57
+ const end = LIVE_END.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
58
+ return text
59
+ .replace(new RegExp(`\\n?${tag}[\\s\\S]*?${end}\\n?`, "g"), "")
60
+ .replace(new RegExp(`\\n?${tag}[\\s\\S]*$`), "") // an unterminated block = the previous write died mid-way
61
+ .replace(/\s+$/, "");
62
+ }
63
+ /** Rewrite this session's live block at the end of `file`, atomically (tmp + rename). Best-effort; never throws. */
64
+ export function recordLiveProgress(file, p) {
65
+ if (!file)
66
+ return false;
67
+ try {
68
+ mkdirSync(dirname(file), { recursive: true });
69
+ const cur = existsSync(file) ? readFileSync(file, "utf8") : "";
70
+ const kept = withoutOwnBlock(cur, p.session);
71
+ const tmp = `${file}.${p.session}.tmp`;
72
+ writeFileSync(tmp, (kept ? kept + "\n\n" : "") + liveProgressBlock(p), { encoding: "utf8", mode: 0o600 });
73
+ renameSync(tmp, file);
74
+ return true;
75
+ }
76
+ catch {
77
+ return false;
78
+ }
79
+ }
80
+ /** The turn ended normally: mark the block completed so the next session is not told to resume a finished turn. */
81
+ export function settleLiveProgress(file, p) {
82
+ return recordLiveProgress(file, { ...p, completed: true });
83
+ }
@@ -14,7 +14,7 @@
14
14
  // either way (this allowlist is the hard gate).
15
15
  export const REMOTE_SAFE_COMMANDS = [
16
16
  { name: "help", description: "list available commands" },
17
- { name: "model", description: "pick a model: operator-1m · operator-128k · moa (mixture-of-agents)", args: "[id]" },
17
+ { name: "model", description: "pick a model — fleet, connected providers, free rows", args: "[id]" },
18
18
  { name: "route", description: "pin routing to an endpoint, or auto (by size)", args: "[endpoint|auto]" },
19
19
  { name: "endpoints", description: "show the Operator endpoint + live health" },
20
20
  { name: "services", description: "ensure/inspect the service lever (Operator+autopilot+searxng); stop searxng", args: "[stop]" },
@@ -11,7 +11,14 @@
11
11
  // settings.models (an explicit hand override by id ALWAYS wins — discovery informs, never overrides an
12
12
  // owner's choice), and cached with a short TTL so it never runs on a render/keystroke path. Kept
13
13
  // dependency-free except the ModelProfile type (the no-cycle rule models.ts documents).
14
- const DEFAULTS = { timeoutMs: 2500, marginPct: 0.98 };
14
+ /** Usable ctx = floor(n_ctx * SERVED_CTX_MARGIN): compaction lands BEFORE the served wall (the manual convention:
15
+ * operator-1m's 300000 under a 307200 wall ≈ 0.976). The one margin discovery and the session's boot probe share. */
16
+ export const SERVED_CTX_MARGIN = 0.98;
17
+ const DEFAULTS = { timeoutMs: 2500, marginPct: SERVED_CTX_MARGIN };
18
+ /** The usable window under a served n_ctx. */
19
+ export function usableCtx(nCtx, marginPct = SERVED_CTX_MARGIN) {
20
+ return Math.floor(nCtx * marginPct);
21
+ }
15
22
  /** A bare base ("http://host:8097") → the OpenAI base the AuroraRouter wants ("http://host:8097/v1").
16
23
  * settings.fleet.auroraNodes holds bare bases; ModelProfile.endpoint includes /v1. */
17
24
  function v1(base) {
@@ -55,6 +62,18 @@ async function getJson(url, timeoutMs, f) {
55
62
  clearTimeout(t);
56
63
  }
57
64
  }
65
+ /** The served window a llama.cpp `/props` body names (default_generation_settings.n_ctx, else n_ctx), or null. */
66
+ function nCtxOf(props) {
67
+ const nCtx = Number(props?.default_generation_settings?.n_ctx ?? props?.n_ctx);
68
+ return Number.isFinite(nCtx) && nCtx > 0 ? nCtx : null;
69
+ }
70
+ /** The RAW served context window of one base (`GET /props` → n_ctx), or null when it does not answer in time or is
71
+ * not a llama.cpp server (a gateway or vendor leg never serves /props). The read probeHost and the session's
72
+ * boot-time probe of the primary share; callers apply usableCtx for the engine's number. */
73
+ export async function probeServedCtx(base, opts = {}) {
74
+ const props = await getJson(`${base.replace(/\/+$/, "")}/props`, opts.timeoutMs ?? DEFAULTS.timeoutMs, opts.fetchImpl ?? fetch);
75
+ return props ? nCtxOf(props) : null;
76
+ }
58
77
  /** Probe one fleet base and build a ModelProfile from what the SERVER reports, or null if it doesn't
59
78
  * answer `/props` in time (→ absent from the picker). `/props` is the source of truth for the context
60
79
  * window (default_generation_settings.n_ctx) and the self-chosen name (model_alias); `/v1/models` is a
@@ -67,8 +86,8 @@ export async function probeHost(base, opts = {}) {
67
86
  const props = await getJson(`${bare}/props`, timeoutMs, f);
68
87
  if (!props)
69
88
  return null; // health gate: no /props → down → not offered
70
- const nCtx = Number(props?.default_generation_settings?.n_ctx ?? props?.n_ctx);
71
- if (!Number.isFinite(nCtx) || nCtx <= 0)
89
+ const nCtx = nCtxOf(props);
90
+ if (!nCtx)
72
91
  return null; // can't size it truthfully → skip
73
92
  const models = await getJson(`${v1(bare)}/models`, timeoutMs, f);
74
93
  const servedId = models?.data?.[0]?.id;
@@ -77,7 +96,7 @@ export async function probeHost(base, opts = {}) {
77
96
  // source is rejected and we fall back to a host tag rather than leak a filesystem path into the picker.
78
97
  const alias = [props?.model_alias, servedId].find((x) => typeof x === "string" && x.length > 0 && !isPathLike(x));
79
98
  const tag = hostTag(bare);
80
- const ctx = Math.floor(nCtx * marginPct);
99
+ const ctx = usableCtx(nCtx, marginPct);
81
100
  return {
82
101
  id: alias ? `fleet-${slug(alias)}-${slug(tag)}` : `fleet-${slug(tag)}`,
83
102
  label: alias ? `${alias} (${tag})` : `Aurora ${fmtK(nCtx)} @ ${tag}`,
@@ -0,0 +1,190 @@
1
+ // Free cloud models — the rows a vendor gateway serves at zero price, found the way discovery.ts finds fleet
2
+ // servers: models are DATA the serving layer advertises, never hand-typed into the catalog. Today the gateway is
3
+ // the Nous preset (BYO_PRESETS.nous); an OpenRouter `:free` listing is the same shape with another preset. Two
4
+ // public JSON reads (no auth), both best-effort and both inside ONE 4 s budget so /model never waits on them: the
5
+ // catalog (`${endpoint}/models`, OpenRouter-style `pricing.prompt`/`completion`, strings or numbers) decides what is
6
+ // free, the vendor's recommended feed decides the order. The last good list is cached on disk (10 min TTL) and
7
+ // served `stale` when the vendor is unreachable, so the rows survive a flaky link. Pure core exported for tests.
8
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
9
+ import { dirname } from "node:path";
10
+ import { operatorPath } from "../config/home.js";
11
+ /** Vendor feeds that rank the free rows (`freeRecommendedModels[].modelName`), by preset account. */
12
+ export const RECOMMENDED_FEEDS = {
13
+ nous: "https://portal.nousresearch.com/api/nous/recommended-models",
14
+ };
15
+ /** The window free rows serve when the catalog states none (the vendor's free tier, not its paid 1M). */
16
+ export const DEFAULT_FREE_CTX = 262144;
17
+ /** The caveat every free row carries — the owner reads it in the picker and again in the /model sys line. */
18
+ export const FREE_TIER_CAVEAT = "free tier — prompts may be used for training (vendor ToS §12.3); 50 RPM / 500k TPM";
19
+ /** Promotional rows with a published end date, by an id fragment. */
20
+ const PROMO_EXPIRY = { laguna: "2026-10-31" };
21
+ const DEFAULTS = { timeoutMs: 4000, ttlMs: 10 * 60_000 };
22
+ // ── pure core ─────────────────────────────────────────────────────────────────
23
+ function price(v) {
24
+ const n = typeof v === "number" ? v : typeof v === "string" && v.trim() ? Number(v) : NaN;
25
+ return Number.isFinite(n) ? n : undefined;
26
+ }
27
+ /** Free = both prices present and summing to zero. No pricing, half a pricing, or an unparsable price is PAID —
28
+ * a row we cannot price must never be handed out as free. */
29
+ export function isFreeRow(row) {
30
+ if (typeof row !== "object" || row === null)
31
+ return false;
32
+ const r = row;
33
+ if (typeof r.id !== "string" || !r.id)
34
+ return false;
35
+ const prompt = price(r.pricing?.prompt);
36
+ const completion = price(r.pricing?.completion);
37
+ return prompt !== undefined && completion !== undefined && prompt + completion === 0;
38
+ }
39
+ /** The catalog body's rows — OpenAI-shaped `{data:[…]}` or a bare array — or undefined for anything else (a 200
40
+ * with junk must not read as "no free rows" and wipe a good cache). */
41
+ export function catalogRows(body) {
42
+ if (Array.isArray(body))
43
+ return body;
44
+ const data = body?.data;
45
+ return Array.isArray(data) ? data : undefined;
46
+ }
47
+ /** `freeRecommendedModels[].modelName` from the feed body, in feed order; junk → none. */
48
+ export function recommendedNames(body) {
49
+ const list = body?.freeRecommendedModels;
50
+ if (!Array.isArray(list))
51
+ return [];
52
+ return list.map((m) => m?.modelName).filter((n) => typeof n === "string" && n.length > 0);
53
+ }
54
+ /** Row id → the profile id's tail: "/" and ":" become "-" (`upstage/solar-mini4:free` → `upstage-solar-mini4-free`). */
55
+ export function freeModelSlug(id) {
56
+ return id.replace(/[/:]/g, "-");
57
+ }
58
+ const PARAM = /^\d+(?:\.\d+)?[bm]$/i; // 501b, 122b, 0.6b
59
+ const ACTIVE = /^a\d+(?:\.\d+)?[bm]$/i; // a23b — the active share of a MoE, always right after the total
60
+ /** The name tokens of a row id: no org prefix, no `:free` SKU suffix. */
61
+ function nameTokens(id) {
62
+ return id.replace(/^.*\//, "").replace(/:free$/i, "").split(/[-_]+/).filter(Boolean);
63
+ }
64
+ function paramSpan(t) {
65
+ const i = t.findIndex((x) => PARAM.test(x));
66
+ if (i === -1)
67
+ return [-1, -1];
68
+ return [i, i + 1 < t.length && ACTIVE.test(t[i + 1]) ? i + 1 : i];
69
+ }
70
+ /** Parameter count parsed from the id: `…-501b-a23b:free` → "501B-A23B", `…-122b:free` → "122B", none → undefined. */
71
+ export function paramsFromId(id) {
72
+ const t = nameTokens(id);
73
+ const [from, to] = paramSpan(t);
74
+ return from === -1 ? undefined : t.slice(from, to + 1).join("-").toUpperCase();
75
+ }
76
+ /** Human label from the id alone (vendor `name` fields carry org prefixes and promo tags): the size tokens drop
77
+ * out, every word is title-cased, one- and two-letter words read as size codes ("S", "XS").
78
+ * `poolside/laguna-s-2.1:free` → "Laguna S 2.1"; `reflection/beam-1.0-501b-a23b:free` → "Beam 1.0". */
79
+ export function freeModelLabel(id) {
80
+ const t = nameTokens(id);
81
+ const [from, to] = paramSpan(t);
82
+ const words = t.filter((_, i) => from === -1 || i < from || i > to);
83
+ const cased = words.map((w) => (/^[a-z]{1,2}$/i.test(w) ? w.toUpperCase() : w.charAt(0).toUpperCase() + w.slice(1)));
84
+ return cased.join(" ") || id;
85
+ }
86
+ function freeProfile(row, preset) {
87
+ const params = paramsFromId(row.id);
88
+ const expiry = Object.entries(PROMO_EXPIRY).find(([frag]) => row.id.includes(frag))?.[1];
89
+ return {
90
+ id: `${preset.account}-${freeModelSlug(row.id)}`,
91
+ label: freeModelLabel(row.id),
92
+ ...(params ? { params } : {}),
93
+ box: `${preset.box ?? preset.label} · free`,
94
+ kind: "single",
95
+ tier: "free",
96
+ desc: `${FREE_TIER_CAVEAT}${expiry ? `, expires ${expiry}` : ""}`,
97
+ endpoint: preset.endpoint,
98
+ model: row.id,
99
+ ctx: typeof row.context_length === "number" && row.context_length > 0 ? row.context_length : DEFAULT_FREE_CTX,
100
+ byo: preset.account,
101
+ transport: "openai",
102
+ };
103
+ }
104
+ const norm = (id) => id.toLowerCase().replace(/:free$/, "");
105
+ /** Pure: the free rows of a catalog as profiles — rows the recommended feed names first (feed order), then the
106
+ * rest by label; duplicate ids keep the first. `rows` is what catalogRows() returned. */
107
+ export function freeModelsFromCatalog(rows, recommended, preset) {
108
+ const rank = new Map(recommended.map((n, i) => [norm(n), i]));
109
+ const seen = new Set();
110
+ const free = [];
111
+ for (const row of rows) {
112
+ if (!isFreeRow(row))
113
+ continue;
114
+ const profile = freeProfile(row, preset);
115
+ if (seen.has(profile.id))
116
+ continue;
117
+ seen.add(profile.id);
118
+ free.push({ rank: rank.get(norm(row.id)) ?? Number.POSITIVE_INFINITY, profile });
119
+ }
120
+ free.sort((a, b) => a.rank - b.rank || a.profile.label.localeCompare(b.profile.label) || a.profile.id.localeCompare(b.profile.id));
121
+ return free.map((f) => f.profile);
122
+ }
123
+ function readCache(path, endpoint) {
124
+ try {
125
+ const j = JSON.parse(readFileSync(path, "utf8"));
126
+ return j && j.endpoint === endpoint && typeof j.at === "number" && Array.isArray(j.rows) && Array.isArray(j.recommended) && j.recommended.every((r) => typeof r === "string")
127
+ ? j : undefined;
128
+ }
129
+ catch {
130
+ return undefined;
131
+ }
132
+ }
133
+ function writeCache(path, c) {
134
+ try {
135
+ mkdirSync(dirname(path), { recursive: true });
136
+ writeFileSync(path, JSON.stringify(c));
137
+ }
138
+ catch { /* best-effort: an unwritable home only costs the offline fallback */ }
139
+ }
140
+ async function getJson(f, url, signal) {
141
+ try {
142
+ const r = await f(url, { headers: { Accept: "application/json" }, signal });
143
+ return r.ok ? await r.json() : undefined;
144
+ }
145
+ catch {
146
+ return undefined;
147
+ } // unreachable / timeout / bad JSON → undefined, never into the picker
148
+ }
149
+ const inflight = new Map();
150
+ /** The vendor's free rows: the disk cache within its TTL, else a live read — catalog + feed under one timeout —
151
+ * that refreshes the cache; a failed read serves the last cached list with `stale: true` (`[]` when there is
152
+ * none). Never throws; concurrent callers share one read. */
153
+ export function fetchFreeModels(preset, opts = {}) {
154
+ const now = opts.now ?? Date.now;
155
+ const path = opts.cachePath ?? operatorPath("free-models.json");
156
+ const cached = readCache(path, preset.endpoint);
157
+ const cachedModels = cached ? freeModelsFromCatalog(cached.rows, cached.recommended, preset) : undefined;
158
+ // A stamp from the future is not fresh (it would pin a planted list forever).
159
+ if (cached && cached.at <= now() && now() - cached.at < (opts.ttlMs ?? DEFAULTS.ttlMs))
160
+ return Promise.resolve({ models: cachedModels, stale: false });
161
+ const key = `${path}\n${preset.endpoint}`;
162
+ const running = inflight.get(key);
163
+ if (running)
164
+ return running;
165
+ const f = opts.fetchImpl ?? fetch;
166
+ const feedUrl = opts.recommendedUrl ?? RECOMMENDED_FEEDS[preset.account];
167
+ const read = (async () => {
168
+ const ac = new AbortController();
169
+ const timer = setTimeout(() => ac.abort(), opts.timeoutMs ?? DEFAULTS.timeoutMs);
170
+ try {
171
+ const [catalog, feed] = await Promise.all([
172
+ getJson(f, `${preset.endpoint}/models`, ac.signal),
173
+ feedUrl ? getJson(f, feedUrl, ac.signal) : undefined,
174
+ ]);
175
+ const rows = catalogRows(catalog);
176
+ if (!rows)
177
+ return { models: cachedModels ?? [], stale: true };
178
+ const recommended = recommendedNames(feed);
179
+ const models = freeModelsFromCatalog(rows, recommended, preset);
180
+ writeCache(path, { at: now(), endpoint: preset.endpoint, rows: rows.filter(isFreeRow), recommended });
181
+ return { models, stale: false };
182
+ }
183
+ finally {
184
+ clearTimeout(timer);
185
+ inflight.delete(key);
186
+ }
187
+ })();
188
+ inflight.set(key, read);
189
+ return read;
190
+ }