okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
4fb068a8c
main
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 ) { 36const meter = ctx . tokenMeter ; 37const llm = ctx . llm ; 38const 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. 41if ( meter && typeof meter . measure === 'function' && ! wrapped . has ( meter )) { 42wrapped . add ( meter ); 43const original = meter . measure ; 44meter . measure = function measure ( session , requestHeader ) { 45const m = original . call ( this , session , requestHeader ); 46const sample = samples . get ( session ); 47if ( ! sample ) return m ; 48const now = m . surfaceTokens + estimateTools ( requestHeader ?? session . requestHeader ?.()); 49const total = Math . max ( m . totalTokens , pressureNow ({ sample, now})); 50if ( total <= m . totalTokens ) return m ; 51const density = densityOf ( sample . real , sample . estimated ); 52return { ...m , totalTokens :total , nodes :m . nodes . map ( n => ({ ...n , tokens :Math . ceil ( n . tokens * density ) })) }; 53}; 54ctx . on ( 'session/event' , ( session , event ) => { 55if ( event . type !== 'assistant/message' ) return ; 56const real = promptTokensOf ( usageOfEvent ( event )); 57if ( ! ( real > 0 )) return ; 58try { 59// The request that was just answered saw the conversation without this answer: its price is the surface before the answer's node. 60const m = original . call ( meter , session ); 61const heuristic = m . nodes . reduce (( n , x ) => n + ( x . seq === event . seq ?0 :x . heuristicTokens ), 0 ); 62const estimated = heuristic + estimateTools ( session . requestHeader ?.()); 63if ( ! ( estimated > 0 )) return ; 64const sample = { real, estimated}; 65samples . set ( session , sample ); 66if ( 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. 72if ( llm && typeof llm . stream === 'function' && ! wrapped . has ( llm )) { 73wrapped . add ( llm ); 74const original = llm . stream ; 75llm . stream = function stream ( options ) { 76if ( options ?. purpose !== 'compaction' ) return original . call ( this , options ); 77return 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). 89if ( llm && typeof llm . prepareCall === 'function' && ! wrapped . has ( llm . prepareCall )) { 90const original = llm . prepareCall ; 91const raised = new WeakSet (); 92const prepare = async function prepareCall ( config , signal , configure ) { 93try { raiseReplyCeiling ( config ?. provider , raised ); } catch ( e ) { log ( 'warn' , `could not raise the reply ceiling: ${ e . message } ` ); } 94return original . call ( this , config , signal , configure ); 95}; 96wrapped . add ( prepare ); 97llm . prepareCall = prepare ; 98} 99function raiseReplyCeiling ( provider , raised ) { 100if ( ! isLocalRoute ( provider )) return ; 101const adapter = llm . adapters ?. get ?.( provider )?. adapter ; 102if ( ! adapter || raised . has ( adapter ) || typeof adapter . streamWithSnapshot !== 'function' || typeof adapter . modelOf !== 'function' ) return ; 103raised . add ( adapter ); 104const stream = adapter . streamWithSnapshot ; 105adapter . streamWithSnapshot = function streamWithSnapshot ( options , snapshot ) { 106let next = options ; 107try { 108if ( isLocalRoute ( options ?. provider )) { 109const model = this . modelOf ( snapshot , options . provider , options . model ); 110const 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. 112if ( model . contextWindow > 0 && asked >= Math . floor ( model . contextWindow * 0.25 )) { 113const cap = replyCap ( model . contextWindow , asked ); 114if ( cap > asked ) next = { ...options , maxTokens :cap }; 115} 116} 117} catch { next = options ; } 118return 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. 124ctx . inject ([ 'commands' ], ( commandCtx ) => { 125commandCtx . commands . register ({ 126definitionId :'strata-context' , 127name :'strata-context' , 128description :'Reports how many tokens the conversation holds now and the size of the model window' , 129handler :async ( invocation ) => { 130try { 131const session = invocation . agent . session ; 132const tokens = meter . measure ( session ). totalTokens ; 133const config = session . requestHeader ?.()?. config ; 134let window = 0 ; 135if ( config ) window = ( await llm . resolveModelInfo ( config . provider , config . model ))?. context ?. contextWindow ?? 0 ; 136return { 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. */ 143async function drain ( iterable ) { 144let text = '' , finish = null ; 145const chunks = []; 146for await ( const chunk of iterable ) { 147chunks . push ( chunk ); 148if ( chunk . type === 'text-delta' ) text += chunk . text ?? '' ; 149else if ( chunk . type === 'finish' ) finish = chunk . reason ; 150} 151return { text, finish, chunks}; 152} 153const refusedForSize = finish => finish ?. kind === 'error' && isContextOverflow ( finish . failure ?? finish ); 154 155async function * summaryStream ( options , original ) { 156options = { ...options , messages :withSummaryLanguage ( options . messages ) }; // #4750: the summary follows the conversation's language 157let window = 0 ; 158try { window = ( await llm . resolveModelInfo ( options . provider , options . model , options . signal ))?. context ?. contextWindow ?? 0 ; } catch { window = 0 ; } 159const messages = options . messages ?? []; 160const key = String ( options . sessionId ?? '' ); 161const summaryTokens = options . maxTokens ?? 4096 ; 162if ( ! ( window > 0 ) || messages . length < 2 ) { yield * original . call ( this , options ); return ; } 163const own = bySessionId . get ( key ); 164let density = Math . max ( careful . get ( key ) ?? 1 , own ?densityOf ( own . real , own . estimated ) :1 ); 165const price = list => list . reduce (( n , m ) => n + estimateMessage ( m ), 0 ) * density ; 166const 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). 168if ( price ( messages ) + estimateTools ({ tools :options . tools }) * density <= limit ) { 169const first = await drain ( original . call ( this , options )); 170if ( ! refusedForSize ( first . finish )) { for ( const chunk of first . chunks ) yield chunk ; return ; } 171density = Math . min ( MAX_DENSITY , density * 1.6 ); 172careful . set ( key , density ); 173log ( '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. 176const instruction = messages [ messages . length - 1 ]; 177const system = messages [ 0 ]?. role === 'system' ?messages [ 0 ] :null ; 178const body = messages . slice ( system ?1 :0 , - 1 ); 179let tools = options . tools ; 180if ( tools && estimateTools ({ tools}) * density > window / 3 ) tools = undefined ; // a long tool list only describes tools: the summary does not need it 181const fixed = ( system ?estimateMessage ( system ) :0 ) * density + estimateTools ({ tools}) * density + estimateMessage ( instruction ) * density ; 182let budget = summaryBudget ({ window, summaryTokens :summaryTokens * 2 , systemTokens :fixed , instructionTokens :0 }); 183for ( let attempt = 0 ; ; attempt ++ ) { 184const runs = splitMessages ( body , Math . max ( 1024 , budget ), density ); 185log ( '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)` ); 186let failed = null , summary = '' ; 187for ( let i = 0 ; i < runs . length && ! failed ; i ++ ) { 188options . signal ?. throwIfAborted ?.(); 189const carried = summary ?[{ role :'user' , content :[{ type :'text' , text :`<compacted-summary>\n ${ summary } \n</compacted-summary>` }] }] :[]; 190const { tools :_drop , ...rest } = options ; 191const piece = { ...rest , ...( tools ?{ tools} :{}), messages :[ ...( system ?[ system ] :[]), ...carried , ...runs [ i ], instruction ] }; 192const { text, finish, chunks} = await drain ( original . call ( this , piece )); 193if ( 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. 195if ( i === runs . length - 1 || finish ?. kind === 'error' || finish ?. kind === 'aborted' ) { for ( const chunk of chunks ) yield chunk ; return ; } 196summary = text ; 197} 198if ( ! failed || attempt >= 3 ) throw Object . assign ( new Error ( failed ?. failure ?. message ?? 'the summary request does not fit the window' ), { code :'CONTEXT_WINDOW_EXCEEDED' }); 199density = Math . min ( MAX_DENSITY , density * 1.6 ); 200careful . set ( key , density ); 201budget = Math . max ( 1024 , budget / 2 ); 202log ( 'warn' , `a piece did not fit; asking again with pieces of about ${ Math . round ( budget )} tokens` ); 203} 204} 205}