howtocode 0.7.61 → 0.7.63

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/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-HQVNWGN7.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}
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-X3KLM35N.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-VOZ3J75B.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-YGC4JVGS.js"),{tiersFrom:ce,writeReachable:de}=await import("./chunk-XBVWQC7P.js"),{readCliCredential:le,renewCliCredentialIfNeeded:pe}=await import("./chunk-WI4YX3JJ.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-5HEL5PJ5.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-PVFHAKN6.js"),{openSession:ve}=await import("./chunk-JOWLG77G.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-7JGPX5FL.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-L27DI5LJ.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)}
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-AFDG4PTM.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-MR6XQ4CA.js"),{tiersFrom:ce,writeReachable:de}=await import("./chunk-XBVWQC7P.js"),{readCliCredential:le,renewCliCredentialIfNeeded:pe}=await import("./chunk-HUWX3NJL.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-U3T2AS5G.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-SXUB7264.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-LXH2ZY6E.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-Y2MUWQ6M.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-L27DI5LJ.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});
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-Y2MUWQ6M.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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "howtocode",
3
- "version": "0.7.61",
3
+ "version": "0.7.63",
4
4
  "type": "module",
5
5
  "description": "HowToCode coding agent. Workbench TUI, sessions, background agents.",
6
6
  "license": "UNLICENSED",
@@ -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};
@@ -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};