okami.mom/strata

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

Niko1221rc1 merge ds-coder (d6a5a7837)4fb068a8c

main
12.8 KiB205 linesraw
1/**
2 * Strata's context plugin for the Harness (plain ESM, loaded by absolute path from the profile, like strata-gate and strata-models).
3 *
4 * What it fixes (2026-10-22 hands-on test, Gyro-S at 64K):
5 *   1. Compaction decided from the Harness's own price of the conversation, 4 characters a token. Code, logs and JSON are about twice as
6 *      dense, so a chat the engine had read as 59,048 tokens was priced at 31,794 and compaction started far too late. Here the token meter
7 *      is calibrated by what the model server reports for each answer (its real prompt size): the measured size is exact, and what was
8 *      added since is priced with the density that measurement showed. Automatic compaction and the manual /compact both measure through
9 *      the token meter, so both read the same number as the context meter in the app.
10 *   2. The summarising request itself could be bigger than the window ("/compact" sent a 66,507-token prompt to a 65,536 window). The
11 *      summary is now asked for in pieces that fit: a message bigger than a piece is cut for the request (the conversation keeps it until
12 *      the summary replaces it), the pieces are summarised one after the other, each building on the summary before it, and a piece the
13 *      server still refuses is halved and tried again.
14 *
15 * How. It wraps `tokenMeter.measure` and `llm.stream` in place, once each (the same way strata-models wraps the subagent tools). Only a
16 * request the Harness marks `purpose: 'compaction'` is touched in `llm.stream`. Nothing in the Harness is rewritten: a Harness update
17 * that renames either leaves compaction as it was, and the test that runs the real Harness fails.
18 */
19import { replyCap } from '../reply-cut.mjs';
20import { densityOf, estimateMessage, estimateTools, isContextOverflow, MAX_DENSITY, pressureNow, promptTokensOf, splitMessages, summaryBudget, usageOfEvent, WINDOW_SLACK, withSummaryLanguage } from '../context-budget.mjs';
21
22export const name = 'strata-context';
23
24/** The routes the host writes for models on this computer (profile.mjs): `strata-local`, `strata-local-<id>`, and their `~s<budget>` copies. */
25const isLocalRoute = provider => typeof provider === 'string' && provider.startsWith('strata-local');
26export const inject = ['tokenMeter', 'llm'];
27
28/** Real prompt measurements per session: { real, estimated } for the last answer the model server reported. */
29const samples = new WeakMap();
30const bySessionId = new Map();
31const wrapped = new WeakSet();
32/** Densities that made a summary request fail on this server, per session id (the next request starts from a more careful one). */
33const careful = new Map();
34
35export function apply(ctx) {
36  const meter = ctx.tokenMeter;
37  const llm = ctx.llm;
38  const log = (level, text) => { try { ctx.logger?.[level]?.(`strata-context: ${text}`); } catch { /* logging never blocks */ } };
39
40  // 1. The measured size of the prompt, from the model server's own report for each answer.
41  if (meter && typeof meter.measure === 'function' && !wrapped.has(meter)) {
42    wrapped.add(meter);
43    const original = meter.measure;
44    meter.measure = function measure(session, requestHeader) {
45      const m = original.call(this, session, requestHeader);
46      const sample = samples.get(session);
47      if (!sample) return m;
48      const now = m.surfaceTokens + estimateTools(requestHeader ?? session.requestHeader?.());
49      const total = Math.max(m.totalTokens, pressureNow({ sample, now }));
50      if (total <= m.totalTokens) return m;
51      const density = densityOf(sample.real, sample.estimated);
52      return { ...m, totalTokens: total, nodes: m.nodes.map(n => ({ ...n, tokens: Math.ceil(n.tokens * density) })) };
53    };
54    ctx.on('session/event', (session, event) => {
55      if (event.type !== 'assistant/message') return;
56      const real = promptTokensOf(usageOfEvent(event));
57      if (!(real > 0)) return;
58      try {
59        // The request that was just answered saw the conversation without this answer: its price is the surface before the answer's node.
60        const m = original.call(meter, session);
61        const heuristic = m.nodes.reduce((n, x) => n + (x.seq === event.seq ? 0 : x.heuristicTokens), 0);
62        const estimated = heuristic + estimateTools(session.requestHeader?.());
63        if (!(estimated > 0)) return;
64        const sample = { real, estimated };
65        samples.set(session, sample);
66        if (session.id) bySessionId.set(String(session.id), sample);
67      } catch (e) { log('warn', `could not record a measurement: ${e.message}`); }
68    });
69  }
70
71  // 2. A summary request that fits the window.
72  if (llm && typeof llm.stream === 'function' && !wrapped.has(llm)) {
73    wrapped.add(llm);
74    const original = llm.stream;
75    llm.stream = function stream(options) {
76      if (options?.purpose !== 'compaction') return original.call(this, options);
77      return summaryStream.call(this, options, original);
78    };
79  }
80
81  // 3. A reply that has room to finish (AGENT-LOST, 11-01). The output budget in the profile is what the Harness's compaction sets aside for a
82  // reply (30 percent of the window; it reads it from the request header), and the same number was also the ceiling of every request: a thinking
83  // model that wrote a 15K-token file after 9K tokens of thinking was cut inside the tool call at 19,660, the unfinished call was dropped and the
84  // turn ended with no file and no word. The header (and so compaction) stays as it is; the request that goes to the model server may produce up
85  // to half the window, at most 64K tokens (replyCap), and pi-ai still clamps it to what the window has left after the prompt. The agent loop
86  // dispatches through the adapter's `streamWithSnapshot`, after the loop has checked the request against its header, so that is where the ceiling
87  // is raised, once per adapter, the first time a local route is prepared. A Harness that renames it leaves the ceiling as it was (the test that
88  // runs the real Harness fails).
89  if (llm && typeof llm.prepareCall === 'function' && !wrapped.has(llm.prepareCall)) {
90    const original = llm.prepareCall;
91    const raised = new WeakSet();
92    const prepare = async function prepareCall(config, signal, configure) {
93      try { raiseReplyCeiling(config?.provider, raised); } catch (e) { log('warn', `could not raise the reply ceiling: ${e.message}`); }
94      return original.call(this, config, signal, configure);
95    };
96    wrapped.add(prepare);
97    llm.prepareCall = prepare;
98  }
99  function raiseReplyCeiling(provider, raised) {
100    if (!isLocalRoute(provider)) return;
101    const adapter = llm.adapters?.get?.(provider)?.adapter;
102    if (!adapter || raised.has(adapter) || typeof adapter.streamWithSnapshot !== 'function' || typeof adapter.modelOf !== 'function') return;
103    raised.add(adapter);
104    const stream = adapter.streamWithSnapshot;
105    adapter.streamWithSnapshot = function streamWithSnapshot(options, snapshot) {
106      let next = options;
107      try {
108        if (isLocalRoute(options?.provider)) {
109          const model = this.modelOf(snapshot, options.provider, options.model);
110          const asked = options.maxTokens ?? model.maxTokens ?? 0;
111          // Only the agent's own reply budget is raised: a summary or a title asks for far less and keeps what it asked.
112          if (model.contextWindow > 0 && asked >= Math.floor(model.contextWindow * 0.25)) {
113            const cap = replyCap(model.contextWindow, asked);
114            if (cap > asked) next = { ...options, maxTokens: cap };
115          }
116        }
117      } catch { next = options; }
118      return stream.call(this, next, snapshot);
119    };
120  }
121
122  // The host asks, with /strata-context, how much of the window the chat holds right now: the same measured number compaction decides on
123  // (JSON in the command's text: { tokens, window }). Before a message goes out, and after /compact, so the person is told true figures.
124  ctx.inject(['commands'], (commandCtx) => {
125    commandCtx.commands.register({
126      definitionId: 'strata-context',
127      name: 'strata-context',
128      description: 'Reports how many tokens the conversation holds now and the size of the model window',
129      handler: async (invocation) => {
130        try {
131          const session = invocation.agent.session;
132          const tokens = meter.measure(session).totalTokens;
133          const config = session.requestHeader?.()?.config;
134          let window = 0;
135          if (config) window = (await llm.resolveModelInfo(config.provider, config.model))?.context?.contextWindow ?? 0;
136          return { kind: 'success', text: JSON.stringify({ tokens, window }) };
137        } catch (e) { return { kind: 'error', text: `strata-context: ${e.message}` }; }
138      },
139    });
140  });
141
142  /** A finished stream: its chunks, the text it wrote and why it ended. */
143  async function drain(iterable) {
144    let text = '', finish = null;
145    const chunks = [];
146    for await (const chunk of iterable) {
147      chunks.push(chunk);
148      if (chunk.type === 'text-delta') text += chunk.text ?? '';
149      else if (chunk.type === 'finish') finish = chunk.reason;
150    }
151    return { text, finish, chunks };
152  }
153  const refusedForSize = finish => finish?.kind === 'error' && isContextOverflow(finish.failure ?? finish);
154
155  async function* summaryStream(options, original) {
156    options = { ...options, messages: withSummaryLanguage(options.messages) };   // #4750: the summary follows the conversation's language
157    let window = 0;
158    try { window = (await llm.resolveModelInfo(options.provider, options.model, options.signal))?.context?.contextWindow ?? 0; } catch { window = 0; }
159    const messages = options.messages ?? [];
160    const key = String(options.sessionId ?? '');
161    const summaryTokens = options.maxTokens ?? 4096;
162    if (!(window > 0) || messages.length < 2) { yield* original.call(this, options); return; }
163    const own = bySessionId.get(key);
164    let density = Math.max(careful.get(key) ?? 1, own ? densityOf(own.real, own.estimated) : 1);
165    const price = list => list.reduce((n, m) => n + estimateMessage(m), 0) * density;
166    const limit = window - summaryTokens - WINDOW_SLACK;
167    // The whole request fits by this price: ask as the Harness would (the model server's cache of the conversation is reused).
168    if (price(messages) + estimateTools({ tools: options.tools }) * density <= limit) {
169      const first = await drain(original.call(this, options));
170      if (!refusedForSize(first.finish)) { for (const chunk of first.chunks) yield chunk; return; }
171      density = Math.min(MAX_DENSITY, density * 1.6);
172      careful.set(key, density);
173      log('warn', 'the summary request did not fit the window; asking in pieces');
174    }
175    // In pieces. The instruction is the last message; the system prompt, when there is one, the first.
176    const instruction = messages[messages.length - 1];
177    const system = messages[0]?.role === 'system' ? messages[0] : null;
178    const body = messages.slice(system ? 1 : 0, -1);
179    let tools = options.tools;
180    if (tools && estimateTools({ tools }) * density > window / 3) tools = undefined;   // a long tool list only describes tools: the summary does not need it
181    const fixed = (system ? estimateMessage(system) : 0) * density + estimateTools({ tools }) * density + estimateMessage(instruction) * density;
182    let budget = summaryBudget({ window, summaryTokens: summaryTokens * 2, systemTokens: fixed, instructionTokens: 0 });
183    for (let attempt = 0; ; attempt++) {
184      const runs = splitMessages(body, Math.max(1024, budget), density);
185      log('info', `summarising ${body.length} messages in ${runs.length} piece(s) for a ${window}-token window (density ${density.toFixed(2)}, about ${Math.round(budget)} tokens a piece)`);
186      let failed = null, summary = '';
187      for (let i = 0; i < runs.length && !failed; i++) {
188        options.signal?.throwIfAborted?.();
189        const carried = summary ? [{ role: 'user', content: [{ type: 'text', text: `<compacted-summary>\n${summary}\n</compacted-summary>` }] }] : [];
190        const { tools: _drop, ...rest } = options;
191        const piece = { ...rest, ...(tools ? { tools } : {}), messages: [...(system ? [system] : []), ...carried, ...runs[i], instruction] };
192        const { text, finish, chunks } = await drain(original.call(this, piece));
193        if (refusedForSize(finish)) { failed = finish; break; }
194        // The last piece's answer is the summary the Harness reads; a piece that ended in another error ends the request the same way.
195        if (i === runs.length - 1 || finish?.kind === 'error' || finish?.kind === 'aborted') { for (const chunk of chunks) yield chunk; return; }
196        summary = text;
197      }
198      if (!failed || attempt >= 3) throw Object.assign(new Error(failed?.failure?.message ?? 'the summary request does not fit the window'), { code: 'CONTEXT_WINDOW_EXCEEDED' });
199      density = Math.min(MAX_DENSITY, density * 1.6);
200      careful.set(key, density);
201      budget = Math.max(1024, budget / 2);
202      log('warn', `a piece did not fit; asking again with pieces of about ${Math.round(budget)} tokens`);
203    }
204  }
205}