okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
538acd098
main
1/** 2* The Strata approval gate: a small Harness plugin (plain ESM, no imports, loaded by absolute path from the profile). 3* 4* Why it exists. The Harness only asks a person when a tool escalates its sandbox. With the sandbox read-only that 5* produced a blocked attempt first (a card full of sandbox and PowerShell errors) and the real Approve/Deny card 6* only on the model's second try. In Manual mode this plugin asks BEFORE a change runs, through the Harness's own 7* approval service, so the person sees exactly one card per change and nothing has run when it appears. 8* 9* How it works. It listens to `tools/pre-execute` (the same seam the Harness's own Auto-review layer uses). For a 10* session whose effective preset is Manual it returns an `ask` decision for every call that is not known to be 11* read-only. The Harness then asks, runs the tool only after an approval, and records the answer. Manual runs with 12* the sandbox open, so an approved change can really happen anywhere the person agreed to; the approval is the 13* control, which is why anything this file cannot prove is read-only asks (fail closed). 14* 15* Children. A subagent's approval policy is pinned to `never` by the Harness (its requests are rejected on the 16* spot). For a child of a Manual chat that would hide the card and the child could not do anything. The gate 17* writes `ask` into that child's log, so the child's request reaches the same single Approve/Deny card. 18* Plan and Bypass children are untouched. 19* 20* The status command `/strata-gate` lets the host confirm the gate is really loaded before it lets a Manual turn 21* start (a Manual chat with no gate would be a chat with the sandbox open and nobody asking). 22*/ 23 24export const name = 'strata-gate' ; 25export const inject = [ 'approval' , 'permissionPresets' , 'sessions' , 'tools' ]; 26 27/** Preset key the host writes for Manual (apps/host/server/agent/profile.mjs MODE_PRESETS). */ 28export const MANUAL_PRESET = 'strata-manual' ; 29/** Preset key the host writes for Plan (read-only, nothing may change). */ 30export const PLAN_PRESET = 'strata-plan' ; 31/** The app's own look-only tool server (the person's instruction tools): it only hands back text. */ 32const LOOK_ONLY_SERVER = 'mcp__strata-instructions__' ; 33/** The tools a person wrote as commands (Settings -> Tools): the card says which one runs and with what text. */ 34const COMMANDS_SERVER = 'mcp__strata-commands__' ; 35/** The browser tool server's name in the agent (Settings -> Tools). Looking at the page does not ask; acting on it does. */ 36const BROWSER_SERVER = 'mcp__browser__' ; 37const BROWSER_LOOKING = new Set ([ 'browser_snapshot' , 'browser_take_screenshot' , 'browser_console_messages' , 'browser_network_requests' , 'browser_wait_for' ]); 38 39/** Tools that cannot change anything on this computer. Everything else asks. */ 40export const READ_ONLY_TOOLS = new Set ([ 41'read' , 'glob' , 'grep' , 'read_image' , 'working_directory' , 'todo_write' , 'skill' , 'present' , 'lsp' , 42'get_goal' , 'create_goal' , 'update_goal' , 'list_agents' , 'list_subagent_models' , 'job_list' , 'job_output' , 43'ask_user_question' , 'exit_plan_mode' , 44// (web_search and web_fetch are not here: the first use in a chat asks, see webDecision.) 45// Delegation: the child it starts is governed by this same gate. 46'subagent' , 'subagent_fork' , 'send_message' , 'interrupt_agent' , 'workflow' , 47]); 48 49const SHELL_TOOLS = new Set ([ 'pwsh' , 'bash' ]); 50 51/** 52* Which shell commands run without a card in Manual mode, and with which options. Safe by construction (#3975): a command is on the list WITH the 53* options that are known to only look. Every other option, long or short, abbreviated or attached, makes the command ask. So a write mode 54* (`sort -o`, `tree -o`, `uniq in out`), a program-execution mode (`sort --compress-program`, `rg --pre`, `git grep -O`), a setting mode 55* (`date -s`) or one that never ends (`tail -f`) cannot slip in, and a word added to the list later starts with no options at all. 56* 57* A spec says what one command accepts: 58* f short options without a value (letters, so `-la` is `-l -a`) v short options that need a value (`-k2`, `-k 2`) 59* vn the same, and the value must be a number o short options with an optional value that must be attached (`-Iseconds`) 60* n a bare `-5` is allowed l long options (`--name`, `--name=value`), spelled in full 61* lv long options that need a value (`--name=value`, `--name value`) ps PowerShell parameter names, lower case, spelled in full 62* max how many operands (files, patterns) are allowed op a check for each operand 63* post a last check from the options seen and the operand count 64*/ 65const words = ( text ) => ( text ?text . trim (). split ( / \s +/ ) :[]); 66const spec = ({ f= '' , v= '' , vn= '' , o= '' , n= false , l= '' , lv= '' , ps= '' , max= Infinity , op= null , post= null }) => 67({ f, v, vn, o, n, l :new Set ( words ( l )), lv :new Set ( words ( lv )), ps :ps ?new Set ([ ...words ( ps ), ...PS_COMMON ]) :null , max, op, post}); 68/** Parameters every cmdlet has that only change how errors and warnings show. (-Debug asks a question and -OutVariable sets one: not listed.) */ 69const PS_COMMON = [ 'erroraction' , 'ea' , 'warningaction' , 'wa' , 'informationaction' , 'ia' , 'verbose' , 'vb' ]; 70const NUMBER = / ^ [ +- ] ? \d + [ A - Za - z ]{ 0 , 3 } $ / ; 71 72/** What `ls`, `dir`, `gci` and `Get-ChildItem` take. */ 73const LS = { f :'aAbBcdDFgGhHiklLmnNopqQrRsStuUvxX1CZ' , v :'ITw' , ps :'path literalpath filter include exclude recurse depth name force file directory hidden readonly system attributes' , 74l :'all almost-all human-readable recursive directory classify reverse size inode dereference color group-directories-first sort time time-style block-size indicator-style si numeric-uid-gid no-group literal hide ignore quote-name escape author file-type full-time width tabsize' }; 75/** What `cat`, `type`, `gc` and `Get-Content` take. (-Wait never ends, so it is not here.) */ 76const CAT = { f :'AbeEnstTuv' , ps :'path literalpath totalcount tail head raw encoding readcount force filter include exclude delimiter stream asbytestream' , 77l :'show-all number-nonblank show-ends number squeeze-blank show-tabs show-nonprinting' }; 78const MEASURE = { ps :'property sum average maximum minimum line word character ignorewhitespace inputobject standarddeviation allstats' }; 79const SELECT = { ps :'first last skip skiplast property expandproperty unique index excludeproperty inputobject' }; 80const WHERE = { ps :'property value inputobject eq ne gt lt ge le like notlike match notmatch contains notcontains in notin is isnot ceq cne cgt clt cge cle clike cnotlike cmatch cnotmatch ccontains cnotcontains cin cnotin' }; 81const GROUP = { ps :'property noelement ashashtable asstring casesensitive inputobject culture' }; 82const FT = { ps :'property autosize wrap hidetableheaders groupby view force expand repeatheader displayerror showerror inputobject' }; 83const FL = { ps :'property view groupby expand force displayerror showerror inputobject' }; 84const SLS = { ps :'pattern path literalpath simplematch casesensitive context list notmatch quiet allmatches include exclude encoding raw inputobject culture noemphasis' }; 85const GETITEM = { ps :'path literalpath name filter include exclude force stream' }; 86const GETLOC = { ps :'psprovider psdrive stack stackname' }; 87const ECHO = { f :'neE' , ps :'inputobject noenumerate' }; 88/** The GNU/BSD grep family. */ 89const GREP = { f :'aiIlLcnvwHhEFGPqrRsTUyzZbxo' , v :'efdD' , vn :'ABCm' , n :true , 90l :'extended-regexp fixed-strings basic-regexp perl-regexp ignore-case no-ignore-case word-regexp line-regexp invert-match count color colour files-with-matches files-without-match max-count only-matching quiet silent no-messages byte-offset with-filename no-filename label line-buffered initial-tab null after-context before-context context text recursive dereference-recursive include exclude exclude-dir binary-files line-number null-data no-group-separator group-separator regexp file directories devices binary' }; 91 92/** Commands that only look, each with the options that are known to be harmless. Matched against the first word of every pipeline segment. */ 93const SPECS = new Map (); 94const add = ( names , s ) => { for ( const name of words ( names )) SPECS . set ( name , spec ( s )); }; 95// PowerShell 96add ( 'get-childitem gci' , { ps :LS . ps }); 97add ( 'ls dir' , LS ); 98add ( 'get-content gc' , { ps :CAT . ps }); 99add ( 'cat type' , CAT ); 100add ( 'get-item gi get-itemproperty' , GETITEM ); 101add ( 'get-location gl' , GETLOC ); 102add ( 'pwd' , { ...GETLOC , f :'LP' }); 103add ( 'select-string sls' , SLS ); 104add ( 'measure-object measure' , MEASURE ); 105add ( 'select-object select' , SELECT ); 106add ( 'where-object where' , WHERE ); 107add ( 'sort-object' , { ps :'property descending unique top bottom casesensitive culture stable inputobject' }); 108add ( 'format-table ft' , FT ); 109add ( 'format-list fl' , FL ); 110add ( 'out-string' , { ps :'stream width inputobject' }); 111add ( 'test-path' , { ps :'path literalpath pathtype isvalid filter include exclude olderthan newerthan' }); 112add ( 'resolve-path' , { ps :'path literalpath relative relativebasepath force' }); 113add ( 'get-filehash' , { ps :'path literalpath algorithm' }); 114add ( 'get-date' , { ps :'format uformat date asutc displayhint year month day hour minute second millisecond' }); 115add ( 'get-command' , { ps :'name commandtype module all syntax listimported totalcount noun verb fullyqualifiedmodule parametername parametertype' }); 116add ( 'get-process' , { ps :'name id includeusername module fileversioninfo inputobject' }); 117add ( 'write-output' , { ps :ECHO . ps }); 118add ( 'echo' , ECHO ); 119add ( 'get-host' , { ps :'' }); 120add ( 'get-psdrive' , { ps :'name psprovider scope literalname' }); 121add ( 'get-help' , { ps :'name full detailed examples parameter category component functionality role' }); 122add ( 'group-object group' , GROUP ); 123add ( 'convertto-json' , { ps :'depth compress enumsasstrings inputobject asarray escapehandling' }); 124add ( 'convertfrom-json' , { ps :'ashashtable depth inputobject noenumerate' }); 125add ( 'select-xml' , { ps :'xml path literalpath xpath content namespace' }); 126add ( 'compare-object' , { ps :'referenceobject differenceobject property includeequal excludedifferent passthru syncwindow casesensitive culture' }); 127add ( 'get-unique' , { ps :'inputobject asstring caseinsensitive onetype' }); 128// POSIX. `sort` and `date` take no PowerShell names here: `sort -o FILE` writes, `date -s` sets the clock, and a PowerShell-looking `-Second` or `-Top` 129// must not be read by a real sort or date as one of those. (Sort-Object and Get-Date above are the PowerShell forms.) 130add ( 'head' , { f :'qvz' , vn :'nc' , n :true , l :'quiet silent verbose zero-terminated lines bytes' }); 131add ( 'tail' , { f :'qvz' , vn :'nc' , n :true , l :'quiet silent verbose zero-terminated lines bytes' }); // no -f, -F, --follow, --retry, --pid, -s: those never end 132add ( 'wc' , { f :'lwcmL' , l :'lines words bytes chars max-line-length' }); 133add ( 'grep egrep fgrep' , GREP ); 134add ( 'rg' , { // no --pre, --pre-glob, --hostname-bin (they run a program) and no -z/--search-zip (it runs decompressors) 135f :'iIsSnNHlcwFxvUoLaquhVpbP' , v :'efgtTr' , vn :'ABCjdMm' , 136l :'ignore-case no-ignore-case smart-case case-sensitive fixed-strings word-regexp line-regexp invert-match count count-matches files-with-matches files-without-match files type-list hidden no-ignore no-ignore-vcs no-ignore-parent no-ignore-dot no-ignore-global no-ignore-messages follow line-number no-line-number with-filename no-filename column heading no-heading null only-matching quiet text multiline multiline-dotall pcre2 no-messages json stats trim unrestricted binary no-config vimgrep pretty byte-offset passthru crlf one-file-system no-unicode regexp file glob iglob type type-not max-count max-depth maxdepth context after-context before-context color replace threads sort sortr max-filesize max-columns path-separator encoding engine ignore-file glob-case-insensitive no-glob-case-insensitive' }); 137add ( 'stat' , { f :'LtxlnqrsFf' , v :'c' , l :'dereference file-system terse format printf' }); 138add ( 'file' , { f :'bhikLnNrvI' , l :'brief dereference no-dereference mime mime-type mime-encoding keep-going no-pad no-buffer raw' }); // no -C, -m, -f, -P (they write or read other files), no -z/-s/-p (they run decompressors, read devices, reset times) 139add ( 'du' , { f :'abchHklmsxLPSD0' , v :'tB' , vn :'d' , l :'all apparent-size bytes total dereference-args human-readable si summarize one-file-system dereference no-dereference separate-dirs count-links inodes null max-depth threshold block-size time time-style exclude' }); 140add ( 'df' , { f :'ahHiklmPTv' , v :'txB' , l :'all human-readable si inodes local portability print-type total sync no-sync output block-size type exclude-type' }); 141add ( 'uname' , { f :'asnrvmpio' , max :0 , l :'all kernel-name nodename kernel-release kernel-version machine processor hardware-platform operating-system' }); 142add ( 'which' , { f :'as' , l :'all' }); 143add ( 'basename' , { f :'az' , v :'s' , l :'multiple zero suffix' }); 144add ( 'dirname' , { f :'z' , l :'zero' }); 145add ( 'realpath' , { f :'emsqzLP' , l :'canonicalize-existing canonicalize-missing no-symlinks quiet zero strip logical physical relative-to relative-base' }); 146add ( 'readlink' , { f :'femnqsvz' , l :'canonicalize canonicalize-existing canonicalize-missing no-newline quiet silent verbose zero' }); 147add ( 'sort' , { f :'bdfghiMnRrsuVzmcC' , v :'kt' , l :'ignore-leading-blanks dictionary-order ignore-case general-numeric-sort human-numeric-sort ignore-nonprinting month-sort numeric-sort random-sort reverse stable unique version-sort zero-terminated check merge sort field-separator key' }); 148// uniq's second operand is its OUTPUT file, so it takes at most one. 149add ( 'uniq' , { f :'cdDuiz' , vn :'fsw' , max :1 , l :'count repeated all-repeated unique ignore-case skip-fields skip-chars check-chars zero-terminated group' }); 150add ( 'cut' , { f :'snz' , v :'bcfd' , l :'complement only-delimited zero-terminated bytes characters fields delimiter output-delimiter' }); 151add ( 'tr' , { f :'cCdst' , max :2 }); 152add ( 'date' , { f :'uR' , o :'I' , v :'dr' , lv :'date reference' , l :'utc universal rfc-email rfc-2822 iso-8601 rfc-3339' , 153op :( word ) => word . startsWith ( '+' ) }); // a bare operand like 1026120026 SETS the clock; only +FORMAT is a format 154add ( 'id' , { f :'ugGnrazZ' , l :'user group groups name real context zero' }); 155add ( 'hostname' , { f :'sfiIdaAyv' , max :0 }); // `hostname NAME` renames the machine 156add ( 'whoami' , { l :'help version' , op :( word ) => / ^\/ ( all | user | groups | priv | upn | fqdn | logonid | nh ) $ / i . test ( word ) }); 157add ( 'tree' , { f :'adfilpsugDFqNQrtvxCnASUchJX' , v :'LPIHT' , vn :'' , l :'help version filelimit charset sort timefmt noreport dirsfirst filesfirst prune du si gitignore matchdirs ignore-case inodes device nolinks' }); // no -o, no -R 158// `less` and `more` are not here: they wait for keys, and `less` can run commands. 159 160/** The names that run without a card (for the tests). */ 161export const readOnlyCommandNames = () => [ ...SPECS . keys ()]; 162 163/** git subcommands that only read, with the options they may take. */ 164const GIT_VIEW = 'oneline graph decorate no-decorate all branches tags remotes stat shortstat numstat dirstat name-only name-status patch no-patch raw summary compact-summary abbrev-commit no-abbrev-commit abbrev reverse follow no-merges merges first-parent full-history simplify-by-decoration simplify-merges ancestry-path left-right left-only right-only cherry-pick cherry-mark cherry topo-order date-order author-date-order relative-date all-match invert-grep regexp-ignore-case extended-regexp fixed-strings perl-regexp no-color color color-words word-diff word-diff-regex minimal patience histogram diff-algorithm check exit-code quiet cached staged merge-base no-index no-ext-diff no-textconv find-renames find-copies find-copies-harder no-renames ignore-space-change ignore-all-space ignore-space-at-eol ignore-blank-lines ignore-cr-at-eol function-context show-function unified inter-hunk-context src-prefix dst-prefix no-prefix full-index binary text source use-mailmap mailmap no-mailmap log-size notes no-notes show-signature diff-merges boundary children parents no-walk sparse date format pretty author committer grep since until after before max-count skip min-parents max-parents diff-filter encoding stat-width stat-name-width stat-graph-width stat-count count' ; 165const LISTING = [ 'l' , 'list' , 'contains' , 'no-contains' , 'merged' , 'no-merged' , 'points-at' ]; 166const GIT = new Map ( Object . entries ({ 167status :spec ({ f :'sbvz' , o :'u' , l :'short branch porcelain long ignored untracked-files ignore-submodules renames no-renames find-renames show-stash ahead-behind no-ahead-behind column no-column verbose null' }), 168log :spec ({ f :'pswbMCizuacmrtqEFPR' , vn :'nU' , v :'SGL' , n :true , l :GIT_VIEW }), 169diff :spec ({ f :'pswbMCizuacmrtqEFPR' , vn :'nU' , v :'SGL' , n :true , l :GIT_VIEW }), 170show :spec ({ f :'pswbMCizuacmrtqEFPR' , vn :'nU' , v :'SGL' , n :true , l :GIT_VIEW }), 171'rev-list' :spec ({ f :'pswbMCizuacmrtqEFPR' , vn :'nU' , v :'SGL' , n :true , l :GIT_VIEW }), 172shortlog :spec ({ f :'sneciw' , n :false , l :` ${ GIT_VIEW } summary numbered email committer group` }), 173// Listing forms only. A name with no list option would CREATE a branch or a tag, and the options that change things are not here. 174branch :spec ({ f :'avri' , l :'list all remotes verbose show-current ignore-case contains no-contains merged no-merged points-at sort format abbrev no-abbrev color no-color column no-column omit-empty' , 175post :( seen , count ) => count === 0 || LISTING . some ( name => seen . has ( name )) }), 176tag :spec ({ f :'li' , o :'n' , l :'list sort contains no-contains merged no-merged points-at format column no-column ignore-case omit-empty color no-color' , 177post :( seen , count ) => count === 0 || LISTING . some ( name => seen . has ( name )) }), 178remote :spec ({ f :'v' , l :'verbose' , max :0 }), 179// `git config KEY` reads and `git config KEY VALUE` writes, so a key is only taken with --get; no --edit, --add, --unset, --file. 180config :spec ({ f :'lz' , l :'list get get-all get-regexp show-origin show-scope local global system worktree bool int bool-or-int path expiry-date type null name-only includes no-includes' , lv :'default' , 181post :( seen , count ) => ( count > 0 ?[ 'get' , 'get-all' , 'get-regexp' ]. some ( name => seen . has ( name )) :seen . has ( 'list' ) || seen . has ( 'l' )) }), 182'rev-parse' :spec ({ f :'q' , l :'show-toplevel git-dir git-common-dir absolute-git-dir abbrev-ref symbolic symbolic-full-name short verify is-inside-work-tree is-inside-git-dir is-bare-repository is-shallow-repository show-prefix show-cdup show-superproject-working-tree all branches tags remotes quiet revs-only no-revs flags no-flags local-env-vars show-object-format path-format' , lv :'default git-path' }), 183'ls-files' :spec ({ f :'cdmoiskuzvtfD' , l :'cached deleted modified others ignored stage directory unmerged killed no-empty-directory error-unmatch exclude-standard exclude full-name eol deduplicate recurse-submodules sparse abbrev resolve-undo format' }), 184'ls-tree' :spec ({ f :'rtdlz' , l :'name-only name-status long full-name full-tree object-only abbrev format' }), 185blame :spec ({ f :'wMCespltbfnc' , v :'L' , l :'porcelain line-porcelain incremental show-email show-name show-number date root abbrev' }), 186describe :spec ({ l :'all tags always long dirty broken contains abbrev match exclude first-parent exact-match candidates' }), 187'cat-file' :spec ({ f :'tsep' , l :'batch batch-check batch-all-objects allow-unknown-type buffer unordered follow-symlinks mailmap use-mailmap' }), // no --textconv, --filters 188// No -O / --open-files-in-pager: they run a program on the matches. 189grep :spec ({ f :'aiIlLcnvwHhEFGPqpWrzUo' , v :'e' , vn :'ABCm' , n :true , l :'no-index untracked cached no-exclude-standard exclude-standard recurse-submodules text ignore-case word-regexp invert-match full-name extended-regexp basic-regexp perl-regexp fixed-strings line-number column files-with-matches name-only files-without-match count null only-matching quiet no-color color break heading show-function function-context all-match and or not max-depth max-count threads after-context before-context context recursive no-recursive' }), 190})); 191 192/** 193* One command's words against its spec: every option has to be one the spec knows (anything else is not understood, so it asks). 194* @param { ReturnType<typeof spec> } sp 195* @param { {t:string,q:boolean}[] } args the words after the command; q marks a quoted text, which is data and never an option 196*/ 197function argumentsAreSafe ( sp , args ) { 198const seen = new Set (); 199let operands = 0 , ended = false ; 200const operand = ( arg ) => { operands ++ ; return operands <= sp . max && ( ! sp . op || sp . op ( arg . t , arg . q )); }; 201const valueOf = ( i , numeric ) => { // the next word as an option's value; it can be a quoted text, a number, or a word that is not an option 202const arg = args [ i + 1 ]; 203if ( ! arg ) return false ; 204return numeric ?NUMBER . test ( arg . t ) :arg . q || ! arg . t . startsWith ( '-' ) || NUMBER . test ( arg . t ); 205}; 206for ( let i = 0 ; i < args . length ; i ++ ) { 207const { t, q} = args [ i ]; 208if ( q || ended || t === '-' || t [ 0 ] !== '-' ) { if ( ! operand ( args [ i ])) return false ; continue ; } 209if ( t === '--' ) { ended = true ; continue ; } 210if ( t . startsWith ( '--' )) { 211const eq = t . indexOf ( '=' ); 212const name = eq < 0 ?t . slice ( 2 ) :t . slice ( 2 , eq ); 213if ( sp . l . has ( name )) { seen . add ( name ); continue ; } 214if ( sp . lv . has ( name )) { seen . add ( name ); if ( eq < 0 ) { if ( ! valueOf ( i , false )) return false ; i ++ ; } continue ; } 215return false ; 216} 217if ( sp . ps ) { 218const named = / ^- ([ A - Za - z ][ A - Za - z0 - 9 ] * )(?: : | $ ) / . exec ( t ); 219if ( named && sp . ps . has ( named [ 1 ]. toLowerCase ())) { seen . add ( named [ 1 ]. toLowerCase ()); continue ; } 220} 221if ( sp . n && / ^-\d + $ / . test ( t )) continue ; 222for ( let j = 1 ; j < t . length ; j ++ ) { 223const c = t [ j ]; 224if ( sp . f . includes ( c )) { seen . add ( c ); continue ; } 225if ( sp . o . includes ( c )) { seen . add ( c ); break ; } 226const numeric = sp . vn . includes ( c ); 227if ( ! numeric && ! sp . v . includes ( c )) return false ; 228seen . add ( c ); 229const rest = t . slice ( j + 1 ); 230if ( rest ) { if ( numeric && ! NUMBER . test ( rest )) return false ; } else { if ( ! valueOf ( i , numeric )) return false ; i ++ ; } 231break ; 232} 233} 234return sp . post ?sp . post ( seen , operands ) :true ; 235} 236 237const SAFE_VERSION = / ^ ( node | python | python3 | py | npm | pnpm | git | dotnet | cargo | rustc | go | java | pip | pip3 ) \s + ( --version | -v | -version | version ) $ / i ; 238 239/** Anything that can chain, redirect, expand or start something else is not read-only. (`sh` as a word, not inside an option like `du -sh`.) */ 240const UNSAFE_SYNTAX = / [ ;&<>`${}() ] | \r | \n | --% | \bout-file\b | \bset-content\b | \badd-content\b | \binvoke- | \biex\b | \bstart- | \bnew- | \bremove- | \bcopy- | \bmove- | \brename- | \bclear- | \bset- | \bpush- | \bexpand- | \bsave- | \binstall- | \bcurl\b | \bwget\b | \bsudo\b | (?< ! [ - \w ]) sh (? ! [ - \w ]) | \bbash\b | \bpwsh\b | \bpowershell\b | \bcmd\b | -exec\b | -delete\b | -execdir\b / i ; 241 242/** 243* The command with every quoted text replaced by a plain stand-in, or null when it cannot be read safely. What is inside quotes is data 244* (a path like "C:\Users\x\Q&A", a pattern like 'a|b'), so an & ; | ( ) < > or { in it must not decide anything. Two things still can: 245* inside double quotes a $ or a backtick expands (a variable, a sub-command), and an unterminated quote means the text was not understood. 246* Either one gives null, and the command asks as before. 247* @param { string } text 248* @param { string[] } [quoted] when given, receives the text inside each quote, in order (the checks on operands read it) 249* @returns { string|null } 250*/ 251export function maskQuotes ( text , quoted ) { 252let out = '' ; 253for ( let i = 0 ; i < text . length ; i ++ ) { 254const c = text [ i ]; 255if ( c !== '"' && c !== "'" ) { out += c ; continue ; } 256let end = text . indexOf ( c , i + 1 ); 257// PowerShell writes a quote inside a quoted text by doubling it ('it''s'): the text goes on past the pair. 258while ( end >= 0 && text [ end + 1 ] === c ) end = text . indexOf ( c , end + 2 ); 259if ( end < 0 ) return null ; 260if ( c === '"' && / [ $` ] / . test ( text . slice ( i + 1 , end ))) return null ; 261// A quoted text is a whole word. One glued to other characters (--out"put"=f, "a"b) or one that starts with a dash could hide an option from the 262// word checks below (git diff "--output=f" writes a file), so those are not understood either. 263const before = text [ i - 1 ], after = text [ end + 1 ]; 264if (( before !== undefined && ! / [ \s | ] / . test ( before )) || ( after !== undefined && ! / [ \s | ] / . test ( after )) || text [ i + 1 ] === '-' ) return null ; 265out += '"_"' ; 266quoted ?. push ( text . slice ( i + 1 , end )); 267i = end ; 268} 269return out ; 270} 271 272/** 273* Whether a shell command only reads. Conservative by design: one unrecognised word or option and the answer is no. 274* Quoted text is data and is looked at after it has been set aside (maskQuotes): Get-ChildItem "C:\Users\x\Q&A" only lists. 275* @param { string } command 276* @returns { boolean } 277*/ 278export function isReadOnlyShell ( command ) { 279const text = String ( command ?? '' ). trim (); 280if ( ! text || text . length > 600 ) return false ; 281if ( SAFE_VERSION . test ( text )) return true ; 282const quoted = []; 283const masked = maskQuotes ( text , quoted ); 284if ( masked === null || UNSAFE_SYNTAX . test ( masked )) return false ; 285let next = 0 ; 286const tokens = masked . split ( '|' ). map ( segment => segment . trim ()). map ( segment => words ( segment ). map ( w => ( w === '"_"' ?{ t :quoted [ next ++ ] ?? '' , q :true } :{ t :w , q :false }))); 287return tokens . every (( segment ) => { 288if ( ! segment . length || segment [ 0 ]. q ) return false ; 289const first = segment [ 0 ]. t . toLowerCase (). replace ( / ^\.\\ / , '' ); 290if ( first === 'git' ) { 291const sub = segment [ 1 ]; 292const sp = sub && ! sub . q ?GIT . get ( sub . t ) :null ; 293return !! sp && argumentsAreSafe ( sp , segment . slice ( 2 )); 294} 295const sp = SPECS . get ( first ); 296return !! sp && argumentsAreSafe ( sp , segment . slice ( 1 )); 297}); 298} 299 300const clip = ( value , max ) => { 301const text = String ( value ?? '' ). replace ( / \s +/ g , ' ' ). trim (); 302return text . length > max ?` ${ text . slice ( 0 , max - 1 )} …` :text ; 303}; 304 305/** The tools that reach the internet. In Manual the first one in a chat asks once; the answer holds for the rest of that chat. */ 306export const WEB_TOOLS = new Set ([ 'web_search' , 'web_fetch' ]); 307/** What the model reads when the person says no. Plain words, and it tells the model what to do next. */ 308export const WEB_REFUSAL = 'The person did not allow web access, so nothing was searched or opened. Go on without it and say so.' ; 309 310/** 311* The question for a web call, in plain words: what is about to leave this computer and where it goes. 312* @param { {name:string, arguments:any} } exec 313* @param { {provider?: string} } [options] provider is the search service's name as the person knows it 314*/ 315export function webDecision ( exec , options = {}) { 316const tool = String ( exec . name ?? '' ); 317const args = exec . arguments && typeof exec . arguments === 'object' ?exec . arguments :{}; 318if ( tool === 'web_search' ) { 319const queries = Array . isArray ( args . queries ) ?args . queries :[ args . query ?? args . q ]; 320const words = clip ( queries . filter ( q => typeof q === 'string' && q . trim ()). join ( '; ' ), 160 ); 321return { kind :'ask' , web :true , reason :`The assistant wants to search the web for: ${ words } . Search words go to ${ options . provider || 'the search service' } .` }; 322} 323return { kind :'ask' , web :true , reason :`The assistant wants to open the web page ${ clip ( args . url , 200 )} . The page's site sees the request.` }; 324} 325 326/** 327* The decision for one call in Manual mode, or null when it needs no question. 328* @param { {name:string, arguments:any} } exec 329* @param { {provider?: string} } [options] 330* @returns { {kind:'ask', reason:string, web?:true}|null } 331*/ 332export function manualDecision ( exec , options = {}) { 333const tool = String ( exec . name ?? '' ); 334const args = exec . arguments && typeof exec . arguments === 'object' ?exec . arguments :{}; 335if ( WEB_TOOLS . has ( tool )) return webDecision ( exec , options ); 336if ( READ_ONLY_TOOLS . has ( tool )) return null ; 337if ( SHELL_TOOLS . has ( tool )) { 338if ( isReadOnlyShell ( args . command )) return null ; 339const what = args . description ?clip ( args . description , 160 ) :clip ( args . command , 160 ); 340return { kind :'ask' , reason :`Run a command that may change things: ${ what } ` }; 341} 342if ( tool === 'write' ) return { kind :'ask' , reason :`Create or replace the file ${ clip ( args . file_path ?? args . path , 200 )} ` }; 343if ( tool === 'edit' ) return { kind :'ask' , reason :`Change the file ${ clip ( args . file_path ?? args . path , 200 )} ` }; 344if ( tool === 'job_kill' ) return { kind :'ask' , reason :'Stop a background task' }; 345if ( tool . startsWith ( LOOK_ONLY_SERVER )) return null ; 346if ( tool . startsWith ( BROWSER_SERVER )) return browserDecision ( tool . slice ( BROWSER_SERVER . length ), args ); 347if ( tool . startsWith ( COMMANDS_SERVER )) return { kind :'ask' , reason :`Run your tool “ ${ tool . slice ( COMMANDS_SERVER . length ). replace ( / _ / g , ' ' )} ” ${ args . input ? ` with: ${ clip ( args . input , 120 )} ` : '' } ` }; 348if ( tool . startsWith ( 'mcp__' )) return { kind :'ask' , reason :`Use the connected tool ${ tool . split ( '__' ). slice ( 1 ). join ( ' / ' )} ` }; 349return { kind :'ask' , reason :`Use the tool ${ tool } ` }; 350} 351 352/** The browser in plain words: opening a page, clicking or typing asks; looking at what is already open does not. */ 353function browserDecision ( name , args ) { 354if ( BROWSER_LOOKING . has ( name ) || ( name === 'browser_tabs' && args . action === 'list' )) return null ; 355const url = clip ( args . url , 200 ); 356if ( name === 'browser_navigate' ) return { kind :'ask' , reason :`Open the web page ${ url } ` }; 357if ( name === 'browser_click' || name === 'browser_hover' || name === 'browser_drag' ) return { kind :'ask' , reason :`Click on the page ${ args . element ? `: ${ clip ( args . element , 120 )} ` : '' } ` }; 358if ( name === 'browser_type' || name === 'browser_fill_form' || name === 'browser_press_key' || name === 'browser_select_option' ) return { kind :'ask' , reason :`Type into the page ${ args . element ? `: ${ clip ( args . element , 120 )} ` : '' } ` }; 359if ( name === 'browser_file_upload' ) return { kind :'ask' , reason :'Send a file from this computer to the page' }; 360if ( name === 'browser_evaluate' || name === 'browser_run_code' ) return { kind :'ask' , reason :'Run a small program inside the web page' }; 361return { kind :'ask' , reason :`Use the browser ( ${ name . replace ( / ^browser_ / , '' ). replace ( / _ / g , ' ' )} )` }; 362} 363 364/** 365* Plan mode changes nothing. A connected tool (a person's tool server, a command they wrote, the browser) is not under the sandbox, so 366* Plan refuses it instead of letting it run. The look-only instruction tools are fine. 367* @returns { {kind:'deny', reason:string}|null } 368*/ 369export function planDecision ( exec ) { 370const tool = String ( exec . name ?? '' ); 371if ( ! tool . startsWith ( 'mcp__' ) || tool . startsWith ( LOOK_ONLY_SERVER )) return null ; 372return { kind :'deny' , reason :'Plan mode only looks and changes nothing, so it cannot use this tool. Switch to Manual or Bypass to use it.' }; 373} 374 375/** 376* @param { object } ctx 377* @param { {web?: {provider?: string, skipAsk?: boolean}} } [config] `web.provider`: the search service's name for the question; 378* `web.skipAsk`: the person's switch in Settings -> Tools, "search the web without asking" (off unless they turned it on) 379*/ 380export function apply ( ctx , config = {}) { 381const web = config . web ?? {}; 382/** Chats (their first session) where the person said yes to the web. One yes holds for the rest of the chat. */ 383const webAllowed = new Set (); 384/** A question already on the screen for a chat, so two searches started together share one card. */ 385const webAsking = new Map (); 386const chatOf = ( session , depth = 0 ) => { 387const parentId = session . header ?. parentSession ; 388if ( session . header ?. origin === 'subagent' && parentId && depth < 6 ) { 389const parent = ctx . sessions . get ( parentId ); 390if ( parent ) return chatOf ( parent , depth + 1 ); 391} 392return session . id ; 393}; 394async function askWeb ( exec , gate , agent ) { 395const chat = chatOf ( agent . session ); 396let question = webAsking . get ( chat ); 397if ( ! question ) { 398question = ctx . approval . request ({ agent, toolName :exec . name , callId :exec . callId , reason :gate . reason , displayReason :{ en :gate . reason }, signal :exec . signal }); 399webAsking . set ( chat , question ); 400const forget = () => { if ( webAsking . get ( chat ) === question ) webAsking . delete ( chat ); }; 401question . then ( forget , forget ); 402} 403const outcome = await question ; 404if ( outcome === 'allowed-once' ) { webAllowed . add ( chat ); return null ; } 405if ( outcome === 'cancelled' ) return { kind :'cancel' }; 406return { kind :'deny' , reason :WEB_REFUSAL }; 407} 408 409/** The preset a session is really working under: a child follows the chat that started it. */ 410const effectivePreset = ( session , depth = 0 ) => { 411const parentId = session . header ?. parentSession ; 412if ( session . header ?. origin === 'subagent' && parentId && depth < 6 ) { 413const parent = ctx . sessions . get ( parentId ); 414if ( parent ) return effectivePreset ( parent , depth + 1 ); 415} 416return ctx . permissionPresets . current ( session ); 417}; 418 419ctx . on ( 'tools/pre-execute' , async ( exec , next ) => { 420const agent = exec . agent ; 421if ( ! agent || exec . name === 'run_code' ) return next (); 422// Fail closed (T4): a session whose preset cannot be read (a reset in progress, a helper whose chat is gone) is treated as Manual, so 423// anything this file cannot prove is read-only still asks. It used to run unasked. 424let preset ; 425try { preset = effectivePreset ( agent . session ); } catch ( e ) { 426preset = MANUAL_PRESET ; 427try { console . warn ( `[strata-gate] could not read the permission mode for this call ( ${ e ?. message ?? e } ); treating it as Manual` ); } catch { /* logging must never decide a permission */ } 428} 429// A helper that was set to ask while the chat was in Manual must stop asking the moment the chat leaves Manual, 430// so a mode change applies to the very next tool call of a running goal and its helpers. 431if ( preset !== MANUAL_PRESET && agent . session . header ?. origin === 'subagent' && ctx . approval . overrideOf ( agent . session ) === 'ask' ) { 432agent . session . append ( 'approval/policy' , { policy :'never' }); 433} 434if ( preset === PLAN_PRESET ) return planDecision ( exec ) ?? next (); 435if ( preset !== MANUAL_PRESET ) return next (); 436const gate = manualDecision ( exec , { provider :web . provider }); 437if ( ! gate ) return next (); 438if ( gate . web ) { 439// The person's switch, or a yes already given in this chat: no question. 440if ( web . skipAsk === true || webAllowed . has ( chatOf ( agent . session ))) return next (); 441// A helper's own approval policy is `never`; it must be `ask` for the question to reach the person. 442if ( agent . session . header ?. origin === 'subagent' && ctx . approval . overrideOf ( agent . session ) !== 'ask' ) { 443agent . session . append ( 'approval/policy' , { policy :'ask' }); 444} 445return ( await askWeb ( exec , gate , agent )) ?? next (); 446} 447// A child's approval policy is pinned to `never` by the Harness; asking is how its request reaches the person. 448if ( agent . session . header ?. origin === 'subagent' && ctx . approval . overrideOf ( agent . session ) !== 'ask' ) { 449agent . session . append ( 'approval/policy' , { policy :'ask' }); 450} 451const downstream = await next (); 452if ( downstream . kind !== 'allow' ) return downstream ; 453return { kind :'ask' , reason :gate . reason , displayReason :{ en :gate . reason } }; 454}, { prepend :true }); 455 456// Lets the host prove the gate is live before it starts a Manual turn. 457ctx . inject ([ 'commands' ], ( commandCtx ) => { 458commandCtx . commands . register ({ 459definitionId :'strata-gate' , 460name :'strata-gate' , 461description :'Reports that the Strata approval gate is active' , 462handler :() => ({ kind :'success' , text :'strata-gate active' }), 463}); 464}); 465}