okami.mom/strata

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

Niko1221Trial2 merge f-0291-pr-nv (97b3d614f)1306424be

main
10.0 KiB174 linesraw
1/**
2 * Token arithmetic for the agent's context, with no I/O (the Harness plugin `plugins/strata-context.mjs` and the host both use it).
3 *
4 * Why it exists. The Harness prices a conversation with a fixed 4 characters per token. Code, logs and JSON are about twice as dense
5 * (2.09 characters per token in the 2026-10-22 hands-on test), so its pressure read 31,794 tokens while the engine had been sent 59,048,
6 * and compaction waited until the window was already past full. The engine reports the real prompt size with every answer; this module
7 * turns that report into the number compaction decides on, and splits a summarising request that would not fit the window.
8 */
9
10/** The Harness's own price of a text: characters over this, plus a fixed cost per block and per message. */
11export const CHARS_PER_TOKEN = 4;
12const BLOCK_OVERHEAD = 4;
13const MESSAGE_OVERHEAD = 4;
14/** The most a real token can be worth in the Harness's units (one character per token is the worst a tokenizer does). */
15export const MAX_DENSITY = 6;
16/** Room kept free in a window for the engine's own framing and the chat template (the engine keeps 64 tokens of slack itself). */
17export const WINDOW_SLACK = 1024;
18
19/** The Harness's price (4 characters a token) of one message, the same arithmetic as its token meter. */
20export function estimateMessage(message) {
21  const content = Array.isArray(message?.content) ? message.content : [];
22  if (message?.role === 'system') {
23    if (!content.length) return 0;
24    let chars = 0;
25    for (const block of content) chars += block?.type === 'text' ? String(block.text ?? '').length : JSON.stringify(block ?? {}).length;
26    return Math.ceil(chars / CHARS_PER_TOKEN) + MESSAGE_OVERHEAD;
27  }
28  let tokens = MESSAGE_OVERHEAD;
29  for (const block of content) {
30    if (block?.type === 'text' || block?.type === 'reasoning') tokens += Math.ceil(String(block.text ?? '').length / CHARS_PER_TOKEN) + BLOCK_OVERHEAD;
31    else if (block?.type === 'tool-call') tokens += Math.ceil(String(block.name ?? '').length / CHARS_PER_TOKEN) + Math.ceil(String(block.arguments ?? '').length / CHARS_PER_TOKEN) + BLOCK_OVERHEAD;
32    else tokens += BLOCK_OVERHEAD + Math.ceil(JSON.stringify(block ?? {}).length / CHARS_PER_TOKEN);
33  }
34  return tokens;
35}
36
37/** The Harness's price of the tool list of a request header. */
38export function estimateTools(header) {
39  const tools = header?.tools;
40  if (!Array.isArray(tools) || !tools.length) return 0;
41  return Math.ceil(JSON.stringify(tools).length / CHARS_PER_TOKEN) + BLOCK_OVERHEAD;
42}
43
44/**
45 * How many real tokens one of the Harness's tokens is worth, from one measured request: the engine said the prompt was `real` tokens,
46 * the Harness priced the same prompt at `estimated`. Never below 1 (a conversation of plain prose is priced about right, and a lower
47 * number would only delay compaction) and never above MAX_DENSITY (a wild sample must not make every step compact).
48 */
49export function densityOf(real, estimated) {
50  if (!(real > 0) || !(estimated > 0)) return 1;
51  return Math.min(MAX_DENSITY, Math.max(1, real / estimated));
52}
53
54/**
55 * The prompt size compaction decides on. `sample` is the last measured request: `real` tokens for a prompt the Harness priced at
56 * `estimated`. `now` is the Harness's price of the conversation now. What was added or removed since the sample is scaled by the sample's
57 * density; the measured part is exact. Without a sample, or when the measurement is lower than the Harness's own price, the Harness's
58 * price stands (it is never an underestimate that makes this smaller).
59 */
60export function pressureNow({ sample = null, now }) {
61  if (!sample || !(sample.real > 0) || !(sample.estimated > 0)) return Math.max(0, now);
62  const density = densityOf(sample.real, sample.estimated);
63  return Math.max(Math.round(now), Math.round(sample.real + density * (now - sample.estimated)));
64}
65
66/** The usage a finished model request reported, as the prompt side only: input plus the cache's reads and writes (output is not in the prompt). */
67export function promptTokensOf(usage) {
68  if (!usage || typeof usage !== 'object') return 0;
69  const n = value => (Number.isFinite(Number(value)) ? Math.max(0, Number(value)) : 0);
70  return n(usage.inputTokens) + n(usage.cacheReadTokens) + n(usage.cacheWriteTokens);
71}
72
73/** The usage of a settled assistant event (a `usage` on the message, or the last usage chunk of its stream). */
74export function usageOfEvent(event) {
75  const data = event?.data;
76  if (!data) return null;
77  if (data.usage && typeof data.usage === 'object') return data.usage;
78  const stream = Array.isArray(data.stream) ? data.stream : [];
79  for (let i = stream.length - 1; i >= 0; i--) if (stream[i]?.type === 'chunk' && stream[i].chunk?.type === 'usage') return stream[i].chunk.usage ?? null;
80  return null;
81}
82
83/**
84 * A summarising request is: the conversation's system prompt and tools, the messages to condense, then the instruction. This is how many
85 * real tokens the messages may take in a window so that all of it, the summary and a safety margin fit.
86 */
87export function summaryBudget({ window, summaryTokens, toolsTokens = 0, systemTokens = 0, instructionTokens = 900, slack = WINDOW_SLACK }) {
88  return Math.floor(window - summaryTokens - toolsTokens - systemTokens - instructionTokens - slack);
89}
90
91/** Text blocks of a message, longest first: the ones worth shortening when a single message is bigger than the budget. */
92function textBlocks(message) {
93  return (Array.isArray(message?.content) ? message.content : []).filter(b => (b?.type === 'text' || b?.type === 'reasoning') && typeof b.text === 'string');
94}
95
96/**
97 * One message cut down to `maxTokens` (in the Harness's price times `density`): the start and the end of its longest text are kept and
98 * the middle is replaced by a line saying how much was left out. Only the copy sent to the summariser is cut; the conversation keeps
99 * the whole message until the summary replaces it.
100 */
101export function clipMessage(message, maxTokens, density = 1) {
102  if (estimateMessage(message) * density <= maxTokens) return message;
103  const blocks = textBlocks(message);
104  if (!blocks.length) return message;
105  const others = estimateMessage({ ...message, content: (message.content ?? []).filter(b => !blocks.includes(b)) }) * density;
106  const room = Math.max(256, maxTokens - others);
107  const share = room / blocks.reduce((n, b) => n + b.text.length, 0) / density * CHARS_PER_TOKEN;   // characters kept per character
108  const content = (message.content ?? []).map((block) => {
109    if (!blocks.includes(block)) return block;
110    const keep = Math.max(200, Math.floor(block.text.length * Math.min(1, share) - 120));
111    if (block.text.length <= keep) return block;
112    const head = Math.ceil(keep * 0.6), tail = keep - head;
113    const left = block.text.length - head - tail;
114    return { ...block, text: `${block.text.slice(0, head)}\n\n[… ${left.toLocaleString('en-US')} characters from the middle are left out of this summary request …]\n\n${block.text.slice(block.text.length - tail)}` };
115  });
116  return { ...message, content };
117}
118
119/** Whether cutting the list in front of index `i` would separate a tool call from its result. */
120function balancedBefore(messages, i) {
121  let open = 0;
122  for (let k = 0; k < i; k++) {
123    const m = messages[k];
124    if (m?.role === 'assistant') open += (Array.isArray(m.content) ? m.content : []).filter(b => b?.type === 'tool-call').length;
125    else if (m?.role === 'tool') open -= 1;
126  }
127  return open <= 0;
128}
129
130/**
131 * Split messages into runs that each fit `budget` real tokens (price `density`), cutting between a tool call's result and the next
132 * message when it can. A message bigger than the budget by itself is clipped first. Order is kept.
133 */
134export function splitMessages(messages, budget, density = 1) {
135  const room = Math.max(512, budget);
136  const sized = messages.map(m => clipMessage(m, Math.floor(room * 0.8), density));
137  const cost = sized.map(m => estimateMessage(m) * density);
138  const runs = [];
139  let start = 0, used = 0;
140  for (let i = 0; i < sized.length; i++) {
141    if (i > start && used + cost[i] > room) {
142      // Cut as late as possible, but never between a tool call and its result when a clean place exists inside the run.
143      let cut = i;
144      while (cut > start + 1 && !balancedBefore(sized, cut)) cut--;
145      if (!balancedBefore(sized, cut)) cut = i;
146      runs.push(sized.slice(start, cut));
147      start = cut;
148      used = cost.slice(start, i).reduce((n, x) => n + x, 0);
149    }
150    used += cost[i];
151  }
152  if (start < sized.length) runs.push(sized.slice(start));
153  return runs;
154}
155
156/** Whether a failure is the model server saying the prompt does not fit its window. */
157export function isContextOverflow(error) {
158  if (!error) return false;
159  if (error.code === 'CONTEXT_WINDOW_EXCEEDED') return true;
160  const text = [error.message, error.cause?.message, error.failure?.message, error.failure?.code].filter(Boolean).join(' ');
161  return /request exceeds the context window|leaves no room to answer|context[_ ]length|context window|too many tokens|maximum context/i.test(text);
162}
163
164/** The Harness asks for "concise English engineering prose", so a Chinese or Russian chat came back summarised in English (#4750). One sentence is added to the
165 *  summary request's last message: write it in the language the person used. Paths, commands and identifiers stay exact. Messages are not changed in place. */
166export const SUMMARY_LANGUAGE_RULE = 'Write the summary in the language the person used in this conversation (English only when they wrote English). The instruction above is in English; that does not change the language of the summary. Keep file paths, commands, error strings, identifiers and numbers exactly as they appear.';
167export function withSummaryLanguage(messages) {
168  if (!Array.isArray(messages) || !messages.length) return messages;
169  const last = messages[messages.length - 1];
170  if (!last || last.role !== 'user') return messages;
171  const content = typeof last.content === 'string' ? last.content + ' ' + SUMMARY_LANGUAGE_RULE
172    : Array.isArray(last.content) ? [...last.content, { type: 'text', text: SUMMARY_LANGUAGE_RULE }] : null;
173  return content === null ? messages : [...messages.slice(0, -1), { ...last, content }];
174}