howtocode 0.7.62 → 0.7.64
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-6JFASNXB.js → chunk-235M52T5.js} +1 -1
- package/dist/{chunk-QPX3GUWH.js → chunk-4A5FL2OO.js} +1 -1
- package/dist/chunk-7LAMZWB5.js +1 -0
- package/dist/{chunk-RZ3BHR46.js → chunk-EERXPN2B.js} +1 -1
- package/dist/{chunk-WYVN27J4.js → chunk-GNDRI3LT.js} +1 -1
- package/dist/{chunk-F4Z65343.js → chunk-GYFZKOJV.js} +50 -50
- package/dist/{chunk-EOEOFJRD.js → chunk-IZEC6RRH.js} +1 -1
- package/dist/{chunk-ZC4QXSQN.js → chunk-NQ3G4X3F.js} +1 -1
- package/dist/{chunk-4A2IUH5P.js → chunk-O5MPUAA5.js} +1 -1
- package/dist/{chunk-ACBAN4MH.js → chunk-RU6VPYMJ.js} +6 -5
- package/dist/{chunk-J5M5TDH3.js → chunk-S3XJFLP4.js} +1 -1
- package/dist/chunk-SVONBXW3.js +3 -0
- package/dist/{chunk-BFNIIJI7.js → chunk-TFAXSHWM.js} +1 -1
- package/dist/{chunk-QPUMLZYJ.js → chunk-TPMW4JXS.js} +1 -1
- package/dist/{chunk-UMFFZTFV.js → chunk-V262WPO6.js} +1 -1
- package/dist/main.js +4 -4
- package/package.json +1 -1
- package/dist/chunk-PVFHAKN6.js +0 -1
- package/dist/chunk-YNMLRZJK.js +0 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as j}from"./chunk-MCAAX33K.js";import{H as m,N as A}from"./chunk-ABDZXFNM.js";import"./chunk-UTYFLLSM.js";import{j as R}from"./chunk-MVVEYKN6.js";import{b as M,d as T,f as D}from"./chunk-TUXY64DT.js";import{a as I}from"./chunk-U3GZBLTM.js";import{a as b}from"./chunk-
|
|
1
|
+
import{b as j}from"./chunk-MCAAX33K.js";import{H as m,N as A}from"./chunk-ABDZXFNM.js";import"./chunk-UTYFLLSM.js";import{j as R}from"./chunk-MVVEYKN6.js";import{b as M,d as T,f as D}from"./chunk-TUXY64DT.js";import{a as I}from"./chunk-U3GZBLTM.js";import{a as b}from"./chunk-V262WPO6.js";import"./chunk-WOT6VMZA.js";import{spawnSync as J}from"node:child_process";import{existsSync as S,readdirSync as E,readFileSync as x,realpathSync as B,statSync as C,writeFileSync as F,unlinkSync as z}from"node:fs";import{dirname as N,join as p}from"node:path";var k=[22,19];async function W(t="https://api.howtofix.id/api/status"){let n=[],[s,e]=process.versions.node.split(".").map(Number),r=s>k[0]||s===k[0]&&e>=k[1];n.push({name:"node",ok:r,detail:`${process.versions.node} (needs >= ${k[0]}.${k[1]})`});let i=J("git",["--version"],{encoding:"utf8"});n.push({name:"git",ok:i.status===0,detail:i.status===0?i.stdout.trim():"not found on PATH"});let o=I();n.push({name:"sandbox",ok:!!o,detail:o??"no working bubblewrap (Linux) or sandbox-exec (macOS); --sandbox unavailable",optional:!0});let l=!1,c=m;try{let d=p(m,`.doctor-${process.pid}`);F(d,"ok"),z(d),l=!0}catch(d){c=`${m} is not writable: ${d instanceof Error?d.message:String(d)}`}n.push({name:"state dir",ok:l,detail:c});let a=p(m,"auth.json"),u="no auth.json \u2014 run `howtocode` and sign in",h=!1;try{let d=JSON.parse(x(a,"utf8")),f=Object.keys(d).length;h=f>0,u=h?`${f} provider credential${f===1?"":"s"}`:u}catch{}n.push({name:"auth",ok:h,detail:u,optional:!0});try{let d=Date.now(),f=await fetch(t,{signal:AbortSignal.timeout(5e3)});n.push({name:"gateway",ok:f.ok,detail:`${t} \u2192 ${f.status} in ${Date.now()-d}ms`,optional:!0})}catch(d){n.push({name:"gateway",ok:!1,detail:`${t} unreachable: ${d instanceof Error?d.message:String(d)}`,optional:!0})}return n.push(G()),n}function G(t=q()){if(t===void 0)return{name:"install",ok:!0,detail:"not an npm install; skipped",optional:!0};if(!S(t))return{name:"install",ok:!0,detail:"no bundled dependencies to check",optional:!0};let n=[],s=0;for(let e of["@netrodev"]){let r=p(t,e);if(S(r))for(let i of E(r)){let o=p(r,i,"dist");if(S(o))for(let l of _(o)){s+=1;let c=x(l,"utf8");for(let a of c.matchAll(/import\("(\.[^"]+)"\)/g)){let u=p(N(l),a[1]);S(u)||n.push(`${e}/${i}: ${u.slice(o.length+1)}`)}}}}return n.length>0?{name:"install",ok:!1,detail:`${n.length} module${n.length===1?"":"s"} missing (${n[0]}); reinstall with \`npm install -g howtocode@latest\``}:{name:"install",ok:!0,detail:`${s} lazy module${s===1?"":"s"} present`}}function q(){try{return p(N(N(B(process.argv[1]??""))),"node_modules")}catch{return}}function _(t,n=[]){let s;try{s=E(t)}catch{return n}for(let e of s){let r=p(t,e);if(e.endsWith(".lazy.js"))n.push(r);else if(!e.includes("."))try{C(r).isDirectory()&&_(r,n)}catch{}}return n}async function ie(){let t=await W(),n=Math.max(...t.map(e=>e.name.length));for(let e of t){let r=e.ok?"ok ":e.optional?"warn":"FAIL";console.log(` ${r} ${e.name.padEnd(n)} ${e.detail}`)}let s=t.filter(e=>!e.ok&&!e.optional);return s.length>0?(console.log(`
|
|
2
2
|
${s.length} problem${s.length===1?"":"s"} must be fixed before a session will work.`),1):0}function ce(t=m){let n=p(t,"models.json"),s;try{s=x(n,"utf8")}catch(a){return a.code==="ENOENT"?console.log(` no models.json at ${n} \u2014 run \`howtocode /connect\` to pull the catalogue`):j(b,"models",a),1}let e;try{e=JSON.parse(s)}catch(a){return console.error(`${b}: models: ${n} is not valid JSON (${a instanceof Error?a.message:String(a)})`),console.error(" fix the file, or delete it and run `howtocode /connect` to write a new one"),1}let r=e.providers??{},i=D(A),o=i?new Set(i.ids):void 0,l=new Set,c=0;for(let[a,u]of Object.entries(r)){let h=u.models??[],d=h.map(f=>f.id).filter(Boolean);for(let f of d)l.add(f);c+=d.length,console.log(` ${a} (${d.length})`);for(let f of h){if(!f.id)continue;let O=T(m).get(f.id),$=M(O??[]),g=$?` ${$}`:"",w=o&&!o.has(f.id)?" \u2014 not on this account":"";console.log(` ${f.id}${g}${w}`)}}if(o){let a=[...l].filter(u=>!o.has(u)).length;console.log(`
|
|
3
3
|
${[...o].filter(u=>l.has(u)).length} of ${c} listed model(s) this account can call${a>0?`; ${a} cannot (kept for other plans)`:""}`)}else console.log("\n which of these this account can call is unknown: run `howtocode` once to record it");return c===0?(console.log(" no models configured"),1):0}function v(t=15,n=m){let s=p(n,"sessions"),e;try{e=E(s)}catch{return[]}let r=[];for(let i of e){let o=p(s,i),l;try{l=E(o)}catch{continue}for(let c of l){if(!c.endsWith(".jsonl"))continue;let a=p(o,c);try{let u=C(a);r.push({file:a,project:i,modified:u.mtimeMs,bytes:u.size})}catch{}}}return r.sort((i,o)=>o.modified-i.modified).slice(0,t)}function le(t){let n=t.indexOf("--search");if(n>=0){let o=t[n+1]?.trim();if(!o)return console.error(`${b}: sessions: --search needs a word or phrase`),2;let l=K(o);if(l.length===0)return console.log(` no session mentions "${o}"`),0;for(let c of l){let a=new Date(c.row.modified).toISOString().replace("T"," ").slice(0,16),u=`${c.matches} hit${c.matches===1?"":"s"}`;console.log(` ${a} ${c.row.project} (${u})`),console.log(` ${c.row.file}`),console.log(` ${c.snippet}`)}return 0}let s=t.indexOf("--limit"),e=s>=0&&Number(t[s+1])||15,r=v(e);if(r.length===0)return console.log(` no saved sessions under ${p(m,"sessions")}`),t.includes("--export")?1:0;let i=t.indexOf("--export");if(i>=0){let o=Number(t[i+1]);if(!Number.isInteger(o)||o<1||o>r.length)return console.error(`${b}: sessions: --export needs a number from the list (1-${r.length})`),2;let l=r[o-1];try{console.log(Q(l.file))}catch(c){return j(b,"sessions",c),1}return 0}return r.forEach((o,l)=>{let c=new Date(o.modified).toISOString().replace("T"," ").slice(0,16),a=Math.round(o.bytes/1024);console.log(` ${String(l+1).padStart(2)} ${c} ${String(a).padStart(6)}k ${o.project}`),console.log(` ${o.file}`)}),0}function H(t){let n=t;try{let s=JSON.parse(t),e=s.message?.content??s.content;if(typeof e=="string"&&e.trim())n=e;else if(Array.isArray(e)){let r=e.map(i=>i&&typeof i=="object"&&"text"in i?String(i.text):"").join(" ");r.trim()&&(n=r)}}catch{}return R(X(n).replace(/\s+/g," ").trim())}function X(t){return t.replace(/\u001b\[[0-9;?]*[ -/]*[@-~]|\u001b\][^\u0007]*\u0007|\u001b[@-Z\\-_]/g,"")}function Z(t,n,s=80){let e=t.toLowerCase().indexOf(n);if(e<0)return t.slice(0,s*2).trim();let r=Math.max(0,e-s),i=Math.min(t.length,e+n.length+s);return`${r>0?"\u2026":""}${t.slice(r,i).trim()}${i<t.length?"\u2026":""}`}function K(t,n=10,s=m){let e=t.toLowerCase(),r=new RegExp(`\\b${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"i"),i=[];for(let o of v(Number.MAX_SAFE_INTEGER,s)){let l;try{l=x(o.file,"utf8")}catch{continue}let c=0,a=0,u=0,h=0,d=!1,f="";for(let $ of l.split(`
|
|
4
4
|
`)){let g=$.toLowerCase(),w=g.indexOf(e);if(w<0)continue;let y=0;for(;w>=0;)y++,w=g.indexOf(e,w+e.length);c+=y;let L=g.includes('"role":"user"'),P=g.includes('"role":"toolresult"')||g.includes('"role":"tool"');L?a+=y:P?h+=y:u+=y,r.test($)&&(d=!0),f||(f=Z(H($),e))}if(c===0)continue;let O=(a>0?100:0)+(u>0?10:0)+Math.min(h,5)+(d?5:0)+Math.min(c,10)/100;i.push({row:o,matches:c,score:O,snippet:f})}return i.sort((o,l)=>l.score-o.score||l.row.modified-o.row.modified).slice(0,n)}function Q(t){let n=[`# Session ${t.split(/[\\/]/).pop()??t}`,""];for(let s of x(t,"utf8").split(`
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{a as x}from"./chunk-UTYFLLSM.js";import{existsSync as V,mkdirSync as J,readFileSync as _}from"node:fs";import{join as $}from"node:path";var S=new Set(["think"]),l;function M(n){let o=new WeakSet,t=e=>{if(e===null||typeof e!="object")return e;if(o.has(e))return"[circular]";if(o.add(e),Array.isArray(e))return e.map(t);let r=e,s={};for(let i of Object.keys(r).sort())s[i]=t(r[i]);return s};try{return JSON.stringify(t(n))??""}catch{return""}}function v(n,o){if(S.has(n))return;let t=`${n}\0${M(o)}`,e=l&&l.signature===t?l.count+1:1;return l={signature:t,count:e},e>=3?{repeats:e}:void 0}function sn(){l=void 0}function A(n,o){return`Refused: ${n} has been called ${o} times in a row with identical arguments, so the last attempt cannot have changed anything. Do not repeat it. Either use different arguments, use a different tool, or stop and report what you found and what is blocking you.`}var O=/^-[a-zA-Z0-9_-]/;function b(n,o){switch(o){case"number":return/^\d+$/.test(n);case"string":return!0;default:return!1}}function L(n,o){if(!/^-[^-]/.test(n)||n.includes("="))return!1;for(let t=1;t<n.length;t++){let e=o[`-${n[t]}`];if(!e)return!1;if(e!=="none")return b(n.slice(t+1),e)}return!0}function I(n,o,t){let e=o;for(;e<n.length;){let r=n[e];if(!r){e++;continue}if(r==="--")break;if(O.test(r)){if(/^-\d+$/.test(r)&&t.safeFlags["-n"]){e++;continue}let s=r.includes("="),[i="",...c]=r.split("="),a=t.safeFlags[i];if(!a){if(!L(r,t.safeFlags))return!1;e++;continue}if(a==="none"){if(s)return!1;e++;continue}if(a==="optional"){e++;continue}if(s){if(!b(c.join("="),a))return!1;e++;continue}let w=n[e+1];if(w===void 0||!b(w,a))return!1;e+=2;continue}if(t.allowPositional===!1)return!1;e++}return!0}var P={"--all":"none","--branches":"none","--tags":"none","--remotes":"none"},u={"--oneline":"none","--graph":"none","--decorate":"none","--no-decorate":"none","--date":"string","--relative-date":"none"},g={"--max-count":"number","-n":"number"},m={"--stat":"none","--numstat":"none","--shortstat":"none","--name-only":"none","--name-status":"none"},d={"--color":"none","--no-color":"none"},h={"--patch":"none","-p":"none","--no-patch":"none","--no-ext-diff":"none","-s":"none"},F={"--author":"string","--committer":"string","--grep":"string"},G={"-l":"none","--list":"none","-a":"none","-r":"none","-v":"none","-vv":"none","-i":"none"},k={"git status":{safeFlags:{"-s":"none","--short":"none","-b":"none","--branch":"none","-u":"optional","--untracked-files":"optional","--porcelain":"optional","--ignored":"none","--long":"none","--no-renames":"none",...d}},"git diff":{safeFlags:{...m,...d,...h,"--cached":"none","--staged":"none","--word-diff":"none","--check":"none","--quiet":"none","--exit-code":"none","--no-renames":"none","--diff-filter":"string","--relative":"string","--full-index":"none","--binary":"none","--abbrev":"number","--unified":"number","-U":"number","--ignore-all-space":"none","--ignore-space-change":"none","--ignore-blank-lines":"none"}},"git log":{safeFlags:{...u,...g,...m,...d,...h,...F,...P,"--since":"string","--after":"string","--until":"string","--before":"string","--follow":"none","--no-merges":"none","--merges":"none","--first-parent":"none","--reverse":"none","--skip":"number","--all":"none","--format":"string","--pretty":"string","--abbrev-commit":"none","--no-abbrev-commit":"none","--left-right":"none"}},"git show":{safeFlags:{...m,...d,...h,...u,"--format":"string","--pretty":"string","--abbrev-commit":"none","--no-patch":"none","-q":"none"}},"git shortlog":{safeFlags:{...g,"-s":"none","--summary":"none","-n":"none","--numbered":"none","-e":"none","--email":"none","-sn":"none","-ns":"none","--all":"none"}},"git reflog":{safeFlags:{...g,...u,...F,"--all":"none","--date":"string"}},"git blame":{safeFlags:{"-L":"string","-w":"none","-c":"none","-n":"none","-s":"none","-e":"none","-p":"none","--porcelain":"none","--line-porcelain":"none","--date":"string","--since":"string","-C":"none","-M":"none"}},"git ls-files":{safeFlags:{"-m":"none","--modified":"none","-o":"none","--others":"none","-i":"none","--ignored":"none","-s":"none","--stage":"none","-d":"none","--deleted":"none","-c":"none","--cached":"none","-u":"none","--unmerged":"none","--exclude-standard":"none","--error-unmatch":"none","-z":"none"}},"git ls-remote":{safeFlags:{"--heads":"none","--tags":"none","--refs":"none","--symref":"none"}},"git rev-parse":{safeFlags:{"--short":"optional","--abbrev-ref":"none","--verify":"none","--quiet":"none","--git-dir":"none","--show-toplevel":"none","--show-cdup":"none","--is-inside-work-tree":"none","--is-bare-repository":"none","--symbolic-full-name":"none","--abbrev":"optional"}},"git rev-list":{safeFlags:{...g,"--count":"none","--all":"none","--objects":"none","--reverse":"none","--max-parents":"number","--min-parents":"number","--no-merges":"none","--first-parent":"none","--abbrev-commit":"none"}},"git describe":{safeFlags:{"--tags":"none","--all":"none","--long":"none","--always":"none","--dirty":"none","--abbrev":"number","--match":"string","--exclude":"string","--first-parent":"none"}},"git cat-file":{safeFlags:{"-p":"none","-t":"none","-s":"none","-e":"none","--batch-check":"none"}},"git for-each-ref":{safeFlags:{"--format":"string","--count":"number","--sort":"string","--points-at":"string","--merged":"string","--no-merged":"string"}},"git grep":{safeFlags:{"-n":"none","--line-number":"none","-i":"none","--ignore-case":"none","-l":"none","--files-with-matches":"none","-c":"none","--count":"none","-w":"none","--word-regexp":"none","-E":"none","--extended-regexp":"none","-F":"none","--fixed-strings":"none","--cached":"none","--untracked":"none","-e":"string","--and":"none","--or":"none","--not":"none"}},"git merge-base":{safeFlags:{"--all":"none","--is-ancestor":"none","--fork-point":"none","--octopus":"none"}},"git stash list":{safeFlags:{...u}},"git worktree list":{safeFlags:{"--porcelain":"none","-v":"none","--verbose":"none","-z":"none"}},"git branch":{safeFlags:{...G,"--merged":"string","--no-merged":"string","--contains":"string","--no-contains":"string","--sort":"string","--format":"string","--points-at":"string","--column":"none","--show-current":"none"},dangerous:n=>{let o=new Set(["--merged","--no-merged","--contains","--no-contains","--sort","--format","--points-at"]),t=!1;for(let e of n){if(t){t=!1;continue}if(o.has(e)){t=!0;continue}if(!e.startsWith("-"))return!0}return!1}},"git tag":{safeFlags:{"-l":"none","--list":"none","-n":"number","--contains":"string","--no-contains":"string","--merged":"string","--sort":"string","--points-at":"string","--column":"none"},dangerous:n=>{let o=new Set(["--contains","--no-contains","--merged","--sort","--points-at"]),t=!1;for(let e of n){if(t){t=!1;continue}if(o.has(e)){t=!0;continue}if(!e.startsWith("-"))return!0}return!1}},"git remote":{safeFlags:{"-v":"none","--verbose":"none"},dangerous:n=>n.some(o=>!o.startsWith("-"))},"git config --get":{safeFlags:{"--local":"none","--global":"none","--system":"none","--get-all":"none","--get-regexp":"none","--list":"none","-l":"none","--show-origin":"none","--null":"none","-z":"none"}}},z=["ls","pwd","cat","head","tail","wc","which","whoami","date","echo","sleep","true","false","type","test","seq","basename","dirname","realpath","stat","file","du","df","tree","uname","hostname","id","groups","tty","cal","uptime","free","locale","printf","grep","rg","fd","jq","bat","column","paste","nl","expand","fold","fmt","md5sum","sha1sum","sha256sum","sha512sum","b2sum","cksum","diff","cmp"],j={find:{safeFlags:{"-name":"string","-iname":"string","-type":"string","-maxdepth":"number","-mindepth":"number","-newer":"string","-path":"string","-not":"none","-print":"none","-print0":"none","-empty":"none","-size":"string","-mtime":"number","-atime":"number","-perm":"string","-L":"none","-H":"none","-P":"none"},dangerous:n=>n.some(o=>/^-(delete|exec|execdir|ok|okdir|fprint0?|fls|fprintf)$/.test(o))},sort:{safeFlags:{"-n":"none","-r":"none","-u":"none","-k":"string","-t":"string","-f":"none","-h":"none","-V":"none","-s":"none","-c":"none","-m":"none","-b":"none","-z":"none"}},uniq:{safeFlags:{"-c":"none","-d":"none","-u":"none","-i":"none","-f":"number","-s":"number","-w":"number"}},cut:{safeFlags:{"-d":"string","-f":"string","-c":"string","-b":"string","-s":"none","--complement":"none","-z":"none"}},tr:{safeFlags:{"-d":"none","-s":"none","-c":"none"}},node:{safeFlags:{"-v":"none","--version":"none"},allowPositional:!1},python:{safeFlags:{"--version":"none"},allowPositional:!1},python3:{safeFlags:{"--version":"none"},allowPositional:!1},npm:{safeFlags:{"--version":"none","-v":"none"},allowPositional:!1},sed:{safeFlags:{"-n":"none","--quiet":"none","-e":"string","-E":"none","-r":"none","--regexp-extended":"none","-s":"none","-u":"none","-z":"none","--posix":"none"},dangerous:n=>n.some(o=>/^-i|^--in-place/.test(o)||/\b[we]\s/.test(o)||/^[we]$/.test(o))},awk:{safeFlags:{"-F":"string","-v":"string","-f":"string"},dangerous:n=>n.some(o=>/\bsystem\s*\(|\|\s*"|>\s*"/.test(o))},xxd:{safeFlags:{"-l":"number","-s":"string","-c":"number","-g":"number","-p":"none","-i":"none","-u":"none","-b":"none","-e":"none","-o":"number"},dangerous:n=>n.some(o=>o==="-r"||/^-[a-z]*r/.test(o))}},R={"npm ls":{safeFlags:{"--depth":"number","--json":"none","--long":"none","--parseable":"none","--all":"none","--prod":"none","--dev":"none","--omit":"string","--link":"none","--global":"none","-g":"none","--silent":"none"}},"npm view":{safeFlags:{"--json":"none","--registry":"string"}},"docker ps":{safeFlags:{"-a":"none","--all":"none","-q":"none","--quiet":"none","--no-trunc":"none","--format":"string","-n":"number","--last":"number","-s":"none","--size":"none","--filter":"string"}},"docker images":{safeFlags:{"-a":"none","--all":"none","-q":"none","--quiet":"none","--no-trunc":"none","--format":"string","--filter":"string","--digests":"none"}},"docker inspect":{safeFlags:{"--format":"string","-f":"string","-s":"none","--size":"none","--type":"string"}},"kubectl get":{safeFlags:{"-o":"string","--output":"string","-n":"string","--namespace":"string","-A":"none","--all-namespaces":"none","--no-headers":"none","-l":"string","--selector":"string","--show-labels":"none","-w":"none","--watch":"none","--sort-by":"string"}},"kubectl describe":{safeFlags:{"-n":"string","--namespace":"string","-l":"string","--selector":"string"}},"cargo tree":{safeFlags:{"--depth":"number","-e":"string","--edges":"string","--no-dev-dependencies":"none","--prefix":"string","-i":"string","--invert":"string","-p":"string","--package":"string"}},"go version":{safeFlags:{}}},N=["cd","alias","history","arch","ip addr","ifconfig"];function D(n){if(!/\$\(|`|\$\{|>|</.test(n)&&!/(?<!&)&(?!&)/.test(n))return n.split(/\|\||&&|;|\|/).map(o=>o.trim()).filter(o=>o.length>0)}function q(n){let o=n.some(e=>/^cd\b/.test(e)),t=n.some(e=>/^git\b/.test(e));return o&&t}function U(n){let o=[],t=/'[^']*'|"[^"]*"|\S+/g;for(let e of n.match(t)??[])o.push(e.length>=2&&/^['"]/.test(e)?e.slice(1,-1):e);return o}function W(n){if(n.length===0)return;let[o="",t=""]=n,e=`${o} ${t}`;if(o==="git"&&t==="config"){let r=n[2];return r==="--get"||r==="--get-all"||r==="--get-regexp"||r==="-l"||r==="--list"?{name:"git config --get",rest:n.slice(3)}:void 0}return o==="git"&&t==="stash"?n[2]==="list"?{name:"git stash list",rest:n.slice(3)}:void 0:o==="git"&&t==="worktree"?n[2]==="list"?{name:"git worktree list",rest:n.slice(3)}:void 0:o==="git"&&k[`git ${t}`]?{name:`git ${t}`,rest:n.slice(2)}:R[e]?{name:e,rest:n.slice(2)}:{name:o,rest:n.slice(1)}}var B=new Set(["echo","printf"]);function H(n){let o=U(n),t=W(o);if(!t)return!1;let{name:e,rest:r}=t;if(B.has(e)&&r.some(i=>i.includes("$")||i.includes("`")))return!1;let s=k[e]??j[e]??R[e];return s?s.dangerous?.(r)?!1:I(r,0,s):!!(z.includes(e)||N.includes(e))}function y(n){let o=D(n);return!o||o.length===0||q(o)?!1:o.every(H)}var Y=["suggest","auto-edit","full-auto"],pn={suggest:"suggest: ask before every edit and command","auto-edit":"auto-edit: edits run, commands ask","full-auto":"full-auto: nothing asks"};function Z(n){return Y.includes(n)}var T={read:0,write:1,exec:2},K={suggest:"read","auto-edit":"write","full-auto":"exec"},X={read:"read",grep:"read",find:"read",ls:"read",think:"read",ask:"read",todo:"read",context:"read",web_search:"read",web_fetch:"read",lsp:"read",quality:"read",workflow:"exec",browser:"exec",goal:"read",enter_plan_mode:"read",exit_plan_mode:"read",edit:"write",write:"write",bash:"exec",powershell:"exec",task:"exec"};function C(n){let o=X[n];return o||(n.startsWith("mcp__")?"write":"exec")}var Q=new Set(["sudo","doas","env","nohup","time","exec","command","nice","setsid","stdbuf"]),nn=new Set(["-u","-g","-p","-C","-S","-U","--user","--group","--prompt","--close-from","--chdir","--setenv","--unset"]);function en(n){let o=(n.match(/"[^"]*"|'[^']*'|\S+/g)??[]).map(s=>s.replace(/^['"]|['"]$/g,"")),t=0;for(;t<o.length;){let s=o[t]??"";if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(s)||Q.has(s)){t++;continue}if(s.startsWith("-")){t+=nn.has(s)?2:1;continue}break}let e=o[t];if(e===void 0)return;let r=e.split("/").pop()??e;if(r==="rm"){let s=o.slice(t+1),i=s.some(a=>/^-[a-zA-Z]*r[a-zA-Z]*$/i.test(a)||a==="--recursive"),c=s.find(a=>!a.startsWith("-"));return i&&(c===void 0||/^(?:\/|\/\*|~|~\/\*|\$HOME|\$HOME\/\*|\*)$/.test(c))?"recursive delete of the filesystem root or home":void 0}if(r==="dd")return o.slice(t+1).some(s=>/^of=\/dev\/(?:sd|nvme|hd|vd)/.test(s))?"raw write to a block device":void 0;if(/^mkfs(?:\.[a-z0-9]+)?$/.test(r))return"filesystem format";if(/:\(\)\s*\{.*\}\s*;:/.test(n))return"fork bomb";if(/^(?:shutdown|reboot|halt|poweroff)$/.test(r))return"host shutdown";if(/>\s*\/etc\/(?:passwd|shadow|sudoers)/.test(n))return"overwrite of a system account file"}var f="full-auto",E=async()=>!1,p=!1;function mn(n){f=n}function hn(n){try{let t=JSON.parse(_($(n,"settings.json"),"utf8")).approvalMode;typeof t=="string"&&Z(t)&&(f=t)}catch{}}function bn(n,o){let t=$(n,"settings.json"),e={};try{let r=JSON.parse(_(t,"utf8"));r&&typeof r=="object"&&!Array.isArray(r)&&(e=r)}catch{if(V(t))return}e.approvalMode=o;try{J(n,{recursive:!0}),x(t,`${JSON.stringify(e,null,2)}
|
|
2
|
+
`)}catch{}}function yn(){return f}function wn(n){p=n}function xn(){return p}function vn(n){E=n}function tn(n,o,t){if(p)return{action:"run"};let e=typeof t?.command=="string"?t.command:"";if(o==="bash"||o==="powershell"){let s=en(e);if(s)return{action:"deny",reason:`Refused in every mode: ${s}.`};if(y(e))return{action:"run"}}let r=C(o);return T[r]<=T[K[n]]?{action:"run"}:{action:"prompt",reason:`this is a ${r}-tier tool`}}function on(n,o){if(o&&typeof o=="object"){let t=o;if((n==="bash"||n==="powershell")&&typeof t.command=="string")return t.command;if((n==="edit"||n==="write")&&typeof t.path=="string"){let e=Array.isArray(t.edits)?` (${t.edits.length} edits)`:"";return`${t.path}${e}`}try{let e=JSON.stringify(t);if(e&&e!=="{}")return e.length>300?`${e.slice(0,297)}...`:e}catch{}}return n}function rn(n,o,t){let e=[`Allow tool: ${n}`];n.startsWith("mcp__")&&e.push("Origin: MCP server tool"),e.push(`Reason: ${t}`);let r=on(n,o);return r!==n&&e.push(r),e.join(`
|
|
3
|
+
`)}function An(n={}){return o=>{o.on("tool_call",async t=>{if(p)return;let e=v(t.toolName,t.input);if(e)return{block:!0,reason:A(t.toolName,e.repeats)};let r=f,s=tn(r,t.toolName,t.input);if(s.action==="run")return;if(s.action==="deny")return{block:!0,reason:s.reason};if(n.interactive===!1)return{block:!0,reason:`Blocked: this is a ${C(t.toolName)}-tier tool and no UI can approve it here (approval mode: ${r}).`};if(!await E(`${t.toolName} wants to run`,rn(t.toolName,t.input,s.reason)))return{block:!0,reason:`Blocked by the user (approval mode: ${r}).`}})}}export{sn as a,y as b,Y as c,pn as d,Z as e,T as f,K as g,C as h,en as i,mn as j,hn as k,bn as l,yn as m,wn as n,xn as o,vn as p,tn as q,on as r,rn as s,An as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{j as a}from"./chunk-MVVEYKN6.js";import{b as r}from"./chunk-
|
|
1
|
+
import{j as a}from"./chunk-MVVEYKN6.js";import{b as r}from"./chunk-V262WPO6.js";import"./chunk-WOT6VMZA.js";function c(e){return{prompt:s=>e.session.prompt(s),abort:()=>e.session.abort(),subscribe:s=>e.session.subscribe(n=>s(n)),getLastAssistantText:()=>a(e.session.getLastAssistantText()??""),lastStopReason:()=>{let s=e.session.state.messages.at(-1);return s?.role==="assistant"?s.stopReason:void 0},dispose:()=>e.dispose()}}async function g(e,s){let{openSession:n}=await import("./chunk-235M52T5.js"),i=t=>n({cwd:t,model:s.model,thinking:s.thinking,continueSession:!1,noSession:!1,sessionPath:void 0,interactive:!1});if(e==="acp"){let{runAcp:t}=await import("./chunk-TOV557ET.js");await t({input:process.stdin,output:process.stdout,version:r,createAgent:async u=>c(await i(u))});return}let{runRpc:p}=await import("./chunk-QOYTPACU.js"),{createJsonEventEncoder:d}=await import("./chunk-MCDEIIEN.js"),o=await i(s.cwd),m=d();await p({input:process.stdin,output:process.stdout,agent:c(o),encodeEvent:t=>m.line(t),state:()=>({sessionId:o.session.sessionId,model:o.modelLabel,cwd:s.cwd})})}export{c as agentFromSession,g as serveProtocol};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g,h,i,j}from"./chunk-
|
|
1
|
+
import{a,b,c,d,e,f,g,h,i,j}from"./chunk-O5MPUAA5.js";import"./chunk-V262WPO6.js";import"./chunk-WOT6VMZA.js";export{h as CLI_CLIENT_HEADER,a as CLI_SIGNING_KEY_ID,i as cliClientHeader,c as cliSignaturePayload,f as cliSigningKeyFingerprint,e as cliSigningKeyMatchesPanel,b as cliSigningPublicKey,d as createNonce,g as describeClient,j as signLoginRequest};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var a="HowToCode",o="0.7.
|
|
1
|
+
var a="HowToCode",o="0.7.64",n=["You are HowToCode, a coding agent. The user wants the fix, not a tour of the problem.",'NEVER report a check you did not run. NEVER state a version, path, result or capability you have not verified \u2014 if you did not check it, say you are unsure. "Not found" is not "impossible": a tool missing from PATH is often installed anyway, and one that is truly absent can usually be installed. Exhaust the real options before calling anything unavailable; when you do report a limit, say plainly what you tried and what you could not do. Unexercised behaviour is not evidence.',"NEVER mention the underlying harness, its vendor or its project name to the user.","Every tool is `read`, `write` or `exec`, and each approval mode auto-approves every tier up to its own: `suggest` runs `read` only, `auto-edit` adds `write`, `full-auto` adds `exec`. A read-only shell command runs in every mode, so inspecting the tree asks nothing.","NEVER aim a command at the filesystem root, a block device or a system account file, and NEVER shut down the host: those are refused in EVERY mode, `full-auto` included, so proposing one wastes the turn. This is not a list of things to avoid \u2014 it is a list of things that will not run.","Lead with the diagnosis in one or two sentences, then change the code. SHOULD prefer the smallest correct change over a rewrite. Name the file and the reason in a short line; do not narrate tool calls.","Fix the problem that was asked for. NEVER add features, refactors, validation, error handling or dependencies nobody requested.","Something reported broken: reproduce it first, confirm the fix after. Cannot reproduce it? Say so \u2014 NEVER edit code and call it fixed.","Tests describe intended behaviour. A failing test means fix the code, not the test: NEVER delete, skip or loosen an assertion to get green, and NEVER re-pin an expected value to whatever the code happens to print.","Anything you cannot settle by reading \u2014 a page, a layout, a screenshot, a CLI, a service, a failure \u2014 run it and look at the result. For a visual task, find a browser the way a real one does: `$PUPPETEER_EXECUTABLE_PATH`, `$CHROME_PATH`, then `which` for google-chrome, chromium and chromium-browser, then /usr/bin, /snap/bin and /var/lib/flatpak, then the puppeteer and playwright caches under the home directory. Still empty? `npx -y puppeteer browsers install chrome`, or `npm i puppeteer-core` against a chrome the image already ships outside PATH. Then drive the real artifact \u2014 open it, read the DOM, click the controls, measure at the widths that matter \u2014 instead of describing what you assume it does.","Done means the requested behaviour works end to end and every stated requirement is met \u2014 not a scaffold, a narrowed test or a plausible subset. Genuinely out of reach? Finish everything else, then say exactly what is missing and what you tried.","SHOULD plan multi-step work with `todo` before starting it, and mark each step done as you finish. A plan the user can see is worth more than a narration of what you are about to do.","Genuinely ambiguous design: enter plan mode, write the plan to the plan file, then present it with `exit_plan_mode`. Use it when several reasonable approaches exist or when a restructuring would be hard to undo. In plan mode `edit` and `write` are refused for every path except the plan file itself \u2014 that limit is enforced, not advisory, so plan the work rather than starting it. Plan mode needs an interactive session in which the user can approve it; when there is no UI it is unavailable, so design the approach yourself instead of calling it.","Work that is independent and would flood this conversation belongs in `task` subagents. Give each a self-contained assignment, then verify the file it wrote rather than trusting its summary. When that work has a shape you can script \u2014 many items through the same stages, or fan-out whose results must be combined \u2014 `workflow` states the orchestration in one place and runs it deterministically; `task` is for the one-off you cannot describe in advance.","MUST give each subagent a self-contained assignment: a child starts with none of this conversation, so a brief that says 'the file we discussed' reaches it as nothing. Choose the agent by what the work is \u2014 scout looks something up, architect returns a plan, reviewer reports issues with file evidence, task changes files \u2014 and NEVER send work that needs an edit to scout or reviewer, because neither can make one.","SHOULD delegate only work that is genuinely parallel: a subagent costs its own session and its own requests on the same quota as this conversation. A single lookup, a file you can read yourself, or a step whose result decides the next step stays here. MUST keep one call to at most six agents and the session to twelve live or parked ones \u2014 a larger fan-out is refused, and the refusal is a limit rather than a failure to work around.","Record a decision, a file's role, or a fact you would otherwise re-derive with `context`: notes survive compaction and are visible to the other agents on the task.","Look it up instead of recalling it: `web_search` and `web_fetch` for anything outside this repo, `lsp` for a definition, reference or diagnostic. Name the source you checked.","Before calling changed code done, run `quality` and `slop` over it and act on what they report. A metric you did not measure is a claim you cannot make.","A command runs under a two-minute default timeout. MUST pass a longer timeout for anything that legitimately takes more than that \u2014 a recursive directory walk, a package install, a build, a network fetch \u2014 and SHOULD prefer a bounded command to an unbounded one: 'du -sh' with an explicit path beats the whole profile, and on Windows/MSYS a recursive 'du' over a profile directory takes minutes rather than seconds.","When a choice blocks the task, use `ask` instead of guessing; when you need to work something out, use `think`, whose text stays out of the transcript.","Above all: NEVER claim a check you did not run, and NEVER call done on a subset."].join(`
|
|
2
2
|
`);function s(e){return e===void 0?void 0:e.replace(/Use \/login to log into a provider[^\n]*/gi,"Connect a provider with /connect or /login:").replace(/^[ \t]*\S*hxf-coding-agent[\\/]docs[\\/][^\n]*$/gim,"").replace(/\bhxf-coding-agent\b/gi,"the harness").replace(/\n{3,}/g,`
|
|
3
3
|
|
|
4
4
|
`).trim()}var i=["# Project notes","","## What this is","","## Commands","- build:","- test:","","## Conventions","-",""].join(`
|
package/dist/main.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{b as G,d as J,e as K}from"./chunk-EZNNALD3.js";import"./chunk-7LA2AMZB.js";import{c as H}from"./chunk-PH72JBBL.js";import{a as B,b as F}from"./chunk-MCAAX33K.js";import{H as $,P as D}from"./chunk-ABDZXFNM.js";import"./chunk-UTYFLLSM.js";import{j as L}from"./chunk-MVVEYKN6.js";import{a as r,b as k}from"./chunk-
|
|
2
|
+
import{b as G,d as J,e as K}from"./chunk-EZNNALD3.js";import"./chunk-7LA2AMZB.js";import{c as H}from"./chunk-PH72JBBL.js";import{a as B,b as F}from"./chunk-MCAAX33K.js";import{H as $,P as D}from"./chunk-ABDZXFNM.js";import"./chunk-UTYFLLSM.js";import{j as L}from"./chunk-MVVEYKN6.js";import{a as r,b as k}from"./chunk-V262WPO6.js";import"./chunk-WOT6VMZA.js";import{existsSync as Oe,mkdirSync as Te,readdirSync as Z,statSync as Ae,writeFileSync as je}from"node:fs";import{join as j}from"node:path";var V={rpc:!0,acp:!0},q={off:!0,minimal:!0,low:!0,medium:!0,high:!0,xhigh:!0,max:!0},z={suggest:!0,"auto-edit":!0,"full-auto":!0},X={text:!0,json:!0,"stream-json":!0};function Re(l){let e=Number(l);if(!Number.isFinite(e)||e<=0)throw new Error(`--max-budget-usd needs a positive number of dollars, got '${l}'`);return e}function P(l,e,p){let i=l[e];if(i?.includes("="))return i.slice(i.indexOf("=")+1);let c=l[e+1];if(!c||c.startsWith("-"))throw new Error(`${p} needs a value`);return l.splice(e+1,1),c}function Y(l){let e={print:!1,continueSession:!1,noSession:!1,help:!1,version:!1,update:!1,checkUpdate:!1,outputFormat:"text",dangerouslySkipPermissions:!1,sandbox:!1,prompt:""},p=[],i=[...l];i[0]==="resume"&&i[1]&&!i[1].startsWith("-")&&(e.resumeId=i[1],i.splice(0,2));for(let c=0;c<i.length;c++){let s=i[c]??"";if(s==="--"){p.push(...i.slice(c+1));break}if(s==="-h"||s==="--help")e.help=!0;else if(s==="-v"||s==="--version")e.version=!0;else if(s==="-p"||s==="--print")e.print=!0;else if(s==="-c"||s==="--continue")e.continueSession=!0;else if(s==="--no-session")e.noSession=!0;else if(s==="--sandbox")e.sandbox=!0;else if(s==="--update")e.update=!0;else if(s==="--check-update")e.checkUpdate=!0;else if(s==="-r"||s==="--resume")e.continueSession=!0;else if(s==="--session"||s.startsWith("--session="))e.sessionPath=P(i,c,"--session");else if(s==="-m"||s==="--model"||s.startsWith("--model="))e.model=P(i,c,"--model");else if(s==="--thinking"||s.startsWith("--thinking="))e.thinking=P(i,c,"--thinking");else if(s==="--approval"||s.startsWith("--approval="))e.approval=P(i,c,"--approval");else if(s==="--output-format"||s.startsWith("--output-format="))e.outputFormat=P(i,c,"--output-format");else if(s==="--max-budget-usd"||s.startsWith("--max-budget-usd="))e.maxBudgetUsd=Re(P(i,c,"--max-budget-usd"));else if(s==="--mode"||s.startsWith("--mode=")){let g=P(i,c,"--mode");if(!V[g])throw new Error(`--mode must be one of: ${Object.keys(V).join(", ")}`);e.mode=g}else if(s==="--acp")e.mode="acp";else if(s==="--dangerously-skip-permissions")e.dangerouslySkipPermissions=!0;else{if(s.startsWith("-"))throw new Error(`unknown option ${s}`);p.push(s)}}if(e.thinking&&!q[e.thinking])throw new Error(`thinking must be one of: ${Object.keys(q).join(", ")}`);if(e.approval&&!z[e.approval])throw new Error(`approval must be one of: ${Object.keys(z).join(", ")}`);if(!X[e.outputFormat])throw new Error(`output-format must be one of: ${Object.keys(X).join(", ")}`);if(e.outputFormat!=="text"&&!e.print)throw new Error(`--output-format ${e.outputFormat} is a machine contract; it needs --print`);if(e.dangerouslySkipPermissions&&!e.print)throw new Error("--dangerously-skip-permissions is for unattended runs; it needs --print. interactively, pick an approval mode instead (/approval, or --approval)");if(e.prompt=p.join(" ").trim(),e.update&&e.checkUpdate)throw new Error("--update installs; --check-update only looks. pick one");if((e.update||e.checkUpdate)&&(e.print||e.continueSession||e.sessionPath||e.prompt))throw new Error("--update and --check-update act on the installation, not a session; they take no prompt");if(e.continueSession&&e.noSession)throw new Error("--continue and --no-session cannot be combined");if(e.sessionPath&&e.noSession)throw new Error("--session and --no-session cannot be combined");if(e.sessionPath&&e.continueSession)throw new Error("--session and --continue cannot be combined");if(e.resumeId&&e.sessionPath)throw new Error("resume <id> and --session cannot be combined");if(e.resumeId&&e.continueSession)throw new Error("resume <id> and --continue cannot be combined");if(e.print&&(e.continueSession||e.sessionPath||e.resumeId))throw new Error("--print runs one prompt in a throwaway session; it cannot be combined with --continue, --session, or resume <id>");if(e.mode&&(e.print||e.prompt))throw new Error(`--mode ${e.mode} is a protocol server: prompts arrive over the protocol, not the command line`);if(e.mode&&(e.continueSession||e.sessionPath))throw new Error(`--mode ${e.mode} opens its own sessions; it cannot be combined with --continue or --session`);if(e.sessionPath&&!e.sessionPath.endsWith(".jsonl"))throw new Error(`--session expects a session file, got '${e.sessionPath}'`);return e}function A(){return`${r} ${k}
|
|
3
3
|
coding agent. layout is a workbench, not a chat log.
|
|
4
4
|
|
|
5
5
|
usage:
|
|
@@ -93,10 +93,10 @@ token; /login takes another provider's key.
|
|
|
93
93
|
`}function Me(l,e=!1){let{message:p,hint:i}=B(l),c=i?`${p}
|
|
94
94
|
${i}`:p;if(!e)return c;let s=l instanceof Error?l.stack:void 0;return s&&s.includes(`
|
|
95
95
|
`)?`${c}
|
|
96
|
-
${s}`:c}function Q(l,e){let p=e?.debug??process.env.HOWTOCODE_DEBUG==="1",i=e?.exit??(s=>process.exit(s)),c=s=>{console.error(`${l}: ${Me(s,p)}`),i(1)};process.on("uncaughtException",c),process.on("unhandledRejection",c)}function Fe(){try{return{cwd:process.cwd()}}catch{return{error:"the current directory no longer exists (it was deleted while the shell stayed in it). cd to a directory that exists, or pass one on the command line."}}}function Ie(){process.stdout.on("error",l=>{throw l.code==="EPIPE"&&process.exit(0),l})}function Ne(){let l=j($,".welcomed");if(!Oe(l)){try{Te($,{recursive:!0}),je(l,k)}catch{return}console.error(`${r} ${k} installed. Docs: https://howtofix.id/code`),console.error("Continue the last session here with: howtocode -c")}}async function Ue(){Ie(),D();let l=performance.now(),e=Fe();if("error"in e){console.error(`${r}: ${e.error}`),process.exitCode=1;return}let p=e.cwd,i=process.env.HXF_FAKE_NODE??process.versions.node,[c,s]=i.split(".").map(t=>Number.parseInt(t,10));if(!Number.isFinite(c)||c<22||c===22&&Number.isFinite(s)&&s<19){console.error(`${r}: Node ${i} is too old. Node 22.19 or newer is required (run "node --version" to check yours), because undici needs zstd, which Node added in 22.19. Upgrade Node and run this again.`),process.exitCode=1;let t=process.argv.slice(2);if(t.some(n=>n==="-h"||n==="--help")){console.log(A());return}if(t.some(n=>n==="-v"||n==="--version")){console.log(`${r} ${k}`);return}return}let g=process.argv.slice(2);if(g[0]==="doctor"||g[0]==="models"||g[0]==="sessions"){let t=g[0];try{let n=await import("./chunk-
|
|
97
|
-
${A()}`),process.exitCode=2;return}if(E.print&&!E.prompt){console.error(`${r}: --print needs a prompt`),process.exitCode=2;return}let{repairGatewayModels:se,ensureGatewaySettings:oe,repairModelFacts:te,syncGatewayModelsOnStart:ne,checkAccount:re,fetchGatewayPrices:ie,readProviderKey:ae}=await import("./chunk-
|
|
96
|
+
${s}`:c}function Q(l,e){let p=e?.debug??process.env.HOWTOCODE_DEBUG==="1",i=e?.exit??(s=>process.exit(s)),c=s=>{console.error(`${l}: ${Me(s,p)}`),i(1)};process.on("uncaughtException",c),process.on("unhandledRejection",c)}function Fe(){try{return{cwd:process.cwd()}}catch{return{error:"the current directory no longer exists (it was deleted while the shell stayed in it). cd to a directory that exists, or pass one on the command line."}}}function Ie(){process.stdout.on("error",l=>{throw l.code==="EPIPE"&&process.exit(0),l})}function Ne(){let l=j($,".welcomed");if(!Oe(l)){try{Te($,{recursive:!0}),je(l,k)}catch{return}console.error(`${r} ${k} installed. Docs: https://howtofix.id/code`),console.error("Continue the last session here with: howtocode -c")}}async function Ue(){Ie(),D();let l=performance.now(),e=Fe();if("error"in e){console.error(`${r}: ${e.error}`),process.exitCode=1;return}let p=e.cwd,i=process.env.HXF_FAKE_NODE??process.versions.node,[c,s]=i.split(".").map(t=>Number.parseInt(t,10));if(!Number.isFinite(c)||c<22||c===22&&Number.isFinite(s)&&s<19){console.error(`${r}: Node ${i} is too old. Node 22.19 or newer is required (run "node --version" to check yours), because undici needs zstd, which Node added in 22.19. Upgrade Node and run this again.`),process.exitCode=1;let t=process.argv.slice(2);if(t.some(n=>n==="-h"||n==="--help")){console.log(A());return}if(t.some(n=>n==="-v"||n==="--version")){console.log(`${r} ${k}`);return}return}let g=process.argv.slice(2);if(g[0]==="doctor"||g[0]==="models"||g[0]==="sessions"){let t=g[0];try{let n=await import("./chunk-S3XJFLP4.js");t==="doctor"?process.exitCode=await n.runDoctor():t==="models"?process.exitCode=n.runModels():process.exitCode=n.runSessions(g.slice(1))}catch(n){F(r,t,n),process.exitCode=1}return}let ee=g[0]==="acp"?["--acp",...g.slice(1)]:g,E;try{E=Y(ee)}catch(t){let n=t instanceof Error?t.message:String(t);console.error(`${r}: ${n}
|
|
97
|
+
${A()}`),process.exitCode=2;return}if(E.print&&!E.prompt){console.error(`${r}: --print needs a prompt`),process.exitCode=2;return}let{repairGatewayModels:se,ensureGatewaySettings:oe,repairModelFacts:te,syncGatewayModelsOnStart:ne,checkAccount:re,fetchGatewayPrices:ie,readProviderKey:ae}=await import("./chunk-GNDRI3LT.js"),{tiersFrom:ce,writeReachable:de}=await import("./chunk-XBVWQC7P.js"),{readCliCredential:le,renewCliCredentialIfNeeded:pe}=await import("./chunk-4A5FL2OO.js"),{AGENT_DIR:h,REACHABLE_CACHE_PATH:ue}=await import("./chunk-ELM3OMOE.js"),{readCachedPrices:me,writeCachedPrices:he}=await import("./chunk-A3LZMZ3C.js"),I=se(h);I>0&&console.error(`${r}: repaired ${I} howtocode model(s) that the gateway would have rejected`);let _,R,M=new Map,C=me(h);if(C){_=C.prices;for(let[t,n]of C.groups)M.set(t,n)}try{let t=le(h),n=t?(await pe(h,t)).credential.accessToken:ae(h,"howtocode");if(n){let[m,u]=await Promise.all([C?Promise.resolve(_??new Map):ie(n,{groups:M}),re(n)]);!C&&m.size>0&&(_=m,he(h,m,M)),u.ok&&(R=u.models)}}catch{}let N=ce(M),O=await te(h,{..._?{prices:_}:{},...N.size>0?{tiers:N}:{}});if(O.changed>0?console.error(`${r}: filled in the context window, reasoning flag and price for ${O.changed} model(s)`):O.message&&console.error(`${r}: model catalogue unavailable (${O.message}); context windows stay at their conservative defaults`),oe(h)&&console.error(`${r}: set httpIdleTimeoutMs in settings.json so a stalled provider recovers instead of hanging`),R){de(ue,R);try{let t=await ne(h,R,_);t.added>0&&console.error(`${r}: added ${t.added} model(s) this account can now reach`)}catch{}}let o=E;if(o.help){console.log(A());return}if(o.version){console.log(`${r} ${k}`);let{cliSigningKeyMatchesPanel:t,cliSigningKeyFingerprint:n}=await import("./chunk-TPMW4JXS.js");t()||(console.error(`${r}: this build's CLI signing key (${n()}) does not match the key the panel verifies against, so sign-in will be refused.`),process.exitCode=1);return}if(o.sandbox&&!process.env.HOWTOCODE_SANDBOXED){let{detectSandbox:t,enterSandbox:n,describeSandbox:m}=await import("./chunk-YX2QDCVK.js"),u=t();if(!u){console.error(`${r}: --sandbox needs a working bubblewrap (Linux) or sandbox-exec (macOS). Neither could be used here \u2014 on Linux this usually means unprivileged user namespaces are disabled.`),process.exitCode=1;return}console.error(m(u)),process.exitCode=n(u,{cwd:p,agentDir:$,argv:[process.execPath,...process.argv.slice(1)]});return}let{installProxy:fe}=await import("./chunk-WKUJ7CFO.js");fe($);let{retireRobloxBridge:ge}=await import("./chunk-CCISJKGS.js");if(ge($),o.update||o.checkUpdate){let{PACKAGE_NAME:t,checkForUpdate:n,installUpdate:m,isInstalledCopy:u}=await import("./chunk-LYLJZVZ7.js"),w=await n(k);if(!w.latest){console.error(`${r}: ${w.message}`),process.exitCode=o.update?1:0;return}if(console.log(w.message),o.checkUpdate||!w.available)return;if(!u()){console.error(`${r}: this copy was not installed by npm, so npm cannot replace it. install it with: npm install -g ${t}`),process.exitCode=1;return}let v=await m({version:w.latest});console.log(v.message),v.ok||(process.exitCode=1);return}let U=process.argv.slice(2);if(U[0]==="preset"){let{runPresetCommand:t}=await import("./chunk-AS4FUFAN.js");process.exitCode=t(U.slice(1));return}let{expandFileReferences:we}=await import("./chunk-TSEKPGK4.js"),{isApprovalMode:be,setApprovalMode:ke,setDangerousBypass:xe,isDangerousBypass:ye}=await import("./chunk-7LAMZWB5.js"),{openSession:ve}=await import("./chunk-235M52T5.js");ke(o.approval&&be(o.approval)?o.approval:"full-auto");let{readWorkbenchSettings:Se}=await import("./chunk-V3R4FYTJ.js");if((o.dangerouslySkipPermissions||Se(h).skipPermissions)&&xe(!0),ye()&&console.error(`${r}: permission checks are OFF \u2014 critical commands (filesystem wipes, fork bombs, host shutdown) and the repeated-call guard are NOT enforced for this run. Turn it off with /settings, or by removing skipPermissions from settings.json.`),o.mode){let{serveProtocol:t}=await import("./chunk-TFAXSHWM.js");await t(o.mode,{cwd:p,model:o.model,thinking:o.thinking});return}let W=t=>ve({cwd:p,model:o.model,thinking:o.thinking,continueSession:t.continueSession??!1,noSession:t.noSession??!1,sessionPath:t.sessionPath,interactive:!o.print});if(o.resumeId&&!o.sessionPath){let t=j($,"sessions"),n=[];try{for(let m of Z(t))for(let u of Z(j(t,m))){if(!u.endsWith(".jsonl")||!u.includes(o.resumeId))continue;let w=j(t,m,u);try{n.push({path:w,mtime:Ae(w).mtimeMs})}catch{}}}catch{}if(n=n.sort((m,u)=>u.mtime-m.mtime),n.length===0){console.error(`${r}: no stored session matches '${o.resumeId}'. Run 'howtocode -c' to continue the latest one in this folder.`),process.exitCode=1;return}n.length>1&&console.error(`${r}: '${o.resumeId}' matches ${n.length} sessions; using the newest (${n[0].path}).`),o.sessionPath=n[0].path}let a=await W({continueSession:o.continueSession,sessionPath:o.sessionPath,noSession:o.noSession||o.print});if(o.print&&a.note&&console.error(a.note),o.maxBudgetUsd!==void 0&&!a.priced){console.error(`${r}: ${K(a.modelLabel,h)}`),await a.dispose(),process.exitCode=2;return}if(o.print){let t=o.prompt.trimStart();if(t.startsWith("/")){let b=t.slice(1).split(/\s+/)[0]??"",{skillInvocation:T}=await import("./chunk-BZJSYOTO.js"),S=a.session.resourceLoader.getSkills().skills.map(f=>f.name);if(!(T(t,S)!==void 0)){let{slashCommands:f}=await import("./chunk-GYFZKOJV.js");if(f(a.session).some(d=>d.name===b)){console.error(`${r}: /${b} runs in the TUI only \u2014 --print sends prompts straight to the model. Run \`howtocode\` without --print for interactive commands.`),await a.dispose(),process.exitCode=2;return}}}let n=o.outputFormat==="stream-json",m=o.outputFormat==="json",u=n||m;if(n){let b={type:"system",subtype:"init",cwd:p,session_id:a.session.sessionId,model:a.modelLabel,output_format:o.outputFormat,max_budget_usd:o.maxBudgetUsd??null,dangerously_skip_permissions:o.dangerouslySkipPermissions,cli_version:k};process.stdout.write(`${JSON.stringify(b)}
|
|
98
98
|
`)}let w,v,Ee=()=>{if(o.maxBudgetUsd===void 0||v!==void 0)return;let b=a.session.getSessionStats().cost;b>o.maxBudgetUsd&&(v={spent:b},a.session.abort())};try{let b,T=H();if(w=a.session.subscribe(d=>{if(n){let y=T.line(d);y!==void 0&&process.stdout.write(y)}if(d.type==="turn_end"&&d.message?.role==="assistant"){let y=d.message;y.stopReason==="error"||y.stopReason==="aborted"||y.errorMessage?b={stopReason:y.stopReason??"error",errorMessage:y.errorMessage}:b=void 0}Ee()}),await a.session.prompt(we(o.prompt,p)),n){let d=T.finish();d!==void 0&&process.stdout.write(d)}let S=L(a.session.getLastAssistantText()??"");if(v){if(console.error(`${r}: ${J(v.spent,o.maxBudgetUsd)}`),u){let d=a.session.getSessionStats();process.stdout.write(`${JSON.stringify({type:"result",subtype:"error_max_budget_usd",is_error:!0,result:S,session_id:a.session.sessionId,duration_ms:Math.round(performance.now()-l),num_turns:d.assistantMessages,total_cost_usd:d.cost,usage:{input_tokens:d.tokens.input,output_tokens:d.tokens.output,cache_read_input_tokens:d.tokens.cacheRead,cache_creation_input_tokens:d.tokens.cacheWrite}})}
|
|
99
99
|
`)}process.exitCode=1;return}let x=a.session.state.messages.at(-1),f=b??(x?.role==="assistant"&&(x.stopReason==="error"||x.stopReason==="aborted"||x.errorMessage)?{stopReason:x.stopReason??"error",errorMessage:x.errorMessage}:void 0);if(u){let d=a.session.getSessionStats();process.stdout.write(`${JSON.stringify({type:"result",subtype:f?f.stopReason==="aborted"?"error_aborted":"error_during_execution":"success",is_error:f!==void 0,result:S,session_id:a.session.sessionId,duration_ms:Math.round(performance.now()-l),num_turns:d.assistantMessages,total_cost_usd:d.cost,usage:{input_tokens:d.tokens.input,output_tokens:d.tokens.output,cache_read_input_tokens:d.tokens.cacheRead,cache_creation_input_tokens:d.tokens.cacheWrite},stop_reason:f?.stopReason??(x?.role==="assistant"?x.stopReason:void 0)})}
|
|
100
100
|
`)}else process.stdout.write(S.endsWith(`
|
|
101
101
|
`)?S:`${S}
|
|
102
|
-
`);if(f&&(process.exitCode=1,f.errorMessage)){console.error(`${r}: ${f.errorMessage}`);let d=G(f.errorMessage);d!==void 0&&console.error(`${r}: ${d}`)}}finally{w?.(),await a.dispose()}return}if(!process.stdin.isTTY||!process.stdout.isTTY){console.error(`${r}: interactive mode needs a terminal. use --print for pipes.`),await a.dispose(),process.exitCode=2;return}Ne();let{runWorkbench:$e}=await import("./chunk-
|
|
102
|
+
`);if(f&&(process.exitCode=1,f.errorMessage)){console.error(`${r}: ${f.errorMessage}`);let d=G(f.errorMessage);d!==void 0&&console.error(`${r}: ${d}`)}}finally{w?.(),await a.dispose()}return}if(!process.stdin.isTTY||!process.stdout.isTTY){console.error(`${r}: interactive mode needs a terminal. use --print for pipes.`),await a.dispose(),process.exitCode=2;return}Ne();let{runWorkbench:$e}=await import("./chunk-GYFZKOJV.js"),{autoUpdateEnabled:Pe,isInstalledCopy:_e}=await import("./chunk-LYLJZVZ7.js"),Ce=_e()&&Pe(`${h}/settings.json`);await $e({cwd:p,modelLabel:a.modelLabel,session:a.session,dispose:()=>a.dispose(),setCompressToolOutput:a.setCompressToolOutput,initialPrompt:o.prompt||void 0,note:a.note,maxBudgetUsd:o.maxBudgetUsd,update:Ce?{current:k,install:!0}:void 0,reopen:W})}Q(r);Ue().catch(l=>{F(r,void 0,l),process.exitCode=1});
|
package/package.json
CHANGED
package/dist/chunk-PVFHAKN6.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{b as a,c as b,d as c,e as d,f as e,g as f,h as g,i as h,j as i,k as j,l as k,m as l,n as m,o as n,p as o,q as p,r as q}from"./chunk-YNMLRZJK.js";import"./chunk-WOT6VMZA.js";export{c as APPROVAL_LABELS,b as APPROVAL_MODES,f as MODE_MAX_TIER,e as TIER_RANK,q as createPermissionExtension,h as criticalCommand,n as decideToolCall,o as describeToolCall,p as formatApprovalPrompt,j as getApprovalMode,d as isApprovalMode,l as isDangerousBypass,a as isReadOnlyCommand,g as resolveTier,i as setApprovalMode,m as setApprovalPrompt,k as setDangerousBypass};
|
package/dist/chunk-YNMLRZJK.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
var C=new Set(["think"]),l;function E(n){let t=new WeakSet,o=e=>{if(e===null||typeof e!="object")return e;if(t.has(e))return"[circular]";if(t.add(e),Array.isArray(e))return e.map(o);let r=e,s={};for(let i of Object.keys(r).sort())s[i]=o(r[i]);return s};try{return JSON.stringify(o(n))??""}catch{return""}}function x(n,t){if(C.has(n))return;let o=`${n}\0${E(t)}`,e=l&&l.signature===o?l.count+1:1;return l={signature:o,count:e},e>=3?{repeats:e}:void 0}function Q(){l=void 0}function v(n,t){return`Refused: ${n} has been called ${t} times in a row with identical arguments, so the last attempt cannot have changed anything. Do not repeat it. Either use different arguments, use a different tool, or stop and report what you found and what is blocking you.`}var $=/^-[a-zA-Z0-9_-]/;function h(n,t){switch(t){case"number":return/^\d+$/.test(n);case"string":return!0;default:return!1}}function O(n,t){if(!/^-[^-]/.test(n)||n.includes("="))return!1;for(let o=1;o<n.length;o++){let e=t[`-${n[o]}`];if(!e)return!1;if(e!=="none")return h(n.slice(o+1),e)}return!0}function L(n,t,o){let e=t;for(;e<n.length;){let r=n[e];if(!r){e++;continue}if(r==="--")break;if($.test(r)){if(/^-\d+$/.test(r)&&o.safeFlags["-n"]){e++;continue}let s=r.includes("="),[i="",...c]=r.split("="),a=o.safeFlags[i];if(!a){if(!O(r,o.safeFlags))return!1;e++;continue}if(a==="none"){if(s)return!1;e++;continue}if(a==="optional"){e++;continue}if(s){if(!h(c.join("="),a))return!1;e++;continue}let y=n[e+1];if(y===void 0||!h(y,a))return!1;e+=2;continue}if(o.allowPositional===!1)return!1;e++}return!0}var S={"--all":"none","--branches":"none","--tags":"none","--remotes":"none"},g={"--oneline":"none","--graph":"none","--decorate":"none","--no-decorate":"none","--date":"string","--relative-date":"none"},u={"--max-count":"number","-n":"number"},p={"--stat":"none","--numstat":"none","--shortstat":"none","--name-only":"none","--name-status":"none"},d={"--color":"none","--no-color":"none"},m={"--patch":"none","-p":"none","--no-patch":"none","--no-ext-diff":"none","-s":"none"},F={"--author":"string","--committer":"string","--grep":"string"},I={"-l":"none","--list":"none","-a":"none","-r":"none","-v":"none","-vv":"none","-i":"none"},A={"git status":{safeFlags:{"-s":"none","--short":"none","-b":"none","--branch":"none","-u":"optional","--untracked-files":"optional","--porcelain":"optional","--ignored":"none","--long":"none","--no-renames":"none",...d}},"git diff":{safeFlags:{...p,...d,...m,"--cached":"none","--staged":"none","--word-diff":"none","--check":"none","--quiet":"none","--exit-code":"none","--no-renames":"none","--diff-filter":"string","--relative":"string","--full-index":"none","--binary":"none","--abbrev":"number","--unified":"number","-U":"number","--ignore-all-space":"none","--ignore-space-change":"none","--ignore-blank-lines":"none"}},"git log":{safeFlags:{...g,...u,...p,...d,...m,...F,...S,"--since":"string","--after":"string","--until":"string","--before":"string","--follow":"none","--no-merges":"none","--merges":"none","--first-parent":"none","--reverse":"none","--skip":"number","--all":"none","--format":"string","--pretty":"string","--abbrev-commit":"none","--no-abbrev-commit":"none","--left-right":"none"}},"git show":{safeFlags:{...p,...d,...m,...g,"--format":"string","--pretty":"string","--abbrev-commit":"none","--no-patch":"none","-q":"none"}},"git shortlog":{safeFlags:{...u,"-s":"none","--summary":"none","-n":"none","--numbered":"none","-e":"none","--email":"none","-sn":"none","-ns":"none","--all":"none"}},"git reflog":{safeFlags:{...u,...g,...F,"--all":"none","--date":"string"}},"git blame":{safeFlags:{"-L":"string","-w":"none","-c":"none","-n":"none","-s":"none","-e":"none","-p":"none","--porcelain":"none","--line-porcelain":"none","--date":"string","--since":"string","-C":"none","-M":"none"}},"git ls-files":{safeFlags:{"-m":"none","--modified":"none","-o":"none","--others":"none","-i":"none","--ignored":"none","-s":"none","--stage":"none","-d":"none","--deleted":"none","-c":"none","--cached":"none","-u":"none","--unmerged":"none","--exclude-standard":"none","--error-unmatch":"none","-z":"none"}},"git ls-remote":{safeFlags:{"--heads":"none","--tags":"none","--refs":"none","--symref":"none"}},"git rev-parse":{safeFlags:{"--short":"optional","--abbrev-ref":"none","--verify":"none","--quiet":"none","--git-dir":"none","--show-toplevel":"none","--show-cdup":"none","--is-inside-work-tree":"none","--is-bare-repository":"none","--symbolic-full-name":"none","--abbrev":"optional"}},"git rev-list":{safeFlags:{...u,"--count":"none","--all":"none","--objects":"none","--reverse":"none","--max-parents":"number","--min-parents":"number","--no-merges":"none","--first-parent":"none","--abbrev-commit":"none"}},"git describe":{safeFlags:{"--tags":"none","--all":"none","--long":"none","--always":"none","--dirty":"none","--abbrev":"number","--match":"string","--exclude":"string","--first-parent":"none"}},"git cat-file":{safeFlags:{"-p":"none","-t":"none","-s":"none","-e":"none","--batch-check":"none"}},"git for-each-ref":{safeFlags:{"--format":"string","--count":"number","--sort":"string","--points-at":"string","--merged":"string","--no-merged":"string"}},"git grep":{safeFlags:{"-n":"none","--line-number":"none","-i":"none","--ignore-case":"none","-l":"none","--files-with-matches":"none","-c":"none","--count":"none","-w":"none","--word-regexp":"none","-E":"none","--extended-regexp":"none","-F":"none","--fixed-strings":"none","--cached":"none","--untracked":"none","-e":"string","--and":"none","--or":"none","--not":"none"}},"git merge-base":{safeFlags:{"--all":"none","--is-ancestor":"none","--fork-point":"none","--octopus":"none"}},"git stash list":{safeFlags:{...g}},"git worktree list":{safeFlags:{"--porcelain":"none","-v":"none","--verbose":"none","-z":"none"}},"git branch":{safeFlags:{...I,"--merged":"string","--no-merged":"string","--contains":"string","--no-contains":"string","--sort":"string","--format":"string","--points-at":"string","--column":"none","--show-current":"none"},dangerous:n=>{let t=new Set(["--merged","--no-merged","--contains","--no-contains","--sort","--format","--points-at"]),o=!1;for(let e of n){if(o){o=!1;continue}if(t.has(e)){o=!0;continue}if(!e.startsWith("-"))return!0}return!1}},"git tag":{safeFlags:{"-l":"none","--list":"none","-n":"number","--contains":"string","--no-contains":"string","--merged":"string","--sort":"string","--points-at":"string","--column":"none"},dangerous:n=>{let t=new Set(["--contains","--no-contains","--merged","--sort","--points-at"]),o=!1;for(let e of n){if(o){o=!1;continue}if(t.has(e)){o=!0;continue}if(!e.startsWith("-"))return!0}return!1}},"git remote":{safeFlags:{"-v":"none","--verbose":"none"},dangerous:n=>n.some(t=>!t.startsWith("-"))},"git config --get":{safeFlags:{"--local":"none","--global":"none","--system":"none","--get-all":"none","--get-regexp":"none","--list":"none","-l":"none","--show-origin":"none","--null":"none","-z":"none"}}},M=["ls","pwd","cat","head","tail","wc","which","whoami","date","echo","sleep","true","false","type","test","seq","basename","dirname","realpath","stat","file","du","df","tree","uname","hostname","id","groups","tty","cal","uptime","free","locale","printf","grep","rg","fd","jq","bat","column","paste","nl","expand","fold","fmt","md5sum","sha1sum","sha256sum","sha512sum","b2sum","cksum","diff","cmp"],P={find:{safeFlags:{"-name":"string","-iname":"string","-type":"string","-maxdepth":"number","-mindepth":"number","-newer":"string","-path":"string","-not":"none","-print":"none","-print0":"none","-empty":"none","-size":"string","-mtime":"number","-atime":"number","-perm":"string","-L":"none","-H":"none","-P":"none"},dangerous:n=>n.some(t=>/^-(delete|exec|execdir|ok|okdir|fprint0?|fls|fprintf)$/.test(t))},sort:{safeFlags:{"-n":"none","-r":"none","-u":"none","-k":"string","-t":"string","-f":"none","-h":"none","-V":"none","-s":"none","-c":"none","-m":"none","-b":"none","-z":"none"}},uniq:{safeFlags:{"-c":"none","-d":"none","-u":"none","-i":"none","-f":"number","-s":"number","-w":"number"}},cut:{safeFlags:{"-d":"string","-f":"string","-c":"string","-b":"string","-s":"none","--complement":"none","-z":"none"}},tr:{safeFlags:{"-d":"none","-s":"none","-c":"none"}},node:{safeFlags:{"-v":"none","--version":"none"},allowPositional:!1},python:{safeFlags:{"--version":"none"},allowPositional:!1},python3:{safeFlags:{"--version":"none"},allowPositional:!1},npm:{safeFlags:{"--version":"none","-v":"none"},allowPositional:!1},sed:{safeFlags:{"-n":"none","--quiet":"none","-e":"string","-E":"none","-r":"none","--regexp-extended":"none","-s":"none","-u":"none","-z":"none","--posix":"none"},dangerous:n=>n.some(t=>/^-i|^--in-place/.test(t)||/\b[we]\s/.test(t)||/^[we]$/.test(t))},awk:{safeFlags:{"-F":"string","-v":"string","-f":"string"},dangerous:n=>n.some(t=>/\bsystem\s*\(|\|\s*"|>\s*"/.test(t))},xxd:{safeFlags:{"-l":"number","-s":"string","-c":"number","-g":"number","-p":"none","-i":"none","-u":"none","-b":"none","-e":"none","-o":"number"},dangerous:n=>n.some(t=>t==="-r"||/^-[a-z]*r/.test(t))}},T={"npm ls":{safeFlags:{"--depth":"number","--json":"none","--long":"none","--parseable":"none","--all":"none","--prod":"none","--dev":"none","--omit":"string","--link":"none","--global":"none","-g":"none","--silent":"none"}},"npm view":{safeFlags:{"--json":"none","--registry":"string"}},"docker ps":{safeFlags:{"-a":"none","--all":"none","-q":"none","--quiet":"none","--no-trunc":"none","--format":"string","-n":"number","--last":"number","-s":"none","--size":"none","--filter":"string"}},"docker images":{safeFlags:{"-a":"none","--all":"none","-q":"none","--quiet":"none","--no-trunc":"none","--format":"string","--filter":"string","--digests":"none"}},"docker inspect":{safeFlags:{"--format":"string","-f":"string","-s":"none","--size":"none","--type":"string"}},"kubectl get":{safeFlags:{"-o":"string","--output":"string","-n":"string","--namespace":"string","-A":"none","--all-namespaces":"none","--no-headers":"none","-l":"string","--selector":"string","--show-labels":"none","-w":"none","--watch":"none","--sort-by":"string"}},"kubectl describe":{safeFlags:{"-n":"string","--namespace":"string","-l":"string","--selector":"string"}},"cargo tree":{safeFlags:{"--depth":"number","-e":"string","--edges":"string","--no-dev-dependencies":"none","--prefix":"string","-i":"string","--invert":"string","-p":"string","--package":"string"}},"go version":{safeFlags:{}}},G=["cd","alias","history","arch","ip addr","ifconfig"];function z(n){if(!/\$\(|`|\$\{|>|</.test(n)&&!/(?<!&)&(?!&)/.test(n))return n.split(/\|\||&&|;|\|/).map(t=>t.trim()).filter(t=>t.length>0)}function D(n){let t=n.some(e=>/^cd\b/.test(e)),o=n.some(e=>/^git\b/.test(e));return t&&o}function q(n){let t=[],o=/'[^']*'|"[^"]*"|\S+/g;for(let e of n.match(o)??[])t.push(e.length>=2&&/^['"]/.test(e)?e.slice(1,-1):e);return t}function j(n){if(n.length===0)return;let[t="",o=""]=n,e=`${t} ${o}`;if(t==="git"&&o==="config"){let r=n[2];return r==="--get"||r==="--get-all"||r==="--get-regexp"||r==="-l"||r==="--list"?{name:"git config --get",rest:n.slice(3)}:void 0}return t==="git"&&o==="stash"?n[2]==="list"?{name:"git stash list",rest:n.slice(3)}:void 0:t==="git"&&o==="worktree"?n[2]==="list"?{name:"git worktree list",rest:n.slice(3)}:void 0:t==="git"&&A[`git ${o}`]?{name:`git ${o}`,rest:n.slice(2)}:T[e]?{name:e,rest:n.slice(2)}:{name:t,rest:n.slice(1)}}var N=new Set(["echo","printf"]);function U(n){let t=q(n),o=j(t);if(!o)return!1;let{name:e,rest:r}=o;if(N.has(e)&&r.some(i=>i.includes("$")||i.includes("`")))return!1;let s=A[e]??P[e]??T[e];return s?s.dangerous?.(r)?!1:L(r,0,s):!!(M.includes(e)||G.includes(e))}function b(n){let t=z(n);return!t||t.length===0||D(t)?!1:t.every(U)}var W=["suggest","auto-edit","full-auto"],rn={suggest:"suggest: ask before every edit and command","auto-edit":"auto-edit: edits run, commands ask","full-auto":"full-auto: nothing asks"};function sn(n){return W.includes(n)}var k={read:0,write:1,exec:2},B={suggest:"read","auto-edit":"write","full-auto":"exec"},H={read:"read",grep:"read",find:"read",ls:"read",think:"read",ask:"read",todo:"read",context:"read",web_search:"read",web_fetch:"read",lsp:"read",quality:"read",workflow:"exec",browser:"exec",goal:"read",enter_plan_mode:"read",exit_plan_mode:"read",edit:"write",write:"write",bash:"exec",powershell:"exec",task:"exec"};function R(n){let t=H[n];return t||(n.startsWith("mcp__")?"write":"exec")}var V=new Set(["sudo","doas","env","nohup","time","exec","command","nice","setsid","stdbuf"]),Y=new Set(["-u","-g","-p","-C","-S","-U","--user","--group","--prompt","--close-from","--chdir","--setenv","--unset"]);function Z(n){let t=(n.match(/"[^"]*"|'[^']*'|\S+/g)??[]).map(s=>s.replace(/^['"]|['"]$/g,"")),o=0;for(;o<t.length;){let s=t[o]??"";if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(s)||V.has(s)){o++;continue}if(s.startsWith("-")){o+=Y.has(s)?2:1;continue}break}let e=t[o];if(e===void 0)return;let r=e.split("/").pop()??e;if(r==="rm"){let s=t.slice(o+1),i=s.some(a=>/^-[a-zA-Z]*r[a-zA-Z]*$/i.test(a)||a==="--recursive"),c=s.find(a=>!a.startsWith("-"));return i&&(c===void 0||/^(?:\/|\/\*|~|~\/\*|\$HOME|\$HOME\/\*|\*)$/.test(c))?"recursive delete of the filesystem root or home":void 0}if(r==="dd")return t.slice(o+1).some(s=>/^of=\/dev\/(?:sd|nvme|hd|vd)/.test(s))?"raw write to a block device":void 0;if(/^mkfs(?:\.[a-z0-9]+)?$/.test(r))return"filesystem format";if(/:\(\)\s*\{.*\}\s*;:/.test(n))return"fork bomb";if(/^(?:shutdown|reboot|halt|poweroff)$/.test(r))return"host shutdown";if(/>\s*\/etc\/(?:passwd|shadow|sudoers)/.test(n))return"overwrite of a system account file"}var w="full-auto",_=async()=>!1,f=!1;function an(n){w=n}function ln(){return w}function cn(n){f=n}function gn(){return f}function un(n){_=n}function J(n,t,o){if(f)return{action:"run"};let e=typeof o?.command=="string"?o.command:"";if(t==="bash"||t==="powershell"){let s=Z(e);if(s)return{action:"deny",reason:`Refused in every mode: ${s}.`};if(b(e))return{action:"run"}}let r=R(t);return k[r]<=k[B[n]]?{action:"run"}:{action:"prompt",reason:`this is a ${r}-tier tool`}}function K(n,t){if(t&&typeof t=="object"){let o=t;if((n==="bash"||n==="powershell")&&typeof o.command=="string")return o.command;if((n==="edit"||n==="write")&&typeof o.path=="string"){let e=Array.isArray(o.edits)?` (${o.edits.length} edits)`:"";return`${o.path}${e}`}try{let e=JSON.stringify(o);if(e&&e!=="{}")return e.length>300?`${e.slice(0,297)}...`:e}catch{}}return n}function X(n,t,o){let e=[`Allow tool: ${n}`];n.startsWith("mcp__")&&e.push("Origin: MCP server tool"),e.push(`Reason: ${o}`);let r=K(n,t);return r!==n&&e.push(r),e.join(`
|
|
2
|
-
`)}function dn(n={}){return t=>{t.on("tool_call",async o=>{if(f)return;let e=x(o.toolName,o.input);if(e)return{block:!0,reason:v(o.toolName,e.repeats)};let r=w,s=J(r,o.toolName,o.input);if(s.action==="run")return;if(s.action==="deny")return{block:!0,reason:s.reason};if(n.interactive===!1)return{block:!0,reason:`Blocked: this is a ${R(o.toolName)}-tier tool and no UI can approve it here (approval mode: ${r}).`};if(!await _(`${o.toolName} wants to run`,X(o.toolName,o.input,s.reason)))return{block:!0,reason:`Blocked by the user (approval mode: ${r}).`}})}}export{Q as a,b,W as c,rn as d,sn as e,k as f,B as g,R as h,Z as i,an as j,ln as k,cn as l,gn as m,un as n,J as o,K as p,X as q,dn as r};
|