okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
4fb068a8c
main
1/** 2* Pure projections from Harness facts to the frames the chat UI already renders. 3* 4* No I/O here, so the mapping can be tested without an agent. The inputs are the two things a 5* `session/follow` stream carries: durable session events (`tool/call`, `approval/asked`, 6* `tool/result`, `turn/end`, ...) and the process-local `assistant-stream` frames (text and 7* reasoning deltas, usage). 8*/ 9 10import { toolUpdate , TokenCount , fmtTokens } from './status.mjs' ; 11import { askFor } from './ask.mjs' ; 12import { FIT_TEXT , fill } from './context-fit.mjs' ; 13import { isContextOverflow } from './context-budget.mjs' ; 14import { ToolDraft , cutCalls } from './reply-cut.mjs' ; 15 16const SHELL = new Set ([ 'pwsh' , 'bash' , 'job_kill' , 'job_output' , 'job_list' ]); 17const WRITE = new Set ([ 'write' , 'edit' ]); 18const READ = new Set ([ 'read' , 'glob' , 'grep' , 'read_image' , 'working_directory' , 'todo_write' , 'get_goal' , 'list_agents' , 'skill' , 'present' ]); 19 20/** Delegation tools have no card: the helper agents show as rows, and the tool's raw reply ("started subagent <id>") is not for the person. */ 21export const NO_CARD = new Set ([ 'subagent' , 'subagent_fork' , 'send_message' , 'interrupt_agent' , 'list_agents' ]); 22 23export function toolScope ( name ) { 24if ( SHELL . has ( name )) return 'shell' ; 25if ( WRITE . has ( name )) return 'write' ; 26if ( READ . has ( name )) return 'read' ; 27return 'connected' ; 28} 29 30/** Shown on a card the mode refused (Plan, Bypass): the model's own error text would say "the user rejected". */ 31export const NOT_IN_MODE = 'Not allowed in this mode. Nothing ran.' ; 32 33const clip = ( value , max ) => { 34const text = String ( value ?? '' ); 35return text . length > max ?` ${ text . slice ( 0 , max - 1 )} …` :text ; 36}; 37 38export function parseArguments ( raw ) { 39if ( raw && typeof raw === 'object' ) return raw ; 40try { const v = JSON . parse ( String ( raw ?? '{}' )); return v && typeof v === 'object' ?v :{}; } catch { return {}; } 41} 42 43/** 44* One plain sentence and one short detail per tool, so a card never shows raw JSON or an internal tool name as its 45* explanation. Unknown tools (a connected MCP server's) fall back to a generic sentence with their arguments. 46*/ 47const WORDS = { 48read :a => [ 'Reads a file.' , a . file_path ?? a . path ], 49glob :a => [ 'Looks for files by name.' , a . pattern ], 50grep :a => [ 'Searches inside files.' , a . pattern ?? a . query ], 51read_image :a => [ 'Looks at a picture.' , a . file_path ?? a . path ], 52working_directory :() => [ 'Checks which folder it is working in.' , '' ], 53todo_write :a => [ 'Updates its to-do list.' , Array . isArray ( a . todos ) ?a . todos . map ( t => t ?. content ?? t ?. title ?? '' ). filter ( Boolean ). join ( '; ' ) :'' ], 54skill :a => [ 'Uses a saved skill.' , a . name ?? a . skill ], 55present :a => [ 'Shows you a result.' , a . file_path ?? a . path ?? a . title ], 56create_goal :a => [ 'Sets a goal to work towards.' , a . objective ], 57update_goal :a => [ 'Updates the goal.' , a . objective ?? a . status ?? '' ], 58get_goal :() => [ 'Checks the current goal.' , '' ], 59web_fetch :a => [ 'Opens a web page.' , a . url ], 60web_search :a => [ 'Searches the web.' , Array . isArray ( a . queries ) ?a . queries . join ( '; ' ) :a . query ], 61workflow :a => [ 'Runs a multi-step plan.' , a . description ?? a . name ?? '' ], 62job_list :() => [ 'Checks the background tasks.' , '' ], 63job_output :a => [ 'Reads what a background task printed.' , a . job_id ?? a . id ], 64job_kill :a => [ 'Stops a background task.' , a . job_id ?? a . id ], 65lsp :a => [ 'Looks up how the code fits together.' , a . file_path ], 66}; 67 68/** 69* What a card says it is doing, in the person's words: [while it runs, when it worked, when it failed]. The UI translates 70* these fixed sentences and writes the target (a file path, the command) beside them, so a row never shows `pwsh · Ran`. 71*/ 72const VERBS = { 73write :[ 'Writing a file' , 'Wrote a file' , "Couldn't write the file" ], 74edit :[ 'Changing a file' , 'Changed a file' , "Couldn't change the file" ], 75read :[ 'Reading a file' , 'Read a file' , "Couldn't read the file" ], 76read_image :[ 'Looking at a picture' , 'Looked at a picture' , "Couldn't look at the picture" ], 77glob :[ 'Searching for files' , 'Searched for files' , "Couldn't search for files" ], 78grep :[ 'Searching inside files' , 'Searched inside files' , "Couldn't search inside files" ], 79pwsh :[ 'Running a command' , 'Ran a command' , 'The command failed' ], 80bash :[ 'Running a command' , 'Ran a command' , 'The command failed' ], 81web_fetch :[ 'Opening a web page' , 'Opened a web page' , "Couldn't open the web page" ], 82web_search :[ 'Searching the web' , 'Searched the web' , "Couldn't search the web" ], 83create_goal :[ 'Setting the goal' , 'Set the goal' , "Couldn't set the goal" ], 84update_goal :[ 'Updating the goal' , 'Updated the goal' , "Couldn't update the goal" ], 85get_goal :[ 'Checking the goal' , 'Checked the goal' , "Couldn't check the goal" ], 86skill :[ 'Loading your skill' , 'Loaded your skill' , "Couldn't load the skill" ], 87todo_write :[ 'Updating its to-do list' , 'Updated its to-do list' , "Couldn't update its to-do list" ], 88present :[ 'Showing you a result' , 'Showed you a result' , "Couldn't show the result" ], 89working_directory :[ 'Checking the folder' , 'Checked the folder' , "Couldn't check the folder" ], 90job_list :[ 'Checking background tasks' , 'Checked background tasks' , "Couldn't check background tasks" ], 91job_output :[ 'Reading a background task' , 'Read a background task' , "Couldn't read the background task" ], 92job_kill :[ 'Stopping a background task' , 'Stopped a background task' , "Couldn't stop the background task" ], 93}; 94const GENERIC_VERBS = [ 'Using a tool' , 'Used a tool' , 'The tool failed' ]; 95/** The browser tool server's tools (Settings -> Tools): the card says what happened to the page, not the tool's internal name. */ 96const BROWSER_VERBS = { 97browser_navigate :[ 'Opening a page in the browser' , 'Opened a page in the browser' , "Couldn't open the page" ], 98browser_click :[ 'Clicking on the page' , 'Clicked on the page' , "Couldn't click on the page" ], 99browser_hover :[ 'Pointing at the page' , 'Pointed at the page' , "Couldn't point at the page" ], 100browser_type :[ 'Typing on the page' , 'Typed on the page' , "Couldn't type on the page" ], 101browser_fill_form :[ 'Typing on the page' , 'Typed on the page' , "Couldn't type on the page" ], 102browser_press_key :[ 'Typing on the page' , 'Typed on the page' , "Couldn't type on the page" ], 103browser_snapshot :[ 'Looking at the page' , 'Looked at the page' , "Couldn't look at the page" ], 104browser_take_screenshot :[ 'Looking at the page' , 'Looked at the page' , "Couldn't look at the page" ], 105browser_evaluate :[ 'Running a small program on the page' , 'Ran a small program on the page' , "Couldn't run the program on the page" ], 106browser_run_code :[ 'Running a small program on the page' , 'Ran a small program on the page' , "Couldn't run the program on the page" ], 107browser_wait_for :[ 'Waiting for the page' , 'Waited for the page' , "Couldn't wait for the page" ], 108browser_navigate_back :[ 'Going back a page' , 'Went back a page' , "Couldn't go back" ], 109browser_tabs :[ 'Managing browser tabs' , 'Managed browser tabs' , "Couldn't manage the browser tabs" ], 110browser_close :[ 'Closing the browser page' , 'Closed the browser page' , "Couldn't close the browser page" ], 111}; 112const BROWSER_GENERIC = [ 'Using the browser' , 'Used the browser' , 'The browser step failed' ]; 113const BROWSER_PREFIX = 'mcp__browser__' , INSTRUCTIONS_PREFIX = 'mcp__strata-instructions__' , COMMANDS_PREFIX = 'mcp__strata-commands__' ; 114/** The person's own tool's name as they wrote it (spaces for underscores). */ 115const ownToolName = name => name . replace ( / ^mcp__strata- (?: instructions | commands ) __ / , '' ). replace ( / _ / g , ' ' ); 116/** The three sentences (running, worked, failed) for a tool, and whether this is one the app knows by name. */ 117function verbsFor ( name ) { 118if ( VERBS [ name ]) return { verbs :VERBS [ name ], known :true }; 119if ( name . startsWith ( BROWSER_PREFIX )) return { verbs :BROWSER_VERBS [ name . slice ( BROWSER_PREFIX . length )] ?? BROWSER_GENERIC , known :true }; 120if ( name . startsWith ( INSTRUCTIONS_PREFIX )) return { verbs :[ 'Reading your instructions' , 'Read your instructions' , "Couldn't read your instructions" ], known :true }; 121if ( name . startsWith ( COMMANDS_PREFIX )) return { verbs :[ 'Running your tool' , 'Ran your tool' , 'Your tool failed' ], known :true }; 122return { verbs :GENERIC_VERBS , known :false }; 123} 124 125/** The sentence for a card in this state (the first for a running or waiting card). */ 126export function toolVerb ( name , state ) { 127const v = verbsFor ( name ). verbs ; 128return state === 'error' ?v [ 2 ] :state === 'done' ?v [ 1 ] :v [ 0 ]; 129} 130/** The ToolCall fields the card needs, from one Harness tool call. */ 131export function presentTool ({ callId, name, args, reason= null }) { 132const scope = toolScope ( name ); 133const words = WORDS [ name ]?.( args ); 134const preview = scope === 'shell' && ! words ?args . command ?? '' 135 :scope === 'write' ?args . file_path ?? args . path ?? args . filePath ?? '' 136 :words ?words [ 1 ] ?? '' :name . startsWith ( INSTRUCTIONS_PREFIX ) || name . startsWith ( COMMANDS_PREFIX ) ?ownToolName ( name ) :/ ^mcp__browser__browser_ ( evaluate | run_code ) $ / . test ( name ) ?'' :args . file_path ?? args . path ?? args . pattern ?? args . url ?? args . element ?? args . query ?? args . text ?? args . action ?? ( Object . keys ( args ). length ?JSON . stringify ( args ) :'' ); 137const effect = reason ?? ( words ?words [ 0 ] :scope === 'shell' ?( args . description ?? 'Runs a command in the workspace.' ) 138 :scope === 'write' ?'Changes a file in the workspace.' 139 :scope === 'read' ?'Reads from the workspace.' :'Uses a connected tool.' ); 140return { id :callId , name, args, preview :clip ( preview , 600 ), effect :clip ( effect , 400 ), scope, verb :toolVerb ( name , 'running' ), target :clip ( verbsFor ( name ). known ?preview :name , 300 ), ask :askFor ( name , args , typeof args . description === 'string' ?args . description :null ) }; 141} 142 143/** A tool's failure in plain words, or null when there is nothing better than the original text. */ 144export function plainToolError ( text ) { 145const t = String ( text ?? '' ); 146if ( / non-public ip | enotfound | getaddrinfo | web fetch failed | econnrefused | econnreset | etimedout | fetch failed / i . test ( t )) return 'That web page could not be opened. Check the address and your internet connection.' ; 147if ( / invalid arguments | missing required property | not a declared property / i . test ( t )) return 'The assistant asked this tool in the wrong way. It will usually try again.' ; 148if ( / unknown or no longer available / i . test ( t )) return 'That skill is not available.' ; 149if ( / cannot modify | must (?: first ) ? be read | has not been read | changed since / i . test ( t )) return 'The file could not be changed. It may need to be read again first, or it changed in the meantime.' ; 150if ( / sandbox | access denied | permission denied | eacces | eperm / i . test ( t )) return 'The computer did not allow this.' ; 151if ( / timed out | timeout / i . test ( t )) return 'This took too long and was stopped.' ; 152if ( / does not declare image input | image input / i . test ( t )) return 'Picture reading is off for this model. Open Models and turn on Read pictures for it (load it again if it is a local model), or choose a model that reads pictures.' ; 153if ( / extension | not a supported image | cannot read / i . test ( t )) return 'This file could not be read.' ; 154return null ; 155} 156 157/** A failed tool's result: the plain sentence first, the original text after it (the card's disclosure is the Details). */ 158export function withPlain ( raw ) { 159const plain = plainToolError ( raw ); 160return plain ?` ${ plain } \n\nDetails: ${ raw . replace ( / ^Error:\s */ , '' )} ` :raw ; 161} 162 163/** What a launch that printed nothing proves, and no more. */ 164export const LAUNCHED_TEXT = 'The command finished without an error, so the program was started. Strata cannot confirm that a window or page actually opened.' ; 165 166/** A command whose whole point is to open something: it has no output to show when it worked. */ 167const LAUNCH = / ( ^ | [ \s ;|&( ])( start-process | start | invoke-item | ii | explorer (?: \.exe ) ?| xdg-open | open | notepad (?: \.exe ) ?| code )(? = [ \s ;|&) ] | $ ) / i ; 168 169/** 170* A command that succeeded and printed nothing says so in words (the card used to show "(no output)" under a "Ran" that could not 171* tell the person whether anything happened). Opening a folder or a window is not something a command can prove it did, so the 172* sentence says only what is known. 173*/ 174export function outcomeText ( tool , text , args = {}) { 175if ( tool === 'pwsh' || tool === 'bash' ) { 176// In the read-only modes PowerShell runs in Constrained Language Mode and complains about the Harness's own output-encoding line: 177// noise appended after a command that worked. It says nothing about the command, so it is not shown. 178text = text . replace ( / \r ? \n ? \[stderr\]\r ? \n (?: Cannot create type\. Only core types are supported in this language mode\. [ \s\S ] * ?CannotCreateTypeConstrainedLanguage\s * ) + $ / , '' ); 179if ( ! text . trim ()) text = '(no output)' ; 180} 181// Starting a program or opening a folder prints nothing when it worked, and also when it did not (a browser given a file:// address, a 182// program that closed at once). T9 / #3576: the card used to say "was opened", and the model repeated it ("I previewed it in a browser to 183// confirm it renders"). It says what is known: the command returned without an error. 184if (( tool === 'pwsh' || tool === 'bash' ) && / ^\(no output\)$ / . test ( text . trim ()) && LAUNCH . test ( String ( args ?. command ?? '' ))) return LAUNCHED_TEXT ; 185if (( tool === 'pwsh' || tool === 'bash' ) && / ^\(no output\)$ / . test ( text . trim ())) return 'The command finished without any error. It printed nothing, so there is nothing more to show.' ; 186return text ; 187} 188 189/** Text of a tool-result message, bounded. */ 190export function resultText ( message ) { 191const parts = Array . isArray ( message ?. content ) ?message . content :[]; 192const text = parts . map ( p => ( p ?. type === 'text' ?p . text :p ?. type ?`[ ${ p . type } ]` :'' )). join ( '\n' ). trim (); 193return clip ( text || '(no output)' , 4000 ); 194} 195 196/** 197* Accumulates one turn's frames. Feed it follow items; it returns the frames to send. 198* It owns the per-turn state (tool cards, usage, text emitted) so the I/O layer stays thin. 199*/ 200export class TurnProjector { 201/** 202* `policy` is the session's approval policy for this turn. Under `never` the Harness rejects an ask by itself, so 203* no question ever reaches the person: the card goes straight from running to denied, without a moment where it 204* offers Approve and Deny buttons that would do nothing. 205*/ 206constructor ({ startedAt= Date . now (), policy= 'ask' , window= 0 } = {}) { 207this . startedAt = startedAt ; 208this . window = Number ( window ) || 0 ; // the model's window, for the figures in the line that says the chat was summarised 209this . summarizing = false ; 210this . policy = policy ; 211this . byPolicy = new Set (); // callIds the approval policy rejected without asking 212this . tools = new Map (); // callId -> { card, calledAt } 213this . tokensIn = 0 ; 214this . tokensOut = 0 ; 215this . contextTokens = null ; // the LAST model request's prompt + reply: what the context holds now (the sums above count every request again) 216this . usageSeen = false ; 217this . firstTokenAt = null ; 218this . streams = new Map (); // attemptId -> { first, last, chunks, chars }: the time a model request actually spent producing 219this . lastStats = 0 ; 220this . emittedText = new Map (); // attemptId -> chars sent live 221this . ended = null ; // the turn/end reason, once seen 222this . denied = new Set (); // callIds a human or the policy rejected 223this . asked = new Map (); // approval id -> callId 224this . onStatus = null ; // (update) => void: what the assistant is doing now (status.mjs); set by the bridge 225this . reasoning = new TokenCount (); 226this . composing = new Map (); // callId -> ToolDraft: a tool call the model is still writing (still here at a cut reply = it was lost) 227this . lastOutput = 0 ; // tokens the LAST model request produced 228this . running = []; // callIds of tools that are running, oldest first 229} 230 231 #status( update ) { if ( this . onStatus ) this . onStatus ( update ); } 232 233/** After a tool ends: another tool still running is what is happening, otherwise the model is working out what to do next. */ 234 #afterTool() { 235const id = this . running . at ( - 1 ); 236const card = id ?this . tools . get ( id )?. card :null ; 237if ( card ) this . #status( toolUpdate ( 'tool' , 'tool' , card . name , card . args , {}, { args :{ tool :card . name , verb :card . verb , target :card . target } })); 238else this . #status({ phase :'waiting' , code :'model-working' , text :'Working out the next step…' }); 239} 240 241 #card( callId , patch ) { 242const entry = this . tools . get ( callId ); 243if ( ! entry ) return null ; 244entry . card = { ...entry . card , ...patch }; 245entry . card . verb = toolVerb ( entry . card . name , entry . card . state ); 246return { type :'agent-tool' , tool :entry . card }; 247} 248 249/* The speed shown while a reply streams, and after it: everything the model generated (reasoning and tool calls included) over the time its 250requests spent producing it, not over the whole turn (tool runs and the wait for the prompt are not decoding). One stream per model 251request; tokens are one per streamed chunk, or characters / 4 when a server batches. */ 252 #produced( attemptId , text , out ) { 253const now = Date . now (); 254const s = this . streams . get ( attemptId ) ?? { first :now , last :now , chunks :0 , chars :0 }; 255s . last = now ; s . chunks += 1 ; s . chars += text . length ; 256this . streams . set ( attemptId , s ); 257if ( now - this . lastStats < 400 ) return ; 258const { tokens, seconds} = this . decode (); 259if ( seconds < 0.5 ) return ; 260this . lastStats = now ; 261out . push ({ type :'stats' , tokensOut :tokens , tps :Number (( tokens / seconds ). toFixed ( 1 )), source :'stream' }); 262} 263 264decode () { 265let tokens = 0 , ms = 0 ; 266for ( const s of this . streams . values ()) { tokens += s . chars / Math . max ( 1 , s . chunks ) < 8 ?s . chunks :Math . ceil ( s . chars / 4 ); ms += s . last - s . first ; } 267return { tokens, seconds :ms / 1000 }; 268} 269 270/** Process one `session/follow` item (event or assistant-stream). Returns frames. */ 271consume ( item ) { 272const out = []; 273if ( item . type === 'assistant-stream' ) { 274const f = item . frame ; 275if ( f . type === 'chunk' ) { 276const c = f . chunk ; 277if ( c . type === 'text-delta' && c . text ) { 278this . firstTokenAt ??= Date . now (); 279this . #produced( f . attemptId , c . text , out ); 280this . emittedAny = true ; 281this . #status({ phase :'answering' , code :'answering' , text :'Writing the answer…' }); 282this . emittedText . set ( f . attemptId , ( this . emittedText . get ( f . attemptId ) ?? 0 ) + c . text . length ); 283out . push ({ type :'delta' , text :c . text }); 284} else if ( c . type === 'reasoning-delta' && c . text ) { 285this . firstTokenAt ??= Date . now (); 286this . #produced( f . attemptId , c . text , out ); 287// The count is for the model's current thinking (each model request starts again from zero), not the whole turn. 288if ( this . reasoningAttempt !== f . attemptId ) { this . reasoning = new TokenCount (); this . reasoningAttempt = f . attemptId ; } 289this . reasoning . add ( c . text ); 290this . #status({ phase :'thinking' , code :'thinking' , text :`Thinking… ${ fmtTokens ( this . reasoning . tokens )} tokens` , key :'Thinking… {0} tokens' , values :[ fmtTokens ( this . reasoning . tokens )], tokens :this . reasoning . tokens , args :{ tokens :this . reasoning . tokens } }); 291out . push ({ type :'reasoning' , text :c . text }); 292} else if ( c . type === 'tool-call-delta' && c . id ) { 293// The model is writing a tool call. For a big file this is the long silent part: nothing else arrives until it is finished. 294const call = this . composing . get ( c . id ) ?? new ToolDraft ( c . id , c . name ?? '' ); 295if ( c . name ) call . name = c . name ; 296const piece = String ( c . argumentsDelta ?? '' ); 297// Writing a tool call (a whole file, say) is decoding too: its tokens are in the engine's output count, so its time belongs in the speed. 298this . #produced( f . attemptId , piece , out ); 299call . add ( piece ); 300this . composing . set ( c . id , call ); 301if ( call . name && ! NO_CARD . has ( call . name )) { 302const target = call . target ; 303const args = target ?{ file_path :target , url :target } :{}; 304this . #status( toolUpdate ( 'preparing' , 'preparing-tool' , call . name , args , { bytes :call . bytes }, { args :{ tool :call . name , verb :toolVerb ( call . name , 'running' ), target :target ?? '' , bytes :call . bytes } })); 305// The live data path of a file being written (AGENT-LOST): the name, a growing size and the tail of the text, at most five times a second. 306const now = Date . now (); 307if ( now - call . at >= 200 ) { call . at = now ; out . push ( call . frame ({ scope :toolScope ( call . name ), verb :toolVerb ( call . name , 'running' ) })); } 308} 309} else if ( c . type === 'usage' && c . usage ) { 310this . usageSeen = true ; 311// The Harness counts input, cache reads and cache writes apart (a prompt the server's conversation cache already held is `cacheReadTokens`, 312// not `inputTokens`): the prompt of a request is all three. Counting only `inputTokens` made a long agent chat look nearly empty (0%). 313const prompt = ( Number ( c . usage . inputTokens ) || 0 ) + ( Number ( c . usage . cacheReadTokens ) || 0 ) + ( Number ( c . usage . cacheWriteTokens ) || 0 ); 314this . tokensIn += prompt ; 315this . tokensOut += Number ( c . usage . outputTokens ) || 0 ; 316this . lastOutput = Number ( c . usage . outputTokens ) || 0 ; 317this . contextTokens = prompt + ( Number ( c . usage . outputTokens ) || 0 ); 318out . push ({ type :'context' , contextTokens :this . contextTokens , contextMax :this . window || undefined }); 319} 320} 321return out ; 322} 323if ( item . type !== 'event' ) return out ; 324const e = item . event ; 325const d = e . data ?? {}; 326switch ( e . type ) { 327case 'assistant/message' :{ 328// Reconcile a text the live frames did not fully carry (a socket gap), never duplicating it. 329const live = [ ...this . emittedText . values ()]. pop () ?? 0 ; 330const text = ( d . message ?. content ?? []). filter ( p => p . type === 'text' ). map ( p => p . text ). join ( '' ); 331if ( text . length > live && live > 0 ) out . push ({ type :'delta' , text :text . slice ( live ) }); 332this . emittedText . clear (); 333break ; 334} 335case 'tool/call' :{ 336if ( NO_CARD . has ( d . name )) break ; 337const args = parseArguments ( d . arguments ); 338const card = { ...presentTool ({ callId :d . callId , name :d . name , args}), state :'running' }; 339this . tools . set ( d . callId , { card, calledAt :e . time }); 340const draft = this . composing . get ( d . callId ); 341this . composing . delete ( d . callId ); 342if ( draft && draft . bytes > 0 && ! NO_CARD . has ( d . name )) out . push ( draft . frame ({ done :true })); 343this . running . push ( d . callId ); 344this . #status( toolUpdate ( 'tool' , 'tool' , d . name , args , {}, { args :{ tool :d . name , verb :card . verb , target :card . target } })); 345out . push ({ type :'agent-tool' , tool :card }); 346break ; 347} 348case 'approval/asked' :{ 349if ( ! d . callId ) break ; 350this . asked . set ( d . id , d . callId ); 351if ( this . policy === 'never' ) break ; 352const entry = this . tools . get ( d . callId ); 353this . #status({ phase :'approval' , code :'waiting-approval' , text :'Waiting for your answer…' , args :{ tool :entry ?. card . name ?? '' } }); 354const patch = { state :'proposed' , effect :clip ( d . reason ?? entry ?. card . effect ?? 'Needs your approval.' , 400 ) }; 355const frame = this . #card( d . callId , patch ); 356if ( frame ) out . push ( frame ); 357break ; 358} 359case 'approval/decided' :{ 360const callId = this . asked . get ( d . id ); 361if ( callId && this . policy === 'never' && d . outcome !== 'allowed-once' ) { 362this . byPolicy . add ( callId ); this . denied . add ( callId ); 363const frame = this . #card( callId , { state :'denied' , result :NOT_IN_MODE }); 364if ( frame ) out . push ( frame ); 365break ; 366} 367this . #afterTool(); 368const frame = callId ?this . decide ( callId , d . outcome ) :null ; 369if ( frame ) out . push ( frame ); 370break ; 371} 372case 'tool/result' :{ 373const callId = d . message ?. toolCallId ; 374const entry = this . tools . get ( callId ); 375if ( ! entry ) break ; 376this . running = this . running . filter ( id => id !== callId ); 377this . #afterTool(); 378const isError = d . message ?. isError === true ; 379const denied = this . denied . has ( callId ); 380const frame = this . #card( callId , { 381state :denied ?'denied' :isError ?'error' :'done' , 382// A card the person (or the mode) refused keeps its plain sentence; the model's own error text ("the user rejected ...") is not for them. 383result :this . byPolicy . has ( callId ) ?NOT_IN_MODE :denied ?( entry . card . result ?? 'Denied. Nothing ran.' ) :isError ?withPlain ( resultText ( d . message )) :outcomeText ( entry . card . name , resultText ( d . message ), entry . card . args ), 384durationMs :Math . max ( 0 , ( e . time ?? 0 ) - entry . calledAt ), 385}); 386if ( frame ) out . push ( frame ); 387break ; 388} 389case 'compaction/start' : 390// The Harness is summarising the older messages to make room: say so while it does, and again (once) when it is done. 391this . summarizing = true ; 392this . #status({ phase :'compacting' , code :'compacting' , text :FIT_TEXT . summarizing , key :FIT_TEXT . summarizing , values :[] }); 393break ; 394case 'compaction/end' : 395if ( ! this . summarizing ) break ; 396this . summarizing = false ; 397this . #afterTool(); 398if ( ! d . error ) { 399const before = this . window > 0 && this . contextTokens ?Math . min ( 100 , Math . round ( 100 * this . contextTokens / this . window )) :null ; 400const text = before === null ?FIT_TEXT . summarizedShort :FIT_TEXT . summarizedWas ; 401const values = before === null ?[] :[ before ]; 402out . push ({ type :'delta' , own :true , text :'\n\n' + fill ( text , values ), key :text , values, noteReason :'compacted' }); 403} 404break ; 405case 'turn/start' : 406// The parent woke up again (a helper finished and reported back): the message goes on, as a new paragraph. 407this . ended = null ; 408if ( this . emittedAny ) out . push ({ type :'delta' , text :'\n\n' }); 409break ; 410case 'turn/end' : 411this . ended = d . reason ?? { kind :'completed' }; 412break ; 413default : 414break ; 415} 416return out ; 417} 418 419/** An approval was decided. `outcome` is the Harness vocabulary. */ 420decide ( callId , outcome ) { 421if ( ! this . tools . has ( callId )) return null ; 422// `approved` is what lets the card say "Approved" (the user answered) rather than "Ran" (it never asked). 423if ( outcome === 'allowed-once' ) return this . #card( callId , { state :'running' , approved :true }); 424this . denied . add ( callId ); 425return this . #card( callId , { state :'denied' , result :outcome === 'rejected' ?'Denied. Nothing ran.' :outcome === 'cancelled' ?'Cancelled. Nothing ran.' :'No one could answer this request, so nothing ran.' }); 426} 427 428/** A reply the model could not finish (the turn ended on the length limit): what it was writing, so nothing is lost without a word. */ 429cut () { 430return { tokens :this . lastOutput , calls :cutCalls ( this . composing . values ()) }; 431} 432 433/** The agent was asked to carry on: the calls it lost are not pending any more. */ 434clearCut () { const frames = this . #dropDrafts(); this . ended = null ; return frames ; } 435 436/** Frames that take the writing cards of calls that will never be whole off the page (the reply was cut, or the turn ended). */ 437 #dropDrafts() { 438const frames = [ ...this . composing . values ()]. filter ( d => d . bytes > 0 && ! NO_CARD . has ( d . name )). map ( d => d . frame ({ done :true , lost :true })); 439this . composing . clear (); 440return frames ; 441} 442 443/** The terminal frames for a finished turn. */ 444finish ( options = {}) { 445const cutInfo = this . ended ?. kind === 'max-tokens' ?this . cut () :null ; 446const dropped = this . #dropDrafts(); 447return [ ...dropped , ...this . #finished( options , cutInfo )]; 448} 449 450 #finished({ model, contextMax, engine= null } = {}, cutInfo = null ) { 451const reason = this . ended ?? { kind :'interrupted' }; 452const durationMs = Date . now () - this . startedAt ; 453const usage = this . usageSeen 454 ?{ tokensIn :this . tokensIn , tokensOut :this . tokensOut , usageSource :'reported' } 455 :{ tokensIn :null , tokensOut :null , usageSource :'unavailable' }; 456const decoded = this . decode (); 457const generated = this . usageSeen && this . tokensOut > 0 ?this . tokensOut :decoded . tokens ; 458// Answer speed, one definition everywhere: all the tokens the model produced over its decode time. The engine's own figures (the ones the 459// Monitor shows) when the bridge could read them; otherwise the stream's own span. A very short reply has almost no span, so its decode time 460// is then the time from its first chunk to the end of the turn (only when no tool ran, so no tool time is in it): the number is still shown. 461let tps = null ; 462if ( engine ?. tps > 0 ) tps = engine . tps ; 463else if ( generated > 0 && decoded . seconds >= 0.3 ) tps = Number (( generated / decoded . seconds ). toFixed ( 1 )); 464else if ( generated > 0 && this . tools . size === 0 && this . firstTokenAt && Date . now () - this . firstTokenAt >= 50 ) tps = Number (( generated / (( Date . now () - this . firstTokenAt ) / 1000 )). toFixed ( 1 )); 465const promptTps = engine ?. promptTps > 0 ?engine . promptTps :null ; 466const base = { durationMs, ttftMs :this . firstTokenAt ?this . firstTokenAt - this . startedAt :null , model, contextMax, tps, ...( promptTps ?{ promptTps} :{}), contextTokens :this . contextTokens }; 467switch ( reason . kind ) { 468case 'completed' : 469return [{ type :'done' , ...base , ...usage , finishReason :'stop' }]; 470case 'max-tokens' : 471return [{ type :'done' , ...base , ...usage , finishReason :'length' , cut :cutInfo }]; 472case 'aborted' : 473return [{ type :'done' , ...base , ...usage , finishReason :'aborted' , cancelled :true }]; 474case 'error' : 475return [{ type :'error' , message :friendlyFailure ( reason . error ), code :isContextFailure ( reason . error ) ?'CONTEXT_WINDOW_EXCEEDED' :reason . error ?. code ?? 'UNKNOWN' , ...( isContextFailure ( reason . error ) ?{ key :FIT_TEXT . full , details :String ( reason . error ?. message ?? '' ) } :{}) }]; 476case 'blocked' : 477return [{ type :'error' , message :'The agent stopped because this turn was blocked by policy.' , code :'BLOCKED' }]; 478default : 479return [{ type :'error' , message :'The agent turn was interrupted before it finished.' , code :'INTERRUPTED' }]; 480} 481} 482} 483 484/** Whether a failure is the model server saying the conversation does not fit its window (its code, or the engine's own words). */ 485export function isContextFailure ( failure ) { 486return isContextOverflow ( failure ) || / context window | too long for | exceeds the context / i . test ( String ( failure ?. message ?? '' )); 487} 488 489/** A model-route failure in words a user can act on. */ 490export function friendlyFailure ( failure ) { 491const message = String ( failure ?. message ?? 'The model request failed.' ); 492if ( isContextFailure ( failure )) return FIT_TEXT . full ; 493if ( / ECONNREFUSED | fetch failed | connect / i . test ( message )) return `The model is not reachable. ${ clip ( message , 200 )} ` ; 494if ( / 401 | 403 | credential | api key / i . test ( message )) return 'The model rejected the credentials. Check the connection in Settings.' ; 495return clip ( message , 400 ); 496}