Spaces:
Running
Running
Download router.js from EncryptidSystems/EdgeAI: direct link, hf CLI and curl.
- Browser
- Download file 22 kB
-
https://huggingface.co/spaces/EncryptidSystems/EdgeAI/resolve/main/router.js
- Command line
-
hf download hf://spaces/EncryptidSystems/EdgeAI/router.js
-
curl -L -o router.js https://huggingface.co/spaces/EncryptidSystems/EdgeAI/resolve/main/router.js
22 kB
| // Champ's router between models and tools, laid out as jev_mesh_2x2 | |
| // (shuttle-repos/jev-mesh-2x2-sky130a): four engines on a 2x2 grid and the die's three ROM tables. | |
| // | |
| // col 0 (small) col 1 (large) | |
| // row 0 e0_0 Lite e0_1 Balanced | |
| // row 1 e1_0 Thinking e1_1 Pro+Think row 1 thinks first | |
| // | |
| // A beat is one thing offered to the router, with the die's four kinds: | |
| // 0 chat (activation) a message for an engine | |
| // 1 tool (weight) a tool's result, loaded into the engine's context | |
| // 2 reload a model switch: the engine's context is cleared, the continuity chain stays | |
| // 3 fence the end of a turn | |
| // | |
| // The gate is the MoE gate of the monodromy note (Encryptid/monodromy/paper): the message gives two | |
| // Bernoulli bits, think (row) and size (col), and their products are the four engines' full | |
| // probabilities (they sum to 1). Top-1 as in Switch Transformers; engines the server does not have | |
| // drop out and the kept gates are renormalized as in GShard. Switching models has a capacity: a | |
| // message whose winner beats the loaded engine by less than CAPACITY follows the residual and stays on | |
| // the loaded engine. The continuity chain (chats.gather) is the shared expert every engine sees. | |
| // A tool's result is admitted into the context as hodgemix --update admits an expert: only when it | |
| // moves the same way as the question (positive cosine); otherwise it stays on its card. | |
| export const ENGINES = [ | |
| { tier: "lite", label: "Lite", row: 0, col: 0 }, | |
| { tier: "balanced", label: "Balanced", row: 0, col: 1 }, | |
| { tier: "thinking", label: "Thinking", row: 1, col: 0 }, | |
| { tier: "pro", label: "Pro+Think", row: 1, col: 1 }, | |
| ]; | |
| export const TIERS = new Set(ENGINES.map((e) => e.tier)); | |
| export const KIND = { chat: 0, tool: 1, reload: 2, fence: 3 }; | |
| // jev_route: {full, kind} -> action. The die's ROM, states 0 to 7. | |
| // stage run on the engine load load into the engine's context | |
| // reset clear the engine pass send it on (to the card, the chain) | |
| export const ROUTE = ["stage", "load", "reset", "pass", "stage", "pass", "reset", "pass"]; | |
| export function route(full, kind) { | |
| return ROUTE[(full ? 4 : 0) | (kind & 3)]; | |
| } | |
| // jev_accept: take or stall. A tool beat is taken when offered; a chat beat when the queue has room | |
| // and the engine can take it (loaded, idle); a reload or fence when the queue has room. | |
| export const DEPTH = 2; | |
| export function accept(kind, s) { | |
| const room = (s.queue || 0) < DEPTH; | |
| if (kind === KIND.tool) return "take"; | |
| if (kind === KIND.chat) return room && !s.busy && !s.loading ? "take" : "stall"; | |
| return room ? "take" : "stall"; | |
| } | |
| // jev_join: hold or emit. Emit on the clock where the engine's result, the west partials (the | |
| // continuity chain carried into this engine) and east room (a place on the page) are all present. | |
| export const JOIN = ["hold", "hold", "hold", "hold", "hold", "hold", "hold", "emit"]; | |
| export function join(result, partials, room) { | |
| return JOIN[(result ? 1 : 0) | (partials ? 2 : 0) | (room ? 4 : 0)]; | |
| } | |
| // ---- the two bits | |
| // A bare "why" (0.1 + 0.25) stays under THINK_AT: "why is the sky blue" is a | |
| // fact to look up, not a chain. "why" with any other cue still thinks. | |
| const THINK = [ | |
| [/\b(why|how come)\b/i, 0.25, "asks why"], | |
| [/\b(prove|proof|derive|reason(?:ing)?|step[- ]by[- ]step|work (?:it )?out|think (?:it )?through)\b/i, 0.35, "reasoning"], | |
| [/\b(compare|trade-?offs?|pros and cons|plan|strategy|debug|diagnose|analy[sz]e|evaluate|solve|calculate|estimate|what if)\b/i, 0.3, "analysis"], | |
| [/\d\s*[-+*/^×÷=]\s*\d|\b(integral|derivative|equation|theorem|probability|algorithm)\b/i, 0.3, "math"], | |
| [/```|\b(function|stack trace|exception|compile|regex|sql|segfault)\b/i, 0.25, "code"], | |
| ]; | |
| const SIZE = [ | |
| [/\b(detailed|thorough|in depth|comprehensive|essay|report|article|story|chapter|full|complete)\b/i, 0.3, "long form"], | |
| [/\b(architecture|design|system|protocol|specification|research|paper|explain)\b/i, 0.2, "broad"], | |
| [/https?:\/\//i, 0.1, "a page"], | |
| ]; | |
| const PLAIN = /^(hi|hey|hello|thanks|thank you|ok|okay|yes|no|sure|cool|nice|good (?:morning|night|evening))\b[\s!.,?]*$/i; | |
| // Same line think.js uses to open a chain. A logic gap at or above this | |
| // selects the thinking engine when the catalog has one. | |
| export const THINK_AT = 0.4; | |
| const LOGIC_GAP = /\b(logic gaps?|does(?:n'?t| not) follow|contradict(?:s|ion)?|missing step|non\s*sequitur)\b/i; | |
| const INFO_GAP = /\b(latest|current|right now|as of|news|headline|weather|forecast|price|cost|score|standing|election|governor|president|population|capital|who is|who was|who are|what is|what was|what are|when did|when was|when is|where is|where was|where are|which|how (?:does|do|did)|why (?:did|was|is|are))\b/i; | |
| // A recipe stays with the model. A page about the dish is the author's story, not the method. | |
| const RECIPE = /\b(?:recipes?)\b|\bhow to (?:make|cook|bake|fry|roast|prepare)\b/i; | |
| const FACT_CUE = /\b(?:search|research|look\s*up|lookup|facts?|causes?|effects?|history|impact)\b|\b(?:provide|cite|with)\s+sources?\b|\b(?:tell me about|write about|essay about)\b|\bdescribe\b(?!\s+how\b)/i; | |
| const FICTION = /\b(?:story|poem|poems|joke|jokes|haiku|limerick|fiction)\b/i; | |
| const CODE_OR_MATH = /\b(?:prove|proof|derive|function|stack trace|exception|compile|regex|sql|segfault|integral|derivative|equation|theorem|probability|algorithm)\b|\d\s*[-+*/^×÷=]\s*\d/i; | |
| const ARITHMETIC = /^\s*what(?:'s| is)?\s+\d[\d\s+\-*/^=().]*\??\s*$/i; | |
| const ABOUT_SELF = /^\s*(who are you|what(?:'s| is) your name)\b/i; | |
| // One engine. News, weather, and prices are a web search. A stable fact is | |
| // Wikipedia. The other engines were adding pages about a different subject. | |
| export const GAP_SOURCES = [ | |
| { source: "wiki", label: "Wikipedia" }, | |
| { source: "duckduckgo", label: "DuckDuckGo" }, | |
| { source: "duck", label: "duck.ai" }, | |
| { source: "gemini", label: "Gemini" }, | |
| ]; | |
| const LIVE = /\b(?:news|headlines?|breaking|latest|today|tonight|this morning|right now|weather|forecast|scores?|standings?|prices?|cost)\b/i; | |
| export function sourceFor(text) { | |
| if (LIVE.test(String(text || ""))) return GAP_SOURCES[1]; | |
| return GAP_SOURCES[0]; | |
| } | |
| // The two search engines take the subject (searchQuery). duck.ai and Gemini answer the question as asked. | |
| export const SUBJECT_SOURCES = new Set(["wiki", "duckduckgo"]); | |
| // A request to write fiction is not a question, even when it says "a dragon who is afraid". | |
| const CREATIVE = /^\s*(?:please\s+)?(?:write|tell|compose|make up|create|draft|give me)\b.{0,40}\b(?:story|stories|poem|poems|joke|jokes|haiku|limerick|fiction|song|fable|tale)\b/i; | |
| export function infoGap(text) { | |
| const t = String(text || "").trim(); | |
| if (!t || PLAIN.test(t) || ABOUT_SELF.test(t) || ARITHMETIC.test(t) || CREATIVE.test(t) || RECIPE.test(t)) return false; | |
| return INFO_GAP.test(t); | |
| } | |
| // A fact is grounded, then searched, before the write: an information gap, a | |
| // fact cue, or a picked search tool. Anything else is answered by the model | |
| // alone. A lookup the question did not need hands a small model an unrelated | |
| // snippet it is then told to answer from, which is where it starts inventing. | |
| export function needsFacts(text, opts) { | |
| const o = opts || {}; | |
| const t = String(text || "").trim(); | |
| if (!t || PLAIN.test(t) || ABOUT_SELF.test(t) || ARITHMETIC.test(t) || RECIPE.test(t)) return false; | |
| if ((o.picks || []).includes("search") || infoGap(t)) return true; | |
| if (FICTION.test(t) || CODE_OR_MATH.test(t)) return false; | |
| return FACT_CUE.test(t); | |
| } | |
| const clamp = (x) => Math.max(0, Math.min(1, x)); | |
| // features: the think and size probabilities of a message, and the cues that set them. | |
| export function features(text, opts) { | |
| const o = opts || {}; | |
| const t = String(text || "").trim(); | |
| const cues = []; | |
| let think = 0.1; | |
| let size = 0.1; | |
| if (PLAIN.test(t)) return { think: 0.02, size: 0.02, cues: ["plain"] }; | |
| for (const [re, w, cue] of THINK) if (re.test(t)) { think += w; cues.push(cue); } | |
| for (const [re, w, cue] of SIZE) if (re.test(t)) { size += w; cues.push(cue); } | |
| const words = t ? t.split(/\s+/).length : 0; | |
| if (words > 60) { size += 0.25; cues.push(words + " words"); } | |
| else if (words > 25) size += 0.12; | |
| const asks = (t.match(/\?/g) || []).length; | |
| if (asks > 1) { think += 0.15; size += 0.1; cues.push(asks + " questions"); } | |
| const lines = t.split(/\n/).filter((l) => /^\s*(?:[-*]|\d+[.)])\s+/.test(l)).length; | |
| if (lines > 2) { size += 0.15; cues.push(lines + " parts"); } | |
| if (o.think) { think = Math.max(think, 0.9); cues.push("Think on"); } | |
| if (LOGIC_GAP.test(t)) { think = Math.max(think, 0.75); cues.push("logic gap"); } | |
| if (infoGap(t)) cues.push("information gap"); | |
| return { think: clamp(think), size: clamp(size), cues }; | |
| } | |
| function planQuery(text) { | |
| return String(text || "").replace(/\s+/g, " ").trim().slice(0, 180); | |
| } | |
| // A search engine wants the subject, not the conversation around it: "Tell me | |
| // about the history of the printing press" found "The Tell-Tale Heart" on | |
| // Wikipedia, and "the history of the printing press" finds "Printing press". | |
| const LEAD_IN = /^(?:(?:please|hey|ok(?:ay)?)[,\s]+)?(?:(?:can|could|would) you\s+)?(?:research|search(?:\s+for)?|look\s*up|lookup|tell me(?:\s+about)?|explain(?:\s+to me)?|describe|give me(?:\s+an?\s+(?:overview|summary)\s+of)?|i (?:want|would like) to know(?:\s+about)?|what(?:'s| is| are| was| were)|who(?:'s| is| are| was| were)|when (?:is|was|did|does)|where (?:is|are|was|were)|why (?:is|are|was|were|do|does|did)|how (?:do|does|did|can|to)(?:\s+(?:i|you|we|they|one))?)\s+/i; | |
| export function searchQuery(text) { | |
| const raw = planQuery(text); | |
| let q = raw; | |
| for (let i = 0; i < 3; i++) { | |
| const next = q.replace(LEAD_IN, "").replace(/^(?:how|what|why)\s+/i, ""); | |
| if (next === q) break; | |
| q = next; | |
| } | |
| q = q.replace(/[\s?.!]+$/, "").trim(); | |
| q = q.replace(/^(?:(?:a|an)\s+)?(?:(?:formatted|simple|easy|basic|quick)\s+)?(?:recipes?|instructions?)(?:\s+(?:for|of|to(?:\s+make)?))?\s+/i, ""); | |
| return (q || raw).slice(0, 120); | |
| } | |
| // The think pass. The model names the route. The person's wording is not a list. | |
| export const THINK_SYSTEM = "Think about what this question is asking for. Do not answer it. " + | |
| "Reply with one word and nothing else.\n" + | |
| "fact — a checkable fact a reference page can settle, such as a place, a person, who holds an office, a capital, a date, a price, the news, or the weather.\n" + | |
| "recipe — they want to cook a dish. You know the ingredients and the method. A page about the dish is the author's story, not the recipe.\n" + | |
| "command — they want a command run, or a file listed, in the guest.\n" + | |
| "talk — you answer it yourself: a meaning, an opinion, a story, code, a greeting, math, or anything that is not a checkable fact."; | |
| export const RECIPE_SYSTEM = "Write the ingredients and the method. Use plain sentences. Start with the ingredients. A label is not the answer."; | |
| export const FACT_SYSTEM = "Answer the question the person asked. Use the notes. A label is not the answer."; | |
| const ROUTES = new Set(["fact", "recipe", "command", "talk"]); | |
| function knownRoute(s) { | |
| const w = String(s || "").toLowerCase().replace(/^[`*_"'.:!]+|[`*_"'.:!]+$/g, ""); | |
| return ROUTES.has(w) ? w : ""; | |
| } | |
| function labelLine(s) { | |
| const fields = String(s || "").trim().split(/\s+/).filter(Boolean); | |
| if (fields.length === 2 && fields[0].replace(/:$/i, "").toLowerCase() === "route") return knownRoute(fields[1]); | |
| if (fields.length !== 1) return ""; | |
| return knownRoute(fields[0]); | |
| } | |
| // Named reports that the think pass put a route word on its own line. | |
| export function named(thought) { | |
| return String(thought || "").split(/\n/).some((line) => labelLine(line)); | |
| } | |
| // A dish the model answers instead of naming. A page about the dish is not the method. | |
| const COOK = /\b(?:recipes?)\b|\bhow (?:do i |to )?(?:make|cook|bake|fry|roast|prepare)\b/i; | |
| // factWhenUnnamed is modelrun's fallback. A named route stands, including talk. | |
| // A pass that starts the answer, and never names a route, still looks up a | |
| // checkable question. A recipe stays with the model. | |
| export function factWhenUnnamed(question, thought) { | |
| if (named(thought)) return false; | |
| const q = String(question || "").trim(); | |
| if (!q || COOK.test(q)) return false; | |
| return needsFacts(q); | |
| } | |
| // routeOf reads the route word. A reflection that never names one is talk. | |
| export function routeOf(thought) { | |
| for (const line of String(thought || "").split(/\n/)) { | |
| const route = labelLine(line); | |
| if (route) return route; | |
| } | |
| return "talk"; | |
| } | |
| // Every reply is a plan. The route word decides it. fact is one lookup, then | |
| // the model writes. recipe, command, and talk are the model alone. A word | |
| // such as "recipe" in the question does not start a lookup. | |
| export function planOf(text, opts) { | |
| const o = opts || {}; | |
| const t = String(text || "").trim(); | |
| const route = ROUTES.has(o.route) ? o.route : "talk"; | |
| const picked = (o.picks || []).includes("search"); | |
| const search = route === "fact" || (picked && route !== "recipe"); | |
| if (PLAIN.test(t) && !o.think && !search) { | |
| return { info: false, logic: false, plain: true, think: false, search: false, route, steps: [{ kind: "model", role: "write" }] }; | |
| } | |
| const f = features(t, { think: o.think }); | |
| const info = search; | |
| const logic = route !== "recipe" && (!!o.think || f.think >= THINK_AT); | |
| const steps = []; | |
| if (search) { | |
| const src = sourceFor(t); | |
| const q = SUBJECT_SOURCES.has(src.source) ? searchQuery(t) : planQuery(t); | |
| steps.push({ kind: "tool", tool: "search", source: src.source, label: src.label, args: { q, source: src.source } }); | |
| } | |
| if (logic) steps.push({ kind: "model", role: "reason" }); | |
| steps.push({ kind: "model", role: "write" }); | |
| const plain = steps.length === 1 && !search; | |
| const system = route === "recipe" ? RECIPE_SYSTEM : search ? FACT_SYSTEM : ""; | |
| return { info, logic, plain, think: logic, search, route, system, steps }; | |
| } | |
| // gate: every engine's probability, p(row) * p(col). | |
| export function gate(f) { | |
| return ENGINES.map((e) => (e.row ? f.think : 1 - f.think) * (e.col ? f.size : 1 - f.size)); | |
| } | |
| // The gate picks a model only. It does not change how a token is sampled: the | |
| // guest samples at the model's own temperature and top-p. (An earlier build | |
| // turned the idle gates into a stacking presence penalty and a per-token | |
| // temperature lottery; the penalty counted the prompt's end-of-turn tokens and | |
| // held answers open past their end.) | |
| // A loop is a long span said twice. The page cuts the second copy and stops | |
| // the sample. Shorter repeats stay: a long answer's conclusion restates its | |
| // opening ("vaccines work by preparing the immune system to fight", 54 | |
| // characters), and a 48-character trigger cut that conclusion off. | |
| const NUCLEUS_MIN = 100; | |
| // An immediate refrain is the same phrase said again with only punctuation | |
| // or a short glue word between the copies. The window meets the long-span | |
| // cut, so one repeated sentence is not left between 80 and 100 characters. | |
| // A conclusion that restates an opening much later is not one: the copies | |
| // have to sit against each other. | |
| const REFRAIN_MIN = 18; | |
| const REFRAIN_GAP = 24; | |
| const REFRAIN_MAX = NUCLEUS_MIN - 1; | |
| function shortGap(gap) { | |
| return gap === "" || /^[\s,;:.!?'"()\-–—]*(?:(?:and|or|the|a|an|into|of)\s+)?$/i.test(gap); | |
| } | |
| export function refrainSpan(text) { | |
| const s = String(text || ""); | |
| const n = s.length; | |
| if (n < REFRAIN_MIN * 2) return ""; | |
| const max = Math.min(REFRAIN_MAX, Math.floor((n - 1) / 2)); | |
| for (let len = max; len >= REFRAIN_MIN; len--) { | |
| const span = s.slice(n - len); | |
| if (span.trim().length < REFRAIN_MIN) continue; | |
| // The period that ends one copy is the start of ". " plus the next copy. | |
| // That match overlaps itself. Keep looking for a copy that ends first. | |
| let prev = s.lastIndexOf(span, n - len - 1); | |
| while (prev >= 0 && prev + len > n - len) { | |
| if (prev === 0) { prev = -1; break; } | |
| prev = s.lastIndexOf(span, prev - 1); | |
| } | |
| if (prev < 0) continue; | |
| const gap = s.slice(prev + len, n - len); | |
| if (gap.length > REFRAIN_GAP || !shortGap(gap)) continue; | |
| return span; | |
| } | |
| return ""; | |
| } | |
| // A capitalized pair said again immediately ("East Berlin into East Berlin"). | |
| function nameRefrain(text) { | |
| const s = String(text || ""); | |
| const m = /([A-Z][A-Za-z'-]{1,})\s+([A-Z][A-Za-z'-]{1,})[\s,;:.!?]*$/.exec(s); | |
| if (!m) return ""; | |
| const pair = m[1] + " " + m[2]; | |
| if (pair.length < 8) return ""; | |
| const prev = s.lastIndexOf(pair, m.index - 1); | |
| // The same pair is not a copy of itself. "Ellicott City." is the answer, | |
| // and a search from before it still finds that one occurrence. | |
| if (prev < 0 || prev + pair.length > m.index) return ""; | |
| const gap = s.slice(prev + pair.length, m.index); | |
| if (gap.length > REFRAIN_GAP || !shortGap(gap)) return ""; | |
| return s.slice(m.index); | |
| } | |
| export function repeatedSpan(text) { | |
| const s = String(text || ""); | |
| const n = s.length; | |
| if (n < NUCLEUS_MIN * 2) return ""; | |
| const max = Math.min(400, Math.floor(n / 2)); | |
| for (let len = max; len >= NUCLEUS_MIN; len--) { | |
| const span = s.slice(n - len); | |
| if (span.trim().length < NUCLEUS_MIN) continue; | |
| if (s.lastIndexOf(span, n - len - 1) >= 0) return span; | |
| } | |
| return ""; | |
| } | |
| // Drops the repeated copy. on 0 leaves the text alone. | |
| export function nucleusCut(text, on) { | |
| const s = String(text || ""); | |
| if (!(Number(on) > 0)) return s; | |
| const span = repeatedSpan(s) || refrainSpan(s) || nameRefrain(s); | |
| if (!span) return s; | |
| let at = s.length - span.length; | |
| // A span can start mid-word. Cut at the word's start so no half word is left. | |
| while (at > 0 && /\w/.test(s[at - 1]) && /\w/.test(s[at])) at--; | |
| const kept = s.slice(0, at).replace(/\s+$/, ""); | |
| // A source list quotes lines that were already said. Keep that list. Rolling | |
| // back to the previous sentence was ending the answer on "Sources: 1." | |
| if (/\bSources:\s/i.test(kept)) return kept.replace(/[,;:]+$/, ""); | |
| // A loop usually starts inside a sentence. End on the last whole sentence | |
| // when one is near, so the reply does not stop on a dangling clause. | |
| // A numbered marker ("1.") is not the end of a sentence. | |
| const tail = kept.slice(-400); | |
| const m = /[\s\S]*[^.!?\d][.!?]["')\]]?(?=\s|$)|[\s\S]*\n/.exec(tail); | |
| if (m && m[0].trim()) return (kept.slice(0, kept.length - tail.length) + m[0]).replace(/\s+$/, ""); | |
| return kept.replace(/[,;:]+$/, ""); | |
| } | |
| // ---- tools: strong cues only; the + picks always win | |
| const TOOL_CUES = [ | |
| ["notes", /\b(save|write|keep|put)\b.{0,40}\b(note|notes)\b|\bmy notes\b/i], | |
| ["tasks", /\b(add|create|make)\b.{0,30}\b(task|to-?do)\b|\bmy (tasks|to-?do list)\b|\bmark\b.{0,30}\bdone\b/i], | |
| ["canvas", /\b(draw|sketch|diagram)\b|\bcanvas\b/i], | |
| ["exec", /\brun\b.{0,20}\b(command|script|code|this)\b|^\s*\$\s+\S/i], | |
| ["gather", /\b(read|open|summari[sz]e|look at)\b.{0,40}https?:\/\//i], | |
| ]; | |
| export function toolsFor(text, picks) { | |
| const out = [...(picks || [])]; | |
| for (const [tool, re] of TOOL_CUES) if (!out.includes(tool) && re.test(String(text || ""))) out.push(tool); | |
| return out; | |
| } | |
| // ---- the decision | |
| export const CAPACITY = 0.2; | |
| // models: [{id, name, tier}] from the catalog. mode: "auto" or a model id. loaded: the id in the guest. | |
| // Returns {model, engine, think, gates, cues, tools, stay, swap, reason}. | |
| export function decide(o) { | |
| const models = o.models || []; | |
| const tools = toolsFor(o.text, o.picks); | |
| const f = features(o.text, { think: o.think }); | |
| const logic = !!o.think || f.think >= THINK_AT; | |
| const byTier = new Map(); | |
| for (const m of models) if (TIERS.has(m.tier) && !byTier.has(m.tier)) byTier.set(m.tier, m); | |
| if (o.mode && o.mode !== "auto") { | |
| const m = models.find((x) => x.id === o.mode) || models.find((x) => x.id === o.loaded) || models[0] || null; | |
| const e = m && ENGINES.find((x) => x.tier === m.tier); | |
| return { model: m, engine: e || null, think: logic, gates: null, cues: f.cues, tools, stay: !!m && m.id === o.loaded, swap: !!m && m.id !== o.loaded, reason: m ? m.name : "" }; | |
| } | |
| const g = gate(f); | |
| // Engines the server has keep their gates, renormalized. | |
| const kept = ENGINES.map((e, i) => (byTier.has(e.tier) ? g[i] : 0)); | |
| const total = kept.reduce((a, b) => a + b, 0); | |
| if (!total) { | |
| const m = models.find((x) => x.id === o.loaded) || models[0] || null; | |
| return { model: m, engine: null, think: logic, gates: g, cues: f.cues, tools, stay: true, swap: false, reason: m ? m.name : "" }; | |
| } | |
| const p = kept.map((x) => x / total); | |
| let top = 0; | |
| for (let i = 1; i < p.length; i++) if (p[i] > p[top]) top = i; | |
| const want = ENGINES[g.indexOf(Math.max(...g))]; | |
| let pick = top; | |
| // Capacity: a switch costs a model load. Close calls follow the residual (the loaded engine). | |
| const loaded = models.find((x) => x.id === o.loaded); | |
| const li = loaded ? ENGINES.findIndex((e) => e.tier === loaded.tier) : -1; | |
| const stay = li >= 0 && li !== top && p[li] > 0 && p[top] - p[li] < CAPACITY; | |
| if (stay) pick = li; | |
| const e = ENGINES[pick]; | |
| const m = byTier.get(e.tier); | |
| const parts = [e.label + " " + p[pick].toFixed(2)]; | |
| if (f.cues.length) parts.push(f.cues.slice(0, 3).join(", ")); | |
| if (want.tier !== e.tier && !byTier.has(want.tier)) parts.push(want.label + " is not on this server"); | |
| if (stay) parts.push("kept loaded (" + ENGINES[top].label + " " + p[top].toFixed(2) + ")"); | |
| if (tools.length) parts.push("tools: " + tools.join(", ")); | |
| return { | |
| model: m, engine: e, think: e.row === 1 || logic, gates: p, cues: f.cues, tools, | |
| stay: m.id === o.loaded, swap: m.id !== o.loaded, reason: parts.join(" · "), | |
| }; | |
| } | |
| // admit: hodgemix --update's rule for a tool result. The result joins the context when it moves the | |
| // same way as the question; otherwise the engine answers alone and the result stays on its card. | |
| export function admit(cos) { | |
| return Number.isFinite(cos) && cos > 0; | |
| } | |