okami.mom/strata

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

Niko1221Merge f-clean-3 (321794636): docs and history (cleanup step 3, items 3.0-3.10); release manifest and capability table with checks, history/ with pointers, link check, tools/ split, bench index; owner OK'd the wording 11-082b36e8a02

main
27.6 KiB357 linesraw
1/**
2 * The Strata profile for the Harness, generated from what the host knows right now.
3 *
4 * The static profile in `integrations/harness/profile/cordis.patch.yml` names one local route on a
5 * fixed port. The app needs more than that: whichever local Strata instances are ready, and one route
6 * per saved API connection, so that each chat can pick its own model. This module writes the same two
7 * Cordis entries (`agent-default-model`, `llm-pi-ai`) for the current set.
8 *
9 * Rules carried over from the integration notes (history/docs/work/IMPLEMENTATION_STATUS.md section 1.8):
10 *   - `llm-pi-ai` config is `{ providers: { "<route>": {...} } }`; a route key at the top level is
11 *     silently ignored.
12 *   - the output budget must fit the whole request, so `maxTokens` is derived from the real context.
13 *   - no cloud route is declared unless the user saved that connection, so nothing can fall back to a
14 *     hosted model by itself.
15 *
16 * Secrets: a route names a credential by an environment-variable NAME (`apiKeyEnv`). The values are
17 * returned separately in `env` for the host to hand to the agent process; they are never written to
18 * the profile file, a prompt, or a log.
19 */
20import { createHash } from 'node:crypto';
21import { fileURLToPath } from 'node:url';
22import { standardPreset } from './preset.mjs';
23import { validMcpName } from '../mcp-names.mjs';
24import { BUDGETS, isPrivateHost } from './llm-shape.mjs';
25import { DDG_PROVIDER_ID } from '../web-search-ddg.mjs';
26
27const PROTOCOL = { 'openai-chat': 'openai-completions', 'openai-responses': 'openai-responses', anthropic: 'anthropic-messages' };
28
29/** A conservative window for an API model whose connection does not report one. */
30export const ASSUMED_API_CONTEXT = 128_000;
31
32/**
33 * The three chat modes as Harness permission presets (see README, "Modes"). A preset is a
34 * sandbox mode plus an approval policy; the Harness switches them with its own `/permission` command.
35 *   manual  open sandbox + ask:        the Strata gate (plugins/strata-gate.mjs) asks BEFORE any change runs; nothing is denied first
36 *   plan    read-only sandbox + never: nothing can change, and the agent is told not to ask
37 *   bypass  danger-full-access + never: the Harness's own full-access, never-ask bundle (its `danger-full-access` preset)
38 */
39export const MODE_PRESETS = Object.freeze({
40  manual: { key: 'strata-manual', sandbox: 'danger-full-access', approval: 'ask', name: 'Manual', description: 'Asks before changing a file or running a command that changes anything.' },
41  plan: { key: 'strata-plan', sandbox: 'read-only', approval: 'never', name: 'Plan', description: 'Read-only. Nothing is changed and no approval prompts appear.' },
42  bypass: { key: 'strata-bypass', sandbox: 'danger-full-access', approval: 'never', name: 'Bypass', description: 'Full access without approval prompts. Files and commands anywhere on this computer run without asking.' },
43});
44export const DEFAULT_MODE = 'manual';
45/** Helper agents running at once when no local engine sets the limit (the Harness's own default). */
46export const DEFAULT_API_HELPERS = 8;
47/**
48 * Helpers a local chat may have at once: at least the engine's request slots, and never fewer than this. With one slot the engine
49 * serves its requests one after the other (its queue is unbounded), so the extra helpers show as waiting for their turn instead
50 * of being refused.
51 */
52export const MIN_LOCAL_HELPERS = 4;
53/** The preset for a chat's stored mode. Anything unknown (older values such as `auto`) gets the strictest ask-first mode. */
54export const modeOf = value => (Object.hasOwn(MODE_PRESETS, value) ? value : DEFAULT_MODE);
55
56/** The approval gate plugin (plain ESM, loaded by absolute path). */
57export const GATE_PLUGIN = fileURLToPath(new URL('./plugins/strata-gate.mjs', import.meta.url));
58/** The app's web search (DuckDuckGo, or the person's own Exa / Perplexity key), registered with the Harness's web seam. */
59/** Compaction that measures the real prompt and summarises in pieces that fit the window (plugins/strata-context.mjs). */
60export const CONTEXT_PLUGIN = fileURLToPath(new URL('./plugins/strata-context.mjs', import.meta.url));
61export const MODELS_PLUGIN = fileURLToPath(new URL('./plugins/strata-models.mjs', import.meta.url));
62export const SEARCH_PLUGIN = fileURLToPath(new URL('./plugins/strata-search.mjs', import.meta.url));
63/** The app's own tool server for the tools a person writes (instructions, commands). */
64export const CUSTOM_TOOLS_SCRIPT = fileURLToPath(new URL('./custom-tools-mcp.mjs', import.meta.url));
65
66/** The search service as the person knows it, for the question that comes before the first web search in a chat. */
67const SEARCH_NAMES = Object.freeze({ builtin: 'DuckDuckGo, or Bing when DuckDuckGo is busy', exa: 'Exa', perplexity: 'Perplexity', deepseek: 'DeepSeek' });
68
69/** What Settings -> Tools says when nothing was chosen. */
70const NO_TOOLS_SETTINGS = Object.freeze({ off: new Set(), search: { provider: 'builtin', key: '' }, webWithoutAsking: false, browserEnabled: false, browserPath: null, browserCli: null, servers: {}, hasInstructionTools: false, hasCommandTools: false, toolFile: null });
71
72/**
73 * The tool servers (MCP) set up for the model in Settings, as Harness client rows. Their tools appear to the agent as
74 * `mcp__<server>__<tool>`. A command or URL goes into the patch as text; a secret (an env value or a header) never does: the row
75 * carries `!!js process.env.<NAME>` and the value travels in the agent process's environment (returned in `env`).
76 */
77export function mcpRows(servers, env, skipped = []) {
78  const rows = [];
79  const ids = new Set();
80  let index = 0;
81  for (const [name, server] of Object.entries(servers ?? {})) {
82    if (!server || server.disabled === true) continue;       // switched off on purpose: not an error
83    // A server that cannot be wired is REPORTED (T6): the model never sees its tools, and a silent drop looked like "the tool does not work".
84    if (!validMcpName(name)) { skipped.push({ name, why: 'name' }); continue; }
85    if (!server.command && !server.url) { skipped.push({ name, why: 'address' }); continue; }
86    if (ids.has(`mcp-${slug(name)}`)) { skipped.push({ name, why: 'duplicate' }); continue; }
87    ids.add(`mcp-${slug(name)}`);
88    const token = (kind, key, value) => {
89      const variable = `STRATA_MCP_${index}_${kind}_${slug(key).replace(/-/g, '_').toUpperCase()}`;
90      env[variable] = String(value);
91      return `@@JS:process.env.${variable}@@`;
92    };
93    const config = { serverName: name, ...(server.command
94      ? { transport: 'stdio', command: String(server.command), args: Array.isArray(server.args) ? server.args.map(String) : [], ...(server.cwd ? { cwd: String(server.cwd) } : {}),
95        ...(server.env && Object.keys(server.env).length ? { env: Object.fromEntries(Object.entries(server.env).map(([k, v]) => [k, token('E', k, v)])) } : {}) }
96      : { transport: 'streamable-http', url: String(server.url), ...(server.headers && Object.keys(server.headers).length ? { headers: Object.fromEntries(Object.entries(server.headers).map(([k, v]) => [k, token('H', k, v)])) } : {}) }) };
97    rows.push({ id: `mcp-${slug(name)}`, name: '@deepseek-ai/dsh-mcp-client', config });
98    index += 1;
99  }
100  return rows;
101}
102
103/**
104 * What the chat says when a tool server was left out (one notice per reason). The sentences are interface copy: they are in every language's
105 * catalog (src/locales/tools-<lang>.json), and the {0} is the list of names exactly as the person wrote them.
106 */
107const SKIPPED_TEXT = {
108  name: 'These tool servers were left out because their names are not allowed: {0}. A name can have up to 32 letters, numbers, hyphens or underscores.',
109  address: 'These tool servers were left out because they have no program or web address: {0}.',
110  duplicate: 'These tool servers were left out because another one has almost the same name: {0}.',
111};
112export function mcpSkippedNotices(skipped) {
113  const out = [];
114  for (const why of Object.keys(SKIPPED_TEXT)) {
115    const names = (skipped ?? []).filter(s => s.why === why).map(s => String(s.name).slice(0, 40));
116    if (names.length) out.push({ code: `mcp-skipped-${why}-${names.join(',')}`.slice(0, 160), message: SKIPPED_TEXT[why].replace('{0}', names.join(', ')) });
117  }
118  return out;
119}
120
121const slug = value => String(value).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 24) || 'x';
122
123/** Identity of one route's wire configuration, secret included by hash only. */
124function fingerprint(provider, secret) {
125  return createHash('sha256').update(JSON.stringify(provider)).update('|').update(secret ?? '').digest('hex').slice(0, 16);
126}
127
128/**
129 * Output budget for an API model, whose real limit the app does not know: a quarter of the window, between 1K and 8K.
130 * (A local model has its own, much larger budget: `localOutputBudget`.)
131 */
132/**
133 * Output budget for a LOCAL model: nearly the whole window, so a thinking model is never cut off mid-thought by the app's own
134 * limit (it was 8192, which stopped big coding answers at exactly 8192 tokens). The engine clamps the request to what is left
135 * of the context (`fit_max_tokens`, which the app turns on for the models it loads), so a long prompt never turns this into an error.
136 */
137export function localOutputBudget(context) {
138  const c = Number.isFinite(context) && context > 0 ? context : 32768;
139  // 30 percent of the window, at most 32K (9,830 tokens at 32K, 19,660 at 64K): far more than the old 8192 that cut big answers off, and it leaves
140  // the rest for the conversation. The Harness's automatic compaction reads this number as the room the reply reserves: with nearly the whole
141  // window reserved it had no room left to measure pressure in and never compacted; with half of it reserved a 32K window compacted every few
142  // steps (the system prompt and tool list alone are about 7K tokens), which slowed a long task to a crawl.
143  return Math.max(4096, Math.min(32768, Math.floor(c * 0.3)));
144}
145
146/**
147 * When the Harness's automatic compaction starts condensing old history, for one model: its own default keeps 64K tokens of headroom,
148 * which on a local window of 32K to 128K leaves no room at all (it then reports a configuration error once and never compacts). An eighth
149 * of what the window has left after the reply's room works from 16K up to the largest windows. Compaction then starts at about 60 percent.
150 */
151export function compactionHeadroom(context, outputBudget) {
152  const room = Math.max(0, (Number.isFinite(context) && context > 0 ? context : 32768) - outputBudget);
153  return Math.max(512, Math.min(65536, Math.floor(room * 0.125)));
154}
155
156/**
157 * The thinking levels the chat's Reasoning menu offers, as wire values for a local Strata model. `off` sends
158 * chat_template_kwargs.enable_thinking false; the rest send it true plus reasoning_effort (the server maps high and max to its top level).
159 */
160export const LOCAL_EFFORTS = Object.freeze({ off: null, low: 'low', medium: 'medium', high: 'high', max: 'high' });
161/** The menu's words to the Harness's level names. */
162export const EFFORT_LEVEL = Object.freeze({ off: 'off', low: 'low', medium: 'medium', high: 'high', max: 'max' });
163/**
164 * The thinking levels for a model on OpenRouter: its `reasoning.effort` words (none, low, medium, high, xhigh). A model takes them when its entry in
165 * OpenRouter's model list names `reasoning` among its supported parameters; the Harness (pi-ai) writes `reasoning: { effort }` into the request.
166 */
167export const OPENROUTER_EFFORTS = Object.freeze({ off: 'none', low: 'low', medium: 'medium', high: 'high', max: 'xhigh' });
168/** Whether a connection is OpenRouter (the catalog entry, or its address), whatever address it is reached at. */
169export const isOpenRouter = conn => conn?.provider === 'openrouter' || (() => { try { return /(^|.)openrouter.ai$/i.test(new URL(conn.baseUrl).hostname); } catch { return false; } })();
170export const effortOf = value => EFFORT_LEVEL[String(value ?? '').toLowerCase()] ?? null;
171
172/**
173 * Output budget for an API model. The connection's own maximum output is used when it is known (`maxOutput`, read from the provider's model
174 * list). Otherwise a generous 32K, never more than the window minus room for the prompt (a quarter of a small window at most is the prompt's).
175 * It used to be a quarter of the window capped at 8,192, which cut a thinking model off while it was still thinking: `length` and no answer.
176 * The budget is the answer's room: a model that thinks keeps what is left of it for the answer, and the Harness sends the window minus the prompt.
177 */
178export const DEFAULT_API_OUTPUT = 32768;
179export function outputBudget(context, maxOutput = null) {
180  const c = Number.isFinite(context) && context > 0 ? context : null;
181  const window = c === null ? Infinity : Math.max(1024, c - Math.min(4096, Math.floor(c / 4)));
182  if (Number.isFinite(maxOutput) && maxOutput > 0) return Math.max(1024, Math.min(Math.floor(maxOutput), window));
183  return Math.max(1024, Math.min(DEFAULT_API_OUTPUT, window));
184}
185
186/**
187 * @param {object} input
188 * @param {Array<{id:string,label?:string,baseUrl:string,modelId:string,context?:number,key?:string,vision?:boolean,slots?:number}>} input.local
189 *        ready local instances; the first is the default route (`strata-local`)
190 * @param {Array<{id:string,name:string,baseUrl:string,protocol:string,apiKey?:string,models:Array<{id:string,name?:string,contextMax?:number|null}>}>} input.connections
191 * @returns {{patch:string, env:Record<string,string>, routes:Array, defaultRoute:object|null, signature:string}}
192 */
193/** What a local model, or an OpenAI-style server on this network, takes for the thinking level (see the comment where a local route is built). */
194const THINKING_COMPAT = { supportsStore: false, thinkingFormat: 'chat-template', chatTemplateKwargs: { enable_thinking: { $var: 'thinking.enabled' }, reasoning_effort: { $var: 'thinking.effort', omitWhenOff: true } } };
195
196export function buildProfile({ local = [], connections = [], gate = true, tools = NO_TOOLS_SETTINGS, skillsDir = null, proxyBase = null, searchMock = null, defaultLocalId = null }) {
197  const providers = {};
198  const env = {};
199  const routes = [];
200  const mcpEnv = {};
201  // Helper agents: at least as many as the engine has request slots (a local model); API models take the Harness's own limit.
202  let slots = 0;
203  /** Per-model compaction timing (see compactionHeadroom). */
204  const compaction = [];
205  /** Routes the person's Response settings can reach: a copy of the provider whose address is this host's forwarding endpoint (see llm-shape.mjs). */
206  const shapeTargets = {};
207  function addShaped(route, def, realBase) {
208    if (!proxyBase) return null;
209    const keys = {};
210    for (const budget of [0, ...BUDGETS]) {
211      const key = `${route}~s${budget}`;
212      providers[key] = { ...def, displayName: `${def.displayName} (with your response settings)`, baseURL: `${proxyBase}/${key}/v1`, ...(budget ? { headers: { ...(def.headers ?? {}), 'x-strata-budget': String(budget) } } : {}) };
213      shapeTargets[key] = realBase;
214      for (const m of def.models) { const w = m.contextWindow, out = m.maxTokens; compaction.push({ provider: key, model: m.id, headroomTokens: compactionHeadroom(w, out) }); }
215      keys[budget] = key;
216    }
217    return keys;
218  }
219
220  local.forEach((inst, index) => {
221    const route = index === 0 ? 'strata-local' : `strata-local-${slug(inst.id)}`;
222    const keyEnv = `STRATA_LOCAL_KEY_${index}`;
223    // pi-ai's OpenAI-compatible client insists on some key before it sends anything. A worker that
224    // does not authenticate gets a fixed placeholder; one that does gets its real key, by reference.
225    env[keyEnv] = inst.key || 'strata-local';
226    const context = inst.context ?? 32768;
227    providers[route] = {
228      displayName: inst.label ? `Strata (local) ${inst.label}` : 'Strata (local)',
229      api: 'openai-completions',
230      baseURL: inst.baseUrl,
231      apiKeyEnv: keyEnv,
232      // A long prompt read sends only SSE comments, which pi-ai's OpenAI client drops, so its 300 s stream-idle timer would cut the
233      // request five minutes in (#3623). 60 minutes is a backstop: serve ends a hung engine and the bridge's watchdog ends a lost turn.
234      streamIdleTimeoutMs: 60 * 60_000,
235      // The Strata server reads the thinking level from `chat_template_kwargs` (enable_thinking, reasoning_effort) or from a top-level
236      // reasoning_effort; a top-level `enable_thinking` (pi-ai's `qwen` format) is ignored, so the model went on thinking with the menu on Off.
237      compat: THINKING_COMPAT,
238      models: [{
239        id: inst.modelId, name: inst.label || inst.modelId, contextWindow: context, maxTokens: localOutputBudget(context),
240        input: inst.vision ? ['text', 'image'] : ['text'],
241        reasoning: true, reasoningEfforts: LOCAL_EFFORTS,
242      }],
243    };
244    compaction.push({ provider: route, model: inst.modelId, headroomTokens: compactionHeadroom(context, localOutputBudget(context)) });
245    slots = Math.max(slots, Number.isFinite(inst.slots) && inst.slots >= 1 ? Math.floor(inst.slots) : 1);
246    const shaped = addShaped(route, providers[route], inst.baseUrl);
247    routes.push({ route, fp: fingerprint(providers[route], env[keyEnv]), kind: 'local', connectionName: 'this computer', instanceId: inst.id, modelId: inst.modelId, name: inst.label || inst.modelId, contextWindow: context, ...(shaped ? { shaped } : {}) });
248  });
249
250  connections.forEach(conn => {
251    const protocol = PROTOCOL[conn.protocol];
252    if (!protocol) return;
253    const route = `api-${slug(conn.id).slice(0, 12)}`;
254    const keyEnv = `STRATA_API_KEY_${slug(conn.id).replace(/-/g, '_').toUpperCase().slice(0, 12)}`;
255    // A model server on this network that wants no key (llama.cpp, LM Studio, another Strata) still needs some value: the OpenAI-style client
256    // refuses to send anything without one, and the person saw "the model rejected the credentials".
257    const keyless = !conn.apiKey && protocol === 'openai-completions';
258    if (conn.apiKey) env[keyEnv] = conn.apiKey;
259    else if (keyless) env[keyEnv] = 'not-needed';
260    let baseURL = conn.baseUrl;
261    if (protocol === 'anthropic-messages') baseURL = baseURL.replace(/\/v1\/?$/, '');
262    // A model server on this computer or network (another Strata PC, llama.cpp, LM Studio) takes the same thinking vocabulary as a local model:
263    // without it the Reasoning menu did nothing for a connection to another Strata machine.
264    const openRouter = protocol === 'openai-completions' && isOpenRouter(conn);
265    const ownServer = protocol === 'openai-completions' && !openRouter && isPrivateHost(baseURL);
266    // A model server on this computer or network has a window of its own size like a local model: the reply keeps half of it, so the Harness can compact the conversation
267    // before the window is full (with nearly all of it reserved for the reply a long task ended with "the prompt leaves no room to answer").
268    const reply = m => (ownServer && Number.isFinite(m.contextMax) && m.contextMax > 0 && !m.maxOutput ? localOutputBudget(m.contextMax) : outputBudget(m.contextMax ?? ASSUMED_API_CONTEXT, m.maxOutput));
269    providers[route] = {
270      displayName: conn.name,
271      api: protocol,
272      baseURL,
273      ...(conn.apiKey || keyless ? { apiKeyEnv: keyEnv } : {}),
274      ...(ownServer ? { compat: THINKING_COMPAT } : openRouter ? { compat: { thinkingFormat: 'openrouter' } } : {}),
275      models: conn.models.map(m => ({
276        id: m.id, name: m.name || m.id,
277        contextWindow: m.contextMax ?? ASSUMED_API_CONTEXT, maxTokens: reply(m),
278        // Pictures are on by default (owner rule): only an explicit no (the person's switch, or the server's own model list or /props) leaves them out.
279        // (any OpenAI-style API: a cloud model the person marked, or whose model list says it reads pictures, takes image_url the same way)
280        input: protocol === 'openai-completions' && m.vision !== false ? ['text', 'image'] : ['text'],
281        ...(ownServer ? { reasoning: true, reasoningEfforts: LOCAL_EFFORTS } : openRouter && m.reasoning === true ? { reasoning: true, reasoningEfforts: OPENROUTER_EFFORTS } : {}),
282      })),
283    };
284    const fp = fingerprint(providers[route], conn.apiKey ?? '');
285    const shaped = ownServer ? addShaped(route, providers[route], baseURL) : null;
286    for (const m of conn.models) { const ctx = m.contextMax ?? ASSUMED_API_CONTEXT; compaction.push({ provider: route, model: m.id, headroomTokens: compactionHeadroom(ctx, reply(m)) }); }
287    for (const m of conn.models) routes.push({ route, fp, kind: 'api', connectionId: conn.id, connectionName: conn.name, modelId: m.id, name: m.name || m.id, contextWindow: m.contextMax ?? ASSUMED_API_CONTEXT, ...(shaped ? { shaped } : {}) });
288  });
289
290  // The model the chat really runs on is the default instance, not whichever one was loaded first (T5: with two models loaded, the tool servers of the
291  // first one were wired to a chat on the second).
292  const defaultInstance = local.find(i => i.id === defaultLocalId) ?? local[0] ?? null;
293  const defaultRoute = routes.find(r => r.kind === 'local' && r.instanceId === defaultInstance?.id) ?? routes.find(r => r.kind === 'local') ?? null;
294  // One Harness, one set of tool servers: the default local model's.
295  const mcpSkipped = [];
296  const mcp = mcpRows({ ...(defaultInstance?.mcpServers ?? {}), ...(tools.servers ?? {}) }, mcpEnv, mcpSkipped);
297  Object.assign(env, mcpEnv);
298  // The person's own instruction and command tools come from the app's tool server; a command tool asks in Manual like any connected tool.
299  const own = (kind, on) => on && tools.toolFile ? [{ id: `mcp-strata-${kind}`, name: '@deepseek-ai/dsh-mcp-client', config: { serverName: `strata-${kind}`, transport: 'stdio', command: process.execPath, args: [CUSTOM_TOOLS_SCRIPT, kind, tools.toolFile] } }] : [];
300  // The browser: Playwright's tool server on the person's own Chrome or Edge, in a separate empty profile (what the Harness's own browser provider does). Every action asks in Manual.
301  const browserRows = tools.browserEnabled && tools.browserPath && tools.browserCli
302    ? [{ id: 'mcp-browser', name: '@deepseek-ai/dsh-mcp-client', config: { serverName: 'browser', transport: 'stdio', command: process.execPath, args: [tools.browserCli, '--browser', 'chromium', '--isolated', ...(process.env.STRATA_BROWSER_HEADLESS === '1' ? ['--headless'] : []), '--executable-path', tools.browserPath] } }] : [];
303  const ownRows = [...own('instructions', tools.hasInstructionTools), ...own('commands', tools.hasCommandTools), ...browserRows];
304  // Web search: DuckDuckGo with no key unless the person chose a keyed service AND saved its key (then that one; never a half-set-up one).
305  const searchOn = !tools.off.has('search');
306  const keyed = ['exa', 'perplexity', 'deepseek'].includes(tools.search.provider) && tools.search.key ? tools.search.provider : null;
307  if (searchOn && keyed) env.STRATA_SEARCH_KEY = tools.search.key;
308  const webRows = !searchOn ? [] : keyed === 'deepseek'
309    ? [{ id: 'web', config: { searchProvider: 'deepseek-official', fetchProvider: 'http' } }, { id: 'web-search-deepseek', config: { apiKeyEnv: 'STRATA_SEARCH_KEY' } }]
310    : [{ id: 'web', config: { searchProvider: keyed ?? DDG_PROVIDER_ID, fetchProvider: 'http' } }, { id: 'web-search-deepseek', disabled: true },
311      { insert: [{ id: 'strata-web-search', name: SEARCH_PLUGIN, config: { provider: keyed ?? 'duckduckgo', keyEnv: 'STRATA_SEARCH_KEY', ...(searchMock ? { mock: searchMock } : {}) } }] }];
312  /** The models a helper agent may be started on: the table the model-choice plugin and the Harness's allow-list are written from. */
313  const subagentRoutes = routes.map(r => ({ provider: r.route, model: r.modelId, name: r.name, connection: r.connectionName, local: r.kind === 'local' }));
314  const entries = [
315    ...(defaultRoute ? [{ id: 'agent-default-model', name: '@deepseek-ai/dsh-agent-default-model', config: { provider: defaultRoute.route, model: defaultRoute.modelId } }] : []),
316    { id: 'llm-pi-ai', name: '@deepseek-ai/dsh-llm-pi-ai', config: { providers } },
317    // The chat modes. Replacing the table also drops the Harness's own three presets: a chat is always in one of ours.
318    { id: 'permission', config: { presets: Object.fromEntries(Object.values(MODE_PRESETS).map(({ key, sandbox, approval, name, description }) => [key, { sandbox, approval, name, description }])), defaultPreset: MODE_PRESETS[DEFAULT_MODE].key } },
319    { id: 'subagent', config: { maxActiveSubagents: slots > 0 ? Math.max(slots, MIN_LOCAL_HELPERS) : DEFAULT_API_HELPERS } },
320    // Manual asks before a change runs, so the person sees one Approve/Deny card and nothing has happened yet.
321    // Its web question names the search service the person chose (a keyed one only when its key is saved), and the person's switch skips the question.
322    ...(gate ? [{ insert: [{ id: 'strata-gate', name: GATE_PLUGIN, config: { web: { provider: SEARCH_NAMES[keyed ?? 'builtin'], skipAsk: tools.webWithoutAsking === true } } }] }] : []),
323    // Compaction decides from what the model server measured, and its summary requests always fit the window (plugins/strata-context.mjs).
324    { insert: [{ id: 'strata-context', name: CONTEXT_PLUGIN, config: {} }] },
325    // Helper agents on a model the person names: every model the app can reach is allowed, and the plugin makes the choice forgiving (plugins/strata-models.mjs).
326    ...(subagentRoutes.length ? [{ id: 'subagent-model-selection-settings', config: { enabled: true, allowedModels: subagentRoutes.map(r => ({ provider: r.provider, model: r.model })) } }] : []),
327    ...(subagentRoutes.length ? [{ insert: [{ id: 'strata-models', name: MODELS_PLUGIN, config: { routes: subagentRoutes } }] }] : []),
328    ...(mcp.length || ownRows.length ? [{ insert: [...mcp, ...ownRows] }] : []),
329    ...webRows,
330    // The reminder tools would be a second scheduler beside the app's Tasks. The tool groups the person switched off in Settings -> Tools are left out.
331    { id: 'preset-standard', name: '@deepseek-ai/dsh-agent-preset', config: standardPreset({ off: tools.off, search: searchOn, skillsDir, compaction }) },
332    // Strata names its chats itself; the Harness's own title request would be an extra model call on
333    // every first prompt (and, for an API route, an unrequested one).
334    { id: 'session-title-llm', disabled: true },
335    // Office documents are not previewed in the app (the converter is not shipped): do not try to start it.
336    { id: 'office-to-pdf', disabled: true },
337  ];
338  // JSON is valid YAML, and a JSON document cannot be mis-quoted by a model id or a display name.
339  // JSON is valid YAML. A tool server's secret is a `!!js process.env.NAME` value, swapped in after stringifying.
340  const json = JSON.stringify(entries, null, 2).replace(/"@@JS:([A-Za-z0-9_.]+)@@"/g, '!!js $1');
341  const patch = `# Generated by the Strata host. Contains credential NAMES only, never values.\n${json}\n`;
342  // The signature decides whether the running agent must be restarted. It covers the secret values
343  // through a hash so a changed key is noticed, and the hash is never reversible into the key.
344  const signature = createHash('sha256').update(patch).update(JSON.stringify(Object.entries(env).sort())).digest('hex').slice(0, 16);
345  // What the agent is offered (tool groups, web search, tool servers, the person's own tools) decides whether a running agent must be
346  // restarted for the next message; the routes are compared separately (a changed context size alone does not restart it).
347  const toolsSignature = createHash('sha256').update(JSON.stringify([mcp, ownRows, webRows, entries.find(e => e.id === 'preset-standard'), env.STRATA_SEARCH_KEY ?? '', mcpEnv])).digest('hex').slice(0, 16);
348  return { patch, env, routes, defaultRoute, signature, toolsSignature, shapeTargets, mcpSkipped };
349}
350
351/** Find the route for a chat's model choice. */
352export function routeFor(profile, choice) {
353  if (!choice) return profile.defaultRoute;
354  if (choice.connectionId) return profile.routes.find(r => r.kind === 'api' && r.connectionId === choice.connectionId && r.modelId === choice.modelId) ?? null;
355  if (choice.instanceId) return profile.routes.find(r => r.kind === 'local' && r.instanceId === choice.instanceId) ?? null;
356  return profile.defaultRoute;
357}