UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

11 lines (10 loc) • 37.4 kB
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } } import{ALLOW,NARROW,combine,defer,describe,dynamicVerdict,judgeGroup,judgeKill,judgeTargets,optionTable,protectedSet,refuse,refuseAll,rowOf,signalNumberOrName,situationOf,vantageChain}from"./chunk-WOHQJ6JB.js";import{spawnSync}from"node:child_process";var SegmentSink=class{constructor(){this.segments=[],this.pipelines=0}newPipeline(){return this.pipelines+=1,this.pipelines}},Unparsed=class extends Error{},MAX_DEPTH=12,MAX_COMMAND_LENGTH=64*1024,MAX_STEPS=4e6,CANDIDATE_WORDS=3,steps=0,step=(count=1)=>{steps+=count,steps>MAX_STEPS&&fail()},fail=()=>{throw new Unparsed},isDigits=text=>/^[0-9]+$/.test(text),NAME_CHAR=/[A-Za-z0-9_]/,ASSIGNMENT=/^[A-Za-z_][A-Za-z0-9_]*(\[[^\]]*\])?\+?=/,isAssignment=word=>{let match=ASSIGNMENT.exec(word.text);return match!==null&&match[0].length<=word.plainPrefix};function matchParen(source,start){let depth=1,index=start;for(;index<source.length;){step();let char=source[index];if(char==="\\"){index+=2;continue}if(char==="'"){let end=source.indexOf("'",index+1);end<0&&fail(),index=end+1;continue}if(char==='"'){index=skipDoubleQuoted(source,index+1);continue}if(char==="`"){index=skipBackticks(source,index+1);continue}if(char==="("&&(depth+=1),char===")"&&(depth-=1,depth===0))return index+1;index+=1}return fail()}function skipDoubleQuoted(source,start){let index=start;for(;index<source.length;){step();let char=source[index];if(char==="\\"){index+=2;continue}if(char==='"')return index+1;if(char==="`"){index=skipBackticks(source,index+1);continue}if(char==="$"&&source[index+1]==="("){index=matchParen(source,index+2);continue}index+=1}return fail()}function skipBackticks(source,start){let index=start;for(;index<source.length;){step();let char=source[index];if(char==="\\"){index+=2;continue}if(char==="`")return index+1;index+=1}return fail()}function matchBrace(source,start){let depth=1,index=start;for(;index<source.length;){step();let char=source[index];if(char==="\\"){index+=2;continue}if(char==="'"){let end=source.indexOf("'",index+1);end<0&&fail(),index=end+1;continue}if(char==='"'){index=skipDoubleQuoted(source,index+1);continue}if(char==="`"){index=skipBackticks(source,index+1);continue}if(char==="$"&&source[index+1]==="("){index=matchParen(source,index+2);continue}if(char==="{"&&(depth+=1),char==="}"&&(depth-=1,depth===0))return index+1;index+=1}return fail()}function isArithmetic(source,open){let outerEnd=matchParen(source,open+1);return matchParen(source,open+2)===outerEnd-1}function unescapeBackticks(body){return body.replace(/\\([$`\\])/g,"$1")}var Lexer=class _Lexer{constructor(source,depth,sink){this.index=0,this.words=[],this.pendingHeredocs=[],this.inDoubleBracket=!1,this.textDepth=0,depth>MAX_DEPTH&&fail(),this.source=source,this.depth=depth,this.sink=sink,this.pipeline=sink.newPipeline()}run(){let source=this.source;for(;this.index<source.length;){step();let char=source[this.index];if(this.word===void 0&&char==="#"){for(;this.index<source.length&&source[this.index]!==` `;)this.index+=1;continue}if(char===" "||char===" "){this.endWord(),this.index+=1;continue}if(char===` `){this.endSegment(),this.index+=1,this.readHeredocBodies();continue}if(char==="\\"){if(source[this.index+1]===` `){this.index+=2;continue}this.index+1>=source.length&&fail(),this.append(source[this.index+1],{quoted:!0}),this.index+=2;continue}if(char==="'"){let end=source.indexOf("'",this.index+1);end<0&&fail(),this.append(source.slice(this.index+1,end),{quoted:!0}),this.index=end+1;continue}if(char==='"'){this.readDoubleQuoted();continue}if(char==="`"){let end=skipBackticks(source,this.index+1);this.nested(unescapeBackticks(source.slice(this.index+1,end-1))),this.append("",{dynamic:!0}),this.index=end;continue}if(char==="$"){this.readDollar();continue}if(this.inDoubleBracket&&!(this.word!==void 0&&!this.word.quoted&&this.word.text==="]]")){this.append(char,{}),this.index+=1;continue}if((char==="<"||char===">")&&source[this.index+1]==="("&&this.word===void 0){let end=matchParen(source,this.index+2);this.nested(source.slice(this.index+2,end-1)),this.append("",{dynamic:!0}),this.index=end;continue}if(char==="<"||char===">"){this.readRedirection();continue}if(char==="&"){if(source[this.index+1]===">"){this.endWord(),this.index+=source[this.index+2]===">"?3:2,this.redirectNext={};continue}this.endSegment(),this.index+=source[this.index+1]==="&"?2:1;continue}if(char==="|"){let orList=source[this.index+1]==="|";this.endSegment(!orList),this.index+=orList||source[this.index+1]==="&"?2:1;continue}if(char===";"){(source[this.index+1]===";"||source[this.index+1]==="&")&&fail(),this.endSegment(),this.index+=1;continue}if(char==="("){this.readOpenParen();continue}char===")"&&fail(),this.append(char,{}),this.word!==void 0&&char==="{"&&(this.word.brace=!0),this.word!==void 0&&(char==="*"||char==="?"||char==="[")&&(this.word.glob=!0),this.index+=1}this.endSegment(),this.pendingHeredocs=[]}append(text,flags){this.word===void 0&&(this.word={text:"",dynamic:!1,quoted:!1,plainPrefix:0,plainEnded:!1,brace:!1,glob:!1});let word=this.word;flags.dynamic&&word.dynamicAt===void 0&&(word.dynamicAt=word.text.length),word.text+=text,flags.dynamic&&(word.dynamic=!0),flags.quoted&&(word.quoted=!0),(flags.dynamic||flags.quoted)&&(word.plainEnded=!0),word.plainEnded||(word.plainPrefix=word.text.length)}nested(source){new _Lexer(source,this.depth+this.textDepth+1,this.sink).run()}endWord(){let word=this.word;if(this.word=void 0,word!==void 0){if(word.brace&&/\{[^}]*(,|\.\.)[^}]*\}/.test(word.text)&&(word.dynamic=!0,word.dynamicAt??=0),word.glob&&word.text!=="["&&word.text!=="[["&&(word.dynamic=!0,word.dynamicAt??=0),this.redirectNext!==void 0){let heredoc=this.redirectNext.heredoc;this.redirectNext=void 0,heredoc!==void 0&&(word.dynamic&&fail(),this.pendingHeredocs.push({delimiter:word.text,expands:!word.quoted,stripTabs:heredoc.stripTabs}));return}!word.quoted&&word.text==="[["&&this.words.every(leader=>!leader.quoted&&RESERVED_LEADERS.has(leader.text))&&(this.inDoubleBracket=!0),!word.quoted&&word.text==="]]"&&this.inDoubleBracket&&(this.inDoubleBracket=!1),this.words.push(word)}}endSegment(pipesOn=!1){this.endWord(),this.redirectNext!==void 0&&fail(),this.inDoubleBracket&&fail(),this.words.length>0&&this.sink.segments.push({words:this.words,pipeline:this.pipeline}),this.words=[],pipesOn||(this.pipeline=this.sink.newPipeline())}readDoubleQuoted(){let source=this.source;for(this.append("",{quoted:!0}),this.index+=1;this.index<source.length;){let char=source[this.index];if(char==='"'){this.index+=1;return}if(char==="\\"){let next=source[this.index+1];if(next===void 0&&fail(),next===` `){this.index+=2;continue}this.append('$`"\\'.includes(next)?next:`\\${next}`,{}),this.index+=2;continue}if(char==="`"){let end=skipBackticks(source,this.index+1);this.nested(unescapeBackticks(source.slice(this.index+1,end-1))),this.append("",{dynamic:!0}),this.index=end;continue}if(char==="$"){this.readDollar();continue}this.append(char,{}),this.index+=1}fail()}readDollar(){let source=this.source,next=source[this.index+1];if(next==="("&&source[this.index+2]==="("&&isArithmetic(source,this.index+1)){let end=matchParen(source,this.index+2);this.nestedText(source.slice(this.index+3,end-2)),this.append("",{dynamic:!0}),this.index=end;return}if(next==="("){let end=matchParen(source,this.index+2);this.nested(source.slice(this.index+2,end-1)),this.append("",{dynamic:!0}),this.index=end;return}if(next==="{"){let end=matchBrace(source,this.index+2);this.nestedText(source.slice(this.index+2,end-1)),this.append("",{dynamic:!0}),this.index=end;return}if(next==="'"){let index=this.index+2;for(;index<source.length&&source[index]!=="'";)index+=source[index]==="\\"?2:1;index>=source.length&&fail(),this.append("",{dynamic:!0,quoted:!0}),this.index=index+1;return}if(next!==void 0&&(NAME_CHAR.test(next)||"@*#?$!-".includes(next))){let index=this.index+1;if(NAME_CHAR.test(next)&&!/[0-9]/.test(next))for(;index<source.length&&NAME_CHAR.test(source[index]);)index+=1;else index+=1;this.append("",{dynamic:!0}),this.index=index;return}this.append("$",{}),this.index+=1}nestedText(text){this.textDepth+=1,this.depth+this.textDepth>MAX_DEPTH&&fail();try{this.scanText(text)}finally{this.textDepth-=1}}scanText(text){let index=0;for(;index<text.length;){let char=text[index];if(char==="\\"){index+=2;continue}if(char==="`"){let end=skipBackticks(text,index+1);this.nested(unescapeBackticks(text.slice(index+1,end-1))),index=end;continue}if(char==="$"&&text[index+1]==="("){let end=matchParen(text,index+2);text[index+2]==="("&&isArithmetic(text,index+1)?this.nestedText(text.slice(index+3,end-2)):this.nested(text.slice(index+2,end-1)),index=end;continue}if(char==="$"&&text[index+1]==="{"){let end=matchBrace(text,index+2);this.nestedText(text.slice(index+2,end-1)),index=end;continue}index+=1}}readRedirection(){let source=this.source,word=this.word;word!==void 0&&!word.quoted&&!word.dynamic&&isDigits(word.text)?this.word=void 0:this.endWord();let char=source[this.index],next=source[this.index+1];if(char==="<"&&next==="<"&&source[this.index+2]==="<"){this.index+=3,this.redirectNext={};return}if(char==="<"&&next==="<"){let stripTabs=source[this.index+2]==="-";this.index+=stripTabs?3:2,this.redirectNext={heredoc:{stripTabs}};return}this.index+=1,char===">"&&(next===">"||next==="|"||next==="&")?this.index+=1:char==="<"&&(next===">"||next==="&")&&(this.index+=1),this.redirectNext={}}readOpenParen(){let source=this.source,word=this.word;if(word!==void 0){(word.quoted||!/^[A-Za-z_][A-Za-z0-9_]*\+?=$/.test(word.text))&&fail();let end2=matchParen(source,this.index+1);this.nestedText(source.slice(this.index+1,end2-1)),this.append("",{dynamic:!0}),this.index=end2;return}if(source[this.index+1]==="("&&isArithmetic(source,this.index)){let end2=matchParen(source,this.index+1);this.nestedText(source.slice(this.index+2,end2-2)),this.index=end2;return}let end=matchParen(source,this.index+1);this.endSegment(),this.nested(source.slice(this.index+1,end-1)),this.index=end}readHeredocBodies(){let source=this.source;for(let heredoc of this.pendingHeredocs){let body=[];for(;!(this.index>=source.length);){let lineEnd=source.indexOf(` `,this.index),end=lineEnd<0?source.length:lineEnd,raw=source.slice(this.index,end);this.index=lineEnd<0?source.length:lineEnd+1;let line=heredoc.stripTabs?raw.replace(/^\t+/,""):raw;if(line===heredoc.delimiter)break;body.push(line)}heredoc.expands&&this.nestedText(body.join(` `))}this.pendingHeredocs=[]}},RESERVED_LEADERS=new Set(["!","{","}","if","then","else","elif","fi","do","done","while","until"]),UNSUPPORTED_LEADERS=new Set(["case","esac","function","coproc"]),LOOP_HEADERS=new Set(["for","select"]),SHELLS=new Set(["bash","sh","zsh","dash","ksh","mksh","ash","yash","posh","fish","csh","tcsh"]),opts=(flags,values="")=>({...Object.fromEntries(flags.split(" ").filter(Boolean).map(name=>[name,!0])),...Object.fromEntries(values.split(" ").filter(Boolean).map(name=>[name,"value"]))});function skipOptions(words,start,table){let index=start;for(;index<words.length;){let word=words[index];word.dynamic&&fail();let text=word.text;if(text==="--")return index+1;if(!text.startsWith("-")||text==="-")return index;if(text.startsWith("--")){let separator=text.indexOf("="),name=separator<0?text:text.slice(0,separator),kind=table[name];kind===void 0&&fail(),index+=kind==="value"&&separator<0?2:1;continue}if(table[text]==="value"){index+=2;continue}if(table[text]===!0){index+=1;continue}let letters=text.slice(1).split(""),consumed=1;for(let[position,letter]of letters.entries()){let kind=table[`-${letter}`];if(kind===void 0){if(/^-[0-9]+$/.test(text)&&table["-N"]===!0)break;fail()}if(kind==="value"){position===letters.length-1&&(consumed=2);break}}index+=consumed}return index}var WRAPPER_OPTIONS={command:opts("-p -v -V"),builtin:opts(""),exec:opts("-c -l","-a"),nohup:opts(""),time:opts("-p -l -v -a --portability --verbose --append","-o -f --output --format"),nice:opts("-N","-n --adjustment"),stdbuf:opts("","-i -o -e --input --output --error"),caffeinate:opts("-d -i -m -s -u","-t -w"),sudo:opts("-A -b -E -H -K -k -n -P -S -V -v --askpass --background --preserve-env --set-home --non-interactive --stdin","-u -g -h -p -C -D -r -t -U -T --user --group --host --prompt --close-from --chdir --role --type --other-user --command-timeout"),doas:opts("-n -s","-u -C"),setsid:opts("-c -f -w --ctty --fork --wait"),ionice:opts("-t --ignore","-c -n --class --classdata")},ENV_OPTIONS=opts("-i -0 -v --ignore-environment --null --debug","-u -C --unset --chdir"),TIMEOUT_OPTIONS=opts("-v --preserve-status --foreground --verbose","-s -k --signal --kill-after"),XARGS_OPTIONS=opts("-0 -r -t -p -x -o --null --no-run-if-empty --verbose --interactive --exit --open-tty","-I -L -n -P -s -d -E -a --max-lines --max-args --max-procs --max-chars --delimiter --eof --arg-file --replace --process-slot-var"),SHELL_OPTIONS=opts("-e -u -x -v -f -n -l -i -s -p -a -b -h -k -m -B -C -E -H -P -T --login --norc --noprofile --posix --restricted --noediting -c","-o -O --rcfile --init-file"),pathBasename=text=>{let parts=text.split("/");return parts[parts.length-1]??text},expandSimpleCommand=(input,out,place)=>{let words=input,start=0;for(;start<words.length;){let word=words[start];if(!word.quoted&&RESERVED_LEADERS.has(word.text)){start+=1;continue}if(!word.quoted&&UNSUPPORTED_LEADERS.has(word.text)&&fail(),isAssignment(word)){start+=1;continue}break}words=words.slice(start);let first=words[0];if(first===void 0)return;if(!first.quoted&&LOOP_HEADERS.has(first.text)){if(words.length===1||words.length===2||words[2]?.text==="in")return;fail()}(first.dynamic||first.text==="")&&fail();let name=pathBasename(first.text);name===""&&fail();let rest=words.slice(1),own={line:[name,...rest.map(word=>word.text)],name,nameSpelling:first.text,words:rest,...place},wrapperEntry={line:[name],name,nameSpelling:first.text,words:[],...place},inside={wrappers:[...place.wrappers,{name,words:rest.map(publicWord)}],pipeline:place.pipeline},expandScript=script=>{for(let segment of lexSegments(script))expandSimpleCommand(segment.words,out,{...inside,pipeline:segment.pipeline})};if(SHELLS.has(name)){out.push(wrapperEntry);let commandIndex=shellCommandIndex(rest);if(commandIndex===void 0){out.push(own);return}let script=rest[commandIndex];(script===void 0||script.dynamic)&&fail(),expandScript(script.text);return}if(name==="eval"){out.push(wrapperEntry),rest.some(word=>word.dynamic)&&fail();let args=rest[0]?.text==="--"?rest.slice(1):rest;expandScript(args.map(word=>word.text).join(" "));return}if(name==="su"){out.push(wrapperEntry);let script=suCommand(rest);if(script===void 0)return;expandScript(script);return}if(name==="trap"){out.push(wrapperEntry);let scriptIndex=rest.findIndex(word=>!word.text.startsWith("-")),script=scriptIndex<0?void 0:rest[scriptIndex];if(script===void 0)return;script.dynamic&&fail(),expandScript(script.text);return}if(name==="env"){out.push(wrapperEntry),rest.some(word=>!word.dynamic&&(word.text==="-S"||word.text.startsWith("--split-string")))&&fail();let index=skipOptions(rest,0,ENV_OPTIONS);for(;index<rest.length&&!rest[index].dynamic&&/^[^=]+=/.test(rest[index].text);)index+=1;expandSimpleCommand(rest.slice(index),out,inside);return}if(name==="timeout"){out.push(wrapperEntry);let index=skipOptions(rest,0,TIMEOUT_OPTIONS);expandSimpleCommand(rest.slice(index+1),out,inside);return}if(name==="xargs"){out.push(wrapperEntry),expandSimpleCommand(rest.slice(skipOptions(rest,0,XARGS_OPTIONS)),out,inside);return}if(name==="find"){out.push(own),rest.some(word=>word.dynamic)&&fail();for(let index=0;index<rest.length;index+=1){if(!["-exec","-execdir","-ok","-okdir"].includes(rest[index].text))continue;let end=index+1;for(;end<rest.length&&rest[end].text!==";"&&rest[end].text!=="+";)end+=1;end>=rest.length&&fail(),expandSimpleCommand(rest.slice(index+1,end),out,inside),index=end}return}let wrapperOptions=WRAPPER_OPTIONS[name];if(wrapperOptions!==void 0){out.push(wrapperEntry),expandSimpleCommand(rest.slice(skipOptions(rest,0,wrapperOptions)),out,inside);return}out.push(own)};function suCommand(rest){for(let index=0;index<rest.length;index+=1){let word=rest[index],text=word.text,long=/^--(session-)?command(=|$)/.exec(text);if(long){let value=long[2]==="="?text.slice(long[0].length):rest[index+1]?.text,source=long[2]==="="?word:rest[index+1];return(value===void 0||source===void 0||source.dynamic)&&fail(),value}if(/^-[A-Za-z]*c/.test(text)&&!text.startsWith("--")){let attached=text.slice(text.indexOf("c")+1),source=attached===""?rest[index+1]:word;return(source===void 0||source.dynamic)&&fail(),attached===""?source.text:attached}}}function shellCommandIndex(rest){let index=0,hasCommandFlag=!1;for(;index<rest.length;){let word=rest[index];word.dynamic&&fail();let text=word.text;if(text==="--"||text==="-"){index+=1;break}if(!text.startsWith("-")&&!text.startsWith("+"))break;if(text.startsWith("--")){let kind=SHELL_OPTIONS[text.split("=")[0]];kind===void 0&&fail(),index+=kind==="value"&&!text.includes("=")?2:1;continue}let letters=text.slice(1);letters.includes("c")&&(hasCommandFlag=!0);for(let letter of letters)SHELL_OPTIONS[`-${letter}`]===void 0&&fail();index+=letters.includes("o")||letters.includes("O")?2:1}return hasCommandFlag?index:void 0}function lexSegments(command){let sink=new SegmentSink;return new Lexer(command,0,sink).run(),sink.segments}function publicWord(word){return{text:word.text,dynamic:word.dynamic,quoted:word.quoted,literalPrefix:word.dynamicAt===void 0?word.text:word.text.slice(0,word.dynamicAt)}}function analyze(command){if(steps=0,!(command.length>MAX_COMMAND_LENGTH))try{let out=[];for(let segment of lexSegments(command))expandSimpleCommand(segment.words,out,{wrappers:[],pipeline:segment.pipeline});return out}catch{return}}function analyzeBashCommand(command){let entries=analyze(command);return entries===void 0?{kind:"unparsed"}:{kind:"parsed",segments:entries.map(entry=>entry.line)}}function analyzeBashCommandWords(command){let entries=analyze(command);return entries===void 0?{kind:"unparsed"}:{kind:"parsed",segments:entries.map(entry=>({name:entry.name,nameSpelling:entry.nameSpelling,nameIsPath:entry.nameSpelling.includes("/"),words:entry.words.map(publicWord),wrappers:entry.wrappers,pipeline:entry.pipeline}))}}function bestEffortCommandLines(command){let words=command.split(/[\s;&|()<>`$'"{}\\]+/).filter(word=>/^[A-Za-z0-9._+/-]+$/.test(word)).map(pathBasename).filter(word=>word!=="");return words.map((_word,index)=>words.slice(index,index+CANDIDATE_WORDS))}var Unreadable=class extends Error{},ANY_CHAR_ESCAPES=new Set(["w","W","s","S","d","D"]),ZERO_WIDTH_ESCAPES=new Set(["b","B","<",">","`","'"]),MAX_PATTERN_LENGTH=4096,MAX_DEPTH2=64,Reader=class{constructor(source){this.index=0,this.emptyBranch=!1,this.source=source}read(){let shape=this.alternation(0);if(this.index<this.source.length)throw new Unreadable(`unbalanced ")" at offset ${this.index}`);return shape}alternation(depth){if(depth>MAX_DEPTH2)throw new Unreadable("nested too deeply");let branches=[this.branch(depth)];for(;this.source[this.index]==="|";)this.index+=1,branches.push(this.branch(depth));return{nullable:branches.some(branch=>branch.nullable),minLiterals:Math.min(...branches.map(branch=>branch.minLiterals))}}branch(depth){let nullable=!0,minLiterals=0,pieces=0;for(;this.index<this.source.length;){let char=this.source[this.index];if(char==="|"||char===")")break;let piece=this.piece(depth);pieces+=1,nullable&&=piece.nullable,minLiterals+=piece.minLiterals}return pieces===0&&(this.emptyBranch=!0),{nullable,minLiterals}}piece(depth){let shape=this.atom(depth);for(;;){let char=this.source[this.index];if(char==="*"||char==="?"){this.index+=1,shape={nullable:!0,minLiterals:0};continue}if(char==="+"){this.index+=1;continue}if(char==="{"){let minimum=this.interval();shape=minimum===0?{nullable:!0,minLiterals:0}:{...shape,minLiterals:shape.minLiterals*minimum};continue}return shape}}interval(){let match=/^\{(\d+)(,(\d*))?\}/.exec(this.source.slice(this.index));if(match===null)throw new Unreadable(`bad interval at offset ${this.index}`);let minimum=Number(match[1]),maximum=match[3]===void 0?minimum:match[3]===""?Number.POSITIVE_INFINITY:Number(match[3]);if(minimum>maximum)throw new Unreadable(`bad interval at offset ${this.index}`);return this.index+=match[0].length,minimum}atom(depth){let char=this.source[this.index];if(char==="*"||char==="+"||char==="?"||char==="{")throw new Unreadable(`"${char}" at offset ${this.index} repeats nothing`);if(char==="("){this.index+=1;let inner=this.alternation(depth+1);if(this.source[this.index]!==")")throw new Unreadable('unbalanced "("');return this.index+=1,inner}if(char==="[")return this.bracket(),{nullable:!1,minLiterals:0};if(char==="^"||char==="$")return this.index+=1,{nullable:!0,minLiterals:0};if(char===".")return this.index+=1,{nullable:!1,minLiterals:0};if(char==="\\"){let escaped=this.source[this.index+1];if(escaped===void 0)throw new Unreadable("trailing backslash");return this.index+=2,ANY_CHAR_ESCAPES.has(escaped)?{nullable:!1,minLiterals:0}:ZERO_WIDTH_ESCAPES.has(escaped)?{nullable:!0,minLiterals:0}:{nullable:!1,minLiterals:1}}return this.index+=1,{nullable:!1,minLiterals:1}}bracket(){let index=this.index+1;for(this.source[index]==="^"&&(index+=1),this.source[index]==="]"&&(index+=1);index<this.source.length;){let char=this.source[index];if(char==="]"){this.index=index+1;return}if(char==="["&&":=.".includes(this.source[index+1]??"")){let delimiter=this.source[index+1],close=this.source.indexOf(`${delimiter}]`,index+2);if(close<0)throw new Unreadable(`unterminated "[${delimiter}"`);index=close+2;continue}index+=1}throw new Unreadable('unbalanced "["')}};function readPattern(pattern){if(pattern.length>MAX_PATTERN_LENGTH)return{kind:"unparsable",why:"it is too long to read"};let reader=new Reader(pattern);try{let shape=reader.read();return{kind:"parsed",emptyBranch:reader.emptyBranch,nullable:shape.nullable,minLiterals:shape.minLiterals}}catch(error){if(error instanceof Unreadable)return{kind:"unparsable",why:error.message};throw error}}function judgePattern(pattern,mode){let reading=readPattern(pattern);if(reading.kind==="unparsable")return{broad:!0,why:`cannot be read as a regular expression (${reading.why})`};if(reading.emptyBranch)return{broad:!0,why:"has an empty alternative, which matches every process"};if(reading.nullable)return{broad:!0,why:"can match the empty string, so it matches every process"};let needed=mode==="exact"?1:2;if(reading.minLiterals>=needed)return{broad:!1};let plural=reading.minLiterals===1?"":"s";return{broad:!0,why:`has a match with ${reading.minLiterals} literal character${plural}, so it matches nearly every process`}}var literal=text=>({text,dynamic:!1,quoted:!1,literalPrefix:text});function expandClusters(words,table){return words.flatMap((word,index)=>{let text=word.text;if(word.dynamic||!/^-[A-Za-z]{2,}$/.test(text)||table.has(text))return[word];if(index===0&&signalNumberOrName(text.slice(1))!==void 0)return[word];let letters=text.slice(1).split("");return letters.every((letter,position)=>{let spec=table.get(`-${letter}`);return spec!==void 0&&(!spec.takesValue||position===letters.length-1)})?letters.map(letter=>literal(`-${letter}`)):[word]})}function splitOption(text,table){if(text.startsWith("--")){let equals=text.indexOf("=");return equals<0?[text,void 0]:[text.slice(0,equals),text.slice(equals+1)]}if(table.has(text))return[text,void 0];let head=text.slice(0,2);return table.get(head)?.takesValue?[head,text.slice(2)]:[text,void 0]}function forward(selection,spec,short,value){if(!spec.ignoreAncestors){if(selection.tool==="killall"){short==="-c"&&value!==void 0?selection.patterns.push(value):spec.selector&&value!==void 0&&selection.args.push(short,value);return}if(spec.callerRelative!==void 0&&value!==void 0&&value.split(",").includes("0")){selection.callerRelative.push({option:short,kind:spec.callerRelative});return}selection.args.push(short,...value===void 0?[]:[value])}}function applyOption(selection,spec,short,value){if(spec.signal){value!==void 0&&signalNumberOrName(value)?.zero===!0&&(selection.signalZero=!0);return}switch(spec.exact&&(selection.exact=!0),spec.regex&&(selection.regex=!0,selection.exact=!1),spec.groups&&(selection.groups=!0),spec.ancestors&&(selection.ancestors=!0),spec.ignoreAncestors&&(selection.ignoreAncestors=!0),spec.ignoreCase&&(selection.ignoreCase=!0),spec.selector&&(selection.selectors+=1),spec.action){case"allow":selection.sendsNothing=!0;return;case"unknown":selection.unknownOption??=short;return;case"drop":case"skip":return;case"forward":forward(selection,spec,short,value);return}}function readSelection(situation,tool,platform){let table=optionTable(tool,platform),selection={tool,patterns:[],args:[],exact:tool==="killall",regex:!1,groups:!1,ancestors:!1,ignoreAncestors:!1,ignoreCase:!1,selectors:0,signalZero:!1,sendsNothing:!1,callerRelative:[]},words=expandClusters(situation.segment.words,table),noteDynamic=what=>{selection.dynamic??=dynamicVerdict(situation,what)},optionsDone=!1;for(let index=0;index<words.length;index+=1){let word=words[index];if(word===void 0)continue;if(optionsDone||!word.literalPrefix.startsWith("-")||word.text==="-"){word.dynamic?noteDynamic("a dynamic pattern"):selection.patterns.push(word.text);continue}if(word.dynamic){noteDynamic("a dynamic option");continue}if(word.text==="--"){optionsDone=!0;continue}let signal=signalNumberOrName(word.text.slice(1));if(signal!==void 0&&(index===0||tool==="killall")){signal.zero&&(selection.signalZero=!0);continue}let[name,attached]=splitOption(word.text,table),spec=table.get(name);if(spec===void 0){selection.unknownOption??=word.text;continue}let value;if(spec.takesValue&&(value=attached===void 0?words[index+1]:literal(attached),attached===void 0&&(index+=1)),value?.dynamic){noteDynamic("a dynamic option value");continue}applyOption(selection,spec,spec.short??name,value?.text)}return selection}var escapeRegex=text=>text.replace(/[.^$|()[\]{}*+?\\]/g,"\\$&");function broadPatternHint(tool,mode,pattern,literalName){return mode==="substring"&&pattern.length===1&&tool==="pkill"?`Match the exact name instead: \`pkill -x ${pattern}\`.`:literalName?NARROW:"Anchor the pattern to the full command (`pkill -f '^<full command prefix>'`) or match the exact name with `-x`."}function judgeSelecting(situation,tool,context,pipedIntoKill2){if(tool==="pgrep"&&!pipedIntoKill2)return ALLOW;let selection=readSelection(situation,tool,context.platform);if(selection.sendsNothing||selection.signalZero||context.platform==="win32")return ALLOW;let mode=selection.exact?"exact":"substring";for(let pattern of selection.patterns){let verdict=judgePattern(pattern,mode);if(verdict.broad){let hint=broadPatternHint(tool,mode,pattern,tool==="killall"&&!selection.regex);return refuse("R1",`the pattern ${JSON.stringify(pattern)} ${verdict.why}`,hint)}}if(tool==="pgrep")return ALLOW;let spelling=situation.segment.nameSpelling;return selection.unknownOption!==void 0?refuse("R5",`\`${spelling}\` option ${selection.unknownOption} is not one the guard can resolve`,"Leave the option out or name the pid."):selection.dynamic!==void 0?selection.dynamic:selection.patterns.length===0&&selection.selectors===0?refuse("R3",`\`${spelling}\` with no name and no selector signals every process it can`,"Name the process."):judgeSelectionTargets(selection,context)}function dryRuns(selection,args){if(selection.tool!=="killall")return[[...args,...selection.patterns]];let base=selection.ignoreCase?[...args,"-i"]:[...args];return selection.patterns.length===0?[base]:selection.patterns.map(name=>selection.regex?[...base,name]:[...base,"-x",escapeRegex(name)])}function callerArgs(selection,context,rows){let args=[...selection.args];for(let relative of selection.callerRelative){let pid=context.vantage.kind==="agent"?context.agentPid:context.vantage.kind==="process"?context.vantage.pid:0,row=rowOf(rows,pid),id=row===void 0?0:relative.kind==="pgid"?row.pgid:row.sid;if(id<=0)return refuse("R5",`the caller's ${relative.kind==="pgid"?"process group":"session"} cannot be read`);args.push(relative.option,String(id))}return args}function judgeSelectionTargets(selection,context){if(selection.callerRelative.length>0&&context.vantage.kind==="fresh-session")return ALLOW;let view=context.view();if(view===void 0)return refuse("R5","the process table cannot be read, so what it selects cannot be checked");let args=callerArgs(selection,context,view.rows);if(!Array.isArray(args))return args;let bsd=context.platform!=="linux";bsd&&!selection.ancestors&&args.unshift("-a");let selected=new Set;for(let run of dryRuns(selection,args)){let result=view.select(run);if(!result.ok)return refuse("R5",`its selection cannot be resolved (${result.reason})`);for(let pid of result.pids)selected.add(pid)}if(selection.ignoreAncestors||bsd&&selection.tool==="pkill"&&!selection.ancestors)for(let pid of vantageChain(context,view.rows))selected.delete(pid);let protectedPids=protectedSet(context,view.rows);if(selection.groups){for(let pgid of new Set([...selected].map(pid=>rowOf(view.rows,pid)?.pgid??pid))){let verdict=judgeGroup(pgid,view.rows,protectedPids);if(verdict.action==="refuse")return verdict}return ALLOW}let hits=[...selected].filter(pid=>protectedPids.has(pid)).sort((a,b)=>a-b);if(hits.length===0)return ALLOW;let named=hits.map(pid=>describe(pid,view.rows,protectedPids.get(pid)??"protected"));return refuse("R2",`it would signal ${named.join(", ")}`)}var KILL_FAMILY=new Set(["kill","pkill","killall"]),basename=text=>text.split("/").pop()??text,quote=text=>`'${text.replaceAll("'","'\\''")}'`;function pipedIntoKill(segment,segments){let position=segments.indexOf(segment);return segments.some((other,index)=>index>position&&other.pipeline===segment.pipeline&&KILL_FAMILY.has(other.name))}function innerScript(segment){if(segment.name==="busybox")return segment.words.some(word=>word.dynamic)?void 0:segment.words.map(word=>quote(word.text)).join(" ");let index=segment.words.findIndex(word=>word.text==="--run"||word.text==="--command"),script=index<0?void 0:segment.words[index+1];return script===void 0||script.dynamic?void 0:script.text}function unwrapOpaque(segment){let wrapper={name:segment.name,words:segment.words};if(segment.name==="nix-shell"||segment.name==="busybox"){let script=innerScript(segment);if(script===void 0)return[];let inner=analyzeBashCommandWords(script);return inner.kind!=="parsed"?[]:inner.segments.map(child=>({...child,wrappers:[...segment.wrappers,wrapper,...child.wrappers]}))}if(segment.name!=="chroot"&&segment.name!=="systemd-run")return[];let index=segment.words.findIndex(word=>!word.dynamic&&KILL_FAMILY.has(basename(word.text))),command=index<0?void 0:segment.words[index];return command===void 0?[]:[{name:basename(command.text),nameSpelling:command.text,nameIsPath:command.text.includes("/"),words:segment.words.slice(index+1),wrappers:[...segment.wrappers,wrapper],pipeline:segment.pipeline}]}function judgeSegment(segment,segments,context){let situation=situationOf(segment,context);switch(segment.name){case"kill":return judgeKill(situation,context);case"pkill":case"killall":return judgeSelecting(situation,segment.name,context,!1);case"pgrep":return judgeSelecting(situation,"pgrep",context,pipedIntoKill(segment,segments));default:return combine(unwrapOpaque(segment).map(inner=>judgeSegment(inner,segments,context)))}}function judgeUnparsed(command){let lines=[command,command.replaceAll("="," "),command.replace(/(^|[\s'"])-S/g,"$1")].flatMap(text=>bestEffortCommandLines(text));for(let[name,second,third]of lines){if(name!=="kill")continue;let signalThenAll=(second==="--"||/^-[A-Za-z0-9]+$/.test(second??""))&&third==="-1";if(second==="-1"||signalThenAll)return refuseAll()}return lines.some(([name])=>KILL_FAMILY.has(name??""))?defer("the command cannot be parsed before it runs"):ALLOW}function judgeCommand(command,context){if(!command.includes("kill"))return ALLOW;let analysis=analyzeBashCommandWords(command);return analysis.kind==="unparsed"?judgeUnparsed(command):combine(analysis.segments.map(segment=>judgeSegment(segment,analysis.segments,context)))}function judgeArgv(argv,context){return argv.some(word=>word.includes("kill"))?judgeCommand(argv.map(quote).join(" "),{...context,shell:"argv"}):ALLOW}function signalTarget(call){return call.group?call.target<0?void 0:{kind:"group",pgid:call.target}:call.target===-1?{kind:"all"}:call.target<=0?{kind:"group",pgid:-call.target}:{kind:"pid",pid:call.target}}function judgeSignal(call,context){if(call.signal===0||call.signal==="0"||call.signal==="SIG0")return ALLOW;if(!Number.isInteger(call.target))return ALLOW;let target=signalTarget(call);return target===void 0?refuse("R5",`a negative process group ${call.target} cannot be signalled`):target.kind==="all"?refuseAll():context.platform==="win32"?ALLOW:judgeTargets([target],context)}import{readdirSync,readFileSync,statSync}from"node:fs";var KILL_GUARD_DEADLINE_MS=2e3;function spawnSyncFromNode(spawnSync2){return(file,args,timeoutMs)=>{let result=spawnSync2(file,args,{timeout:timeoutMs,encoding:"utf8"});return result.error===void 0?{status:result.status,stdout:result.stdout??""}:void 0}}var PS_ROW=/^\s*(-?\d+)\s+(-?\d+)\s+(-?\d+)\s+(-?\d+)\s+(-?\d+)\s+(.*)$/;function parsePsRows(text){let rows=[];for(let line of text.split(` `)){let match=PS_ROW.exec(line);if(match===null)continue;let rest=match[6]??"",first=rest.trim().split(/\s+/)[0]??"";rows.push({pid:Number(match[1]),ppid:Number(match[2]),pgid:Number(match[3]),sid:Number(match[4]),uid:Number(match[5]),comm:first.split("/").pop()??first,args:rest.trim()})}return rows}function readProcRows(deadline){let rows=[];for(let entry of readdirSync("/proc"))if(/^\d+$/.test(entry)){if(Date.now()>deadline)return;try{let stat=readFileSync(`/proc/${entry}/stat`,"utf8"),close=stat.lastIndexOf(")"),fields=stat.slice(close+2).split(" ");rows.push({pid:Number(entry),ppid:Number(fields[1]),pgid:Number(fields[2]),sid:Number(fields[3]),uid:statSync(`/proc/${entry}`).uid,comm:stat.slice(stat.indexOf("(")+1,close),args:readFileSync(`/proc/${entry}/cmdline`,"utf8").replaceAll("\0"," ").trim()})}catch{}}return rows.length>0?rows:void 0}function readPsRows(spawnSync2){let result=spawnSync2("ps",["-A","-o","pid=,ppid=,pgid=,sess=,uid=,comm=,args="],KILL_GUARD_DEADLINE_MS);if(result===void 0||result.status!==0)return;let rows=parsePsRows(result.stdout);return rows.length>0?rows:void 0}function parsePids(text){return text.split(` `).map(line=>line.trim()).filter(line=>/^\d+$/.test(line)).map(Number)}function createProcessView(platform,spawnSync2){if(platform==="win32")return;let rows;if(platform==="linux")try{rows=readProcRows(Date.now()+KILL_GUARD_DEADLINE_MS)}catch{rows=void 0}return rows??=readPsRows(spawnSync2),rows===void 0?void 0:{rows,select:args=>{let result=spawnSync2("pgrep",args,KILL_GUARD_DEADLINE_MS);return result===void 0||result.status===null?{ok:!1,reason:"pgrep did not finish"}:result.status===1?{ok:!0,pids:[]}:result.status!==0?{ok:!1,reason:`pgrep exited ${result.status}`}:{ok:!0,pids:parsePids(result.stdout)}}}}function killGuardContext(options){let{spawnSync:spawnSync2,...context}=options,read=!1,view;return{...context,view:()=>(read||(read=!0,view=createProcessView(context.platform,spawnSync2)),view)}}var isRecord=value=>typeof value=="object"&&value!==null;function parseKillGuardRequest(value){if(!isRecord(value))return;let vantagePid=typeof value.vantagePid=="number"&&Number.isInteger(value.vantagePid)?value.vantagePid:void 0,extra=vantagePid===void 0?{}:{vantagePid};if(value.kind==="command"&&typeof value.command=="string")return{kind:"command",command:value.command,...extra};if(value.kind==="argv"&&Array.isArray(value.argv)&&value.argv.every(word=>typeof word=="string"))return{kind:"argv",argv:value.argv,...extra};let signal=value.signal;if(value.kind==="signal"&&typeof value.target=="number"&&typeof value.group=="boolean"&&(typeof signal=="number"||typeof signal=="string"||signal===null))return{kind:"signal",target:value.target,group:value.group,signal,...extra}}function vantageOf(request,agentPid){return request.vantagePid===void 0?{kind:"fresh-session"}:request.vantagePid===agentPid?{kind:"agent"}:{kind:"process",pid:request.vantagePid}}function decideKillGuardRequest(value,options){let request=parseKillGuardRequest(value);if(request===void 0)return refuse("R5","the kill-guard check was malformed");let platform=options.platform??process.platform,read=!1,view,readView=options.view??(()=>(read||(read=!0,view=createProcessView(platform,spawnSyncFromNode(spawnSync))),view)),shell=request.kind==="command"?"sh":"argv",context={platform,agentPid:options.agentPid,...options.agentPpid===void 0?{}:{agentPpid:options.agentPpid},vantage:vantageOf(request,options.agentPid),shell,view:readView};switch(request.kind){case"command":return judgeCommand(request.command,context);case"argv":return judgeArgv(request.argv,context);case"signal":return judgeSignal({target:request.target,group:request.group,signal:request.signal??void 0},context)}}export{analyzeBashCommand,bestEffortCommandLines,judgeCommand,spawnSyncFromNode,killGuardContext,decideKillGuardRequest};