okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-split-fb3 into f-split-int (locale keys re-added after the card-list strings)7b06ea51b

main
9.0 KiB151 linesraw
1/**
2 * Which model did the person (or the assistant) mean when a helper agent is started with a model?
3 *
4 * The Harness's `subagent` tool wants an exact `provider` route key and an exact model id. People say "ask DeepSeek", "use the local
5 * model", "ask deepseek/deepseek-v3.2" or a display name in other letters; a route key such as `api-1b2c3d4e-5f` is something no
6 * model can guess. This module turns what was asked into one route, or into a plain answer that says what to do next.
7 *
8 * Pure and dependency free: the profile writes the route table, the `strata-models` Harness plugin and the tests call it.
9 *
10 * A route is `{ provider, model, name, connection, local }`:
11 *   provider    the route key in the Harness profile (what the Harness needs)
12 *   model       the model id the server knows
13 *   name        the name the person sees in the model picker
14 *   connection  the connection's name ("OpenRouter") or "this computer" for a local model
15 *   local       true for a model running in the Strata engine
16 */
17
18/** The words people use for the model that runs in Strata on this computer. */
19const LOCAL_WORDS = new Set(['local', 'localmodel', 'localstrata', 'thelocalmodel', 'mylocalmodel', 'strata', 'stratalocal', 'stratamodel', 'localstratamodel', 'strataslocalmodel', 'default', 'thismodel', 'samemodel', 'themodel', 'thislocalmodel']);
20
21/** Letters and digits only, lower case: "DeepSeek: V3.2" and "deepseek v3.2" meet. */
22export const squash = value => String(value ?? '').toLowerCase().replace(/[^\p{L}\p{N}]+/gu, '');
23const words = value => String(value ?? '').toLowerCase().split(/[^\p{L}\p{N}.]+/u).filter(Boolean);
24
25/** Edit distance, capped: enough to tell "deepseek-v3.2" from "deepseek-v3.1" and "depseek" from "deepseek". */
26function distance(a, b, cap = 4) {
27  if (Math.abs(a.length - b.length) > cap) return cap + 1;
28  let prev = Array.from({ length: b.length + 1 }, (_, i) => i);
29  for (let i = 1; i <= a.length; i++) {
30    const row = [i];
31    let best = row[0];
32    for (let j = 1; j <= b.length; j++) {
33      row[j] = Math.min(prev[j] + 1, row[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
34      best = Math.min(best, row[j]);
35    }
36    if (best > cap) return cap + 1;
37    prev = row;
38  }
39  return prev[b.length];
40}
41
42/** Every spelling by which this route can be asked for, as squashed strings (an exact spelling, not a guess). */
43function exactKeys(route) {
44  const keys = new Set();
45  const add = value => { const s = squash(value); if (s) keys.add(s); };
46  add(route.model); add(route.name);
47  add(`${route.provider}/${route.model}`);
48  add(`${route.connection}/${route.model}`); add(`${route.connection} ${route.name}`); add(`${route.connection}: ${route.name}`); add(`${route.name} ${route.connection}`);
49  add(`${route.name} (${route.connection})`);
50  return keys;
51}
52
53/** The loose pieces a guess can match: the id, its last part after a slash, the name and the connection. */
54function looseForms(route) {
55  const forms = [route.model, String(route.model).split('/').pop(), route.name, `${route.connection} ${route.name}`];
56  return forms.map(squash).filter(Boolean);
57}
58
59/** One line for a model in a list the assistant or the person reads. */
60export function routeLine(route) {
61  const where = route.local ? 'running on this computer' : route.connection;
62  return `${route.name} (${where}): provider "${route.provider}", model "${route.model}"`;
63}
64
65/** The whole list as text, kept short enough for a small model's context. */
66export function routeList(routes, { max = 30 } = {}) {
67  const lines = routes.slice(0, max).map(r => `- ${routeLine(r)}`);
68  if (routes.length > max) lines.push(`- ...and ${routes.length - max} more (ask for the name of one of them, or the part of its id you know)`);
69  return lines.join('\n');
70}
71
72/**
73 * Resolve one request.
74 * @param {Array<{provider:string,model:string,name:string,connection:string,local:boolean}>} routes
75 * @param {{provider?:string, model?:string}} request what the caller wrote (either or both)
76 * @returns {{status:'inherit'}|{status:'exact',route:object,how:string}|{status:'confirm',route:object,others:object[]}|{status:'ambiguous',options:object[]}|{status:'none'}}
77 *   inherit: nothing was asked (the helper uses the chat's model); exact: one model; confirm: one close guess to check with the person;
78 *   ambiguous: several models fit; none: nothing fits.
79 */
80export function resolveModel(routes, request = {}) {
81  const provider = typeof request.provider === 'string' ? request.provider.trim() : '';
82  const model = typeof request.model === 'string' ? request.model.trim() : '';
83  if (!provider && !model) return { status: 'inherit' };
84  // 1. The exact route the Harness knows.
85  if (provider && model) {
86    const hit = routes.find(r => r.provider === provider && r.model === model);
87    if (hit) return { status: 'exact', route: hit, how: 'route' };
88  }
89  const texts = [model, provider, provider && model ? `${provider}/${model}` : '', provider && model ? `${provider} ${model}` : ''].filter(Boolean);
90  const squashed = [...new Set(texts.map(squash).filter(Boolean))];
91  // 2. A spelling of one route: its id, "provider/id", its name or "connection name", in any letters.
92  const exact = routes.filter(r => { const keys = exactKeys(r); return squashed.some(s => keys.has(s)); });
93  // A name that fits several routes of one model id on different connections is not decided by the id alone: prefer the one the other half names.
94  if (exact.length > 1 && provider && model) {
95    const both = exact.filter(r => { const c = squash(r.connection); return squash(provider) === c || squash(provider) === squash(r.provider); });
96    if (both.length === 1) return { status: 'exact', route: both[0], how: 'spelling' };
97  }
98  if (exact.length === 1) return { status: 'exact', route: exact[0], how: 'spelling' };
99  if (exact.length > 1) return { status: 'ambiguous', options: exact };
100  // 3. The local model by its everyday words.
101  const locals = routes.filter(r => r.local);
102  if (squashed.some(s => LOCAL_WORDS.has(s)) && locals.length) {
103    return locals.length === 1 ? { status: 'exact', route: locals[0], how: 'local' } : { status: 'ambiguous', options: locals };
104  }
105  // 4. A close guess: part of an id or a name, a small typo.
106  const scored = [];
107  for (const route of routes) {
108    const forms = looseForms(route);
109    let best = Infinity;
110    for (const s of squashed) {
111      for (const form of forms) {
112        if (s.length >= 3 && form === s) best = Math.min(best, 0);
113        else if (s.length >= 4 && (form.includes(s) || s.includes(form) && form.length >= 4)) best = Math.min(best, 1);
114        else if (s.length >= 5) best = Math.min(best, distance(s, form, 2) <= 2 ? 2 : Infinity);
115      }
116      // every word the caller wrote appears in the id or the name ("flash deepseek")
117      const wanted = words(texts.join(' '));
118      const haystack = squash(`${route.name} ${route.model} ${route.connection}`);
119      if (wanted.length && wanted.every(w => w.length >= 2 && haystack.includes(squash(w)))) best = Math.min(best, 1.5);
120    }
121    if (best < Infinity) scored.push({ route, score: best });
122  }
123  scored.sort((a, b) => a.score - b.score || a.route.name.length - b.route.name.length);
124  if (!scored.length) return { status: 'none' };
125  const top = scored[0];
126  const close = scored.filter(s => s.score === top.score);
127  if (close.length === 1) return { status: 'confirm', route: top.route, others: scored.slice(1, 4).map(s => s.route) };
128  return { status: 'ambiguous', options: scored.slice(0, 6).map(s => s.route) };
129}
130
131/** What the person or assistant typed, for a message ("deepseek", "openrouter/deepseek"). */
132export const asked = request => [request.provider, request.model].filter(v => typeof v === 'string' && v.trim()).join(' / ');
133
134/**
135 * The text the `subagent` tool answers with when the model could not be settled. `null` when the call can go ahead (the caller then
136 * uses the `exact` route or inherits). Plain words, with the next step; never a route key as the only thing said.
137 */
138export function modelProblem(routes, request) {
139  const result = resolveModel(routes, request);
140  const what = asked(request);
141  if (result.status === 'inherit' || result.status === 'exact') return null;
142  if (!routes.length) return 'No other model is set up. Nothing was started. Add a model in Models, or start the helper without naming a model.';
143  if (result.status === 'confirm') {
144    const r = result.route;
145    return `No model is called "${what}". Nothing was started. Did you mean ${r.name} (${r.local ? 'running on this computer' : r.connection})? Ask the person "Did you mean ${r.name}?" and, when they agree, call subagent again with provider "${r.provider}" and model "${r.model}".`;
146  }
147  if (result.status === 'ambiguous') {
148    return `More than one model fits "${what}". Nothing was started. Ask the person which one they mean, then call subagent again with that model's provider and model:\n${routeList(result.options, { max: 8 })}`;
149  }
150  return `No model is called "${what}". Nothing was started. These are the models that can be used:\n${routeList(routes)}\nChoose one of them, or tell the person it is not set up (they can add it in Models).`;
151}