okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
85269ca15
main
1/** 2* The agent bridge: Strata chats as Harness sessions. 3* 4* What it owns 5* - the pinned Harness process (one, lazily started, restarted only when a route it needs changed); 6* - the stable Strata-chat -> Harness-session map, persisted next to the host's other state; 7* - one `session/follow` stream per live turn, projected into the NDJSON frames the chat UI renders; 8* - approvals: the Harness `approval/request` waterfall in, the user's Approve/Deny back out; 9* - Stop: `session/cancel` for exactly one session, resolved only once the turn has really ended. 10* 11* What it deliberately does not do 12* - it never falls back to another model: a chat picks a route (local instance or saved API 13* connection) and a missing route is a typed error; 14* - it never implements Stop by killing the Harness (that would cancel every other chat); 15* - it never holds a secret outside the environment of the agent process it starts. 16*/ 17import { existsSync , mkdirSync , readFileSync , renameSync , writeFileSync } from 'node:fs' ; 18import { join , resolve } from 'node:path' ; 19import { homedir , tmpdir } from 'node:os' ; 20import { fileURLToPath } from 'node:url' ; 21import { randomUUID } from 'node:crypto' ; 22import { GatewayClient } from './gateway-client.mjs' ; 23import { HarnessProcess , resolveHarness , redact , stopStaleAgent } from './harness-runtime.mjs' ; 24import { StatusReporter } from './status.mjs' ; 25import { buildProfile , routeFor , MODE_PRESETS , modeOf , effortOf , localOutputBudget , compactionHeadroom } from './profile.mjs' ; 26import { TurnProjector , parseArguments as parseArgs } from './events.mjs' ; 27import { ChildProjector } from './children.mjs' ; 28import { nearestBudget } from './llm-shape.mjs' ; 29import { DeliverableTracker , ActivityGroups , FolderClaims } from './deliverables.mjs' ; 30import { SkillsUsed , skillInfoFrom } from './skills-used.mjs' ; 31import { turnEngineSpeed } from './engine-speed.mjs' ; 32import { TurnGuard , guardNote , GUARD_NOTES } from './turn-guard.mjs' ; 33import { cutNotice , cutNudge } from './reply-cut.mjs' ; 34 35/** How often one turn asks the agent to carry on after a reply the length limit cut (each time in smaller pieces). */ 36export const MAX_CUT_RETRIES = 2 ; 37import { buildAnswer , parseQuestions } from './user-questions.mjs' ; 38import { BASE_TOKENS , COUNT_ABOVE_CHARS , FIT_TEXT , countTokens , decideFit , fill , grouped } from './context-fit.mjs' ; 39import { PlanStore , planPrompt , parsePlan , parsePoints , stepObjective , stepLine , firstSentence , stepSummary , planAsPrompt , editedSteps , planView , researchPrompt , researchWritePrompt , RESEARCH_NUDGE , parseSources } from './plan.mjs' ; 40 41/** 42* A failure the person can read. `message` is a plain sentence with the next step; `details` keeps the technical 43* text for the Details disclosure (experts), already free of secrets. 44*/ 45export class AgentUnavailable extends Error { 46constructor ( message , code = 'agent-unavailable' , details = null ) { super ( message ); this . name = 'AgentUnavailable' ; this . code = code ; this . details = details ; } 47} 48 49/** The plain sentence for a raw agent failure text, whatever produced it. */ 50export function plainAgentFailure ( raw ) { 51const text = String ( raw ?? '' ); 52if ( / did not print its address | exited during start | could not start | ECONNREFUSED. * 127\.0\.0\.1 | refused the launch token | socket / i . test ( text )) return 'The coding assistant could not start. Try again. If it keeps happening, close and reopen Strata.' ; 53if ( / process stopped | lost the session stream | stream did not open | session stream / i . test ( text )) return 'The coding assistant stopped unexpectedly, so this answer is incomplete. Send your message again.' ; 54if ( / did not accept the message / i . test ( text )) return 'The coding assistant did not take this message. Send it again in a moment.' ; 55return text ; 56} 57 58/** 59* A failure thrown while a turn starts, as `{ message, details, code }` for the chat's error card. The agent's own errors read like 60* `session/create: tool-bash (...): waiting for shell ...` (a plugin chain that never started): never shown raw. The plain sentence 61* goes in `message`; the technical text goes in `details`, which the app shows only behind Details. 62*/ 63export function plainTurnFailure ( err ) { 64const raw = String ( err ?. message ?? err ?? '' ); 65const details = typeof err ?. details === 'string' && err . details ?err . details :raw ; 66if ( err instanceof AgentUnavailable ) return { message :err . message , details, code :err . code ?? 'AGENT_ERROR' }; 67if ( err ?. code === 'agent-preset/invalid' || / waiting for ( shell | subprocess | ptcRuntime | workflowEngine | sandbox ) | failed to import | did not activate / i . test ( raw )) { 68return { message :'The coding assistant is missing a part it needs, so it cannot work on files yet. Close and reopen Strata. If it keeps happening, reinstall Strata. Chatting without tools still works.' , details, code :'AGENT_INCOMPLETE' }; 69} 70if ( / ^ [ a - z ][ a - z- ] * \/ [ a - z ][ a - z- ] * : / i . test ( raw ) || / ^ ( gateway | rpc ) / i . test ( raw )) { 71return { message :'The coding assistant could not start this message. Try again. If it keeps happening, close and reopen Strata.' , details, code :err ?. code ?? 'AGENT_ERROR' }; 72} 73return { message :plainAgentFailure ( raw ), details, code :err ?. code ?? 'AGENT_ERROR' }; 74} 75 76/** The Harness's plugins start one after another: until they are all up, session/create answers "<plugin>: waiting for <service>". */ 77const STARTING_UP = / waiting for ( shell | subprocess | ptcRuntime | workflowEngine | sandbox ) / i ; 78 79/** 80* Create a Harness session, waiting for its plugins to finish starting. Right after the app opens (or the Harness restarts) the first 81* message can arrive before they are up: that is retried every `retryMs` for up to `readyMs` (`onWait` tells the page "Starting the assistant…") 82* instead of failing the first chat. Any other error is thrown at once; a start that never finishes is a plain AGENT_NOT_READY error 83* with the Harness's text kept for Details. Returns null when `cancelled()` turns true while waiting. 84*/ 85export async function createSessionWhenReady ( create , { readyMs= 60_000 , retryMs= 1_500 , onWait= () => {}, cancelled= () => false , now= Date . now } = {}) { 86const until = now () + readyMs ; 87for (;;) { 88try { return await create (); } catch ( e ) { 89const text = String ( e ?. message ?? e ?? '' ); 90if ( ! STARTING_UP . test ( text )) throw e ; 91if ( now () >= until ) throw new AgentUnavailable ( 'The assistant could not start. Try again in a moment.' , 'AGENT_NOT_READY' , text ); 92onWait (); 93await new Promise ( r => setTimeout ( r , retryMs )); 94if ( cancelled ()) return null ; 95} 96} 97} 98 99/** Attached pictures (data addresses) as the Harness's image prompt parts. */ 100export function imageParts ( images ) { 101return ( Array . isArray ( images ) ?images :[]). map ( i => { 102const m = / ^data: ( image\/ (?: png | jpeg | webp )) ;base64, ( . + ) $ / . exec ( String ( i ?. url ?? '' )); 103return m ?{ type :'image' , mediaType :m [ 1 ], data :m [ 2 ], name :String ( i . name ?? 'Picture' ). slice ( 0 , 120 ) } :null ; 104}). filter ( Boolean ); 105} 106 107/** A timer that never keeps the process alive by itself. */ 108const after = ( ms , fn ) => { const t = setTimeout ( fn , ms ); t . unref ?.(); return t ; }; 109/** The app's own host folder: never a place an answer's files can be (this file lives in <host>/server/agent). */ 110const HOST_DIR = fileURLToPath ( new URL ( '../..' , import . meta. url )); 111 112const deferred = () => { let resolve ; const promise = new Promise ( r => { resolve = r ; }); return { promise, resolve}; }; 113 114/** 115* @param { object } options 116* @param { string } options.dataDir the host's data directory (agent state lives in `<dataDir>/agent`) 117* @param { string|null } [options.componentsDir] where installed components live 118* @param { () => Array } options.localInstances ready local instances (see profile.mjs) 119* @param { () => Array } options.connections saved API connections WITH their keys (host-internal) 120* @param { () => (string|null) } [options.defaultLocalId] the local instance the chat runs on: its tool servers are the agent's (T5) 121* @param { NodeJS.ProcessEnv } [options.env] 122* @param { string } [options.nodePath] the Node runtime that runs the Harness 123* @param { (line:string)=>void } [options.log] 124*/ 125export function createAgentBridge ({ dataDir, componentsDir= null , bundledDir= null , gate= true , localInstances, connections, tools= () => undefined , defaultLocalId= () => null , skillsDir= () => null , onGoal= () => {}, onPlan= () => {}, onQueue= () => {}, proxyBase= null , searchMock= null , expertSampling= () => null , engineProgress= () => null , engineGraceMs= 30 * 60_000 , stallMs= 4 * 60_000 , stallToolMs= 20 * 60_000 , env= process . env , nodePath= process . execPath , log= () => {}, startTimeoutMs= 120_000 , sessionReadyMs= 60_000 , sessionRetryMs= 1_500 }) { 126const root = join ( dataDir , 'agent' ); 127const home = join ( root , 'home' ); 128const sessionsFile = join ( root , 'sessions.json' ); 129mkdirSync ( root , { recursive :true }); 130/** Which chat's file tools wrote which file, for chats that share a folder (#5008). */ 131const folderClaims = new FolderClaims (); 132 133/** 134* Where the turn's file tracker must never look (deliverables.mjs): the app, the engine and its components, Strata's own data, AppData 135* and temp. `forbid` ones also switch tracking off when the chat's folder is one of them or inside one. 136*/ 137function trackerFolders () { 138const user = env . USERPROFILE ?? env . HOME ?? homedir (); 139const forbid = [ HOST_DIR , componentsDir , bundledDir ]. filter ( Boolean ); 140const exclude = [ dataDir , tmpdir (), env . LOCALAPPDATA , env . APPDATA , env . ProgramData , env . ProgramFiles , env [ 'ProgramFiles(x86)' ], env . TEMP , env . TMP , 141join ( user , 'AppData' ), join ( user , '.cache' ), join ( user , '.config' ), join ( user , '.local' ), join ( user , 'Library' )]. filter ( Boolean ); 142return { forbid, exclude}; 143} 144 145/** chatId -> { sessionId, cwd, createdAt } */ 146let sessionMap = {}; 147if ( existsSync ( sessionsFile )) { 148try { sessionMap = JSON . parse ( readFileSync ( sessionsFile , 'utf8' )) ?? {}; } catch { sessionMap = {}; } 149} 150const persist = () => { 151const temp = ` ${ sessionsFile } . ${ randomUUID ()} .tmp` ; 152writeFileSync ( temp , JSON . stringify ( sessionMap , null , 2 )); 153renameSync ( temp , sessionsFile ); 154}; 155 156/** @type { {hp:HarnessProcess, gw:GatewayClient, profile:object, clientId:string|null, generation:number, events:object}|null } */ 157let rt = null ; 158let generation = 0 ; 159let lastError = null ; 160let starting = null ; 161const chats = new Map (); // chatId -> { turn, route, routeGeneration } 162const plans = new PlanStore ( join ( root , 'plans.json' )); 163/** chatId -> messages the person typed while a goal ran: [{ id, text, at, deliverAt }]; delivered between steps or when the goal ends */ 164const queues = new Map (); 165const queueView = chatId => ( queues . get ( chatId ) ?? []). map (({ id, text, at, deliverAt}) => ({ id, text, at, deliverAt})); 166const pending = new Map (); // `${sessionId}:${callId}` -> { eventId, sessionId, callId, at } 167const questions = new Map (); // `${sessionId}:${callId}` -> the agent's own question waiting for the person: { eventId, sessionId, callId, items, at, clientId } (#4244) 168const chatOfSession = sessionId => Object . keys ( sessionMap ). find ( id => sessionMap [ id ]?. sessionId === sessionId ) ?? null ; 169const idleWaiters = new Set (); 170 171const chat = id => { let c = chats . get ( id ); if ( ! c ) { c = { id, turn :null , route :null , routeGeneration :- 1 }; chats . set ( id , c ); } return c ; }; 172const activeTurns = () => [ ...chats . values ()]. filter ( c => c . turn ). length ; 173const notifyIdle = () => { if ( activeTurns () === 0 ) { for ( const w of idleWaiters ) w (); idleWaiters . clear (); } }; 174const waitIdle = ( signal , ms ) => new Promise (( resolve , reject ) => { 175if ( activeTurns () === 0 ) return resolve (); 176const timer = setTimeout (() => { idleWaiters . delete ( done ); reject ( new AgentUnavailable ( 'Another chat is still working and the list of models changed. Try again when it finishes.' , 'agent-busy' )); }, ms ); 177const done = () => { clearTimeout ( timer ); resolve (); }; 178idleWaiters . add ( done ); 179signal ?. addEventListener ( 'abort' , () => { clearTimeout ( timer ); idleWaiters . delete ( done ); reject ( signal . reason ?? new Error ( 'aborted' )); }, { once :true }); 180}); 181 182/** The agent's profile now, plus where its shaped routes really lead (read by the forwarding endpoint). */ 183let shapeTargets = {}; 184function buildProfileNow () { 185const profile = buildProfile ({ local :localInstances (), connections :connections (), gate, tools :tools (), skillsDir :skillsDir (), proxyBase, searchMock, defaultLocalId :defaultLocalId () }); 186shapeTargets = profile . shapeTargets ?? {}; 187return profile ; 188} 189const llmTarget = key => shapeTargets [ key ] ?? null ; 190 191function harnessInfo () { return resolveHarness ({ env, componentsDir, bundledDir}); } 192/** Where the agent component is (the browser tool server lives inside it), or null. */ 193const harnessDir = () => { const h = harnessInfo (); return h . ok ?h . dir :null ; }; 194 195/** The capability state the app shows. Never carries a token or a key. */ 196function status () { 197const h = harnessInfo (); 198if ( ! h . ok ) return { state :'unavailable' , reason :'The coding assistant isn’t installed on this computer yet. Chat works without it.' , detail :h . reason , code :'component-missing' }; 199const profile = buildProfileNow (); 200return { 201state :rt ?. hp . running ?'ready' :starting ?'starting' :lastError ?'error' :'idle' , 202reason :lastError ?plainAgentFailure ( lastError ) === lastError ?'The coding assistant could not start. Try again.' :plainAgentFailure ( lastError ) :null , 203detail :lastError ?? null , 204harness :{ version :h . version }, 205runtime :rt ?. hp . running ?{ pid :rt . hp . pid , generation :rt . generation } :null , 206routes :profile . routes . map (({ route, kind, modelId, name, contextWindow}) => ({ route, kind, modelId, name, contextWindow})), 207// tool servers that could not be wired (a name the rule does not allow, no program or address): the chat says so 208skippedServers :profile . mcpSkipped ?? [], 209activeTurns :activeTurns (), 210pendingApprovals :pending . size , 211}; 212} 213 214async function startRuntime ( profile ) { 215const h = harnessInfo (); 216if ( ! h . ok ) throw new AgentUnavailable ( 'The coding assistant isn’t installed on this computer yet. Chat works without it.' , 'component-missing' , h . reason ); 217mkdirSync ( home , { recursive :true }); 218const stale = stopStaleAgent ( join ( root , 'harness.pid' )); 219if ( stale ) log ( `agent · stopped a leftover Harness process (pid ${ stale } ) from an earlier run` ); 220const patchFile = join ( root , `profile- ${ profile . signature } .patch.yml` ); 221writeFileSync ( patchFile , profile . patch ); 222const workdir = join ( root , 'run' ); 223const hp = new HarnessProcess ({ 224harness :h , home, patchFile, cwd :workdir , env :profile . env , nodePath, logFile :join ( root , 'harness.log' ), pidFile :join ( root , 'harness.pid' ), 225onExit :exit => { 226log ( `agent · the Harness process exited (code ${ exit . code } )` ); 227if ( rt ?. hp === hp ) { lastError = 'The agent process stopped.' ; rt = null ; } 228for ( const c of chats . values ()) c . turn ?. abortFromRuntime ( 'The agent process stopped before this turn finished.' ); 229}, 230}); 231const info = await hp . start ({ timeoutMs :startTimeoutMs }); 232const gw = new GatewayClient ({ baseUrl :info . baseUrl , token :info . token }); 233await gw . connect (); 234const next = { hp, gw, profile, clientId :null , generation :++ generation , events :null }; 235next . events = gw . openStream ( '$events' , {}, { 236onItem :value => onHostEvent ( next , value ), 237onError :e => log ( `agent · event stream: ${ redact ( e . message , Object . values ( profile . env ))} ` ), 238}); 239rt = next ; 240lastError = null ; 241log ( `agent · Harness ${ h . version ?? '' } ready (pid ${ hp . pid } , ${ profile . routes . length } route(s))` ); 242return next ; 243} 244 245/** The local engine's own speed for this turn's requests (null when it cannot be read: the stream's estimate stays). */ 246async function engineSpeedOf ( route , projector ) { 247const inst = localInstances (). find ( i => i . id === route . instanceId ); 248if ( ! inst ) return null ; 249return turnEngineSpeed ({ baseUrl :inst . baseUrl , key :inst . key , since :projector . startedAt , attempts :projector . streams . size , timeoutMs :800 }); 250} 251 252/** Make sure a runtime exists that knows the route this turn needs. */ 253async function ensureRuntime ( choice , signal ) { 254for (;;) { 255if ( starting ) { await starting . catch (() => {}); continue ; } 256const profile = buildProfileNow (); 257const route = routeFor ( profile , choice ); 258if ( ! route ) { 259throw new AgentUnavailable ( choice ?. connectionId 260 ?'This API model is no longer available. Choose another model in the chat picker.' 261 :'No local model is ready for the agent. Load a model in Models, or choose an API model.' , 'model-unavailable' ); 262} 263const known = rt ?. hp . running && rt . profile . toolsSignature === profile . toolsSignature && rt . profile . routes . some ( r => r . route === route . route && r . modelId === route . modelId && r . fp === route . fp ); 264if ( known ) return { rt, route}; 265starting = ( async () => { 266if ( rt ?. hp . running ) { 267await waitIdle ( signal , 120_000 ); 268const old = rt ; rt = null ; 269old . events ?. close (); old . gw . close (); await old . hp . stop (); 270} 271try { return await startRuntime ( profile ); } catch ( e ) { 272lastError = redact ( String ( e . message ?? e ), Object . values ( profile . env )); 273throw e instanceof AgentUnavailable ?e :new AgentUnavailable ( plainAgentFailure ( lastError ) === lastError ?'The coding assistant could not start. Try again. If it keeps happening, close and reopen Strata.' :plainAgentFailure ( lastError ), 'agent-start-failed' , lastError ); 274} 275})(); 276try { await starting ; } finally { starting = null ; } 277} 278} 279 280function onHostEvent ( runtime , value ) { 281if ( value . type === 'ready' ) { runtime . clientId = value . clientId ; return ; } 282if ( value . type === 'waterfall' && value . event === 'approval/request' ) { 283const r = value . request ?? {}; 284if ( ! r . callId ) return ; 285pending . set ( ` ${ value . agentId } : ${ r . callId } ` , { eventId :value . eventId , sessionId :value . agentId , callId :r . callId , tool :r . toolName , reason :r . reason ?? null , at :Date . now (), clientId :runtime . clientId }); 286} else if ( value . type === 'waterfall' && value . event === 'user-questions/request' ) { 287// The agent of a chat that is running in front of the person asks the person: the question goes to the page (the question card above the message box) and the 288// Harness waits for the answer. Anything else (a helper's question, a chat that is stopping, a request with nothing to show) is declared 289// unanswerable, which makes the tool return an error the model reads and carries on from, instead of a turn that waits forever. 290const r = value . request ?? {}; 291const chatId = chatOfSession ( value . agentId ); 292const turn = chatId ?chats . get ( chatId )?. turn :null ; 293const items = parseQuestions ( r . questions ); 294// A goal or a plan step runs without anyone there: a question would stall it, so it is declined at once (the model reads "could not be answered" and goes on). 295if ( ! turn || turn . finished || turn . stopping || turn . goalRun || turn . plan || ! turn . announceQuestion || ! items . length ) { 296void runtime . gw . answerEvent ({ clientId :runtime . clientId , eventId :value . eventId , outcome :'next' }). catch (() => {}); 297} else { 298const callId = String ( r . wait ?. callId ?? value . eventId ); 299questions . set ( ` ${ value . agentId } : ${ callId } ` , { eventId :value . eventId , sessionId :value . agentId , callId, items, at :Date . now (), clientId :runtime . clientId }); 300turn . announceQuestion ({ type :'agent-question' , callId, questions :items }); 301} 302} else if ( value . type === 'cancel' ) { 303for ( const [ k , v ] of questions ) if ( v . eventId === value . eventId ) { questions . delete ( k ); chats . get ( chatOfSession ( v . sessionId ))?. turn ?. announceQuestion ?.({ type :'agent-question-end' , callId :v . callId }); } 304for ( const [ k , v ] of pending ) if ( v . eventId === value . eventId ) pending . delete ( k ); 305} 306} 307 308async function sessionFor ( c , cwd , runtime , { onWait= () => {} } = {}) { 309let known = sessionMap [ c . id ]; 310// The chat's folder changed: the agent's working folder and sandbox are fixed when its session starts, so the chat gets a new session 311// in the new folder (the earlier conversation is carried into its first message, as for any fresh session). 312if ( known && cwd && known . cwd && resolve ( known . cwd ) !== resolve ( cwd )) { delete sessionMap [ c . id ]; persist (); known = null ; } 313if ( known ) return { sessionId :known . sessionId , fresh :false }; 314const created = await createSessionWhenReady (() => runtime . gw . rpc ( 'session/create' , { request :{ cwd} }), { readyMs :sessionReadyMs , retryMs :sessionRetryMs , onWait, cancelled :() => c . cancelStart }); 315if ( ! created ) return null ; 316sessionMap [ c . id ] = { sessionId :created . sessionId , cwd, createdAt :new Date (). toISOString () }; 317persist (); 318return { sessionId :created . sessionId , fresh :true }; 319} 320 321/** 322* Put the session into the preset of the chat's mode, through the Harness's own `/permission` command, and 323* check that it took. A turn never starts in a mode other than the one asked for: if the switch cannot be 324* confirmed the turn fails closed with a typed error instead of running with unknown permissions. 325*/ 326async function applyMode ( runtime , sessionId , mode ) { 327const want = MODE_PRESETS [ mode ]. key ; 328const read = async () => { 329const r = await runtime . gw . rpc ( 'session/projections' , { request :{ sessionId, keys :[ 'permissions' ] } }); 330return r ?. values ?. permissions ?. currentValue ?? null ; 331}; 332try { 333if ( await read () !== want ) { 334const done = await runtime . gw . rpc ( 'commands/execute' , { agentId :sessionId , line :`/permission ${ want } ` , submittedAttachments :[] }); 335if ( done ?. result ?. kind !== 'success' ) throw new Error ( done ?. result ?. text ?? 'the agent did not recognise the command' ); 336const now = await read (); 337if ( now !== want ) throw new Error ( `the session reports " ${ now } " instead of " ${ want } "` ); 338} 339} catch ( e ) { 340throw new AgentUnavailable ( `Strata could not set this chat to ${ MODE_PRESETS [ mode ]. name } mode, so nothing ran. Try again.` , 'mode-unavailable' , e . message ); 341} 342// Manual leaves the sandbox open and relies on the Strata gate to ask first. Without the gate it must not start. 343if ( mode === 'manual' && ! runtime . gateChecked ) { 344try { 345const probe = await runtime . gw . rpc ( 'commands/execute' , { agentId :sessionId , line :'/strata-gate' , submittedAttachments :[] }); 346if ( probe ?. result ?. kind !== 'success' || ! String ( probe . result . text ?? '' ). includes ( 'strata-gate active' )) throw new Error ( 'the approval gate is not loaded' ); 347runtime . gateChecked = true ; 348} catch ( e ) { 349throw new AgentUnavailable ( 'Strata could not make sure the coding assistant asks before changing anything, so nothing ran. Close and reopen Strata, then try again.' , 'mode-unavailable' , e . message ); 350} 351} 352} 353 354/** 355* Run one agent turn for a Strata chat and stream it as frames. 356* `signal` means the client went away: the turn keeps running (that is not Stop). 357*/ 358async function runTurn ( options ) { 359const c = chat ( options . chatId ); 360if ( c . turn || c . starting ) throw new AgentUnavailable ( 'This chat is still working. Stop it or wait for it to finish.' , 'turn-active' ); 361// From here until the Harness has the prompt, Stop has no session to cancel; it cancels the start. 362c . starting = true ; c . cancelStart = false ; 363try { return await runTurnInner ( c , options ); } finally { c . starting = false ; } 364} 365 366async function runTurnInner ( c , { chatId, message, workspacePath, choice= null , mode= null , history= [], onFrame, requestId= `req- ${ randomUUID ()} ` , signal, goal= null , thinking= null , thinkingBudget= 0 , images= [], planTask= null , planRun= null , researchTopic= null }) { 367let send = onFrame ; let attached = true ; 368// A research run gathers first; what the assistant writes while gathering is notes, not the answer, so it is not shown. 369let hideDeltas = !! researchTopic ; 370signal ?. addEventListener ( 'abort' , () => { send = () => {}; attached = false ; }, { once :true }); 371// What the assistant itself wrote in this run (not our own step lines): a plan turn reads its plan from it, a step reads its summary. 372const written = { all :'' , step :'' , reasoning :'' }; 373// The frame that closed the turn, kept with the turn's text for a page that comes back after it ended (attach). 374let terminal = null ; 375// The turn guard (turn-guard.mjs): counts failing searches, searches, plan rewrites and a nearly full context. Set up once the route is known. 376let guard = null ; 377const raw = frame => { if ( frame . type === 'done' || frame . type === 'error' ) terminal = frame ; try { send ( frame ); } catch { send = () => {}; attached = false ; } }; 378// What the turn made (files) and compact activity lines (notes-split-agent8.md): derived from the cards the turn already sends. 379const tracker = new DeliverableTracker ( workspacePath , { ...trackerFolders (), claims :folderClaims , owner :chatId }); 380let toolsRan = false ; // a turn that ran no tool wrote nothing, so there is nothing to look for at its end 381try { tracker . snapshot (); } catch { /* a folder that cannot be read has no deliverables */ } 382const groups = new ActivityGroups ({ emit :raw }); 383const skills = new SkillsUsed ({ emit :raw , info :skillInfoFrom ( skillsDir ()) }); 384const emit = frame => { 385if ( frame . type === 'reasoning' && frame . text && written . reasoning . length < 2_000_000 ) written . reasoning += frame . text ; 386if ( frame . type === 'delta' && ! frame . own ) { written . all += frame . text ; written . step += frame . text ; if ( guard ) trip ( guard . text ( frame . text )); if ( hideDeltas ) return ; } 387if ( frame . own ) { const { own, ...rest } = frame ; frame = rest ; } 388if ( frame . type === 'delta' && frame . text ) groups . text (); 389if ( frame . type === 'agent-tool' && frame . tool ) { 390if ([ 'done' , 'error' ]. includes ( frame . tool . state ) && ! [ 'read' , 'read_image' , 'glob' , 'grep' , 'web_fetch' , 'web_search' ]. includes ( frame . tool . name )) toolsRan = true ; 391let made = null ; 392if ( frame . tool . state === 'done' && ( frame . tool . name === 'write' || frame . tool . name === 'edit' )) { try { made = tracker . check ( frame . tool . args ?. file_path ?? frame . tool . args ?. path , { explicit :true }); } catch { made = null ; } } 393raw ( frame ); 394if ( made ) raw ( made ); 395if ( guard ) trip ( guard . card ( frame . tool )); 396groups . card ( frame . tool , made ); 397skills . card ( frame . tool ); 398return ; 399} 400raw ( frame ); 401}; 402// What the assistant is doing right now, one small frame (status.mjs). Cleared before the final frame of the turn. 403const reporter = new StatusReporter ({ emit}); 404 405emit ({ type :'queued' , requestId}); 406reporter . set ({ phase :'starting' , code :'starting' , text :'Starting…' }); 407const { rt :runtime , route} = await ensureRuntime ( choice , signal ); 408const made = await sessionFor ( c , workspacePath , runtime , { onWait :() => reporter . set ({ phase :'starting' , code :'assistant-starting' , text :'Starting the assistant…' }) }); 409const { sessionId, fresh} = made ?? {}; 410const cancelled = () => { reporter . clear (); emit ({ type :'done' , finishReason :'aborted' , cancelled :true , tokensIn :null , tokensOut :null , usageSource :'unavailable' , durationMs :0 , model :route . name , contextMax :route . contextWindow }); return { cancelled :true }; }; 411if ( c . cancelStart || ! made ) return cancelled (); 412 413// The model and the chat's thinking level (the Reasoning menu) are sent to the Harness when either changed. A level the route does 414// not have (an API model with its own vocabulary) is dropped and the model's own default stands: never an error for the person. 415const level = effortOf ( thinking ?? 'Medium' ); // the menu's default is Medium 416// Response settings the Harness cannot send itself (the thinking budget, the Expert sampling) go through this host's forwarding 417// endpoint, on a copy of the route; with every setting at its default the route is used directly, as before. 418const budget = level === 'off' ?0 :nearestBudget ( thinkingBudget ); 419const sampling = proxyBase && route . shaped ?expertSampling () :null ; 420const provider = route . shaped && ( budget || sampling ) ?route . shaped [ budget ] :route . route ; 421const wanted = ` ${ provider } / ${ route . modelId } / ${ level ?? '' } ` ; 422if ( c . route !== wanted || c . routeGeneration !== runtime . generation ) { 423const select = effort => runtime . gw . rpc ( 'session/selectModel' , { request :{ sessionId, provider, model :route . modelId , ...( effort ?{ reasoningEffort :effort } :{}) } }); 424try { 425try { await select ( level ); } catch ( e ) { if ( ! level || e . code === 'session/not-found' ) throw e ; await select ( null ); } 426} catch ( e ) { 427if ( e . code === 'session/not-found' ) { delete sessionMap [ c . id ]; persist (); } 428throw new AgentUnavailable ( `The coding assistant could not use ${ route . name } . Pick the model again and retry.` , 'model-unavailable' , e . message ); 429} 430c . route = wanted ; c . routeGeneration = runtime . generation ; 431} 432 433// The chat's permission mode is read once, here, for this whole turn. A change the user makes while the 434// turn runs applies to the next one, so a running turn never sees its permissions move under it. 435const appliedMode = planTask ?'plan' :modeOf ( mode ); 436await applyMode ( runtime , sessionId , appliedMode ); 437 438// Does the message fit the model's window? Asked before anything is sent, with the model server's own count (context-fit.mjs). A message 439// that fits once the older messages are a summary is sent after a summary; one that can never fit is not sent, and the person is told 440// plainly and offered the two ways out. Whatever cannot be counted goes through: the Harness recovers from a refusal by itself. 441if ( ! goal && route . kind === 'local' ) { 442const fit = await fitCheck ({ runtime, route, sessionId, fresh, history, message}). catch (() => null ); 443if ( fit ?. action === 'too-large' ) { 444reporter . clear (); 445const values = [ grouped ( fit . tokens ), grouped ( fit . window )]; 446const text = fill ( FIT_TEXT . tooLarge , values ); 447emit ({ type :'error' , message :text , key :FIT_TEXT . tooLarge , values, code :'CONTEXT_MESSAGE_TOO_LARGE' , tokens :fit . tokens , window :fit . window }); 448return { error :text }; 449} 450if ( fit ?. action === 'summarize' ) { 451reporter . set ({ phase :'compacting' , code :'compacting' , text :FIT_TEXT . summarizing , key :FIT_TEXT . summarizing , values :[] }); 452const done = await compactChat ( runtime , sessionId ); 453reporter . clear (); 454if ( done . ok ) emit ( summarizedNote ( done . before , done . after , fit . window )); 455} 456} 457 458const projector = new TurnProjector ({ policy :MODE_PRESETS [ appliedMode ]. approval , window :route . contextWindow }); 459if ( ! goal ) guard = new TurnGuard ({ plan :!! planTask , contextMax :route . kind === 'local' ?route . contextWindow :0 }); // a saved connection's window is often only assumed: never judged by a guess 460projector . onStatus = update => { if ( ! turn ?. parentOpen && turn ?. children . size && [ ...turn . children . values ()]. some ( h => ! h . done ) && update . phase === 'waiting' ) return ; reporter . set ( update ); }; 461const turn = { 462 sessionId, projector, route, requestId, live :false , lastSeq :- 1 , 463ended :deferred (), follow :null , snapshot :deferred (), finished :false , prompted :false , stopBeforePrompt :false , 464abortFromRuntime :reason => finishTurn ( reason ), finish :failure => finishTurn ( failure ), 465// Helper agents (subagents) the Harness started for this chat, and the state of the run around them. 466children :new Map (), subagentCalls :new Map (), parentOpen :false , stopping :false , settleTimer :null , mode :appliedMode , 467plan :null , advancing :false , goalRun :false , lastActivity :Date . now (), heard :Date . now (), engineMark :null , watchdog :null , 468research :researchTopic ?{ phase :'gather' , nudged :false , waitingStart :false } :null , 469}; 470c . turn = turn ; 471if ( workspacePath ) folderClaims . begin ( workspacePath , chatId ); 472/** 473* A page that comes back (a reload, a new window) takes the running turn over again. Everything that was said while no page was there is 474* sent as one catch-up: the start, the text and thinking so far (a `resync`), every tool card as it is now (the ones waiting for a yes 475* included) and the questions waiting for an answer. After that the turn's frames flow to the new page as they did to the old one. 476*/ 477turn . reattach = ({ onFrame, signal :again }) => { 478send = onFrame ; attached = true ; 479again ?. addEventListener ( 'abort' , () => { send = () => {}; attached = false ; }, { once :true }); 480raw ({ type :'start' , model :route . name , contextMax :route . contextWindow , demo :false , remoteModel :route . kind === 'api' , agent :true , mode :appliedMode , sessionId, requestId, skills :[], resumed :true , ...( planTask ?{ planning :true } :{}) }); 481raw ({ type :'resync' , content :hideDeltas ?'' :written . all , reasoning :written . reasoning }); 482for ( const t of projector . tools . values ()) if ( t . card ) raw ({ type :'agent-tool' , tool :t . card }); 483for ( const q of questions . values ()) if ( q . sessionId === sessionId ) raw ({ type :'agent-question' , callId :q . callId , questions :q . items }); 484}; 485/** 486* A turn must always end. If the Harness sends nothing at all for a while (a tool that never returns, a model server that went 487* quiet, a lost event) the turn is stopped and ended with a plain message instead of showing "thinking" forever. A running tool gets 488* a longer allowance than a quiet model (a build can be silent for minutes). Whatever the assistant finished is kept. 489*/ 490turn . watchdog = setInterval (() => { 491if ( turn . finished || turn . stopping ) return ; 492const toolRunning = [ ...projector . tools . values ()]. some ( x => x . card ?. state === 'running' || x . card ?. state === 'proposed' ) || pending . size > 0 && pendingFor ( chatId ). length > 0 ; 493const limit = toolRunning ?stallToolMs :stallMs ; 494// A local engine reading a long prompt sends the Harness nothing for minutes (#3623). Its /metrics progress counts as activity, 495// for at most engineGraceMs after the Harness last spoke: progress for another chat cannot keep a lost turn alive forever. 496if ( turn . route ?. kind === 'local' && Date . now () - turn . heard < engineGraceMs ) { 497let mark = null ; 498try { mark = engineProgress ( turn . route . instanceId ); } catch { /* no progress known: the Harness alone decides */ } 499if ( mark != null && mark !== turn . engineMark ) { turn . engineMark = mark ; turn . lastActivity = Date . now (); return ; } 500} 501if ( Date . now () - turn . lastActivity < limit ) return ; 502turn . stalledFor = Math . round (( Date . now () - turn . lastActivity ) / 1000 ); 503turn . stopping = true ; 504void runtime . gw . rpc ( 'session/cancel' , { request :{ sessionId} }). catch (() => {}); 505for ( const h of turn . children . values ()) if ( ! h . done ) void runtime . gw . rpc ( 'subagents/interruptByParent' , { childSessionId :h . id , parentSessionId :sessionId , mode :'continuable' }). catch (() => {}); 506const mins = Math . max ( 1 , Math . round ( turn . stalledFor / 60 )); 507turn . finish ( `The assistant stopped answering for ${ mins > 1 ? mins + ' minutes' : 'a minute' } , so I ended this turn. Anything it already finished is kept. Send your message again to go on.` ); 508}, Math . min ( 15_000 , Math . max ( 200 , Math . floor ( stallMs / 4 )))); 509turn . watchdog . unref ?.(); 510async function finishTurn ( failure ) { 511if ( turn . finished ) return ; 512turn . finished = true ; 513for ( const [ k , v ] of questions ) if ( v . sessionId === turn . sessionId ) questions . delete ( k ); 514clearTimeout ( turn . settleTimer ); 515clearInterval ( turn . watchdog ); 516turn . follow ?. close (); 517for ( const child of turn . children . values ()) child . follow ?. close (); 518if ( turn . stopping && ! failure ) projector . ended = turn . guard ?{ kind :'completed' } :{ kind :'aborted' , reason :{ kind :'user' } }; 519reporter . clear (); 520const extra = []; 521try { if ( toolsRan ) for ( const d of tracker . sweep ()) { emit ( d ); groups . addFile ( d ); } } catch { /* never blocks the end of a turn */ } 522if ( workspacePath ) folderClaims . end ( workspacePath , chatId ); 523groups . end (); 524if ( researchTopic && ! failure && ! turn . stopping ) { const sources = parseSources ( written . all ); if ( sources . length ) extra . push ({ type :'research' , topic :researchTopic , sources}); } 525try { extra . push ( ...settlePlan ( failure )); } catch { /* a plan frame must never break the end of a turn */ } 526// The turn guard: a turn the app stopped, or one that ended with no words, always ends with one plain message (a plan card carries it itself). 527let noteReason = turn . guard ?? null ; 528// A reply the length limit cut ends with a sentence that says so (and what was lost), never with silence (AGENT-LOST). 529const cutEnd = ! failure && ! turn . stopping && projector . ended ?. kind === 'max-tokens' ; 530if ( cutEnd && ! noteReason ) { 531const note = cutNotice ({ ...projector . cut (), retrying :false }); 532extra . push ({ type :'delta' , own :true , text :` 533 534${ note . text } ` , key :note . key , values :note . values , noteReason :'cut' }); 535} 536if ( ! noteReason && ! cutEnd && guard && ! failure && ! turn . stopping && ! turn . goalRun ) { 537noteReason = guard . silent ({ ended :projector . ended , wrote :projector . emittedAny === true , acted :projector . tools . size > 0 , contextTokens :projector . contextTokens }); 538} 539if ( noteReason && ! extra . some ( f => f . type === 'plan' && f . event === 'proposed' )) { const note = guardNote ( noteReason ); if ( note ) extra . push ( note ); } 540for ( const f of extra ) emit ( f ); 541// The answer speed of a turn on this computer is the engine's own (tokens it produced over its decode time, as the Monitor shows it). 542const engine = ! failure && route . kind === 'local' ?await engineSpeedOf ( route , projector ) :null ; 543const frames = failure ?[{ type :'error' , message :plainAgentFailure ( failure ), details :failure , code :'AGENT_STOPPED' }] :projector . finish ({ model :route . name , contextMax :route . contextWindow , engine}); 544for ( const f of frames . slice ( 0 , - 1 )) emit ( f ); 545// Messages typed while the goal ran and not delivered between steps go back to the page now, to be sent as ordinary messages. 546if ( turn . goalRun && attached ) { 547const left = queueView ( chatId ); 548if ( left . length ) { queues . delete ( chatId ); onQueue ( chatId , []); emit ({ type :'queued-release' , messages :left . map (({ id, text}) => ({ id, text})) }); } 549} 550for ( const f of frames . slice ( - 1 )) emit ( f ); 551c . turn = null ; 552// What a page that was away needs to show the end of this turn (attach, below). 553c . last = { requestId, sessionId, mode :appliedMode , model :route . name , contextMax :route . contextWindow , remoteModel :route . kind === 'api' , content :hideDeltas ?'' :written . all . slice ( 0 , 4_000_000 ), reasoning :written . reasoning , cards :[ ...projector . tools . values ()]. filter ( t => t . card ). map ( t => t . card ), terminal}; 554turn . ended . resolve ({ reason :projector . ended , failure :failure ?? null }); 555notifyIdle (); 556// A turn that filled the context, or that the guard stopped, leaves a long history behind: summarise the older part now so the next message has room. 557if ( noteReason === 'context' || noteReason === 'searches' || noteReason === 'searches-failed' || noteReason === 'rewrites' || / context window | too long | exceeds / i . test ( String ( projector . ended ?. error ?. message ?? '' ))) void compactSession ( runtime , sessionId ); 558} 559 560emit ({ type :'start' , model :route . name , contextMax :route . contextWindow , demo :false , remoteModel :route . kind === 'api' , agent :true , mode :appliedMode , sessionId, requestId, skills :[], ...( planTask ?{ planning :true } :{}) }); 561 562turn . follow = runtime . gw . openStream ( 'session/follow' , { request :{ address :{ kind :'session' , sessionId}, assistantStream :true } }, { 563onItem :item => { 564if ( item . type === 'snapshot' ) { 565if ( turn . lastSeq < 0 ) turn . lastSeq = item . cursor ; 566else for ( const r of item . records ?? []) if ( r . type === 'event' && r . event . seq > turn . lastSeq ) handle ({ type :'event' , event :r . event }); 567turn . snapshot . resolve (); 568return ; 569} 570handle ( item ); 571}, 572onError :e => finishTurn ( `The agent lost the session stream: ${ e . message } ` ), 573}); 574 575/** The guard says stop: end the turn the way Stop does, but as a normal end with a plain message (finishTurn). */ 576function trip ( reason ) { 577if ( ! reason || turn . guard || turn . finished || turn . stopping ) return ; 578turn . guard = reason ; 579log ( `agent · turn guard: ${ reason } (searches ${ guard ?. searches ?? 0 } , failed in a row ${ guard ?. failedInARow ?? 0 } , plan rewrites ${ guard ?. rewrites ?? 0 } )` ); 580void stop ( chatId ). catch (() => {}); 581} 582 583function handle ( item ) { 584if ( turn . finished ) return ; 585turn . lastActivity = Date . now (); 586turn . heard = turn . lastActivity ; 587if ( item . type === 'event' ) { 588const e = item . event ; 589if ( e . seq <= turn . lastSeq ) return ; 590turn . lastSeq = e . seq ; 591// The turn is ours from the user message that carries our request id. Until then an older, 592// detached turn on the same session may still be finishing; its events are not ours. 593if ( ! turn . live ) { 594if ( e . type === 'user/message' && e . data ?. source ?. rpcId === requestId ) turn . live = true ; 595return ; 596} 597} else if ( ! turn . live ) return ; 598for ( const f of projector . consume ( item )) emit ( f ); 599if ( guard && projector . contextTokens != null ) trip ( guard . context ( projector . contextTokens )); 600if ( item . type === 'event' ) watchParent ( item . event ); 601} 602 603// -- helper agents --------------------------------------------------------------------------------------- 604 605const rowFrame = child => ({ type :'agent' , agent :child . cp . agent () }); 606const emitRow = ( child , force = false ) => { 607const now = Date . now (); 608if ( ! force && now - child . lastRow < 400 ) { child . rowPending = true ; return ; } 609child . lastRow = now ; child . rowPending = false ; 610emit ( rowFrame ( child )); 611const working = [ ...turn . children . values ()]. filter ( h => ! h . done ). length ; 612if ( working && ! turn . parentOpen ) reporter . set ({ phase :'helpers' , code :'helpers' , text :`Helpers are working ( ${ working } )…` , key :'Helpers are working ({0})…' , values :[ working ], args :{ n :working } }); 613}; 614 615function openChild ( d ) { 616const id = d . childId ; 617if ( ! id || turn . children . has ( id )) return ; 618const cp = new ChildProjector ({ id, name :d . label || 'Helper' }); 619const child = { id, cp, follow :null , noticed :false , done :false , lastRow :0 , rowPending :false , endedAt :0 }; 620turn . children . set ( id , child ); 621emitRow ( child , true ); 622const fold = item => { 623if ( turn . finished ) return ; 624turn . lastActivity = turn . heard = Date . now (); 625// A helper that finishes before its throttled "working" row went out would show queued -> completed and never "working": send the held row first. 626if ( item . type === 'event' && item . event . type === 'turn/end' && child . rowPending ) emitRow ( child , true ); 627const { frames, row} = cp . consume ( item ); 628for ( const f of frames ) emit ( f ); 629if ( item . type === 'event' && item . event . type === 'turn/end' ) { child . done = true ; child . endedAt = Date . now (); emitRow ( child , true ); armSettle (); return ; } 630if ( item . type === 'event' && child . done && cp . status === 'working' ) { child . done = false ; } 631if ( row ) emitRow ( child ); 632}; 633child . follow = runtime . gw . openStream ( 'session/follow' , { 634request :{ address :{ kind :'subagent' , parentSessionId :sessionId , childSessionId :id , mode :d . mode ?? 'unknown' }, assistantStream :true }, 635}, { 636onItem :item => { 637if ( item . type === 'snapshot' ) { for ( const r of item . records ?? []) if ( r . type === 'event' ) fold ({ type :'event' , event :r . event }); return ; } 638fold ( item ); 639}, 640onError :e => { 641log ( `agent · helper stream ended: ${ e . message } ` ); 642if ( ! child . done ) { child . done = true ; child . endedAt = Date . now (); cp . status = 'failed' ; cp . failure = 'Lost contact with this helper.' ; cp . endedAt = Date . now (); emitRow ( child , true ); armSettle (); } 643}, 644}); 645// A late reader still gets the final row: flush any row held back by the throttle. 646child . flush = after ( 500 , function tick () { if ( ! turn . finished && child . rowPending ) emitRow ( child , true ); if ( ! turn . finished && ! child . done ) child . flush = after ( 500 , tick ); }); 647} 648 649function watchParent ( e ) { 650const d = e . data ?? {}; 651switch ( e . type ) { 652case 'turn/start' : 653turn . parentOpen = true ; 654if ( turn . research ) turn . research . waitingStart = false ; 655turn . cutWaiting = false ; 656clearTimeout ( turn . settleTimer ); 657// After Stop, a helper's report would start a new turn that nobody asked for. 658if ( turn . stopping ) void runtime . gw . rpc ( 'session/cancel' , { request :{ sessionId} }). catch (() => {}); 659break ; 660case 'turn/end' : 661turn . parentOpen = false ; 662armSettle (); 663break ; 664// The first turn of a prompt may have started before this follow stream attached (no turn/start seen): any step of the parent is proof that it is 665// still working. Without this a helper that finished while the parent was still answering ended the run early ("The agent turn was interrupted"). 666case 'step/start' : 667if ( ! turn . parentOpen ) { turn . parentOpen = true ; clearTimeout ( turn . settleTimer ); } 668break ; 669case 'tool/call' : 670if ( d . name === 'subagent' || d . name === 'subagent_fork' ) turn . subagentCalls . set ( d . callId , parseArgs ( d . arguments )); 671break ; 672case 'subagent/catalog' : 673openChild ( d ); 674break ; 675case 'tool/result' :{ 676const call = turn . subagentCalls . get ( d . message ?. toolCallId ); 677const text = ( d . message ?. content ?? []). map ( p => p . text ?? '' ). join ( ' ' ); 678const started = / started subagent ([ 0 - 9a - f- ]{ 36 }) / i . exec ( text ); 679const child = started ?turn . children . get ( started [ 1 ]) :null ; 680if ( call && child ) { child . cp . task = String ( call . prompt ?? call . description ?? '' ). replace ( / \s +/ g , ' ' ). trim (). slice ( 0 , 140 ); emitRow ( child , true ); } 681break ; 682} 683case 'user/message' : 684if ( d . source ?. kind === 'goal' && Number . isInteger ( d . source . round )) { turn . goalRound = d . source . round ; void announceGoal (); } 685// falls through 686case 'agent/inbox/spliced' :{ 687const hit = JSON . stringify ( d ); 688if ( ! /Background subagent / . test ( hit )) break ; 689for ( const child of turn . children . values ()) if ( hit . includes ( child . id )) child . noticed = true ; 690break ; 691} 692default : 693break ; 694} 695} 696 697// -- plans and goal steps ---------------------------------------------------------------------------------- 698 699const planFrame = ( event , plan , extra = {}) => ({ type :'plan' , event, plan :planView ( plan ), ...extra }); 700const publishPlan = ( event , plan ) => { onPlan ( chatId , event , planView ( plan )); return planFrame ( event , plan ); }; 701const stepFrame = ( plan , index ) => { 702const st = plan . steps [ index ]; 703return { type :'plan-step' , planId :plan . id , stepId :st . id , index :index + 1 , total :plan . steps . length , state :st . state , text :st . text , summary :st . summary ?? null , line :stepLine ( index , plan . steps . length , st . text , st . state === 'running' ?'started' :st . state ) }; 704}; 705const currentStep = plan => plan . steps . findIndex ( x => x . state !== 'done' && x . state !== 'skipped' ); 706 707/** What the end of the turn means for the plan: a plan turn makes one; a step run records where it stopped. */ 708function settlePlan ( failure ) { 709if ( planTask ) { 710if ( failure || ( turn . stopping && ! turn . guard )) return []; 711const parsed = parsePlan ( written . all , planTask ); 712if ( ! parsed ) return []; 713const plan = plans . create ( chatId , { title :parsed . title , steps :parsed . steps , request :planTask , ...( turn . guard ?{ caution :GUARD_NOTES [ turn . guard ] } :{}) }); 714return [ publishPlan ( 'proposed' , plan )]; 715} 716const run = turn . plan ; 717if ( ! run ) return []; 718const plan = plans . get ( chatId ); 719if ( ! plan || plan . id !== run . id ) return []; 720if ( plan . state !== 'running' ) return []; 721const out = []; 722const at = currentStep ( plan ); 723plans . update ( chatId , p => { 724if ( at < 0 ) { p . state = 'done' ; return ; } 725// The step that was running goes back to waiting, so Resume runs it again. 726p . steps [ at ]. state = 'pending' ; 727p . state = 'paused' ; 728}); 729const updated = plans . get ( chatId ); 730if ( at >= 0 ) out . push ( stepFrame ( updated , at )); 731out . push ( publishPlan ( updated . state === 'done' ?'done' :'paused' , updated )); 732return out ; 733} 734 735/** The goal the Harness runs for the plan's next waiting step, and the frames that say so. */ 736async function startStep ( plan , index ) { 737plans . update ( chatId , p => { p . state = 'running' ; p . goalStarted = true ; p . steps [ index ]. state = 'running' ; }); 738const now = plans . get ( chatId ); 739await runtime . gw . rpc ( 'goals/create' , { agentId :sessionId , request :{ objective :stepObjective ( now , index ) } }); 740written . step = '' ; written . stepAt = Date . now (); 741emit ( stepFrame ( now , index )); 742emit ( publishPlan ( 'step' , now )); 743const st = now . steps [ index ]; 744reporter . set ({ phase :'goal' , code :'goal-step' , text :stepLine ( index , now . steps . length , st . text , 'started' ), key :'{0}' , values :[ st . text ], args :{ step :index + 1 , steps :now . steps . length } }); 745} 746 747/** One goal step finished: say so, hand over queued messages, and begin the next step (or end the plan). */ 748async function advancePlan () { 749const run = turn . plan ; 750const plan = plans . get ( chatId ); 751if ( ! run || ! plan || plan . id !== run . id ) return false ; 752const at = currentStep ( plan ); 753if ( at < 0 ) return false ; 754const cards = [ ...projector . tools . values ()]. filter ( x => x . calledAt >= ( written . stepAt ?? 0 ) - 50 && x . card ?. state === 'done' ). map ( x => x . card ); 755const summary = stepSummary ( cards , written . step . split ( / \n\s * \n / ). filter ( Boolean ). at ( - 1 ) ?? written . step ); 756plans . update ( chatId , p => { p . steps [ at ]. state = 'done' ; p . steps [ at ]. summary = summary ; }); 757let now = plans . get ( chatId ); 758emit ( stepFrame ( now , at )); 759emit ({ type :'delta' , own :true , text :`\n\n ${ stepLine ( at , now . steps . length , now . steps [ at ]. text , 'done' )} \n` }); 760const next = currentStep ( now ); 761emit ( publishPlan ( next < 0 ?'done' :'step' , next < 0 ?( plans . update ( chatId , p => { p . state = 'done' ; }), plans . get ( chatId )) :now )); 762await deliverQueued ( at + 1 ); 763if ( turn . stopping || turn . finished ) return true ; 764if ( next < 0 ) return false ; 765// One step per turn (Time-skip): the plan stays open for the next step, which starts in a session of its own so the conversation never grows across steps. 766if ( run . once ) { plans . update ( chatId , p => { p . state = 'approved' ; }); emit ( publishPlan ( 'step' , plans . get ( chatId ))); return false ; } 767await startStep ( plans . get ( chatId ), next ); 768void announceGoal (); 769return true ; 770} 771 772/** Hand the person's queued messages to the assistant, one at a time, each answered before the next. */ 773async function deliverQueued ( afterStep ) { 774const list = queues . get ( chatId ) ?? []; 775while ( list . length && ! turn . stopping && ! turn . finished ) { 776const item = list . shift (); 777if ( ! list . length ) queues . delete ( chatId ); 778onQueue ( chatId , queueView ( chatId )); 779emit ({ type :'queued-message' , state :'delivered' , message :{ id :item . id , text :item . text , at :item . at , deliverAt :item . deliverAt }, afterStep, queue :queueView ( chatId ) }); 780try { await runtime . gw . rpc ( 'session/prompt' , { request :{ requestId :`queued- ${ randomUUID ()} ` , sessionId, mode :'queue' , content :[{ type :'text' , text :item . text }] } }); } 781catch { emit ({ type :'queued-release' , messages :[{ id :item . id , text :item . text }] }); continue ; } 782// Wait for the answer: the parent opens a turn for it and closes it again. 783const t0 = Date . now (); 784while ( ! turn . parentOpen && Date . now () - t0 < 4000 && ! turn . finished ) await new Promise ( r => setTimeout ( r , 50 )); 785while ( turn . parentOpen && ! turn . finished && ! turn . stopping ) await new Promise ( r => setTimeout ( r , 100 )); 786} 787} 788 789/** 790* The run is over when the parent is idle and every helper has finished and reported back. A helper's report 791* wakes the parent a moment after the helper ends, so a helper that ended but has not reported yet keeps the run 792* open (for a few seconds at most); after Stop nobody waits for reports. 793*/ 794function armSettle () { 795clearTimeout ( turn . settleTimer ); 796if ( turn . finished ) return ; 797turn . settleTimer = after ( turn . stopping ?1200 :turn . children . size ?600 :0 , async () => { 798if ( turn . finished || turn . parentOpen || turn . advancing ) return ; 799const open = [ ...turn . children . values ()]; 800if ( open . some ( c => ! c . done )) return ; 801if ( ! turn . stopping ) { 802if ( open . some ( c => ! c . noticed && Date . now () - c . endedAt < 8000 )) { armSettle (); return ; } 803// An armed goal starts its next round as soon as the agent is idle: the run is not over until the goal stops. 804const current = await goalGet (); 805if ( turn . finished || turn . parentOpen ) return ; 806if ( current && current . phase === 'active' && current . activation === 'armed' ) { turn . settleTimer = after ( 700 , armSettle ); return ; } 807// A reply the length limit cut (AGENT-LOST): the agent lost what it was writing. Say so in the chat and ask it to carry on in smaller pieces, twice at most. 808if ( turn . cutWaiting ) { turn . settleTimer = after ( 300 , armSettle ); return ; } 809if ( projector . ended ?. kind === 'max-tokens' && ! turn . goalRun && ! turn . stopping && ( turn . cuts ?? 0 ) < MAX_CUT_RETRIES ) { 810const cut = projector . cut (); 811turn . cuts = ( turn . cuts ?? 0 ) + 1 ; 812const note = cutNotice ({ ...cut , retrying :true }); 813emit ({ type :'delta' , own :true , text :` 814 815${ note . text } 816 817` , key :note . key , values :note . values , noteReason :'cut' }); 818for ( const f of projector . clearCut ()) emit ( f ); 819turn . cutWaiting = true ; 820try { await runtime . gw . rpc ( 'session/prompt' , { request :{ requestId :`cut- ${ randomUUID ()} ` , sessionId, mode :'queue' , content :[{ type :'text' , text :cutNudge ( cut ) }] } }); } 821catch { turn . cutWaiting = false ; finishTurn ( null ); return ; } 822turn . settleTimer = after ( 500 , armSettle ); 823return ; 824} 825// Research: gather (search and read pages), then write the answer in the fixed shape. A step that did not open pages is sent back once. 826if ( turn . research && ! turn . stopping ) { 827const r = turn . research ; 828if ( r . waitingStart ) { turn . settleTimer = after ( 300 , armSettle ); return ; } 829const opened = [ ...projector . tools . values ()]. filter ( x => x . card ?. name === 'web_fetch' && x . card . state === 'done' ). length ; 830const prompt = r . phase === 'write' ?null :( opened < 2 && ! r . nudged ) ?RESEARCH_NUDGE :researchWritePrompt ( researchTopic ); 831if ( prompt ) { 832if ( prompt !== RESEARCH_NUDGE ) { r . phase = 'write' ; hideDeltas = false ; written . all = '' ; reporter . set ({ phase :'waiting' , code :'research-writing' , text :'Writing the answer…' , key :'Writing the answer…' , values :[], args :{} }); } else r . nudged = true ; 833r . waitingStart = true ; 834try { await runtime . gw . rpc ( 'session/prompt' , { request :{ requestId :`research- ${ randomUUID ()} ` , sessionId, mode :'queue' , content :[{ type :'text' , text :prompt }] } }); } 835catch { r . waitingStart = false ; hideDeltas = false ; finishTurn ( null ); return ; } 836turn . settleTimer = after ( 500 , armSettle ); 837return ; 838} 839} 840// A plan step's goal is complete: record it, deliver queued messages, start the next step. 841if ( turn . plan && current && current . phase === 'complete' && ! turn . advancing ) { 842turn . advancing = true ; 843let more = false ; 844try { more = await advancePlan (); } catch ( e ) { emit ({ type :'delta' , own :true , text :`\n\nThe plan stopped: ${ plainGoalError ( e )} \n` }); } 845turn . advancing = false ; 846if ( more && ! turn . finished && ! turn . stopping ) { turn . settleTimer = after ( 700 , armSettle ); return ; } 847} 848 849if ( turn . goalRun && current ) { const line = goalEnding ( current ); if ( line ) emit ({ type :'delta' , text :line }); } 850if ( turn . goalRun ) await announceGoal ( true ); 851} 852finishTurn ( null ); 853}); 854} 855const goalGet = () => runtime . gw . rpc ( 'goals/get' , { agentId :sessionId }). catch (() => undefined ); 856/** The goal's state to the page: a `goal` frame, the SSE event for the bar, and (while a round runs) the status line. */ 857async function announceGoal ( final = false ) { 858const view = await goalGet (); 859if ( turn . finished && ! final ) return ; 860const goal = goalObject ( view , chatId ); 861emit ({ type :'goal' , goal}); 862onGoal ( chatId , goal ); 863if ( ! final && goal && goal . phase === 'active' && turn . goalRound ) reporter . set ({ phase :'goal' , code :'goal-step' , text :'Working on the goal…' , args :{ round :turn . goalRound , max :goal . maxRounds } }); 864} 865turn . announceGoal = announceGoal ; 866turn . announceQueue = frame => emit ( frame ); 867turn . announceQuestion = frame => emit ( frame ); 868 869const snapshotTimer = {}; 870await Promise . race ([ turn . snapshot . promise , new Promise (( _ , rej ) => { snapshotTimer . t = after ( 20_000 , () => rej ( new Error ( 'the session stream did not open' ))); })]) 871. catch ( e => { finishTurn ( e . message ); }) 872. finally (() => clearTimeout ( snapshotTimer . t )); 873if ( turn . finished ) return { error :true }; 874if ( turn . stopBeforePrompt || c . cancelStart ) { projector . ended = { kind :'aborted' , reason :{ kind :'user' } }; finishTurn ( null ); return { cancelled :true }; } 875 876if ( goal ) { 877// A goal run has no prompt of its own: the Harness's goal driver starts the rounds. Everything from now on is ours. 878turn . live = true ; turn . goalRun = true ; 879try { 880if ( planRun ) { 881const plan = plans . get ( chatId ); 882if ( ! plan || plan . id !== planRun . planId ) throw new AgentUnavailable ( 'That plan is no longer there. Ask for a new one with /plan.' , 'plan-gone' ); 883turn . plan = { id :plan . id , once :!! planRun . once }; 884const at = currentStep ( plan ); 885if ( at < 0 ) throw new AgentUnavailable ( 'Every step of this plan is already done.' , 'plan-done' ); 886if ( goal . action === 'resume' && plan . goalStarted ) { 887plans . update ( chatId , p => { p . state = 'running' ; p . steps [ at ]. state = 'running' ; }); 888await startGoal ( runtime , sessionId , goal ); 889emit ( publishPlan ( 'step' , plans . get ( chatId ))); 890} else await startStep ( plan , at ); 891} else { 892await startGoal ( runtime , sessionId , goal ); 893} 894} catch ( e ) { finishTurn ( e instanceof AgentUnavailable ?e . message :plainGoalError ( e )); return { error :true }; } 895reporter . set ({ phase :'waiting' , code :'reading-prompt' , text :'Reading your message…' }); 896void announceGoal (); 897} else { 898let prompt = message ; 899if ( fresh && history . length ) prompt = withEarlierConversation ( history , message ); 900try { 901await runtime . gw . rpc ( 'session/prompt' , { request :{ requestId, sessionId, mode :'queue' , content :[{ type :'text' , text :prompt }, ...imageParts ( images )] } }); 902} catch ( e ) { 903finishTurn ( `The agent did not accept the message: ${ e . message } ` ); 904return { error :true }; 905} 906} 907if ( ! goal ) reporter . set ({ phase :'waiting' , code :'reading-prompt' , text :'Reading your message…' }); 908turn . prompted = true ; 909if ( turn . stopBeforePrompt ) { 910// Stop landed in the instant between 'prompt sent' and 'prompt accepted'. A cancel before the turn 911// starts arms nothing, so wait for the turn to be ours, then cancel it. 912for ( let i = 0 ; i < 100 && ! turn . live && ! turn . finished ; i ++ ) await new Promise ( r => setTimeout ( r , 50 )); 913if ( ! turn . finished ) await runtime . gw . rpc ( 'session/cancel' , { request :{ sessionId} }). catch (() => {}); 914} 915 916// Wait for the turn, or for the client to leave. Leaving does not stop the turn. 917const gone = new Promise ( r => signal ?. addEventListener ( 'abort' , () => r ( 'detached' ), { once :true })); 918const outcome = await Promise . race ([ turn . ended . promise , gone ]); 919if ( outcome === 'detached' ) return { detached :true , sessionId, ended :turn . ended . promise . then ( r => ({ ...r , tokensOut :projector . tokensOut })) }; 920return { sessionId, reason :outcome . reason , tokensIn :projector . tokensIn , tokensOut :projector . tokensOut }; 921} 922 923// -- /goal ----------------------------------------------------------------------------------------------- 924 925/** Create or resume the chat's goal; the Harness's goal driver then runs the rounds by itself. */ 926async function startGoal ( runtime , sessionId , goal ) { 927if ( goal . action === 'create' ) { 928const request = { objective :goal . objective , ...( goal . maxRounds ?{ maxGoalRounds :goal . maxRounds } :{}) }; 929await runtime . gw . rpc ( 'goals/create' , { agentId :sessionId , request}); 930return ; 931} 932const current = await runtime . gw . rpc ( 'goals/get' , { agentId :sessionId }); 933if ( ! current ) throw new AgentUnavailable ( 'There is no goal to continue. Start one with /goal followed by what you want done.' , 'goal-none' ); 934await runtime . gw . rpc ( 'goals/resume' , { agentId :sessionId , ref :{ id :current . id , revision :current . revision } }); 935} 936 937async function pauseGoal ( runtime , sessionId , chatId = null ) { 938try { 939const current = await runtime . gw . rpc ( 'goals/get' , { agentId :sessionId }); 940if ( current && current . phase === 'active' ) { 941await runtime . gw . rpc ( 'goals/pause' , { agentId :sessionId , ref :{ id :current . id , revision :current . revision } }); 942if ( chatId ) onGoal ( chatId , goalObject ( await runtime . gw . rpc ( 'goals/get' , { agentId :sessionId }). catch (() => undefined ))); 943} 944} catch { /* no goal service, or nothing to pause */ } 945} 946 947/** The goal as the page and the goal bar see it (notes-split-agent3.md), or null. */ 948function goalObject ( view , chatId = null ) { 949if ( ! view ) return null ; 950const phase = [ 'active' , 'paused' , 'complete' , 'blocked' ]. includes ( view . phase ) ?view . phase :'blocked' ; 951// A goal that is running a plan (or the points of a goal) shows the plan's title and which step it is on. 952const plan = chatId ?plans . get ( chatId ) :null ; 953const running = plan && plan . goalStarted && [ 'running' , 'paused' ]. includes ( plan . state ) ?plan :null ; 954const at = running ?running . steps . findIndex ( x => x . state !== 'done' && x . state !== 'skipped' ) :- 1 ; 955const step = running && at >= 0 ?{ index :at + 1 , total :running . steps . length , text :running . steps [ at ]. text } :null ; 956return { objective :step ?running . title :String ( view . objective ?? '' ), ...( step ?{ step} :{}), phase, round :view . roundsStarted ?? 0 , maxRounds :view . maxGoalRounds ?? null , ...( phase === 'blocked' ?{ blocked :plainBlocker ( view . blockedReason ) } :{}) }; 957} 958 959/** The goal of a chat now, from the Harness (null: none, or the agent is not running). */ 960async function goalState ( chatId ) { 961const known = sessionMap [ chatId ]?. sessionId ; 962if ( ! known || ! rt ?. hp . running ) return null ; 963return goalObject ( await rt . gw . rpc ( 'goals/get' , { agentId :known }). catch (() => undefined ), chatId ); 964} 965 966/** Pause, edit or remove the goal from the goal bar. Instant; resume runs rounds and goes through the chat stream. */ 967async function goalControl ({ chatId, action, text}) { 968const known = sessionMap [ chatId ]?. sessionId ; 969if ( ! known || ! rt ?. hp . running ) throw new AgentUnavailable ( 'There is no goal in this chat yet.' , 'goal-none' ); 970const current = await rt . gw . rpc ( 'goals/get' , { agentId :known }). catch (() => undefined ); 971if ( ! current ) throw new AgentUnavailable ( 'There is no goal in this chat yet.' , 'goal-none' ); 972const ref = { id :current . id , revision :current . revision }; 973try { 974if ( action === 'pause' ) { if ( current . phase === 'active' ) await rt . gw . rpc ( 'goals/pause' , { agentId :known , ref}); } 975else if ( action === 'clear' ) await rt . gw . rpc ( 'goals/clear' , { agentId :known , ref}); 976else if ( action === 'edit' ) { 977const objective = String ( text ?? '' ). trim (). slice ( 0 , 4000 ); 978if ( ! objective ) throw new AgentUnavailable ( 'A goal needs a few words about what you want done.' , 'goal-text' ); 979await rt . gw . rpc ( 'goals/edit' , { agentId :known , ref, request :{ objective} }); 980} else throw new AgentUnavailable ( 'That goal action is not known.' , 'goal-action' ); 981} catch ( e ) { throw e instanceof AgentUnavailable ?e :new AgentUnavailable ( plainGoalError ( e ), 'goal-failed' , e . message ); } 982if ( action === 'clear' ) { const plan = plans . get ( chatId ); if ( plan && [ 'running' , 'paused' ]. includes ( plan . state )) { plans . update ( chatId , p => { p . state = 'stopped' ; for ( const st of p . steps ) if ( st . state === 'running' ) st . state = 'pending' ; }); onPlan ( chatId , 'stopped' , planView ( plans . get ( chatId ))); } } 983const goal = action === 'clear' ?null :goalObject ( await rt . gw . rpc ( 'goals/get' , { agentId :known }). catch (() => undefined ), chatId ); 984onGoal ( chatId , goal ); 985return { goal}; 986} 987 988/** The goal's state in plain words. */ 989function describeGoal ( view ) { 990if ( ! view ) return 'No goal is set. Start one with /goal followed by what you want done.' ; 991const what = `" ${ view . objective } "` ; 992if ( view . phase === 'active' ) return `Working on the goal ${ what } .` ; 993if ( view . phase === 'paused' ) return `The goal ${ what } is paused. Type /goal resume to go on.` ; 994if ( view . phase === 'complete' ) return `The goal ${ what } is complete.` ; 995return `The goal ${ what } stopped: ${ plainBlocker ( view . blockedReason )} ` ; 996} 997 998/** 999* Handle a "/goal ..." line for a chat, as the Harness's own /goal command reads it: nothing = show the goal, 1000* clear, pause, resume, edit <text>, or any other text = a new goal. Starting or resuming runs the rounds and 1001* streams them like a chat turn (Stop pauses the goal); every other verb answers at once. 1002*/ 1003async function goalCommand ( options ) { 1004const { chatId, line, onFrame} = options ; 1005const text = String ( line ?? '' ). trim (); 1006const verb = text . split ( / \s +/ )[ 0 ]?. toLowerCase () ?? '' ; 1007const rest = text . slice ( verb . length ). trim (); 1008const say = reply => { 1009onFrame ({ type :'queued' , requestId :`goal- ${ randomUUID ()} ` }); 1010onFrame ({ type :'start' , model :'' , contextMax :0 , demo :false , remoteModel :false , agent :true , mode :modeOf ( options . mode ), skills :[] }); 1011onFrame ({ type :'delta' , text :reply }); 1012onFrame ({ type :'done' , finishReason :'stop' , tokensIn :null , tokensOut :null , usageSource :'unavailable' , durationMs :0 }); 1013return { goal :true }; 1014}; 1015if ( tools ()?. off ?. has ( 'goals' )) return say ( 'Goals are turned off. You can turn them back on in Settings, Tools.' ); 1016const known = sessionMap [ chatId ]?. sessionId ; 1017const quick = [ '' , 'clear' , 'pause' , 'edit' , 'complete' ]. includes ( verb ) || ( verb === 'status' ); 1018let runtime = rt ; 1019if ( quick ) { 1020if ( ! known || ! runtime ?. hp . running ) return say ( verb === '' || verb === 'status' ?describeGoal ( null ) :'There is no goal in this chat yet.' ); 1021const current = await runtime . gw . rpc ( 'goals/get' , { agentId :known }). catch (() => undefined ); 1022const ref = current ?{ id :current . id , revision :current . revision } :null ; 1023try { 1024if ( verb === '' || verb === 'status' ) return say ( describeGoal ( current )); 1025if ( ! ref ) return say ( 'There is no goal in this chat yet.' ); 1026if ( verb === 'clear' ) { await runtime . gw . rpc ( 'goals/clear' , { agentId :known , ref}); return say ( 'The goal is cleared.' ); } 1027if ( verb === 'pause' ) { 1028if ( current . phase === 'active' ) await runtime . gw . rpc ( 'goals/pause' , { agentId :known , ref}); 1029return say ( describeGoal ( await runtime . gw . rpc ( 'goals/get' , { agentId :known }))); 1030} 1031if ( verb === 'complete' ) { await runtime . gw . rpc ( 'goals/complete' , { agentId :known , ref}); return say ( 'The goal is marked complete.' ); } 1032if ( verb === 'edit' ) { 1033if ( ! rest ) return say ( 'Type /goal edit followed by the new wording of the goal.' ); 1034await runtime . gw . rpc ( 'goals/edit' , { agentId :known , ref, request :{ objective :rest } }); 1035return say ( `The goal now reads: " ${ rest } ".` ); 1036} 1037} catch ( e ) { return say ( plainGoalError ( e )); } 1038} 1039if ( verb === 'resume' ) { 1040const plan = plans . get ( chatId ); 1041const goalPlan = plan && plan . goalStarted && plan . state === 'paused' ?{ planId :plan . id } :null ; 1042return runTurn ({ ...options , goal :{ action :'resume' }, ...( goalPlan ?{ planRun :goalPlan } :{}) }); 1043} 1044// A goal whose own words hold numbered points ("1. ... 2. ... 3. ...") runs point by point, each one reported. 1045const points = parsePoints ( text ); 1046if ( points ) { 1047const plan = plans . create ( chatId , { title :points . title , steps :points . steps , request :text , source :'goal' , state :'approved' }); 1048onPlan ( chatId , 'approved' , planView ( plan )); 1049return runTurn ({ ...options , goal :{ action :'create' , objective :text }, planRun :{ planId :plan . id } }); 1050} 1051// Any other text is a new goal. One unfinished goal at a time (the Harness's rule): say so in plain words. 1052return runTurn ({ ...options , goal :{ action :'create' , objective :text } }); 1053} 1054 1055// -- /plan ----------------------------------------------------------------------------------------------- 1056 1057/** A short answer in the chat that the page translates (the sentence is in the interface catalog, "values" fill its slots). */ 1058function sayKey ( options , template , values = []) { 1059const { onFrame} = options ; 1060onFrame ({ type :'queued' , requestId :'compact-' + randomUUID () }); 1061onFrame ({ type :'start' , model :'' , contextMax :0 , demo :false , remoteModel :false , agent :true , mode :modeOf ( options . mode ), skills :[] }); 1062onFrame ({ type :'delta' , text :fill ( template , values ), key :template , values}); 1063onFrame ({ type :'done' , finishReason :'stop' , tokensIn :null , tokensOut :null , usageSource :'unavailable' , durationMs :0 }); 1064return { compact :true }; 1065} 1066 1067/** A short answer in the chat (no model): the same frames a turn sends. */ 1068function sayOnce ( options , reply ) { 1069const { onFrame} = options ; 1070onFrame ({ type :'queued' , requestId :`plan- ${ randomUUID ()} ` }); 1071onFrame ({ type :'start' , model :'' , contextMax :0 , demo :false , remoteModel :false , agent :true , mode :modeOf ( options . mode ), skills :[] }); 1072onFrame ({ type :'delta' , text :reply }); 1073onFrame ({ type :'done' , finishReason :'stop' , tokensIn :null , tokensOut :null , usageSource :'unavailable' , durationMs :0 }); 1074return { plan :true }; 1075} 1076 1077/** 1078* "/plan <what you want>": the assistant looks around (the chat is put in Plan mode for this turn, so nothing can change), writes the 1079* plan, and the host sends it as a `plan` frame. Nothing runs until the person approves it. 1080*/ 1081async function planCommand ( options ) { 1082const task = String ( options . line ?? '' ). trim (); 1083if ( ! task ) { 1084const open = plans . get ( options . chatId ); 1085return sayOnce ( options , open && [ 'proposed' , 'approved' ]. includes ( open . state ) 1086 ?'A plan is waiting for you above. Approve it, edit it or reject it, or type /plan followed by something else to make a new one.' 1087 :'Type /plan followed by what you want done, for example: /plan build a small pagoda page. I will look around and write a plan; nothing changes until you approve it.' ); 1088} 1089return runTurn ({ ...options , message :planPrompt ( task ), planTask :task , mode :'plan' }); 1090} 1091 1092/** 1093* "/research <topic>": the assistant searches the web, opens and reads pages, and writes a short structured answer (Summary, Key findings, 1094* Sources). The host also sends the sources as a `research` frame before the end of the turn. Needs web search turned on. 1095*/ 1096async function researchCommand ( options ) { 1097const topic = String ( options . line ?? '' ). trim (); 1098if ( ! topic ) return sayOnce ( options , 'Type /research followed by what you want to know, for example: /research how do heat pumps compare with gas boilers. I will search the web, read the pages and answer with sources.' ); 1099if ( tools ()?. off ?. has ( 'search' )) return sayOnce ( options , 'Research needs web search, which is turned off. Turn it on in Settings, Tools (DuckDuckGo needs no key), then try again.' ); 1100return runTurn ({ ...options , message :researchPrompt ( topic ), researchTopic :topic }); 1101} 1102 1103const planGone = () => new AgentUnavailable ( 'There is no plan waiting in this chat. Ask for one with /plan followed by what you want done.' , 'plan-gone' ); 1104function planOf ( chatId , planId ) { 1105const plan = plans . get ( chatId ); 1106if ( ! plan || ( planId && plan . id !== planId )) throw planGone (); 1107return plan ; 1108} 1109const mustBeOpen = plan => { if ( plan . state !== 'proposed' && plan . state !== 'approved' ) throw new AgentUnavailable ( 'This plan has already been used. Ask for a new one with /plan.' , 'plan-used' ); }; 1110 1111/** A short note added to every step of the chat's plan (the Time-skip B path: where its work comes from). */ 1112function setPlanBriefing ( chatId , text ) { plans . update ( chatId , p => { p . briefing = String ( text ?? '' ). slice ( 0 , 600 ); }); } 1113 1114/** The plan of a chat, or null. */ 1115const planState = chatId => planView ( plans . get ( chatId )); 1116 1117/** Approve, edit or reject the plan; instant. Approve also returns the message that carries the plan out as an ordinary turn. */ 1118function planControl ({ chatId, planId, action, steps, title}) { 1119const plan = planOf ( chatId , planId ); 1120if ( action === 'edit' ) { 1121mustBeOpen ( plan ); 1122const next = editedSteps ( steps , plan . steps ); 1123const t = String ( title ?? '' ). replace ( / \s +/ g , ' ' ). trim (). slice ( 0 , 80 ); 1124plans . update ( chatId , p => { p . steps = next ; if ( t ) p . title = t ; p . state = 'proposed' ; }); 1125onPlan ( chatId , 'edited' , planView ( plans . get ( chatId ))); 1126return { plan :planView ( plans . get ( chatId )) }; 1127} 1128if ( action === 'approve' ) { 1129mustBeOpen ( plan ); 1130plans . update ( chatId , p => { p . state = 'approved' ; }); 1131const approved = plans . get ( chatId ); 1132onPlan ( chatId , 'approved' , planView ( approved )); 1133return { plan :planView ( approved ), prompt :planAsPrompt ( approved ) }; 1134} 1135if ( action === 'reject' ) { 1136mustBeOpen ( plan ); 1137plans . update ( chatId , p => { p . state = 'rejected' ; }); 1138onPlan ( chatId , 'rejected' , planView ( plans . get ( chatId ))); 1139return { plan :planView ( plans . get ( chatId )) }; 1140} 1141throw new AgentUnavailable ( 'That plan action is not known.' , 'plan-action' ); 1142} 1143 1144/** "Start as goal": each step of the plan becomes a goal step, run one after another and reported. Streams like a chat turn. */ 1145async function planGoal ( options ) { 1146const { chatId, planId} = options ; 1147let plan ; 1148try { plan = planOf ( chatId , planId ); } catch ( e ) { return sayOnce ( options , e . message ); } 1149if ( modeOf ( options . mode ) === 'plan' ) return sayOnce ( options , 'Plan mode only looks, so it cannot carry out a plan. Switch this chat to Manual or Bypass, then start it again.' ); 1150if ( plan . state === 'paused' && plan . goalStarted ) return goalCommand ({ ...options , line :'resume' }); 1151try { mustBeOpen ( plan ); } catch ( e ) { return sayOnce ( options , e . message ); } 1152if ( tools ()?. off ?. has ( 'goals' )) return sayOnce ( options , 'Goals are turned off. You can turn them back on in Settings, Tools.' ); 1153plans . update ( chatId , p => { p . state = 'approved' ; }); 1154onPlan ( chatId , 'approved' , planView ( plans . get ( chatId ))); 1155return runTurn ({ ...options , goal :{ action :'create' , objective :plan . title }, planRun :{ planId :plan . id , once :options . once === true } }); 1156} 1157 1158/** A paused plan becomes open again (a step that did not finish is tried again in a fresh session). */ 1159function reopenPlan ( chatId ) { const p = plans . get ( chatId ); if ( p && p . state === 'paused' ) { plans . update ( chatId , x => { x . state = 'approved' ; }); onPlan ( chatId , 'approved' , planView ( plans . get ( chatId ))); } } 1160 1161/** Give up on one step with a plain note (a check that cannot be done here) so the rest of the plan can go on. */ 1162function skipStep ( chatId , index , note ) { plans . update ( chatId , p => { const st = p . steps [ index ]; if ( st ) { st . state = 'skipped' ; st . summary = String ( note ?? 'Skipped.' ). slice ( 0 , 140 ); } if ( p . state === 'paused' ) p . state = 'approved' ; }); onPlan ( chatId , 'step' , planView ( plans . get ( chatId ))); } 1163 1164/** Forget the chat's agent session (not its plan): the next turn starts a fresh one in the same folder. */ 1165function resetSession ( chatId ) { 1166if ( chats . get ( chatId )?. turn || chats . get ( chatId )?. starting ) throw new AgentUnavailable ( 'This chat is still working.' , 'turn-active' ); 1167delete sessionMap [ chatId ]; persist (); 1168} 1169 1170// -- the agent's own questions ------------------------------------------------------------------------------ 1171 1172/** 1173* The person's answer to a question the agent asked (#4244), or a skip. The answer is checked against the questions that were asked, then sent 1174* to the Harness as the result of the waiting `user-questions/request`; a skip declares the question unanswerable, as before, and the model 1175* carries on. 1176*/ 1177async function answerQuestion ({ chatId, callId, answers, skip= false }) { 1178const sessionId = sessionMap [ chatId ]?. sessionId ; 1179const key = ` ${ sessionId } : ${ callId } ` ; 1180const entry = questions . get ( key ); 1181if ( ! entry || ! rt ?. hp . running ) throw new AgentUnavailable ( 'That question was already answered, or the assistant has gone on.' , 'question-gone' ); 1182const outcome = skip ?'next' :buildAnswer ( entry . items , answers ); 1183await rt . gw . answerEvent ({ clientId :entry . clientId ?? rt . clientId , eventId :entry . eventId , outcome}); 1184questions . delete ( key ); 1185return { ok :true , skipped :!! skip }; 1186} 1187 1188// -- a message for a helper --------------------------------------------------------------------------------- 1189 1190/** 1191* The person's own words for one helper (#4749), through the Harness's `subagents/prompt`: it delivers one browser-authored message to a 1192* continuable child through its live parent. "steer" reaches a working helper at its next step; "queue" gives a helper that has finished 1193* (or is between steps) a new turn. The Harness refuses a helper that cannot take messages (a one-shot one) and a parent that is not live; 1194* either comes back as a plain sentence. 1195*/ 1196async function messageHelper ({ chatId, helperId, text, delivery= 'queue' }) { 1197const clean = String ( text ?? '' ). trim (). slice ( 0 , 8000 ); 1198if ( ! clean ) throw new AgentUnavailable ( 'Type a few words for the helper.' , 'helper-empty' ); 1199if ( ! /^ [ \w .:@- ]{ 1 , 160 } $ / . test ( String ( helperId ?? '' ))) throw new AgentUnavailable ( 'That helper is not known.' , 'helper-unknown' ); 1200const parent = sessionMap [ chatId ]?. sessionId ; 1201if ( ! parent || ! rt ?. hp . running ) throw new AgentUnavailable ( 'The assistant is not running in this chat, so it cannot pass a message on. Send a message in the chat first.' , 'helper-idle' ); 1202try { 1203const receipt = await rt . gw . rpc ( 'subagents/prompt' , { request :{ requestId :`helper- ${ randomUUID ()} ` , parentSessionId :parent , childSessionId :String ( helperId ), mode :'continuable' , delivery :delivery === 'steer' ?'steer' :'queue' , content :[{ type :'text' , text :clean }] } }); 1204return { ok :true , messageId :receipt ?. messageId ?? null , delivery :delivery === 'steer' ?'steer' :'queue' }; 1205} catch ( e ) { 1206log ( `agent · message for a helper refused: ${ String ( e ?. message ?? e ). slice ( 0 , 200 )} ` ); 1207throw new AgentUnavailable ( / continuable | one-shot | not. * ( found | live | open ) | unavailable | closed | ended / i . test ( String ( e ?. message ?? '' )) ?'This helper cannot take a message any more. Ask the assistant in the chat to start a new one.' :'The message could not be delivered right now. Try again in a moment.' , 'helper-refused' ); 1208} 1209} 1210 1211// -- messages typed while a goal runs ---------------------------------------------------------------------- 1212 1213/** Queue a message for the running goal. It is delivered between steps, or handed back to the page when the goal ends or pauses. */ 1214function queueMessage ({ chatId, text}) { 1215const turn = chats . get ( chatId )?. turn ; 1216if ( ! turn || ! turn . goalRun || turn . stopping || turn . finished ) throw new AgentUnavailable ( 'No goal is running in this chat, so there is nothing to queue behind. Send the message as usual.' , 'queue-idle' ); 1217const clean = String ( text ?? '' ). trim (). slice ( 0 , 8000 ); 1218if ( ! clean ) throw new AgentUnavailable ( 'Type a few words to queue.' , 'queue-empty' ); 1219const list = queues . get ( chatId ) ?? []; 1220if ( list . length >= 20 ) throw new AgentUnavailable ( 'Twenty messages are already waiting. Wait for some to be delivered.' , 'queue-full' ); 1221const item = { id :randomUUID (), text :clean , at :new Date (). toISOString (), deliverAt :turn . plan ?'step' :'end' }; 1222list . push ( item ); queues . set ( chatId , list ); 1223const message = { id :item . id , text :item . text , at :item . at , deliverAt :item . deliverAt }; 1224onQueue ( chatId , queueView ( chatId )); 1225turn . announceQueue ?.({ type :'queued-message' , state :'queued' , message, queue :queueView ( chatId ) }); 1226return { message, queue :queueView ( chatId ) }; 1227} 1228 1229/** Take a queued message back (the x on it). A message already being delivered cannot be taken back. */ 1230function cancelQueued ({ chatId, id}) { 1231const list = queues . get ( chatId ) ?? []; 1232const at = list . findIndex ( m => m . id === id ); 1233if ( at < 0 ) throw new AgentUnavailable ( 'That message was already sent or removed.' , 'queue-gone' ); 1234const [ item ] = list . splice ( at , 1 ); 1235if ( ! list . length ) queues . delete ( chatId ); 1236onQueue ( chatId , queueView ( chatId )); 1237chats . get ( chatId )?. turn ?. announceQueue ?.({ type :'queued-message' , state :'cancelled' , message :{ id :item . id , text :item . text , at :item . at , deliverAt :item . deliverAt }, queue :queueView ( chatId ) }); 1238return { queue :queueView ( chatId ) }; 1239} 1240 1241/** Messages waiting for a chat, and (after a goal ended while the page was away) the ones it should now send. */ 1242function takeQueue ( chatId , { release= false } = {}) { 1243const turn = chats . get ( chatId )?. turn ; 1244const list = queueView ( chatId ); 1245if ( release && ! turn && list . length ) { queues . delete ( chatId ); onQueue ( chatId , []); return { queue :[], released :list . map (({ id, text}) => ({ id, text})) }; } 1246return { queue :list , released :[] }; 1247} 1248 1249/** 1250* The person changed the chat's mode while a turn (a goal and its helpers included) is running. The new preset 1251* is put on the session at once, the running turn's own bookkeeping follows, and questions already waiting are 1252* settled the way the new mode would have settled them: Bypass allows them, Plan rejects them. 1253*/ 1254async function setMode ( chatId , mode ) { 1255const want = modeOf ( mode ); 1256const c = chats . get ( chatId ); 1257const sessionId = sessionMap [ chatId ]?. sessionId ; 1258if ( ! rt || ! sessionId ) return { applied :false , mode :want , reason :'no session yet' }; 1259if ( c ?. turn && c . turn . mode === want ) return { applied :true , mode :want , settled :0 }; 1260await applyMode ( rt , sessionId , want ); 1261let settled = 0 ; 1262if ( c ?. turn ) { 1263c . turn . mode = want ; 1264c . turn . projector . policy = MODE_PRESETS [ want ]. approval ; 1265if ( want !== 'manual' ) { 1266const helpers = c . turn . children ; 1267for ( const [ key , entry ] of [ ...pending . entries ()]) { 1268if ( entry . sessionId !== sessionId && ! helpers ?. has ( entry . sessionId )) continue ; 1269pending . delete ( key ); 1270try { await rt . gw . answerEvent ({ clientId :entry . clientId ?? rt . clientId , eventId :entry . eventId , outcome :want === 'bypass' ?'allowed-once' :'rejected' }); settled ++ ; } catch { /* already answered */ } 1271} 1272} 1273} 1274return { applied :true , mode :want , settled}; 1275} 1276 1277/** Answer one pending approval. `decision` is `approve` or `deny`. */ 1278async function approve ({ chatId, callId, decision}) { 1279const sessionId = sessionMap [ chatId ]?. sessionId ; 1280// A helper agent's question carries the helper's session id in front of its call id. Only a helper that belongs to 1281// THIS chat's run can be answered from this chat. 1282const [ maybeChild ] = String ( callId ). split ( ':' ); 1283const ownHelper = callId . includes ( ':' ) && chats . get ( chatId )?. turn ?. children . has ( maybeChild ); 1284const key = ownHelper ?callId :` ${ sessionId } : ${ callId } ` ; 1285// The durable `approval/asked` (which makes the card say "needs approval") and the waterfall frame 1286// (which makes it answerable) travel on different streams; a fast click can beat the second one. 1287let entry = sessionId ?pending . get ( key ) :null ; 1288for ( let i = 0 ; ! entry && sessionId && i < 40 ; i ++ ) { 1289await new Promise ( r => setTimeout ( r , 50 )); 1290entry = pending . get ( key ); 1291} 1292if ( ! entry ) throw new AgentUnavailable ( 'That question is no longer waiting for an answer.' , 'approval-gone' ); 1293if ( ! rt ?. hp . running ) throw new AgentUnavailable ( 'That question expired because the coding assistant restarted. Ask again.' , 'approval-gone' ); 1294pending . delete ( key ); 1295try { 1296await rt . gw . answerEvent ({ clientId :entry . clientId ?? rt . clientId , eventId :entry . eventId , outcome :decision === 'approve' ?'allowed-once' :'rejected' }); 1297} catch ( e ) { 1298throw new AgentUnavailable ( 'Your answer could not be delivered. Ask again.' , 'approval-gone' , e . message ); 1299} 1300return { ok :true }; 1301} 1302 1303/** 1304* Stop one chat's turn. Resolves only once the turn has ended (or the wait times out), because the 1305* Harness acknowledges a cancel as admitted, not as done. 1306*/ 1307/** What the chat holds now and the model's window, as the context plugin measures them (null when it cannot be read). */ 1308async function contextOf ( runtime , sessionId ) { 1309try { 1310const r = await runtime . gw . rpc ( 'commands/execute' , { agentId :sessionId , line :'/strata-context' , submittedAttachments :[] }); 1311if ( r ?. result ?. kind !== 'success' ) return null ; 1312const v = JSON . parse ( String ( r . result . text )); 1313return Number . isFinite ( v . tokens ) ?{ tokens :Math . round ( v . tokens ), window :Number ( v . window ) > 0 ?Math . round ( v . window ) :0 } :null ; 1314} catch { return null ; } 1315} 1316 1317/** The decision of context-fit.mjs for the message about to be sent, or null when the model server cannot count it. */ 1318async function fitCheck ({ runtime, route, sessionId, fresh, history, message}) { 1319const inst = localInstances (). find ( i => i . id === route . instanceId ); 1320if ( ! inst || ! ( route . contextWindow > 0 )) return null ; 1321const carried = fresh && history . length ?withEarlierConversation ( history , message ) :message ; 1322if ( carried . length < COUNT_ABOVE_CHARS ) return null ; 1323const count = text => countTokens ({ baseUrl :inst . baseUrl , key :inst . key , model :inst . modelId , text}); 1324let tokens = await count ( carried ); 1325if ( tokens == null ) return null ; 1326const now = fresh ?null :await contextOf ( runtime , sessionId ); 1327const window = now ?. window || route . contextWindow ; 1328const pressure = now ?. tokens ?? 0 ; 1329// Where the Harness starts summarising by itself on this window (profile.mjs: the reply keeps its room, then the headroom). 1330const reply = localOutputBudget ( window ); 1331const threshold = Math . floor ( Math . min ( window * 0.8 , window - reply - compactionHeadroom ( window , reply ))); 1332let verdict = decideFit ({ window, pressure, messageTokens :tokens , threshold}); 1333// The earlier conversation carried into a fresh session is what pushed it over: send the message alone instead. 1334if ( verdict . action === 'too-large' && carried !== message ) { 1335const alone = await count ( message ); 1336if ( alone != null ) { tokens = alone ; verdict = decideFit ({ window, pressure, messageTokens :alone , threshold}); } 1337} 1338return { ...verdict , tokens, window, pressure}; 1339} 1340 1341/** 1342* Summarise the older part of a chat with the Harness's /compact and say what happened. Never throws. 1343* ok:true carries the figures before and after; ok:false says why (nothing to summarise, busy, failed). 1344*/ 1345async function compactChat ( runtime , sessionId ) { 1346const before = await contextOf ( runtime , sessionId ); 1347let result ; 1348try { result = ( await runtime . gw . rpc ( 'commands/execute' , { agentId :sessionId , line :'/compact' , submittedAttachments :[] }))?. result ; } 1349catch ( e ) { return { ok :false , reason :/ not.found | no such / i . test ( String ( e . message )) ?'nothing' :'failed' , before, text :String ( e . message ?? e ) }; } 1350const text = String ( result ?. text ?? '' ); 1351log ( 'agent · compact: ' + ( result ?. kind ?? 'none' ) + ' ' + text . slice ( 0 , 140 )); 1352if ( result ?. kind === 'success' && / ^Compacted / i . test ( text )) return { ok :true , before, after :await contextOf ( runtime , sessionId ) }; 1353if ( result ?. kind === 'success' ) return { ok :false , reason :'nothing' , before, text}; 1354if ( / active compaction | not idle / i . test ( text )) return { ok :false , reason :'busy' , before, text}; 1355// The Harness cannot make a summary smaller than what is left when the chat holds little beyond its first prompt: that is nothing to summarise, not a failure. 1356const little = before && before . window > 0 && before . tokens - BASE_TOKENS < before . window * 0.25 ; 1357return { ok :false , reason :little && / useful summary | not smaller / i . test ( text ) ?'nothing' :'failed' , before, text}; 1358} 1359 1360/** The line in the chat that explains why the context meter fell: how full it was and how full it is. */ 1361function summarizedNote ( before , after , window ) { 1362const w = after ?. window || before ?. window || window || 0 ; 1363const pct = v => Math . max ( 0 , Math . min ( 100 , Math . round ( 100 * v . tokens / w ))); 1364const known = w > 0 && before && after ; 1365const template = known ?FIT_TEXT . summarized :FIT_TEXT . summarizedShort ; 1366const values = known ?[ pct ( before ), pct ( after )] :[]; 1367return { type :'delta' , own :true , text :'\n\n' + fill ( template , values ), key :template , values, noteReason :'compacted' }; 1368} 1369 1370/** "/compact": summarise the older messages of this chat now, and say in plain words what happened. */ 1371async function compactCommand ( options ) { 1372const { chatId, choice, signal} = options ; 1373const c = chat ( chatId ); 1374const say = ( template , values = []) => sayKey ( options , template , values ); 1375if ( c . turn || c . starting ) return say ( FIT_TEXT . compactBusy ); 1376const known = sessionMap [ chatId ]?. sessionId ; 1377if ( ! known ) return say ( FIT_TEXT . noChatYet ); 1378let runtime ; 1379try { ({ rt :runtime } = await ensureRuntime ( choice , signal )); } catch { return say ( FIT_TEXT . compactFailed ); } 1380const done = await compactChat ( runtime , known ); 1381if ( done . ok ) { 1382const note = summarizedNote ( done . before , done . after , 0 ); 1383return say ( note . key , note . values ); 1384} 1385if ( done . reason === 'busy' ) return say ( FIT_TEXT . compactBusy ); 1386if ( done . reason === 'nothing' ) { 1387const w = done . before ?. window || 0 ; 1388const pct = w > 0 && done . before ?Math . round ( 100 * done . before . tokens / w ) :0 ; 1389return say ( pct >= 60 ?FIT_TEXT . nothingFull :FIT_TEXT . nothingToSummarize , pct >= 60 ?[ pct ] :[]); 1390} 1391return say ( FIT_TEXT . compactFailed ); 1392} 1393 1394/** Summarise the older part of a session with the Harness's own /compact. Best effort: the next message compacts again by itself when it must. */ 1395async function compactSession ( runtime , sessionId ) { 1396try { 1397const r = await runtime . gw . rpc ( 'commands/execute' , { agentId :sessionId , line :'/compact' , submittedAttachments :[] }); 1398log ( `agent · compact after a stopped turn: ${ r ?. result ?. kind ?? 'done' } ${ String ( r ?. result ?. text ?? '' ). slice ( 0 , 120 )} ` ); 1399} catch ( e ) { log ( `agent · compact after a stopped turn failed: ${ e . message } ` ); } 1400} 1401 1402async function stop ( chatId , { waitMs= 20_000 } = {}) { 1403const c = chats . get ( chatId ); 1404const turn = c ?. turn ; 1405if ( ! turn && c ?. starting ) { c . cancelStart = true ; return { stopped :true , ended :'cancelled-before-start' , ms :0 }; } 1406if ( ! turn || ! rt ) return { stopped :false , reason :'no active turn' }; 1407const t0 = Date . now (); 1408if ( ! turn . prompted ) { 1409// The Harness has not been given the prompt yet, so there is nothing to cancel there. 1410turn . stopBeforePrompt = true ; 1411const early = await Promise . race ([ turn . ended . promise , new Promise ( r => setTimeout (() => r ( null ), 100 ))]); 1412if ( early ) return { stopped :true , ended :early . reason ?. kind ?? 'aborted' , ms :Date . now () - t0 }; 1413} 1414turn . stopping = true ; 1415await pauseGoal ( rt , turn . sessionId , chatId ); 1416// Helpers first: a helper still working would otherwise report back and wake the parent again. 1417await Promise . allSettled ([ ...turn . children . values ()]. filter ( h => ! h . done ). map ( h => rt . gw . rpc ( 'subagents/interruptByParent' , { childSessionId :h . id , parentSessionId :turn . sessionId , mode :'continuable' }))); 1418await rt . gw . rpc ( 'session/cancel' , { request :{ sessionId :turn . sessionId } }). catch ( e => { if ( turn . parentOpen ) throw e ; }); 1419// Nothing is running in the parent (it was waiting for its helpers): the run ends once they are all down. 1420if ( ! turn . parentOpen ) { clearTimeout ( turn . settleTimer ); turn . settleTimer = after ( 300 , () => { if ( ! turn . finished && ! turn . parentOpen && [ ...turn . children . values ()]. every ( h => h . done )) turn . finish ( null ); }); } 1421let timer ; const result = await Promise . race ([ turn . ended . promise , new Promise ( r => { timer = after ( waitMs , () => r ( null )); })]); 1422clearTimeout ( timer ); 1423if ( ! result ) return { stopped :false , pending :true , reason :'the turn is still stopping' }; 1424return { stopped :true , ended :result . reason ?. kind ?? 'unknown' , ms :Date . now () - t0 }; 1425} 1426 1427/** The turn running for a chat now, for a page that has just loaded; null when none. */ 1428function turnOf ( chatId ) { 1429const t = chats . get ( chatId )?. turn ; 1430if ( ! t || t . finished ) return null ; 1431return { chatId, sessionId :t . sessionId , requestId :t . requestId , mode :t . mode , stopping :!! t . stopping , pending :pendingFor ( chatId ) }; 1432} 1433/** Every chat with a turn running. */ 1434function runningTurns () { return [ ...chats . keys ()]. map ( turnOf ). filter ( Boolean ); } 1435/** 1436* Take a turn over from a new page. A running turn: the catch-up, then the live frames until it ends or the page leaves again. A turn that 1437* ended while no page was there (`requestId` names it): its text, tool cards and closing frame once. null when there is nothing to take over. 1438*/ 1439function attach ({ chatId, requestId= null , onFrame, signal}) { 1440const c = chats . get ( chatId ); 1441const turn = c ?. turn ; 1442if ( turn && ! turn . finished && typeof turn . reattach === 'function' ) { 1443if ( requestId && turn . requestId !== requestId ) return null ; 1444turn . reattach ({ onFrame, signal}); 1445return { ended :turn . ended . promise . then (() => undefined ), live :true }; 1446} 1447const last = c ?. last ; 1448if ( ! last || ! requestId || last . requestId !== requestId ) return null ; 1449onFrame ({ type :'start' , model :last . model , contextMax :last . contextMax , demo :false , remoteModel :last . remoteModel , agent :true , mode :last . mode , sessionId :last . sessionId , requestId :last . requestId , skills :[], resumed :true }); 1450onFrame ({ type :'resync' , content :last . content , reasoning :last . reasoning }); 1451for ( const card of last . cards ) onFrame ({ type :'agent-tool' , tool :card }); 1452if ( last . terminal ) onFrame ( last . terminal ); 1453return { ended :Promise . resolve (), live :false }; 1454} 1455function pendingFor ( chatId ) { 1456const sessionId = sessionMap [ chatId ]?. sessionId ; 1457const helpers = chats . get ( chatId )?. turn ?. children ; 1458return [ ...pending . values ()]. filter ( p => p . sessionId === sessionId || helpers ?. has ( p . sessionId )) 1459. map ( p => ( p . sessionId === sessionId ?p :{ ...p , callId :` ${ p . sessionId } : ${ p . callId } ` })). map (({ callId, tool, reason, at}) => ({ callId, tool, reason, at})); 1460} 1461 1462/** Every chat that has an approval waiting, for the task board: the chat, its working folder and what is waiting (same items as pendingFor). */ 1463function pendingAll () { 1464if ( ! pending . size ) return []; 1465return Object . keys ( sessionMap ). map ( chatId => ({ chatId, folder :sessionMap [ chatId ]?. cwd ?? null , pending :pendingFor ( chatId ) })). filter ( c => c . pending . length ); 1466} 1467 1468async function close () { 1469const r = rt ; rt = null ; 1470if ( r ) { r . events ?. close (); r . gw . close (); await r . hp . stop (); } 1471} 1472 1473/** Let go of a chat's Harness session mapping (a task starts every run in a session of its own). */ 1474function forget ( chatId ) { if ( chats . get ( chatId )?. turn ) return ; delete sessionMap [ chatId ]; chats . delete ( chatId ); persist (); } 1475 1476return { compactCommand, messageHelper, answerQuestion, goalState, goalControl, harnessDir, status, turnOf, runningTurns, attach, runTurn, goalCommand, planCommand, researchCommand, llmTarget, setPlanBriefing, resetSession, reopenPlan, skipStep, planGoal, planControl, planState, queueMessage, cancelQueued, takeQueue, forget, approve, setMode, stop, pendingFor, pendingAll, close, sessionOf :chatId => sessionMap [ chatId ]?. sessionId ?? null , workingFolder :chatId => sessionMap [ chatId ]?. cwd ?? null , isRunning :chatId => !! chats . get ( chatId )?. turn , _debug :() => ({ rt, sessionMap}) }; 1477} 1478 1479/** A goal that stopped by itself, in words. */ 1480export function plainBlocker ( reason ) { 1481if ( ! reason ) return 'it could not go on.' ; 1482if ( reason . code === 'round-limit' ) return 'it worked for the most steps it was allowed. Type /goal clear, then start a new goal to go on.' ; 1483return String ( reason . message ?? 'it could not go on.' ); 1484} 1485 1486/** What a goal run says when it ends. */ 1487export function goalEnding ( view ) { 1488if ( view . phase === 'complete' ) return '\n\n*The goal is complete.*' ; 1489if ( view . phase === 'blocked' ) return `\n\n*The goal stopped: ${ plainBlocker ( view . blockedReason )} *` ; 1490if ( view . phase === 'paused' ) return '\n\n*The goal is paused. Type /goal resume to go on.*' ; 1491return '' ; 1492} 1493 1494/** A goal request the Harness refused, as a sentence. */ 1495export function plainGoalError ( e ) { 1496const message = String ( e ?. message ?? e ); 1497if ( / already | unfinished | current goal / i . test ( message )) return 'This chat already has a goal that is not finished. Type /goal edit to change it, /goal clear to remove it, or /goal to see it.' ; 1498if ( / GOAL_NONE | no goal / i . test ( message ) || e ?. code === 'goal-none' ) return 'There is no goal to continue. Start one with /goal followed by what you want done.' ; 1499if ( / objective / i . test ( message )) return 'A goal needs a few words about what you want done, for example: /goal make every test pass.' ; 1500return 'The goal could not be changed right now. Try again in a moment.' ; 1501} 1502 1503/** The Harness session of a chat that existed before the agent did knows nothing; carry a bounded summary. */ 1504export function withEarlierConversation ( history , message ) { 1505const rows = history . filter ( m => ( m . role === 'user' || m . role === 'assistant' ) && typeof m . content === 'string' && m . content . trim ()). slice ( - 12 ); 1506if ( ! rows . length ) return message ; 1507const text = rows . map ( m => ` ${ m . role } : ${ m . content . length > 1500 ? ` ${ m . content . slice ( 0 , 1499 )} …` : m . content } ` ). join ( '\n' ); 1508return `Earlier in this conversation, before you were given tools:\n ${ text } \n\nCurrent message:\n ${ message } ` ; 1509}