okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
4fb068a8c
main
1// AGENT-LOST (11-01): a reply the length limit cut inside a tool call used to vanish: no file, no card, no sentence. 2// Pure parts always run; the end-to-end ones need a built Harness (STRATA_HARNESS_DIR) and use the scripted model server. 3import test from 'node:test' ; 4import assert from 'node:assert/strict' ; 5import { mkdtempSync , mkdirSync , rmSync , existsSync , readFileSync } from 'node:fs' ; 6import { tmpdir } from 'node:os' ; 7import { join } from 'node:path' ; 8import { replyCap , unescapeJsonTail , ToolDraft , cutCalls , cutNotice , cutNudge } from '../server/agent/reply-cut.mjs' ; 9import { TurnProjector } from '../server/agent/events.mjs' ; 10import { startScriptedWorker } from './helpers/scripted-worker.mjs' ; 11import { createAgentBridge , MAX_CUT_RETRIES } from '../server/agent/agent-bridge.mjs' ; 12import { resolveHarness } from '../server/agent/harness-runtime.mjs' ; 13import { localOutputBudget } from '../server/agent/profile.mjs' ; 14 15const HARNESS = process . env . STRATA_HARNESS_DIR ; 16const skip = ! HARNESS || ! resolveHarness ({ env :process . env }). ok ?'STRATA_HARNESS_DIR is not set to a built Harness' :false ; 17 18test ( 'the reply ceiling is half the window up to 64K tokens and never below what compaction reserves' , () => { 19assert . equal ( replyCap ( 65536 , localOutputBudget ( 65536 )), 32768 ); 20assert . ok ( replyCap ( 65536 , localOutputBudget ( 65536 )) > localOutputBudget ( 65536 ), '19,660 was the cut that lost the pagoda' ); 21assert . equal ( replyCap ( 131072 , localOutputBudget ( 131072 )), 65536 ); 22assert . equal ( replyCap ( 262144 , localOutputBudget ( 262144 )), 65536 , 'at most 64K tokens, so a loop cannot run for an hour' ); 23assert . equal ( replyCap ( 8192 , localOutputBudget ( 8192 )), 4096 ); 24assert . equal ( replyCap ( 0 , 5000 ), 16384 , 'no window known: 32K is assumed' ); 25assert . equal ( replyCap ( 4096 , 4096 ), 4096 , 'never below the reserve' ); 26}); 27 28test ( 'JSON text is read back for the preview, and a half-written escape is dropped' , () => { 29assert . equal ( unescapeJsonTail ( 'a\\nb\\t\\"c\\"\\\\d' ), 'a\nb\t"c"\\d' ); 30assert . equal ( unescapeJsonTail ( 'line\\' ), 'line' ); 31assert . equal ( unescapeJsonTail ( 'x\\u00e9y' ), 'xéy' ); 32assert . equal ( unescapeJsonTail ( 'x\\u00' ), 'x' ); 33}); 34 35test ( 'a call being written knows its file, its size, its lines and the tail of its text' , () => { 36const d = new ToolDraft ( 'c1' , 'write' ); 37for ( const piece of [ '{"file_pa' , 'th":"C:\\\\work\\\\pagoda.html","con' , 'tent":"<!doctype html>\\n<html>\\n' ]) d . add ( piece ); 38assert . equal ( d . target , 'C:\\work\\pagoda.html' ); 39assert . equal ( d . lines , 2 ); 40assert . equal ( d . preview (), '<!doctype html>\n<html>\n' ); 41for ( let i = 0 ; i < 400 ; i ++ ) d . add ( `<div class=\\"row ${ i } \\">text ${ i } </div>\\n` ); 42assert . ok ( d . bytes > 10_000 ); 43assert . equal ( d . lines , 402 ); 44const p = d . preview ( 1000 ); 45assert . ok ( p . length <= 1000 && p . endsWith ( '</div>\n' ) && ! p . includes ( '\\n' ) && p . includes ( 'class="row' ), 'the tail, read back, ends where the model is' ); 46const f = d . frame ({ scope :'write' , verb :'Writing' }); 47assert . deepEqual ( Object . keys ( f . draft ). sort (), [ 'bytes' , 'done' , 'id' , 'lines' , 'name' , 'preview' , 'scope' , 'target' , 'verb' ]); 48assert . equal ( d . frame ({ done :true }). draft . preview , '' , 'a finished draft carries no text' ); 49}); 50 51test ( 'the file is found when the model writes its name after the text, or split between two pieces' , () => { 52const d = new ToolDraft ( 'c2' , 'write' ); 53d . add ( '{"content":"line one\nline two\n' ); 54assert . equal ( d . target , '' ); 55d . add ( 'more","file_pa' ); d . add ( 'th":"/w/big.txt"}' ); 56assert . equal ( d . target , '/w/big.txt' ); 57}); 58 59test ( 'the sentences name the file and the size, say what to do, and the nudge asks for smaller parts' , () => { 60const draft = new ToolDraft ( 'a' , 'write' ); draft . add ( '{"file_path":"/w/pagoda.html","content":"' ); draft . bytes = 52_300 ; 61const calls = cutCalls ([ draft ]); 62assert . deepEqual ( calls , [{ name :'write' , target :'/w/pagoda.html' , bytes :52_300 }]); 63const again = cutNotice ({ calls, tokens :19660 , retrying :true }); 64assert . match ( again . text , / reached its length limit \(19,660 tokens\) while writing pagoda\.html \(52 KB\), so that write did not happen\. I asked the assistant to look at what is on disk and write the rest in smaller parts\. / ); 65const last = cutNotice ({ calls, tokens :19660 }); 66assert . match ( last . text , / Say “continue” / ); 67assert . match ( cutNotice ({ tokens :500 }). text , / ^The reply reached its length limit \(500 tokens\) and was cut off\. Say “continue” / ); 68assert . match ( cutNudge ({ calls, tokens :19660 }), / writing \/w\/pagoda\.html in one tool call, so that call did not run [ \s\S ] * Do not delete or start over a file that is already complete [ \s\S ] * smaller parts / ); 69assert . match ( cutNudge ({}), / cut off by the output limit / ); 70for ( const n of [ again , last ]) assert . equal ( n . text , n . key . replace ( / \{ ( \d ) \} / g , ( _ , i ) => n . values [ i ]), 'the key and its values make the sentence' ); 71}); 72 73// ------------------------------------------------------------------------------------------------ the projector 74 75const chunk = ( c , attemptId = 'a1' ) => ({ type :'assistant-stream' , frame :{ type :'chunk' , attemptId, chunk :c } }); 76const event = ( type , data = {}) => ({ type :'event' , event :{ type, time :Date . now (), data} }); 77 78test ( 'the projector streams a growing draft frame for a call being written, and the whole call ends it' , () => { 79const p = new TurnProjector (); 80const frames = []; 81const head = '{"file_path":"big.txt","content":"' ; 82frames . push ( ...p . consume ( chunk ({ type :'tool-call-delta' , id :'c1' , name :'write' , argumentsDelta :head }))); 83assert . equal ( frames . filter ( f => f . type === 'agent-tool-draft' ). length , 1 , 'the first piece shows at once' ); 84const first = frames . find ( f => f . type === 'agent-tool-draft' ). draft ; 85assert . equal ( first . name , 'write' ); assert . equal ( first . target , 'big.txt' ); assert . equal ( first . scope , 'write' ); assert . equal ( first . verb , 'Writing a file' ); 86// A burst inside 200 ms sends no more frames, but the next one after the pause carries everything so far. 87for ( let i = 0 ; i < 20 ; i ++ ) p . consume ( chunk ({ type :'tool-call-delta' , id :'c1' , argumentsDelta :`entry ${ i } \\n` })); 88assert . equal ( p . composing . get ( 'c1' ). lines , 20 ); 89p . composing . get ( 'c1' ). at = 0 ; 90const later = p . consume ( chunk ({ type :'tool-call-delta' , id :'c1' , argumentsDelta :'entry 20\\n' })). find ( f => f . type === 'agent-tool-draft' ). draft ; 91assert . equal ( later . lines , 21 ); assert . match ( later . preview , / entry 20\n$ / ); 92const out = p . consume ( event ( 'tool/call' , { callId :'c1' , name :'write' , arguments :'{"file_path":"big.txt","content":"x"}' })); 93assert . ok ( out . some ( f => f . type === 'agent-tool' ), 'the ordinary card takes over' ); 94assert . equal ( out . find ( f => f . type === 'agent-tool-draft' )?. draft . done , true , 'and the draft is closed' ); 95assert . equal ( p . composing . size , 0 ); 96}); 97 98test ( 'a reply cut in a call: the done frame says length and what was lost, and the draft is taken down' , () => { 99const p = new TurnProjector (); 100p . consume ( chunk ({ type :'tool-call-delta' , id :'c9' , name :'write' , argumentsDelta :'{"file_path":"/w/pagoda.html","content":"abc' })); 101p . consume ( chunk ({ type :'usage' , usage :{ inputTokens :6000 , outputTokens :19660 } })); 102p . consume ( event ( 'turn/end' , { reason :{ kind :'max-tokens' } })); 103assert . deepEqual ( p . cut (), { tokens :19660 , calls :[{ name :'write' , target :'/w/pagoda.html' , bytes :p . composing . get ( 'c9' ). bytes }] }); 104const frames = p . finish ({ model :'m' , contextMax :65536 }); 105const drop = frames . find ( f => f . type === 'agent-tool-draft' ); 106assert . ok ( drop && drop . draft . done && drop . draft . lost , 'the writing card goes away' ); 107const done = frames . at ( - 1 ); 108assert . equal ( done . type , 'done' ); assert . equal ( done . finishReason , 'length' ); 109assert . equal ( done . cut . tokens , 19660 ); assert . equal ( done . cut . calls [ 0 ]. target , '/w/pagoda.html' ); 110}); 111 112test ( 'a call nobody writes a card for (a helper agent) makes no draft' , () => { 113const p = new TurnProjector (); 114const out = p . consume ( chunk ({ type :'tool-call-delta' , id :'s1' , name :'subagent' , argumentsDelta :'{"prompt":"x' })); 115assert . equal ( out . filter ( f => f . type === 'agent-tool-draft' ). length , 0 ); 116}); 117 118// ------------------------------------------------------------------------------------------------ with the real Harness 119 120async function rig ( t , { window= 65536 } = {}) { 121const worker = await startScriptedWorker ({ chunkDelayMs :5 }); 122const dir = mkdtempSync ( join ( tmpdir (), 'strata-lost-' )); 123const ws = join ( dir , 'ws' ); mkdirSync ( ws , { recursive :true }); 124const logs = []; 125const bridge = createAgentBridge ({ dataDir :dir , localInstances :() => [{ id :'i' , label :'S' , baseUrl :worker . url , modelId :'scripted-model' , context :window , slots :2 }], connections :() => [], 126env :process . env , startTimeoutMs :90_000 , log :l => logs . push ( l ) }); 127t . after ( async () => { await bridge . close (); await worker . close (); try { rmSync ( dir , { recursive :true , force :true , maxRetries :3 }); } catch { /* best effort */ } }); 128return { worker, bridge, ws, logs, base :( chatId , onFrame ) => ({ chatId, workspacePath :ws , mode :'bypass' , thinking :'Off' , onFrame}) }; 129} 130const words = frames => frames . filter ( f => f . type === 'delta' ). map ( f => f . text ). join ( '' ); 131const capOf = q => q . params . max_tokens ?? q . params . max_completion_tokens ; 132const writes = r => r . worker . requests . filter ( q => q . directive === 'cutwrite' || q . directive === 'cutalways' ); 133 134test ( 'every model request may produce half the window, not the 30 percent the Harness reserves for compaction' , { skip}, async ( t ) => { 135const r = await rig ( t ); 136const out = []; 137await r . bridge . runTurn ({ ...r . base ( 'c0' , f => out . push ( f )), message :'SCRIPT:echo hello' }); 138const asked = r . worker . requests . find ( q => q . directive === 'echo' ); 139assert . ok ( asked , 'the model was asked' ); 140assert . equal ( capOf ( asked ), 32768 , `the request carried ${ capOf ( asked )} ; the pagoda's carried 19660` ); 141}); 142 143test ( 'a small window still gets a request that fits it (the Harness clamps to the room left)' , { skip}, async ( t ) => { 144const r = await rig ( t , { window :8192 }); 145await r . bridge . runTurn ({ ...r . base ( 'c0s' , () => {}), message :'SCRIPT:echo hello' }); 146const asked = r . worker . requests . find ( q => q . directive === 'echo' ); 147assert . ok ( capOf ( asked ) > 0 && capOf ( asked ) <= 4096 , `max_tokens ${ capOf ( asked )} for an 8K window` ); 148}); 149 150test ( 'a reply cut inside a file write: the chat says so, the agent is asked to go on in smaller parts, and the file gets written' , { skip}, async ( t ) => { 151const r = await rig ( t ); 152const out = []; 153await r . bridge . runTurn ({ ...r . base ( 'c1' , f => out . push ( f )), message :'SCRIPT:cutwrite big.txt' }); 154const said = out . find ( f => f . type === 'delta' && f . noteReason === 'cut' ); 155assert . ok ( said , 'a sentence about the cut' ); 156assert . match ( said . text , / while writing big\.txt / ); assert . match ( said . text , / that write did not happen. I asked the assistant to look at what is on disk and write the rest in smaller parts / ); 157assert . equal ( out . filter ( f => f . type === 'error' ). length , 0 ); 158const done = out . filter ( f => f . type === 'done' ). at ( - 1 ); 159assert . equal ( done . finishReason , 'stop' , 'the turn ends on the agent\'s own finish, not on the cut' ); 160assert . ok ( existsSync ( join ( r . ws , 'big.txt' )), 'the file is on disk' ); 161assert . match ( readFileSync ( join ( r . ws , 'big.txt' ), 'utf8' ), / entry 0001 / ); 162assert . match ( words ( out ), / Written in parts / ); 163assert . equal ( writes ( r ). length , 3 , 'the cut reply, the nudged write, the closing words' ); 164assert . ok ( writes ( r )[ 1 ]. raw . includes ( 'cut off by the output limit' ), 'the second request carries the nudge' ); 165const drafts = out . filter ( f => f . type === 'agent-tool-draft' ); 166assert . ok ( drafts . length >= 2 , 'the writing was shown live' ); 167assert . ok ( drafts . some ( f => ! f . draft . done && f . draft . name === 'write' ), 'a writing card opened as soon as the model named the call' ); 168// The Harness hands the streamed pieces over in batches (a few a second at most), so a short script may show only the first and the last. 169assert . ok ( drafts . some ( f => f . draft . done && f . draft . lost && f . draft . target === 'big.txt' && f . draft . bytes > 1000 ), 'and taken down, with its file and size, when it was lost' ); 170}); 171 172test ( `a model that is cut every time is asked ${ MAX_CUT_RETRIES } times, then the turn ends with a plain sentence, never silently` , { skip}, async ( t ) => { 173const r = await rig ( t ); 174const out = []; 175await r . bridge . runTurn ({ ...r . base ( 'c2' , f => out . push ( f )), message :'SCRIPT:cutalways big.txt' }); 176assert . equal ( writes ( r ). length , MAX_CUT_RETRIES + 1 ); 177const notes = out . filter ( f => f . type === 'delta' && f . noteReason === 'cut' ); 178assert . equal ( notes . length , MAX_CUT_RETRIES + 1 , 'one sentence per cut' ); 179assert . match ( notes . at ( - 1 ). text , / that write did not happen\. Say “continue” / ); 180const done = out . filter ( f => f . type === 'done' ). at ( - 1 ); 181assert . ok ( done , 'the turn ended' ); 182assert . equal ( done . finishReason , 'length' ); 183assert . equal ( done . cut . calls [ 0 ]. target , 'big.txt' ); 184assert . equal ( existsSync ( join ( r . ws , 'big.txt' )), false , 'nothing half-written is left behind' ); 185});