okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
fcb0c2d0e
main
1/** 2* Plans (the /plan command) and goal points, as the host sees them. Pure helpers plus a small store; the bridge drives them. 3* 4* A plan is a short numbered list the assistant wrote after looking around (the chat was in Plan mode: nothing could change). The 5* person approves it, edits it, rejects it, or starts it as a goal whose steps are the plan's steps. A /goal whose text already has 6* numbered points ("1. ... 2. ... 3. ...") is run the same way, so a point is a step and each one is reported. 7* 8* Plan shape (also what the page renders, notes-split-agent6.md): 9* { id, chatId, title, request, source: 'plan'|'goal', state, steps: [{ id, text, detail, state, summary }], createdAt, updatedAt, goalStarted } 10* plan.state: proposed | approved | rejected | running | paused | done | stopped 11* step.state: pending | running | done | failed | skipped 12*/ 13 14import { randomUUID } from 'node:crypto' ; 15import { existsSync , mkdirSync , readFileSync , renameSync , writeFileSync } from 'node:fs' ; 16import { dirname } from 'node:path' ; 17 18export const MAX_STEPS = 12 ; 19const MAX_TEXT = 140 ; 20const MAX_DETAIL = 220 ; 21 22const clean = s => String ( s ?? '' ). replace ( / \*\* | __ | ` / g , '' ). replace ( / \s +/ g , ' ' ). trim (); 23const clip = ( s , n ) => ( s . length > n ?s . slice ( 0 , n - 1 ). trimEnd () + '…' :s ); 24 25/** "Write the file — one file, inline styles" into { text, detail }. */ 26function splitStep ( raw ) { 27const s = clean ( raw ). replace ( / ^ (?: step\s * \d + \s * [: .\- ] \s * ) / i , '' ); 28const at = s . search ( / \s [ —– ] \s | \s-\s | :\s / ); 29const head = at > 8 ?s . slice ( 0 , at ) :s ; 30const rest = at > 8 ?s . slice ( at ). replace ( / ^\s * [ —–: \- ] \s */ , '' ) :'' ; 31return { text :clip ( head . replace ( / [ .;: ] + $ / , '' ), MAX_TEXT ), detail :clip ( rest , MAX_DETAIL ) }; 32} 33 34/** The instruction a plan turn gets in front of the person's request. */ 35export function planPrompt ( task ) { 36return [ 37'Make a plan for the request below. Do not change anything: you may only look (read files, list folders, search).' , 38'When you have looked enough, end your reply with the plan as a numbered list: one short line per step, in the order they should be done.' , 39'Put a short heading line right before the list, like "## Pagoda page" (two to five words that name the plan).' , 40'You may add the reason after a dash. Use 3 to 8 steps. Write nothing after the list.' , 41'' , 42`Request: ${ task } ` , 43]. join ( '\n' ); 44} 45 46/** 47* The plan in a reply: its last run of numbered lines (at least two). Lines that follow a step and are indented or bulleted are that 48* step's detail. Returns null when the reply holds no list, so the page shows the reply as it is and never a made-up plan. 49*/ 50export function parsePlan ( text , request = '' ) { 51const lines = String ( text ?? '' ). replace ( / \r / g , '' ). split ( '\n' ); 52const item = / ^\s { 0 , 3 }(?: step\s + ) ? ( \d { 1 , 2 })[ .): ] \s + ( \S. * ) $ / i ; 53const runs = []; 54let run = null ; 55lines . forEach (( line , i ) => { 56const m = item . exec ( line ); 57if ( m ) { 58const n = Number ( m [ 1 ]); 59if ( run && n === run . items . length + 1 ) { run . items . push ({ raw :m [ 2 ], extra :[] }); run . end = i ; return ; } 60if ( n === 1 ) { run = { start :i , end :i , items :[{ raw :m [ 2 ], extra :[] }] }; runs . push ( run ); return ; } 61run = null ; return ; 62} 63if ( run && / ^\s + \S / . test ( line )) { run . items . at ( - 1 ). extra . push ( clean ( line . replace ( / ^\s * [ -*• ] \s */ , '' ))); run . end = i ; return ; } 64if ( run && / ^\s * [ -*• ] \s + \S / . test ( line )) { run . items . at ( - 1 ). extra . push ( clean ( line . replace ( / ^\s * [ -*• ] \s */ , '' ))); run . end = i ; return ; } 65if ( run && line . trim () === '' ) return ; 66run = null ; 67}); 68const best = runs . filter ( r => r . items . length >= 2 ). at ( - 1 ); 69if ( ! best ) return null ; 70const steps = best . items . slice ( 0 , MAX_STEPS ). map (( it , k ) => { 71const { text :t , detail} = splitStep ( it . raw ); 72const extra = clip ( it . extra . join ( ' ' ), MAX_DETAIL ); 73return { id :`s ${ k + 1 } ` , text :t , detail :detail || extra , state :'pending' , summary :null }; 74}). filter ( s => s . text ); 75if ( steps . length < 2 ) return null ; 76let title = '' ; 77for ( let i = best . start - 1 ; i >= 0 && i >= best . start - 6 ; i -- ) { 78const h = / ^\s * # { 1 , 6 } \s + ( . + ? ) \s * $ / . exec ( lines [ i ]); 79if ( h ) { title = clean ( h [ 1 ]); break ; } 80} 81return { title :clip ( title || clean ( request ) || 'Plan' , 80 ), steps}; 82} 83 84/** Numbered points inside a goal's own words ("1. a 2. b" on lines or in one line); at least two, counting up from 1. */ 85export function parsePoints ( objective ) { 86const text = String ( objective ?? '' ). replace ( / \r / g , '' ); 87const found = []; 88const re = / (?: ^ | \s )( \d { 1 , 2 })[ .) ] \s +/ g ; 89let m ; const marks = []; 90while (( m = re . exec ( text ))) marks . push ({ n :Number ( m [ 1 ]), at :m . index , after :m . index + m [ 0 ]. length }); 91let want = 1 ; let start = - 1 ; 92const seq = []; 93for ( const k of marks ) { 94if ( k . n === want ) { if ( want === 1 ) start = seq . length ; seq . push ( k ); want ++ ; } 95else if ( k . n === 1 ) { seq . length = 0 ; seq . push ( k ); want = 2 ; } 96} 97if ( seq . length < 2 ) return null ; 98seq . forEach (( k , i ) => found . push ( clean ( text . slice ( k . after , i + 1 < seq . length ?seq [ i + 1 ]. at :undefined )))); 99const aim = clean ( text . slice ( 0 , seq [ 0 ]. at )). replace ( / [: \-–— ] + $ / , '' ). trim (); 100const steps = found . slice ( 0 , MAX_STEPS ). map (( t , k ) => { 101const { text :s , detail} = splitStep ( t ); 102return { id :`s ${ k + 1 } ` , text :s , detail, state :'pending' , summary :null }; 103}). filter ( s => s . text ); 104if ( steps . length < 2 ) return null ; 105return { title :clip ( aim || steps [ 0 ]. text , 80 ), steps}; 106} 107 108/** A step that is about looking at the result in a browser or window: it must never hang or fail a whole run on a machine with no screen. */ 109export const isViewStep = text => / \b ( open | view | launch | preview | look at | check | confirm | verify ) \b [ ^ \n ]{ 0 , 60 } \b ( browser | in chrome | in edge | in firefox | window | on screen ) \b / i . test ( String ( text ?? '' )); 110 111/** The goal the Harness runs for step `index` (0-based): one step, with the aim and the steps around it named. */ 112export function stepObjective ( plan , index ) { 113const n = plan . steps . length ; const s = plan . steps [ index ]; 114const done = plan . steps . slice ( 0 , index ). map (( x , i ) => ` ${ i + 1 } . ${ x . text } ${ x . summary ? ' (' + String ( x . summary ). slice ( 0 , 100 ) + ')' : '' } ` ). join ( '; ' ); 115return [ 116`Overall aim: ${ plan . title } .` , 117`You are on step ${ index + 1 } of ${ n } : ${ s . text } ${ s . detail ? ` ( ${ s . detail } )` : '' } .` , 118done ?`Already done: ${ done } .` :'' , 119plan . briefing ?String ( plan . briefing ) :'' , 120isViewStep ( s . text ) ?'This step is about seeing the result. To show a local image, SVG, HTML page or PDF, use the present tool (a browser cannot open file:// addresses). Never wait for a program to close. If a person is at this computer and you start a browser, start it so the command returns at once (Windows: Start-Process; macOS: open; Linux: xdg-open) and say only that you started it, not that the page rendered. If there is no screen, check the page without a visible window: use the headless browser tool if you have one, otherwise read the file and its script for mistakes, and say in one plain sentence what you could and could not check. Then finish the step.' :'' , 121'Do only this step, check that it worked, and then finish the goal.' , 122index + 1 < n ?'The next steps are handled separately: do not start them.' :'' , 123]. filter ( Boolean ). join ( ' ' ); 124} 125 126const WORD = { started :'started' , done :'done' , failed :"didn't finish" , stopped :'stopped' , skipped :'skipped' }; 127/** One short friendly line for a step: "Write the roof — done" (no step counter: the owner removed it). */ 128export function stepLine ( index , total , text , state ) { 129return ` ${ clip ( clean ( text ), 90 )} — ${ WORD [ state ] ?? state } ` ; 130} 131 132/** The short summary of a step from the words it closed with: the first sentence, plain. */ 133export function firstSentence ( text , max = 140 ) { 134const s = clean ( String ( text ?? '' ). replace ( / ^# + \s. * $ / gm , '' ). replace ( / ^ [ -* ] \s +/ gm , '' )); 135if ( ! s ) return null ; 136const m = / ^ ( . { 12 ,} ? [ .!? ])(?: \s | $ ) / . exec ( s ); 137return clip ( m ?m [ 1 ] :s , max ); 138} 139 140/** 141* The short summary of a finished step: what it changed (from the tool cards: "Wrote pagoda.html, Changed style.css"), else the first 142* sentence of its closing words when that reads as a result. A sentence about what is NOT done, or about later steps, is never a summary. 143*/ 144export function stepSummary ( cards , closing ) { 145const done = []; 146for ( const c of cards ?? []) { 147const verb = / ^ ( Wrote | Changed | Created | Edited | Deleted | Removed | Moved | Renamed ) \b / . exec ( String ( c ?. verb ?? '' ))?.[ 1 ]; 148const target = String ( c ?. target ?? '' ). split ( / [ \\ / ] / ). filter ( Boolean ). at ( - 1 ); 149if ( ! verb || ! target ) continue ; 150const line = verb + ' ' + clip ( target , 40 ); 151if ( ! done . includes ( line )) done . push ( line ); 152} 153if ( done . length ) return clip ( done . slice ( 0 , 3 ). join ( ', ' ) + ( done . length > 3 ?' and more' :'' ), 140 ); 154const s = firstSentence ( closing ); 155return s && ! /not done | not yet | remaining | handled separately | next steps ?| later steps ?| still (?: need | to ) | todo / i . test ( s ) ?s :null ; 156} 157 158/** The words a person sees for the plan, as one message the model can carry out (the plain Approve path). */ 159export function planAsPrompt ( plan ) { 160return [ 'Carry out this plan, step by step, and tell me briefly when each step is done.' , '' , plan . title ?`Plan: ${ plan . title } ` :'' , ...plan . steps . map (( s , i ) => ` ${ i + 1 } . ${ s . text } ${ s . detail ? ` ( ${ s . detail } )` : '' } ` )]. filter (( l , i ) => l !== '' || i === 1 ). join ( '\n' ); 161} 162 163/** A step list from the person's edit: texts only, validated and capped. Throws a plain sentence for an unusable list. */ 164export function editedSteps ( input , previous = []) { 165if ( ! Array . isArray ( input )) throw Object . assign ( new Error ( 'A plan needs a list of steps.' ), { code :'plan-steps' }); 166const steps = input . map (( x , k ) => { 167const text = clip ( clean ( typeof x === 'string' ?x :x ?. text ), MAX_TEXT ); 168const detail = clip ( clean ( typeof x === 'string' ?'' :x ?. detail ), MAX_DETAIL ); 169const kept = previous . find ( p => p . id === x ?. id ); 170return text ?{ id :kept ?. id ?? `s ${ k + 1 } ` , text, detail, state :'pending' , summary :null } :null ; 171}). filter ( Boolean ). slice ( 0 , MAX_STEPS ); 172if ( ! steps . length ) throw Object . assign ( new Error ( 'A plan needs at least one step.' ), { code :'plan-steps' }); 173// ids must be unique and in order of the list 174steps . forEach (( s , i ) => { s . id = `s ${ i + 1 } ` ; }); 175return steps ; 176} 177 178/** The latest plan of each chat, kept in memory and in one small file so a restart does not lose a proposal. */ 179export class PlanStore { 180constructor ( file = null ) { 181this . file = file ; this . plans = new Map (); 182if ( file && existsSync ( file )) { 183try { for ( const p of JSON . parse ( readFileSync ( file , 'utf8' ))) if ( p ?. chatId ) this . plans . set ( p . chatId , p ); } catch { /* a damaged file starts empty */ } 184} 185} 186 #save() { 187if ( ! this . file ) return ; 188try { 189mkdirSync ( dirname ( this . file ), { recursive :true }); 190const tmp = this . file + '.tmp' ; 191writeFileSync ( tmp , JSON . stringify ([ ...this . plans . values ()])); 192renameSync ( tmp , this . file ); 193} catch { /* the plan still lives in memory */ } 194} 195get ( chatId ) { return this . plans . get ( chatId ) ?? null ; } 196create ( chatId , { title, steps, request= '' , source= 'plan' , state= 'proposed' , caution= null }) { 197const now = new Date (). toISOString (); 198const plan = { id :randomUUID (), chatId, title, request, source, state, steps, createdAt :now , updatedAt :now , goalStarted :false , ...( caution ?{ caution} :{}) }; 199this . plans . set ( chatId , plan ); this . #save(); 200return plan ; 201} 202update ( chatId , fn ) { 203const plan = this . plans . get ( chatId ); 204if ( ! plan ) return null ; 205fn ( plan ); plan . updatedAt = new Date (). toISOString (); 206this . #save(); 207return plan ; 208} 209clear ( chatId ) { this . plans . delete ( chatId ); this . #save(); } 210} 211 212/** What the page gets: a copy with no host-only fields. */ 213export const planView = plan => ( plan ?JSON . parse ( JSON . stringify ( plan )) :null ); 214 215// ---- /research ------------------------------------------------------------------------------------------------------------------ 216 217/** The first research prompt: find and read pages, take notes. What the assistant writes here is not shown; the answer is written in a second step. */ 218export function researchPrompt ( topic ) { 219return [ 220`Research task: ${ topic } ` , 221'' , 222'Do these steps in order. Do not skip a step.' , 223'1. Call web_search to find pages about the task.' , 224'2. Call web_fetch to open at least two of the pages you found, and read them. Do not rely on the search results alone.' , 225'3. When you have read them, reply with short notes: the facts you found, each with the web address of the page it came from.' , 226]. join ( '\n' ); 227} 228 229/** Sent when the assistant answered without opening pages. */ 230export const RESEARCH_NUDGE = 'You have not opened enough pages yet. Call web_fetch now on at least two of the pages from your search, read them, then reply with short notes and the web address of each page.' ; 231 232/** The second research prompt: write the answer in the fixed shape. */ 233export function researchWritePrompt ( topic ) { 234return [ 235`Now write the final answer to the research task: ${ topic } ` , 236'Use only what you read on the pages. Do not call any tool. Start your reply with the line "## Summary" and use exactly these three headings:' , 237'## Summary' , 238'Three to five sentences, in plain words. If the sources disagree or something could not be found, say so.' , 239'## Key findings' , 240'- One finding per line, each ending with its source number in square brackets, like [1].' , 241'## Sources' , 242'1. Page title - web address' , 243'2. Page title - web address' , 244'List only pages you opened.' , 245]. join ( '\n' ); 246} 247 248/** The numbered sources at the end of a research answer: [{ n, title, url }]. Empty when there are none. */ 249export function parseSources ( text ) { 250const lines = String ( text ?? '' ). replace ( / \r / g , '' ). split ( '\n' ); 251const at = lines . map ( l => / ^\s { 0 , 3 } # { 1 , 6 } \s * sources\b / i . test ( l ) || / ^\s * \* { 0 , 2 } sources\* { 0 , 2 } : ? \s * $ / i . test ( l )). lastIndexOf ( true ); 252if ( at < 0 ) return linkSources ( text ); 253const out = []; 254for ( const line of lines . slice ( at + 1 )) { 255if ( / ^\s { 0 , 3 } # { 1 , 6 } \s / . test ( line )) break ; 256const url = / ( https ? :\/\/ [ ^ \s )> \] "' ] + ) / . exec ( line )?.[ 1 ]?. replace ( / [ .,; ] + $ / , '' ); 257if ( ! url ) continue ; 258const md = / \[ ([ ^ \] ] + ) \]\(https ? :\/\/ / . exec ( line ); 259const before = line . slice ( 0 , line . indexOf ( url )). replace ( / ^\s * (?: \d + [ .) ] | [ -*• ]) \s */ , '' ). replace ( / [ \s\- –—:(<[ ] + $ / , '' ). replace ( / \*\* | ` / g , '' ). trim (); 260const title = clean ( md ?.[ 1 ] ?? before ) || (() => { try { return new URL ( url ). hostname ; } catch { return url ; } })(); 261if ( ! out . some ( s => s . url === url )) out . push ({ n :out . length + 1 , title :clip ( title , 120 ), url}); 262} 263return out . slice ( 0 , 20 ); 264} 265 266/** No Sources section: the pages the answer links to, in the order they appear, so the page can still list where it came from. */ 267function linkSources ( text ) { 268const out = []; 269const re = / \[ ([ ^ \] ]{ 1 , 160 }) \]\( ( https ? :\/\/ [ ^ \s ) ] + ) \) | ( https ? :\/\/ [ ^ \s )> \] "' ] + ) / g ; 270let m ; 271while (( m = re . exec ( String ( text ?? '' ))) && out . length < 8 ) { 272const url = ( m [ 2 ] ?? m [ 3 ]). replace ( / [ .,; ] + $ / , '' ); 273if ( out . some ( x => x . url === url )) continue ; 274let host = url ; try { host = new URL ( url ). hostname ; } catch { /* keep the address */ } 275out . push ({ n :out . length + 1 , title :clip ( clean ( m [ 1 ] ?? '' ) || host , 120 ), url}); 276} 277return out ; 278}