okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b7bcbcde9
main
1/** 2* The folder a chat works in, and what can be done with a file in it. 3* 4* - Each chat can have its own project folder ("Select a folder" above the input). It becomes the agent's working folder and 5* sandbox for that chat and is remembered per chat. 6* - A file in that folder is opened by its PATH (file:///...), never through a local web address: in the browser, in its own app, 7* shown in the folder (Explorer /select), or copied as a path. Only files inside the chat's folder (or one the agent made 8* there) can be named, so a request cannot reach anywhere else. 9*/ 10 11import { spawn } from 'node:child_process' ; 12import { existsSync , mkdirSync , readFileSync , renameSync , statSync , writeFileSync , realpathSync } from 'node:fs' ; 13import { basename , dirname , isAbsolute , relative , resolve , sep } from 'node:path' ; 14import { pathToFileURL } from 'node:url' ; 15import { externalEnvironment } from './external-env.mjs' ; 16 17/** A folder no chat may use as its project: the top of a drive, or the system's own folders. */ 18export function refusedFolder ( dir ) { 19const p = resolve ( dir ); 20if ( dirname ( p ) === p ) return 'Choose a folder inside a drive, not the whole drive.' ; 21if ( process . platform === 'win32' ) { 22const win = ( process . env . SystemRoot ?? 'C:\\Windows' ). toLowerCase (); 23const q = p . toLowerCase (); 24if ( q === win || q . startsWith ( win + sep ) || / ^ [ a - z ] :\\ ( program files ( \(x86\) ) ?| programdata )( \\ | $ ) / . test ( q )) return 'That is a system folder. Choose one of your own folders.' ; 25} else if ( / ^\/ ( bin | boot | dev | etc | lib | lib64 | proc | root | run | sbin | sys | usr | var )( \/ | $ ) / . test ( p ) && ! /^\/run\/media\/ [ ^ / ] + \/. / . test ( p )) return 'That is a system folder. Choose one of your own folders.' ; 26return null ; 27} 28 29export const isInside = ( root , target ) => { 30const rel = relative ( resolve ( root ), resolve ( target )); 31return rel === '' || ( !! rel && ! rel . startsWith ( '..' ) && ! isAbsolute ( rel )); 32}; 33 34/** The chat -> folder table, kept in one small file. */ 35export function createChatFolders ({ file}) { 36let table = {}; 37try { const parsed = JSON . parse ( readFileSync ( file , 'utf8' )); if ( parsed && typeof parsed === 'object' && ! Array . isArray ( parsed )) table = parsed ; } catch { /* first run */ } 38const save = () => { 39try { mkdirSync ( dirname ( file ), { recursive :true }); const tmp = file + '.tmp' ; writeFileSync ( tmp , JSON . stringify ( table , null , 2 )); renameSync ( tmp , file ); } catch { /* kept in memory */ } 40}; 41const alive = p => { try { return statSync ( p ). isDirectory (); } catch { return false ; } }; 42return { 43/** The folder of a chat, or null (none chosen, or it was deleted: then the chat falls back to the default). */ 44get ( chatId ) { const p = table [ chatId ]; return typeof p === 'string' && alive ( p ) ?p :null ; }, 45info ( chatId ) { const p = table [ chatId ]; return p ?{ path :p , name :basename ( p ) || p , exists :alive ( p ) } :null ; }, 46set ( chatId , dir ) { 47const target = resolve ( String ( dir ?? '' ). trim ()); 48if ( ! String ( dir ?? '' ). trim () || ! isAbsolute ( target )) throw Object . assign ( new Error ( 'Choose a folder first.' ), { code :'folder-missing' }); 49let st ; try { st = statSync ( target ); } catch { throw Object . assign ( new Error ( "That folder doesn't exist." ), { code :'folder-missing' }); } 50if ( ! st . isDirectory ()) throw Object . assign ( new Error ( "That's a file, not a folder." ), { code :'folder-missing' }); 51const why = refusedFolder ( target ); 52if ( why ) throw Object . assign ( new Error ( why ), { code :'folder-refused' }); 53table [ chatId ] = target ; save (); 54return { path :target , name :basename ( target ) || target , exists :true }; 55}, 56clear ( chatId ) { delete table [ chatId ]; save (); }, 57}; 58} 59 60/** 61* The folder a chat's files live in, one rule for the agent's writes, Open, Show in folder, preview and attach: 62* 1. the folder the person chose for this chat; else 63* 2. the folder the agent actually worked in for it (its session's working folder, so it is the one it wrote to); else 64* 3. the default workspace (Documents/Strata/Workspace, or STRATA_WORKSPACE), where a chat with no folder is run. 65* A folder that no longer exists is skipped. Never null while the default exists, so a chat with no chosen folder can still open its files. 66*/ 67export function chatRootOf ({ chosen= null , used= null , fallback= null } = {}) { 68const alive = p => { try { return !! p && statSync ( p ). isDirectory (); } catch { return false ; } }; 69for ( const p of [ chosen , used , fallback ]) if ( alive ( p )) return resolve ( p ); 70return fallback ?resolve ( fallback ) :null ; 71} 72 73/** The real path of a file the chat may touch, or throws a plain sentence. Symbolic links are followed before the check. */ 74export function resolveChatFile ( root , rawPath ) { 75if ( ! root ) throw Object . assign ( new Error ( 'This chat has no folder yet. Choose one first.' ), { code :'no-folder' }); 76const given = String ( rawPath ?? '' ). trim (); 77if ( ! given ) throw Object . assign ( new Error ( 'Which file?' ), { code :'file-missing' }); 78const full = isAbsolute ( given ) ?resolve ( given ) :resolve ( root , given ); 79let real ; try { real = realpathSync ( full ); } catch { throw Object . assign ( new Error ( 'That file is no longer there.' ), { code :'file-missing' }); } 80let realRoot ; try { realRoot = realpathSync ( root ); } catch { realRoot = resolve ( root ); } 81if ( ! isInside ( realRoot , real )) throw Object . assign ( new Error ( "That file is outside this chat's folder, so it was not opened." ), { code :'outside' }); 82return real ; 83} 84 85/** 86* Start a program and return at once: detached, no shared output, never waited for. 87* `STRATA_OPENER=record` (tests) records the command instead of starting anything. 88*/ 89export function launch ( command , args , { recorder= null } = {}) { 90if ( process . env . STRATA_OPENER === 'record' || recorder ) { ( recorder ?? launch . recorded ). push ([ command , ...args ]); return ; } 91// xdg-open and the browser it starts are the system's programs: they get the environment the AppImage was started from, not Strata's libraries. 92const child = spawn ( command , args , { detached :true , stdio :'ignore' , windowsHide :false , env :externalEnvironment () }); 93child . on ( 'error' , () => {}); 94child . unref (); 95} 96launch . recorded = []; 97 98/** What "open" means on each system, for the browser, the file's own app, or the folder. */ 99export function openCommand ( how , file , platform = process . platform ) { 100const url = pathToFileURL ( file ). href ; 101if ( how === 'folder' ) { 102if ( platform === 'win32' ) return [ 'explorer.exe' , [ `/select, ${ file } ` ]]; 103if ( platform === 'darwin' ) return [ 'open' , [ '-R' , file ]]; 104return [ 'xdg-open' , [ dirname ( file )]]; 105} 106if ( how === 'browser' ) { 107if ( platform === 'win32' ) return [ 'rundll32.exe' , [ 'url.dll,FileProtocolHandler' , url ]]; // the default browser, handed a file:// address 108if ( platform === 'darwin' ) return [ 'open' , [ url ]]; 109return [ 'xdg-open' , [ url ]]; 110} 111if ( platform === 'win32' ) return [ 'rundll32.exe' , [ 'url.dll,FileProtocolHandler' , file ]]; 112if ( platform === 'darwin' ) return [ 'open' , [ file ]]; 113return [ 'xdg-open' , [ file ]]; 114} 115 116export function openFile ( root , rawPath , how = 'app' , { platform= process . platform , recorder= null } = {}) { 117if ( ! [ 'browser' , 'app' , 'folder' ]. includes ( how )) throw Object . assign ( new Error ( 'That way of opening is not known.' ), { code :'bad-how' }); 118const file = resolveChatFile ( root , rawPath ); 119const [ cmd , args ] = openCommand ( how , file , platform ); 120launch ( cmd , args , { recorder}); 121return { ok :true , started :true , path :file , url :pathToFileURL ( file ). href , how}; 122} 123 124// ---- previews, raw bytes and "attach as context" ----------------------------------------------------------------------------------- 125 126import { readFileSync as readBytes } from 'node:fs' ; 127import { fileType } from './agent/deliverables.mjs' ; 128 129const MIME = { png :'image/png' , jpg :'image/jpeg' , jpeg :'image/jpeg' , gif :'image/gif' , webp :'image/webp' , svg :'image/svg+xml' , bmp :'image/bmp' , ico :'image/x-icon' , 'application/pdf' }; 130export const mimeOf = file => MIME [ String ( file ). split ( '.' ). pop (). toLowerCase ()] ?? 'application/octet-stream' ; 131const MAX_PREVIEW_TEXT = 1_000_000 ; 132 133/** A small CSV/TSV reader for the table preview: quotes, doubled quotes, commas/tabs inside quotes. */ 134export function parseCsv ( text , delimiter = ',' , maxRows = 500 ) { 135const rows = []; let row = [], cell = '' , quoted = false ; 136for ( let i = 0 ; i < text . length && rows . length < maxRows ; i ++ ) { 137const ch = text [ i ]; 138if ( quoted ) { if ( ch === '"' ) { if ( text [ i + 1 ] === '"' ) { cell += '"' ; i ++ ; } else quoted = false ; } else cell += ch ; } 139else if ( ch === '"' ) quoted = true ; 140else if ( ch === delimiter ) { row . push ( cell ); cell = '' ; } 141else if ( ch === '\n' || ch === '\r' ) { if ( ch === '\r' && text [ i + 1 ] === '\n' ) i ++ ; row . push ( cell ); rows . push ( row ); row = []; cell = '' ; } 142else cell += ch ; 143} 144if ( rows . length < maxRows && ( cell !== '' || row . length )) { row . push ( cell ); rows . push ( row ); } 145return rows ; 146} 147 148/** 149* What the sidebar needs to show a file: { kind, name, size, text?, rows?, rawUrl? }. 150* html: the text (the page renders it sandboxed); markdown: the text; csv: parsed rows; pdf and images: the address of the raw bytes 151* (/api/files/raw), which only serves a file inside the chat's folder; code and text: the text. Too big to show: kind only and a plain note. 152*/ 153export function previewFile ( root , rawPath , sessionId ) { 154const file = resolveChatFile ( root , rawPath ); 155const st = statSync ( file ); const kind = fileType ( file ); 156const base = { kind, name :basename ( file ), path :file , size :st . size , mtime :Math . round ( st . mtimeMs ), url :pathToFileURL ( file ). href }; 157const raw = `/api/files/raw?sessionId= ${ encodeURIComponent ( sessionId )} &path= ${ encodeURIComponent ( file )} ` ; 158if ( kind === 'image' || kind === 'pdf' ) return { ...base , rawUrl :raw , mime :mimeOf ( file ) }; 159if ( kind === 'other' ) return { ...base , note :'This kind of file has no preview. Open it in its own app.' }; 160if ( st . size > MAX_PREVIEW_TEXT ) return { ...base , note :'This file is too big to show here. Open it in its own app.' }; 161const buf = readBytes ( file ); 162if ( buf . subarray ( 0 , 2048 ). includes ( 0 )) return { ...base , kind :'other' , note :'This file is not text, so it has no preview.' }; 163const text = buf . toString ( 'utf8' ); 164if ( kind === 'csv' ) return { ...base , rows :parseCsv ( text , file . toLowerCase (). endsWith ( '.tsv' ) ?'\t' :',' ), truncated :text . split ( '\n' ). length > 500 }; 165return { ...base , text}; 166} 167 168/** The bytes of a picture or PDF inside the chat's folder. */ 169export function rawFile ( root , rawPath ) { 170const file = resolveChatFile ( root , rawPath ); 171const mime = mimeOf ( file ); 172if ( mime === 'application/octet-stream' ) throw Object . assign ( new Error ( 'Only pictures and PDFs are served this way.' ), { code :'bad-type' }); 173return { bytes :readBytes ( file ), mime}; 174} 175 176/** Files the person attached from a deliverable; the next message to the chat names them (@path), so the assistant reads them again. */ 177export function createAttachments () { 178const table = new Map (); 179return { 180list :chatId => [ ...( table . get ( chatId ) ?? [])], 181add ( chatId , file ) { const l = table . get ( chatId ) ?? []; if ( ! l . includes ( file )) l . push ( file ); table . set ( chatId , l . slice ( - 10 )); return [ ...table . get ( chatId )]; }, 182remove ( chatId , file ) { const l = ( table . get ( chatId ) ?? []). filter ( f => f !== file ); table . set ( chatId , l ); return l ; }, 183/** Take them for the next message (and forget them). */ 184take ( chatId ) { const l = table . get ( chatId ) ?? []; table . delete ( chatId ); return l ; }, 185}; 186} 187/** The message with its attachments named in front, as the assistant's instructions explain (@path is a file the person pointed at). */ 188export const withAttachments = ( message , files ) => ( files . length ?files . map ( f => '@' + ( / \s / . test ( f ) ?'"' + f + '"' :f )). join ( ' ' ) + ' ' + message :message );