okami.mom/strata

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

Niko1221merge f-split-agent6 0b871e2d7 (compaction, /research, response settings, browser and skills checks, time-skip file order, step summaries) into f-split-intc163678f7

main
6.6 KiB118 linesraw
1/**
2 * Response settings for agent turns.
3 *
4 * The chat's own path sends the Expert sampling (temperature, top-p, top-k, repeat penalty, seed) and the composer's thinking budget with
5 * every request. The agent's requests are made by the Harness, which has no place for either, so they never reached the model. When a
6 * person has changed one of them, the agent's model route goes through the small forwarding endpoint below (on this computer only), which
7 * adds exactly the fields that differ from the defaults and passes everything else through untouched. With every setting at its default the
8 * agent talks to the model directly, byte for byte as before.
9 *
10 * Only a local model, or an OpenAI-style server on this computer or this network, is shaped: a cloud service would reject fields it does not know.
11 */
12
13import http from 'node:http';
14import https from 'node:https';
15
16/** The thinking budgets the composer offers (0 = no limit is not a budget). */
17export const BUDGETS = Object.freeze([2048, 8192, 32768]);
18/** The offered budget nearest to what a chat asks for (0 stays 0). */
19export function nearestBudget(value) {
20  const n = Number(value);
21  if (!Number.isFinite(n) || n <= 0) return 0;
22  return BUDGETS.reduce((best, b) => (Math.abs(b - n) < Math.abs(best - n) ? b : best), BUDGETS[0]);
23}
24
25/** Expert setting id -> request field, and the default each one has (the catalog's recommended value). */
26const SAMPLING = Object.freeze({
27  'sample.temp': ['temperature', 0.6],
28  'sample.topP': ['top_p', 0.95],
29  'sample.topK': ['top_k', 40],
30  'sample.repeat': ['repeat_penalty', 1.05],
31  'sample.seed': ['seed', -1],
32});
33
34/** The request fields for the Expert settings that are not at their default, or null when all are. */
35export function samplingFromExpert(expert) {
36  const out = {};
37  for (const [id, [field, recommended]] of Object.entries(SAMPLING)) {
38    const v = expert?.[id];
39    if (typeof v === 'number' && Number.isFinite(v) && v !== recommended) out[field] = v;
40  }
41  if (expert?.['sample.speedProjection'] === false) out.experimental_speed_projection = false;
42  const cap = Number(expert?.['sample.maxTokens']);
43  if (Number.isFinite(cap) && cap > 0) out.max_tokens = Math.floor(cap);
44  return Object.keys(out).length ? out : null;
45}
46
47/**
48 * The request body with the person's settings added. A field the request already carries is left alone (the Harness's own wins), the
49 * thinking budget is only added while thinking is on, and an output cap only ever lowers the request's own.
50 */
51export function shapeBody(body, { sampling = null, budget = 0 } = {}) {
52  if (!body || typeof body !== 'object' || Array.isArray(body)) return body;
53  const out = { ...body };
54  for (const [field, value] of Object.entries(sampling ?? {})) {
55    if (field === 'max_tokens' || field === 'max_completion_tokens') continue;
56    if (out[field] === undefined) out[field] = value;
57  }
58  if (sampling?.max_tokens) {
59    for (const key of ['max_tokens', 'max_completion_tokens']) if (Number.isFinite(out[key])) out[key] = Math.min(out[key], sampling.max_tokens);
60    if (out.max_tokens === undefined && out.max_completion_tokens === undefined) out.max_tokens = sampling.max_tokens;
61  }
62  const thinkingOff = out.chat_template_kwargs?.enable_thinking === false;
63  if (budget > 0 && !thinkingOff && out.reasoning_budget_tokens === undefined) out.reasoning_budget_tokens = budget;
64  return out;
65}
66
67/** An address on this computer or on a private network: where the person's own model servers live. */
68export function isPrivateHost(url) {
69  let host;
70  try { host = new URL(url).hostname.toLowerCase(); } catch { return false; }
71  host = host.replace(/^\[|\]$/g, '');
72  if (host === 'localhost' || host === '::1' || host.endsWith('.local') || host.endsWith('.lan')) return true;
73  const m = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/.exec(host);
74  if (!m) return false;
75  const [a, b] = [Number(m[1]), Number(m[2])];
76  return a === 127 || a === 10 || (a === 192 && b === 168) || (a === 172 && b >= 16 && b <= 31) || (a === 169 && b === 254) || (a === 100 && b >= 64 && b <= 127);
77}
78
79const HOP = new Set(['host', 'connection', 'content-length', 'transfer-encoding', 'keep-alive', 'upgrade', 'proxy-connection']);
80
81/**
82 * The forwarding endpoint. `targetOf(key)` gives the real base address of a shaped route (or null), `samplingNow()` the Expert fields that
83 * differ from the defaults right now. Called for `/api/internal/agent-llm/<key>/<path>`; this computer's own address only.
84 */
85export function createLlmProxy({ targetOf, samplingNow }) {
86  return function handle(req, res, key, rest) {
87    const remote = req.socket?.remoteAddress ?? '';
88    if (!/^(::1|127\.|::ffff:127\.)/.test(remote)) { res.writeHead(403, { 'content-type': 'application/json' }); res.end(JSON.stringify({ error: 'This endpoint is for the assistant on this computer only.' })); return; }
89    const base = targetOf(key);
90    if (!base) { res.writeHead(404, { 'content-type': 'application/json' }); res.end(JSON.stringify({ error: 'Unknown model route.' })); return; }
91    const chunks = [];
92    req.on('data', c => chunks.push(c));
93    req.on('error', () => res.destroy());
94    req.on('end', () => {
95      let body = Buffer.concat(chunks);
96      const budget = nearestBudget(req.headers['x-strata-budget']);
97      if (req.method === 'POST' && /\/chat\/completions\/?$/.test(rest) && body.length) {
98        try { body = Buffer.from(JSON.stringify(shapeBody(JSON.parse(body.toString('utf8')), { sampling: samplingNow(), budget }))); } catch { /* not JSON: pass it on untouched */ }
99      }
100      // The route's address is the model's own base (it ends in /v1): the assistant's /v1 is that same prefix.
101      const target = new URL(base.replace(/\/+$/, '') + rest.replace(/^\/v1(?=\/|$|\?)/, ''));
102      const headers = {};
103      for (const [k, v] of Object.entries(req.headers)) if (!HOP.has(k) && !k.startsWith('x-strata-')) headers[k] = v;
104      headers['content-length'] = String(body.length);
105      const lib = target.protocol === 'https:' ? https : http;
106      const upstream = lib.request(target, { method: req.method, headers }, reply => {
107        const out = { ...reply.headers }; delete out['transfer-encoding']; delete out.connection;
108        res.writeHead(reply.statusCode ?? 502, out);
109        reply.pipe(res);
110        reply.on('error', () => res.destroy());
111      });
112      upstream.on('error', e => { if (!res.headersSent) { res.writeHead(502, { 'content-type': 'application/json' }); res.end(JSON.stringify({ error: `The model server could not be reached: ${e.message}` })); } else res.destroy(); });
113      // The assistant stopped waiting (Stop): stop the model too.
114      res.on('close', () => { if (!res.writableEnded) upstream.destroy(); });
115      upstream.end(body);
116    });
117  };
118}