okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
a16109803
main
1/** 2* Helper agents (the Harness's subagents) as the rows the chat already has. 3* 4* A helper is a child session of the chat's Harness session. This module is the pure part: it folds one child's 5* `session/follow` items into 6* - an `agent` frame (the shape `apps/host/src/lib/agents.ts updateAgent` merges into the chat's existing rows: 7* id, name, description, status, durationMs, tokens, updatedAt), and 8* - tool cards, but only for a helper's request that needs the person (an approval). Everything else a helper does 9* stays in its row; the transcript is not filled with the work of four helpers at once. 10* 11* A helper's approval card is the same card a direct request gets (state `proposed`, answered with the same 12* Approve/Deny route). Its id is `<childSessionId>:<callId>`, which is also the key the bridge keeps the pending 13* question under, so the answer finds the helper that asked and no other chat can answer it. 14* 15* Wording is for the person reading the row, not for a log: no session ids, no tool internals. 16*/ 17import { friendlyFailure , parseArguments , presentTool , resultText , toolScope } from './events.mjs' ; 18 19const clip = ( value , max ) => { 20const text = String ( value ?? '' ). replace ( / \s +/ g , ' ' ). trim (); 21return text . length > max ?` ${ text . slice ( 0 , max - 1 )} …` :text ; 22}; 23 24/** What a helper is doing, in words (shown as the row's description while it works). */ 25export function activityOf ( name , args = {}) { 26const scope = toolScope ( name ); 27if ( scope === 'shell' ) return 'Running a command' ; 28if ( scope === 'write' ) return 'Changing files' ; 29if ( name === 'web_fetch' || name === 'web_search' ) return 'Looking something up online' ; 30if ( name === 'read' || name === 'glob' || name === 'grep' || name === 'read_image' ) return 'Reading files' ; 31if ( name === 'subagent' || name === 'subagent_fork' ) return 'Handing work to another helper' ; 32if ( scope === 'read' ) return 'Looking through the project' ; 33return 'Using a tool' ; 34} 35 36export class ChildProjector { 37/** 38* @param { {id:string, name?:string, task?:string, now?:()=>number} } options 39*/ 40constructor ({ id, name= 'Helper' , task= '' , now= () => Date . now () }) { 41this . id = id ; 42this . name = clip ( name , 60 ) || 'Helper' ; 43this . task = clip ( task , 140 ); 44this . now = now ; 45this . startedAt = now (); 46this . status = 'queued' ; 47this . tokens = 0 ; 48this . sawUsage = false ; 49this . activity = null ; 50this . closing = '' ; // the helper's last words, shown once it finished 51this . failure = null ; 52this . endedAt = null ; 53this . tools = new Map (); // callId -> { card, calledAt, asked } 54this . asked = new Map (); // approval id -> callId 55this . lastEmit = 0 ; 56} 57 58/** The row as the UI merges it. */ 59agent () { 60const at = this . now (); 61const done = this . status === 'completed' || this . status === 'failed' || this . status === 'cancelled' ; 62let description = this . task ; 63if ( this . status === 'queued' ) description = this . task ?`Waiting for its turn. ${ this . task } ` :'Waiting for its turn.' ; 64if ( this . status === 'working' && this . activity ) description = this . activity ; 65if ( this . status === 'completed' ) description = this . closing ?clip ( this . closing , 140 ) :'Finished.' ; 66if ( this . status === 'failed' ) description = this . failure ?? 'Stopped because something went wrong.' ; 67if ( this . status === 'cancelled' ) description = 'Stopped.' ; 68return { 69id :this . id , name :this . name , description, status :this . status , 70durationMs :Math . max ( 0 , ( done ?this . endedAt :at ) - this . startedAt ), tokens :this . tokens , updatedAt :at , 71}; 72} 73 74 #cardId( callId ) { return ` ${ this . id } : ${ callId } ` ; } 75 76 #card( callId , patch ) { 77const entry = this . tools . get ( callId ); 78if ( ! entry ) return null ; 79entry . card = { ...entry . card , ...patch }; 80return { type :'agent-tool' , tool :entry . card }; 81} 82 83/** 84* Fold one follow item. Returns `{ frames, row }`: card frames to send now, and whether the row changed 85* (the caller decides when to send it, so a stream of usage chunks does not flood the page). 86*/ 87consume ( item ) { 88const frames = []; 89let row = false ; 90const set = ( status ) => { if ( this . status !== status ) { this . status = status ; row = true ; } }; 91 92if ( item . type === 'assistant-stream' ) { 93const f = item . frame ; 94if ( f . type === 'chunk' && f . chunk ?. type === 'usage' && f . chunk . usage ) { 95this . sawUsage = true ; 96this . tokens += ( Number ( f . chunk . usage . inputTokens ) || 0 ) + ( Number ( f . chunk . usage . outputTokens ) || 0 ); 97row = true ; 98} else if ( f . type === 'chunk' && ( f . chunk ?. type === 'text-delta' || f . chunk ?. type === 'reasoning-delta' )) { 99if ( this . status === 'queued' ) set ( 'working' ); 100} 101return { frames, row}; 102} 103if ( item . type !== 'event' ) return { frames, row}; 104const e = item . event ; 105const d = e . data ?? {}; 106switch ( e . type ) { 107case 'step/start' : 108case 'turn/start' : 109// A request was sent. Whether the engine has room for it yet is told by its first word: until then the helper is waiting for its turn. 110// A helper that had finished and got a new message starts over as waiting. 111if ( this . finished ) { this . endedAt = null ; this . failure = null ; set ( 'queued' ); } 112break ; 113case 'assistant/message' :{ 114const text = ( d . message ?. content ?? []). filter ( p => p . type === 'text' ). map ( p => p . text ). join ( '' ). trim (); 115if ( text ) this . closing = text ; 116break ; 117} 118case 'tool/call' :{ 119const args = parseArguments ( d . arguments ); 120const card = { ...presentTool ({ callId :this . #cardId( d . callId ), name :d . name , args}), state :'running' , agentName :this . name }; 121this . tools . set ( d . callId , { card, calledAt :e . time , asked :false }); 122this . activity = activityOf ( d . name , args ); 123set ( 'working' ); 124row = true ; 125break ; 126} 127case 'approval/asked' :{ 128if ( ! d . callId || ! this . tools . has ( d . callId )) break ; 129this . asked . set ( d . id , d . callId ); 130const entry = this . tools . get ( d . callId ); 131entry . asked = true ; 132const frame = this . #card( d . callId , { state :'proposed' , effect :clip ( ` ${ this . name } asks: ${ d . reason ?? 'to use a tool' } ` , 400 ) }); 133if ( frame ) frames . push ( frame ); 134break ; 135} 136case 'approval/decided' :{ 137const callId = this . asked . get ( d . id ); 138const entry = callId ?this . tools . get ( callId ) :null ; 139if ( ! entry ) break ; 140const frame = d . outcome === 'allowed-once' 141 ?this . #card( callId , { state :'running' , approved :true }) 142 :this . #card( callId , { state :'denied' , result :d . outcome === 'rejected' ?'Denied. Nothing ran.' :'Cancelled. Nothing ran.' }); 143if ( frame ) frames . push ( frame ); 144break ; 145} 146case 'tool/result' :{ 147const callId = d . message ?. toolCallId ; 148const entry = this . tools . get ( callId ); 149if ( ! entry ) break ; 150if ( entry . asked ) { 151const wasDenied = entry . card . state === 'denied' ; 152const frame = this . #card( callId , { 153state :wasDenied ?'denied' :d . message ?. isError === true ?'error' :'done' , 154result :wasDenied ?entry . card . result :resultText ( d . message ), 155durationMs :Math . max ( 0 , ( e . time ?? 0 ) - entry . calledAt ), 156}); 157if ( frame ) frames . push ( frame ); 158} 159this . activity = null ; 160row = true ; 161break ; 162} 163case 'turn/end' :{ 164const reason = d . reason ?? { kind :'completed' }; 165this . endedAt = this . now (); 166if ( reason . kind === 'aborted' ) set ( 'cancelled' ); 167else if ( reason . kind === 'error' ) { this . failure = clip ( friendlyFailure ( reason . error ), 140 ); set ( 'failed' ); } 168else if ( reason . kind === 'blocked' || reason . kind === 'interrupted' ) { this . failure = 'Stopped before it finished.' ; set ( 'failed' ); } 169else set ( 'completed' ); 170// A request still waiting when its helper ended can no longer be answered. 171for ( const [ callId , entry ] of this . tools ) { 172if ( entry . asked && entry . card . state === 'proposed' ) { 173const frame = this . #card( callId , { state :'denied' , result :'Cancelled. Nothing ran.' }); 174if ( frame ) frames . push ( frame ); 175} 176} 177row = true ; 178break ; 179} 180default : 181break ; 182} 183return { frames, row}; 184} 185 186get finished () { return this . status === 'completed' || this . status === 'failed' || this . status === 'cancelled' ; } 187}