okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
e82c70698
main
1import { api } from './client' ; 2import type { PreviewArtifact } from './artifacts' ; 3import { tidyAnswer } from './answer-text' ; 4 5/** 6* Deliverables and grouped activity (notes-split-agent8.md, item 12). The host sends `deliverable` frames for every file the assistant wrote or 7* changed and `activity-group` frames for runs of tool use between two pieces of text. A reply keeps them in the order they came, so the text 8* that arrives between activities reads as one continuous piece. 9*/ 10export type DeliverableKind = 'html' | 'markdown' | 'pdf' | 'csv' | 'image' | 'code' | 'text' | 'other' ; 11export interface Deliverable { path :string ; abs :string ; name :string ; kind :DeliverableKind ; status :'created' | 'changed' ; size :number ; lines :number | null ; added :number ; removed :number ; 12/** Which write came last in this reply (set when the host's frames are merged): the newest is the run's main result. */ order ?:number } 13export interface GroupFile { path :string ; name :string ; kind :DeliverableKind ; status :string ; added :number ; removed :number } 14/** What is happening in a run right now (the host sends it while the group is open and drops it when the group closes): `label` is the step in plain words 15* ("Writing pagoda.html"), `output` the last line the step printed or the progress it can name ("412 lines written"). Optional: a group without it draws as before. */ 16export interface GroupLive { label ?:string ; output ?:string ; 17/** A file being written right now (from `message.drafts`): characters so far, lines so far and the last lines of the text. */ 18bytes ?:number ; lines ?:number ; tail ?:string } 19export interface ActivityGroup { id :string ; closed :boolean ; line :string ; added :number ; removed :number ; files :GroupFile []; live ?:GroupLive } 20export type MessageBlock = { kind :'text' ; text :string } | ({ kind :'group' } & ActivityGroup ); 21 22const KINDS = [ 'html' , 'markdown' , 'pdf' , 'csv' , 'image' , 'code' , 'text' , 'other' ]; 23const num = ( v :unknown ) => ( Number . isFinite ( Number ( v )) ?Number ( v ) :0 ); 24 25export function readDeliverable ( raw :unknown ) :Deliverable | null { 26if ( ! raw || typeof raw !== 'object' ) return null ; 27const f = raw as Record < string , unknown >; 28if ( typeof f . path !== 'string' || ! f . path ) return null ; 29const name = typeof f . name === 'string' && f . name ?f . name :f . path . split ( / [\\/] / ). at ( - 1 ) ?? f . path ; 30return { 31path :f . path , abs :typeof f . abs === 'string' ?f . abs :f . path , name, kind :KINDS . includes ( String ( f . kind )) ?f . kind as DeliverableKind :'other' , 32status :f . status === 'changed' ?'changed' :'created' , size :num ( f . size ), lines :f . lines === null || f . lines === undefined ?null :num ( f . lines ), added :num ( f . added ), removed :num ( f . removed ), 33}; 34} 35 36export function readGroup ( raw :unknown ) :ActivityGroup | null { 37if ( ! raw || typeof raw !== 'object' ) return null ; 38const g = raw as Record < string , unknown >; 39if ( typeof g . id !== 'string' || ! g . id ) return null ; 40const files = Array . isArray ( g . files ) ?g . files . flatMap (( x ) :GroupFile [] => { 41const d = readDeliverable ( x ); 42return d ?[{ path :d . path , name :d . name , kind :d . kind , status :d . status , added :d . added , removed :d . removed }] :[]; 43}) :[]; 44const liveRaw = g . live && typeof g . live === 'object' ?g . live as Record < string , unknown > :null ; 45const last = ( text :string ) => text . trim (). split ( / \r?\n / ). at ( - 1 ) ! . slice ( 0 , 200 ); 46const live :GroupLive | undefined = liveRaw && g . closed !== true ?{ ...( typeof liveRaw . label === 'string' && liveRaw . label ?{ label :liveRaw . label . slice ( 0 , 160 ) } :{}), ...( typeof liveRaw . output === 'string' && liveRaw . output . trim () ?{ output :last ( liveRaw . output ) } :{}) } :undefined ; 47return { id :g . id , closed :g . closed === true , line :typeof g . line === 'string' ?g . line :'' , added :num ( g . added ), removed :num ( g . removed ), files, ...( live && ( live . label || live . output ) ?{ live} :{}) }; 48} 49 50/** The `skills-used` frame: the skills this reply used, each with the name the person gave it and a one-line description. */ 51export function readSkills ( raw :unknown ) :{ name :string ; description :string }[] { 52const list = ( raw as { skills ?:unknown } | null )?. skills ; 53if ( ! Array . isArray ( list )) return []; 54return list . flatMap ( x => { 55const s = x as Record < string , unknown >; 56return typeof s ?. name === 'string' && s . name ?[{ name :s . name , description :typeof s . description === 'string' ?s . description :'' }] :[]; 57}). slice ( 0 , 20 ); 58} 59 60/** Add streamed text to the reply's ordered pieces: it continues the last text piece, or starts a new one after an activity line. */ 61export function appendText ( blocks :MessageBlock [] | undefined , text :string ) :MessageBlock [] { 62const list = blocks ?? [], last = list . at ( - 1 ); 63if ( last ?. kind === 'text' ) return [ ...list . slice ( 0 , - 1 ), { kind :'text' , text :tidyAnswer ( last . text + text ) }]; 64return [ ...list , { kind :'text' , text :tidyAnswer ( text ) }]; 65} 66 67/** A group frame is re-sent while it grows: the same id replaces its line; a new id goes after what came before. */ 68export function upsertGroup ( blocks :MessageBlock [] | undefined , group :ActivityGroup ) :MessageBlock [] { 69const list = blocks ?? [], at = list . findIndex ( b => b . kind === 'group' && b . id === group . id ); 70const next :MessageBlock = { kind :'group' , ...group }; 71return at >= 0 ?list . map (( b , i ) => ( i === at ?next :b )) :[ ...list , next ]; 72} 73 74/** The same file may be written more than once in a run: one card per path, with its latest numbers. */ 75export function mergeDeliverable ( list :Deliverable [] | undefined , file :Deliverable ) :Deliverable [] { 76const have = list ?? [], at = have . findIndex ( f => f . path === file . path ); 77const order = have . reduce (( n , f ) => Math . max ( n , f . order ?? 0 ), 0 ) + 1 ; 78if ( at < 0 ) return [ ...have , { ...file , order}]; 79const old = have [ at ]; 80return have . map (( f , i ) => ( i === at ?{ ...file , order, status :old . status === 'created' ?'created' :file . status , added :old . added + file . added , removed :old . removed + file . removed } :f )); 81} 82 83/** The kinds the sidebar preview shows and a finished run may open by itself: pages, markdown, PDFs, pictures, tables and plain text (not code or unknown files). */ 84export const SIDEBAR_KINDS :DeliverableKind [] = [ 'html' , 'markdown' , 'pdf' , 'image' , 'csv' , 'text' ]; 85 86/** 87* The one file a finished run opens in the sidebar, or null. The file the answer names wins (the last one it mentions); otherwise the one 88* written last. Only kinds the sidebar can show count, so a run that made a script and a page opens the page, and several files open one. 89*/ 90export function mainResult ( files :Deliverable [] | undefined , answer :string ) :Deliverable | null { 91const shown = ( files ?? []). filter ( f => SIDEBAR_KINDS . includes ( f . kind )); 92if ( ! shown . length ) return null ; 93const text = answer . toLowerCase (); 94let named :Deliverable | null = null , at = - 1 ; 95for ( const f of shown ) { 96const mention = Math . max ( text . lastIndexOf ( f . name . toLowerCase ()), text . lastIndexOf ( f . path . toLowerCase ())); 97if ( mention > at ) { at = mention ; named = f ; } 98} 99if ( named ) return named ; 100return shown . reduce (( best , f ) => (( f . order ?? 0 ) >= ( best . order ?? 0 ) ?f :best )); 101} 102 103/** Past this many files a run's results are one compact summary (the two folders and a count that opens the list) instead of one card per file. */ 104export const COMPACT_FILES_FROM = 6 ; 105 106/** The folder part of a path inside the chat's folder, with forward slashes ('' for a file that sits directly in it). */ 107export const dirOf = ( path :string ) :string => { const parts = path . replace ( / \\ / g , '/' ). split ( '/' ). filter ( Boolean ); parts . pop (); return parts . join ( '/' ); }; 108 109/** 110* The folder a run delivered to, relative to the chat's folder ('' means the chat's folder itself): the folder of the run's main result (the file the 111* answer names, else the one written last); with no previewable result, the top-level folder that holds the most files. A tie goes to the folder written to last. 112*/ 113export function deliveryFolder ( files :Deliverable [] | undefined , answer :string ) :string { 114const list = files ?? []; 115const main = mainResult ( list , answer ); 116if ( main ) return dirOf ( main . path ); 117const counts = new Map < string , { n :number ; last :number }>(); 118for ( const f of list ) { 119const top = dirOf ( f . path ). split ( '/' )[ 0 ] ?? '' ; 120const c = counts . get ( top ) ?? { n :0 , last :0 }; 121counts . set ( top , { n :c . n + 1 , last :Math . max ( c . last , f . order ?? 0 ) }); 122} 123let best = '' , at :{ n :number ; last :number } | null = null ; 124for ( const [ dir , c ] of counts ) if ( ! at || c . n > at . n || ( c . n === at . n && c . last > at . last )) { best = dir ; at = c ; } 125return best ; 126} 127 128/** The chat's folder on disk, worked out from a file's absolute and relative paths (for a host that does not say it). */ 129export function rootOf ( file :{ abs :string ; path :string } | undefined ) :string { 130if ( ! file ) return '' ; 131const abs = file . abs . replace ( / \\ / g , '/' ), rel = file . path . replace ( / \\ / g , '/' ). replace ( / ^\.?\/ / , '' ); 132return abs . endsWith ( '/' + rel ) ?abs . slice ( 0 , abs . length - rel . length - 1 ) :'' ; 133} 134 135export const fileTypeLabel = ( d :{ kind :DeliverableKind ; name :string }) => { 136const ext = d . name . includes ( '.' ) ?d . name . split ( '.' ). at ( - 1 ) ! . toUpperCase () :'' ; 137return d . kind === 'markdown' ?'MD' :d . kind === 'html' ?'HTML' :d . kind === 'csv' ?'CSV' :d . kind === 'pdf' ?'PDF' :ext && ext . length <= 10 ?ext :d . kind . toUpperCase (); 138}; 139 140export function fileSize ( bytes :number ) :string { 141if ( bytes < 1024 ) return ` ${ bytes } B` ; 142if ( bytes < 1024 * 1024 ) return ` ${( bytes / 1024 ). toFixed ( bytes < 10240 ? 1 : 0 )} KB` ; 143return ` ${( bytes / 1024 / 1024 ). toFixed ( 1 )} MB` ; 144} 145 146const csvText = ( rows :string [][]) => rows . map ( r => r . map ( c => ( / [",\n] / . test ( c ) ?`" ${ c . replace ( / " / g , '""' )} "` :c )). join ( ',' )). join ( '\n' ); 147 148interface PreviewAnswer { kind :DeliverableKind ; name :string ; path :string ; size :number ; mtime ?:number ; url ?:string ; text ?:string ; rows ?:string [][]; rawUrl ?:string ; note ?:string } 149 150/** The sidebar preview of a file: the host reads it (only inside the chat's folder) and the page draws it as a website, markdown, table, picture, PDF or code. */ 151export async function previewOf ( sessionId :string , file :{ path :string ; name :string }) :Promise < PreviewArtifact > { 152const a = await api . get < PreviewAnswer >( `/api/files/preview?sessionId= ${ encodeURIComponent ( sessionId )} &path= ${ encodeURIComponent ( file . path )} ` ); 153const id = `file: ${ a . path } ` , title = a . name || file . name , at = Date . now (), version = a . mtime !== undefined ?` ${ a . mtime } : ${ a . size } ` :undefined ; 154if ( a . kind === 'image' && a . rawUrl ) return { id, kind :'image' , title, url :a . rawUrl , version, at}; 155if ( a . kind === 'pdf' && a . rawUrl ) return { id, kind :'pdf' , title, url :a . rawUrl , version, at}; 156if ( a . kind === 'html' && a . text !== undefined ) return { id, kind :'website' , title, content :a . text , at}; 157if ( a . kind === 'markdown' && a . text !== undefined ) return { id, kind :'markdown' , title, content :a . text , at}; 158if ( a . kind === 'csv' && a . rows ) return { id, kind :'table' , title, content :csvText ( a . rows ), at}; 159if ( a . text !== undefined ) return { id, kind :'code' , title, content :a . text , at}; 160throw new Error ( a . note || 'This file has no preview. Open it in its own app.' ); 161} 162 163export const fileAction = { 164open :( sessionId :string , path :string , how :'browser' | 'app' | 'folder' ) => api . post ( '/api/files/open' , { sessionId, path, how}), 165fullPath :async ( sessionId :string , path :string ) => ( await api . get <{ path :string }>( `/api/files/path?sessionId= ${ encodeURIComponent ( sessionId )} &path= ${ encodeURIComponent ( path )} ` )). path , 166attach :( sessionId :string , path :string ) => api . post ( '/api/chat/attachments' , { sessionId, path}), 167}; 168 169export const rawUrlOf = ( sessionId :string , path :string ) => `/api/files/raw?sessionId= ${ encodeURIComponent ( sessionId )} &path= ${ encodeURIComponent ( path )} ` ; 170