@0perator/operator 0.1.331 → 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.
@@ -2,6 +2,7 @@ import { acquireEndpoint, releaseEndpoint, isDegenerate, trimLoop } from "./auro
2
2
  import { anthropicKey } from "./anthropic.js";
3
3
  import { classifyFailure, backoffMs, sleep } from "./selfheal.js";
4
4
  const ANTHROPIC_VERSION = "2023-06-01";
5
+ const MAX_OUTPUT_TOKENS = 128_000; // the vendor's output ceiling for the current Claude family — a larger max_tokens is a 400
5
6
  const FETCH_TRIES = 3; // same pre-response transient retry budget as aurora.fetchChat (no bytes streamed yet → safe)
6
7
  /** OpenAI tool-call `arguments` is a JSON STRING; Anthropic `input` is an OBJECT. Parse defensively — a
7
8
  * malformed/empty string becomes `{}` (messages.ts already sanitizes history, but a live round may not). */
@@ -84,15 +85,16 @@ export function toAnthropicTools(tools) {
84
85
  }
85
86
  return out.length ? out : undefined;
86
87
  }
87
- /** Build the Anthropic /v1/messages request body from AuroraOpts. temperature is clamped to Anthropic's
88
- * [0,1] (the engine's 0.7 default is already in range; a caller passing an OpenAI-style >1 would 400). */
88
+ /** Build the Anthropic /v1/messages request body from AuroraOpts. No sampling knobs: the current Claude family
89
+ * rejects `temperature`/`top_p`/`top_k` (400), so the engine's temperature is dropped here rather than clamped.
90
+ * `thinking` is omitted on purpose — omitted means the model's adaptive default, while a token budget or
91
+ * `{type:"disabled"}` is a 400 — and max_tokens is capped at the vendor's output ceiling. */
89
92
  export function anthropicRequestBody(messages, o, stream) {
90
93
  const { system, messages: amsgs } = toAnthropicConversation(messages);
91
94
  const tools = toAnthropicTools(o.tools);
92
95
  return JSON.stringify({
93
96
  model: o.model,
94
- max_tokens: o.maxTokens ?? 8192,
95
- temperature: Math.max(0, Math.min(1, o.temperature ?? 0.7)),
97
+ max_tokens: Math.min(o.maxTokens ?? 8192, MAX_OUTPUT_TOKENS),
96
98
  ...(system ? { system } : {}),
97
99
  messages: amsgs,
98
100
  ...(tools ? { tools } : {}),
@@ -135,6 +137,11 @@ async function fetchMessages(o, key, body) {
135
137
  }
136
138
  throw lastErr;
137
139
  }
140
+ /** What the owner sees when the provider's safety classifier declines a reply. The partial output is discarded
141
+ * and no tool call from it runs — the vendor's rule for a refusal stop is "discard, then branch on stop_reason". */
142
+ export function refusalNote(category) {
143
+ return `[declined by the provider's safety classifier${category ? ` (${category})` : ""} — nothing from that reply was run]`;
144
+ }
138
145
  /** Parse the Anthropic SSE event stream into normalized deltas. Events seen:
139
146
  * message_start (usage.input_tokens), content_block_start (text | tool_use | thinking),
140
147
  * content_block_delta (text_delta | input_json_delta | thinking_delta), message_delta (stop_reason +
@@ -239,7 +246,7 @@ async function* anthropicDeltas(messages, o) {
239
246
  else if (type === "message_delta") {
240
247
  const del = j.delta;
241
248
  const u = j.usage;
242
- yield { finishReason: del?.stop_reason, usage: u?.output_tokens != null ? { output: u.output_tokens } : undefined };
249
+ yield { finishReason: del?.stop_reason, refusalCategory: del?.stop_details?.category ?? null, usage: u?.output_tokens != null ? { output: u.output_tokens } : undefined };
243
250
  }
244
251
  else if (type === "error") {
245
252
  const e = j.error;
@@ -272,6 +279,7 @@ export async function anthropicChat(messages, o) {
272
279
  let degenerate = false;
273
280
  let sinceCheck = 0;
274
281
  let finishReason;
282
+ let refusalCategory = null;
275
283
  let promptTokens;
276
284
  let outputTokens;
277
285
  const LOOP_CHECK_EVERY = 200;
@@ -285,8 +293,10 @@ export async function anthropicChat(messages, o) {
285
293
  reasoning += d.reasoning;
286
294
  o.onReasoning?.(d.reasoning);
287
295
  }
288
- if (d.finishReason)
296
+ if (d.finishReason) {
289
297
  finishReason = d.finishReason;
298
+ refusalCategory = d.refusalCategory ?? null;
299
+ }
290
300
  if (d.usage?.input != null) {
291
301
  promptTokens = d.usage.input;
292
302
  o.onMeta?.({ promptTokens: d.usage.input });
@@ -320,6 +330,18 @@ export async function anthropicChat(messages, o) {
320
330
  }
321
331
  if (degenerate)
322
332
  content = trimLoop(content);
333
+ // A refusal can land mid-stream after a complete tool_use block: nothing from a declined reply may run.
334
+ if (finishReason === "refusal") {
335
+ return {
336
+ content: refusalNote(refusalCategory),
337
+ toolCalls: [],
338
+ reasoningContent: reasoning || undefined,
339
+ stopReason: "content_filter",
340
+ tokens: outputTokens,
341
+ tokensExact: !!outputTokens && outputTokens > 0,
342
+ promptTokens,
343
+ };
344
+ }
323
345
  const toolCalls = [...tools.entries()]
324
346
  .sort(([a], [b]) => a - b)
325
347
  .map(([idx, e]) => ({
@@ -27,7 +27,7 @@ export async function anthropicComplete(system, user, opts = {}) {
27
27
  body: JSON.stringify({
28
28
  model: opts.model || DEFAULT_MODEL,
29
29
  max_tokens: opts.maxTokens ?? 4096,
30
- temperature: opts.temperature ?? 0.3,
30
+ ...(/^claude-haiku-4-5/.test(opts.model || DEFAULT_MODEL) ? { temperature: opts.temperature ?? 0.3 } : {}), // the 5.x family rejects sampling fields
31
31
  system,
32
32
  messages: [{ role: "user", content: user }],
33
33
  }),
@@ -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,
@@ -146,7 +146,7 @@ export function needsClosingSteer(content, hasOpenTasks) {
146
146
  /** True for a final the ENGINE wrote (a stop/pause/yield note or the no-reply status) rather than the model — the
147
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
148
  export function isEngineFinal(content) {
149
- return /^\s*(?:\[(?:stopped|paused|turn ended|no reply came back from the model)\b|\((?:the model returned an empty response|hit the output limit before an answer landed))/i.test(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
150
  }
151
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
152
  "one question if you are blocked. If a tool call is needed, make the call — but never return nothing.";
@@ -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);
@@ -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
+ }