okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
1306424be
main
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 ) { 21const content = Array . isArray ( message ?. content ) ?message . content :[]; 22if ( message ?. role === 'system' ) { 23if ( ! content . length ) return 0 ; 24let chars = 0 ; 25for ( const block of content ) chars += block ?. type === 'text' ?String ( block . text ?? '' ). length :JSON . stringify ( block ?? {}). length ; 26return Math . ceil ( chars / CHARS_PER_TOKEN ) + MESSAGE_OVERHEAD ; 27} 28let tokens = MESSAGE_OVERHEAD ; 29for ( const block of content ) { 30if ( block ?. type === 'text' || block ?. type === 'reasoning' ) tokens += Math . ceil ( String ( block . text ?? '' ). length / CHARS_PER_TOKEN ) + BLOCK_OVERHEAD ; 31else 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 ; 32else tokens += BLOCK_OVERHEAD + Math . ceil ( JSON . stringify ( block ?? {}). length / CHARS_PER_TOKEN ); 33} 34return tokens ; 35} 36 37/** The Harness's price of the tool list of a request header. */ 38export function estimateTools ( header ) { 39const tools = header ?. tools ; 40if ( ! Array . isArray ( tools ) || ! tools . length ) return 0 ; 41return 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 ) { 50if ( ! ( real > 0 ) || ! ( estimated > 0 )) return 1 ; 51return 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}) { 61if ( ! sample || ! ( sample . real > 0 ) || ! ( sample . estimated > 0 )) return Math . max ( 0 , now ); 62const density = densityOf ( sample . real , sample . estimated ); 63return 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 ) { 68if ( ! usage || typeof usage !== 'object' ) return 0 ; 69const n = value => ( Number . isFinite ( Number ( value )) ?Math . max ( 0 , Number ( value )) :0 ); 70return 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 ) { 75const data = event ?. data ; 76if ( ! data ) return null ; 77if ( data . usage && typeof data . usage === 'object' ) return data . usage ; 78const stream = Array . isArray ( data . stream ) ?data . stream :[]; 79for ( let i = stream . length - 1 ; i >= 0 ; i -- ) if ( stream [ i ]?. type === 'chunk' && stream [ i ]. chunk ?. type === 'usage' ) return stream [ i ]. chunk . usage ?? null ; 80return 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 }) { 88return 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 ) { 93return ( 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 ) { 102if ( estimateMessage ( message ) * density <= maxTokens ) return message ; 103const blocks = textBlocks ( message ); 104if ( ! blocks . length ) return message ; 105const others = estimateMessage ({ ...message , content :( message . content ?? []). filter ( b => ! blocks . includes ( b )) }) * density ; 106const room = Math . max ( 256 , maxTokens - others ); 107const share = room / blocks . reduce (( n , b ) => n + b . text . length , 0 ) / density * CHARS_PER_TOKEN ; // characters kept per character 108const content = ( message . content ?? []). map (( block ) => { 109if ( ! blocks . includes ( block )) return block ; 110const keep = Math . max ( 200 , Math . floor ( block . text . length * Math . min ( 1 , share ) - 120 )); 111if ( block . text . length <= keep ) return block ; 112const head = Math . ceil ( keep * 0.6 ), tail = keep - head ; 113const left = block . text . length - head - tail ; 114return { ...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}); 116return { ...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 ) { 121let open = 0 ; 122for ( let k = 0 ; k < i ; k ++ ) { 123const m = messages [ k ]; 124if ( m ?. role === 'assistant' ) open += ( Array . isArray ( m . content ) ?m . content :[]). filter ( b => b ?. type === 'tool-call' ). length ; 125else if ( m ?. role === 'tool' ) open -= 1 ; 126} 127return 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 ) { 135const room = Math . max ( 512 , budget ); 136const sized = messages . map ( m => clipMessage ( m , Math . floor ( room * 0.8 ), density )); 137const cost = sized . map ( m => estimateMessage ( m ) * density ); 138const runs = []; 139let start = 0 , used = 0 ; 140for ( let i = 0 ; i < sized . length ; i ++ ) { 141if ( 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. 143let cut = i ; 144while ( cut > start + 1 && ! balancedBefore ( sized , cut )) cut -- ; 145if ( ! balancedBefore ( sized , cut )) cut = i ; 146runs . push ( sized . slice ( start , cut )); 147start = cut ; 148used = cost . slice ( start , i ). reduce (( n , x ) => n + x , 0 ); 149} 150used += cost [ i ]; 151} 152if ( start < sized . length ) runs . push ( sized . slice ( start )); 153return runs ; 154} 155 156/** Whether a failure is the model server saying the prompt does not fit its window. */ 157export function isContextOverflow ( error ) { 158if ( ! error ) return false ; 159if ( error . code === 'CONTEXT_WINDOW_EXCEEDED' ) return true ; 160const text = [ error . message , error . cause ?. message , error . failure ?. message , error . failure ?. code ]. filter ( Boolean ). join ( ' ' ); 161return / 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 ) { 168if ( ! Array . isArray ( messages ) || ! messages . length ) return messages ; 169const last = messages [ messages . length - 1 ]; 170if ( ! last || last . role !== 'user' ) return messages ; 171const content = typeof last . content === 'string' ?last . content + ' ' + SUMMARY_LANGUAGE_RULE 172 :Array . isArray ( last . content ) ?[ ...last . content , { type :'text' , text :SUMMARY_LANGUAGE_RULE }] :null ; 173return content === null ?messages :[ ...messages . slice ( 0 , - 1 ), { ...last , content}]; 174}